from sklearn.decomposition import KernelPCA
from matplotlib import pyplot as plt
import pandas as pd, numpy as np, os
import pywt

base_path = os.path.dirname(os.path.abspath(__file__))
data_path = os.path.join(base_path, "../data/12053002165")
output_path = os.path.join(base_path, "../data/solar")

if not os.path.exists(output_path):
    os.makedirs(output_path, exist_ok=True)

train_data_raw = pd.read_excel(os.path.join(data_path, "train_in.xlsx"), header=None).values
test_data_raw = pd.read_excel(os.path.join(data_path, "test_in.xlsx"), header=None).values
train_target_raw = pd.read_excel(os.path.join(data_path, "train_out.xlsx"), header=None).values
test_target_raw = pd.read_excel(os.path.join(data_path, "test_out.xlsx"), header=None).values

train_data, test_data = list(), list()

timesteps = 24
num_input = 6
reduction_size = 15
scales = 3

"""
Column 0: history power
Column 3: B0062T
"""

pca = KernelPCA(n_components=reduction_size, kernel="rbf")
fre_data = list()

for i in range(timesteps, len(train_data_raw)):
    temp_row = list()
    pf = list()
    for j in range(0, timesteps):
        pf.append(train_data_raw[i - j][0])

    pf = np.array(pf)
    pf, freqs = pywt.cwt(pf, range(1, scales), wavelet='morl')
    pf = pf.flatten().tolist()
    temp_row.extend(train_data_raw[i].tolist())
    if train_data_raw[i][3] >= train_data_raw[i - 1][3] and train_data_raw[i - 1][3] != 0:
        temp_row[3] = train_data_raw[i][3] - train_data_raw[i - 1][3]

    fre_data.append(pf)
    train_data.append(temp_row)

train_data = np.array(train_data)

fre_data = np.array(fre_data)
pca.fit(fre_data)
fre_data = pca.fit_transform(fre_data)
train_data = np.append(train_data, fre_data, axis=1)

fre_data = list()

for i in range(timesteps, len(test_data_raw)):

    temp_row = list()
    pf = list()
    for j in range(0, timesteps):
        pf.append(test_data_raw[i - j][0])
    pf = np.array(pf)
    pf, freqs = pywt.cwt(pf, range(1, scales), wavelet='morl')
    pf = pf.flatten().tolist()
    temp_row.extend(test_data_raw[i].tolist())
    if test_data_raw[i][3] >= test_data_raw[i - 1][3] and test_data_raw[i - 1][3] != 0:
        temp_row[3] = test_data_raw[i][3] - test_data_raw[i - 1][3]

    fre_data.append(pf)
    test_data.append(temp_row)

test_data = np.array(test_data)

fre_data = np.array(fre_data)
pca.fit(fre_data)
fre_data = pca.fit_transform(fre_data)
test_data = np.append(test_data, fre_data, axis=1)

train_target = train_target_raw[timesteps:]
test_target = test_target_raw[timesteps:]

train_data_df = pd.DataFrame(train_data)
train_target_df = pd.DataFrame(train_target)
test_data_df = pd.DataFrame(test_data)
test_target_df = pd.DataFrame(test_target)

### Normalizaion

for i in range(num_input, reduction_size + num_input):

    train_max, train_min = train_data_df[i].max(), train_data_df[i].min()
    test_max, test_min = test_data_df[i].max(), test_data_df[i].min()
    _max, _min = max(train_max, test_max), min(train_min, test_min)
    if _max - _min != 0:
        train_data_df[i] = (train_data_df[i] - _min) / (_max - _min)
        test_data_df[i] = (test_data_df[i] - _min) / (_max - _min)

train_data_df.to_excel(os.path.join(output_path, "train_in.xlsx"), index=False, header=None)
test_data_df.to_excel(os.path.join(output_path, "test_in.xlsx"), index=False, header=None)
train_target_df.to_excel(os.path.join(output_path, "train_out.xlsx"), index=False, header=None)
test_target_df.to_excel(os.path.join(output_path, "test_out.xlsx"), index=False, header=None)


import argparse
import os
import torch
import torchvision as tv
from at_learner_core.utils import transforms
from at_learner_core.configs import dict_to_namespace
from at_learner_core.utils import transforms as transforms

from at_learner_core.utils import joint_transforms as j_transforms
from at_learner_core.utils import sequence_transforms as s_transforms
from PIL import Image

L = 16
image_size = 112
modality_list = ['stat_r1000', 'stat_r1']
of_modality_list = ['optical_flow', 'optical_flow_start']

test_seq_transform = tv.transforms.Compose([
    s_transforms.LinspaceTransform(L, key_list=['data']),
])

train_seq_transform = tv.transforms.Compose([
    tv.transforms.RandomApply([
        s_transforms.DuplicateElements(1, False, ['data'], 'target', 1, True)
    ], p=0.5),
    s_transforms.LinspaceTransform(L, key_list=['data'], max_start_index=0),
])

preprocess_transform = transforms.Transform4EachElement([
    transforms.RemoveBlackBorders(),
    transforms.SquarePad(),
    tv.transforms.Resize(image_size),
])

postprocess_transform = tv.transforms.Compose([
    transforms.CreateNewItem(transforms.RankPooling(C=1000), 'data', 'stat_r1000'),
    transforms.CreateNewItem(transforms.RankPooling(C=1), 'data', 'stat_r1'),

    transforms.DeleteKeys(['data']),

    transforms.Transform4EachKey([
        transforms.Transform4EachElement([
            # tv.transforms.Resize(112),
            tv.transforms.ToTensor(),
        ]),
        transforms.StackTensors(squeeze=True),
        tv.transforms.Normalize(mean=[0.5, 0.5], std=[0.5, 0.5])
    ], key_list=of_modality_list),

    transforms.Transform4EachKey([
        tv.transforms.Resize(112),
        tv.transforms.ToTensor(),
        tv.transforms.Normalize(mean=[0.5], std=[0.5])],
        key_list=modality_list)
])

train_image_transform = tv.transforms.Compose([
    transforms.Transform4EachKey([
        preprocess_transform,
        tv.transforms.RandomApply([j_transforms.ColorJitter(0.2, 0.2, 0.2, 0.2)], p=0.5),
    ], key_list=['data']),

    transforms.Transform4EachKey([
        tv.transforms.RandomApply([
            transforms.Transform4EachElement([
                tv.transforms.RandomApply([
                    tv.transforms.RandomRotation(5)
                ], p=0.5)
            ])], p=0.5),
        tv.transforms.RandomApply([
            transforms.Transform4EachElement([
                tv.transforms.RandomApply([
                    tv.transforms.RandomCrop(image_size, padding=5, pad_if_needed=True)
                ], p=0.5)
            ])
        ], p=0.5),
        tv.transforms.RandomApply([
            transforms.Transform4EachElement([
                tv.transforms.RandomApply([
                    tv.transforms.ColorJitter(0.05, 0.05, 0.05, 0.00)
                ], p=0.5)
            ])
        ], p=0.5),
    ], key_list=['data']),
    transforms.CreateNewItem(transforms.LiuOpticalFlowTransform((0, 4), (L - 4, L)), 'data', 'optical_flow'),
    transforms.CreateNewItem(transforms.LiuOpticalFlowTransform((0, 1), (2, 4)), 'data', 'optical_flow_start'),
    postprocess_transform

])

test_image_transform = tv.transforms.Compose([
    transforms.Transform4EachKey([
        preprocess_transform,
    ], key_list=['data']),
    transforms.CreateNewItem(transforms.LiuOpticalFlowTransform(0, L-1), 'data', 'optical_flow'),
    transforms.CreateNewItem(transforms.LiuOpticalFlowTransform(0, 1), 'data', 'optical_flow_start'),
    postprocess_transform
])

