import pygame, math, sys, random
from pygame.locals import *

def pointInWedge(wedge, wedgeX, wedgeY, pointX, pointY):
    blockSize = 20
    if pointX >= wedgeX and pointX <= wedgeX+blockSize and pointY >= wedgeY and pointY <= wedgeY+blockSize:
        if wedge == 2:
            return pointX+pointY > wedgeX+wedgeY+blockSize
        elif wedge == 3:
            return pointX-wedgeX < pointY-wedgeY
        elif wedge == 4:
            return pointX+pointY < wedgeX+wedgeY+blockSize
        elif wedge == 5:
            return pointX-wedgeX > pointY-wedgeY
        else:
            return True
    else:
        return False

class Player:

    def __init__(this, x, y, teamColor, player, **kwargs):
        this.x = x
        this.y = y
        this.w = kwargs.get("width", 20)
        this.h = kwargs.get("height", 20)
        this.hat = kwargs.get("hat", 0)
        this.gunOn = kwargs.get("gun", 0)
        this.gun = guns[this.gunOn]
        this.speed = kwargs.get("speed", 2.5)
        this.gravity = kwargs.get("gravity", 0.1)
        this.jumpHeight = kwargs.get("jumpHeight", 5)
        this.maxSpeed = kwargs.get("maxSpeed", 4)
        this.teamColor = teamColor
        this.cursor = [0,0]
        this.yVel = 0
        this.theKey = 0
        this.delay = random.randint(0, this.gun.firerate)
        this.dir = random.randint(0,4)
        if this.dir == 2:
            this.dir = 0
        this.id = player
        this.health = 100
        this.inBlock = False
        this.outOfBlock = True
        this.lastShot = player
        this.you = False
        this.kills = 0

    def loopInfo(this, key, value):
        if key[0] == this.id:
            if key[1] == "damage":
                this.health -= key[2]
                this.lastShot = key[3]
            elif key[1] == "kill":
                this.gunOn += 1
                if this.gunOn > len(guns)-1:
                    this.gunOn = len(guns)-1
                this.gun = guns[this.gunOn]
                this.health += 20
                this.kills += 1
            return False
        return True

    def draw(this, surface, playerInfo):
        pygame.draw.rect(surface, this.teamColor, (this.x,this.y,this.w,this.h))
        this.gun.draw(surface, 0.03, [this.x+this.w/2,this.y+this.h/2], math.atan2(this.cursor[1]-this.y, this.cursor[0]-this.x))
        return playerInfo.filter(this.loopInfo)

    def playPlayer(this, mouseState, mouseX, mouseY, keys, blocks):
        this.cursor = [mouseX, mouseY]
        if keys[K_a] or keys[K_LEFT]:
            this.x -= this.speed
            this.theKey = K_LEFT
        if keys[K_d] or keys[K_RIGHT]:
            this.x += this.speed
            this.theKey = K_RIGHT
        blocks.loop(this.Xcol)
        if (keys[K_w] or keys[K_UP]) and this.yVel == 0:
            this.yVel = -this.jumpHeight-0.001
        this.yVel += this.gravity
        if this.yVel > this.maxSpeed:
            this.yVel = this.maxSpeed
        this.y += this.yVel
        blocks.loop(this.Ycol)
        this.delay -= 1
        if mouseState and this.delay < 0:
            this.delay = this.gun.firerate
            returnArray = []
            for i in range(this.gun.shots):
                angle = math.atan2(this.cursor[1]-this.y-this.h/2, this.cursor[0]-this.x-this.w/2)
                spread = random.randrange(-this.gun.spread, this.gun.spread)*math.pi/180
                velX = math.cos(angle + spread)
                velY = math.sin(angle + spread)
                offsetX = math.cos(angle)
                offsetY = math.sin(angle)
                returnArray.append([this.x+offsetX*30+this.w/2, this.y+offsetY*30+this.h/2, velX*this.gun.bulletspeed, velY*this.gun.bulletspeed, this.gun.damage*100, this.id])
            return returnArray
        else:
            return []

    def playAI(this, blocks, aiTrigger, players):
        this.outOfBlock = True
        aiTrigger.loop(this.changeDir)
        this.inBlock = not this.outOfBlock
        this.closestPlayer = 1000000
        players.loop(this.shootClosestPlayer)
        if this.dir == 0 or this.dir == 1:
            this.x -= this.speed
            this.theKey = K_LEFT
        elif this.dir == 3 or this.dir == 4:
            this.x += this.speed
            this.theKey = K_RIGHT
        blocks.loop(this.Xcol)
        if (this.dir == 1 or this.dir == 2 or this.dir == 3) and this.yVel == 0:
            this.yVel = -this.jumpHeight-0.001
        this.yVel += this.gravity
        if this.yVel > this.maxSpeed:
            this.yVel = this.maxSpeed
        this.y += this.yVel
        blocks.loop(this.Ycol)
        this.delay -= 1
        if this.delay < 0:
            this.delay = this.gun.firerate
            returnArray = []
            for i in range(this.gun.shots):
                angle = math.atan2(this.cursor[1]-this.y-this.h/2, this.cursor[0]-this.x-this.w/2)
                spread = random.randrange(-this.gun.spread, this.gun.spread)*math.pi/180
                velX = math.cos(angle + spread)
                velY = math.sin(angle + spread)
                offsetX = math.cos(angle)
                offsetY = math.sin(angle)
                returnArray.append([this.x+offsetX*30+this.w/2, this.y+offsetY*30+this.h/2, velX*this.gun.bulletspeed, velY*this.gun.bulletspeed, this.gun.damage, this.id])
            return returnArray
        else:
            return []

    def shootClosestPlayer(this, key, value):
        if key.id != this.id:
            d = math.dist((this.x, this.y), (key.x, key.y))
            if d < this.closestPlayer:
                this.closestPlayer = d
                this.cursor[0] = key.x+key.w/2
                this.cursor[1] = key.y+key.h/2

    def changeDir(this, key, value):
        blockSize = 20
        row = key[1]
        col = key[2]
        if this.x+this.w > row*blockSize and this.x < row*blockSize+blockSize and this.y+this.h > col*blockSize and this.y < col*blockSize+blockSize:
            this.outOfBlock = False
            if not this.inBlock:
                options = key[0]
                dirOptions = []
                for option in options:
                    if option == 1:
                        dirOptions.append(2)
                    elif option == 2:
                        dirOptions.append(0)
                        dirOptions.append(1)
                    elif option == 3:
                        dirOptions.append(3)
                        dirOptions.append(4)
                this.dir = dirOptions[random.randint(0, len(dirOptions)-1)]
                this.inBlock = True

    def pointInBlock(this, blockX, blockY, pointX, pointY):
        blockSize = 20
        return pointX > blockX and pointX < blockX+blockSize and pointY > blockY and pointY < blockY+blockSize

    def Xcol(this, key, value):
        blockSize = 20
        row = key[1]
        col = key[2]
        if key[0] == 1:
            if this.x+this.w > row*blockSize and this.x < row*blockSize+blockSize and this.y+this.h > col*blockSize and this.y < col*blockSize+blockSize:
                if this.theKey == K_RIGHT:
                    this.x = row*blockSize-this.w
                elif this.theKey == K_LEFT:
                    this.x = row*blockSize+blockSize
        elif key[0] == 2:
            if pointInWedge(2, row*blockSize, col*blockSize, this.x, this.y) or pointInWedge(2, row*blockSize, col*blockSize, this.x+this.w, this.y) or pointInWedge(2, row*blockSize, col*blockSize, this.x, this.y+this.h):
                if this.theKey == K_LEFT:
                    this.x += this.speed
                elif this.theKey == K_RIGHT:
                    this.x -= this.speed
            elif pointInWedge(2, row*blockSize, col*blockSize, this.x+this.w, this.y+this.h):
                this.y -= this.speed
                this.yVel = 0
            elif this.pointInBlock(row*blockSize, col*blockSize, this.x+this.w, this.y):
                if this.theKey == K_LEFT:
                    this.x += this.speed
                elif this.theKey == K_RIGHT:
                    this.x -= this.speed
        elif key[0] == 3:
            if pointInWedge(3, row*blockSize, col*blockSize, this.x, this.y) or pointInWedge(3, row*blockSize, col*blockSize, this.x+this.w, this.y) or pointInWedge(3, row*blockSize, col*blockSize, this.x+this.w, this.y+this.h):
                if this.theKey == K_LEFT:
                    this.x += this.speed
                elif this.theKey == K_RIGHT:
                    this.x -= this.speed
            elif pointInWedge(3, row*blockSize, col*blockSize, this.x, this.y+this.h):
                this.y -= this.speed
                this.yVel = 0
            elif this.pointInBlock(row*blockSize, col*blockSize, this.x, this.y):
                if this.theKey == K_LEFT:
                    this.x += this.speed
                elif this.theKey == K_RIGHT:
                    this.x -= this.speed
        elif key[0] == 4:
            if pointInWedge(4, row*blockSize, col*blockSize, this.x, this.y+this.h) or pointInWedge(4, row*blockSize, col*blockSize, this.x+this.w, this.y) or pointInWedge(4, row*blockSize, col*blockSize, this.x+this.w, this.y+this.h):
                if this.theKey == K_LEFT:
                    this.x += this.speed
                elif this.theKey == K_RIGHT:
                    this.x -= this.speed
            elif pointInWedge(4, row*blockSize, col*blockSize, this.x, this.y):
                this.y += this.speed
            elif this.pointInBlock(row*blockSize, col*blockSize, this.x, this.y+this.h):
                if this.theKey == K_LEFT:
                    this.x += this.speed
                elif this.theKey == K_RIGHT:
                    this.x -= this.speed
        elif key[0] == 5:
            if pointInWedge(5, row*blockSize, col*blockSize, this.x, this.y) or pointInWedge(5, row*blockSize, col*blockSize, this.x, this.y+this.h) or pointInWedge(5, row*blockSize, col*blockSize, this.x+this.w, this.y+this.h):
                if this.theKey == K_LEFT:
                    this.x += this.speed
                elif this.theKey == K_RIGHT:
                    this.x -= this.speed
            elif pointInWedge(5, row*blockSize, col*blockSize, this.x+this.w, this.y):
                this.y += this.speed
            elif this.pointInBlock(row*blockSize, col*blockSize, this.x+this.w, this.y+this.h):
                if this.theKey == K_LEFT:
                    this.x += this.speed
                elif this.theKey == K_RIGHT:
                    this.x -= this.speed
    def Ycol(this, key, value):
        blockSize = 20
        row = key[1]
        col = key[2]
        if key[0] == 1:
            if this.x+this.w > row*blockSize and this.x < row*blockSize+blockSize and this.y+this.h > col*blockSize and this.y < col*blockSize+blockSize:
                if this.yVel > 0:
                    this.y = col*blockSize-this.h
                    this.yVel = 0
                else:
                    this.y -= this.yVel*1.1
                    this.yVel = 0.5
        elif key[0] != 0:
            onCorner = False
            if key[0] == 2:
                if pointInWedge(4, row*blockSize, col*blockSize, this.x, this.y+this.h):
                    onCorner = True
            if key[0] == 3:
                if pointInWedge(5, row*blockSize, col*blockSize, this.x+this.w, this.y+this.h):
                    onCorner = True
            if key[0] == 4:
                if pointInWedge(2, row*blockSize, col*blockSize, this.x+this.w, this.y):
                    onCorner = True
            if key[0] == 5:
                if pointInWedge(3, row*blockSize, col*blockSize, this.x, this.y):
                    onCorner = True
            if pointInWedge(key[0], row*blockSize, col*blockSize, this.x, this.y) or pointInWedge(key[0], row*blockSize, col*blockSize, this.x+this.w, this.y) or pointInWedge(key[0], row*blockSize, col*blockSize, this.x, this.y+this.h) or pointInWedge(key[0], row*blockSize, col*blockSize, this.x+this.w, this.y+this.h) or onCorner:
                if this.yVel > 0:
                    this.y -= this.yVel*1.1
                    this.yVel = 0
                else:
                    this.y -= this.yVel*1.1
                    this.yVel = 0.5

