import torch
from torch import nn

class ShellProvider(nn.Module):
    """
    This layer calculates distance of each atom in a molecule to its closest neighbouring atoms.

    Parameters
    ----------

    """
    def __init__(self):
        super(ShellProvider,self).__init__()

    def forward(self, atoms, neighbors,
                 cell=None, shift_vector=None, atom_idx=None, cutoff=None):
        """
        The main driver to calculate distances of atoms in a shell from center atom.

        Parameters
        ----------
        atoms: torch.Tensor
            XYZ coordinates of atoms in molecules.
            shape: (B, A, 3)

        neighbors: torch.Tensor
            index of neighbors of atoms.
            shape: (B, A/A', max_nbh)

        cell: torch.Tensor, optional (default: None)
            unit cell vectors. If cell is not None, shift_vector must be also provided.
            shape: (3, 3)

        shift_vector: torch.Tensor, optional (default: None)
            number of cell boundaries crossed by the bond between atom i and j
            (as presented by ASE library (ase.neighborlist module)
            shape: (B, A/A', N, 3)

        atom_idx: torch.Tensor, optional (default: None)
            Due to the memory explosion or any other considerations, only a few atoms in a molecule can
            be selected to be fed in to the next layers. The total number of atom_idx is the actual batch size.
            shape: (n_batch, n_atoms_masked)
            This is a list of indices, and if it's given, the batch size (n_batch) must be one.

        cutoff: float, optional (default: None)
            One last call to the cutoff for neighbour search. This helps to compile multiple resolutions, e.g., in a
            multi-channel model.

        Returns
        -------
        torch.Tensor: distance vector with shape: (B, A, N, 3)

        """
        # B: batch size
        # A: n_atoms
        # A': n_atoms_masked
        # N : max n_neighbours

        if atom_idx is not None:

            # sanity check
            if atom_idx.size()[0] != neighbors.size()[0] and neighbors.size()[0] > atoms.size()[0]:
                msg = '@ShellProvider: If atom_idx is provided, the first dimension of neighbors must be smaller than atoms.'
                raise ValueError(msg)

            # get positions of target atoms
            n_atoms = neighbors.shape[0]  # ==A'
            target_pos = atoms[atom_idx.view(n_atoms),:]              # A', 3
            # target_nbh = neighbours[atom_idx.view(n_atoms),:]             # A', N
            target_nbh_pos = atoms[neighbors, :]            # A', N, 3
            distance_vector = target_nbh_pos - target_pos[ :, None, :]    # A', N, 3

            # D = positions[j]-positions[i]+S.dot(cell)
            # S: shift_vector

            # add S.dot(cell)
            if cell is not None:        # 3, 3
                dim = shift_vector.size()
                shift = torch.bmm(shift_vector.view(dim[0], dim[1]*dim[2], dim[3]), cell)  # B, A'*N, 3
                shift = shift.view(dim)
                distance_vector = distance_vector + shift         # B, A', N, 3

            # distance = torch.norm(distance_vector, 2, 3)

        else:
            # get positions of target atoms
            n_atoms = neighbors.shape[0]  # ==A
            # target_nbh = neighbours[atom_idx.view(n_atoms),:]             # A, N
            target_nbh_pos = atoms[:, neighbors]  # B, A, N, 3
            distance_vector = target_nbh_pos - atoms[:, :, None, :]  # B, A, N, 3

            # D = positions[j]-positions[i]+S.dot(cell)
            # S: shift_vector

            # add S.dot(cell)
            if cell is not None:  # 3, 3
                dim = shift_vector.size()
                shift = torch.bmm(shift_vector.view(dim[0], dim[1] * dim[2], dim[3]), cell)  # B, A'*N, 3
                shift = shift.view(dim)
                distance_vector = distance_vector + shift  # B, A', N, 3

            # distance = torch.norm(distance_vector, 2, 3)

        return distance_vector

def atom_distances(
    positions,
    neighbors,
    cell=None,
    cell_offsets=None,
    return_vecs=False,
    normalize_vecs=False,
    neighbor_mask=None,
):
    r"""Compute distance of every atom to its neighbors.

    This function uses advanced torch indexing to compute differentiable distances
    of every central atom to its relevant neighbors.

    Args:
        positions (torch.Tensor):
            atomic Cartesian coordinates with (N_b x N_at x 3) shape
        neighbors (torch.Tensor):
            indices of neighboring atoms to consider with (N_b x N_at x N_nbh) shape
        cell (torch.tensor, optional):
            periodic cell of (N_b x 3 x 3) shape
        cell_offsets (torch.Tensor, optional) :
            offset of atom in cell coordinates with (N_b x N_at x N_nbh x 3) shape
        return_vecs (bool, optional): if True, also returns direction vectors.
        normalize_vecs (bool, optional): if True, normalize direction vectors.
        neighbor_mask (torch.Tensor, optional): boolean mask for neighbor positions.

    Returns:
        (torch.Tensor, torch.Tensor):
            distances:
                distance of every atom to its neighbors with
                (N_b x N_at x N_nbh) shape.

            dist_vec:
                direction cosines of every atom to its
                neighbors with (N_b x N_at x N_nbh x 3) shape (optional).

    """

    # Construct auxiliary index vector
    n_batch = positions.size()[0]
    idx_m = torch.arange(n_batch, device=positions.device, dtype=torch.long)[
        :, None, None
    ]
    # Get atomic positions of all neighboring indices
    pos_xyz = positions[idx_m, neighbors[:, :, :], :]

    # Subtract positions of central atoms to get distance vectors
    dist_vec = pos_xyz - positions[:, :, None, :]

    # add cell offset
    if cell is not None:
        B, A, N, D = cell_offsets.size()
        cell_offsets = cell_offsets.view(B, A * N, D)
        offsets = cell_offsets.bmm(cell)
        offsets = offsets.view(B, A, N, D)
        dist_vec += offsets

    # Compute vector lengths
    distances = torch.norm(dist_vec, 2, 3)

    if neighbor_mask is not None:
        # Avoid problems with zero distances in forces (instability of square
        # root derivative at 0) This way is neccessary, as gradients do not
        # work with inplace operations, such as e.g.
        # -> distances[mask==0] = 0.0
        tmp_distances = torch.zeros_like(distances)
        tmp_distances[neighbor_mask != 0] = distances[neighbor_mask != 0]
        distances = tmp_distances

    if return_vecs:
        tmp_distances = torch.ones_like(distances)
        tmp_distances[neighbor_mask != 0] = distances[neighbor_mask != 0]

        if normalize_vecs:
            dist_vec = dist_vec / tmp_distances[:, :, :, None]
        return distances, dist_vec
    return distances

class AtomDistances(nn.Module):
    r"""Layer for computing distance of every atom to its neighbors.

    Args:
        return_directions (bool, optional): if True, the `forward` method also returns
            normalized direction vectors.

    """

    def __init__(self, return_directions=False):
        super(AtomDistances, self).__init__()
        self.return_directions = return_directions

    def forward(
        self, positions, neighbors, cell=None, cell_offsets=None, neighbor_mask=None
    ):
        r"""Compute distance of every atom to its neighbors.

        Args:
            positions (torch.Tensor): atomic Cartesian coordinates with
                (N_b x N_at x 3) shape.
            neighbors (torch.Tensor): indices of neighboring atoms to consider
                with (N_b x N_at x N_nbh) shape.
            cell (torch.tensor, optional): periodic cell of (N_b x 3 x 3) shape.
            cell_offsets (torch.Tensor, optional): offset of atom in cell coordinates
                with (N_b x N_at x N_nbh x 3) shape.
            neighbor_mask (torch.Tensor, optional): boolean mask for neighbor
                positions. Required for the stable computation of forces in
                molecules with different sizes.

        Returns:
            torch.Tensor: layer output of (N_b x N_at x N_nbh) shape.

        """
        return atom_distances(
            positions,
            neighbors,
            cell,
            cell_offsets,
            return_vecs=self.return_directions,
            normalize_vecs=True,
            neighbor_mask=neighbor_mask,
        )

def triple_distances(
    positions,
    neighbors_j,
    neighbors_k,
    offset_idx_j=None,
    offset_idx_k=None,
    cell=None,
    cell_offsets=None,
):
    """
    Get all distances between atoms forming a triangle with the central atoms.
    Required e.g. for angular symmetry functions.

    Args:
        positions (torch.Tensor): Atomic positions
        neighbors_j (torch.Tensor): Indices of first neighbor in triangle
        neighbors_k (torch.Tensor): Indices of second neighbor in triangle
        offset_idx_j (torch.Tensor): Indices for offets of neighbors j (for PBC)
        offset_idx_k (torch.Tensor): Indices for offets of neighbors k (for PBC)
        cell (torch.tensor, optional): periodic cell of (N_b x 3 x 3) shape.
        cell_offsets (torch.Tensor, optional): offset of atom in cell coordinates
            with (N_b x N_at x N_nbh x 3) shape.

    Returns:
        torch.Tensor: Distance between central atom and neighbor j
        torch.Tensor: Distance between central atom and neighbor k
        torch.Tensor: Distance between neighbors

    """
    nbatch, _, _ = neighbors_k.size()
    idx_m = torch.arange(nbatch, device=positions.device, dtype=torch.long)[
        :, None, None
    ]

    pos_j = positions[idx_m, neighbors_j[:], :]
    pos_k = positions[idx_m, neighbors_k[:], :]

    if cell is not None:
        # Get the offsets into true cartesian values
        B, A, N, D = cell_offsets.size()

        cell_offsets = cell_offsets.view(B, A * N, D)
        offsets = cell_offsets.bmm(cell)
        offsets = offsets.view(B, A, N, D)

        # Get the offset values for j and k atoms
        B, A, T = offset_idx_j.size()

        # Collapse batch and atoms position for easier indexing
        offset_idx_j = offset_idx_j.view(B * A, T)
        offset_idx_k = offset_idx_k.view(B * A, T)
        offsets = offsets.view(B * A, -1, D)

        # Construct auxiliary aray for advanced indexing
        idx_offset_m = torch.arange(B * A, device=positions.device, dtype=torch.long)[
            :, None
        ]

        # Restore proper dmensions
        offset_j = offsets[idx_offset_m, offset_idx_j[:]].view(B, A, T, D)
        offset_k = offsets[idx_offset_m, offset_idx_k[:]].view(B, A, T, D)

        # Add offsets
        pos_j = pos_j + offset_j
        pos_k = pos_k + offset_k

    # if positions.is_cuda:
    #    idx_m = idx_m.pin_memory().cuda(async=True)

    # Get the real positions of j and k
    R_ij = pos_j - positions[:, :, None, :]
    R_ik = pos_k - positions[:, :, None, :]
    R_jk = pos_j - pos_k

    # + 1e-9 to avoid division by zero
    r_ij = torch.norm(R_ij, 2, 3) + 1e-9
    r_ik = torch.norm(R_ik, 2, 3) + 1e-9
    r_jk = torch.norm(R_jk, 2, 3) + 1e-9

    return r_ij, r_ik, r_jk

