import time

def paint_pynpgraph(sitename, host, service = "Check_MK", show=True):
    if show:
        site_url = html.site_status[sitename]["site"]["url_prefix"]
        pynp_timerange = get_painter_option("pynp_timerange")
        from_ts, to_ts = "", ""

        if pynp_timerange != None:
            vs = multisite_painter_options["pynp_timerange"]['valuespec']
            from_ts, to_ts = map(int, vs.compute_range(pynp_timerange)[0])
            from_ts_str = time.strftime("%d.%m.%Y %H:%M", time.localtime(from_ts))
            to_ts_str   = time.strftime("%d.%m.%Y %H:%M", time.localtime(to_ts))
        else:
            from_ts_str, to_ts_str = "",""

        height = get_painter_option("pynp_height")
        width = get_painter_option("pynp_width")

        return "pynpgraph", "
" \
                            "
" \
                            "    " \
                            "    " \
                            "    " \
                            "
" \
                            "
" \
                            "" % (site_url, host, service, from_ts, to_ts, width, height, host, service, from_ts_str, to_ts_str, site_url, host, service, from_ts, to_ts)
    return "pynpgraph", ""

multisite_painters["svc_pynp_graph" ] = {
    "title"   : "PyNP service graph",
    "short"   : "Performance Graph",
    "columns" : [ "host_name", "service_description", "service_pnpgraph_present" ],
    "options" : [ "pynp_timerange", "pynp_width", "pynp_height" ],
    "paint"   : lambda row: paint_pynpgraph(row["site"], row["host_name"], row["service_description"], row["service_pnpgraph_present"])
}

multisite_painter_options["pynp_timerange"] = {
    'valuespec' : Timerange(
        title = _("PyNP Timerange"),
        default_value = "w0",
        include_time = True,
    )
}

multisite_painter_options["pynp_height"] = {
    'valuespec' : DropdownChoice(
        title = _("PyNP Height"),
        default_value = "100",
        choices = [
            ("50",  _("50px")),
            ("75",  _("75px")),
            ("100", _("100px")),
            ("150", _("150px")),
            ("200", _("200px"))
        ]
    )
}

multisite_painter_options["pynp_width"] = {
    'valuespec' : DropdownChoice(
        title = _("PyNP Width"),
        default_value = "auto",
        choices = [
            ("auto", _("auto")),
            ("320",  _("320px")),
            ("400",  _("400px")),
            ("600",  _("600px")),
            ("800",  _("800px"))
        ]
    )
}


#方法1：递归
def M(n):
    if(n == 0):
        return  0
    elif(n == 1):
        return 1
    else:
        return n*M(n-1)
#n = int(input("阶乘数："))
#print(M(n))

#方法2：遍历
def M2():
    n = int(input("阶乘数："))
    if n<0:
        print("负数没有阶乘")
    elif n==0:
        print("0的阶乘为0")
    else:
        f = 1
        for i in range(1,n+1):
            f *=i
        print("{}的阶乘为：{}".format(n,f))
M2()


import sys
import csv
import argparse
import os
import io
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types

parser = argparse.ArgumentParser()
parser.add_argument('--input_file', type=str, help='Input audio file. Must be .flac')

def main():

	args = parser.parse_args()
	input_path = args.input_file

	transcribe_file(input_path)

def transcribe_file(speech_file):
    """Transcribe the given audio file."""
    try:
        client = speech.SpeechClient()
    except:
        print("authentication needed")
        exit(1)

    with io.open(speech_file, 'rb') as audio_file:
        content = audio_file.read()

    audio = types.RecognitionAudio(content=content)
    config = types.RecognitionConfig(
        encoding=enums.RecognitionConfig.AudioEncoding.FLAC,
        model="command_and_search",
        language_code='en-US',
        )
    response = client.recognize(config, audio)
    # Each result is for a consecutive portion of the audio. Iterate through
    # them to get the transcripts for the entire audio file.

    for result in response.results:
        # The first alternative is the most likely one for this portion.
        print(u'Transcript: {}'.format(result.alternatives[0].transcript))

if __name__ == '__main__':

    main()


def main():
    try:
        heating_deg = cooling_deg = 0

        infilename = input('Enter file name: ')
        infile = open(infilename, 'r')

        for avg_temp in infile:
            avg_temp = float(avg_temp)
            if avg_temp < 60:
                heating_deg = heating_deg + (60 - avg_temp)
            elif avg_temp > 80:
                cooling_deg = cooling_deg + (avg_temp - 80)

        print('Heating degrees: {0} \nCooling degrees: {1}'.format(heating_deg, cooling_deg))

    except:
        print('Enter a valid number')

main()


a = str(input("enter 5 digit binary value "))
if(len(a)<5):
    b = int(a,2)
    print("decimal "+str(b))

    c = oct(b)
    print("octal "+str(b))

    d = hex(b)
    print("hextal "+str(b))
else:
    print("wrong ")


sqsz = 50

import pygame, random, math
class Monster(pygame.sprite.Sprite):

    movement = ['rrruuuurrrddddddlllddrrrrruuuuuuuurrrrdddrdrddddrruuuurrrrrr',
                'rrrruuulldddrrrrurrdddrrrruuuuluurrrrrddddrrrrr',
                'rrrrrurrdrrdrrurrrurrdrrrrr']

    def __init__(self,life,speed,value,level):
        pygame.sprite.Sprite.__init__(self)

        self.level = level
        self.x = -1*50+25
        self.y = 5*50+25
        self.movementspot = 0
        self.movementtimes = 0
        self.rect = self.image.get_rect()
        self.rect.center = (self.x, self.y)
        self.alive = True
        self.life = life
        self.speed = speed
        self.value = value

    def hit(self,damage):
        self.life-=damage

    def isdead(self):
        if self.life <= 0:
            return True
        else:
            return False

    def move(self):
        if self.movementspot == len(Monster.movement[self.level]):
            self.alive = False
            return

        way = Monster.movement[self.level][self.movementspot]
        if way == 'r':
            self.x = self.x + self.speed
        elif way == 'l':
            self.x = self.x -self.speed
        elif way == 'u':
            self.y = self.y -self.speed
        elif way == 'd':
            self.y = self.y +self.speed

        self.movementtimes = self.movementtimes +1
        if self.movementtimes == sqsz/self.speed:
            self.movementspot = self.movementspot +1
            self.movementtimes = 0
        self.rect.center = (self.x, self.y)

class BasicMonster(Monster):

    image = None

    def __init__(self,level):
        if BasicMonster.image is None:
            BasicMonster.image = pygame.image.load("Monster.png")
        self.image = BasicMonster.image
        Monster.__init__(self,2,2,10,level)

class LifeMonster(Monster):

    image = None

    def __init__(self,level):
        if LifeMonster.image is None:
            LifeMonster.image = pygame.image.load("LifeMonster.png")
        self.image = LifeMonster.image
        Monster.__init__(self,5,2,10,level)

class SpeedMonster(Monster):

    image = None

    def __init__(self,level):
        if SpeedMonster.image is None:
            SpeedMonster.image = pygame.image.load("SpeedMonster.png")
        self.image = SpeedMonster.image
        Monster.__init__(self,2,4.1666666666666666,10,level)

class HenchMonster(Monster):
    image = None

    def __init__(self,level):
        if HenchMonster.image is None:
            HenchMonster.image = pygame.image.load("HenchMonster.png")
        self.image = HenchMonster.image
        Monster.__init__(self,3,2,10,level)

class LifeyMonster(Monster):

    image = None

    def __init__(self,level):
        if LifeyMonster.image is None:
            LifeyMonster.image = pygame.image.load("LifeMonster.png")
        self.image = LifeyMonster.image
        Monster.__init__(self,5,2.5,10,level)