class Gun:

    def __init__(this, name, scale, translation, **kwargs):
        this.scale = scale
        this.translation = translation
        this.damage = kwargs.get("damage", 10)
        this.firerate = kwargs.get("firerate", 10)
        this.bulletspeed = kwargs.get("bulletspeed", 3)
        this.spread = kwargs.get("spread", 0)
        this.shots = kwargs.get("shots", 1)
        this.name = name
        this.shapes = pygame.image.load("guns/" + this.name + ".png")

    def draw(this, surface, scale, translation, rotation):
        while rotation > math.pi:
            rotation -= 2*math.pi
        while rotation < -math.pi:
            rotation += 2*math.pi
        originalRect = this.shapes.get_rect()
        if (rotation > -math.pi/2 and rotation < math.pi/2):
            flip = 1
            gunImage = pygame.transform.rotate(pygame.transform.flip(pygame.transform.scale(this.shapes, (round(originalRect.width*this.scale*scale), round(originalRect.height*this.scale*scale))), 0, 0), -rotation*180/math.pi)
        else:
            flip = -1
            gunImage = pygame.transform.rotate(pygame.transform.flip(pygame.transform.scale(this.shapes, (round(originalRect.width*this.scale*scale), round(originalRect.height*this.scale*scale))), 0, 1), -rotation*180/math.pi)
        gunRect = gunImage.get_rect()
        gunRect.center = (translation[0] + (math.cos(rotation)*this.translation[0]+math.cos(rotation+math.pi/2)*this.translation[1]*flip)*scale*this.scale, translation[1] + (math.sin(rotation)*this.translation[0]+math.sin(rotation+math.pi/2)*this.translation[1]*flip)*scale*this.scale)
        surface.blit(gunImage, gunRect)

guns = [
    Gun("Glock 19", 0.8, [300, 50], damage=5, firerate=20, bulletspeed=7, spread=3),
    Gun("Spas 12", 1, [300, -10], damage=4, firerate=40, bulletspeed=6, spread=10, shots=10),
    Gun("Howa 1500", 1.2, [300, -10], damage=20, firerate=30, bulletspeed=10, spread=1),
    Gun("PLR-16", 1, [300, -10], damage=3, firerate=1, bulletspeed=7, spread=20),
    Gun("AWM", 1.2, [300, -10], damage=45, firerate=80, bulletspeed=15, spread=1),
    Gun("AK-47", 0.9, [300, 100], damage=2, firerate=2, bulletspeed=7, spread=6),
]


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head or k <= 1:
            return head
        dummy = ListNode(-1)
        dummy.next = head
        temp = dummy
        while temp:
            temp = self.reverseNextK(temp, k)
        return dummy.next

    def reverseNextK(self, head, k):
        # Check if there are k nodes left
        temp = head
        for i in range(k):
            if not temp.next:
                return None
            temp = temp.next

        # The last node when the k nodes reversed
        node = head.next
        prev = head
        curr = head.next
        # Reverse k nodes
        for i in range(k):
            nextNode = curr.next
            curr.next = prev
            prev = curr
            curr = nextNode
        # Connect with head and tail
        node.next = curr
        head.next = prev
        return node

Leetcode分类/7. LinkedList/Leetcode_25_Reverse Nodes in k-Group/learning_solution.py


s=input()
n=int(input())
list1=[]

# list1 will store every row which will be created from input string by putting characters in zigzag pattern in the rows

for x in range(n):
    list1.append("")
k=2*n-2
for x in range(len(s)):
    k1=x%k             #after every k=2*n-2 positions the row index to which character to be appended will repeat
    if(k1<=n-2):
        list1[k1]+=s[x] #k1 acts as a referece by which we calculate the row index , in it's less than n-1 it will itself act as row index, otherwise "how much distant is from k " will act as row index

    else:
        k1=k-k1
        list1[k1]+=s[x]
res=""

for x in range(len(list1)):
    res+=list1[x]

print("input string:",s)
print("output string:",res)


import gcj

def paths_from(mx, i):
	pf = 0
	B = len(mx)

	if i == B - 1:
		return 0

	for j in range(i + 1, B):
		if j == B - 1 and mx[i][j]:
			pf += 1
		elif mx[i][j]:
			pf += paths_from(mx, j)

	#print("pf " + str(i) + " = " + str(pf))
	return pf

def check(mx, M):
	pf = paths_from(mx, 0)
	print(mx, M, pf)
	return pf == M

ifile, ofile = gcj.get_files('B')

T = int(ifile.readline().strip())
for t in range(T):
	B, M = map(int, ifile.readline().strip().split(' '))

	mx = [[0] * B for b in range(B)]

	for i in range(1, B):
		for j in range(i + 1, B):
			mx[i][j] = 1

	#print(str(1 << (B - 1)))

	if M > (1 << (B - 2)):
		ans = "IMPOSSIBLE"
	else:
		#print(B)
		i = 0
		while M > 0:
			#print(B)
			if M % 2 == 1:
				mx[0][B - 1 - i] = 1

			M >>= 1
			i += 1

	#	print(check(mx, M))
		ans = "POSSIBLE"
		for i in range(B):
			ans += "\n" + ''.join(list(map(str, mx[i])))

	gcj.print_answer(ofile, t, ans)


"""
Created on Fri Jan 27 10:10:19 2017

@author: Dan
"""
from fenics import *
import os
import numpy as np
import matplotlib.pyplot as plt

## Convert mesh from GMSH format
ifilename = 'cellMesh3.msh'
ofilename = ifilename.split('.')[0]+'.xml'
if not os.path.isfile('%s'%ofilename):
    os.system('dolfin-convert %s %s'%(ifilename, ofilename))

# Import the mesh and determine relevant boundaries/subdomains
mesh = Mesh(ofilename)
subdomains = MeshFunction("size_t", mesh, "%s_physical_region.xml"%ofilename.split('.')[0])
boundaries = MeshFunction("size_t", mesh, "%s_facet_region.xml"%ofilename.split('.')[0])

# Rename subdomain numbers from GMSH
rename_subdomains = CellFunction("size_t", mesh)
rename_subdomains.set_all(0)
rename_subdomains.array()[subdomains.array()==0] = 1
rename_subdomains.array()[subdomains.array()==1] = 2

# Rename boundary numbers from GMSH
rename_boundaries = FacetFunction("size_t", mesh)
rename_boundaries.set_all(0)
rename_boundaries.array()[boundaries.array()==55] = 1
rename_boundaries.array()[boundaries.array()==56] = 2
rename_boundaries.array()[boundaries.array()==57] = 3

# print([len(rename_boundaries.array()[rename_boundaries.array()==3]),
#        len(rename_boundaries.array()[rename_boundaries.array()==2]),
#        len(rename_boundaries.array()[rename_boundaries.array()==1]),
#        len(rename_boundaries.array()[rename_boundaries.array()==0])])
#
# print([len(rename_subdomains.array()[rename_subdomains.array()==2]),
#        len(rename_subdomains.array()[rename_subdomains.array()==1]),
#        len(rename_subdomains.array()[rename_subdomains.array()==0])])

# Rename interface numbers from GMSH
rename_interface = FacetFunction("size_t", mesh)
rename_interface.set_all(0)
rename_interface.array()[boundaries.array()==33] = 1

# Generate test/trial functions in function space
V = FunctionSpace(mesh, 'CG', 1)
u = TrialFunction(V)
v = TestFunction(V)
dx = Measure("dx", domain=mesh, subdomain_data=rename_subdomains)
ds = Measure("ds", domain=mesh, subdomain_data=rename_boundaries)

## Define boundary conditions
source = 1.0
sink = 0.0

bcs = [ DirichletBC(V, source, rename_boundaries, 1),
        DirichletBC(V, sink, rename_boundaries, 2),
        DirichletBC(V, sink, rename_boundaries, 3)]

# Define material properties
pi = 1e-9
po = 1.0

## Assemble parts of problem
f = Constant(0)
g = Constant(0)
a0 = inner(po*nabla_grad(u), nabla_grad(v))*dx(1)
a1 = inner(pi*nabla_grad(u), nabla_grad(v))*dx(2)
a = a0 + a1
L = f*v*dx(1) + f*v*dx(2)

## Redefine u as a function in function space V for the solution
u = Function(V)

## Solve PDE and store solution in u
set_log_level(PROGRESS)
solve(a == L, u, bcs)

## Save solution to file in VTK format
ofile = 'Cell/StaticCellModel_asdf.pvd'
print('  [+] Output to %s'%(ofile))
vtkfile = File(ofile)
vtkfile << u


"""Algorithms for spectral clustering"""

# Author: Gael Varoquaux <gael.varoquaux@normalesup.org>
#         Brian Cheung
#         Wei LI <kuantkid@gmail.com>
#         Andrew Knyazev <Andrew.Knyazev@ucdenver.edu>
# License: BSD 3 clause

import warnings
from numbers import Integral, Real

import numpy as np
from scipy.linalg import LinAlgError, qr, svd
from scipy.sparse import csc_matrix

from ..base import BaseEstimator, ClusterMixin, _fit_context
from ..manifold import spectral_embedding
from ..metrics.pairwise import KERNEL_PARAMS, pairwise_kernels
from ..neighbors import NearestNeighbors, kneighbors_graph
from ..utils import as_float_array, check_random_state
from ..utils._param_validation import Interval, StrOptions, validate_params
from ._kmeans import k_means

def cluster_qr(vectors):
    """Find the discrete partition closest to the eigenvector embedding.

        This implementation was proposed in [1]_.

    .. versionadded:: 1.1

        Parameters
        ----------
        vectors : array-like, shape: (n_samples, n_clusters)
            The embedding space of the samples.

        Returns
        -------
        labels : array of integers, shape: n_samples
            The cluster labels of vectors.

        References
        ----------
        .. [1] :doi:`Simple, direct, and efficient multi-way spectral clustering, 2019
            Anil Damle, Victor Minden, Lexing Ying
            <10.1093/imaiai/iay008>`

    """

    k = vectors.shape[1]
    _, _, piv = qr(vectors.T, pivoting=True)
    ut, _, v = svd(vectors[piv[:k], :].T)
    vectors = abs(np.dot(vectors, np.dot(ut, v.conj())))
    return vectors.argmax(axis=1)

