from __future__ import annotations

import time
from datetime import date, datetime, timedelta
from logging import getLogger
from time import struct_time
from typing import Any, Callable

import pytz

from .compat import IS_WINDOWS
from .constants import is_date_type_name, is_timestamp_type_name
from .converter import (
    ZERO_EPOCH,
    SnowflakeConverter,
    _adjust_fraction_of_nanoseconds,
    _extract_timestamp,
    _generate_tzinfo_from_tzoffset,
)
from .sfbinaryformat import SnowflakeBinaryFormat, binary_to_python
from .sfdatetime import SnowflakeDateFormat, SnowflakeDateTime, SnowflakeDateTimeFormat

logger = getLogger(__name__)

def format_sftimestamp(
    ctx: dict[str, Any], value: datetime | struct_time, franction_of_nanoseconds: int
) -> str:
    sf_datetime = SnowflakeDateTime(
        datetime=value, nanosecond=franction_of_nanoseconds, scale=ctx.get("scale")
    )
    return ctx["fmt"].format(sf_datetime) if ctx.get("fmt") else str(sf_datetime)

class SnowflakeConverterSnowSQL(SnowflakeConverter):
    """Snowflake Converter for SnowSQL.

    Format data instead of just converting the values into native
    Python objects.
    """

    def __init__(self, **kwargs) -> None:
        super().__init__(**kwargs)
        self._support_negative_year = kwargs.get("support_negative_year", True)

    def _get_format(self, type_name: str) -> str:
        """Gets the format."""
        fmt = None
        if type_name == "DATE":
            fmt = self._parameters.get("DATE_OUTPUT_FORMAT")
            if not fmt:
                fmt = "YYYY-MM-DD"
        elif type_name == "TIME":
            fmt = self._parameters.get("TIME_OUTPUT_FORMAT")
        elif type_name + "_OUTPUT_FORMAT" in self._parameters:
            fmt = self._parameters[type_name + "_OUTPUT_FORMAT"]
            if not fmt:
                fmt = self._parameters["TIMESTAMP_OUTPUT_FORMAT"]
        elif type_name == "BINARY":
            fmt = self._parameters.get("BINARY_OUTPUT_FORMAT")
        return fmt

    #
    # FROM Snowflake to Python objects
    #
    # Note: Callable doesn't implement operator|
    def to_python_method(
        self, type_name: str, column: dict[str, Any]
    ) -> Callable | None:
        ctx = column.copy()
        if ctx.get("scale") is not None:
            ctx["max_fraction"] = int(10 ** ctx["scale"])
            ctx["zero_fill"] = "0" * (9 - ctx["scale"])
        fmt = None
        if is_date_type_name(type_name):
            datetime_class = time.struct_time if not IS_WINDOWS else date
            fmt = SnowflakeDateFormat(
                self._get_format(type_name),
                support_negative_year=self._support_negative_year,
                datetime_class=datetime_class,
            )
        elif is_timestamp_type_name(type_name):
            fmt = SnowflakeDateTimeFormat(
                self._get_format(type_name),
                data_type=type_name,
                support_negative_year=self._support_negative_year,
                datetime_class=SnowflakeDateTime,
            )
        elif type_name == "BINARY":
            fmt = SnowflakeBinaryFormat(self._get_format(type_name))
        logger.debug("Type: %s, Format: %s", type_name, fmt)
        ctx["fmt"] = fmt
        converters = [f"_{type_name}_to_python"]
        for conv in converters:
            try:
                return getattr(self, conv)(ctx)
            except AttributeError:
                pass
        logger.warning("No column converter found for type: %s", type_name)
        return None  # Skip conversion

    def _BOOLEAN_to_python(self, ctx):
        """No conversion for SnowSQL."""
        return lambda value: "True" if value in ("1", "True") else "False"

    def _FIXED_to_python(self, ctx):
        """No conversion for SnowSQL."""
        return None

    def _REAL_to_python(self, ctx):
        """No conversion for SnowSQL."""
        return None

    def _BINARY_to_python(self, ctx):
        """BINARY to a string formatted by BINARY_OUTPUT_FORMAT."""
        return lambda value: ctx["fmt"].format(binary_to_python(value))

    def _DATE_to_python(self, ctx: dict[str, str | None]) -> Callable:
        """Converts DATE to struct_time/date.

        No timezone is attached.
        """

        def conv(value: str) -> str:
            return ctx["fmt"].format(time.gmtime(int(value) * (24 * 60 * 60)))

        def conv_windows(value):
            ts = ZERO_EPOCH + timedelta(seconds=int(value) * (24 * 60 * 60))
            return ctx["fmt"].format(date(ts.year, ts.month, ts.day))

        return conv if not IS_WINDOWS else conv_windows

    def _TIMESTAMP_TZ_to_python(self, ctx: dict[str, Any]) -> Callable:
        """Converts TIMESTAMP TZ to datetime.

        The timezone offset is piggybacked.
        """
        scale = ctx["scale"]
        max_fraction = ctx.get("max_fraction")

        def conv0(encoded_value: str) -> str:
            value, tz = encoded_value.split()
            microseconds = float(value)
            tzinfo = _generate_tzinfo_from_tzoffset(int(tz) - 1440)
            try:
                t = datetime.fromtimestamp(microseconds, tz=tzinfo)
            except OSError as e:
                logger.debug("OSError occurred but falling back to datetime: %s", e)
                t = ZERO_EPOCH + timedelta(seconds=microseconds)
                if pytz.utc != tzinfo:
                    t += tzinfo.utcoffset(t)
                t = t.replace(tzinfo=tzinfo)
            fraction_of_nanoseconds = _adjust_fraction_of_nanoseconds(
                value, max_fraction, scale
            )

            return format_sftimestamp(ctx, t, fraction_of_nanoseconds)

        def conv(encoded_value: str) -> str:
            value, tz = encoded_value.split()
            microseconds = float(value[0 : -scale + 6])
            tzinfo = _generate_tzinfo_from_tzoffset(int(tz) - 1440)
            try:
                t = datetime.fromtimestamp(microseconds, tz=tzinfo)
            except (OSError, ValueError) as e:
                logger.debug("OSError occurred but falling back to datetime: %s", e)
                t = ZERO_EPOCH + timedelta(seconds=microseconds)
                if pytz.utc != tzinfo:
                    t += tzinfo.utcoffset(t)
                t = t.replace(tzinfo=tzinfo)

            fraction_of_nanoseconds = _adjust_fraction_of_nanoseconds(
                value, max_fraction, scale
            )

            return format_sftimestamp(ctx, t, fraction_of_nanoseconds)

        return conv if scale > 6 else conv0

    def _TIMESTAMP_LTZ_to_python(self, ctx: dict[str, Any]) -> Callable:
        def conv(value: str) -> str:
            t, fraction_of_nanoseconds = self._pre_TIMESTAMP_LTZ_to_python(value, ctx)
            return format_sftimestamp(ctx, t, fraction_of_nanoseconds)

        return conv

    def _TIMESTAMP_NTZ_to_python(self, ctx: dict[str, Any]) -> Callable:
        """Converts TIMESTAMP NTZ to Snowflake Formatted String.

        No timezone info is attached.
        """

        def conv(value: str) -> str:
            microseconds, fraction_of_nanoseconds = _extract_timestamp(value, ctx)
            try:
                t = time.gmtime(microseconds)
            except (OSError, ValueError) as e:
                logger.debug("OSError occurred but falling back to datetime: %s", e)
                t = ZERO_EPOCH + timedelta(seconds=(microseconds))
            return format_sftimestamp(ctx, t, fraction_of_nanoseconds)

        return conv

    _TIME_to_python = _TIMESTAMP_NTZ_to_python


import os
import time
import argparse
from datetime import datetime
from utils.CpuMonitor import CpuMonitor
from utils.GpuMonitor import GpuMonitor
from utils.Recoder import Recoder
from utils.Printer import print_info, print_err, print_warn

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--cpu-only', help='Only record CPU temperature', action='store_true')
    parser.add_argument('--sample-interval',
                        help='Specify the data retrieve interval in seconds. Default is 10 seconds',
                        type=int, default=10)
    parser.add_argument('--log-file', help='Record CSV file. Default is ./statistic.csv',
                        type=str, default='./statistic.csv')
    return parser.parse_args()

def main():
    args = get_args()
    sample_interval = args.sample_interval

    log_file = args.log_file
    log = Recoder(log_file)

    cpu_tester = None
    gpu_tester = None

    try:
        if not args.cpu_only:
            print_info("[INFO] Start to record GPU/CPU temperature in every {} sec.".format(str(sample_interval)))
            cpu_tester = CpuMonitor()
            gpu_tester = GpuMonitor()
            log.generate_table_header(cpu_tester.num, gpu_tester.num)
        else:
            print_warn("[WARN] Only collect CPU Temperature.")
            print_info("[INFO] Start to record CPU temperature in every {} sec.\033[0m".format(str(sample_interval)))
            cpu_tester = CpuMonitor()
            log.generate_table_header(cpu_tester.num)

        while True:
            timestamp = str(datetime.now()).split('.')[0]
            data_row = [timestamp]
            data_row.extend(cpu_tester.get_statistics())
            if gpu_tester is not None:
                data_row.extend(gpu_tester.get_statistics())

            log.write_record_file(','.join(data_row))
            time.sleep(sample_interval)

    except KeyboardInterrupt:
        print()
        print_err("[ERROR] Keyboard Interrupted, temperature recording program exit.")
        exit()

if __name__ == '__main__':
    main()


# This program is a print queue simulator.
# The program reads instructions off of a web page
# pertaining to addition, removal, and printing of documents
# as well as showing contents of the print queue

# Assignment 2 for CISC 121, Summer 2017
# Author: Andy Wang

import urllib.request

'''
Reads instructions from a web page using the
urlopen function in the urllib.request module.
Places each line of instructions in list cmdList.
Continues reading until an empty bytes variable is read.
Returns cmdList
'''
def readHtml():
    html=b'temp'
    cmdList=[]
    response = urllib.request.urlopen("http://research.cs.queensu.ca/home/cords2/printsim.txt")
    while html!=b'':
        html = response.readline()
        data = html.decode('utf-8').split()
        cmdList.append(data)
    cmdList.remove([])                      #removes the "decoded" empty bytes variable
    return cmdList

