from ..common.common_imports import *
from ..common.files import *
from dataclasses import dataclass
import os
from pathlib import Path
from evdspy.EVDSlocal.messages.error_classes import BucketFromSeriesFolderCreateError
from evdspy.EVDSlocal.config.config import *
from ..config.apikey_class import ApikeyClass
from ..initial.start_args import Args
from ..components.options_class import Options, load_options, SingletonOptions, read_user_options_on_load
from evdspy.EVDSlocal.initial.start_options import default_data_folder_name, Default_Prefix_
from evdspy.EVDSlocal.components.bucket_from_series import BucketFromSeriesFile, null_BucketFromSeriesFile
from evdspy.EVDSlocal.components.url_class import URLClass
from evdspy.EVDSlocal.components.api_params import Series, DateStart, DateEnd, dataTypeParam, dataTypeEnum
from typing import Tuple, Union, List
from rich import inspect

# ------------------------------------------------------------------------------
# -------------------------------------------------EvdsSeri----------------------
@dataclass
class EvdsSeri:
    """
    EvdsSeri
    """
    ID: str
    bfs: BucketFromSeriesFile
    name: str = ""
    subject: str = ""

    def __repr__(self):
        content = f"""
        <EvdsSeri>
            ID : {self.ID}
            name : {self.name}
            subject : {self.subject}
            bfs : {self.bfs}
        </EvdsSeri>
"""
        # print(content)
        return content

#   ----------------------------------------------------------    / EvdsSeri
liste = ('TP.IHRACATBEC.9999', 'TP.IHRACATBEC.31', 'TP.IHRACATBEC.41')
seri_evds_test_objs = tuple(EvdsSeri(x, bfs=null_BucketFromSeriesFile) for x in liste)

# ------------------------------------------------------------------------------
# /*
#               EvdsSeriesRequest
#
# ------------------------------------------------------------------------------
# */
@dataclass
class EvdsSeriesRequest:
    bfs: BucketFromSeriesFile
    options_: Optional[Options] = load_options()
    # series_list: field(default_factory=list) = field(default_factory=list[seri_evds_test_objs])
    series_list: field(default_factory=list) = tuple(seri_evds_test_objs)
    complete_url_instance: URLClass = None

    def __post_init__(self):
        read_user_options_on_load()
        self.start_date: str = SingletonOptions().get_valid_value("default_start_date")
        self.end_date: str = SingletonOptions().get_valid_value("default_end_date")
        self.update_url_instance()

    def update_url_instance(self):
        """_summary_
        update_url_instance
        """

        date_start: DateStart = DateStart(value=self.start_date)
        date_end: DateEnd = DateEnd(value=self.end_date)
        type_param = dataTypeParam(value=dataTypeEnum.csv)

        slist: Tuple[str] = tuple(x.ID for x in self.series_list)
        series_instance = Series(slist)
        full_list = [series_instance, date_start, date_end, type_param]

        complete_url_instance = URLClass(full_list)

        number_of_series = len(slist)
        # ADD other params from file
        complete_url_instance.add_formulas(self.bfs.formulas, number_of_series)
        complete_url_instance.add_frequency(self.bfs.frequency)
        complete_url_instance.add_aggtype(self.bfs.aggregateType, number_of_series)
        api_key = ApikeyClass().get_valid_api_key()
        complete_url_instance.add_apikey(api_key)
        self.complete_url_instance = URLClass(complete_url_instance.url_items)
        self.complete_url_instance.refresh_url()
        self.complete_url_instance.create_report()

#   ----------------------------------------------------------    / EvdsSeriesRequest
test_series_ = EvdsSeriesRequest(options_=load_options(), series_list=seri_evds_test_objs,
                                 bfs=null_BucketFromSeriesFile)
# ------------------------------------------------------------------------------
# /*
#               EvdsSeriesRequestWrapper(s)
#
# ------------------------------------------------------------------------------
# */
from abc import ABC, abstractmethod

@dataclass
class EvdsSeriesRequestWrapper():
    name: str
    subject: str
    EvdsSeriesRequest_: EvdsSeriesRequest
    bfs: BucketFromSeriesFile = None  # field(default=null_BucketFromSeriesFile)

    # bfs: BucketFromSeriesFile = null_BucketFromSeriesFile

    def __post_init__(self):
        self.EvdsSeriesRequest_.bfs = self.bfs

def EvdsSeriesRequestWrapperBasic(name: str, subject: str, EvdsSeriesRequest_: EvdsSeriesRequest):
    bfs = BucketFromSeriesFile(name, subject, prefix=Default_Prefix_)
    return EvdsSeriesRequestWrapper(name, subject, EvdsSeriesRequest_, bfs)

def EvdsSeriesRequestWrapperFromFile(bfs: BucketFromSeriesFile, EvdsSeriesRequest_: EvdsSeriesRequest):
    return EvdsSeriesRequestWrapper(bfs.subject, bfs.subject, EvdsSeriesRequest_, bfs)

#   ----------------------------------------------------------    / EvdsSeriesRequestWrapper
__all__ = [
    'EvdsSeriesRequest',
    'test_series_',
    'EvdsSeri',
    'EvdsSeriesRequestWrapper',
    'EvdsSeriesRequestWrapperFromFile',
    'EvdsSeriesRequestWrapperBasic',
]


from input_classes.interface import Interface
import pygame

class Human(Interface):
    def __init__(self):
        self.key_converter = {
            1073741906 : "up",
            1073741905 : "down",
            1073741904 : "left",
            1073741903 : "right"
        }

    def get_action(self, world):
        key_l = []
        for event in pygame.event.get():
            pressed_key = "Not pressed"

            if event.type == pygame.locals.QUIT:
                return "Quit"

            elif event.type == pygame.locals.KEYDOWN:
                pressed_key = event.key

            key_l.append(pressed_key)

        if len(key_l) == 0:
            key_l.append("Not pressed")

        action_list = list(filter(lambda x: x!="Not pressed", key_l))

        if len(action_list) == 0:
            return "Not pressed"
        else:
            return self.key_converter.get(action_list[0], "Not pressed")


import requests
from lxml import etree
from time import sleep
from opencontext_py.libs.generalapi import GeneralAPI

class OaiPmhClientAPI():
    """ A simple, not fully functional client API for OAI-PMH services
    """

    NAMESPACES = {
        'oai': 'http://www.openarchives.org/OAI/2.0/',
        'oai_dc': 'http://www.openarchives.org/OAI/2.0/oai_dc/',
        'dc': 'http://purl.org/dc/elements/1.1/',
        'xsi': 'http://www.w3.org/2001/XMLSchema-instance'
    }
    SLEEP_TIME = .5

    def __init__(self):
        self.request_error = False
        self.delay_before_request = self.SLEEP_TIME
        self.graph = False
        self.request_url = False

    def get_list_records(self, url, resumption_token=None):
        """
        gets OAI-PMH list records, with an optional resumption_token
        """
        xml = None
        params = None
        if 'verb=ListRecords' not in url:
            params = {}
            params['verb'] = 'ListRecords'
        if isinstance(resumption_token, str):
            if '?' in url:
                # do this to avoid URL encoding the resumption token
                url += '&resumptionToken=' + resumption_token
            else:
                url += '?resumptionToken=' + resumption_token
        if self.delay_before_request > 0:
            # default to sleep BEFORE a request is sent, to
            # give the remote service a break.
            sleep(self.delay_before_request)
        url_content = None
        if isinstance(params, dict):
            try:
                gapi = GeneralAPI()
                r = requests.get(url,
                                 params=params,
                                 timeout=240,
                                 headers=gapi.client_headers)
                self.request_url = r.url
                r.raise_for_status()
                url_content = r.content
            except:
                self.request_error = True
                url_content = None
        else:
            try:
                gapi = GeneralAPI()
                r = requests.get(url,
                                 timeout=240,
                                 headers=gapi.client_headers)
                self.request_url = r.url
                r.raise_for_status()
                url_content = r.content
            except:
                self.request_error = True
                url_content = None
        return url_content


import os
import json
import pandas as pd
from datetime import datetime

now = datetime.now()
print('start time : ', now.strftime('%Y-%m-%d %H:%M:%S'))

path = r'D:\project\구문검사결과지\test'
path_to = r'D:\project\구문검사결과지\results'
csvanme = r'results.csv'

df_total = pd.DataFrame(columns=['파일명', '오류 위치','검사 항목','검사 조건','오류 값','오류 메시지'])
list_filename = []
list_errorposition = []
list_testele = []
list_testcondition = []
list_errorvalue = []
list_errormessage = []

list_json = os.listdir(path)

totalcount_errorele = 0
totalcount_errorfile = 0
totalcount_file = len(list_json)
totalcount_ele = 0

