t = int(input())
val = 0
for i in range(t):
    arr = list(map(int,input().split(" ")))
    c = arr[0]
    s = arr[0]
    n = 0
    for j in arr:
        c = max(j,j*c)
        s = max(s,c)
        val = val + 1
        if val == 3:
            n= n+ 1
            arr = arr[n:]
    print(s)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/8/23 9:40 AM
# @Author : Yuchen
# @File : Task4_Dutch_National_Flag_Problem.py
# @Software: PyCharm

"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
You're not allowed to use any sorting function that Python provides.

Note: O(n) does not necessarily mean single-traversal.
e.g. if you traverse the array twice, that would still be an O(n) solution but it will not count as single traversal.
"""

# version 1, cost more sapce complexity
def sort_012_v1(input_list):
    """
    Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.

    Args:
       input_list(list): List to be sorted
    """
    list1, list2, list3 = list(), list(), list()
    for i in input_list:
        if i == 0:
            list1.append(i)
        elif i == 1:
            list2.append(i)
        elif i == 2:
            list3.append(i)

    return list1 + list2 + list3

# version 2 ,better solution
def sort_012(input_list):
    """
    The idea is to put 0 and 2 in their correct positions, which will make sure
    all the 1s are automatically placed in their right positions
    """
    # initialize pointers for next positions of 0 and 2
    next_pos_0 = 0
    next_pos_2 = len(input_list) - 1

    front_index = 0

    while front_index <= next_pos_2:
        if input_list[front_index] == 0:
            input_list[front_index] = input_list[next_pos_0]
            input_list[next_pos_0] = 0
            next_pos_0 += 1
            front_index += 1
        elif input_list[front_index] == 2:
            input_list[front_index] = input_list[next_pos_2]
            input_list[next_pos_2] = 2
            next_pos_2 -= 1
        else:
            front_index += 1
    return input_list

def test_function(test_case):
    sorted_array = sort_012_v1(test_case)
    print(sorted_array)
    if sorted_array == sorted(test_case):
        print("Pass")
    else:
        print("Fail")

if __name__ == '__main__':
    # Test1 , edge case: empty input list, should return []
    test_function([])

    # Test2 , edge case: only has two of the expected elements
    test_function([0, 0, 2, 2, 2])

    # Test3 , general test
    test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2])
    test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1])
    test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2])


import sys;read=sys.stdin.readline
from collections import defaultdict
N,S = map(int,read().split())
nums = list(map(int,read().split()))
nums.sort()
start = 0
end = N-1
answer = 0
while start<end:
    hap = sum(nums[start:end+1])
    if hap==S:
        answer += 1
        start += 1
    elif hap<S:
        start += 1
    else:
        end -= 1
print(answer)


import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard
import random

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.tracer(0)

player = Player()
score = Scoreboard()

screen.listen()
screen.onkey(player.move, "w")
screen.onkey(player.move, "Up")

car_amount = 0
loops = 8
cars_collection = []
game_is_on = True
sleeping = 0.05

while game_is_on:
    time.sleep(sleeping)
    screen.update()

    if player.ycor() > 260:
        player.next_level()
        score.level_up()
        if sleeping > 0.02:
            sleeping -= 0.01

    if car_amount < 35 and loops > 10:
        for n in range(0, random.randint(0, 1)):
            car = CarManager()
            car_amount += 1
            cars_collection.append(car)
        loops = 0

    for n in cars_collection:
        if n.xcor() < -320:
            cars_collection.remove(n)
            car_amount -= 1
        else:
            n.drive()

        if player.distance(n) < 20:
            game_is_on = False
            score.game_over()

    loops += 1

screen.exitonclick()


import pandas as pd
import glob
import sys

if len(sys.argv) != 2:
	print("Syntax: {} <filepattern.csv> # e.g. autocontents-yyyy-mm-dd.csv or 'autocontents-*.csv'", file=sys.stderr)
	sys.exit(1)

filepattern = sys.argv[1]

datafiles = glob.glob(filepattern)
datafiles.sort()

csvmode = False
if len(datafiles) > 1:
	csvmode = True

if csvmode:
	f = open("dupedetector.csv", "w")
	print("#date,dupes,dupespct", file=f)

for datafile in datafiles:
	present = {}
	dupes = {}

	df = pd.read_csv(datafile, names="name,id,publisherAlias,deploymentCount,labels,description,homePageUrl,caps".split(","))
	for idx, fid, vendor in df[["id", "publisherAlias"]].itertuples():
		arn, name = fid.split("/")
		if not name in present:
			present[name] = vendor
		else:
			d = dupes.get(name, [])
			if not present[name] in d:
				d.append(present[name])
			d.append(vendor)
			dupes[name] = d

	ndupes = sum(len(dupes[x]) for x in dupes)
	dupepct = round(100 * ndupes / len(df), 2)
	if csvmode:
		date = datafile.replace(".csv", "")[-10:]
		print("{},{},{}".format(date, ndupes, dupepct), file=f)
	else:
		print(dupes)
		print("{} → {} out of {} = {}%".format(len(dupes), ndupes, len(df), dupepct))

if csvmode:
	f.close()


from selenium import webdriver

BASE_URL = "https://github.com/"

# How long to wait for commands.
IMPLICITLY_WAIT = 4

# For negative assertions, set the delay much lower.
IMPLICITLY_WAIT_QUICK_ASSERT = 1

# Add a delay after page navigation.
GOTO_DELAY = 0.5

# Add a delay between commands.
PER_COMMAND_DELAY = 0.1

# Configure the browser to use.
DRIVER = webdriver.Firefox


"""O mais dificil nesta questão é solucionar o 'negócio' da questão e não a
lógica em si."""

"""importamos o módulo math para facilitar os cálculos e nos familiarizarmos com os
módulos Python."""
import math

x = float(input('Digite a coordenada X do dardo: '))
y = float(input('Digite a coordenada Y do dardo: '))
dst_dardo = math.sqrt((x-0)**2 + (y-0)**2) # dAB² = (xB – xA)² + (yB – yA)².
r_alvo = 10

#a_alvo = math.pi * math.pow(r_alvo,2) #area da circunferencia do alvo
#c_alvo = 2 * math.pi * r_alvo #circunferencia do alvo

if dst_dardo <= r_alvo:
    print(True)
else:
    print(False)
    print()


from flask import Flask, request, jsonify
from hackMIT import run_hackMIT
app = Flask(__name__)

@app.route('/chat', methods=['POST'])
def chat():
    data = request.json
    user_input = data.get('user_input')
    state = data.get('state', 'start')

    next_state, response = run_hackMIT(state, user_input)

    return jsonify({'state': next_state, 'response': response})


import argparse
import os
import os.path as osp
import time
import json

import numpy as np
import torch
import torch.nn as nn
import torch.optim

import models
import ebms
from ebms import ActRateTracker
from datasets import load_dataset, get_num_classes
from tools.penalize_transformation import validate, train, plot_curve, save_stats, eval_acc_loss
from tools.utils import sample_input
from metrics.calc_info import calc_information_for_epoch_KDE
from tools.lib import update_lr, save_obj, set_seed

def parse_args():
    parser = argparse.ArgumentParser(description='Penalize the transformation complexity')
    parser.add_argument("--data-root", type=str, default="./data",
                        help="the root folder of datasets")
    parser.add_argument("--dataset", type=str, default="cifar10",
                        help="the name of the dataset")
    parser.add_argument('--arch', type=str, default='resmlp10',
                        help='model architecture')

    parser.add_argument('--model-lr', default=1e-2, type=float,
                        metavar='LR', help='initial learning rate')
    parser.add_argument('--model-lr-decay', default=2, type=float)
    parser.add_argument('--epochs', default=201, type=int, metavar='EPOCHS',
                        help='number of total epochs to run')
    parser.add_argument('--batch-size', default=128, type=int,
                        metavar='BS', help='mini-batch size (default: 128)')
    parser.add_argument('--default_train', action="store_true",
                        help='train without complexity loss')

    parser.add_argument("--penalize-layers", type=str, default="layers.5.act,layers.6.act,layers.7.act,layers.8.act",
                        help="which layers to penalize the transformation complexity")
    parser.add_argument("--energy-functions", type=str, default="E_3072d,E_3072d,E_3072d,E_3072d",
                        help="configuration of the energy function of each layer")
    parser.add_argument("--n-channels", type=str, default="3072,3072,3072,3072",
                        help="# of channels in gating layers")

    parser.add_argument('--ebm-lr', default=1e-4, type=float)
    parser.add_argument('--ebm-lr-decay', default=2, type=float)
    parser.add_argument('--l_step', default=5, type=int, metavar='L_STEP',
                        help='langevin step number')
    parser.add_argument('--tau', default=0.001, type=float, metavar='TAU',
                        help='tau is the step length in langevin step')
    parser.add_argument('--loss_lambda', default=-4.0, type=float, metavar='LAMBDA',
                        help='control the ratio between criterion loss and f function loss')
    parser.add_argument("--train-interval", type=int, default=10)

    parser.add_argument('--plot', action="store_true",
                        help='whether we should plot the loss function and train/test accuracy')
    parser.add_argument('--print-freq', '-p', default=50, type=int,
                        metavar='N', help='print every x batches (default: 50)')
    parser.add_argument("--save-folder", default="./saved-models")

    parser.add_argument("--gpu-id", type=int, default=0)
    parser.add_argument("--seed", type=int, default=1234)

    parser.add_argument("--evaluate", action="store_true")
    parser.add_argument("--num-per-class", type=int, default=200)

    args = parser.parse_args()
    print()
    print(args)
    print()
    return args

def load_model(args):
    model = models.__dict__[args.arch](activation_type="swish").to(args.gpu_id)
    optimizer = torch.optim.SGD(model.parameters(), args.model_lr, momentum=0.9, weight_decay=5e-4)
    if args.default_train:
        return model, [], [], optimizer, []

    model.set_store_soft_gating_states(save_layers=args.penalize_layers)
    f_list = [ebms.__dict__[e_func]().to(args.gpu_id) for e_func in args.energy_functions.split(",")]
    q_list = [ActRateTracker(n_channels=int(n_c)).to(args.gpu_id) for n_c in args.n_channels.split(",")]
    f_optimizer_list = [
        torch.optim.SGD(f_list[i].parameters(), args.ebm_lr, momentum=0.9, weight_decay=5e-4)
        for i in range(len(f_list))
    ]
    return model, f_list, q_list, optimizer, f_optimizer_list

def setup(args):
    seed = args.seed
    set_seed(seed)

    if not args.default_train:
        args.save_folder = osp.join(args.save_folder, f"dataset={args.dataset}_model={args.arch}",
                                    f"M__bs={args.batch_size}_model-lr={args.model_lr}_epochs={args.epochs}_"
                                    f"E__l={args.l_step}_tau={args.tau}_lambda={args.loss_lambda}"
                                    f"_interval={args.train_interval}_seed={args.seed}")
    else:
        args.save_folder = osp.join(args.save_folder, f"dataset={args.dataset}_model={args.arch}",
                                    f"M__bs={args.batch_size}_model-lr={args.model_lr}"
                                    f"_epochs={args.epochs}_seed={args.seed}")

    if not args.evaluate:
        os.makedirs(args.save_folder, exist_ok=True)
        os.makedirs(osp.join(args.save_folder, "model"), exist_ok=True)
        os.makedirs(osp.join(args.save_folder, "curve"), exist_ok=True)

        with open(osp.join(args.save_folder, "hparams.json"), "w") as f:
            json.dump(vars(args), f, indent=4)
    else:
        args.model_path = osp.join(args.save_folder, "model", "model.pth")
        os.makedirs(osp.join(args.save_folder, "evaluate"), exist_ok=True)

        with open(osp.join(args.save_folder, "hparams_eval.json"), "w") as f:
            json.dump(vars(args), f, indent=4)

def main(args):

    setup(args)

    plot_dic = {
        "loss_label": [],
        "loss_compl": [],
        "loss_total": [],
        **{f"loss_compl_{i}": [] for i in range(len(args.penalize_layers.split(",")))},
        **{f"loss_f_{i}": [] for i in range(len(args.penalize_layers.split(",")))},
        **{f"p_{i}": [] for i in range(len(args.penalize_layers.split(",")))},
        "train_acc": [],
        "test_acc": []
    }

    model_lr_list = np.logspace(np.log10(args.model_lr), np.log10(args.model_lr) - args.model_lr_decay, args.epochs)
    f_lr_list = np.logspace(np.log10(args.ebm_lr), np.log10(args.ebm_lr) - args.ebm_lr_decay, args.epochs)

    train_loader, val_loader = load_dataset(dataset=args.dataset, data_root=args.data_root, batch_size=args.batch_size)
    model, f_list, q_list, optimizer, f_optimizer_list = load_model(args=args)
    assert len(f_list) == len(q_list)
    criterion = nn.CrossEntropyLoss()

    for epoch in range(args.epochs):
        # update learning rates
        update_lr(optimizer, model_lr_list[epoch])
        for ebm_id in range(len(f_list)):
            update_lr(f_optimizer_list[ebm_id], f_lr_list[epoch])
        print('current lr {:.5e}'.format(optimizer.param_groups[0]['lr']))

        # train and evaluate the model
        train(args, train_loader, model, f_list, q_list, criterion, optimizer, f_optimizer_list, epoch, plot_dic)
        prec1 = validate(val_loader, model, criterion, print_freq=args.print_freq, device=args.gpu_id)

        plot_dic["test_acc"].append(prec1)

        if args.plot or True:
            plot_curve(plot_dict=plot_dic, save_path=osp.join(args.save_folder, "curve", "curve.png"))

        save_obj(plot_dic, osp.join(args.save_folder, "curve", "data.bin"))

    torch.save(model.cpu().state_dict(), os.path.join(args.save_folder, "model", "model.pth"))
    for ebm_id in range(len(f_list)):
        torch.save(f_list[ebm_id].cpu().state_dict(), os.path.join(args.save_folder, "model", f"f{ebm_id}.pth"))
        torch.save(q_list[ebm_id].cpu().state_dict(), os.path.join(args.save_folder, "model", f"q{ebm_id}.pth"))

    save_stats(plot_dict=plot_dic, save_path=osp.join(args.save_folder, "model", "stats.txt"))

def main_evaluate(args):

    setup(args)

    # load dataset and model
    train_loader, val_loader = load_dataset(dataset=args.dataset, data_root=args.data_root,
                                            batch_size=args.batch_size, shuffle_train=False, data_aug_train=False)
    train_loader_sample, _ = load_dataset(dataset=args.dataset, data_root=args.data_root,
                                          batch_size=1, shuffle_train=False, data_aug_train=False)
    model, _, _, _, _ = load_model(args=args)
    model.load_state_dict(torch.load(args.model_path, map_location=torch.device(f"cuda:{args.gpu_id}")))
    model.eval()
    print(f"Model loaded from {args.model_path}")

    # sample some input images for calculating transformation complexity (See Appendix G.1)
    num_classes = get_num_classes(args.dataset)
    input, label = sample_input(num_classes=num_classes, num_per_class=args.num_per_class,
                                data_loader=train_loader_sample, device=args.gpu_id)

    # generating the gating states
    with torch.no_grad():
        model(input)
    num_samples = input.shape[0]
    sigma = [model.sigma_list[layer_id].reshape(num_samples, -1) for layer_id in model.sigma_list.keys()]
    sigma = torch.cat(sigma, dim=1)
    for t in model.sigma_list.values():
        if len(t.shape) == 4:
            sigma = sigma.unsqueeze(2).unsqueeze(3)
            break
    sigma_label = [sigma, label]

    # calculate transformation complexity
    ret_dict = {}
    network_info = calc_information_for_epoch_KDE(sigma_label, device=args.gpu_id)
    HS = network_info[0]['local_IXT']  # H(\Sigma)
    ISY = network_info[0]['local_ITY']  # I(X;\Sigma;Y)
    ret_dict["HS"] = HS.item()
    ret_dict["ISY"] = ISY.item()

    # calculate loss and accuracy
    _, train_loss = eval_acc_loss(model, train_loader, device=args.gpu_id)
    test_acc, test_loss = eval_acc_loss(model, val_loader, device=args.gpu_id)
    ret_dict["train_loss"] = train_loss
    ret_dict["test_loss"] = test_loss
    ret_dict["test_acc"] = test_acc

    save_obj(ret_dict, osp.join(args.save_folder, "evaluate", "info.bin"))
    with open(osp.join(args.save_folder, "evaluate", "info.json"), "w") as f:
        json.dump(ret_dict, f, indent=4)

    return ret_dict

if __name__ == '__main__':
    args = parse_args()
    if not args.evaluate:
        main(args)
    else:
        main_evaluate(args)


from rapid_api import city_founding, create_hotel_message
from keyboards.inline.buttons import city_markup, quantity_hotels_markup, \
    photo_y_n_markup, quantity_photo_markup
from loader import bot
from states.state_for_lowprice import UserInfoState
from loguru import logger
from datetime import date
from telegram_bot_calendar import DetailedTelegramCalendar, LSTEP

@bot.message_handler(commands=['low_price', 'high_price', 'bestdeal'])
@logger.catch
def start(message):
    bot.set_state(message.from_user.id, UserInfoState.command, message.chat.id)

    with bot.retrieve_data(message.from_user.id, message.chat.id) as data:
        data['command'] = message.text[1:]

    bot.send_message(message.chat.id, '🗺В какой город направляетесь?')
    bot.set_state(message.from_user.id, UserInfoState.city, message.chat.id)

@bot.message_handler(state=UserInfoState.city)
@logger.catch
def city(message):
    # список районов города

    cities_list = city_founding(message.text)

    if cities_list is None:
        bot.send_message(message.chat.id, 'Извините, не могу найти такой город(( '
                                          'Пожалуйста, проверьте правильность написания города')
    else:
        bot.send_message(message.chat.id, '🏙Уточните, пожалуйста, район города:',
                         reply_markup=city_markup(cities_list))
        # bot.set_state(message.from_user.id, UserInfoState.quantity_hotels, message.chat.id)

        with bot.retrieve_data(message.from_user.id, message.chat.id) as data:
            data['city'] = message.text
            logger.info('city={text}'.format(text=message.text))

@bot.callback_query_handler(func=lambda call: call.data.endswith('_1'))
@logger.catch
def city_area(call):
    # сохраняет id района города
    # календарь

    with bot.retrieve_data(call.from_user.id, call.message.chat.id) as data:
        data['city_area_id'] = call.data[:-2]

    bot.delete_message(call.message.chat.id, call.message.message_id)
    calendar, step = DetailedTelegramCalendar(calendar_id='in',
                                              min_date=date.today(),
                                              max_date=date(2024, 10, 21)).build()

    ru_steps = {'y': 'год', 'm': 'месяц', 'd': 'день'}
    bot.send_message(call.message.chat.id, f'🗓Выберите дату заезда:\n{ru_steps[step]}',
                     reply_markup=calendar)

@bot.callback_query_handler(func=DetailedTelegramCalendar.func(calendar_id='in'))
@logger.catch
def call_back_check_in(call):
    result, key, step = DetailedTelegramCalendar(
        calendar_id='in',
        locale='ru',
        min_date=date.today(),
        max_date=date(2024, 3, 31)
    ).process(call.data)

    ru_steps = {'y': 'год', 'm': 'месяц', 'd': 'день'}

    if not result and key:
        bot.edit_message_text(f"Выберите: {ru_steps[step]}",
                              chat_id=call.message.chat.id,
                              message_id=call.message.message_id,
                              reply_markup=key)
    elif result:
        bot.edit_message_text(f"🗓Дата заезда: {result}",
                              call.message.chat.id,
                              call.message.message_id)
        with bot.retrieve_data(call.from_user.id, call.message.chat.id) as data:
            data['check_in'] = result

        calendar, step = DetailedTelegramCalendar(
            calendar_id='out',
            min_date=date.today(),
            max_date=date(2024, 3, 31)
        ).build()

        bot.send_message(call.message.chat.id, f'🗓Выберите дату выезда:\n{ru_steps[step]}',
                         reply_markup=calendar)

@bot.callback_query_handler(func=DetailedTelegramCalendar.func(calendar_id='out'))
@logger.catch
def call_back_check_out(call):
    with bot.retrieve_data(call.from_user.id, call.message.chat.id) as data:
        result, key, step = DetailedTelegramCalendar(
            calendar_id='out',
            locale='ru',
            min_date=data['check_in'],
            max_date=date(2024, 3, 31)).process(call_data=call.data)

    if not result and key:
        ru_steps = {'y': 'год', 'm': 'месяц', 'd': 'день'}
        bot.edit_message_text(f"Выберите {ru_steps[step]}",
                              chat_id=call.message.chat.id,
                              message_id=call.message.message_id,
                              reply_markup=key)
    elif result:
        bot.edit_message_text(f"🗓Дата выезда: {result}",
                              call.message.chat.id,
                              call.message.message_id)

        with bot.retrieve_data(call.from_user.id, call.message.chat.id) as data:
            data['check_out'] = result

            if data['command'] == 'bestdeal':
                bot.send_message(call.message.chat.id, '💲Введите минимальную стоимость отеля за ночь:')
                bot.set_state(call.from_user.id, UserInfoState.min_price, call.message.chat.id)
            else:
                bot.send_message(call.message.chat.id, 'Сколько отелей показать?',
                                 reply_markup=quantity_hotels_markup())
                # bot.set_state(call.message.from_user.id, UserInfoState.photo_y_n, call.message.chat.id)

@bot.callback_query_handler(func=lambda call: call.data.endswith('_2'))
@logger.catch
def photo_y_n(call):
    # сохраняет количество отелей
    # фото отелей

    with bot.retrieve_data(call.from_user.id, call.message.chat.id) as data:
        data['quantity_hotels'] = int(call.data[:-2])

    bot.delete_message(call.message.chat.id, call.message.message_id)
    bot.send_message(call.message.chat.id, 'Показать фото отелей?',
                     reply_markup=photo_y_n_markup())
    # bot.set_state(call.message.from_user.id, UserInfoState.quantity_photo, call.message.chat.id)

@bot.callback_query_handler(func=lambda call: call.data.endswith('_3'))
@logger.catch
def quantity_photo(call):
    # если да - запрашивает количество фото
    # если нет - список отелей

    bot.delete_message(call.message.chat.id, call.message.message_id)
    if call.data[:-2] == 'Да':
        bot.send_message(call.message.chat.id, 'Сколько фото показать?',
                         reply_markup=quantity_photo_markup())
        # bot.set_state(call.message.from_user.id, UserInfoState.hotels, call.message.chat.id)
    else:
        with bot.retrieve_data(call.from_user.id, call.message.chat.id) as data:
            days = (data['check_out'] - data['check_in']).days
            create_hotel_message(bot_data=data,
                                 days_count=days,
                                 user_id=call.from_user.id)

@bot.callback_query_handler(func=lambda call: call.data.endswith('_4'))
@logger.catch
def hotels(call):
    # сохраняет количество фото
    # список отелей

    with bot.retrieve_data(call.from_user.id, call.message.chat.id) as data:
        data['quantity_photo'] = int(call.data[:-2])

        bot.delete_message(call.message.chat.id, call.message.message_id)
        days = (data['check_out'] - data['check_in']).days
        create_hotel_message(bot_data=data,
                             days_count=days,
                             user_id=call.from_user.id,
                             photo_quantity=data['quantity_photo'])


#!/usr/bin/python

from __future__ import print_function
import argparse

parser = argparse.ArgumentParser(description="Using information found in the AHL Data spreadsheet, this creates several PED files that assign phenotypes for the various pathogens or conditions that were tested for. Healthy animals are controls, animals that test positive are cases, and diseased animals that were not tested or test negative are not considered.", epilog = "RS Fraser, April 25, 2017")

parser.add_argument("ped_file", help="The original PED file that is used as a template")
parser.add_argument("ahl_file", help="The AHL file containing the pathogen/condition data. Pigs as columns, conditions as rows. Test positive = 1; anything else is set as a phenotype to ignore")

args = parser.parse_args()

ped = open(args.ped_file, 'r')
ahl = open(args.ahl_file, 'r')

x_dict = {}

for line in ahl:

	line = line.rstrip()
	if "animal_id" in line:
		pig_id_keys = line.split("\t")

	else:
		line_fields = line.split("\t")
		rsid_dict = line_fields[0] + "_dict"
		rsid_dict = {}

		for i in range(len(line_fields)):
			if i == 0:
				rsid = line_fields[i]
			else:
				rsid_dict[pig_id_keys[i]] = line_fields[i]

		x_dict[rsid] = rsid_dict

for k,v in x_dict.items():

	filename_str = k + ".ped"
	filename = open(filename_str, 'w')

	for ped_line in ped:

		ped_line = ped_line.rstrip()
		ped_line_fields = ped_line.split("\t")

		if "-" not in ped_line:
			print(ped_line, file = filename)

		else:

			for k2, v2 in x_dict[k].items():

				if ped_line_fields[0] == k2:

					for i in range(5):
						print(ped_line_fields[i], sep="\t", end="\t", file = filename)

					if "1" in x_dict[k][k2]:
						print("2", sep="", end="\t", file = filename)

					else:
						print("-9", end="\t", file = filename)

					for i in range(6, len(ped_line_fields)):
						print(ped_line_fields[i], sep="\t", end="\t", file = filename)

					print("", file = filename)

	#holy shit did it take awhile to debug this bastard. The issue with this nested for loop is that once the ped file has been iterated over, python doesn't reset it back to the start... so the first key value from teh dictionary would iterate over the entire ped file, and the ped file would be at it's "end". The seek function resets the file's position to the defined value - thus, for every key iteration, it starts the ped file back at the start. Whoosh....
	ped.seek(0)


import json
import nextcord
from cmds.ban import ban
from nextcord.ext import commands
from core.classes import Cog_Extension

class Ban_list(Cog_Extension):
    @commands.command()
    @commands.has_any_role(978680963099942912, 979385876209610752, 978956326359138314, 1070679396165373984, 1080095809175035984)    # 社長、工程師、管理員
    async def ban_list(self, ctx):
        with open('data/list.json', 'r', encoding = 'utf-8') as ban_l:
            banlast = json.load(ban_l)
        list_embed = nextcord.Embed(title = "ban人名單", color = 0xffe380)
        for i in banlast['ban']:
            u_name = self.bot.get_user(i)
            list_embed.add_field(name = u_name, value = i, inline = False)
        await ctx.send(embed = list_embed)
        print(f'-> List ban_list for {ctx.author}')

def setup(bot):
    bot.add_cog(Ban_list(bot))


#coding=utf-8
__author__ = 'wanglu'

import hashlib
import logging

from flask import Blueprint,request

from ..weixin import receive
from ..weixin import reply
import main.config.app_settings as conf

weixin_blueprint = Blueprint("weixin_blueprint",__name__)

logger = logging.getLogger(__name__)

@weixin_blueprint.route("/",methods=["GET","POST"])
def index():

    try:
        if request.method == "GET":
            signature = request.args["signature"]
            echostr = request.args["echostr"]
            timestamp = request.args["timestamp"]
            nonce = request.args["nonce"]

            token = conf.APP_TOKEN

            list = [token,timestamp,nonce]
            list.sort()
            sha1 = hashlib.sha1()
            map(sha1.update, list)
            hashcode = sha1.hexdigest()
            print ("handle/GET func: hashcode, signature: ", hashcode, signature)

            if hashcode == signature:
                return echostr
            else:
                return ""

        if request.method == "POST":
            webData = request.data
            logger.info("Handle Post webdata is: %s" % webData)   #后台打日志
            recMsg = receive.parse_xml(webData)
            if isinstance(recMsg, receive.Msg):
                toUser = recMsg.FromUserName
                fromUser = recMsg.ToUserName
                if  recMsg.MsgType == 'text':
                    if recMsg.Content == "test":
                        content = "test"
                    elif recMsg.Content == "baidu":
                        content = "test http://www.baidu.com"
                    else:
                        content = "test"
                    replyMsg = reply.TextMsg(toUser, fromUser, content)
                    return replyMsg.send()
                if recMsg.MsgType == 'image':
                    mediaId = recMsg.MediaId
                    replyMsg = reply.ImageMsg(toUser, fromUser, mediaId)
                    return replyMsg.send()
                else:
                    return reply.Msg().send()
            elif isinstance(recMsg,receive.Event):
                toUser = recMsg.FromUserName
                fromUser = recMsg.ToUserName
                if recMsg.Event == "VIEW":
                    content = "Menu Event View"
                    replyMsg = reply.TextMsg(toUser,fromUser,content)
                    return replyMsg.send()
            else:
                logger.info("暂且不处理")
                return "success"
    except Exception as err:
        return "error"


from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import torch
from absl import app, flags

from modules.models import PPG2ECG

flags.DEFINE_string("weights", "", "model weights for inferencing")
flags.DEFINE_string("input", "example/PPG.npy", "input data (numpy array)")
FLAGS = flags.FLAGS

def main(argv):
    # prepare the parameters
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    # prepare the model
    model = PPG2ECG(
        input_size=200,
        use_stn=True,
        use_attention=True).to(device)

    # load the model state
    model.load_state_dict(torch.load(Path(FLAGS.weights))["net"])
    model.eval()

    # prepare the inference data (PPG data)
    ppg = np.load(Path(FLAGS.input))
    print("ppg shape: {}".format(ppg.shape))

    # run through the data
    idx = 0
    step = 100
    ecg = []
    while True:
        # out of range for ppg data
        if (idx+200) > len(ppg):
            break
        # preprocess the single data to match the input size
        input_data = ppg[idx:idx+200]

        # reshape the data to [1, 200]
        input_data = input_data.reshape((1, -1))

        # move ppg data to torch tensor and device
        input_data = torch.from_numpy(input_data).to(device).float()

        # inference
        # in torch, you need (batch, data) for forward
        # so you should unsqueeze the input data by unsqueeze(0)
        # now the input size should be [1, 1, 200]
        with torch.no_grad():
            output_data = model(input_data.unsqueeze(0))
            output_data = output_data["output"].cpu()
            ecg.append(output_data[0, 0])  # [1, 1, 200] -> [200,]
        idx += step

    # model performs better in middle [50:150] for whole output [0:200]
    # also we drop first 50 and last 50 for ppg to align the ppg and ecg
    ecg = [e[50:150] for e in ecg]
    ppg = ppg[50:-50]

    # show the plot
    ecg = torch.cat(ecg)
    plt.plot(ppg, label="ppg")
    plt.plot(ecg, label="ecg")
    plt.legend()
    plt.show()

if __name__ == "__main__":
    app.run(main)


#!/usr/bin/env python3
import os, sys, glob
from reeds.modules import do_EDS_energy_minimization as energy_minimization

sys.path.append(os.getcwd())

from global_definitions import fM, bash
from global_definitions import name, root_dir
from global_definitions import gromosXX_bin, gromosPP_bin, ene_ana_lib
from global_definitions import in_top_file, in_cnf_file, in_pert_file, in_disres_file, in_template_eds_imd

#Step Specifics
out_dir = root_dir+"/0_emin"
in_name = name+"_minimization"

##make folder
out_dir = bash.make_folder(out_dir)

#In- Files
topology_state_opt = fM.Topology(top_path=in_top_file, disres_path=in_disres_file, perturbation_path=in_pert_file)
system = fM.System(coordinates=in_cnf_file, name=in_name, top=topology_state_opt)
print(system)

#DO:

energy_minimization.do(in_simSystem = system,
                       in_imd_template_path = in_template_eds_imd,
                       out_root_dir = out_dir,
                       in_gromosXX_bin_dir = gromosXX_bin,
                       in_gromosPP_bin_dir = gromosPP_bin,
                       submit=True,
                       nmpi_per_replica=1
                     )


from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
from odoo.models import expression
from odoo.tools.safe_eval import safe_eval

class EducationExam(models.Model):
    _name = "education.exam"
    _description = "Education Exam"
    _inherit = ["portal.mixin", "mail.thread", "mail.activity.mixin"]

    name = fields.Char(string="Name", required=True)
    exam_type_id = fields.Many2one(
        comodel_name="education.exam.type", string="Exam Type", required=True)
    n_line_id = fields.Many2one(
        comodel_name="education.notebook.line", string="Notebook Line",
        required=True, domain="[('exists_master', '=', False)]")
    schedule_id = fields.Many2one(
        comodel_name="education.schedule", related="n_line_id.schedule_id",
        string="Class Schedule", store=True)
    eval_type = fields.Selection(
        related="n_line_id.eval_type", string="Evaluation Season")
    teacher_id = fields.Many2one(
        comodel_name="hr.employee", related="n_line_id.schedule_id.teacher_id",
        string="Teacher", store=True)
    academic_year_id = fields.Many2one(
        comodel_name="education.academic_year",
        related="n_line_id.schedule_id.academic_year_id",
        string="Academic Year", store=True)
    subject_id = fields.Many2one(
        comodel_name="education.subject",
        related="n_line_id.schedule_id.subject_id",
        string="Education Subject", store=True)
    date = fields.Date(string="Exam date")
    eval_percent = fields.Float(string="Percent (%)", required=True)
    state = fields.Selection(
        selection=[("draft", "New"),
                   ("progress", "Marking"),
                   ("done", "Graded"),
                   ("closed", "Closed"), ],
        default="draft", track_visibility="onchange")
    second_chance_exam_id = fields.Many2one(
        comodel_name="education.exam", string="Second-chance Exam Of")
    second_chance_exam_ids = fields.One2many(
        comodel_name="education.exam", inverse_name="second_chance_exam_id",
        string="Second-chance Exams")
    type_exam_name = fields.Selection(
        related="exam_type_id.e_type", string="General Exam Type")
    mark_close_date = fields.Date(string="Closing Date")
    record_ids = fields.One2many(
        comodel_name="education.record", inverse_name="exam_id",
        string="Academic Records")
    record_count = fields.Integer(
        compute="_compute_record_count", string="# Records", store=True)
    description = fields.Text(string="Description")

    @api.multi
    def action_generate_record(self):
        record_obj = self.env["education.record"]
        for exam in self.filtered(lambda e: e.state in ('draft', 'progress')):
            n_line = exam.n_line_id
            for student in n_line.schedule_id.student_ids:
                parent_record = n_line.find_or_create_student_record(student)
                record = record_obj.search([
                    ("exam_id", "=", exam.id),
                    ("n_line_id", "=", n_line.id),
                    ("student_id", "=", student.id),
                    ("parent_record_id", "=", parent_record.id),
                ])
                if not record:
                    record_obj.create({
                        "exam_id": exam.id,
                        "student_id": student.id,
                        "n_line_id": n_line.id,
                        "parent_record_id": parent_record.id,
                        "date": exam.date,
                    })

    @api.multi
    @api.depends("record_ids")
    def _compute_record_count(self):
        for exam in self:
            exam.record_count = len(exam.record_ids)

    @api.multi
    def button_show_records(self):
        self.ensure_one()
        action = self.env.ref(
            "education_evaluation_notebook.education_record_action")
        action_dict = action.read()[0] if action else {}
        action_dict["context"] = safe_eval(
            action_dict.get("context", "{}"))
        action_dict["context"].update({
            "default_exam_id": self.id,
            "hide_calculated": True,
        })
        domain = expression.AND([
            [("exam_id", "=", self.id)],
            safe_eval(action.domain or "[]")])
        action_dict.update({"domain": domain})
        return action_dict

    @api.multi
    def action_marking(self):
        for exam in self.filtered(lambda e: e.state == "draft"):
            if not exam.date:
                raise ValidationError(
                    _('You must set an exam date.'))
            exam.state = "progress"

    @api.multi
    def action_graded(self):
        for exam in self.filtered(lambda e: e.state == "progress"):
            exam.state = "done"

    @api.multi
    def action_close_exam(self):
        today = fields.Date.context_today(self)
        for exam in self.filtered(lambda e: e.state == "done"):
            exam.write({
                "state": "closed",
                "mark_close_date": today
            })

    @api.multi
    def action_draft(self):
        for exam in self.filtered(lambda e: e.state != "closed"):
            exam.state = "draft"


# -*- coding: utf-8 -*-
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

from colin.checks.abstract.filesystem import FileSystemCheck

class FileCopy(FileSystemCheck):

    def __init__(self):
        super().__init__(name="httpd_installed",
                         message="Package httpd has to be isntalled (dnf install -y httpd).",
                         description="Use RUN for running a command inside an image. Použij RUN pro spuštění příkazu v obraze.",
                         reference_url="https://docs.docker.com/engine/reference/builder/#copy",
                         files=['/usr/sbin/httpd'],
                         tags=['filesystem', 'copy', 'openhouse'],
                         all_must_be_present=False)


#!/usr/bin/env python3
import csv,socket
from qpython import qconnection,qtype

SBS_HOST=('localhost',30003)
TP_HOST=('localhost',5010)
SBS_FIELDS=('mType','tType','sessionId','aircraftId','hexIdent','flightId','generatedDate','generatedTime','loggedDate','loggedTime','callSign','altitude','groundSpeed','track','lat','lon','verticalRate','squawk','alert','emergency','spi','isOnGround')
TBL_FIELDS=(
  ('hexIdent',qtype.QSYMBOL),
  ('mType',qtype.QSYMBOL),
  ('tType',qtype.QSHORT),
  ('callSign',qtype.QSYMBOL),
  ('altitude',qtype.QINT),
  ('groundSpeed',qtype.QINT),
  ('track',qtype.QINT),
  ('lat',qtype.QDOUBLE),
  ('lon',qtype.QDOUBLE),
  ('verticalRate',qtype.QINT),
  ('squawk',qtype.QSYMBOL),
  ('alert',qtype.QBOOL),
  ('emergency',qtype.QBOOL),
  ('spi',qtype.QBOOL),
  ('isOnGround',qtype.QBOOL)
)

def toQtype(val,qt):
 try:return qtype.PY_TYPE[qt](val)
 except:return qtype.qnull(qt)

def toTblRow(sbsRow):
 return [toQtype(sbsRow[fd[0]],fd[1]) for fd in TBL_FIELDS]

def main():
 with socket.create_connection(SBS_HOST) as sc,qconnection.QConnection(TP_HOST[0],TP_HOST[1]) as tp:
  reader=csv.DictReader(sc.makefile(),fieldnames=SBS_FIELDS)
  for row in reader:tp.sync('.u.upd',toQtype('fd',qtype.QSYMBOL),toTblRow(row))

if __name__=="__main__":main()


from datetime import datetime
from django.db.models import Q

def create_date_filter(query_params):
    start_date = query_params.get('start_date', None)
    end_date = query_params.get('end_date', None)

    _q = Q()

    if start_date:
        start_date = datetime.strptime(start_date, '%Y-%m-%d').date()
        _q &= Q(created_at__date__gte=start_date)
    if end_date:
        end_date = datetime.strptime(end_date, '%Y-%m-%d').date()
        _q &= Q(created_at__date__lte=end_date)

    return _q


import random
import json
import torch
from Classes.Model import NeuralNet
from nltk_utils import bag_of_words, tokenize, stem

def main():

    # Set-up
    FILE = r'data\processed\model.pth'
    data = torch.load(FILE)

    input_size = data['input_size']
    hidden_size = data['hidden_size']
    output_size = data['output_size']
    all_words = data['all_words']
    tags = data['tags']
    model_state = data['model_state']

    with open(r'data\training_data\train.json') as f:
        intents = json.load(f)

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    model = NeuralNet(input_size, hidden_size, output_size).to(device)
    model.load_state_dict(model_state)
    model.eval()

    botName = "Albert"
    print(f"{botName}> Hello, I am {botName}, let's talk fitness!")

    while True:
        sentence = input("You: ")
        if sentence == "quit":
            break

        sentence = tokenize(sentence)
        X = bag_of_words(sentence, all_words)
        X = X.reshape(1, X.shape[0])
        X = torch.from_numpy(X).to(device)

        output = model(X)
        _, predicted = torch.max(output, 1)
        print(predicted)
        tag = tags[predicted.item()]

        probs = torch.softmax(output, dim=1)
        prob = probs[0][predicted.item()] # type: ignore
        print(f"{botName}> {tag} ({prob:.2f})")

        # Confidence routing
        if prob.item() > 0.75:
            for intent in intents['intents']:
                if tag == intent['tag']:
                    print(f"{botName}> {random.choice(intent['responses'])}")
                    break
        else:
            print(f"{botName}> I'm sorry, I don't understand.")

    pass

if __name__ == "__main__":
    main()


"""
util.async_helpers - various utilities for asyncio functions and tasks.
"""

from functools import wraps
from typing import TypeVar, Callable, Awaitable, cast, Any

import asyncio

async def asyncio_yield() -> None:
    """
    Ensure that the current task yields to the event loop.

    The python async framework only switches between concurrently-running tasks when
    the currently-running task hits a leaf call that requires waiting for an event on
    the loop. That means that you can have a very long call of nice coroutines with
    async def and await call() that still effectively "block" other concurrent tasks
    from actually executing.

    There's also not really a nice way to yield to the event loop explicitly. The best
    way to do it is to drop in await asyncio.sleep(0), which will yield to the loop and
    let something else run.

    If you have an async call chain that is used in a tight loop and at no point contains
    an await() call that will yield the loop - this will be anything that
    - Involves touching a file descriptor that is registered with an asyncio protocol
    - Involves waiting for a Future
    - Involves waiting for another task
    - Involves specifically invoking an asyncio scheduling operation like gather()
    - Uses asyncio.sleep()

    You should drop an await asyncio_yield() at the most frequent leaf call to make sure
    that other tasks on the loop get a chance to run.
    """
    await asyncio.sleep(0)

Wrapped = TypeVar("Wrapped", bound=Callable[..., Awaitable[Any]])

def ensure_yield(async_def_func: Wrapped) -> Wrapped:
    """
    A decorator that makes sure that asyncio_yield() is called after the decorated async
    function finishes executing.
    """

    # _wrapper can be typed using ParamSpec https://docs.python.org/3/library/typing.html#typing.ParamSpec
    # when we
    # - bump to a mypy version that supports it (>0.930)
    # - either go to python 3.10 or bump typing_extensions to 4.2.0
    # Until then, this is a mess of opaque type vars and disabling internal checking because of their
    # opacity. The cast on line 58 should keep the external interface of the annotated function correct.
    @wraps(async_def_func)
    async def _wrapper(*args: Any, **kwargs: Any) -> Any:
        ret = await async_def_func(*args, **kwargs)
        await asyncio_yield()
        return ret

    return cast(Wrapped, _wrapper)


n = int(input())
for _ in range(n):
    g = list(map(int, input().split()))
    orginal = g
    g= g[1:]
    g= g[:-1]
    test= g[0]
    g= g[1:]
    if min(g) > test:
        print(g.index(max(g))+2)
    else:
        print(g.index(min(g))+2)


"""Add settings table