def get_config(protocol_name):
    config = {
        'head_config': {
            'task_name': 'rgb_track',
            'exp_name': f'exp1_{protocol_name}',
            'text_comment': '',
        },

        'checkpoint_config': {
            'out_path': None,
            'save_frequency': 1,
        },

        'datalist_config': {
            'trainlist_config': {
                'dataset_name': 'VideoDataset',
                'datalist_path': '../data/train_list.txt',
                'protocol_name': protocol_name,
                'data_columns': [('rgb_path', 'data')],
                'target_columns': ('label', 'target'),
                'group_column': 'video_id',
                'sampler_config': {
                    'name': 'NumElements',
                    'class_column': 'label',
                    'num_elem_per_epoch': 20.0,
                },
                'sequence_transforms': train_seq_transform,
                'transforms': train_image_transform,

            },
            'testlist_configs': {
                'dataset_name': 'VideoDataset',
                'datalist_path': '../data/dev_list.txt',
                'protocol_name': protocol_name,
                'data_columns': [('rgb_path', 'data')],
                'target_columns': ('label', 'target'),
                'group_column': 'video_id',
                'sequence_transforms': test_seq_transform,
                'transforms': test_image_transform,
            }
        },

        'train_process_config': {
            'nthreads': 8,
            'ngpu': 1,
            'batchsize': 32,
            'nepochs': 5,
            'resume': None,
            'optimizer_config': {
                'name': 'Adam',
                'lr_config': {
                    'lr_type': 'StepLR',
                    'lr': 0.0001,
                    'lr_decay_period': 5,
                    'lr_decay_lvl': 0.5,
                },
                'weight_decay': 1e-05,
            },
        },

        'test_process_config': {
            'run_frequency': 1,
            'metric': {
                'name': 'acer',
                'target_column': 'target',
            }
        },

        'wrapper_config': {
            'wrapper_name': 'MultiModalWrapper',
            'input_modalities': modality_list + of_modality_list,
            'backbone': 'simplenet112',
            'nclasses': 1,
            'loss': 'BCE',
            'pretrained': None,
        },

        'logger_config': {
            'logger_type': 'log_combiner',
            'loggers': [
                {'logger_type': 'terminal',
                 'log_batch_interval': 5,
                 'show_metrics': {
                     'name': 'acer',
                     'fpr': 0.01,
                 }},
            ]

        },
        'manual_seed': 42,
        'resume': None,
    }

    ns_conf = argparse.Namespace()
    dict_to_namespace(ns_conf, config)
    return ns_conf

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Options')
    parser.add_argument('--savepath',
                        type=str,
                        default='experiments/',
                        help='Path to save options')
    args = parser.parse_args()

    for idx in range(1, 4):
        configs = get_config(f'protocol_4_{idx}')
        out_path = os.path.join(args.savepath,
                                configs.head_config.task_name,
                                configs.head_config.exp_name)
        os.makedirs(out_path, exist_ok=True)
        if configs.checkpoint_config.out_path is None:
            configs.checkpoint_config.out_path = out_path
        filename = os.path.join(out_path,
                                configs.head_config.task_name + '_' + configs.head_config.exp_name + '.config')

        torch.save(configs, filename)
        print('Options file was saved to ' + filename)


from app.main.constants import DISTANCE_TO_NEIGHBOURS
from app.main.models.adjacent_polygon import Adjacent_Polygon
from app.main.models.polygon import Polygon
from app.main.services.extraction_helper import ExtractionHelper

class NeighbourExtraction():
    def get_neighbours(self, polygons: list, this_polygon: Polygon) -> list[Adjacent_Polygon]:
        '''
        Description: This method checks the scaling of the plans and if they can be matched.
        Params: polygons: list, this_polygon: Polygon
        Return: potential_neighbors: list[Adjacent_Polygon]
        Exception: ---
        '''
        potential_neighbors = []
        for other_polygon in polygons:
            if other_polygon == this_polygon:
                continue
            else:
                shapely_polygon = ExtractionHelper.transform_polygon_to_shapely_polygon(
                    this_polygon)
                shapely_polygon_other = ExtractionHelper.transform_polygon_to_shapely_polygon(
                    other_polygon)

                if shapely_polygon.distance(shapely_polygon_other) < DISTANCE_TO_NEIGHBOURS:
                    adjacent_polygon = Adjacent_Polygon(other_polygon.id)
                    potential_neighbors.append(adjacent_polygon)
        return potential_neighbors
    pass


from pydantic import ValidationError

from saltapi.web.schema.common import ProposalCode
import pytest

@pytest.mark.parametrize("code", ["2021-1-SCI-001", "2022-2-ORP-007", "2023-1-DDT-001"])
def test_valid_proposal_code(code: str):
    assert ProposalCode.validate(code) == code

@pytest.mark.parametrize(
    "invalid_code",
    [
        "20a1-1-ABC-123",  # Invalid year
        "2021-3-ABC-123",  # Invalid semester
        "2021-1-_ABC-123",  # Underscore can't start the letter sequence
        "2021-1-ABC_-123",  # Underscore can't end the letter sequence
        "2021-1-ABC-12",  # Invalid number of digits
    ],
)
def test_invalid_proposal_code(invalid_code: str):
    with pytest.raises(ValueError, match="incorrect proposal code"):
        ProposalCode.validate(invalid_code)

def test_non_string_input():
    with pytest.raises(TypeError, match="string required"):
        ProposalCode.validate(123)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 15 08:02:43 2018

@author: mfromano
"""

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr  2 10:31:21 2018

@author: mfromano
"""

# run hua-an's motion correction

import motion_correction2
import scipy.io as sio
import numpy as np

fi = sio.loadmat('/fastdata/ca-imaging-ed/metadata_raw_gcamp.mat')
fi = fi['metaout']

for i in np.arange(0,1):
    if fi[0][i]:
        currfiles = [a[0] for a in fi[0][i][1][0]]
        suffix = fi[0][i][0][0]
        motion_correction2.motion_correction(filename_list=currfiles[0:4])


from protobuf.message import Message
from protobuf.property import Property
from protobuf.typed import TYPES, WIRE_TYPES
from protobuf.ProtobufSyntaxError import ProtobufSyntaxError

PRIORITIES = {
    'required',
    'optional',
    'repeated'
}

def _read_file(filename):
    with open(filename) as f:
        code = f.read()
    return code

def parse(filename):
    code = _read_file(filename)
    lines = []
    start = 0
    for i in range(len(code)):
        if code[i] == '{' or code[i] == '}' or code[i] == ';':
            lines.append(code[start:i + 1].strip())
            start = i + 1

    message = None
    for line in lines:
        if line[-1] == '{':
            string = line[:-1].split()
            if len(string) != 2:
                raise ProtobufSyntaxError(f'unexpected string: {line}')
            if string[0] == 'message':
                if message is None:
                    message = Message(line.split()[1], None)
                else:
                    message.classes.append(Message(line.split()[1], message))
                    message = message.classes[-1]
                TYPES[message.name] = type(message.name, (), {})
                WIRE_TYPES[message.name] = 2
            elif string[0] == 'enum':
                if message is None:
                    message = Message(line.split()[1], None, True)
                else:
                    message.enums.append(
                        Message(line.split()[1], message, True))
                    message = message.enums[-1]
                TYPES[message.name] = type(message.name, (), {})
                WIRE_TYPES[message.name] = 0
            else:
                raise ProtobufSyntaxError(f'unexpected string: {line}')
        if line[-1] == ';':
            if line.strip()[:6] == 'syntax':
                line = line[:-1].split('=')
                if len(line) != 2:
                    raise ProtobufSyntaxError(f'unexpected string: {line}')
                line = line[1].strip()
                if eval(line) != 'proto2':
                    raise ProtobufSyntaxError(f'unexpected syntax, expected proto2')
                continue

            line = line[:-1]
            default = line.split('default')
            if len(default) < 2:
                default = None
            elif len(default) == 2:
                if len(default[0].split('[')) != 2 or len(default[1].split(']')) != 2:
                    raise ProtobufSyntaxError(f'Incorrect string {line}')
                default = line.split('[')[1].split('=')[1].split(']')[0].strip()
                line = line.split('[')[0]
            else:
                raise ProtobufSyntaxError(f'Incorrect string {line}')
            w = line.split('=')
            if len(w) != 2:
                raise ProtobufSyntaxError(f'Incorrect string {line}')
            line = ' '.join([w[0], w[1]])
            words = line.split()
            if not message.is_enum:
                if len(words) != 4 or words[1] not in TYPES or words[0] not in PRIORITIES:
                    raise ProtobufSyntaxError(f'unexpected string: {line}')

                if words[1] == 'string' and default is not None:
                    try:
                        default = eval(default)
                    except Exception:
                        raise Exception('Something went wrong')

                field_number = int(words[3])
                prop = Property(
                    words[2], field_number, default, words[1], words[0], WIRE_TYPES[words[1]])
            else:
                if len(words) != 2:
                    raise ProtobufSyntaxError(f'unexpected string: {line}')
                field_number = int(words[1])
                prop = Property(words[0], field_number)

            if prop.priority == 'optional':
                message.optional_properties.append(prop)
            elif prop.priority == 'required':
                if prop.default is None:
                    message.required_properties.append(prop)
                else:
                    message.req_def_properties.append(prop)
            message.properties.append(prop)
            message.properties_dict[field_number] = prop

        if line[-1] == '}':
            if message.parent is not None:
                message = message.parent

    return message


