import argparse
import logging
import os
import random
import time

import numpy as np
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader, SubsetRandomSampler
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm

from dataset.cifar import DATASET_GETTERS, t_v_split
from dataset import ood_data
from utils import AverageMeter, accuracy, get_score, get_roc_sklearn, get_pr_sklearn, get_fpr

best_acc = 0
logger = logging.getLogger(__name__)

def set_seed(args):
    random.seed(args.seed)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    if args.n_gpu > 0:
        torch.cuda.manual_seed_all(args.seed)

def main():
    parser = argparse.ArgumentParser(description='PyTorch AIOL Evaluation')
    parser.add_argument('--gpu-id', default='0', type=int,
                        help='id(s) for CUDA_VISIBLE_DEVICES')
    parser.add_argument('--num-workers', type=int, default=4,
                        help='number of workers')
    parser.add_argument('--root', default='/data0/OOD_Data', type=str,
                        help='root of the dataset path')
    parser.add_argument('--dataset', default='cifar10', type=str,
                        choices=['cifar10', 'cifar100'],
                        help='dataset name')
    parser.add_argument('--num-labeled', type=int, default=1000,
                        help='number of labeled data')
    parser.add_argument("--expand-labels", action="store_true",
                        help="expand labels to fit eval steps")
    parser.add_argument('--arch', default='wideresnet', type=str,
                        choices=['wideresnet'],
                        help='dataset name')
    parser.add_argument('--batch-size', default=64, type=int,
                        help='train batchsize')
    parser.add_argument('--use-ema', action='store_true', default=True,
                        help='use EMA model')
    parser.add_argument('--ema-decay', default=0.999, type=float,
                        help='EMA decay rate')
    parser.add_argument('--mu', default=7, type=int,
                        help='coefficient of unlabeled batch size')
    parser.add_argument('--T', default=1., type=float,
                        help='pseudo label temperature')
    parser.add_argument('--out', default='./results/temp',
                        help='directory to output the result')
    parser.add_argument('--resume', default='', type=str,
                        help='path to latest checkpoint (default: none)')
    parser.add_argument('--seed', default=None, type=int,
                        help="random seed")
    parser.add_argument("--amp", action="store_true",
                        help="use 16-bit (mixed) precision through NVIDIA apex AMP")
    parser.add_argument("--opt_level", type=str, default="O1",
                        help="apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']."
                        "See details at https://nvidia.github.io/apex/amp.html")
    parser.add_argument("--local_rank", type=int, default=-1,
                        help="For distributed training: local_rank")
    parser.add_argument('--no-progress', action='store_true',
                        help="don't use progress bar")
    parser.add_argument('--seen-ood', type=str, default='imagenet32',
                        choices=['cifar10', 'cifar100', 'imagenet32', 'svhn', 'split'],
                        help="choose seen OOD data")

    args = parser.parse_args()
    global best_acc

    def create_model(args):
        import models.wideresnet as models
        model = models.build_wideresnet(depth=args.model_depth,
                                        widen_factor=args.model_width,
                                        dropout=0,
                                        num_classes=args.num_classes)
        logger.info("Total params: {:.2f}M".format(
            sum(p.numel() for p in model.parameters())/1e6))
        return model

    if args.local_rank == -1:
        device = torch.device('cuda', args.gpu_id)
        args.world_size = 1
        args.n_gpu = torch.cuda.device_count()
    else:
        torch.cuda.set_device(args.local_rank)
        device = torch.device('cuda', args.local_rank)
        torch.distributed.init_process_group(backend='nccl')
        args.world_size = torch.distributed.get_world_size()
        args.n_gpu = 1

    args.device = device

    print(dict(args._get_kwargs()))

    if args.seed is not None:
        set_seed(args)

    logging.basicConfig(
    format="%(asctime)s - %(levelname)s - %(name)s -   %(message)s",
    datefmt="%m/%d/%Y %H:%M:%S",
    level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN)

    if args.local_rank in [-1, 0]:
        os.makedirs(args.out, exist_ok=True)
        args.writer = SummaryWriter(args.out)
        logger.addHandler(
            logging.FileHandler(os.path.join(os.path.dirname(args.resume), "eval.log"), "a")
        )

    # find the temperature of last epoch during training via train.log
    try:
        train_log_path = os.path.join(os.path.dirname(args.resume), "train.log")
        with open(train_log_path, 'r') as f:
            lines = f.readlines()
        for line in lines[::-1]:
            line = line.strip()
            if 'temperature' in line:
                import re
                r = re.findall("[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?", line)
                args.T = float(r[0])
                break
    except:
        args.T = 1
    logger.info('T:%.4f' % args.T)

    args.model_depth = 28
    args.model_width = 2
    if args.dataset == 'cifar10':
        args.num_classes = 10
        if args.seen_ood == 'split':
            args.num_classes = 6
            args.num_labeled = 600

    elif args.dataset == 'cifar100':
        args.num_classes = 100
        if args.seen_ood == 'split':
            args.num_classes = 65
            args.num_labeled = 6500

    if args.local_rank not in [-1, 0]:
        torch.distributed.barrier()

    test_id_dataset, test_ood_dataset = DATASET_GETTERS[args.dataset].get_cifar(args, mode='val')

    if args.local_rank == 0:
        torch.distributed.barrier()

    # test loader
    test_indices, _ = t_v_split(args, test_id_dataset.targets)

    test_loader = DataLoader(
        test_id_dataset,
        sampler=SubsetRandomSampler(test_indices),
        batch_size=args.batch_size,
        num_workers=args.num_workers,
        pin_memory=True,
        )

    # seen ood loader
    if args.seen_ood == 'split':
        seen_ood_loader = DataLoader(
            test_ood_dataset,
            shuffle=False,
            batch_size=args.batch_size,
            num_workers=args.num_workers,
            pin_memory=True)
    else:
        seen_ood_loader = ood_data.__dict__[args.seen_ood](args, mode='seen')

    # unseen ood loader
    unseen_ood_loaders_dict = {}
    ds = ['cifar10', 'cifar100', 'svhn', 'blobs', 'texture', 'imagenet32', 'isun', 'lsun', 'places365']
    ds.remove(args.dataset)
    if args.seen_ood != 'split':
        ds.remove(args.seen_ood)

    for d in ds:
        ood_loader = ood_data.__dict__[d](args)
        unseen_ood_loaders_dict[d] = ood_loader

    if args.local_rank not in [-1, 0]:
        torch.distributed.barrier()

    model = create_model(args)

    if args.local_rank == 0:
        torch.distributed.barrier()

    model.to(args.device)

    ema_model = None
    if args.use_ema:
        from models.ema import ModelEMA
        ema_model = ModelEMA(args, model, args.ema_decay)

    if args.resume:
        print("==> Resuming from checkpoint..")
        assert os.path.isfile(
            args.resume), "Error: no checkpoint directory found!"
        args.out = os.path.dirname(args.resume)
        checkpoint = torch.load(args.resume)
        best_acc = checkpoint['best_acc']
        args.start_epoch = checkpoint['epoch']
        model.load_state_dict(checkpoint['state_dict'])
        if args.use_ema:
            ema_model.ema.load_state_dict(checkpoint['ema_state_dict'])

    if args.local_rank != -1:
        model = torch.nn.parallel.DistributedDataParallel(
            model, device_ids=[args.local_rank],
            output_device=args.local_rank, find_unused_parameters=True)

    if args.use_ema:
        test_model = ema_model.ema
    else:
        test_model = model

    test(args, test_loader, test_model)
    ood_detect_seen(args, test_loader, seen_ood_loader, test_model)
    ood_detect_unseen(args, test_loader, unseen_ood_loaders_dict, test_model)
    logger.info('\n')

def test(args, test_loader, model):
    batch_time = AverageMeter()
    data_time = AverageMeter()
    losses = AverageMeter()
    top1 = AverageMeter()
    top5 = AverageMeter()
    end = time.time()

    if not args.no_progress:
        test_loader = tqdm(test_loader,
                           disable=args.local_rank not in [-1, 0])

    with torch.no_grad():
        for batch_idx, (inputs, targets) in enumerate(test_loader):
            data_time.update(time.time() - end)
            model.eval()

            inputs = inputs.to(args.device)
            targets = targets.to(args.device)
            outputs = model(inputs)
            loss = F.cross_entropy(outputs, targets)

            prec1, prec5 = accuracy(outputs, targets, topk=(1, 5))
            losses.update(loss.item(), inputs.shape[0])
            top1.update(prec1.item(), inputs.shape[0])
            top5.update(prec5.item(), inputs.shape[0])

            batch_time.update(time.time() - end)
            end = time.time()
            if not args.no_progress:
                test_loader.set_description("Test Iter: {batch:4}/{iter:4}. Data: {data:.3f}s. Batch: {bt:.3f}s. Loss: {loss:.4f}. top1: {top1:.2f}. top5: {top5:.2f}. ".format(
                    batch=batch_idx + 1,
                    iter=len(test_loader),
                    data=data_time.avg,
                    bt=batch_time.avg,
                    loss=losses.avg,
                    top1=top1.avg,
                    top5=top5.avg,
                ))
        if not args.no_progress:
            test_loader.close()

    logger.info(args.seen_ood)
    logger.info("top-1 acc: {:.2f}".format(top1.avg))
    logger.info("top-5 acc: {:.2f}".format(top5.avg))
    return losses.avg, top1.avg

def ood_detect_seen(args, id_loader, ood_loader, model):
    score_id = get_score(model, id_loader, args)
    score_ood = get_score(model, ood_loader, args)
    auroc = get_roc_sklearn(score_id, score_ood)
    fpr95 = get_fpr(score_id, score_ood)
    aupr = get_pr_sklearn(score_id, score_ood)
    logger.info("auc: %.1f\tfpr: %.1f\taupr: %.1f\tseen: %s" % (auroc * 100, fpr95 * 100, aupr * 100, args.seen_ood))

def ood_detect_unseen(args, test_loader, ood_loaders_dict, model):
    score_id = get_score(model, test_loader, args)
    auc_unseen_sum = 0
    fpr_unseen_sum = 0
    aupr_unseen_sum = 0
    unseen_num = 0

    for ood_name, ood_loader in ood_loaders_dict.items():
        score_ood = get_score(model, ood_loader, args)
        auroc = get_roc_sklearn(score_id, score_ood)
        fpr95 = get_fpr(score_id, score_ood)
        aupr = get_pr_sklearn(score_id, score_ood)

        logger.info("auc: %.1f\tfpr: %.1f\taupr: %.1f\t%s" % (auroc * 100, fpr95 * 100, aupr * 100, ood_name))

        auc_unseen_sum += auroc
        fpr_unseen_sum += fpr95
        aupr_unseen_sum += aupr
        unseen_num += 1

    logger.info("auc: %.1f\tfpr: %.1f\taupr: %.1f\tunseen" % (auc_unseen_sum / unseen_num * 100, fpr_unseen_sum / unseen_num * 100, aupr_unseen_sum / unseen_num * 100))

if __name__ == '__main__':
    main()


class Solution:
    def fairCandySwap(self, A, B):
        """
        :type A: List[int]
        :type B: List[int]
        :rtype: List[int]
        """

        sum_of_A = sum(A)
        sum_of_B = sum(B)

        target = (sum_of_A - sum_of_B) // 2

        if len(A) <= len(B):
            hash_B = dict([(x, 0) for x in B])

            for a in A:
                if a - target in hash_B:
                    return [a, a - target]

        else:
            hash_A = dict([(x, 0) for x in A])

            for b in B:
                if b + target in hash_A:
                    return [b + target,b]

if __name__ == '__main__':

    r = Solution().fairCandySwap([1,1],[2,2])
    print(r)


import os
import re
import sys
# Add submodules to path
from datetime import datetime

from Common_classes.DBConnector import DBConnector, BLM, BeamInterval, Run, BeamMode
from multiprocessing import Pool
from source.Plotters.PlotCalc import PlotCalc

# from config import BLM_LIST_DIR, PICKLE_INTENSITY_INTERVALS_PATH, PLOTS_DIR_PATH
from source.Calculators.Integral.BeamModeSubIntervalsCalc import BeamModeSubIntervalsCalc
from source.Calculators.Integral.PostOffsetCorrectedIntegralCalc import PostOffsetCorrectedIntegralCalc
from source.Calculators.Integral.PreOffsetCorrectedIntegralCalc import PreOffsetCorrectedIntegralCalc
from source.Calculators.Integral.RawIntegralCalc import RawIntegralCalc
from source.Calculators.Offset.PostOffsetCalc import PostOffsetCalc
from source.Calculators.Offset.PreOffsetCalc import PreOffsetCalc
# from source.Plotters.BLMsPlotter import BLMsPlotter
from source.BLMProcess import BLMProcess
import logging
from arguments_parser import build_blm_dose_calc_parser
import pandas as pd
# from lhc_runs import lhc_runs, extract_runs

BLM_LIST_DIR = '/mnt/monitoring_analysis/data/blm_lists'