class SuperSpeedMonster(Monster):

    image = None

    def __init__(self,level):
        if SpeedMonster.image is None:
            SpeedMonster.image = pygame.image.load("SpeedMonster.png")
        self.image = SpeedMonster.image
        Monster.__init__(self,4,4.1666666666666666,10,level)


from turtle import Turtle

class Newgame(Turtle):
    def __init__(self):
        super().__init__()
        self.score = 0
        self.penup()
        self.hideturtle()
        self.pencolor("white")
        self.goto(0, 0)

    def start_new_game(self):
        self.write(f"NEW GAME?", align="center", font=("Courier", 20, "normal"))


import random, copy

from aligner.bounds import in_bounds, get_bound
from aligner.scoring_and_similarity import get_segment_mfcc_cosine_similarity_score

from utilities import conversion_audio_sample_rate as sr
from utilities import conf, on_press_key

prune_types = {}
paths_visited = {}

def initialize_path_pruning():
    global prune_types
    prunes = [
                "poor_path_branching",
                "poor_path_fill",
                "poor_path_cosine",
                "bounds",
                "continuity",
                'duplicate_path_prune',
                'mfcc_correlate_overlap',
                "scope_cached",
                'exact_search_start_cache',
                'full_search_start_cache'
              ]

    for prune_type in prunes:
        prune_types[prune_type] = 0

    global paths_visited
    paths_visited.clear()

    global last_checkpoint_cache
    last_checkpoint_cache.clear()

def should_prune_path(reaction, current_path, current_start, reaction_start):
    global prune_types

    reaction_audio = reaction.get('reaction_audio_data')
    base_audio_length = len(conf.get('song_audio_data'))

    if current_start < .95 * base_audio_length and is_path_quality_poor(reaction, current_path):
        prune_types["poor_path_branching"] += 1
        return True

    if len(current_path) > 0:
        path_key = str(current_path)
        if path_key in paths_visited:
            prune_types["duplicate_path_prune"] += 1
            # print('duplicate path')
            return True
        paths_visited[path_key] = 1

    alignment_bounds = reaction['alignment_bounds']
    if alignment_bounds is not None:
        upper_bound = get_bound(alignment_bounds, current_start, len(reaction_audio))
        if not in_bounds(upper_bound, current_start, reaction_start):
            # print(f'\tBounds Prune! {current_start / sr} {reaction_start / sr} not in bounds (upper_bound={upper_bound}!')
            prune_types['bounds'] += 1
            # print('bounds prune')
            return True

    return False

def is_path_quality_poor(reaction, path):
    global prune_types

    spacing_min_length = 2.5 * sr
    spacing_max_separation = 15 * sr
    path_without_fillers = [p for p in path if not p[4]]
    if len(path_without_fillers) >= 3:
        first = path_without_fillers[-3]
        middle = path_without_fillers[-2]
        last = path_without_fillers[-1]
        if not first[-1] and not middle[-1] and not last[-1]: # ignore fillers
            # if first[1] - first[0] < spacing_min_length and middle[1] - middle[0] < spacing_min_length and last[1] - last[0] < spacing_min_length:
            if (first[1] - first[0]) + (middle[1] - middle[0]) + (last[1] - last[0]) < 3 * spacing_min_length:
                if middle[0] - first[1] > spacing_max_separation and last[0] - middle[1] > spacing_max_separation:
                    return True

    # Poor quality:
    #  - reaction separation greater than .1s and less than 1s and no filler
    #  - three+ non filler segments less than 2.5 seconds with spacing between
    #  - first segment is less than 3s, followed by 60s+ of space...
    #      ...or first two segments are separated by .1s and average < 6s

    short_segments = 0
    short_separation = 0

    filler_duration = 0
    duration = 0

    for i, segment in enumerate(path):
        if len(segment) == 5:
            (reaction_start, reaction_end, current_start, current_end, filler) = segment
        else:
            (reaction_start, reaction_end, current_start, current_end, filler, strokes) = segment

        duration += current_end - current_start
        if filler:
            filler_duration += current_end - current_start
            continue

        if i > 0:
            space_before = reaction_start - path[i-1][1]
            filler_before = path[i-1][4]
        else:
            filler_before = True
            space_before = 0

        if i < len(path) - 1:
            space_after = path[i+1][0] - reaction_end
            filler_after = path[i+1][4]
        else:
            filler_after = True
            space_after = 0

        if i == 0 and len(path) > 1 and not filler_after and space_after > 60 * sr and (reaction_end - reaction_start) < 3 * sr:
            return True

        if i == 0 and len(path) > 2 and not filler_after and space_after > .1 * sr and path[i+2][0] - path[i+1][1] > .1 * sr and ((reaction_end - reaction_start) + (path[1][1] - path[1][0])) < 6 * sr:
            return True

        if (not filler_before and .1 * sr < space_before < sr) or (not filler_after and .1 * sr < space_after < sr):
            return True

        if (reaction_end - reaction_start) < 2.5 * sr:

            # we're not going to consider the last segment, because we might add to it the next time it branches
            if (i == 0 or space_before > sr / 10 ) and i < len(path) - 1 and space_after > sr / 10:
                short_segments += 1
                if short_segments >= 3:
                    return True

        cosine_sim = get_segment_mfcc_cosine_similarity_score(reaction, segment)
        if not filler and cosine_sim < .250:
            prune_types['poor_path_cosine'] += 1
            return True

    if filler_duration * sr  > (10 * len(conf.get('song_audio_data')) / 3): # no more than 10 seconds of filler per three minutes of base audio
        prune_types['poor_path_fill']
        return True

    return False

last_checkpoint_cache = {}
def find_last_checkpoint_crossed(current_start):
    global last_checkpoint_cache
    checkpoints = conf.get('checkpoints')

    if current_start not in last_checkpoint_cache:
        previous_checkpoint = -1
        for checkpoint in checkpoints:
            if current_start < checkpoint:
                break
            previous_checkpoint = checkpoint
        last_checkpoint_cache[current_start] = previous_checkpoint

    return last_checkpoint_cache[current_start]

def print_prune_data():
    global prune_types

    checkpoints = conf.get('checkpoints')

    for k,v in prune_types.items():
        print(f"\t{k}: {v}")

def initialize_checkpoints():
    base_audio = conf.get('song_audio_data')

    samples_per_checkpoint = 2 * sr

    timestamps = []
    start = s = 6
    while s < len(base_audio):
        if s / sr >= start:
            timestamps.append(s)
        s += samples_per_checkpoint

    return timestamps

on_press_key('ø', print_prune_data)


from django.shortcuts import render,redirect,get_object_or_404
from gameplay.models import Game
from django.contrib.auth.decorators import login_required
from player.forms import InvitationForm
from player.models import Invitation
from django.core.exceptions import PermissionDenied

# Create your views here.
@login_required
def home(request):
    # first_player=Game.objects.filter(
    # first_player__username=request.user,
    #     status="F"
    # )
    # second_player = Game.objects.filter(
    #     second_player__username=request.user,
    #     status="S"
    # )
    # print(first_player)
    # print(second_player)
    # totallist=list(first_player)+list(second_player)
    # my_games=Game.object.games_for_user(request.user)
    # active_games=my_games.active()
    print(request.user)
    my_games=Game.objects.games_for_user(request.user)
    invitations=request.user.invitations_received.all()
    active_games=my_games.active()
    return render(request,"player/home.html",{
        "ngames":Game.objects.count(),
        "totalgames":active_games,
        "invitations":invitations
    })

@login_required
def new_invitation(request):
    if request.method=="POST":
        # temp= request.POST.copy()
        # temp['from_user']=request.user
        # print(request.POST)
        invitation=Invitation(from_user=request.user)
        form=InvitationForm(data=request.POST,instance=invitation)
        if form.is_valid():
            form.save()
            return  redirect("player_home")
    else:
        form=InvitationForm()
    return render(request,'player/new_invitation_form.html',{"form":form})

