from pyxavi.config import Config
from pyxavi.logger import Logger
from janitor.lib.system_info import SystemInfo
from janitor.lib.system_info_templater import SystemInfoTemplater
from janitor.lib.publisher import Publisher
from janitor.lib.mastodon_helper import MastodonHelper
from janitor.objects.queue_item import QueueItem
from janitor.objects.message import Message, MessageType
from flask import Flask
from flask_restful import Resource, Api, reqparse

app = Flask(__name__)
api = Api(app)

DEFAULT_MESSAGE_TYPE = str(MessageType.NONE)

class ListenSysInfo(Resource):
    '''
    Listener from remote SysInfo Report requests to log
    '''

    def __init__(self):
        self._config = Config()
        self._logger = Logger(self._config).getLogger()
        self._sys_info = SystemInfo(self._config)
        self._parser = reqparse.RequestParser()
        self._parser.add_argument(
            'sys_data', type=dict, required=True, help='No sys_data provided', location='json'
        )
        self._logger.info("Init SysInfo Listener")

        super(ListenSysInfo, self).__init__()

    def post(self):
        """
        This is going to receive the POST request
        """

        self._logger.info("Run SysInfo Listener app")

        # Get the data
        args = self._parser.parse_args()
        if "sys_data" in args:
            sys_data = args["sys_data"]
        else:
            return {
                "error": "Expected dict under a \"sys_data\" variable was not present."
            }, 400

        # If there is no issue, just stop here.
        if not self._sys_info.crossed_thresholds(sys_data, ["hostname"]):
            self._logger.info("No issues found. Ending here.")
            return 200

        # Make it a message
        message = SystemInfoTemplater(self._config).process_report(sys_data)

        # Publish the queue
        mastodon = MastodonHelper.get_instance(self._config)
        publisher = Publisher(self._config, mastodon)
        self._logger.info("Publishing one message")
        publisher.publish_one(QueueItem(message))

        self._logger.info("End.")
        return 200

class ListenMessage(Resource):
    '''
    Listener from remote Message requests to log
    '''

    def __init__(self):
        self._config = Config()
        self._logger = Logger(self._config).getLogger()
        self._parser = reqparse.RequestParser()
        self._parser.add_argument(
            'summary',
            # type = str,
            # required = True,
            # help = 'No message provided',
            location='form'
        )
        self._parser.add_argument(
            'message',
            # type = str,
            # required = True,
            # help = 'No message provided',
            location='form'
        )
        self._parser.add_argument(
            'hostname',
            # type = str,
            # required = True,
            # help = 'No hostname provided',
            location='form'
        )
        self._parser.add_argument(
            'message_type',
            # type = str,
            # required = True,
            # help = 'No message provided',
            location='form'
        )
        self._logger.info("Init Message Listener Listener")

        super(ListenMessage, self).__init__()

    def post(self):
        """
        This is going to receive the POST request
        """

        self._logger.info("Run Message Listener app")

        # Get the data
        args = self._parser.parse_args()
        if "summary" in args and args["summary"] is not None:
            summary = args["summary"]
        else:
            summary = None
        if "message_type" in args and args["message_type"] is not None:
            message_type = args["message_type"]
        else:
            message_type = DEFAULT_MESSAGE_TYPE
        if "message" in args and args["message"] is not None:
            text = args["message"]
        else:
            return {
                "error": "Expected string under a \"message\" variable was not present."
            }, 400
        if "hostname" in args and args["hostname"] is not None:
            hostname = args["hostname"]
        else:
            return {
                "error": "Expected string under a \"hostname\" variable was not present."
            }, 400

        # Build the message
        icon = MessageType.icon_per_type(message_type)
        if not summary:
            message = Message(text=f"{icon} {hostname}:\n\n{text}")
        else:
            message = Message(summary=f"{icon} {hostname}:\n\n{summary}", text=f"{text}")

        # Publish the queue
        mastodon = MastodonHelper.get_instance(self._config)
        publisher = Publisher(self._config, mastodon)
        self._logger.info("Publishing one message")
        publisher.publish_one(QueueItem(message))

        self._logger.info("End.")
        return 200

api.add_resource(ListenSysInfo, '/sysinfo')
api.add_resource(ListenMessage, '/message')

if __name__ == '__main__':
    app.run(
        host=Config().get("app.service.listen.host"),
        port=Config().get("app.service.listen.port")
    )


from dataclasses import dataclass
import cv2
import math
import numpy as np
import base64
import struct
from numpy import int16, int8, uint16, uint8, uint32, int32

def drawHor(frame, theta, phi):
    widAngle = 65
    heiAngle = widAngle*3.0/4.0
    height, width, channels = frame.shape
    pm = (width/2, height/2)
    pm = (pm[0], pm[1]+theta/widAngle*height)
    r = width * .25
    p1 = (int(pm[0]-r*math.cos(phi/57.0)), int(pm[1]+r*math.sin(phi/57.0)))
    p2 = (int(pm[0]+r*math.cos(phi/57.0)), int(pm[1]-r*math.sin(phi/57.0)))
    cv2.line(frame,p1,p2,(0,255,0),3)
    return frame

def drawRange(frame, range):
    height, width, channels = frame.shape
    L = 12
    R = 28
    B = 50
    Um = height - B
    min = 50
    max = 1000
    if (range > 1000):
        range=1000
    if (range < 50):
        range=50

    U = int((Um-B)*range/(max-min))
    color = (0, int(range/(max-min)*255), 255-int(range/(max-min)*255))
    frame = cv2.rectangle(frame, (L,B), (R, U), color, -1)
    return frame

def drawState(frame,state):
    height, width, channels = frame.shape
    text = ''
    if (state == 0x01):
        text = 'MAN'
    font = cv2.FONT_HERSHEY_SIMPLEX
    org = (width-150, height-50)
    fontScale = 1
    color = (255, 0, 0)
    thickness = 2
    frame = cv2.putText(frame, text, org, font, fontScale, color, thickness, cv2.LINE_AA)
    return frame

@dataclass
class tlmAHRS:
    time: uint32 = 0
    phi: int16 = 0
    theta: int16 = 0
    psi: int16 = 0
    P: int16 = 0
    Q: int16 = 0
    R: int16 = 0
    accX: int16 = 0
    accY: int16 = 0
    accZ: int16 = 0
    smiec: int16 = 0 #?????

@dataclass
class dataAHRS:
    time: float = 0.0
    phi: float = 0.0
    theta: float = 0.0
    psi: float = 0.0
    P: float = 0.0
    Q: float = 0.0
    R: float = 0.0
    accX: float = 0.0
    accY: float = 0.0
    accZ: float = 0.0

def encodeTlm(line):
    bytes = base64.b64decode(line)
    tlm = struct.unpack('@Lhhhhhhhhhh',bytes)
    tlm = tlmAHRS(tlm[0], tlm[1], tlm[2], tlm[3], tlm[4], tlm[5], tlm[6], tlm[7], tlm[8], tlm[9], tlm[10])
    return tlm


# -*- coding: utf-8 -*-
"""
Created on Thu Apr 12 15:42:52 2018

@author: liuyang
"""

from datetime import datetime
import numpy as np
import pandas as pd
import MYSQLPD as sql
import math

def DatetoDigit(date):
    digitdate=date.year*10000+date.month*100+date.day
    return digitdate

#读取交易日期列表
def GetTradeDates(BegT,EndT,Freq='D'):
    TDs=pd.read_csv(r"D:\Sam\PYTHON\Tradedates.csv",encoding='utf_8_sig',parse_dates=[0])
    BTTD=TDs[(TDs['TRADEDATE']>=BegT)&(TDs['TRADEDATE']<=EndT)]
    if Freq=='W':
        TDDF=BTTD[['TRADEDATE','IsWeekEnd']]
        TDList=TDDF[TDDF['IsWeekEnd']==1].TRADEDATE.tolist()
        return TDList
    elif Freq=='D':
        TDList=BTTD[['TRADEDATE']].TRADEDATE.tolist()

        return TDList

"""得到每日收益率数据的函数"""
def GetDayReturn(date):
        digitdate=DatetoDigit(date)
        dbname1='tyb_stock'
        #SQLstrHead1='select * from stockdaily_basic where TRADEDATE='
        SQLstrHead1='select TRADEDATE,STOCKID,BFQCLOSE,HFQCLOSE,DAYRETURN,TRADABLE from stockdaily_basic where TRADEDATE='
        SQLstr1=SQLstrHead1+str(digitdate)
        #SQLstr2=SQLstrHead2+str(digitPD)
        DF=sql.toDF(SQLstr1,dbname1)
        DF=DF.rename(columns={'DAYRETURN':'RETURN'})
        #DF=DF[['TRADEDATE','STOCKID','BFQCLOSE','DAYRETURN','TRADABLE']]
        #DF=DF.loc[(DF['SWLV1']!=0)&(DF['TRADABLE']==1)]
        print(date)
        return DF

"""得到指定间隔区间收益率的函数"""
def GetIntervalReturn(d1,d2):

    DF1=GetDayReturn(d1)
    DF2=GetDayReturn(d2)
    DFL=DF1[['STOCKID','HFQCLOSE']]
    DFL=DFL.rename(columns={'HFQCLOSE':'LASTCLOSE'})
    DFM=pd.merge(DF2, DFL, how='left',on='STOCKID')
    DFM['RETURN']=(DFM['HFQCLOSE']-DFM['LASTCLOSE'])*100/DFM['HFQCLOSE']
    DFR=DFM[['TRADEDATE','STOCKID','HFQCLOSE','LASTCLOSE','TRADABLE','RETURN']]
    print(d2)

    return DFR

"""得到某一日的因子数据"""
def GetFactor(date):
        digitdate=DatetoDigit(date)
        dbname1='tyb_stock'
        #SQLstrHead1='select * from stockdaily_basic where TRADEDATE='
        SQLstrHead1='select TRADEDATE,STOCKID,MARKETVALUE,SWLV1,SWLV2,TRADABLE,BP from stockdaily_factor1 where TRADEDATE='
        SQLstr1=SQLstrHead1+str(digitdate)
        #SQLstr2=SQLstrHead2+str(digitPD)
        DF=sql.toDF(SQLstr1,dbname1)
        print(date)
        #DF=DF.rename(columns={'DAYRETURN':'RETURN'})
        #DF=DF[['TRADEDATE','STOCKID','BFQCLOSE','DAYRETURN','TRADABLE']]
        #DF=DF.loc[(DF['SWLV1']!=0)&(DF['TRADABLE']==1)]
        return DF

starttime = datetime.now()
#设定回测起止日期
BegT=datetime(2007,1,1)
EndT=datetime(2017,12,31)

TDList=GetTradeDates(BegT,EndT,Freq='D')
TDNum=len(TDList)

AllData=pd.DataFrame()

#Data=[GetDayReturn(TDList[i]) for i in range(0,TDNum)]  #每日收益率数据
#Data=[GetIntervalReturn(TDList[i-1],TDList[i]) for i in range(1,TDNum)]  #每日收益率数据
Data=[GetFactor(TDList[i]) for i in range(0,TDNum)]