def discretize(
    vectors, *, copy=True, max_svd_restarts=30, n_iter_max=20, random_state=None
):
    """Search for a partition matrix which is closest to the eigenvector embedding.

    This implementation was proposed in [1]_.

    Parameters
    ----------
    vectors : array-like of shape (n_samples, n_clusters)
        The embedding space of the samples.

    copy : bool, default=True
        Whether to copy vectors, or perform in-place normalization.

    max_svd_restarts : int, default=30
        Maximum number of attempts to restart SVD if convergence fails

    n_iter_max : int, default=30
        Maximum number of iterations to attempt in rotation and partition
        matrix search if machine precision convergence is not reached

    random_state : int, RandomState instance, default=None
        Determines random number generation for rotation matrix initialization.
        Use an int to make the randomness deterministic.
        See :term:`Glossary <random_state>`.

    Returns
    -------
    labels : array of integers, shape: n_samples
        The labels of the clusters.

    References
    ----------

    .. [1] `Multiclass spectral clustering, 2003
           Stella X. Yu, Jianbo Shi
           <https://people.eecs.berkeley.edu/~jordan/courses/281B-spring04/readings/yu-shi.pdf>`_

    Notes
    -----

    The eigenvector embedding is used to iteratively search for the
    closest discrete partition.  First, the eigenvector embedding is
    normalized to the space of partition matrices. An optimal discrete
    partition matrix closest to this normalized embedding multiplied by
    an initial rotation is calculated.  Fixing this discrete partition
    matrix, an optimal rotation matrix is calculated.  These two
    calculations are performed until convergence.  The discrete partition
    matrix is returned as the clustering solution.  Used in spectral
    clustering, this method tends to be faster and more robust to random
    initialization than k-means.

    """

    random_state = check_random_state(random_state)

    vectors = as_float_array(vectors, copy=copy)

    eps = np.finfo(float).eps
    n_samples, n_components = vectors.shape

    # Normalize the eigenvectors to an equal length of a vector of ones.
    # Reorient the eigenvectors to point in the negative direction with respect
    # to the first element.  This may have to do with constraining the
    # eigenvectors to lie in a specific quadrant to make the discretization
    # search easier.
    norm_ones = np.sqrt(n_samples)
    for i in range(vectors.shape[1]):
        vectors[:, i] = (vectors[:, i] / np.linalg.norm(vectors[:, i])) * norm_ones
        if vectors[0, i] != 0:
            vectors[:, i] = -1 * vectors[:, i] * np.sign(vectors[0, i])

    # Normalize the rows of the eigenvectors.  Samples should lie on the unit
    # hypersphere centered at the origin.  This transforms the samples in the
    # embedding space to the space of partition matrices.
    vectors = vectors / np.sqrt((vectors**2).sum(axis=1))[:, np.newaxis]

    svd_restarts = 0
    has_converged = False

    # If there is an exception we try to randomize and rerun SVD again
    # do this max_svd_restarts times.
    while (svd_restarts < max_svd_restarts) and not has_converged:
        # Initialize first column of rotation matrix with a row of the
        # eigenvectors
        rotation = np.zeros((n_components, n_components))
        rotation[:, 0] = vectors[random_state.randint(n_samples), :].T

        # To initialize the rest of the rotation matrix, find the rows
        # of the eigenvectors that are as orthogonal to each other as
        # possible
        c = np.zeros(n_samples)
        for j in range(1, n_components):
            # Accumulate c to ensure row is as orthogonal as possible to
            # previous picks as well as current one
            c += np.abs(np.dot(vectors, rotation[:, j - 1]))
            rotation[:, j] = vectors[c.argmin(), :].T

        last_objective_value = 0.0
        n_iter = 0

        while not has_converged:
            n_iter += 1

            t_discrete = np.dot(vectors, rotation)

            labels = t_discrete.argmax(axis=1)
            vectors_discrete = csc_matrix(
                (np.ones(len(labels)), (np.arange(0, n_samples), labels)),
                shape=(n_samples, n_components),
            )

            t_svd = vectors_discrete.T * vectors

            try:
                U, S, Vh = np.linalg.svd(t_svd)
            except LinAlgError:
                svd_restarts += 1
                print("SVD did not converge, randomizing and trying again")
                break

            ncut_value = 2.0 * (n_samples - S.sum())
            if (abs(ncut_value - last_objective_value) < eps) or (n_iter > n_iter_max):
                has_converged = True
            else:
                # otherwise calculate rotation and continue
                last_objective_value = ncut_value
                rotation = np.dot(Vh.T, U.T)

    if not has_converged:
        raise LinAlgError("SVD did not converge")
    return labels

@validate_params(
    {"affinity": ["array-like", "sparse matrix"]},
    prefer_skip_nested_validation=False,
)
def spectral_clustering(
    affinity,
    *,
    n_clusters=8,
    n_components=None,
    eigen_solver=None,
    random_state=None,
    n_init=10,
    eigen_tol="auto",
    assign_labels="kmeans",
    verbose=False,
):
    """Apply clustering to a projection of the normalized Laplacian.

    In practice Spectral Clustering is very useful when the structure of
    the individual clusters is highly non-convex or more generally when
    a measure of the center and spread of the cluster is not a suitable
    description of the complete cluster. For instance, when clusters are
    nested circles on the 2D plane.

    If affinity is the adjacency matrix of a graph, this method can be
    used to find normalized graph cuts [1]_, [2]_.

    Read more in the :ref:`User Guide <spectral_clustering>`.

    Parameters
    ----------
    affinity : {array-like, sparse matrix} of shape (n_samples, n_samples)
        The affinity matrix describing the relationship of the samples to
        embed. **Must be symmetric**.

        Possible examples:
          - adjacency matrix of a graph,
          - heat kernel of the pairwise distance matrix of the samples,
          - symmetric k-nearest neighbours connectivity matrix of the samples.

    n_clusters : int, default=None
        Number of clusters to extract.

    n_components : int, default=n_clusters
        Number of eigenvectors to use for the spectral embedding.

    eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'}
        The eigenvalue decomposition method. If None then ``'arpack'`` is used.
        See [4]_ for more details regarding ``'lobpcg'``.
        Eigensolver ``'amg'`` runs ``'lobpcg'`` with optional
        Algebraic MultiGrid preconditioning and requires pyamg to be installed.
        It can be faster on very large sparse problems [6]_ and [7]_.

    random_state : int, RandomState instance, default=None
        A pseudo random number generator used for the initialization
        of the lobpcg eigenvectors decomposition when `eigen_solver ==
        'amg'`, and for the K-Means initialization. Use an int to make
        the results deterministic across calls (See
        :term:`Glossary <random_state>`).

        .. note::
            When using `eigen_solver == 'amg'`,
            it is necessary to also fix the global numpy seed with
            `np.random.seed(int)` to get deterministic results. See
            https://github.com/pyamg/pyamg/issues/139 for further
            information.

    n_init : int, default=10
        Number of time the k-means algorithm will be run with different
        centroid seeds. The final results will be the best output of n_init
        consecutive runs in terms of inertia. Only used if
        ``assign_labels='kmeans'``.

    eigen_tol : float, default="auto"
        Stopping criterion for eigendecomposition of the Laplacian matrix.
        If `eigen_tol="auto"` then the passed tolerance will depend on the
        `eigen_solver`:

        - If `eigen_solver="arpack"`, then `eigen_tol=0.0`;
        - If `eigen_solver="lobpcg"` or `eigen_solver="amg"`, then
          `eigen_tol=None` which configures the underlying `lobpcg` solver to
          automatically resolve the value according to their heuristics. See,
          :func:`scipy.sparse.linalg.lobpcg` for details.

        Note that when using `eigen_solver="lobpcg"` or `eigen_solver="amg"`
        values of `tol<1e-5` may lead to convergence issues and should be
        avoided.

        .. versionadded:: 1.2
           Added 'auto' option.

    assign_labels : {'kmeans', 'discretize', 'cluster_qr'}, default='kmeans'
        The strategy to use to assign labels in the embedding
        space.  There are three ways to assign labels after the Laplacian
        embedding.  k-means can be applied and is a popular choice. But it can
        also be sensitive to initialization. Discretization is another
        approach which is less sensitive to random initialization [3]_.
        The cluster_qr method [5]_ directly extracts clusters from eigenvectors
        in spectral clustering. In contrast to k-means and discretization, cluster_qr
        has no tuning parameters and is not an iterative method, yet may outperform
        k-means and discretization in terms of both quality and speed.

        .. versionchanged:: 1.1
           Added new labeling method 'cluster_qr'.

    verbose : bool, default=False
        Verbosity mode.

        .. versionadded:: 0.24

    Returns
    -------
    labels : array of integers, shape: n_samples
        The labels of the clusters.

    Notes
    -----
    The graph should contain only one connected component, elsewhere
    the results make little sense.

    This algorithm solves the normalized cut for `k=2`: it is a
    normalized spectral clustering.

    References
    ----------

    .. [1] :doi:`Normalized cuts and image segmentation, 2000
           Jianbo Shi, Jitendra Malik
           <10.1109/34.868688>`

    .. [2] :doi:`A Tutorial on Spectral Clustering, 2007
           Ulrike von Luxburg
           <10.1007/s11222-007-9033-z>`

    .. [3] `Multiclass spectral clustering, 2003
           Stella X. Yu, Jianbo Shi
           <https://people.eecs.berkeley.edu/~jordan/courses/281B-spring04/readings/yu-shi.pdf>`_

    .. [4] :doi:`Toward the Optimal Preconditioned Eigensolver:
           Locally Optimal Block Preconditioned Conjugate Gradient Method, 2001
           A. V. Knyazev
           SIAM Journal on Scientific Computing 23, no. 2, pp. 517-541.
           <10.1137/S1064827500366124>`

    .. [5] :doi:`Simple, direct, and efficient multi-way spectral clustering, 2019
           Anil Damle, Victor Minden, Lexing Ying
           <10.1093/imaiai/iay008>`

    .. [6] :doi:`Multiscale Spectral Image Segmentation Multiscale preconditioning
           for computing eigenvalues of graph Laplacians in image segmentation, 2006
           Andrew Knyazev
           <10.13140/RG.2.2.35280.02565>`

    .. [7] :doi:`Preconditioned spectral clustering for stochastic block partition
           streaming graph challenge (Preliminary version at arXiv.)
           David Zhuzhunashvili, Andrew Knyazev
           <10.1109/HPEC.2017.8091045>`
    """

    clusterer = SpectralClustering(
        n_clusters=n_clusters,
        n_components=n_components,
        eigen_solver=eigen_solver,
        random_state=random_state,
        n_init=n_init,
        affinity="precomputed",
        eigen_tol=eigen_tol,
        assign_labels=assign_labels,
        verbose=verbose,
    ).fit(affinity)

    return clusterer.labels_