class TriplesDistances(nn.Module):
    """
    Layer that gets all distances between atoms forming a triangle with the
    central atoms. Required e.g. for angular symmetry functions.
    """

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

    def forward(self, positions, neighbors_j, neighbors_k):
        """
        Args:
            positions (torch.Tensor): Atomic positions
            neighbors_j (torch.Tensor): Indices of first neighbor in triangle
            neighbors_k (torch.Tensor): Indices of second neighbor in triangle

        Returns:
            torch.Tensor: Distance between central atom and neighbor j
            torch.Tensor: Distance between central atom and neighbor k
            torch.Tensor: Distance between neighbors

        """
        return triple_distances(positions, neighbors_j, neighbors_k)

def neighbor_elements(atomic_numbers, neighbors):
    """
    Return the atomic numbers associated with the neighboring atoms. Can also
    be used to gather other properties by neighbors if different atom-wise
    Tensor is passed instead of atomic_numbers.

    Args:
        atomic_numbers (torch.Tensor): Atomic numbers (Nbatch x Nat x 1)
        neighbors (torch.Tensor): Neighbor indices (Nbatch x Nat x Nneigh)

    Returns:
        torch.Tensor: Atomic numbers of neighbors (Nbatch x Nat x Nneigh)

    """
    # Get molecules in batch
    n_batch = atomic_numbers.size()[0]
    # Construct auxiliary index
    idx_m = torch.arange(n_batch, device=atomic_numbers.device, dtype=torch.long)[
        :, None, None
    ]
    # Get neighbors via advanced indexing
    neighbor_numbers = atomic_numbers[idx_m, neighbors[:, :, :]]
    return neighbor_numbers

class NeighborElements(nn.Module):
    """
    Layer to obtain the atomic numbers associated with the neighboring atoms.
    """

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

    def forward(self, atomic_numbers, neighbors):
        """
        Args:
            atomic_numbers (torch.Tensor): Atomic numbers (Nbatch x Nat x 1)
            neighbors (torch.Tensor): Neighbor indices (Nbatch x Nat x Nneigh)

        Returns:
            torch.Tensor: Atomic numbers of neighbors (Nbatch x Nat x Nneigh)
        """
        return neighbor_elements(atomic_numbers, neighbors)


import numpy as np
from PIL import Image

def apply_alpha(image, alpha):
    """Apply alpha to entire image, taking into account any existing alpha mask."""
    im = image.copy()
    if 'A' not in image.getbands():
        im.putalpha(int(round(alpha * 255)))
        return im
    elif image.mode == 'RGBA':
        a = bytes(bytearray((np.array(bytearray(image.split()[3].tobytes())) * alpha + 0.5).astype('int8')))
        im.putalpha(Image.frombytes('L', image.size, a))
        return im
    else:
        raise ValueError('incorrect image mode (was %s)' % image.mode)


"""

    get_google_API_data.py

    Gets google API data, for a certain set of keywords, for a given date

    Takes the following args:

    DATE: date to scrape for (format: yyyy-mm-dd) (e.g., 2020-02-16)

"""
import os
import sys
import re
import boto3
import pytrends
from pytrends.request import TrendReq
import pandas as pd
import datetime

if __name__ == "__main__":

    # get consts, creds, args
    KEYWORDS = ["covid", "coronavirus", "lockdown", "quarantine", "vaccine"]

    AWS_BUCKET = os.environ["AWS_BUCKET"]
    AWS_ACCESS = os.environ["AWS_ACCESS"]
    AWS_SECRET = os.environ["AWS_SECRET"]

    FRESH_SCRAPES_FILENAME = ""
    INTEREST_OVER_TIME_FILENAME = "interest_over_time_"
    INTEREST_BY_REGION_FILENAME = "interest_by_region_"

    LOCAL_SCRAPES_DIR = "../../tweets/google_API_scrapes/"
    AWS_SCRAPES_DIR = "google_API_scrapes/"

    LOCAL_TIME_FILENAME = LOCAL_SCRAPES_DIR + INTEREST_OVER_TIME_FILENAME
    LOCAL_REGION_FILENAME = LOCAL_SCRAPES_DIR + INTEREST_BY_REGION_FILENAME

    AWS_TIME_FILENAME = AWS_SCRAPES_DIR + INTEREST_OVER_TIME_FILENAME
    AWS_REGION_FILENAME = AWS_SCRAPES_DIR + INTEREST_BY_REGION_FILENAME

    DATE = sys.argv[1]

    # check DATE format
    REGEX = re.compile("^[0-9]{4}-[0-9]{2}-[0-9]{2}$")

    if not REGEX.match(DATE):
        raise ValueError(
            "DATE has incorrect format (must be in yyyy-mm-dd format)")

    # log into S3
    s3 = boto3.client('s3',
                      aws_access_key_id=AWS_ACCESS,
                      aws_secret_access_key=AWS_SECRET)

    print(f"Getting Google API trends data for {DATE}")

    try:
        # start API call
        pytrends_API = TrendReq()

        pytrends_API.build_payload(
            kw_list=KEYWORDS, geo="US", timeframe=f"{DATE} {DATE}")

        # get trends over time and by region, and export locally:
        pytrends_API.interest_over_time().to_csv(LOCAL_TIME_FILENAME + DATE + ".csv")
        pytrends_API.interest_by_region().to_csv(LOCAL_REGION_FILENAME + DATE + ".csv")

        # upload to AWS
        s3.upload_file(LOCAL_TIME_FILENAME + DATE + ".csv",
                       AWS_BUCKET, AWS_TIME_FILENAME + DATE + ".csv")
        s3.upload_file(LOCAL_REGION_FILENAME + DATE + ".csv",
                       AWS_BUCKET, AWS_REGION_FILENAME + DATE + ".csv")

        # delete local versions of the file
        os.remove(LOCAL_TIME_FILENAME + DATE + ".csv")
        os.remove(LOCAL_REGION_FILENAME + DATE + ".csv")

        print(f"Finished getting Google API trends data for {DATE}")

    except Exception as e:
        print("Error in getting Google API trends data")
        print(e)
        print(f"Error occurred for the following date: {DATE}")

    finally:
        print(
            f"Finished running get_google_API_data.py on (in UTC time): {datetime.datetime.utcnow()}")


# Exercício 3 - Crie a classe Smartphone com 2 atributos, tamanho e interface e crie a classe MP3Player com os
# atributos capacidade. A classe MP3player deve herdar os atributos da classe Smartphone.

class Smartphone():

  def __init__(self, tamanho=5, interface='8.0'):
    self.tamanho = tamanho
    self.interface = interface

class MP3Player(Smartphone):

  def __init__(self, capacidade=25):
    Smartphone.__init__(self)
    self.capacidade = capacidade

Ipod = MP3Player(30)

print(Ipod.tamanho)
print(Ipod.interface)
print(Ipod.capacidade)


S = int(input())
cnt = 0
result = 0

for i in range(1, S+1): # 1부터 자연수 S까지
    cnt += i
    result += 1
    if (cnt == S): break
    if ((S - cnt) <= i): # 남은 값이 자연수보다 작거나 같으면
        break

print(result)


import re

def extractWords(text):
	keywords = {}
	listUrl = {}
	listOfWords = []

	# On parcourt tous le retour Json
	for i in range(len(text)):
		url = text[i]['url']
		title = text[i]['title']
		description = text[i]['description']
		content = text[i]['content']

		# On concatène tous les string que l'on va analyser
		textToAnalyze = str(title) + ' ' + str(description) + ' ' + str(content)
		# Appel de la fonction pour 'nettoyer' les données à analyser
		listOfWords = normalizeWords(textToAnalyze)
		for word in listOfWords :
			if word not in keywords:   # Pour chaque mort
				keywords[word] = 1     # On initialise un compteur à 1
				listUrl[word] = [url]  # On initialise un tableau d'url
				listUrl[word].append(title)

			else :
				keywords[word] +=1
				if(url  not in listUrl[word]): # Si l'url n'est pas présente dans le tableau, on l'ajoute
					listUrl[word].append(url)
					listUrl[word].append(title)

	sortedKeyWord = sorted(keywords.items(), key=lambda x: x[1], reverse=True) # Tri des mots qui reviennent le plus souvent
	keywords.clear() # On va re créer notre dictionnaire de données
	for y in sortedKeyWord:
		keywords[y[0]] = {       # Pour chaque mot
			'compteur':y[1],     # Son compteur d'apparition
			'url':listUrl[y[0]],  # Sa liste d'URL
		}

	return keywords

# Charge une liste de mot 'inutile' d'un fichier .txt
def loadUselessWords():
	uselessWords = []
	with open('uselessWords.txt', encoding='utf-8') as f:
		for word in f.readlines():
			word = re.sub("\W","",word)
			uselessWords.append(word)
	return uselessWords

# Nettoie les mots à compter
def normalizeWords(text):
	uselessWords = loadUselessWords()
	normalizeWords = []

	text = re.sub("\W"," ",text) # Enlève tous les caractères qui ne sont pas des mots
	text = re.sub("\d+", " ",text) #Enlève les nombres
	text = text.lower()
	words = re.split("\s",text)
	# On enlève les mots de moins de 2 caractères
	for w in words :
		if(len(w) > 2 and w not in uselessWords):
			normalizeWords.append(w)

	return normalizeWords


from collections import deque

n = int(input())
quee = deque([i for i in range(1,n+1)])
while(len(quee)>1) :
    quee.popleft()
    num = quee.popleft()
    quee.append(num)

print(quee[0])


class ListNode:
  def __init__(self, x):
    self.val = x
    self.next = None

  def reverseListRecursive(self, head):
    if head == None:
      return None
    if head.next == None:
      return head
    second = head.next
    head.next = None
    reverseRest = self.reverseListRecursive(second)
    second.next = head
    return reverseRest

  def reverseListIterative(self, head):
    curr = head.next
    head.next = None
    prev = head
    while curr != None:
      temp = curr.next
      curr.next = prev
      prev = curr
      curr = temp
    return prev

  def arr2list(self, arr):
    head = ListNode(0)
    curr = head
    for (i, a) in enumerate(arr):
        curr.next = ListNode(a)
        curr = curr.next
    head = head.next
    return head

  def list2arr(self, head):
    arr = []
    while head != None:
        arr.append(head.val)
        head = head.next
    return arr

  def to_array(self):
    return self.list2arr(self)

# ln = ListNode(0)
# arr = [3, 5, 6]
# head = ln.arr2list(arr)
# # reveresed = ln.reverseListRecursive(head)
# reveresed = ln.reverseListIterative(head)
# print ln.list2arr(reveresed)


import pandas as pd, os
from bisect import bisect_left, bisect_right
from collections import defaultdict