@login_required()
def accept_invitation(request,id):
    invitation=get_object_or_404(Invitation,pk=id)
    if not request.user==invitation.to_user:
        raise PermissionDenied
    if request.method=="POST":
        if "accept" in request.POST:
            game=Game.objects.create(first_player=invitation.to_user,second_player=invitation.from_user)
        invitation.delete()
        return redirect(game)
    else:
        return render(request,"player/accept_invitation_form.html",{
            'invitation':invitation
        })


"""
Подсистема server - подсистема серверного взаимодейтсвия
Подразделяется на 5 классов:

Client - класс клиента
ConfigClass - класс настроек сервера
ThreadedTCPRequestHandler - класс Обработчиков входящих запросов
MessageProcessor — класс Процессоров полученных соединений
ServerExecutor - класс Исполнителей полученных команд
ConnectionClass - класс установленных соединений
"""

import socket
import socketserver

from client.message import InputMessage, OutputMessage
from client.utils import parse_string

class ConfigClass(object):
    """
    ConfigClass - класс настроек клиента.
    Содержит константы и/или настройки для работы клиента.
    Не инстанциируется непосредственно - лишь является одним из родителей класса Server.
    """

    def __init__(self):
        """
        Метод инициализации.
        Устанавливаются некоторые предопределенные значения.
        """

        self.version = '0.1'
        self.small_cache_size = 10
        self.chunk_size = 1024
        self.server_adr = ('localhost', 15151)

class Client(socketserver.ThreadingTCPServer, ConfigClass):
    """
    Client - класс клиента.
    """

    def __init__(self,
                 app,
                 client_address: tuple,
                 RequestHandlerClass,
                 MessageProcessorClass,
                 ClientExecutorClass):
        """
        Метод инициализации.
        Отрабатывают функции инициализации родителей,
        создаёт пустой список для открытых соединений,
        инстанциируются Процессор сообщений и Исполнитель сообщений.
        Создаются буфера активных соединений и сообщений, ожидающих ответа.

        :param app: экземпляр класса ClientApp для работы которого инстанциируется клиент
        :param client_address: кортеж (IP: string, PORT: int)
        :param RequestHandlerClass: Класс Обработчика входящих запросов (для последующей инстанциации)
        :param MessageProcessorClass: Класс Процессора полученных соединений (для последующей инстанциации)
        :param ClientExecutorClass: Класс Исполнителя полученных команд (для последующей инстанциации)
        """

        self.app = app
        super().__init__(client_address, RequestHandlerClass)
        ConfigClass.__init__(self)
        self.msg_proc = MessageProcessorClass(self)
        self.executor = ClientExecutorClass(self)
        self.connection_buffer = []
        self.pending_messages = []
        self.killed_on_server = False

    def send_message(self, message: OutputMessage, DEBUG: bool = False):
        """
        Метод отправки сообщения серверу.

        :param DEBUG:
        :param message: сообщение - объект класса OutputMessage
        """

        for msg in message.encode():
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
                sock.connect((self.server_adr[0], self.server_adr[1]))
                sock.sendall(bytes(msg, 'utf-8'))
                print("sent {}".format(msg))
                sock.close()
                if DEBUG:
                    _ = input()
        self.pending_messages.append(message.id)

class ConnectionClass(object):
    """
    ConnectionClass — класс установленных соединений между приложениями.
    """

    def __init__(self, session_hash: str, size_list: list):
        """
        Инстанциируется при приеме первого запроса от другого приложения,
        в процессе получения остаточных запросов -  наполняется информацией,
        уничтожается в результате Процессинга.

        :param session_hash: входящий хэш сеанса (для проверки актуальности версий и поиска уже открытых сеансов)
        :param size_list: массив из boolean, определяющий превышает ли закодированная информация в сообщении буфер
        TCP-соединения. Если превышает (True) - то информация будет выслана несколькими запросами, следовательно
        нужно грамотно декодировать во время Обработки.
        """

        self.hash_trace = session_hash[:10]
        self.size_list = size_list
        self.data = []

class MessageProcessor(object):
    """
    MessageProcessor - класс процессоров полученных соединений.
    Инстанцируется при запуске сервера.
    Восстанавливает сообщения из соединений, полученных при обработке входящих запросов.
    """

    def __init__(self, client_instance: Client):
        """
        Метод инициализации объекта.
        :param client_instance: объект класса Client для работы которого инстанциируется Процессор полученных соединений
        """

        self.client = client_instance

    def process_response(self, connection: ConnectionClass):
        """
        Метод процессинга ответного соединения.
        Создает экземпляр класса InputMessage с данными из ответного
        соединения сервера.
        Удаляет сообщение из списка необработанных сообщений.

        :param connection: экземпляр класса
        ConnectionClass — установленное соединение, которое необходимо от-Процессить.
        """

        input_params = []
        for key_value in connection.data:
            input_params.append(parse_string(key_value))
        message = InputMessage(self.client.chunk_size, input_params)
        if message.id in self.client.pending_messages:
            self.execute_message(message)
            self.client.pending_messages.remove(message.id)

    def execute_message(self, message: InputMessage):
        """
        Метод проверки и исполнения команды из ответа сервера.
        Устанавливает соответствие между командой входящего сообщения
        и методом экземпляра Исполнителя полученных команд.

        :param message: экземпляр класса InputMessage — сообщение, которое содержит исполняемую команду
        """

        cmd = getattr(message, 'cmd')
        if cmd in getattr(self.client.executor, '_get_available_commands')():
            try:
                getattr(self.client.executor, cmd)(message)
            except Exception as e:
                raise e
        else:
            print('Client command {} not available'.format(cmd))

class ClientExecutor(object):
    """
    ClientExecutor - класс Исполнителей полученных команд.
    Исполняет команды, полученные от других приложений.
    Доступные команды представляют собой публичные методы этого класса.

    Новая команда должна добавляться объявлением соответствующего метода, для которого единственным аргументом будет
    экземпляр класса InputMessage!
    """

    def __init__(self, client_instance: Client):
        """
        Метод инициализации объекта.

        :param client_instance: объект класса Client для работы которого инстанциируется Исполнитель полученных команд.
        """

        self.client = client_instance

    @staticmethod
    def clt_print(message: InputMessage):
        print(message.msg)

    def approve_init(self, message: InputMessage):
        self.client.app.session = int(message.msg)

    def svr_approve(self, message: InputMessage):
        if message.msg == 'delete_session':
            self.client.killed_on_server = True
        print('Server successfully executed command {}!'.format(message.msg))

    def _get_available_commands(self):
        return [key for key in [s for s in dir(self) if s[:1] != '_' and callable((getattr(self, s)))]]

class ClientThreadedTCPRequestHandler(socketserver.BaseRequestHandler):

    def handle(self):
        """
        Метод handle вызывается как только клиент получает ответ от сервера.
        """

        data = str(self.request.recv(self.server.chunk_size), 'utf-8')
        print("got {} from {}".format(data, self.client_address))
        session_hash = data.split(':')[0]

        if len(session_hash) == 40:
            size_list = [True if int(i) > self.server.chunk_size else False for i in
                         data.split(':')[1][:-1].split('|')[:-1]]
            size_list.insert(0, False)
            connection = ConnectionClass(session_hash, size_list)
            self.server.connection_buffer.append(connection)

        elif len(session_hash) == 20:
            for connection in self.server.connection_buffer:
                if session_hash[:10] == connection.hash_trace:
                    self.server.connection_buffer.remove(connection)
                    self.server.msg_proc.process_response(connection)
                else:
                    print('InvalidConnection! Failed to remove {}'.format(session_hash))

        elif len(session_hash) == 10:
            for connection in self.server.connection_buffer:
                if session_hash == connection.hash_trace:
                    if not connection.size_list[len(connection.data)]:
                        connection.data.append(data.split(':', 1)[1])
                    else:
                        connection.data[-1] += data.split(':', 1)[1]
                else:
                    print('InvalidConnection! Failed to update {}'.format(session_hash))