def save_to_excel(blms, fname='blms'):
    writer = pd.ExcelWriter(fname + '.xlsx')
    for blm in blms:
        blm.get_as_pandas_dataframe().to_excel(writer,blm.name)
    writer.save()

def save_to_excel_beam_modes(blms, fname, all_beam_modes):
    writer = pd.ExcelWriter(fname + '.xlsx')
    rslt = pd.concat([blm.get_beam_mode_doses_as_dataframe(all_beam_modes) for blm in blms], axis=0)
    rslt.to_excel(writer,'data')
    writer.save()

if __name__ == '__main__':
    dbc_test = DBConnector('pcen35754', db_name='lhc_raw', user='jenkins')
    dbc_test.connect_to_db()
    dbc_test.build_database()
    dbc_test.commit()
    runs = list(dbc_test.get_lhc_runs())
####################################################################################

    parser = build_blm_dose_calc_parser(runs)
    args = parser.parse_args()
    # print(args.start_date)

    dbc_test.close()
############################# Parsed command line arguments assignment ########
    # runs = Run.extract_runs(args)
    # start = runs[0][0]
    # end = runs[-1][1]
    requested_run = Run.extract_runs_from_command_line_argument(args, runs)
    blm_csv_list_filename = args.file_name
    number_of_simultaneous_processes = args.processes_num
    should_plot_total = args.pt
    should_plot_intensity_norm = args.pi
    should_plot_luminosity_norm = bool(args.pl)
    should_save_excel = args.save_to_excel
    luminosity = args.pl # 39.31 if start.year == 2016 else 37.83
    should_plot_cumsum = args.pcs
    logging_level = getattr(logging, args.logging_level)
    blm_raw_data_dir = args.raw_blm_path
    pickled_blm_dir = args.pickled_blm_path
    field = args.field_name
    IP_num = args.ir if args.ir else args.arc

    blm_filter_function_name = 'ir' if args.ir else None
    blm_filter_function_name = 'arc' if args.arc else None
    if not blm_filter_function_name:
        blm_filter_function_name = 'all'

    should_plot_heatmap = False
    left_offset = 700
    right_offset = 700

# ####################################################################################
    logging.basicConfig(level=logging_level)

    calculators = [PreOffsetCalc(), PreOffsetCorrectedIntegralCalc(),
                   RawIntegralCalc(),
                   PostOffsetCalc(), PostOffsetCorrectedIntegralCalc(),
                   BeamModeSubIntervalsCalc(),
                   # PlotCalc('plots')
                   ]

    dbc_test.connect_to_db()
    dbc_test.build_database()
    dbc_test.commit()

    if blm_csv_list_filename is not None:
        # blms_list = ['BLMED.04R8.B2C10_TDI.4R8.B2', ]
        blm_list_file_path = os.path.join(BLM_LIST_DIR, blm_csv_list_filename)
        blms_list = pd.read_csv(blm_csv_list_filename, header=None)[0].values
        filter_func = BLM.name.in_(blms_list)
    else:
        filter_func = True

    blms = list(dbc_test.session.query(BLM).filter(filter_func).all())
    # blms =list(filter(lambda  blm: '16L2' in blm.name or '17L2' in blm.name or '15L2' in blm.name, blms))
    print(len(blms))
    beam_modes = list(dbc_test.session.query(BeamMode))
    beam_intervals = list(filter(lambda beam_interval: beam_interval.start_time in requested_run, dbc_test.session.query(BeamInterval).all()))
    dbc_test.close()

    should_plot = should_plot_total or should_plot_cumsum or should_plot_intensity_norm or should_plot_luminosity_norm
    should_return_blm = should_plot or should_save_excel
    blm_process = BLMProcess(requested_run, field, calculators, should_return_blm, dbc_test, beam_intervals)
    # Reading and processing BLMs data
    # with Pool(processes=number_of_simultaneous_processes) as pool:
    #     blm_names_blm_intervals = {pseudoBLM.name: pseudoBLM.blm_intervals for pseudoBLM in pool.map(blm_process.run, blms[:]) if pseudoBLM is not None}

    blm_names_blm_intervals = {pseudoBLM.name: pseudoBLM.blm_intervals for pseudoBLM in list(map(blm_process.run, blms[:])) if pseudoBLM is not None}
    if blm_process.should_return_blm:

        blm_names = set(blm_names_blm_intervals.keys())
        for blm in blms:
            # print(blm.name, blm_names)
            if blm.name in blm_names:
                blm.blm_intervals_filtered = blm_names_blm_intervals[blm.name]
                # for i in blm.blm_intervals_filtered:
                #     print('{:%Y-%m-%d %H:%M}\t{:%Y-%m-%d %H:%M}\t{:.3e}\t{:.3e}'.format(i.start_time, i.end_time, i.integrated_dose, i.offset_pre))
            else:
                blm.blm_intervals_filtered = []
                # sys.exit()
        logging.info('Analysed BLM types: {}'.format(', '.join(set(blm.get_blm_type() for blm in blms))))

        if should_save_excel and blms:
            # save_to_excel_beam_modes(blms, 'BLMs_with_beam_modes_{}'.format(requested_run),beam_modes)
            save_to_excel_beam_modes(blms, 'BLMs_with_beam_modes_{:%Y%m%d}_{:%Y%m%d}'.format(requested_run.get_earliest_date(), requested_run.get_latest_date()),beam_modes)

        if should_plot:
            # Plotting
            pass
            # p = BLMsPlotter('.')
            # if should_plot_luminosity_norm:
            #     p.plot_luminosity_normalized_dose(blms, lambda blm: blm.get_pre_oc_dose(), luminosity)
            # if should_plot_intensity_norm:
            #     p.plot_intensity_normalized_dose(blms, lambda blm: blm.get_pre_oc_dose(), lambda blm: blm.get_oc_intensity_integral())
            # if should_plot_cumsum:
            #     p.plot_total_cumulated_dose(blms, lambda blm, start, end: blm.get_pre_oc_dose(start, end))
            # if should_plot_total:
            #     p.plot_total_dose(blms, lambda blm: blm.get_pre_oc_dose())
            # if should_plot_heatmap:
            #     p.heat_map_plot(blms)


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

"""
Есть идея создать бота для девочек
То есть девочка переходит по ссылке, пишет боту, а он присылает ей рандомную открытку на 8 марта и какое-то поздравление
Открытки и поздравления сейчас в процессе

Девочка переходит по ссылке, дальше бот предлагает ей получить открытку или поздравление, девочка получает то,
что выбрала, потом можно еще выбрать. Можешь еще давать вопросы какие-то наводящие, например
"Привет, ты мальчик или девочка" , про курс или направление можно спросить

"""
import random
from vk_api.longpoll import VkEventType
import importlib
import botlib

HEADERS = {"user-agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.2"}

def _start():
    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW and event.to_me and event.text:
            sent_message = event.text
            user_id = event.user_id

            # Обычные сообщения. Ответ на них приоритетнее

            # ответ на начать
            if sent_message.lower() in botlib.HELLO_USER_MESSAGES:
                botlib.send(user_id, botlib.HELLO_ANSWER_MESSAGE % botlib.UserVK(user_id).get_name(), keyboard=botlib.json_main_kb)

            # ответ на просьбу получить открытку
            elif sent_message.lower() == botlib.CONST_JSON["keyboards"]["main"]["card"]["text"].lower():
                botlib.send(user_id, botlib.CONST_JSON["answers"]["yourCard"], attachment=random.choice(botlib.IMAGES_LIST))

            # ответ на просьбу получить поздравление
            elif sent_message.lower() == botlib.CONST_JSON["keyboards"]["main"]["greeting"]["text"].lower():
                botlib.send(user_id, random.choice(botlib.greetings_file))

            # ответ на просьбу получить описание пасхалки
            elif sent_message.lower() == botlib.CONST_JSON["keyboards"]["main"]["about_egg_1"]["text"].lower():
                botlib.send(user_id, botlib.about_egg_file)

            # обработка секретного сообщения, которое могут получить только девушки
            elif sent_message.lower() == botlib.CONST_JSON["answers"]["secretTriggerMessage"].lower():
                if botlib.UserVK(user_id).get_sex() == "женский":
                    botlib.send(user_id, botlib.CONST_JSON["answers"]["secretMessage"] % botlib.UserVK(user_id).get_name(), attachment=botlib.SECRET_IMAGE)
                    botlib.send(int(botlib.CONST_VK_ADMIN_ID),
                                f"🎁 [id{user_id}|{botlib.UserVK(user_id).get_name()} {botlib.UserVK(user_id).get_name('last')}] нашла пасхалку!")
                else:
                    botlib.send(user_id, botlib.HELLO_ERROR_MESSAGE)

            # обработка команды АВТОР
            elif sent_message.lower() == botlib.CONST_JSON["keyboards"]["main"]["author"]["text"].lower():
                botlib.send(user_id, botlib.CONST_JSON["answers"]["author"])

            # команды администратора
            elif str(user_id) in botlib.CONST_VK_ADMINLIST_COMMSEP and sent_message.lower()[0] == "/":
                command = sent_message.lower().split()
                botlib.send(user_id, f"🍕 Вы запустили операцию: "+command[0])

                if int(user_id) != int(botlib.CONST_VK_ADMIN_ID):
                    botlib.send(int(botlib.CONST_VK_ADMIN_ID), f"🍕 Администратор [id{user_id}|{botlib.UserVK(user_id).get_name()} {botlib.UserVK(user_id).get_name('last')}] запустил операцию: "+command[0])

                if command[0] == "/обновить":
                    """Команда перезагружает текстовый и графический контент бота.
                    Если были внесены изменения в ветке content, то надо выполнить эту команду.

                    Команда останавливает бота до окончания операции!"""
                    importlib.reload(botlib)
                    botlib.send(user_id, "🍕 Обновление бота завершено")
                    if int(user_id) != int(botlib.CONST_VK_ADMIN_ID):
                        botlib.send(int(botlib.CONST_VK_ADMIN_ID),
                                f"🍕 Администратор [id{user_id}|{botlib.UserVK(user_id).get_name()} {botlib.UserVK(user_id).get_name('last')}] завершил операцию: " +
                                command[0])
                    raise ValueError(command[0])

                elif command[0] == "/статус":
                    """Команда показывает отправителю свой статус"""
                    botlib.send(user_id, "🍕 Вы являетесь администратором чат-бота")

                elif command[0] == "/помощь":
                    """Команда показывает всю основную информацию о боте"""
                    botlib.send(user_id, botlib.HELP_ADMIN)

                elif command[0] == "/список_админов":
                    """Команда отправляет список администраторов

                    Команда останавливает бота до окончания операции!"""
                    admin_list = ""
                    for e in botlib.CONST_VK_ADMINLIST_COMMSEP:
                        admin_list += f"[id{e}|{botlib.UserVK(int(e)).get_name()} {botlib.UserVK(int(e)).get_name('last')}]\n"
                    botlib.send(user_id, "🍕 Список админов чат-бота:\n" + admin_list)

                elif command[0] == "/количество_диалогов":
                    """Команда отправляет список написавших пользователей. Не выполнять без особенной необходимости!"""
                    response = botlib.VK.method("messages.getConversations", {"access_token": botlib.CONST_JSON["tokenVK"]})
                    botlib.send(user_id, f"🍕 Количество диалогов с сообществом на данный момент: {response['count']}")

                else:
                    botlib.send(user_id, f"🍕 Команда " + command[0] + " не найдена. Попробуйте написать /помощь, чтобы получить список доступных команд.")
            else:
                botlib.send(user_id, botlib.HELLO_ERROR_MESSAGE)

while True:
    try:
        vk = botlib.VK
        longpoll = botlib.LONGPOLL
        upload = botlib.UPLOAD
        print('Бот запущен!')
        print(__doc__)
        _start()
    except Exception:
        pass


soma = int()
idade1 = int()
nome1 = ''
count = int()
for i in range(1, 5):
    nome = str(input('Digite o {}º nome:'.format(i))).strip()
    idade = int(input('Digite a {}ª idade:'.format(i)))
    sexo = str(input('Digite o {}º sexo (m para masculino e f para feminino):'.format(i))).strip()
    soma += idade

    if sexo in 'mM':
        if i == 1:
            idade1 = idade
            nome1 = nome
        elif idade > idade1:
            idade1 = idade
            nome1 = nome
    if sexo in 'Ff':
        if idade < 20:
            count += 1
print('A média de idade do grupo é de {}'.format(soma/4))
print('O homem mais velho se chama {}'.format(nome1))
print('Desse grupo {} mulheres tem menos que 20 anos.'.format(count))


import nextcord
from nextcord.ext import commands

