import pandas as pd
from dataclasses import dataclass
from pathlib import Path

@dataclass
class InlineDiff:
    owner: str
    project: str
    version: str
    fpath: str
    sline: int
    scol: int
    eline: int
    ecol: int
    label: str
    pair_hash: str

    def is_null(self):
        return pd.isnull(self.sline) and pd.isnull(self.scol) and pd.isnull(self.eline) and pd.isnull(self.ecol)

    def is_same(self, other):
        return self.owner == other.owner and self.project == other.project and self.version == other.version and \
               self.fpath == other.fpath and self.label == other.label

    def inbounds(self, other):
        if self.sline > other.eline:
            return False

        if other.sline > self.eline:
            return False

        if self.sline == other.sline:
            if self.eline == other.eline:
                return self.scol >= other.scol and self.ecol <= other.ecol
            if self.eline < other.eline:
                return self.scol >= other.scol

        if self.sline > other.sline:
            if self.eline < other.eline:
                return True
            if self.eline == other.eline:
                return self.ecol <= other.ecol

        return False

    def to_dict(self, **kwargs):
        il_dict = {'owner': self.owner, 'version': self.version, 'project': self.project, 'fpath': self.fpath,
                   'sline': self.sline, 'scol': self.scol, 'eline': self.eline, 'ecol': self.ecol, 'label': self.label,
                   'pair_hash': self.pair_hash}

        if kwargs:
            il_dict.update(kwargs)

        return il_dict

    def to_list(self):
        return [self.owner, self.project, self.version, self.fpath, self.sline, self.scol, self.eline, self.ecol,
                self.label, self.pair_hash]

    def __str__(self):
        return f"{self.owner},{self.project},{self.version},{self.fpath},{self.sline},{self.scol},{self.eline}," \
               f"{self.ecol},{self.label},{self.pair_hash}"

@dataclass
class FunctionBoundary(InlineDiff):
    ftype: str = None
    label: str = ''
    pair_hash: str = ''

    @staticmethod
    def parse_fn_inline_diffs(fn_boundaries: dict, owner: str, project: str, version: str, fpath: str):
        def get_fn_bound(fn_bound_str: str, ftype: str):
            sline, scol, eline, ecol = fn_bound_str.split(",")
            return FunctionBoundary(sline=int(sline), scol=int(scol), eline=int(eline), ecol=int(ecol), ftype=ftype,
                                    owner=owner, project=project, version=version, fpath=fpath)

        fn_decs = [get_fn_bound(fn_dec, 'fnDec') for fn_dec in fn_boundaries['fnDec']] if 'fnDec' in fn_boundaries else []
        fn_exps = [get_fn_bound(fn_exp, 'fnExp') for fn_exp in fn_boundaries['fnExps']] if 'fnExps' in fn_boundaries else []

        return fn_decs, fn_exps

    def to_list(self):
        return super().to_list() + [self.ftype]

    def is_contained(self, other):
        start_ok = (self.sline < other.sline) or (self.sline == other.sline and self.scol <= other.scol)
        end_ok = (self.eline > other.eline) or (self.eline == other.eline and self.ecol >= other.ecol)

        return start_ok and end_ok

    def __str__(self):
        return super().__str__() + ',' + self.ftype

@dataclass
class DiffBlock:
    start: int
    a_path: str
    b_path: str

    def to_dict(self):
        return {"start": self.start, "a_path": self.a_path, "b_path": self.b_path}

@dataclass
class Entry:
    project: str
    owner: str
    a_version: str
    b_version: str
    diff_block: DiffBlock
    label: str
    a_file_size: int = None
    b_file_size: int = None

    @property
    def full_a_path(self):
        return Path(self.owner, self.project, self.a_version, self.diff_block.a_path)

    @property
    def full_b_path(self):
        return Path(self.owner, self.project, self.b_version, self.diff_block.b_path)

    def to_dict(self):
        diff_block_dict = self.diff_block.to_dict()
        diff_block_dict.update({"owner": self.owner, "project": self.project, "a_version": self.a_version,
                                "b_version": self.b_version, "label": self.label, 'a_file_size': self.a_file_size,
                                'b_file_size': self.b_file_size})

        return diff_block_dict

    def __str__(self):
        return f"{self.owner},{self.project},{self.a_version},{self.b_version},{self.diff_block.start}," \
               f"{self.diff_block.a_path},{self.diff_block.b_path},{self.a_file_size},{self.b_file_size},{self.label}"


from __future__ import annotations
import copy
import re
from schemy import Schema
from datetime import date
from datetime import datetime

class Dataset(object):

    def __init__(self
        , schema:Schema=None
        , date_out_format='yyyy-MM-dd hh:mm:ss'):
        """
        """
        self.__set_schema(schema)
        self._data = []
        self._idx = 0
        self._date_out_format = date_out_format

    def __iter__(self):
        return self.rewind()

    def __next__(self):
        return self.next()

    def __set_schema(self
        , schema:Schema=None):
        """
        Private set method to schema.
        """
        if not schema:
            schema = Schema()
        self._schema = schema

    def __str__(self)->str:
        string = self.to_str(limit=10)
        if self.len()>10:
            string += '...\n'
        if not self.is_empty():
            string += '\n' + str(self.len()) + ' registros.'
        return string

    def load(drive:str, **kwargs:dict):
        pass

    def save(drive:str, **kwargs:dict):
        pass

    def get_fields_size(self, rate:float=0.0)->dict:
        """
        """
        field_list = self._schema.get_all_field_pos()
        sizes = dict(zip(field_list.keys(), [0]*len(field_list)))
        #print(sizes)
        for row in self._data:
            _row = self._parse_row(row)
            for f, p in field_list.items():
                p = p - 1 # a posicao dos campos comecao com 0, nao 1
                s = len(str(_row[p]))
                if sizes[f]<s:
                    sizes[f] = s
        if rate>0:
            for f, s in sizes.items():
                sizes[f] = int(s + (s*rate))
        return sizes

    def columns(self):
        return self._schema.get_names()

    def to_str(self, length:int=None, limit:int=None)->str:
        """
        length: length of each column
        """
        fields = self._schema.get_names()
        if not fields:
            return '| * No fields * |'

        field_size = self.get_fields_size()

        width = []
        for fname in fields:
            name_width = len(fname)
            val_width = field_size[fname]
            if length and val_width>name_width:
                val_width = 4 if length<4 else length
            width.append(val_width if val_width>name_width else name_width)
        #
        r = '| ' + ' | '.join([name.ljust(width[j], ' ')[:width[j]] for j, name in enumerate(fields)]) + ' |\n'
        for i, row in enumerate(self._data):
            _row = self._parse_row(row)
            if limit and i>=limit:
                break
            r += '| ' + ' | '.join([str(val).ljust(width[j], ' ')[:width[j]] for j, val in enumerate(_row)]) + ' |\n'
        return r

    def get_schema(self):
        """
        Pega o objeto de schema.
        """
        return self._schema

    def _insert_list(self, row:list, idx:int=None):
        """
        """
        if len(row)!=len(self._schema.get_names()):
            # print((len(row), len(self._schema.get_names()), row))
            raise Exception("Número de colunas a inserir difere do número de colunas do schema definido.")
        if not idx:
            self._data.append(copy.copy(row))
        else:
            self._data[idx] = copy.copy(row)

    def _insert(self, row, idx:int=None)->Dataset:
        """
        Insere dados no dataset.
        """
        if type(row) is dict:
            nrow = [None]*len(self._schema.get_names())
            for k, v in row.items():
                pos = self._schema.get_field_pos(k)
                if not pos:
                    raise Exception("O campo '%s' onde se está tentando inserir não existe." % k)
                pos = pos - 1
                nrow[pos] = v
            row = nrow
            self._insert(row, idx)
        elif type(row) is list:
            self._insert_list(row)
            """
            if len(row)!=len(self._schema.get_names()):
                print((len(row), len(self._schema.get_names()), row))
                raise Exception("Número de colunas a inserir difere do número de colunas do schema definido.")
            if not idx:
                self._data.append(copy.copy(row))
            else:
                self._data[idx] = copy.copy(row)
            """
        elif type(row) is tuple:
            self._insert(list(row), idx)
        else:
            # print(type(row))
            raise Exception("Tipo não reconhecido.")
        return self

    def insert(self, row)->Dataset:
        """
        Insere dados no dataset.
        """
        return self._insert(row)

    def update(self, row, idx:int)->Dataset:
        """
        Atualiza uma linha no dataset.
        """
        return self._insert(row, idx)

    def delete(self, idx)->Dataset:
        """
        Deleta uma determinada posicao.
        """
        del self._data[idx]
        return self

    def current_update(self, row)->Dataset:
        """
        Atualiza a linha na posicao do
        cursor atual do dataset.
        """
        return self._insert(row, self._idx)

    def current_delete(self)->Dataset:
        """
        Deleta a linha onde o cursor estah
        """
        del self._data[self._idx]
        return self

    def current_insert(self, row)->Dataset:
        """
        Insere dados no dataset.
        """
        return self.update(row, self._idx)

    def get_index(self):
        """
        Pega a posicao atual do indice.
        """
        return self._idx

    def rownumber(self):
        """
        Pega a posicao atual do indice.
        """
        return self._idx

    def add_field(self
        , name:str
        , ftype=str
        , size:int=50
        , default=None
        , primary_key:bool=False
        , auto_increment:int=0
        , col_ref:int=None
        , pos='a'
        , out_format:str=None
        , optional:bool=True):
        self._schema.add_field(name=name
            , ftype=ftype
            , size=size
            , default=default
            , primary_key=primary_key
            , auto_increment=auto_increment
            , col_ref=col_ref
            , pos=pos
            , optional=optional
            , out_format=out_format)
        pos = self._schema.get_field_pos(name)
        if not pos:
            raise Exception("Error creating new field '{}'.".format(name))
        pos = pos - 1
        for _, row in enumerate(self._data):
            row[pos:pos] = [None] # [default]
        return self

    def remove_col(self, col):
        pos = self._schema.get_field_pos(col)
        if pos:
            self._schema.rm_field(pos)
            pos = pos - 1
            for row in self._data:
                del row[pos]
        return self

    def copy(self, copy_data=True)->Dataset:
        """
        Faz uma copia do dataset. Usa-se
        para fazer transformações sem
        destruir o original.
        """
        cp = Dataset(copy.deepcopy(self._schema))
        cp._date_out_format = self._date_out_format
        if copy_data:
            cp._data = copy.deepcopy(self._data)
        return cp

    def cut(self, start:int=0, end:int=None)->Dataset:
        """
        Faz um corte no dataset retornando
        um intevalo selecionando
        """
        if end is None:
            end = len(self._data)
        self._data = self._data[start:end]
        return self

    def is_empty(self)->bool:
        """
        Diz se o dataset estah vazio.
        """
        return len(self._data)==0

    def count(self)->int:
        return self.len()

    def len(self)->int:
        """
        Quantidade de linhas do Dataset
        """
        return len(self._data)

    def rewind(self)->Dataset:
        """
        """
        self._idx = 0
        return self

    def first(self)->Dataset:
        """
        """
        self.rewind()
        return self.current()

    def current(self):
        """
        """
        if self._idx<0:
            return None
        try:
            return self._parse_row(self._data[self._idx])
        except:
            raise StopIteration

    def next(self):
        """
        """

        if self._idx>=len(self._data):
            raise StopIteration
        row = self._data[self._idx]
        self._idx += 1
        return row

        v = self.current()
        self._idx += 1
        return v

    def prev(self):
        """
        """
        self._idx = self._idx - 1
        return self.current()

    def last(self):
        """
        """
        self._idx = self.len() - 1
        return self.current()

    def truncate(self)->Dataset:
        """
        Limpa a base de dados.
        """
        self.rewind()
        self._data = []
        return self

    def readrow(self, idx:int):
        """
        """
        row = self._data[idx]
        return self._parse_row(row)

    def __date_out_format_convert(self, date_out_format:str):
        """
        The regular dataformat (SQL data format) is
        not the same of datetime object in Python.
        This method is to convert the SQL format to
        Python format, so it can be used to convert
        datatime objects value to string.
        @see _parse_row()
        """
        date_out_format = date_out_format.replace('yyyy', '%Y').\
            replace('MM', '%m').\
            replace('dd', '%d').\
            replace('hh', '%H').\
            replace('mm', '%M').\
            replace('ss', '%S')
        return date_out_format

    def _parse_row(self, row:list):
        """
        Method to out lines parsing None values
        and casting other types to string.
        """
        parsed_row = []
        for i, col in enumerate(row):

            ftype = self._schema._schema[i]._f['ftype']
            default = self._schema._schema[i]._f['default']
            out_format = self._schema._schema[i]._f['out_format']

            # if value is null use default value
            col = default if col is None else col

            # se tiver algum valor
            if col is not None:
                # se for do tipo datetime
                if ftype in [datetime, date]:
                    out_format = self._date_out_format if out_format is None else out_format
                    col = col.strftime(self.__date_out_format_convert(out_format))
            parsed_row.append(col)
        return parsed_row

    def where(self, filter):
        filter_result = self.filter(filter)
        data = [v for i, v in enumerate(self._data) if filter_result[i]]
        #new_dataset = copy.copy(self)
        #new_dataset._data = data
        self._data = data
        # return new_dataset
        return self

    def all(self):
        """
        Get all data. Parsed. Without any filter or order.
        """
        all_data = []
        for row in self._data:
            all_data.append(self._parse_row(row))
        return all_data

    def filter(self, filter)->list:
        """
        equal usa-se um dicionário: {'[campo]':2}
        diff usa-se um dicionário: {'[campo]diff':2}
        in o valor deve ser um array: {'campo':['Valor1', 'Teste']}
        and deve-se se usar uma lista: [{}, {}] ou um dicionario com várias posicoes  {'campo':2, 'campo2':'Valor2'}
        or deve-se usar uma tupla: ({}, {})
        """
        def parse_name(name):
            m = re.findall(r'\[([a-zA-Z0-9\_]+)\]([a-zA-Z]*)', name)
            if m:
                return m[0]
        # por padrao considera tudo
        filter_result = [True]*len(self._data)
        fpos = self._schema.get_all_field_pos()
        for i, row in enumerate(self._data):
            row = self._parse_row(row)
            if type(filter) is dict:
                for k, v in filter.items():
                    mod = ''
                    # se a chave for string
                    if type(k) is str:
                        parsed = parse_name(k)
                        if parsed:
                            k = parsed[0]
                            mod = parsed[1].lower()
                        if k not in fpos:
                            raise Exception("The field '{}' used in the filter does not exist in the schema.".format(k))
                        k = fpos[k]-1
                    if not mod:
                        mod = 'equal'
                    if (mod=='equal' and row[k]!=v)\
                        or (mod=='diff' and row[k]==v)\
                        or (mod=='like' and v not in row[k])\
                        or (mod=='notlike' and v in row[k]):
                        filter_result[i] = False
                        continue
        return filter_result