from crawlerbots.facebookCrawlerBot import main as fbMain
# from crawlerbots.kakaostoryCrawlerBot import main as kksMain
# from crawlerbots.instagramCrawlerBot import main as instaMain
from crawlerbots.db_mysql_select import DatabaseConnection
from self import self

page = DatabaseConnection()
facebook_list = []
kakaoStroy_list = []
origin_ph_list = []
origin_name_list = []
for i in page:
    origin_ph_list.append(i[1])
    origin_name_list.append(i[15])
    # facebook_list.append(i[9])
    kakaoStroy_list.append(i[6])

fbMain(facebook_list, origin_ph_list, origin_name_list)


import nextcord
from nextcord.ext import commands, tasks
import openai
import os
import re
from langdetect import detect
from config import TRANSLATE_CHANNEL

# Initialize the OpenAI API
openai.api_key = os.environ['Key_OpenAI']

def is_english(text):
    try:
        return detect(text) == 'en'
    except:
        return False

def preprocess_message(text):
    # Remove mentions
    cleaned_text = re.sub(r'@\w+', '', text)
    return cleaned_text.strip()

def should_translate(text):
    cleaned_text = preprocess_message(text)

    # If the cleaned message is empty, don't translate
    if not cleaned_text:
        return False

    # Check for non-Latin scripts
    non_latin_patterns = [
        r'[\u0600-\u06FF]',  # Arabic
        r'[\u0980-\u09FF]',  # Bengali
        r'[\u4E00-\u9FFF\U00020000-\U0002A6DF]',  # Chinese
        r'[\u0400-\u04FF]',  # Cyrillic
        r'[\u0900-\u097F]',  # Devanagari
        r'[\u0370-\u03FF]',  # Greek
        r'[\u0A80-\u0AFF]',  # Gujarati
        r'[\u0A00-\u0A7F]',  # Gurmukhi
        r'[\u0590-\u05FF]',  # Hebrew
        r'[\u3040-\u30ff\u3400-\u4DBF]',  # Japanese
        r'[\u0C80-\u0CFF]',  # Kannada
        r'[\uAC00-\uD7AF]',  # Korean
        r'[\u0D00-\u0D7F]',  # Malayalam
        r'[\u0B00-\u0B7F]',  # Oriya (Odia)
        r'[\u0D80-\u0DFF]',  # Sinhala
        r'[\u0B80-\u0BFF]',  # Tamil
        r'[\u0C00-\u0C7F]',  # Telugu
        r'[\u0E00-\u0E7F]',  # Thai
        r'[\u0F00-\u0FFF]'   # Tibetan
    ]
    for pattern in non_latin_patterns:
        if re.search(pattern, cleaned_text):
            return True

    # Check for minimum number of words on cleaned text
    if len(cleaned_text.split()) < 3:
        return False

    # Check for URLs on cleaned text
    url_regex = r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"
    if re.search(url_regex, cleaned_text):
        return False

    # Check for primarily alphanumeric content on cleaned text
    alphanumeric_regex = r"^[a-zA-Z0-9]+$"
    if re.search(alphanumeric_regex, cleaned_text):
        return False

    # Language check on cleaned text
    if is_english(cleaned_text):
        return False

    return True