class RockPaperScissors(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    async def rps(self, ctx):
        player1 = ctx.author
        await ctx.send(
            f"{player1.mention}, please choose rock, paper, or scissors.")
        msg1 = await self.client.wait_for(
            'message',
            check=lambda m: m.author == player1 and m.content.lower(
            ) in ['rock', 'paper', 'scissors'])
        player1_choice = msg1.content.lower()

        player2_mentions = list(
            filter(lambda x: x != player1, ctx.message.mentions))
        if len(player2_mentions) != 1:
            await ctx.send(
                f"{player1.mention}, you need to mention one other player to play with!"
            )
            return

        player2 = player2_mentions[0]
        await ctx.send(
            f"{player2.mention}, please choose rock, paper, or scissors.")
        msg2 = await self.client.wait_for(
            'message',
            check=lambda m: m.author == player2 and m.content.lower(
            ) in ['rock', 'paper', 'scissors'])
        player2_choice = msg2.content.lower()

        winner = None
        if player1_choice == player2_choice:
            result = "It's a tie!"
        elif player1_choice == 'rock' and player2_choice == 'scissors':
            winner = player1
        elif player1_choice == 'paper' and player2_choice == 'rock':
            winner = player1
        elif player1_choice == 'scissors' and player2_choice == 'paper':
            winner = player1
        else:
            winner = player2

        if winner is not None:
            result = f"{winner.mention} wins!"
        await ctx.send(
            f"{player1.mention} chose {player1_choice}, {player2.mention} chose {player2_choice}. {result}"
        )

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


class Solution:
    ### 240. Search a 2D Matrix II ###
    # @param {integer[][]} matrix
    # @param {integer} target
    # @return {boolean}
    def searchMatrix(self, matrix, target):
        if not matrix: return False

        m, n = len(matrix), len(matrix[0])
        i, j = m-1, 0
        while 0<=i<m and 0<=j<n:
            if matrix[i][j] == target: return True
            elif matrix[i][j] > target: i-=1
            else: j+=1

        return False

    ### 241. Different Ways to Add Parentheses ###
    # @param {string} input
    # @return {integer[]}
    def diffWaysToCompute(self, input):
        if not input: return []

        res = []
        for i in xrange(len(input)):
            if input[i] in '+-*':
                for x in self.diffWaysToCompute(input[:i]):
                    for y in self.diffWaysToCompute(input[i+1:]):
                        if input[i] == '+': res.append(x+y)
                        if input[i] == '-': res.append(x-y)
                        if input[i] == '*': res.append(x*y)
        if not res: res.append(int(input))

        return res

    ### 242. Valid Anagram ###
    # @param {string} s
    # @param {string} t
    # @return {boolean}
    def isAnagram(self, s, t):
        if not s and not t: return True

        cnt = {}
        for x in s:
            if x in cnt: cnt[x] += 1
            else: cnt[x] = 1
        for x in t:
            if x in cnt and cnt[x]: cnt[x] -= 1
            else: return False
        for _, v in cnt.items():
            if v > 0: return False

        return True

    ### 257. Binary Tree Paths ###
    # @param {TreeNode} root
    # @return {string[]}
    def binaryTreePaths(self, root):
        if not root: return []
        if not root.left and not root.right: return [str(root.val)]

        return [str(root.val)+'->'+x for x in self.binaryTreePaths(root.left)+self.binaryTreePaths(root.right)]

    ### 258. Add Digits ###
    # @param {integer} num
    # @return {integer}
    def addDigits(self, num):
        if not num: return 0
        if num % 9 == 0: return 9
        return num % 9

    ### 260. Single Number III ###
    # @param {integer[]} nums
    # @return {integer[]}
    def singleNumber(self, nums):
        if not nums: return []
        if len(nums) <= 2: return nums

        xor = reduce(int.__xor__, nums)
        lastBit, le, ri = xor & (-xor), 0, 0
        for x in nums:
            if x & lastBit: le ^= x
            else: ri ^= x

        return [le, ri]

    ### 263. Ugly Number ###
    # @param {integer} num
    # @return {boolean}
    def isUgly(self, num):
        if num <= 0: return False
        if num < 7: return True

        while num%2 == 0: num /= 2
        while num%3 == 0: num /= 3
        while num%5 == 0: num /= 5

        return num == 1

    ### 264. Ugly Number II ###
    # @param {integer} n
    # @return {integer}
    def nthUglyNumber(self, n):
        if n <= 0: return 0

        dp, i2, i3, i5 = [1], 0, 0, 0
        for _ in range(n-1):
            c2, c3, c5 = dp[i2]*2, dp[i3]*3, dp[i5]*5
            res = min(c2, c3, c5)
            dp.append(res)
            if res == c2: i2 += 1
            if res == c3: i3 += 1
            if res == c5: i5 += 1

        return dp[-1]

    ### 268. Missing Number ###
    # @param {integer[]} nums
    # @return {integer}
    def missingNumber(self, nums):
        if not nums: return 0
        return len(nums)*(len(nums)+1)/2-sum(nums)


from nnsight import LanguageModel

model = LanguageModel("gpt2", device_map="cuda:0")

with model.invoke("hello world") as invoker:
    hidden_states = model.transformer.h[-1].output[0].save()

print(invoker.output)
print(hidden_states.value)


import time
import pytest
import shutil
import os
from AppiumFramework.base.DriverClass import Driver

"""
This method will be called each time a testClass is executed
it sets the driver instance and quit it at the end of each
test case
"""
@pytest.fixture(scope="class")
def oneTimeSetUp(request):
    driver1 = Driver()
    driver = driver1.getDriverMethod()

    if request.cls is not None:
        request.cls.driver = driver

    yield driver
    driver.quit()

"""
This method will clean up our previous logs to have a clean report
and without previous runs information
"""
@pytest.fixture(scope="session")
def cleanLogs():
    logFile = open("Code2LEad.log", 'w')
    logFile.close()
    shutil.rmtree("/Users/rene.cortes/PycharmProjects/AppiumPython/AppiumFramework/reports/allureReports")
    # time.sleep(5)
    os.mkdir("/Users/rene.cortes/PycharmProjects/AppiumPython/AppiumFramework/reports/allureReports")


"""
Jon William Taylor
Date: November 1 2021
Assignment: Visualization Output and Line Graph

About the program:
This program will read data from a file, draw a line graph from it, and display the output

Input: Will take survey data from a file and process it

Output: Will draw a line graph from the survey data
"""
print(__doc__)

### import statements here

### define sub functions here

### the main function

from matplotlib import pyplot as plt

import csv
import numpy as np

#get two lists of random numbers
from random import randint

x = [] #places the data for the x axis
y1 = [] #places the data for the first y axis
y2 = [] #places the data for the second y axis
def line_graph():
    with open(r'Demographic_Stats_By_Zip_Code.csv') as csv_file: #opens the file
        plot_values = csv.reader(csv_file, delimiter = ",")
        header = next(plot_values) #starts plotting the values
        counter = 0 #starts the process of reading the values
        for row in plot_values:
            counter += 1 #counts each row for data
            #if counter > 20:
                #break
            x.append(int(row[0]))
            y1.append(int(row[2])) #total female participants
            y2.append(int(row[3])) #total male participants

    the_header = str(header).strip('[')
    the_header = str(the_header).strip(']')
    headers = the_header.split(',') #splits the data

    for header in headers:
        h = header.lstrip("'") #splits the data
        h = h.rstrip("'") #splits the data
        #print(h)
    #title_plots = title_plots.strip("'")
    print(headers[0])
    print(headers[2])
    print(headers[3])

    xValues = np.arange(len(x)) #starts arranging the values on the graph
    plt.plot(xValues, y1, linestyle='--', marker='o', c='red', linewidth=2, markersize=5, mec='black', mfc='blue', label="Female") #determines the characteristics of first y axis
    plt.plot(xValues, y2, linestyle=':', marker='v', c='green', linewidth=2, markersize=5, mec='blue', mfc='yellow', label='Male') #determines the characteristics of second y axis
    plt.legend() #places the legend on the graph
    plt.xlabel(headers[0].strip().strip("'"))
    plt.ylabel(headers[1].strip().strip("'"))
    plt.xticks(np.arange(len(x)), x) #arranges the data into a graph
    #plt.set_xtickslabels(x, rotation=90)
    plt.title("Female and Male Survey Participants") #names the top of the graph
    plt.tight_layout()
    plt.savefig(r"C:\Users\Desktop\OutputGraph.png") #outputs the graph into a png file at file location
    plt.show() #shows the graph as a png file

def main():
    line_graph()

if __name__ == '__main__':
    main()

ZipCode/PA06 Visualization Output and Line Graph.py


__all__ = [
    "AMU",
    "C",
    "cs",
    "E",
    "fce",
    "fci",
    "fLH",
    "FloatUnit",
    "fpe",
    "fpi",
    "fUH",
    "IntUnit",
    "KB",
    "lD",
    "lpe",
    "lpi",
    "ME",
    "MP",
    "oce",
    "oci",
    "oLH",
    "ope",
    "opi",
    "oUH",
    "rce",
    "rci",
    "VA",
    "vTe",
    "vTi",
]

import math

from scipy import constants

pconst = constants.physical_constants

class FloatUnit(float):
    """Template class for floats with a unit attribute."""

    def __new__(cls, value, cgs_unit):
        """
        :param float value: value of constant
        :param str cgs_unit: string representation of of cgs unit
        :return: value of constant
        :rtype: float
        """
        obj = super().__new__(cls, value)
        obj._unit = cgs_unit
        return obj

    def __init__(self, value, cgs_unit):
        super().__init__()

    @property
    def unit(self):
        """units of constant"""
        return self._unit

class IntUnit(int):
    """Template class for ints with a unit attribute."""

    def __new__(cls, value, cgs_unit):
        """
        :param int value: value of constant
        :param str cgs_unit: string representation of of cgs unit
        :return: value of constant
        :rtype: int
        """
        obj = super().__new__(cls, value)
        obj._unit = cgs_unit
        return obj

    def __init__(self, value, cgs_unit):
        super().__init__()

    @property
    def unit(self):
        """units of constant"""
        return self._unit

#: atomic mass unit (g)
AMU = FloatUnit(1000.0 * constants.m_u, "g")

#: speed of light (cm/s)
C = FloatUnit(100.0 * constants.c, "cm s^-1")

#: fundamental charge (statcoul)
E = FloatUnit(4.8032e-10, "statcoul")

#: Boltzmann constant (erg/K)
KB = FloatUnit(1.3807e-16, "erg k^-1")

#: electron mass (g)
ME = FloatUnit(1000.0 * constants.m_e, "g")

#: proton mass (g)
MP = FloatUnit(1000.0 * constants.m_p, "g")

# ---- frequency constants ----
def fce(Bo, **kwargs):
    """
    electron-cyclotron frequency (Hz)

    .. math::

        f_{ce} = \\frac{\Omega_{ce}}{2 \pi}
        = -\\frac{|e| B_{o}}{2 \pi m_{e} c}

    :param float Bo: magnetic field (in Gauss)

    .. note:: see function :func:`oce`
    """
    _fce = oce(Bo) / (2.0 * math.pi)
    return FloatUnit(_fce, "Hz")

def fci(Bo, m_i, Z, **kwargs):
    """
    ion-cyclotron frequency (Hz)

    .. math::

        f_{ci} = \\frac{\Omega_{ci}}{2 \pi}
        = \\frac{Z |e| B_{o}}{2 \pi m_{i} c}

    :param float Bo: magnetic-field (in Gauss)
    :param float m_i: ion-mass (in g)
    :param int Z: charge number

    .. note:: see function :func:`oci`
    """
    _fci = oci(Bo, m_i, Z) / (2.0 * constants.pi)
    return FloatUnit(_fci, "Hz")

def fLH(Bo, m_i, n_i, Z, **kwargs):
    """
    Lower-Hybrid Resonance frequency (Hz)

    .. math::
        f_{LH} = \\frac{\omega_{LH}}{2 \pi}

    :param float Bo: magnetic field (in Gauss)
    :param float m_i: ion mass (in g)
    :param float n_i: ion number density (in :math:`cm^{-3}`)
    :param int Z: ion charge number

    .. note:: for details see function :func:`oLH`
    """
    _fLH = oLH(Bo, m_i, n_i, Z) / (2.0 * math.pi)
    return FloatUnit(_fLH, "Hz")

def fpe(n_e, **kwargs):
    """
    electron-plasma frequency (Hz)

    .. math::

        f_{pe} = \\frac{\omega_{pe}}{2 \pi}
        = \sqrt{\\frac{n_{e} e^{2}}{\pi m_{e}}}

    :param float n_e: electron number density (in :math:`cm^{-3}`)

    .. note:: see function :func:`ope`
    """
    _fpe = ope(n_e) / (2.0 * math.pi)
    return FloatUnit(_fpe, "Hz")

def fpi(m_i, n_i, Z, **kwargs):
    """
    ion-plasma frequency (Hz)

    .. math::

        f_{pi} = \\frac{\omega_{pi}}{2 \pi}
        = \sqrt{\\frac{n_{i} (Z e)^{2}}{\pi m_{i}}}

    :param float m_i: ion mass (in g)
    :param float n_i: ion number density (in :math:`cm^{-3}`)
    :param int Z: ion charge number

    .. note:: see function :func:`opi`
    """
    _fpi = opi(m_i, n_i, Z) / (2.0 * math.pi)
    return FloatUnit(_fpi, "Hz")

def fUH(Bo, n_e, **kwargs):
    """
    Upper-Hybrid Resonance frequency (Hz)

    .. math::

        f_{UH} = \\frac{\omega_{UH}}{2 \pi}

    :param float Bo: magnetic field (in Gauss)
    :param float n_e: electron number density (in :math:`cm^{-3}`)

    .. note:: see function :func:`oUH`
    """
    _fUH = oUH(Bo, n_e) / (2.0 * math.pi)
    return FloatUnit(_fUH, "Hz")

def oce(Bo, **kwargs):
    """
    electron-cyclotron frequency (rad/s)

    .. math::

        \Omega_{ce} = -\\frac{|e| B_{o}}{m_{e} c}

    :param float Bo: magnetic-field (in Gauss)
    """
    _oce = (-E * Bo) / (ME * C)
    return FloatUnit(_oce, "rad s^-1")

def oci(Bo, m_i, Z, **kwargs):
    """
    ion-cyclotron frequency (rads / s)

    .. math::

        \Omega_{ci} = \\frac{Z |e| B_{o}}{m_{i} c}

    :param float Bo: magnetic-field (in Gauss)
    :param float m_i: ion-mass (in g)
    :param int Z: charge number
    """
    _oci = (Z * E * Bo) / (m_i * C)
    return FloatUnit(_oci, "rad s^-1")

def oLH(Bo, m_i, n_i, Z, **kwargs):
    """
    Lower-Hybrid Resonance frequency (rad/s)

    .. math::
        \\frac{1}{\omega_{LH}^{2}}=
        \\frac{1}{\Omega_{i}^{2}+\omega_{pi}^{2}}
        + \\frac{1}{\\lvert \Omega_{e}\Omega_{i} \\rvert}

    .. note::

        This form is for a quasi-neutral plasma that satisfies

        .. math::
            \\frac{Z m_{e}}{m_{i}} \ll
            1 - \\left(\\frac{V_{A}}{c}\\right)^{2}

    :param float Bo: magnetic field (in Gauss)
    :param float m_i: ion mass (in g)
    :param float n_i: ion number density (in :math:`cm^{-3}`)
    :param int Z: ion charge number
    """
    _args = {"Bo": Bo, "m_i": m_i, "n_i": n_i, "Z": Z}
    _opi = opi(**_args)
    _oce = oce(**_args)
    _oci = oci(**_args)
    first_term = 1.0 / ((_oci**2) + (_opi**2))
    second_term = 1.0 / math.fabs(_oce * _oci)
    _olh = math.sqrt(1.0 / (first_term + second_term))
    return FloatUnit(_olh, "rad s^-1")

def ope(n_e, **kwargs):
    """
    electron-plasma frequency (in rad/s)

    .. math::

        \omega_{pe}^{2} = \\frac{4 \pi n_{e} e^2}{m_{e}}

    :param float n_e: electron number density (in :math:`cm^{-3}`)
    """
    _ope = math.sqrt(4 * math.pi * n_e * E * E / ME)
    return FloatUnit(_ope, "rad s^-1")

def opi(m_i, n_i, Z, **kwargs):
    """
    ion-plasma frequency (in rad/s)

    .. math::

        \omega_{pi}^{2} = \\frac{4 \pi n_{i} (Z e)^{2}}{m_{i}}

    :param float m_i: ion mass (in g)
    :param float n_i: ion number density (in :math:`cm^{-3}`)
    :param int Z: ion charge number
    """
    _opi = math.sqrt(4 * math.pi * n_i * (Z * E) * (Z * E) / m_i)
    return FloatUnit(_opi, "rad s^-1")

def oUH(Bo, n_e, **kwargs):
    """
    Upper-Hybrid Resonance frequency (rad/s)

    .. math::

        \omega_{UH}^{2} =\omega_{pe}^{2} + \Omega_{ce}^{2}

    :param float Bo: magnetic field (in Gauss)
    :param float n_e: electron number density (in :math:`cm^{-3}`)
    """
    _ope = ope(n_e)
    _oce = oce(Bo)
    _ouh = math.sqrt((_ope**2) + (_oce**2))
    return FloatUnit(_ouh, "rad s^-1")

# ---- length constants ----
def lD(kT, n, **kwargs):
    """
    Debye Length (in cm)

    .. math::

        \lambda_{D} = \sqrt{\\frac{k_{B} T}{4 \pi n e^{2}}}

    :param float kT: temperature (in eV)
    :param float n: number density (in :math:`cm^{-3}`)
    """
    kT = kT * constants.e * 1.0e7  # eV to ergs
    _lD = math.sqrt(kT / (4.0 * math.pi * n)) / E
    return FloatUnit(_lD, "cm")

def lpe(n_e, **kwargs):
    """
    electron-inertial length (cm)

    .. math::

        l_{pe} = \\frac{c}{\omega_{pe}}

    :param float n_e: electron number density (in :math:`cm^{-3}`)

    .. note:: see function :func:`ope`
    """
    _lpe = C / ope(n_e)
    return FloatUnit(_lpe, "cm")

def lpi(m_i, n_i, Z, **kwargs):
    """
    ion-inertial length (cm)

    .. math::

        l_{pi} = \\frac{c}{\omega_{pi}}

    :param float m_i: ion mass (in g)
    :param float n_i: ion number density (in :math:`cm^{-3}`)
    :param int Z: ion charge number

    .. note:: see function :func:`opi`
    """
    _lpi = C / opi(m_i, n_i, Z)
    return FloatUnit(_lpi, "cm")

def rce(Bo, kTe, **kwargs):
    """
    electron gyroradius (cm)

    .. math::

        r_{ce} = \\frac{v_{T_{e}}}{\Omega_{ce}}

    :param float Bo: magnetic field (in Gauss)
    :param float kTe: electron temperature (in eV)

    .. note:: see functions :func:`vTe` and :func:`oce`
    """
    _rce = vTe(kTe) / abs(oce(Bo))
    return FloatUnit(_rce, "cm")

def rci(Bo, kTi, m_i, Z, **kwargs):
    """
    ion gyroradius (cm)

    .. math::

        r_{ci} = \\frac{v_{T_{i}}}{\Omega_{ci}}

    :param float Bo: magnetic field (in Gauss)
    :param float kTi: ion temperature (in eV)
    :param float m_i: ion mass (in g)
    :param int Z: ion charge number

    .. note:: see functions :func:`vTi` and :func:`oci`
    """
    _rci = vTi(kTi, m_i) / oci(Bo, m_i, Z)
    return FloatUnit(_rci, "cm")

# ---- velocity constants ----
def cs(kTe, m_i, Z, gamma=1.0, **kwargs):
    """
    ion sound speed (cm/s)

    .. math::

        C_{s} = \sqrt{\\frac{\gamma Z k T_{e}}{m_{i}}}

    .. note::

        :math:`\gamma=1` for the case of :math:`T_{i}\ll T_{e}`
        (DEFAULT)

    :param float kTe: electron temperature (in eV)
    :param float m_i: ion mass (in g)
    :param int Z: charge number
    :param float gamma: adiabatic index
    """
    # TODO: double check adiabatic index default value
    kTe = kTe * constants.e * 1.0e7  # eV to ergs
    _cs = math.sqrt(gamma * Z * kTe / m_i)
    return FloatUnit(_cs, "cm s^-1")

def VA(Bo, m_i, n_i, **kwargs):
    """
    Alfvén Velocity (in cm/s)

    .. math::

        V_{A} = \\frac{B_{o}}{\sqrt{4 \pi n_{i} m_{i}}}

    :param float Bo: magnetic field (in Gauss)
    :param float m_i: ion mass (in g)
    :param float n_i: ion number density (in :math:`cm^{-3}`)
    """
    _VA = Bo / math.sqrt(4.0 * math.pi * n_i * m_i)
    return FloatUnit(_VA, "cm s^-1")

def vTe(kTe, **kwargs):
    """
    electron thermal velocity (in cm/s)

    .. math::

        v_{T_{e}} = \sqrt{\\frac{k T_{e}}{m_{e}}}

    :param float kTe: electron temperature (in eV)
    """
    kTe = kTe * constants.e * 1.0e7  # eV to erg
    _vTe = math.sqrt(kTe / ME)
    return FloatUnit(_vTe, "cm s^-1")

def vTi(kTi, m_i, **kwargs):
    """
    ion thermal velocity (in cm/s)

    .. math::

        v_{T_{i}} = \sqrt{\\frac{k T_{i}}{m_{i}}}

    :param float kTi: ion temperature (in eV)
    :param float m_i: ion mass (in g)
    """
    kTi = kTi * constants.e * 1.0e7  # eV to erg
    _vTi = math.sqrt(kTi / m_i)
    return FloatUnit(_vTi, "cm s^-1")


#!/usr/bin/python3
# -*- coding: utf-8 -*-

#
# 对这个程序的一些说明：
#
# 1. 因手上只有一个步进动机，
# 只写了控制步进动机一(Motor One)的控制程序，其余的四个动机控制代码尚未编写
#
# 2. 显示超声测距实时距离的界面，五个界面测的都是同一个超声模块测的数值
# 之后根据需要修改即可
#

from flask import Flask, render_template, request
from flask_script import Manager
from time import sleep
import threading
import hardware
import config

app = Flask(__name__)
app.config.from_object(config)
manager = Manager(app)

@app.route('/')
def hello_world():
    return render_template("index.html")

#
# 定义全局变量
# 之后要修改要定义 motor_status 的值是从数据库中读取以读取实时状态
motor_1_status = "stop"
# motor_2_status = "stop"
# motor_3_status = "stop"
# motor_4_status = "stop"
# motor_5_status = "stop"

#
# ######################## motor settings ########################
# motor one settings
class motor_1_run:
    def __init__(self):
        global motor_1_status
        self.motor = hardware.motor()

    def set_fast(self):
        sleep(0.05)
        self.motor.motor_speed(speed=3)
        sleep(0.05)
        # print("set fast model")

    def set_middle(self):
        sleep(0.05)
        self.motor.motor_speed(speed=2)
        sleep(0.05)
        # print("set middle model")

    def set_low(self):
        sleep(0.05)
        self.motor.motor_speed(speed=1)
        sleep(0.05)
        # print("set low model")

    def run_fast(self):
        self.set_fast()
        self.motor.motor_start()
        while motor_1_status == "fast":
            pass

    def run_middle(self):
        self.set_middle()
        self.motor.motor_start()
        while motor_1_status == "middle":
            pass

    def run_low(self):
        self.set_low()
        self.motor.motor_start()
        while motor_1_status == "low":
            pass

    def run_stop(self):
        self.motor.motor_stop()

# ################### motor controlling #####################

# motor one
# 定义在函数内部，页面刷新后，会释放掉对象，导致刷新页面后会停止
# 因为这个原因，只能定义在函数外面了
motor_one = motor_1_run()

@app.route('/motor_1')
def motor_1():

    global motor_1_status
    motor_order = request.args.get("motor_order")

    if (motor_1_status != "fast") and (motor_order == "fast"):
        # 分配线程，执行线程
        t = threading.Thread(target=motor_one.run_fast, args=())
        t.start()
        sleep(0.02)
        motor_1_status = "fast"
        print("motor one run in fast speed")

    elif (motor_1_status != "middle") and (motor_order == "middle"):

        # same as before
        t = threading.Thread(target=motor_one.run_middle, args=())
        t.start()
        sleep(0.02)
        motor_1_status = "middle"
        print("motor one run in middle speed")

    elif (motor_1_status != "low") and (motor_order == "low"):

        # same as before
        t = threading.Thread(target=motor_one.run_low, args=())
        t.start()
        sleep(0.02)
        motor_1_status = "low"
        print("motor one run in low speed")

    elif (motor_1_status != "stop") and (motor_order == "stop"):

        motor_one.run_stop()
        # 停止动机需要时间
        sleep(0.5)
        motor_1_status = "stop"

    elif (motor_order == "fast") and (motor_1_status == "fast"):
        print("motor one has run in fast speed")

    elif (motor_order == "middle") and (motor_1_status == "middle"):
        print("motor one has run in middle speed")

    elif (motor_order == "low") and (motor_1_status == "low"):
        print("motor one has run in low speed")

    elif (motor_order == "stop") and (motor_1_status == "stop"):
        print("motor one has stopped")

    return motor_1_status

# need add the motor control codes
@app.route('/motor_2')
def motor_2():
    motor_order = request.args.get("motor_order")
    # the controlling motor codes
    return motor_order

# need add the motor control codes
@app.route('/motor_3')
def motor_3():
    motor_order = request.args.get("motor_order")
    # the controlling motor codes
    return motor_order

# need add the motor control codes
@app.route('/motor_4')
def motor_4():
    motor_order = request.args.get("motor_order")
    # the controlling motor codes
    return motor_order

# need add the motor control codes
@app.route('/motor_5')
def motor_5():
    motor_order = request.args.get("motor_order")
    # the controlling motor codes
    return motor_order

# ################### ultrasound real time ##################
@app.route('/ultrasound_1')
def ultrasound_1():
    ultrasound = hardware.ultrasound()
    distance = ultrasound.get_distance_cm()
    return str(distance)

## need to modify ##
@app.route('/ultrasound_2')
def ultrasound_2():
    ultrasound = hardware.ultrasound()
    distance = ultrasound.get_distance_cm()
    return str(distance)

## need to modify ##
@app.route('/ultrasound_3')
def ultrasound_3():
    ultrasound = hardware.ultrasound()
    distance = ultrasound.get_distance_cm()
    return str(distance)

## need to modify ##
@app.route('/ultrasound_4')
def ultrasound_4():
    ultrasound = hardware.ultrasound()
    distance = ultrasound.get_distance_cm()
    return str(distance)

## need to modify ##
@app.route('/ultrasound_5')
def ultrasound_5():
    ultrasound = hardware.ultrasound()
    distance = ultrasound.get_distance_cm()
    return str(distance)

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


def start(data_s):
	import os,sys
	from urllib.request import urlopen
	from bs4 import BeautifulSoup

	if data_s == '1':
		b = '09'
	elif data_s == '2':
		b = '08'
	elif data_s == '3':
		b = '06'
	elif data_s == '4':
		b = '11'
	elif data_s == '5':
		b = '05'
	elif data_s == '6':
		b = '07'
	elif data_s == '7':
		b = '10'
	elif data_s == '8':
		b = '17'
	elif data_s == '9':
		b = '02'
	elif data_s == '10':
		b = '01'
	elif data_s == '11':
		b = '16'
	elif data_s == '12':
		b = '15'
	elif data_s == '13':
		b = '13'
	elif data_s == '14':
		b = '12'
	elif data_s == '15':
		b = '04'
	elif data_s == '16':
		b = '03'
	elif data_s == '17':
		b = '14'

	a = data_s
## 코로나 확진자 ----------------------------------------------------------------
	html = urlopen("http://ncov.mohw.go.kr/")
	soup = BeautifulSoup(html.read(), 'html.parser')
	html.close()

	coro_name = soup.find("button",{"type":"button","data-city":"map_city"+a}).select(".name")
	coro_num =  soup.find("button",{"type":"button","data-city":"map_city"+a}).select(".num")
	coro_before =  soup.find("button",{"type":"button","data-city":"map_city"+a}).select(".before")

	temp1 = []
	for a in coro_name:
	        temp1 += a.get_text()
	coro_name = ''.join(temp1)

	temp2 = []
	for a in coro_num:
	        temp2 += a.get_text()
	coro_num = ''.join(temp2)

	temp3 = []
	for a in coro_before:
	        temp3 += a.get_text()
	coro_before = ''.join(temp3)

##미세먼지--------------------------------------------------------------------------------------

	html = urlopen("https://search.naver.com/search.naver?where=nexearch&query=%EB%AF%B8%EC%84%B8%EB%A8%BC%EC%A7%80&ie=utf8&sm=tab_she&qdt=0")
	dust_html = BeautifulSoup(html.read(), 'html.parser')
	html.close()

	dust_num = dust_html.find("div", {"class":"map_area"}).find("a", {"class":"ct"+b+" lv2 _local"}).em.string
	dust = int(dust_num)

## 초미세먼지-------------------------------------------------------------------------------------

	html = urlopen("https://search.naver.com/search.naver?where=nexearch&sm=tab_etc&query=%EC%A0%84%EA%B5%AD%EC%B4%88%EB%AF%B8%EC%84%B8%EB%A8%BC%EC%A7%80")
	ufdust = BeautifulSoup(html.read(), 'html.parser')
	html.close()

	ufdust_num = ufdust.find("div", {"class":"map_area"}).find("a", {"class":"ct"+b+" lv2 _local"}).em.string
	ufdust = int(ufdust_num)

## 출력문-----------------------------------------------------------------------------------------

	if dust>0:
		dust_state = "좋음"
	elif dust>30:
		dust_state = "보통"
	elif dust>80:
		dust_state = "나쁨"
	elif dust>150:
		dust_state = "매우 나쁨"

	if ufdust>0:
		ufdust_state = "좋음"
	elif ufdust>15:
		ufdust_state = "보통"
	elif ufdust>35:
		ufdust_state = "나쁨"
	elif ufdust>75:
		ufdust_state = "매우 나쁨"

	ak = "오늘 코로나 상황을 알려 드리겠습니다.  " + coro_name + "지역의  코로나  확진자  수 는 " + coro_num + "명 이고 어제 보다" + coro_before + "명 증가 됐습니다"
	bk = " ()() "+coro_name + "지역 미세먼지 농도 수치는 " + str(dust) + "이므로 " +dust_state + " 상태 이고 초미세먼지 농도 수치는  "+ str(ufdust) +" 이므로 "+ufdust_state+" 상태 입니다."
	fi = " 오늘 하루도 행복한 하루 되세요"
	print(ak+bk+fi)
	text = "http://translate.google.com/translate_tts?ie=UTF-8&total=1&idx=0&textlen=32&client=tw-ob&q="+ak+bk+fi+"&tl=ko-kr"
	os.system('wget -q -U Mozilla -O mp3_file.mp3 "%s"' %text)
	os.system('mplayer mp3_file.mp3')

	return 0;

import socket

me = socket.socket()
me.bind(('192.168.43.152',7895))

me.listen(5)

while True:
        conn, addr = me.accept()
        data = conn. recv(1024).decode()
        if not data :
                break
        n = data.index('\r\n\r\n')+4
        data = data[n:len(data)]
        print(data)
        func = data
        if func > '0':
                data = start(data)
                func = 0
        sdata = 'HTTP/1.1 200 OK \r\n\r\n '+str(data)
        conn.send(sdata.encode())
        conn.close()
        if data == '99' or data == 99:
                break


#!/usr/bin/env python
import cv2
from openni2_device_init import visionsensor
import numpy as np
from PIL import Image
from io import BytesIO
import time
import zlib

class VideoCamera(object):
    def __init__(self,x = 640, y = 480, fps = 30, rgb_mirror = False,
            depth_mirror = False, rgb = True, depth = True):
        self.device = visionsensor(x = x, y = y, fpd = fps, rgb_mirror = rgb_mirror,
                depth_mirror = depth_mirror, rgb = rgb, depth = depth)
        self.rgb = rgb
        self.depth = depth
        time.sleep(1)

    def __del__(self):
        self.device.stop()

    def get_frame(self, rgb_compress = 75):
        jpeg = ''
        depth = ''
        if self.rgb:
            rgb = self.device.getRgb()
            #img = Image.fromarray(rgb)
            #fpath =BytesIO()
            #img.save(fpath, quality = 75, format = "JPEG")
            #fpath.seek(0)
            encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), rgb_compress]
            ret, jpeg = cv2.imencode('.jpg', rgb, encode_param)
            jpeg = jpeg.tobytes()
        if self.depth:
            depth = zlib.compress(self.device.getDepth2Int8())
        return jpeg, depth