"""
729. 我的日程安排表 I
实现一个 MyCalendar 类来存放你的日程安排。如果要添加的日程安排不会造成 重复预订 ，则可以存储这个新的日程安排。
当两个日程安排有一些时间上的交叉时（例如两个日程安排都在同一时间内），就会产生 重复预订 。
日程可以用一对整数 start 和 end 表示，这里的时间是半开区间，即 [start, end), 实数 x 的范围为，  start <= x < end 。
实现 MyCalendar 类：
MyCalendar() 初始化日历对象。
boolean book(int start, int end) 如果可以将日程安排成功添加到日历中而不会导致重复预订，返回 true 。
否则，返回 false 并且不要将该日程安排添加到日历中。
"""
import sortedcontainers

class MyCalendar:

    def __init__(self):
        self.queue = sortedcontainers.SortedDict()

    def book(self, start: int, end: int) -> bool:
        index = self.queue.bisect_left(end)
        if index == 0 or self.queue.items()[index - 1][1] <= start:
            self.queue[start] = end
            return True
        return False


import pygame
import time

from SweepLine import *
from Polygon import *

pygame.init()
pygame.font.init()
myfont = pygame.font.SysFont('Comic Sans MS', 10)
width = 800
height = 600

screen = pygame.display.set_mode((width, height), pygame.RESIZABLE)
clock = pygame.time.Clock()

red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
white = (255, 255, 255)
black = (0, 0, 0)
brown = (160, 58, 0)
purple = (80, 0, 160)

xPositionRect = 20
yPositionRect = 20
running = True
flightList = []

inputListPoly = []
xCoordinate = input("Enter starting point of segment: x")
yCoordinate = input("Enter starting point of segment: y")
xCoordinateEnd = input("Enter ending point of segment: x")
yCoordinateEnd = input("Enter ending point of segment: y")
while xCoordinate.isnumeric() and yCoordinate.isnumeric() and xCoordinateEnd.isnumeric() and yCoordinateEnd.isnumeric():
    try:
        x1 = float(xCoordinate)
        y1 = float(yCoordinate)
        x2 = float(xCoordinateEnd)
        y2 = float(yCoordinateEnd)
        inputListPoly.append(Segment(Point(x1, y1), Point(x2, y2)))
        xCoordinate = input("Enter starting point of segment: x")
        yCoordinate = input("Enter starting point of segment: y")
        xCoordinateEnd = input("Enter ending point of segment: x")
        yCoordinateEnd = input("Enter ending point of segment: y")
    except ValueError:
        print("Input error")

lowerLimit = int(input("Enter lower limit of airspace"))
upperLimit = int(input("Enter upper limit of airspace"))

lowerVelocity = int(input("Enter lower speed limit"))
upperVelocity = int(input("Enter upper speed limit"))

closeRange = int(input("Enter close range"))

poly = Polygon(inputListPoly, lowerLimit, upperLimit)
"""
50
50
500
50
500
50
300
200
300
200
300
400
300
400
600
550
600
550
150
550
150
550
50
50

100
500
1
5
40
"""
startTime = time.time()
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    screen.fill(white)

    intersections = []
    currentTime = time.time()
    if currentTime - startTime >= 1:
        flightType = random.randint(1, 3)
        if flightType == 3:
            newFlight = Flight.generateFlight(poly, lowerVelocity, upperVelocity, "external", closeRange)
        elif flightType == 2:
            newFlight = Flight.generateFlight(poly, lowerVelocity, upperVelocity, "internal", closeRange)
        else:
            newFlight = Flight.generateFlight(poly, lowerVelocity, upperVelocity, "half-internal", closeRange)
        flightList.append(newFlight)
        startTime = currentTime

    for flight in flightList:
        if poly.isInPoly(flight.currentPosition):
            flight.outsidePoly = False
        else:
            flight.outsidePoly = True

    intersections = getIntersections(flightList)

    poly.draw(screen)
    Flight.draw(flightList, pygame, screen, intersections, myfont)

    clock.tick(10)
    pygame.display.update()
pygame.quit()


from unittest import TestCase
import logging
import mock
from twitter_monitor.basic_stream import PrintingListener

try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

import sys, os
import json
import time

logger = logging.getLogger("twitter_monitor")

class TestPrintingListener(TestCase):
    def setUp(self):
        logger.manager.disable = logging.CRITICAL
        self.out = StringIO()
        self.example_status = {"key": "value"}
        self.listener = PrintingListener(out=self.out)

    def test_defaults_to_stdout(self):
        listener = PrintingListener()
        self.assertEqual(listener.out, sys.stdout)

    def test_output_is_configurable(self):
        self.assertEqual(self.listener.out, self.out)

    def test_prints_on_status(self):
        """Tweet json should be printed"""

        self.listener.on_status(self.example_status)

        output = self.out.getvalue().strip()
        self.assertEqual(output, json.dumps(self.example_status))

    def test_prints_newlines_between_tweets(self):
        """There must be newlines between tweets"""

        num_tweets = 4
        tweet_json_text = json.dumps(self.example_status)
        expected_output = ""

        for i in range(num_tweets):
            self.listener.on_status(self.example_status)
            expected_output += tweet_json_text + os.linesep

        expected_output = expected_output.strip()
        output = self.out.getvalue().strip()
        self.assertEqual(output, expected_output)

    def test_counts_received_tweets(self):
        self.assertEqual(self.listener.received, 0)

        self.listener.on_status(self.example_status)
        self.assertEqual(self.listener.received, 1)

        self.listener.on_status(self.example_status)
        self.assertEqual(self.listener.received, 2)

    def test_allows_termination(self):
        # It should start out saying to continue
        go_on = self.listener.on_status(self.example_status)
        self.assertTrue(go_on)

        self.listener.set_terminate()

        # Now it should indicate to stop
        go_on = self.listener.on_status(self.example_status)
        self.assertFalse(go_on)

    @mock.patch('twitter_monitor.basic_stream.logger')
    def test_logs_statistics(self, logger):
        # Wait briefly post-creation
        time.sleep(0.1)

        self.listener.print_status()
        self.assertTrue(logger.info.called)

    def test_resets_received_after_stats(self):
        self.listener.received = 1
        self.listener.print_status()
        self.assertEqual(self.listener.received, 0)


import os
import time
import datetime

# Función para limpiar la pantalla
def limpiar_pantalla():
    if os.name == 'nt':  # Para sistemas Windows
        os.system('cls')  # Comando para borrar pantalla

# Función de mostrar mensaje con animación
def mostrar_mensaje(texto):
    for letra in texto:
        print(letra, end='', flush=True)
        time.sleep(0.01)
    print()

# Función para preguntar la materia a estudiar
def materia_preguntar():
    while True:
        materia = input("¿Qué materia tienes que estudiar? ")
        if not materia.isnumeric(): #Comprobrar que este escrito en letra
            return materia
        else:
            mostrar_mensaje("¡ERROR!")
            mostrar_mensaje("¡DEBES ESCRIBIR EL TEXTO EN LETRAS!")

# Función para preguntar en qué día hay que estudiar la materia
def dias_estudio(materia):
    while True:
        estudiar_materia = input("¿En qué día tienes que estudiar para " + str(materia) + "? (YYYY-MM-DD) ")
        try:
            fecha_estudio = datetime.datetime.strptime(estudiar_materia, "%Y-%m-%d") #Para que escriba el año, mes y dia (Podes cambiarlo si quieres)
            return fecha_estudio
        except ValueError: #Para que cuando te tire error si digitaste mal no aparezca cualquier error y aparezca lo que vos queres
            print("Error: Formato de fecha incorrecto. Introduce la fecha en el formato solicitado (YYYY-MM-DD).".upper())

# Función para saber en qué día quieres estudiar
def dias_querer_estudiar(materia):
    while True:
        querer_estudiar = input("¿En qué día quieres estudiar para " + str(materia) + "? (YYYY-MM-DD) ")
        try:
            fecha_estudio = datetime.datetime.strptime(querer_estudiar, "%Y-%m-%d")
            return fecha_estudio
        except ValueError:  #Para que cuando te tire error si digitaste mal no aparezca cualquier error y aparezca lo que vos queres
            print("Error: Formato de fecha incorrecto. Introduce la fecha en el formato solicitado (YYYY-MM-DD).".upper())