def test_extract_features():
    """
    This function tests the 'extract_features' function by using a sample source code text.
    The test is successful if the function does not raise any exceptions and returns a tensor.
    """
    source_code_text = '/* Sample source code text */'
    feature_matrix = extract_features(source_code_text)
    assert isinstance(feature_matrix, torch.Tensor), 'The function should return a tensor.'
    assert feature_matrix.shape[0] > 0, 'The tensor should not be empty.'

test_extract_features()


import torch

from diffusers import StableDiffusionImg2ImgPipeline, StableDiffusionPipeline

def check_cuda_device()->torch.device:
    """Check if cuda is available and return the device"""
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    return device

def get_the_model(model_id:str = "stabilityai/stable-diffusion-2")->StableDiffusionPipeline:
    """Get the model"""
    pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
    device = check_cuda_device()
    pipe.to(device)

    return pipe

def get_image_to_image_model(model_id:str="stabilityai/stable-diffusion-2")->StableDiffusionImg2ImgPipeline:
    """Get the image to image model"""
    pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
        model_id, torch_dtype=torch.float16
    )

    device = check_cuda_device()
    pipe.to(device)

    return pipe

def gen_initial_img(int_prompt:str)->torch.Tensor:
    """Generate the initial image"""
    model = get_the_model()
    image = model(int_prompt, num_inference_steps=100).images[0]

    return image

def generate_story_images(int_prompt:str, story_steps:list)->dict:
    """Generate the ilustrations for the story"""
    image_dic = {}
    step_zero_img = gen_initial_img(int_prompt)
    img2img_model = get_image_to_image_model()

    initialisation_img = step_zero_img

    for idx, story_step in enumerate(story_steps):
        step_img = img2img_model(
            prompt=story_step,
            image=initialisation_img,
            strength=0.5,
            guidance_scale=6,
            num_inference_steps=100,
        ).images[0]
        image_dic[idx] = {"image": step_img, "prompt": story_step}
        initialisation_img = step_img

    return image_dic


import sys
input = sys.stdin.readline

def solution(X):
    line = 1
    while line < X:
        X -= line
        line += 1

    if line % 2 == 1:
        up = line - X + 1
        low = X
    else:
        up = X
        low = line - X + 1

    print(up, '/', low, sep="")

if __name__ == '__main__':
    X = int(input().strip())
    solution(X)


def search():
    city = city_entry.get()
    #print(city)
    url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=88e88f570f80d0d47352c988b6e52865"
    result = requests.get(url).json()
    temperature = (result["main"]["temp"]) - 273.15
    temp_lbl['text'] = "Temperature at " + city + " is " + str(int(temperature))+ "°C"

def reset():
    city_entry.delete(0, tk.END)
    temp_lbl['text'] = ''

root = tk.Tk()
root.title("Weather App")
root.geometry("300x500")
root.configure(bg='powder blue')

head1 = tk.Label(root,
                 text="Enter your city",
                 font=("bold", 16),
                 fg="blue",
                 bg="powder blue")
head1.configure(bg='powder blue')
head1.pack(pady=10)

city = tk.StringVar()
city_entry = tk.Entry(root, textvariable=city)
city_entry.pack(pady=7)

search_btn = tk.Button(root,
                       text="Search Weather",
                       width=12,
                       command=search,
                       bg="navy blue",
                       fg="white")
search_btn.pack(pady=10)

reset_btn = tk.Button(root, text="Reset", command=reset, bg="yellow")
reset_btn.pack(pady=10)

temp_lbl = tk.Label(root, text="")
temp_lbl.configure(bg="powder blue")
temp_lbl.pack(padx=5, pady=3)

root.mainloop()


# -*- coding: utf-8 -*-
import re
import numpy as np
import pandas as pd

filename = "D.motif"
file = open(filename, "r")

order = ['C','T','G','A'] #ordem dos nucleotídeos

seq_list = [] # lista com todas as sequências
qtd_list = [] #lista com a quantidade de cada sequência

position = 0
id_nuc = -1

for line in file:
  line_data = line
  aux = re.split("\t", line_data) #retirando a tabulação entre a sequência e o número
  seq_list.append(aux[0])
  qtd_list.append(int(aux[1].rstrip()))

#configuração do modo como o numpy lida com números do tipo float -> senão sai uns números doidos do tipo 6.4757e+08
float_formatter = lambda x: "%f" % x
np.set_printoptions(formatter={'float_kind':float_formatter})

#inicialização da pssm -> colocada uma coluna a mais para guardar a overall freq. quando necessário
pssm = np.zeros((4, len(seq_list[0])+1), dtype=object)

for n in order: #para cada nucleotideo
  id_nuc = id_nuc + 1
  for seq in seq_list: #para cada sequencia
    seq_position = seq_list.index(seq) #pega a posição dessa sequência na lista
    for position in range(0,len(seq)): #para cada posição dessa sequência
      if n == seq[position]:

        pssm[id_nuc,position] = pssm[id_nuc,position] + qtd_list[seq_position]
  # pssm[id_nuc,len(seq_list[0])] = sum(pssm[id_nuc:])

print("\n--------- Matriz de Quantidades Totais:")
# impressão com labels
df = pd.DataFrame(pssm[0:4,0:len(seq_list[0])], index=list(order), columns=range(1,len(seq_list[0])+1))
print("\n")
print(df)

pssm = pssm/sum(qtd_list)

print("\n\n--------- Matriz de Frequências Totais:")
# impressão com labels
df = pd.DataFrame(pssm[0:4,0:len(seq_list[0])], index=list(order), columns=range(1,len(seq_list[0])+1))
print("\n")
print(df)

for i in range(0,4):
  #somar os valores da linha e dividí-los pela quantidade de posições, para encontrar a Overall freq.
  pssm[i,len(seq_list[0])] = pssm[i,i:len(seq_list[0])].sum() / len(seq_list[0])

  #dividir cada valor da linha pela Overall freq. encontrada acima
  for j in range(0,len(seq_list[0])):
    pssm[i,j] = pssm[i,j]/pssm[i,len(seq_list[0])]

print("\n\n--------- Matriz de Frequências Totais Normalizadas:")
# impressão com labels
df = pd.DataFrame(pssm[0:4,0:len(seq_list[0])], index=list(order), columns=range(1,len(seq_list[0])+1))
print("\n")
print(df)

#Converte os scores normalizados para escala logarítmica na base 2

for i in range(0,4):
  for j in range(0,len(seq_list[0])):
    if pssm[i,j] != 0:
      pssm[i,j] = np.log2(pssm[i,j])
    else:
      pssm[i,j] = '--'

print("\n\n--------- PSSM Completa:")
# impressão com labels
df = pd.DataFrame(pssm[0:4,0:len(seq_list[0])], index=list(order), columns=range(1,len(seq_list[0])+1))
print("\n")
print(df)

df.to_csv('D_scores_totais.csv')

file.close()

ATV 8 - Busca de Motivos em Sequências Conservadas/BioinfAtividadePratica8/main.py


#!/usr/bin/python

import sys, os, argparse, operator, re, itertools
from itertools import chain, combinations

def combs(l):
    return [1,1,2,4,7][len(l)-1]