AllData=pd.concat(Data,ignore_index=True)

"""
for i in range(0,TDNum):
    d0=TDList[i]
    ASDF=GetDayReturn(d0)
    AllData=pd.concat([AllData,ASDF])
    print (d0)
"""
"""
for i in range(1,TDNum):
    d0=TDList[i-1]
    d1=TDList[i]
    ASDF=GetIntervalReturn(d0,d1)
    AllData=pd.concat([AllData,ASDF])
    print (d1)
"""
stoptime = datetime.now()
print(stoptime-starttime)


from django.db import models, transaction
from django.dispatch import receiver
from django.db.models.signals import post_delete
from api.espo_api_client import EspoClientMixin
from django.conf import settings
from petuni_main.celery import app

CRM_DO_NOTHING = 0
CRM_SOFT_DELETE = 1
CRM_TRUE_DELETE = 2

class CRMSignalMixin(EspoClientMixin, models.Model):
    crm_id = models.CharField(max_length=18, null=True, blank=True, unique=True)
    crm_api_path = None
    serializer_class = None
    request_type = None
    queryset = None
    sync_delete = CRM_DO_NOTHING # 0 не делаем ничего, 1 - шлем PATCH, 2 - шлем DELETE

    def get_crm_api_action(self):
        """
        Возвращает action для запроса EspoApi
        """
        assert self.crm_api_path is not None, f'crm_api_path for {self.__class__.__name__} is undefined'
        if self.crm_id:
            return f'{self.crm_api_path}/{self.crm_id}'
        return self.crm_api_path

    @classmethod
    def get_queryset(cls):
        if cls.queryset is None:
            return cls.objects.all()
        return cls.queryset

    @classmethod
    def get_crm_serializer_class(cls):
        """
        Возвращает сериализатор для запроса EspoApi
        """
        assert cls.serializer_class is not None, f'serializer for {cls.__name__} is undefined'
        return cls.serializer_class

    def get_request_type(self):
        """
        Возвращает method для запроса EspoApi
        """
        if self.crm_id:
            return 'PATCH'
        return 'POST'

    def get_sync_delete(self):
        """
        Если sync_delete == True, будет отправлена таска на удаление в crm,
        иначе обновление (для неудаляемых записей с safe-delete)
        """
        assert self.sync_delete is not None, f'sync_delete for {self.__class__.__name__} is undefined'
        return self.sync_delete

    def crm_sync_delete(self):
        """
        Синхронизация удаления
        """
        method = 'DELETE'
        data = {}
        action = self.get_crm_api_action()
        response = self.client.request(method, action, data)

    def send_espo_request(self, *args, **kwargs):
        """
        Синхронизация сохранения модели с crm
        """
        queryset = self.get_queryset()
        queryset = queryset.select_for_update()
        with transaction.atomic():
            instance = queryset.get(pk=self.pk) # TODO теперь мы берем инстанс в самой таске.
                                                # можно переделать через селф
            serializer_ = instance.get_crm_serializer_class()
            data = serializer_(instance).data
            data['skipDuplicateCheck'] = True
            method = instance.get_request_type()
            action = instance.get_crm_api_action()
            response = self.client.request(method, action, data)
            if not instance.crm_id:
                instance.crm_id = response.get('id')
                instance.save(*args, dont_sync=True, **kwargs)

    def crm_request_related_link(self, category_id, link):
        """
        Для создания связи между сущностями в срм. link - имя сущности,
        category_id - айди записи этой сущности.
        """
        self.refresh_from_db()
        assert self.crm_id is not None, "impossible to relate without crm_id"
        params = {'id': category_id}
        action = self.get_crm_api_action()
        link_action = f'{action}/{link}'
        self.client.request('POST', link_action, params=params)

    def crm_push(self, *args, **kwargs):
        """
        Вызов синхронизации с crm
        """
        self.send_espo_request(*args, **kwargs)

    def save(self, *args, **kwargs):
        dont_sync = kwargs.pop('dont_sync', False)
        with transaction.atomic():
            super().save(*args, **kwargs)
            if (dont_sync != True and settings.CRM_ENABLED and
                             self.get_queryset().filter(pk=self.pk).exists()):
                s = app.signature(
                    'crm.crm_sync',
                    kwargs={
                        'instance_id': self.pk,
                        'class_name': self.__class__.__name__
                    }
                )
                transaction.on_commit(lambda: s.apply_async())

    class Meta:
        abstract = True

@receiver(post_delete)
def crm_sync_delete(sender, instance, **kwargs):
    if isinstance(instance, CRMSignalMixin) and instance.sync_delete == CRM_TRUE_DELETE:
        with transaction.atomic():
            s = app.signature(
                    'crm.crm_sync_delete',
                    kwargs={
                        'instance': instance
                    }
            )
            transaction.on_commit(lambda:s.apply_async())


from flask.views import MethodView
from flask_jwt_extended import jwt_required
from flask_smorest import Blueprint, abort

from db import db
from Models import NoteModel, CategoryModel
from schemas import NoteSchema, NoteQuerySchema, CategorySchema
from sqlalchemy.exc import IntegrityError

blp = Blueprint("note", __name__, description="Operations on note")

@blp.route("/note")
class NoteList(MethodView):
    @jwt_required()
    @blp.arguments(NoteQuerySchema, location="query", as_kwargs=True)
    @blp.response(200, NoteSchema(many=True))
    def get(self, kwargs):
        user_id = kwargs.get("user_id")
        category_id = kwargs.get("category_id")
        if user_id and category_id:
            query = NoteModel.query.filter_by(user_id=user_id, category_id=category_id)
            return query
        if user_id:
            query = NoteModel.query.filter_by(user_id=user_id)
            return query
        if category_id:
            query = NoteModel.query.filter_by(category_id=category_id)
            return query
        return NoteModel.query.all()

    @jwt_required()
    @blp.arguments(NoteSchema)
    @blp.response(200, NoteSchema)
    def post(self, request_data):
        note = NoteModel(**request_data)
        category_id = request_data.get("category_id")
        category_owner_id = CategoryModel.query.with_entities(CategoryModel.owner_id).filter_by(id=category_id).scalar()
        if category_owner_id == request_data["user_id"] or category_owner_id is None:
            try:
                db.session.add(note)
                db.session.commit()
            except IntegrityError:
                abort(400, message="Error when creating note")
            return note
        abort(403, message="User has no access to this category")


#!/usr/bin/env python
# -*- coding: utf-8 -*-

__authors__ = 'Bruno Adelé <bruno@adele.im>'
__copyright__ = 'Copyright (C) 2013 Bruno Adelé'
__description__ = """A metar domolib"""
__license__ = 'GPL'
__version__ = '0.0.1'

# Require metar
# pip install git+https://github.com/tomp/python-metar.git

import re

try:
    from urllib.request import urlopen
except ImportError:
    from urllib import urlopen

from metar import Metar

from domolib.commons.decorator import command
from domolib.commons import cache

class dlmetar():
    def getresults(self, station):
        results = {}

        # Get Metar information
        url = 'http://weather.noaa.gov/pub/data/observations/metar/stations'

        r = None
        r = urlopen('%s/%s.TXT' % (url, station))

        if r.getcode() is None or r.getcode() != 200:
            return None

        # Extract only Metar informations
        m = re.search(
            '%s .*' % station,
            r.read().decode('utf-8')
        )

        if not m:
            return

        # Decode metar informations
        code = m.group(0)
        decode = Metar.Metar(code)

        # Get temperature
        if decode.temp:
            results['temp'] = decode.temp.value()

        # Get dewpt temperature
        if decode.dewpt:
            results['dewpt'] = decode.dewpt.value()

        # Get pressure
        if decode.press:
            results['pressure'] = decode.press.value()

        # Visibility
        if decode.vis:
            results['visibility'] = int(decode.vis.value())

        # Get wind speed
        if decode.wind_speed:
            results['wind_speed'] = decode.wind_speed.value() * 1.852

        # Calculate the relative humidity
        if decode.temp and decode.dewpt:
            temp = decode.temp.value()
            dewpt = decode.dewpt.value()
            results['humidity'] = round(
                100 * ((112 - 0.1 * temp + dewpt) / (112 + 0.9 * temp)) ** 8,
                2
            )

        # Calculate the wind chill or heat index
        if decode.temp and decode.wind_speed:
            speed = decode.wind_speed.value() * 1.852
            temp = decode.temp.value()
            results['wind_chill'] = round(
                13.12 + 0.6215 * temp +
                (0.3965 * temp - 11.37) * speed ** 0.16,
                2
            )

        return results

@command
def get_metarinfo(oaci_station):
    """
    Get a weather from metar report
    :param oaci_station:
    :return:
    """

    # Get result from cache
    mycache = cache.cache(cachefile='dlmetar.get_metarinfo')
    result = mycache.getcachedresults()
    if result:
        return result

    # Compute the result and store in the cache file
    obj = dlmetar()
    result = obj.getresults(station=oaci_station)
    mycache.setcacheresults(result)

    return result


#imports csv functions
import csv
import datetime
from os import read

#Dictionary for storing products
prod_dict = {

}
#Dictionary for storing requests
req_dict = {

}

#Dictionary for the receipt
receipt_dict = {

}

number_of_items = 0

subtotal = 0

current_date_and_time = datetime.datetime.now()

# Format the current date and time to include only
# the day of the week, the hour, and the minute.
formatted_dt = current_date_and_time.strftime("%A %I:%M %p")

#Open products.csv
with open("/Users/elijah/BYUI/Programming with functinos/Week3/products.csv") as products:
    reader = csv.reader(products)

    #Skip first row
    next(reader)

    #Populate Dictionary
    for row in reader:
        #Elements
        #0 - Product Number
        prod_num = row[0]
        #1 - Product Name
        prod_name = row[1]
        #2 - Retail Price
        prod_cost = row[2]

        #add element to dict
        prod_dict[prod_num] = [prod_name,prod_cost]

#Open requests.csv
with open("/Users/elijah/BYUI/Programming with functinos/Week3/request.csv") as request:
    reader = csv.reader(request)

    next(reader)

    for item in reader:
        # 0 - Product Number
        prod_num = item[0]
        # 1 - Quantity
        prod_quant = item[1]

        #add item to dictionary
        req_dict[prod_num] = prod_quant

# Display Products
#print(f"THIS IS THE PRODUCTS DICT : \n{prod_dict}")
# Display Requests
#print(f"THIS IS THE REQUEST DICT : \n{req_dict}")

print("\nRequested Items : \n")
for req_item in req_dict:
    #receipt_dict[req_item] = [prod_dict[req_item]]
    name = prod_dict[req_item][0]
    cost = prod_dict[req_item][1]
    count = req_dict[req_item][0]

    subtotal += (float(cost) * int(count))

    print(f"{name:.15} : {count:.2} @ ${cost:.5} \n")

tax = subtotal * 0.06
total = subtotal + tax

print("------------------------------\n")
print(f"Subtotal : {subtotal:.2f}")
print(f"Tax : {tax:.2f}")
print(f"Total : {total:.2f}")
print("\n------------------------------\n")
print(f"Date and time of checkout : {formatted_dt}\n\n")