#Función para restar días
def dias_restantes(estudiar_materia,querer_estudiar):
    dias_restar=(estudiar_materia-querer_estudiar).days #Para que no aparezca hora ni nada
    if dias_restar>=0:
        mostrar_mensaje("Faltan " + str(dias_restar) + " dias para el examen.")
        return dias_restar
    else:
        mostrar_mensaje("¡ERROR DE PROGRAMA")
        mostrar_mensaje("IMPOSIBLE CALCULAR DIAS NEGATIVOS. ¡INTENTE NUEVAMENTE!")
        exit()#cerrar programa
#Funcion para calcular un porcentaje de aprobacion o no
def calcular_porcentaje_estudio(dias_restar):
    if dias_restar < 1: #porcentaje si te queda menos de un dia de estudio
        porcentaje = 2.5
        mostrar_mensaje("¡Reza para que te vaya bien!")
        mostrar_mensaje("Recomendación: Tuviste que haberte puesto a estudiar unos dias antes.")
    elif dias_restar < 2:
        porcentaje = 14.7
        mostrar_mensaje("Tienes pocas posibilidad de aprobar :(")
        mostrar_mensaje("Recomendación: Dos dias no es suficiente para estudiar, así que estudia las proximas 24/7.")

    elif dias_restar < 3:
        porcentaje = 35.9
        mostrar_mensaje("Puede que te vaya bien")
        mostrar_mensaje("Recomendación: Repasa antes de arrancar la prueba.")

    elif dias_restar < 4:
        porcentaje = 67.3
        mostrar_mensaje("Sin dudas fuiste listo")
        mostrar_mensaje("Recomendación: Repasa todos los dias un rato y ya lo tendras.")
    elif dias_restar < 5:
        porcentaje = 75.9
        mostrar_mensaje("Tienes altas posibilidades de aprobar para el examen!")
        mostrar_mensaje("Recomendación: Tomatelo con calma, tienes 5 dias.")
    elif dias_restar < 6:
        porcentaje = 89.3
        mostrar_mensaje("Vas a aprobar, quedate tranqui")
        mostrar_mensaje("Recomendación: Tomate unos matesitos, ya la tenes.")
    elif dias_restar < 7:
        porcentaje = 95.4
        mostrar_mensaje("Minimo un 8 tenes que sacarle loquita")
        mostrar_mensaje("Recomendación: Ya la tene mi loco.")
    else:
        porcentaje = 100  # Porcentaje de estudio si quedan más de 7 dias para estudiar
        mostrar_mensaje("Si no aprobas, es porque sos tremendo salame")
        mostrar_mensaje("Recomendación: No te puedo recomendar nada, hace MUCHISIMOS dias que estas estudiando.")
    return porcentaje

# Función para preguntar si desea obtener información sobre otra materia
def preguntar_otra_materia():
    while True:
        opcion = input("¿Deseas obtener información sobre otra materia? (S/N): ")
        if opcion.upper() == 'S':
            return True
        elif opcion.upper() == 'N':
            mostrar_mensaje("¡Gracias por haber usado el programa!")
            mostrar_mensaje("¡Hasta luego!")
            return False
        else:
            mostrar_mensaje("Opción inválida. Por favor, ingresa 'S' para sí o 'N' para no.")

# Estructura del programa
def ejecutar_programa():
    while True:
        limpiar_pantalla()
        materia = materia_preguntar()
        fecha_estudio = dias_estudio(materia)
        fecha_querer_estudiar = dias_querer_estudiar(materia)
        dias_restantes_valor = dias_restantes(fecha_estudio, fecha_querer_estudiar)
        porcentaje_estudio = calcular_porcentaje_estudio(dias_restantes_valor)
        mostrar_mensaje("Posibilidad de aprobar el examen: " + str(porcentaje_estudio) + "%") #Muestra la posibilidad que tienes de aprobar el examen

        if not preguntar_otra_materia():
            break
# Ejecución del programa
ejecutar_programa()


#!/usr/bin/env python3

# this script checks for fonts

import pygame

# Initialize pygame
pygame.init()

# Get the available system fonts
fonts = pygame.font.get_fonts()

# Print the available fonts
for font in fonts:
    print(font)


import os

from .base import *  # noqa
from .base import env

# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = True
# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = env(
    "DJANGO_SECRET_KEY",
    default="ieKutp0u2v2LgCyPVIwZZDXKxu4EJDOpXp5aJrDf555MCpd5C7g65LLdFQqjWdW6",
)
# https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ["localhost", "0.0.0.0", "127.0.0.1", "*"]

# CACHES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#caches
CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
        "LOCATION": "",
    }
}

# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#email-host
EMAIL_HOST = env("EMAIL_HOST", default="mailhog")
# https://docs.djangoproject.com/en/dev/ref/settings/#email-port
EMAIL_PORT = 1025

# WhiteNoise
# ------------------------------------------------------------------------------
# http://whitenoise.evans.io/en/latest/django.html#using-whitenoise-in-development
INSTALLED_APPS = ["whitenoise.runserver_nostatic"] + INSTALLED_APPS  # noqa F405

# django-debug-toolbar
# ------------------------------------------------------------------------------
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#prerequisites
INSTALLED_APPS += ["debug_toolbar"]  # noqa F405
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#middleware
MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"]  # noqa F405
# https://django-debug-toolbar.readthedocs.io/en/latest/configuration.html#debug-toolbar-config
DEBUG_TOOLBAR_CONFIG = {
    "DISABLE_PANELS": ["debug_toolbar.panels.redirects.RedirectsPanel"],
    "SHOW_TEMPLATE_CONTEXT": True,
}
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#internal-ips
INTERNAL_IPS = ["127.0.0.1", "10.0.2.2"]
if env("USE_DOCKER") == "yes":
    import socket

    hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
    INTERNAL_IPS += [".".join(ip.split(".")[:-1] + ["1"]) for ip in ips]
    try:
        _, _, ips = socket.gethostbyname_ex("node")
        INTERNAL_IPS.extend(ips)
    except socket.gaierror:
        # The node container isn't started (yet?)
        pass

# django-extensions
# ------------------------------------------------------------------------------
# https://django-extensions.readthedocs.io/en/latest/installation_instructions.html#configuration
INSTALLED_APPS += ["django_extensions"]  # noqa F405
# Celery
# ------------------------------------------------------------------------------

# https://docs.celeryq.dev/en/stable/userguide/configuration.html#task-eager-propagates
CELERY_TASK_EAGER_PROPAGATES = True
# Pycharm resolve static
# ------------------------------------------------------------------------------
STATICFILES_DIRS += [  # noqa F405
    os.path.join(
        os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "one", "static"
    ),
    os.path.join(
        os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "one", "assets"
    ),
]

# Django Code Generator
# ------------------------------------------------------------------------------
INSTALLED_APPS += ["django_code_generator"]  # noqa F405

# Your stuff...
# ------------------------------------------------------------------------------


""" SESSION
between frontend and backend. """

# -*- coding: utf-8 -*-
# From Python 3
import json
# From Program
from backend.database.dbmanager import DbManager
from frontend.window import Window
from frontend.displayer import Displayer

class Session():
    def __init__(self):
        """ 'displayer'     (obj): instance of Displayer.
            'user_id'       (int): User id who use program. """

        # Instances
        self.displayer = None
        self.user_id = None
        self.gui_language = "en"

        self.dbmanager = DbManager()
        self.window = Window()
        self.displayer = Displayer(
            window=self.window,
            session=self
        )

        self.start_session()
        self.window.mainloop()

    def start_session(self):
        """ Start the new session. """

        if self.dbmanager.err == 0:
            self.displayer.display(
                f_view="user_welcome"
            )
        elif self.dbmanager.err >= 1:
            self.displayer.display(
                f_view="update_server_conn"
            )

    def get_script(
        self,
        file_name=None,
        package_name=None
    ):
        """ get the .json scripts.
            'language'  (str): 'fr' or 'en'.
            'view_name' (str): file name whitout '.py'. """

        if package_name is None:
            with open(
                "frontend/languages/{}/{}.json"
                .format(self.gui_language, file_name)
            ) as json_data:

                json_dict = json.load(json_data)
        else:
            with open(
                "frontend/languages/{}/{}/{}.json"
                .format(self.gui_language, package_name, file_name)
            ) as json_data:

                json_dict = json.load(json_data)

        return json_dict

    def off_requests(
        self,
        req_type=None,
        **kwargs
    ):
        """ Open Food Facts requests. """

        result = None

        for key, value in kwargs.items():

            if key == "language":
                language = value

        if self.dbmanager.err >= 1:
            self.dbmanager.start()

        if req_type == "categories":

            self.dbmanager.offmanager.get_categories(
                language=language
            )

            result = self.dbmanager.offmanager.categories

        return result

    def upload(
        self,
        language=None,
        categories=None
    ):
        """
        """

        count = 0
        for cat in categories:

            products = self.dbmanager.offmanager.get_products(
                    language=language, category=cat
                )

            self.dbmanager.db_category.create(
                category_name=cat,
                category_off_id=cat,
                category_products=0
            )

            for product in products:

                self.dbmanager.db_product.create(
                    product_name=product.get("product_name"),
                    product_url=product.get("product_url"),
                    product_creator=product.get("product_creator"),
                    product_stores=product.get("product_stores"),
                    product_nutriscore=product.get("product_nutriscore"),
                    product_image_url=product.get("product_image_url"),
                    product_kcal=product.get("product_kcal"),
                    product_kj=product.get("product_kj"),
                    product_category_id=count,
                    product_sugar=product.get("product_sugar"),
                    product_brands=product.get("product_brands")
                )

            count += 1


import os
import json
import docker
import pickle

from libTarget import TargetCfg
from apiusage.libProjAnalyzer import BaseAnalyzer

import cfgs

import logging
logger = logging.getLogger(__name__)