class peak_table:
    def __init__(self, table_path):
        f = open(table_path, 'r')
        info = f.readlines()[1:]
        f.close()
        self.peaks = {}
        self.peaks_index = defaultdict(list)

        for line in info:
            cur_line = [x.strip() for x in line.split('\t')]
            chromosome, start, end = cur_line[0:3]
            width, total_signal, height = cur_line[4:7]
            cur_peak = peak(chromosome, int(start), int(end), int(width), float(total_signal), float(height))
            if chromosome in self.peaks:
                self.peaks[chromosome][start].add(cur_peak)
                self.peaks[chromosome][end].add(cur_peak)
            else:
                self.peaks[chromosome] = defaultdict(set)
                self.peaks[chromosome][start].add(cur_peak)
                self.peaks[chromosome][end].add(cur_peak)
        for chromosome in self.peaks.keys():
            self.peaks_index[chromosome] = sorted(self.peaks[chromosome].keys())

    def get_peaks(self, chromosome, start, end):
        indexes = self.peaks_index[chromosome]
        start_index = bisect_left(indexes, start)
        end_index = bisect_right(indexes, end)
        candidates = indexes[start_index:end_index]
        result_peaks = set()
        for c in candidates:
            for p in self.peaks[chromosome][c]:
                result_peaks.add(p)

        return result_peaks

class peak:
    def __init__(self, chromosome, start, end, width, total_signal, height):
        self.chromosome = chromosome
        self.start = start
        self.end = end
        self.width = width
        self.total_signal = total_signal
        self.height =height


p=list()

try:
  a=int(input())

except:
  print("Invalid Input")

else:
  i=2
  j=2
  while(i<=a):
    if(a%i == 0):
      print(i)
      if(i%j == 0):

        if(i == j):
          print(i)
          p.append(i)
          j-=1
    i+=1

Player/Set2/Prime No's in Sorted format(Not Completed).py


print('Handle Exceptions')
try:
    print(x)
except:
    print('value has not been defined!!!')

print('Raise an exception')
x=-1
try:
    if x<0:
        raise Exception(' ******value is not less than 0')
except Exception as e:
   print(e)

import sys
import os

def check():
    try:
        while True:
            x=int(input('To exist type 0: '))
            if x==0:
                sys.exit()
    except ValueError as e:
        print('Value exception occured !!!')
        print(e)
        check()
    except SystemExit:
          print('System exit has been called')
    finally:
        print('Bye Bye !!!!!')
check()
number=10
from sl3_exception.my_exceptions import ValueTooLarge,ValueTooSmallError
while True:
    try:
        i_num=int(input('Guess a number between 1 to 20 ? :'))
        if i_num<number:
            raise ValueTooSmallError('This value is too small, try again!!')
        elif i_num>number:
            raise ValueTooLarge('This value is to large , try agian!!')
        break
    except ValueTooSmallError as e:
        print(e.args)

    except ValueTooLarge as e:
        print(e)

print('Congrad you guess the right number')


import os

import qt
import vtk

from slicer.i18n import tr as _

from SegmentEditorEffects import *

class SegmentEditorFillBetweenSlicesEffect(AbstractScriptedSegmentEditorAutoCompleteEffect):
    """AutoCompleteEffect is an effect that can create a full segmentation
    from a partial segmentation (not all slices are segmented or only
    part of the target structures are painted).
    """

    def __init__(self, scriptedEffect):
        AbstractScriptedSegmentEditorAutoCompleteEffect.__init__(self, scriptedEffect)
        scriptedEffect.name = "Fill between slices"  # no tr (don't translate it because modules find effects by name)
        scriptedEffect.title = _("Fill between slices")

    def clone(self):
        import qSlicerSegmentationsEditorEffectsPythonQt as effects

        clonedEffect = effects.qSlicerSegmentEditorScriptedEffect(None)
        clonedEffect.setPythonSource(__file__.replace("\\", "/"))
        return clonedEffect

    def icon(self):
        iconPath = os.path.join(os.path.dirname(__file__), "Resources/Icons/FillBetweenSlices.png")
        if os.path.exists(iconPath):
            return qt.QIcon(iconPath)
        return qt.QIcon()

    def helpText(self):
        return "" + _("""Interpolate segmentation between slices
. Instructions:

Create complete segmentation on selected slices using any editor effect.
Segmentation will only expanded if a slice is segmented but none of the direct neighbors are segmented, therefore
do not use sphere brush with Paint effect and always leave at least one empty slice between segmented slices.

All visible segments will be interpolated, not just the selected segment.

The complete segmentation will be created by interpolating segmentations in empty slices.

Masking settings are ignored. If segments overlap, segment higher in the segments table will have priority.
The effect uses  morphological contour interpolation method.

""")

    def computePreviewLabelmap(self, mergedImage, outputLabelmap):
        import vtkITK

        interpolator = vtkITK.vtkITKMorphologicalContourInterpolator()
        interpolator.SetInputData(mergedImage)
        interpolator.Update()
        outputLabelmap.DeepCopy(interpolator.GetOutput())
        imageToWorld = vtk.vtkMatrix4x4()
        mergedImage.GetImageToWorldMatrix(imageToWorld)
        outputLabelmap.SetImageToWorldMatrix(imageToWorld)


import cv2 as cv
import numpy as np
import time
import PoseModule as pm
import serial

cap = cv.VideoCapture('squat1.mp4')

ser = serial.Serial()

color = (255, 0, 255)
detector = pm.poseDetector()
set = 0
dir = 0 # 0: up & 1: down
pTime = 0
t = 10
count = 0

while True:
    _, img = cap.read()

    img = detector.findPose(img, False)
    lmList = detector.findPosition(img, False)
    # print(lmList)
    if len(lmList) != 0:
        angle = detector.findAngle(img, 23, 25, 27)

        per = np.interp(angle, (185, 270), (0, 100))

        bar = np.interp(angle, (185, 270), (650, 100))

        if per == 100:
            if dir == 0:
                count += 0.5
                dir = 1
        if per == 0:
            if dir == 1:
                count += 0.5
                dir = 0
        # print(count)

        # Draw Bar
        cv.rectangle(img, (1100, 100), (1175, 650), color, 3)
        cv.rectangle(img, (1100, int(bar)), (1175, 650), color, cv.FILLED)
        cv.putText(img, f'{int(per)} %', (1100, 75), cv.FONT_HERSHEY_PLAIN, 4,
                    color, 4)

    #     # Draw Curl Count
        cv.putText(img, str(int(count)), (45, 670), cv.FONT_HERSHEY_PLAIN, 15,
                    (255, 0, 0), 25)
    print(count)

    cv.imshow("Image", img)
    cv.waitKey(1)


# -*- coding: utf-8 -*-

from flask import Flask, render_template, request, flash, redirect
from contact_model import Contact
app = Flask(__name__)
app.secret_key = 'some_secret'
app.debug = True

@app.route(r'/', methods=['GET'])
def contact_book():
    contacts = Contact.query().fetch()
    return render_template('contact_book.html', contacts=contacts)

@app.route(r'/add', methods=['GET', 'POST'])
def add_contact():

    if request.form:
        contact = Contact(name=request.form.get('name'),
                          phone=request.form.get('phone'),
                          email=request.form.get('email'))
        contact.put()
        flash('Se ha agregado el contacto')
    return render_template('add_contact.html')

@app.route(r'/contacts/<uid>', methods=['GET'])
def contact_details(uid):
    contact = Contact.get_by_id(int(uid))

    if not contact:
        return redirect('/', code=301)

    return render_template('contact.html', contact=contact)

@app.route(r'/delete', methods=['POST'])
def delete_contact():
    contact = Contact.get_by_id(int(request.form.get('uid')))
    contact.key.delete()
    return redirect('/contacts/{}'.format(contact.key.id()))

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


# -*- coding: utf-8 -*-
"""
Created on Fri Mar  5 15:51:41 2021

@author: Filip
"""

import hyperspy.api as hs
import numpy as np
from coreshellp import *
from specerr import SpecErrAbs2D
from specMapDiff import cLoadsFacs
import matplotlib.pyplot as plt

def addSpectrum(a,spec,specthickness):
    L = len(spec.data)
    mat = np.zeros((len(a),len(a[0]),L))

    for i in range(0,len(a)):
        for j in range(0,len(a[0])):
            mat[i,j,0:L]=(a[i,j]/specthickness)*spec.data

    specMat = hs.signals.Signal1D(mat)
    specMat.set_signal_type("EDS_TEM")
    specMat.get_calibration_from(spec)
    return specMat

s = hs.load("./Spectra/MC simulation of  a 0.020 µm base, 0.020 µm high block*.msa",stack=True,signal_type="EDS_TEM")

sCu = s.inav[-1]
sAg  = s.inav[0]
sC = hs.load("./Spectra/Carbonbackground.msa",signal_type="EDS_TEM")

size = 100
sCore = (sCu*0.9 + sAg*0.1)/10
sShell = (sCu*0.1 + sAg*+0.9)/10

carbonMat = addSpectrum(np.ones((size,size)),sC,1)
background = hs.signals.Signal1D(carbonMat)
background.metadata.General.title = 'Background'

mat = CoreShellP(size,30,20,1,1,1)
cs_mat = CoreShellSpec(mat,sCore,sShell)
cs_mat = cs_mat.getmatr() + carbonMat
amount = 10

hsList = []

for x in range(1,amount):
    sList = []
    for y in range(0,x):
        sList.append(hs.signals.Signal1D(cs_mat))
        sList[-1].add_poissonian_noise(keep_dtype=True)
    if x > 1:
        hsList.append(hs.stack(sList))
    else:
        hsList.append(sList[-1])

NMFresults = []
decomp_dim = 3
for stack in hsList:
    stack.decomposition(output_dimension = decomp_dim ,algorithm='NMF',normalize_poissonian_noise=True)
    NMF_facs = stack.get_decomposition_factors()
    NMF_loads = stack.get_decomposition_loadings()
    NMFresults.append([NMF_facs,NMF_loads])

#%%

for each in NMFresults:
    NMF_facs = each[0]
    for f in NMF_facs:
        f.data /= f.data.max()
    hs.plot.plot_spectra(NMF_facs,style='cascade')
    hs.plot.plot_images(each[1].split(), cmap='mpl_colors',
            axes_decor='off', per_row=3,
            scalebar=[0], scalebar_color='white',
            padding={'top': 0.95, 'bottom': 0.05,
                     'left': 0.05, 'right':0.78})


"""
A module to search for a specified game from approved vendors
Inputs: Search query, website links
"""

import urllib
import googlesearch
import requests
import bs4
from googlesearch import search
from bs4 import BeautifulSoup

#Import specific vendor scrapers
from PriceTrackerApp.scrapersAndAPIs import \
        amznScraper, nintendoScraper, steamAPI, xboxScraper, psScraper