import json
from math import e
import stat
from typing import Dict
from data.google.google_email_repository import GooleCalendarEventRepository
from services.google_auth_service import GoogleAuthService
from framework.logger import get_logger
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from framework.serialization import Serializable
from framework.crypto.hashing import sha256
from datetime import datetime, timedelta
from dateutil import parser

logger = get_logger(__name__)

GOOGLE_CALENDAR_SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']

class CalendarEvent(Serializable):
    def __init__(
        self,
        id: str,
        status: str,
        link: str,
        created_date,
        updated_date,
        summary: str,
        description: str,
        event_type: str,
        location: str,
        creator: str,
        organizer: str,
        start_date: Dict,
        end_date: Dict,
        visibility: str,
        attendees: list,
        reminders: list,
        extended_properties,
        recurring_event_id: str
    ):
        self.id = id
        self.status = status
        self.link = link
        self.created_date = created_date
        self.updated_date = updated_date
        self.summary = summary
        self.description = description
        self.event_type = event_type
        self.location = location
        self.creator = creator
        self.organizer = organizer
        self.start_date = start_date
        self.end_date = end_date
        self.visibility = visibility
        self.attendees = attendees
        self.reminders = reminders
        self.extended_properties = extended_properties
        self.recurring_event_id = recurring_event_id

    def generate_hash_key(
        self
    ):
        data = json.dumps(self.to_dict(), default=str)
        return sha256(data)

    @staticmethod
    def from_entity(data: Dict):
        return CalendarEvent(
            id=data.get('id'),
            status=data.get('status'),
            link=data.get('link'),
            created_date=data.get('created_date'),
            updated_date=data.get('updated_date'),
            summary=data.get('summary'),
            description=data.get('description'),
            event_type=data.get('event_type'),
            location=data.get('location'),
            creator=data.get('creator'),
            organizer=data.get('organizer'),
            start_date=data.get('start_date'),
            end_date=data.get('end_date'),
            visibility=data.get('visibility'),
            attendees=data.get('attendees'),
            reminders=data.get('reminders'),
            extended_properties=data.get('extended_properties'),
            recurring_event_id=data.get('recurring_event_id'))

    @staticmethod
    def from_event(data: Dict):
        start_date = {
            'datetime': data.get('start', dict()).get('dateTime'),
            'timezone': data.get('start', dict()).get('timeZone')
        }

        end_date = {
            'datetime': data.get('end', dict()).get('dateTime'),
            'timezone': data.get('end', dict()).get('timeZone')
        }

        return CalendarEvent(
            id=data.get('id'),
            status=data.get('status'),
            link=data.get('htmlLink'),
            created_date=data.get('created'),
            updated_date=data.get('updated'),
            summary=data.get('summary'),
            description=data.get('description'),
            event_type=data.get('eventType'),
            location=data.get('location'),
            creator=data.get('creator', dict()).get('email'),
            organizer=data.get('organizer', dict()).get('email'),
            start_date=start_date,
            end_date=end_date,
            visibility=data.get('visibility'),
            attendees=data.get('attendees'),
            reminders=data.get('reminders'),
            extended_properties=data.get('extendedProperties'),
            recurring_event_id=data.get('recurringEventId'))

def ensure_datetime(
    value: datetime | str
) -> datetime:
    if isinstance(value, datetime):
        return value

    return parser.parse(value)

class CalendarService:
    def __init__(
        self,
        auth_service: GoogleAuthService,
        repository: GooleCalendarEventRepository
    ):
        self.__auth_service = auth_service
        self.__repository = repository

    async def get_calendar_client(
        self
    ) -> Credentials:
        logger.info(f'Fetching calendar client')
        auth = await self.__auth_service.get_auth_client(
            scopes=GOOGLE_CALENDAR_SCOPES)

        return build("calendar", "v3", credentials=auth)

    async def get_calendar_events(
        self,
        start_date: str | datetime,
        end_date: str | datetime
    ):
        logger.info(
            f'Fetching calendar events from {start_date} to {end_date}')

        start_date = ensure_datetime(start_date)
        end_date = ensure_datetime(end_date)

        service = await self.get_calendar_client()

        events_result = service.events().list(
            calendarId='primary',
            timeMin=f'{start_date.isoformat()}Z',
            timeMax=f'{end_date.isoformat()}Z',
            singleEvents=True,
            orderBy='startTime'
        ).execute()

        events = events_result.get('items', [])

        events = [CalendarEvent.from_event(event) for event in events]

        return events

    async def sync_calendar_events(
        self
    ):
        logger.info(f'Syncing calendar events')

        end_date = datetime.now().strftime('%Y-%m-%d')
        start_date = (datetime.now() - timedelta(days=90)).strftime('%Y-%m-%d')


import os
import pandas as pd
from joblib import Parallel, delayed
from util import get_interfaces_path, iter_cdd

NUM_WORKERS = 20

def get_counts(sfam_id):
    path = os.path.join(get_interfaces_path(dataset_name), "by_superfamily",
        str(int(sfam_id)), "{}_bsa.h5".format(int(sfam_id)))
    store = pd.HDFStore(path)

    obs = store.get("/observed")
    obs_sizes = obs.groupby("ppi_type").size().reset_index(name='observed').T
    del obs

    inf = store.get("/inferred")
    inf_sizes = inf.groupby("ppi_type").size().reset_index(name='inferred').T

    sizes = pd.concat([obs_size, inf_sizes], axis=1)

    changed = inf.groupby(["ppi_type", "ppi_type_obs"]).size().reset_index(name='count')
    #changed = changed[changed["ppi_type"]!=changed["ppi_type_obs"]]
    changed = changed.apply(lambda r: pd.Series({
        "{}->{}".format(r.ppi_type_obs, r.ppi_type):r.count}, index="inferred"), axis=1)
    del inf
    store.close()
    del store

    import pdb; pdb.set_trace()
    sizes = pd.concat([sizes, changed], axis=1)

def plot_ppi_types(superfams=None):
    if superfams is not None:
        return

    sizes = Parallel(n_jobs=NUM_WORKERS)(delayed(get_counts)(sfam_id) \
        for _, sfam_id in iter_cdd(use_id=True, group_superfam=True))


from django.conf.urls.defaults import *
from django.contrib.auth.models import User
from django.views.generic.simple import direct_to_template

from board.feeds import LatestPosts
from board.rpc import rpc_post, rpc_lookup, rpc_preview, rpc_ban
from board.views import *

feeds = {'latest': LatestPosts}

js_info_dict = {
    'packages': ('board',),
}

urlpatterns = patterns('',
    (r'^$', thread_index, {}, 'board_index'),
    (r'search-results/$', search),
    (r'feedback/sent/$', direct_to_template, {'template':
        'board/feedback_sent.html'}),

    (r'^private/$', private_index, {}, 'board_private_index'),
    (r'^categories/$', category_index, {}, 'board_category_index'),
    (r'^favorites/$', favorite_index, {}, 'board_favorite_index'),
    (r'^edit_post/(?P<original>\d+)/$', edit_post, {}, 'board_edit_post'),
    (r'^threads/$', thread_index, {}, 'board_thread_index'),
    (r'^threads/id/(?P<thread_id>\d+)/$', thread, {}, 'board_thread'),
    (r'^threads/category/(?P<cat_id>\d+)/$', category_thread_index, {}, 'board_category_thread_index'),
    (r'^threads/category/(?P<cat_id>\d+)/newtopic/$', new_thread, {}, 'board_new_thread'),
    (r'^threads/post/(?P<post_id>\d+)/$', locate_post, {}, 'board_locate_post'),
    (r'^settings/$', edit_settings, {}, 'board_edit_settings'),

    # Groups
    (r'^groups/(?P<group_id>\d+)/manage/$', manage_group, {}, 'board_manage_group'),
    (r'^groups/(?P<group_id>\d+)/invite/$', invite_user_to_group, {}, 'board_invite_user_to_group'),
    (r'^groups/(?P<group_id>\d+)/remuser/$', remove_user_from_group, {}, 'board_remove_user_from_group'),
    (r'^groups/(?P<group_id>\d+)/grant_admin/$', grant_group_admin_rights, {}, 'board_grant_group_admin_rights'),

    (r'^del_thread/(?P<the_id>\d+)/$', 'board.views.del_thread'),

    # Invitations
    (r'invitations/(?P<invitation_id>\d+)/discard/$', discard_invitation, {}, 'board_discard_invitation'),
    (r'invitations/(?P<invitation_id>\d+)/answer/$', answer_invitation, {}, 'board_answer_invitation'),

    # RPC
    (r'^rpc/action/$', rpc, {}, 'board_rpc_action'),
    (r'^rpc/postrev/$', rpc_post, {}, 'board_rpc_postrev'),
    (r'^rpc/preview/$', rpc_preview, {}, 'board_rpc_preview'),
    (r'^rpc/user_lookup/$', rpc_lookup,
            {
                'queryset':User.objects.all(),
                'field':'username',
            }, 'board_rpc_user_lookup'
        ),
    (r'^rpc/ban/$', rpc_ban),

    # feeds
    (r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}, 'board_feeds'),

    # javascript translations
    (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict, 'board_js_i18n'),
)


import numpy as np
import pandas as pd
import tensorflow as tf
import json
from keras.models import Model, Sequential
from keras.layers import Input, Activation, Dense
from keras.optimizers import SGD
from keras.utils.np_utils import to_categorical
from flask import Flask, render_template, jsonify

app = Flask(__name__, template_folder ='templates',static_url_path='/static')

# Pandas read CSV
sf_train = pd.read_csv('p5_training_data.csv')

# korelasi matriks ke target
corr_matrix = sf_train.corr()
print(corr_matrix['type'])

# buang kolom
sf_train.drop(sf_train.columns[[5, 12, 14, 21, 22, 23]], axis=1, inplace=True)
print(sf_train.head())

# baca CSV
sf_train = pd.read_csv('p5_training_data.csv')

# Korelasi matriks target
corr_matrix = sf_train.corr()
print(corr_matrix['type'])

# buang kolom
sf_train.drop(sf_train.columns[[5, 12, 14, 21, 22, 23]], axis=1, inplace=True)
print(sf_train.head())

# panda baca data Val
sf_val = pd.read_csv('p5_val_data.csv')

# Buang kolom
sf_val.drop(sf_val.columns[[5, 12, 14, 21, 22, 23]], axis=1, inplace=True)

# Get Pandas array value (Convert ke array NumPy)
train_data = sf_train.values
val_data = sf_val.values

# Use columns 2-akhir sbg Input
train_x = train_data[:,2:]
val_x = val_data[:,2:]

# Use columns 1 sebagai Output/Target (pake One-Hot Encoding)
train_y = to_categorical( train_data[:,1] )
val_y = to_categorical( val_data[:,1] )

# bikin jaringan
inputs = Input(shape=(16,))
h_layer = Dense(10, activation='sigmoid')(inputs)

# aktivasi softmax baut klasifikasi multiklas
outputs = Dense(3, activation='softmax')(h_layer)