for json_ in list_json:
    path_json = os.path.join(path, json_)

    with open(path_json, "r", encoding='UTF8') as json_ele:
        dict_jsoncontents = json.load(json_ele)

    count_errorele = 0
    count_ele = 0

    #####################################
    ###          images 검사          ###
    #####################################

    # /images/id 검사
    if dict_jsoncontents['images']['id'] == '':
        list_filename.append(json_)
        list_errorposition.append('/images/id')
        list_testele.append('필수여부')
        list_testcondition.append(' ')
        list_errorvalue.append(' ')
        list_errormessage.append('_')
        count_errorele +=1
        count_ele += 1
    else:
        count_ele += 1

    # /images/width 검사
    if dict_jsoncontents['images']['width'] == '' :
        list_filename.append(json_)
        list_errorposition.append('/images/width')
        list_testele.append('최소값')
        list_testcondition.append('400')
        list_errorvalue.append(dict_jsoncontents['images']['width'])
        list_errormessage.append('_')
        count_errorele +=1
        count_ele += 1

    elif int(dict_jsoncontents['images']['width']) < 400 :
        list_filename.append(json_)
        list_errorposition.append('/images/width')
        list_testele.append('최소값')
        list_testcondition.append('400')
        list_errorvalue.append(dict_jsoncontents['images']['width'])
        list_errormessage.append('_')
        count_errorele +=1
        count_ele += 1

    else:
        count_ele += 1

    # /images/height 검사
    if dict_jsoncontents['images']['height'] == '' :
        list_filename.append(json_)
        list_errorposition.append('/images/height')
        list_testele.append('최소값')
        list_testcondition.append('400')
        list_errorvalue.append(dict_jsoncontents['images']['height'])
        list_errormessage.append('_')
        count_errorele +=1
        count_ele += 1

    elif int(dict_jsoncontents['images']['height']) < 400 :
        list_filename.append(json_)
        list_errorposition.append('/images/height')
        list_testele.append('최소값')
        list_testcondition.append('400')
        list_errorvalue.append(dict_jsoncontents['images']['height'])
        list_errormessage.append('_')
        count_errorele +=1
        count_ele += 1

    else:
        count_ele += 1

    # /images/filename 검사
    if dict_jsoncontents['images']['filename'] == '':
        list_filename.append(json_)
        list_errorposition.append('/images/filename')
        list_testele.append('필수여부')
        list_testcondition.append(' ')
        list_errorvalue.append(' ')
        list_errormessage.append('_')
        count_errorele +=1
        count_ele += 1
    else:
        count_ele += 1

    # /images/volume 검사
    if 'volume' in  dict_jsoncontents['images'].keys():
        count_ele += 1

    #####################################
    ###          metas 검사           ###
    #####################################

    # /metas/id 검사
    if 'id' in dict_jsoncontents['metas'].keys():
        count_ele += 1

    # /metas/age 검사
    if dict_jsoncontents['metas']['age'] == '':
        list_filename.append(json_)
        list_errorposition.append('/metas/age')
        list_testele.append('필수여부')
        list_testcondition.append(' ')
        list_errorvalue.append(' ')
        list_errormessage.append('_')
        count_errorele +=1
        count_ele += 1
    else:
        count_ele += 1

    # /metas/gender 검사
    if dict_jsoncontents['metas']['gender'] not in ['M', 'F']:
        list_filename.append(json_)
        list_errorposition.append('/metas/gender')
        list_testele.append('유효값')
        list_testcondition.append("\"M\",\"F\"")
        list_errorvalue.append(dict_jsoncontents['metas']['gender'])
        list_errormessage.append('_')
        count_errorele +=1
        count_ele += 1
    else:
        count_ele += 1

    # /metas/phase 검사
    if dict_jsoncontents['metas']['phase'] not in ['Velum', 'OTE']:
        list_filename.append(json_)
        list_errorposition.append('/metas/phase')
        list_testele.append('유효값')
        list_testcondition.append("\"Velum\",\"OTE\"")
        list_errorvalue.append(dict_jsoncontents['metas']['phase'])
        list_errormessage.append('_')
        count_errorele +=1
        count_ele += 1
    else:
        count_ele += 1

    # /metas/position 검사
    if dict_jsoncontents['metas']['position'] not in ['awake', 'supine','lateral','resupine']:
        list_filename.append(json_)
        list_errorposition.append('/metas/position')
        list_testele.append('유효값')
        list_testcondition.append("\"awake\",\"supine\",\"lateral\",\"resupine\"")
        list_errorvalue.append(dict_jsoncontents['metas']['position'])
        list_errormessage.append('_')
        count_errorele +=1
        count_ele += 1
    else:
        count_ele += 1

    # /metas/SpO2 검사
    if dict_jsoncontents['metas']['SpO2'] == '':
        list_filename.append(json_)
        list_errorposition.append('/metas/SpO2')
        list_testele.append('필수여부')
        list_testcondition.append(' ')
        list_errorvalue.append(' ')
        list_errormessage.append('_')
        count_errorele +=1
        count_ele += 1
    else:
        count_ele += 1

    # /metas/AHI 검사
    if dict_jsoncontents['metas']['AHI'] == '':
        list_filename.append(json_)
        list_errorposition.append('/metas/AHI')
        list_testele.append('필수여부')
        list_testcondition.append(' ')
        list_errorvalue.append(' ')
        list_errormessage.append('_')
        count_errorele +=1
        count_ele += 1
    else:
        count_ele += 1

    # /metas/bmi 검사
    if 'bmi' in dict_jsoncontents['metas'].keys():
        count_ele += 1

    # /metas/position 검사
    if dict_jsoncontents['metas']['obstruction'] not in ['no', 'partial','complete']:
        list_filename.append(json_)
        list_errorposition.append('/metas/obstruction')
        list_testele.append('유효값')
        list_testcondition.append("\"no\",\"partial\",\"complete\"")
        list_errorvalue.append(dict_jsoncontents['metas']['obstruction'])
        list_errormessage.append('_')
        count_errorele +=1
        count_ele += 1
    else:
        count_ele += 1

    # /metas/cause 검사
    if dict_jsoncontents['metas']['cause'] not in ['no', 'Velum','Tongue_Base','Epiglottis']:
        list_filename.append(json_)
        list_errorposition.append('/metas/cause')
        list_testele.append('유효값')
        list_testcondition.append("\"no\",\"Velum\",\"Tongue_Base\",\"Epiglottis\"")
        list_errorvalue.append(dict_jsoncontents['metas']['cause'])
        list_errormessage.append('_')
        count_errorele +=1
        count_ele += 1
    else:
        count_ele += 1

    #####################################
    ###        annoatation 검사       ###
    #####################################

    for annotation_ele in dict_jsoncontents['annotations']:

        # /annotation/id 검사
        if annotation_ele['id'] == '':
            list_filename.append(json_)
            list_errorposition.append('/annotations/id')
            list_testele.append('필수여부')
            list_testcondition.append(' ')
            list_errorvalue.append(' ')
            list_errormessage.append('_')
            count_errorele +=1
            count_ele += 1
        else:
            count_ele += 1

        # /annotation/image_id 검사
        if annotation_ele['image_id'] == '':
            list_filename.append(json_)
            list_errorposition.append('/annotations/image_id')
            list_testele.append('필수여부')
            list_testcondition.append(' ')
            list_errorvalue.append(' ')
            list_errormessage.append('_')
            count_errorele +=1
            count_ele += 1
        else:
            count_ele += 1

        # /annotation/category_id 검사
        if annotation_ele['category_id'] not in ['6000', '6001','6002','6003','6004','6005']:
            list_filename.append(json_)
            list_errorposition.append('/annotations/category_id')
            list_testele.append('유효값')
            list_testcondition.append("\"6000\",\"6001\",\"6002\",\"6003\",\"6004\",\"6005\"")
            list_errorvalue.append(annotation_ele['category_id'])
            list_errormessage.append('_')
            count_errorele +=1
            count_ele += 1
        else:
            count_ele += 1

        # /annotation/category_name 검사
        if annotation_ele['category_name'] not in ['Velum', 'Airway1','Posterior_lateral_wall','Tongue_Base','Epiglottis','Airway2']:
            list_filename.append(json_)
            list_errorposition.append('/annotations/category_name')
            list_testele.append('유효값')
            list_testcondition.append("\"Velum\",\"Airway1\",\"Posterior_lateral_wall\",\"Tongue_Base\",\"Epiglottis\",\"Airway2\"")
            list_errorvalue.append(annotation_ele['category_name'])
            list_errormessage.append('_')
            count_errorele +=1
            count_ele += 1
        else:
            count_ele += 1

        # /annotation/type 검사
        if annotation_ele['type'] not in ['poly']:
            list_filename.append(json_)
            list_errorposition.append('/annotations/type')
            list_testele.append('유효값')
            list_testcondition.append("\"poly\"")
            list_errorvalue.append(annotation_ele['type'])
            list_errormessage.append('_')
            count_errorele +=1
            count_ele += 1
        else:
            count_ele += 1

        # /annotation/color 검사
        if annotation_ele['color'] == '':
            list_filename.append(json_)
            list_errorposition.append('/annotations/color')
            list_testele.append('필수여부')
            list_testcondition.append(' ')
            list_errorvalue.append(' ')
            list_errormessage.append('_')
            count_errorele +=1
            count_ele += 1
        else:
            count_ele += 1

        # /annotation/points 검사
        if annotation_ele['points'] == []:
            list_filename.append(json_)
            list_errorposition.append('/annotations/points')
            list_testele.append('필수여부')
            list_testcondition.append(' ')
            list_errorvalue.append(' ')
            list_errormessage.append('_')
            count_errorele +=1
            count_ele += 1
        else:
            count_ele += 1

            for points_ele in annotation_ele['points']:

                # /annotation/points/[] 검사
                if points_ele == []:
                    list_filename.append(json_)
                    list_errorposition.append('/annotations/points/[]')
                    list_testele.append('필수여부')
                    list_testcondition.append(' ')
                    list_errorvalue.append(' ')
                    list_errormessage.append('_')
                    count_errorele +=1
                    count_ele += 1
                else:
                    count_ele += 1

    totalcount_errorele += count_errorele
    totalcount_ele += count_ele

    if count_errorele > 0 :
        totalcount_errorfile += 1

df_total['파일명'] = list_filename
df_total['오류 위치'] = list_errorposition
df_total['검사 항목'] = list_testele
df_total['검사 조건'] = list_testcondition
df_total['오류 값'] = list_errorvalue
df_total['오류 메시지'] = list_errormessage

path_results = os.path.join(path_to, csvanme)
df_total.to_csv(path_results, encoding = 'cp949', index = False)

print('정확도(파일): ', round(((totalcount_file-totalcount_errorfile)/totalcount_file)*100,2),'%')
print('정확도(항목): ', round(((totalcount_ele-totalcount_errorele)/totalcount_ele)*100,2),'%')
print('오류 건수(파일): ', totalcount_errorfile)
print('오류 건수(항목): ', totalcount_errorele)
print('전체 건수(파일): ', totalcount_file)
print('전체 건수(항목): ', totalcount_ele)

now = datetime.now()
print('end time : ', now.strftime('%Y-%m-%d %H:%M:%S'))


import string

all_groups = []
group_badges = []
item_priority = list('0' + string.ascii_lowercase + string.ascii_uppercase)

with open('input.txt') as f:
    for line in f.read().split('\n'):
        all_groups.append(line)

for key, value in enumerate(all_groups):
    if key % 3 == 0:
        temp_badge_var = []
        for item in all_groups[key]:
            if item in all_groups[key + 1] and item in all_groups[key + 2] and item not in temp_badge_var:
                temp_badge_var.append(item)
        group_badges += temp_badge_var

print(f"All elf group badges: {group_badges}")

sum_of_priorities = sum([item_priority.index(item) for item in group_badges])

print(f"Sum of item priorities: {sum_of_priorities}")


import torch
import torch.nn as nn

"""
Build loss functions for SegDetector.
Details about the built functions:
Input:
    pred: A dict which contains predictions.
        prob: The text segmentation prediction.
        thresh: The threshold prediction
        binary: Value produced by `step_function(prob - thresh)`.
    target:
        gt: Text regions bitmap gt.
        mask: Ignore mask, pixels where value is 1 indicates no contribution to loss.
        thresh_mask: Mask indicates regions cared by thresh supervision.
        thresh_map: Threshold gt.
Return:
    (loss, metrics).
    loss: A scalar loss value.
    metrics: A dict contraining partial loss values.
"""

class BalanceBCELoss(nn.Module):
    '''
    DiceLoss on prob.
    For SegDetector without adaptive module.
    '''

    def __init__(self, eps=1e-6):
        super(BalanceBCELoss, self).__init__()
        from .balance_cross_entropy_loss import BalanceCrossEntropyLoss
        self.loss = BalanceCrossEntropyLoss(eps=eps)

    def forward(self, pred, target):
        loss = self.loss(pred['prob'], target['gt'], target['mask'])
        return loss, dict(dice_loss=loss)

class AdaptiveDiceLoss(nn.Module):
    '''
    Integration of DiceLoss on both prob prediction and binary prediction.
    '''

    def __init__(self, eps=1e-6):
        super(AdaptiveDiceLoss, self).__init__()
        from .dice_loss import DiceLoss
        self.main_loss = DiceLoss(eps)
        self.binary_loss = DiceLoss(eps)

    def forward(self, pred, target):
        prob = pred['prob']
        binary = pred['binary']
        gt = target['gt']
        mask = target['mask']
        main_loss = self.main_loss(prob, gt, mask)
        binary_loss = self.binary_loss(binary, gt, mask)
        loss = main_loss + binary_loss
        return loss, dict(main_loss=main_loss, binary_loss=binary_loss)

class AdaptiveInstanceDiceLoss(nn.Module):
    '''
    InstanceDiceLoss on both prob and bianry.
    '''

    def __init__(self, iou_thresh=0.2, thresh=0.3):
        super(AdaptiveInstanceDiceLoss, self).__init__()
        from .dice_loss import InstanceDiceLoss, DiceLoss
        self.main_loss = DiceLoss()
        self.main_instance_loss = InstanceDiceLoss(threshold=thresh, iou_thresh=iou_thresh)
        self.binary_loss = DiceLoss()
        self.binary_instance_loss = InstanceDiceLoss(threshold=thresh, iou_thresh=iou_thresh)
        self.weights = nn.ParameterDict(
            dict(main=nn.Parameter(torch.ones(1)),
                 thresh=nn.Parameter(torch.ones(1)),
                 main_instance=nn.Parameter(torch.ones(1)),
                 binary_instance=nn.Parameter(torch.ones(1))
            )
        )

    def partial_loss(self, weight, loss):
        return loss / weight + 0.5 * torch.log(weight)

    def forward(self, pred, target):
        main_loss = self.main_loss(pred['prob'], target['gt'], target['mask'])
        binary_loss = self.binary_loss(pred['binary'], target['gt'], target['mask'])
        main_instance_loss = self.main_instance_loss(pred['prob'], target['gt'], target['mask'])
        binary_instance_loss = self.binary_instance_loss(pred['binary'], target['gt'], target['mask'])
        loss = self.partial_loss(self.weights['main'], main_loss) \
               + self.partial_loss(self.weights['thresh'], binary_loss) \
               + self.partial_loss(self.weights['main_instance'], main_instance_loss) \
               + self.partial_loss(self.weights['binary_instance'], binary_instance_loss)
        metrics = dict(main_loss=main_loss,
                       binary_loss=binary_loss,
                       main_instance_loss=main_instance_loss,
                       binary_instance_loss=binary_instance_loss)

        metrics.update(self.weights)
        return loss, metrics