class TranslationButton(nextcord.ui.Button):
    def __init__(self, message_id, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.message_id = message_id  # Store the original message's ID

    async def callback(self, interaction: nextcord.Interaction):
        # Fetch the translation using the message ID
        translation = self.view.cog.translations.get(self.message_id, "Translation not found.")

        # Send the translation as an ephemeral message
        await interaction.response.send_message(translation, ephemeral=True)

class TranslationView(nextcord.ui.View):
    def __init__(self, cog, message_id, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.cog = cog
        self.add_item(TranslationButton(message_id, label="TR", style=nextcord.ButtonStyle.primary))

class TranslationCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.translations = {}  # Dictionary to store translations
        self.cleanup_task = self.clean_translations.start()

    @tasks.loop(hours=1)
    async def clean_translations(self):
        """Cleanup task to remove translations older than 1 hour."""
        self.translations = {}

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.channel.id == TRANSLATE_CHANNEL and not message.author.bot:
            if should_translate(message.content):
                chat_message = [{"role": "user", "content": f"Translate the following to English: '{message.content}'"}]
                response = openai.ChatCompletion.create(
                    model="gpt-4",
                    messages=chat_message,
                    temperature=0.2,
                    max_tokens=1000,
                    frequency_penalty=0.0
                )
                translation = response['choices'][0]['message']['content'].strip()
                self.translations[message.id] = translation

                # Send an empty message with just the 'Translation' button below the original message
                view = TranslationView(self, message_id=message.id, timeout=None)
                await message.channel.send("", view=view)

    def cog_unload(self):
        self.cleanup_task.cancel()

def setup(bot):
    bot.add_cog(TranslationCog(bot))
    print("Translation cog loaded")


import os

from astropy.io import fits
import numpy as np

from . import db_indicies as dbi
from . import load_fits

# Indicies of fits file arrays2018/180625/101501_180625.1129.fits
FLG_IND = 4
TEL_DIV_IND = 5

def write_back_tellurics(spectrum_path, model, pwv, order_wv_ranges, shards):

  # 1: Open file
  f = fits.open(spectrum_path, do_not_scale_image_data=True)

  # 2: Write telluric divided spectrum
  for order in range(0, 86):
    if order in shards:
      #only one spectrum in shard
      spectrum = next(iter(shards[order].spectra.values()))

      # 2(a) Create tellurics array filled with nans
      tellurics = np.zeros(len(f[1].data.tellurics[order]))
      tellurics.fill(np.nan)

      # 2(b) Find the pixel at which the calculated telluric spectrum starts/
      # ends, and paste it into array
      l_cutoff_wv, r_cutoff_wv = order_wv_ranges[order]
      l_cutoff_px = np.argmax(f[1].data.wavelength[order] > l_cutoff_wv)
      r_cutoff_px = np.argmax(f[1].data.wavelength[order] > r_cutoff_wv)
      good_px=np.where(np.logical_not(np.isnan(f[1].data.spectrum[order])))[0]
      l_cutoff_px = l_cutoff_px if l_cutoff_px > good_px[0] else good_px[0]
      r_cutoff_px = r_cutoff_px if r_cutoff_px < good_px[-1] else good_px[-1]
      tellurics[l_cutoff_px:r_cutoff_px] = spectrum.tel_lin_y

      # 2(c) Set telluric array in file
      f[1].data.tellurics[order] = tellurics
    else:
      f[1].data.tellurics[order] = np.ones(len(f[1].data.tellurics[order]))

  # 3: Write PWV to header
  pwv_msg = "Calculated telluric intensity at 6940.18A"
  f[1].header.set("PWV", pwv, pwv_msg)

  # 4: Overwrite
  f.writeto(spectrum_path, overwrite=True)
  f.close()

def write_PWV_header(spectra_folder, out_folder, calibrators):

  """
  Writes CRYSTAL's PWV metric to calibration spectra headers
  """

  w_calibrator, z_calibrator, f_order = calibrators

  for PWV, filename in zip(w_calibrator, f_order):
    spectrum_path = os.path.join(spectra_folder, filename)
    f = fits.open(spectrum_path, do_not_scale_image_data=True)
    f[0].header["SEL_PWV"] = abs(PWV)
    f.writeto(os.path.join(out_folder, filename))
    f.close()

#def write_tellurics_to_fits(spectrum_path, out_folder, model, mu, shards):

#  # 1: Open file
#  f = fits.open(spectrum_path, do_not_scale_image_data=True)

#  # 2: Write telluric flags
#  order_shift = 0
#  if load_fits.find_epoch_from_date(f[0].header["DATE-OBS"]) == 2:
#    order_shift = 1

#  for row in model:
#    f[0].data[int(row[dbi.ORD_IND]) + order_shift, int(row[dbi.PX_IND]), FLG_IND] = 2

#  # 3: Write telluric divided spectrum
#  for shard in shards.values():
#    spectrum = next(iter(shard.spectra.values())) #only one spectrum in shard
#    f[0].data[shard.order + order_shift, shard.lo_px:shard.hi_px, TEL_DIV_IND] = spectrum.tel_lin_y

#  # 4: Write PWV to header
#  #f[1].header["PWV"] = str(np.exp(mu))
#  f[0].header["CALC-PWV"] = str(np.exp(mu))
#  #print("write_fits: CALC-PWV:{}".format(f[0].header["CALC-PWV"]))
#
#  # 5: Open destination and write
#  out_filename = os.path.basename(os.path.splitext(spectrum_path)[0]) + "t.fits"
#  out_path = os.path.join(out_folder, out_filename)
#  f.writeto(out_path, overwrite=True)
#  f.close()


# Define a function factorial() with one input n. [The default value of n needs to
# be 5]. Use the factorial() function and other inbuilt functions to find the
# maximum between the following:
# 1. 5!+3!-21 and 2!+4!+12
# 2. 26!+31! and 22!+35!
# 3. 21!+34!-15! and 31!+27!-19!
# Hint: you can use the min() and max() inbuilt functions of python.
def factorial(num):
    factorial=1
    for i in range(1,num + 1):
        factorial = factorial*i
    return factorial

factorial(5)
print(max(factorial(5)+factorial(3)-21,factorial(2)+factorial(4)+12))
print(max(factorial(26)+factorial(31),factorial(22)+factorial(35)))
print(max(factorial(21)+factorial(34)-factorial(15),factorial(31)+factorial(27)-factorial(19)))


import unittest
from astar import *

class TestAStar(unittest.TestCase):

    def test_heuristic(self):
        h_test = h((5, 4), (10, 7))
        h2_test = h((10, 3), (100, 20))

        self.assertEqual(h_test, 8)
        self.assertEqual(h2_test, 107)

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


from tkinter import *

from PIL import ImageTk, Image

root = Tk()
root.title('leer coderen bij Codemy.com')
root.iconbitmap('c:/gui/ ')

my_img1 = ImageTk.PhotoImage(Image.open("IMG_1136.png"))
my_img2 = ImageTk.PhotoImage(Image.open("IMG_2004.png"))

#image_list = [my_img1, my_img2]

#my_label = Label(image=my_img1)
#my_label.grid(row=0, column=0, columnspan=3)
#my_label.pack()

button_back = Button(root, "<<")
button_exit = Button(root, text="exit program", command=root.quit)
button_forward = Button(root, text=">>")

button_back.grid(row=1, column=0)
button_exit.grid(row=1, column=1)
button_forward.grid(row=1, column=2)

#button_quit = Button(root, text="exit program", command=root.quit)
#button_quit.pack()

root.mainloop()


#!/usr/bin/env python3

from itertools import permutations

def count_sums(l: list[int], target, i: int=0, sum_=0):
    global counter
    if sum_ == target:
        counter += 1
        return
    if sum_ < target and i < len(l):
        # Try to add the current element and already move our index to the next
        # element if it would succeed.
        count_sums(l, target, i + 1, sum_ + l[i])

        # If the adding above did not work, we'll come here and just move to
        # the next element.
        count_sums(l, target, i + 1, sum_)

with open("input") as data:
    containers = [int(c.strip()) for c in data]
eggnog = 150
counter = 0
count_sums(containers, eggnog)
print()
print(counter)


import pandas as pd
import numpy as np
import time
# Doc du lieu VCB 2009->2018
dataset_train = pd.read_csv('5000000 BT Records.csv')
training_set = dataset_train.iloc[:, 1:2].values

# print(training_set)

no_of_sample = len(training_set)
print(no_of_sample)

WINDOW_SIZE = 7 # 7 ngay
HORIZON_SIZE = 1 # 1 ngay

start = time.time()
steps = np.expand_dims(np.arange(WINDOW_SIZE + HORIZON_SIZE ),axis=0)
# print(steps, steps.shape)

add_matrix = np.expand_dims(np.arange(no_of_sample - WINDOW_SIZE - HORIZON_SIZE + 1), axis=0).T
# print(add_matrix, add_matrix.shape)

indexs = steps + add_matrix
# print(indexs, indexs.shape)

data  = training_set[indexs,0]
# print(data)

X_train, y_train = data[:,:WINDOW_SIZE], data[:,-HORIZON_SIZE:]
# print(X_train[0], y_train[0])
print("Time: ", time.time() - start)
# VCB 10 nam: Time:  0.00017690658569335938
# Bank transsaciton 1M: Time:  0.1764988899230957
# Bank transaction 5M: Time:  1.0231671333312988


import tkinter as tk
from tkinter import ttk

from chessengine import Chess
from dbmanager import ChessDatabase

class ChessGUI:
    """Responsible for handling the Tkinter GUI."""
    def __init__(self):
        self.init_window = tk.Tk()
        self.init_window.geometry("220x250")

        # Handling white's widgets.
        white_label = tk.Label(self.init_window, text="White", font=("CAD:", 20))
        white_label.grid(row=0, column=0)

        white_frame = tk.Frame(self.init_window)
        white_frame.grid(row=1, column=0)
        white_name = tk.Label(white_frame, text="Name: ")
        white_name.grid(row=0, column=0)
        self.white_name_entry = tk.Entry(white_frame)
        self.white_name_entry.grid(row=0, column=1)
        white_elo = tk.Label(white_frame, text="ELO: ")
        white_elo.grid(row=1, column=0)
        self.white_elo_entry = tk.Entry(white_frame)
        self.white_elo_entry.grid(row=1, column=1)

        # Handling blacks widgets.
        black_label = tk.Label(self.init_window, text="Black", font=("CAD:", 20))
        black_label.grid(row=2, column=0)

        black_frame = tk.Frame(self.init_window)
        black_frame.grid(row=3, column=0)
        black_name = tk.Label(black_frame, text="Name: ")
        black_name.grid(row=0, column=0)
        self.black_name_entry = tk.Entry(black_frame)
        self.black_name_entry.grid(row=0, column=1)
        black_elo = tk.Label(black_frame, text="ELO: ")
        black_elo.grid(row=1, column=0)
        self.black_elo_entry = tk.Entry(black_frame)
        self.black_elo_entry.grid(row=1, column=1)

        err = "Names should be between 1 and 20\ncharacters long, and ELO ratings\nmust be " + \
              "be integers between 1 and 5000."
        self.invalid_data_label = tk.Label(self.init_window, foreground="#F0F0F0", text=err)
        self.invalid_data_label.grid(row=4, column=0)

        # Buttons.
        button_frame = tk.Frame(self.init_window)
        button_frame.grid(row = 5, column=0)

        start_game_button = tk.Button(button_frame, text="Start Game", command=self.start_chess_game)
        start_game_button.grid(row=0, column=0)

        view_database_button = tk.Button(button_frame, text="View Database", command=self.view_database)
        view_database_button.grid(row=0, column=1)

        quit_button = tk.Button(button_frame, text="Quit", command=self.init_window.destroy)
        quit_button.grid(row=0, column=2)

        self.init_window.mainloop()

    def start_chess_game(self):
        """Starts the chess game, if the details entered are valid."""
        w_name = self.white_name_entry.get().strip()
        w_elo = self.white_elo_entry.get().strip()
        b_name = self.black_name_entry.get().strip()
        b_elo = self.black_elo_entry.get().strip()

        if len(w_name) == 0 or len(w_name) > 20 or len(b_name) == 0 or len(b_name) > 20 or \
           not w_elo.isdigit() or not b_elo.isdigit():
            self.invalid_data_label.configure(fg="red")
            return

        if int(w_elo) < 1 or int(w_elo) > 5000 or int(b_elo) < 1 or int(b_elo) > 5000:
            self.invalid_data_label.configure(fg="red")
            return

        self.init_window.destroy()

        chess = Chess()
        chess.display_users(w_name, w_elo, b_name, b_elo)
        chess.start_game()

    def view_database(self):
        view_database_window = tk.Tk()
        view_database_window.geometry("700x300")

        table_frame = tk.Frame(view_database_window)
        table_frame.pack()

        scroll_bar = tk.Scrollbar(table_frame)
        scroll_bar.pack(side=tk.RIGHT, fill=tk.Y)

        table = ttk.Treeview(table_frame, yscrollcommand=scroll_bar.set)
        table.pack()

        scroll_bar.config(command=table.yview)

        table['columns'] = ('game_id', 'w_name', 'w_elo', 'b_name', 'b_elo', 'winner', 'moves')

        table.column("#0", width=0, stretch=tk.NO)
        table.column("game_id", anchor=tk.CENTER, width=30)
        table.column("w_name", anchor=tk.CENTER, width=120)
        table.column("w_elo", anchor=tk.CENTER, width=80)
        table.column("b_name", anchor=tk.CENTER, width=120)
        table.column("b_elo", anchor=tk.CENTER, width=80)
        table.column("winner", anchor=tk.CENTER, width=80)
        table.column("moves", anchor=tk.CENTER, width=170)

        table.heading("#0", text="", anchor=tk.CENTER)
        table.heading("game_id", text="ID", anchor=tk.CENTER)
        table.heading("w_name", text="White's name", anchor=tk.CENTER)
        table.heading("w_elo", text="While's ELO", anchor=tk.CENTER)
        table.heading("b_name", text="Black's Name", anchor=tk.CENTER)
        table.heading("b_elo", text="Black's ELO", anchor=tk.CENTER)
        table.heading("winner", text="Winner", anchor=tk.CENTER)
        table.heading("moves", text="Moves played", anchor=tk.CENTER)

        db = ChessDatabase()
        games = db.get_entries()
        db.close()
        for i, game in enumerate(games):
            moves = game[6].split("\n")[0] + ".."
            table.insert(parent='', index='end', iid=i, text='',
                         values=(game[0], game[1], game[2], game[3], game[4],
                                 game[5], moves))

        table.pack()

        enter_game_id_label = tk.Label(view_database_window, text='Enter game ID to view the full list of moves:')
        enter_game_id_label.pack()
        game_id_entry = tk.Entry(view_database_window)
        game_id_entry.pack()
        view_moves_button = tk.Button(view_database_window, text='View',
                                      command=lambda : self.view_moves_of_game(game_id_entry.get()))
        view_moves_button.pack()

        view_database_window.mainloop()

    def view_moves_of_game(self, game_id: str):
        if not game_id.isdigit():
            return

        db = ChessDatabase()
        games = db.get_entries()
        db.close()

        game_id = int(game_id)
        found = False
        for game in games:
            if game_id == game[0]:
                found = True
                break

        if not found:
            return

        text = game[6] + "\n" + "WINNER: " + game[5]

        view_moves_window = tk.Tk()
        view_moves_window.geometry("250x400")

        moves_label = tk.Label(view_moves_window, text=text)
        moves_label.pack()

        view_moves_window.mainloop()


import torch.utils.data as data
import PIL.Image as Image
import os
import numpy as np
import torch
from torch.utils.data import DataLoader
from torch import autograd, optim
from torchvision.transforms import transforms
from networks.cenet import CE_Net_
import cv2
import nibabel as nib
import time

x_transforms = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize([0.5], [0.5])
])