model = Model(inputs=inputs, outputs=outputs)

# Optimizer / Update Rule
sgd = SGD(lr=0.001)

# Compile model dengan Cross Entropy Loss
model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy'])

# Training model dan pake validation data
model.fit(train_x, train_y, batch_size=10, epochs=5000, verbose=1, validation_data=(val_x, val_y))
model.save_weights('weights.h5')

# Predict semual Validation data
predict = model.predict(val_x)

# Visualisasi Prediksi
#df = pd.DataFrame(predict)
#df.columns = [ 'Strength', 'Agility', 'Intelligent' ]
#df.index = val_data[:,0]

#web server pake flask buat render template
@app.route('/index')
@app.route('/')
def index():
	return render_template("index.html")

@app.route('/dota2', methods=['GET'])
def dota():
	'''
	df = pd.DataFrame(predict)
	df.columns = [ 'Strength', 'Agility', 'Intelligent' ]
	df.index = val_data[:,0]
	data = df.to_dict(orient='index')
	return jsonify({'data':data})
	'''
	df = pd.DataFrame(predict)
	df.columns = [ 'Strength', 'Agility', 'Intelligent' ]
	df.index = val_data[:,0]
	temp = df.to_dict('records')
	columnNames = df.columns.values
	rowwNames = df.index
	return render_template('record.html', records=temp, colnames=columnNames,len=len(rowwNames), rownames=rowwNames)

if __name__ == '__main__':
	app.run(host='0.0.0.0', port=5000)


from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path

urlpatterns = [

    path('admin/', admin.site.urls),
    path('', include('monitoramento.urls')),
    path('users/', include('users.urls')),
    path('clientes/', include('clientes.urls')),
    path('veiculos/', include('veiculos.urls')),
    path('', include('grupoveiculos.urls')),
    path('', include('escritorio.urls')),
    path('', include('tecnico.urls')),
    path('cadastro/', include('cadastros.urls')),

]

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


from classifiers.decision_tree import DecisionTree
from collections import Counter
from utils.utility import pick_result
from random import randrange

import numpy

__author__ = 'Simon & Oskar'

class RandomForest:
    def __init__(self, max_depth = None, min_samples_leaf = 1, n_estimators = 10, sample_size = 200, max_features = None):
        self.criterion = "gini"
        self.max_features = max_features
        self.max_depth = max_depth
        self.min_samples_leaf = min_samples_leaf
        self.laplace = 0
        self.n_estimators = n_estimators
        self.bagging = 0
        self.sample_size = sample_size

        self.n_classes = None
        self.decision_trees = list()

    def fit(self, X, y):
        if self.n_classes is None:
            self.n_classes = numpy.unique(y)

        if self.sample_size is None:
            self.sample_size = X.shape[0] / self.n_estimators

        rand_features = numpy.zeros(shape = (self.n_estimators, self.sample_size, X.shape[1]),
                                    dtype = numpy.float)

        rand_classes = numpy.zeros((self.n_estimators, self.sample_size))

        for i in range(self.n_estimators):
            temp = numpy.zeros(shape = (self.sample_size, X.shape[1]),
                               dtype = numpy.float)

            temp_class = numpy.zeros(shape = self.sample_size,
                                     dtype = numpy.float)

            for j in range(self.sample_size):
                r = randrange(0, X.shape[0])
                temp[j] = X[r]
                temp_class[j] = y[r]

            rand_features[i] = temp
            rand_classes[i] = temp_class

        for i in range(self.n_estimators):
            decision_tree = DecisionTree(max_features = self.max_features,
                                         max_depth = self.max_depth,
                                         min_samples_leaf = self.min_samples_leaf,
                                         laplace = self.laplace)

            decision_tree.fit(X = rand_features[i],
                              y = rand_classes[i])

            self.decision_trees.append(decision_tree)

    def predict(self, X):
        final_result = numpy.zeros((X.shape[0]))

        for row in range(X.shape[0]):
            result = numpy.zeros((self.n_estimators, 1))

            for i in range(self.n_estimators):
                result[i] = self.decision_trees[i].predict(numpy.array([X[row]]))

            result_flattened = result.ravel()
            c = Counter(result_flattened).most_common(numpy.unique(result_flattened).size)

            final_result[row] = pick_result(c)

        return final_result

    def predict_proba(self, X):
        final_result = numpy.zeros((X.shape[0], len(self.n_classes)), numpy.float)

        for row in range(X.shape[0]):
            result = numpy.zeros((self.n_estimators, len(self.n_classes)), numpy.float)
            for i in range(self.n_estimators):
                result[i] = self.decision_trees[i].predict_proba(numpy.array([X[row]]))
            result.astype(numpy.float)
            for r in result:
                for i in range(final_result.shape[1]):
                    final_result[row, i] += r[i].astype(numpy.float) / float(self.n_estimators)

        return final_result


from copy import copy
import itertools
from typing import List, Union
import pytest  # type: ignore[import]

from testlib import on_time

from cmk.base.plugins.agent_based import job
from cmk.base.plugins.agent_based.agent_based_api.v1 import (
    clusterize,
    Result,
    State as state,
    Metric,
    type_defs,
)

SECTION_1: job.Section = {
    'SHREK': {
        'running': False,
        'start_time': 1547301201,
        'exit_code': 0,
        'metrics': {
            'real_time': 120.0,
            'user_time': 1.0,
            'system_time': 0.0,
            'reads': 0,
            'writes': 0,
            'max_res_bytes': 1234000,
            'avg_mem_bytes': 1000,
            'invol_context_switches': 12,
            'vol_context_switches': 23,
        },
    },
    'SNOWWHITE': {
        'running': False,
        'start_time': 1557301201,
        'exit_code': 1,
        'running_start_time': [
            1557301261, 1557301321, 1557301381, 1557301441, 1537301501, 1557301561
        ],
        'metrics': {
            'real_time': 360.0,
            'user_time': 0.0,
            'system_time': 0.0,
            'reads': 0,
            'writes': 0,
            'max_res_bytes': 2224000,
            'avg_mem_bytes': 0,
            'invol_context_switches': 1,
            'vol_context_switches': 2,
        },
    },
}

SECTION_2: job.Section = {
    'backup.sh': {
        'running': False,
        'start_time': 1415204091,
        'exit_code': 0,
        'running_start_time': [1415205713],
        'metrics': {
            'real_time': 281.65,
            'user_time': 277.7,
            'system_time': 32.12,
            'reads': 0,
            'writes': 251792,
            'max_res_bytes': 130304000,
            'avg_mem_bytes': 0,
            'invol_context_switches': 16806,
            'vol_context_switches': 32779,
        },
    },
    'cleanup_remote_logs': {
        'running': False,
        'start_time': 1415153430,
        'exit_code': 0,
        'metrics': {
            'real_time': 9.9,
            'user_time': 8.85,
            'system_time': 0.97,
            'reads': 96,
            'writes': 42016,
            'max_res_bytes': 11456000,
            'avg_mem_bytes': 0,
            'invol_context_switches': 15,
            'vol_context_switches': 274,
        },
    },
}

TIME = 1594300620.0, "CET"

def _modify_start_time(
    j: job.Job,
    start_time: Union[float, List[int]],
) -> job.Job:
    new_job: job.Job = copy(j)
    if isinstance(start_time, list):
        new_job['running_start_time'] = start_time
    else:
        new_job['start_time'] = start_time
    return new_job

@pytest.mark.parametrize("timestr,expected_result", [
    ('0:00.00', 0.),
    ('1:02.00', 62.),
    ('35:30:2.12', 35 * 60**2 + 30 * 60 + 2.12),
])
def test_job_parse_real_time(timestr, expected_result):
    assert job._job_parse_real_time(timestr) == expected_result

@pytest.mark.parametrize("string_table,expected_parsed_data", [
    (
        [
            ['==>', 'SHREK', '<=='],
            ['start_time', '1547301201'],
            ['exit_code', '0'],
            ['real_time', '2:00.00'],
            ['user_time', '1.00'],
            ['system_time', '0.00'],
            ['reads', '0'],
            ['writes', '0'],
            ['max_res_kbytes', '1234'],
            ['avg_mem_kbytes', '1'],
            ['invol_context_switches', '12'],
            ['vol_context_switches', '23'],
            ['==>', 'SNOWWHITE', '<=='],
            ['start_time', '1557301201'],
            ['exit_code', '1'],
            ['real_time', '6:00.00'],
            ['user_time', '0.00'],
            ['system_time', '0.00'],
            ['reads', '0'],
            ['writes', '0'],
            ['max_res_kbytes', '2224'],
            ['avg_mem_kbytes', '0'],
            ['invol_context_switches', '1'],
            ['vol_context_switches', '2'],
            ['==>', 'SNOWWHITE.27997running', '<=='],
            ['start_time', '1557301261'],
            ['==>', 'SNOWWHITE.28912running', '<=='],
            ['start_time', '1557301321'],
            ['==>', 'SNOWWHITE.29381running', '<=='],
            ['start_time', '1557301381'],
            ['==>', 'SNOWWHITE.30094running', '<=='],
            ['start_time', '1557301441'],
            ['==>', 'SNOWWHITE.30747running', '<=='],
            ['start_time', '1537301501'],
            ['==>', 'SNOWWHITE.31440running', '<=='],
            ['start_time', '1557301561'],
        ],
        SECTION_1,
    ),
    (
        [
            ['==>', 'backup.sh', '<=='],
            ['start_time', '1415204091'],
            ['exit_code', '0'],
            ['real_time', '4:41.65'],
            ['user_time', '277.70'],
            ['system_time', '32.12'],
            ['reads', '0'],
            ['writes', '251792'],
            ['max_res_kbytes', '130304'],
            ['avg_mem_kbytes', '0'],
            ['invol_context_switches', '16806'],
            ['vol_context_switches', '32779'],
            ['==>', 'backup.sh.running', '<=='],
            ['start_time', '1415205713'],
            ['==>', 'cleanup_remote_logs', '<=='],
            ['start_time', '1415153430'],
            ['exit_code', '0'],
            ['real_time', '0:09.90'],
            ['user_time', '8.85'],
            ['system_time', '0.97'],
            ['reads', '96'],
            ['writes', '42016'],
            ['max_res_kbytes', '11456'],
            ['avg_mem_kbytes', '0'],
            ['invol_context_switches', '15'],
            ['vol_context_switches', '274'],
        ],
        SECTION_2,
    ),
])
def test_parse(string_table, expected_parsed_data):
    assert job.parse_job(string_table) == expected_parsed_data