def searchGame(query):
    """Returns list of links with their associated vendor name for a game specified"""

    #query should include 'buy', 'purchase', etc. at the end to bring up most useful results
    query = query + " buy"
    links = []
    for i in search(query, tld="co.in", lang="en", country="na", user_agent=googlesearch.get_random_user_agent(), num=12, start=0, stop=10, pause=2):

        site = i.split(".")

        #list of vendors we know how to scrape info from
        vendors = ["steampowered", "xbox", "amazon", "nintendo", "playstation"]
        for j in vendors:
            if site[1] == j:
                soup = BeautifulSoup(requests.get(i).text, 'html.parser')
                title = (soup.find_all('title')[0].get_text()).lower()

                #Often empty search results for sites will come up
                #as well as soundtracks and expansions for the game - remove them
                banned_keywords = ["search", "recommended", "soundtrack",
                        "expansion", "dlc", "bundle", "collector's"]

                if j != "amazon":
                    if all(i not in title for i in banned_keywords):
                        links.append((i, site[1]))
                #if the website is amazon, but sure result is from 'video games' category
                else:
                    headers = headers = {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
                    'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                    'Accept-Language' : 'en-US,en;q=0.5',
                    'Accept-Encoding' : 'gzip',
                    'DNT' : '1', # Do Not Track Request Header
                    'Connection' : 'close'
                    }
                    page = requests.get(i, headers=headers)
                    soup  = bs4.BeautifulSoup(page.content, "html.parser")

                    try:
                        category = soup.find("a", attrs={'class' : 'a-link-normal a-color-tertiary'}).string.strip()
                    except AttributeError:
                        category = ""

                    if category == "Video Games":
                        if all(i not in title for i in banned_keywords):
                            links.append((i, site[1]))

    return links

def scrapeGame(links):
    """Given list of links with their associated website name, scrape info using appropriate scraper and return game dict"""
    gameList = []
    for url, vendor in links:
        #Simulate user - otherwise sites like amazon will block
        headers = headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
        'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language' : 'en-US,en;q=0.5',
        'Accept-Encoding' : 'gzip',
        'DNT' : '1', # Do Not Track Request Header
        'Connection' : 'close'
        }
        page = requests.get(url, headers=headers)
        soup  = bs4.BeautifulSoup(page.content, "html.parser")
        parsed_url = urllib.parse.urlparse(url)
        vendorHost = parsed_url.netloc.strip()
        if vendor == "amazon":
            title = amznScraper.get_title(soup)
            price = amznScraper.get_price(soup)
            platform = amznScraper.get_platform(soup)

            #Remove scrap from platform
            if platform != "Platform Not Found":
                platform = platform.split(':')[1]
                platform = platform.split('|')[0]
                platform = platform.lstrip()
                platform = platform.rstrip()
                platform = [platform]

                #Amazon will sometimes include platform name in title - remove
                p = platform[0].lower()
                p = ''.join([i for i in p if not i.isdigit()])
                p = p.strip()
                p = p.capitalize()
                title = title.split(p)[0]
                title = title.rstrip()
                title = title.lstrip()

            #remove $ sign, convert to float
            price = price[1:]
            try:
                price = float(price)
            except ValueError:
                price = float('inf')

        if vendor == "nintendo":
            title = nintendoScraper.get_title(soup)
            price = nintendoScraper.get_price(soup)
            platform = [nintendoScraper.get_platform(soup)]

            #problem with scraping from nintendo
            try:
                price = float(price)
            except ValueError:
                price = float('inf')

        if vendor == "steampowered":
            title, price, platform = steamAPI.getGame(url)

            #Steam stores price as integers, convert to float for comparison
            if price:
                price = int(price) / 100.0
            else:
                price = 0.0

        if vendor == "xbox":
            title = xboxScraper.get_title(soup)
            price = xboxScraper.get_price(soup)
            platform = xboxScraper.get_platform(soup)

            title = title.rstrip()
            title = title.lstrip()

            #remove $ sign, convert to float
            price = price[1:]
            try:
                price = float(price)
            except ValueError:
                price = float('inf')

        if vendor == "playstation":
            title = psScraper.get_title(soup)
            price = psScraper.get_price(soup)
            platform = [psScraper.get_platform(soup)]

            #remove $ sign, convert to float
            price = price[1:]
            try:
                price = float(price)
            except ValueError:
                price = float('inf')

        if title is not None and title != "":
            #remove unicode
            title = title.encode("ascii", "ignore")
            title = title.decode()

            #get rid of console specific
            title = title.split(' PS')[0]

            if len(platform) > 0:
                gameID = title + platform[0]
                gameID = gameID.lower().replace(" ", "")
                gameID = ''.join(filter(str.isalnum, gameID))
            else:
                gameID = title
            gameDict = {'title': title, 'vendor': vendorHost, 'price': price, 'url': url, 'platform': platform, 'gameID': gameID}
            gameList.append(gameDict)

    return gameList


import datetime

from little_brother import process_info

EVENT_TYPE_START_MASTER = "START_MASTER"
EVENT_TYPE_START_CLIENT = "START_CLIENT"
EVENT_TYPE_STOP_CLIENT = "STOP_CLIENT"
EVENT_TYPE_LOGIN_NOT_PERMITTED = "LOGIN_NOT_PERMITTED"
EVENT_TYPE_LOGIN_PERMITTED = "LOGIN_PERMITTED"
EVENT_TYPE_KILL_PROCESS = "KILL_PROCESS"
EVENT_TYPE_UPDATE_CONFIG = "UPDATE_CONFIG"
EVENT_TYPE_UPDATE_LOGIN_MAPPING = "UPDATE_LOGIN_MAPPING"
EVENT_TYPE_PROCESS_START = "PROCESS_START"
EVENT_TYPE_PROHIBITED_PROCESS = "PROHIBITED_PROCESS"
EVENT_TYPE_PROCESS_DOWNTIME = "PROCESS_DOWNTIME"
EVENT_TYPE_PROCESS_END = "PROCESS_END"

EVENT_TYPE_DUMMY_1 = "DUMMY1"

def create_process_info_from_event(p_event):
    return process_info.ProcessInfo(
        p_hostname=p_event.hostname,
        p_hostlabel=p_event.hostlabel,
        p_pid=p_event.pid,
        p_username=p_event.username,
        p_processhandler=p_event.processhandler,
        p_processname=p_event.processname,
        p_start_time=p_event.process_start_time,
        p_percent=p_event.percent)

class AdminEvent(object):

    def __init__(self, p_hostname=None,
                 p_username=None,
                 p_pid=None,
                 p_processhandler=None,
                 p_processname=None,
                 p_event_type=None,
                 p_event_time=None,
                 p_process_start_time=None,
                 p_text=None,
                 p_locale=None,
                 p_payload=None,
                 p_downtime=0,
                 p_percent=100,
                 p_hostlabel=None,
                 p_delay=0):
        if p_event_time is None:
            p_event_time = datetime.datetime.now()

        self.hostname = p_hostname
        self.username = p_username
        self.pid = p_pid
        self.processhandler = p_processhandler
        self.processname = p_processname
        self.event_type = p_event_type
        self.event_time = p_event_time
        self.process_start_time = p_process_start_time
        self.text = p_text
        self.locale = p_locale
        self.payload = p_payload
        self.downtime = p_downtime
        self.percent = p_percent
        self.hostlabel = p_hostlabel
        self.delay = p_delay

    def __str__(self):
        return "AdminEvent (type=%s, host=%s, user=%s, process=%s, PID=%s)" % (
            self.event_type, self.hostname, self.username, self.processname,
            str(self.pid) if self.pid is not None else "-")

    def __eq__(self, p_other):
        return (self.hostname == p_other.hostname and
                self.username == p_other.username and
                self.processhandler == p_other.processhandler and
                self.pid == p_other.pid and
                self.event_type == p_other.event_type and
                self.text == p_other.text and
                self.payload == p_other.payload)

    def get_key(self):
        return process_info.get_key(p_hostname=self.hostname, p_pid=self.pid, p_start_time=self.process_start_time)


import random
import numpy as np
import statistics

def camel():
    repeticiones = 100
    iteraciones = 10000

    sigma = 0.1
    mejor = 1000
    rep = 1000

    # BUsqueda local iterada
    for i in range(repeticiones):
        # Busqueda local
        for j in range(iteraciones):
            # Vecindario
            x1 = random.uniform(-3, 3)
            x2 = random.uniform(-2, 2)

            term1 = (4-2.1*x1**2+(x1**4)/3) * x1**2
            term2 = x1*x2
            term3 = (-4+4*x2**2) * x2**2

            y = term1 + term2 + term3
            s = np.random.normal(y, sigma)
            if s < rep:
                rep = s

        if rep < mejor:
            mejor = rep

    return mejor

if __name__ == "__main__":
    lista_mejor = []
    for i in range(30):
        resultado = camel()
        print(resultado)
        lista_mejor.append(resultado)

    prom = statistics.mean(lista_mejor)
    st_dev = statistics.pstdev(lista_mejor)

    print("Promedio mejor: ", prom)
    print("Desviación estanadar mejor: ", st_dev)


# -*- coding: utf-8 -*-

from django.http import HttpResponseRedirect, HttpResponseNotFound
from django.views.generic import View
from vi_municipales_2016.models import PosibleFacebookPage
from vi_municipales_2016.forms import CandidateFacebookPageForm
from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.views.generic.edit import FormView
from elections.models import Candidate
from django.views.generic.base import RedirectView
from elections.models import Election
from vi_municipales_2016.scraper import Scraper
from vi_municipales_2016.tasks import scrape_election, verify_facebook_page
from django.core.urlresolvers import reverse

class VerificarBase(View):
    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        self.user = request.user
        if not self.user.is_staff:
            return HttpResponseNotFound('No encontrado')
        self.facebook_page = get_object_or_404(PosibleFacebookPage,
                                               id=self.kwargs['pk'])
        return super(VerificarBase, self).dispatch(request, *args, **kwargs)

    def process(self):
        pass

    def get(self, request, *args, **kwargs):
        self.process()
        return HttpResponseRedirect(self.facebook_page.candidate.get_absolute_url())

class VerificarSi(VerificarBase):
    def process(self):
        self.facebook_page.verify()

class VerificarNo(VerificarBase):
    def process(self):
        self.facebook_page.verified = False
        self.facebook_page.save()

class AgregarFacebookCandidato(FormView):
    form_class = CandidateFacebookPageForm

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        self.user = request.user
        if not self.user.is_staff:
            return HttpResponseNotFound('No encontrado')
        self.candidate = get_object_or_404(Candidate, pk=self.kwargs['pk'])
        return super(AgregarFacebookCandidato, self).dispatch(request, *args, **kwargs)

    def get_success_url(self):
        return self.candidate.get_absolute_url()

    def get_form_kwargs(self):
        kwargs = super(AgregarFacebookCandidato, self).get_form_kwargs()
        kwargs['candidate'] = self.candidate
        return kwargs

    def form_valid(self, form):
        form.validate_facebook_page()
        return super(AgregarFacebookCandidato, self).form_valid(form)