Revision ID: c7dd6d36b41e
Revises: 68968c14ecde
Create Date: 2022-11-02 08:46:15.446878

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'c7dd6d36b41e'
down_revision = '68968c14ecde'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('settings',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('lcd_brightness', sa.Integer(), nullable=True),
    sa.Column('wifi_enabled', sa.Boolean(), nullable=True),
    sa.Column('bluetooth_enabled', sa.Boolean(), nullable=True),
    sa.Column('lights_enabled', sa.Boolean(), nullable=True),
    sa.Column('upload_enabled', sa.Boolean(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('settings')
    # ### end Alembic commands ###


import io
import os
import urllib

import requests
from PIL import Image
from telethon import events

HAREM = os.environ.get("HAREM", False)

opener = urllib.request.build_opener()
useragent = "Mozilla/5.0 (Linux; Android 9; SM-G960F Build/PPR1.180610.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.157 Mobile Safari/537.36"
opener.addheaders = [("User-agent", useragent)]

if HAREM:

    @catub.on(events.NewMessage, outgoing=False, from_users=792028928)
    async def waifus_are_eternal(event):
        if event.is_private:
            return
        if event.media:
            borg = event.client
            if "Add" in event.raw_text:
                logger.info("OwO! A Waifu.")
                waifu_moment = io.BytesIO()
                await borg.download_media(event.media, waifu_moment)
                try:
                    image = Image.open(waifu_moment)
                except OSError:
                    return
                name = "waifu.png"
                image.save(name, "PNG")
                image.close()
                searchUrl = "https://www.google.com/searchbyimage/upload"
                file_img = {
                    "encoded_image": (name, open(name, "rb")),
                    "image_content": "",
                }
                response = requests.post(
                    searchUrl, files=file_img, allow_redirects=False
                )
                os.remove(name)
                if response.status_code == 400:
                    return
                fetchUrl = response.headers["Location"]
                match = await ParseSauce(fetchUrl + "&preferences?hl=en&fg=1#languages")
                guessp = match["best_guess"]
                if not guessp:
                    return
                guess = guessp.replace("Results for", "").replace(" ", "")
                await borg.send_message(event.chat_id, f"/protecc {guess}")


import cv2
import numpy as np
from config import *

def yolo_prediction(img):
    # Load Yolo
    net = cv2.dnn.readNet(YOLO_MODEL, YOLO_CONFIG)

    # Name custom object
    classes = ["ecg"]

    layer_names = net.getLayerNames()
    output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
    colors = np.random.uniform(0, 255, size=(len(classes), 3))

    coords = list()

    # img = cv2.resize(img, None, fx=0.4, fy=0.4)
    # img = cv2.resize(img, dsize=(1280,720))

    height, width, channels = img.shape

    # Detecting objects
    blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)

    net.setInput(blob)
    outs = net.forward(output_layers)

    # Showing informations on the screen
    class_ids = []
    confidences = []
    boxes = []
    for out in outs:
        for detection in out:
            scores = detection[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]
            if confidence > 0.3:
                # Object detected
                center_x = int(detection[0] * width)
                center_y = int(detection[1] * height)
                w = int(detection[2] * width)
                h = int(detection[3] * height)

                # Rectangle coordinates
                x = int(center_x - w / 2)
                y = int(center_y - h / 2)

                boxes.append([x, y, w, h])
                confidences.append(float(confidence))
                class_ids.append(class_id)

    # ? show predictions image
    indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
    font = cv2.FONT_HERSHEY_PLAIN
    detection_image = img.copy()
    for i in range(len(boxes)):
        if i in indexes:
            x, y, w, h = boxes[i]

            coords.append([[x,abs(y)],[x + w, y + h]])

            label = str(classes[class_ids[i]])
            color = colors[class_ids[i]]
            cv2.rectangle(detection_image, (x, y), (x + w, y + h), color, 2)
            cv2.putText(detection_image, label, (x, y + 30), font, 3, color, 2)

    cv2.imshow("detection_image", detection_image)
    key = cv2.waitKey(0)

    cv2.destroyAllWindows()

    return coords, img

img_path = 'src/full/anormal-S.jpg'
img = cv2.imread(img_path)

coords, img = yolo_prediction(img)

for pts in coords:
    try:
        pt1, pt2 = pts
        print(pt1,pt2)
        cutted_image = img[pt1[1]:pt2[1], pt1[0]:pt2[0]]
        cv2.imshow('img',cutted_image)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
    except Exception as e:
        print(e)


from unittest.mock import MagicMock, Mock

from pg_stream_copy.encoder import Encoder

from . import data

def test_all_1() -> None:
    writer = MagicMock()
    append_mock = writer.append = Mock()

    with Encoder(data.SET1_SCHEMA, writer) as encoder:
        append_mock.assert_called_once_with(b"PGCOPY\n\xff\r\n\x00\x00\x00\x00\x00\x00\x00\x00\x00")
        writer.reset_mock()

        encoder.append_tuple(data.SET1_ROW_TUPLE)
        append_mock.assert_called_once_with(data.SET1_ROW_BINARY)
        writer.reset_mock()

        encoder.append_dict(data.SET1_ROW_DICT)
        append_mock.assert_called_once_with(data.SET1_ROW_BINARY)
        writer.reset_mock()

    append_mock.assert_called_once_with(b"\xff\xff")
    writer.reset_mock()


from P4 import P4,P4Exception
import config

p4 = P4()
p4.port = config.P4PORT
p4.user = config.P4USER

try:
  p4.connect()
  # p4 servers
  servers = p4.run( "servers" )
  for server in servers:
    for key in server:
      print(key, "=", server[key])
    print()
  p4.disconnect()
except P4Exception:
  for e in p4.errors:
      print(e)


import time
from typing import Dict

import jwt
from decouple import config

JWT_SECRET = config("secret")
JWT_ALGORITHM = config("algorithm")

def token_response(token: str):
    return {
        "access_token": token
    }

def signJWT(user: Dict) -> Dict[str, str]:
    payload = {
        "id": user["id"],
        "firstname": user["firstName"],
        "lastname": user["lastName"],
        "roles": user["roles"],
        "expires": time.time()+60000
    }
    token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM)
    print({**user, "access_token": token})
    return {**user, "access_token": token}

def decodeJWT(token: str) -> dict:
    try:
        decoded_token = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
        return decoded_token if decoded_token["expires"] >= time.time() else None
    except:
        return {}


from pathlib import Path
from typing import Tuple, Optional, Callable, Any

import numpy as np
from torchvision.datasets import CIFAR10

from definitions import DATASETS_DIR
from PIL import Image

class CIFAR10SSL(CIFAR10):
    """
    Dataset CIFAR10 adapted for semi-supervised learning.

    Adapts CIFAR10 dataset class provided by PyTorch by allowing a
    range which selects a subset of images for each class.

    CIFAR-10 dataset consists of 60k 32x32 colour images, from 10
    classes, 6k images per class. 50k are training images and 10k
    are test images. The home page of the dataset is provided
    in <https://www.cs.toronto.edu/~kriz/cifar.html> by the
    University of Toronto.
    """

    # number of examples per class in train and test
    per_class_train = 5000
    per_class_test = 1000

    def __init__(self,
                 root_path: str or Path,
                 train: bool,
                 data_range: Tuple[int, int],
                 weak_transform: Optional[Callable] = None,
                 strong_transform: Optional[Callable] = None,
                 target_transform: Optional[Callable] = None):
        """
        Constructor of CIFAR10SSL dataset object.

        :param root_path:
            path to store or look up data.
        :param train:
            get data from train set (50000 images) or from test set (10000 images).
        :param data_range:
            range of images to select from every class.
        """

        super(CIFAR10SSL, self).__init__(root=root_path,
                                         train=train,
                                         download=True,
                                         target_transform=target_transform)

        self.__order_data()
        self.data_range = data_range
        self.__resolve_data_range()
        self.shuffle_data()

        # weak and strong transformations
        self.weak_transform = weak_transform
        self.strong_transform = strong_transform

    def __getitem__(self, index: int) -> Tuple[Any, ...]:
        """
        Get example from dataset using index.

        :param index:
            index to search in database.

        :return:
            Image applying transformations if exists, and label.
        """

        # retrieve data based on index
        img, target = self.data[index], self.targets[index]

        # consistency with original implementation
        img = Image.fromarray(img)
        weak, strong = None, None

        # weak augmentation
        if self.weak_transform is not None:
            weak = self.weak_transform(img)
        # strong augmentation
        if self.strong_transform is not None:
            strong = self.strong_transform(img)

        # target transform
        if self.target_transform is not None:
            target = self.target_transform(target)

        # if no weak transformation original img is output
        weak = img if not self.weak_transform else weak

        # if not strong augmentation, usual return
        if not self.strong_transform:
            return weak, target

        return weak, strong, target

    def shuffle_data(self):
        """
        Shuffle both data and its targets randomly.
        """

        # obtain random permutation
        permutation = np.random.permutation(len(self))

        # apply permutation to data and targets
        self.targets = self.targets[permutation]
        self.data = self.data[permutation]

    def mean_and_std(self) -> Tuple[list, list]:
        """
        :return:
            mean and standard deviation of dataset per channel.
        """

        return ((self.data / 255).mean(axis=(0, 1, 2)),
                (self.data / 255).std(axis=(0, 1, 2)))

    def __order_data(self):
        """
        Order data sequentially by class index (0 to 9).
        """

        # get order from targets then apply it to data and targets
        order = np.asarray(self.targets).argsort()
        self.targets = np.asarray(self.targets)[order].astype(np.int64)
        self.data = self.data[order]

    def __resolve_data_range(self):
        """
        Select a reduced number of examples per class using a range.
        """

        # check if data_range is a tuple with 2 elements
        assert isinstance(self.data_range, tuple), 'range must be a tuple'
        assert len(self.data_range) == 2, 'range tuple must have exactly two integers'

        # check if both data_range elements are integers
        range_l, range_h = self.data_range
        assert isinstance(range_l, int) and isinstance(range_h, int), 'numbers must be integers'

        # check if data_range is within boundaries and valid
        max_val = self.per_class_train if self.train else self.per_class_test
        assert 0 <= range_l < range_h <= max_val, f'invalid range (max {max_val} img/class)'

        # select data and targets specified by validated data_range
        ids = [idx + max_val * nclass for nclass in range(len(self.classes)) for idx in range(range_l, range_h)]
        self.data = self.data[ids]
        self.targets = self.targets[ids]

class CIFAR100SSL(CIFAR10SSL):
    """
    Dataset CIFAR100 adapted for semi-supervised learning.

    Adapts CIFAR100 dataset class provided by PyTorch by allowing a
    range which selects a subset of images for each class.

    CIFAR-100 dataset consists of 60k 32x32 colour images, from 100
    classes, 600 images per class. 50k are training images and 10k
    are test images. The home page of the dataset is provided
    in <https://www.cs.toronto.edu/~kriz/cifar.html> by the
    University of Toronto.

    This is a subclass of the `CIFAR10SSL` Dataset.
    """

    base_folder = "cifar-100-python"
    url = "https://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz"
    filename = "cifar-100-python.tar.gz"
    tgz_md5 = "eb9058c3a382ffc7106e4002c42a8d85"
    train_list = [
        ["train", "16019d7e3df5f24257cddd939b257f8d"],
    ]

    test_list = [
        ["test", "f0ef6b0ae62326f3e7ffdfab6717acfc"],
    ]
    meta = {
        "filename": "meta",
        "key": "fine_label_names",
        "md5": "7973b15100ade9c7d40fb424638fde48",
    }

    # number of examples per class in train and test
    per_class_train = 500
    per_class_test = 100

if __name__ == "__main__":
    path = DATASETS_DIR / 'cifar10'
    cifar10ds = CIFAR10SSL(root_path=path,
                           train=True,
                           data_range=(0, 5000))
    print('Total number of images in dataset: ', len(cifar10ds))
    print('Total number of classes in dataset: ', len(cifar10ds.classes))
    mean, std = cifar10ds.mean_and_std()
    print(f"""
    Mean +/- Std: {mean} +/- {std}
    """)

    path1 = DATASETS_DIR / 'cifar100'
    cifar100ds = CIFAR100SSL(root_path=path1,
                             train=True,
                             data_range=(0, 500))
    print('Total number of images in dataset: ', len(cifar100ds))
    print('Total number of classes in dataset: ', len(cifar100ds.classes))
    mean, std = cifar100ds.mean_and_std()
    print(f"""
    Mean +/- Std: {mean} +/- {std}
    """)


import django
import pdoc
import os
import pathlib

if __name__ == "__main__":
    os.environ["DJANGO_SETTINGS_MODULE"] = "ecstasy_project.settings"
    django.setup()

    doc = pdoc.pdoc(
        "app_settings",
        "!app_settings.migration",
        "check",
        "!check.migration",
        "!check.tests",
        "devicemanager",
        "!devicemanager.tests",
        "net_tools",
        "!net_tools.migration",
        "maps",
        "!maps.migration",
        "gathering",
        "!gathering.migration",
        "ring_manager",
        "!ring_manager.migration",
        output_directory=pathlib.Path(__file__).parent / "static" / "docs",
    )


import cv2
import numpy as np
dictionary = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_250)