class SpectralClustering(ClusterMixin, BaseEstimator):
    """Apply clustering to a projection of the normalized Laplacian.

    In practice Spectral Clustering is very useful when the structure of
    the individual clusters is highly non-convex, or more generally when
    a measure of the center and spread of the cluster is not a suitable
    description of the complete cluster, such as when clusters are
    nested circles on the 2D plane.

    If the affinity matrix is the adjacency matrix of a graph, this method
    can be used to find normalized graph cuts [1]_, [2]_.

    When calling ``fit``, an affinity matrix is constructed using either
    a kernel function such the Gaussian (aka RBF) kernel with Euclidean
    distance ``d(X, X)``::

            np.exp(-gamma * d(X,X) ** 2)

    or a k-nearest neighbors connectivity matrix.

    Alternatively, a user-provided affinity matrix can be specified by
    setting ``affinity='precomputed'``.

    Read more in the :ref:`User Guide <spectral_clustering>`.

    Parameters
    ----------
    n_clusters : int, default=8
        The dimension of the projection subspace.

    eigen_solver : {'arpack', 'lobpcg', 'amg'}, default=None
        The eigenvalue decomposition strategy to use. AMG requires pyamg
        to be installed. It can be faster on very large, sparse problems,
        but may also lead to instabilities. If None, then ``'arpack'`` is
        used. See [4]_ for more details regarding `'lobpcg'`.

    n_components : int, default=None
        Number of eigenvectors to use for the spectral embedding. If None,
        defaults to `n_clusters`.

    random_state : int, RandomState instance, default=None
        A pseudo random number generator used for the initialization
        of the lobpcg eigenvectors decomposition when `eigen_solver ==
        'amg'`, and for the K-Means initialization. Use an int to make
        the results deterministic across calls (See
        :term:`Glossary <random_state>`).

        .. note::
            When using `eigen_solver == 'amg'`,
            it is necessary to also fix the global numpy seed with
            `np.random.seed(int)` to get deterministic results. See
            https://github.com/pyamg/pyamg/issues/139 for further
            information.

    n_init : int, default=10
        Number of time the k-means algorithm will be run with different
        centroid seeds. The final results will be the best output of n_init
        consecutive runs in terms of inertia. Only used if
        ``assign_labels='kmeans'``.

    gamma : float, default=1.0
        Kernel coefficient for rbf, poly, sigmoid, laplacian and chi2 kernels.
        Ignored for ``affinity='nearest_neighbors'``.

    affinity : str or callable, default='rbf'
        How to construct the affinity matrix.
         - 'nearest_neighbors': construct the affinity matrix by computing a
           graph of nearest neighbors.
         - 'rbf': construct the affinity matrix using a radial basis function
           (RBF) kernel.
         - 'precomputed': interpret ``X`` as a precomputed affinity matrix,
           where larger values indicate greater similarity between instances.
         - 'precomputed_nearest_neighbors': interpret ``X`` as a sparse graph
           of precomputed distances, and construct a binary affinity matrix
           from the ``n_neighbors`` nearest neighbors of each instance.
         - one of the kernels supported by
           :func:`~sklearn.metrics.pairwise.pairwise_kernels`.

        Only kernels that produce similarity scores (non-negative values that
        increase with similarity) should be used. This property is not checked
        by the clustering algorithm.

    n_neighbors : int, default=10
        Number of neighbors to use when constructing the affinity matrix using
        the nearest neighbors method. Ignored for ``affinity='rbf'``.

    eigen_tol : float, default="auto"
        Stopping criterion for eigen decomposition of the Laplacian matrix.
        If `eigen_tol="auto"` then the passed tolerance will depend on the
        `eigen_solver`:

        - If `eigen_solver="arpack"`, then `eigen_tol=0.0`;
        - If `eigen_solver="lobpcg"` or `eigen_solver="amg"`, then
          `eigen_tol=None` which configures the underlying `lobpcg` solver to
          automatically resolve the value according to their heuristics. See,
          :func:`scipy.sparse.linalg.lobpcg` for details.

        Note that when using `eigen_solver="lobpcg"` or `eigen_solver="amg"`
        values of `tol<1e-5` may lead to convergence issues and should be
        avoided.

        .. versionadded:: 1.2
           Added 'auto' option.

    assign_labels : {'kmeans', 'discretize', 'cluster_qr'}, default='kmeans'
        The strategy for assigning labels in the embedding space. There are two
        ways to assign labels after the Laplacian embedding. k-means is a
        popular choice, but it can be sensitive to initialization.
        Discretization is another approach which is less sensitive to random
        initialization [3]_.
        The cluster_qr method [5]_ directly extract clusters from eigenvectors
        in spectral clustering. In contrast to k-means and discretization, cluster_qr
        has no tuning parameters and runs no iterations, yet may outperform
        k-means and discretization in terms of both quality and speed.

        .. versionchanged:: 1.1
           Added new labeling method 'cluster_qr'.

    degree : float, default=3
        Degree of the polynomial kernel. Ignored by other kernels.

    coef0 : float, default=1
        Zero coefficient for polynomial and sigmoid kernels.
        Ignored by other kernels.

    kernel_params : dict of str to any, default=None
        Parameters (keyword arguments) and values for kernel passed as
        callable object. Ignored by other kernels.

    n_jobs : int, default=None
        The number of parallel jobs to run when `affinity='nearest_neighbors'`
        or `affinity='precomputed_nearest_neighbors'`. The neighbors search
        will be done in parallel.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    verbose : bool, default=False
        Verbosity mode.

        .. versionadded:: 0.24

    Attributes
    ----------
    affinity_matrix_ : array-like of shape (n_samples, n_samples)
        Affinity matrix used for clustering. Available only after calling
        ``fit``.

    labels_ : ndarray of shape (n_samples,)
        Labels of each point

    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 0.24

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Defined only when `X`
        has feature names that are all strings.

        .. versionadded:: 1.0

    See Also
    --------
    sklearn.cluster.KMeans : K-Means clustering.
    sklearn.cluster.DBSCAN : Density-Based Spatial Clustering of
        Applications with Noise.

    Notes
    -----
    A distance matrix for which 0 indicates identical elements and high values
    indicate very dissimilar elements can be transformed into an affinity /
    similarity matrix that is well-suited for the algorithm by
    applying the Gaussian (aka RBF, heat) kernel::

        np.exp(- dist_matrix ** 2 / (2. * delta ** 2))

    where ``delta`` is a free parameter representing the width of the Gaussian
    kernel.

    An alternative is to take a symmetric version of the k-nearest neighbors
    connectivity matrix of the points.

    If the pyamg package is installed, it is used: this greatly
    speeds up computation.

    References
    ----------
    .. [1] :doi:`Normalized cuts and image segmentation, 2000
           Jianbo Shi, Jitendra Malik
           <10.1109/34.868688>`

    .. [2] :doi:`A Tutorial on Spectral Clustering, 2007
           Ulrike von Luxburg
           <10.1007/s11222-007-9033-z>`

    .. [3] `Multiclass spectral clustering, 2003
           Stella X. Yu, Jianbo Shi
           <https://people.eecs.berkeley.edu/~jordan/courses/281B-spring04/readings/yu-shi.pdf>`_

    .. [4] :doi:`Toward the Optimal Preconditioned Eigensolver:
           Locally Optimal Block Preconditioned Conjugate Gradient Method, 2001
           A. V. Knyazev
           SIAM Journal on Scientific Computing 23, no. 2, pp. 517-541.
           <10.1137/S1064827500366124>`

    .. [5] :doi:`Simple, direct, and efficient multi-way spectral clustering, 2019
           Anil Damle, Victor Minden, Lexing Ying
           <10.1093/imaiai/iay008>`

    Examples
    --------
    >>> from sklearn.cluster import SpectralClustering
    >>> import numpy as np
    >>> X = np.array([[1, 1], [2, 1], [1, 0],
    ...               [4, 7], [3, 5], [3, 6]])
    >>> clustering = SpectralClustering(n_clusters=2,
    ...         assign_labels='discretize',
    ...         random_state=0).fit(X)
    >>> clustering.labels_
    array([1, 1, 1, 0, 0, 0])
    >>> clustering
    SpectralClustering(assign_labels='discretize', n_clusters=2,
        random_state=0)
    """

    _parameter_constraints: dict = {
        "n_clusters": [Interval(Integral, 1, None, closed="left")],
        "eigen_solver": [StrOptions({"arpack", "lobpcg", "amg"}), None],
        "n_components": [Interval(Integral, 1, None, closed="left"), None],
        "random_state": ["random_state"],
        "n_init": [Interval(Integral, 1, None, closed="left")],
        "gamma": [Interval(Real, 0, None, closed="left")],
        "affinity": [
            callable,
            StrOptions(
                set(KERNEL_PARAMS)
                | {"nearest_neighbors", "precomputed", "precomputed_nearest_neighbors"}
            ),
        ],
        "n_neighbors": [Interval(Integral, 1, None, closed="left")],
        "eigen_tol": [
            Interval(Real, 0.0, None, closed="left"),
            StrOptions({"auto"}),
        ],
        "assign_labels": [StrOptions({"kmeans", "discretize", "cluster_qr"})],
        "degree": [Interval(Integral, 0, None, closed="left")],
        "coef0": [Interval(Real, None, None, closed="neither")],
        "kernel_params": [dict, None],
        "n_jobs": [Integral, None],
        "verbose": ["verbose"],
    }

    def __init__(
        self,
        n_clusters=8,
        *,
        eigen_solver=None,
        n_components=None,
        random_state=None,
        n_init=10,
        gamma=1.0,
        affinity="rbf",
        n_neighbors=10,
        eigen_tol="auto",
        assign_labels="kmeans",
        degree=3,
        coef0=1,
        kernel_params=None,
        n_jobs=None,
        verbose=False,
    ):
        self.n_clusters = n_clusters
        self.eigen_solver = eigen_solver
        self.n_components = n_components
        self.random_state = random_state
        self.n_init = n_init
        self.gamma = gamma
        self.affinity = affinity
        self.n_neighbors = n_neighbors
        self.eigen_tol = eigen_tol
        self.assign_labels = assign_labels
        self.degree = degree
        self.coef0 = coef0
        self.kernel_params = kernel_params
        self.n_jobs = n_jobs
        self.verbose = verbose

    @_fit_context(prefer_skip_nested_validation=True)
    def fit(self, X, y=None):
        """Perform spectral clustering from features, or affinity matrix.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
                (n_samples, n_samples)
            Training instances to cluster, similarities / affinities between
            instances if ``affinity='precomputed'``, or distances between
            instances if ``affinity='precomputed_nearest_neighbors``. If a
            sparse matrix is provided in a format other than ``csr_matrix``,
            ``csc_matrix``, or ``coo_matrix``, it will be converted into a
            sparse ``csr_matrix``.

        y : Ignored
            Not used, present here for API consistency by convention.

        Returns
        -------
        self : object
            A fitted instance of the estimator.
        """
        X = self._validate_data(
            X,
            accept_sparse=["csr", "csc", "coo"],
            dtype=np.float64,
            ensure_min_samples=2,
        )
        allow_squared = self.affinity in [
            "precomputed",
            "precomputed_nearest_neighbors",
        ]
        if X.shape[0] == X.shape[1] and not allow_squared:
            warnings.warn(
                "The spectral clustering API has changed. ``fit``"
                "now constructs an affinity matrix from data. To use"
                " a custom affinity matrix, "
                "set ``affinity=precomputed``."
            )

        if self.affinity == "nearest_neighbors":
            connectivity = kneighbors_graph(
                X, n_neighbors=self.n_neighbors, include_self=True, n_jobs=self.n_jobs
            )
            self.affinity_matrix_ = 0.5 * (connectivity + connectivity.T)
        elif self.affinity == "precomputed_nearest_neighbors":
            estimator = NearestNeighbors(
                n_neighbors=self.n_neighbors, n_jobs=self.n_jobs, metric="precomputed"
            ).fit(X)
            connectivity = estimator.kneighbors_graph(X=X, mode="connectivity")
            self.affinity_matrix_ = 0.5 * (connectivity + connectivity.T)
        elif self.affinity == "precomputed":
            self.affinity_matrix_ = X
        else:
            params = self.kernel_params
            if params is None:
                params = {}
            if not callable(self.affinity):
                params["gamma"] = self.gamma
                params["degree"] = self.degree
                params["coef0"] = self.coef0
            self.affinity_matrix_ = pairwise_kernels(
                X, metric=self.affinity, filter_params=True, **params
            )

        random_state = check_random_state(self.random_state)
        n_components = (
            self.n_clusters if self.n_components is None else self.n_components
        )
        # We now obtain the real valued solution matrix to the
        # relaxed Ncut problem, solving the eigenvalue problem
        # L_sym x = lambda x  and recovering u = D^-1/2 x.
        # The first eigenvector is constant only for fully connected graphs
        # and should be kept for spectral clustering (drop_first = False)
        # See spectral_embedding documentation.
        maps = spectral_embedding(
            self.affinity_matrix_,
            n_components=n_components,
            eigen_solver=self.eigen_solver,
            random_state=random_state,
            eigen_tol=self.eigen_tol,
            drop_first=False,
        )
        if self.verbose:
            print(f"Computing label assignment using {self.assign_labels}")

        if self.assign_labels == "kmeans":
            _, self.labels_, _ = k_means(
                maps,
                self.n_clusters,
                random_state=random_state,
                n_init=self.n_init,
                verbose=self.verbose,
            )
        elif self.assign_labels == "cluster_qr":
            self.labels_ = cluster_qr(maps)
        else:
            self.labels_ = discretize(maps, random_state=random_state)

        return self

    def fit_predict(self, X, y=None):
        """Perform spectral clustering on `X` and return cluster labels.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
                (n_samples, n_samples)
            Training instances to cluster, similarities / affinities between
            instances if ``affinity='precomputed'``, or distances between
            instances if ``affinity='precomputed_nearest_neighbors``. If a
            sparse matrix is provided in a format other than ``csr_matrix``,
            ``csc_matrix``, or ``coo_matrix``, it will be converted into a
            sparse ``csr_matrix``.

        y : Ignored
            Not used, present here for API consistency by convention.

        Returns
        -------
        labels : ndarray of shape (n_samples,)
            Cluster labels.
        """
        return super().fit_predict(X, y)

    def _more_tags(self):
        return {
            "pairwise": self.affinity in [
                "precomputed",
                "precomputed_nearest_neighbors",
            ]
        }