class ContainerAnalyzer(BaseAnalyzer):

	def __init__(self, cfg):
		super().__init__(cfg)
		if not os.path.exists(self.cfg.workdir):
			os.makedirs(self.cfg.workdir, exist_ok=True)
		self.docker = None

	def get_ana_results(self):
		with open(self.cfg.projanaresult, 'r') as f:
			return json.load(f)

	def analyze_wrap(self, params, debug=False):
		if self.cfg.language == 'c':
			TargetCfg.pickleTo(self.cfg, self.cfg.headerpickle)
			with open(self.cfg.headerparampickle, 'wb') as f:
				pickle.dump(params, f)
			#print('@@params are %s' % (str(params)))

			dockercmd = 'python3 /root/workspace/fuzzdrivergpt/apiusage/libProjAnalyzer.py %s %s' % (self.cfg.headerpickle, self.cfg.headerparampickle)
			if debug:
				logger.info(dockercmd)
				dockercmd = 'sleep 10h'

			imagename = self.cfg.imagename

			envs = [
				"PYTHONPATH=/root/workspace/fuzzdrivergpt",
			]

			dockervolumns = [
				'%s:%s' % (self.cfg.workdir, self.cfg.workdir),
				'%s:%s' % (self.cfg.cachedir, self.cfg.cachedir),
				'%s/libTarget.py:/root/workspace/fuzzdrivergpt/libTarget.py' % (cfgs.FDGPT_DIR),
				'%s/apiusage/__init__.py:/root/workspace/fuzzdrivergpt/apiusage/__init__.py' % (cfgs.FDGPT_DIR),
				'%s/apiusage/libProjAnalyzer.py:/root/workspace/fuzzdrivergpt/apiusage/libProjAnalyzer.py' % (cfgs.FDGPT_DIR),
				'%s/apiusage/libAPIDocManualCollector.py:/root/workspace/fuzzdrivergpt/apiusage/libAPIDocManualCollector.py' % (cfgs.FDGPT_DIR),
				'%s/cfgs.py:/root/workspace/fuzzdrivergpt/cfgs.py' % (cfgs.FDGPT_DIR),
			]

			dockervolumns.append("%s:/tmp/cc-func-parser-0.5-jar-with-dependencies.jar" % (cfgs.FDGPT_ANTLR))

			if os.path.exists(cfgs.FDGPT_JDK):
				dockervolumns.append("%s:/root/workspace/fuzzdrivergpt/jdk-19.0.2" % (cfgs.FDGPT_JDK))

			workdir = self.cfg.workdir
			#print('@@@ the working dir is %s' % (self.cfg.workdir))

			# run the docker
			client = docker.from_env()

			try:
				self.docker = client.containers.run(imagename, environment=envs, command=dockercmd, volumes=dockervolumns, working_dir=workdir, privileged=True, remove=False, detach=True)

			except Exception as ex:
				logger.error('meet exception when run docker %s' % (ex))
				raise ex

			if debug:
				logger.info('docker exec -it %s bash' % (self.docker.name))
				os._exit(0)

			self.docker.reload()
			rets = self.docker.wait()
			if rets['StatusCode'] != 0:
				logger.error('>> Container does not start as expected, check the logs inside the docker:\n\n%s\n' % (self.docker.logs().decode('utf-8', errors='ignore')))
				logger.error('>> Stack track outside container:')
				raise Exception('starting container meets error')

			self.docker.remove(force=True)

			logger.debug('analysis result file %s has been created' % (self.cfg.projanaresult))
		else:
			raise Exception('Unsupported language %s' % (self.cfg.language))


# 1. Задайте список, состоящий из произвольных чисел, количество задаёт пользователь.
# Напишите программу, которая найдёт сумму элементов списка, стоящих на нечётных позициях(не индексах).
# in
# 5

# out
# [10, 2, 3, 8, 9]
# 22

# in
# 4

# out
# [4, 2, 4, 9]
# 8

from random import randint

def creating_a_new_list():
    size = int(input("Input the size of the list: "))
    lst = []

    for i in range(size):
        lst.append(randint(0, 10))

    print(f"Random list is: {lst}")
    return lst

def sum_up_odd_numbers(random_list):

    sum_up = 0

    for pos in range(len(random_list)):
        if pos % 2 == 0:
            sum_up += random_list[pos]
        else: sum_up += 0
        print(pos + 1, random_list[pos], end = "\n")

    print(f"Asked sum is: {sum_up}")

my_list = creating_a_new_list()
sum_up_odd_numbers(my_list)


################################################################################
# Code from
# https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py
# Modified the original code so that it also loads images from the current
# directory as well as the subdirectories
################################################################################
import torch.utils.data as data

import glabtools.io as io

# def make_dataset(bucket_path, subslice, fnames):
#     """
#     Return list of paths in cottoncandy bucket.
#
#     bucket_path : str
#         The path to the directory that has the individual subject data. Path
#         should have fields to fill in, e.g. "/path/to/{subject}/"
#
#     subslice : list of tuples
#         List of (subject ID (str), slice number (int)) for every slice.
#
#     fnames : list
#         Names of files that should be extracted from each folder.
#     """
#     images = []
#
#     for sspair in subslice:
#         isub, islice = sspair
#         f_ims = []
#         if len(fnames) > 1: # quantitative images
#             for fname in fnames:
#                 path = bucket_path.format(subject=isub, fname=fname)
#                 f_ims.append(path)
#             f_ims.append(islice)
#         else:
#             f_ims.append(bucket_path.format(subject=isub, slice=str(islice), fname=fnames[0]))
#         images.append(f_ims)
#
#     return images

# def default_loader(path):
#     return Image.open(path).convert('RGB')

class MRFFolder(data.Dataset):

    def __init__(self, bucket, bucket_path, subslices, return_paths=False,
                 transform=None, dset='mrf'):
        """
        dset: a string, 'mrf' or 'quant', specifying which dataset is desired.
        """
        # imgs = make_dataset(bucket_path, subslice, fnames)
        if len(subslices) == 0:
            raise(RuntimeError("Found 0 images!!! AHHHHHH :0"))
        # self.imgs = imgs
        self.subslices = subslices
        self.transform = transform
        self.return_paths = return_paths
        self.bucket = bucket
        self.bucket_path = bucket_path
        self.dset = dset

        self.cci = io.get_cc_interface(self.bucket)

    def __getitem__(self, index):
        subject, nslice = self.subslices[index]

        if self.dset == 'mrf':
            path = self.bucket_path.format(subject=subject,
                                           slice=str(nslice),
                                           fname='mrf.npy')
        elif self.dset == 'quant':
            path = self.bucket_path.format(subject=subject,
                                           slice=str(nslice),
                                           fname='t1_t2_pd.npy')
        else:
            raise ValueError('Invalid value for parameter dset.')
        # print('Downloading: ' + str(path))
        dl_tries = 0
        while True:
            try:
                img = self.cci.download_npy_array(path)
                break
            except:
                dl_tries += 1
                if dl_tries > 10:
                    raise Exception('failed to download ' + str(path))
        return img

    def __len__(self):
        return len(self.subslices)


"""Tracker - physical particle tracker"""

# ------------------------------------
# tracker.py
# Part of the LADiM Model
#
# Bjørn Ådlandsvik, <bjorn@imr.no>
# Institute of Marine Research
#
# Licensed under the MIT license
# ------------------------------------
from __future__ import annotations

import logging
from typing import TYPE_CHECKING, Any

import numba  # type: ignore
import numpy as np

if TYPE_CHECKING:
    from ladim.forcing import BaseForce

ParticleArray = np.ndarray  # 1D array, one element per particle
Velocity = tuple[ParticleArray, ParticleArray]

PARALLEL = False
DEBUG = False

logger = logging.getLogger(__name__)
if DEBUG:
    logger.setLevel(logging.DEBUG)

class Tracker:
    """The physical particle tracking kernel"""

    def __init__(
        self,
        advection: str,  # EF, RK2, or RK4
        diffusion: float = 0.0,
        vertdiff: float = 0.0,
        vertical_advection: bool = False,
        *,
        modules: dict[str, Any]
        # modules: Optional[dict[str, Any]] = None,
    ) -> None:
        logger.info("Initiating the particle tracker")
        self.modules = modules
        self.dt = modules["time"].dt / np.timedelta64(1, "s")
        self.advection = advection  # Name of advection method
        logger.info("  Advection method: %s", advection)

        # advect <- requested advection method
        # advection = string "EF", "RK2", "RK4"
        # advect = the actual method
        if self.advection:
            self.advect = getattr(self, self.advection)

        self.vertical_advection = vertical_advection
        if vertical_advection:
            logger.info("  Vertical advection activated")

        self.diffusion = bool(diffusion)
        self.D = diffusion
        if self.diffusion:
            logger.info("  Horizontal diffusion: %s m²/s", diffusion)

        self.vertdiff = bool(vertdiff)
        self.Dz = vertdiff
        if self.vertdiff:
            logger.info("  Vertical diffusion: %s m²/s", vertdiff)

        self.rng = np.random.default_rng()

    def update(self) -> None:
        """Move the particles one time step"""

        state = self.modules["state"]
        grid = self.modules["grid"]
        force = self.modules["forcing"]

        X, Y, Z = state.X, state.Y, state.Z

        self.dx, self.dy = grid.metric(X, Y)

        self.xmin = grid.xmin + 0.01
        self.xmax = grid.xmax - 0.01
        self.ymin = grid.ymin + 0.01
        self.ymax = grid.ymax - 0.01

        U = np.zeros_like(X)
        V = np.zeros_like(Y)

        # --- Advection ---
        if self.advection:
            Uadv, Vadv = self.advect(X, Y, Z, force)
            U += Uadv
            V += Vadv

        # --- Diffusion ---
        if self.diffusion:
            Udiff, Vdiff = self.diffuse(num_particles=len(X))
            U += Udiff
            V += Vdiff

        # --- Move the particles

        # New position, if OK
        X1 = X + U * self.dt / self.dx
        Y1 = Y + V * self.dt / self.dy

        # Kill particles trying to move out of the grid
        out_of_grid = ~grid.ingrid(X1, Y1)
        state.alive[out_of_grid] = False
        state.active[out_of_grid] = False  # Not necessary if they are removed

        # Do not move inactive particles
        inactive = ~state.active
        X1[inactive] = X[inactive]
        Y1[inactive] = Y[inactive]

        # Land, boundary treatment. Do not move the particles onto land
        # Consider a sequence of different actions
        onland = ~grid.atsea(X1, Y1)
        X1[onland] = X[onland]
        Y1[onland] = Y[onland]

        # Update the particle positions
        state["X"] = X1
        state["Y"] = Y1

        # --- Vertical movement ---

        # Sample the depth level
        h = None
        if self.vertdiff or self.vertical_advection:
            # if hasattr(grid, "sample_depth") and callable(grid.sample_depth):
            #     h = grid.sample_depth(X, Y)
            # elif hasattr(grid, "depth") and callable(grid.depth):
            #     h = grid.depth(X, Y)
            h = grid.depth(X, Y)

            # Diffusion
            if self.vertdiff:
                W = self.diffuse_vert(num_particles=len(X))
                Z += W * self.dt

            # Advection
            if self.vertical_advection:
                W = force.variables["w"]
                Z += W * self.dt

            # Reflexive boundary conditions at surface
            Z[Z < 0] *= -1

            # Reflexive boundary conditions at bottom
            if h is not None:
                below_seabed = Z > h
                Z[below_seabed] = 2 * h[below_seabed] - Z[below_seabed]

            # Update particle positions
            state["Z"] = Z

    def EF(
        self, X: ParticleArray, Y: ParticleArray, Z: ParticleArray, force: BaseForce
    ) -> Velocity:
        """Euler-Forward advective velocity"""

        U, V = force.velocity(X, Y, Z)

        return U, V

    def RK2(
        self, X: ParticleArray, Y: ParticleArray, Z: ParticleArray, force: BaseForce
    ) -> Velocity:
        """Runge-Kutta second order = Heun scheme

        This version does not sample velocities outside the grid
        """

        dt = self.dt
        dtdx = dt / self.dx
        dtdy = dt / self.dy

        U, V = force.velocity(X, Y, Z)
        X1, Y1 = RKstep(X, Y, U, V, 0.5, dtdx, dtdy)
        clip(X, Y, self.xmin, self.xmax, self.ymin, self.ymax)

        return force.velocity(X1, Y1, Z, fractional_step=0.5)

    def RK4(
        self, X: ParticleArray, Y: ParticleArray, Z: ParticleArray, force: BaseForce
    ) -> Velocity:
        """Runge-Kutta fourth order advection

        This version does not sample velocities outside the grid

        """

        dt = self.dt
        dtdx = dt / self.dx
        dtdy = dt / self.dy
        xmin, xmax, ymin, ymax = self.xmin, self.xmax, self.ymin, self.ymax

        U1, V1 = force.velocity(X, Y, Z, fractional_step=0.0)
        X1, Y1 = RKstep(X, Y, U1, V1, 0.5, dtdx, dtdy)
        clip(X1, Y1, xmin, xmax, ymin, ymax)

        U2, V2 = force.velocity(X1, Y1, Z, fractional_step=0.5)
        X2, Y2 = RKstep(X, Y, U2, V2, 0.5, dtdx, dtdy)
        clip(X2, Y2, xmin, xmax, ymin, ymax)

        U3, V3 = force.velocity(X2, Y2, Z, fractional_step=0.5)
        X3, Y3 = RKstep(X, Y, U3, V3, 1.0, dtdx, dtdy)
        clip(X3, Y3, xmin, xmax, ymin, ymax)

        U4, V4 = force.velocity(X3, Y3, Z, fractional_step=1.0)

        return RK4avg(U1, U2, U3, U4), RK4avg(V1, V2, V3, V4)

    def diffuse(self, num_particles: int) -> Velocity:
        """Random walk diffusion"""

        # Diffusive velocity
        stddev = (2 * self.D / self.dt) ** 0.5
        U = stddev * self.rng.normal(size=num_particles)
        V = stddev * self.rng.normal(size=num_particles)

        return U, V

    def diffuse_vert(self, num_particles: int) -> ParticleArray:
        """Random walk diffusion"""

        # Diffusive velocity
        stddev = (2 * self.Dz / self.dt) ** 0.5
        W: ParticleArray = stddev * self.rng.normal(size=num_particles)
        return W