import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('datasets/dataset.csv')

df.columns = ["Date", "Celsius temperature", "Pressure", "Direction", "Speed"]

df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d')

df = df.dropna().reset_index(drop=True)

df['Fahrenheit temperature'] = 9/5 * df['Celsius temperature'] + 32

def describe_column(df: pd.DataFrame, parametr: str) -> pd.Series | None:
    """
    Получение статистической информации
    Args:
      df: Dataframe с исходными значениями
      parametr: имя столбца фрейма данных, для которого находится статистическое описание
    Returns:
      Ряд, содержащий статистическое описание
    """
    if parametr in df.columns:
        return df[parametr].describe()
    else:
        return None

def filter_celsius_temp(df: pd.DataFrame, celsius_temp: int) -> pd.DataFrame:
    """
    Фильтрация по столбцу температура в градусах Цельсия
    Args:
      df: Dataframe с исходными значениями
      celsius_temp: температура в градусах Цельсия
    Returns:
      Dataframe с днями, в течение которых температура не ниже заданной
    """
    return df[df["Celsius temperature"] >= celsius_temp]

def filter_by_date(df: pd.DataFrame, end_date: str, start_date: str) -> pd.DataFrame:
    """
    Фильтрация по дате
    Args:
      df: Dataframe с исходными значениями
      start_date: Дата начала
      end_date: Дата окончания
    Returns:
      Dataframe с днями в диапазоне [start_date; end_date]
    """
    start_date = pd.to_datetime(start_date, format='%Y-%m-%d')
    end_date = pd.to_datetime(end_date, format='%Y-%m-%d')
    return df[(start_date <= df["Date"]) & (df["Date"] <= end_date)]