'''
Calculates time reequired to process a document
based on format, colour/bw, and pages.
Parameter docInfo is the info for the relevant document.
Returns -1 if file format is invalid (not pdf, docx, pptx, or jpg)
Otherwise, returns estimated time
'''
def calcTime(docInfo):
    time=0
    if docInfo["type"]=="pdf":
        if docInfo["colour"]=="bw":
            time=time+4*int(docInfo["pages"])
        else:
            time=time+30*int(docInfo["pages"])
    elif docInfo["type"]=="pptx" or docInfo["type"]=="docx":
        if docInfo["colour"]=="bw":
            time=time+6*int(docInfo["pages"])
        else:
            time=time+20*int(docInfo["pages"])
    elif docInfo["type"]=="jpg":
        if docInfo["colour"]=="bw":
            time=time+10*int(docInfo["pages"])
        else:
            time=time+60*int(docInfo["pages"])
    else:
        return -1                           #returns -1 for an invalid file format
    return time

'''
Used to determine where to place a new document in queue.
Parameters include the current queue and estimated time
for the new document.
Returns "head" if the document should be placed at the front.
Otherwise, returns n, being the position in queue
'''
def findPlace(currentQ,newTime):
    n=0
    ptr=currentQ
    while ptr["data"]["time"]<=newTime and ptr["next"]!=None:
        ptr=ptr["next"]
        n=n+1
    if n==0 and ptr["data"]["time"]>newTime:
        return "head"
    elif ptr["data"]["time"]>newTime:       #in case the current ptr location contains a slower document
        n=n-1
    return n

'''
Function used to add a new document to queue.
Parameters include info about the new document and the current queue.
Ignores document if file format is invalid.
Adds document based on position found using findPlace().
Special cases exist for the first document or a cleared/empty queue.
Returns updated currentQ.
'''
def submit(docInfo,currentQ):
    docData={"data":{"id":docInfo[1],"type":docInfo[2],"pages":docInfo[3],"colour":docInfo[4]}}
    docTime=calcTime(docData["data"])
    docData["data"]["time"]=docTime
    if docTime==-1:                         #ignore document if file format is invalid
        pass
    else:
        print("Adding job",docData["data"]["id"],"to the queue. It will require",docTime,"seconds to process.")
        ptr=currentQ
        if currentQ==None:                  #special case for cleared queue
            currentQ={}
            currentQ["data"]=docData["data"]
            currentQ["next"]=None
        elif "data" not in currentQ:        #special case for first document
            docData["next"]=None
            currentQ=docData
        else:
            position=findPlace(currentQ,docTime)
            if position=="head":
                docData["next"]=ptr
                currentQ=docData
            else:
                counter=0
                while counter<position:     #counts to n based on findPlace()
                    ptr=ptr["next"]
                    counter=counter+1
                docData["next"]=ptr["next"]
                ptr["next"]=docData
    return currentQ

'''
Shows the current print queue.
Parameter is the current queue
Prints the number of items in the queue and estimated total time.
Optional lines to show all document data or job IDs
'''
def queue(currentQ):             #prints a linked list
    if currentQ==None:
        print("The queue is empty")
    else:
        ptr=currentQ
        printTime=0
        inQueue=0
        while ptr["next"]!=None:
            print(ptr["data"])              #optional line - shows all info for queue items
            #print(ptr["data"]["id"])       #optional line - shows specific queue items
            inQueue=inQueue+1
            printTime=printTime+int(ptr["data"]["time"])
            ptr=ptr["next"]
        print(ptr["data"])                  #optional line - shows all info for queue
        #print(ptr["data"]["id"])           #optional line - shows specific queue item
        printTime=printTime+int(ptr["data"]["time"])
        inQueue=inQueue+1
        print("There are",inQueue,"items in queue. Estimated total print time is",printTime,"seconds.")

'''
Function used to "print" first document in queue.
Parameter is the current queue.
Prints and removes the first document.
Returns updated queue.
'''
def printDoc(currentQ):
    if currentQ==None:
        print("There are no documents in queue")
    else:
        print("Printing job",currentQ["data"]["id"])
        currentQ=currentQ["next"]
    return currentQ

'''
Function used to removea specific document from the queue.
Parameters include ID for document to be removed and current queue.
Specific case when document to be removed is at the head.
Returns updated queue.
'''
def removeDoc(cmdInfo,currentQ):
    ptr=currentQ
    prevLoc={}
    print("Removing job",cmdInfo[1])
    if cmdInfo[1]==ptr["data"]["id"] and prevLoc=={}:
        currentQ=currentQ["next"]
    elif cmdInfo[1]!=ptr["data"]["id"] and prevLoc=={}:
        prevLoc=currentQ
        ptr=ptr["next"]
        while ptr["next"]!=None:
            if cmdInfo[1]==ptr["data"]["id"]:
                prevLoc["next"]=ptr["next"]
                break
            ptr=ptr["next"]
            prevLoc=prevLoc["next"]
    return currentQ

'''
Top level function.
Determines command and calls appropriate function.
Optional line allows pausing between each command
'''
def main():
    cmdList=readHtml()
    currentQ={"next":None}
    for i in range(len(cmdList)):
        command=cmdList[i][0]
        if command=="submit":
            currentQ=submit(cmdList[i],currentQ)
        elif command=="queue":
            queue(currentQ)
        elif command=="print":
            currentQ=printDoc(currentQ)
        elif command=="remove":
            currentQ=removeDoc(cmdList[i],currentQ)
        #input("Press enter to continue to the next command")
        print("")

main()


from __future__ import annotations

import datetime
from dataclasses import dataclass, field
import random
from typing import List, Dict, Any

from chess_manager.M import turn_model

MAX_STR_LEN = 122

def check_valid_int(user_int_input: Any) -> bool:
    """ Vérifie si l'input de l'utilisateur est un int valide. """
    try:
        int(user_int_input)
        return True
    except ValueError:
        return False

def check_valid_str(user_str_input: Any) -> bool | str:
    """ Vérifie si l'input de l'utilisateur est un str valide. """
    if not 0 < len(user_str_input) < MAX_STR_LEN:
        return f"You must enter from 1 to {MAX_STR_LEN} char."
    return True

TOURNAMENT_FORM_VALIDATOR: Dict = {
    'name': check_valid_str,
    'place': check_valid_str,
    'description': check_valid_str,
    'turn_nbr': check_valid_int,
    'player_nbr': check_valid_int
}

def _shuffle_player_list(player_list: List) -> List:
    """Retourne une nouvelle liste mélangée"""
    randomised_list = player_list[:]
    random.shuffle(randomised_list)
    return randomised_list

def _order_player_by_score(full_player_data: List) -> List:
    full_player_data.sort(key=lambda individual_player_data: individual_player_data[1], reverse=True)
    return full_player_data

def _reset_player_pairing(ordered_player_data: List) -> List:
    """Visite chaque joueur de la liste reçue et en reinitialise le compteur d'adversaires"""
    for player_data in ordered_player_data:
        player_data[0].clear_player_pairing()
    return ordered_player_data

def _make_player_pair(ordered_player_data: List) -> List:
    """
    Reçoit une liste de (joueurs, score) et retourne une liste de paire (joueurs, score) classé par score
    décroissant. Si tous les joueurs ont déjà joué les uns contre les autres, les historiques de pairage sont
    réinitialisés
    """
    player_pairs = list()
    working_list = ordered_player_data[:]

    adversary_index = 0
    current_pairing_player = working_list.pop(0)

    while len(working_list) > 0:
        if current_pairing_player[0].has_played_against(working_list[adversary_index][0]):
            adversary_index += 1
            if adversary_index >= len(working_list):
                print("Cannot make more player pair without player playing each other again")
                return _make_player_pair(_reset_player_pairing(ordered_player_data[:]))
            continue
        player_pairs.append((current_pairing_player, working_list.pop(adversary_index)))
        adversary_index = 0

        if len(working_list) < 1:
            break
        current_pairing_player = working_list.pop(0)
    return player_pairs

@dataclass
class TournamentM:
    """Représentation d'un tournoi d'échec"""
    name: str
    place: str
    turn_nbr: int = 4
    description: str = "No description"
    player_nbr: int = 0
    players: List = field(default_factory=list)
    turn_list: List = field(default_factory=list)
    start_date: str | None = None
    end_date: str | None = None
    tournament_id: int = -1

    def __post_init__(self) -> None:
        if self.start_date is None:
            self.start_date = datetime.datetime.now().strftime("%d/%m/%y %H:%M")

    def register_turn(self, turn: turn_model.TurnM) -> None:
        self.turn_list.append(turn)

    def get_current_turn_nbr(self) -> int:
        return len(self.turn_list)

    @property
    def is_finished(self) -> bool:
        if self.end_date is not None:
            return True
        if self.get_current_turn_nbr() < self.turn_nbr:
            return False
        return self.turn_list[-1].finished

    def end_tournament(self) -> None:
        if self.end_date is not None:
            return
        self.end_date = datetime.datetime.now().strftime("%d/%m/%y %H:%M")

    def get_next_turn_player_pair(self) -> List:
        if self.get_current_turn_nbr() > 0:
            return _make_player_pair(_order_player_by_score(self.turn_list[-1].get_turn_data()))
        player_list = _shuffle_player_list(self.players)
        player_data = [[player, 0] for player in player_list]
        return _make_player_pair(_order_player_by_score(player_data))

    def from_obj_to_dict(self) -> Dict:
        return {'name': self.name,
                'place': self.place,
                'turn_nbr': int(self.turn_nbr),
                'description': self.description,
                'player_nbr': int(self.player_nbr),
                'players': [player.player_id for player in self.players],
                'turn_list': [turn.turn_id for turn in self.turn_list],
                'start_date': self.start_date,
                'end_date': self.end_date,
                'tournament_id': self.tournament_id,
                }


# App Libraries
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
import plotly.graph_objs as go
import base64

# Replication strategy library
from Asian_Option_CRR import *

# Input of rep strat descriptions
from inputDescriptions import list_input

# Creating the app object from Dash library
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP], #theme for modern-looking buttons, sliders, etc
	                      external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML', "./assets/mathjax.js"], #usage of LaTeX in the app
	                      meta_tags=[{"content": "width=device-width"}] #content gets adapted to user device width
	                      )
server = app.server

# Author parameters
bg_color="#506784",
font_color="#F3F6FA"
author = "Michel Vanderhulst"
emailAuthor = "michelvanderhulst@hotmail.com"
supervisor = "Prof. Frédéric Vrins"
emailSupervisor = "frederic.vrins@uclouvain.be"
logo1path = "./pictures/1200px-Louvain_School_of_Management_logo.svg.png"
logo1URL  = "https://uclouvain.be/en/faculties/lsm"
logo2path = "./pictures/1280px-NovaSBE_Logo.svg.png"
logo2URL  = "https://www2.novasbe.unl.pt/en/"