@numba.njit(parallel=PARALLEL)
def RKstep0(
    X: ParticleArray,
    Y: ParticleArray,
    U: ParticleArray,
    V: ParticleArray,
    frac: float,
    dtdx: ParticleArray,
    dtdy: ParticleArray,
) -> tuple[ParticleArray, ParticleArray]:
    Xp = X + frac * U * dtdx
    Yp = Y + frac * V * dtdy
    return Xp, Yp

@numba.njit(parallel=False)
def RKstep1(
    X: ParticleArray,
    Y: ParticleArray,
    U: ParticleArray,
    V: ParticleArray,
    frac: float,
    dtdx: ParticleArray,
    dtdy: ParticleArray,
) -> Velocity:
    """Do a forward Runge-Kutta (partial) step"""

    N = len(X)
    Xp = np.empty(N)
    Yp = np.empty(N)
    for i in numba.prange(N):
        Xp[i] = X[i] + frac * U[i] * dtdx[i]
        Yp[i] = Y[i] + frac * V[i] * dtdy[i]
    return X, Y

RKstep = RKstep1

@numba.njit(parallel=PARALLEL)
def clip(
    X: ParticleArray,
    Y: ParticleArray,
    xmin: float,
    xmax: float,
    ymin: float,
    ymax: float,
) -> None:
    """Clip particle positions in place towards forcing domain boundary"""
    for p in numba.prange(len(X)):
        X[p] = max(min(X[p], xmax), xmin)
        Y[p] = max(min(Y[p], ymax), ymin)

@numba.njit(parallel=PARALLEL)
def RK4avg(
    U1: ParticleArray, U2: ParticleArray, U3: ParticleArray, U4: ParticleArray
) -> ParticleArray:
    """Average velocity component for Runge-Kutta 4-th order"""
    return (U1 + 2 * U2 + 2 * U3 + U4) / 6.0


from sys import argv

script,filename = argv

print("file name is %r." % filename)

print("Opening the file...")
target = open(filename, 'w+')

print("truncating this file...")
target.truncate()

buf = input("write the words:\n")

target.write(buf)

target.seek(0, 0)
words = target.read()
print("the words in %r is:\n" % filename)
print(words)

target.close()
print("%r is closed\n" % filename)


#!/usr/bin/env python3

import os
import subprocess as sb
import re
import socket

def find_posix_active_connections():

    result = str(sb.check_output('netstat -natp', shell=True))
    ip_addresses = re.findall("[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{1,3}", result)

    return ip_addresses

def system_connections():

    if os.name == 'posix':
        return find_posix_active_connections()
    else:
        return find_ntos_active_connections()

def main():

    ip_addresses = system_connections()
    for ip in ip_addresses:
        addr, port = ip.split(':')
        print('[+] IP: {} Connected To PORT: {}'.format(addr, port))

    acon = []
'''
    # code to check active connections
    for ip in ip_addresses:
        addr, port = ip.split(':')

        try:
            acon.append(socket.create_connection((addr, port), timeout=1))
        except OSError:
            pass
    print(acon)
'''

if __name__ == '__main__':
    main()


from datasets import load_searches_v2
from classifier_searches import fit_and_predict, calculate_base_score
import numpy as np

from sklearn.naive_bayes import MultinomialNB
from sklearn.ensemble import AdaBoostClassifier

X, Y = load_searches_v2()

X_train, X_validate, X_test = np.split(X, [int(.8*len(X)), int(.9*len(X))])
y_train, y_validate, y_test = np.split(Y, [int(.8*len(Y)), int(.9*len(Y))])

model_MultinomialNB = MultinomialNB()
resultado_MultinomialNB = fit_and_predict('MultinomialNB', model_MultinomialNB, X_train, X_test, y_train, y_test)

model_AdaBoostClassifier = AdaBoostClassifier()
resultado_AdaBoostClassifier = fit_and_predict('AdaBoostClassifier', model_AdaBoostClassifier, X_train, X_test, y_train, y_test)

if resultado_MultinomialNB > resultado_AdaBoostClassifier:
    vencedor = model_MultinomialNB
else:
    vencedor = model_AdaBoostClassifier

resultado = vencedor.predict(X_validate)
acertos = (resultado == y_validate)

total_de_acertos = sum(acertos)
total_de_elementos = len(X_validate)
taxa_de_acerto = 100.0 * total_de_acertos/total_de_elementos

print(f'score in real world of winner algorithm (validation data): {round(taxa_de_acerto,2)}%')
print(f'base score: {calculate_base_score(y_validate)}%')
print(f'number of validations: {len(X_validate)}')


#!/usr/bin/env python3

""" Graded Lab #4 for Inf1340, Fall 2015

    This program computes federal and provincial sales tax.
    Assume that the provincial sales tax is 5 percent and
    the federal sales tax is 2.5 percent. It displays the
    amount of the purchase, the provincial sales tax, the
    federal sales tax, the total tax, and the total of the
    sale.
"""

__author__ = 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2015 Susan Sim"
__license__ = "MIT License"

# Rewrite this code to use global constants, local variables and functions
# Output the text to a file instead of printing it

TAX_PR=.05
TAX_FED=.025
def calc_total_tax():
    tax_total=TAX_PR+TAX_FED
    return(tax_total)

def bill_of_sale(purchase):
    val = ("Amount of purchase: {0:.2f}".format(purchase))+"\n"+("Provincial tax: {0:.2f}".format(purchase * .05))+"\n"+("Federal tax: {0:.2f}".format(purchase * .025))+"\n"+("Total tax: {0:.2f}".format(purchase *tax_amount))+"\n"+("Total sale: {0:.2f}".format(purchase * 1.075))
    return(val)
tax_amount=calc_total_tax()
ob = open("out_mib.txt","w+")
ob.write(bill_of_sale(100));
ob.close()


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

"""
intuition:
we maintain a carry var just like we do in manual addition

% --> gives us the digit to be put in the place
// --> gives us the carry for next digit addition

add remaining digits from l1 or l2 and carry

implementation:
comments shown below

analysis:
we go through each node in both lists so time complexity is
T = O(n + m)

only a few pointers and a var so space complexity is
S = O(k)

"""

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:

        curr_l1 = l1
        curr_l2 = l2
        carry = 0

        dummy = ListNode()
        curr = dummy

        while curr_l1 is not None and curr_l2 is not None:

            curr_sum = (curr_l1.val + curr_l2.val + carry) % 10
            carry = (curr_l1.val + curr_l2.val + carry) // 10
            curr.next = ListNode(curr_sum)
            curr = curr.next

            curr_l1 = curr_l1.next
            curr_l2 = curr_l2.next

        # add any remaining numbers left in l1 and carry if > 0
        while curr_l1 is not None:
            curr_sum = (curr_l1.val + carry) % 10
            carry = (curr_l1.val + carry) // 10
            curr.next = ListNode(curr_sum)
            curr = curr.next
            curr_l1 = curr_l1.next

        # add any remaining numbers left in l2 and carry if > 0
        while curr_l2 is not None:
            curr_sum = (curr_l2.val + carry) % 10
            carry = (curr_l2.val + carry) // 10
            curr.next = ListNode(curr_sum)
            curr = curr.next
            curr_l2 = curr_l2.next

        # any remaining carry must be added as a digit as well
        if carry:
            curr.next = ListNode(carry)

        return dummy.next


# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

from mach.decorators import Command, CommandArgument
from mach.test.providers import throw2

@Command("throw", category="testing")
@CommandArgument("--message", "-m", default="General Error")
def throw(command_context, message):
    raise Exception(message)

@Command("throw_deep", category="testing")
@CommandArgument("--message", "-m", default="General Error")
def throw_deep(command_context, message):
    throw2.throw_deep(message)


num = ["-8", "1", "5", "13", "45", "99"]
while True:
    x =input("Hãy đoán 1 số trong dãy: ")
    if x in num:
        print("Số",x,"có trong dãy!")
        index = num.index(x)
        print("Số",x, "ở vị trí số",index)

        break
    else:
        print("Try again!")


import pytesseract
import cv2
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# set browser to Firefox (requires geckodriver.exe in main Python executable folder
browser = webdriver.Firefox()
# set config for OCR
custom_config = r'-l eng --oem 3 --psm 6'

# resize all input images to factor for different screen resolutions
width = 1024
height = 576
dim = (width, height)

# cropping values
h = 110
w = 95
# column 1 (2 tags)
y1 = 275
x1 = 345
# column 2 (2 tags)
y2 = 275
x2 = 450
# column 3 (1 tag)
h3 = 55
w3 = 98
y3 = 275
x3 = 560

# function to read image, pre-process it for OCR, then use OCR to get the recruitment tags from the screenshot
def gettags(file_name):
	# read image
	img = cv2.imread(file_name)

	# resize image to factor for different resolutions
	resized = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)
	resized1 = resized[y1:y1 + h, x1:x1 + w]
	resized2 = resized[y2:y2 + h, x2:x2 + w]
	resized3 = resized[y3:y3 + h3, x3:x3 + w3]

	# pre-process images for better results
	resized1 = cv2.bitwise_not(resized1)
	resized2 = cv2.bitwise_not(resized2)
	resized3 = cv2.bitwise_not(resized3)

	# find tags by column and split them into lists of strings
	col1 = pytesseract.image_to_string(resized1, config=custom_config)
	col1 = col1.splitlines()
	col2 = pytesseract.image_to_string(resized2, config=custom_config)
	col2 = col2.splitlines()
	col3 = pytesseract.image_to_string(resized3, config=custom_config)
	col3 = col3.splitlines()

	# concatenate column into main tag list
	tag_list = col1 + col2 + col3
	# replace in-game 'Crowd-Control' tag to aceship 'Crowd Control' tag
	tag_list = [sub.replace('Crowd-Control', 'Crowd Control') for sub in tag_list]
	print("Tag List:", tag_list)
	return tag_list