class ScrapeElectionView(RedirectView):
    permanent = False
    query_string = True

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        self.user = self.request.user
        if not self.user.is_staff:
            return HttpResponseNotFound('No encontrado')
        self.election = get_object_or_404(Election,
                                          slug=self.kwargs['slug'])
        return super(ScrapeElectionView, self).dispatch(*args, **kwargs)

    def get_redirect_url(self, *args, **kwargs):
        scrape_election.delay(self.election)
        return reverse('election_view', kwargs={'slug': self.election.slug})


from oot.oot import Oot
from oot.Accessor import Accessor
from oot.Utils import setSeed
import os, random, requests, time

CACHE_ENABLED = True
SEED = None
LOGDIR = 'logs'
GAMEDIR = 'roms'
game = Oot(gamedir=GAMEDIR, logdir=LOGDIR)
accessor = Accessor(game)

### Cell to randomize enemies ONLY
start_time = time.time()
SEED = 91542915092.487943#'Winnie'
seed = SEED if SEED else str(start_time)
setSeed(seed)
print("Seed: {}".format(seed) )
selected_enemy = None#{'fn': 'En_Torch2', 'object_fn': 'object_torch2', 'var': ('FFFF', '')} # Mostly for debug will change all enemies to this type

def _readVars(string):
    if len(string) < 2:
        return []
    return map(lambda x: x.strip(), string.split(","))

enemies = {}
for enemy in accessor.reader.getEnemyIndex()[1:]:
    enemy_info = accessor.reader.lookupEnemyByIndex(enemy)
    if enemy_info['Enabled']:
        key = enemy_info['Requirements']
        if enemy_info['Requirements'] not in enemies:
            enemies[key] = {}
        # Variables are of the form 'XXXX (), '
        variables = enemy_info['Variable\'s'].split(',')
        variables = [v.split(' (') for v in variables]
        real_variables = []
        for v in variables:
            var = v[0].strip()
            if len(var) != 4:
                raise Exception("Enemy {} has invalid variable {}".format(enemy, list(var)))
            descr = ''
            if len(v) > 1:
                descr = v[1].split(')')[0]
            real_variables.append((var,descr))
        # From Variables just a list of variables rather than having the description too
        from_variables = enemy_info['From-Var\'s']
        if len(from_variables) > 0:
            print(from_variables)
        enemies[key][enemy] = {
            "actor_fn": enemy_info['Actor FN'],
            "object_fn": enemy_info['Object FN'],
            "variables": real_variables,
            "from_variables": from_variables,
            "descr": descr,
            "type": key,
            "enemy": enemy
        }

available_actors = accessor.reader.getEnemyActorNames()
available_objects = accessor.reader.getEnemyObjectNames()

def isEnemyObject(st):
    return st in available_objects
def isEnemyActor(st):
    return st in available_actors

object_enemies = { k: [e["object_fn"] for e in v.values()] for k,v in enemies.items() }

actor_var_pairs = {}
from_actor_var_pairs = {}
for t,el in enemies.items():
    for e in el.values():
        for var in e["variables"]:
            actor_var_pairs['{}-{}'.format(e['actor_fn'], var[0])] = e
        for var in _readVars(e["from_variables"]):
            from_actor_var_pairs['{}-{}'.format(e['actor_fn'], var[0])] = e
print("enemy-type lists created: {}".format(time.time()-start_time))

accessor.readData()
print("Data read, {} sec".format(time.time()-start_time))

rooms_list = accessor.reader.getRoomNames()
rooms = accessor.generateRooms(rooms_list)
print("Room Info Generated, {} sec".format(time.time()-start_time))

# I think I can just assume that a object is only related to one actor in a room

# Once I have every actor linked to an object, it will be easier to have a way to look and see what actors are associated with an object
myx = None # Debug variable
def _getObjType(obj, actors, room):
    global myx
    # Find the actor that is associated with the object, and return that actors type
    for actor in actors:
        if actor.object_name == obj.filename:
            n = '{}-{}'.format(actor.filename,actor.var)
            if not n in actor_var_pairs:
                myx = (actor, obj, room, n)
                if not n in from_actor_var_pairs:
                    return False # don't randomize
                else:
                    return actor_var_pairs[n]['type'] # I think this works because the from vars enemies aren't in the main pool
            return actor_var_pairs[n]['type']
    return False#'dont-randomize' # object doesn't have a corresponding actor so it's probably dynamically generated. so don't randomize

def _getActorType(actor):
    return actor_var_pairs['{}-{}'.format(actor.filename, actor.var)]['type']
def _getObjs(tpe):
    return object_enemies[tpe]
def _getActors(tpe, objects):
    return [a for a in enemies[tpe].values() if a['object_fn'] in objects]
    # Return all the actors associated with those objects that match the given type
def _getAvailableActors(actor, possible_objects):
    t = _getActorType(actor)
    return [(a['actor_fn'], a['variables'], a['enemy']) for a in _getActors(t, possible_objects)]
def _writeEnemySpoilers(spoilers, fn):
    fn = os.path.join(LOGDIR, fn)
    with open(fn, "w") as f:
        for name, setup in spoilers.items():
            if len(setup['objects']) > 0 or len(setup['actors']) > 0:
                f.write('{}\n'.format(name))
            if len(setup['objects']) > 0:
                f.write(' objects\n')
            for o in setup['objects']:
                f.write('  {} -> {}\n'.format(o['old'], o['new']))
            if len(setup['actors']) > 0:
                f.write(' actors\n')
            for a in setup['actors']:
                f.write('  {} [{}] -> {} [{}] ({})\n'.format(a['old'], a['old_var'], a['new'], a['new_var'], a['descr']))
    pass # Write out a formatted spoiler log

spoilers = {}
for r, room in rooms.items():
    for n, setup in room.setups.items():
        for actor in setup['actors']:
            if not isEnemyActor(actor.filename):
                continue
            i = available_actors.index(actor.filename)
            actor.setObject(available_objects[i])
        setup_spoiler = {'objects':[],'actors':[]}
        _getRoomName = lambda r,n: '{}-{} ({})'.format(r,n,room.descr)
#         print('{}-{}'.format(r,n))
        spoilers[_getRoomName(r,n)] = setup_spoiler
        possible_objects = []
        for obj in setup['objects']:
            if not isEnemyObject(obj.filename):
                continue
            tpe = _getObjType(obj, setup['actors'], (r,n)) # Function will need to look at the related actor to see what the type is
            if not tpe:
                continue
            new_obj = random.choice(_getObjs(tpe)) if not selected_enemy else selected_enemy['object_fn']
            room.replaceObject(obj.filename, new_obj, n)
            possible_objects.append(new_obj)
            setup_spoiler['objects'].append({'old':obj.filename, 'new':new_obj})
        for actor in setup['actors']:
            # I have to figure out a way to find the index

            index = [i for i in setup['actors'] if i.filename == actor.filename].index(actor)

            var_str = '{}-{}'.format(actor.filename,actor.var)
            if not (isEnemyActor(actor.filename) and var_str in list(actor_var_pairs.keys())+list(from_actor_var_pairs.keys())) :
                if isEnemyActor(actor.filename):
#                     if room.fn == 'Bmori1_room_6':
#                         raise Exception()

                    pass#print("Excluding {}/{} in room {} setup # {}".format(actor.filename, actor.var, room.fn, n))
                continue # Only randomize enemies that have defined variables

            choices = _getAvailableActors(actor, possible_objects)
            if len(choices) == 0:
                continue # This should account for cases where 1 actor in a room can't be randomized but other's can
                # Because otherwise the object would get changed out and then the one that didn't get randomized won't spawn

            choice = random.choice(choices)# ( actor, var_list)
            new_actor = choice[0] if not selected_enemy else selected_enemy['fn']
            new_var = random.choice(choice[1]) if not selected_enemy else selected_enemy['var'] # (varid, descr)
            setup_spoiler['actors'].append({'old': actor.filename, 'new': new_actor, 'old_var': actor.var, 'new_var': new_var, 'descr': new_actor[2]})
            room.replaceActor(actor.filename, new_actor, new_var=new_var[0], index=index, setup=n, replaceObject=False)
print("Rooms Randomized, {} sec".format(time.time()-start_time))

# Optionally set the spawn location
accessor.spawnAt(0x3)

# Print out spoilers
_writeEnemySpoilers(spoilers, "spoiler.log")
print("Replacement Log Written".format(time.time()-start_time))

accessor.writeData()
print("New ROM Written {}".format(time.time()-start_time))


import json
import os
from pathlib import Path

import pytest

from sphinx_needs.config import NeedsSphinxConfig
from sphinx_needs.data import SphinxNeedsData

@pytest.mark.parametrize(
    "test_app", [{"buildername": "needs_id", "srcdir": "doc_test/doc_needs_builder"}], indirect=True
)
def test_doc_needs_id_builder(test_app):
    app = test_app
    app.build()
    out_dir = app.outdir
    env = app.env
    data = SphinxNeedsData(env)
    needs_config = NeedsSphinxConfig(env.config)
    needs = data.get_or_create_needs().values()  # We need a list of needs for later filter checks
    needs_build_json_per_id_path = needs_config.build_json_per_id_path
    needs_id_path = os.path.join(out_dir, needs_build_json_per_id_path)
    assert os.path.exists(needs_id_path)
    for need in needs:
        need_id = need["id"]
        need_file_name = f"{need_id}.json"
        needs_json = Path(needs_id_path, need_file_name)
        assert os.path.exists(needs_json)
        with open(needs_json) as needs_file:
            needs_file_content = needs_file.read()
        needs_list = json.loads(needs_file_content)
        assert needs_list["versions"]["1.0"]["needs"][need_id]["docname"]


import tensorflow as tf
import numpy as np
import os
from scipy.stats import multivariate_normal
import pickle

def sample_Z(m, n):
    '''Gaussian prior for G(Z)'''
    return np.random.normal(size=[m,n])

def setup_directories(*dirs):
    for _dir in dirs:
        if not os.path.exists(_dir):
            os.makedirs(_dir)

def get_flags(dataset, exp_no):
    path = "results/{}/exp_{}/checkpoint/flags".format(dataset, exp_no)
    with open(path, 'rb') as file:
        FLAGS = pickle.load(file)
    return FLAGS