y_transforms = transforms.ToTensor()

# 是否使用cuda
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
#device = torch.device("cpu")

#liver   'ckp_challenge_only/CE_LITS_and_challenge_model_epoch138.pth'
#tumor   'ckp_challenge_only/CE_LITS_and_challenge_model_epoch142.pth'

def end_to_end(raw_path,liver_model_path,tumor_model_path):

    volume = nib.load(raw_path).get_fdata()
    volume = np.transpose(volume, [2,0,1])

    liver_model = CE_Net_(3, 1).to(device)
    liver_model.load_state_dict(torch.load(liver_model_path))
    liver_model.to(device)
    liver_model.eval()

    liver_target = []

    tumor_model = CE_Net_(3, 1).to(device)
    tumor_model.load_state_dict(torch.load(tumor_model_path))
    tumor_model.to(device)
    tumor_model.eval()

    tumor_target = []

    for i in range(volume.shape[0]):
        a = volume[i]
        img_x = Image.fromarray(np.int16(np.array(volume[i])))
        h,w = img_x.size
        img_x = img_x.resize((512,512))
        img_x = img_x.convert('RGB')
        img_x = x_transforms(img_x)
        img_x = img_x.to(device)
        img_x = torch.unsqueeze(img_x, 0)

        img_liver = liver_model(img_x)
        img_tumor = tumor_model(img_x)

        trann = transforms.ToPILImage()

        img_liver = torch.squeeze(img_liver)
        img_liver = img_liver.detach().cpu().numpy()
        img_liver = np.transpose(img_liver,[1,2,0])
        img_liver[img_liver>=0.5] = 255
        img_liver = img_liver.astype(np.uint8)
        img_liver = trann(img_liver)
        img_liver = img_liver.convert('L')
        img_liver = img_liver.resize((h,w))
        img_liver = np.asarray(img_liver)

        img_tumor = torch.squeeze(img_tumor)
        img_tumor = img_tumor.detach().cpu().numpy()
        img_tumor = np.transpose(img_tumor,[1,2,0])
        img_tumor[img_tumor>=0.5] = 255
        img_tumor = img_tumor.astype(np.uint8)
        img_tumor = trann(img_tumor)
        img_tumor = img_tumor.convert('L')
        img_tumor = img_tumor.resize((h,w))
        img_tumor = np.asarray(img_tumor)

        #肝脏后处理
        img_liver = img_liver.copy()
        img_liver[img_tumor==255] = 255
        kernel = np.ones((7,7),np.uint8)
        img_liver[img_liver>=1] = 1
        img_liver = cv2.erode(img_liver,kernel)#腐蚀
        img_liver = cv2.dilate(img_liver,kernel,iterations = 1)#膨胀
        img_liver[img_liver>=1] = 255
        #肝脏后处理结束

        #肿瘤后处理
        img_tumor = img_tumor.copy()
        img_tumor[img_liver!=255] = 0
        #肿瘤后处理结束

        img_liver[img_liver>=1] = 1
        liver_target.append(img_liver)

        img_tumor[img_tumor>=1] = 1
        tumor_target.append(img_tumor)

    liver_target = np.asarray(liver_target)
    liver_target = np.transpose(liver_target, [1,2,0])
    liver_nib = nib.Nifti1Image(liver_target, affine=np.eye(4))

    tumor_target = np.asarray(tumor_target)
    tumor_target = np.transpose(tumor_target, [1,2,0])
    tumor_nib = nib.Nifti1Image(tumor_target, affine=np.eye(4))

    return liver_nib,tumor_nib

def run():
    liver_model_path = 'ckp_challenge_finally/liver_138.pth'
    tumor_model_path = 'ckp_challenge_finally/tumor_142.pth'

    liver_path = "D:/deep_learning/u_net_liver-test/liver"
    ls = os.listdir(liver_path)

    for i in range(len(ls)):
        nii_path = os.path.join(liver_path,ls[i],"liver.nii")
        liver_nib,tumor_nib = end_to_end(nii_path,liver_model_path,tumor_model_path)

        save_liver = os.path.join(liver_path,ls[i],"liver_seg.nii")
        save_tumor = os.path.join(liver_path,ls[i],"liver_nid.nii")

        nib.save(liver_nib,save_liver)
        nib.save(tumor_nib,save_tumor)

##处理一个病人10-15秒（GPU）
##处理一个病人169秒（CPU）

if __name__ == '__main__':

    time_start = time.time()

    liver_model_path = 'ckp_challenge_finally/liver_138.pth'
    tumor_model_path = 'ckp_challenge_finally/tumor_142.pth'

    nii_path = "liver/liver_1/liver.nii"

    liver_nib,tumor_nib = end_to_end(nii_path,liver_model_path,tumor_model_path)

    nib.save(liver_nib,"liver/liver_1/liver_seg.nii")
    nib.save(tumor_nib,"liver/liver_1/liver_nid.nii")

    time_end  = time.time()
    print(time_end-time_start)


import streamlit as st
from streamlit_extras.switch_page_button import switch_page
def add_eyewitness():
    st.header("Add an eyewitness")
    name = st.text_input("Enter the name of the eyewitness", key='name')
    desc = st.text_input("Enter a description of the witness", key = 'desc')
    pic = st.file_uploader("Upload the picture of the eyewitness",type=['.jpg','.jpeg','.png'], key='picture')
    pic_bytes=None
    if pic is not None:
        pic_bytes=pic.read()
        st.image(pic_bytes)
    context = st.text_input("Enter the context of the interview",help ='Enter what the subject being discussed is. This helps the model create an accurate summary of the text', key=f'context')
    audio_file = st.file_uploader("Upload the recording transcript: ",type=['.wav','.ogg','.mp3','.wave'], accept_multiple_files=False, key=f'uploader')
    if audio_file is not None:
        audio_bytes = audio_file.read()

        # st.write(st.session_state["witnesses"])
        if st.button("Add Eyewitness:"):
            st.session_state["witnesses"][f"Witness {st.session_state['count']}"]={
            "Name": name,
            "desc": desc,
            "pic": pic_bytes if pic_bytes is not None else pic_bytes,
            "context": context,
            "audio_bytes": audio_bytes
            }
            st.success("Eyewitness added successfully")
            st.session_state['count']+=1
            if st.session_state['refresh']==0:
                st.session_state['refresh']=1
    # if audio_file is not None:
    #     audio_bytes = audio_file.read()
    #     st.audio(audio_bytes, format='audio/wav')
    #     analysis_button = st.button("Perform analysis")
    #     if analysis_button:
    #         analyze(audio_bytes, context)