def main(args):
    adaptors = sorted([int(x) for x in open(args.file).readlines()])

    a_range = [0] + adaptors + [adaptors[-1]+3]
    grouped = sorted([j-i for i, j in zip(a_range[:-1], a_range[1:])])
    grouped = map(len, [list(j) for i, j in itertools.groupby(grouped)])
    print(reduce(operator.mul, grouped))

    contiguous = [[0]]
    ptr = 0
    for i in range(1, len(a_range)):
        if a_range[i] - a_range[i-1] == 1:
            contiguous[ptr].append(a_range[i])
        else:
            contiguous.append([a_range[i]])
            ptr += 1
    #print(contiguous)
    print(reduce(operator.mul, map(combs, contiguous)))

if __name__ == "__main__":
    default_file = sys.argv[0].split("-")[0] + "-input.txt"
    ap = argparse.ArgumentParser(description="2020 Day 10 AOC: Adaptor Array")
    ap.add_argument("file", help="Input file", default=default_file, nargs="?")
    args = ap.parse_args()
    main(args)


from operator import add
from itertools import permutations
from math import gcd
from functools import reduce
import time

class Moon():
    def __init__(self, position, velocity=(0, 0, 0)):
        self.position = position
        self.velocity = velocity

    def gravity_influence(self, other_moons):
        for m in other_moons:
            if m != self:
                self.velocity = add_tuples(
                    self.velocity,
                    gravity(self.position, m.position))

    def update_postion(self):
        self.position = add_tuples(self.position, self.velocity)

    def __repr__(self):
        return f"pos = <x ={self.position[0]:>3}, y ={self.position[1]:>3}, z ={self.position[2]:>3}>, " + \
               f"vel = <x ={self.velocity[0]:>3}, y ={self.velocity[1]:>3}, z ={self.velocity[2]:>3}>\n"

def gravity_p(a, b):
    if a == b:
        return 0
    if a < b:
        return 1
    else:
        return -1

def gravity(a, b):
    return (gravity_p(a[0], b[0]),
            gravity_p(a[1], b[1]),
            gravity_p(a[2], b[2]))

def add_tuples(p, v):
    return tuple(map(add, p, v))

def step(moons):
    for m in moons:
        m.gravity_influence(moons)
    for m in moons:
        m.update_postion()
    return moons

def energy(moons):
    total = 0
    for m in moons:
        pot = sum(map(abs, m.position))
        kin = sum(map(abs, m.velocity))
        total += (pot * kin)
    return total

def axis_period(moons, axis):
    # store the initial state of all moons position on axis
    # the assumption here is that the initial state will be the period boundary
    initial_p = [m.position[axis] for m in moons]
    initial_v = [m.velocity[axis] for m in moons]
    counter = 0
    while True:
        moons = step(moons)
        counter += 1
        if [m.position[axis] for m in moons] == initial_p and [m.velocity[axis] for m in moons] == initial_v:
            return counter

def lcms(numbers):
    return reduce(lcm, numbers)

def lcm(a, b):
    return (a * b) // gcd(a, b)

if __name__ == "__main__":
    moons = [
        Moon((-1, 0, 2), (0, 0, 0)),
        Moon((2, -10, -7), (0, 0, 0)),
        Moon((4, -8, 8), (0, 0, 0)),
        Moon((3, 5, -1), (0, 0, 0))
    ]

    for _ in range(10):
        moons = step(moons)
    assert(energy(moons) == 179)

    periods = [axis_period(moons, i) for i in range(3)]
    assert(lcms(periods) == 2772)

    # didn't bother with parsing the input this time
    # just hand encoded the values
    moons = [
        Moon((6, -2, -7), (0, 0, 0)),
        Moon((-6, -7, -4), (0, 0, 0)),
        Moon((-9, 11, 0), (0, 0, 0)),
        Moon((-3, -4, 6), (0, 0, 0))
    ]
    m2 = moons.copy()

    # part 1
    for _ in range(1000):
        moons = step(moons)
    print("Energy after 1000", energy(moons))

    # part 2
    # people smarter than me figured out the axis and lcm approach
    periods = [axis_period(m2, i) for i in range(3)]
    print("Period", lcms(periods))


import discord
from discord.ext import commands