RESULTS_SHREK: List[Union[Metric, Result]] = [
    Result(state=state.OK, summary='Latest exit code: 0'),
    Result(state=state.OK, summary='Real time: 2 minutes 0 seconds'),
    Metric('real_time', 120.0),
    Result(state=state.OK, notice='Latest job started at Jan 12 2019 14:53:21'),
    Metric('start_time', 1547301201.0),
    Result(state=state.OK, summary='Job age: 1 year 178 days'),
    Result(state=state.OK, notice='Avg. memory: 1000 B'),
    Metric('avg_mem_bytes', 1000.0),
    Result(state=state.OK, notice='Invol. context switches: 12'),
    Metric('invol_context_switches', 12.0),
    Result(state=state.OK, notice='Max. memory: 1.18 MiB'),
    Metric('max_res_bytes', 1234000.0),
    Result(state=state.OK, notice='Filesystem reads: 0'),
    Metric('reads', 0.0),
    Result(state=state.OK, notice='System time: 0 seconds'),
    Metric('system_time', 0.0),
    Result(state=state.OK, notice='User time: 1 second'),
    Metric('user_time', 1.0),
    Result(state=state.OK, notice='Vol. context switches: 23'),
    Metric('vol_context_switches', 23.0),
    Result(state=state.OK, notice='Filesystem writes: 0'),
    Metric('writes', 0.0),
]

def _aggr_shrek_result(node: str) -> Result:
    return Result(**dict(
        zip(  # type: ignore
            ("state", "notice"),
            clusterize.aggregate_node_details(node, RESULTS_SHREK),
        )))

@pytest.mark.parametrize(
    "job_data, age_levels, exit_code_to_state_map, expected_results",
    [
        (
            SECTION_1['SHREK'],
            (0, 0),
            {
                0: state.OK
            },
            RESULTS_SHREK,
        ),
        (
            SECTION_1['SHREK'],
            (1, 2),
            {
                0: state.OK
            },
            itertools.chain(
                RESULTS_SHREK[0:5],
                [
                    Result(
                        state=state.CRIT,
                        summary='Job age: 1 year 178 days (warn/crit at 1 second/2 seconds)',
                    ),
                ],
                RESULTS_SHREK[6:],
            ),
        ),
        (
            SECTION_1['SHREK'],
            (0, 0),
            {
                0: state.WARN
            },
            itertools.chain(
                [
                    Result(
                        state=state.WARN,
                        summary='Latest exit code: 0',
                    ),
                ],
                RESULTS_SHREK[1:],
            ),
        ),
        (
            _modify_start_time(
                SECTION_1['SHREK'],
                [1557301261, 1557301321, 1557301381, 1557301441, 1537301501, 1557301561],
            ),
            (1, 2),
            {
                0: state.OK
            },
            itertools.chain(
                RESULTS_SHREK[:3],
                [
                    Result(
                        state=state.OK,
                        notice=('6 jobs are currently running, started at'
                                ' May 08 2019 09:41:01, May 08 2019 09:42:01,'
                                ' May 08 2019 09:43:01, May 08 2019 09:44:01,'
                                ' Sep 18 2018 22:11:41, May 08 2019 09:46:01'),
                    ),
                    Result(
                        state=state.CRIT,
                        summary=('Job age (currently running): '
                                 '1 year 63 days (warn/crit at 1 second/2 seconds)'),
                    ),
                ],
                RESULTS_SHREK[6:],
            ),
        ),
    ],
)
def test_process_job_stats(
    job_data,
    age_levels,
    exit_code_to_state_map,
    expected_results,
):
    with on_time(*TIME):
        assert list(job._process_job_stats(
            job_data,
            age_levels,
            exit_code_to_state_map,
        )) == list(expected_results)

@pytest.mark.parametrize(
    "item, params, section, expected_results",
    [
        (
            'SHREK',
            type_defs.Parameters({'age': (0, 0)},),
            SECTION_1,
            RESULTS_SHREK,
        ),
        (
            'item',
            type_defs.Parameters({'age': (0, 0)},),
            {
                'item': {}
            },
            [Result(state=state.UNKNOWN, summary='Got incomplete information for this job')],
        ),
        (
            'cleanup_remote_logs',
            type_defs.Parameters({'age': (0, 0)},),
            SECTION_2,
            [
                Result(state=state.OK, summary='Latest exit code: 0',
                       details='Latest exit code: 0'),
                Result(
                    state=state.OK, summary='Real time: 9 seconds', details='Real time: 9 seconds'),
                Metric('real_time', 9.9),
                Result(state=state.OK, notice='Latest job started at Nov 05 2014 03:10:30'),
                Metric('start_time', 1415153430.0),
                Result(state=state.OK, summary='Job age: 5 years 248 days'),
                Result(state=state.OK, notice='Avg. memory: 0 B'),
                Metric('avg_mem_bytes', 0.0),
                Result(state=state.OK, notice='Invol. context switches: 15'),
                Metric('invol_context_switches', 15.0),
                Result(state=state.OK, notice='Max. memory: 10.9 MiB'),
                Metric('max_res_bytes', 11456000.0),
                Result(state=state.OK, notice='Filesystem reads: 96'),
                Metric('reads', 96.0),
                Result(state=state.OK, notice='System time: 970 milliseconds'),
                Metric('system_time', 0.97),
                Result(state=state.OK, notice='User time: 8 seconds'),
                Metric('user_time', 8.85),
                Result(state=state.OK, notice='Vol. context switches: 274'),
                Metric('vol_context_switches', 274.0),
                Result(state=state.OK, notice='Filesystem writes: 42016'),
                Metric('writes', 42016.0),
            ],
        ),
        (
            'backup.sh',
            type_defs.Parameters({'age': (1, 2)},),
            SECTION_2,
            [
                Result(state=state.OK, summary='Latest exit code: 0'),
                Result(state=state.OK, summary='Real time: 4 minutes 41 seconds'),
                Metric('real_time', 281.65),
                Result(state=state.OK,
                       notice='1 job is currently running, started at Nov 05 2014 17:41:53'),
                Result(
                    state=state.CRIT,
                    summary=
                    'Job age (currently running): 5 years 247 days (warn/crit at 1 second/2 seconds)'
                ),
                Result(state=state.OK, notice='Avg. memory: 0 B'),
                Metric('avg_mem_bytes', 0.0),
                Result(state=state.OK, notice='Invol. context switches: 16806'),
                Metric('invol_context_switches', 16806.0),
                Result(state=state.OK, notice='Max. memory: 124 MiB'),
                Metric('max_res_bytes', 130304000.0),
                Result(state=state.OK, notice='Filesystem reads: 0'),
                Metric('reads', 0.0),
                Result(state=state.OK, notice='System time: 32 seconds'),
                Metric('system_time', 32.12),
                Result(state=state.OK, notice='User time: 4 minutes 37 seconds'),
                Metric('user_time', 277.7),
                Result(state=state.OK, notice='Vol. context switches: 32779'),
                Metric('vol_context_switches', 32779.0),
                Result(state=state.OK, notice='Filesystem writes: 251792'),
                Metric('writes', 251792.0),
            ],
        ),
        (
            'missing',
            type_defs.Parameters({'age': (1, 2)},),
            SECTION_2,
            [],
        ),
    ],
)
def test_check_job(item, params, section, expected_results):
    with on_time(*TIME):
        assert list(job.check_job(item, params, section)) == expected_results

@pytest.mark.parametrize(
    "item, params, section, expected_results",
    [
        (
            'SHREK',
            type_defs.Parameters({'age': (0, 0)},),
            {
                'node1': SECTION_1
            },
            [
                _aggr_shrek_result('node1'),
                Result(
                    state=state.OK,
                    summary=
                    '1 node in state OK, 0 nodes in state WARN, 0 nodes in state CRIT, 0 nodes in state UNKNOWN',
                ),
            ],
        ),
        (
            'SHREK',
            type_defs.Parameters({'age': (0, 0)},),
            {
                'node1': SECTION_1,
                'node2': SECTION_1,
            },
            [
                _aggr_shrek_result('node1'),
                _aggr_shrek_result('node2'),
                Result(
                    state=state.OK,
                    summary=
                    '2 nodes in state OK, 0 nodes in state WARN, 0 nodes in state CRIT, 0 nodes in state UNKNOWN',
                ),
            ],
        ),
        (
            'SHREK',
            type_defs.Parameters({
                'age': (3600, 7200),
                'outcome_on_cluster': 'best',
            },),
            {
                'node1': SECTION_1,
                'node2': {
                    'SHREK': _modify_start_time(
                        SECTION_1['SHREK'],
                        1594293430.9147654,
                    ),
                },
            },
            [
                Result(state=state.OK,
                       notice=('[node1]: Latest exit code: 0\n'
                               '[node1]: Real time: 2 minutes 0 seconds\n'
                               '[node1]: Latest job started at Jan 12 2019 14:53:21\n'
                               '[node1]: Job age: 1 year 178 days (warn/crit at 1 hour'
                               ' 0 minutes/2 hours 0 minutes)(!!)\n'
                               '[node1]: Avg. memory: 1000 B\n'
                               '[node1]: Invol. context switches: 12\n'
                               '[node1]: Max. memory: 1.18 MiB\n'
                               '[node1]: Filesystem reads: 0\n'
                               '[node1]: System time: 0 seconds\n'
                               '[node1]: User time: 1 second\n'
                               '[node1]: Vol. context switches: 23\n'
                               '[node1]: Filesystem writes: 0')),
                Result(state=state.OK,
                       notice=('[node2]: Latest exit code: 0\n'
                               '[node2]: Real time: 2 minutes 0 seconds\n'
                               '[node2]: Latest job started at Jul 09 2020 13:17:10\n'
                               '[node2]: Job age: 1 hour 59 minutes (warn/crit at 1 hour'
                               ' 0 minutes/2 hours 0 minutes)(!)\n'
                               '[node2]: Avg. memory: 1000 B\n'
                               '[node2]: Invol. context switches: 12\n'
                               '[node2]: Max. memory: 1.18 MiB\n'
                               '[node2]: Filesystem reads: 0\n'
                               '[node2]: System time: 0 seconds\n'
                               '[node2]: User time: 1 second\n'
                               '[node2]: Vol. context switches: 23\n'
                               '[node2]: Filesystem writes: 0')),
                Result(state=state.WARN,
                       summary=('0 nodes in state OK, 1 node in state WARN,'
                                ' 1 node in state CRIT, 0 nodes in state UNKNOWN')),
            ],
        ),
        (
            'missing',
            type_defs.Parameters({'age': (0, 0)},),
            {
                'node1': SECTION_1,
                'node2': SECTION_2,
            },
            [
                Result(
                    state=state.UNKNOWN,
                    summary='Received no data for this job from any of the nodes',
                ),
            ],
        ),
    ],
)
def test_cluster_check_job(item, params, section, expected_results):
    with on_time(*TIME):
        assert list(job.cluster_check_job(item, params, section)) == expected_results


# Library and Modules used
import os
import cv2
import numpy as np
import customtkinter as ctk
from tkinter import *
from rembg import remove
from pathlib import Path
from threading import Thread
from datetime import datetime
from deepface import DeepFace
from PIL import Image ,ImageTk
from tkinter import ttk, filedialog
from pdf2image import convert_from_path
from tkinter.messagebox import showerror, showinfo

# Creating functions whihch used to provide fnctionality to pages
def Imgo( file, w, h) :

    # Image processing
    img = Image.open( file )
    pht = ImageTk.PhotoImage( img.resize( (w,h), Image.Resampling.LANCZOS))
    return pht

def change( can, page) :

    # Switching canvas
    can.destroy()
    page()