def display(data: dict):
    st.header(data["Name"])
    try:
        st.image(data["pic"], width=200)
    except AttributeError:
        st.write("No picture provided")

    audio_bytes = data['audio_bytes']
    context=data["context"]
    desc = data["desc"]

    st.subheader("Description")
    if desc:
        st.write(desc)
    else:
        st.write("No description provided for the witness")

    st.subheader("Context")
    if context:
        st.write(context)
    else:
        st.write("No context provided for the transcription")

    st.write("## Listen to transcript: ")
    st.audio(audio_bytes, format='audio/wav')
    analysis_button = st.button("Perform analysis")
    if analysis_button:
        st.session_state["curr_data"]=data
        st.session_state['analyze']=1
        switch_page("analysis")


# -*- coding: utf-8 -*-
"""
Created on Sun Feb 19 23:05:06 2023

@author: hp
"""
#Write A Python Program To Get Number To Check, Whether It Is Positive OR Negative

n=int(input("Enter a number : "))
if(n>0):
    print("Positive Number")
else:
    print("Negative Number")


from account.models import Account, EmailAddress
from mozilla_django_oidc.auth import OIDCAuthenticationBackend, default_username_algo

class PinaxOIDCAuthenticationBackend(OIDCAuthenticationBackend):

    def create_user(self, claims):
        """
        Create a user account for the given claims.

        This method is overridden to ensure we create a user account
        which will work in the DUA world.
        """
        username = claims.get("preferred_username", default_username_algo(claims["email"]))
        user = self.UserModel(username=username, email=claims["email"])
        user._disable_account_creation = True
        user.set_unusable_password()
        user.save()
        extra = {}
        if claims.get("zoneinfo"):
            extra["timezone"] = claims["zoneinfo"]
        if claims.get("locale"):
            extra["language"] = claims["locale"]
        Account.create(**{
            "request": self.request,
            "user": user,
            "create_email": False,
            **extra,
        })
        if claims.get("email_verified", False):
            EmailAddress.objects.create(
                email=user.email,
                verified=True,
                primary=True,
            )
        else:
            EmailAddress.objects.add_email(user, user.email, confirm=True)
        return user

    def verify_claims(self, claims):
        checks = set()
        email = claims.get("email")
        if email:
            try:
                email_address = EmailAddress.objects.get(email__iexact=email)
            except EmailAddress.DoesNotExist:
                checks.add(True)
            else:
                # check if the found email address is verified.
                # we need this because if the user has an unverified
                # email address we never get to fail the authentication.
                # however, this is being overly protective because all
                # users who authenticate with OIDC will have a verified
                # email address.
                # @@@ consider creating a django.contrib.messages message
                checks.add(email_address.verified)
        return all(checks)

    def filter_users_by_claims(self, claims):
        email = claims.get("email")
        if not email:
            return self.UserModel.objects.none()
        try:
            email_address = EmailAddress.objects.get(
                email__iexact=email,
                verified=True,
            )
        except EmailAddress.DoesNotExist:
            return self.UserModel.objects.none()
        else:
            return self.UserModel.objects.filter(pk=email_address.user_id)


import os

import jinja2
import yaml

def load_config(config_directory, env_file, config_env_overrides=None):
    if config_env_overrides is None:
        config_env_overrides = {}

    with open(os.path.join(config_directory, env_file)) as env_fd:
        config_env = yaml.load(env_fd)

    for key, value in config_env_overrides.items():
        config_env[key] = value

    jinja_env = jinja2.Environment(
        loader=jinja2.FileSystemLoader(config_directory),
        trim_blocks=True,
        lstrip_blocks=True,
    )

    sources = (
        entry
        for entry in os.listdir(config_directory)
        if entry != env_file
        and os.path.isfile(os.path.join(config_directory, entry))
    )

    result = config_env.copy()

    for source in sources:
        template = jinja_env.get_template(source)
        yaml_config = template.render(config_env)
        result[source.split(".")[0]] = yaml.load(yaml_config)

    return result


from __future__ import unicode_literals, print_function, division
__author__ = "mozman <mozman@gmx.at>"

from .compatibility import is_stream, StringIO
from .filemanager import FileManager

class ByteStreamManager(FileManager):
    def __init__(self, buffer=None):
        if is_stream(buffer):
            self._zipfile_as_bytes = buffer.getvalue()
        else:
            self._zipfile_as_bytes = buffer
        super(ByteStreamManager, self).__init__()

    def save(self, filename, backup=False):
        if is_stream(filename):
            filename.write(self.tobytes())
        else:
            with open(filename, 'wb') as fp:
                fp.write(self.tobytes())

    def has_zip(self):
        return self._zipfile_as_bytes is not None

    def _open_bytestream(self):
        return StringIO(self._zipfile_as_bytes)


from setuptools import setup, find_packages
import os

with open(os.path.join(os.path.dirname(__file__), 'README.md')) as README:
    DESCRIPTION = README.read()

with open('requirements.txt') as f:
    required = f.read().splitlines()

setup(
    name='OpenReader',
    version='0.1',
    packages = find_packages(),
    include_package_data = True,
    author = "Not Google",
    license='LICENSE.md',
    long_description=DESCRIPTION,
    description="Reading RSS feeds like it's 2012",
    url="https://github.com/craigsonoffergus/OpenReader",
    install_requires=required,
)


from typing import Tuple, Optional
import torch
from torch import nn

from towhee.models.max_vit.max_vit_block import MaxViTStage
from towhee.models.max_vit.configs import get_configs
from towhee.models.utils import create_model as towhee_model