# Creating the app header
def header():
    return html.Div(
                id='app-page-header',
                children=[
                    html.Div(children=[html.A(id='lsm-logo',
                                              children=[html.Img(style={'height':'6%', 'width':'6%'}, src='data:image/png;base64,{}'.format(base64.b64encode(open(f"{logo1path}", 'rb').read()).decode()))],
                                              href=f"{logo1URL}",
                                              target="_blank", #open link in new tab
                                              style={"margin-left":"10px"}
                                              ),

                                       html.Div(children=[html.H5("Asian option replication strategy app"),
                                                          html.H6("Cox-Ross-Rubinstein model")
                                                          ],
                                                 style={"display":"inline-block", "font-family":'sans-serif','transform':'translateY(+32%)', "margin-left":"10px"}),

                                       html.Div(children=[dbc.Button("About", id="popover-target", outline=True, style={"color":"white", 'border': 'solid 1px white'}),
                                                          dbc.Popover(children=[dbc.PopoverHeader("About"),
                                                                                dbc.PopoverBody([f"{author}",
                                                                                f"\n {emailAuthor}",
                                                                                html.Hr(),
                                                                                f"This app was built for my Master's Thesis, under the supervision of {supervisor} ({emailSupervisor})."]),
                                                                                ],

                                                                       id="popover",
                                                                       is_open=False,
                                                                       target="popover-target"),
                                                          ],
                                                 style={"display":"inline-block","font-family":"sans-serif","marginLeft":"55%", "margin-right":"10px"}),

                                     html.A(id="nova-logo",
                                            children=[html.Img(style={"height":"9%","width":"9%"}, src="data:image/png;base64,{}".format(base64.b64encode(open(f"{logo2path}","rb").read()).decode()))],
                                            href=f"{logo2URL}",
                                            target="_blank",
                                            style={}
                                            )
                                      ]
                             ,style={"display":"inline-block"}),
                         ],
                style={
                    'background': bg_color,
                    'color': font_color,
                    "padding-bottom": "10px",
                    "padding-top":"-10px"
                }
            )

# Creating the app body
def body():
    return html.Div(children=[
            html.Div(id='left-column', children=[
                dcc.Tabs(
                    id='tabs', value='About this App',
                    children=[
                        dcc.Tab(
                            label='About this App',
                            value='About this App',
                            children=html.Div(children=[
                                html.Br(),
                                html.H4('What is this app?', style={"text-align":"center"}),
                                html.P(f"""This app computes the replication strategy of Asian options on a set of given inputs, in the Cox-Ross-Rubinstein framework"""),
                                html.P(f"""The goal is to showcase that under the Cox-Ross-Rubinstein model assumptions (see "Model" tab), the price \(V_0\) given by the pricing formula is "arbitrage-free".
                                           Indeed, we show that in this case, it is possible to build a strategy that"""),
                                html.Ul([html.Li("Can be initiated with \(V_0\) cash at time \(0\)."),
                                         html.Li('Is self-financing (i.e., no need to "feed" the strategy  with extra cash later'),
                                         html.Li("Will deliver exactly the payoff of the option at maturity")
                                       ]),
                                html.Hr(),
                                html.P(["""
                                      The considered options are Asian options paying \(\psi(T)\) at maturity \(T\) where \(\psi(X)\) is the payoff function. Defining \(S_{ave}(T)\) as the underlying asset average price, we have \
                                      that for a call, the payoff function is \(\psi(T)=max(0,S_{ave}(T)-K)\) and for a put \(\psi(S_T)=max(0,K-S_{ave}(T))\) where K is the strike price."""]),
                                html.Hr(),
                                html.P("""Read more about options: https://en.wikipedia.org/wiki/Option_(finance)"""),
                            ])
                        ),
                        dcc.Tab(
                            label="Model",
                            value="Model",
                            children=[html.Div(children=[
                                html.Br(),
                                html.H4("Model assumptions", style={"text-align":"center"}),
                                "Its main assumptions are:",
                                html.Ul([html.Li("Does not consider dividends and transaction costs"),
                                         html.Li("The volatility and risk-free rate are assumed constant"),
                                         html.Li("Fraction of shares can be traded"),
                                         html.Li("The underlying asset can only either go 'up' by a fixed factor \(u<1\) or 'down' by \(0<d<1\)."),
                                         html.Li("The log-returns are independent at all periods")]),
                                html.Hr(),
                                html.H4("Underlying asset dynamics", style={"text-align":"center"}),
                                html.P([
                                        """
                                        Under CRR, the underlying asset follows a geometric random walk with drift \(\mu\delta\) and volatility \(\sigma\sqrt{\delta}\). The probability to go \
                                        'up' and 'down' are respectively \(p\) and \(q=1-p\) (under \(\mathcal{P}\)).The stock price at period \(i\) can be modeled as a function of a binomial \
                                        random variable, and the constant 'up' and 'down' factors computed: $$u=e^{\mu\delta+\sigma\sqrt{\delta}}$$ $$d=e^{\mu\delta-\sigma\sqrt{\delta}}$$ \
                                        The \(\mathcal{Q}\)-probability allowing the discounted stock price to be a martingale amounts to the \(\\tilde{p}\) value (under \(\mathcal{Q}\)) \
                                        that leads to the martingale property: \(\\tilde{p}=\\frac{e^{r}-d}{u-d}\).
                                        """]),
                                html.Hr(),
                                html.H4("Option price", style={"text-align":"center"}),
                                html.P(["""
                                        With the CRR, the stock tree and the option intrinsic value are easily computed at all nodes. Under the pricing measure \(\mathcal{Q}\), \
                                        the option price of a node is simply the discounted value of the two children nodes. The price tree is therefore filled backwards, starting from the leaves (i.e. the payoff).\
                                        The pricing formula is thus $$V_i=e^{-r\\delta}(V_{i+1}\\tilde{p}+V_{i+1}\\tilde{q})$$
                                        """]),
                                html.Hr(),
                                html.H4("Academic references", style={"text-align":"center"}),
                                html.Ul([html.Li("Vrins, F.  (2020). Course notes for LLSM2225:  Derivatives Pricing. (Financial Engineering Program, Louvain School of Management, Université catholique de Louvain)"),
                                         html.Li("Shreve, S. E. (2004). Stochastic Calculus for Finance I The Binomial Asset Pricing Model (2nd ed.). Springer Finance.")
                                       ]),
                                ])]),
                        #
                        #
                        dcc.Tab(
                            label="Appr-oach",
                            value="Methodology",
                            children=[html.Div(children=[
                                html.Br(),
                                html.H4("Methodology followed", style={"text-align":"center"}),
                                html.P([
                                    """
                                    To prove that the risk-neutral price is arbitrage-free, let us try to perfectly replicate it with a strategy. If the strategy is successfull, then
                                    the price is unique and therefore arbitrage-free. For an Asian option, we will also denote with \(s_0\) the stock price at time 0 and \(Y_n=\sum_{k=0}^{n}s_k\) the sum of the
                                    stock prices between times zero and n. From there, the payoff at time 3 will be \((\\frac{1}{4}Y_{3}-K)^+\) with strike K. Then, let \(V_n(s,y)\) be the price of
                                    the Asian option at node n if \(s_n=s\) and \(Y_n=y\).
                                    """]),
                                html.Hr(),
                                html.H4("Replicating portfolio", style={"text-align":"center"}),
                                html.P([
                                    """
                                    Let us start a replication strategy based on the option price: \(\Pi_{0} = V_{0}(s,y)\). The portfolio is composed of a cash account and a equity account.
                                     At each period, the number of shares to hold is given by $$\Delta_{n}(s,y) = \\frac{V_{n+1}(us, y + us)-V_{n+1}(ds, y + ds)}{(u-d)s}$$
                                     The initial amount of cash will be \(c_{0} = \Pi_{0} - \Delta_{0}(s,y)s_{0}\). At each node, a portfolio rebalancing is needed to ensure that the portfolio value is
                                     equal to the option price. Before the rebalancing, \(\Delta\) is the same from node to node, the cash account grew at the risk-free rate \(c_{n}=c_{n-1}e^{r}\),
                                     and the portfolio is the sum of both equity and cash positions $$\Pi_{n} = c_{n}+\Delta_{n}(s,y)s_{n}$$
                                     The rebalancing is done by updating the shares to hold $$\Delta_{n}(s,y) = \\frac{V_{n+1}(us, y + us)-V_{n+1}(ds, y + ds)}{(u-d)s}$$ and ensuring that the value
                                      of the strategy before and after the rebalancing is the same $$c_{n}=\pi_{n}-(\Delta_{n-1}-\Delta_{n})s_{n}$$
                                      The tree is computed forward, and will at all times replicate with option price. At the end of it we obtain the option payoff.
                                    """]),
                                ])]),
                        #
                        #
                        dcc.Tab(
                            label='Input',
                            value='Input',
                            children=html.Div(children=[
                                                html.Br(),
                                                #
                                                html.P(
                                                    """
                                                    Hover your mouse over any input to get its definition.
                                                    """
                                                ),
                                                dcc.Dropdown(
                                                    id='CallOrPut',
                                                    options=[{'label':'Asian Call option', 'value':"Call"},
                                                             {'label':'Asian Put option', 'value':"Put"}],
                                                    value='Call'),
                                                #
                                                html.Br(),
                                                #
                                                html.Div(children=[html.Label('Spot price', title=list_input["Spot price"], style={'font-weight': 'bold', "text-align":"left", "width":"25%",'display': 'inline-block'} ),
                                                                   dcc.Input(id="S", value=100, type='number', style={"width":"16%", 'display': 'inline-block'}),
                                                                   html.P("",id="message_S", style={"font-size":12, "color":"red", "padding":5, 'width': '55%', "text-align":"left", 'display': 'inline-block'})
                                                                  ]
                                                        ),
                                               html.Div(children=[html.Label("Strike", title=list_input["Strike"], style={'font-weight': 'bold',"text-align":"left", "width":"25%",'display': 'inline-block'} ),
                                                                 dcc.Input(id="K", value=100, type='number', style={"width":"16%", 'display': 'inline-block'}),
                                                                 html.P("",id="message_K", style={"font-size":12, "color":"red", "padding":5, 'width': '55%', "text-align":"left", 'display': 'inline-block'})
                                                                ],
                                                      ),
                                                html.Div(children=[html.Label("Drift", title=list_input["Drift"], style={'font-weight': 'bold', 'display': 'inline-block'}),
                                                                   html.Label(id="drift", style={'display': 'inline-block'}),
                                                                  ]),
                                                #
                                                dcc.Slider(id='mu', min=-0.30, max=0.30, value=0.10, step=0.01, marks={-0.30: '-30%', 0:"0%", 0.30: '30%'}),
                                                #
                                                html.Div([html.Label('Volatility', title=list_input["Volatility"], style={'font-weight': 'bold', "display":"inline-block"}),
                                                          html.Label(id="sigma", style={"display":"inline-block"}),]),
                                                #
                                                dcc.Slider(id='vol', min=0, max=0.5, step=0.01, value=0.15, marks={0:"0%", 0.25:"25%", 0.50:"50%"}),
                                                #
                                                html.Div([html.Label('Risk-free rate', title=list_input["Risk-free rate"], style={'font-weight': 'bold', "display":"inline-block"}),
                                                          html.Label(id="riskfree", style={"display":"inline-block"}),]),
                                                dcc.Slider(id='Rf', min=0, max=0.1, step=0.01, value=0.05, marks={0:"0%", 0.05:"5%", 0.1:"10%"}),
                                                #
                                                html.Div([html.Label('Maturity', title=list_input["Maturity"], style={'font-weight':'bold', "display":"inline-block"}),
                                                          html.Label(id="matu", style={"display":"inline-block"}),]),
                                                dcc.Slider(id='T', min=0.25, max=5,
                                                           marks={0.25:"3 months", 3:"3 years", 5:"5 years"}, step=0.25, value=3),
                                                #
                                                html.Br(),
                                                html.Div(children=[html.Label('Tree periods: ', title=list_input["Tree periods"], style={'font-weight': 'bold', "text-align":"left", "width":"30%",'display': 'inline-block'} ),
                                                                   dcc.Input(id="tree_periods", value=3, type='number', style={"width":"16%", 'display': 'inline-block'}),
                                                                   html.P("",id="message_tree", style={"font-size":12, "color":"red", "padding":5, 'width': '40%', "text-align":"left", 'display': 'inline-block'})
                                                                  ],
                                                        ),
                                                ])),
        ],),], style={'float': 'left', 'width': '25%', 'margin':"30px"}),
    ])