class Helper():
    def __init__(self, FLAGS):
        self.FLAGS = FLAGS
        self.exp_dir = None
        self.exp_no = 0

    def setup_directories(self):
        result_dir = "results/" + self.FLAGS.dataset + "/"
        setup_directories(result_dir)

        i = 0
        self.exp_dir = result_dir + "exp_{}/".format(i)
        while os.path.exists(self.exp_dir):
            i += 1
            self.exp_dir = result_dir + "exp_{}/".format(i)
        self.exp_no = i
        os.makedirs(self.exp_dir)

        self.FLAGS.output_dir = self.exp_dir + self.FLAGS.output_dir
        self.FLAGS.summaries_dir = self.exp_dir + self.FLAGS.summaries_dir
        self.FLAGS.array_dir = self.exp_dir + self.FLAGS.array_dir
        self.FLAGS.checkpoint_dir = self.exp_dir + self.FLAGS.checkpoint_dir

        setup_directories(self.FLAGS.output_dir, self.FLAGS.summaries_dir, self.FLAGS.array_dir, self.FLAGS.checkpoint_dir)

        with open(self.FLAGS.checkpoint_dir + "flags", 'wb') as file:
            pickle.dump(self.FLAGS, file, protocol=pickle.HIGHEST_PROTOCOL)

        return self.FLAGS

def setup_eigval_dict(_dict, optimizer):
    _dict[optimizer] = []
    _dict['{}_ul'.format(optimizer)] = []
    _dict['{}_lr'.format(optimizer)] = []
    return _dict

def update_eigval_dict(_dict, optimizer, eigv, eigv_ul, eigv_lr):
    _dict[optimizer].append(eigv)
    _dict['{}_ul'.format(optimizer)].append(eigv_ul)
    _dict['{}_lr'.format(optimizer)].append(eigv_lr)
    return _dict

def get_sample_pdf(means, variances, cat_probs, modes, X):
    sums = np.zeros(np.array(X).shape[0])
    for n, x in enumerate(X):
        for i in range(modes):
            sums[n] += cat_probs[i] * multivariate_normal.pdf(x, means[i], variances[i])
    return sums

def load_opt_arrays(FLAGS):
    _dir = FLAGS.array_dir
    opt_methods_keys = FLAGS.opt_methods.split(" ")
    opt_methods = dict()
    if not os.path.exists(_dir):
        os.makedirs(_dir)
    for method in opt_methods_keys:
        opt_methods[method + "_g"] = np.array([])
        opt_methods[method + "_d"] = np.array([])
        if os.path.isfile(_dir + method +"_g.npy"):
            opt_methods[method + "_g"] = np.load(_dir + method +"_g.npy")
        if os.path.isfile(_dir + method +"_d.npy"):
            opt_methods[method + "_d"] = np.load(_dir + method +"_d.npy")

    return opt_methods

def save_opt_methods(opt_methods, out_dir):
    for key in opt_methods.keys():
        np.save(out_dir + key + ".npy", opt_methods[key])

def set_seed(seed=None):
    if seed is None:
        seed = np.random.choice(150)
    print("Random Seed {}".format(seed))
    np.random.seed(seed)
    tf.set_random_seed(seed)
    return seed

def safe_append(dict, key, val):
    if key not in dict.keys():
        dict[key] = list([val])
    else:
        dict[key].append(val)
    return dict

def save_log(x):
    x = np.clip(x, 1E-10, 1E10)
    return np.log(x)


from ext import db
import datetime

class FixedTagModel(db.Model):
    __tablename__ = 'fixed_tag'
    __table_args__ = {'schema': 'meta'}

    id = db.Column(db.Integer, primary_key=True)
    tag_type_id = db.Column(db.Integer, db.ForeignKey('meta.tag_type.id'), nullable=False)
    description = db.Column(db.String(30), nullable=False)
    field_name = db.Column(db.String(30), nullable=False)

    @property
    def serialize(self):
        return {
            'id': str(self.id),
            'tag_type_id': str(self.tag_type_id),
            'description': self.description,
            'field_name': self.field_name,
        }


import time
import math
from tqdm import tqdm  # tqdm_notebook as tqdm
import numpy as np
import os
import sys
import torch
from torch.utils import data
import utils
from torch.nn.utils import clip_grad_value_

# import torch.nn.functional as F
from transformer import Constants
from transformer.Generator import Generator

# from math_dataset import VOCAB_SZ, MAX_QUESTION_SZ, MAX_ANSWER_SZ, np_decode_string
from math_dataset import MAX_QUESTION_SZ, np_decode_string
from loss import compute_performance
from checkpoints import (
    rotating_save_checkpoint,
    build_checkpoint,
    save_checkpoint,
)
from math_dataset import np_encode_string, question_to_position_batch_collate_fn

def train(
    name,
    model,
    training_data,
    optimizer,
    device,
    epochs,
    validation_data=None,
    tb=None,
    log_interval=100,
    interpolate_interval=1,
    interpolate_data=None,
    start_epoch=0,
    start_batch=0,
    total_loss=0,
    n_char_total=0,
    n_char_correct=0,
    run_batches=0,
    best_valid_accu=0.0,
    best_valid_loss=float("Inf"),
    best_interpolate_accu=0.0,
    best_interpolate_loss=float("Inf"),
    run_max_batches=None,
    extrapolate_data=None,
    checkpoint=True,
    lr=None,
    warmup_lr=None,
    warmup_interval=None,
    smoothing=False,
):
    print("~~~ Beginning Training ~~~~")
    print(
        f"Start epoch: {start_epoch}, Start batch: {start_batch}, Max batch: {run_max_batches}"
    )

    for epoch_i in range(start_epoch, epochs):

        start = time.time()

        print(
            f"[ Epoch: {epoch_i} / {epochs}, Run Batch: {run_batches} / {run_max_batches}]"
        )

        train_loss, train_accu, new_batch_count, done = train_epoch(
            model=model,
            name=name,
            training_data=training_data,
            optimizer=optimizer,
            device=device,
            epoch=epoch_i,
            tb=tb,
            log_interval=log_interval,
            max_batches=run_max_batches,
            run_batch_count=run_batches,
            start_batch=start_batch,
            total_loss=total_loss,
            n_char_total=n_char_total,
            n_char_correct=n_char_correct,
            lr=lr,
            warmup_lr=warmup_lr,
            warmup_interval=warmup_interval,
            smoothing=smoothing,
        )

        run_batches = new_batch_count

        print(
            "[Training]  loss: {train_loss}, ppl: {ppl: 8.6f}, accuracy: {accu:3.3f} %, "
            "elapse: {elapse:3.3f}ms".format(
                train_loss=train_loss,
                ppl=math.exp(min(train_loss, 100)),
                accu=100 * train_accu,
                elapse=(time.time() - start) * 1000,
            )
        )

        if not utils.is_preempted():
            inference_datasets = {}
            if interpolate_data:
                inference_datasets["interpolate"] = interpolate_data
            if extrapolate_data:
                inference_datasets["extrapolate"] = extrapolate_data

            for group, dataset in inference_datasets.items():
                start = time.time()
                inference_loss, inference_acc = inference_epoch(
                    model, dataset, device, epoch_i, group, tb, log_interval,
                )
                print(
                    "[{group}]  loss: {inference_loss},  ppl: {ppl: 8.5f}, accuracy: {accu:3.3f} %, "
                    "elapse: {elapse:3.3f}ms".format(
                        group=group,
                        inference_loss=inference_loss,
                        ppl=math.exp(min(inference_loss, 100)),
                        accu=100 * inference_acc,
                        elapse=(time.time() - start) * 1000,
                    )
                )

        if done or checkpoint:
            print("Building checkpoint..")
            start = time.time()
            state = build_checkpoint(
                name=name,
                model=model,
                optimizer=optimizer,
                acc=train_accu,
                loss=train_loss,
                epoch=epoch_i if not done and checkpoint else epoch_i + 1,
                run_batches=run_batches,
                # is_preempted=utils.is_preempted(),
                start_batch=0,
                lr=lr,
            )

            if utils.is_cloud():
                print("Saving to google cloud..")
                checkpoint_name = "checkpoint"
                if done:
                    checkpoint_name = (
                        f"{checkpoint_name}_b{run_batches}_e{epoch_i}_complete"
                    )
                elif checkpoint:
                    checkpoint_name = f"{checkpoint_name}_b{run_batches}_e{epoch_i}"

                save_checkpoint(
                    state=state, name=checkpoint_name, path="./checkpoints",
                )
            else:
                rotating_save_checkpoint(
                    state,
                    prefix=f"{name}_{run_batches}_training",
                    path="./checkpoints",
                    nb=5,
                )
            print(f"Save checkpoint time: {(time.time() - start) * 1000}ms")
            # if utils.is_preempted():
            #     print("Completed preemption handling. Cleanly exiting.")
            #     sys.exit(0)

        if done:
            print(
                f"Reached max batch. Breaking out of training at the end of epoch {epoch_i}"
            )
            break

        start_batch = 0
        training_data.dataset.endEpoch()
        training_data.dataset.shuffleData()

    print("~~~~~~ Completed training ~~~~~~")

    if utils.is_cloud():
        print("Shutting down instance")
        os.system("sudo shutdown -h now")

def train_epoch(
    model,
    name,
    training_data,
    optimizer,
    device,
    epoch,
    tb=None,
    log_interval=100,
    max_batches=None,
    run_batch_count=0,
    start_batch=0,
    total_loss=0,
    n_char_total=0,
    n_char_correct=0,
    lr=None,
    warmup_lr=None,
    warmup_interval=None,
    smoothing=False,
):

    training_iter = iter(training_data)

    if start_batch > 0:
        last_question = np_encode_string(training_data.dataset.__getitem__(-1)["q"])
        print(f"Final question before checkpoint was {last_question}")

    model.train()
    # interrupted_batch = None
    done = False

    loss_per_char = 0
    accuracy = 0

    for batch_idx, batch in enumerate(training_iter, start=start_batch):
        if utils.is_preempted():
            print("Exiting...")
            sys.exit(0)

        if warmup_interval is not None and batch_idx == warmup_interval:
            print(f"End of warmup. Swapping learning rates from {warmup_lr} to {lr}")
            for param_group in optimizer.param_groups:
                warmup_lr = lr
                param_group["lr"] = lr

        batch_qs, batch_qs_pos, batch_as, batch_as_pos = map(
            lambda x: x.to(device), batch
        )

        gold_as = batch_as[:, 1:]

        optimizer.zero_grad()
        pred_as = model(batch_qs, batch_qs_pos, batch_as, batch_as_pos)

        loss, n_correct = compute_performance(pred_as, gold_as, smoothing=smoothing)

        loss.backward()

        # Clip gradients, paper uses 0.1
        clip_grad_value_(model.parameters(), 0.1)

        # update parameters
        optimizer.step()

        # note keeping
        total_loss += loss.item()

        non_pad_mask = gold_as.ne(Constants.PAD)
        n_char = non_pad_mask.sum().item()
        n_char_total += n_char
        n_char = n_char if n_char > 1 else 1

        batch_loss = loss / n_char
        loss_per_char = total_loss / n_char_total

        n_char_correct += n_correct
        batch_acc = n_correct / n_char
        accuracy = n_char_correct / n_char_total
        print(
            f"Batch: {batch_idx}. Acc: {accuracy:.6f}. Loss: {loss_per_char:.6f}. Batch_acc: {batch_acc:.6f}. Batch_loss: {batch_loss:.6f} "
        )

        # TODO: automatically trim the TB logs that go beyond the preempted checkpoint
        if tb is not None and batch_idx % log_interval == 0:
            tb.add_scalars(
                {
                    "loss_per_char": loss_per_char,
                    "accuracy": accuracy,
                    "batch_loss": batch_loss,
                    "batch_acc": batch_acc,
                },
                group="train",
                sub_group="batch",
                global_step=run_batch_count,
            )

        run_batch_count += 1

        if max_batches is not None and run_batch_count == max_batches:
            print(
                f"Reached {run_batch_count} batches on max_batches of {max_batches}. Breaking from epoch."
            )
            # interrupted_batch = batch_idx
            done = True
            break

        if batch_idx % 251 == 0 and batch_idx != 0:
            print(
                f"Checkpointing on batch: {batch_idx}. Accuracy: {accuracy}. Loss per char: {loss_per_char}. Time: {time.time()}"
            )
            print(f"Last question is {batch_qs[-1]}")

            state = build_checkpoint(
                name=name,
                model=model,
                optimizer=optimizer,
                acc=accuracy,
                loss=loss_per_char,
                epoch=epoch,
                run_batches=run_batch_count,
                start_batch=batch_idx + 1,
                total_loss=total_loss,
                n_char_total=n_char_total,
                n_char_correct=n_char_correct,
                lr=warmup_lr,
            )

            save_checkpoint(
                state=state, name=f"{name}_latest_checkpoint", path="./checkpoints"
            )

        # if utils.is_preempted():
        #     print(
        #         f"Preemption at end of Epoch batch: {batch_idx} and new Run batch: {run_batch_count}. Breaking from epoch."
        #     )
        #     interrupted_batch = batch_idx
        #     break

    if tb is not None and not utils.is_preempted():
        tb.add_scalars(
            {"loss_per_char": loss_per_char, "accuracy": accuracy},
            group="train",
            sub_group="epoch",
            global_step=epoch,
        )

    return loss_per_char, accuracy, run_batch_count, done