class ping(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def ping(self, ctx):
        '''
        Pong! Get the bot latency with this command.
        '''

        latency = self.bot.latency
        await ctx.send("Pong! `" + str(int(latency * 100)) + "ms`")

def setup(bot):
    bot.add_cog(ping(bot))


# Embedded file name: scripts/client/gui/Scaleform/daapi/view/lobby/ny/ny_craft.py
import BigWorld
from gui.Scaleform.daapi.settings.views import VIEW_ALIAS
from gui.Scaleform.daapi.view.lobby.ny.ny_helper_view import NYHelperView
from gui.Scaleform.daapi.view.meta.NYScreenCraftMeta import NYScreenCraftMeta
from gui.Scaleform.genConsts.NY_CONSTANTS import NY_CONSTANTS
from gui.Scaleform.locale.NY import NY
from gui.shared.formatters import text_styles
from helpers import dependency
from items.new_year_types import TOY_TYPES, NATIONAL_SETTINGS, NATIONAL_SETTINGS_IDS_BY_NAME, TOY_TYPES_IDS_BY_NAME
from items.new_year_types import g_cache
from new_year.new_year_sounds import NYSoundEvents
from skeletons.new_year import INewYearUIManager

def toyTypeByIndex(index):
    if index == 0 or len(TOY_TYPES) < index:
        return None
    else:
        return TOY_TYPES[index - 1]

def toyLevelByIndex(index):
    if index == 0:
        return None
    else:
        return index

def toyNationByIndex(index):
    if index == 2:
        return 'modernWestern'
    elif index == 3:
        return 'traditionalWestern'
    elif index == 0 or len(NATIONAL_SETTINGS) < index:
        return None
    else:
        return NATIONAL_SETTINGS[index - 1]

def indexByToyType(type):
    if type is None:
        return 0
    else:
        return TOY_TYPES_IDS_BY_NAME.get(type, None) + 1

def indexByToyLevel(level):
    if level is None:
        return 0
    else:
        return level

def indexByToyNation(nation):
    if nation == 'modernWestern':
        return 2
    elif nation == 'traditionalWestern':
        return 3
    elif nation is None:
        return 0
    else:
        return NATIONAL_SETTINGS_IDS_BY_NAME.get(nation, None) + 1

def getStyle(isEnabled):
    if isEnabled:
        return text_styles.tutorial
    return text_styles.main

class NYCraft(NYHelperView, NYScreenCraftMeta):
    newYearUIManager = dependency.descriptor(INewYearUIManager)

    def __init__(self, ctx = None):
        super(NYCraft, self).__init__(ctx)
        self.__toyNation = None
        self.__toyLevel = None
        self.__toyType = None
        return

    def onClose(self):
        self._switchToNYMain(previewAlias=VIEW_ALIAS.LOBBY_NY_CRAFT)

    def _populate(self):
        super(NYCraft, self)._populate()
        self._newYearController.clearCraftedToys()
        selectedToy = self.newYearUIManager.getSelectedCraftToy()
        self.__toyType = selectedToy.get('type', None) if selectedToy else None
        self.__toyLevel = selectedToy.get('level', None) if selectedToy else None
        self.__toyNation = selectedToy.get('nation', None) if selectedToy else None
        initData = {'shardsBtnLabel': NY.CRAFTSCREEN_BUTTONS_SHARDSBTN,
         'craftBtnLabel': NY.CRAFTSCREEN_BUTTONS_CRAFTBTN,
         'title': NY.CRAFTSCREEN_TITLE,
         'shardsDescription': NY.CRAFTSCREEN_DESCRIPTION,
         'toyFragmentCount': BigWorld.wg_getIntegralFormat(self._newYearController.getToyFragments()),
         'nationsBlock': {'title': NY.CRAFTSCREEN_NATIONSLIDER_TITLE,
                          'selectedId': indexByToyNation(self.__toyNation),
                          'typeId': NY_CONSTANTS.NATIONS_SECTION,
                          'tooltips': [NY.CRAFTSCREEN_NATIONSLIDER_TOOLTIP_ANY,
                                       NY.CRAFTSCREEN_NATIONSLIDER_TOOLTIP_SOVIET,
                                       NY.CRAFTSCREEN_NATIONSLIDER_TOOLTIP_MODERNWESTERN,
                                       NY.CRAFTSCREEN_NATIONSLIDER_TOOLTIP_TRADITIONALWESTERN,
                                       NY.CRAFTSCREEN_NATIONSLIDER_TOOLTIP_ASIAN]},
         'typesBlock': {'title': NY.CRAFTSCREEN_TYPESLIDER_TITLE,
                        'selectedId': indexByToyType(self.__toyType),
                        'typeId': NY_CONSTANTS.TYPES_SECTION,
                        'tooltips': [NY.CRAFTSCREEN_TYPESLIDER_TOOLTIP_ANY,
                                     NY.CRAFTSCREEN_TYPESLIDER_TOOLTIP_TOP,
                                     NY.CRAFTSCREEN_TYPESLIDER_TOOLTIP_HANGING,
                                     NY.CRAFTSCREEN_TYPESLIDER_TOOLTIP_GARLAND,
                                     NY.CRAFTSCREEN_TYPESLIDER_TOOLTIP_GIFT,
                                     NY.CRAFTSCREEN_TYPESLIDER_TOOLTIP_SNOWMAN,
                                     NY.CRAFTSCREEN_TYPESLIDER_TOOLTIP_HOUSE_DECORATION,
                                     NY.CRAFTSCREEN_TYPESLIDER_TOOLTIP_HOUSE_LAMP,
                                     NY.CRAFTSCREEN_TYPESLIDER_TOOLTIP_STREET_GARLAND]},
         'levelsBlock': {'title': NY.CRAFTSCREEN_LEVELSLIDER_TITLE,
                         'selectedId': indexByToyLevel(self.__toyLevel),
                         'typeId': NY_CONSTANTS.LEVELS_SECTION,
                         'tooltips': [NY.CRAFTSCREEN_LEVELSLIDER_TOOLTIP_ANY,
                                      NY.CRAFTSCREEN_LEVELSLIDER_TOOLTIP_1,
                                      NY.CRAFTSCREEN_LEVELSLIDER_TOOLTIP_2,
                                      NY.CRAFTSCREEN_LEVELSLIDER_TOOLTIP_3,
                                      NY.CRAFTSCREEN_LEVELSLIDER_TOOLTIP_4,
                                      NY.CRAFTSCREEN_LEVELSLIDER_TOOLTIP_5]},
         'carouselData': self.__getToysVO()}
        self.as_setInitDataS(initData)
        self.__updatePrice()
        NYSoundEvents.playSound(NYSoundEvents.ON_OPEN_CRAFT)
        NYSoundEvents.setState(NYSoundEvents.STATE_ON_CRAFT)
        self._newYearController.onToyFragmentsChanged += self.__onToyFragmentsChanged
        self._newYearController.onCraftedToysChanged += self.__onCraftedToysChanged
        return

    def __getToysVO(self):
        toys = [ g_cache.toys[toyId] for toyId in self._newYearController.craftedToys ]
        result = []
        for toy in toys:
            result.append({'icon': toy.icon})

        return result

    def __onCraftedToysChanged(self, toyId):
        toy = g_cache.toys[toyId]
        self.as_setCraftS({'icon': toy.icon,
         'id': toyId,
         'level': toy.rank,
         'settings': toy.setting})

    def __updatePrice(self):
        price = self._newYearController.getPriceForCraft(self.__toyType, self.__toyNation, self.__toyLevel)
        fragments = self._newYearController.getToyFragments()
        isCraftEnabled = price <= fragments
        self.as_setPriceS(price, isCraftEnabled)
        self.as_setCraftButtonEnableS(isCraftEnabled)
        self.as_setShardsButtonShineS(not isCraftEnabled)

    def __onToyFragmentsChanged(self, fragmentsCount):
        self.__updatePrice()
        self.as_updateShardsS(BigWorld.wg_getIntegralFormat(fragmentsCount))

    def onFilterChange(self, type, index):
        oldPrice = self._newYearController.getPriceForCraft(self.__toyType, self.__toyNation, self.__toyLevel)
        if type == NY_CONSTANTS.TYPES_SECTION:
            NYSoundEvents.playSound(NYSoundEvents.CRAFT_SELECT_TYPE_OR_LEVEL)
            self.__toyType = toyTypeByIndex(index)
        elif type == NY_CONSTANTS.LEVELS_SECTION:
            NYSoundEvents.playSound(NYSoundEvents.CRAFT_SELECT_TYPE_OR_LEVEL)
            self.__toyLevel = toyLevelByIndex(index)
        elif type == NY_CONSTANTS.NATIONS_SECTION:
            self.__toyNation = toyNationByIndex(index)
            NYSoundEvents.playSound(NYSoundEvents.CRAFT_SELECT_SETTING)
            NYSoundEvents.setBoxSwitch(self.__toyNation)
        newPrice = self._newYearController.getPriceForCraft(self.__toyType, self.__toyNation, self.__toyLevel)
        fragments = self._newYearController.getToyFragments()
        if newPrice > fragments >= oldPrice:
            NYSoundEvents.playSound(NYSoundEvents.CRAFT_COST_SAME)
        if newPrice != oldPrice:
            NYSoundEvents.playSound(NYSoundEvents.CRAFT_COST_INCREASED if newPrice > oldPrice else NYSoundEvents.CRAFT_COST_DECREASED)
        NYSoundEvents.playSound(NYSoundEvents.CRAFT_MACHINE_ANIMATION)
        selectedToy = {'type': self.__toyType,
         'level': self.__toyLevel,
         'nation': self.__toyNation}
        self.newYearUIManager.setSelectedCraftToy(selectedToy)
        self.__updatePrice()

    def onCraft(self):
        NYSoundEvents.playSound(NYSoundEvents.CRAFT_BUTTON_PRESSED_CRAFT)
        self._newYearController.craftToy(self.__toyType, self.__toyNation, self.__toyLevel)

    def onGetShards(self):
        NYSoundEvents.playSound(NYSoundEvents.CRAFT_TO_BREAK)
        self._switchToBreak(previewAlias=VIEW_ALIAS.LOBBY_NY_CRAFT)

    def onToyCreatePlaySound(self, level):
        NYSoundEvents.playSound(NYSoundEvents.CRAFT_TOY_CRAFTED)
        NYSoundEvents.setRTPC(NYSoundEvents.RTPC_TOYS, int(level))

    def _dispose(self):
        NYSoundEvents.playSound(NYSoundEvents.ON_CLOSE_CRAFT)
        self._newYearController.onToyFragmentsChanged -= self.__onToyFragmentsChanged
        self._newYearController.onCraftedToysChanged -= self.__onCraftedToysChanged
        super(NYCraft, self)._dispose()


import numpy as np
from src.deep_learning.RGrad.function import mean

from src.deep_learning.RGrad.tensor import Tensor
from src.deep_learning.RGrad.transform import Conv2D, Linear, ReLUBlock

def test_linear():
    linear_transform = Linear(3, 2)
    params = linear_transform.params()
    assert len(params) == 2
    for param in params:
        if param.shape == (2,):
            bias_tensor = param
        elif param.shape == (2, 3):
            weight_tensor = param

    assert weight_tensor.shape == (2, 3)
    assert bias_tensor.shape == (2,)

    inpt_tensor = Tensor(np.array([[1, 2, 3], [4, 5, 6]]))
    linear_transform.bias_param.tensor.elems[0] = 0.5
    linear_transform.bias_param.tensor.elems[1] = 0.6
    linear_transform.weight_param.tensor.elems[0][0] = 1
    linear_transform.weight_param.tensor.elems[0][1] = 2
    linear_transform.weight_param.tensor.elems[0][2] = 3
    linear_transform.weight_param.tensor.elems[1][0] = 4
    linear_transform.weight_param.tensor.elems[1][1] = 5
    linear_transform.weight_param.tensor.elems[1][2] = 6
    output_tensor = linear_transform(inpt_tensor)
    assert output_tensor.shape == (2, 2)
    assert np.allclose(output_tensor.elems, np.array([[14.5, 32.6], [32.5, 77.6]]))

    scalar_output = mean(output_tensor)
    scalar_output.backward()
    assert weight_tensor.grad_array.shape == (2, 3)
    assert bias_tensor.grad_array.shape == (2,)

def test_relu_block():
    relu_block = ReLUBlock(3, 2)
    params = relu_block.params()
    assert len(params) == 2
    for param in params:
        if param.shape == (2,):
            bias_tensor = param
        elif param.shape == (2, 3):
            weight_tensor = param
    assert weight_tensor.shape == (2, 3)
    assert bias_tensor.shape == (2,)

    inpt_tensor = Tensor(np.ones([4, 3]))
    output_tensor = relu_block(inpt_tensor)
    assert output_tensor.shape == (4, 2)

def test_conv2d():
    conv2d_transform = Conv2D(4, 5, 5, 3)
    input_ims = Tensor(np.ones((8, 12, 12, 3)))

    output = conv2d_transform(input_ims)
    assert output.shape == (8, 8, 8, 4)

    output = mean(output)
    output.backward()

    params = conv2d_transform.params()
    assert len(params) == 1
    assert params[0] is conv2d_transform.kernels.tensor
    assert params[0].grad_array.shape == (4, 5, 5, 3)


import requests
from pathlib import Path

def download_lenna(ouput_dir: str = "./data"):
    """Download lenna image from http://www.lenna.org/lena_std.tif

    Args:
        ouput_dir (str, optional): Output directory.
            Defaults to "./data".
    """
    url = "http://www.lenna.org/lena_std.tif"
    responce = requests.get(url)
    output_filepath = Path(ouput_dir).joinpath("lena_std.tif")
    output_filepath.parent.mkdir(parents=True, exist_ok=True)
    with open(output_filepath, "wb") as f:
        f.write(responce.content)


#-----main-----

a = list(map(int, input().split()))

#find the smallest number in the list
min = 100
for i in a:
    if i < min:
        min = i

#find the largest number in the list
max = 0
for i in a:
    if i > max:
        max = i

#find the sum of the list
sum = 0
for i in a:
    sum += i

#find the average of the list
avg = sum / len(a)

#find the median of the list
a.sort()
if len(a) % 2 == 0:
    median = (a[len(a) // 2] + a[len(a) // 2 - 1]) / 2
else:
    median = a[len(a) // 2]

#find the mode of the list
mode = 0
for i in a:
    if a.count(i) > mode:
        mode = i

#find the range of the list
range = max - min

#find the variance of the list
variance = 0
for i in a:
    variance += (i - avg)**2
variance /= len(a)

#find the standard deviation of the list
stdev = variance**0.5

#find the sum of the squares of the list
sumsq = 0
for i in a:
    sumsq += i**2

#find the sum of the cubes of the list
sumsqc = 0
for i in a:
    sumsqc += i**3

#find the sum of the list
sum = 0
for i in a:
    sum += i

#find the sum of the reciprocals of the list
sumrec = 0
for i in a:
    sumrec += 1/i

#find the sum of the squares of the reciprocals of the list
sumsqrec = 0
for i in a:
    sumsqrec += 1/(i**2)

#find the sum of the cubes of the reciprocals of the list
sumsqcrec = 0
for i in a:
    sumsqcrec += 1/(i**3)

#find the sum of the nth powers of the list
n = 3
sumn = 0
for i in a:
    sumn += i**n

#find the sum of the nth roots of the list
n = 3
sumnroot = 0
for i in a:
    sumnroot += i**(1/n)

#find the sum of the nth powers of the reciprocals of the list
n = 3
sumnrec = 0
for i in a:
    sumnrec += 1/(i**n)

#find the sum of the nth roots of the reciprocals of the list
n = 3
sumnrootrec = 0
for i in a:
    sumnrootrec += 1/(i**(1/n))

#find the sum of the reciprocals of the nth powers of the list
n = 3
sumrecn = 0
for i in a:
    sumrecn += 1/(i**n)

#find the sum of the reciprocals of the nth roots of the list
n = 3
sumrecnroot = 0
for i in a:
    sumrecnroot += 1/(i**(1/n))

#find the sum of the reciprocals of the nth powers of the reciprocals of the list
n = 3
sumrecnrec = 0
for i in a:
    sumrecnrec += 1/(1/(i**n))

#find the sum of the reciprocals of the nth roots of the reciprocals of the list
n = 3
sumrecnrootrec = 0
for i in a:
    sumrecnrootrec += 1/(1/(i**(1/n)))

#find the sum of the reciprocals of the nth powers of the list
n = 3
sumrecn = 0
for i in a:
    sumrecn += 1/(i**n)

#find the sum of the reciprocals of the nth roots of the list
n = 3
sumrecnroot = 0
for i in a:
    sumrecnroot += 1/(i**(1/n))

#find the sum of the reciprocals of the nth powers of the reciprocals of the list
n = 3
sumrecnrec = 0
for i in a:
    sumrecnrec += 1/(1/(i**n))

#find the sum of the reciprocals of the nth roots of the reciprocals of the list
n = 3
sumrecnrootrec = 0
for i in a:
    sumrecnrootrec += 1/(1/(i**(1/n)))


import unittest
import requests

class ApiTest(unittest.TestCase):

    def setUp(self):
        self.BASE_URL = 'http://127.0.0.1:8093/'

    def test_01_insurance(self):

        #given
        data = {
            "code_insurance" : "L12fd5",
            "name_insurance" : "NATIXIS",
        }

        #when
        r = requests.post(self.BASE_URL + "insurances", json=data)
        print("testCreateInsurance" + r.text)

        #then
        self.assertEqual(r.status_code, requests.codes.ok)

    def test_02_getInsurance(self):
        r = requests.get(self.BASE_URL + "insurances")
        print("testGetContract" + r.text)
        self.assertEqual(r.status_code, requests.codes.ok)

    def test_03_GetInsuranceId(self):
        r = requests.get(self.BASE_URL + "insurances/" + str(1))
        print("testGetInsuranceId :" + r.text)
        self.assertEqual(r.status_code, requests.codes.ok)

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


from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

import numpy as np
import pandas as pd
import nltk
from nltk.corpus import PlaintextCorpusReader

get_ipython().magic('matplotlib inline')
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})
plt.rc('xtick', labelsize=20)
plt.rc('ytick', labelsize=20)

# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# ... lexical diversity score - as given in nltk site
# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

def lexical_diversity(my_text_data):
    tokens = len(my_text_data)
    types = len(set(my_text_data))
    diversity_score = types / tokens
    return diversity_score

# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# ... some directory and file name definitions
# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

files = ".*\.txt"
home_dir = "/home/mcdevitt/_ds/_smu/msds_7337_nlp/homework_01/"
corpus_root = "./texts"
plot_dir = "./plots/"

# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# ... read in texts / assemble corpus for evaluation
# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

readers = PlaintextCorpusReader(corpus_root, files)

readers.fileids()

corpus = nltk.Text(readers.words())

# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# ... create table to accumulate summary data
# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

results_tbl = pd.DataFrame(columns =
    ['text_name',
     'num_chars',
     'num_words',
     'num_sents',
     'num_vocab',
     'tokens',
     'types',
     'lex_div'])

i_index = []
i_index = 0

# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# ... loop thru each text to assemble metrics
# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

print("Some basic statistics\n")

for fileid in readers.fileids():
    num_chars = len(readers.raw(fileid))
    num_words = len(readers.words(fileid))
    num_sents = len(readers.sents(fileid))
    tokens = len(readers.words(fileid))
    types = len(set(readers.words(fileid)))
    num_vocab = len(set(w.lower() for w in readers.words(fileid)))
#    print(round(num_chars/num_words, 2),
#          round(num_words/num_sents, 2),
#          round(num_words/num_vocab, 2), fileid)
    rtxt = readers.words(fileid)
    ldiv = lexical_diversity(rtxt)
    print(round(ldiv, 4), fileid)

    table_data = {
     'text_name' : fileid,
     'num_chars' : num_chars,
     'num_words' : num_words,
     'num_sents' : num_sents,
     'num_vocab' : num_vocab,
     'tokens' : tokens,
     'types' : types,
     'lex_div' : ldiv
    }

    df_tbl = pd.DataFrame(table_data,
        columns = ['text_name',
             'num_chars',
             'num_words',
             'num_sents',
             'num_vocab',
             'tokens',
             'types',
             'lex_div'],
    index = [i_index + 1])
    i_index += 1
    results_tbl = results_tbl.append(df_tbl)

results_tbl = results_tbl.sort_values(results_tbl.columns[7])
print('Results_tbl - sorted by col 8')
results_tbl

# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# ... normalize each column by max column value
# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

results = results_tbl.copy()
results = results.sort_values(results.columns[7], ascending = False)

df = results.iloc[:, 1:8]
df_nrml = df / df.max()

df_labels = results.iloc[:, 0]
df_labels

results = pd.concat([df_labels, df_nrml], axis = 1)

results['vocab_ldiv'] = results.apply(lambda x: x.lex_div * (x.num_words), axis=1)
results['vocab_ldiv'] = results['vocab_ldiv'] / results['vocab_ldiv'].max()

print('Results - ')
results

# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# ... plot - lexical diversity scores - sorted in ascending TTR
# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

N = 9
ind = np.arange(N)
width = 0.5

_ = plt.figure(figsize = (18, 10))
offset = 0
plt.bar(ind + offset, results_tbl['lex_div'], width, label='Lex_Div', color = 'tomato')

plt.xticks(ind + width / 2, results_tbl['text_name'])
plt.xticks(rotation=90)
plt.legend(loc='upper left')
plt.title('Lexical Diversity - Selected Readers', fontsize = '30')

axes = plt.gca()
axes.set_ylim([0, 0.2])

plt.savefig(plot_dir + 'nltk_readers_ttr.png')
plt.show()

# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# ... plot - vocabulary size - sorted in ascending TTR
# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

N = 9
ind = np.arange(N)
width = 0.4

_ = plt.figure(figsize = (18, 10))
offset = width / 2
plt.bar(ind + offset, results_tbl['num_vocab'], width, label='Vocab', color = 'orchid')
plt.bar(ind + offset + width, results_tbl['types'], width, label='Types', color = 'cornflowerblue')

plt.xticks(ind + width / 2, results_tbl['text_name'])
plt.xticks(rotation=90)
plt.legend(loc='upper left')
plt.title('Vocabulary Size - Selected Readers', fontsize = '30')

axes = plt.gca()

plt.savefig(plot_dir + 'nltk_readers_vocab.png')
plt.show()

# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# ... plot - vocabulary size - vs other stats - scatter plots
# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

N = 9
ind = np.arange(N)
width = 0.4

_ = plt.figure(figsize = (18, 10))
offset = width / 2
plt.scatter(results_tbl['num_vocab'], np.log10(results_tbl['types']), color = 'orchid', s = 100)
plt.scatter(results_tbl['num_vocab'], np.log10(results_tbl['tokens']), color = 'slateblue', s = 100)
plt.scatter(results_tbl['num_vocab'], np.log10(results_tbl['num_sents']), color = 'cornflowerblue', s = 100)
plt.scatter(results_tbl['num_vocab'], np.log10(results_tbl['num_chars']), color = 'darkcyan', s = 100)

plt.legend(loc='upper left', fontsize = '25')
plt.title('Vocabulary Size - Selected Readers', fontsize = '30')
plt.xlabel('Number of Vocabulary Words', fontsize = '25')
plt.ylabel('Corresponding Statistics (log10 scale)', fontsize = '25')

axes = plt.gca()
axes.set_ylim([1, 7])

plt.savefig(plot_dir + 'nltk_metrics_vs_vocab.png')
plt.show()

# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# ... plot comparison of all (normalized) metrics - sorted in descending TTR
# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
results = results.sort_values(results_tbl.columns[7], ascending = False)
N = 9
ind = np.arange(N)
width = 0.143

_ = plt.figure(figsize = (18, 8))
offset = width / 2
plt.bar(ind + offset, results['lex_div'], width, label='Lex_Div', color = 'tomato')
plt.bar(ind + offset + width, results['num_chars'], width, label='Chars', color = 'dodgerblue')
plt.bar(ind + offset + width*2, results['num_words'], width, label='Words', color = 'slateblue')
plt.bar(ind + offset + width*3, results['num_sents'], width, label='Sentences', color = 'cornflowerblue')
plt.bar(ind + offset + width*4, results['num_vocab'], width, label='Vocab', color = 'orchid')
plt.bar(ind + offset + width*5, results['vocab_ldiv'], width, label='Vocab_LDiv', color = 'darkcyan')

plt.xticks(ind + width / 2, results['text_name'])
plt.xticks(rotation=90)
plt.legend(loc='upper left')
plt.title('Normalized Characteristics Comparison (Lex Div Sorted)', fontsize = '30')

axes = plt.gca()
axes.set_ylim([-0.1, 1.1])

plt.savefig(plot_dir + 'nltk_readers_ttr_normalized.png')
plt.show()

# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# ... plot comparison of all (normalized) metrics -
# ... sorted in descending TTR*num_tokens
# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

results = results.sort_values(results_tbl.columns[8], ascending = False)
N = 9
ind = np.arange(N)
width = 0.143

_ = plt.figure(figsize = (18, 8))

offset = width / 2
plt.bar(ind + offset, results['lex_div'], width, label='Lex_Div', color = 'tomato')
plt.bar(ind + offset + width, results['num_chars'], width, label='Chars', color = 'dodgerblue', alpha = 0.9)
plt.bar(ind + offset + width*2, results['num_words'], width, label='Words', color = 'slateblue', alpha = 0.9)
plt.bar(ind + offset + width*3, results['num_sents'], width, label='Sentences', color = 'cornflowerblue', alpha = 0.9)
plt.bar(ind + offset + width*4, results['num_vocab'], width, label='Vocab', color = 'orchid', alpha = 0.9)
plt.bar(ind + offset + width*5, results['vocab_ldiv'], width, label='Vocab_LDiv', color = 'c')

plt.xticks(ind + width / 2, results['text_name'])
plt.xticks(rotation=90)
plt.legend(loc='upper right')
plt.title('Normalized Characteristics Comparison (Lex Div * Vocab)', fontsize = '30')

axes = plt.gca()
axes.set_ylim([-0.1, 1.1])

plt.savefig(plot_dir + 'nltk_readers_ttrxtokens_normalized.png')
plt.show()

# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# ... end_of_file
# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-