# Creating the app graphs
def graphs():
    return html.Div(id='right-column',
                    children=[
                        html.Br(),
                        html.Div([
                            html.Div(children=[dcc.Markdown(children=''' #### Cumulative sum of stock'''),
                                               dcc.Graph(id='option_intrinsic'),],
                                     style={"float":"right", "width":"45%", "display":"inline-block"}),
                            html.Div(children=[dcc.Markdown(children=''' #### Stock simulation (GRW) '''),
                                               dcc.Graph(id='stock_simul'),],
                                     style={"float":"right", "width":"55%", "display":"inline-block"}),
                                ]),
                        html.Div([
                            html.Div(children=[dcc.Markdown(children=''' #### Option price'''),
                                               dcc.Graph(id='option_price'),],
                                     style={"float":"right", "width":"45%", "display":"inline-block"}),
                            html.Div(children=[dcc.Markdown(children=''' #### Portfolio after rebalancing'''),
                                               dcc.Graph(id='port_details'),],
                                     style={"float":"right", "width":"55%", "display":"inline-block"}),
                                ]),
                        html.Div([
                            html.Div(children=[dcc.Markdown(children=''' #### Cash account after rebalancing'''),
                                               dcc.Graph(id='cash_acc'),],
                                     style={"float":"right", "width":"45%", "display":"inline-block"}),
                            html.Div(children=[dcc.Markdown(children=''' #### Shares held after rebalancing'''),
                                               dcc.Graph(id='nbr_shares'),],
                                     style={"float":"right", "width":"55%", "display":"inline-block"}),
                                ]),

                             ],
                    style={'float': 'right', 'width': '70%'})

# Building together the app layout: header, body and graphs
app.layout = html.Div(
                id='main_page',
                children=[
                    dcc.Store(id='memory-output'),
                    header(),
                    body(),
                    graphs(),
                         ],
                     )

# App interactivity 1: calling the replication strategy everytime the user changes an input
@app.callback(
	Output('memory-output', 'data'),
	[Input('CallOrPut', 'value'),
     Input("S","value"),
     Input("K", "value"),
     Input("Rf", "value"),
     Input("T","value"),
     Input("mu","value"),
     Input("vol", "value"),
     Input("tree_periods", "value"),])
def get_rep_strat_data(CallOrPut, S, K, Rf,T,mu,vol,tree_periods):
	nbrofsharesLabel, cashLabel, portfolioLabel, optionpriceLabel, intrinsicLabel, stocksLabel, edge_x, edge_y, node_x, node_y, u, d, probUp, probDown = RepStrat_Asian_Option_CRR(CallOrPut, S, K, Rf, T, mu, vol, tree_periods)

	return nbrofsharesLabel, cashLabel, portfolioLabel, optionpriceLabel, intrinsicLabel, stocksLabel, edge_x, edge_y, node_x, node_y, u, d, probUp, probDown

# App interactivity 2: plot of stock simulation + CRR u, d, probUp & probDown values
@app.callback(
    Output('stock_simul', 'figure'),
    [Input('memory-output', 'data'),])
def graph_stock_simul(data):
	nbrofsharesLabel, cashLabel, portfolioLabel, optionpriceLabel, intrinsicLabel, stocksLabel, edge_x, edge_y, node_x, node_y, u, d, probUp, probDown = data

	return{
       'layout': go.Layout(
        title={'yref':"paper",
        		'y':1,
        		"yanchor":"bottom"},
        #margin={"t":15},
        margin=dict(
                l=0,
                #r=50,
                #b=100,
                t=15,
                #pad=4
            ),
        # showlegend=False,
        xaxis={'showgrid': False, # thin lines in the background
    		   'zeroline': False, # thick line at x=0
               'visible': False,},  # numbers below}
        yaxis={'showgrid': False, # thin lines in the background
    		   'zeroline': False, # thick line at x=0
               'visible': False,},  # numbers below}
        legend=dict(
            x=0,
            y=0.8,
            traceorder='normal',
            bgcolor='rgba(0,0,0,0)'),
    ),
    	'data': [
	        go.Scatter(
	            x=edge_x,
	            y=edge_y,
	            mode='lines',
	            line=dict(width=0.5),
	            hoverinfo='none',
	            showlegend=False,
	            ),
	        go.Scatter(
	        	x=node_x,
	        	y=node_y,
	        	mode='markers+text',
	        	marker=dict(size=40),
	        	text=stocksLabel,
	        	showlegend=False,
	        	hoverinfo='none',
	        	),
	        go.Scatter(
	        	x=[None],
	        	y=[None],
	        	mode='markers',
	        	name=f'Up factor: {u}'
	        	),
	     	go.Scatter(
	        	x=[None],
	        	y=[None],
	        	mode='markers',
	        	name=f'Down factor: {d}'
	        	),
	     	go.Scatter(
	        	x=[None],
	        	y=[None],
	        	mode='markers',
	        	name=f'Prob up: {probUp}'
	        	),
	     	go.Scatter(
	        	x=[None],
	        	y=[None],
	        	mode='markers',
	        	name=f'Prob down: {probDown}'
	        	),
	    ],
}

# App interactivity 3: plot of portfolio (cash + equity accounts)
@app.callback(
    Output('port_details', 'figure'),
    [Input('memory-output', 'data'),])
def graph_portf_details(data):
		nbrofsharesLabel, cashLabel, portfolioLabel, optionpriceLabel, intrinsicLabel, stocksLabel, edge_x, edge_y, node_x, node_y, u, d, probUp, probDown = data

		return{
       'layout': go.Layout(
        title={'yref':"paper",
        		'y':1,
        		"yanchor":"bottom"},
        showlegend=False,
        margin=dict(
                l=0,
                #r=50,
                #b=100,
                t=15,
                #pad=4
            ),
        xaxis={'showgrid': False, # thin lines in the background
    		   'zeroline': False, # thick line at x=0
               'visible': False,},  # numbers below}
        yaxis={'showgrid': False, # thin lines in the background
    		   'zeroline': False, # thick line at x=0
               'visible': False,}  # numbers below}
    ),
    	'data': [
	        go.Scatter(
	            x=edge_x,
	            y=edge_y,
	            mode='lines',
	            line=dict(width=0.5),
	            hoverinfo='none',
	            ),
	        go.Scatter(
	        	x=node_x,
	        	y=node_y,
	        	mode='markers+text',
	        	marker=dict(size=40),
	        	text=portfolioLabel,
	        	hoverinfo='none',
	        	),
	    ],
}

# App interactivity 4: plot of number of shares to hold at all nodes
@app.callback(
    Output('nbr_shares', 'figure'),
    [Input('memory-output', 'data'),])
def graph_nbr_of_shares(data):
		nbrofsharesLabel, cashLabel, portfolioLabel, optionpriceLabel, intrinsicLabel, stocksLabel, edge_x, edge_y, node_x, node_y, u, d, probUp, probDown = data

		return{
       'layout': go.Layout(
        title={'yref':"paper",
        		'y':1,
        		"yanchor":"bottom"},
        showlegend=False,
        margin=dict(
                l=0,
                #r=50,
                #b=100,
                t=15,
                #pad=4
            ),        xaxis={'showgrid': False, # thin lines in the background
    		   'zeroline': False, # thick line at x=0
               'visible': False,},  # numbers below}
        yaxis={'showgrid': False, # thin lines in the background
    		   'zeroline': False, # thick line at x=0
               'visible': False,}  # numbers below}
    ),
    	'data': [
	        go.Scatter(
	            x=edge_x,
	            y=edge_y,
	            mode='lines',
	            line=dict(width=0.5),
	            hoverinfo='none',
				),
	        go.Scatter(
	        	x=node_x,
	        	y=node_y,
	        	mode='markers+text',
	        	marker=dict(size=40),
	        	text=nbrofsharesLabel,
	        	hoverinfo='none',
	        	),
	    ],
}

# App interactivity 5: cash account
@app.callback(
    Output('cash_acc', 'figure'),
    [Input('memory-output', 'data'),])