def average_monthly_temperature(df: pd.DataFrame, parametr: str) -> pd.Series | None:
    """
    Группировка по месяцам с вычислением среднего значения температуры
    Args:
      df: Dataframe с исходными значениями
      parametr: Столбец, указывающий, какая температура берется
    Returns:
      Ряд, показывающий среднее значение за все месяцы

    """
    if parametr in ["Celsius temperature", 'Fahrenheit temperature']:
        return df.groupby(df.Date.dt.month)[parametr].mean()

def show_temperature_graph(df: pd.DataFrame, parametr: str) -> None:
    """
    Отображение графика температуры за весь период
    Args:
      df: Dataframe с исходными значениями
      parametr: Столбец, указывающий, какая температура берется

    """
    if parametr in ["Celsius temperature", 'Fahrenheit temperature']:
        fig = plt.figure(figsize=(30, 5))
        plt.ylabel(parametr)
        plt.xlabel("date")
        plt.title('Изменение температуры')
        plt.plot(df["Date"], df[parametr], color='green', linestyle='-', linewidth=2)
        plt.show()

def show_monthly_temperature_statistics(df: pd.DataFrame, month: int, year: int) -> None:
    """
    Отображение графика температуры за указанный месяц в году
    и отображение медианы и средних значений
    Args:
      df: Dataframe с исходными значениями
      month: Месяц, для которого строится график температуры
      year: Год, для которого строится график температуры

    """
    month_df = df[(df.Date.dt.month == month) & (df.Date.dt.year == year)]
    fig = plt.figure(figsize=(30, 5))

    fig.add_subplot(1, 3, 1)
    plt.ylabel("Celsius temperature")
    plt.xlabel("Date")
    plt.plot(month_df.Date.dt.day, month_df["Celsius temperature"],
             color='green', linestyle='-', linewidth=2, label='Celsius temperature')
    plt.axhline(y=month_df["Celsius temperature"].mean(), color='yellow', label="Average value")
    plt.axhline(y=month_df["Celsius temperature"].median(), color='blue', label="Median")
    plt.legend(loc=2, prop={'size': 10})

    fig.add_subplot(1, 3, 2)
    plt.ylabel("Fahrenheit temperature")
    plt.xlabel("Date")
    plt.plot(month_df.Date.dt.day, month_df["Fahrenheit temperature"],
             color='red', linestyle='--', linewidth=2, label='Fahrenheit temperature')
    plt.axhline(y=month_df["Fahrenheit temperature"].mean(), color='yellow', label="Average value")
    plt.axhline(y=month_df["Fahrenheit temperature"].median(), color='blue', label="Median")
    plt.legend(loc=2, prop={'size': 10})

    plt.show()

if __name__ == "__main__":
    filtered_temp_df = filter_celsius_temp(df, 25)
    filtered_date_df = filter_by_date(df, '2023-01-01', '2023-12-31')
    show_monthly_temperature_statistics(df, 1, 2023)


num=input()
n=int(num)
cycle=0
while True:
  a=n//10
  b=n%10
  c=(a+b)%10
  n=(b*10)+c

  cycle+=1
  if(int(num)==n):
    break
print(cycle)


import logging
import urllib2

from google.appengine.api import users
from google.appengine.ext.ndb import Cursor

import webapp2

from webapp2_extras import auth, sessions, jinja2
from webapp2_extras.routes import RedirectRoute

from agar.auth import authentication_required
from agar.env import on_production_server

from config import coal_config
from filters import FILTERS
from models import User, Server, Player, LogLine, PlaySession

def uri_for_pagination(name, cursor=None):
    uri = webapp2.uri_for(name)
    if cursor is not None and cursor != 'START':
        uri = "{0}?cursor={1}".format(uri, cursor)
    return uri

class JinjaHandler(webapp2.RequestHandler):
    _filters = FILTERS
    _globals = {
        'uri_for': webapp2.uri_for,
        'uri_for_pagination': uri_for_pagination
    }

    @webapp2.cached_property
    def jinja2(self):
        return jinja2.get_jinja2(factory=self.jinja2_factory)

    def jinja2_factory(self, app):
        j = jinja2.Jinja2(app)
        j.environment.filters.update(self._filters)
        j.environment.globals.update(self._globals)
        return j

    def get_template_context(self, context=None):
        return context

    def render_template(self, filename, context={}):
        context = self.get_template_context(context)
        self.response.write(self.jinja2.render_template(filename, **context))