def mistake( message) :

    # Pop up window for errors
    showerror( title = "Error Occured", message = message )

def inform( message) :

    # Pop up window for info
    showinfo( title = "Done", message = message )

def analysis1( path1, path2, sample ) :

    # First method for image analysis
    result_1 = DeepFace.verify( img1_path = path1 , img2_path = path2,
                                    enforce_detection = False, model_name = "VGG-Face",
                                        distance_metric = "cosine", detector_backend = "opencv" )

    if result_1["verified"] :

        # Add image if match
        matches.add( sample )

def analysis2( path1, path2, sample ) :

    # Second method for image analysis
    result_2 = DeepFace.verify( img1_path = path1 , img2_path = path2,
                                    enforce_detection = False, model_name = "VGG-Face",
                                        distance_metric = "euclidean_l2", detector_backend = "ssd" )

    if result_2["verified"] :

        # Add image if match
        matches.add( sample )

def sortingImages() :

    # Sorting Images and Saving them in folders
    if ( values[2] != "" and values[4] != "" ) :

        main_img = {}
        check_img = {}

        # Processing First folder
        for img in os.listdir( values[2] ) :

            main_path = values[2] + '/' + str(img)
            main_img[img] = cv2.imread( main_path )

        # Processing Second folder
        for img in os.listdir( values[4] ) :

            check_path = values[4] + '/' + str(img)
            check_img[img] = cv2.imread( check_path )

        # Analysing both the folders together
        for x in main_img.keys() :

            for y in check_img.keys() :

                # Both at same time
                Thread(target = analysis1( main_img[x], check_img[y], y )).start()
                Thread(target = analysis2( main_img[x], check_img[y], y )).start()

            new_dir = os.path.join( values[2], str( x[ : len(x)-4] + "match") )
            os.mkdir( new_dir )

            for i in matches :

                # Saving Images to new directory
                cv2.imwrite( os.path.join( new_dir, i), check_img[i] )

            # Clearing the previous data from set
            matches.clear()

        # Message of completion
        inform( "Sorted And Saved" )
        values[2] = ""
        values[4] = ""

    else :

        # Showing error due to empty credientials
        mistake( "Empty Fields" )

def findingImages( label ) :

    # Finding similar images
    if ( values[0] != "" and values[2] != "" ) :

        # Processing image
        values[1] = cv2.imread( values[0] )

        # Getting into images of given folder
        for img in os.listdir( values[2] ) :

            img2_path = values[2] + '/' + str(img)
            values[3] = cv2.imread( img2_path )

            # Both at same time
            Thread(target = analysis1( values[1], values[3], img )).start()
            Thread(target = analysis2( values[1], values[3], img )).start()

        # For searching folder, method 2

        # df = DeepFace.find( img_path = values[0], db_path = values[2], enforce_detection = False )
        # res = pd.DataFrame( df )
        # for i in res["identity"] :
        #     print(i)

    # Show data
    if matches == set() :

        # Message in the frame
        label.configure( text = "No File Found")

    else :

        # Showing results in order
        x = 50
        output = ""

        for i in matches :

            if ( len(output + i) > x ) :

                x = x + 50
                output = output + os.linesep

            output = str(output + i + ", ")

        label.configure( text = output[:len(output)-2],
                            text_font = (ft[1], 20, "bold"))
        label.place_configure( x = 50, y = 50, anchor = "nw" )

    # Clearing previously processed data
    values[0] = ""
    values[1] = np.array([0,0,0])
    values[2] = ""
    values[3] = np.array([0,0,0])
    matches.clear()

def convertFile( can, formate ) :

    if ( values[0] == "" ) :
        mistake("Add or Enter File Path")
        return

    # Coverting files to another specified formate
    convert_to = formate.get()
    if (convert_to == "Select Type ") :
        mistake("Select File Format")
        return

    file_types = { "Select Type " : False,
                    "   PDF" : [ "PDF file", "*.pdf"],
                     "   PNG" : [ "PNG file", "*.png"],
                      "   JPG" : [ "JPG file", "*.jpg"],
                       "   JPEG" : [ "JPEG file", "*.jpeg"] }

    # Formate to which we have to convert
    convert_to = file_types[convert_to]

    try :
        # Checking Entrybox
        if( values[0][-3:] == convert_to[1][2:] ) :

            # Error due to converting to same formate
            mistake("SAME FORMATE")

        elif ( values[0] != "" ) and convert_to :

            # Converting pdf files
            if ( values[0][-3:] == 'pdf' ) :

                # Finding address to save file
                dirc = filedialog.askdirectory( initialdir = os.getcwd(), title = "Save file")

                # Poppler's Path
                poppler_path = os.path.join( os.getcwd(), r"poppler-23.01.0\Library\bin")

                # Processing page(s) of pdf
                pages = convert_from_path( pdf_path = values[0], poppler_path = poppler_path )

                # Getting into page(s) of pdf
                for page in pages :

                    file = datetime.now().strftime('%Y%m%d%H%M%S')
                    file = dirc + '/' + str(file) + convert_to[1][1:]
                    page.save(  Path(file), convert_to[1][2:])

            # Converting to pdf formate
            elif ( convert_to[1][2:] == "pdf" ) :

                # Finding address to save file
                file = filedialog.asksaveasfile( initialdir = os.getcwd(),
                                                    title = "Save file",
                                                        defaultextension = f"{convert_to[1]}",
                                                            filetypes =[( convert_to[0], f"{convert_to[1]}" )] )

                # Saving file
                let = Image.open( values[0] )
                to_pdf = let.convert('RGB')
                to_pdf.save( file.name )
                file.close()

            # For other types of formate conversion
            else :

                # Finding address to save file
                file = filedialog.asksaveasfile( initialdir = os.getcwd(), title = "Save file",
                                                    defaultextension = f"{convert_to[1]}",
                                                        filetypes =[( convert_to[0], f"{convert_to[1]}" )] )

                # Saving file
                values[1] = cv2.imread( values[0] )
                cv2.imwrite( file.name, values[1])
                file.close()

            # Clearing previously processed data
            values[0] = ""
            values[1] = np.array([0,0,0])

            # Message of complition and return back
            inform( "FILE SAVED" )
            change( can, menuPage)

        else :

            # Showing error due empty credientials
            mistake( "ENTER FILE NAME!" )

    except :
        mistake("Invalid Entry")

def removeBackground( click ) :

    # Removing the background of given Image

    # Checking entry
    if values[0] == "" :

        # Showing error due to empty credientials
        mistake( "FILE NOT FOUND!")

    else :

        # Removing the background of the Image
        original = cv2.imread( values[0] )
        values[1] = remove(original)
        values[0] = ""

        # Disabling the button after removing
        click.configure( state = DISABLED)

def savingFile( can ) :

    # Saving the file to a particular address
    if values[1].any() != 0 :

        # Finding address to save file
        file = filedialog.asksaveasfile( initialdir = os.getcwd(), title = "Save file",
                                            defaultextension = "*.png",
                                                filetypes = [( "PNG file", "*.png"), ( "JPG file", "*.jpg")] )

        # Saving file
        cv2.imwrite( file.name, values[1])
        values[1] = np.array([0,0,0])
        file.close()

        # Showing message of complition and returning back
        inform( "FILE SAVED" )
        change( can, menuPage)

    else :

        # Showing error due to empty credientials
        mistake( "ENTER FILE NAME!" )

def openingFolder( folder_path ) :

    # Opening Folder using filedialog
    if ( folder_path.get() != "" ) :

        # Getting path of folder from entry box
        open_folder = folder_path.get()

    else :

        # Getting path of folder from dialog
        open_folder = filedialog.askdirectory( initialdir = os.getcwd() ,title = "Browse Folder")

    # Checking for empty address
    if ( open_folder != "" ) :

        values[2] = open_folder

        if ( folder_path.get() != "" ) :
            folder_path.delete( 0, END)

        folder_path.insert( 0, open_folder )

    else :

        # Showing error due to empty credientials
        mistake( "FIELD EMPTY!" )

def openingFolder2( folder_path ) :

    # Opening Folder using filedialog
    if ( folder_path.get() != "" ) :

        # Getting path of folder from entry box
        open_folder = folder_path.get()

    else :

        # Getting path of folder from dialog
        open_folder = filedialog.askdirectory( initialdir = os.getcwd(), title = "Browse Folder")

    # Checking for empty address
    if ( open_folder != "" ) :

        values[4] = open_folder

        if ( folder_path.get() != "" ) :
            folder_path.delete( 0, END)

        folder_path.insert( 0, open_folder )

    else :

        # Showing error due to empty credientials
        mistake( "FIELD EMPTY!" )

def openingFile( file_path, file_formate ) :

    # Opening File
    if ( file_path.get() != "" ) :

        # Getting path of file from entry box
        open_file = file_path.get()

    else :

        # Getting path of file from filedialog
        open_file = filedialog.askopenfilename( initialdir = os.getcwd(), title = "Open file", filetypes = file_formate )

    # Checking for empty address
    if ( open_file != "" ) :

        values[0] = open_file

        if ( file_path.get() != "" ) :
            file_path.delete( 0, END)

        file_path.insert( 0, open_file )

    else :

        # Showing error due to empty credientials
        mistake( "FIELD EMPTY!" )

def checkLogin( can, page, user, pwrd ) :

    # Checking the login credientials
    if ( user.get() != "" and pwrd.get() != "" ) :

        if ( user.get() == "JustFunfact" and pwrd.get() == "star is burning" ) :

            # Login, same entry found
            change( can, page )

        else :

            # Showing error due to no match
            mistake("ENTRY DOESN'T MATCH")

    else :

        # Showing error due to empty credientials
        mistake( "EMPTY FIELDS")