def graph_cash_account(data):
		nbrofsharesLabel, cashLabel, portfolioLabel, optionpriceLabel, intrinsicLabel, stocksLabel, edge_x, edge_y, node_x, node_y, u, d, probUp, probDown = data
		return{
       'layout': go.Layout(
        title={'yref':"paper",
        		'y':1,
        		"yanchor":"bottom"},
        showlegend=False,
        margin=dict(
                l=0,
                #r=50,
                #b=100,
                t=15,
                #pad=4
            ),
        xaxis={'showgrid': False, # thin lines in the background
    		   'zeroline': False, # thick line at x=0
               'visible': False,},  # numbers below}
        yaxis={'showgrid': False, # thin lines in the background
    		   'zeroline': False, # thick line at x=0
               'visible': False,}  # numbers below}
    ),
    	'data': [
	        go.Scatter(
	            x=edge_x,
	            y=edge_y,
	            mode='lines',
	            line=dict(width=0.5),
	            hoverinfo='none',
	            ),
	        go.Scatter(
	        	x=node_x,
	        	y=node_y,
	        	mode='markers+text',
	        	marker=dict(size=40),
	        	text=cashLabel,
	        	hoverinfo='none',
	        	),
	    ],
}

# App interactivity 6: option price through risk-neutral valuation
@app.callback(
    Output('option_price', 'figure'),
    [Input('memory-output', 'data'),])
def graph_option_pricee(data):
		nbrofsharesLabel, cashLabel, portfolioLabel, optionpriceLabel, intrinsicLabel, stocksLabel, edge_x, edge_y, node_x, node_y, u, d, probUp, probDown = data
		return{
       'layout': go.Layout(
        title={'yref':"paper",
        		'y':1,
        		"yanchor":"bottom"},
        showlegend=False,
        margin=dict(
                l=0,
                #r=50,
                #b=100,
                t=15,
                #pad=4
            ),
        xaxis={'showgrid': False, # thin lines in the background
    		   'zeroline': False, # thick line at x=0
               'visible': False,},  # numbers below}
        yaxis={'showgrid': False, # thin lines in the background
    		   'zeroline': False, # thick line at x=0
               'visible': False,}  # numbers below}
    ),
    	'data': [
	        go.Scatter(
	            x=edge_x,
	            y=edge_y,
	            mode='lines',
	            line=dict(width=0.5),
	            hoverinfo='none',
	            ),
	        go.Scatter(
	        	x=node_x,
	        	y=node_y,
	        	mode='markers+text',
	        	marker=dict(size=40),
	        	text=optionpriceLabel,
	        	hoverinfo='none',
	        	),
	    ],
}

# App interactivity 7: cumulative sum of stock price for the asian option average
@app.callback(
    Output('option_intrinsic', 'figure'),
    [Input('memory-output', 'data'),])
def graph_option_cumsum(data):
		nbrofsharesLabel, cashLabel, portfolioLabel, optionpriceLabel, intrinsicLabel, stocksLabel, edge_x, edge_y, node_x, node_y, u, d, probUp, probDown = data
		return{
       'layout': go.Layout(
        title={'yref':"paper",
        		'y':1,
        		"yanchor":"bottom"},
        showlegend=False,
        margin=dict(
                l=0,
                #r=50,
                #b=100,
                t=15,
                #pad=4
            ),
        xaxis={'showgrid': False, # thin lines in the background
    		   'zeroline': False, # thick line at x=0
               'visible': False,},  # numbers below}
        yaxis={'showgrid': False, # thin lines in the background
    		   'zeroline': False, # thick line at x=0
               'visible': False,}  # numbers below}
    ),
    	'data': [
	        go.Scatter(
	            x=edge_x,
	            y=edge_y,
	            mode='lines',
	            line=dict(width=0.5),
	            hoverinfo='none',
	            ),
	        go.Scatter(
	        	x=node_x,
	        	y=node_y,
	        	mode='markers+text',
	        	marker=dict(size=40),
	        	text=intrinsicLabel,
	        	hoverinfo='none',
	        	),
	    ],
}

# App input checks
@app.callback(Output('message_S', 'children'),
              [Input('S', 'value')])
def check_input_S(S):
    if S<0:
        return f'Cannot be lower than 0.'
    else:
        return ""

@app.callback(Output('message_K', 'children'),
              [Input('K', 'value')])
def check_input_K(K):
    if K<0:
        return f'Cannot be lower than 0.'
    else:
        return ""

@app.callback(Output('message_tree', 'children'),
              [Input('tree_periods', 'value')])
def check_input_K(tree__periods):
    if tree__periods<1:
        return f'Cannot be lower than 1.'
    else:
        return ""

# App input visuals
@app.callback(Output('drift', 'children'),
              [Input('mu', 'value')])
def display_value(value):
    return f': {int(value*100)}%'

@app.callback(Output('sigma', 'children'),
              [Input('vol', 'value')])
def display_value2(value):
    return f': {int(value*100)}%'

@app.callback(Output('riskfree', 'children'),
              [Input('Rf', 'value')])
def display_value3(value):
    return f': {int(value*100)}%'

@app.callback(Output('matu', 'children'),
              [Input('T', 'value')])
def display_value4(value):
    if value==0.25 or value==0.5 or value==0.75:
        return f": {int(value*12)} months"
    elif value == 1:
        return f': {value} year'
    else:
        return f': {value} years'

# Opens the "About" button top right
@app.callback(
    Output("popover", "is_open"),
    [Input("popover-target", "n_clicks")],
    [State("popover", "is_open")],
)
def toggle_popover(n, is_open):
    if n:
        return not is_open
    return is_open

# Main function, runs the app
if __name__ == '__main__':
    app.run_server(debug=True)


# -*- coding: utf-8 -*-
"""
Created on Fri Dec  4 11:20:09 2020

@author: KANNAN
"""

from flask import Flask, render_template, request
import emoji
#import sklearn
import pickle

model = pickle.load(open("diabetes_logreg.pkl", "rb"))

app = Flask(__name__)

@app.route('/')

def home():
    return render_template('Diabetes.html')

@app.route('/predict', methods = ["GET", "POST"])

def Diabetes():
    if request.method == "POST":

        Glucose = float(request.form["Glucose"])
        if (Glucose > 0 and Glucose < 140):
            Glucose_Prediabetes = 0
            Glucose_Diabetes = 0
        elif(Glucose >= 140 and Glucose < 200):
            Glucose_Prediabetes = 1
            Glucose_Diabetes = 0
        else:
            Glucose_Prediabetes = 0
            Glucose_Diabetes = 1

        BloodPressure = float(request.form["BloodPressure"])
        if (BloodPressure > 0 and BloodPressure < 80):
            BloodPressure_Hyper_St1 = 0
            BloodPressure_Hyper_St2 = 0
            BloodPressure_Hyper_Emer = 0
        elif (BloodPressure >=80 and BloodPressure < 90):
            BloodPressure_Hyper_St1 = 1
            BloodPressure_Hyper_St2 = 0
            BloodPressure_Hyper_Emer = 0
        elif (BloodPressure >= 90 and BloodPressure < 120):
            BloodPressure_Hyper_St1 = 0
            BloodPressure_Hyper_St2 = 1
            BloodPressure_Hyper_Emer = 0
        else:
            BloodPressure_Hyper_St1 = 0
            BloodPressure_Hyper_St2 = 0
            BloodPressure_Hyper_Emer = 1

        BMI = float(request.form["BMI"])
        if (BMI > 0 and BMI < 18.5):
            BMI_Normal = 0
            BMI_Overweight = 0
            BMI_Obese = 0
        elif (BMI >= 18.5 and BMI < 24.9):
            BMI_Normal = 1
            BMI_Overweight = 0
            BMI_Obese = 0
        elif (BMI >= 24.9 and BMI < 29.9):
            BMI_Normal = 0
            BMI_Overweight = 1
            BMI_Obese = 0
        else:
            BMI_Normal = 0
            BMI_Overweight = 0
            BMI_Obese = 1

        Insulin = float(request.form["Insulin"])
        if (Insulin >= 100 and Insulin <= 126):
            Insulin_Normal = 1
        else:
            Insulin_Normal = 0

        Pregnancies = float(request.form["Pregnancies"])
        Pregnancies = (Pregnancies - 3.874593) / 3.443637

        SkinThickness = float(request.form["SkinThickness"])
        SkinThickness = (SkinThickness - 29.180782) / 8.94289800

        DiabetesPedigreeFunction = float(request.form["DiabetesPedigreeFunction"])
        DiabetesPedigreeFunction = (DiabetesPedigreeFunction - 0.466471) / 0.333203

        Age = float(request.form["Age"])
        Age = (Age - 33.594463) / 12.016168

        prediction = model.predict([[
            Pregnancies,
            SkinThickness,
            DiabetesPedigreeFunction,
            Age,
            BMI_Normal,
            BMI_Overweight,
            BMI_Obese,
            BloodPressure_Hyper_St1,
            BloodPressure_Hyper_St2,
            BloodPressure_Hyper_Emer,
            Glucose_Prediabetes,
            Glucose_Diabetes,
            Insulin_Normal
            ]])

        output = prediction[0]
        if output == 0:
            text = "You are Healthy!!"+"\U0001F603"
        else:
            text = "You have Diabetes"+"\U0001F61E"

        return render_template('Diabetes.html',prediction_text = text)

    return render_template('Diabetes.html')

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


import os
import numpy as np
import warnings
from equilib import equi2cube
import cv2

import torch

from PIL import Image

def main():
    image_path = "./data/images/000001.jpg"

    equi_img = Image.open(image_path)
    img_mode = equi_img.mode

    equi_img = np.asarray(equi_img)
    print("equi_img: ", equi_img.shape)

    equi_img = np.transpose(equi_img, (2, 0, 1))
    print(equi_img.shape)

    rots = {
        "roll": 0,
        "pitch": 0,
        "yaw": 0
    }

    mode = "bilinear"
    # mode = "bicubic"
    # mode  = "nearest"

    equi_img_torch = torch.from_numpy(equi_img).to('cuda')

    #cube = equi2cube(equi = equi_img,cube_format="horizon", rots=rots, w_face=3368, z_down=False, mode=mode)
    cube = equi2cube(equi = equi_img_torch,cube_format="horizon", rots=rots, w_face=3368, z_down=False, mode=mode)

    cube = cube.to('cpu').detach().numpy().copy()

    print("cube.shape", cube.shape)
    print("type: ", type(cube))
    print("size: ", cube.size, "shape: ", cube.shape)
    cube = cube.transpose(1,2,0)
    out_image = Image.fromarray(cube, img_mode)

    out_path = "./data/results/00001.jpg"
    out_image.save(out_path)