class MaxViT(nn.Module):
    """
    Implementation of the MaxViT proposed in:
    https://arxiv.org/pdf/2204.01697.pdf

    Args:
        in_channels (`int`):
            Number of input channels to the convolutional stem. Default 3
        depths (`Tuple[int, ...]`):
            Depth of each network stage. Default (2, 2, 5, 2)
        channels (`Tuple[int, ...]`):
            Number of channels in each network stage. Default (64, 128, 256, 512)
        num_classes (`int`):
            Number of classes to be predicted. Default 1000
        embed_dim (`int`):
            Embedding dimension of the convolutional stem. Default 64
        num_heads (`int`):
            Number of attention heads. Default 32
        grid_window_size (`Tuple[int, int]`):
            Grid/Window size to be utilized. Default (7, 7)
        attn_drop (`float`):
            Dropout ratio of attention weight. Default: 0.0
        drop (`float`):
            Dropout ratio of output. Default: 0.0
        drop_path (`float`):
            Dropout ratio of path. Default: 0.0
        mlp_ratio (`float`):
            Ratio of mlp hidden dim to embedding dim. Default: 4.0
        act_layer (`nn.Module`):
            Type of activation layer to be utilized. Default: nn.GELU
        norm_layer (`nn.Module`):
            Type of normalization layer to be utilized. Default: nn.BatchNorm2d
        norm_layer_transformer (`nn.Module`):
            Normalization layer in Transformer. Default: nn.LayerNorm
        global_pool (`str`):
            Global polling type to be utilized. Default "avg"
    """

    def __init__(
            self,
            in_channels: int = 3,
            depths: Tuple[int, ...] = (2, 2, 5, 2),
            channels: Tuple[int, ...] = (64, 128, 256, 512),
            num_classes: int = 1000,
            embed_dim: int = 64,
            num_heads: int = 32,
            grid_window_size: Tuple[int, int] = (7, 7),
            attn_drop: float = 0.,
            drop: float = 0.,
            drop_path: float = 0.,
            mlp_ratio: float = 4.,
            act_layer=nn.GELU,
            norm_layer=nn.BatchNorm2d,
            norm_layer_transformer=nn.LayerNorm,
            global_pool: str = "avg"
    ) -> None:
        """ Constructor method """
        # Call super constructor
        super().__init__()
        # Check parameters
        assert len(depths) == len(channels), "For each stage a channel dimension must be given."
        assert global_pool in ["avg", "max"], f"Only avg and max is supported but {global_pool} is given"
        # Save parameters
        self.num_classes: int = num_classes
        # Init convolutional stem
        self.stem = nn.Sequential(
            nn.Conv2d(in_channels=in_channels, out_channels=embed_dim, kernel_size=(3, 3), stride=(2, 2),
                      padding=(1, 1)),
            act_layer(),
            nn.Conv2d(in_channels=embed_dim, out_channels=embed_dim, kernel_size=(3, 3), stride=(1, 1),
                      padding=(1, 1)),
            act_layer(),
        )
        # Init blocks
        drop_path = torch.linspace(0.0, drop_path, sum(depths)).tolist()
        stages = []
        for index, (depth, channel) in enumerate(zip(depths, channels)):
            stages.append(
                MaxViTStage(
                    depth=depth,
                    in_channels=embed_dim if index == 0 else channels[index - 1],
                    out_channels=channel,
                    num_heads=num_heads,
                    grid_window_size=grid_window_size,
                    attn_drop=attn_drop,
                    drop=drop,
                    drop_path=drop_path[sum(depths[:index]):sum(depths[:index + 1])],
                    mlp_ratio=mlp_ratio,
                    act_layer=act_layer,
                    norm_layer=norm_layer,
                    norm_layer_transformer=norm_layer_transformer
                )
            )
        self.stages = nn.Sequential(*stages)
        self.global_pool: str = global_pool
        self.head = nn.Linear(channels[-1], num_classes)

    # @torch.jit.ignore
    # def no_weight_decay(self) -> Set[str]:
    #     """ Gets the names of parameters to not apply weight decay to.
    #     Returns:
    #         nwd (Set[str]): Set of parameter names to not apply weight decay to.
    #     """
    #     nwd = set()
    #     for n, _ in self.named_parameters():
    #         if "relative_position_bias_table" in n:
    #             nwd.add(n)
    #     return nwd

    def reset_classifier(self, num_classes: int, global_pool: Optional[str] = None) -> None:
        """
        Method results the classification head
        Args:
            num_classes (`int`):
                Number of classes to be predicted.
            global_pool (`str`):
                If not global pooling is updated.
        """
        self.num_classes: int = num_classes
        if global_pool is not None:
            self.global_pool = global_pool
        self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()

    def forward_features(self, data: torch.Tensor) -> torch.Tensor:
        """
        Forward pass of feature extraction.
        Args:
            data (`torch.Tensor`):
                Input images of the shape [B, C, H, W].
        Returns:
            output (`torch.Tensor`):
                Image features of the backbone.
        """
        output = data
        for stage in self.stages:
            output = stage(output)
        return output

    def forward_head(self, data: torch.Tensor, pre_logits: bool = False):
        """
        Forward pass of classification head.
        Args:
            data (`torch.Tensor`):
                Input features.
            pre_logits (`bool`):
                If true pre-logits are returned.
        Returns:
            output (`torch.Tensor`):
                Classification output of the shape [B, num_classes].
        """
        if self.global_pool == "avg":
            data = data.mean(dim=(2, 3))
        elif self.global_pool == "max":
            data = torch.amax(data, dim=(2, 3))
        return data if pre_logits else self.head(data)

    def forward(self, data: torch.Tensor) -> torch.Tensor:
        """ Forward pass
        Args:
            data (`torch.Tensor`):
                Input images of the shape [B, C, H, W].
        Returns:
            output (`torch.Tensor`):
                Classification output of the shape [B, num_classes].
        """
        output = self.forward_features(self.stem(data))
        output = self.forward_head(output)
        return output

def create_model(
        model_name: str = None,
        pretrained: bool = False,
        checkpoint_path: str = None,
        device: str = None,
        **kwargs
        ):
    configs = get_configs(model_name)
    configs.update(**kwargs)

    model = towhee_model(MaxViT, configs=configs, pretrained=pretrained, checkpoint_path=checkpoint_path, device=device)
    return model


import streamlit as st
import altair as alt
import inspect
from vega_datasets import data

@st.experimental_memo
def get_chart_67593(use_container_width: bool):
    import altair as alt
    import pandas as pd

    data = pd.DataFrame([dict(id=i) for i in range(1, 101)])

    person = (
        "M1.7 -1.7h-0.8c0.3 -0.2 0.6 -0.5 0.6 -0.9c0 -0.6 "
        "-0.4 -1 -1 -1c-0.6 0 -1 0.4 -1 1c0 0.4 0.2 0.7 0.6 "
        "0.9h-0.8c-0.4 0 -0.7 0.3 -0.7 0.6v1.9c0 0.3 0.3 0.6 "
        "0.6 0.6h0.2c0 0 0 0.1 0 0.1v1.9c0 0.3 0.2 0.6 0.3 "
        "0.6h1.3c0.2 0 0.3 -0.3 0.3 -0.6v-1.8c0 0 0 -0.1 0 "
        "-0.1h0.2c0.3 0 0.6 -0.3 0.6 -0.6v-2c0.2 -0.3 -0.1 "
        "-0.6 -0.4 -0.6z"
    )

    chart = alt.Chart(data).transform_calculate(
        row="ceil(datum.id/10)"
    ).transform_calculate(
        col="datum.id - datum.row*10"
    ).mark_point(
        filled=True,
        size=50
    ).encode(
        x=alt.X("col:O", axis=None),
        y=alt.Y("row:O", axis=None),
        shape=alt.ShapeValue(person)
    ).properties(
        width=400,
        height=400
    ).configure_view(
        strokeWidth=0
    )

    tab1, tab2 = st.tabs(["Streamlit theme (default)", "Altair native theme"])

    with tab1:
        st.altair_chart(chart, theme="streamlit", use_container_width=True)
    with tab2:
        st.altair_chart(chart, theme=None, use_container_width=True)

try:
    st.expander("See code").code(inspect.getsource(get_chart_67593))
    get_chart_67593(use_container_width=True)
except Exception as e:
    st.exception(e)


def rsp(mine, yours):
    allowed = ['가위', '바위', '보']
    if mine not in allowed:
        raise ValueError("'가위', '바위', '보' 가운데 하나의 값만 입력받을 수 있습니다.")
    if yours not in allowed:
        raise ValueError("'가위', '바위', '보' 가운데 하나의 값만 입력받을 수 있습니다.")

# rsp('가위','바')
# try-except 문을 넣어서 예외를 잡아내면 프로그램이 종료되지 않는다.
try:
    rsp('가위','바')
except ValueError:
    print('잘못된 값을 넣었습니다')

classroom = {
    '1반':[162,175,198,137,145,199],
    '2반':[165,177,157,160,191]
}
try:
    for class_id, heights in classroom.items():
        for height in heights:
            if height > 190:
                print(class_id, '에 190이 넘는 학생이 있습니다')
                raise StopIteration
except StopIteration:
    print('정상종료')