cap = cv2.VideoCapture(3)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)

curr_x = 400
curr_y = 70 + 50
while True:
    ret, img = cap.read()
    print(img)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    res = cv2.aruco.detectMarkers(gray, dictionary)
    if res is not None:
        if 83 in res[1]:
            index = np.where(res[1] == 83)[0][0]
            x1 = (res[0][index][0][0][0] + res[0][index][0][2][0])//2
            y1 = (res[0][index][0][0][1] + res[0][index][0][2][1])//2
            cv2.circle(img, (int(x1), int(y1)), 10, (0, 0, 255), -1)
    cv2.imshow("asd.png", img)
    if cv2.waitKey(25) & 0xFF == ord('s'):
        with open('r.txt', 'a') as fd:
            fd.write(f"{curr_x} {curr_y} {x1} {y1}")
            fd.write('\n')
        curr_x += 50
        if curr_x >= 2800:
            curr_x = 200
            curr_y += 50
        if curr_y >= 2000:
            print("Finish")


#Crie um programa que leia dois valores e mostre um menu na tela:
#[ 1 ] somar
#[ 2 ] multiplicar
#[ 3 ] maior
#[ 4 ] novos números
#[ 5 ] sair do programa
#Seu programa deverá realizar a operação solicitada em cada caso.