def get_callback_url(handler, next_url=None):
    if next_url is None:
        next_url = handler.request.path_qs
    callback_url = handler.uri_for('login_callback')
    if next_url:
        callback_url = "{0}?next_url={1}".format(callback_url, urllib2.quote(next_url))
    return callback_url

def get_login_url(handler, next_url=None):
    callback_url = get_callback_url(handler, next_url=next_url)
    if users.get_current_user() is None:
        return users.create_login_url(callback_url)
    return callback_url

def authenticate(handler, required=True, admin=False):
    user_dict = handler.auth.get_user_by_session()
    if not user_dict:
        user = None
    else:
        user = handler.auth.store.user_model.get_by_id(user_dict['user_id'])
    if user is not None:
        allowed = None
        for wlu in coal_config.USER_WHITELIST:
            if user.email == wlu['email']:
                allowed = wlu
                update = False
                if not user.active:
                    user.active = True
                    update = True
                if user.admin != allowed['admin']:
                    user.admin = allowed['admin']
                    update = True
                if user.username != allowed['username']:
                    user.username = allowed['username']
                    update = True
                if update:
                    user.put()
        if not allowed:
            user.active = False
            user.put()
            user = None
    if required and not user:
        handler.redirect(get_login_url(handler), abort=True)
    if admin and not user.admin:
        handler.redirect('/', abort=True)
    return user

class UserAwareHandler(JinjaHandler):
    @webapp2.cached_property
    def session_store(self):
        return sessions.get_store(request=self.request)

    @webapp2.cached_property
    def session(self):
        return self.session_store.get_session(backend="datastore")

    @webapp2.cached_property
    def auth(self):
        return auth.get_auth(request=self.request)

    @webapp2.cached_property
    def user_info(self):
        user_info = self.auth.get_user_by_session()
        return user_info

    @webapp2.cached_property
    def user(self):
        user = self.auth.store.user_model.get_by_id(self.user_info['user_id']) if self.user_info else None
        return user

    def logged_in(self):
        return self.auth.get_user_by_session() is not None

    def logout(self, redirect_url=None):
        redirect_url = redirect_url or '/'
        self.auth.unset_session()
        logout_url = users.create_logout_url(redirect_url)
        self.redirect(logout_url)

    def dispatch(self):
        try:
            super(UserAwareHandler, self).dispatch()
        finally:
            self.session_store.save_sessions(self.response)

    def get_template_context(self, context=None):
        template_context = dict()
        if context:
            template_context.update(context)
        template_context['flashes'] = self.session.get_flashes()
        template_context['request'] = self.request
        template_context['user'] = self.user
        template_context['config'] = coal_config
        template_context['server'] = Server.global_key().get()
        return template_context

class GoogleAppEngineUserAuthHandler(UserAwareHandler):
    def login_callback(self):
        next_url = self.request.params.get('next_url', '')
        gae_user = users.get_current_user()
        if not gae_user:
            self.redirect(get_login_url(self, next_url=next_url), abort=True)
        auth_id = User.get_gae_user_auth_id(gae_user=gae_user)
        user = self.auth.store.user_model.get_by_auth_id(auth_id)
        if user:
            # existing user. just log them in.
            self.auth.set_session(self.auth.store.user_to_dict(user))
            # update access for gae admins
            if users.is_current_user_admin():
                if not (user.active and user.admin):
                    user.admin = True
                    user.put()
        else:
            # check whether there's a user currently logged in
            # then, create a new user if no one is signed in,
            # otherwise add this auth_id to currently logged in user.
            if self.logged_in and self.user:
                u = self.user
                u.auth_ids.append(auth_id)
                u.populate(email=gae_user.email(), nickname=gae_user.nickname())
                if users.is_current_user_admin():
                    u.admin = True
                u.put()
            else:
                ok, user = self.auth.store.user_model.create_user(
                    auth_id,
                    email=gae_user.email(),
                    nickname=gae_user.nickname(),
                    admin=users.is_current_user_admin()
                )
                if ok:
                    self.auth.set_session(self.auth.store.user_to_dict(user))
                else:
                    logging.debug('create_user() returned False with strings: %s' % user)
                    user = None
                    self.auth.unset_session()
        if not (user and user.active):
            next_url = '/'
        self.redirect(next_url or '/')

class BaseHander(UserAwareHandler):
    def head(self, *args):
        """Head is used by Twitter. If not there the tweet button shows 0"""
        pass

class HomeHandler(BaseHander):
    @authentication_required(authenticate=authenticate)
    def get(self):
        open_sessions_query = PlaySession.query_latest_open()
        # Get open sessions
        playing_usernames = []
        open_sessions = []
        for open_session in open_sessions_query:
            if open_session.username and open_session.username not in playing_usernames:
                playing_usernames.append(open_session.username)
                open_sessions.append(open_session)
        # Get new chats
        new_chats_query = LogLine.query_latest_chats()
        last_chat_view = self.request.user.last_chat_view
        if last_chat_view is not None:
            new_chats_query = new_chats_query.filter(LogLine.timestamp > last_chat_view)
        new_chats, chats_cursor, more = new_chats_query.fetch_page(20)
        if new_chats:
            self.request.user.record_chat_view(new_chats[0].timestamp)
        # Render with context
        context = {'open_sessions': open_sessions, 'new_chats': new_chats, 'chats_cursor': chats_cursor}
        self.render_template('home.html', context=context)

class PagingHandler(BaseHander):
    def get_results_with_cursors(self, query, reverse_query, size):
        cursor = self.request.get('cursor', None)
        if cursor:
            try:
                cursor = Cursor.from_websafe_string(cursor)
            except:
                cursor = None
        next_cursor = previous_cursor = None
        if cursor is not None:
            reverse_cursor = cursor.reversed()
            reverse_results, reverse_next_cursor, reverse_more = reverse_query.fetch_page(
                size, start_cursor=reverse_cursor
            )
            if reverse_more:
                previous_cursor = reverse_next_cursor.reversed()
                previous_cursor = previous_cursor.to_websafe_string()
            else:
                previous_cursor = 'START'
        results, next_cursor, more = query.fetch_page(size, start_cursor=cursor)
        if more:
            next_cursor = next_cursor.to_websafe_string()
        else:
            next_cursor = None
        return results, previous_cursor, next_cursor

class ChatsHandler(PagingHandler):
    @authentication_required(authenticate=authenticate)
    def get(self):
        self.request.user.record_chat_view()
        results, previous_cursor, next_cursor = self.get_results_with_cursors(
            LogLine.query_latest_chats(), LogLine.query_oldest_chats(), coal_config.RESULTS_PER_PAGE
        )
        if results:
            self.request.user.record_chat_view(results[0].timestamp)
        context = {'chats': results, 'previous_cursor': previous_cursor, 'next_cursor': next_cursor}
        self.render_template('chats.html', context=context)

class PlayersHandler(PagingHandler):
    @authentication_required(authenticate=authenticate)
    def get(self):
        results, previous_cursor, next_cursor = self.get_results_with_cursors(
            Player.query_all_reverse(), Player.query_all(), coal_config.RESULTS_PER_PAGE
        )
        context = {'players': results, 'previous_cursor': previous_cursor, 'next_cursor': next_cursor}
        self.render_template('players.html', context=context)

class PlaySessionsHandler(PagingHandler):
    @authentication_required(authenticate=authenticate)
    def get(self):
        results, previous_cursor, next_cursor = self.get_results_with_cursors(
            PlaySession.query_latest(), PlaySession.query_oldest(), coal_config.RESULTS_PER_PAGE
        )
        context = {'play_sessions': results, 'previous_cursor': previous_cursor, 'next_cursor': next_cursor}
        self.render_template('play_sessions.html', context=context)

application = webapp2.WSGIApplication(
    [
        RedirectRoute('/login_callback', handler='main.GoogleAppEngineUserAuthHandler:login_callback', name='login_callback'),
        RedirectRoute('/logout', handler='main.GoogleAppEngineUserAuthHandler:logout', name='logout'),
        RedirectRoute('/', handler=HomeHandler, name="home"),
        RedirectRoute('/chats', handler=ChatsHandler, strict_slash=True, name="chats"),
        RedirectRoute('/players', handler=PlayersHandler, strict_slash=True, name="players"),
        RedirectRoute('/sessions', handler=PlaySessionsHandler, strict_slash=True, name="play_sessions")
    ],
    config={
        'webapp2_extras.sessions': {'secret_key': coal_config.SECRET_KEY},
        'webapp2_extras.auth': {'user_model': 'models.User'}
    },
    debug=not on_production_server
)


# -*- coding: utf-8 -*-
import sys
# 这里我们提供必要的引用。基本控件位于pyqt5.qtwidgets模块中。
from PyQt5.QtWidgets import QWidget, QFileSystemModel, QTreeView, QVBoxLayout, \
    QApplication,QMenu, QMessageBox, QInputDialog
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QDir, Qt

class FileWidget(QWidget):
    def __init__(self):
        super().__init__()
        # QWidget部件是PyQt5所有用户界面对象的基类。他为QWidget提供默认构造函数。默认构造函数没有父类。
        # 创建一个文件系统模型
        self.file_model = QFileSystemModel()
        # 设置目录为当前工作目录
        self.file_model.setRootPath(QDir.currentPath())
        # 创建树视图，构建文件目录视图
        self.treeview = QTreeView()
        # 绑定此文件模型
        self.treeview.setModel(self.file_model)
        '''
        设置当前勾结点索引为当前工作目录
        如果想从整个文件系统根节点开始浏览视图，
        简单删掉此行即可
        '''
        self.treeview.setRootIndex(self.file_model.index(QDir.currentPath()))
        # 头部显示排序戳
        self.treeview.header().setSortIndicatorShown(True)

        # 创建右键菜单
        self.treeview.setContextMenuPolicy(Qt.CustomContextMenu)
        # point = self.treeview.pos()
        self.treeview.customContextMenuRequested.connect(self.generateMenu)

        '''
        # 底部按钮布局
        self.mkdirButton = QPushButton("Make Directory...")
        self.rmButton = QPushButton("Remove")
        buttonLayout = QHBoxLayout()
        buttonLayout.addWidget(self.mkdirButton)
        buttonLayout.addWidget(self.rmButton)
        '''
        # 文件管理界面布局
        layout = QVBoxLayout()
        layout.addWidget(self.treeview)
        # layout.addLayout(buttonLayout)

        # resize()方法调整窗口的大小。600px宽300px高
        self.resize(600, 300)
        # move()方法移动窗口在屏幕上的位置到x = 300，y = 300坐标。
        self.move(300, 300)
        # 设置窗口的标题
        self.setWindowTitle('File Manage')
        # 设置窗口的图标
        self.setWindowIcon(QIcon('File-Explorer.png'))
        self.setLayout(layout)

    # 生成右键菜单
    def generateMenu(self, position):
        # 索引默认值
        row_num = -1
        # 遍历确定行号
        for i in self.treeview.selectionModel().selection().indexes():
            row_num = i.row()
        # 保证选中有效项
        if row_num != -1:
            # 创建右键菜单
            menu = QMenu()
            # 提供删除和创建文件/文件夹选项
            item1 = menu.addAction("Delete")
            item2 = menu.addAction("NewDirectory")
            # 在光标处显示执行菜单
            action = menu.exec_(self.treeview.mapToGlobal(position))
            if action == item1:
                #弹出消息框确认此次删除操作
                res = self.msgbox()
                if res:
                    self.delete()
                else:
                    return
            elif action == item2:
                self.mkdirectory()
            else:
                return
        else:
            return

    # 删除选定文件/文件夹
    def delete(self):
        index = self.treeview.currentIndex()
        if index.isValid():
            fileInfo = self.file_model.fileInfo(index)
            if fileInfo.isDir():
                self.file_model.rmdir(index)
            else:
                self.file_model.remove(index)

    # 确认框
    def msgbox(self):
        msgBox = QMessageBox()
        msgBox.setWindowTitle("Warning")
        msgBox.setText("Delete the file/dir you selected?")
        msgBox.setStandardButtons(QMessageBox.Yes
                                  | QMessageBox.No)
        msgBox.setDefaultButton(QMessageBox.No)
        # button = QMessageBox.question("Warning", "delete the file/dir?",
        #                               QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        button = msgBox.exec_()
        if button == QMessageBox.No:
            return False
        elif button == QMessageBox.Yes:
            return True

    # 创建文件夹
    def mkdirectory(self):
        index = self.treeview.rootIndex()
        if index.isValid():
            # 弹出输入框录入文件名
            dirname,ok = QInputDialog.getText(self,"File Name","Input an unique dir name:")
            if ok:
                self.file_model.mkdir(index, dirname)
            else:
                return

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_F3:
            self.close()