"""djangoProject URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
# backend/urls.py

from django.contrib import admin
from django.urls import path, include                 # add this
from drf_yasg import openapi
# from drf_yasg.views import get_schema_view
# from drf_spectacular import openapi
from drf_yasg.views import get_schema_view
from rest_framework import routers                    # add this
from candidate import views as candidateviews
from client import views as clientsviews

from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView

api_info = openapi.Info(
    title="Back End API",
    description="CareIgnition Back End API for code demo",
    default_version="0.0.1",
    terms_of_service="https://www.google.com/policies/terms/",
    contact=openapi.Contact(email="jasonmvallee@gmail.com"),
    license=openapi.License(name="No License"),
)

schema_view = get_schema_view(
    api_info,
    public=True,
)

router = routers.DefaultRouter()                      # add this
router.register(r'candidates', candidateviews.CandidateView, 'candidate')
router.register(r'clients', clientsviews.ClientView)
router.register(r'jobs', clientsviews.JobView)
router.register(r'outreaches', clientsviews.OutreachView)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include(router.urls)),                # add this
    path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
    # Optional UI:
    path('api/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),
    path('api/schema/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'),
]


#求菲波那切数列
# 1 1 2 3 5 8 13 21 34 55
'''用函数实现'''
def fib1(n):
    stack=[]
    if n == 0 or n == 1:
       return 1
    else:
       stack.append(1)
       stack.append(1)
       for i in range(2,n):
          stack.append(stack[i-1]+stack[i-2])
       return stack
print (fib1(8))

def fib2(n):
    count=0
    a,b =0,1
    while count < n:
      print (b)
      a,b = b,a +b
      count +=1
    return 'done'
print (fib2(5))

'''用yield生成器'''
def fib3(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1
for i in fib3(5):
    print (i)

'''用递归实现'''
def fib4(n):
    if n == 0 or n == 1:
       return 1
    return fib4(n-1)+fib4(n-2)
print (fib4(5))

'''用滑动窗口实现 这么做是把a,b的值向前移动了 节省来回赋值的麻烦'''
def fib5(n):
    a,b = 1,1
    for i in range(n+1):
        if i == 0 or i == 1:
           a,b = 1,1
        else:
           a,b = b,a+b
    return b
print (fib5(5))


from YNABpy import Parser

YNAB_DATA_FILE = "F:/Development/PortableGit/YNABpy/YNABpy/test_budget.ynab3"
yparser = Parser.YNAB3_Parser(YNAB_DATA_FILE)

transaction_lister = yparser.get_transaction_lister()
category_lister = yparser.get_category_lister()

# test filtering transaction list based on category name substring

print("\nFilter by transactions with category that match 'Cars':\n")

for t in transaction_lister.get_transactions_by_category_name('Cars'):
    print("'" + t.get_payee() + " ($" + t.get_outflow() + " outflow) ' matches 'Cars'")

# test filtering transaction list based on payee substring

print("\nFilter by transactions with payee that matches 'Canadian':\n")

for t in transaction_lister.get_transactions_by_payee('Canadian'):
    print("'" + t.get_payee() + " ($" + t.get_outflow() + " outflow) ' matches 'Canadian'")

# test filtering transaction list based on payee memo

print("\nFilter by transactions with payee that matches 'immigration':\n")

for t in transaction_lister.get_transactions_by_memo('immigration'):
    print("'" + t.get_memo() + " ($" + t.get_outflow() + " outflow)' matches 'immigration'")

# test inflow/outflow filtering

print("\nTransactions going out that are between $1000 and $9000:")
for t in transaction_lister.get_transactions_by_outflow_filter([1000, 9000]):
    t_date = "?"

    if t.get_payee() != None:
        t_payee = t.get_payee()

    if t.get_date() != None:
        t_date = t.get_date()

    print(t_payee + " (outflow of $" + str(t.get_outflow()) + ") on " + t_date + " )")

print("\nTransactions coming in that are between $1000 and $9000:")

for t in transaction_lister.get_transactions_by_inflow_filter([1000, 9000]):
    t_date = "?"

    if t.get_payee() != None:
        t_payee = t.get_payee()

    if t.get_date() != None:
        t_date = t.get_date()

    print(t_payee + " (inflow of $" + str(t.get_inflow()) + ") on " + t_date + " )")

# test category subchild name filtering

print()
print("Category listing (with subcategories whose name matches 'Fun':")

for c in category_lister.get_content():
    print("Cat : " + c.get_name() + "(type: " + c.get_type() + ")")
    for x in c.get_children('Fun'):
        print("Sub Cat :" + x.get_name() + " (Parent Name is is " + x.get_parent().get_name() + ")")


class Solution:
    def isValid(self, s: str) -> bool:
        newStack = []
        dic = {")": "(", "}": "{", "]":"["}

        for x in s:
            if x in dic:
                if newStack and newStack[-1] == dic[x]:
                    newStack.pop()
                else:
                    return False
            else:
                newStack.append(x)

        return True if not newStack else False


#!/usr/bin/python

"""
    starter code for exploring the Enron dataset (emails + finances)
    loads up the dataset (pickled dict of dicts)

    the dataset has the form
    enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }

    {features_dict} is a dictionary of features associated with that person
    you should explore features_dict as part of the mini-project,
    but here's an example to get you started:

    enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000

"""

import pickle
import pprint

enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "r"))
pp = pprint.PrettyPrinter(indent=4)

def main():

    print("Number of people: {}".format(len(enron_data)))
    print("Number of features per person: {}".format(len(enron_data.values()[0])))

    poi_count = 0
    poi_without_total_payments = 0

    print("Keys = {}".format(enron_data.values()[0]))

    restricted_stock_deferred = 0
    for i in enron_data.values():
        if i["poi"] == 1:
            poi_count += 1
            if i["total_payments"] == 'NaN':
                poi_without_total_payments += 1
        if i['restricted_stock_deferred'] != 'NaN':
            restricted_stock_deferred += 1

    print("People with restricted stock deferred = {}".format(restricted_stock_deferred))
    print("PoI's without total payments: {}".format(poi_without_total_payments))
    print("Percentage PoI's without total payments: {}".format(float(poi_without_total_payments)/poi_count))

    print("Number of persons of interest: {}".format(poi_count))
    # print(enron_data["PRENTICE JAMES"].keys())
    print("James Prentice's stock value: {}".format(enron_data["PRENTICE JAMES"]["total_stock_value"]))
    print("Wesley Colwell's email messages to poi's: {}".format(enron_data["COLWELL WESLEY"]["from_this_person_to_poi"]))
    print("Jeffrey Skilling's exercised stock option value: {}".format(returnPerson("Jeffrey K Skilling")["exercised_stock_options"]))

    for person in ["Kenneth L Lay", "Jeffrey K Skilling", "Andrew S Fastow"]:
        print("{}: {}".format(person, returnPerson(person)["total_payments"]))

    pp.pprint(returnPerson("Kenneth L Lay"))

    number_of_known_emails = 0
    number_of_quantified_salaries = 0
    number_of_existing_total_payments = 0
    for i in enron_data.values():
        if i["salary"] != 'NaN':
            number_of_quantified_salaries += 1
        if i["email_address"] != 'NaN':
            number_of_known_emails += 1
        if i["total_payments"] != 'NaN':
            number_of_existing_total_payments += 1
    print("Number of known emails: {}".format(number_of_known_emails))
    print("Number of quantified salaries: {}".format(number_of_quantified_salaries))
    print("Number of people with total payments: {}".format(number_of_existing_total_payments))
    print("Percentage of people with total payments: {}".format(float(number_of_existing_total_payments)/len(enron_data)))

    exercised_options_list = []
    salary_list = []
    enron_data.pop("TOTAL", 0)
    for key, value in enron_data.items():
        exercised_options_list.append(value["exercised_stock_options"])
        salary_list.append(value["salary"])

    exercised_options_list.sort()
    salary_list.sort()
    print(exercised_options_list)
    print(salary_list)

def returnPerson(name):
    names = name.split(" ")
    first_name = names[0].upper()
    last_name = ''
    middle_initial = ''

    if len(names) == 2:
        last_name = names[1].upper()
        return enron_data["{} {}".format(last_name, first_name)]
    elif len(names) == 3:
        middle_initial = names[1].upper()
        last_name = names[2].upper()
        return enron_data["{} {} {}".format(last_name, first_name, middle_initial)]

if __name__ == "__main__":
    main()


def heapsort(arr):
    """
    Sorts an array using the heapsort algorithm.

    Parameters:
        arr (list): The array to be sorted.
    """
    n = len(arr)

    # Build a max heap
    for i in range(n // 2 - 1, -1, -1):
        heap(arr, n, i)

    # Move the largest element to the end and heapify the remaining elements
    for i in range(n - 1, 0, -1):
        swap(arr, i, 0)
        heap(arr, i, 0)

def heap(arr, n, i):
    """
    Heapify the array by comparing the value at index i with its left and right child.
    If necessary, swap the value with the maximum of the three and recursively heapify the affected subtree.

    Args:
        arr (List[int]): The array to be heapified.
        n (int): The size of the heap.
        i (int): The index of the element to be heapified.

    Returns:
        None
    """
    m = i  # Initialize the maximum value index
    left = 2 * i + 1  # Calculate the left child index
    right = 2 * i + 2  # Calculate the right child index

    # Compare the value at index i with its left child
    if left < n and arr[m] < arr[left]:
        m = left

    # Compare the value at index i with its right child
    if right < n and arr[m] < arr[right]:
        m = right

    # If the maximum value index is not the same as the current index i, swap the values
    if m != i:
        swap(arr, m, i)
        heap(arr, n, m)

def swap(arr, x, y):
    arr[x], arr[y] = arr[y], arr[x]

if __name__ == "__main__":
    arr = [3, 6, 4, 3, 4, 6, -2, 4, -35, 7]
    heapsort(arr)
    print(arr)