class L1DiceLoss(nn.Module):
    '''
    L1Loss on thresh, DiceLoss on prob and binary.
    '''

    def __init__(self, eps=1e-6, l1_scale=10):
        super(L1DiceLoss, self).__init__()
        self.dice_loss = AdaptiveDiceLoss(eps=eps)
        from .l1_loss import MaskL1Loss
        self.l1_loss = MaskL1Loss()
        self.l1_scale = l1_scale

    def forward(self, pred, target):
        dice_loss, metrics = self.dice_loss(pred, target)
        l1_loss, l1_metric = self.l1_loss(pred['thresh'], target['thresh_map'], target['thresh_mask'])

        loss = dice_loss + self.l1_scale * l1_loss
        metrics.update(**l1_metric)
        return loss, metrics

class FullL1DiceLoss(L1DiceLoss):
    '''
    L1loss on thresh, pixels with topk losses in non-text regions are also counted.
    DiceLoss on binary and prob.
    '''

    def __init__(self, eps=1e-6, l1_scale=10):
        nn.Module.__init__(self)
        self.dice_loss = AdaptiveDiceLoss(eps=eps)
        from .l1_loss import BalanceL1Loss
        self.l1_loss = BalanceL1Loss()
        self.l1_scale = l1_scale

class L1BalanceCELoss(nn.Module):
    '''
    Balanced CrossEntropy Loss on `prob`,
    MaskL1Loss on `thresh`,
    DiceLoss on `binary`.
    '''
    def __init__(self, eps=1e-6, l1_scale=10, bce_scale=5):
        super(L1BalanceCELoss, self).__init__()
        from .dice_loss import DiceLossV2
        from .l1_loss import MaskL1Loss
        from .balance_cross_entropy_loss import BalanceCrossEntropyLossV2
        self.dice_loss = DiceLossV2(eps=eps)
        self.l1_loss = MaskL1Loss()
        self.bce_loss = BalanceCrossEntropyLossV2()

        self.l1_scale = l1_scale
        self.bce_scale = bce_scale

    def forward(self, pred, target):
        bce_loss = self.bce_loss(pred['prob'], target['gt'], target['mask'])
        metrics = dict(bce_loss=bce_loss)
        if 'thresh' in pred:
            l1_loss, l1_metric = self.l1_loss(pred['thresh'], target['thresh_map'], target['thresh_mask'])
            dice_loss = self.dice_loss(pred['binary'], target['gt'], target['mask'])
            metrics['binary_loss'] = dice_loss
            loss = dice_loss + self.l1_scale * l1_loss + bce_loss * self.bce_scale
            metrics.update(**l1_metric)
        else:
            loss = bce_loss
        return loss, metrics

class L1BCEMiningLoss(nn.Module):
    '''
    Basicly the same with L1BalanceCELoss, where the bce loss map is used as
        attention weights for DiceLoss
    '''

    def __init__(self, eps=1e-6, l1_scale=10, bce_scale=5):
        super(L1BCEMiningLoss, self).__init__()
        from .dice_loss import DiceLoss
        from .l1_loss import MaskL1Loss
        from .balance_cross_entropy_loss import BalanceCrossEntropyLoss
        self.dice_loss = DiceLoss(eps=eps)
        self.l1_loss = MaskL1Loss()
        self.bce_loss = BalanceCrossEntropyLoss()

        self.l1_scale = l1_scale
        self.bce_scale = bce_scale

    def forward(self, pred, target):
        bce_loss, bce_map = self.bce_loss(pred['prob'], target['gt'], target['mask'], return_origin=True)
        l1_loss, l1_metric = self.l1_loss(pred['thresh'], target['thresh_map'], target['thresh_mask'])
        bce_map = (bce_map - bce_map.min()) / (bce_map.max() - bce_map.min())
        dice_loss = self.dice_loss(pred['binary'], target['gt'], target['mask'], weights=bce_map + 1)
        metrics = dict(bce_loss=bce_loss, binary_loss=dice_loss)
        loss = dice_loss + self.l1_scale * l1_loss + bce_loss * self.bce_scale
        metrics.update(**l1_metric)
        return loss, metrics

class L1LeakyDiceLoss(nn.Module):
    '''
    LeakyDiceLoss on binary, MaskL1Loss on thresh, DiceLoss on binary.
    '''

    def __init__(self, eps=1e-6, coverage_scale=5, l1_scale=10):
        super(L1LeakyDiceLoss, self).__init__()
        from .dice_loss import DiceLoss, LeakyDiceLoss
        from .l1_loss import MaskL1Loss
        self.main_loss = LeakyDiceLoss(coverage_scale=coverage_scale)
        self.l1_loss = MaskL1Loss()
        self.binary_loss = DiceLoss(eps=eps)

        self.l1_scale = l1_scale

    def forward(self, pred, target):
        main_loss, metrics = self.main_loss(pred['prob'], target['gt'], target['mask'])
        binary_loss = self.binary_loss(pred['binary'], target['gt'], target['mask'])
        l1_loss, l1_metric = self.l1_loss(pred['thresh'], target['thresh_map'], target['thresh_mask'])
        metrics.update(**l1_metric, binary_loss=binary_loss)
        loss = main_loss + binary_loss + l1_loss * self.l1_scale
        return loss, metrics


# QUESTION 1:
# Input: Given a list of numbers separated with a comma. The numbers 5 and 8 are present in the list.
# Assume that 8 always comes after 5.
# Case 1: num1 -> Add all numbers which do not lie between 5 and 8 in the Input List.
# Case 2: num2 -> Numbers formed by concatenating all numbers from 5 to 8 in the list
# Output: Sum of num1 and num2
# Example: 3,2,6,5,1,4,8,9
# Num1: 3+2+6+9 =20
# Num2: 5148O/p=5148+20 = 5168

if __name__ == '__main__':
    list1 = [3, 2, 6, 5, 1, 4, 8, 9, 1, 2, 3]
    list2 = []
    for i in list1:
        if i == 5:
            break
        else:
            list2.append(i)
    j = list1.index(8)
    for k in range(j+1, len(list1)):
        list2.append(list1[k])
    num1 = sum(list2)
    num2 = 0
    for k in range(list1.index(5), list1.index(8)+1):
        num2 = num2*10+list1[k]
    print(list2)
    print(num1)
    print(num2)
    print(num2+num1)
    print(num1-num2)


import discord, json, typing, datetime, asyncio
from discord.ext import commands
from utils import errors, checks

def get_embed(title, description='', color=0xf4fa72):
    return discord.Embed(title=title,description=description,color=color)

class profile(commands.Cog):
    def __init__(self, client):
        self.client = client
        self.pool = self.client.pool
        self.checks = checks.checks(self.pool)

        self._profile_setup.add_check(self.checks.registered)

    @commands.group(name = "프로필", invoke_without_command = True)
    async def _profile(self, ctx, user: typing.Optional[discord.Member] = None):
        if ctx.guild is None:
            await ctx.send(embed=get_embed("<a:no:698461934613168199> | 서버내에서만 사용가능한 명령어 입니다.",0xff0000))
            return
        if not user: user = ctx.author

        try:
            st = str(user.status)
            if st == "online": sta = ":green_circle: 온라인"
            elif st == "offline": sta = ":black_circle: 오프라인"
            elif st == "idle": sta = ":yellow_circle: 자리 비움"
            else: sta = ":no_entry: 방해 금지"
        except: sta = "불러오는데 실패"

        if str(user.id) in self.pool: embcolor = int(self.pool[str(user.id)]["profile"]["color"], 16)
        else: embcolor = 0xf4fa72
        embed = discord.Embed(title=f"👤 | **{user.name} 님의 프로필**", description=("" if user.name == user.display_name else f"**서버내 닉네임**: {user.display_name}\n") + f'**유저 ID**: {user.id}\n**현재 상태**: {sta}',color=embcolor)
        embed.set_thumbnail(url=user.avatar_url)

        date = datetime.datetime.utcfromtimestamp(((int(user.id) >> 22) + 1420070400000)/1000)
        embed.add_field(name="Discord 가입 일시", value=str(date.year) + "년 " + str(date.month) + "월 " + str(date.day) + "일 ")
        joat = user.joined_at.isoformat()
        embed.add_field(name="서버 가입 일시", value=joat[0:4]+'년 '+joat[5:7]+'월 '+joat[8:10]+'일')

        if user.bot:
            embed.add_field(name="봇 초대장 생성",value=f"[초대장](https://discord.com/oauth2/authorize?client_id={user.id}&scope=bot&permissions=0)")
        else:
            if user.guild_permissions.administrator: embed.add_field(name="서버 권한", value="Admin")
            else: embed.add_field(name="서버 권한", value="User")
            if str(user.id) in self.pool.keys():
                if self.pool[str(user.id)]["profile"]["money_open"]:
                    reinlist = [[k, v["starforce"]] for k, v in self.pool[str(user.id)]["reinforce"].items() if v["level"] >= 100]
                    str_ = [f':star:**x{i[1]}** {i[0]}' for i in reinlist]
                    embed.add_field(
                        name="Lemon System",
                        value=f">>> **Permission**: {self.pool[str(user.id)]['permission']}\n" +
                        ("\n**블랙리스트에 등재된 유저입니다!**" if self.pool[str(user.id)]['blacklist'] else
                        f"**Money**: {self.pool[str(user.id)]['money']}원\n" +
                        f"**bank**: {self.pool[str(user.id)]['bank']}원\n" +
                        f"**100레벨 이상 강화 아이템 갯수** : {len(reinlist)}개\n" + ', '.join(str_)
                        )
                    )
                else:
                    embed.add_field(
                        name = "Lemon System",
                        value = "프로필 비공개 유저입니다!"
                    )
        await ctx.send(embed=embed)

    @_profile.command(name = "설정")
    async def _profile_setup(self, ctx):
        color = hex(int(self.pool[str(ctx.author.id)]["profile"]["color"], 16))
        show = "공개" if self.pool[str(ctx.author.id)]["profile"]["money_open"] else "비공개"
        des = f"✏ : 프로필 색 변경 (현재 색 {color})\n🔍 : 프로필 비공개 설정 (현재 {show})\n❌ : 취소"
        msg = await ctx.send(embed=get_embed("⚙ | 프로필 설정", des))
        emjs=["✏", "🔍", "❌"]
        for i in emjs:
            await msg.add_reaction(i)
        def check(reaction, user):
            return user == ctx.author and msg.id == reaction.message.id and str(reaction.emoji) in emjs
        try:
            reaction, user = await self.client.wait_for('reaction_add', check=check, timeout=60)
        except asyncio.TimeoutError:
            await asyncio.gather(msg.delete(),ctx.send(embed=get_embed('⏰ | 시간이 초과되었습니다!',"", 0xFF0000)))
            return
        else:
            e = str(reaction.emoji)
            if e == "✏":

                await ctx.send(f"프로필 카드 색을 변경합니다!\n현재 색은 **{color}**입니다.\n변경할 색을 **0x를 붙인 HEX코드로** 적어주세요!")

                def check(author):
                    def inner_check(message):
                        if message.author != author: return False
                        else: return True
                    return inner_check

                try: msg = await self.client.wait_for('message',check=check(ctx.author),timeout=20)
                except asyncio.TimeoutError:
                    self.gaming_list.remove(ctx.author.id)
                    await ctx.send(embed=get_embed('⏰ | 시간이 초과되었습니다!',"", 0xFF0000))
                    return
                else:
                    n = msg.content
                    await ctx.send(n)
                    try: scan = str(hex(int(n, 16)))
                    except: await ctx.send("올바르지 않은 입력 양식입니다!")
                    else:
                        if (n is not scan) or not (0 < int(n,16) < 376926741):
                            self.pool[str(user.id)]["profile"]["color"] = n
                            color = self.pool[str(user.id)]["profile"]["color"]
                            await ctx.send(f"프로필 카드 색을 {color}로 변경하였습니다!")
                            return

                    await ctx.send("올바르지 않은 입력 양식입니다!")

            elif e == "🔍":
                self.pool[str(ctx.author.id)]["profile"]["money_open"] = ~self.pool[str(ctx.author.id)]["profile"]["money_open"]
                show = "공개" if self.pool[str(ctx.author.id)]["profile"]["money_open"] else "비공개"
                await ctx.send(f"프로필을 {show}상태로 변경합니다!")

            elif e == "❌":
                await ctx.send("취소되었습니다.")

