import re
import sys
import time
import random

class Stochastic(object):

    def __init__(self, text_file):
        """Init stochastic object
        Takes in name of file"""
        self.text_file = text_file
        data_list = self.create_data()
        self.histogram = self.create_histogram(data_list)
        self.total_word_count = self.count_words()

    def count_words(self):
        """Count all the words in the histogram"""
        total_word_count = 0
        for key in self.histogram:
            total_word_count += self.histogram[key]
        return total_word_count

    def create_data(self):
        """Takes no parameters.
        Returns a list of all words in the file"""
        with open(self.text_file) as words_file:
            raw_data = words_file.read()
            raw_data = raw_data.lower()
            raw_data = raw_data.replace('\n', ' ')
            raw_data = re.sub('[^a-z]+', ' ', raw_data)
            data_list = raw_data.split(" ")
            return data_list

    def create_histogram(self, data_list):
        """Takes in list of words.
        Returns dictionary of words and frequency"""
        histogram = {}
        get = histogram.get
        for word in data_list:
            histogram[word] = get(word, 0) + 1
        return histogram

    def create_sentence(self, word_num):
        """Takes in number of words in sentence, and histogram.
        Returns sentence."""

        sentence = []
        for index in range(0, word_num):
            word = self.stochastic()
            sentence.append(word)
        return " ".join(sentence)
        # return sentence

    def stochastic(self):
        """Takes in histogram and total word count.
        Returns random word based on probability"""
        index = random.randint(1, self.total_word_count)

        for word in self.histogram:
            frequency = self.histogram[word]
            if index > frequency:
                index -= frequency
            else:
                return word

if __name__ == "__main__":
    start_time = time.time()
    word_num = int(sys.argv[1])
    text_file = 'dracula.txt'
    dracula_stochastic = Stochastic(text_file)
    sentence = dracula_stochastic.create_sentence(word_num)

    end_time = time.time()
    run_time = end_time - start_time
    # print(sentence_histogram)
    print(sentence)
    # print(dracula_stochastic.total_word_count)
    print("Run time:", run_time)


# -*- coding: utf-8 -*-
"""
Created on Wed Feb 12 16:12:37 2020

@author: TatuEdi
"""
import numpy as np

entradas = np.array([1, 7, 5]) #Se entradas[0] = 1 o resultado é positivo se for -1 é negativo
pesos = np.array([0.8, 0.1, 0])

def soma(e, p):
    return e.dot(p)
#dot é o produto escalar

s = soma(entradas, pesos)

def stepFunc(soma):
    if(soma >=1):
        return 1
    return 0

r = stepFunc(s)


import fileinput, re, time

GRID_SIZE = 4000000

def readinput():
    sensors = []
    beacons = []
    for line in fileinput.input():
        match = re.findall(r"x=(-?\d+), y=(-?\d+)", line.strip())
        sensors.append(tuple(map(int, (match[0]))))
        beacons.append(tuple(map(int, (match[1]))))
    return sensors, beacons

def distance(sensor, beacon):
    return abs(sensor[0] - beacon[0]) + abs(sensor[1] - beacon[1])

def solve_part_one(sensors, beacons):
    x_points = set()
    y = 2000000
    for sensor, beacon in zip(sensors, beacons):
        beacon_dist = distance(sensor, beacon)
        y_dist = abs(sensor[1] - y)
        x_points_to_cover = beacon_dist - y_dist
        if x_points_to_cover > 0:
            for x in range(
                sensor[0] - x_points_to_cover,
                sensor[0] + x_points_to_cover,
            ):
                x_points.add(x)

    print("part one:", len(x_points))

def covers_x(sensor, beacon, y):
    beacon_dist = distance(sensor, beacon)
    y_dist = abs(sensor[1] - y)
    x_points_to_cover = beacon_dist - y_dist
    if x_points_to_cover > 0:
        x1 = sensor[0] - x_points_to_cover
        x2 = sensor[0] + x_points_to_cover
        if x1 < 0:
            x1 = 0
        if x2 > GRID_SIZE:
            x2 = GRID_SIZE
        return x1, x2
    else:
        return 0, 0

def merge(intervals):
    if len(intervals) == 0 or len(intervals) == 1:
        return intervals
    intervals.sort(key=lambda x: x[0])
    result = [intervals[0]]
    for interval in intervals[1:]:
        if interval[0] <= result[-1][1] + 1:
            result[-1][1] = max(result[-1][1], interval[1])
        else:
            result.append(interval)
    return result

def solve_part_two(sensors, beacons):
    start_time = time.time()
    for y in range(0, GRID_SIZE):
        # y = 100
        intervals = []
        for sensor, beacon in zip(sensors, beacons):
            x1, x2 = covers_x(sensor, beacon, y)
            if not (x1 == 0 and x2 == 0):
                intervals.append([x1, x2])
        # print(intervals)
        if len(intervals) > 0:
            mergedIntervals = merge(intervals)
            if len(mergedIntervals) > 1:
                x = mergedIntervals[0][1] + 1
                print("part two:", x * 4000000 + y)
    print("--- %s seconds ---" % (time.time() - start_time))

sensors, beacons = readinput()
solve_part_one(sensors, beacons)
solve_part_two(sensors, beacons)


def test():
    matrix = [
        ['C', 'X', 'T', 'Z'],
        ['X', 'A', 'Y', 'Z'],
        ['W', 'X', 'Q', 'R'],
    ]
    assert [(0,0), (1,1), (0,2)] == find_string(matrix, 'CAT')

def find_string(matrix, s):
    substrings = []
    for row in range(len(matrix)):
        for col in range(len(matrix[0])):
            c = matrix[row][col]
            if c == s[0]:
                if len(s) == 1:
                    return [(row, col)]
                substrings.append([(row, col)])
    while substrings:
        substring = substrings.pop()
        row, col = substring[-1]
        deltas = [
            (-1, -1), (-1, 0), (-1, 1),
            ( 0, -1),          ( 0, 1),
            ( 1, -1), ( 1, 0), ( 1, 1),
        ]
        for rd, cd in deltas:
            rn = row + rd
            cn = col + cd
            if (rn, cn) in substring:
                # don't allow repeats
                continue
            try:
                c = matrix[rn][cn]
            except IndexError:
                continue
            if c != s[len(substring)]:
                continue
            new_substring = substring + [(rn,cn)]
            if len(new_substring) == len(s):
                return new_substring
            substrings.append(new_substring)
    return None

test()


from aocd import data
import re
import numpy as np
import pandas as pd
from datetime import datetime

dl = data.split('\n')

def create_timeseries(data):
    # Create the Dataframe
    pattern = re.compile(r'\[(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2}) (?P<hour>\d{2}):(?P<minute>\d{2})\] (?P<action>.+)')
    actions = pd.Series(data)   # load into series
    df = actions.str.extract(pattern, expand=True)  # Expand via regex pattern

    # Create the timeseries index
    df[['year','month','day','hour','minute']] = df[['year','month','day','hour','minute']].apply(pd.to_numeric)  # Convert to int
    df[['year']] = 2018  # Forcing in-bounds year https://pandas-docs.github.io/pandas-docs-travis/timeseries.html#timeseries-oob
    df['ts'] = df.apply(lambda r: datetime(r.year, r.month, r.day, r.hour, r.minute, 0, 0), axis=1)  # Create timestamp field
    df['ts'] = pd.to_datetime(df.ts)  # Cast to pandas datetime
    df.drop(columns=['year','month','day', 'hour', 'minute'], inplace=True)  # Don't need these anymore
    df.set_index('ts', inplace=True)

    # Pull out guard id and set asleep flag
    guard_regex_pattern = re.compile(r'Guard #(?P<guard_id>\d+) begins shift')
    df['guard_id'] = df['action'].str.extract(guard_regex_pattern, expand=True)  # Pull out guard id
    df['asleep'] = np.where(df['action'] == 'falls asleep', 1, 0)

    # Fill empty timeslots so we have every minute to work with and filldown
    idx = pd.date_range(start=min(df.index), end=max(df.index), freq='min')
    idx = idx[(idx.hour == 0) | (idx.hour == 23)]  # Add entries for each minute during the midnight hour and before when they click in
    df = df.reindex(idx)
    df.sort_index(inplace=True)

    df['asleep'].ffill(inplace=True)  # filldown asleep flag
    df['guard_id'].ffill(inplace=True)  # Fill down guard id
    df['minute'] = df.index.minute
    return df

def part_a(data):
    df = create_timeseries(data)

    # Group by guard and minute and add them
    guard_sum = df.groupby(['guard_id']).sum()
    guard_num = guard_sum.idxmax().asleep # Sleepiest guard

    # Get guard schedule
    minute_sum = df[df['guard_id'] == guard_num].groupby('minute').sum()
    min_num = minute_sum.idxmax().asleep  # Sleepiest minute

    return int(guard_num) * int(min_num)

def part_b(data):
    df = create_timeseries(data)

    # Group by guard_id and minute
    sleepiest_guard_min = df.groupby(['guard_id','minute']).sum()
    i = sleepiest_guard_min.idxmax()
    return int(i.asleep[0]) * int(i.asleep[1])

ex1 = [
    '[1518-11-01 00:00] Guard #10 begins shift',
    '[1518-11-01 00:05] falls asleep',
    '[1518-11-01 00:25] wakes up',
    '[1518-11-01 00:30] falls asleep',
    '[1518-11-01 00:55] wakes up',
    '[1518-11-01 23:58] Guard #99 begins shift',
    '[1518-11-02 00:40] falls asleep',
    '[1518-11-02 00:50] wakes up',
    '[1518-11-03 00:05] Guard #10 begins shift',
    '[1518-11-03 00:24] falls asleep',
    '[1518-11-03 00:29] wakes up',
    '[1518-11-04 00:02] Guard #99 begins shift',
    '[1518-11-04 00:36] falls asleep',
    '[1518-11-04 00:46] wakes up',
    '[1518-11-05 00:03] Guard #99 begins shift',
    '[1518-11-05 00:45] falls asleep',
    '[1518-11-05 00:55] wakes up']

assert part_a(ex1) == 240
print("A: {}".format(part_a(dl)))

assert part_b(ex1) == 4455
print("B: {}".format(part_b(dl)))


from . import views
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
    path('become-staff/', views.become_staff,name="become_staff"),
    path('staff-admin/', views.staff_admin,name="staff_admin"),
    path('logout/', views.logoutUser, name="logout" ),
    path('login/', views.loginUser, name='login'),
    path('add-product/', views.add_product,name="add_product"),
    path('edit-staff/', views.edit_staff, name='edit_staff'),
    path('', views.staffs, name='staffs'),
    path('<int:staff_id>/', views.staff, name='staff'),
    path('edit-product/<str:pk>/', views.edit_product,name="edit_product"),
    path('delete-product/<str:pk>/', views.delete_product, name="delete_product"),

]

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


import streamlit as st
import pandas as pd
import altair as alt

from urllib.error import URLError

@st.cache
def get_vaccination_data():
    """
    Data from Covid19India.org

    """
    COVID_INDIA_URL = "http://api.covid19india.org/csv/latest/cowin_vaccine_data_statewise.csv"
    df = pd.read_csv(COVID_INDIA_URL)
    return df

try:

    df = get_vaccination_data()
    pivot_table = df.pivot(index = 'State', columns = 'Updated On',values='Total Individuals Vaccinated')
    new_cols = dict(zip(pivot_table.columns, [pd.to_datetime(x,format="%d/%m/%Y").date() for x in pivot_table.columns]))
    df_formatted = pivot_table.rename(columns= new_cols, inplace=False)
    states = st.multiselect(
        "Choose states", list(df_formatted.index), ["Andhra Pradesh", "Goa"]
    )

    if not states:
        st.error("Please select at least one state.")
    else:
        data =  df_formatted.loc[states]
        st.write("### Vaccinations", data.sort_index())
        data = data.T.reset_index()
        data = pd.melt(data, id_vars=["Updated On"]).rename(
            columns={"Updated On": "date", "value": "Total Individuals Vaccinated"}
        )
        chart = (
            alt.Chart(data)
            .mark_line()
            .encode(
                x="date:T",
                y=alt.Y("Total Individuals Vaccinated:Q", stack=None),
                color="State:N",
            )
        )
    st.altair_chart(chart, use_container_width=True)