if __name__ == '__main__':
    # 每一PyQt5应用程序必须创建一个应用程序对象。sys.argv参数是一个列表，从命令行输入参数。
    app = QApplication(sys.argv)
    # QWidget部件是PyQt5所有用户界面对象的基类。他为QWidget提供默认构造函数。默认构造函数没有父类。
    widget = FileWidget()
    widget.show()
    sys.exit(app.exec_())


#!/usr/bin/env python3

import sys
import numpy as np

def LargestSquareOfOnes(mat):
  mat     = mat.copy()
  bestval = -1
  bestloc = None
  for y in range(data.shape[0]-2,-1,-1):
    for x in range(data.shape[1]-2,-1,-1):
      if mat[y,x]>0:
        mat[y,x] = min(mat[y+1,x],mat[y,x+1],mat[y+1,x+1])+1
        if mat[y,x]>bestval:
          bestval = mat[y,x]
          bestloc = (y,x)
  return bestval,bestloc

if len(sys.argv)!=3:
  print("{0} <prefix/onlydim> <LAYOUT FILE>".format(sys.argv[0]))
  print("\tprefix  = Prefix for layout files")
  print("\tonlydim = Only output the largest square dimension")
  sys.exit(-1)

data = open(sys.argv[2],'r').readlines()

#a = "ned/ned_tiles.layout"
#data  = open(a,'r').readlines()

#data = np.random.rand(10,10)
#data = (data>0.3).astype(np.int)

data  = [x.strip().split(',') for x in data]
fgrid = data.copy()
data  = [ [1 if len(x.strip())>0 else 0 for x in line] for line in data]
data  = np.array(data)

bestval, bestloc = LargestSquareOfOnes(data)

if sys.argv[1]=="onlydim":
  print("{0:43} {1}".format(sys.argv[2],bestval))
else:
  for size in range(1,bestval+1):
    with open(sys.argv[1]+str(size)+".layout",'w') as fout:
      for y in range(bestloc[0],bestloc[0]+size):
        fout.write(','.join(fgrid[y][bestloc[1]:bestloc[1]+size])+"\n")


"""
# My first app
Here's our first attempt at using data to create a table:
"""

import streamlit as st
import pandas as pd
from prediction import prediction

DATASET_FILE = "./cleaned_dataset.csv"
dataset_df = pd.read_csv(DATASET_FILE)

n = st.slider('Number of topics to show', 1, 15)

text = st.text_input('Review', 'Type here...')

if st.button('Predict'):
    topics = prediction(text, n)

    if type(topics) is str:
        st.write(topics)
    else:
        for i, topic in enumerate(topics):
            st.write(f"{i + 1} : {topic}")


from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from db_config import db_url

app = Flask(__name__)
app.jinja_env.variable_start_string = '%%'
app.jinja_env.variable_end_string = '%%'
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
app.config['SQLALCHEMY_DATABASE_URI'] = db_url
# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://账号:密码@url:端口/数据库名'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['ALLOW_FILE'] = ['jpg', 'jpeg', 'gif', 'png', 'bmp']
db = SQLAlchemy(app)


import os
import glob
import csv
import sys
import numpy as np
import pandas as pd
from natsort import natsorted
import matplotlib.pyplot as plt
import matplotlib
# matplotlib.use('Agg')

directory = 'binary/20210303/unet_rgb_otsu_loop'
guide = 'RGB'
title = 'U-Net(RGB+Otsu)loop'
csv_name = 'eva_all.csv'
plot_label = ['train_accuracy', 'test_accuracy', 'validation_accuracy']
epoch = 120
nas_path = 'Z:/hayakawa/'
out_dir = 'binary/20210303/plot'
total_ave_list = np.zeros([len(plot_label), epoch])
csv_files = glob.glob(nas_path + directory + '/*/CsvDatas/' + csv_name)
if not csv_files:
    print(nas_path + '/*/CsvDatas/' + csv_name)
    print('no file')
    sys.exit()
csv_files = natsorted(csv_files)
os.makedirs(nas_path + out_dir, exist_ok=True)
ave_list = np.zeros([len(plot_label), len(csv_files), epoch])  # ラベル数, ds数, ステップ数
for ds_index in range(len(csv_files)):  # ds単位
    print(csv_files[ds_index])
    ds_name = os.path.dirname(os.path.dirname(csv_files[ds_index]))[-1]
    df = pd.read_csv(csv_files[ds_index])
    for label_index in range(len(plot_label)):  # ラベル単位
        ave_list[label_index, ds_index, :] = df[plot_label[label_index]].values[:epoch]
for label_index in range(len(plot_label)):  # ラベル単位
    total_ave_list[label_index, :] = np.mean(ave_list[label_index, :, :], axis=0)

outpath = nas_path + out_dir + '/' + title + '.png'
x = list(range(1, epoch + 1))
for label_index in range(len(plot_label)):  # ラベル単位
    plt.plot(x, total_ave_list[label_index, :], label=plot_label[label_index])
plt.xlabel("Evaluation step")
plt.ylabel("Accuracy")
plt.title(title + ' 6 dataset average')
plt.ylim([0.97, 1])
plt.xlim([0, epoch + 1])
loc = ['train', 'test', 'validation']
plt.legend(title="accuracy", loc='lower right')
# plt.legend(title="name", loc=loc)
plt.savefig(outpath)
plt.show()


from monitoring_system.drivers.sensors.Sensor import Sensor

class DigitalReadSensor(Sensor):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.pin = self._get_wpi_pin(self.pin)
        self._register_pins([self.pin], [])

    def get_measurements(self):
        return {
            'digital': self._digital_read(self.pin)
        }


#Random range numbers.
from random import randrange

#OpenCV library.
import cv2

#Load pre-trained frontalface data.
trained_face_data=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

'''

#This one is for random or many images.

#Choose any image.
random_image=cv2.imread('iAm.jpg')

#Covert to greyscale.
greyscale_image=cv2.cvtColor(random_image,cv2.COLOR_BGR2GRAY)

#Detect faces.
face_directions=trained_face_data.detectMultiScale(greyscale_image)

#Wrap faces with rectangles.
for(x,y,w,h) in face_directions:
    cv2.rectangle(random_image,(x,y),(x+w,y+h),(0,randrange(129,256),0),2)

#Shows the image with faces.
cv2.imshow('face detector app',random_image)

#Apply this so that everything work.
cv2.waitKey()

'''

# '''

#Live video capture.
live_webcam_video=cv2.VideoCapture(0)

#loop forever over frames.
while True:

    #read the current frame.
    successful_frame_read,frame=live_webcam_video.read()

    #Convert to greyscale.
    greyscale_webcam=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

    #Detect faces.
    face_directions=trained_face_data.detectMultiScale(greyscale_webcam)

    #Wrap faces with rectangles.
    for(x,y,w,h) in face_directions:
        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,randrange(129,256),0),2)

    #Shows the image with faces.
    cv2.imshow('Face Detector App (Press Q to quit!)',frame)

    #Apply this so that everything work.
    key=cv2.waitKey(1)

    #Press Q or q to quit.
    if key==81 or key==113:
        break

#Release the VideoCapture object.
live_webcam_video.release()

#Everything worked perfectly.
print('Code Completed!')

# '''


from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
import pandas as pd

driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))

quotes_no = int(input("How many quotes do you wish to scrape?\n-> "))

while quotes_no > 90:
    quotes_no = int(input("Quotes requested for is greater than the available amounts of quotes existing\n"
                          "Total quotes is 90\nHow many quotes do you wish to scrape?\n-> "))

driver.get("http://quotes.toscrape.com/")
title = driver.title

print(title)

quotes = []
author = []
dateOfBirth = []
description = []
location = []

c_p = 1
while c_p != quotes_no:
    for i in driver.find_elements(By.CLASS_NAME, 'text'):
        quotes.append(i.text)
    for i in driver.find_elements(By.LINK_TEXT, '(about)'):
        i.click()
        auth = driver.find_element(By.CLASS_NAME, 'author-title').text
        author.append(auth)
        dob = driver.find_element(By.CLASS_NAME, 'author-born-date').text
        dateOfBirth.append(dob)
        locatn = driver.find_element(By.CLASS_NAME, 'author-born-location').text
        location.append(locatn[3:])
        desc = driver.find_element(By.CLASS_NAME, 'author-description').text
        description.append(desc)
        driver.back()
    driver.find_element(By.PARTIAL_LINK_TEXT, 'Next ').click()
    if c_p == quotes_no:
        break
    c_p += 1

driver.close()

data = {
    'Author': author,
    "DateOfBirth": dateOfBirth,
    "Location": location,
    "Quotes": quotes,
    "Description": description
}

quotesToScrape = pd.DataFrame(data)

print(data)

name_file = input("\nPlease note enter just the filename without the file extension\nEnter a preferred file name:\n-> ")

name_of_file = str(name_file + ".csv")

quotesToScrape.to_csv(name_of_file, index=False)


from .UserAgent import UserAgent

import pprint

class CmdIssue:
    def __init__(self, config_obj):
        self.issue_endpoint = config_obj.base_url + '/issues'
        self.pp = pprint.PrettyPrinter(indent=4)
        self.ua = UserAgent()

    def view(self, issue_id):
        # view the detail of a chosen pull request
        endpoint = self.issue_endpoint + '/' + str(issue_id)

        issue = self.ua.get(endpoint)

        print("Title: {}".format(issue['title']))
        print("ID: {}".format(issue['id']))
        print("Assigned to {}".format(issue['assignee']))
        print("Summary:\n\t{}".format(issue['content']['raw']))
        return 1

    def create(self, details={}):
        data = {
            "title": details['title'],
            "content": {
                "raw": details['content']
            }
        }

        new_issue = self.ua.post(self.issue_endpoint, data)
        print("New issue (ID={}) is created ({})".format(new_issue['id'], new_issue['links']['self']['href']))

        return 1

    def status(self, issue_id):
        endpoint = self.issue_endpoint + '/' + str(issue_id)

        issue = self.ua.get(endpoint)

        print("Title: {}".format(issue['title']))
        print("Status: {}, Type: {}, Priority: {}".format(issue['state'], issue['kind'], issue['priority']))
        return 1

    def close(self, issue_id, status="closed"):
        endpoint = self.issue_endpoint + '/' + str(issue_id) + '/changes'
        data = {
            "changes": {
                "state": { "new": status }
            }
        }
        self.ua.post(endpoint, data)
        print("Issue (ID={}) is {}".format(str(issue_id), status))
        return 1

    def list(self, id):
        # list all issue
        issues = self.ua.get(self.issue_endpoint)

        for issue in issues['values']:
            if issue['state'] == 'closed':
                continue
            print("Title: {}".format(issue['title']))
            print("ID: {}".format(issue['id']))
            print("Assigned to {}".format(issue['assignee']))
            print("Summary:\n\t{}\n".format(issue['content']['raw']))
        return 1


import torch
from torch.autograd import Variable
import numpy as np

def bbox_transform(ex_rois, gt_rois):
    ex_widths = ex_rois[:, 2] - ex_rois[:, 0] + 1.0
    ex_heights = ex_rois[:, 3] - ex_rois[:, 1] + 1.0
    ex_ctr_x = ex_rois[:, 0] + 0.5 * ex_widths
    ex_ctr_y = ex_rois[:, 1] + 0.5 * ex_heights

    gt_widths = gt_rois[:, 2] - gt_rois[:, 0] + 1.0
    gt_heights = gt_rois[:, 3] - gt_rois[:, 1] + 1.0
    gt_ctr_x = gt_rois[:, 0] + 0.5 * gt_widths
    gt_ctr_y = gt_rois[:, 1] + 0.5 * gt_heights

    targets_dx = (gt_ctr_x - ex_ctr_x) / ex_widths
    targets_dy = (gt_ctr_y - ex_ctr_y) / ex_heights
    targets_dw = np.log(gt_widths / ex_widths)
    targets_dh = np.log(gt_heights / ex_heights)

    targets = np.vstack(
        (targets_dx, targets_dy, targets_dw, targets_dh)).transpose()
    return targets

def bbox_transform_inv(boxes, deltas):
    if boxes.shape[0] == 0:
        return np.zeros((0, deltas.shape[1]), dtype=deltas.dtype)

    boxes = boxes.astype(deltas.dtype, copy=False)

    widths = boxes[:, 2] - boxes[:, 0] + 1.0
    heights = boxes[:, 3] - boxes[:, 1] + 1.0
    ctr_x = boxes[:, 0] + 0.5 * widths
    ctr_y = boxes[:, 1] + 0.5 * heights

    dx = deltas[:, 0::4]
    dy = deltas[:, 1::4]
    dw = deltas[:, 2::4]
    dh = deltas[:, 3::4]

    pred_ctr_x = dx * widths[:, np.newaxis] + ctr_x[:, np.newaxis]
    pred_ctr_y = dy * heights[:, np.newaxis] + ctr_y[:, np.newaxis]
    pred_w = np.exp(dw) * widths[:, np.newaxis]
    pred_h = np.exp(dh) * heights[:, np.newaxis]

    pred_boxes = np.zeros(deltas.shape, dtype=deltas.dtype)
    # x1
    pred_boxes[:, 0::4] = pred_ctr_x - 0.5 * pred_w
    # y1
    pred_boxes[:, 1::4] = pred_ctr_y - 0.5 * pred_h
    # x2
    pred_boxes[:, 2::4] = pred_ctr_x + 0.5 * pred_w
    # y2
    pred_boxes[:, 3::4] = pred_ctr_y + 0.5 * pred_h

    return pred_boxes