def setup(client):
    client.add_cog(profile(client))


import os
import re

resDIR = "C:/Users/fhc_workPC1/Documents/Looker/MFCC data by Looker/MFCC with Labels for Health"
tarFILE = "C:/Users/fhc_workPC1/Documents/Looker/MFCC data by Looker/fileListForHealth.txt"

files = os.listdir(resDIR)

with open(tarFILE, 'w', errors='ignore') as of:
    for f in files:
        f = f.strip('1_')
        f = f.strip('_MFCC.txt')
        of.write(f+'\n')


import random
from datetime import datetime

from django.core.cache import cache
from django.db import connection
from django.db.models import Q, Count
from django.shortcuts import render

# Create your views here.
from django.views import View
from ArticleManageSystem.settings import DATETIME_FORMAT
from common.models import Article, Content, FeedBack, Comment, Tag, CommentFeedBack
from utils.common_mixin import FrontLoggedMixin, FrontMixin

class UserArticleView(FrontLoggedMixin, View):
    def get_template(self):
        if self.if_list:
            self.model = Article
            page = self.request.GET.get("page")
            if not page:
                most_hot = Article.objects.filter(is_deleted=0,
                                                  status=4).values("title", "id").order_by("-read_times")[:5]
                most_comment = Comment.objects.filter(article__is_deleted=0, article__status=4)\
                    .values("article__title", "article_id").annotate(count=Count("article_id")).order_by("-count")[:5]
                self.context.update({"most_hot": most_hot, "most_comment": most_comment})
            self.template = "article_o/article_list_add.html"
        else:
            id = self.request.GET.get("id")
            id = int(id)
            self.model = Content
            self.template = "article_o/article_detail_4.html"
            good_view = FeedBack.objects.filter(article_id=id, feed_back=1).count()
            bad_view = FeedBack.objects.filter(article_id=id, feed_back=2).count()
            comments = Comment.objects.filter(article_id=id)
            for comment in comments:
                comment.good_view = CommentFeedBack.objects.filter(comment_id=comment.id, feed_back=1).count()
                comment.bad_view = CommentFeedBack.objects.filter(comment_id=comment.id, feed_back=2).count()
            comm_count = comments.count()
            this_tags = tuple(Article.objects.get(id=id).tags.all().values_list("id", flat=True))
            sql = "SELECT distinct a.id, a.title FROM common_article a left join common_article_tags t " \
                  "on a.id = t.article_id WHERE t.tag_id in %s and a.id != %s and a.status=4 and is_deleted=0"
            cursor = connection.cursor()
            cursor.execute(sql, [this_tags, id])
            if_like = list(cursor.fetchall())
            random.shuffle(if_like)
            extra = {}
            extra["if_like"] = if_like[:4]
            extra["article_id"] = id
            extra["good_view"] = good_view
            extra["bad_view"] = bad_view
            extra["comments"] = comments
            extra["comm_count"] = comm_count
            self.context.update(extra)

    def get_list_values(self):
        """
        如果不需要重命名就用字符串，否则前面写跨表的方式，values跨表用双下划线，后面写要改的名字
        """
        self.list_values = [
            "id",
            "img",
            "title",
            "author",
            "pub_time",
            ["category__name", "category_name"],
            # ["content__content", "content_val"],
        ]

    def get_detail_values(self):
        """
        如果不需要重命名就用字符串，否则前面写跨表的方式，详情跨表用点，后面写要改的名字
        """
        self.detail_values = [
            "content",
            ["article.title", "title"],
            ["article_id", "id"],
            ["article.category.name", "category"], ["article.tags.all().values('name', 'id')", "tags"],
            ["article.author", "author"]
        ]

    def get_change(self, request):
        if not self.if_list:
            obj_id = request.GET.get("id")
            try:
                obj = Article.objects.get(id=obj_id)
            except Exception:
                self.template = "public/error.html"
            else:
                obj.read_times += 1
                obj.last_read_time = datetime.now().strftime(DATETIME_FORMAT)
                obj.save()

    def get(self, request):
        cur_page = request.GET.get("page", "1")
        if cur_page != "1":
            self.is_ajax = 1
        self.and_field = {"status": 4, "is_deleted": 0}
        self.detail_id_field = "article_id"
        self.get_list_values()
        self.get_detail_values()
        self.get_change(request)
        if self.template:
            return render(request, self.template)
        self.get_template()
        return super().get(request)

class DianZan(FrontMixin, View):
    def post(self, request):
        id = request.POST.get("id")
        view = int(request.POST.get("view"))
        extra = {}
        extra["is_view"] = 0
        user = self.user_id
        check = FeedBack.objects.filter(article_id=id, user_id=user)
        if check:
            obj = check.first()
            if obj.feed_back == view:
                extra["is_view"] = 1
            else:
                obj.feed_back = view
            obj.save()
        else:
            FeedBack.objects.create(article_id=id, user_id=user, feed_back=view)
        self.is_ajax = 1
        good_view = FeedBack.objects.filter(article_id=id, feed_back=1).count()
        bad_view = FeedBack.objects.filter(article_id=id, feed_back=2).count()
        extra["good_view"] = good_view
        extra["bad_view"] = bad_view
        self.context.update(extra)
        return super().post(request)

class CommentView(FrontMixin, View):
    def post(self, request):
        user = self.user_id
        id = request.POST.get("id")
        content = request.POST.get("content")
        parent_id = request.POST.get("parent_id")
        Comment.objects.create(article_id=id, parent_comment_id=parent_id, content=content, user_id=user)
        extra = {}
        extra["comments"] = Comment.objects.filter(article_id=id)
        self.is_ajax = 1
        return super().post(request)

class CommentDianZan(FrontMixin, View):
    def post(self, request):
        id = request.POST.get("id")
        view = int(request.POST.get("view"))
        extra = {}
        extra["is_view"] = 0
        user_id = self.user_id
        check = CommentFeedBack.objects.filter(comment_id=id, user_id=user_id)
        if check:
            obj = check.first()
            if obj.feed_back == view:
                extra["is_view"] = 1
            else:
                obj.feed_back = view
            obj.save()
        else:
            CommentFeedBack.objects.create(comment_id=id, user_id=user_id, feed_back=view)
        self.is_ajax = 1
        good_view = CommentFeedBack.objects.filter(comment_id=id, feed_back=1).count()
        bad_view = CommentFeedBack.objects.filter(comment_id=id, feed_back=2).count()
        extra["good_view"] = good_view
        extra["bad_view"] = bad_view
        self.context.update(extra)
        return super().post(request)


import logging
import sys
import time
from logging import Logger

import matplotlib.pyplot as plt
from adjustText import adjust_text

from cobras_ts.cobras import COBRAS
from cobras_ts.cobras_logger import ClusteringLogger
from datasets import Dataset
from evaluate_clusterings.evaluation.ari import get_ARI
from generate_clusterings.algorithms.my_mpckmeans import MyMPCKMeans
from generate_clusterings.algorithms.my_npu import NPU
from generate_clusterings.algorithms.noise_robust_npu import NoiseRobustNPU
from querier.labelquerier import LabelQuerier
from querier.noisy_labelquerier import ProbabilisticNoisyQuerier

counter = 0

def plotting(logger, ground_truth_querier):
    # use latex for font rendering
    # mpl.rcParams['text.usetex'] = True
    global counter
    # plt.ion()
    fig, phase_plot = plt.subplots(1, 1, sharex='all', figsize=(18, 8))
    # ari_plot.plot(ari)

    # all the user constraints that have been received
    all_user_constraint = logger.all_user_constraints
    all_noisy_user_constraints = [(idx, con) for idx, con in enumerate(all_user_constraint) if
                                  ground_truth_querier._query_points(*con.get_instance_tuple()) != con.is_ML()]

    # the constraints that are detected as noisy
    detected_noisy_data = logger.detected_noisy_constraint_data

    phase_data = logger.algorithm_phases

    phase_plot.plot(phase_data)

    texts = []
    # plot constraint reusage
    # for x, (correctly_reused, wrongly_reused, _) in enumerate(logger.constraint_reusing_data):
    #     if correctly_reused > 0:
    #         phase_plot.scatter([x], [phase_data[x]], marker='o', c='tab:blue', s=40)
    #     if wrongly_reused > 0:
    #         phase_plot.scatter([x], [phase_data[x]], marker='o', c='tab:red', s=30)

    for (x, detected_noisy_constraint) in detected_noisy_data:

        if x < len(phase_data):

            # print(detected_noise, constraint_type, i1, i2)

            real_constraint_type = ground_truth_querier._query_points(detected_noisy_constraint.i1,
                                                                      detected_noisy_constraint.i2)
            phase_plot.scatter([x], [phase_data[x]], marker='D', c='g', s=90)
            if real_constraint_type != detected_noisy_constraint.is_ML():  # the detected noise was indeed noisy
                text = phase_plot.text(x, phase_data[x], str(detected_noisy_constraint), color="green", ha="center",
                                       va="center")
            else:
                text = phase_plot.text(x, phase_data[x], str(detected_noisy_constraint), color="tab:orange",
                                       ha="center",
                                       va="center")
            texts.append(text)
    for idx, noisy_constraint in all_noisy_user_constraints:
        constraint_str = str(noisy_constraint)
        phase_plot.scatter([idx], [phase_data[idx]], marker='x', c='r', s=50)
        text = phase_plot.text(idx, phase_data[idx], constraint_str, color='red', ha='center', va='center')
        texts.append(text)
    adjust_text(texts, arrowprops=dict(arrowstyle='->', color='black'), only_move={'points': 'y', 'text': 'y'})
    phase_plot.set_xticks(range(0, 61, 1), [str(n) if n % 5 == 0 else "" for n in range(0, 61)])
    plt.ylabel("Algorithm phase")
    plt.xlabel("#queries")
    plt.tight_layout()
    plt.show()
    counter += 1

    # plt.waitforbuttonpress()

    plt.close(fig)

def simpleRun(dataset_name):
    start = time.time()
    dataset = Dataset(dataset_name)

    basic_logger = Logger("cobras", logging.DEBUG)
    handler = logging.StreamHandler(sys.stderr)
    handler.setFormatter(logging.Formatter('[%(levelname)s] %(message)s'))
    basic_logger.addHandler(handler)

    cobras_logger = ClusteringLogger()
    ALGO_TO_USE = "cobras"
    if ALGO_TO_USE == "cobras":
        clusterer = COBRAS(minimum_approximation_order=3, maximum_approximation_order=5, noise_probability=0.05,
                           certainty_threshold=0.95, correct_noise=True,
                           logger=basic_logger, cobras_logger=cobras_logger)

        # logger.vis = ConstraintGraphVisualisation(clusterer)
        clusterings, _, _, _ = clusterer.fit(dataset.data, -1, None,
                                             ProbabilisticNoisyQuerier(cobras_logger, dataset.target, 0.05, 100))

        logger = clusterer._cobras_log

    elif ALGO_TO_USE == 'nnpu-mpck':
        clusterer = NoiseRobustNPU(MyMPCKMeans(), 3, 8, 0.05, 0.95, cobras_logger)
        clusterings, _, _, _ = clusterer.fit(dataset.data, dataset.number_of_classes(), None,
                                             ProbabilisticNoisyQuerier(cobras_logger, dataset.target, 0.05, 50))
        logger = clusterer.logger

    elif ALGO_TO_USE == 'npu-mpck':
        clusterer = NPU(MyMPCKMeans())
        clusterings, _,_,_ = clusterer.fit(dataset.data, dataset.number_of_classes(), None, ProbabilisticNoisyQuerier(None, dataset.target, 0.05,50))
        logger = None
    else:
        raise Exception(f"unknown algorithm to use {ALGO_TO_USE}")
    # print(clustering, dataset.target)
    end = time.time()
    ground_truth_querier =LabelQuerier(None, dataset.target, None)
    print("took: ", end - start)
    # print("correctly reused", sum([x for x, _, _ in logger.constraint_reusing_data]))
    # print("wrongly reused", sum([x for _, x, _ in logger.constraint_reusing_data]))
    print("produced ARI:", get_ARI(clusterings[-1], dataset.target))
    aris = [get_ARI(cluster, dataset.target) for cluster in clusterings]
    fig, ax = plt.subplots(1,1)
    ax.plot(aris)
    fig.show()
    if logger is not None:
        print("corrected_constraint_set + mistakes:")
        # logger.add_mistake_information(ground_truth_querier)
        # for constraint_number, _, mistakes in logger.corrected_constraint_sets:
        #     print("\t", constraint_number, ")", len(mistakes), "mistakes ", mistakes)
        plotting(logger, ground_truth_querier)