# Designing pages of respective functionality
def clearBack() :

    # Image Background removing

    # Defining Structure
    third_page = Canvas( root,
                          width = wid, height = hgt,
                           bg = "black", highlightcolor = "#3c5390",
                            borderwidth = 0 )
    third_page.pack( fill = "both", expand = True )

    # Background Image
    back_image = Imgo( os.path.join( os.getcwd(), "Background\Clear_Back_Page.jpg" ), 1498, 875)
    third_page.create_image( 0, 0, image = back_image , anchor = "nw")

    # Heading
    third_page.create_text( 500, 120, text = "Remove Background",
                             font = ( ft[0], 45, "bold"), fill = "#1c54df" )

    # Return Button
    ret = Imgo( os.path.join( os.getcwd(), r'Design\arrow.png' ), 45, 35)
    ret_bt = ctk.CTkButton( master = root, image = ret, text = None,
                             width = 60, height = 40, corner_radius = 23,
                              bg_color = "#d3eafc", fg_color = "red",
                               hover_color = "#ff5359", border_width = 0,
                                command = lambda : change( third_page, menuPage) )
    ret_bt_win = third_page.create_window( 30, 20, anchor = "nw", window = ret_bt )

    # Accessing the file
    file_path = ctk.CTkEntry( master = root,
                                placeholder_text = "Enter Path", text_font = ( ft[4], 20 ),
                                 width = 580, height = 30, corner_radius = 14,
                                  placeholder_text_color = "#494949", text_color = "#242424",
                                   fg_color = "#c3c3c3", bg_color = "#d3eafc",
                                    border_color = "white", border_width = 3)
    file_path_win = third_page.create_window( 125, 200, anchor = "nw", window = file_path )

    file_formate = [( "PNG file", "*.png"), ( "JPG file", "*.jpg")]

    # Adding file path
    add_bt = ctk.CTkButton( master = root,
                             text = "Add..", text_font = ( ft[1], 20 ),
                              width = 60, height = 40, corner_radius = 14,
                               bg_color = "#d3eafc", fg_color = "red", text_color = "white",
                                hover_color = "#ff5359", border_width = 0,
                                 command = lambda : openingFile( file_path, file_formate) )
    add_bt_win = third_page.create_window( 860, 200-2, anchor = "nw", window = add_bt )

    #Design to display
    img_to_rem = Imgo( os.path.join( os.getcwd(), 'Design\Clear_back_design.png' ), 370, 370)
    third_page.create_image( 600-20, 350, image = img_to_rem , anchor = "nw")

    # Background removing button
    rem_bt = ctk.CTkButton( master = root,
                             text = "Remove", text_font = ( ft[4], 25 ),
                              width = 170, height = 50, corner_radius = 14,
                               bg_color = "#98e2fe", fg_color = "red", text_color = "white",
                                hover_color = "#ff5359", border_width = 0,
                                text_color_disabled = "#a4a4a4",
                                 command = lambda : removeBackground(rem_bt) )
    rem_bt_win = third_page.create_window( 300, 500, anchor = "nw", window = rem_bt )

    # Saving Image button
    save_bt = ctk.CTkButton( master = root,
                             text = "Save Image", text_font = ( ft[4], 25 ),
                              width = 220, height = 50, corner_radius = 14,
                               bg_color = "#98e2fe", fg_color = "red", text_color = "white",
                                hover_color = "#ff5359", border_width = 0,
                                 command = lambda : savingFile( third_page) )
    save_bt_win = third_page.create_window( 1000, 500, anchor = "nw", window = save_bt )

    root.mainloop()

def convertImage() :

     # Defining Structure
    fourth_page = Canvas( root,
                           width = wid, height = hgt,
                            bg = "black", highlightcolor = "#3c5390",
                             borderwidth = 0 )
    fourth_page.pack( fill = "both", expand = True )

    # Background Image
    back_image = Imgo( os.path.join( os.getcwd(), "Background\Convert_Img_Page.jpg" ), 1498, 875)
    fourth_page.create_image( 0, 0, image = back_image , anchor = "nw")

    # Heading
    fourth_page.create_text( 500, 120, text = "Convert Images",
                                font = ( ft[0], 45, "bold" ), fill = "#1c54df" )

    # Return Button
    ret = Imgo( os.path.join( os.getcwd(), r'Design\arrow.png' ), 45, 35)
    ret_bt = ctk.CTkButton( master = root,
                             image = ret, text = None,
                              width = 60, height = 40, corner_radius = 23,
                               bg_color = "#d3eafc", fg_color = "red",
                                hover_color = "#ff5359", border_width = 0,
                                 command = lambda : change( fourth_page, menuPage) )
    ret_bt_win = fourth_page.create_window( 30, 20, anchor = "nw", window = ret_bt )

    # Accessing the file
    file_path = ctk.CTkEntry( master = root,
                                placeholder_text = "Enter Path", text_font = ( ft[4], 20 ),
                                 width = 580, height = 30, corner_radius = 14,
                                  placeholder_text_color = "#494949", text_color = "#242424",
                                   fg_color = "#c3c3c3", bg_color = "#d3eafc",
                                    border_color = "white", border_width = 3)
    file_path_win = fourth_page.create_window( 300, 210, anchor = "nw", window = file_path )

    file_formate = [( "PNG file", "*.png"), ( "JPG file", "*.jpg"), ( "JPEG file", "*.jpeg"), ( "PDF file", "*.pdf") ]

    # Adding file path
    add_bt = ctk.CTkButton( master = root,
                             text = "Add..", text_font = ( ft[1], 20 ),
                              width = 60, height = 40, corner_radius = 14,
                               bg_color = "#d3eafc", fg_color = "red", text_color = "white",
                                hover_color = "#ff5359", border_width = 0,
                                 command = lambda : openingFile( file_path, file_formate) )
    add_bt_win = fourth_page.create_window( 1035, 210-2, anchor = "nw", window = add_bt )

    #Design to display
    img_to_con = Imgo( os.path.join( os.getcwd(), "Design\Convert_img_design.png" ), 390, 390)
    fourth_page.create_image( 600-50, 350, image = img_to_con , anchor = "nw")

    # Option menu
    opt = ctk.StringVar(value = "Select Type " )
    com = ctk.CTkOptionMenu( master = root, variable = opt,
                              values = [ "   PDF", "   PNG", "   JPG", "   JPEG"],
                               text_font = ( ft[4], 20),
                                width = 170, height = 40, corner_radius = 15,
                                 bg_color = "#9ae2fe", fg_color = "red", text_color = "white",
                                  button_color = "#363fc8", button_hover_color = "#676fe8",
                                   dropdown_color = "#ff6c3d", dropdown_hover_color = "red",
                                    dropdown_text_color = "white", dropdown_text_font = ( ft[4], 16),
                                     dynamic_resizing = True )
    # com.set("Select File")
    com_win = fourth_page.create_window( 1000, 400, anchor = "nw", window = com )

    # Saving Image button
    save_bt = ctk.CTkButton( master = root,
                             text = "Save Image", text_font = ( ft[4], 22 ),
                              width = 200, height = 40, corner_radius = 14,
                               bg_color = "#98e2fe", fg_color = "red", text_color = "white",
                                hover_color = "#ff5359", border_width = 0,
                                 command = lambda : convertFile( fourth_page, com) )
    save_bt_win = fourth_page.create_window( 1005, 620, anchor = "nw", window = save_bt )

    root.mainloop()

def findImage() :

     # Defining Structure
    fifth_page = Canvas( root, width =
                          wid, height = hgt,
                           bg = "black", highlightcolor = "#3c5390",
                            borderwidth = 0 )
    fifth_page.pack( fill = "both", expand = True )

    # Background Image
    back_image = Imgo( os.path.join( os.getcwd(), "Background\Find_Img_Page.jpg" ), 1498, 875)
    fifth_page.create_image( 0, 0, image = back_image , anchor = "nw")

    # Heading
    fifth_page.create_text( 400, 120, text = "Find Image", font = ( ft[0], 45, "bold" ), fill = "#1c54df" )

    # Return Button
    ret = Imgo( os.path.join( os.getcwd(), r'Design\arrow.png' ), 45, 35 )
    ret_bt = ctk.CTkButton( master = root,
                             image = ret, text = None,
                              width = 60, height = 40, corner_radius = 23,
                               bg_color = "#d3eafc", fg_color = "red",
                                hover_color = "#ff5359", border_width = 0,
                                 command = lambda : change( fifth_page, menuPage) )
    ret_bt_win = fifth_page.create_window( 30, 20, anchor = "nw", window = ret_bt )

    # Accessing the image
    file_path = ctk.CTkEntry( master = root,
                                placeholder_text = "Enter Image Path", text_font = ( ft[4], 20 ),
                                 width = 603, height = 30, corner_radius = 14,
                                  placeholder_text_color = "#494949", text_color = "#242424",
                                   fg_color = "#c3c3c3", bg_color = "#d3eafc",
                                    border_color = "white", border_width = 3)
    file_path_win = fifth_page.create_window( 300, 210, anchor = "nw", window = file_path )

    file_formate = [( "PNG file", "*.png"), ( "JPG file", "*.jpg") ]

    # Adding image path
    add_bt = ctk.CTkButton( master = root,
                             text = "Add..", text_font = ( ft[1], 20 ),
                              width = 60, height = 40, corner_radius = 14,
                               bg_color = "#d3eafc", fg_color = "red", text_color = "white",
                                hover_color = "#ff5359", border_width = 0,
                                 command = lambda : openingFile( file_path, file_formate) )
    add_bt_win = fifth_page.create_window( 1065, 210-2, anchor = "nw", window = add_bt )

    # Accessing the folder
    folder_path = ctk.CTkEntry( master = root,
                                 placeholder_text = "Enter Folder Path", text_font = ( ft[4], 20 ),
                                  width = 580, height = 30, corner_radius = 14,
                                   placeholder_text_color = "#494949", text_color = "#242424",
                                    fg_color = "#c3c3c3", bg_color = "#d3eafc",
                                     border_color = "white", border_width = 3)
    folder_path_win = fifth_page.create_window( 300, 295, anchor = "nw", window = folder_path )

    # Browse folder button
    browse_bt = ctk.CTkButton( master = root,
                                text = "Browse", text_font = ( ft[1], 20 ),
                                  width = 100, height = 40, corner_radius = 14,
                                   bg_color = "#d3eafc", fg_color = "red", text_color = "white",
                                    hover_color = "#ff5359", border_width = 0,
                                     command = lambda : openingFolder( folder_path ) )
    browse_bt_win = fifth_page.create_window( 1035, 295-2, anchor = "nw", window = browse_bt )

    # Frame
    mess = ctk.CTkFrame( master = fifth_page,
                          width = 780, height = 300, corner_radius = 30,
                           bg_color = "#d5eafd", fg_color = "#97e1fe",
                            border_color = "#4d89eb", border_width = 6)
    mess.place_configure( x = 280, y = 480, anchor = "nw")

    # Label in frame
    frm_label = ctk.CTkLabel( master = mess,
                                text = "Insert Values", text_font = (ft[0], 45, "bold"),
                                 width = 200, height = 50, corner_radius = 15,
                                  bg_color = "#97e1fe", fg_color = "#97e1fe", text_color = "#1c54df"  )
    frm_label.place_configure( x = 220, y = 120, anchor = "nw" )

    # Image Finding button
    find_bt = ctk.CTkButton( master = root,
                                text = "Find", text_font = ( ft[1], 24 ),
                                  width = 160, height = 45, corner_radius = 14,
                                   bg_color = "#d3eafc", fg_color = "red", text_color = "white",
                                    hover_color = "#ff5359", border_width = 0,
                                     command = lambda : findingImages( frm_label ) )
    find_bt_win = fifth_page.create_window( 650, 400, anchor = "nw", window = find_bt )

    root.mainloop()