if __name__ == "__main__":
    main()


from users import User
from userfile import UserFile
from places import Places
from get_poi import TripAdvisorApi
from poi_data import PoiData

# Initialise user object and conduct API_key_check
# If no API key, user given instructions to subscribe.
# API_key saved as a persistent environment variable in src/.env and
# application rebooted, If there is a stored API_key, application
# will proceed.
user = User()

# place selection
place = Places()
selected_region = place.select_region()

# userfile object creation to search past history and display result if exists
user_file = UserFile(selected_region, user.path)
user_file.searchfile = f"{user_file.region[0]}-{user_file.region[1]}.json"

# history check at region level
history_check = user_file.search_and_display_data(selected_region)

# history check at city level
if not history_check:
    user_file.city = place.select_city(user_file.region)
    user_file.searchfile = f"{user_file.city[0]}-{user_file.city[1]}.json"
    history_check = user_file.search_and_display_data(user_file.city)

# look up TripAdvisorAPI if region and city does not exist in cached file
# Extract and consolidate data
# Save and display data
if not history_check:
    search_api = TripAdvisorApi(user_file.region, user_file.city)
    api_results = search_api.poi_search()
    results_data = PoiData(api_results[0], api_results[1])
    results_data.extract()
    results_data.consolidate_categories()

    # Save and display data
    user_file.read_flag_and_save(results_data.place_info, api_results[2])


from django.contrib.auth.models import Group
from mf.crud.models import Dolar, HistoryOperations, Permisology
from mf.user.models import User
from django.utils import timezone
from datetime import date, datetime, timedelta

def convertToDecimalFormat(n):
    return n.replace('.', '').replace(',', '.')

def get_dollar():
    data = []
    try:
        dolar1 = Dolar.objects.using('default').get(pk=1)
        dl1 = float(dolar1.dolar)
    except:
        new_dolar1 = Dolar()
        new_dolar1.dolar = '1000000'
        new_dolar1.save()

        dolar1 = Dolar.objects.using('default').get(pk=1)
        dl1 = float(dolar1.dolar)

    try:
        dolar2 = Dolar.objects.using('default').get(pk=2)
        dl2 = float(dolar2.dolar)
    except:
        new_dolar2 = Dolar()
        new_dolar2.dolar = '1200000'
        new_dolar2.save()

        dolar1 = Dolar.objects.using('default').get(pk=1)
        dl1 = float(dolar1.dolar)

    data = {
        'dolar1': dl1,
        'dolar2': dl2
    }

    return data

def ValidatePermissions(perms, requestGroup):
    autorized = False
    try:
        permsRequired = perms
        pk = requestGroup.id

        group = Group.objects.get(pk=pk)
        permsRequired = perms

        for p in permsRequired:
            if not group.permissions.filter(codename=p).exists():
                autorized = False
                break
            else:
                autorized = True
    except:
        autorized = False
    return autorized

def RegisterOperation(db, user, action):
    date = timezone.localtime(timezone.now())
    result = 0
    try:
        h = HistoryOperations()
        h.datejoined = date.strftime('%Y-%m-%d | %H:%M:%S %p')
        h.userSession_id = user
        h.description = action
        h.save()
    except:
        result = 1
    return result

def get_q_events_today():
    data = 0
    try:
        start = date.today()
        end = start + timedelta(days=7)
        start_date = start.strftime('%Y-%m-%d')
        end_date = end.strftime('%Y-%m-%d')
        total = 0

        search = Permisology.objects.all()
        if len(start_date) and len(end_date):
            search = search.filter(day__range=[start_date, end_date])
            for s in search:
                total = int(total) + 1
            data = total
    except:
        pass
    return data

def get_events_today():
    data = []
    total = 0
    start = date.today()
    end = start + timedelta(days=7)
    start_date = start.strftime('%Y-%m-%d')
    end_date = end.strftime('%Y-%m-%d')

    search = Permisology.objects.all()
    if len(start_date) and len(end_date):
        search = search.filter(day__range=[start_date, end_date])
    for s in search:
        data.append(
            {
                'name': s.name,
                'description': s.description,
                'day': s.day.strftime('%Y-%m-%d'),
            }
        )
    return data


from os import *
from sys import *
from collections import *
from math import *

'''
    Following is the Binary Tree node structure:
    class TreeNode:
        def __init__(self, data=0, left=None, right=None):
            self.data = data
            self.left = left
            self.right = right
'''

def getInOrderTraversal(root):

    # Write your code here.
    stack = []
    result = []
    subtree = root
    while stack or subtree:
        if subtree:
            stack.append(subtree)
            subtree = subtree.left
        else:
            subtree = stack.pop()
            result.append(subtree.data)
            subtree= subtree.right
    return result

CodingNinjas/inorder traversal without recursion.py


'''
l = [i for i in range(len_string - len_sub + 1) if string[i:i + len_sub] == sub_string]
1.If you want to find the first index of the substring in the original string
l[0] is your destination

2.If you want to find every index of the snstring in the original
l[::] is what you want

3.If you want the number of times that the substring occurs in the given string
len(l) is what you want
'''
def count_substring(string, sub_string):
    len_string = len(string)
    len_sub = len(sub_string)
    n = sum([1 for i in range(len_string - len_sub + 1) if string[i:i + len_sub] == sub_string])
    return n

def count_substring(string, sub_string): #use recursion and a built in function
    if string.find(sub_string) < 0:
        return 0
    else:
        return 1 + count_substring(string[string.find(sub_string) + 1:], sub_string)

def hackerrankInString(s):
    # This function decide whether the substring in string(sub_string is Not secutive in the original string)
    # All the characters in substring in string(the same order also), but interrupted by some noises
    #Example: sub_string:hackerrank   string:hereiamstackerrank
    sub_string = 'hackerrank'
    length = len(sub_string)
    index = 0
    for c in s:
        if c == sub_string[index]:
            index += 1
            if index == length:
                return 'YES'
    return 'NO'


from __future__ import unicode_literals

import os
import shutil
import unittest
from doctpl.core import TemplateInfo

class TemplateInfoTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # setup TemplateInfo.
        TemplateInfo.CONFIG_DIR = os.path.join(os.getcwd(), '.doctpl')
        TemplateInfo.setup()
        # mkdir testdir.
        cls.testdir = os.path.join(
            TemplateInfo.CONFIG_DIR,
            'testdir',
        )
        os.mkdir(cls.testdir)

    @classmethod
    def tearDownClass(cls):
        shutil.rmtree(cls.testdir)

    def test_avaliable_templates(self):
        self.assertEqual(
            set(TemplateInfo.template_objects),
            {'template_a', 'template_b'},
        )

    def test_copy_for_not_existed_file(self):
        target_not_exist = os.path.join(
            self.testdir,
            'not_exist',
        )
        if os.path.exists(target_not_exist):
            os.remove(target_not_exist)

        template_object = TemplateInfo.template_objects['template_a']
        path = template_object.copy_to('./.doctpl/testdir/not_exist')

        self.assertEqual(path, target_not_exist)
        with open(path, 'r') as f:
            self.assertEqual(
                f.read(),
                "template_a's content.\n",
            )

    def test_copy_for_existed_file(self):
        target_exist = os.path.join(
            self.testdir, 'exist')
        # create empty file.
        open(target_exist, 'w').close()

        template_object = TemplateInfo.template_objects['template_a']
        with self.assertRaises(Exception) as context:
            template_object.copy_to('./.doctpl/testdir/exist')

        self.assertIn(
            'Already Existed',
            ''.join(context.exception.args),
        )

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


import re
from pprint import pprint
import csv
from decorator import to_log

if __name__ == '__main__':
    # читаем адресную книгу в формате CSV в список contacts_list
    with open("phonebook_raw.csv", encoding='utf-8') as f:
        rows = csv.reader(f, delimiter=",")
        contacts_list = list(rows)

    # rewriting phone numbers
    phone_num = r'(\+7|8)\s?\(?(\w{3})\)?\s?-?(\w{3})-?(\w{2})-?(\w{2})(\s?)(\(?((доб\.)\s(\w{4}))\)?)?'
    num_format = r'+7(\2)\3-\4-\5\6\9\10'

    i = 1
    form_list = contacts_list
    while i < len(contacts_list):
        form_list[i][5] = re.sub(phone_num, num_format, contacts_list[i][5])
        i += 1

    # pprint(form_list)

    # put names, surnames... as different elements

    @to_log(path=r"C:\Users\olesy\PycharmProjects\regex_decorated\log.txt")
    def arrange_names(some_list):
        new_list = some_list

        for n in range(0, 2):
            for i in range(1, 9):
                if re.search(r'\s', some_list[i][n]):
                    name = some_list[i][n].split(' ')
                    if n == 0:
                        if some_list[i][1] != '':
                            name.extend(some_list[i][3:])
                            new_list[i] = name
                        else:
                            name.extend(some_list[i][2:])
                            new_list[i] = name
                    else:
                        new_list[i][n] = name[0]
                        new_list[i][n + 1] = name[1]
                else:
                    pass

        return new_list

    arrange_names(form_list)


import random

def gtn():
    sec_num = random.randint(1, 1000)

    no_of_tries = 0

    print("Welcome to Guess The Number Game!")
    print("I'm thinking of a number between 1 and 1000. Can you guess it?")

    while True:
        user_guess = int(input("Enter your guess: "))
        no_of_tries += 1

        if user_guess < sec_num:
            print("Too low! Try again.")
        elif user_guess > sec_num:
            print("Too high! Try again.")
        else:
            print("Congratulations! You guessed the number in", no_of_tries, "tries.")
            break


import cv2
import numpy as np

img2 = cv2.imread("images.jpg")
img1 = cv2.imread("new quantum.PNG")

rows, cols, channels = img2.shape  # Reading image details
roi = img1[0:rows, 0:cols]

img2g = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)  # converting to grayscale
# defining mask , makes our logo black and background white
ret, mask = cv2.threshold(img2g, 220, 255, cv2.THRESH_BINARY_INV)

# cv2.imshow('mask',mask)

mask_inv = cv2.bitwise_not(mask)  # defining non_masked area
# adds our inv_mask to region of image of main image
img_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)
img_fg = cv2.bitwise_and(img2, img2, mask=mask)  # our logo after adding mask
dst = img_bg+img_fg  # we get our logo with our original image background
# swaps the region of image original image to logo with same backgound
img1[0:rows, 0:cols] = dst