if __name__ == '__main__':
    # while True:
    simpleRun("iris")


import os
import asyncio
import copy
import json
import heapq
import logging
import operator
from collections import Counter
from collections.abc import Mapping
from .backends.message import SendMessage, TellMessage
from ..typing import BandType

logger = logging.getLogger(__name__)

MARS_ENABLE_PROFILING = int(os.environ.get("MARS_ENABLE_PROFILING", 0))

class _ProfilingOptionDescriptor:
    def __init__(self, _type, default):
        self._name = None
        self._type = _type
        self._default = default

    def __get__(self, obj, cls):
        if obj is None:
            return self
        v = obj._options.get(self._name)
        if v is None:
            v = os.environ.get(f"MARS_PROFILING_{self._name.upper()}", self._default)
        if v is not None:
            v = self._type(v)
        # Cache the value.
        obj.__dict__[self._name] = v
        return v

    def set_name(self, name: str):
        self._name = name

class _ProfilingOptionsMeta(type):
    def __init__(cls, name, bases, classdict):
        super(_ProfilingOptionsMeta, cls).__init__(name, bases, classdict)
        for k, v in classdict.items():
            if isinstance(v, _ProfilingOptionDescriptor):
                v.set_name(k)

class _ProfilingOptions(metaclass=_ProfilingOptionsMeta):
    debug_interval_seconds = _ProfilingOptionDescriptor(float, default=None)
    slow_calls_duration_threshold = _ProfilingOptionDescriptor(int, default=1)
    slow_subtasks_duration_threshold = _ProfilingOptionDescriptor(int, default=10)

    def __init__(self, options):
        if isinstance(options, Mapping):
            invalid_keys = options.keys() - type(self).__dict__.keys()
            if invalid_keys:
                raise ValueError(f"Invalid profiling options: {invalid_keys}")
            self._options = options
        elif options in (True, False, None):
            self._options = {}
        else:
            raise ValueError(f"Invalid profiling options: {options}")

class DummyOperator:
    @staticmethod
    def set(key, value):
        pass

    @staticmethod
    def inc(key, value):
        pass

    @staticmethod
    def nest(key):
        return DummyOperator

    @staticmethod
    def values():
        return []

    @staticmethod
    def empty():
        return True

class ProfilingDataOperator:
    __slots__ = ("_target",)

    def __init__(self, target):
        self._target = target

    def set(self, key, value):
        self._target[key] = value

    def inc(self, key, value):
        old = self._target.get(key, 0)
        self._target[key] = old + value

    def nest(self, key):
        v = self._target.setdefault(key, {})
        if not isinstance(v, dict):
            raise TypeError(
                f"The value type of key {key} is {type(v)}, but a dict is expected."
            )
        return ProfilingDataOperator(v)

    def values(self):
        return self._target.values()

    def empty(self):
        return len(self._target) == 0

class _CallStats:
    def __init__(self, options: _ProfilingOptions):
        self._options = options
        self._call_counter = Counter()
        self._slow_calls = []

    def collect(self, message, duration: float):
        key = (message.actor_ref.uid, message.content[0])
        self._call_counter[key] += 1
        if duration < self._options.slow_calls_duration_threshold:
            return
        key = (
            duration,
            message.actor_ref.uid,
            message.actor_ref.address,
            message.content,
        )
        try:
            if len(self._slow_calls) < 10:
                heapq.heappush(self._slow_calls, key)
            else:
                heapq.heapreplace(self._slow_calls, key)
        except TypeError:
            pass

    def to_dict(self) -> dict:
        most_calls = {}
        for name_tuple, count in self._call_counter.most_common(10):
            uid, method_name = name_tuple
            most_calls[f"{uid.decode('utf-8')}.{method_name}"] = count
        slow_calls = {}
        for duration, uid, address, content in sorted(
            self._slow_calls, key=operator.itemgetter(0), reverse=True
        ):
            method_name, _batch, args, kwargs = content
            slow_calls[
                f"[{address}]{uid.decode('utf-8')}.{method_name}(args={args}, kwargs={kwargs})"
            ] = duration
        return {"most_calls": most_calls, "slow_calls": slow_calls}

class _SubtaskStats:
    def __init__(self, options: _ProfilingOptions):
        self._options = options
        self._band_counter = Counter()
        self._slow_subtasks = []

    def collect(self, subtask, band: BandType, duration: float):
        band_address = band[0]
        self._band_counter[band_address] += 1
        if duration < self._options.slow_subtasks_duration_threshold:
            return
        key = (duration, band_address, subtask)
        try:
            if len(self._slow_subtasks) < 10:
                heapq.heappush(self._slow_subtasks, key)
            else:
                heapq.heapreplace(self._slow_subtasks, key)
        except TypeError:
            pass

    def to_dict(self) -> dict:
        band_subtasks = {}
        key = operator.itemgetter(1)
        if len(self._band_counter) > 10:
            items = self._band_counter.items()
            band_subtasks.update(heapq.nlargest(5, items, key=key))
            band_subtasks.update(reversed(heapq.nsmallest(5, items, key=key)))
        else:
            band_subtasks.update(
                sorted(self._band_counter.items(), key=key, reverse=True)
            )
        slow_subtasks = {}
        for duration, band, subtask in sorted(
            self._slow_subtasks, key=operator.itemgetter(0), reverse=True
        ):
            slow_subtasks[f"[{band}]{subtask}"] = duration
        return {"band_subtasks": band_subtasks, "slow_subtasks": slow_subtasks}

class _ProfilingData:
    def __init__(self):
        self._data = {}
        self._call_stats = {}
        self._subtask_stats = {}
        self._debug_task = {}

    def init(self, task_id: str, options=None):
        options = _ProfilingOptions(options)
        logger.info(
            "Init profiling data for task %s with debug interval seconds %s.",
            task_id,
            options.debug_interval_seconds,
        )
        self._data[task_id] = {
            "general": {},
            "serialization": {},
            "most_calls": {},
            "slow_calls": {},
            "band_subtasks": {},
            "slow_subtasks": {},
        }
        self._call_stats[task_id] = _CallStats(options)
        self._subtask_stats[task_id] = _SubtaskStats(options)

        async def _debug_profiling_log():
            while True:
                try:
                    r = self._data.get(task_id, None)
                    if r is None:
                        logger.info("Profiling debug log break.")
                        break
                    r = copy.copy(r)  # shadow copy is enough.
                    r.update(self._call_stats.get(task_id).to_dict())
                    r.update(self._subtask_stats.get(task_id).to_dict())
                    logger.warning("Profiling debug:\n%s", json.dumps(r, indent=4))
                except Exception:
                    logger.exception("Profiling debug log failed.")
                await asyncio.sleep(options.debug_interval_seconds)

        if options.debug_interval_seconds is not None:
            self._debug_task[task_id] = task = asyncio.create_task(
                _debug_profiling_log()
            )
            task.add_done_callback(lambda _: self._debug_task.pop(task_id, None))

    def pop(self, task_id: str):
        logger.info("Pop profiling data of task %s.", task_id)
        debug_task = self._debug_task.pop(task_id, None)
        if debug_task is not None:
            debug_task.cancel()
        r = self._data.pop(task_id, None)
        if r is not None:
            r.update(self._call_stats.pop(task_id).to_dict())
            r.update(self._subtask_stats.pop(task_id).to_dict())
        return r

    def collect_actor_call(self, message, duration: float):
        if self._call_stats:
            message_type = type(message)
            if message_type is SendMessage or message_type is TellMessage:
                for stats in self._call_stats.values():
                    stats.collect(message, duration)

    def collect_subtask(self, subtask, band: BandType, duration: float):
        if self._subtask_stats:
            stats = self._subtask_stats.get(subtask.task_id)
            if stats is not None:
                stats.collect(subtask, band, duration)

    def __getitem__(self, item):
        key = item if isinstance(item, tuple) else (item,)
        v = None
        d = self._data
        for k in key:
            v = d.get(k, None)
            if v is None:
                break
            else:
                d = v
        return DummyOperator if v is None else ProfilingDataOperator(v)

ProfilingData = _ProfilingData()


from __future__ import annotations

from pathlib import Path
from typing import Any

import albumentations as A
import cv2
import numpy as np
import torch
from omegaconf import DictConfig
from torch import Tensor, nn

from anomalib_extend.data import TaskType
from anomalib_extend.data.utils.boxes import masks_to_boxes

from anomalib_extend.deploy.inferencers.base_inferencer import Inferencer

class TorchInferencer(Inferencer):
    """PyTorch implementation for the inference.

    Args:
        path (str | Path): Path to Torch model weights.
        device (str): Device to use for inference. Options are auto, cpu, cuda. Defaults to "auto".
    """

    def __init__(
        self,
        path: str | Path,
        device: str = "auto",
    ) -> None:
        self.device = self._get_device(device)

        # Load the model weights.
        self.model = self.load_model(path)
        self.metadata = self._load_metadata(path)
        self.transform = A.from_dict(self.metadata["transform"])

    @staticmethod
    def _get_device(device: str) -> torch.device:
        """Get the device to use for inference.

        Args:
            device (str): Device to use for inference. Options are auto, cpu, cuda.

        Returns:
            torch.device: Device to use for inference.
        """
        if device not in ("auto", "cpu", "cuda", "gpu"):
            raise ValueError(f"Unknown device {device}")

        if device == "auto":
            device = "cuda" if torch.cuda.is_available() else "cpu"
        elif device == "gpu":
            device = "cuda"
        return torch.device(device)

    def _load_metadata(self, path: str | Path | None = None) -> dict | DictConfig:
        """Load metadata from file.

        Args:
            path (str | Path): Path to the model pt file.

        Returns:
            dict: Dictionary containing the metadata.
        """
        metadata = torch.load(path, map_location=self.device)["metadata"] if path else {}
        return metadata

    def load_model(self, path: str | Path) -> nn.Module:
        """Load the PyTorch model.

        Args:
            path (str | Path): Path to model ckpt file.

        Returns:
            (AnomalyModule): PyTorch Lightning model.
        """

        model = torch.load(path, map_location=self.device)["model"]
        model.eval()
        return model.to(self.device)

    def pre_process(self, image: np.ndarray) -> Tensor:
        """Pre process the input image by applying transformations.

        Args:
            image (np.ndarray): Input image

        Returns:
            Tensor: pre-processed image.
        """
        processed_image = self.transform(image=image)["image"]

        if len(processed_image) == 3:
            processed_image = processed_image.unsqueeze(0)

        return processed_image.to(self.device)

    def forward(self, image: Tensor) -> Tensor:
        """Forward-Pass input tensor to the model.

        Args:
            image (Tensor): Input tensor.

        Returns:
            Tensor: Output predictions.
        """
        return self.model(image)

    def post_process(self, predictions: Tensor, metadata: dict | DictConfig | None = None) -> dict[str, Any]:
        """Post process the output predictions.

        Args:
            predictions (Tensor): Raw output predicted by the model.
            metadata (dict, optional): Meta data. Post-processing step sometimes requires
                additional meta data such as image shape. This variable comprises such info.
                Defaults to None.

        Returns:
            dict[str, str | float | np.ndarray]: Post processed prediction results.
        """
        if metadata is None:
            metadata = self.metadata

        if isinstance(predictions, Tensor):
            anomaly_map = predictions.detach().cpu().numpy()
            pred_score = anomaly_map.reshape(-1).max()
        else:
            # NOTE: Patchcore `forward`` returns heatmap and score.
            #   We need to add the following check to ensure the variables
            #   are properly assigned. Without this check, the code
            #   throws an error regarding type mismatch torch vs np.
            if isinstance(predictions[1], (Tensor)):
                anomaly_map, pred_score = predictions
                anomaly_map = anomaly_map.detach().cpu().numpy()
                pred_score = pred_score.detach().cpu().numpy()
            else:
                anomaly_map, pred_score = predictions
                pred_score = pred_score.detach()

        # Common practice in anomaly detection is to assign anomalous
        # label to the prediction if the prediction score is greater
        # than the image threshold.
        pred_label: str | None = None
        if "image_threshold" in metadata:
            pred_idx = pred_score >= metadata["image_threshold"]
            pred_label = "Anomalous" if pred_idx else "Normal"

        pred_mask: np.ndarray | None = None
        if "pixel_threshold" in metadata:
            pred_mask = (anomaly_map >= metadata["pixel_threshold"]).squeeze().astype(np.uint8)

        anomaly_map = anomaly_map.squeeze()
        anomaly_map, pred_score = self._normalize(anomaly_maps=anomaly_map, pred_scores=pred_score, metadata=metadata)

        if isinstance(anomaly_map, Tensor):
            anomaly_map = anomaly_map.detach().cpu().numpy()

        if "image_shape" in metadata and anomaly_map.shape != metadata["image_shape"]:
            image_height = metadata["image_shape"][0]
            image_width = metadata["image_shape"][1]
            anomaly_map = cv2.resize(anomaly_map, (image_width, image_height))

            if pred_mask is not None:
                pred_mask = cv2.resize(pred_mask, (image_width, image_height))

        if self.metadata["task"] == TaskType.DETECTION:
            pred_boxes = masks_to_boxes(torch.from_numpy(pred_mask))[0][0].numpy()
            box_labels = np.ones(pred_boxes.shape[0])
        else:
            pred_boxes = None
            box_labels = None

        return {
            "anomaly_map": anomaly_map,
            "pred_label": pred_label,
            "pred_score": pred_score,
            "pred_mask": pred_mask,
            "pred_boxes": pred_boxes,
            "box_labels": box_labels,
        }