if __name__ == "__main__":
	try:
		# ask for user-input image file
		image_file = input("Enter screenshot filename: ")
		# get tags from screenshot
		tags = gettags(image_file)
		# browse to aceship recruitment calculator, switch server to EN
		browser.get('https://aceship.github.io/AN-EN-Tags/akhr.html')
		sleep(1)
		server = browser.find_element_by_id('navitemRegion')
		sleep(0.25)
		server.click()
		server_en = browser.find_element_by_link_text('English')
		sleep(0.25)
		server_en.click()

		# iterate over tag list and input tags
		tag_input = browser.find_element_by_id('fastInput')
		for i in range(len(tags)):
			sleep(0.25)
			tag_input.send_keys(tags[i])
			sleep(0.25)
			tag_input.send_keys(Keys.ENTER)
	except IOError:
		pass


import numpy as np

class PoseSequence:
    def __init__(self, metadata=None):
        self.poses = []
        self.labels = []
        self.metadata = metadata

    def add_pose(self, pose, label=None):
        self.poses.append(pose)
        self.labels.append(label)

    def calculate_velocity_xyz(self):
        last_pose = None
        for pose in self.poses:
            if not last_pose:
                pose.add_data('velocity_xyz', np.zeros(pose.data['position_xyz'].shape))
                last_pose = pose
            else:
                velocity = pose.data['position_xyz'] - last_pose.data['position_xyz']
                pose.add_data('velocity_xyz', velocity)
                last_pose = pose

    def to_numpy(self, data_types):
        action_data = []
        for pose in self.poses:
            pose_data = None
            for data_type in data_types:
                if pose_data is None:
                    pose_data = pose.data[data_type]
                else:
                    pose_data = np.concatenate((pose_data, pose.data[data_type]), axis=1)
            action_data.append(pose_data)
        return np.array(action_data)

    def __str__(self):
       return '{}  \t {} poses'.format(self.metadata, len(self.poses))

    def __repr__(self):
        return self.__str__()


def parseInput():
    with open("input", 'r') as input_file:
        return input_file.readlines()

def buildGraph(data):
    graph = {}
    for d in data:
        planets = d.split(')')
        graph[planets[1].strip()] = planets[0].strip()
    return graph

def calculateOrbits(graph):
    orbits = 0
    for planet, node in graph.items():
        orbits += calculateIndirectOrbits(node, graph)
    return orbits

def calculateIndirectOrbits(node, graph):
    orbits = 1
    if graph.get(node):
        orbits += calculateIndirectOrbits(graph.get(node), graph)
    return orbits

def findDistance(graph):
    santa = graph.get('SAN')
    you = graph.get('YOU')
    santa_parents = []
    you_parents = []
    while santa:
        santa_parents.append(santa)
        santa = graph.get(santa)
    while you:
        you_parents.append(you)
        you = graph.get(you)
    diff = list(set(santa_parents)- set(you_parents))
    diff.extend(list(set(you_parents)- set(santa_parents)))
    return len(diff)

def solution():
    data = parseInput()
    graph = buildGraph(data)
    orbits = calculateOrbits(graph)
    distance = findDistance(graph)
    print(1, orbits)
    print(2, distance)

if __name__ == "__main__":
    solution()


# -*- coding: utf-8 -*-
"""
Created on Sun Jan  1 18:05:08 2023

@author: Rahul
"""
import warnings
warnings.filterwarnings('ignore')

import pandas as pd
import numpy as np

df = pd.read_csv("D:\\DS\\books\\ASSIGNMENTS\\Naive Bayes\\SalaryData_Test.csv")
df
df.info()
df.shape

df.head()
df.dtypes

#Finding the special characters in the data frame
df.isin(['?']).sum(axis=0)
print(df[0:5])

df.native.value_counts()
df.native.unique()

df.workclass.value_counts()
df.workclass.unique()

df.occupation.value_counts()
df.occupation.unique()

df.sex.value_counts()

#finding categorical and numerical
cat = [var for var in df.columns if df[var].dtype=='O']
print('There are {} categorical variables\n'.format(len(cat)))
print('The categorical variables are :\n\n', cat)

#find numerical variables
num = [var for var in df.columns if df[var].dtype!='O']
print('There are {} numerical variables\n'.format(len(num)))
print('The numerical variables are :', num)

# check if there are any missing values missing values in categorical variables

df[cat].isnull().sum()

df[num].isnull().sum()

# Visualisation
import seaborn as sns
import matplotlib.pyplot as plt

df["age"].hist()
df["educationno"].hist()
df["capitalgain"].hist()
df["capitalloss"].hist()
df["hoursperweek"].hist()

t1 = pd.crosstab(index=df["education"],columns=df["workclass"])
t1.plot(kind='bar')

t2 = pd.crosstab(index=df["education"],columns=df["Salary"])
t2.plot(kind='bar')

t3 = pd.crosstab(index=df["sex"],columns=df["race"])
t3.plot(kind='bar')

t4 = pd.crosstab(index=df["maritalstatus"],columns=df["sex"])
t4.plot(kind='bar')

# Outliers dectection and treating outliers
df.boxplot("age",vert=False)
Q1=np.percentile(df["age"],25)
Q3=np.percentile(df["age"],75)
IQR=Q3-Q1
LW=Q1-(2.0*IQR)
UW=Q3+(2.0*IQR)
df["age"]<LW
df[df["age"]<LW]
df[df["age"]<LW].shape
df["age"]>UW
df[df["age"]>UW]
df[df["age"]>UW].shape
df["age"]=np.where(df["age"]>UW,UW,np.where(df["age"]<LW,LW,df["age"]))

df.boxplot("educationno",vert=False)
Q1=np.percentile(df["educationno"],25)
Q3=np.percentile(df["educationno"],75)
IQR=Q3-Q1
LW=Q1-(2.0*IQR)
UW=Q3+(2.0*IQR)
df["educationno"]<LW
df[df["educationno"]<LW]
df[df["educationno"]<LW].shape
df["educationno"]>UW
df[df["educationno"]>UW]
df[df["educationno"]>UW].shape
df["educationno"]=np.where(df["educationno"]>UW,UW,np.where(df["educationno"]<LW,LW,df["educationno"]))

df.boxplot("hoursperweek",vert=False)
Q1=np.percentile(df["hoursperweek"],25)
Q3=np.percentile(df["hoursperweek"],75)
IQR=Q3-Q1
LW=Q1-(2.0*IQR)
UW=Q3+(2.0*IQR)
df["hoursperweek"]<LW
df[df["hoursperweek"]<LW]
df[df["hoursperweek"]<LW].shape
df["hoursperweek"]>UW
df[df["hoursperweek"]>UW]
df[df["hoursperweek"]>UW].shape
df["hoursperweek"]=np.where(df["hoursperweek"]>UW,UW,np.where(df["hoursperweek"]<LW,LW,df["hoursperweek"]))

df.boxplot("capitalgain",vert=False)
Q1=np.percentile(df["capitalgain"],25)
Q3=np.percentile(df["capitalgain"],75)
IQR=Q3-Q1
LW=Q1-(2.0*IQR)
UW=Q3+(2.0*IQR)
df["capitalgain"]<LW
df[df["capitalgain"]<LW]
df[df["capitalgain"]<LW].shape
df["capitalgain"]>UW
df[df["capitalgain"]>UW]
df[df["capitalgain"]>UW].shape
df["capitalgain"]=np.where(df["capitalgain"]>UW,UW,np.where(df["capitalgain"]<LW,LW,df["capitalgain"]))

df.boxplot("capitalloss",vert=False)
Q1=np.percentile(df["capitalloss"],25)
Q3=np.percentile(df["capitalloss"],75)
IQR=Q3-Q1
LW=Q1-(2.0*IQR)
UW=Q3+(2.0*IQR)
df["capitalloss"]<LW
df[df["capitalloss"]<LW]
df[df["capitalloss"]<LW].shape
df["capitalloss"]>UW
df[df["capitalloss"]>UW]
df[df["capitalloss"]>UW].shape
df["capitalloss"]=np.where(df["capitalloss"]>UW,UW,np.where(df["capitalloss"]<LW,LW,df["capitalloss"]))

# Spliting
X=df.iloc[:,0:13]
X.columns
Y=df["Salary"]

# split X and y into training and testing sets

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.3, random_state = 0)

# display categorical variables
categorical = [col for col in X_train.columns if X_train[col].dtypes == 'O']
categorical

# display numerical variables
numerical = [col for col in X_train.columns if X_train[col].dtypes != 'O']
numerical

#Data Transformation
#pip install category_encoders
import category_encoders as ce

encoder = ce.OneHotEncoder(cols=['workclass', 'education', 'maritalstatus', 'occupation', 'relationship',
                                 'race', 'sex', 'native'])
X_train = encoder.fit_transform(X_train)
X_test = encoder.transform(X_test)
X_train.head()

from sklearn.preprocessing import MinMaxScaler #fixed import

scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

#model fitting
from sklearn.naive_bayes import GaussianNB
gnb = GaussianNB()
# fit the model
gnb.fit(X_train, y_train)

y_pred_train = gnb.predict(X_train)
y_pred_test = gnb.predict(X_test)

from sklearn.metrics import accuracy_score
print("trainin score:",accuracy_score(y_train, y_pred_train).round(2))
print("test score:",accuracy_score(y_test, y_pred_test).round(2))

from sklearn.naive_bayes import BernoulliNB
bn = BernoulliNB()

bn.fit(X_train, y_train)

y_pred_train = bn.predict(X_train)
y_pred_test = bn.predict(X_test)

from sklearn.metrics import accuracy_score
print("trainin score:",accuracy_score(y_train, y_pred_train).round(2))
print("test score:",accuracy_score(y_test, y_pred_test).round(2))

from sklearn.naive_bayes import MultinomialNB
mb = MultinomialNB()

mb.fit(X_train, y_train)

y_pred_train = mb.predict(X_train)
y_pred_test = mb.predict(X_test)

from sklearn.metrics import accuracy_score
print("trainin score:",accuracy_score(y_train, y_pred_train).round(2))
print("test score:",accuracy_score(y_test, y_pred_test).round(2))

from sklearn.svm import SVC

svc_class = SVC(kernel='linear')

svc_class.fit(X_train,y_train)

y_predict_train = svc_class.predict(X_train)
y_predict_test = svc_class.predict(X_test)

print("trainin score:",accuracy_score(y_train, y_pred_train).round(2))
print("test score:",accuracy_score(y_test, y_pred_test).round(2))

from sklearn.linear_model import LogisticRegression

logreg = LogisticRegression()

logreg.fit(X_train,y_train)

#prediction
y_pred_train = logreg.predict(X_train)
y_pred_test = logreg.predict(X_test)

print("trainin score:",accuracy_score(y_train, y_pred_train).round(2))
print("test score:",accuracy_score(y_test, y_pred_test).round(2))


def get_ans(a,k):
    imp = []
    non_imp = []
    luck = 0

    for i in range(0,len(a)):
        if a[i][1]==1:
            imp.append(a[i][0])
        else:
            non_imp.append(a[i][0])
    imp.sort(reverse = True)

    for i in range(0,len(imp)):

        if i<=(k-1):
            luck += imp[i]
        else:
            luck -= imp[i]

    luck += sum(non_imp)

    print(luck)

n,k = map(int,input().split(" "))
aa = []
for i in range(0,n):
    m,y=map(int,input().split(" "))
    aa.append([m,y])
print(aa)

get_ans(aa,k)


import numpy as np
import cv2
import cv2.aruco as aruco
import glob

criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
#cap = cv2.VideoCapture(cv2.CAP_DSHOW)
cap = cv2.VideoCapture(10)

# set opencv videocapture properties for width, height and fps
cap.set(cv2.CAP_PROP_AUTOFOCUS, 0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 3840)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 2160)
cap.set(cv2.CAP_PROP_FPS, 30)

while (True):
    ret, frame = cap.read()

    # display the resulting frame
    cv2.imshow('frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()


from scapy.all import *

def detect_dnscachepois(cap, ur_ip):
    pcap = rdpcap(cap)

    # dns packet filter
    dns_packets = [pkt for pkt in pcap if DNS in pkt]
    detected_dnscp = []

    # test response by dns srv
    for pkt in dns_packets:
        if pkt.haslayer(DNSRR):
            if pkt.haslayer(IP):  # Add a check for the IP layer
                if pkt[DNSRR].rdata != ur_ip:
                    if '127.0.0' in pkt[IP].src:
                        continue
                    else:
                        detected_dnscp.append(pkt[IP].src)
    detected_dnscp = list(set(detected_dnscp))
    return detected_dnscp

# print(detect_dnscachepois('398in190-150323.pcapng','192.168.138.15'))


import sys
import re

symb = {
	"%":"percentage",
	"$":"dollar",
	"+":"plus",
	"1":"one",
	"2":"two",
	"3":"three",
	"4":"four",
	"5":"five",
	"6":"six",
	"7":"seven",
	"8":"eight",
	"9":"nine",
	"0":"zero",
	".dom" : "dot com",
	"½" : "half",
	"°": "degree",
	"µl" : "microliter",
	"Oz" : "ounce",
	"ml" : "milliliter",
	"kg" : "kilogram",
	}

	#"мой" : "",
	#"мужчина" : "",
	#"рута" : "",
	#"сильный" : "",
	#"червона" : "",
	#"オマエモナー" : "",
	#"中文" : "",
	#"國語" : "",
	#"漢字" : "",
	#"華人" : ""
	#}

def removeUTF(inputString):
	return inputString.encode("ascii", "ignore").decode()

def hasNumbers(inputString):
	return any(char.isdigit() for char in inputString)

def replaceSymb(inputString):
	no_punct = inputString
	for key in symb:
		if key in  no_punct:
			no_punct = no_punct.replace(key," "+symb[key]+" ")
	return removeMultiSpace(no_punct.strip())

def removePunc(inputString):
	punctuations = '''!()-[]{};:"\,<>./?^&*_~`#회|°–='''
	no_punct = ""
	for char in inputString:
		if char not in punctuations:
			no_punct = no_punct + char
	return removeMultiSpace(no_punct.strip())

def removeMultiSpace(inputString):
	return re.sub("\s\s+" , " ", inputString)

op1 = open(sys.argv[1]+"_clean","w")
#op2 = open("text_numbers.txt","w")

# @$%

with open(sys.argv[1],"r") as f1:
	for line in f1:
		ls = line.strip()
		ls = replaceSymb(removeUTF(ls))
		if not hasNumbers(ls):
			p1 = removePunc(ls).lower()
			op1.write(p1+"\n")
		#else:
		#	p1 = removePunc(ls)
		#	op2.write(p1+"\n")


# 두 수 n, k를 입력받아 n이 1이 될 때까지 두 과정중 하나를 반복적으로 선택하여 수행.
# 1) n에서 1을 뺀다.
# 2) n을 k로 나눈다. (나머지가 없을 경우에만 가능)
# 수행 횟수를 최소로 하여 구하기

import sys

# 익숙해지기 위해 라인 단위로 입력을 받아봄
data = sys.stdin.readline().rstrip()

# 입력받은 값을 공백 기준으로 나눠서 인덱스를 활용해 저장
n = int(data[0:data.index(' ')])

k = int(data[data.index(' ') + 1 : len(data)])

# 수행 횟수
count = 0

# n이 1이 될 때까지 반복
while n != 1:
  # 나머지가 없으면 나누기
  if n % k == 0:
    n //= k
    count += 1
  # 나머지가 있으면 1씩 빼기
  else:
    n -= 1
    count += 1

# 수행횟수 출력
print(count)


import numpy as np
import matplotlib.pyplot as plt
import os
import matplotlib

mode='GS'
L='5'
tmax=None
J=1
jmax=7
numIt=24000
outputEvery=130
dt=0.004
tIts=numIt//outputEvery
ks=['0.1', '0.3', '0.5', '0.7', '1.0']
Workers = ['W1','W2','W3','W4','W5']

ts=np.array([it*dt for it in range(numIt+1) if it%outputEvery==0])
if tmax==None:
    last_t = len(ts)
else:
    last_t = np.sum(ts<tmax)
times_computed=len(ts)

matplotlib.rcParams.update({'font.size': 22})

fig1=plt.figure(figsize=(20,10))

ax1 = []

ax1.append(fig1.add_subplot(111))

ax1[0].set_xlabel("Time (a.u.)")

ax1[0].grid(True)

pops_corr={}
pops_cwf={}
pops_leg={}

for k0, Wi in zip(ks, Workers):
    pops_corr[k0] = np.loadtxt(f"./{Wi}/DATA_population_correction.txt")
    pops_cwf[k0] = np.loadtxt(f"./{Wi}/DATA_populations_CWF.txt")
    pops_leg[k0] = np.loadtxt(f"./{Wi}/DATA_populations_legacy.txt")

numTrajs_pops_corr=[]
numTrajs_pops_leg=[]
numTrajs_pops_cwf=[]

for k0 in ks:
    numTrajs_pops_corr.append( pops_corr[k0].shape[0]//ts.shape[0])
    numTrajs_pops_leg.append( pops_leg[k0].shape[0]//ts.shape[0])
    numTrajs_pops_cwf.append( pops_cwf[k0].shape[0]//ts.shape[0])

print(numTrajs_pops_corr, numTrajs_pops_leg, numTrajs_pops_cwf)

# PLOT AVERAGE POPULATIONS of the ansatz GIVEN BY THE TRAJECTORIES
average_populations_corr={}
average_populations_leg={}

numTrajs=min(numTrajs_pops_corr)
for k0 in ks:
    average_populations_corr[k0]=np.zeros(( times_computed, next(iter(pops_corr.values())).shape[1]), dtype=np.float64)
    for i in range(numTrajs):
        beg=i*times_computed
        end=(i+1)*times_computed
        average_populations_corr[k0]+=pops_corr[k0][ beg:end,:]
    average_populations_corr[k0]/=numTrajs

numTrajs=min(numTrajs_pops_leg)
for k0 in ks:
    average_populations_leg[k0]=np.zeros(( times_computed, next(iter(pops_leg.values())).shape[1]), dtype=np.float64)
    for i in range(numTrajs):
        beg=i*times_computed
        end=(i+1)*times_computed
        average_populations_leg[k0]+=pops_leg[k0][ beg:end,:]
    average_populations_leg[k0]/=numTrajs

for k0 in ks:
    norm = np.sum(average_populations_corr[k0][:last_t,:], axis=1)
    for j in range(jmax+1):
        ax1[0].plot(ts[:last_t], average_populations_corr[k0][:last_t,j]/norm, '-', label=f"State j={j}", linewidth=1.0, markersize=2 )
    ax1[0].set_ylabel('Population in j-th TSEig')
    ax1[0].set_title(r"$\bf{"+mode+" L = "+L+" \ \ J = "+str(J)+" \ \ k0 ="+k0+"}$\nAverage accross trajectories\nof Corrected cwf product state populations", fontdict = {'fontsize' : 22})
    ax1[0].grid(True)
    ax1[0].legend()
    fig1.savefig(f"Average_Populations_Correction_{mode}_L{L}_k0_{k0}.png",dpi=400,bbox_inches='tight')
    ax1[0].clear()

for k0 in ks:
    #norm = np.sum(average_populations_leg[k0][:last_t,:], axis=1)
    norm=1
    for j in range(jmax+1):
        ax1[0].plot(ts[:last_t], average_populations_leg[k0][:last_t,j]/norm, '-', label=f"State j={j}", linewidth=1.0, markersize=2 )
    ax1[0].set_ylabel('Population in j-th TSEig')
    ax1[0].set_title(r"$\bf{"+mode+" L = "+L+" \ \  J = "+str(J)+" \ \ k0 ="+k0+"}$\nAverage accross trajectories\nof legacy cwf product state populations", fontdict = {'fontsize' : 22})
    ax1[0].grid(True)
    ax1[0].legend()
    fig1.savefig(f"Average_Populations_Legacy_{mode}_L{L}_k0_{k0}.png",dpi=400,bbox_inches='tight')
    ax1[0].clear()

# PLOT AVERAGE POPULATIONS computed with the approximated CWF definitions
numTrajs=min(numTrajs_pops_cwf)
current_time_diff_trajs=np.zeros((numTrajs, next(iter(pops_cwf.values())).shape[1]), dtype=np.float64)
populations_approx=np.zeros((times_computed, next(iter(pops_cwf.values())).shape[1]), dtype=np.float64)

for k0 in ks:
    for t in range(last_t):
        for traj in range(numTrajs):
            current_time_diff_trajs[traj, :]= pops_cwf[k0][ traj*times_computed+t,:]
        current_time_diff_trajs=current_time_diff_trajs[np.argsort(current_time_diff_trajs[:,0]),:] # order them by x position
        for traj in range(numTrajs-1):
            dx=current_time_diff_trajs[traj+1,0]-current_time_diff_trajs[traj,0]
            populations_approx[t,:]+=dx*(current_time_diff_trajs[traj+1,:]+
                                                current_time_diff_trajs[traj,:])
        populations_approx[t,:]*=0.5
    norm = np.sum(populations_approx[:last_t, 1:], axis=1)
    for j in range(jmax+1):
        ax1[0].plot(ts[:last_t], populations_approx[:last_t,j+1]/norm, '-', label=f"State j={j}", linewidth=1.0, markersize=2 )
    ax1[0].set_ylabel('Population in j-th TSEig')
    ax1[0].set_title(r"$\bf{"+mode+" L = "+L+"\ \ J = "+str(J)+" \ \ k0 ="+k0+"}$\nIntegrated across different trajectory\ncwf-s in y used as a dynamic grid for full wf", fontdict = {'fontsize' : 22})
    ax1[0].grid(True)
    ax1[0].legend()
    fig1.savefig(f"Approx_Populations_using_CWF_definition_{mode}_L{L}_k0_{k0}.png",dpi=400,bbox_inches='tight')
    ax1[0].clear()


import requests
from collections import deque
from lxml import etree
import hashlib
from pybloom_live import BloomFilter
import threading
import time
import os

class CrawlBSF:
    request_headers = {
        'host': "www.mafengwo.cn",
        'connection': "keep-alive",
        'cache-control': "no-cache",
        'upgrade-insecure-requests': "1",
        'user-agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36",
        'accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        'accept-language': "zh-CN,en-US;q=0.8,en;q=0.6"
    }

    cur_level = 0
    max_level = 5
    dir_name = 'mafengwo/'
    iter_width = 50
    downloaded_urls = []
    if not os.path.exists(dir_name):
        os.makedirs(dir_name)
    du_md5_file_name = dir_name + 'md5.txt'  # save records of downloaded urls' md5
    du_url_file_name = dir_name + 'urls.txt'  # save records of downloaded urls

    bloom_downloaded_urls_md5 = BloomFilter(1024 * 1024 * 16, 0.01)
    bloom_url_queue = BloomFilter(1024 * 1024 * 16, 0.01)

    cur_queue = deque()  # current crawling quque
    child_queue = deque()  # storage quque for next level crawl

    def __init__(self, url):
        self.root_url = url
        self.cur_queue.append(url)
        self.du_file = open(self.du_url_file_name, 'a+')
        self.nm_url=0
        try:
            self.md5_file = open(self.du_md5_file_name, 'r')
            self.downloaded_urls = self.md5_file.readlines()
            self.md5_file.close()
            for urlmd5 in self.downloaded_urls:
                self.bloom_downloaded_urls_md5.add(urlmd5[:-2])
        except IOError:
            print("File not found")
        finally:
            self.md5_file = open(self.du_md5_file_name, 'a+')

    def enqueueUrl(self, url):
        if url not in self.bloom_url_queue and hashlib.md5(url.encode("utf-8")).hexdigest() not in crawler.bloom_downloaded_urls_md5:
            self.child_queue.append(url)
            self.bloom_url_queue.add(url)
            self.nm_url+=1

    def dequeuUrl(self):
        try:
            return self.cur_queue.popleft()
        except IndexError:
            return None

    def close(self):
        self.md5_file.close()
        self.du_file.close()

num_downloaded_pages = 0

# download the page content
def get_page_content(cur_url):
    global num_downloaded_pages
    print("downloading %s at level %d" % (cur_url, crawler.cur_level))
    try:
        req = requests.request("get", cur_url, headers=crawler.request_headers)
        req.raise_for_status()
        req.encoding = req.apparent_encoding
        html_page = req.text
        filename = cur_url[7:].replace('/', '_')
        with open("%s%s.html" % (crawler.dir_name, filename), 'wb+') as fo:
            fo.write(html_page.encode("utf-8"))
    except requests.RequestException as e:
        print(e)
        return
    except IOError as Arguments:
        print(Arguments)
        return
    except Exception as Arguments:
        print(Arguments)
        return
    # print 'add ' + hashlib.md5(cur_url).hexdigest() + ' to list'

    # save page and set bloomfilter
    dumd5 = hashlib.md5(cur_url.encode("utf-8")).hexdigest()
    crawler.bloom_downloaded_urls_md5.add(dumd5)
    crawler.md5_file.write(dumd5 + '\r\n')
    crawler.du_file.write(cur_url + '\r\n')
    crawler.bloom_downloaded_urls_md5.add(dumd5)
    num_downloaded_pages += 1

    html = etree.HTML(html_page.lower())
    hrefs = html.xpath(u"//a")
    for href in hrefs:
        try:
            if 'href' in href.attrib:
                val = href.attrib['href']
                if val.find('javascript:') != -1:
                    continue
                if val.startswith('http://') is False:
                    if val.startswith('/'):
                        val = 'http://www.mafengwo.cn' + val
                    else:
                        continue
                if val[-1] == '/':
                    val = val[0:-1]
                # if hashlib.md5(val).hexdigest() not in self.downloaded_urls:
                crawler.enqueueUrl(val)

                # else:
                # print 'Skip %s' % (val)
        except ValueError:
            continue

crawler = CrawlBSF("http://www.mafengwo.cn")
start_time = time.time()

# if it's the first page (start url), if true, crawl it in main thread in sync(blocking) mode
# 如果是第一个抓取页面的话，在主线程用同步（阻塞）的模式下载，后续的页面会通过创建子线程的方式异步爬取
is_root_page = True
threads = []
max_threads = 10

CRAWL_DELAY = 0.6

while True:
    url = crawler.dequeuUrl()
    # Go on next level, before that, needs to wait all current level crawling done
    if url is None:
        crawler.cur_level += 1
        for t in threads:
            t.join()
        if crawler.cur_level == crawler.max_level:
            break
        if len(crawler.child_queue) == 0:
            break

        print("第{}级共有{}个url，爬取中.....".format(
            crawler.cur_level,crawler.nm_url))
        crawler.cur_queue = crawler.child_queue
        crawler.child_queue = deque()
        crawler.nm_url=0
        continue

    # looking for an empty thread from pool to crawl

    if is_root_page:
        get_page_content(url)
        is_root_page = False
    else:
        while True:
            # first remove all finished running threads
            for t in threads:
                if not t.is_alive():
                    threads.remove(t)
            if len(threads) >= max_threads:
                time.sleep(CRAWL_DELAY)
                continue
            try:
                t = threading.Thread(
                    target=get_page_content, name=None, args=(url,))
                threads.append(t)
                # set daemon so main thread can exit when receives ctrl-c
                t.setDaemon(True)
                t.start()
                time.sleep(CRAWL_DELAY)
                break
            except Exception as e:
                print("Error: unable to start thread"+"%s" % e)
crawler.close()
print('%d pages downloaded, time cost %0.2f seconds' %
      (num_downloaded_pages, time.time()-start_time))


# Activity 1
# The program consists of the user selecting which shape they would like to calculate.
# All of the shapes are in a class to be easier to work with.
# The user has to implement the sides of the shape.
# It displays the answers at the end.
# Error handling has been included.

import math
import sys

class Shape_Area():
    def area_triangle(self, base, height):
        return base * height / 2

    def area_square(self, length):
        return length ** 2

    def area_rectangle(self, width, height):
        return width * height

    def area_parallelogram(self, base, height):
        return base * height

    def area_trapezoid(self, side, base):
        return (side + base) / 2

    def area_circle(self, radius):
        return math.pi * radius ** 2

def get_choice():
    choice = input("Please enter one of the following abbreviations: T for triangle, S for square, R for rectangle, P for parallelogram, TR for trapezoid or C for circle: ")
    return choice

def shape_triangle():
    try:
        base = float(input("Enter the base: "))
        height = float(input("Enter the vertical height: "))
        shape = Shape_Area()
        area = shape.area_triangle(base, height)
        return area
    except TypeError:
        print("You need to enter a number!")
        print(sys.exc_info()[1])
    except ValueError:
        print("You need to enter a number!")
        print(sys.exc_info()[1])

def shape_square():
    try:
        side = float(input("Enter the length of a side: "))
        shape = Shape_Area()
        area = shape.area_square(side)
        return area
    except TypeError:
        print("You need to enter a number!")
        print(sys.exc_info()[1])
    except ValueError:
        print("You need to enter a number!")
        print(sys.exc_info()[1])

def shape_rectangle():
    try:
        height = float(input("Enter the vertical height: "))
        width = float(input("Enter the width: "))
        shape = Shape_Area()
        area = shape.area_rectangle(width, height)
        return area
    except TypeError:
        print("You need to enter a number!")
        print(sys.exc_info()[1])
    except ValueError:
        print("You need to enter a number!")
        print(sys.exc_info()[1])

def shape_parallelogram():
    try:
        base = float(input("Enter the base: "))
        height = float(input("Enter the vertical height: "))
        shape = Shape_Area()
        area = shape.area_parallelogram(base, height)
        return area
    except TypeError:
        print("You need to enter a number!")
        print(sys.exc_info()[1])
    except ValueError:
        print("You need to enter a number!")
        print(sys.exc_info()[1])

def shape_trapezoid():
    try:
        base = float(input("Enter the base: "))
        side = float(input("Enter the length of a side: "))
        shape = Shape_Area()
        area = shape.area_trapezoid(side, base)
        return area
    except TypeError:
        print("You need to enter a number!")
        print(sys.exc_info()[1])
    except ValueError:
        print("You need to enter a number!")
        print(sys.exc_info()[1])

def shape_circle():
    try:
        radius = float(input("Enter the radius: "))
        shape = Shape_Area()
        area = shape.area_circle(radius)
        return area
    except TypeError:
        print("You need to enter a number!")
        print(sys.exc_info()[1])
    except ValueError:
        print("You need to enter a number!")
        print(sys.exc_info()[1])

def main():
    print("\t\tWelcome to the Shape Area Program!\n\n")
    choice = get_choice()
    if (choice == "T" or choice == "t"):
        area = shape_triangle()
        print("The area of a triangle is ", round(area, 2))
    elif (choice == "S" or choice == "s"):
        area = shape_square()
        print("The area of a square is ", round(area, 2))
    elif (choice == "R" or choice == "r"):
        area = shape_rectangle()
        print("The area of a rectangle is ", round(area, 2))
    elif (choice == "P" or choice == "p"):
        area = shape_parallelogram()
        print("The area of a parallelogram is ", round(area, 2))
    elif (choice == "Tr" or choice == "tr"):
        area = shape_trapezoid()
        print("The area of a trapezoid is ", round(area, 2))
    elif (choice == "C" or choice == "c"):
        area = shape_circle()
        print("The area of a circle is ", round(area, 2))
    else:
        raise Exception("You must enter T for triangle, S for square, R for rectangle, P for parallelogram, TR for trapezoid or C for circle!", sys.exc_info()[1])
    print("\n\n\t\tThank you for using the Shape Area Program!")

main()


""""(*@ \section{Day 11: Dumbo Octopus} @*)"""""

from util import *

def preprocess(stdin):
    for line in stdin.splitlines():
        yield convert_sequence(line)

""""(*@ \subsection{Task One} @*)"""""

def return_or_none(lines, x, y):
    """Hack to avoid checking ranges"""
    try:
        return lines[x][y]
    except IndexError:
        return None

def get_surrounding_positions(lines, x, y):
    positions = [(dx, dy)
                    for dx in range(x-1, x+2)
                    for dy in range(y-1, y+2)
                    if (dx,dy) != (x,y)]

    for x, y in positions:
        if x < 0 or y < 0:
            continue
        if return_or_none(lines, x, y) is not None:
            yield (x, y)

def flash(octopuses, flashes, position):
    x, y = position

    # can only flash once
    if (x,y) in flashes:
        return

    energy = octopuses[x][y]
    if energy > 9:
        flashes.add((x, y))

        for (dx, dy) in get_surrounding_positions(octopuses, x, y):
            octopuses[dx][dy] += 1
            flash(octopuses, flashes, (dx, dy))

def step(octopuses):
    flashes = set()
    # increment first
    for x, row in enumerate(octopuses):
        for y, _ in enumerate(row):
            octopuses[x][y] += 1

    # flash after
    for x, row in enumerate(octopuses):
        for y, _ in enumerate(row):
            flash(octopuses, flashes, (x, y))

    # zero out last
    for x, y in flashes:
        octopuses[x][y] = 0

    return flashes

def task1(lines):
    lines = list(lines)

    total = 0
    for _ in range(100):
        total += len(step(lines))

    return total

""""(*@ \subsection{Task Two} @*)"""""

def task2(lines):
    lines = list(lines)
    size = len(lines) * len(lines[0])

    i = 1
    while True:
        if len(step(lines)) == size:
            return i

        i += 1

run(globals())


# 라이브러리 읽어들이기
from bs4 import BeautifulSoup

# 분석하고 싶은 HTML
html = """

스크래핑이란

웹페이지를 분석하는것

원하는 부분을 추출하는것

"""

# HTml 분석하기
soup = BeautifulSoup(html, 'html.parser')

# 원하는 부분 추출하기
h1 = soup.html.body.h1
p1 = soup.html.p
p2 = p1.next_sibling.next_sibling

h1_find = soup.find(id="title")
p_find = soup.find(id="body")

# 요소 글자 출력하기
print("h1 = " + h1.string)
print("p1 = " + p1.string)
print("p2 = " + p2.string)

print("h1_find = " + h1_find.string)
print("p_find = " + p_find.string)