def clip_boxes(boxes, im_shape):
    """
    Clip boxes to image boundaries.
    """

    # x1 >= 0
    boxes[:, 0::4] = np.maximum(np.minimum(boxes[:, 0::4], im_shape[1] - 1), 0)
    # y1 >= 0
    boxes[:, 1::4] = np.maximum(np.minimum(boxes[:, 1::4], im_shape[0] - 1), 0)
    # x2 < im_shape[1]
    boxes[:, 2::4] = np.maximum(np.minimum(boxes[:, 2::4], im_shape[1] - 1), 0)
    # y2 < im_shape[0]
    boxes[:, 3::4] = np.maximum(np.minimum(boxes[:, 3::4], im_shape[0] - 1), 0)
    return boxes

def filter_boxes(boxes, min_size):
    """Remove all boxes with any side smaller than min_size.
    """
    ws = boxes[:, 2] - boxes[:, 0] + 1
    hs = boxes[:, 3] - boxes[:, 1] + 1
    keep = np.where((ws >= min_size) & (hs >= min_size))[0]
    return keep

# torch tensors
def bbox_overlaps(a, bb): # (anchors, gt_boxes)
    if isinstance(a, np.ndarray):
        a = torch.from_numpy(a)
    if isinstance(bb, np.ndarray):
        bb = torch.from_numpy(bb)

    oo = []
    for b in bb:
        x1 = a.select(1, 0).clone()
        x1[x1.lt(b[0])] = b[0]
        y1 = a.select(1, 1).clone()
        y1[y1.lt(b[1])] = b[1]
        x2 = a.select(1, 2).clone()
        x2[x2.gt(b[2])] = b[2]
        y2 = a.select(1, 3).clone()
        y2[y2.gt(b[3])] = b[3]

        w = x2 - x1 + 1
        h = y2 - y1 + 1
        inter = torch.mul(w, h).float()
        aarea = torch.mul((a.select(1, 2) - a.select(1, 0) + 1),
                          (a.select(1, 3) - a.select(1, 1) + 1)).float()
        barea = (b[2] - b[0] + 1) * (b[3] - b[1] + 1)

        # intersection over union overlap
        o = torch.div(inter, (aarea + barea - inter))
        # set invalid entries to 0 overlap
        o[w.lt(0)] = 0
        o[h.lt(0)] = 0
        oo += [o]
    return torch.cat([o.view(-1, 1) for o in oo], 1)

def to_var(x):
    if isinstance(x, np.ndarray):
        return Variable(torch.from_numpy(x), requires_grad=False)
    elif torch.is_tensor(x):
        return Variable(x, requires_grad=True)
    elif isinstance(x, tuple):
        t = []
        for i in x:
            t.append(to_var(i))
        return t
    elif isinstance(x, Variable):
        return x

class AverageMeter(object):
    """Computes and stores the average and current value"""
    def __init__(self):
        self.reset()

    def reset(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count


import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from math import sqrt, log

def calculate_k(x, y, through_zero=False):
    '''
    Вычисление коэффициентов для аппроксимации зависимостью y = kx + b
    '''
    n = len(x)
    m_x = x.mean()
    m_y = y.mean()
    m_xx = (x * x). mean()
    m_yy = (y * y).mean()
    m_xy = (x * y).mean()
    m_x_m_x = x.mean() * x.mean()
    m_y_m_y = y.mean() * y.mean()

    k = 0
    s_k = 0
    b = 0
    s_b = 0

    if through_zero:
        k = m_xy / m_xx
        s_k = (1 / sqrt(n)) * sqrt((m_yy / m_xx) - k ** 2)
        return [k, s_k]

    else:
        k = (m_xy - m_x * m_y) / (m_xx - m_x_m_x)
        b = m_y - k * m_x

        s_k = (1 / sqrt(n)) * sqrt((m_yy - m_y_m_y) / (m_xx - m_x_m_x) - k ** 2)
        s_b = s_k * sqrt(m_xx - m_x_m_x)
        return [k, s_k, b, s_b]

dfturb1 = pd.read_csv('/home/alphonse/ML_learning/graphs/one33/logplogq1.csv')

lnq1 = (dfturb1.copy().q).map(lambda x: log(x / 100000))
lnp1 = (dfturb1.p).map(lambda x: log(x / 1000))

print(calculate_k(lnp1, lnq1))

x = np.arange(-1.8, -0.6, 0.01)
plt.scatter(lnp1, lnq1)
plt.plot(x, calculate_k(lnp1, lnq1)[0] * x + calculate_k(lnp1, lnq1)[2], label='Первая трубка')

dfturb2 = pd.read_csv('/home/alphonse/ML_learning/graphs/one33/logplogq2.csv')

lnq2 = (dfturb2.copy().q).map(lambda x: log(x / 100000))
lnp2 = (dfturb2.p).map(lambda x: log(x / 1000))

print(calculate_k(lnp2, lnq2))

x = np.arange(-1.8, -0.6, 0.01)
plt.scatter(lnp2, lnq2)
plt.plot(x, calculate_k(lnp2, lnq2)[0] * x + calculate_k(lnp2, lnq2)[2], label='Вторая трубка')

dfturb3 = pd.read_csv('/home/alphonse/ML_learning/graphs/one33/logplogq3.csv')

lnq3 = (dfturb3.copy().q).map(lambda x: log(x / 100000))
lnp3 = (dfturb3.p).map(lambda x: log(x / 1000))

print(calculate_k(lnp3, lnq3))

x = np.arange(-1.8, -0.6, 0.01)
plt.scatter(lnp3, lnq3)
plt.plot(x, calculate_k(lnp3, lnq3)[0] * x + calculate_k(lnp3, lnq3)[2], label='Третья трубка')

plt.xlabel(r'$\ln \Delta P$', fontsize=14)
plt.ylabel(r'$\ln Q$', fontsize=14)
plt.legend(loc='best', fontsize=14)

plt.show()


'''
    작성일: 2023년 10월 4일
    작성자: 컴퓨터공학과 202395022 윤진환
    설명: 반복을 제어하는 break, continue
         교재 137페이지

    Test word: Programming
    Pr
'''

word = input("단어를 입력하세요")

print("::break1::")
for i in word: #i에 word의 한 문자씩 입력
    if i=="a" or i == "e" or i =="i" or i == "o"  or i == "u": #만약 i의 값이 aeiou중 하나라면 반복 정지
        break #포함된 반복이 종료된다.
    else: #아니면 줄바꿈 없이 출력
        print(i,end='')

print()

print("::break2::")
for i in word: #i에 word의 한 문자씩 입력
    if i in ["a",'e','i','o','u','A','E','I','O','U']: #만약 i의 값이 aeiou중 하나라면 반복 정지
        break #포함된 반복이 종료된다.
    else: #아니면 줄바꿈 없이 출력
        print(i,end='')

print()

print("::continue::")
for i in word: #i에 word의 한 문자씩 입력
    if i in ["a",'e','i','o','u','A','E','I','O','U']:
        continue #반복문 처음으로 돌아가라 => 반복할 문장을 어느정도 조정하기 위해 사용

    print(i,end='') #continue아래에 있으므로 모음은 출력하지 않는다


from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import gettext_lazy as _

from . import models, forms
from .forms import AuthenticationForm

admin.site.login_form = AuthenticationForm

# Register your models here.
@admin.register(models.User)
class UserAdmin(UserAdmin):
    add_form = forms.CreateUserForm
    add_form_template = 'admin/accounts/user/add_form.html'
    list_display = (
        'uuid', 'email', 'first_name', 'last_name', 'is_staff', 'date_joined',
    )
    search_fields = (
        'uuid', 'email', 'first_name', 'last_name',
    )
    ordering = ('-date_joined',)
    readonly_fields = ('uuid', 'last_login', 'date_joined',)

    fieldsets = (
        (None, {'fields': ('uuid', 'email', 'password')}),
        (_('Personal info'), {'fields': ('first_name', 'last_name',)}),
        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                       'groups', 'user_permissions')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('first_name', 'last_name'),
        }),
    )


# Definition for a binary tree node.
class TreeNode(object):
     def __init__(self, val=0, left=None, right=None):
            self.val = val
            self.left = left
            self.right = right
class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        ### solving using BFS
        if root==None: return 0
        depth=0

        queue=[root]

        while len(queue)!=0:
            depth+=1

            for i in range(len(queue)):
                curr=queue.pop(0)
                if curr.left!=None: queue.append(curr.left)
                if curr.right!=None: queue.append(curr.right)

        return depth

### complexity analysis
## time complexity O(n)
## space complexity O(n) with n=number of nodes


import requests
from xml.etree import ElementTree as ET
import sys
from concurrent.futures import ThreadPoolExecutor

def check_url(url):
    if not url or "://" not in url:
        print(f"Skipping invalid URL: {url}")
        return True  # or False, depending on how you want to handle this case

    try:
        response = requests.head(url, allow_redirects=True)
        if response.headers.get('Content-Type') == 'application/xml':
            response = requests.get(url)
            if "AccessDenied" in response.text:
                return False
    except Exception as e:
        print(f"Error checking URL {url}: {e}")
    return True

def check_urls(urls):
    with ThreadPoolExecutor() as executor:
        results = list(executor.map(check_url, urls))
    return results

def main(feed_url):
    response = requests.get(feed_url)
    root = ET.fromstring(response.content)

    urls_to_check = [element.get('url') for element in root.findall(".//*[@url]")]
    results = check_urls(urls_to_check)
    non_downloadable_urls = [url for url, result in zip(urls_to_check, results) if not result]

    print("URLs with Access Denied:")
    for url in non_downloadable_urls:
        print(url)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python checkmrss.py <MRSS_Feed_URL>")
        sys.exit(1)

    feed_url = sys.argv[1]
    main(feed_url)


from pyfirmata import Arduino
import yaml
import os

# load config as variables
with open("config.yaml", "r") as f:
    config = yaml.load(f, yaml.Loader)
    locals().update(config)
use_motor = os.environ["use_motor"] == "True"

if use_motor:
    board = Arduino("/dev/ttyACM0")

    in1 = board.get_pin("d:{}:o".format(_in1))
    in2 = board.get_pin("d:{}:o".format(_in2))
    ena = board.get_pin("d:{}:p".format(_ena))
    in3 = board.get_pin("d:{}:o".format(_in3))
    in4 = board.get_pin("d:{}:o".format(_in4))
    enb = board.get_pin("d:{}:p".format(_enb))

def get_moveset():
    if use_motor:
        return {"w": forward, "a": left, "s": stop, "d": right}
    else:
        # print next line
        return {"w": print, "a": print, "s": print, "d": print}

def forward():
    in1.write(1)
    in2.write(0)
    in3.write(1)
    in4.write(0)
    ena.write(speed)
    enb.write(speed)

def left():
    in1.write(1)
    in2.write(0)
    in3.write(0)
    in4.write(1)
    ena.write(speed)
    enb.write(speed)

def right():
    in1.write(0)
    in2.write(1)
    in3.write(1)
    in4.write(0)
    ena.write(speed)
    enb.write(speed)

def stop():
    in1.write(0)
    in2.write(0)
    in3.write(0)
    in4.write(0)
    ena.write(0)
    enb.write(0)


import numpy as np

DZ=0.1
ZMAX=10.0001

def read_snapshot_table(file):
    """Function to read snapshot table and return disctionaries of
       snapshot versus redshift and vice versa"""
    snap,a,z,t,tyr=np.loadtxt(file,skiprows=1,unpack=True,
                              dtype=[('Snap','i4'),('a','f4'),('z','f4'),('t','f4'),('tyr','f4')])
    nsnap=len(snap)
    snap_to_z={snap[i]:z[i] for i in np.arange(nsnap)}
    z_to_snap={}
    for zz in np.arange(0,ZMAX,DZ):
        # Lots of rounding error, so this is a fudge to fix it.
        ilow=np.where(z > zz)[0][-1] # ilow is index of snaps with higher redshift
        if ilow==nsnap-1: ilow=ilow-1
        if z[ilow]+z[ilow+1]>2*zz:
            z_to_snap.update([(str(DZ*(zz/DZ)),snap[ilow])])
        else:
            z_to_snap.update([(str(DZ*(zz/DZ)),snap[ilow+1])])
    return (snap_to_z,z_to_snap)