n1 = int(input('Digite o valor 1: '))
n2 = int(input('Digite o valor 2: '))
opcao = 0
calc = 0
print('MENU')
print('[1]Somar \n[2]Multiplicar \n[3]Maior \n[4]Novos números \n[5]Sair do programa \n')
while opcao != 5:
    opcao = int(input('Digite uma opção: '))
    if opcao == 1:
       calc = n1 + n2
       print('Soma dos valores: {}'.format(calc))
    elif opcao == 2:
        calc = n1 * n2
        print('Multiplicação dos valores: {}'.format(calc))
    elif opcao == 3:
        if n1 > n2:
            print('{} é maior que {}'.format(n1, n2))
        elif n2 > n1:
            print('{} é maior que {}'.format(n2, n1))
        else:
            print('{} e {} são iguais'.format(n1, n2))
    elif opcao == 4:
        n1 = int(input('Digite o novo valor de 1: '))
        n2 = int(input('Digite o novo valor de 2: '))
print('FIM DO PROGRAMA')


#!/usr/bin/python3
"""
sends a request to URL and displays the body
of the response (decoded in utf-8)
prints error code for urllib.error.HTTPError
"""
import urllib.request
import sys

if __name__ == "__main__":
    try:
        with urllib.request.urlopen(sys.argv[1]) as response:
            html = response.read()
            dc = html.decode('utf8')
        print(dc)

    except urllib.error.HTTPError as e:
        print("Error code: {}".format(e.code))