except URLError as e:
    st.error(
        """
        **This demo requires internet access.**

        Connection error: %s
    """
        % e.reason
    )


import time
import sys, os
from collections import deque
from tracker import Tracker #time tracker

class UnreachableExitError(BaseException):
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return 'They\'re all gonna die :('

with Tracker() as t: #time tracker

    maze = [] #create any maze you want where "O" - Start; "X" - Finish
    maze.append(['X',' ',' ','#','#','#'])
    maze.append(['#','#',' ',' ',' ',' '])
    maze.append(['#',' ','#','#','#',' '])
    maze.append([' ',' ',' ',' ','#',' '])
    maze.append(['#',' ','#',' ',' ',' '])
    maze.append(['#','#','#',' ','#','#'])
    maze.append(['#','#',' ',' ','#','#'])
    maze.append(['#',' ',' ',' ',' ',' '])
    maze.append([' ',' ',' ','#','#',' '])
    maze.append([' ','#','#',' ','#',' '])
    maze.append(['#',' ',' ',' ',' ',' '])
    maze.append(['#','#','#',' ','#','#'])
    maze.append(['#','#','#',' ',' ','#'])
    maze.append(['O',' ',' ',' ','#',' '])
    maze.append(['#',' ','#','#','#',' '])
    maze.append(['#',' ',' ',' ',' ',' '])
    maze.append(['#',' ','#',' ',' ',' '])
    maze.append(['#','#','#',' ','#',' '])
    maze.append(['#','#','#',' ','#',' '])
    maze.append(['#',' ',' ',' ','#',' '])
    maze.append(['#',' ','#','#','#',' '])
    maze.append(['#',' ','#','#','#',' '])
    maze.append(['#',' ',' ',' ',' ',' '])
    maze.append(['#','#','#','#','#',' '])

    path = deque() #main queue
    been_here = {} #to avoid jumping to the squares which has already been checked

    #printing the path to the exit of the maze simply and nicely
    def print_maze(start_coords, final_coords, fin_direction, maze):
        line = start_coords[0]
        step = start_coords[1]
        for direction in fin_direction:

            if direction == 'L':
                step -= 1
                if maze[line][step] != ' ':
                    for row in maze:
                        print(row)
                    return

                maze[line][step] = 'o'
                for row in maze:
                    print(row)

            if direction == 'R':
                step += 1
                if maze[line][step] != ' ':
                    for row in maze:
                        print(row)
                    return

                maze[line][step] = 'o'
                for row in maze:
                    print(row)

            if direction == 'U':
                line -= 1
                if maze[line][step] != ' ':
                    for row in maze:
                        print(row)
                    return

                maze[line][step] = 'o'
                for row in maze:
                    print(row)

            if direction == 'D':
                line += 1
                if maze[line][step] != ' ':
                    for row in maze:
                        print(row)
                    return

                maze[line][step] = 'o'
                for row in maze:
                    print(row)

            time.sleep(0.3)
            os.system('cls') #for window cmd to clear the console before printing the next maze

    def find_start(maze):
        for line in range(len(maze)):
            for step in range(len(maze[line])):
                if maze[line][step] == 'O':
                    return [line, step]

    def finding_path(maze, line, step, direction=''):
        been_here[(line, step)] = 'START' #first square is checked now
        while True:
            if not line - 1 < 0: #invalid move, coz it goes outside the maze
                if maze[line - 1][step] == ' ': #valid move
                    if not been_here.get((line - 1, step)): #if the squared has already been saved, we're too late, someone's got here faster, but if not:
                        path.append([direction + 'U', [line - 1, step]])#check UP later
                        been_here[(line - 1, step)] = direction + 'U'#okay, UP square will be checked 100%, so we save it
                elif maze[line - 1][step] == 'X':#the destination point, first to this place is the fastest(shortest in this algorithm)
                    return [direction + 'U', [line - 1, step]] #return the results

            #others directions are getting checked just the same as the UP
            if not line + 1 > len(maze) - 1:
                if maze[line + 1][step] == ' ':
                    if not been_here.get((line + 1, step)):
                        path.append([direction + 'D', [line + 1, step]])
                        been_here[(line + 1, step)] = direction + 'D'
                elif maze[line + 1][step] == 'X':
                    return [direction + 'D', [line + 1, step]]

            if not step - 1 < 0:
                if maze[line][step - 1] == ' ':
                    if not been_here.get((line, step - 1)):
                        path.append([direction + 'L', [line, step - 1]])
                        been_here[(line, step - 1)] = direction + 'L'
                elif maze[line][step - 1] == 'X':
                    return [direction + 'L', [line, step - 1]]

            if not step + 1 > len(maze[line]) - 1:
                if maze[line][step + 1] == ' ':
                    if not been_here.get((line, step + 1)):
                        path.append([direction + 'R', [line, step + 1]])
                        been_here[(line, step + 1)] = direction + 'R'
                elif maze[line][step + 1] == 'X':
                    return [direction + 'R', [line, step + 1]]

            try: #if path is empty it means that the destination is not reachable
                direction, coords = path.popleft() #won't be able to pop from the empty array
                line, step = coords
            except IndexError as err:
                raise UnreachableExitError('The exit is unreachable') from err

    start = find_start(maze)
    try:
        try:
            fin_direction, fin_coords = finding_path(maze, *start)
            print_maze(start, fin_coords, fin_direction, maze)
        except UnreachableExitError as err:
            print(err.msg)
            print(err)
            print(f'Python to blame, it says => {err.__cause__}')
    except Exception:
        print('Something\'s really dumb just happened')


# Unir em um novo vetor os elementos de dois vetores

# Nome do projeto: União de Vetores
# Linguagem: Python
# Utilizações: Variáveis, Repetições e Vetores
# Autor: Rafael Lua - rafaellua13

vetor1 = [1,2,3,4,5]
vetor2 = [4,5,6,7,8,9]
vetor3 = [""] * (len(vetor1) + len(vetor2))

for x in range(len(vetor1)):
  vetor3[x] = vetor1[x]

cont = len(vetor1) - 1

for z in range(len(vetor2)):

    for y in range(len(vetor1)):
      if vetor2[z] != vetor1[y]:
        existe = False

      else:
        existe = True
        break

    if existe == False:
      cont += 1
      vetor3[cont] = vetor2[z]

#print(vetor3)

for a in range(len(vetor3)):
  print(vetor3[a], end = " ")

print()


import pygame
from Exit_gate import *
from Platforms import *
from Enemy import *
from Coin import *

blob_group = pygame.sprite.Group()
platform_group = pygame.sprite.Group()
lava_group = pygame.sprite.Group()
exit_group = pygame.sprite.Group()
coin_group = pygame.sprite.Group()