import re

class ExtratorURL:
    def __init__(self: object, url: str) -> None:
        self.url = self.sanitiza_url(url)
        self.valida_url()

    def sanitiza_url(self: object, url: str) -> str:
        if isinstance(url, str):
            return url.strip()
        else:
            return ''

    def valida_url(self: object) -> None:
        if not self.url:
            raise ValueError('A URL está vazia')

        padrao_url = re.compile(
            '(http(s)?://)?(www.)?bytebank.com(.br)?/cambio'
        )
        match = padrao_url.match(url)
        if not match:
            raise ValueError('A URL não é válida')

    def get_url_base(self: object) -> str:
        indice_interrogacao = self.url.find('?')
        url_base = self.url[:indice_interrogacao]
        return url_base

    def get_url_parametro(self: object) -> str:
        indice_interrogacao = self.url.find('?')

        if indice_interrogacao:
            url_parametro = self.url[indice_interrogacao + 1 :]
            return url_parametro

    def get_valor_parametro(self: object, parametro_busca) -> int:
        indice_parametro = self.get_url_parametro().find(parametro_busca)
        indice_valor = indice_parametro + len(parametro_busca) + 1
        indice_e_comercial = self.get_url_parametro().find('&', indice_valor)

        if indice_e_comercial == -1:
            valor = self.get_url_parametro()[indice_valor:]
        else:
            valor = self.get_url_parametro()[indice_valor:indice_e_comercial]
        return valor

    def __len__(self: object) -> int:
        return len(self.url)

    def __str__(self: object) -> str:
        return f'{self.url}\nParâmetros: {self.get_url_parametro()}\nURL Base: {self.get_url_base()}'

    def __eq__(self: object, other: str) -> bool:
        return self.url == other.url

url = "bytebank.com/cambio?quantidade=100&moedaOrigem=dolar&moedaDestino=real"
extrator_url = ExtratorURL(url)

print(f'O tamanho da URL é de {len(extrator_url)} caracteres')
print(extrator_url)

moeda_origem = extrator_url.get_valor_parametro('moedaOrigem')
moeda_destino = extrator_url.get_valor_parametro('moedaDestino')
quantidade = extrator_url.get_valor_parametro('quantidade')

valor_dolar = 5.50

def consersao_moeda() -> None:
    if moeda_origem == 'dolar' and moeda_destino == 'real':
        conversao = int(quantidade) * valor_dolar
        print(
            f'{quantidade} dolares convertidos para real dá {conversao} reais'
        )
    elif moeda_origem == 'real' and moeda_destino == 'dolar':
        conversao = int(quantidade) // valor_dolar
        print(
            f'{quantidade} reais convertidos para dolar dá {conversao} dolares'
        )

consersao_moeda()


from compute_graph import ComputeNode, register_computation

GEOSPATIAL_NODE_TYPE = "geospatial"
functions = ["subset", "subregion", "lat", "lon", "time", "lev", "axis"]

INVALID_GEOSPATIAL_FUNC = "Expected geospatial function; received '%s'."

@register_computation(GEOSPATIAL_NODE_TYPE)
def compute_geo(attributes):
    array = attributes["array"]
    func = attributes["func"]
    args = attributes.get("args", {})

    if func == "subset":
        return array(**args)

    if func == "subregion":
        return array.subRegion(**args)

    if func == "lat":
        return array.getLatitude()

    if func == "lon":
        return array.getLongitude()

    if func == "time":
        return array.getTime()

    if func == "lev":
        return array.getLevel()

    if func == "axis":
        return array.getAxis(args["index"])

class GeospatialFunction(ComputeNode):
    def __init__(self, func, array, **args):
        super(GeospatialFunction, self).__init__()
        self.node_type = GEOSPATIAL_NODE_TYPE
        self.node_params = {
            "func": "Function used for calculation.",
            "array": "Array to perform function on"
        }
        if func not in functions:
            raise ValueError(INVALID_GEOSPATIAL_FUNC % func)
        self.func = func
        self.array = array
        if args:
            self.args = args


import numpy as np

from . import _GradientDescent
from toolboxTom.logger import Logger

log = Logger(name='ProximalDescent')

class ProximalDescent(_GradientDescent):
    """Gradient Descent with the nesterov momentum"""
    def __init__(self, problem, decreasing_rate='', f_theta='boyd',
                 restart=False, debug=0, **kwargs):
        self.restart = restart
        if debug > 0:
            debug -= 1
            log.set_level(10)
        super(ProximalDescent, self).__init__(
            problem, decreasing_rate=decreasing_rate,
            debug=debug, **kwargs)
        self.theta = [1, 1]
        if type(f_theta) is float:
            self.theta = [1-f_theta]*2
        self.p_grad = np.zeros(self.pb.pt.shape)
        self.f_theta = f_theta
        self.alpha = 1/self.pb.L

    def __repr__(self):
        return ('Proximal Descent' +
                (' with Restart' if self.restart else ''))

    def p_update(self):
        '''Update the parameters with the nesterov momentum
        '''
        self.ppt = self.pb.pt

        lr = self._get_lr()
        lmbd = self.pb.lmbd
        ak, ak1 = self.theta
        self.yn = self.pb.pt+ak*(1/ak1-1)*self.p_grad
        grad = self.pb.grad(self.yn)

        self.pb._update(self.pb.prox(self.yn-lr*grad, lmbd*lr))

        # Restart if needed
        res_cond = (self.yn - self.pb.pt).dot((self.pb.pt - self.ppt).T).sum()
        if self.restart and res_cond > 0:
            log.debug('Restart')
            self.yn = self.ppt
            grad = self.pb.grad(self.yn)
            self.pb._update(self.pb.prox(self.yn-lr*grad, lmbd*lr))

        #Update momentum information
        self.p_grad = self.pb.pt-self.ppt
        self.theta = [self._theta(ak), ak]
        return np.sum(self.p_grad*self.p_grad)

    def _theta(self, ak):
        if self.f_theta == 'boyd':
            ak2 = ak*ak
            return (np.sqrt(ak2*ak2+4*ak2)-ak2)/2
        if self.f_theta == 'k2':
            return 2/(self.t+3)
        elif type(self.f_theta) == float:
            return 1-self.f_theta
        return 0.2


#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__		= "HSC, GDT, MCU"
__date__		= "$March 8, 2011 12:02:34 PM$"
__version__		= "0.1.0.1"
__copyright__		= "Copytight 2011 %s" %__author__
__webpage__		= "http://code.google.com/p/gml/"

REPO = "http://www.infoiasi.ro/gml/repo.lst"
LOCAL_REPOSITORY = "repo.lst"

# === DO NOT MODIFY BELOW ===

import sys, os, re, hashlib, zipfile, shutil

if sys.version_info < (2, 6):
	raise("Not tested on this version of python. If you think it might work, please disable this check.")
	from urllib import urlretrieve
elif sys.version_info > (3, 0):
	from urllib.request import urlretrieve
else:
	from urllib import urlretrieve

from ctypes import *
from glob import glob
from time import strftime, localtime, sleep
from os.path import basename, dirname, isfile, exists, join
from os import makedirs
from os import name as OS_TYPE

plugin_data = {"algorithms":"alg", "connectors":"dbc", "databases":"db", "notifiers":"ntf"}

class OParse:
	__options = {}

	def __init__(self, argv, version):
		self.argv = argv
		self.version = version

		self.add_option('version', short_alias='-v', long_alias='--version', param_nr=0, help='Display version information and exit', callback=self.display_version)
		self.add_option('help', short_alias='-h', long_alias='--help', param_nr=0, help='Display commands and a description', callback=self.usage)

	def __is_short_opt(self, opt):
		if not opt.startswith("-") or len(opt) != 2:
			return ""
		for _opt in self.__options.keys():
			if self.__options[_opt].short_alias == opt.lower():
				return self.__options[_opt].__name__

	def __is_long_opt(self, opt):
		if not opt.startswith("--") or len(opt) < 4:
			return ""
		for _opt in self.__options.keys():
			if self.__options[_opt].long_alias == opt.lower():
				return self.__options[_opt].__name__

	def display_version(self, params):
		print("Version: %s" %self.version)

	def usage(self, params):
		from os.path import basename
		print("Usage: %s command [options]\n\nCommands:" %basename(self.argv[0]))
		options = [x for x in self.__options.keys()]
		options.sort()
		for opt in options:
			tmp_params = "0"
			if self.__options[opt].param_nr < 0:
				tmp_params = "variable number"
			else:
				if self.__options[opt].param_nr == 0:
					tmp_params = "None"
				else:
					tmp_params = str(self.__options[opt].param_nr)
			if self.__options[opt].accept_no_param:
				tmp_params += " (use with 0 parameters for more info)"
			print("  %s, %s, %s\n\tdescription: %s\n\tparameters: %s" %(
				self.__options[opt].__name__,
				self.__options[opt].short_alias,
				self.__options[opt].long_alias,
				self.__options[opt].help,
				tmp_params)
			)

	def add_option(self, name, short_alias="", long_alias="", param_nr=0, accept_no_param=False, help="", callback=None):
		name = name.lower()
		short_alias = short_alias.lower()
		long_alias = long_alias.lower()
		if name in self.__options.keys():
			raise NameError("Duplicate option: %s" %name)
		for argv in self.__options.keys():
			if self.__options[argv].short_alias == short_alias:
				raise NameError("Duplicate short alias: %s. Already used for '%s' option." %(short_alias, argv))
			if self.__options[argv].long_alias == long_alias:
				raise NameError("Duplicate long alias: %s. Already used for '%s' option." %(long_alias, argv))
		tmp_obj = type(
				name,
				(object,),
				{
					'callback':callback,
					'help':help,
					'short_alias':short_alias.lower(),
					'long_alias':long_alias.lower(),
					'param_nr':param_nr,
					'accept_no_param':accept_no_param
				}
			      )
		self.__options[name] = tmp_obj

	def parse(self):
		if len(sys.argv) == 1:
			self.usage([])
			return
		consumed = []
		for argv in self.argv[1:]:
			if argv in consumed:
				continue
			tmp = ""
			if not argv in self.__options.keys():
				tmp = self.__is_short_opt(argv)
				if tmp == "":
					tmp = self.__is_long_opt(argv)
				if tmp == "" and not tmp is None:
					print("Unknown option: %s" %argv)
					return
				else:
					argv = tmp
			opt = self.__options[argv]
			if opt.param_nr == -1:
				opt.param_nr = len(self.argv) - 2
			if len(self.argv) < 2 + opt.param_nr and not opt.accept_no_param: #FIXME
				print("[ERROR] Expecting %d parameters" %opt.param_nr)
				return
			if not opt.callback is None:
				opt.callback(self.argv[2:2+opt.param_nr])
			else:
				print("[WARN] No callback function for '%s' option set!" %argv)
			consumed += (self.argv[:2+opt.param_nr])
			break #FIXME: allows only one command at a time
		if len(consumed) != len(self.argv):
			print("Some options did not get parsed") #TODO: add what options