#!/usr/bin/env python3

m = []
with open("input.txt") as fh:

    for line in fh:
        tmp = []
        for n in line.strip():
           tmp.append(int(n))
        m.append(tmp)

print(m)

h = len(m)
w = len(m[0])

s = []
l = [(1,0),(0,1),(-1,0),(0,-1)]

for y in range(h):
    for x in range(w):
        me = m[y][x]
        fnord = []

        for pos in l:
            (i,j) = pos
            tY = y - i
            tX = x - j

            if (tX < 0 or tY < 0 or
                (tX >= w  or tY >= h ) or
                (i == 0 and j == 0)) :
                continue

            fnord.append(m[tY][tX])

        foo = min(fnord)
        if foo > me:
            s.append(me+1)

print(sum(s))


'''
Main data structures of blockchain.

Rather than fully decode the data into python object,
we access the required fields from cbor data.
It's more efficient this way at most scenario.

We also try to cache raw data, to prevent re-serialization.
'''
import cbor
import base64
import binascii
import itertools
from collections import defaultdict
from .utils import hash_serialized, hash_data, verify
from .address import Address, AddressContent
from .random import Random
from . import config

class DecodedBase(object):
    def __init__(self, data, raw=None, hash=None):
        self.data = data
        self._raw = raw
        self._hash = hash

    @classmethod
    def from_raw(cls, raw, hash=None):
        return cls(cbor.loads(raw), raw, hash)

    def raw(self):
        if not self._raw:
            self._raw = cbor.dumps(self.data)
        return self._raw

    def hash(self):
        if not self._hash:
            self._hash = hash_serialized(self.raw())
        return self._hash