#Dummy coin beside the score
score_coin = Coin(tile_size//2, tile_size//2)
coin_group.add(score_coin)

class World:
    def __init__(self, data):
        self.tile_list = []

        dirt_img = pygame.image.load('img/dirt.png')
        grass_img = pygame.image.load('img/grass.png')
        # lava_img = pygame.image.load('img/lava.png')

        row_count = 0
        for row in data:
            col_count = 0
            for tile in row:
                if tile == 1:
                    img = pygame.transform.scale(dirt_img, (tile_size, tile_size))
                    img_rect = img.get_rect()
                    img_rect.x = col_count*tile_size
                    img_rect.y = row_count*tile_size
                    tile = (img, img_rect)
                    self.tile_list.append(tile)
                if tile == 2:
                    img = pygame.transform.scale(grass_img, (tile_size, tile_size))
                    img_rect = img.get_rect()
                    img_rect.x = col_count*tile_size
                    img_rect.y = row_count*tile_size
                    tile = (img, img_rect)
                    self.tile_list.append(tile)
                if tile == 3:
                    blob = Enemy(col_count*tile_size, row_count*tile_size+15)
                    blob_group.add(blob)
                if tile == 4:   # Horizontol
                    platform = Platform(col_count*tile_size, row_count*tile_size, 1, 0)
                    platform_group.add(platform)
                if tile == 5:   # Vertical
                    platform = Platform(col_count*tile_size, row_count*tile_size, 0, 1)
                    platform_group.add(platform)
                if tile == 6:
                    lava = Lava(col_count*tile_size, row_count*tile_size+tile_size//2)
                    lava_group.add(lava)
                if tile == 7:
                    coin = Coin(col_count*tile_size + (tile_size // 2), row_count*tile_size + tile_size//2)
                    coin_group.add(coin)
                if tile == 8:
                    exi = Exit(col_count*tile_size, row_count*tile_size- (tile_size//2))
                    exit_group.add(exi)
                col_count += 1
            row_count += 1

    def draw(self, screen):
        for tile in self.tile_list:
            screen.blit(tile[0], tile[1])


import socket
import random
from collections import defaultdict

def encode_utf(message):
    """Encodes a given message to utf-8 encoding

    :param message: The message to be encoded to utf-8
    :type message: str
    :return: The utf-8 encoded message
    """
    return str(message).encode('utf-8')

def decode_utf(message):
    """Decodes a given message from utf-8 encoding

    :param message: The message to be decoded to utf-8
    :return: The utf-8 decoded message
    """
    return message.decode('utf-8')

def get_sentence():
    """Function that creates a random sentence based on th principle of Markov chains

    :return:
    """
    with open("dracula.txt") as f:
        words = f.read().split()

    word_dict = defaultdict(list)
    for word, next_word in zip(words, words[1:]):
        word_dict[word].append(next_word)

    word = "Dracula"
    word_list = []
    while not word.endswith("."):
        word_list.append(word)
        word = random.choice(word_dict[word])

    _sentence = " ".join(word_list)
    return _sentence

class TCPClient:
    def __init__(self, host, port):
        self.serverName = host
        self.serverPort = port
        self.clientSocket = None

    def create(self):
        """Class method to create a TCP socket object and instantiates the clientSocket
        class variable

        """
        try:
            self.clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except socket.error as e:
            print(f"Error creating socket: {e}")

    def connect(self):
        """Class method to connect the client socket to given server ip address (serverName)
        and server port (serverPort).

        """
        try:
            self.clientSocket.connect((self.serverName, self.serverPort))
        except socket.error as e:
            print(f"Error creating socket: {e}")

    def send_message(self, sentence):
        """Class method to send a message from client to server

        :param sentence: The message (the sentence from client) that needs to be transmitted
        """
        try:
            self.clientSocket.send(encode_utf(sentence))
        except socket.error as e:
            print(f"Error sending data: {e}")

    def receive_message(self):
        """Class method to receive a message from server

        :return: The message returned from server
        :rtype: bytes
        """
        try:
            message = self.clientSocket.recv(1024)
            return message
        except socket.error as e:
            print(f"Error receiving data: {e}")

    def close_socket(self):
        """Method to close the created socket

        """
        self.clientSocket.close()

    def get_word_and_char_count(self, sentence_to_send):
        """The main driver mechanics that sends sentence to the server
        and return results from the server.

        :param sentence_to_send: The sentence to be send
        :type sentence_to_send: str
        :returns:
            - word_count - The number of words returned
            - num_chars - the number of characters returned
        """
        print(f"The sentence is: {sentence_to_send}")
        self.send_message(sentence_to_send)
        word_count, num_chars = [int(i) for i in decode_utf(self.receive_message()).split('\n')]
        print(f"The number of words is {word_count} and the characters is {num_chars}")
        return word_count, num_chars

if __name__ == '__main__':
    print("Client fired up:")
    serverName = socket.gethostname()  # ‘hostname’
    serverPort = 12000
    ip_address = socket.gethostbyname(serverName)
    client = TCPClient(ip_address, serverPort)
    client.create()
    client.connect()
    sentence = get_sentence()
    client.get_word_and_char_count(sentence)
    client.close_socket()


import random
from itertools import chain, zip_longest

import pytest

from semantic_release.commit_parser.scipy import (
    ScipyCommitParser,
    ScipyParserOptions,
    tag_to_section,
)
from semantic_release.enums import LevelBump

from tests.const import SCIPY_FORMATTED_COMMIT_BODY_PARTS
from tests.util import xdist_sort_hack

@pytest.fixture
def default_scipy_parser_options():
    return ScipyCommitParser.parser_options()

@pytest.fixture
def default_scipy_parser(default_scipy_parser_options):
    return ScipyCommitParser(default_scipy_parser_options)

@pytest.fixture(params=tag_to_section.keys())
def scipy_tag(request):
    return request.param

@pytest.fixture(
    params=xdist_sort_hack(
        [
            "scipy.stats.qmc: centered-discrepancy optimization of a Latin hypercube",
            "inverse missing in idstn, idctn (#14479)",
            "Merge pull request #14447 from AnirudhDagar/rename_ndimage_modules",
            "Add tests for args kwarg in quad_vec",
            "badge with version of the doc in the navbar (#14132)",
            "Bump scipy from 1.7.0 to 1.7.1 (#28)",
            "avoid nan if angle=0 in RotvecRotation",
        ]
    )
)
def subject(request):
    return request.param

@pytest.fixture(params=xdist_sort_hack(SCIPY_FORMATTED_COMMIT_BODY_PARTS))
def body_parts(request):
    return request.param

@pytest.fixture
def expected_response_scipy(
    default_scipy_parser_options, scipy_tag, subject, body_parts
):
    bump_level = default_scipy_parser_options.tag_to_level[scipy_tag]
    type_ = tag_to_section[scipy_tag]
    changelog_body = (subject, *body_parts)
    return (bump_level, type_, None, changelog_body)

def _make_scipy_commit(scipy_tag, subject, body_parts):
    body = "\n\n".join(body_parts)
    return f"{scipy_tag}: {subject}\n\n{body}"

@pytest.fixture
def valid_scipy_commit(scipy_tag, subject, body_parts):
    return _make_scipy_commit(scipy_tag, subject, body_parts)

@pytest.fixture(
    params=xdist_sort_hack(
        [
            k
            for k, v in ScipyParserOptions().tag_to_level.items()
            if v is LevelBump.PATCH
        ]
    )
)
def scipy_commits_patch(request, subject):
    return [
        _make_scipy_commit(request.param, subject, body_parts)
        for body_parts in SCIPY_FORMATTED_COMMIT_BODY_PARTS
    ]

@pytest.fixture(
    params=xdist_sort_hack(
        [
            k
            for k, v in ScipyParserOptions().tag_to_level.items()
            if v is LevelBump.MINOR
        ]
    )
)
def scipy_commits_minor(request, subject, default_scipy_parser_options):
    patch_tags = [
        k
        for k, v in default_scipy_parser_options.tag_to_level.items()
        if v is LevelBump.PATCH
    ]
    patch_commits = [
        _make_scipy_commit(random.choice(patch_tags), subject, body_parts)
        for body_parts in SCIPY_FORMATTED_COMMIT_BODY_PARTS
    ]
    minor_commits = [
        _make_scipy_commit(request.param, subject, body_parts)
        for body_parts in SCIPY_FORMATTED_COMMIT_BODY_PARTS
    ]
    return list(
        chain.from_iterable(
            zip_longest(minor_commits, patch_commits, fillvalue="uninteresting")
        )
    )

@pytest.fixture(
    params=xdist_sort_hack(
        [
            k
            for k, v in ScipyParserOptions().tag_to_level.items()
            if v is LevelBump.MAJOR
        ]
    )
)
def scipy_commits_major(request, subject, default_scipy_parser_options):
    patch_tags = [
        k
        for k, v in default_scipy_parser_options.tag_to_level.items()
        if v is LevelBump.PATCH
    ]
    minor_tags = [
        k
        for k, v in default_scipy_parser_options.tag_to_level.items()
        if v is LevelBump.MINOR
    ]
    patch_commits = [
        _make_scipy_commit(random.choice(patch_tags), subject, body_parts)
        for body_parts in SCIPY_FORMATTED_COMMIT_BODY_PARTS
    ]
    minor_commits = [
        _make_scipy_commit(random.choice(minor_tags), subject, body_parts)
        for body_parts in SCIPY_FORMATTED_COMMIT_BODY_PARTS
    ]
    major_commits = [
        _make_scipy_commit(request.param, subject, body_parts)
        for body_parts in SCIPY_FORMATTED_COMMIT_BODY_PARTS
    ]
    return list(
        chain.from_iterable(
            zip_longest(
                major_commits, minor_commits, patch_commits, fillvalue="uninteresting"
            )
        )
    )


from django.urls import path

from . import views

app_name = 'ploadmin'

urlpatterns = [
    path('', views.test, name='test'),
    path('detail/<int:user_id>', views.detail, name='detail'),
    path('results/', views.results, name='results'),
    path('modify/<int:user_id>', views.modify, name='modify'),
    path('index', views.index, name='index'),
    path('login', views.login, name='login'),
    path('home', views.home, name='home'),
    path('user', views.user, name='user'),
    path('signin', views.signin, name='signin'),
    path('country', views.country, name='country'),
]


import unittest2 as unittest

import ROOT

from monitoring_app import tasks

class TestPages(unittest.TestCase):
    def setUp(self):
        self.fextension = 'root'
        # The fname and keys match those of the data generated by
        # `generate_histograms.py`
        self.dummy_fname = 'histograms.root'
        self.dummy_keys = ['histogram_{0}'.format(i) for i in range(4)]
        self.dummy_th1 = ROOT.TH1F('dummy:xtitle:ytitle', 'dummy', 10, 0, 1)
        self.dummy_th1.FillRandom('gaus', 1000)

    def tearDown(self):
        # Delete TH1 so we don't create multiple instances with the same name
        del self.dummy_th1

    def test_add_file_extension(self):
        """Extension is added to a filename when not present."""
        fname = 'filename'
        fname_expected = '{0}.{1}'.format(fname, self.fextension)
        assert tasks.add_file_extension(fname) == fname_expected

    def test_dont_add_file_extension_again(self):
        """Extension is not added to a filename if already present."""
        fname = 'filename.{0}'.format(self.fextension)
        assert tasks.add_file_extension(fname) == fname

    def test_data_for_th1f(self):
        """Appropriate information is provided on TH1F ROOT objects."""
        data = tasks.data_for_object(self.dummy_th1)
        for key in ('binning', 'values', 'uncertainties', 'axis_titles'):
            assert key in data
        nbins = self.dummy_th1.GetNbinsX()
        assert len(data['binning']) == nbins
        assert len(data['values']) == nbins
        assert len(data['uncertainties']) == nbins
        assert len(data['axis_titles']) == 2
        assert data['axis_titles'][0] == self.dummy_th1.GetXaxis().GetTitle()
        assert data['axis_titles'][1] == self.dummy_th1.GetYaxis().GetTitle()

    def test_data_for_unknown_tobject(self):
        """No information should be returned for unsupported ROOT objects."""
        # Use a child of TObject that we don't support
        obj = ROOT.TH3D()
        data = tasks.data_for_object(obj)
        assert not data

    def test_get_key_from_file(self):
        """Dictionary describing key in file is returned."""
        data = tasks.get_key_from_file(self.dummy_fname, self.dummy_keys[0])
        for k in ('success', 'data'):
            assert k in data
        data_data = data['data']
        assert data['success'] == True
        assert data_data
        for k in ('filename', 'key_name', 'key_title', 'key_class', 'key_data'):
            assert k in data_data
        assert data_data['filename'].endswith(self.dummy_fname)
        assert data_data['key_name'] == self.dummy_keys[0]
        assert data_data['key_title'] == 'Gaussian'
        assert data_data['key_class'] == 'TH1F'

    def test_get_key_from_file_invalid_filename(self):
        """Error dictionary is returned with message."""
        # As this test intentionally tries to open a non-existent file, which
        # ROOT would by default print an error about, temporarily change the
        # logging level to suppress such a message
        originalErrorIgnoreLevel = ROOT.gErrorIgnoreLevel
        ROOT.gErrorIgnoreLevel = ROOT.kFatal
        data = tasks.get_key_from_file('fake_file.root', self.dummy_keys[0])
        ROOT.gErrorIgnoreLevel = originalErrorIgnoreLevel
        for k in ('success', 'message'):
            assert k in data
        assert 'data' not in data
        assert data['success'] == False
        assert data['message'].startswith('Could not open')

    def test_get_key_from_file_invalid_key_name(self):
        """Error dictionary is returned with message."""
        data = tasks.get_key_from_file(self.dummy_fname, 'fake_key')
        for k in ('success', 'message'):
            assert k in data
        assert 'data' not in data
        assert data['success'] == False
        assert data['message'].startswith('Could not find')

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


import requests
from dotenv import load_dotenv
import os
load_dotenv()

api_key = os.getenv('MUSICMIX_KEY')
def getLyrics(q_track, q_artist):
    q_track = q_track.strip()
    q_artist = q_artist.strip()
    # Replace All space (unicode is \\s) to %20
    q_track = q_track.replace(' ', "%20")
    q_artist = q_artist.replace(' ', "%20")

    response = requests.get("https://api.musixmatch.com/ws/1.1/matcher.lyrics.get&apikey="+api_key+"&q_track="+q_track+"&q_artist="+q_artist)
    #print(response.status_code)
    data = response.json()
    lyrics = data["message"]["body"]["lyrics"]["lyrics_body"]

    result = ""
    i = 0
    for line in lyrics.split('\n'):
        result += line + " "
        i += 1
    return result


from datetime import datetime

from example.v1.example_protodc import Example, ExampleWatOneof as Oneof

dc = Example(
    life_the_universe_and_everything=42,
    examples=[
        Example(life_the_universe_and_everything=43),
    ],
    time=datetime.now()
)

dc.javascript = "eval('while(true){}')"

# Round trip to JSON and back.
txt = dc.to_protojson()
dc2 = Example.from_protojson(txt)

# Round trip to a python protobuf and back.
pb = dc.to_protobuf()
dc3 = Example.from_protobuf(pb)

# Check that nothing was lost in translation...
print(dc == dc2 == dc3)


import numpy as np

def read_GOCAD_ts(tsfile):
    r"""Read GOCAD triangulated surface (*.ts) file

    Parameters
    ----------
    tsfile : str
        Path to triangulated surface (*.ts) file

    Returns
    -------
    vrts : (n, 3) numpy.ndarray
        Vertices in XYZ coordinates
    trgl : (m, 3) numpy.ndarray of int
        Array of indexes where each row represents the indexes for a particular
        triangle. Note that the order of the vertices matter, as they defined
        normal vectors; i.e. :math:`\hat{n} = (\mathbf{p_2 - p_1}) \times (\mathbf{p_3 - p_1})`
    """

    import re

    fid = open(tsfile, "r")
    line = fid.readline()

    # Skip all the lines until the vertices
    while re.match("TFACE", line) is None:
        line = fid.readline()

    line = fid.readline()
    vrtx = []

    # Run down all the vertices and save in array
    while re.match("VRTX", line):
        l_input = re.split(r"[\s*]", line)
        temp = np.array(l_input[2:5])
        vrtx.append(temp.astype(float))

        # Read next line
        line = fid.readline()

    vrtx = np.asarray(vrtx)

    # Skip lines to the triangles
    while re.match("TRGL", line) is None:
        line = fid.readline()

    # Run down the list of triangles
    trgl = []

    # Run down all the vertices and save in array
    while re.match("TRGL", line):
        l_input = re.split(r"[\s*]", line)
        temp = np.array(l_input[1:4])
        trgl.append(temp.astype(int))

        # Read next line
        line = fid.readline()

    trgl = np.asarray(trgl)

    return vrtx, trgl

def download(url, folder=".", overwrite=False, verbose=True):
    """Download all files stored in a cloud directory.

    Parameters
    ----------
    url : str or list of str
        A single URL or a list of URLs for all cloud directories containing files
        you wish to download.
    folder : str
        Path to the directory where all files are downloaded to. This function will
        create the directory if the directory does not already exist.
    overwrite : bool
        If ``True``, the function will overwrite preexisting files with new files
        in the case they both have identical names. If ``False``, the name of the
        file being downloaded is change if it is identical to a preexisting file name.
    verbose : bool
        Print download progress
    """

    # Download from cloud
    import urllib.request
    import os
    import sys

    def rename_path(downloadpath):
        splitfullpath = downloadpath.split(os.path.sep)

        # grab just the filename
        fname = splitfullpath[-1]
        fnamesplit = fname.split(".")
        newname = fnamesplit[0]

        # check if we have already re-numbered
        newnamesplit = newname.split("(")

        # add (num) to the end of the filename
        if len(newnamesplit) == 1:
            num = 1
        else:
            num = int(newnamesplit[-1][:-1])
            num += 1

        newname = "{}({}).{}".format(newnamesplit[0], num, fnamesplit[-1])
        return os.path.sep.join(splitfullpath[:-1] + newnamesplit[:-1] + [newname])

    # grab the correct url retriever
    if sys.version_info < (3,):
        urlretrieve = urllib.urlretrieve
    else:
        urlretrieve = urllib.request.urlretrieve

    # ensure we are working with absolute paths and home directories dealt with
    folder = os.path.abspath(os.path.expanduser(folder))

    # make the directory if it doesn't currently exist
    if not os.path.exists(folder):
        os.makedirs(folder)

    if isinstance(url, str):
        filenames = [url.split("/")[-1]]
    elif isinstance(url, list):
        filenames = [u.split("/")[-1] for u in url]

    downloadpath = [os.path.sep.join([folder, f]) for f in filenames]

    # check if the directory already exists
    for i, download in enumerate(downloadpath):
        if os.path.exists(download):
            if overwrite is True:
                if verbose is True:
                    print("overwriting {}".format(download))
            elif overwrite is False:
                while os.path.exists is True:
                    download = rename_path(download)

                if verbose is True:
                    print("file already exists, new file is called {}".format(download))
                downloadpath[i] = download

    # download files
    urllist = url if isinstance(url, list) else [url]
    for u, f in zip(urllist, downloadpath):
        print("Downloading {}".format(u))
        urlretrieve(u, f)
        print("   saved to: " + f)

    print("Download completed!")
    return downloadpath if isinstance(url, list) else downloadpath[0]


import torch
from torch.autograd import Function

class GuidedBackpropReLU(Function):
    @staticmethod
    def forward(ctx, input):
        positive_mask = (input > 0).type_as(input)
        output = torch.addcmul(
            torch.zeros(input.size()).type_as(input), input, positive_mask
        )
        ctx.save_for_backward(input, output)
        return output

    @staticmethod
    def backward(ctx, grad_output):
        input, output = ctx.saved_variables

        positive_mask_1 = (input > 0).type_as(grad_output)
        positive_mask_2 = (grad_output > 0).type_as(grad_output)
        grad_input = torch.addcmul(
            torch.zeros(input.size()).type_as(input),
            torch.addcmul(
                torch.zeros(input.size()).type_as(input), grad_output, positive_mask_1
            ),
            positive_mask_2,
        )

        return grad_input

def guide_relu(self, input):
    output = GuidedBackpropReLU.apply(input)
    return output


# -*- coding: utf-8 -*-
"""
Created on Tue Jan 14 11:42:10 2020

@author: Henry Huang in Elekta Shanghai Co. Ltd.
"""

from HYP_TP_60 import Initialization_MON60
import sys
import pandas as pd

pt_id = sys.argv[1]
delivery_method = sys.argv[2]
fx = sys.argv[3]
prep_dose=sys.argv[4]
#LABEL equals 'Site' in Monaco script
LABEL=sys.argv[5]
grid_dose = sys.argv[6]
path = sys.argv[7]
protocol_xlsx = sys.argv[8]
PT_path = sys.argv[9]
planname = sys.argv[10]
iter = sys.argv[11]

#pt_id = '003'
#delivery_method = 'VMAT'
#fx = 28
#prep_dose= 61.6
#LABEL equals 'Site' in Monaco script
#LABEL= 'NPC'
#grid_dose = 3 # mm
#path = 'C:/autotemplate/HYPSolution6.0'
#protocol_xlsx = 'C:/autotemplate/XHprotocol.xlsx'
#PT_path = 'C:/Users/Public/Documents/CMS/FocalData/Installation/Clinic_XH/1~'
#planname = '05291023'
#iter = '0'

OAR_preferences = ['Brain Stem','Oral Cavity']

X = Initialization_MON60(pt_id,
                       delivery_method,
                       fx,
                       prep_dose,
                       grid_dose,
                       path,
                       protocol_xlsx,
                       PT_path)

protocol_dict = X.extract_xlsx(pt_id)  # protocol_dict store the constraints in protocol

#DVH = X.csv_read_to_dvh() # DVH Raw Data Struct
#dvh_inf = X.DVH_MAX_MEAN(DVH) # Dmean and Dmax extracted

# need to change if Yvonne could provide the modified version of DVH Statistics table
#dvh_stat_calc = X.DVH_Stat_Extract(dvh_inf,DVH)

###############################################################################
###############################################################################
######### Monaco TPS load Treatment Template into GUI #########################
######### Start Phase 1 Optimization Fleunce Map Optimization #################
######### Monaco TPS export DVH.csv and current template.hyp file #############
###############################################################################
###############################################################################

# absolute DVH csv file path
DVH_JSON ='C:/autotemplate/dvh/DVHStatistics_' + pt_id + '_' + planname + '_' + str(iter) + '.json'

# temporary hyp file path
hyp_path = 'C:/autotemplate/temporary.hyp'

# updated hyp file path
#FMO1_hyp_path_updated = 'C:/Users/Public/Documents/CMS/FocalData/MonacoTemplates'
FMO1_hyp_path_updated = 'C:/autotemplate/'

# load treatment plan template (raw data structure)
# strt_fun,strt_index,line = X.read_template()    # need to update
line,strt_index,IMRT_TABLE = X.Read_Template_60()
print(IMRT_TABLE)

# read DVH Statistics Information from Monaco TPS
dvh_stat_calc = X.DVH_Stat_Extract_JSON(DVH_JSON)

# start Fine Tunning Template file
New_IMRT_CONSTRAINT,Old_IMRT_CONSTRAINT = X.MAIN_Tune_TP_60(LABEL,
                   DVH_JSON,
                   OAR_preferences,
                   pt_id,
                   delivery_method)

IMRT_cosntraints_path = 'C:/autotemplate/IMRTconstraints/' + pt_id + '_' + planname + "_" + iter + '.csv'
New_IMRT_CONSTRAINT.to_csv(IMRT_cosntraints_path, encoding='utf-8')

path = 'C:/GitFolder/RL-Application-in-TPS/AUTO-PLANNING/AutoTemplateTuning/projects/dose prediction/DATA'


import torch
import torch.nn as nn
import numpy as np

import torchvision
import util

import skimage.measure
from torch.nn import functional as F

from pytorch_prototyping import pytorch_prototyping
import custom_layers
import geometry
import hyperlayers

class SRNsModel(nn.Module):
    def __init__(self,
                 num_instances,
                 latent_dim,
                 tracing_steps,
                 has_params=False,
                 fit_single_srn=False,
                 use_unet_renderer=False,
                 freeze_networks=False):
        super().__init__()

        self.latent_dim = latent_dim
        self.has_params = has_params

        self.num_hidden_units_phi = 256
        self.phi_layers = 4  # includes the in and out layers
        self.rendering_layers = 5  # includes the in and out layers
        self.sphere_trace_steps = tracing_steps
        self.freeze_networks = freeze_networks
        self.fit_single_srn = fit_single_srn

        if self.fit_single_srn:  # Fit a single scene with a single SRN (no hypernetworks)
            self.phi = pytorch_prototyping.FCBlock(hidden_ch=self.num_hidden_units_phi,
                                                   num_hidden_layers=self.phi_layers - 2,
                                                   in_features=3,
                                                   out_features=self.num_hidden_units_phi)
        else:
            # Auto-decoder: each scene instance gets its own code vector z
            self.latent_codes = nn.Embedding(num_instances, latent_dim).cuda()
            nn.init.normal_(self.latent_codes.weight, mean=0, std=0.01)

            self.hyper_phi = hyperlayers.HyperFC(hyper_in_ch=self.latent_dim,
                                                 hyper_num_hidden_layers=1,
                                                 hyper_hidden_ch=self.latent_dim,
                                                 hidden_ch=self.num_hidden_units_phi,
                                                 num_hidden_layers=self.phi_layers - 2,
                                                 in_ch=3,
                                                 out_ch=self.num_hidden_units_phi)

        self.ray_marcher = custom_layers.Raymarcher(num_feature_channels=self.num_hidden_units_phi,
                                                    raymarch_steps=self.sphere_trace_steps)

        if use_unet_renderer:
            self.pixel_generator = custom_layers.DeepvoxelsRenderer(nf0=32, in_channels=self.num_hidden_units_phi,
                                                                    input_resolution=128, img_sidelength=128)
        else:
            self.pixel_generator = pytorch_prototyping.FCBlock(hidden_ch=self.num_hidden_units_phi,
                                                               num_hidden_layers=self.rendering_layers - 1,
                                                               in_features=self.num_hidden_units_phi,
                                                               out_features=3,
                                                               outermost_linear=True)

        if self.freeze_networks:
            all_network_params = (list(self.pixel_generator.parameters())
                                  + list(self.ray_marcher.parameters())
                                  + list(self.hyper_phi.parameters()))
            for param in all_network_params:
                param.requires_grad = False

        # Losses
        self.l2_loss = nn.MSELoss(reduction="mean")

        # List of logs
        self.logs = list()

        print(self)
        print("Number of parameters:")
        util.print_network(self)

    def get_regularization_loss(self, prediction, ground_truth):
        """Computes regularization loss on final depth map (L_{depth} in eq. 6 in paper)

        :param prediction (tuple): Output of forward pass.
        :param ground_truth: Ground-truth (unused).
        :return: Regularization loss on final depth map.
        """
        _, depth = prediction

        neg_penalty = (torch.min(depth, torch.zeros_like(depth)) ** 2)
        return torch.mean(neg_penalty) * 10000

    def get_image_loss(self, prediction, ground_truth):
        """Computes loss on predicted image (L_{img} in eq. 6 in paper)

        :param prediction (tuple): Output of forward pass.
        :param ground_truth: Ground-truth (unused).
        :return: image reconstruction loss.
        """
        pred_imgs, _ = prediction
        trgt_imgs = ground_truth['rgb']

        trgt_imgs = trgt_imgs.cuda()

        loss = self.l2_loss(pred_imgs, trgt_imgs)
        return loss

    def get_latent_loss(self):
        """Computes loss on latent code vectors (L_{latent} in eq. 6 in paper)
        :return: Latent loss.
        """
        if self.fit_single_srn:
            self.latent_reg_loss = 0
        else:
            self.latent_reg_loss = torch.mean(self.z ** 2)

        return self.latent_reg_loss

    def get_psnr(self, prediction, ground_truth):
        """Compute PSNR of model image predictions.

        :param prediction: Return value of forward pass.
        :param ground_truth: Ground truth.
        :return: (psnr, ssim): tuple of floats
        """
        pred_imgs, _ = prediction
        trgt_imgs = ground_truth['rgb']

        trgt_imgs = trgt_imgs.cuda()
        batch_size = pred_imgs.shape[0]

        if not isinstance(pred_imgs, np.ndarray):
            pred_imgs = util.lin2img(pred_imgs).detach().cpu().numpy()

        if not isinstance(trgt_imgs, np.ndarray):
            trgt_imgs = util.lin2img(trgt_imgs).detach().cpu().numpy()

        psnrs, ssims = list(), list()
        for i in range(batch_size):
            p = pred_imgs[i].squeeze().transpose(1, 2, 0)
            trgt = trgt_imgs[i].squeeze().transpose(1, 2, 0)

            p = (p / 2.) + 0.5
            p = np.clip(p, a_min=0., a_max=1.)

            trgt = (trgt / 2.) + 0.5

            ssim = skimage.measure.compare_ssim(p, trgt, multichannel=True, data_range=1)
            psnr = skimage.measure.compare_psnr(p, trgt, data_range=1)

            psnrs.append(psnr)
            ssims.append(ssim)

        return psnrs, ssims

    def get_comparisons(self, model_input, prediction, ground_truth=None):
        predictions, depth_maps = prediction

        batch_size = predictions.shape[0]

        # Parse model input.
        intrinsics = model_input["intrinsics"].cuda()
        uv = model_input["uv"].cuda().float()

        x_cam = uv[:, :, 0].view(batch_size, -1)
        y_cam = uv[:, :, 1].view(batch_size, -1)
        z_cam = depth_maps.view(batch_size, -1)

        normals = geometry.compute_normal_map(x_img=x_cam, y_img=y_cam, z=z_cam, intrinsics=intrinsics)
        normals = F.pad(normals, pad=(1, 1, 1, 1), mode="constant", value=1.)

        predictions = util.lin2img(predictions)

        if ground_truth is not None:
            trgt_imgs = ground_truth["rgb"]
            trgt_imgs = util.lin2img(trgt_imgs)

            return torch.cat((normals.cpu(), predictions.cpu(), trgt_imgs.cpu()), dim=3).numpy()
        else:
            return torch.cat((normals.cpu(), predictions.cpu()), dim=3).numpy()

    def get_output_img(self, prediction):
        pred_imgs, _ = prediction
        return util.lin2img(pred_imgs)

    def write_updates(self, writer, predictions, ground_truth, iter, prefix=""):
        """Writes tensorboard summaries using tensorboardx api.

        :param writer: tensorboardx writer object.
        :param predictions: Output of forward pass.
        :param ground_truth: Ground truth.
        :param iter: Iteration number.
        :param prefix: Every summary will be prefixed with this string.
        """
        predictions, depth_maps = predictions
        trgt_imgs = ground_truth['rgb']

        trgt_imgs = trgt_imgs.cuda()

        batch_size, num_samples, _ = predictions.shape

        # Module"s own log
        for type, name, content, every_n in self.logs:
            name = prefix + name

            if not iter % every_n:
                if type == "image":
                    writer.add_image(name, content.detach().cpu().numpy(), iter)
                    writer.add_scalar(name + "_min", content.min(), iter)
                    writer.add_scalar(name + "_max", content.max(), iter)
                elif type == "figure":
                    writer.add_figure(name, content, iter, close=True)
                elif type == "histogram":
                    writer.add_histogram(name, content.detach().cpu().numpy(), iter)
                elif type == "scalar":
                    writer.add_scalar(name, content.detach().cpu().numpy(), iter)
                elif type == "embedding":
                    writer.add_embedding(mat=content, global_step=iter)

        if not iter % 100:
            output_vs_gt = torch.cat((predictions, trgt_imgs), dim=0)
            output_vs_gt = util.lin2img(output_vs_gt)
            writer.add_image(prefix + "Output_vs_gt",
                             torchvision.utils.make_grid(output_vs_gt,
                                                         scale_each=False,
                                                         normalize=True).cpu().detach().numpy(),
                             iter)

            rgb_loss = ((predictions.float().cuda() - trgt_imgs.float().cuda()) ** 2).mean(dim=2, keepdim=True)
            rgb_loss = util.lin2img(rgb_loss)

            fig = util.show_images([rgb_loss[i].detach().cpu().numpy().squeeze()
                                    for i in range(batch_size)])
            writer.add_figure(prefix + "rgb_error_fig",
                              fig,
                              iter,
                              close=True)

            depth_maps_plot = util.lin2img(depth_maps)
            writer.add_image(prefix + "pred_depth",
                             torchvision.utils.make_grid(depth_maps_plot.repeat(1, 3, 1, 1),
                                                         scale_each=True,
                                                         normalize=True).cpu().detach().numpy(),
                             iter)

        writer.add_scalar(prefix + "out_min", predictions.min(), iter)
        writer.add_scalar(prefix + "out_max", predictions.max(), iter)

        writer.add_scalar(prefix + "trgt_min", trgt_imgs.min(), iter)
        writer.add_scalar(prefix + "trgt_max", trgt_imgs.max(), iter)

        if iter:
            writer.add_scalar(prefix + "latent_reg_loss", self.latent_reg_loss, iter)

    def forward(self, input, z=None):
        self.logs = list() # log saves tensors that"ll receive summaries when model"s write_updates function is called

        # Parse model input.
        instance_idcs = input["instance_idx"].long().cuda()
        pose = input["pose"].cuda()
        intrinsics = input["intrinsics"].cuda()
        uv = input["uv"].cuda().float()

        if self.fit_single_srn:
            phi = self.phi
        else:
            if self.has_params: # If each instance has a latent parameter vector, we"ll use that one.
                if z is None:
                    self.z = input["param"].cuda()
                else:
                    self.z = z
            else: # Else, we"ll use the embedding.
                self.z = self.latent_codes(instance_idcs)

            phi = self.hyper_phi(self.z) # Forward pass through hypernetwork yields a (callable) SRN.

        # Raymarch SRN phi along rays defined by camera pose, intrinsics and uv coordinates.
        points_xyz, depth_maps, log = self.ray_marcher(cam2world=pose,
                                                       intrinsics=intrinsics,
                                                       uv=uv,
                                                       phi=phi)
        self.logs.extend(log)

        # Sapmle phi a last time at the final ray-marched world coordinates.
        v = phi(points_xyz)

        # Translate features at ray-marched world coordinates to RGB colors.
        novel_views = self.pixel_generator(v)

        # Calculate normal map
        with torch.no_grad():
            batch_size = uv.shape[0]
            x_cam = uv[:, :, 0].view(batch_size, -1)
            y_cam = uv[:, :, 1].view(batch_size, -1)
            z_cam = depth_maps.view(batch_size, -1)

            normals = geometry.compute_normal_map(x_img=x_cam, y_img=y_cam, z=z_cam, intrinsics=intrinsics)
            self.logs.append(("image", "normals",
                              torchvision.utils.make_grid(normals, scale_each=True, normalize=True), 100))

        if not self.fit_single_srn:
            self.logs.append(("embedding", "", self.latent_codes.weight, 500))
            self.logs.append(("scalar", "embed_min", self.z.min(), 1))
            self.logs.append(("scalar", "embed_max", self.z.max(), 1))

        return novel_views, depth_maps


import math
from collections import deque
def divisors(n):
	d1 = deque()
	d2 = deque()
	for i in range(1, math.ceil(math.sqrt(n))):
		if n % i == 0:
			d1.append(i)
			d2.appendleft(int(n/i))
	s = math.sqrt(n)
	if n % s == 0:
		return list(d1) + [int(math.sqrt(n))] + list(d2)
	else:
		return list(d1) + list(d2)

user = int(input())
print(len(divisors(user)))


# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding("utf-8")

from project.database import db, Base
from marshmallow import Schema, fields
import datetime

class ShipmentMethod(Base):
    __tablename__ = 'shipment_methods'
    id = db.Column(db.BigInteger, primary_key=True)
    title = db.Column(db.String(length=100), nullable=False)
    description = db.Column(db.Text, nullable=False)
    price = db.Column(db.DECIMAL(precision=20, scale=4), default=0)

    created_at = db.Column(db.TIMESTAMP, default=datetime.datetime.now, nullable=False)
    updated_at = db.Column(db.TIMESTAMP, default=datetime.datetime.now, nullable=False, onupdate=datetime.datetime.now)

    def __str__(self):
        return self.title + " با هزینه ارسال : " + str(self.price)

class ShipmentMethodSchema(Schema):
    id = fields.Int()
    title = fields.Str()
    description = fields.Str()
    price = fields.Str()


# -*- coding: utf-8 -*-
"""
Created on Mon Aug 26 12:04:45 2019

@author: DELL
"""
a1=1;
a2=2;
a=0
sum=2;
while True:
    a=a1+a2;
    a1=a2;
    a2=a;
    remainer=a%2;
    if a>4000000:
        break;
    if remainer==0:
        sum=sum+a;

print("sum=",sum,19//100)


from math import floor

def valid_word(word):
    """Word consists of [a-Z-]
    First and last char are alpha chars.

    >>> valid_word("test-")
    False
    >>> valid_word("alp-oma")
    False
    >>> valid_word("a#bc")
    False
    """
    return all(c.isalpha() for c in word)
    # allAlpha = [c.isalpha() for c in word]
    # extraChars = [False] + [c in ["-"] for c in word[1:-1]] + [False]
    # return all(allAlpha[i] or extraChars[i] for i in range(len(allAlpha)))

def endword(line):
    """
    >>> endword("Lo ferm voler qu'el cor m'intra")
    'intra'
    >>> endword("no'm pot ges becs escoissendre ni ongla")
    'ongla'
    >>> endword("de lauzengier qui pert per mal dir s'arma;")
    'arma'
    """
    tl = [c.isalpha() for c in line]
    tl.reverse()
    end = tl.index(True)

    word = line[::-1][end:][::-1]
    while not valid_word(word):
        word = word[1:]
        if len(word) == 1:
            return word
    return word

def stanzas(filename):
    """
    >>> stanzas('sestina0.txt')
    [['intra', 'ongla', 'arma', 'verja', 'oncle', 'cambra'], ['cambra', 'intra', 'oncle', 'ongla', 'verja', 'arma'], ['arma', 'cambra', 'verja', 'intra', 'ongla', 'oncle'], ['oncle', 'arma', 'ongla', 'cambra', 'intra', 'verja'], ['verja', 'oncle', 'intra', 'arma', 'cambra', 'ongla'], ['ongla', 'verja', 'cambra', 'oncle', 'arma', 'intra'], ['oncle', 'arma', 'intra']]
    >>> stanzas('sestina1.txt')
    [['enters', 'nail', 'soul', 'rod', 'uncle', 'room'], ['room', 'enters', 'uncle', 'nail', 'rod', 'soul'], ['soul', 'room', 'rod', 'enters', 'nail', 'uncle'], ['uncle', 'soul', 'nail', 'room', 'enters', 'rod'], ['rod', 'uncle', 'enters', 'soul', 'room', 'nail'], ['nail', 'rod', 'room', 'uncle', 'soul', 'enters'], ['nail', 'soul', 'enters']]
    >>> stanzas('sestina2.txt')
    [['woe', 'sound', 'cryes', 'part', 'sleepe', 'augment'], ['augment', 'woe', 'sound', 'cryes', 'part', 'sleepe'], ['sleepe', 'augment', 'woe', 'sound', 'cryes', 'part'], ['part', 'sleepe', 'augment', 'woe', 'sound', 'cryes'], ['cryes', 'part', 'sleepe', 'augment', 'woe', 'sound'], ['sound', 'cryes', 'part', 'sleepe', 'augment', 'woe'], ['sound', 'part', 'augment']]
    """
    ll = [[]]
    with open(filename, "r") as f:
        for line in f:
            if len(line.strip()) == 0:
                if ll[-1]:
                    ll.append([])
            else:
                ll[-1].append(endword(line).lower())
    return ll

def permutation(wordlist, pattern=None):
    """
    >>> permutation(['a', 'b', 'c', 'd', 'e', 'f'])
    ['f', 'a', 'e', 'b', 'd', 'c']
    >>> permutation(['a', 'b', 'c', 'd', 'e'])
    ['e', 'a', 'd', 'b', 'c']
    >>> permutation(['rose', 'love', 'heart', 'sang', 'rhyme', 'woe'])
    ['woe', 'rose', 'rhyme', 'love', 'sang', 'heart']
    >>> permutation(['woe', 'rose', 'rhyme', 'love', 'sang', 'heart'])
    ['heart', 'woe', 'sang', 'rose', 'love', 'rhyme']
    >>> permutation(['rose', 'love', 'heart', 'sang', 'rhyme'])
    ['rhyme', 'rose', 'sang', 'love', 'heart']
    >>> permutation(['rose', 'love', 'heart', 'sang', 'rhyme', 'woe'], [6, 1, 5, 2, 4, 3])
    ['woe', 'rose', 'rhyme', 'love', 'sang', 'heart']
    >>> permutation(['rose', 'love', 'heart', 'sang', 'rhyme', 'woe'], [6, 5, 4, 3, 2, 1])
    ['woe', 'rhyme', 'sang', 'heart', 'love', 'rose']
    >>> permutation(['rose', 'love', 'heart', 'sang', 'rhyme', 'woe'], [6, 1, 5, 3, 4, 3])
    Traceback (most recent call last):
    AssertionError: invalid permutation
    """
    amount = len(wordlist)
    if pattern:
        # pattern has right amount of unique elements
        assert amount == len(set(pattern)), "invalid permutation"

        assert all(
            list(set(pattern))[i] == i + 1 for i in range(amount)
        ), "invalid permutation"

    else:
        # canonical permutation
        pattern = [i + 1 for i in range(amount)]

        half = floor(amount / 2)

        p1, p2 = pattern[:half], pattern[half:]
        pattern = [None] * (len(p1) + len(p2))
        pattern[::2] = p2[::-1]
        pattern[1::2] = p1

    return [wordlist[idx - 1] for idx in pattern]

def sestina(filename, pattern=None):
    """
    >>> sestina('sestina0.txt')
    True
    >>> sestina('sestina0.txt', [6, 1, 5, 2, 4, 3])
    True
    >>> sestina('sestina1.txt')
    True
    >>> sestina('sestina2.txt')
    False
    >>> sestina('sestina2.txt', [6, 1, 2, 3, 4, 5])
    True
    """
    sz = stanzas(filename)

    words = sz[0]

    n = len(words)

    # check if all stanzas have words contained in set
    for stanza in sz[1:]:
        if any(word not in words for word in stanza):
            # print("Unrecognized word.")
            return False

    # check if right amount of stanzas
    if len(sz) == n:
        envoi = False
    elif len(sz) == n + 1:
        envoi = True
    else:
        # print("Number of stanzas is wrong.")
        return False

    # check length of envoi
    if envoi and len(sz[-1]) != floor(n / 2):
        # print("Envoi has wrong length.")
        return False

    # check if permutations are correct
    perm = sz[0]
    for i in range(1, n):
        new_perm = permutation(perm, pattern)
        perm = sz[i]

        if any(new_perm[j].lower() != perm[j].lower() for j in range(len(perm))):
            # print(f"Invalid permutation of stanzas on alinea {i+1}.")
            return False

    # otherwise valid sestina
    return True

if __name__ == "__main__":
    import doctest

    doctest.testmod()


from Consola import Consola
from Bicicleta import Bicicleta
from Tv import Tv
from Scoter import Scoter

#lista de Eficiencia
listaEficiencia = ["A", "B", "C", "D", "E", "F"]

# Función para registrar un TV y agregarlo a la lista de TVs
def registrar_tv():
    print("Registrando un nuevo TV:")
    marca = input("Ingrese la marca: ")
    voltaje = int(input("Ingrese el voltaje (en voltios): "))
    precio = float(input("Ingrese el precio: "))
    eficiencia = input("Ingrese la eficiencia (A, B, C, D, E o F): ")
    tamanio = float(input("Ingrese el tamaño en pulgadas: "))

    # Validaciones simples
    if voltaje < 0 or precio < 0 or tamanio < 0 or eficiencia.upper() not in listaEficiencia:
        print("Error: Datos ingresados no válidos para registrar un TV.")
        return

    tv = Tv(marca, voltaje, precio, eficiencia, tamanio)
    listaTvs.append(tv)
    print("TV registrado exitosamente.")

# Función para registrar una consola y agregarla a la lista de consolas
def registrar_consola():
    print("Registrando una nueva Consola:")
    marca = input("Ingrese la marca: ")
    nombre_consola = input("Ingrese el nombre de la consola: ")
    version = input("Ingrese la versión (Lite u otra): ")
    voltaje = int(input("Ingrese el voltaje (en voltios): "))
    precio = float(input("Ingrese el precio: "))
    eficiencia = input("Ingrese la eficiencia (A, B, C, D, E o F): ")

    # Validaciones
    if voltaje <= 0 or precio <= 0 or eficiencia.upper() not in listaEficiencia:
        print("Error: Datos ingresados no válidos para registrar una Consola.")
        return

    # Crear el objeto Consola y agregarlo a la lista
    consola = Consola(marca, nombre_consola, version, voltaje, precio, eficiencia)
    listaConsolas.append(consola)
    print("Consola registrada exitosamente.")

# Función para registrar una bicicleta y agregarla a la lista de bicicletas
def registrar_bicicleta():
    print("Registrando una nueva Bicicleta:")
    marca = input("Ingrese la marca: ")
    aro = float(input("Ingrese el aro: "))
    peso = float(input("Ingrese el peso en kg: "))
    precio = float(input("Ingrese el precio: "))

    # Validaciones
    if aro < 0 or peso < 0 or precio < 0:
        print("Error: Datos ingresados no válidos para registrar una Bicicleta.")
        return

    # Crear el objeto Bicicleta y agregarlo a la lista
    bicicleta = Bicicleta(aro, peso, precio, marca)
    listaBicicletas.append(bicicleta)
    print("Bicicleta registrada exitosamente.")

def registrar_scooter():
    print("Registrando un nuevo Scooter:")
    marca = input("Ingrese la marca: ")
    voltaje = int(input("Ingrese el voltaje (en voltios): "))
    precio = float(input("Ingrese el precio: "))
    eficiencia = input("Ingrese la eficiencia (A, B, C, D, E o F): ")
    aro = float(input("Ingrese el aro: "))
    velocidad = int(input("Ingrese la velocidad (en km/h): "))
    peso = float(input("Ingrese el peso en kg: "))

    # Validaciones
    if voltaje <= 0 or precio <= 0 or aro <= 0 or velocidad <= 0 or peso <= 0 or eficiencia.upper() not in listaEficiencia:
        print("Error: Datos ingresados no válidos para registrar un Scooter.")
        return

    # Crear el objeto Scooter y agregarlo a la lista
    scooter = Scoter(marca, voltaje, precio, eficiencia, aro, velocidad, peso)
    listaScoters.append(scooter)
    print("Scooter registrado exitosamente.")

# Función para cotizar los TVs y mostrar la información
def cotizar_tvs():
    print("Cotizando TVs:")
    for tv in listaTvs:
        print(tv.cotizar())

# Función para cotizar las consolas y mostrar la información
def cotizar_consolas():
    print("Cotizando Consolas:")
    for consola in listaConsolas:
        print(consola.cotizar())

# Función para cotizar los scooters y mostrar la información
def cotizar_scooters():
    for scooter in listaScoters:
        print(scooter.cotizar())

# Función para cotizar las bicicletas y mostrar la información
def cotizar_bicicletas():
    print("Cotizando Bicicletas:")
    for bicicleta in listaBicicletas:
        print(bicicleta.cotizar())

# Función para mostrar el menú de opciones
def menu():
    print("Menú:")
    print("1. Registrar TV")
    print("2. Registrar Consola")
    print("3. Registrar Bicicleta")
    print("4. Registrar Scoter")
    print("5. Cotizar TVs")
    print("6. Cotizar Consolas")
    print("7. Cotizar Bicicletas")
    print("8. Cotizar Scooters")
    print("9. Salir")

# Lista para almacenar los productos
listaTvs = []
listaConsolas = []
listaScoters = []
listaBicicletas = []

while True:
    menu()
    opcion = int(input("Seleccione una opción: "))

    if opcion == 1:
        registrar_tv()
    elif opcion == 2:
        registrar_consola()
    elif opcion == 3:
        registrar_bicicleta()
    elif opcion == 4:
        registrar_scooter()
    elif opcion == 5:
        cotizar_tvs()
    elif opcion == 6:
        cotizar_consolas()
    elif opcion == 7:
        cotizar_bicicletas()
    elif opcion == 8:
        cotizar_scooters()
    elif opcion == 9:
        break
    else:
        print("Opción no válida. Por favor, seleccione una opción válida.")

# Fin del programa


import torch
from torch import Tensor

import mmdeploy
from mmdeploy.core import FUNCTION_REWRITER, mark
from mmdeploy.mmcv.ops import ONNXNMSop, TRTBatchedNMSop
from mmdeploy.utils import Backend, is_dynamic_batch

class BatchNMSOp(torch.autograd.Function):
    @staticmethod
    def forward(ctx, bboxes, scores, score_threshold, iou_threshold, max_size_per_class, max_total_size, image_size):
        """
        boxes (torch.Tensor): boxes in shape (batch, N, C, 4).
        scores (torch.Tensor): scores in shape (batch, N, C).
        return:
            nmsed_boxes: (1, N, 4)
            nmsed_scores: (1, N)
            nmsed_classes: (1, N)
            nmsed_num: (1,)
        """

        # Phony implementation for onnx export
        nmsed_boxes = bboxes[:, :max_total_size, 0, :]
        nmsed_scores = torch.rand(1, max_total_size)
        nmsed_classes = torch.arange(max_total_size * bboxes.shape[0], dtype=torch.long)
        nmsed_num = torch.Tensor([max_total_size])

        return nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_num

    @staticmethod
    def symbolic(g, bboxes, scores, score_thr, iou_thr, max_size_p_class, max_t_size, image_size):
        nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_num = g.op('BatchMultiClassNMS',
            bboxes, scores, score_threshold_f=score_thr, iou_threshold_f=iou_thr,
            max_size_per_class_i=max_size_p_class, max_total_size_i=max_t_size, image_size_i=image_size, outputs=4)
        return nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_num

def batch_nms_op(bboxes, scores, score_threshold, iou_threshold, max_size_per_class, max_total_size, image_size):
    """
    boxes (torch.Tensor): boxes in shape (N, 4).
    scores (torch.Tensor): scores in shape (N, ).
    """

    if bboxes.dtype == torch.float32:
        bboxes = bboxes.reshape(bboxes.shape[0], bboxes.shape[1], -1, 4).half()
        scores = scores.reshape(scores.shape[0], scores.shape[1], -1).half()
    else:
        bboxes = bboxes.reshape(bboxes.shape[0], bboxes.shape[1], -1, 4)
        scores = scores.reshape(scores.shape[0], scores.shape[1], -1)

    nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_num = BatchNMSOp.apply(bboxes, scores,
        score_threshold, iou_threshold, max_size_per_class, max_total_size, image_size)
    nmsed_boxes = nmsed_boxes.float()
    nmsed_scores = nmsed_scores.float()
    nmsed_classes = nmsed_classes.long()
    dets = torch.cat((nmsed_boxes.reshape((-1, max_total_size, 4)), nmsed_scores.reshape((-1, max_total_size, 1))), -1)
    labels = nmsed_classes.reshape((-1, max_total_size))
    labels = labels.int()
    return dets, labels

def select_nms_index(scores: torch.Tensor,
                     boxes: torch.Tensor,
                     nms_index: torch.Tensor,
                     batch_size: int,
                     keep_top_k: int = -1):
    """Transform NMS output.
    Args:
        scores (Tensor): The detection scores of shape
            [N, num_classes, num_boxes].
        boxes (Tensor): The bounding boxes of shape [N, num_boxes, 4].
        nms_index (Tensor): NMS output of bounding boxes indexing.
        batch_size (int): Batch size of the input image.
        keep_top_k (int): Number of top K boxes to keep after nms.
            Defaults to -1.
    Returns:
        tuple[Tensor, Tensor]: (dets, labels), `dets` of shape [N, num_det, 5]
            and `labels` of shape [N, num_det].
    """
    batch_inds, cls_inds = nms_index[:, 0], nms_index[:, 1]
    box_inds = nms_index[:, 2]

    # index by nms output
    scores = scores[batch_inds, cls_inds, box_inds].unsqueeze(1)
    boxes = boxes[batch_inds, box_inds, ...]
    dets = torch.cat([boxes, scores], dim=1)

    # batch all
    batched_dets = dets.unsqueeze(0).repeat(batch_size, 1, 1)
    batch_template = torch.arange(
        0, batch_size, dtype=batch_inds.dtype, device=batch_inds.device)
    batched_dets = batched_dets.where(
        (batch_inds == batch_template.unsqueeze(1)).unsqueeze(-1),
        batched_dets.new_zeros(1))

    batched_labels = cls_inds.unsqueeze(0).repeat(batch_size, 1)
    batched_labels = batched_labels.where(
        (batch_inds == batch_template.unsqueeze(1)),
        batched_labels.new_ones(1) * -1)

    N = batched_dets.shape[0]

    # expand tensor to eliminate [0, ...] tensor
    batched_dets = torch.cat((batched_dets, batched_dets.new_zeros((N, 1, 5))),
                             1)
    batched_labels = torch.cat((batched_labels, batched_labels.new_zeros(
        (N, 1))), 1)

    # sort
    is_use_topk = keep_top_k > 0 and \
                  (torch.onnx.is_in_onnx_export() or keep_top_k < batched_dets.shape[1])
    if is_use_topk:
        _, topk_inds = batched_dets[:, :, -1].topk(keep_top_k, dim=1)
    else:
        _, topk_inds = batched_dets[:, :, -1].sort(dim=1, descending=True)
    topk_batch_inds = torch.arange(
        batch_size, dtype=topk_inds.dtype,
        device=topk_inds.device).view(-1, 1).expand_as(topk_inds)
    batched_dets = batched_dets[topk_batch_inds, topk_inds, ...]
    batched_labels = batched_labels[topk_batch_inds, topk_inds, ...]

    # slice and recover the tensor
    return batched_dets, batched_labels

def _multiclass_nms(boxes: Tensor,
                    scores: Tensor,
                    max_output_boxes_per_class: int = 1000,
                    iou_threshold: float = 0.5,
                    score_threshold: float = 0.05,
                    pre_top_k: int = -1,
                    keep_top_k: int = -1):
    """Create a dummy onnx::NonMaxSuppression op while exporting to ONNX.
    This function helps exporting to onnx with batch and multiclass NMS op. It
    only supports class-agnostic detection results. That is, the scores is of
    shape (N, num_bboxes, num_classes) and the boxes is of shape (N, num_boxes,
    4).
    """
    max_output_boxes_per_class = torch.LongTensor([max_output_boxes_per_class])
    iou_threshold = torch.tensor([iou_threshold], dtype=torch.float32)
    score_threshold = torch.tensor([score_threshold], dtype=torch.float32)
    batch_size = scores.shape[0]
    pre_top_k = 1024
    if pre_top_k > 0:
        max_scores, _ = scores.max(-1)
        _, topk_inds = max_scores.topk(pre_top_k)
        batch_inds = torch.arange(batch_size).view(
            -1, 1).expand_as(topk_inds).long()
        boxes = boxes[batch_inds, topk_inds, :]
        scores = scores[batch_inds, topk_inds, :]

    #scores = scores.permute(0, 2, 1)
    dets, labels = batch_nms_op(boxes, scores, score_threshold.item(), iou_threshold.item(),
                                256, 96, (2048, 2048))
    return dets, labels

def _multiclass_nms_single(boxes: Tensor,
                           scores: Tensor,
                           max_output_boxes_per_class: int = 1000,
                           iou_threshold: float = 0.5,
                           score_threshold: float = 0.05,
                           pre_top_k: int = -1,
                           keep_top_k: int = -1):
    """Create a dummy onnx::NonMaxSuppression op while exporting to ONNX.
    Single batch nms could be optimized.
    """
    max_output_boxes_per_class = torch.LongTensor([max_output_boxes_per_class])
    iou_threshold = torch.tensor([iou_threshold], dtype=torch.float32)
    score_threshold = torch.tensor([score_threshold], dtype=torch.float32)

    # pre topk
    if pre_top_k > 0:
        max_scores, _ = scores.max(-1)
        _, topk_inds = max_scores.squeeze(0).topk(pre_top_k)
        boxes = boxes[:, topk_inds, :]
        scores = scores[:, topk_inds, :]

    scores = scores.permute(0, 2, 1)
    selected_indices = ONNXNMSop.apply(boxes, scores,
                                       max_output_boxes_per_class,
                                       iou_threshold, score_threshold)

    cls_inds = selected_indices[:, 1]
    box_inds = selected_indices[:, 2]

    scores = scores[:, cls_inds, box_inds].unsqueeze(2)
    boxes = boxes[:, box_inds, ...]
    dets = torch.cat([boxes, scores], dim=2)
    labels = cls_inds.unsqueeze(0)

    # pad
    dets = torch.cat((dets, dets.new_zeros((1, 1, 5))), 1)
    labels = torch.cat((labels, labels.new_zeros((1, 1))), 1)

    # topk or sort
    is_use_topk = keep_top_k > 0 and \
                  (torch.onnx.is_in_onnx_export() or keep_top_k < dets.shape[1])
    if is_use_topk:
        _, topk_inds = dets[:, :, -1].topk(keep_top_k, dim=1)
    else:
        _, topk_inds = dets[:, :, -1].sort(dim=1, descending=True)
    topk_inds = topk_inds.squeeze(0)
    dets = dets[:, topk_inds, ...]
    labels = labels[:, topk_inds, ...]

    return dets, labels

@FUNCTION_REWRITER.register_rewriter(
    func_name='mmdeploy.codebase.mmdet.core.post_processing._multiclass_nms')
def multiclass_nms__default(ctx,
                            boxes: Tensor,
                            scores: Tensor,
                            max_output_boxes_per_class: int = 1000,
                            iou_threshold: float = 0.5,
                            score_threshold: float = 0.05,
                            pre_top_k: int = -1,
                            keep_top_k: int = -1):
    """Create a dummy onnx::NonMaxSuppression op while exporting to ONNX.
    This function helps exporting to onnx with batch and multiclass NMS op.
    It only supports class-agnostic detection results. That is, the scores
    is of shape (N, num_bboxes, num_classes) and the boxes is of shape
    (N, num_boxes, 4).
    Args:
        boxes (Tensor): The bounding boxes of shape [N, num_boxes, 4].
        scores (Tensor): The detection scores of shape
            [N, num_boxes, num_classes].
        max_output_boxes_per_class (int): Maximum number of output
            boxes per class of nms. Defaults to 1000.
        iou_threshold (float): IOU threshold of nms. Defaults to 0.5.
        score_threshold (float): score threshold of nms.
            Defaults to 0.05.
        pre_top_k (int): Number of top K boxes to keep before nms.
            Defaults to -1.
        keep_top_k (int): Number of top K boxes to keep after nms.
            Defaults to -1.
    Returns:
        tuple[Tensor, Tensor]: (dets, labels), `dets` of shape [N, num_det, 5]
            and `labels` of shape [N, num_det].
    """
    deploy_cfg = ctx.cfg
    batch_size = boxes.size(0)
    if not is_dynamic_batch(deploy_cfg) and batch_size == 1:
        return _multiclass_nms_single(
            boxes,
            scores,
            max_output_boxes_per_class=max_output_boxes_per_class,
            iou_threshold=iou_threshold,
            score_threshold=score_threshold,
            pre_top_k=pre_top_k,
            keep_top_k=keep_top_k)
    else:
        return _multiclass_nms(
            boxes,
            scores,
            max_output_boxes_per_class=max_output_boxes_per_class,
            iou_threshold=iou_threshold,
            score_threshold=score_threshold,
            pre_top_k=pre_top_k,
            keep_top_k=keep_top_k)

@FUNCTION_REWRITER.register_rewriter(
    func_name='mmdeploy.codebase.mmdet.core.post_processing._multiclass_nms',
    backend='tensorrt')
def multiclass_nms_static(ctx,
                          boxes: Tensor,
                          scores: Tensor,
                          max_output_boxes_per_class: int = 1000,
                          iou_threshold: float = 0.5,
                          score_threshold: float = 0.05,
                          pre_top_k: int = -1,
                          keep_top_k: int = -1):
    """Wrapper for `multiclass_nms` with TensorRT.
    Args:
        ctx (ContextCaller): The context with additional information.
        boxes (Tensor): The bounding boxes of shape [N, num_boxes, 4].
        scores (Tensor): The detection scores of shape
            [N, num_boxes, num_classes].
        max_output_boxes_per_class (int): Maximum number of output
            boxes per class of nms. Defaults to 1000.
        iou_threshold (float): IOU threshold of nms. Defaults to 0.5.
        score_threshold (float): score threshold of nms.
            Defaults to 0.05.
        pre_top_k (int): Number of top K boxes to keep before nms.
            Defaults to -1.
        keep_top_k (int): Number of top K boxes to keep after nms.
            Defaults to -1.
    Returns:
        tuple[Tensor, Tensor]: (dets, labels), `dets` of shape [N, num_det, 5]
            and `labels` of shape [N, num_det].
    """
    boxes = boxes if boxes.dim() == 4 else boxes.unsqueeze(2)
    keep_top_k = max_output_boxes_per_class if keep_top_k < 0 else min(
        max_output_boxes_per_class, keep_top_k)
    dets, labels = TRTBatchedNMSop.apply(boxes, scores, int(scores.shape[-1]),
                                         pre_top_k, keep_top_k, iou_threshold,
                                         score_threshold, -1)

    return dets, labels

@mark('multiclass_nms', inputs=['boxes', 'scores'], outputs=['dets', 'labels'])
def multiclass_nms(*args, **kwargs):
    """Wrapper function for `_multiclass_nms`."""
    return mmdeploy.codebase.mmdet.core.post_processing._multiclass_nms(
        *args, **kwargs)

@FUNCTION_REWRITER.register_rewriter(
    func_name='mmdeploy.codebase.mmdet.core.post_processing._multiclass_nms',
    backend=Backend.TORCHSCRIPT.value)
def multiclass_nms__torchscript(ctx,
                                boxes: Tensor,
                                scores: Tensor,
                                max_output_boxes_per_class: int = 1000,
                                iou_threshold: float = 0.5,
                                score_threshold: float = 0.05,
                                pre_top_k: int = -1,
                                keep_top_k: int = -1):
    """rewrite for torchscript batched nms.
    Use batched_nms from torchvision instead of custom nms.
    """
    # TODO: simplify inference for non-batch model
    from torchvision.ops import batched_nms
    batch_size = scores.shape[0]
    num_boxes = scores.shape[1]
    num_classes = scores.shape[2]
    box_per_cls = len(boxes.shape) == 4
    scores = torch.where(scores > score_threshold, scores, scores.new_zeros(1))

    # pre-topk
    if pre_top_k > 0:
        max_scores, _ = scores.max(-1)
        _, topk_inds = max_scores.topk(pre_top_k)
        batch_inds = torch.arange(batch_size).view(
            -1, 1).expand_as(topk_inds).long()
        boxes = boxes[batch_inds, topk_inds, ...]
        scores = scores[batch_inds, topk_inds, :]
        num_boxes = scores.shape[1]

    idxs = torch.arange(0, batch_size, device=scores.device).unsqueeze(1)
    idxs = idxs.repeat(1, num_boxes).view(-1)

    keeps = [None] * num_classes
    for cls_id in range(num_classes):
        box = boxes if not box_per_cls else boxes[:, :, cls_id, :]
        score = scores[:, :, cls_id]
        box = box.view(-1, 4)
        score = score.view(-1)
        box_keep = batched_nms(box, score, idxs, iou_threshold=iou_threshold)
        box_keep = box_keep[:max_output_boxes_per_class * batch_size]
        batch_keep = idxs[box_keep]
        cls_keep = torch.ones_like(box_keep) * cls_id
        box_keep = box_keep - batch_keep * num_boxes
        keeps[cls_id] = torch.stack([batch_keep, cls_keep, box_keep], dim=1)

    keeps = torch.cat(keeps)
    scores = scores.permute(0, 2, 1)
    dets, labels = select_nms_index(
        scores, boxes, keeps, batch_size, keep_top_k=keep_top_k)

    return dets, labels


import cv2
from LabFiles import *
from lib.utils.Timer import *
from lib.Homography import *

Timer.start('program')

# read file
imGreen = cv2.imread(LabFiles.input(3, 2, 'green'))
imPoster = cv2.imread(LabFiles.input(3, 2, 'poster'))

H = np.array([[0.8346, -0.0058, -141.3292],
              [0.0116, 0.8025, -78.2148],
              [-0.0002, -0.0006, 1.]])
homography = Homography(H)

result = homography.applyInterpolated(imPoster, imGreen)

# print result

cv2.imwrite(LabFiles.output(3, 2, 'homographied-interpolated'), result)

# stoper
Timer.stop('program')

# show
LabFiles.show(3, 2, 'homographied-interpolated')


import rospy
from timeit import default_timer as timer
import threading

def example_rosbag_end_callback():
    print("Executing code 1s (wall) after rosbag end.")
    return

def example_rosbag_start_callback():
    print("Executing code 1s (wall) after rosbag start.")
    return

class RosbagEndDetector(object):
    def __init__(self, rosbag_end_callback=None, rosbag_start_callback=None):
        self.latest_rostime = None
        self.rosbag_started = False
        if rosbag_start_callback is None:
            rosbag_start_callback = example_rosbag_start_callback
        if rosbag_end_callback is None:
            rosbag_end_callback = example_rosbag_end_callback
        self.rosbag_start_callback = rosbag_start_callback
        self.rosbag_end_callback = rosbag_end_callback
        # start checking in separate thread
        self.check_every_s()

    def check_every_s(self):
        if self.latest_rostime is None:
            self.latest_rostime = rospy.Time.now()
        else:
            rostime = rospy.Time.now()
            if (rostime-self.latest_rostime) <= rospy.Duration(0.05):
                if self.rosbag_started:
                    rospy.logwarn("Rosbag end/pause detected!")
                    self.rosbag_end_callback()
                    return
            else:
                if not self.rosbag_started:
                    rospy.logwarn("Rosbag started, enabling end detector.")
                    self.rosbag_started = True
                    self.rosbag_start_callback()
            self.latest_rostime = rostime
        threading.Timer(1, self.check_every_s).start()


import argparse
import pandas as pd

def size_in_bits(nb):
    return nb.bit_length()

def read_addr_n_bits(input, size):
    res = input[:size]
    return int(res, 2)

def write_addr_n_bits(addr, size):
    res = str(bin(addr)[2:])
    padding = size - len(res)
    zeros = '0' * padding
    res = zeros + res
    return res

def uncompress(file, dico, special_character='%'):
    """
    Uncompress a file with an initial dictionary
    :param file: file to decompress
    :param dico: initial dictionary
    :return: the string corresponding to the uncompression of the file
    """
    max_addr = len(dico) - 1
    addr_size = size_in_bits(max_addr)
    output = ''
    df = pd.DataFrame(columns=['Buffer', 'Input', 'New sequence', 'Address',
                               'Output'])
    buffer = ''
    df_i = 0
    while file:
        addr = read_addr_n_bits(file, addr_size)
        file = file[addr_size:]
        input = dico[addr]
        if special_character in input:
            # increase the size by the number of special character
            addr_size += len(input)
            input_print = f"@D[{input}]={addr}"
            df.loc[df_i] = [buffer, input_print, '', '', '']
            df_i += 1
        else:
            new_seq = buffer + input[0]

            if new_seq in dico:
                input_print = f"@D[{input}]={addr}"
                df.loc[df_i] = [buffer, input_print, '', '', '']
                df_i += 1
                buffer += new_seq
            else:
                dico.append(new_seq)
                max_addr += 1

                buffer = new_seq[-1:] + input[1:]
                output_local = new_seq[:-1]

                input_print = f"@D[{input}]={addr}"
                df.loc[df_i] = [buffer, input_print, new_seq, max_addr,
                                output_local]
                df_i += 1
                output += output_local

    # No more character available. Hence empty the buffer
    df.loc[df_i] = [buffer, '', '', '', buffer]
    df_i += 1
    output += buffer

    return output

def make_dico(file, special_character='%'):
    dico_set = set()
    for c in file:
        dico_set.add(c)
    dico_set.add(special_character)
    dico = list(dico_set)
    dico.sort()
    return dico

def compress(file, special_character='%'):
    """
    Compress a file (its content)
    :param file: file to compress
    :param special_character:
    :return: list of address (integers) which represents the output
    """

    def check_size_address(addr_output, curr_size, output):
        addr_size = size_in_bits(addr_output)
        delta_size = addr_size - curr_size

        if delta_size > 0:
            addr_special_character = dico.index(special_character)
            df.loc[df_i - 1]['Output'] = \
                f"@[{special_character * delta_size}]=" \
                f"{addr_special_character * delta_size}"

            for i in range(delta_size):
                output += write_addr_n_bits(addr_special_character, curr_size)

        return delta_size, output

    dico = make_dico(file, special_character)

    addr = len(dico)
    output = ''
    df = pd.DataFrame(columns=['Buffer', 'Input', 'New sequence', 'Address',
                               'Output'])

    curr_size = size_in_bits(addr - 1)
    df_i = 0
    buffer = ''
    for input in file:  # foreach input character in the file

        new_seq = buffer + input
        if new_seq in dico:
            df.loc[df_i] = [buffer, input, '', '', '']
            buffer = new_seq
        else:  # the new sequence does not exist in the dictionary
            # Update dico
            dico.append(new_seq)
            output_local = new_seq[:-1]  # all except last character
            addr_output = dico.index(output_local)

            # Check size of the address
            delta_size, output = check_size_address(addr_output, curr_size,
                                                    output)
            if delta_size > 0:
                curr_size += delta_size

            # update table
            output_local = f"@[{output_local}]={addr_output}"
            df.loc[df_i] = [buffer, input, new_seq, addr, output_local]
            addr += 1
            buffer = new_seq[-1]

            # Update output
            output += write_addr_n_bits(addr_output, curr_size)

        df_i += 1

    # no more characters. Empty the buffer now
    assert (buffer in dico)

    addr_output = dico.index(buffer)
    delta_size, output = check_size_address(addr_output, curr_size, output)
    if delta_size > 0:
        curr_size += delta_size

    output_local = f"@[{buffer}]={addr_output}"
    df.loc[df_i] = [buffer, '', '', '', output_local]
    df_i += 1
    output += write_addr_n_bits(addr_output, curr_size)

    return output, df, dico

def process_compression_results(filename, output, df, dico, file_content):
    # Get the prefix of the file name
    prefix = filename[filename.rfind('/') + 1:]
    prefix = prefix[:-4]  # avoid .txt extension

    # Save LZW table
    table_file = prefix + '_LZWtable.csv'
    df.to_csv(table_file, index=False)

    # Save dico
    df_dico = pd.DataFrame(columns=dico)
    dico_file = prefix + '_dico.csv'
    df_dico.to_csv(dico_file, index=False)

    # Save the output of the compression
    output_file = prefix + '.lzw'
    output_file = open(output_file, "w")
    output_file.write(output)

    dico_init = make_dico(file_content)
    # -2 to avoid computing the special character and address begins at 0
    # Not sure though
    size_before_compression = size_in_bits(len(dico_init) - 2) \
                              * len(file_content)
    output_file.write(f"\nSize before LZW compression: "
                      f"{size_before_compression}")
    output_file.write(f"\nSize after LZW compression: {len(output)}")
    # Should i round here?
    ratio = round(len(output) / size_before_compression, 3)
    output_file.write(f"\nCompression ratio: {ratio}\n")
    output_file.close()

def save_output(filename, output, ext=""):
    # Get the prefix of the file name
    prefix = filename[filename.rfind('/') + 1:]
    prefix = prefix[:-4]  # avoid .lzw extension

    # Save output file
    output_file = prefix + ext
    output_file = open(output_file, "w")
    output_file.write(output)
    output_file.close()

def get_dictionary_from_csv(file):
    """
    Get the dictionary from a csv file
    :param file: .txt file corresponding to the csv file
    :return: list of words in the dictionary
    """
    csv_file = file[:-4]  # avoid .txt extension
    csv_file += "_dico.csv"
    dic = pd.read_csv(csv_file, delimiter=',')
    return list(dic.columns)

def get_file_content(filename):
    """
    Get the whole content of a file.
    :param filename:
    :return: return a string with the content of the file
    """
    fp = open(filename, "r")
    file_content = fp.read()
    fp.close()

    # if the last character is an end of line, remove it
    if file_content[-1] == '\n':
        file_content = file_content[:-1]
    return file_content

if __name__ == '__main__':
    #  parse command line
    parser = argparse.ArgumentParser(description='LZW compression and '
                                                 'decompression')
    parser.add_argument('-p', type=str, nargs=1, help="path to the file to "
                                                      "process")
    parser.add_argument('-c', action='store_true', help="Compress a file")
    parser.add_argument('-u', action='store_true', help="Uncompress a file")

    args = parser.parse_args()
    filename = args.p[0]

    #  Process the file
    if args.c:
        # Get the whole content of the file
        file_content = get_file_content(filename)
        output, df_res, dico_res = compress(file_content)
        process_compression_results(filename, output, df_res, dico_res,
                                    file_content)

    if args.u:
        # Get the initial dictionary
        dic = get_dictionary_from_csv(filename)
        # Get the string to uncompress
        file_content = get_file_content(filename)
        output = uncompress(file_content, dic)
        save_output(filename, output, ".txt")


from json.encoder import JSONEncoder
import datetime
import decimal
import uuid

class DefaultJsonEncoder(JSONEncoder):
    """
    An encoder specially created to encode datetime
    objects or other specific Python representations
    """
    def default(self, obj):
        # Date/Time string spcifications at ECMA 262
        # https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15

        if isinstance(obj, datetime.datetime):
            representation = obj.isoformat()
            if representation.endswith('+00:00'):
                representation = representation[:-6] + 'Z'
            return representation

        if isinstance(obj, datetime.time):
            if datetime.timezone and datetime.timezone.is_aware(obj):
                raise ValueError('Cannot represent timezon-aware times.')
            return obj.isoformat()

        if isinstance(obj, datetime.date):
            return str(obj)

        if isinstance(obj, datetime.timedelta):
            return str(obj.total_seconds())

        if isinstance(obj, decimal.Decimal):
            return float(obj)

        if isinstance(obj, uuid.UUID):
            return str(obj)

        if isinstance(obj, bytes):
            return obj.decode()

        if hasattr(obj, 'tolist'):
            return obj.tolist()

        # Conversion for lists and tuples
        if hasattr(obj, '__getitem__'):
            convert_to = list if isinstance(obj, (list, tuple)) else dict
            try:
                return convert_to(obj)
            except Exception:
                raise

        if hasattr(obj, '__iter__'):
            return tuple(item for item in obj)

        return super().default(obj)