def md5sum(filePath):
	md5 = hashlib.md5()
	file = open(filePath, "rb")
	while True:
		data = file.read(8192)
		if not data:
			break
		md5.update(data)
	file.close()
	return md5.hexdigest()

def __add_to_path(path):
	if OS_TYPE == 'nt':
		from winreg import CreateKey, SetValueEx, QueryValueEx, HKEY_CURRENT_USER, REG_EXPAND_SZ
		from win32gui import SendMessage
		from win32con import HWND_BROADCAST, WM_SETTINGCHANGE
		envpath = None
		HKCU = HKEY_CURRENT_USER
		ENV = "Environment"
		PATH = "PATH"
		DEFAULT = "%PATH%"
		with CreateKey(HKCU, ENV) as key:
			try:
				envpath = QueryValueEx(key, PATH)[0]
			except WindowsError:
				envpath = DEFAULT
			paths = [envpath]
			if path and path not in envpath and os.path.isdir(path):
					paths.append(path)
			envpath = os.pathsep.join(paths)
			try:
				SetValueEx(key, PATH, 0, REG_EXPAND_SZ, envpath)
				SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, 'Environment')
			except WindowsError:
				return False
			return True
	else:
		return False

def __add_to_pypath(path):
	if OS_TYPE == 'nt':
		from winreg import CreateKey, SetValueEx, QueryValueEx, HKEY_LOCAL_MACHINE, REG_SZ
		envpath = ""
		HKLM = HKEY_LOCAL_MACHINE
		PythonPath = r"SOFTWARE\Python\PythonCore\%s\PythonPath" %sys.version.split()[0] #FIXME: 3.1.3 --> 3.1
		with CreateKey(HKLM, PythonPath) as key:
			try:
				envpath = QueryValueEx(key, "")[0]
			except WindowsError:
				return False
			paths = [envpath]
			if path and path not in envpath and os.path.isdir(path):
					paths.append(path)
			envpath = os.pathsep.join(paths)
			try:
				SetValueEx(key, "", 0, REG_SZ, envpath)
			except WindowsError:
				return False
			return True
	else:
		return False

def add_to_path(path):
	cm = ConsoleMessages()
	cm.print_msg("\n[Registry operations]")
	if not __add_to_path(path):
		cm.print_error("Could not add GML root dir to PATH")
		exit(1)
	else:
		cm.print_msg("  [ -- ] Done adding GML root dir to PATH. Changes will be\n  visible in a new command line")
	#if not __add_to_pypath(path):
	#	cm.print_error("Could not add GML root dir to PYTHONPATH")
	#	exit(1)
	#else:
	#	cm.print_msg("  [ -- ] Done adding GML root dir to PYTHONPATH")

class Plugin:
	__no_data = b"No data set"

	def __init__(self, plg_name):
		self.plg_name = plg_name
		self.__cm = ConsoleMessages()
		try:
			self.dll = CDLL(self.plg_name)
		except:
			self.__cm.print_error("Could not load plugin: %s" %self.plg_name)

	def get_author(self):
		author = c_char_p(self.__no_data)
		try:
			author = c_char_p(self.dll.GetInterfaceAuthor())
		except:
			pass
		if author.value is None or author.value == "":
			return self.__no_data.decode('ascii')
		else:
			return author.value.decode('ascii')

	def get_description(self):
		description = c_char_p(self.__no_data)
		try:
			description = c_char_p(self.dll.GetInterfaceDescription())
		except:
			pass
		if description.value is None or description.value == "":
			return self.__no_data.decode('ascii')
		else:
			return description.value.decode('ascii')

	def get_version(self, ret_type=str):
		version = c_int(0)
		try:
			version = c_int(self.dll.GetInterfaceVersion())
		except:
			pass
		if version.value is None or version.value == 0:
			return self.__no_data
		else:
			return version.value

	def get_properties(self):
		tmp_fname = b"~prop.tmp"
		ret = "\n"
		ready = c_bool(False)
		try:
			ready = c_bool(self.dll.SaveInterfaceTemplate(c_char_p(tmp_fname)))
		except:
			pass
		if ready:
			RFILE = None
			lines = []
			try:
				RFILE = open(tmp_fname, "rt")
				lines = RFILE.readlines()
			except:
				pass
			finally:
				if RFILE != None:
					RFILE.close()
				if os.path.isfile(tmp_fname):
					try:
						os.remove(tmp_fname)
					except:
						pass
			ignore = False
			for line in lines:
				line = line.strip();
				if len(line) == 0:
					continue
				if line.startswith("["):
					ignore = True
				if line.endswith("]"):
					ignore = False
					continue
				if ignore:
					continue
				ret += "\t" + line + "\n"
		return ret

class ConsoleMessages:
	def __source_info(self):
		return sys._getframe(2).f_code.co_filename, sys._getframe(2).f_lineno, sys._getframe(2).f_code.co_name

	def __timestamp(self):
		return strftime("%d %b %Y %H:%M:%S", localtime())

	def print_error(self, msg):
		fname, line, func = self.__source_info()
		print("[ERROR]\n   Message\t: %s\n   Source\t: %s:%d::%s\n   Timestamp\t: %s" %(msg, fname, line, func, self.__timestamp()))
		return False

	def print_msg(self, msg):
		print(msg)

class unzip:
	cm = None
	def __init__(self, verbose = False, percent = 10):
		self.verbose = verbose
		self.percent = percent
		self.cm = ConsoleMessages()

	def __makedirs(self, fname, basedir):
		directories = self.__listdirs(fname)
		for dname in directories:
			curdir = join(basedir, dname).replace("/","")
			if not exists(curdir):
				try:
					makedirs(curdir)
				except:
					return self.cm.print_error("Could not create directory: \"%s\"" %curdir)
		return True

	def __listdirs(self, fname):
		zf = zipfile.ZipFile(fname)
		dirs = []
		for name in zf.namelist():
			if name.endswith('/'):
				dirs.append(name)
		dirs.sort()
		return dirs

	def extract(self, fname, root):
		if not isfile(fname):
			return self.cm.print_error("File doesn't exist: \"%s\"" %fname)

		if not root.endswith(':') and not exists(root):
			try:
				makedirs(root)
			except:
				return cm.print_error("Could not make root directory: \"%s\"" %root)

		zf = zipfile.ZipFile(fname)
		if zf.testzip() != None:
			return self.cm.print_error("Invalid zip archive: \"%s\"" %fname)

		zf.extractall(path=root)
		return True

class Downloader:
	repository = None
	cm = None
	root = ""
	lrepo_file = ""

	def __init__(self, repository=None, root=""):
		self.repository = repository
		self.root = root
		self.lrepo_file = join(self.root, LOCAL_REPOSITORY)
		self.cm = ConsoleMessages()

	def __report_hook(self, numblocks, blocksize, filesize, dest):
		try:
			percent = min((numblocks*blocksize*100)/filesize, 100)
		except:
			percent = 100
		if numblocks != 0:
			sys.stdout.write("\b"*70)
			sys.stdout.write("  [%3d%%] %-61s" % (percent, dest))

	def update(self):
		self.cm.print_msg("[Update process]")
		ret = True
		if self.repository == None:
			return False
		if not self.download(self.repository, self.lrepo_file):
			return False
		if isfile(self.lrepo_file):
			RFILE = None
			lines = []
			try:
				RFILE = open(self.lrepo_file)
				lines = RFILE.readlines()
			except:
				return False
			finally:
				if RFILE != None:
					RFILE.close()
			for line in lines:
				line = line.strip()
				if len(line) == 0 or line.startswith("#"):
					continue
				sline = line.split("|")
				if len(sline) != 4:
					return self.cm.print_error("Invalid line in repo.lst: \"%s\". Update/Install will not continue" %line)
				if sline[0].startswith("action="):
					action = sline[0].split("=")[-1]
					if action == "get":
						fname = join(self.root, sline[2])
						if isfile(fname):
							if sline[3] != md5sum(fname):
								ret &= self.download(sline[1], fname)
							else:
								sys.stdout.write("  [ -- ] %-61s [OK]\n" %fname)
						else:
							ret &= self.download(sline[1], fname)
					elif action == "inflate":
						unz = unzip()
						sys.stdout.write("Inflating %s ..." %sline[1])
						if not unz.extract(join(self.root, sline[1]), join(self.root, sline[2])):
							return False
						sys.stdout.write("\b"*70)
						sys.stdout.write("  [ -- ] Inflating %-51s [OK]\n" %fname)
					else:
						return self.cm.print_error("Unknown action from repository file: \"%s\". Will not continue" %action)
				else:
					return self.cm.print_error("Unknown repository format")
		else:
			ret = False
		return ret

	def download(self, src, dest):
		sys.stdout.write("Download: " + src)
		if not exists(dirname(dest)):
			try:
				makedirs(dirname(dest))
			except:
				return self.cm.print_error("Could not create target dir: \"%s\"" %dirname(dest))
		try:
			if sys.stdout.isatty():
				urlretrieve(src, dest, lambda nb, bs, fs, dst=dest: self.__report_hook(nb, bs, fs, dst))
			else:
				urlretrieve(src, dest)
		except:
			sys.stdout.write(" [ERROR]\n")
			return False
		else:
			sys.stdout.write(" [OK]\n")
		return True