class DecodedBlockHeader(DecodedBase):
    def prev_header(self):
        return self.data[1][1]

    def slot(self):
        '''
        (epoch, slotid)

        slotid: None means genesis block.
        '''
        if self.is_genesis():
            epoch = self.data[1][3][0]
            slotid = None
        else:
            epoch, slotid = self.data[1][3][0]
        return epoch, slotid

    def is_genesis(self):
        return self.data[0] == 0

    def difficulty(self):
        if self.is_genesis():
            n, = self.data[1][3][1]
        else:
            n, = self.data[1][3][2]
        return n

    def tx_count(self):
        if not self.is_genesis():
            return self.data[1][2][0][0]

    def protocol_magic(self):
        return self.data[1][0]

    def leader_key(self):
        assert not self.is_genesis()
        return self.data[1][3][1]

    def unknowns(self):
        return self.data[1][4][2]

class DecodedTransaction(DecodedBase):
    @classmethod
    def build(cls, inputs, outputs, attrs=None):
        '''
        inputs: [(txid, ix)]
        outputs: [(address, n)]
        '''
        data = (
            cbor.VarList([  # inputs
                (0, cbor.Tag(24, cbor.dumps((txid, ix))))
                for txid, ix in inputs
            ]),
            cbor.VarList([  # outputs
                (cbor.loads(Address.decode_base58(addr).encode()), c)
                for addr, c in outputs
            ]),
            attrs or {}  # attrs
        )
        return cls(data)

    def tx(self):
        from .wallet import Tx
        return Tx(self.hash(), self.inputs(), self.outputs())

    def inputs(self):
        from .wallet import TxIn
        return set(TxIn(*cbor.loads(item.value))
                   for tag, item in self.data[0]
                   if tag == 0)

    def outputs(self):
        from .wallet import TxOut
        return [TxOut(cbor.dumps(addr), c)
                for addr, c in self.data[1]]

class DecodedTxAux(DecodedBase):
    '(Tx, TxWitness)'
    @classmethod
    def build(cls, tx, witnesses):
        '''
        witnesses: [(pubkey, signature)]
        '''
        assert len(tx.inputs()) == len(witnesses)
        return cls((
            tx.data,
            [(0, cbor.Tag(24, cbor.dumps((pk, sig))))
             for pk, sig in witnesses]
        ))

    def transaction(self):
        return DecodedTransaction(self.data[0])

    def verify(self, undo):
        '''
        undo: [TxOut]
        '''
        for txin, wit, out in itertools.zip_longest(
                self.transaction().inputs(),
                self.data[1],
                undo):
            if wit[0] != 0:
                print('only support pubkey witness')
                return False
            pk, sig = cbor.loads(wit[1].value)
            if not out:
                return False
            addr = Address.decode(out.addr)
            if not addr.verify_pubkey(pk):
                return False
            if not verify('tx', pk, sig, hash_data(self.data[0])):
                print('sig verify fail')
                return False
        return True

class DecodedBlock(DecodedBase):
    def header(self):
        return DecodedBlockHeader([self.data[0], self.data[1][0]])

    def is_genesis(self):
        return self.data[0] == 0

    def transactions(self):
        assert not self.is_genesis()
        # GenericBlock -> MainBody -> [(Tx, TxWitness)]
        return [DecodedTransaction(tx) for tx, _ in self.data[1][1][0]]

    def txaux(self):
        assert not self.is_genesis()
        # GenericBlock -> MainBody -> [(Tx, TxWitness)]
        return [DecodedTxAux(data) for data in self.data[1][1][0]]

    def txs(self):
        'Transaction list in wallet format.'
        return map(lambda t: t.tx(), self.transactions())

    def utxos(self):
        'Set of inputs spent, and UTxO created.'
        from .wallet import TxIn
        txins = set()
        utxo = {}
        # Process in reversed order, so we can remove inputs spent by current block.
        for t in reversed(self.transactions()):
            tx = t.tx()
            for idx, txout in enumerate(tx.outputs):
                # new utxo
                txin = TxIn(tx.txid, idx)
                if txin not in txins:
                    utxo[txin] = txout
            for txin in tx.inputs:
                txins.add(txin)
        return txins, utxo

    def unknowns(self):
        return self.data[1][2][0]

    def leaders(self):
        assert self.is_genesis()
        return self.data[1][1]