def inference_epoch(model, data, device, epoch, group, tb=None, log_interval=100):
    model.eval()

    total_loss = 0
    n_char_total = 0
    n_char_correct = 0

    with torch.no_grad():
        for batch_idx, batch in enumerate(tqdm(data, mininterval=2, leave=False)):
            # prepare data
            batch_qs, batch_qs_pos, batch_as, batch_as_pos = map(
                lambda x: x.to(device), batch
            )
            gold_as = batch_as[:, 1:]

            # forward
            pred_as = model(batch_qs, batch_qs_pos, batch_as, batch_as_pos)
            loss, n_correct = compute_performance(pred_as, gold_as, smoothing=False)

            # note keeping
            total_loss += loss.item()

            non_pad_mask = gold_as.ne(Constants.PAD)
            n_char = non_pad_mask.sum().item()
            n_char_total += n_char
            n_char_correct += n_correct

    loss_per_char = total_loss / n_char_total
    accuracy = n_char_correct / n_char_total

    if tb is not None:
        tb.add_scalars(
            {"loss_per_char": loss_per_char, "accuracy": accuracy},
            group=group,
            sub_group="epoch",
            global_step=epoch,
        )

    return loss_per_char, accuracy

def predict(generator, data, device, max_predictions=None):
    if max_predictions is not None:
        cur = max_predictions
    else:
        cur = len(data)

    resps = []
    for batch_idx, batch in enumerate(data):
        if cur == 0:
            break
        batch_qs, batch_qs_pos = map(lambda x: x.to(device), batch)
        all_hyp, all_scores = generator.generate_batch(batch_qs, batch_qs_pos)

        for i, idx_seqs in enumerate(all_hyp):
            for j, idx_seq in enumerate(idx_seqs):
                r = np_decode_string(np.array(idx_seq))
                s = all_scores[i][j].cpu().item()
                resps.append({"resp": r, "score": s})
        cur -= 1

    return resps

def predict_benchmark(generator, data, device, max_predictions=None):
    resps = []
    dataset_size = len(data)
    for batch_idx, (batch_qs, batch_qs_pos, batch_as) in enumerate(data):
        start = time.time()

        all_hyp, all_scores = generator.generate_batch(batch_qs, batch_qs_pos)

        for i, idx_seqs in enumerate(all_hyp):
            g = np_decode_string(np.array(idx_seqs[0]))
            s = all_scores[i][0].cpu().item()
            a = batch_as[i]
            c = g == a
            resp = {"correct": c, "guess": g, "answer": a, "score": s}
            print(resp)
            resps.append(resp)

        print(
            f"Batch {batch_idx + 1} of {math.ceil(dataset_size/len(idx_seqs))}, time {time.time() - start}s."
        )

    return resps

def predict_dataset(
    dataset,
    model,
    device,
    callback,
    max_batches=None,
    beam_size=5,
    max_token_seq_len=MAX_QUESTION_SZ,
    n_best=1,
    batch_size=1,
    num_workers=1,
):

    generator = Generator(
        model,
        device,
        beam_size=beam_size,
        max_token_seq_len=max_token_seq_len,
        n_best=n_best,
    )

    if max_batches is not None:
        cur = max_batches
    else:
        cur = len(dataset)

    resps = []
    for batch_idx, batch in enumerate(dataset):
        if cur == 0:
            break

        batch_qs, batch_qs_pos, _ = map(lambda x: x.to(device), batch)
        all_hyp, all_scores = generator.generate_batch(batch_qs, batch_qs_pos)

        callback(batch_idx, all_hyp, all_scores)

        cur -= 1
    return resps

def predict_multiple(
    questions,
    model,
    device,
    beam_size=5,
    max_token_seq_len=MAX_QUESTION_SZ,
    n_best=1,
    batch_size=1,
    num_workers=1,
):

    questions = list(map(lambda q: np_encode_string(q), questions))
    questions = data.DataLoader(
        questions,
        batch_size=1,
        shuffle=False,
        num_workers=1,
        collate_fn=question_to_position_batch_collate_fn,
    )

    generator = Generator(
        model,
        device,
        beam_size=beam_size,
        max_token_seq_len=max_token_seq_len,
        n_best=n_best,
    )

    return predict(generator, questions, device)

def predict_single(
    question, model, device, beam_size=5, max_token_seq_len=MAX_QUESTION_SZ, n_best=1
):

    generator = Generator(
        model,
        device,
        beam_size=beam_size,
        max_token_seq_len=max_token_seq_len,
        n_best=n_best,
    )

    qs = [np_encode_string(question)]
    qs, qs_pos = question_to_position_batch_collate_fn(qs)
    qs, qs_pos = qs.to(device), qs_pos.to(device)

    all_hyp, all_scores = generator.generate_batch(qs, qs_pos)
    # resp = np_decode_string(np.array(all_hyp[0][0]))

    resps = []
    for i, idx_seqs in enumerate(all_hyp):
        for j, idx_seq in enumerate(idx_seqs):
            r = np_decode_string(np.array(idx_seq))
            s = all_scores[i][j].cpu().item()
            resps.append({"resp": r, "score": s})

    return resps


# @Author       : Ruopeng Gao
# @Date         : 2022/12/2
import math
import os
import torch
import random

from collections import defaultdict
from random import randint
from PIL import Image

import data.transforms as T
from .mot import MOTDataset