class ActionHandler:
	def __init__(self, root):
		self.__cm = ConsoleMessages()
		self.__root = os.path.dirname(root)

	def handle_install(self, params):
		if os.path.exists(params[0]):
			if os.path.isfile(params[0]):
				self.__cm.print_error("Installation directory exists and it is a file. Install aborted")
				return False
		else:
			try:
				os.makedirs(params[0])
			except:
				self.__cm.print_error("Could not create %s. Please check is user has enough rights" %params[0])
				return False
		self.__install_root = params[0]
		d = Downloader(repository=REPO, root=params[0])
		if not d.update():
			self.__cm.print_error("Could not update GML")
			return False
		add_to_path(params[0])
		try:
			shutil.copyfile(os.path.join(self.__install_root, "gmllib.py"), os.path.join(sys.prefix, "Lib\\gmllib.py"))
		except:
			self.__cm.print_error("Could not copy 'gmllib.py' to %s" %(os.path.join(sys.prefix, "Lib")))
		WFILE = None
		try:
			WFILE = open(os.path.join(sys.prefix, "Lib\\gmllib.py"), "wt")
			WFILE.write("""import sys
sys.path.append(r'%s')
from attributelist import *
from ialgorithm import *
from builder import *
""" %os.path.join(self.__install_root, "Python"))
			WFILE.close()
		except:
			self.__cm.print_error("Could not modify 'gmllib.py'")
		try:
			shutil.move(os.path.join(self.__install_root, "gmllib.py"), os.path.join(self.__install_root, "gmllib.py.bak"))
		except:
			pass
		self.__cm.print_msg("== Done ==")

	def handle_list(self, params, show_info=False):
		if len(params) == 0:
			self.__cm.print_msg("Posible parameters:")
			for elem in plugin_data.keys():
				self.__cm.print_msg("  %s" %elem)
		else:
			param = params[0].lower()
			err = True
			for lparam in [x.lower() for x in plugin_data.keys()]: #FIXME: beautifie code
				for found in re.findall(param, lparam):
					found = found.lower()
					if found in [x.lower() for x in plugin_data.keys()]:
						err = False
						for fname in glob(os.path.join(os.path.join(self.__root, found), "*." + plugin_data[found])):
							self.__cm.print_msg("%s" %os.path.basename(fname).split(".")[0])
							if show_info:
								plugin = Plugin(fname)
								self.__cm.print_msg("  Author: %s\n  Version: %d\n  Description: %s\n  Properties: %s\n" %(plugin.get_author(), plugin.get_version(), plugin.get_description(), plugin.get_properties()))
			if err:
				self.__cm.print_msg("Unknown parameter for 'list' command: %s" %param)
				return

	def handle_info(self, params):
		if len(params) < 2:
			self.handle_list(params, show_info=True)

if __name__ == '__main__':
	action_handler = ActionHandler(sys.argv[0])
	optparse = OParse(sys.argv, "0.1.0.1")
	optparse.add_option('info',
				short_alias='-i',
				long_alias='--info',
				param_nr=-1,
				accept_no_param=True,
				help='Display a description for the given plugins',
				callback=action_handler.handle_info)
	optparse.add_option('list',
				short_alias='-l',
				long_alias='--list',
				param_nr=1,
				accept_no_param=True,
				help='List available options for given pattern',
				callback=action_handler.handle_list)
	optparse.add_option('install',
				long_alias='--install',
				param_nr=1,
				help='Install GML',
				callback=action_handler.handle_install)
	optparse.parse()


from shared import read_int, create_save_directory
import os
import struct

class Entry:
    def __init__(self):
        self.ID = None
        self.size = None
        self.neg = -1
        self.format = None

        self.data = None

    def load(self, stream):
        self.size = read_int(stream, 4)
        self.neg = read_int(stream, 4, sign=True)
        self.ID = read_int(stream, 4)
        self.format = read_int(stream, 4)

        if self.neg > 0: print(f"If you are seeing this lemme know: {self.ID}")

        self.data = stream.read(self.size)

class Pack:
    def __init__(self):
        self.ID = None
        self.entries = None

    def load(self, path):
        if not os.path.isfile(path):
            print(f"Unable to Open Requested File: {path}\n\tFile Not Found.")
            return False

        self.entries = []
        with open(path, "rb") as stream:
            self.ID = read_int(stream, 4)
            entry_count = read_int(stream, 4)
            offsets = [read_int(stream, 4) for x in range(entry_count)]
            for offset in offsets:
                stream.seek(offset)
                new_entry = Entry()
                new_entry.load(stream)
                self.entries.append(new_entry)
            return True

    def extract(self, path):
        if not self.entries:
            print("Unable to Extract Entries: None Have Been Loaded.")
            return False
        create_save_directory(path)

        print(f'Saving {len(self.entries)} Textures to: "{path}"')
        for index, entry in enumerate(self.entries):
            print(f'\tFile {index} : {path}/{index}.{"tga" if entry.format == 0 else ".dds"}')
            open(path + "/" + str(index) + (".tga" if entry.format == 0 else ".dds"), "wb").write(entry.data)
        return True


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        # two pointer with constant gap method
        dummyHead = ListNode(0, head)
        fast = slow = dummyHead
        for _ in range(n):
            fast = fast.next

        while fast.next:
            fast = fast.next
            slow = slow.next

        delNode = slow.next
        slow.next = delNode.next
        delNode.next = None
        del delNode

        head = dummyHead.next
        dummyHead.next = None
        del dummyHead

        return head


from setuptools.extension import Library, Extension
from setuptools import setup
from distutils.sysconfig import get_config_var

# "cpython-36m-x86_64-linux-gnu"
SOABI = get_config_var("SOABI")
# e.g. "linux"
MACHDEP = get_config_var("MACHDEP")
# e.g. "x86_64"
AR = get_config_var("AR").split("-")[0]
# e.g. "3.6"
VERSION = get_config_var("VERSION")

ACTUAL_LIB_DIR = "build/lib.%s-%s-%s" % (MACHDEP, AR, VERSION)

lib0 = Library("lib0",
               sources=["lib0/lib0.cpp"])

ext0 = Extension("_ext0",
                 sources=["ext0/ext0.cpp"],
                 include_dirs=["lib0/"],
                 libraries=["lib0." + SOABI],
                 library_dirs=[ACTUAL_LIB_DIR]
                 )

setup(
    name='exampe_setuptools',
    version='1.2',
    author='Michal Orsak',
    author_email='michal.o.socials@gmail.com',
    ext_modules=[lib0, ext0],
)


class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        sIndex: int = 0

        for tChar in t:
            if(sIndex == len(s)):
                return True
            elif(tChar == s[sIndex]):
                sIndex += 1

        return sIndex == len(s)


import torch
import torch.nn as nn
from torch.nn import init
import torch.nn.functional as F

import torch.utils.data
import math
device = torch.device("cuda:3" if torch.cuda.is_available() else "cpu")
class LayerNorm(nn.Module):
    """
    layer norm
    """
    def __init__(self,feature_dim,eps=1e-6):
        super(LayerNorm,self).__init__()
        self.gamma = nn.Parameter(torch.ones((feature_dim,)))
        self.register_parameter("gamma",self.gamma)
        self.beta = nn.Parameter(torch.zeros((feature_dim,)))
        self.register_parameter("beta",self.beta)
        self.eps = eps

    def forward(self,x):
        #x:[batch_size,embed_dim]
        mean = x.mean(-1,keepdim=True)
        std = x.std(-1,keepdim=True)
        return self.gamma*(x-mean)/(std+self.eps)+self.beta

def get_activation_function(activation,context_str):
    if activation == "leakyrelu":
        return nn.LeakyReLU(negative_slope=0.2)
    elif activation == "relu":
        return nn.ReLU()
    elif activation == "sigmoid":
        return nn.Sigmoid()
    elif activation == "tanh":
        return nn.Tanh()
    else:
        raise Exception("{} activation not recognized.".format(context_str+' '+activation))

class SingleFeedForwardNN(nn.Module):
    """
    single layer fully connected feed forward neural network
    """
    def __init__(self,input_dim,
                    output_dim,
                    dropout_rate=None,
                    activation="sigmoid",
                    use_layernormalize=False,
                    skip_connection=False,
                    context_str=""):
        super(SingleFeedForwardNN,self).__init__()
        self.input_dim = input_dim
        self.output_dim = output_dim

        if dropout_rate is not None:
            self.dropout = nn.Dropout(p=dropout_rate)
        else:
            self.dropout = None

        self.act = get_activation_function(activation,context_str)

        if use_layernormalize:
            self.layernorm = nn.LayerNorm(self.output_dim)
        else:
            self.layernorm = None

        if self.input_dim == self.output_dim:
            self.skip_connection = skip_connection
        else:
            self.skip_connection = False

        self.linear = nn.Linear(self.input_dim,self.output_dim)
        nn.init.xavier_uniform(self.linear.weight)

    def forward(self,input_tensor):
        assert input_tensor.size()[-1] == self.input_dim
        #Linear layer

        input_tensor = input_tensor.to(device)
        # print(device,input_tensor.is_cuda)
        output = self.linear(input_tensor)
        #non-linerity
        output = self.act(output)

        if self.dropout is not None:
            output = self.dropout(output)

        if self.skip_connection:
            output = output + input_tensor

        if self.layernorm is not None:
            output = self.layernorm(output)

        return output

class MultiLayerFeedForwardNN(nn.Module):
    """
    N fully connected feed forward NN
    """
    def __init__(self,input_dim,
                    output_dim,
                    num_hidden_layers=0,
                    dropout_rate=None,
                    hidden_dim=-1,
                    activation="sigmoid",
                    use_layernormalize=False,
                    skip_connection=False,
                    context_str=None):
        super(MultiLayerFeedForwardNN,self).__init__()
        self.input_dim = input_dim
        self.output_dim = output_dim
        self.num_hidden_layers = num_hidden_layers
        self.dropout_rate = dropout_rate
        self.hidden_dim = hidden_dim
        self.activation = activation
        self.use_layernormalize = use_layernormalize
        self.skip_connection = skip_connection
        self.context_str = context_str

        self.layers = nn.ModuleList()
        if self.num_hidden_layers <= 0:
            self.layers.append(SingleFeedForwardNN(input_dim=self.input_dim,
                                                   output_dim=self.output_dim,
                                                   dropout_rate=self.dropout_rate,
                                                   activation=self.activation,
                                                   use_layernormalize=False,
                                                   skip_connection=False,
                                                   context_str=self.context_str))
        else:
            self.layers.append(SingleFeedForwardNN(input_dim=self.input_dim,
                                                   output_dim=self.hidden_dim,
                                                   dropout_rate=self.dropout_rate,
                                                   activation=self.activation,
                                                   use_layernormalize=self.use_layernormalize,
                                                   skip_connection=self.skip_connection,
                                                   context_str=self.context_str))
            for i in range(self.num_hidden_layers-1):
                self.layers.append(SingleFeedForwardNN(input_dim=self.hidden_dim,
                                                   output_dim=self.hidden_dim,
                                                   dropout_rate=self.dropout_rate,
                                                   activation=self.activation,
                                                   use_layernormalize=self.use_layernormalize,
                                                   skip_connection=self.skip_connection,
                                                   context_str=self.context_str))

            self.layers.append(SingleFeedForwardNN(input_dim=self.hidden_dim,
                                                   output_dim=self.output_dim,
                                                   dropout_rate=self.dropout_rate,
                                                   activation=self.activation,
                                                   use_layernormalize=False,
                                                   skip_connection=False,
                                                   context_str=self.context_str))

    def forward(self,input_tensor):
        assert input_tensor.size()[-1] == self.input_dim
        input_tensor = input_tensor.to(device)
        # print(input_tensor.is_cuda)
        output = input_tensor
        for i in range(len(self.layers)):
            output = self.layers[i](output)
        return output