def genesis_block(prev_header, epoch, leaders):
    'create genesis block'
    return DecodedBlock([
        0,
        [[
            config.PROTOCOL_MAGIC,
            prev_header.hash(),
            hash_data(leaders),
            [epoch, prev_header.difficulty()],
            {}
        ], leaders],
        {}
    ])

def avvm_pk(s):
    s = s.replace('_', '/').replace('-', '+')
    s = base64.b64decode(s)
    assert len(s) == 32
    return s

def genesis_balances():
    return [(AddressContent.redeem(avvm_pk(k)).address(), int(v))
            for k, v in config.GENESIS['avvmDistr'].items()] + \
        [(Address.decode_base58(k), int(v))
         for k, v in config.GENESIS['nonAvvmBalances'].items()]

def bootstrap_distr(c):
    # bootstrap
    stakeholders = config.GENESIS['bootStakeholders']
    sum_weight = sum(stakeholders.values())
    result = []
    if c < sum_weight:
        for holder, weight in stakeholders.items():
            result.append((binascii.unhexlify(holder), min(c, weight)))
            c -= weight
            if c < 0:
                break
    else:
        d, m = divmod(c, sum_weight)
        stakes = [weight * d for _, weight in stakeholders.items()]
        if m > 0:
            ix = Random(hash_data(m)).number(len(stakeholders))
            stakes[ix] += m
        result = zip(map(binascii.unhexlify, stakeholders.keys()), stakes)

    return result

def addr_stakes(addr, c):
    dist = addr.attrs.get(0)
    if dist is None:
        return bootstrap_distr(c)
    else:
        # TODO
        assert False

def genesis_stakes():
    stakes = defaultdict(int)
    for addr, c in genesis_balances():
        for holder, n in addr_stakes(addr, c):
            stakes[holder] += n
    return stakes

def fts(slotcount, seed, coinsum, stakelist):
    'if stakelist is consistant with coinsum, no exception'
    assert coinsum > 0

    # generate coin indexes.
    rnd = Random(seed)
    indices = [(slot, rnd.number(coinsum)) for slot in range(slotcount)]
    indices.sort(key=lambda t: t[1])  # sort by coin index

    leaders = []
    it = iter(stakelist)
    current_holder, upper_range = next(it)
    for slot, idx in indices:
        while True:
            if idx <= upper_range:
                leaders.append((slot, current_holder))
                break

            current_holder, c = next(it)
            upper_range += c

    assert len(leaders) == slotcount
    leaders.sort(key=lambda t: t[0])  # sort by slot index
    return [leader for _, leader in leaders]

def genesis_block0():
    'create the first genesis block from config.'
    stakes = genesis_stakes().items()
    # TODO cardano-sl used HM.toList to sort genesis stakes, so...
    leaders = fts(
        config.GENESIS['protocolConsts']['k'] * 10,
        config.GENESIS['ftsSeed'].encode(),
        sum(n for _, n in stakes),
        stakes,
    )
    return DecodedBlock([
        0,
        [[
            config.PROTOCOL_MAGIC,
            config.GENESIS_HASH,
            hash_data(leaders),
            [0, 0],
            {}
        ], leaders],
        {}
    ])

if __name__ == '__main__':
    config.use('mainnet')
    blk = genesis_block0()
    leaders = blk.leaders()

    from cardano.storage import Storage
    store = Storage('test_db')
    db_leaders = store.genesis_block(0).leaders()

    # compare with official result.
    for i in range(10):
        print(leaders[i], db_leaders[i])


with open("igfollowers.csv", "r") as f:
    lines = f.readlines()
    newlines = [line.replace(",", "").replace("\t", ",") for line in lines]
    print(newlines)
    # print(lines)

with open("igfollowersclean.csv", "w") as clean:
    clean.writelines(newlines)


from django.conf.urls import patterns, include, url
from dogapp.views import search, listall, addNew

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'Roverexample.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
	#url(r'^time/$', current_datetime),

    url(r'^admin/', include(admin.site.urls)),
	url(r'^search/$', search),
	url(r'^listall/$', listall),
	url(r'^addNew/$', addNew),
)


import seaborn as sns
import numpy as np

def buildColorMap(n_trial_data, min_nFrames, groupByFly = False):
    # Extract classes for each fly (1 = MDN, 2 = SS01049...)
    classes = [] # List of colours attributed to each strain for later plotting
    strains = [] # Strain corresponding to each fly
    unique_classes = [] # Unique version of 'classes'

    if groupByFly:
        nObservationsPerStrain = list(n_trial_data.values())
    else:
        nObservationsPerStrain = [val*min_nFrames for val in n_trial_data.values()]

    for i, key in enumerate(n_trial_data.keys()):
        unique_classes.append(sns.color_palette()[i])

        for j in range(nObservationsPerStrain[i]):
            classes.append(sns.color_palette()[i])
            strains.append(key)

    classes = np.array(classes)
    strains = np.array(strains)
    unique_classes = np.array(unique_classes)

    return classes, strains, unique_classes


import pyaudio
import numpy as np
import wave
import math
import random

from time import sleep

import pylab as pl

random.seed()

CHUNK = 256
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 48000
MAX_AMP = 2**15 - 1

class Audio(pyaudio.PyAudio):

    def __init__(self, channels=1,
                 rate=RATE,
                 chunk=CHUNK,
                 format=FORMAT):
        pyaudio.PyAudio.__init__(self)

        self.chan = channels
        self.rate = rate
        self.chunk = chunk
        self.format = format
        self.nptype = self.get_np_type(format)

        self.data = np.array([], dtype=self.nptype)

        self.istream = None
        self.ostream = None

        self.chunk_index = 0

    def __del__(self):
        self.terminate()

    def get_chunk(self):
        tmpstr = self.istream.read(self.chunk)
        array = np.fromstring(tmpstr, dtype=self.nptype)
        self.data = np.append(self.data, array)

    def put_chunk(self):
        slice_from = self.chunk_index*self.chunk
        slice_to = min(self.data.shape[0], slice_from + self.chunk)

        if slice_from > self.data.shape[0]:
            raise IndexError
        array = self.data[slice_from:slice_to]
        self.ostream.write(array.tostring())
        self.chunk_index += 1

    def open_input_stream(self):
        self.istream = self.open(format=self.format,
                                 channels=self.chan,
                                 rate=self.rate,
                                 input=True,
                                 frames_per_buffer=self.chunk)

    def close_input_stream(self):
        self.istream.close()
        self.istream = None

    def open_output_stream(self):
        self.ostream = self.open(format=self.format,
                                 channels=self.chan,
                                 rate=self.rate,
                                 output=True)
        self.chunk_index = 0

    def close_output_stream(self):
        self.ostream.close()
        self.ostream = None

    def record(self, time=5.0):
        self.data = np.array([], dtype=self.nptype)
        self.open_input_stream()
        print("Recording...")
        for i in range(0, int(time * self.rate/self.chunk)):
            self.get_chunk()
        print("Done Recording")
        self.close_input_stream()

    def play(self):
        self.open_output_stream()
        self.chunk_index = 0
        print("Playing...")
        while True:
            try:
                self.put_chunk()
            except IndexError:
                break

        sleep(0.4)
        self.close_output_stream()

    def save(self, path):
        raw = self.data.tostring()
        wf = wave.open(path, 'wb')
        wf.setnchannels(self.chan)
        wf.setsampwidth(self.get_sample_size(self.format))
        wf.setframerate(self.rate)
        wf.writeframes(raw)
        wf.close()

    def load(self, path):
        wf = wave.open(path, "rb")
        self.format = self.get_format_from_width(wf.getsampwidth())
        self.nptype = self.get_np_type(self.format)
        self.chan = wf.getnchannels()
        self.rate = wf.getframerate()
        self.data = np.array([], dtype=self.nptype)
        raw = wf.readframes(self.chunk)
        while raw:
            array = np.fromstring(raw, dtype=self.nptype)
            self.data = np.append(self.data, array)
            raw = wf.readframes(self.chunk)
        wf.close()

    def get_np_type(self, type):
        if type == pyaudio.paInt16:
            return np.int16

    def get_pa_type(self, type):
        if type == np.int16:
            return pyaudio.paInt16

    def add_echo(self, repeat, delay):
        length = self.data.shape[0]
        array = np.zeros(length + repeat*delay, dtype=np.float)

        for i in range(0, repeat+1):
            start = i*delay
            end = length + i*delay
            scale = 2**(i+1)
            array[start:end] += self.data / scale
        self.data = np.rint(array).astype(self.nptype)

    def rescale(self, val):
        if not 0 <= val <= 1:
            raise ValueError("Expected scaling factor between 0 and 1")

        peak = np.max(np.abs(self.data))

        rescale_factor = val*MAX_AMP/peak

        self.data = (self.data * rescale_factor).astype(self.nptype)

    def create_tone(self, frequency, length, amplitude):
        if not 0 <= amplitude <= 1:
            raise ValueError("Expected amplitude between 0 and 1")

        s = np.zeros(length, self.nptype)

        for i in range(0, length):
            s[i] = amplitude * MAX_AMP \
                   * math.sin(frequency * i * 2 * math.pi/self.rate)

        self.data = s

    def create_noise(self, length, amplitude):

        if not 0 <= amplitude <= 1:
            raise ValueError("Expected amplitude between 0 and 1")

        s = np.zeros(length, self.nptype)

        for i in range(0, length):
            s[i] = amplitude * MAX_AMP * random.random()

        self.data = s

    def add(self, other):
        length = max(self.data.shape[0], other.data.shape[0])
        array = np.zeros(length, dtype=self.nptype)
        array += self.data / 2.0
        array += other.data / 2.0
        self.data = array

    def __len__(self):
        return self.data.shape[0]

    def get_samplerange(self):
        if self.nptype == np.int16:
            return math.pow(2, 16)

    def compute_fft(self, start, end):
        dur = end - start
        fft = pl.fft(self.data[start:end])
        real_range = np.ceil((dur+1)/2.0)
        fft = fft[0:real_range]
        fft = abs(fft)

        return fft * np.hanning(len(fft))

    def change_speed(self, factor):
        indxs = np.round(np.arange(0, len(self.data), factor))
        indxs = indxs[indxs < len(self.data)].astype(int)
        self.data = self.data[indxs]

    def time_stretch_fft(self, factor, windowsize=1024, overlap=512, apply_hanning=True):
        phase = np.zeros(windowsize)
        if apply_hanning:
            amp_window = np.hanning(windowsize)
        else:
            amp_window = np.ones(windowsize, dtype=np.float)
        result = np.zeros(int(len(self.data) / factor + windowsize))

        for i in np.arange(0, len(self.data)-(windowsize+overlap), overlap*factor, dtype=np.int):
            a1 = self.data[i: i + windowsize]
            a2 = self.data[i + overlap: i + windowsize + overlap]

            s1 = np.fft.fft(amp_window * a1)
            s2 = np.fft.fft(amp_window * a2)
            phase = (phase + np.angle(s2/s1)) % 2*np.pi
            a2_rephased = np.fft.ifft(np.abs(s2)*np.exp(1j*phase))

            i2 = int(i/factor)
            result[i2:i2 + windowsize] += amp_window*np.real(a2_rephased)
        result = ((2**(16-4)) * result/result.max())

        self.data = result.astype(self.nptype)

    def plot_waveform(self, start=0, end=-1, x_unit="samples"):
        array = self.data[start:end]
        num_samples = len(array)
        if x_unit == "samples":
            pl.plot(range(num_samples), array)
            pl.xlabel('Time (Samples)')
        elif x_unit == "time":
            end_time = self.samples_to_time(num_samples)
            y_steps = np.arange(0, end_time, float(end_time) / num_samples)
            pl.plot(y_steps, array)
            pl.xlabel('Time (s)')
        pl.ylabel('Amplitude')
        samplerange = self.get_samplerange()
        pl.ylim([-samplerange/2, samplerange/2])
        pl.show()

    def plot_spectrum(self, array, start=0, end=-1, plot_log=False):
        array = array[start:end]
        len_arr = len(array)
        freq_axis = np.arange(0, len_arr, 1.0)  # * (self.rate / len_arr)
        if plot_log:
            pl.plot(freq_axis/1000, 10*np.log10(array), color='k')
            pl.ylabel('Power (dB)')
        else:
            pl.plot(freq_axis/1000, array, color='k')
        pl.xlabel('Frequency (kHz)')
        pl.show()