cv2.imshow('res', img1)
cv2.imwrite('result.jpg', img1)
cv2.waitKey(0)
cv2.destroyAllWindows()


while(1) :
    data = list(map(int, input().split()))
    data.sort()

    if (data[0]==0) and (data[1]==0) and (data[2]==0) :
        break
    else :
        if data[2]**2 == data[0]**2 + data[1]**2 :
            print('right')
        else :
            print('wrong')

ALGORITHM/BAEKJOON/SOURCE/15. PrimeNumber(소수 판별)/4. 직각삼각형.py


A = [int(i) for i in open('26.txt') if ' ' not in i]
A.sort()
s = k = 0
while s < 8200 and k < 970:
    s += A[k]
    k += 1
s -= A[k-1] + A[k-2]
maxi = 0
for i in range(k-2, len(A)):
    if s + A[i] > 8200:
        break
    if maxi < A[i]:
        maxi = A[i]
print(k-1, maxi)


# A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words such that:

# The first word in the sequence is beginWord.
# The last word in the sequence is endWord.
# Only one letter is different between each adjacent pair of words in the sequence.
# Every word in the sequence is in wordList.
# Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.

# Example 1:

# Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
# Output: 5
# Explanation: One shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog" with 5 words.
# Example 2:

# Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
# Output: 0
# Explanation: The endWord "cog" is not in wordList, therefore there is no possible transformation.

# Constraints:

# 1 <= beginWord.length <= 10
# endWord.length == beginWord.length
# 1 <= wordList.length <= 5000
# wordList[i].length == beginWord.length
# beginWord, endWord, and wordList[i] consist of lowercase English letters.
# beginWord != endWord
# All the strings in wordList are unique.
from collections import deque
class Solution:
    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
        graph = {}
        for word in wordList:
            for i in range(len(word)):
                graph.setdefault(word[:i]+'*'+word[i+1:],[]).append(word)
        #print(graph)
        queue = deque([(beginWord,1)])
        visited = set([beginWord])
        while queue:
            curword, length = queue.popleft()
            #print(curword,length)
            if curword == endWord:
                return length
            for i in range(len(curword)):
                pattern = curword[:i]+'*'+curword[i+1:]
                #print("pattern",pattern)
                for nextWord in graph.get(pattern,[]):
                    #print(nextWord)
                    if nextWord not in visited:
                        queue.append((nextWord,length+1))
                        visited.add(nextWord)
        return 0


from homepageapp.models import ModelsNewSQL02Model
from django.conf import settings
from django.http import JsonResponse
from django.core.files.storage import FileSystemStorage
import os
from django.shortcuts import get_object_or_404, render
from django.core.paginator import Paginator
# repairOrder model was added on 11/5/2022. Deleted on 11/18/2022
from django.utils.translation import gettext_lazy as _
from django.contrib import messages
from django.utils import timezone
from django.shortcuts import render, redirect
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
import json
from django.contrib.auth.mixins import LoginRequiredMixin
from appointments.forms import AppointmentCreationForm, AppointmentImagesForm
from appointments.forms import AppointmentImagesForm, AppointmentImageFormSet
from appointments.models import AppointmentRequest, AppointmentImages
from django.views.generic import CreateView, FormView, TemplateView
from django.views.generic import DetailView
from django.views.generic import ListView
from formtools.wizard.views import WizardView
from django.urls import reverse_lazy
import calendar
from formtools.wizard.views import SessionWizardView
from appointments.models import APPT_STATUS_CANCELLED, APPT_STATUS_NOT_SUBMITTED

# 2023-04-10

def appointment_create_view_for_customer(request):
    # form = AppointmentCreationForm(request.POST or None)
    if request.method == 'POST':
        # form = AppointmentCreationForm(request.POST)
        form = AppointmentCreationForm(request.POST, request.FILES)
        image_formset = AppointmentImageFormSet(
            request.POST, request.FILES, user=request.user)
        image_form = AppointmentImagesForm(
            request.POST, request.FILES, user=request.user)
    # form = AppointmentCreationForm(request.POST)
        if form.is_valid():  # and image_formset.is_valid()
            # form.save()
            form.save(commit=False)
            appointment_data = form.cleaned_data
            # appointment_data.user = request.user
            appointment_data = json.dumps(appointment_data, default=str)
            request.session['appointment_data'] = appointment_data
            # request.session['images'] = [image_form.cleaned_data for image_form in image_formset]
            # request.session['submitted_form'] = json.dumps(form, default=dict)[0]
            # json.dumps(my_dictionary, indent=4, sort_keys=True, default=str)
            # appointment = form.save(commit=False)
            # appointment.appointment_requested_datetime = timezone.now()
            # appointment.save()
            # kwargs = {'appointment': appointment}
            # TODO: Send email to customer about service request status

            return redirect('appointments:appointment-preview-view')
        else:
            print(form.errors)  # print out the form errors
            # return redirect('appointment_preview', args=[appointment.appointment_id])
    else:
        form = AppointmentCreationForm
        image_formset = AppointmentImageFormSet(
            queryset=AppointmentImages.objects.none())
        image_form = AppointmentImagesForm()
    # context = {'form': form}
    context = {'form': form, 'image_formset': image_formset,
               'image_form': image_form}

    return render(request, 'appointments/10_appointment_create.html', context)

def appointment_preview_view(request):
    # appointment = kwargs.get('appointment', None)
    appointment_data = request.session.get('appointment_data')
    images = request.session.get('images')
    # submitted_form = request.session.get('submitted_form')
    if not appointment_data:
        return redirect('appointments:appointment-create-view')
    # 2024-04-10 using json.loads to load back the appointment_data.
    # otherwise appointment_data will be
    appointment_data = json.loads(appointment_data)
    images = json.loads(images)
# if request.method == 'GET':
    form = AppointmentCreationForm(appointment_data)
    appointment = AppointmentRequest(**appointment_data)
    context = {'form': form,
               'appointment': appointment,
               }
    if request.method == 'POST':
        appointment.appointment_status = APPT_STATUS_NOT_SUBMITTED
        appointment.save()
        messages.success(
            request, 'Appointment has been submitted successfuly.')
        request.session.pop('appointment_data')
        return redirect('appointments:appointment-success-view')
    return render(request, 'appointments/20_appointment_preview.html', context)

    # form = AppointmentCreationForm(request.POST)
    # if form.is_valid():
    #     appointment = AppointmentRequest(form.fields)
    #     appointment.save()
    #     messages.success(request, 'Appointment has been submitted successfuly.')
    #     request.session.pop('appointment_data')
    # # send_appointment_confirmation_email(appointment)
    #     return redirect('appointments:appointment-success')
    # return redirect('appointment_success')
    # form = AppointmentCreationForm(initial=kwargs)
    # return render(request, 'appointments/02-appointment-preview.html', {'form': form})
    # elif 'confirm' in request.POST:
    #     form = AppointmentCreationForm(request.POST)
    #     if form.is_valid():
    #         appointment = form.save(commit=False)
    #         appointment.appointment_status = 'C'
    #         appointment.save()
    #         # Send confirmation email -- pending
    #         # 2023-04-10
    #         # subject = 'Appointment Confirmed'
    #         # html_message = render_to_string('appointment_confirmation_email.html', {'appointment': appointment})
    #         # plain_message = strip_tags(html_message)
    #         # from_email = 'Your Company <noreply@yourcompany.com>'
    #         # to_email = appointment.appointment_email
    #         # send_mail(subject, plain_message, from_email, [to_email], html_message=html_message)

    # # else:
    # #     return redirect('appointment-create-view')
    # # form = AppointmentCreationForm()

    # context = {'form': form}
    # return render(request, 'appointments/02-appointment-preview.html', context)
    # return redirect('appointment-create-view')

def appointment_success(request):
    return render(request, 'appointments/30_appointment_creation_success.html')

# version 2 of appointment creation.

class AppointmentCreateView(SessionWizardView):
    # def get_template_names(self):
    #     return ['appointments/12_appointment_create_v2_step_1.html', 'appointments/13_appointment_create_v2_step_2.html']
    template_name = 'appointments/11_appointment_create_v2.html'

    file_storage = FileSystemStorage(location=os.path.join(
        settings.DEFAULT_FILE_STORAGE, 'appointment_images'))
    form_list = [
        ('upload images', AppointmentImageFormSet),
        ('new_appointment', AppointmentCreationForm),
    ]

    success_url = reverse_lazy('appointments:appointment-preview-view')

    def done(self, form_list, **kwargs):
        image_formset, appointment_form = form_list
        appointment_form.save(commit=False)
        appointment_data = appointment_form.cleaned_data
        images = image_formset.save(commit=False)
        appointment_data = json.dumps(appointment_data, default=str)
        images = json.dumps(images, default=str)
        self.request.session['appointment_data'] = appointment_data
        self.request.session['images'] = images
        # talent_data = {}
        #     talent_data.update(form.cleaned_data)
        # # # Create the talent record
        # # talent = TalentsModel.objects.create(**talent_data)
        # talent = TalentsModel(**talent_data)
        # Get the current user
        # Add a success message
        # messages.success(self.request, "Talent created successfully.")
        # return redirect("talent_management:talent_list", {'talent': talent})
        return redirect('appointments:appointment-preview-view')

class AppointmentPreviewView(FormView):
    template_name = 'appointments/20_appointment_preview.html'
    # form_class = AppointmentCreationForm
    success_url = reverse_lazy('appointments:appointment-success-view')

    def form_valid(self, form):
        self.request.session['appointment_data'] = self.request.POST
        return super().form_valid(form)

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['data'] = self.request.session.get('appointment_data', {})
        return kwargs

class AppointmentSuccessView(TemplateView):
    template_name = 'appointments/30_appointment_creation_success.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        appointment_data = self.request.session.get('appointment_data', {})
        if appointment_data:
            appointment = AppointmentRequest(**appointment_data)
            appointment.save()
            self.request.session['appointment_data'] = None
            context['appointment'] = appointment
        return context