class ResLayer(nn.Module):
    def __init__(self,linear_size):
        super(ResLayer,self).__init__()
        self.l_size = linear_size
        self.nonlin1 = nn.ReLU(inplace=True)
        self.nonlin2 = nn.ReLU(inplace=True)
        self.dropout1 = nn.Dropout()
        self.w1 = nn.Linear(self.l_size,self.l_size)
        self.w2 = nn.Linear(self.l_size,self.l_size)

    def forward(self,x):
        y = self.w1(x)
        y = self.nonlin1(y)
        y = self.dropout1(y)
        y = self.w2(y)
        y = self.nonlin2(y)
        out = x+y
        return out

class FCNet(nn.Module):
    def __init__(self,num_inputs,num_filts,num_hidden_layers):
        super(FCNet,self).__init__()
        self.num_hidden_layers = num_hidden_layers
        self.feats = nn.Sequential()
        self.feats.add_module("ln_1",nn.Linear(num_inputs,num_filts))
        self.feats.add_module("relu_1",nn.ReLU(inplace=True))
        for i in range(num_hidden_layers):
            self.feats.add_module("resnet_{}".format(i+1),ResLayer(num_filts))

    def forward(self,x):
        loc_emb = self.feats(x)
        return loc_emb


# -------------------------------------------------------------------------------------------------
# Imports
# -------------------------------------------------------------------------------------------------

import asyncio
import base64
import sys
import logging
import traceback
from pathlib import Path
import json
import io
from pprint import pprint
import urllib.request

from joblib import Memory
import numpy as np
import websockets
from PIL import Image

from datoviz import Requester, Renderer

logger = logging.getLogger('datoviz')

class Bunch(dict):
    def __init__(self, *args, **kwargs):
        self.__dict__ = self
        super().__init__(*args, **kwargs)

# -------------------------------------------------------------------------------------------------
# CONSTANTS
# -------------------------------------------------------------------------------------------------

CURDIR = Path(__file__).parent.resolve()
WIDTH = 800
HEIGHT = 600
MAX_COUNT = 10_000_000
ALPHA = 128
SIZE = 5
COLOR = 128

DEFAULT_URI = "https://ibl.flatironinstitute.org/public/cortexlab/Subjects/KS023/2019-12-10/001/alf/probe01/"
SESSIONS = {
    "https://ibl.flatironinstitute.org/public/cortexlab/Subjects/KS023/2019-12-10/001/alf/probe01/": {
        "times": "spikes.times.99ed1a2d-bb18-4f86-92f3-23a15b7d9972.npy",
        "clusters": "spikes.clusters.2e3a207d-6b7a-41b3-80b9-d759a6557b55.npy",
        "depths": "spikes.depths.9cbed712-3d4e-44d4-8ec8-f915a884e667.npy"
    },

    "https://ibl.flatironinstitute.org/public/churchlandlab/Subjects/CSHL047/2020-01-20/001/alf/probe00/": {
        "times": "spikes.times.32609666-84f6-4b20-8450-afc311b3e64e.npy",
        "clusters": "spikes.clusters.a44513ba-069e-443a-bcb6-1de2a5071615.npy",
        "depths": "spikes.depths.879aedc4-227d-4234-828e-9d9f78b7323e.npy",
    },

    "https://ibl.flatironinstitute.org/public/mainenlab/Subjects/ZM_2240/2020-01-21/001/alf/probe00/": {
        "times": "spikes.times.be8c4562-f83d-45c3-ba4d-7ac9eec94b85.npy",
        "clusters": "spikes.clusters.33e2b747-8cf9-48d7-9814-69c6aa30cd59.npy",
        "depths": "spikes.depths.7ba042a8-cc40-416f-8390-12b0c8f4009f.npy",
    }
}

# -------------------------------------------------------------------------------------------------
# Data access
# -------------------------------------------------------------------------------------------------

MEMORY = Memory(".")

@MEMORY.cache
def download(url):
    with urllib.request.urlopen(url) as f:
        return io.BytesIO(f.read())

def normalize(x):
    m = x.min()
    M = x.max()
    if m == M:
        logger.warning("degenerate values")
        M = m + 1
    return -1 + 2 * (x - m) / (M - m)

def from_base64(buf):
    r = base64.decodebytes(buf.encode('ascii'))
    return np.frombuffer(r, dtype=np.uint8)

# -------------------------------------------------------------------------------------------------
# Renderer
# -------------------------------------------------------------------------------------------------

MVP_BUFFER = "AACAPwAAAAAAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAAAAAACAPwAAgD8AAAAAAAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAAAAAAAAgD8AAIA/AAAAAAAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAAAAAA=="
VIEWPORT_BUFFER = "AAAAAAAAAAAAAEhEAAAWRAAAAAAAAIA/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAwAAWAIAAAAAAAAAAAAAIAMAAFgCAAAAAAAAAAAAAAAAAAAAAAAA"

board_id = 1
graphics_id = 2
mvp_id = 10
viewport_id = 11
vertex_id = 3

def get_data(uri, st_name, sd_name, t0=0, t1=1):
    spike_times = np.load(download(uri + st_name))
    spike_depths = np.load(download(uri + sd_name))
    spike_depths[np.isnan(spike_depths)] = 0

    assert 0 <= t0 and t0 < t1

    # HACK: will need resize_dat request to lift this limitation
    assert spike_times.shape[0] <= MAX_COUNT

    # # DEBUG
    # spike_times = spike_times[:MAX_COUNT]
    # spike_depths = spike_depths[:MAX_COUNT]

    # Select spikes in the time range.
    imin = np.searchsorted(spike_times, t0)
    imax = np.searchsorted(spike_times, t1)

    logger.debug(f"downloaded {len(spike_times)} spikes, keep {imax - imin}")

    spike_times = spike_times[imin:imax]
    spike_depths = spike_depths[imin:imax]

    x = normalize(spike_times)
    y = normalize(spike_depths)

    n = spike_times.shape[0]
    arr = np.zeros(
        n, dtype=[('pos', np.float32, 3), ('color', np.uint8, 4), ('size', np.float32)])

    arr["pos"][:, 0] = x
    arr["pos"][:, 1] = y

    arr["size"][:] = SIZE

    v = COLOR
    a = ALPHA
    arr['color'][:, 0] = v
    arr['color'][:, 1] = v
    arr['color'][:, 2] = v
    arr['color'][:, 3] = a

    return arr

def record(rqr, count):
    logger.debug(f"draw {count} spikes")

    rqr.record_begin(board_id)
    rqr.record_viewport(board_id, 0, 0, 0, 0)
    rqr.record_draw(board_id, graphics_id, 0, count)
    rqr.record_end(board_id)

def create(rqr, rnd, uri, st_name, sd_name, t0=0, t1=1):
    with rqr.requests():
        rqr.create_board(WIDTH, HEIGHT, background=(
            255, 255, 255), id=board_id)
        rqr.create_graphics(board_id, 1, id=graphics_id)

        rqr.create_dat(5, 200, id=mvp_id)
        rqr.bind_dat(graphics_id, 0, mvp_id)
        rqr.upload_dat(mvp_id, 0, from_base64(MVP_BUFFER))

        rqr.create_dat(5, 80, id=viewport_id)
        rqr.bind_dat(graphics_id, 1, viewport_id)
        rqr.upload_dat(viewport_id, 0, from_base64(VIEWPORT_BUFFER))

        rqr.create_dat(2, 20 * MAX_COUNT, id=vertex_id)
        rqr.set_vertex(graphics_id, vertex_id)
        data = get_data(uri, st_name, sd_name, t0=t0, t1=t1)
        rqr.upload_dat(vertex_id, 0, data)

        record(rqr, data.shape[0])

    rqr.submit(rnd)

def update(rqr, rnd, uri, st_name, sd_name, t0=0, t1=1):
    with rqr.requests():
        data = get_data(uri, st_name, sd_name, t0=t0, t1=t1)
        rqr.upload_dat(vertex_id, 0, data)
        record(rqr, data.shape[0])
    rqr.submit(rnd)

def render(rqr, rnd, board_id=1):
    # Trigger a redraw.
    with rqr.requests():
        rqr.update_board(board_id)
    rqr.submit(rnd)

    # Get the image.
    img = rnd.get_png(board_id)
    logger.debug(f"retrieved the PNG image with {len(img)} bytes")

    # Return as PNG
    output = io.BytesIO(img)
    return output

# -------------------------------------------------------------------------------------------------
# Server
# -------------------------------------------------------------------------------------------------

async def process_requests(websocket):
    rqr = Requester()
    rnd = Renderer()
    created = False

    while True:
        try:
            msg = await websocket.recv()
            logger.debug("new message")
            msg = json.loads(msg)
            if 'set_session' in msg:
                uri = msg['set_session']['uri']
                st_name = msg['set_session']['spike_times']
                sd_name = msg['set_session']['spike_depths']
                t0 = msg['set_session'].get('start_time', 0)
                t1 = msg['set_session'].get('stop_time', 1)

                create(rqr, rnd, uri, st_name, sd_name, t0=t0, t1=t1)

            elif 'update_time' in msg:
                t0 = msg['update_time'].get('start_time', 0)
                t1 = msg['update_time'].get('stop_time', 1)

                update(rqr, rnd, uri, st_name, sd_name, t0=t0, t1=t1)

            img = render(rqr, rnd, 1)
            logger.debug(
                f"sending back the image with {img.getbuffer().nbytes} bytes...")
            img.seek(0)
            await websocket.send(img)
        except (websockets.ConnectionClosedOK, websockets.ConnectionClosedError):
            logger.debug("server connection closed")
            break
        except Exception as e:
            logger.error(traceback.format_exc())
            break
    logger.debug("server stopped")

async def server():
    async with websockets.serve(process_requests, "localhost", 1234, max_size=None):
        logger.info("Starting the websockets server")
        await asyncio.Future()  # run forever

# -------------------------------------------------------------------------------------------------
# Client
# -------------------------------------------------------------------------------------------------

async def set_session(websocket, uri, t0=0, t1=1):
    msg = {
        'set_session': {
            'uri': uri,
            'spike_times': SESSIONS[uri]['times'],
            'spike_depths': SESSIONS[uri]['depths'],
            'start_time': t0,
            'stop_time': t1,
        },
    }
    await websocket.send(json.dumps(msg))

async def update_time(websocket, t0=0, t1=1):
    msg = {
        'update_time': {
            'start_time': t0,
            'stop_time': t1,
        },
    }
    await websocket.send(json.dumps(msg))

async def recv_img(websocket, filename):
    logger.debug("client waiting for an incoming message...")
    buf = await websocket.recv()
    logger.info(f"received buffer with {len(buf)} bytes")
    with open(filename, 'wb') as f:
        f.write(buf)

async def client():
    async with websockets.connect("ws://localhost:1234", max_size=None) as websocket:
        try:
            logger.info("starting the websockets client")

            await set_session(websocket, DEFAULT_URI, t0=0, t1=100)
            await recv_img(websocket, 'img0.png')

            await update_time(websocket, t0=1000, t1=1010)
            await recv_img(websocket, 'img1.png')

            logger.info("stopping the websockets client")

        except Exception as e:
            logger.error(traceback.format_exc())

# -------------------------------------------------------------------------------------------------
# Entry-point
# -------------------------------------------------------------------------------------------------

if __name__ == "__main__":
    if len(sys.argv) <= 1 or sys.argv[-1] == 'server':
        asyncio.run(server())
    elif sys.argv[1] == 'client':
        asyncio.run(client())