def sum_audio(audio_objects):
    length = len(max(audio_objects, key=len))
    scale = 1.0/len(audio_objects)

    array = np.zeros(length, dtype=np.int16)

    for obj in audio_objects:
        array += np.rint(obj.data * scale).astype(np.int16)

    new_object = Audio()
    new_object.data = array

    return new_object

def test_add():
    c = Audio()
    e = Audio()
    g = Audio()

    c.create_tone(261.63, 240000, 0.8)
    e.create_tone(329.63, 240000, 0.8)
    g.create_tone(392.00, 240000, 0.8)

    chord = sum_audio((c, e, g))

    chord.play()

if __name__ == "__main__":
    d = Audio()
    d.load('kdt48.wav')
    d.time_stretch_fft(0.9, 4096, 256)
    d.play()


"""
Function to slice trainging/testing/validation data

Notes
-----
Author  : Zachary Labe
Date    : 9 September 2022
Version : 1

Usage
-----
[1] segment_data(data,fac,random_segment_seed)
"""

###############################################################################
###############################################################################
###############################################################################
### Select data to test, train on
def segment_data(data,classesl,ensTypeExperi,fac,random_segment_seed):
    """
    Function to segment data based on ensemble members

    Usage
    -----
    segment_data(data,classesl,ensTypeExperi,fac,random_segment_seed)
    """
    print('\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Using segment_data function!\n')

    ### Import modules
    import numpy as np
    import sys
    import tensorflow.keras as keras

    ### Create class weights
    def class_weight_creator(Y):
        class_dict = {}
        weights = np.max(np.sum(Y, axis=0)) / np.sum(Y, axis=0)
        for i in range( Y.shape[-1] ):
            class_dict[i] = weights[i]
        return class_dict

    if random_segment_seed == None:
        random_segment_seed = int(int(np.random.randint(1, 100000)))
    np.random.seed(random_segment_seed)

###############################################################################
###############################################################################
###############################################################################
    ###################################################################
    ### Large Ensemble experiment
    if ensTypeExperi == 'ENS':

        ### Flip GCM and ensemble member axes
        datanew = np.swapaxes(data,0,1)
        classeslnew = np.swapaxes(classesl,0,1)

    if fac < 1 :
        nrows = datanew.shape[0]
        segment_train = int(np.round(nrows * fac))
        segment_val = int(nrows*(1-fac)-1)
        segment_test = nrows - segment_train - segment_val
        print('--------------------------------------------------------------------')
        print('Training on',segment_train,'ensembles, Testing on',segment_test,'ensembles, Validation on',segment_val,'ensembles')
        print('--------------------------------------------------------------------')

        ### Picking out random ensembles for training/testing/validation
        i = 0
        trainIndices = list()
        while i < segment_train:
            line = np.random.randint(0, nrows)
            if line not in trainIndices:
                trainIndices.append(line)
                i += 1
            else:
                pass

        i = 0
        testIndices = list()
        while i < segment_test:
            line = np.random.randint(0, nrows)
            if line not in trainIndices:
                if line not in testIndices:
                    testIndices.append(line)
                    i += 1
            else:
                pass

        i = 0
        valIndices = list()
        while i < segment_val:
            line = np.random.randint(0, nrows)
            if line not in trainIndices:
                if line not in testIndices:
                    if line not in valIndices:
                        valIndices.append(line)
                        i += 1
            else:
                pass

###############################################################################
###############################################################################
###############################################################################
        ### Training segment----------
        data_train = np.empty((len(trainIndices),datanew.shape[1],
                                datanew.shape[2],datanew.shape[3],
                                datanew.shape[4]))
        Ytrain = np.empty((len(trainIndices),classeslnew.shape[1],
                            classeslnew.shape[2]))
        for index,ensemble in enumerate(trainIndices):
            data_train[index,:,:,:,:] = datanew[ensemble,:,:,:,:]
            Ytrain[index,:,:] = classeslnew[ensemble,:,:]

        ### Random ensembles are picked
        print('\n----------------------------------------')
        print('Training on ensembles: ',trainIndices)
        print('Testing on ensembles: ',testIndices)
        print('Validation on ensembles: ',valIndices)
        print('----------------------------------------')
        print('\n----------------------------------------')
        print('org data - shape', datanew.shape)
        print('training data - shape', data_train.shape)

        ### Reshape into X and Y
        Xtrain = data_train.reshape((data_train.shape[0]*data_train.shape[1]*data_train.shape[2]),(data_train.shape[3]*data_train.shape[4]))
        Ytrain = Ytrain.reshape((Ytrain.shape[0]*Ytrain.shape[1]*Ytrain.shape[2]))
        Xtrain_shape = (data_train.shape[0],data_train.shape[1])

###############################################################################
###############################################################################
###############################################################################
        ### Testing segment----------
        data_test = np.empty((len(testIndices),datanew.shape[1],
                                datanew.shape[2],datanew.shape[3],
                                datanew.shape[4]))
        Ytest = np.empty((len(testIndices),classeslnew.shape[1],
                            classeslnew.shape[2]))
        for index,ensemble in enumerate(testIndices):
            data_test[index,:,:,:,:] = datanew[ensemble,:,:,:,:]
            Ytest[index,:,:] = classeslnew[ensemble,:,:]

        ### Random ensembles are picked
        print('----------------------------------------\n')
        print('----------------------------------------')
        print('Training on ensembles: count %s' % len(trainIndices))
        print('Testing on ensembles: count %s' % len(testIndices))
        print('Validation on ensembles: count %s' % len(valIndices))
        print('----------------------------------------\n')

        print('----------------------------------------')
        print('org data - shape', datanew.shape)
        print('testing data - shape', data_test.shape)
        print('----------------------------------------')

        ### Reshape into X and Y
        Xtest= data_test.reshape((data_test.shape[0]*data_test.shape[1]*data_test.shape[2]),(data_test.shape[3]*data_test.shape[4]))
        Ytest = Ytest.reshape((Ytest.shape[0]*Ytest.shape[1]*Ytest.shape[2]))
        Xtest_shape = (data_test.shape[0],data_test.shape[1])

###############################################################################
###############################################################################
###############################################################################
        ### Validation segment----------
        data_val = np.empty((len(valIndices),datanew.shape[1],
                                datanew.shape[2],datanew.shape[3],
                                datanew.shape[4]))
        Yval = np.empty((len(valIndices),classeslnew.shape[1],
                            classeslnew.shape[2]))
        for index,ensemble in enumerate(valIndices):
            data_val[index,:,:,:,:] = datanew[ensemble,:,:,:,:]
            Yval[index,:,:] = classeslnew[ensemble,:,:]

        ### Random ensembles are picked
        print('\n----------------------------------------')
        print('Training on ensembles: count %s' % len(trainIndices))
        print('Testing on ensembles: count %s' % len(testIndices))
        print('Validation on ensembles: count %s' % len(valIndices))
        print('----------------------------------------\n')
        print('----------------------------------------')
        print('org data - shape', datanew.shape)
        print('Validation data - shape', data_val.shape)
        print('----------------------------------------')

        ### Reshape into X and Y
        Xval= data_val.reshape((data_val.shape[0]*data_val.shape[1]*data_val.shape[2]),(data_val.shape[3]*data_val.shape[4]))
        Yval = Yval.reshape((Yval.shape[0]*Yval.shape[1]*Yval.shape[2]))
        Xval_shape = (data_val.shape[0],data_val.shape[1])

        ### One-hot vectors
        Ytrain = keras.utils.to_categorical(Ytrain)
        Ytest = keras.utils.to_categorical(Ytest)
        Yval = keras.utils.to_categorical(Yval)

        ### Class weights
        class_weight = class_weight_creator(Ytrain)

    else:
        print(ValueError('WRONG EXPERIMENT!'))
    return Xtrain,Ytrain,Xtest,Ytest,Xval,Yval,Xtrain_shape,Xtest_shape,Xval_shape,testIndices,trainIndices,valIndices,class_weight


"""
:type  param_1: {String}
:rtype: string
"""

def checkCase(res, start, end, ch):
    rev = 25;
    while (start <= end):
        if (ord(ch) == start):
            res.append(chr(ord(ch) + rev))
        rev -= 2;
        start += 1;

def alpha_mirror(str):
    res = []
    for ch in str:
        if (ord(ch) >= 97 and ord(ch) <= 122):
            checkCase(res, 97, 122, ch)
        elif (ord(ch) >= 65 and ord(ch) <= 90):
            checkCase(res, 65, 90, ch)
        else:
            res.append(ch)
    return "".join(res)

# str = "Nb slihv rh Znzarmt."
# str = "My horse is Amazing."
# str = "abc"
print(alpha_mirror(str))