class AppointmentListView(LoginRequiredMixin, ListView):
    model = AppointmentRequest
    context_object_name = 'appointments'
    template_name = 'appointments/50_appointment_list.html'
    login_url = reverse_lazy('internal_users:internal_user_login')

    def get_queryset(self):
        # `__` double undestore..more researched are needed.
        qs = AppointmentRequest.objects.prefetch_related(
            'appointment_repair_order').exclude(appointment_status=APPT_STATUS_CANCELLED).all()
        # qs=qs.filter(appointment_status=APPT_STATUS_CANCELLED)
        # select_related('repair_order_customer').prefetch_related('repair_order_customer__addresses')
        # repair order phase defines the WIP (work-in-progress) caegory. 6 means invoice.

        return qs

class AppointmentDetailView(DetailView):
    model = AppointmentRequest
    context_object_name = 'appointment'
    template_name = 'appointments/60_appointment_detail.html'
    # login_url = '/users/login'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['form'] = AppointmentImagesForm()
        return context

    def post(self, request, *args, **kwargs):
        appointment = self.get_object()
        form = AppointmentImagesForm(request.POST, request.FILES)
        if form.is_valid():
            image = form.save(commit=False)
            image.appointment = appointment
            image.save()
        return self.get(request, *args, **kwargs)

    # def post(self, request, *args, **kwargs):
    #     talent = self.get_object()
    #     form = TalentDocumentsForm(request.POST, request.FILES)
    #     if form.is_valid():
    #         document = form.save(commit=False)
    #         document.talent = talent
    #         document.save()
    #     return self.get(request, *args, **kwargs)

    # def get_queryset(self):
    #     queryset = super().get_queryset()
    #     return queryset.filter(user=self.request.user)

class AppointmentDetailByConfirmationIdView(AppointmentDetailView):
    def get_queryset(self):
        queryset = AppointmentRequest.objects.filter(
            appointment_confirmation_id=self.args['appointment_confirmation_id'])
        return queryset.filter(user=self.request.user)

def appointment_get_vehicle_models(request, make_id):
    models = ModelsNewSQL02Model.objects.filter(
        make_id=make_id).all().order_by('model_name')
    model_dict_list = list(models.values('model_id', 'model_name'))
    model_tuple_list = [(model.pk, model.model_name) for model in models]
    # return JsonResponse(model_tuple_list, safe=False)
    return JsonResponse(model_dict_list, safe=False)

def appointment_image_list(request, pk):
    appointment = AppointmentRequest.objects.get(pk=pk)
    images = AppointmentImages.objects.filter(
        image_is_active=True).filter(appointment=appointment).all()
    return render(request, 'appointments/70_appointment_image_list.html', {'images': images, 'appointment': appointment})

def appointment_image_soft_delete(request, image_id):
    image = get_object_or_404(AppointmentImages, image_id=image_id)
    image.image_is_active = False
    image.save()
    messages.add_message(request, messages.INFO,
                         "Image selected has been deleted.")
    return redirect('appointment:appointment_image_list')


"""
@author Joe

This file contains some pretty functions
"""

def get_top_k_indexes_of_list(target_list, k, is_max=True, min_value=None):
    """
    get the top k indexes of elements in list

    Example:
    Problem: I have a list say a = [5,3,1,4,10],
            and I need to get a index of top two values of the list viz 5 and 10.
            Is there a one-liner that python offers for such a case?
    Usage: get_top_k_indexes_of_list(target_list=a, k=2, is_max=True)

    link: https://stackoverflow.com/questions/13070461/get-index-of-the-top-n-values-of-a-list-in-python

    :param target_list: target list
    :param k: the number of indexes
    :param is_max: True means max else False means min
    :param min_value: if min_value is not None
            filter the indexes whose value less than or equals to min_value
    :return: a list of indexes
    """
    indexes = sorted(range(len(target_list)), key=lambda i: target_list[i], reverse=is_max)[:k]
    result = list()
    if min_value is not None:
        for index in indexes:
            if target_list[index] <= min_value:
                break
            result.append(index)
    else:
        result = indexes
    return result

def get_elements_from_list(target_list, indexes):
    """
    get elements from target_list by indexes
    :param target_list: target list
    :param indexes: a list of indexes
    :return: a list of elements
    """
    elements = [target_list[i] for i in indexes]
    return elements


import argparse

from alarm import __version__
from alarm.constants import ALLOWED_EXTENSIONS, ON_WINDOWS

def parse_args(args):
    """Passing in args makes this easier to test:
    https://stackoverflow.com/a/18161115
    """
    parser = argparse.ArgumentParser(
        description="Play an alarm after N minutes",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )

    duration_group = parser.add_mutually_exclusive_group(required=True)
    duration_group.add_argument(
        "-s", "--seconds", type=int, help="Number of seconds before playing alarm"
    )
    duration_group.add_argument(
        "-m", "--minutes", type=int, help="Number of minutes before playing alarm"
    )

    run_mode_group = parser.add_mutually_exclusive_group()
    if not ON_WINDOWS:
        run_mode_group.add_argument(
            "-b",
            "--background",
            action="store_true",
            default=False,
            help="Run timer in the background",
        )
    run_mode_group.add_argument(
        "-d",
        "--display_timer",
        action="store_true",
        default=False,
        help="Show timer in console",
    )

    alarm_file_group = parser.add_mutually_exclusive_group()
    alarm_file_group.add_argument(
        "-l",
        "--song_library",
        help=(
            "Take a random song from a song library directory, "
            f"supported formats: {', '.join(sorted(ALLOWED_EXTENSIONS))}"
        ),
    )
    alarm_file_group.add_argument(
        "-f", "--file", help="File path to song to play as alarm"
    )
    alarm_file_group.add_argument(
        "-M", "--message", help="Set an audio message to play for alarm"
    )
    parser.add_argument(
        "-v", "--version", action="version", version=f"%(prog)s {__version__}"
    )
    parser.add_argument("-t", "--timeout", type=int, help="Stop alarm after N seconds")
    parser.add_argument(
        "-r",
        "--repeat",
        type=int,
        default=1,
        help="Repeat alarm cycle N times (only works in foreground)",
    )
    return parser.parse_args(args)


import pandas as pd
import xml.etree.ElementTree as ET

# Load the XML data
tree = ET.parse('statement_short.xml')
root = tree.getroot()

# Define a function to extract data from the XML elements
def extract_data(elem):
    data = {}
    for child in elem:
        if len(child) == 0:
            data[child.tag] = child.text
        else:
            data[child.tag] = extract_data(child)
    return data

# Extract the data from the XML and create a DataFrame
data = []
for elem in root:
    data.append(extract_data(elem))
df = pd.DataFrame(data)
df1 = pd.read_xml('statement_short.xml')

# Display the DataFrame
print(df1)


import torch
import torch.nn as nn

class ChannelAttention(nn.Module):
    def __init__(self, in_planes, ratio=16):
        super(ChannelAttention, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.max_pool = nn.AdaptiveMaxPool2d(1)

        self.fc = nn.Sequential(nn.Conv2d(in_planes, in_planes // 16, 1, bias=False),
                                nn.ReLU(),
                                nn.Conv2d(in_planes // 16, in_planes, 1, bias=False))
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        avg_out = self.fc(self.avg_pool(x))
        max_out = self.fc(self.max_pool(x))
        out = avg_out + max_out
        return self.sigmoid(out)

class SpatialAttention(nn.Module):
    def __init__(self, kernel_size=7):
        super(SpatialAttention, self).__init__()

        self.conv1 = nn.Conv2d(2, 1, kernel_size, padding=kernel_size // 2, bias=False)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        avg_out = torch.mean(x, dim=1, keepdim=True)
        max_out, _ = torch.max(x, dim=1, keepdim=True)
        x = torch.cat([avg_out, max_out], dim=1)
        x = self.conv1(x)
        return self.sigmoid(x)

class conv_block(nn.Module):
    def __init__(self, in_c, out_c):
        super().__init__()

        self.conv1 = nn.Conv2d(in_c, out_c, kernel_size=3, padding=1)
        self.in1 = nn.InstanceNorm2d(out_c)

        self.conv2 = nn.Conv2d(out_c, out_c, kernel_size=3, padding=1)
        self.in2 = nn.InstanceNorm2d(out_c)

        self.relu = nn.ReLU()

        self.ca = ChannelAttention(out_c)
        self.sa = SpatialAttention()

    def forward(self, inputs):
        x = self.conv1(inputs)
        x = self.in1(x)
        x = self.relu(x)

        x = self.conv2(x)
        x = self.in2(x)
        x = self.relu(x)

        x = self.ca(x) * x
        x = self.sa(x) * x

        return x

class encoder_block(nn.Module):
    def __init__(self, in_c, out_c):
        super().__init__()

        self.conv = conv_block(in_c, out_c)
        self.pool = nn.MaxPool2d((2, 2))

    def forward(self, inputs):
        x = self.conv(inputs)
        p = self.pool(x)

        return x, p

class decoder_block(nn.Module):
    def __init__(self, in_c, out_c):
        super().__init__()

        self.up = nn.ConvTranspose2d(in_c, out_c, kernel_size=2, stride=2, padding=0)
        self.conv = conv_block(out_c + out_c, out_c)

    def forward(self, inputs, skip):
        x = self.up(inputs)
        x = torch.cat([x, skip], axis=1)
        x = self.conv(x)
        return x

class build_unet(nn.Module):
    def __init__(self):
        super().__init__()

        """ Encoder """
        self.e1 = encoder_block(3, 64)
        self.e2 = encoder_block(64, 128)
        self.e3 = encoder_block(128, 256)
        self.e4 = encoder_block(256, 512)

        """ Bottleneck """
        self.b1 = conv_block(512, 640)
        self.b2 = conv_block(640, 768)
        self.b3 = conv_block(768, 896)
        self.b4 = conv_block(896, 1024)

        """ Decoder """
        self.d1 = decoder_block(1024, 512)
        self.d2 = decoder_block(512, 256)
        self.d3 = decoder_block(256, 128)
        self.d4 = decoder_block(128, 64)

        """ Classifier """
        self.outputs = nn.Conv2d(64, 1, kernel_size=1, padding=0)

    def forward(self, inputs):
        """ Encoder """
        s1, p1 = self.e1(inputs)
        s2, p2 = self.e2(p1)
        s3, p3 = self.e3(p2)
        s4, p4 = self.e4(p3)

        """ Bottleneck """
        b = self.b1(p4)
        b = self.b2(b)
        b = self.b3(b)
        b = self.b4(b)

        """ Decoder """
        d1 = self.d1(b, s4)
        d2 = self.d2(d1, s3)
        d3 = self.d3(d2, s2)
        d4 = self.d4(d3, s1)

        outputs = self.outputs(d4)

        return outputs