list = []
tuple = ()
items = ""

while items != "none":
    items = input("enter a grocery item, or none to exit: ")
    if items != "none":
        list.append(items)

print("Now go to the store! this is your item list: ")
for x in list:
    print(x)

while len(list) != 0:
    cart = input("what did you put in your cart?")
    if cart in list:
        for things in tuple:
            (cart, price, quantity) = things
        price = int(input("what was the price of the item? "))
        quantity = input("How many did you get? ")
        list.remove(cart)
    elif cart not in list:
        print("Item not in list. Enter an item that was previously added to the list")

print(tuple)
print("Go check out!")


from flask import render_template, session, url_for, redirect, send_from_directory, request, flash
from health_tracker import app, db
from health_tracker.forms import HealthForm, LoginForm, RegistrationForm
from health_tracker.models import Entry, User
from health_tracker.graphics import UserData
from datetime import datetime
from flask_login import current_user, login_user, login_required, logout_user
from werkzeug.urls import url_parse
import os

@app.route('/', methods=['post', 'get'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('survey'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(name=form.name.data).first()
        if user is None or not user.check_password(form.password.data):
            flash("Invalid name or password", 'error')
            return redirect(url_for('login'))
        login_user(user, remember=True)
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('survey')
        return redirect(next_page)
    return render_template('login.html', form=form)

@app.route('/logout')
def logout():
    logout_user()
    flash("Logged out.", 'info')
    return redirect(url_for('login'))

@app.route('/signup', methods=['post', 'get'])
def sign_up():
    sign_up_form = RegistrationForm()
    if sign_up_form.validate_on_submit():
        user = User(name=sign_up_form.name.data, password_hash="null")
        user.set_password(sign_up_form.password.data)
        db.session.add(user)
        db.session.commit()
        flash("Registration successful.", 'info')
        return redirect(url_for('login'))
    return render_template('sign_up.html', sign_up=sign_up_form)

@app.route('/survey', methods=['post', 'get'])
@login_required
def survey():
    name = current_user.name
    form = HealthForm()
    if request.method == 'POST' and form.validate():
        date_entry = form.date.data
        date = Entry.query.filter_by(name=name,
                                     date=datetime(date_entry.year, date_entry.month, date_entry.day)).first()
        if date:
            flash("That date already has an entry :(", "error")
            return render_template('survey.html', name=name.title(), form=form)
        entry = Entry(name=name,
                      date=datetime(date_entry.year, date_entry.month, date_entry.day),
                      hours_of_sleep=form.hours_of_sleep.data,
                      rest=form.rest.data,
                      fatigue=form.fatigue.data,
                      exercise=form.exercise.data,
                      meditation=form.meditation.data,
                      stress=form.stress.data,
                      emotion=form.emotion.data,
                      comfort=form.comfort.data,
                      arousal=form.arousal.data,
                      headache=form.headache.data,
                      cannabis=form.cannabis.data,
                      morning=form.morning.data
                      )
        db.session.add(entry)
        db.session.commit()
        return render_template('thank_you.html', name=name.title())
    else:
        return render_template('survey.html', name=name.title(), form=form)

@app.route('/data')
@login_required
def data():
    name = current_user.name
    user = UserData(name)
    user.get_data_sqlite()
    csv_file = '{}_data_{}.csv'.format(name, datetime.today().strftime("%Y"))
    xlsx_file = csv_file.replace('.csv', '.xlsx')
    if os.getcwd().endswith('health_tracker'):
        path = os.path.join(os.getcwd(), 'health_tracker', 'uploads')
    else:
        path = os.path.join(os.getcwd(), 'health_tracker', 'health_tracker', 'uploads')
    user.to_csv(os.path.join(path, csv_file))
    user.to_excel(os.path.join(path, xlsx_file))
    user.pygal_line_plot(['stress', 'fatigue', 'comfort', 'arousal', 'rest'])
    return render_template('data.html', user=user)

@app.route('/visualized_data')
@login_required
def visuals():
    name = current_user.name
    path = url_for('static', filename='{}_line_graph.svg'.format(name))
    return render_template('visuals.html', path=path)

@app.route('/download_csv')
@login_required
def download_csv():
    name = current_user.name
    file = '{}_data_{}.csv'.format(name, datetime.today().strftime("%Y"))
    if os.getcwd().endswith('health_tracker'):
        path = os.path.join(os.getcwd(), 'health_tracker', 'uploads')
    else:
        path = os.path.join(os.getcwd(), 'health_tracker', 'health_tracker', 'uploads')
    return send_from_directory(path, file, as_attachment=True)

@app.route('/download_xlsx')
@login_required
def download_xlsx():
    name = current_user.name
    file = '{}_data_{}.xlsx'.format(name, datetime.today().strftime("%Y"))
    if os.getcwd().endswith('health_tracker'):
        path = os.path.join(os.getcwd(), 'health_tracker', 'uploads')
    else:
        path = os.path.join(os.getcwd(), 'health_tracker', 'health_tracker', 'uploads')
    return send_from_directory(path, file, as_attachment=True)

@app.route('/table')
@login_required
def table():
    name = current_user.name
    user = UserData(name)
    user.get_data_sqlite()
    user.pandas_df
    html = user.build_table()
    return render_template('table.html', html=html)


from enum import Enum

class OrderStatus(Enum):
    PENDING = {
        "id": 1,
        "name": "PENDING",
    }
    CONFIRMED = {
        "id": 2,
        "name": "CONFIRMED",
    }
    DELIVERING = {
        "id": 3,
        "name": "DELIVERING",
    }
    DELIVERED = {
        "id": 4,
        "name": "DELIVERED",
    }
    CANCELED = {
        "id": 5,
        "name": "CANCELED",
    }
    COMPLETED = {
        "id": 6,
        "name": "COMPLETED"
    }
    NOTRECEIVED = {
        "id": 7,
        "name": "NOTRECEIVED"
    }

class PaymentMethod(Enum):
    DIRECT = {
        "id": 1,
        "name": "DIRECT"
    }
    PAYPAL = {
        "id": 2,
        "name": "PAYPAL"
    }


#!/bin/python3.9

class main():
	def __init__(self):
		self.uppercase = 0
		self.lowercase = 0
		self.vowels = 0
		self.consonants = 0
		self.space = 0
		self.string = ""

	def getstr(self):
		self.string = input("Enter the letter : ")

	def upper_case(self):
		for letter in self.string:
			if (letter.isupper()):
				self.uppercase += 1

	def lower_case(self):
		for letter in self.string:
			if (letter.islower()):
				self.lowercase += 1

	def vowvels(self):
		for letter in self.string:
			if (letter in ("A","a","E","e","I","i","O","o","U","u" )):
				self.vowels += 1

	def consonant(self):
		for letter in self.string:
			if (letter in ("A","a","E","e","I","i","O","o","U","u" )):
				self.consonants += 1

	def spaces(self):
		for letter in self.string:
			if (letter == " "):
				self.space += 1

	def execute(self):
		self.upper_case()
		self.lower_case()
		self.vowvels()
		self.consonant()
		self.spaces()

	def display(self):
		print("The Given Strings Contains ")
		print("%d Uppercase Letters " %self.uppercase)
		print("%d Lowercase Letters " %self.lowercase)
		print("%d Vowels Letters " %self.vowels)
		print("%d Consonants Letters " %self.consonants)
		print("%d space Letters " %self.space)

r = main()
r.getstr()
r.execute()
r.display()


import pygame
from modelo.Bala import *

class Nave(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load('img/nave/ovni-min.png')
        self.rect = self.image.get_rect()
        self.rect.centerx = 512
        self.rect.centery = 560
        self.speed = 0.3
        self.listaDisparo = []
        self.vida = True
        self.hearts = 3
        self.soundShot = pygame.mixer.Sound('sounds/disparo2.wav')

    def moverIZQ(self,time):
        if self.vida == True:
            if self.rect.left >= 0:
                self.rect.centerx -= self.speed * time

    def moverDER(self,time):
        if self.vida == True:
            if self.rect.right <= 1024:
                self.rect.centerx += self.speed * time

    def luces(self,timer,time):
        if int(timer/1000) == self.timeChange :
            self.timeChange += 1
            self.posimg += 1

            if self.posimg > len(self.lstimg) -1:
                self.posimg = 0
    def disparar(self):
        bala = Bala(self.rect.centerx,self.rect.top)
        self.listaDisparo.append(bala)
        self.soundShot.play()

    def dibujar(self,superficie):
        superficie.blit(self.image,self.rect)


#!/usr/bin/env python

from runtest import TestBase
import subprocess as sp

TDIR='xxx'

class TestCase(TestBase):
    def __init__(self):
        TestBase.__init__(self, 'sleep', result="""
# DURATION    TID     FUNCTION
            [32537] | main(1) {
            [32537] |   foo() {
            [32537] |     bar() {
   2.080 ms [32537] |       usleep(2000);
   2.084 ms [32537] |     } /* bar */
   2.102 ms [32537] |   } /* foo */
   2.103 ms [32537] | } /* main */
""")

    def build(self, cflags='', ldflags=''):
        if cflags.find('-finstrument-functions') >= 0:
            return TestBase.TEST_SKIP
        return TestBase.build(self, cflags, ldflags)

    def pre(self):
        record_cmd = "%s record -A %s -A %s -R %s -d %s %s" % \
                     (TestBase.ftrace, 'main@arg1', '(malloc|free|usleep)@plt,arg1', \
                      'malloc@retval', TDIR, 't-' + self.name)
        sp.call(record_cmd.split())
        return TestBase.TEST_SUCCESS

    def runcmd(self):
        return '%s replay -t 1ms -d %s' % (TestBase.ftrace, TDIR)

    def post(self, ret):
        sp.call(['rm', '-rf', TDIR])
        return ret

    def sort(self, output):
        """ This function post-process output of the test to be compare.
            It ignores blank and comment (#) lines and remaining functions. """
        result = []
        for ln in output.split('\n'):
            # ignore blank lines and comments
            if ln.strip() == '' or ln.startswith('#'):
                continue
            func = ln.split('|', 1)[-1]
            result.append(func)

        return '\n'.join(result)


import sys
import os
import h5py
import numpy as np
import torch
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import torchvision.transforms.functional as TF
import torchvision.transforms as T
from PIL import Image

DATA_FOLDER_PATH = './dataset/'

data_file_name = {
    'nyu' : 'nyu_depth_v2_labeled.mat'
}

class MyDataset(Dataset):
  ''''
  Characterizes a dataset for PyTorch
  '''
  def __init__(self, inputs, labels, transform=None, target_transform=None):
        'Initialization'
        self.images = inputs
        self.labels = labels
        self.N = self.images.shape[0]
        self.transform = transform
        self.target_transform = target_transform

  def __len__(self):
        'Denotes the total number of samples'
        return self.N

  def __getitem__(self, index):
        'Generates one sample of data'
        # Select sample
        label = self.labels[index, :]
        img = self.images[index, :]

        #print("")
        #print(label.shape)
        #print(img.shape)
        org_size = list(img.shape)[0:2]
        img = np.moveaxis(img,0,-1)
        #img = T.ToTensor()(img)
        #label = T.ToTensor()(label)
        #print(img.shape)
        #print(label.shape)

        img = T.ToPILImage()(img)
        label = T.ToPILImage()(label)

        #print(img.size)
        #print(label.size)

        #img = np.transpose(img,(1,2,0))

        #img = T.ToPILImage()(img)
        #label = T.ToPILImage()(label)

        if self.transform is not None:

            #color_jitter = T.ColorJitter(brightness, contrast, saturation, hue)
            #img = T.RandomApply([color_jitter],p=0.6)(img)
            img = T.RandomApply([T.Grayscale(num_output_channels=3)],p=0.2)(img)
            if np.random.rand() > .5:
                #print("rot")
                r = np.random.uniform(-5,5)
                img = TF.rotate(img,r)
                label = TF.rotate(label,r)

            if np.random.rand() > 1:
                #print("scale")
                s = np.random.randint(1,3)

                size = [x*s for x in org_size]
                img = TF.resize(img,size)
                img = TF.center_crop(img,org_size)

                label = TF.resize(label,size)
                label = TF.center_crop(label,org_size)
                label = T.ToPILImage()(np.array(label)/s)

            if np.random.rand() > .4:
                #print("flip")
                img = TF.hflip(img)
                label = TF.hflip(label)

        else:
            pass
            #print("CRAP")

        img = T.ToTensor()(img)
        label = T.ToTensor()(label)

        #if self.transform is not None:
        img = T.Normalize([0.5145, 0.4555, 0.4275],[0.2541, 0.2605, 0.2748])(img)*255
        #else:
        #    img = img

        label = torch.squeeze(label)
        #print(img.shape)
        #print(label.shape)

        sample = {'image': img, 'label': label}

        return sample

  def set_transform(self, transform):
        self.transform = transform

def load_nyu_data(path):
    """
    Load NYU depth v2 dataset

    Inputs:
    - path

    Returns:
    data_x: (N, 3, H, W) numpy array of pixel value
    data_y: (N, H, W) numpy array of depth value
    """
    with h5py.File(path, 'r') as f:
        data_x = np.swapaxes(np.array(f.get('images')), 2, 3) # f shape: (N, 3, W, H)
        data_y = np.swapaxes(np.array(f.get('depths')), 1, 2)

    x_train_data = data_x[:960, ]
    y_train_data = data_y[:960, ]
    x_val_data = data_x[960:1200, ]
    y_val_data = data_y[960:1200, ]
    x_test_data = data_x[1200:,]
    y_test_data = data_y[1200:,]

    # transform = T.Compose([
    #         T.ToTensor(),
    #         T.Normalize((125.0117, 107.3517, 101.7845), (67.4572, 69.5167, 71.9448))
    #     ])
    # data_x = np.zeros((1449, 3, 480, 640))
    # data_y = np.zeros((1449, 480, 640))

    train_data = MyDataset(data_x[:1040, ], data_y[:1040, ])
    val_data = MyDataset(data_x[1040:1300, ], data_y[1040:1300, ])
    test_data = MyDataset(data_x[1300:,], data_y[1300:,]) # use first image for visualization!

    #loader = DataLoader(train_data, batch_size=1, num_workers=1)
    #data = next(iter(loader))

    #print(np.array(data['image'].view(x_train_data.shape[0],x_train_data.shape[1],-1)*1.0).shape)
    #xmean = torch.sum((T.ToTensor()(np.array(data['image'].view(x_train_data.shape[0],x_train_data.shape[1],-1)*1.0))).mean(1),0)/x_train_data.shape[0]
    #xstd = torch.sum((T.ToTensor()(np.array(data['image'].view(x_train_data.shape[0],x_train_data.shape[1],-1)*1.0))).std(1),0)/x_train_data.shape[0]
    #ymean = torch.sum((T.ToTensor()(np.array(data['label'].view(y_train_data.shape[0],-1)*1.0))).mean(0),0)/y_train_data.shape[0]
    #ystd = torch.sum((T.ToTensor()(np.array(data['label'].view(y_train_data.shape[0],-1)*1.0))).std(0),0)/y_train_data.shape[0]

    #print(xmean)
    #print(ymean)
    #print(xstd)
    #print(ystd)
    #stop

    return train_data, val_data, test_data

def load_data(dataset):
    """
    Load dataset

    Inputs:
    - dataset: name of the dataset, which should match the key of `data_file_name`.

    Returns:
    - data_x: (N, C, H, W) numpy array of pixel value
    - data_y: (N, H, W) numpy array of depth value
    """
    data_path = os.path.join(DATA_FOLDER_PATH, data_file_name[dataset])
    train_data, val_data, test_data = load_nyu_data(data_path)
    return train_data, val_data, test_data

def calMeanStd(dataset):
    loader = DataLoader(
        dataset,
        batch_size=10,
        num_workers=1,
        shuffle=False
    )

    mean = 0.
    std = 0.
    nb_samples = 0.
    for d in loader:
        data = d['image'].to(dtype=torch.float32)
        batch_samples = data.size(0)
        data = data.view(batch_samples, data.size(1), -1)
        mean += data.mean(2).sum(0)
        std += data.std(2).sum(0)
        nb_samples += batch_samples

    mean /= nb_samples
    std /= nb_samples
    return mean, std


T = int(input())
d = ''

for t in range(1, T+1):
    a, b, c = map(int, input().split())
    if a == b:
        d = c
    else :
        d = a + b - c

    print(f'#{t} {d}')

SWEA/D3/3456. 직사각형 길이 찾기/직사각형 길이 찾기.py

직사각형 길이 찾기.py


import json

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 1.brandorder――柱状
def brandorder():
    plt.figure(figsize=(13, 9))
    with open("./json/brandOrder.json", 'r') as load_f:
        brandorder_list = json.load(load_f)
    x, y = [], []
    for br in brandorder_list:
        if br[1] > 1000:
            x.append(br[0])
            y.append(br[1])
    plt.bar(x, y, color='pink')
    ax1 = plt.gca()
    ax1.set_facecolor('#E6E6E6')
    plt.grid(b=True, color='#FFFFFF')
    for key, spine in ax1.spines.items():
        if key == 'right' or key == 'top' or key == 'left' or key == 'bottom':
            spine.set_visible(False)
    plt.legend(("各品牌用户数",))
    plt.xticks(rotation=30)
    plt.xlabel("品牌", size=18)
    plt.ylabel("用户数", size=18)
    plt.savefig("./img/brandorder.png")
    print("brandorder图保存成功！")
    plt.close()

# 2.brandsumofprice――柱状
def brandsumofprice():
    plt.figure(figsize=(13, 9))
    with open("./json/brandSumOfPrice.json", 'r') as load_f:
        brandsumofprice_list = json.load(load_f)
    x, y = [], []
    for br in brandsumofprice_list:
        if len(str(br[0])) > 7:
            x.append(br[0][:7] + "\n" + br[0][7:])
        else:
            x.append(br[0])
        y.append(br[1])

    plt.bar(x, y, color='pink')
    ax2 = plt.gca()
    ax2.set_facecolor('#E6E6E6')
    plt.grid(b=True, color='#FFFFFF')
    for key, spine in ax2.spines.items():
        if key == 'right' or key == 'top' or key == 'left' or key == 'bottom':
            spine.set_visible(False)

    plt.legend(("各品牌销售数据",))
    plt.xticks(rotation=30)
    plt.xlabel("品牌", size=18)
    plt.ylabel("销售额（千万）", size=18)
    plt.title("平台每月销量", size=18)
    plt.savefig("./img/brandsumofprice.png")
    print("brandsumofprice图保存成功！")
    plt.close()

# 3.categorysumofprice――柱状
def categorySumOfPrice():
    plt.figure(figsize=(13, 9))
    with open("./json/categorySumOfPrice.json", 'r') as load_f:
        categorySumOfPrice_list = json.load(load_f)
    x, y = [], []
    for br in categorySumOfPrice_list:
        x.append(br[0])
        y.append(br[1])
    plt.bar(x, y, color='#F781F3')
    plt.legend(("类别",))
    plt.savefig("./img/categorySumOfPrice.png")
    print("categorySumOfPrice图保存成功！")
    plt.close()

# 4.categoryuser――柱状
def categoryUser():
    plt.figure(figsize=(13, 9))
    with open("./json/categoryUser.json", 'r') as load_f:
        categoryUser_list = json.load(load_f)
    x, y = [], []
    for br in categoryUser_list:
        x.append(br[0])
        y.append(br[1])
    plt.bar(x, y)
    plt.legend(("类别",))
    plt.savefig("./img/categoryUser.png")
    print("categoryUser图保存成功！")
    plt.close()

# 5.hourorder――折线
def hourorder():
    plt.figure(figsize=(13, 9))
    with open("./json/HourOrder.json", 'r') as load_f:
        hourorder_list = json.load(load_f)
    x, y = [], []
    for br in hourorder_list:
        x.append(br[0])
        y.append(br[1])
    plt.plot(x, y, color='red')
    plt.xlabel("时间", size=18)
    plt.ylabel("用户购买量", size=18)
    plt.xticks(range(0, 25))
    plt.savefig("./img/hourorder.png")
    print("hourorder图保存成功！")
    plt.close()

# 6.monthorder――折线
def monthorder():
    with open("./json/MonthOrder.json", 'r') as load_f:
        monthorder_list = json.load(load_f)
    x, y = [], []
    for br in monthorder_list:
        x.append(br[0])
        y.append(br[1])
    plt.plot(x, y, color='pink')
    plt.xlabel("月份", size=18)
    plt.ylabel("销量", size=18)
    plt.savefig("./img/monthorder.png")
    print("monthorder图保存成功！")
    plt.close()

# 7.monthsumofprice――折线
def monthsumofprice():
    with open("./json/MonthSumOfPrice.json", 'r') as load_f:
        monthsumofprice_list = json.load(load_f)
    x, y = [], []
    for br in monthsumofprice_list:
        x.append(br[0])
        y.append(br[1])
    plt.title("每月消费总金额（单位/元）", size=18)
    ax3 = plt.gca()
    ax3.set_facecolor('#E6E6E6')
    plt.grid(b=True, color='#FFFFFF', axis='y')
    for key, spine in ax3.spines.items():
        if key == 'right' or key == 'top' or key == 'left' or key == 'bottom':
            spine.set_visible(False)
    plt.plot(x, y, color='pink')
    plt.savefig("./img/monthsumofprice.png")
    print("monthsumofprice图保存成功！")
    plt.close()

# 8.monthuser――折线
def monthuser():
    with open("./json/MonthUser.json", 'r') as load_f:
        monthuser_list = json.load(load_f)
    x, y = [], []
    for br in monthuser_list:
        x.append(br[0])
        y.append(br[1])
    plt.title("每月消费人数", size=18)
    ax4 = plt.gca()
    ax4.set_facecolor('#E6E6E6')
    plt.grid(b=True, color='#FFFFFF', axis='y')
    for key, spine in ax4.spines.items():
        if key == 'right' or key == 'top' or key == 'left' or key == 'bottom':
            spine.set_visible(False)
    plt.plot(x, y, color='pink')
    plt.savefig("./img/monthuser.png")
    print("monthuser图保存成功！")
    # plt.close()
    plt.show()

if __name__ == '__main__':
    # brandorder()
    # brandsumofprice()
    # categorySumOfPrice()
    # categoryUser()
    # hourorder()
    # monthorder()
    # monthsumofprice()
    monthuser()


import pytest
import numpy as np
import pandas as pd
from unittest import TestCase
from pingouin.distribution import (
    gzscore,
    normality,
    anderson,
    epsilon,
    homoscedasticity,
    sphericity,
)
from pingouin import read_dataset

# Generate random dataframe
df = read_dataset("mixed_anova.csv")
df_nan = df.copy()
df_nan.iloc[[4, 15], 0] = np.nan
df_pivot = df.pivot(index="Subject", columns="Time", values="Scores").reset_index(drop=True)

# Create random normal variables
np.random.seed(1234)
x = np.random.normal(scale=1.0, size=100)
y = np.random.normal(scale=0.8, size=100)
z = np.random.normal(scale=0.9, size=100)

# Two-way repeated measures (epsilon and sphericity)
data = read_dataset("rm_anova2")
idx, dv = "Subject", "Performance"
within = ["Time", "Metric"]
pa = data.pivot_table(index=idx, columns=within[0], values=dv)
pb = data.pivot_table(index=idx, columns=within[1], values=dv)
pab = data.pivot_table(index=idx, columns=within, values=dv)
# pab_single is a multilevel dataframe with shape columns.levshape = (1, 3)
pab_single = pab.xs("Pre", level=0, drop_level=False, axis=1)
# Create a 3-level mutlilevel columns (to test ValueError)
pab_3fac = pab_single.copy()
old_idx = pab_single.columns.to_frame()
old_idx.insert(0, "new_level_name", [0, 0, 0])
pab_3fac.columns = pd.MultiIndex.from_frame(old_idx)

# Two-way repeated measures (3, 4)
np.random.seed(123)
dv = np.random.normal(scale=3, size=600)
w1 = np.repeat(["P1", "P2", "P3"], 200)
w2 = np.tile(np.repeat(["A", "B", "C", "D"], 50), 3)
subj = np.tile(np.tile(np.arange(50), 4), 3)
df3 = pd.DataFrame({"dv": dv, "within1": w1, "within2": w2, "subj": subj})
idx, dv = "subj", "dv"
within = ["within1", "within2"]
pa1 = df3.pivot_table(index=idx, columns=within[0], values=dv)
pb1 = df3.pivot_table(index=idx, columns=within[1], values=dv)
pab1 = df3.pivot_table(index=idx, columns=within, values=dv)

class TestDistribution(TestCase):
    """Test distribution.py."""

    def test_gzscore(self):
        """Test function gzscore."""
        raw = np.random.lognormal(size=100)
        gzscore(raw)

    def test_normality(self):
        """Test function test_normality."""
        # List / 1D array
        normality(x, alpha=0.05)
        normality(x.tolist(), method="normaltest", alpha=0.05)
        # Pandas DataFrame
        df_nan_piv = df_nan.pivot(index="Subject", columns="Time", values="Scores")
        normality(df_nan_piv)  # Wide-format dataframe
        normality(df_nan_piv["August"])  # pandas Series
        # The line below is disabled because test fails on python 3.5
        # assert stats_piv.equals(normality(df_nan, group='Time', dv='Scores'))
        normality(df_nan, group="Group", dv="Scores", method="normaltest")
        normality(df_nan, group="Group", dv="Scores", method="jarque_bera")
        # Long-format but some groups are too small
        # https://github.com/raphaelvallat/pingouin/issues/319
        df_small = pd.DataFrame(
            {
                "group": [0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 2, 3],
                "variable": [5, 6, 8, 9, 5, 5, 2, 3, 4, 5, np.nan, 8],
            }
        )
        stats = normality(df_small, dv="variable", group="group")
        assert np.isnan(stats.loc[[1, 3], "pval"]).all()
        assert not np.isnan(stats.loc[[0, 2], "pval"]).all()
        assert (stats.loc[[1, 3], "normal"] == "False").all()

    def test_homoscedasticity(self):
        """Test function test_homoscedasticity."""
        hl = homoscedasticity(data=[x, y], alpha=0.05)
        homoscedasticity(data=[x, y], method="bartlett", alpha=0.05)
        hd = homoscedasticity(data={"x": x, "y": y}, alpha=0.05)
        hd2 = homoscedasticity(data={"x": x, "y": y}, alpha=0.05, center="mean")
        assert hl.equals(hd)
        assert not hd.equals(hd2)
        # Wide-format DataFrame
        homoscedasticity(df_pivot)
        # Long-format
        homoscedasticity(df, dv="Scores", group="Time")

    def test_epsilon(self):
        """Test function epsilon."""
        df_pivot = df.pivot(index="Subject", columns="Time", values="Scores").reset_index(drop=True)
        eps_gg = epsilon(df_pivot)
        eps_hf = epsilon(df_pivot, correction="hf")
        eps_lb = epsilon(df_pivot, correction="lb")
        # In long-format
        eps_gg_rm = epsilon(df, subject="Subject", within="Time", dv="Scores")
        eps_hf_rm = epsilon(df, subject="Subject", within="Time", dv="Scores", correction="hf")
        assert np.isclose(eps_gg_rm, eps_gg)
        assert np.isclose(eps_hf_rm, eps_hf)
        # Compare with ezANOVA
        assert np.allclose([eps_gg, eps_hf, eps_lb], [0.9987509, 1, 0.5])

        # Time has only two values so epsilon is one.
        assert epsilon(pa, correction="lb") == epsilon(pa, correction="gg")
        assert epsilon(pa, correction="gg") == epsilon(pa, correction="hf")
        # Lower bound <= Greenhouse-Geisser <= Huynh-Feldt
        assert epsilon(pb, correction="lb") <= epsilon(pb, correction="gg")
        assert epsilon(pb, correction="gg") <= epsilon(pb, correction="hf")
        assert epsilon(pab, correction="lb") <= epsilon(pab, correction="gg")
        assert epsilon(pab, correction="gg") <= epsilon(pab, correction="hf")
        # Lower bound == 0.5 for pb and pab
        assert epsilon(pb, correction="lb") == epsilon(pab, correction="lb")
        assert np.allclose(epsilon(pb), 0.9691030)  # ez
        assert np.allclose(epsilon(pb, correction="hf"), 1.0)  # ez
        # Epsilon for the interaction (shape = (2, N))
        assert np.allclose(epsilon(pab), 0.7271664)
        assert np.allclose(epsilon(pab, correction="hf"), 0.831161)
        assert epsilon(pab) == epsilon(pab.swaplevel(axis=1))
        assert epsilon(pab_single) == epsilon(pab_single.swaplevel(axis=1))
        eps_gg_rm = epsilon(data, subject="Subject", dv="Performance", within=["Time", "Metric"])
        assert eps_gg_rm == epsilon(pab)
        # Now with a (3, 4) two-way design
        assert np.allclose(epsilon(pa1), 0.9963275)
        assert np.allclose(epsilon(pa1, correction="hf"), 1.0)
        assert np.allclose(epsilon(pb1), 0.9716288)
        assert np.allclose(epsilon(pb1, correction="hf"), 1.0)
        assert 0.8 < epsilon(pab1) < 0.90  # Pingouin = .822, ez = .856
        eps_gg_rm = epsilon(df3, subject="subj", dv="dv", within=["within1", "within2"])
        assert eps_gg_rm == epsilon(pab1)
        # With missing values
        eps_gg_rm = epsilon(df_nan, subject="Subject", within="Time", dv="Scores")
        # 3 repeated measures factor
        with pytest.raises(ValueError):
            epsilon(pab_3fac)

    def test_sphericity(self):
        """Test function test_sphericity.
        Compare with ezANOVA.
        """
        _, W, _, _, p = sphericity(df_pivot, method="mauchly")
        assert round(W, 3) == 0.999
        assert np.round(p, 3) == 0.964
        _, W, _, _, p = sphericity(df, dv="Scores", subject="Subject", within="Time")  # Long-format
        assert round(W, 3) == 0.999
        assert np.round(p, 3) == 0.964
        assert sphericity(pa)[0]  # Only two levels so sphericity = True
        spher = sphericity(pb)
        assert spher[0]
        assert round(spher[1], 3) == 0.968  # W
        assert spher[3] == 2  # dof
        assert np.isclose(spher[4], 0.8784418)  # P-value
        # JNS
        sphericity(df_pivot, method="jns")
        sphericity(df, dv="Scores", subject="Subject", within=["Time"], method="jns")
        # Two-way design of shape (2, N)
        spher = sphericity(pab)
        assert round(spher[1], 3) == 0.625
        assert spher[3] == 2
        assert np.isclose(spher[4], 0.1523917)
        assert sphericity(pab)[1] == sphericity(pab.swaplevel(axis=1))[1]
        spher_long = sphericity(
            data, subject="Subject", dv="Performance", within=["Time", "Metric"]
        )
        assert round(spher_long[1], 3) == 0.625
        assert np.isclose(spher[4], spher_long[4])
        sphericity(pab_single)  # For coverage
        # Now with a (3, 4) two-way design
        # First, main effect
        spher = sphericity(pb1)
        assert spher[0]
        assert round(spher[1], 3) == 0.958  # W
        assert round(spher[4], 4) == 0.8436  # P-value
        spher2 = sphericity(df3, subject="subj", dv="dv", within=["within2"])
        assert spher[1] == spher2[1]
        assert spher[4] == spher2[4]
        # And then interaction (ValueError)
        with pytest.raises(ValueError):
            sphericity(pab1)
        # Same with long-format
        with pytest.raises(ValueError):
            sphericity(df3, subject="subj", dv="dv", within=["within1", "within2"])
        # 3 repeated measures factor
        with pytest.raises(ValueError):
            sphericity(pab_3fac)
        # With missing values
        sphericity(df_nan, subject="Subject", within="Time", dv="Scores")

    def test_anderson(self):
        """Test function test_anderson."""
        assert anderson(np.random.random(size=1000))[0] is False
        assert anderson(np.random.normal(size=10000))[0] is True


from spacy.matcher import Matcher
import re

class InformationExtractor():
    def __init__(self, nlp):
        self.nlp = nlp
        self.matcher = Matcher(self.nlp.vocab)
        self.matcher.add("SALUTATION", None, [{"LOWER": "good"}, {"LOWER": "morning"}],
                                     [{"LOWER": "good"}, {"LOWER": "evening"}],
                                     [{"LOWER": "good"}, {"LOWER": "afternoon"}],
                                     [{"LOWER": "good"}, {"LOWER": "night"}])

        mention_flag = lambda text: bool(re.compile(r'\@(\w+)').match(text))
        IS_MENTION = self.nlp.vocab.add_flag(mention_flag)

        self.matcher.add("MENTION", None, [{IS_MENTION: True}])

        self.matcher.add("PUNCT", None, [{"IS_PUNCT": True}])

        self.matcher.add("FEELING", None, [{"LOWER": "i"}, {"LEMMA":"be"},
                                         {"POS": "ADV", "OP": "*"},
                                         {"POS": "ADJ"}])

        self.matcher.add("DOING", None, [{"LOWER": "i"}, {"LEMMA": "be"},
                                         {"POS": "VERB"},
                                         {},
                                         {}])

    def extract_salutation(self, text, city):
        matches = self.matcher(text)
        return self._matches_to_json(matches, text, city, "SALUTATION")

    def extract_mention(self, text, city):
        matches = self.matcher(text)
        return self._matches_to_json(matches, text, city, "MENTION")

    def extract_punct(self, text, city):
        matches = self.matcher(text)
        return self._matches_to_json(matches, text, city, "PUNCT")

    def extract_feeling(self, text, city):
        matches = self.matcher(text)
        return self._matches_to_json(matches, text, city, "FEELING")

    def extract_doing(self, text, city):
        matches = self.matcher(text)
        return self._matches_to_json(matches, text, city, "DOING")

    def extract_all_rules(self, text, city):
        matches = self.matcher(text)
        return self._matches_to_json(matches, text, city)

    def _matches_to_json(self, matches, txt, city, specific_rule=False):
        output = []
        if len(matches) != 0:
            for match in matches:
                rule = self.nlp.vocab.strings[match[0]]
                text = str(txt[match[1]:match[2]])

                if rule == "PUNCT":
                    if text not in ["!","?"]:
                        continue

                if not specific_rule:
                    output.append({'rule':rule,
                           'text':text,
                           'city': city})
                else:
                    if rule == specific_rule:
                        output.append({'rule':rule,
                           'text':text,
                           'city': city})
        return output