class MOT17(MOTDataset):
    def __init__(self, config: dict, split: str, transform):
        super(MOT17, self).__init__(config=config, split=split, transform=transform)

        self.config = config
        self.transform = transform
        self.use_motsynth = config["USE_MOTSYNTH"]
        self.use_crowdhuman = config["USE_CROWDHUMAN"]
        self.motsynth_rate = config["MOTSYNTH_RATE"]
        if self.use_motsynth:
            multi_random_state = random.getstate()
            random.seed(config["SEED"])
            self.unified_random_state = random.getstate()
            random.setstate(multi_random_state)
        else:
            self.unified_random_state = None

        assert split == "train", f"Split {split} is NOT supported."
        self.mot17_seqs_dir = os.path.join(config["DATA_ROOT"], config["DATASET"], "images", split)
        self.mot17_gts_dir = os.path.join(config["DATA_ROOT"], config["DATASET"], "gts", split)
        self.crowdhuman_seq_dir = os.path.join(config["DATA_ROOT"], "CrowdHuman", "images", "val")
        self.crowdhuman_gts_dir = os.path.join(config["DATA_ROOT"], "CrowdHuman", "gts", "val")
        # Training MOT17, using MOT17 train split and crowdhuman val splits
        self.motsynth_seqs_dir = os.path.join(config["DATA_ROOT"], "MOTSynth", "frames")
        self.motsynth_gts_dir = os.path.join(config["DATA_ROOT"], "MOTSynth", "gts")

        self.sample_steps: list = config["SAMPLE_STEPS"]
        self.sample_intervals: list = config["SAMPLE_INTERVALS"]
        self.sample_modes: list = config["SAMPLE_MODES"]
        self.sample_lengths: list = config["SAMPLE_LENGTHS"]
        self.sample_mot17_join: int = config["SAMPLE_MOT17_JOIN"]
        self.sample_stage = None
        self.sample_begin_frame_paths = None
        self.sample_length = None
        self.sample_mode = None
        self.sample_interval = None
        self.sample_vid_tmax = None

        self.mot17_gts = defaultdict(lambda: defaultdict(list))
        self.crowdhuman_gts = defaultdict(list)
        self.motsynth_gts = defaultdict(lambda: defaultdict(list))

        self.mot17_seq_names = [seq for seq in os.listdir(self.mot17_seqs_dir) if "SDP" in seq]
        for vid in self.mot17_seq_names:
            mot17_gts_dir = os.path.join(self.mot17_gts_dir, vid, "img1")
            mot17_gt_paths = [os.path.join(mot17_gts_dir, filename) for filename in os.listdir(mot17_gts_dir)]
            for mot17_gt_path in mot17_gt_paths:
                for line in open(mot17_gt_path):
                    _, i, x, y, w, h, v = line.strip("\n").split(" ")
                    i, x, y, w, h, v = map(float, (i, x, y, w, h, v))
                    i, x, y, w, h = map(int, (i, x, y, w, h))
                    t = int(mot17_gt_path.split("/")[-1].split(".")[0])
                    self.mot17_gts[vid][t].append([i, x, y, w, h])
        # Prepare for MOTSynth
        if self.use_motsynth:
            self.motsynth_seq_names = [seq for seq in os.listdir(self.motsynth_seqs_dir)]
            for vid in self.motsynth_seq_names:
                motsynth_gt_path = os.path.join(self.motsynth_gts_dir, vid, "gt", "gt.txt")
                for line in open(motsynth_gt_path):
                    t, i, *xywh, a, b, c = line.strip().split(",")[:9]
                    if int(a) == 0 or not int(b) == 1 or float(c) == 0:
                        continue
                    x, y, w, h = map(float, xywh)
                    self.motsynth_gts[vid][int(t)].append([int(i), x, y, w, h])
        crowdhuman_gt_filenames = os.listdir(self.crowdhuman_gts_dir)
        for filename in crowdhuman_gt_filenames:
            crowdhuman_gt_path = os.path.join(self.crowdhuman_gts_dir, filename)
            image_name = filename.split(".")[0]
            for line in open(crowdhuman_gt_path):
                _, i, x, y, w, h = line.strip("\n").split(" ")
                i, x, y, w, h = map(int, (i, x, y, w, h))
                self.crowdhuman_gts[image_name].append([i, x, y, w, h])

        self.set_epoch(epoch=0)     # init datasets

        return

    def __len__(self):
        assert self.sample_begin_frame_paths is not None, "Please use set_epoch to init DanceTrack Dataset."
        return len(self.sample_begin_frame_paths)

    def __getitem__(self, item):
        begin_frame_path = self.sample_begin_frame_paths[item]
        frame_paths = self.sample_frame_paths(begin_frame_path=begin_frame_path)
        imgs, infos = self.get_multi_frames(frame_paths=frame_paths)

        if infos[0]["dataset"] == "MOT17":
            imgs, infos = self.transform["MOT17"](imgs, infos)
        else:
            imgs, infos = self.transform["CrowdHuman"](imgs, infos)

        return {
            "imgs": imgs,
            "infos": infos
        }

    def set_epoch(self, epoch: int):
        # Copy from dancetrack.py
        self.sample_begin_frame_paths = list()
        self.sample_vid_tmax = dict()
        self.sample_stage = 0
        for step in self.sample_steps:
            if epoch >= step:
                self.sample_stage += 1
        assert self.sample_stage < len(self.sample_steps) + 1
        self.sample_length = self.sample_lengths[min(len(self.sample_lengths) - 1, self.sample_stage)]
        self.sample_mode = self.sample_modes[min(len(self.sample_modes) - 1, self.sample_stage)]
        self.sample_interval = self.sample_intervals[min(len(self.sample_intervals) - 1, self.sample_stage)]
        # End of Copy
        # Add Crowdhuman:
        if self.use_crowdhuman:
            for image_name in self.crowdhuman_gts:
                self.sample_begin_frame_paths.append(os.path.join(self.crowdhuman_seq_dir, f"{image_name}.jpg"))
        if epoch >= self.sample_mot17_join:
            for vid in self.mot17_gts.keys():
                t_min = min(self.mot17_gts[vid].keys())
                t_max = max(self.mot17_gts[vid].keys())
                self.sample_vid_tmax[vid] = t_max
                for t in range(t_min, t_max - (self.sample_length - 1) + 1):
                    self.sample_begin_frame_paths.append(
                        os.path.join(self.mot17_seqs_dir, vid, "img1", str(t).zfill(6) + ".jpg")
                    )

        if self.use_motsynth:
            multi_random_state = random.getstate()
            random.setstate(self.unified_random_state)
            for vid in self.motsynth_gts.keys():
                t_min = min(self.motsynth_gts[vid].keys())
                t_max = max(self.motsynth_gts[vid].keys())
                self.sample_vid_tmax[vid] = t_max
                for t in range(t_min, t_max - (self.sample_length - 1) + 1):
                    if random.random() > self.motsynth_rate:
                        continue
                    self.sample_begin_frame_paths.append(
                        os.path.join(self.motsynth_seqs_dir, vid, "rgb", str(t).zfill(4) + ".jpg")
                    )
            self.unified_random_state = random.getstate()
            random.setstate(multi_random_state)

        return

    def sample_frame_paths(self, begin_frame_path: str) -> list[str]:
        if "CrowdHuman" in begin_frame_path:
            return [begin_frame_path] * self.sample_length
        if self.sample_mode == "random_interval":
            assert self.sample_length > 1, "Sample Length is less than 2."
            vid = begin_frame_path.split("/")[-3]
            begin_t = int(begin_frame_path.split("/")[-1].split(".")[0])
            remain_frames = self.sample_vid_tmax[vid] - begin_t
            max_interval = math.floor(remain_frames / (self.sample_length - 1))
            interval = min(randint(1, self.sample_interval), max_interval)
            frame_idx = [begin_t + interval * i for i in range(self.sample_length)]
            if "MOTSynth" in begin_frame_path:
                frame_paths = [os.path.join(self.motsynth_seqs_dir, vid, "rgb", str(t).zfill(4) + ".jpg") for t in frame_idx]
            else:
                frame_paths = [os.path.join(self.mot17_seqs_dir, vid, "img1", str(t).zfill(6) + ".jpg") for t in frame_idx]

            return frame_paths
        else:
            raise NotImplementedError(f"Do not support sample mode '{self.sample_mode}'.")

    def get_single_frame(self, frame_path: str):
        if "CrowdHuman" in frame_path:
            frame_name = frame_path.split("/")[-1].split(".")[0]
            gt = self.crowdhuman_gts[frame_name]
        elif "MOT17" in frame_path or "MOTSynth" in frame_path:
            frame_idx = int(frame_path.split("/")[-1].split(".")[0])
            vid = frame_path.split("/")[-3]
            if "MOTSynth" in frame_path:
                gt = self.motsynth_gts[vid][frame_idx]
            else:
                gt = self.mot17_gts[vid][frame_idx]
        else:
            raise RuntimeError(f"Frame path '{frame_path}' has no GTs.")
        img = Image.open(frame_path)

        crowdhuman_ids_offset = 100000

        info = {}

        info["boxes"] = list()
        info["ids"] = list()
        info["labels"] = list()
        info["areas"] = list()
        info["dataset"] = "MOT17" if ("MOT17" in frame_path or "MOTSynth" in frame_path) else "CrowdHuman"

        for i, x, y, w, h in gt:
            info["boxes"].append(list(map(float, (x, y, w, h))))
            info["areas"].append(w * h)
            info["ids"].append(i if "MOT17" in frame_path else i + crowdhuman_ids_offset)
            info["labels"].append(0)
        info["boxes"] = torch.as_tensor(info["boxes"])
        info["areas"] = torch.as_tensor(info["areas"])
        info["ids"] = torch.as_tensor(info["ids"], dtype=torch.long)
        info["labels"] = torch.as_tensor(info["labels"], dtype=torch.long)
        # xywh to xyxy
        if len(info["boxes"]) > 0:
            info["boxes"][:, 2:] += info["boxes"][:, :2]
        else:
            info["boxes"] = torch.zeros((0, 4))
            info["ids"] = torch.zeros((0, ), dtype=torch.long)
            info["labels"] = torch.zeros((0, ), dtype=torch.long)

        return img, info

    def get_multi_frames(self, frame_paths: list[str]):
        return zip(*[self.get_single_frame(frame_path=path) for path in frame_paths])

def transforms_for_train(coco_size: bool = False, overflow_bbox: bool = False, reverse_clip: bool = False):
    scales = [608, 640, 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992]

    return {
        "MOT17": T.MultiCompose([
            T.MultiRandomHorizontalFlip(),
            T.MultiRandomSelect(
                T.MultiRandomResize(scales, max_size=1536),
                T.MultiCompose([
                    T.MultiRandomResize([400, 500, 600] if coco_size else [800, 1000, 1200]),
                    T.MultiRandomCrop(
                        min_size=384 if coco_size else 800,
                        max_size=600 if coco_size else 1200,
                        overflow_bbox=overflow_bbox),
                    T.MultiRandomResize(scales, max_size=1536)
                ])
            ),
            T.MultiHSV(),
            T.MultiCompose([
                T.MultiToTensor(),
                T.MultiNormalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])  # from COCO/MOTR
            ]),
            T.MultiReverseClip(reverse=reverse_clip)
        ]),
        "CrowdHuman": T.MultiCompose([
            T.MultiRandomHorizontalFlip(),
            T.MultiRandomShift(),
            T.MultiRandomSelect(
                T.MultiRandomResize(scales, max_size=1536),
                T.MultiCompose([
                    T.MultiRandomResize([400, 500, 600] if coco_size else [800, 1000, 1200]),
                    T.MultiRandomCrop(
                        min_size=384 if coco_size else 800,
                        max_size=600 if coco_size else 1200,
                        overflow_bbox=overflow_bbox),
                    T.MultiRandomResize(scales, max_size=1536)
                ])
            ),
            T.MultiHSV(),
            T.MultiCompose([
                T.MultiToTensor(),
                T.MultiNormalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])  # from COCO/MOTR
            ]),
            T.MultiReverseClip(reverse=reverse_clip)
        ])
    }

def build(config: dict, split: str):
    if split == "train":
        return MOT17(config=config, split=split, transform=transforms_for_train())
    else:
        raise NotImplementedError(f"MOT Dataset 'build' function do not support split {split}.")


import pyttsx3
import os

import pypdf2
import datetime
from tkinter.filedialog import *
book=askopenfilename()
pdfreader=pypdf2.pdffilereader(book)
pages=pdfreader.numpages

for num in range(0,pages):
    page=pdfreader.getpage(num)
    text=page.extracttext()
    print("pdf content is:",text)
    player=pyttsx3.init()
    player.say(text)
    player.runandwait()
strtime=datetime.datetime.now().strftime("%h:%m:%s")
f=open(r"c:\users\hp\desktop\pdfrhistory.txt","r+")
z=[]
r=[]
r.append(book)
r.append(strtime)
z.append(r)

f.write(str(book)+str(strtime)+str("   ***   "))
s=f.readlines()
print("your activity:",r)


import pygame
from pygame import Vector2 as V2
from typing import Set
from random import randint

pygame.init()
display = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()

class Particle:
    def __init__(self, loc: V2) -> None:
        self.loc = loc
        self.r = 5
        self.velocity = V2(randint(-5, 5), 3)
        self.lifetime = 255

    def update_loc(self) -> None:
        self.loc += self.velocity
        self.velocity.x *= 0.97
        self.velocity.y *= 1.04
        self.lifetime *= 0.96

    def draw(self) -> None:
        cv = 255 - self.lifetime
        pygame.draw.circle(display, (cv, cv, cv), self.loc, self.r)

class ParticleSystem:
    def __init__(self) -> None:
        self.particles: Set[Particle] = set()

    def emit(self, loc: V2) -> None:
        p = Particle(loc)
        self.particles.add(p)

    def draw(self) -> None:
        particles_to_remove = set()
        for p in self.particles:
            p.update_loc()
            p.draw()

            if p.lifetime <= 1:
                particles_to_remove.add(p)

        for p in particles_to_remove:
            self.particles.remove(p)
            print("Particle", p, "was removed")

ps = ParticleSystem()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
           pygame.quit()
           exit()

    pk = pygame.key.get_pressed()

    if pk[pygame.K_SPACE]:
       ps.emit(V2(250, 50))

    display.fill((255, 255, 255))
    ps.draw()
    pygame.display.update()
    clock.tick(60)