def sortImage() :

     # Defining Structure
    sixth_page = Canvas( root,
                          width = wid, height = hgt,
                           bg = "black", highlightcolor = "#3c5390",
                            borderwidth = 0 )
    sixth_page.pack( fill = "both", expand = True )

    # Background Image
    back_image = Imgo( os.path.join( os.getcwd(), "Background\Sort_Image_Page.jpg" ), 1498, 875)
    sixth_page.create_image( 0, 0, image = back_image , anchor = "nw")

    # Heading
    sixth_page.create_text( 400, 120, text = "Sort Images",
                                font = ( ft[0], 45, "bold" ), fill = "#1c54df" )

    # Return Button
    ret = Imgo( os.path.join( os.getcwd(), r'Design\arrow.png' ), 45, 35)
    ret_bt = ctk.CTkButton( master = root,
                             image = ret, text = None,
                              width = 60, height = 40, corner_radius = 23,
                               bg_color = "#d3eafc", fg_color = "red",
                                hover_color = "#ff5359", border_width = 0,
                                 command = lambda : change( sixth_page, menuPage) )
    ret_bt_win = sixth_page.create_window( 30, 20, anchor = "nw", window = ret_bt )

    # Accessing the folder1
    folder1_path = ctk.CTkEntry( master = root,
                                  placeholder_text = "Enter Folder 1 Path", text_font = ( ft[4], 20 ),
                                   width = 580, height = 30, corner_radius = 14,
                                    placeholder_text_color = "#494949", text_color = "#242424",
                                     fg_color = "#c3c3c3", bg_color = "#d3eafc",
                                      border_color = "white", border_width = 3)
    folder1_path_win = sixth_page.create_window( 300, 210, anchor = "nw", window = folder1_path )

    # Browse folde1 button
    browse_bt_1 = ctk.CTkButton( master = root,
                                  text = "Browse", text_font = ( ft[1], 20 ),
                                    width = 100, height = 40, corner_radius = 14,
                                     bg_color = "#d3eafc", fg_color = "red", text_color = "white",
                                      hover_color = "#ff5359", border_width = 0,
                                       command = lambda : openingFolder( folder1_path ) )
    browse_bt_1_win = sixth_page.create_window( 1035, 210-2, anchor = "nw", window = browse_bt_1 )

    # Accessing the folder2
    folder2_path = ctk.CTkEntry( master = root,
                                  placeholder_text = "Enter Folder 2 Path", text_font = ( ft[4], 20 ),
                                   width = 580, height = 30, corner_radius = 14,
                                    placeholder_text_color = "#494949", text_color = "#242424",
                                     fg_color = "#c3c3c3", bg_color = "#d3eafc",
                                      border_color = "white", border_width = 3)
    folder2_path_win = sixth_page.create_window( 300, 295, anchor = "nw", window = folder2_path )

    # Browse folder2 button
    browse_bt_2 = ctk.CTkButton( master = root,
                                  text = "Browse", text_font = ( ft[1], 20 ),
                                    width = 100, height = 40, corner_radius = 14,
                                     bg_color = "#d3eafc", fg_color = "red", text_color = "white",
                                      hover_color = "#ff5359", border_width = 0,
                                       command = lambda : openingFolder2( folder2_path ) )
    browse_bt_2_win = sixth_page.create_window( 1035, 295-2, anchor = "nw", window = browse_bt_2 )

    # Sorting button
    sort_bt = ctk.CTkButton( master = root,
                                text = "Start Sorting", text_font = ( ft[0], 24 ),
                                  width = 250, height = 45, corner_radius = 14,
                                   bg_color = "#99e2fe", fg_color = "red", text_color = "white",
                                    hover_color = "#ff5359", border_width = 0,
                                     command = lambda : sortingImages() )
    sort_bt_win = sixth_page.create_window( 610, 540, anchor = "nw", window = sort_bt )

    root.mainloop()

def menuPage() :

    # Defining Structure
    second_page = Canvas( root,
                           width = wid, height = hgt,
                            bg = "black", highlightcolor = "#3c5390",
                             borderwidth = 0 )
    second_page.pack( fill = "both", expand = True )

    # Background Image
    back_image = Imgo( os.path.join( os.getcwd(), "Background\Menu_Page.jpg" ), 1498, 875)
    second_page.create_image( 0, 0, image = back_image , anchor = "nw")

    # Heading
    second_page.create_text( 350, 120, text = "Content...",
                                font = ( ft[0], 45, "bold" ), fill = "#1c54df" )

    # Back Ground remover page window
    backRem = Imgo( os.path.join( os.getcwd(), "Design\Clear_Back_logo.png" ), 220, 200 )
    backRem_bt = ctk.CTkButton( master = root,
                                 image = backRem, compound = "top",
                                  text = "Clear Back", text_font = ( ft[0], 22, "bold" ),
                                   text_color = "white",
                                    width = 230, height = 240, corner_radius = 10,
                                     bg_color = "#d3eafc", fg_color = "#2d435b",
                                      hover_color = "#fdbf38", border_width = 0,
                                       command = lambda : change( second_page, clearBack ))
    backRem_bt_win = second_page.create_window( 190, 250, anchor = "nw", window = backRem_bt)

    # Image converter page window
    imgConvert = Imgo( os.path.join( os.getcwd(), "Design\Convert_Img_logo.png" ), 220, 200 )
    imgConvert_bt = ctk.CTkButton( master = root,
                                    image = imgConvert, compound = "top",
                                     text = "Converter", text_font = ( ft[0], 22, "bold" ),
                                      text_color = "white",
                                       width = 230, height = 240, corner_radius = 10,
                                        bg_color = "#d3eafc", fg_color = "#2d435b",
                                         hover_color = "#fdbf38", border_width = 0,
                                          command = lambda : change( second_page, convertImage ))
    imgConvert_bt_win = second_page.create_window( 500, 400, anchor = "nw", window = imgConvert_bt )

    # Search image page window
    findImg = Imgo( os.path.join( os.getcwd(), "Design\Find_Img_logo.png" ), 220, 200 )
    findImg_bt = ctk.CTkButton( master = root,
                                 image = findImg, compound = "top",
                                  text = "Find Image", text_font = ( ft[0], 22, "bold" ),
                                   text_color = "white",
                                    width = 230, height = 240, corner_radius = 10,
                                     bg_color = "#d3eafc", fg_color = "#2d435b",
                                      hover_color = "#fdbf38", border_width = 0,
                                       command = lambda : change( second_page, findImage ))
    findImg_bt_win = second_page.create_window( 810, 250, anchor = "nw", window = findImg_bt )

    # Sort image page window
    imgSort =Imgo( os.path.join( os.getcwd(), "Design\Sort_Img_logo.png" ), 220, 200 )
    imgSort_bt = ctk.CTkButton( master = root,
                                 image = imgSort, compound = "top",
                                  text = "Sort Images", text_font = ( ft[0], 22, "bold" ),
                                   text_color = "white",
                                    width = 230, height = 240, corner_radius = 10,
                                     bg_color = "#d3eafc", fg_color = "#2d435b",
                                      hover_color = "#fdbf38",  border_width = 0,
                                       command = lambda : change( second_page, sortImage ))
    imgSort_bt_win = second_page.create_window( 1120, 400, anchor = "nw", window = imgSort_bt )

    # Logout button
    log = Imgo( os.path.join( os.getcwd(), "Design\logout.png" ), 35, 35 )
    log_bt = ctk.CTkButton( master = root,
                             image = log, text = None,
                              width = 45, height = 45, corner_radius = 23,
                               bg_color = "#357adf", fg_color = "red",
                                hover_color = "#ff5359", border_width = 0,
                                 command = lambda : change( second_page, loginPage ))
    log_bt_win = second_page.create_window( 1420, 20, anchor = "nw", window = log_bt )

    root.mainloop()

def loginPage() :

    global user, pwrd, first_page

    # Defining Structure
    first_page = Canvas( root,
                          width = wid, height = hgt,
                           bg = "black", highlightcolor = "#3c5390",
                            borderwidth = 0 )
    first_page.pack( fill = "both", expand = True )

    # Background Image
    back_image = Imgo( os.path.join( os.getcwd(), "Background\Login_Page.jpg" ), 1498, 875)
    design_image = Imgo( os.path.join( os.getcwd(), "Design\Login_Design.png" ), 600, 400)
    first_page.create_image( 0, 0, image = back_image , anchor = "nw")
    first_page.create_image( 350, 325, image = design_image, anchor = "nw")

    # Heading
    first_page.create_text( 450, 150, text = "Image Sorter",
                                font = ( ft[0], 45, "bold" ), fill = "#1c54df" )
    first_page.create_text( 1150, 380, text = "Welcome\n    Back",
                                font = ( ft[0], 26, "bold" ), fill = "#0b4bf5" )

    # Entry of username and password
    user = ctk.CTkEntry( master = root,
                          placeholder_text = "Username", text_font = ( ft[1], 20 ),
                           width = 220, height = 30, corner_radius = 14,
                            placeholder_text_color = "#666666", text_color = "#191919",
                             fg_color = "#e1f5ff", bg_color = "#9ae2fe",
                              border_color = "white", border_width = 3)
    user_win = first_page.create_window( 1015, 470, anchor = "nw", window = user )

    pwrd = ctk.CTkEntry( master = root,
                          placeholder_text = "Password", text_font = ( ft[1], 20 ),
                           width = 220, height = 30, corner_radius = 14,
                            placeholder_text_color = "#666666", text_color = "#191919",
                             fg_color = "#e1f5ff", bg_color = "#9ae2fe",
                              border_color = "white", border_width = 3, show = "*" )
    pwrd_win = first_page.create_window( 1015, 550, anchor = "nw", window = pwrd )

    # Login button
    log_bt = ctk.CTkButton( master = root,
                             text = "Login", text_font = ( ft[0], 22 ),
                              text_color = "white",
                               width = 50, height = 25, corner_radius = 15,
                                bg_color = "#9ae2fe", fg_color = "red",
                                 hover_color = "#ff5359", border_width = 0,
                                  command = lambda : checkLogin( first_page, menuPage, user, pwrd ))
    log_bt_win = first_page.create_window( 1090, 650, anchor = "nw", window = log_bt )

    root.mainloop()

if __name__  == "__main__" :

    # Defining Main theme of all widgets
    ctk.set_appearance_mode( "dark" )
    ctk.set_default_color_theme( "dark-blue" )
    wid = 1200
    hgt = 700

    global root

    root = ctk.CTk()
    root.title( "Image Sorter" )
    root.iconbitmap( os.path.join( os.getcwd(), "Design\Project_Icon.ico" ))
    root.geometry( "1200x700+200+80" )
    root.resizable( False, False )
    ft = [ "Tahoma", "Seoge UI", "Heloia", "Book Antiqua", "Microsoft Sans Serif"]
    values = [ "", np.array([0,0,0]), "", np.array([0,0,0]), ""]
    matches = set()

    loginPage()


# Enter your code here. Read input from STDIN. Print output to STDOUT
if __name__ == '__main__':
    n = int(input())
    #print(n)
    input_string = input()
    numbers = list(map(int, input_string.split()))
    #mean
    numbersum = sum(numbers)
   # print (numbersum)
    mean = numbersum/n
    print (mean)
    #meadian
    numbers.sort()
    #print (numbers)
    if (n %2 ==1):
        median = numbers[int(n/2)-1]
    else:
        middle = [int(n/2)-1,int(n/2)]
        denominator = [numbers[i] for i in middle]
        #print (denominator)
        donominatorsum = sum(denominator)
        #print (donominatorsum)
        median = donominatorsum/2
    print (median)

    from collections import Counter
    c = Counter(numbers)
    print (c.most_common(1)[0][0])