# 画图用到的函数
# liyi，2019/7/1

import numpy as np

def smooth(step,value,window=10000,overlap=0.2):
    # 对 episode value 进行加窗平滑 7/1
    # 返回窗内的均值和标准差
    smooth_step = []
    smooth_value_mean = []
    smooth_value_std = []
    down_limit = 0
    up_limit = window
    count = 0
    while up_limit<=step[-1]:
        smooth_step += [count]
        temp_value = value[np.array(step>=down_limit) & np.array(step<up_limit)]
        smooth_value_mean += [temp_value.mean()]
        smooth_value_std += [temp_value.std()]
        count += 1
        down_limit += window*overlap
        up_limit += window*overlap
    #print(len(smooth_step))
    #print(smooth_value_mean)
    #print(smooth_value_std)
    return np.array(smooth_step), np.array(smooth_value_mean), np.array(smooth_value_std)

def smooth2(reward, window=10):
    down_limit = 0
    up_limit = window
    smooth_reward = []
    while up_limit <= len(reward):
        temp_reward = reward[down_limit:up_limit]
        smooth_reward += [temp_reward.mean()]
        down_limit += window
        up_limit += window

    return smooth_reward

def statistic(value_list):
    # 输入的是一个 list，每个元素都是一组平滑处理后的 episode value 实验数据
    # 返回多个实验的均值和方差
    lengthes = [len(v) for v in value_list]
    length = min(lengthes)
    value_list = [v[0:length] for v in value_list]
    value = np.stack(value_list)
    value_mean = value.mean(axis=0)
    value_std = value.std(axis=0)
    return value_mean, value_std


from typing import Dict, List, Set, Tuple, Optional, Any, Callable, NoReturn, Union, Mapping, Sequence, Iterable
from transformers import AutoTokenizer, AutoModelForCausalLM

# either GPT2 or another Question answering or text generation model
# https://colab.research.google.com/github/philschmid/fine-tune-GPT-2/blob/master/Fine_tune_a_non_English_GPT_2_Model_with_Huggingface.ipynb
# https://towardsdatascience.com/fine-tuning-gpt2-for-text-generation-using-pytorch-2ee61a4f1ba7
# https://towardsdatascience.com/natural-language-generation-part-2-gpt-2-and-huggingface-f3acb35bc86a
# text generation pe engleza(gpt2): gpt2
# question answering squad2 pe engleza (roberta): deepset/roberta-base-squad2
# perceiver multimodal to be tried

import pdb

def main():
    ro_gpt2_models = ["readerbench/RoGPT2-base", "readerbench/RoGPT2-large", "readerbench/RoGPT2-medium"]
    print(ro_gpt2_models)
    tokenizer = AutoTokenizer.from_pretrained('readerbench/RoGPT2-base')
    model = AutoModelForCausalLM.from_pretrained('readerbench/RoGPT2-base')
    inputs = tokenizer.encode("Este o zi de vara", return_tensors='pt')
    text = model.generate(inputs, max_length=1024, no_repeat_ngram_size=2)
    print(tokenizer.decode(text[0]))

    """
    input:
    Este o zi de vara
    output:
    Este o zi de vara, cu soare, în care soarele strălucește în toată splendoarea sa.
    Este ziua în amiaza mare, când soarele răsare la amiază. În această zi, soarele este la fel de strălucitor ca
    și luna.<|endoftext|>
    """

if __name__ == "__main__":
    main()


def evalRPN(tokens):
    """
    :type tokens: List[str]
    :rtype: int
    """
    stack = []
    valid_signs = ['+', '-', '*', "/"]

    for index, num in enumerate(tokens):
        if num in valid_signs:
            num1= int(stack.pop())
            num2= int(stack.pop())

            if num == "+":
                temp = num2 + num1
            elif num == "-":
                temp = num2 - num1
            elif num == "*":
                temp = num2 * num1
            elif num == "/":
                temp = int(float(num2)/num1)

            stack.append(temp)

        else:
            stack.append(int(num))

    return stack[0]

print(evalRPN(["10","6","9","3","+","-11","*","/","*","17","+","5","+"]))


from __future__ import unicode_literals
"""
A simplified client to notarising documents on the Bitcoin blockchain.

Uses the Ascribe.io SPOOL library to
 - manage generating addresses,
 - selecting tx inputs/outputs and
 - building txs

"""
from spool import Spool
from spool import Wallet

from bitcoin import bin_hash160, bin_to_b58check

import hashlib
from builtins import object, str, super
import sys
import os

_magicbyte = 111
spool = Spool()
min_confirmations = 0

# Federation wallet is responsible for maintaining a list of addresses that contain just enough Bitcoin for sending custom OP_RETURN transactions.

def fund_federation_wallet(fed_wallet, fund_wallet, fund_wallet_secret):
	from_address = fund_wallet.root_address[1]
	to_address = fed_wallet.root_address[1]
	nfees = int(os.environ.get('NFEES'))
	ntokens = int(os.environ.get('NTOKENS'))

	unsigned_tx = spool._t.simple_transaction(from_address,
											 [(to_address, spool.FEE)] * nfees + [(to_address, spool.TOKEN)] * ntokens,
											 min_confirmations=min_confirmations)
	signed_tx = spool._t.sign_transaction(unsigned_tx, fund_wallet_secret)
	return signed_tx

# Generate tx to notarise data on blockchain
def generate_notarise_tx(fed_address, fed_pass, data_to_notarise):
	unsigned_tx = spool.simple_spool_transaction(fed_address,
                                                [fed_address],
                                                op_return=str(data_to_notarise),
                                                min_confirmations=min_confirmations)

	signed_tx = spool._t.sign_transaction(unsigned_tx, fed_pass)

	return signed_tx

# def generate_unqiue_addr_for_path(wallet, path):
# 	gendPath, addr = wallet.address_from_path(path)
# 	print("Generated address %s from %s" % addr, gendPath)

def gen_address_for_data(data):
	print("Hashing data: "+str(data))

	# https://gist.github.com/patricklodder/b27fb3e91c0566272976#file-gistfile1-py-L390
	# RIPEMD160(SHA256(data))
	fingerprint = bin_hash160(data.encode())
	print("Data fingerprint: "+str(fingerprint.encode('hex')))

	address = str(bin_to_b58check(fingerprint), magicbyte=_magicbyte)
	print("Final address: "+str(address))

	return address

def push_tx(tx):
	tx_id = spool._t.push(tx)
	print("Pushed tx %s" % tx_id)
	return tx_id

if __name__ == "__main__":
	cmd = sys.argv[1]

	FUND_WALLET_SECRET = os.environ.get('FUND_WALLET_SECRET')
	FEDERATION_WALLET_SECRET = os.environ.get('FED_WALLET_SECRET')

	fund_wallet = Wallet(FUND_WALLET_SECRET)
	fed_wallet = Wallet(FEDERATION_WALLET_SECRET)

	if cmd == 'fund':
		print("Funding federation wallet %s..." % fed_wallet.root_address[1])
		tx = fund_federation_wallet(fed_wallet, fund_wallet, FUND_WALLET_SECRET)
		txid = push_tx(tx)
		print("https://www.blocktrail.com/BTC/tx/%s" % txid)

	elif cmd == 'notarise':

		data = sys.argv[2]
		if(len(data) < 16):
			print("Data needs to be 16+ bytes")
			raise Exception

		data_prefixed = "TEST"+str(data)
		if(len(data_prefixed) > 80):
			print("Data needs to be 80 bytes or less")
			raise Exception

		print('Notarising data...')

		tx_hex = generate_notarise_tx(fed_wallet.root_address[1], FEDERATION_WALLET_SECRET, data_prefixed)

		print("Pushing %s" % tx_hex)
		push_tx(tx_hex)

	else:
		print("Syntax: registerWorkSimple.py (fund | notarise) <data>")

	exit(0)


import gym

from envs.common_wrappers import NoopResetEnv, ClipRewardEnv, MaxAndSkipEnv, ProcessFrame84
from envs.common_wrappers import FrameStack, ExtraTimeLimit, ImageToPyTorch, NormalizedEnv, RescaleImageEnv
from envs.dm_lab_env import Dmlab_env

def make_atari(args):
    env = gym.make(args.env_name)
    env = NoopResetEnv(env, noop_max=args.noop_max)
    if args.clip_rewards:
        env = ClipRewardEnv(env)
    if 'NoFrameskip' in env.spec.id and args.skip_frames > 0:
        env = MaxAndSkipEnv(env, skip=args.skip_frames)
    env = ProcessFrame84(env, crop=False)
    if args.stack_frames > 1:
        env = FrameStack(env, args.stack_frames)
    env = ExtraTimeLimit(env, args.max_episode_steps)
    env = ImageToPyTorch(env)
    if args.normalize_env:
        env = NormalizedEnv(env)
    return env

def make_dm_lab(args, recording):
    env = Dmlab_env(args)
    if recording:
        env = RescaleImageEnv(env, size=(args.prev_frame_h, args.prev_frame_w))
    if args.clip_rewards:
        env = ClipRewardEnv(env)
    if args.skip_frames > 0:
        env = MaxAndSkipEnv(env, skip=args.skip_frames)
    if args.stack_frames > 1:
        env = FrameStack(env, args.stack_frames)
    env = ImageToPyTorch(env)
    if args.normalize_env:
        env = NormalizedEnv(env)
    return env

def make_env(env_args, recording=False):
    if env_args.env_type == "atari":
        return make_atari(env_args)
    elif env_args.env_type == "dmlab":
        return make_dm_lab(env_args, recording)
    else:
        raise NotImplemented


import keras.datasets.mnist
import tensorflow as tf
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import Normalizer
from sklearn.model_selection import GridSearchCV

# data import
(x_train, y_train), _ = keras.datasets.mnist.load_data()

# data preprocessing
n = len(x_train)
m = len(x_train[0])
x_train_reshaped = x_train.reshape((n, m * m))
x_train_reshaped = x_train_reshaped[:6000]
y_train = y_train[:6000]

# train test split
x_train, x_test, y_train, y_test = train_test_split(x_train_reshaped, y_train, test_size=0.3, random_state=40)

# normalize data
normalizer = Normalizer()
x_train_norm = normalizer.fit_transform(x_train)
x_test_norm = normalizer.fit_transform(x_test)

params_knn = {
    'n_neighbors': [3, 4],
    'weights': ['uniform', 'distance'],
    'algorithm': ['auto', 'brute']
}

params_forest = {
    'n_estimators': [300, 500],
    'max_features': ['auto', 'log2'],
    'class_weight': ['balanced', 'balanced_subsample']
}

def fit_predict_eval(model, name, features_train, features_test, target_train, target_test):
    # here you fit the model
    model.fit(features_train, target_train)
    # make a prediction
    y_pred = model.predict(features_test)
    # calculate accuracy and save it to score
    score = accuracy_score(y_pred, target_test)
    print(f'Model: {model}\nAccuracy: {score}\n')

# example
# code
# fit_predict_eval(
#     model=KNeighborsClassifier(),
#     name='KNeighborsClassifier',
#     features_train=x_train_norm,
#     features_test=x_test_norm,
#     target_train=y_train,
#     target_test=y_test
# )
#
# fit_predict_eval(
#     model=RandomForestClassifier(random_state=40, n_jobs=-1),
#     name='RandomForestClassifier',
#     features_train=x_train_norm,
#     features_test=x_test_norm,
#     target_train=y_train,
#     target_test=y_test
# )

# grid search knn
# grid_search_knn = GridSearchCV(KNeighborsClassifier(), param_grid=params_knn, n_jobs=-1, scoring='accuracy')
# grid_search_knn.fit(x_train_norm, y_train)
# print(grid_search_knn.best_estimator_)

# grid search forest
# grid_search_forest = GridSearchCV(RandomForestClassifier(random_state=40), param_grid=params_forest,
#                                   n_jobs=-1, scoring='accuracy')
# grid_search_forest.fit(x_train_norm, y_train)
# print(grid_search_forest.best_estimator_)

print("K-nearest neighbours algorithm")
print("best estimator: KNeighborsClassifier(n_neighbors=4, weights='distance')")
knn = KNeighborsClassifier(n_neighbors=4, weights='distance')
knn.fit(x_train_norm, y_train)
y_pred_knn = knn.predict(x_test_norm)
print(f"accuracy: {accuracy_score(y_pred_knn, y_test)}\n")

print("Random forest algorithm")
print("best estimator: RandomForestClassifier(class_weight='balanced_subsample', max_features='log2',"
      " n_estimators=300, random_state=40)")
forest = RandomForestClassifier(class_weight='balanced_subsample', max_features='log2',
                                n_estimators=300, random_state=40)
forest.fit(x_train_norm, y_train)
y_pred_f = forest.predict(x_test_norm)
print(f"accuracy: {accuracy_score(y_pred_f, y_test)}")

Classification of Handwritten Digits/Classification of Handwritten Digits/task/analysis.py


####
#this a program for basic snake game
###
import turtle
import random
import time
##we are using the turtle,for the graphics and animation
##random mainly used to create food at random positions as required
##time is used indelaying the time to start a new game after the game is over

w = 500
h = 500
food_size = 10
delay = 100
global score,highest_score ## globalizing the variables so it can be used within some functions
highest_score=0
score=0
offsets = {
    "up": (0, 20),
    "down": (0, -20),
    "left": (-20, 0),
    "right": (20, 0)
}
## we are initializing important variables as in food_size for food size,w_h for the width and height of the window,others are scores,except offset.

pe = turtle.Turtle()

pe.color('white')
pe.penup()
pe.hideturtle()
pe.goto(216, 228)
pe.write('Score: 0', align='right', font=('ubuntu', 14, 'bold'))
##creating object pe to display score on turtle screen with specifications

rop=turtle.Turtle()
rop.color('gold')
rop.penup()
rop.hideturtle()
rop.goto(-246,228)
rop.write('Highest Score: 0',align='left',font=('ubuntu',15,'italic'))
##creating object pe to display highest score on turtle screen with specifications

def reset():
    global snake, snake_dir, food_position  ##to use the globalized variables
    snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
    snake_dir = "up"
    food_position = get_random_food_position()
    food.goto(food_position)
    move_snake()
##created a function reset , to start a new game after a game over

def move_snake():          ## function to control and animate the movement of the snake
    global snake_dir

    new_head = snake[-1].copy()      ##creating new heads
    new_head[0] = snake[-1][0] + offsets[snake_dir][0]
    new_head[1] = snake[-1][1] + offsets[snake_dir][1]

    if new_head in snake[:-1]:        ##setting a condition for game over
        game_over()    ## calling the function game over as the head of the snake hits its body/tail
        reset()        ##to reset the game after game over
        pe.clear()     ##to clear the score and reset at 0
    else:
        snake.append(new_head)    ##creating a new head/body as it eats a food

        if not food_collision():
            snake.pop(0)
        else:
            global score
            score=score+10         ## increasing score for a food eaten
            pe.clear()
            pe.write(f'Score: {score} ', align='right',font=('ubuntu', 14, 'bold'))      ##rewriting the increased score

        if snake[-1][0] > w / 2:
            snake[-1][0] -= w
        elif snake[-1][0] < - w / 2:
            snake[-1][0] += w
        elif snake[-1][1] > h / 2:
            snake[-1][1] -= h
        elif snake[-1][1] < -h / 2:
            snake[-1][1] += h
        ## if the snake goes out of the boundary,then making the snake head come out of its opposite end

        pen.clearstamps()

        for segment in snake:
            pen.goto(segment[0], segment[1])
            pen.stamp()

        screen.update()

        turtle.ontimer(move_snake, delay)

def food_collision():
    global food_position
    if get_distance(snake[-1], food_position) < 20:
        food_position = get_random_food_position()
        food.goto(food_position)
        return True
    return False
##setting condition for the snake to eat food make the food dissapear

def get_random_food_position():
    x = random.randint(- w / 2 + food_size, w / 2 - food_size)
    y = random.randint(- h / 2 + food_size, h / 2 - food_size)
    return (x, y)
##function to assign food randomly to continue the game

def get_distance(pos1, pos2):
    x1, y1 = pos1
    x2, y2 = pos2
    distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
    return distance
## we use this function to know if snake has gotten closer to the food

def go_up():
    global snake_dir
    if snake_dir != "down":
        snake_dir = "up"

def go_right():
    global snake_dir
    if snake_dir != "left":
        snake_dir = "right"

def go_down():
    global snake_dir
    if snake_dir!= "up":
        snake_dir = "down"

def go_left():
    global snake_dir
    if snake_dir != "right":
        snake_dir = "left"
##go_up/doe/right/left are the main controls that the player would use to control the movement of the snake

def game_over():     ##function game over.
    t =turtle.Turtle()
    t.goto(0, 0)
    t.color('orange')
    t.penup()
    t.hideturtle()
    t.write('Game Over\n', align='center', font=('ubuntu', 26, 'bold'))
    t.write('Please wait a while to play again!!',
            align='center', font=('ubuntu', 14, 'bold'))   ##game over message
    time.sleep(3)
    t.clear()
    time.sleep(1)  ## delaying time to reset()
    global score,highest_score

    rop.clear()
    if score>highest_score:
        highest_score=score
    rop.write(f'Highest_Score: {highest_score} ', align='left',font=('ubuntu', 15, 'italic'))      ##writing/rewriting the highest sore

    score=0     ##setting the score to 0 again

screen = turtle.Screen()
screen.setup(w, h)
screen.title("snake(akash)")
screen.bgcolor("indigo")
screen.setup(500, 500)
screen.tracer(0)
##completing the screen set up

pen = turtle.Turtle("circle")
pen.penup()
pen.color('orange')
##object pen to create snake

food = turtle.Turtle()
food.shape("turtle")
food.color("red")
food.shapesize(food_size / 20)
food.penup()
##object food for the foodof snake

screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_right, "Right")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")
##using onkey to trace the keyboard buttons pressed by the player and operate accordingly

reset()
turtle.done()


import services

def get_daily_household_income():
    total_daily_income = 0
    for sim_info in services.active_household():
        for career in sim_info.career_tracker.careers.values():
            total_daily_income += career.get_daily_pay()
    return total_daily_income

def get_hourly_household_income():
    total_hourly_income = 0
    for sim_info in services.active_household():
        for career in sim_info.career_tracker.careers.values():
            total_hourly_income += career.get_hourly_pay()
    return total_hourly_income


from flask import Flask, request
import statistics

app = Flask(__name__)

@app.route('/')
def index():
    return "Usage;\n<Operation>?X=<Value1, Value2, ..., ValueN>\n"

def Inputs_method():
    try:
        inputs = request.args.get('X', type=str)
        inputs = inputs.split(',')
        values = []
        for value in inputs:
            value = float(value)
            values.append(value)
        return values
    except ValueError:
        Error_msg = "There are error values in inputs, Please provide a list of values,for example 1,2,3,4\n"
        return Error_msg

@app.route('/max')
def maximum():
    values = Inputs_method()
    if not type(values) is str:
        values.sort(reverse=True)
        if values[0].is_integer():
            return str(int(values[0])) + ' \n'
        else:
            return str(float(round(values[0], 3))) + ' \n'
    else:
        return values

@app.route('/min')
def minimum():
    values = Inputs_method()
    if not type(values) is str:
        values.sort()
        if values[0].is_integer():
            return str(int(values[0])) + ' \n'
        else:
            return str(float(round(values[0], 3))) + ' \n'

    else:
        return values

@app.route('/average')
def average():
    values = Inputs_method()
    if not type(values) is str:
        avrg = statistics.mean(values)
        if avrg.is_integer():
            return str(int(avrg)) + ' \n'
        else:
            return str(float(round(avrg, 3))) + ' \n'
    else:
        return values

@app.route('/avg')
def avg():
    values = Inputs_method()
    if not type(values) is str:
        avrg = statistics.mean(values)
        if avrg.is_integer():
            return str(int(avrg)) + ' \n'
        else:
            return str(float(round(avrg, 3))) + ' \n'
    else:
        return values

@app.route('/mean')
def mean():
    values = Inputs_method()
    if not type(values) is str:
        avrg = statistics.mean(values)
        if avrg.is_integer():
            return str(int(avrg)) + ' \n'
        else:
            return str(float(round(avrg, 3))) + ' \n'

@app.route('/median')
def median():
    values = Inputs_method()
    if not type(values) is str:
        med = statistics.median(values)
        if med.is_integer():
            return str(int(med)) + ' \n'
        else:
            return str(float(round(med, 3))) + ' \n'

    else:
        return values

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


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

x = 500
y = 500
direction = 0
matr = np.matrix(np.zeros((x, y)))
arr = np.array([int(x/2), int(y/2), 0])
# polozenie (x,y) i kierunek ruchu 0 - E, 1 - N, 2 - W, 3 - S

def nextstep(matr, arr):
    if arr[2] == 0:
        arr[0] += 1
    if arr[2] == 1:
        arr[1] += 1
    if arr[2] == 2:
        arr[0] -= 1
    if arr[2] == 3:
        arr[1] -= 1
    if matr[arr[0], arr[1]] == 0:
        arr[2] = (arr[2] + 1) % 4
        matr[arr[0], arr[1]] = 1
    else:
        arr[2] = (arr[2] + 3) % 4
        matr[arr[0], arr[1]] = 0

fig = plt.figure()
im = plt.imshow(matr, vmax=1)

def animate(i):
    nextstep(matr, arr)
    im.set_data(matr)
    return im,

anim = FuncAnimation(fig, animate, frames=2000000, interval=0, blit=True)
plt.show()


import torch.nn as nn
import torchvision.models as models

from attention_model import Attn_Net_Gated

def get_final_model(model_name, attention_module, hidden_dim, hidden_dim2, use_b, dropout):

    if attention_module != None:
        if attention_module == 'faisal':

            if model_name == 'RESNET18':
                dim = 512
            elif model_name == 'RESNET50':
                dim = 1024
            else:
                print('wrong model name')
                exit()

            model = Attn_Net_Gated(dim,hidden_dim,hidden_dim2,dropout,use_b,1)
        else:
            exit() # not running the other anymore

    else:
        if model_name == 'RESNET18':
            model = get_model(model_name)

        else:
            print('Wrong model name')
            exit()

    model = model.cuda()
    return model

def get_model(model_name):

    if model_name == 'RESNET18':

        model = models.resnet18(pretrained=True)
        for param in model.parameters():
            param.requires_grad = False

        fc = nn.Linear(in_features=512, out_features=1, bias=True)
        model.fc = fc

        for param in model.fc.parameters():
            param.requires_grad = True

    elif model_name == 'RESNET50':
        model = models.resnet50(pretrained=True)
        for param in model.parameters():
            param.requires_grad = False

        fc = nn.Linear(in_features=2048, out_features=1, bias=True)
        model.fc = fc

        for param in model.fc.parameters():
            param.requires_grad = True

    return model


# Discord imports
import discord
from discord.ext import tasks

#Misc imports
from datetime import datetime
import json, os

# File imports
from src.indicators import TA
from src.chart import Charter
from src.stream import Streamer
from src.trade_finder import TradeFinder
from src.alert_logger import Logger
import src.helper as Helper

#-------------------------------------- Bot initiation and loop --------------------------------------#

bot = discord.Bot()

# Read config
TOKEN, PARAMETERS, ids, PAIRS = Helper.read_config()
# Make pairs upper case
PAIRS = [pair.upper() for pair in PAIRS]
GUILD_ID = ids["guild_id"]

# Initate classes
TechnicalAnalyzer = TA()
DataStreamer = Streamer(PARAMETERS["rank_by_marketcap"])
TradeScraper = TradeFinder(DataStreamer, TechnicalAnalyzer, PARAMETERS["vol_breakout_threashold"], PARAMETERS["vol_breakout_timeframe"])
AlertLogger = Logger()

@bot.event
async def on_ready():
    print("Bot is ready to scrape coins!!")
    if not scrape_market.is_running():
        scrape_market.start()

@tasks.loop(seconds = PARAMETERS["scrape_interval"])
async def scrape_market():
    print(f"{datetime.utcnow()} - Busy scraping market!")

    # Do market scrape if channel is supplied in config.json
    vol_breakout_alerts = None if ids["volume_breakout_channel"] == "" else ids["volume_breakout_channel"]
    if vol_breakout_alerts is not None:
        # TODO Perform the stuff in a subproces to still be able to access the bot commands
        # Check for high volume moves to the upside
        # Try/except is due to weird extra curly bracket error
        try:
            tfs_triggers = await TradeScraper.checkVol(PAIRS)
        except Exception as e:
            if e.__class__.__name__ == "JSONDecodeError":
                Helper.clean_tfs_log()
                tfs_triggers = await TradeScraper.checkVol(PAIRS)
            else:
                print(f"Error occured: {e}")
                tfs_triggers = None

        if tfs_triggers is None:
            print("No high volume breakouts!")
        else:
            channel = bot.get_channel(vol_breakout_alerts)
            await channel.send(f":alarm_clock: Caught high volume breakouts! :alarm_clock: \n{tfs_triggers.to_string()}")

    # Check if any alerts have been triggered
    if os.path.isfile("alerts.json"):
        symbols = AlertLogger.get_symbols()
        price_triggers = TradeScraper.checkPriceAlerts(symbols)
        vol_triggers = TradeScraper.checkVolumeAlerts(symbols)

        # Alert users that their alert(s) has/have been triggered
        alerts = price_triggers + vol_triggers
        channel = bot.get_channel(ids["alerts_channel"])
        await Helper.alert_user(channel, alerts)

        # Remove alerts after being triggered
        [AlertLogger.rm_alert(alert) for alert in alerts if alert["delete"] == "true"]

    print(f"{datetime.utcnow()} - Done scraping!")

@scrape_market.before_loop
async def set_status():
    await bot.change_presence(activity = discord.Activity(type = discord.ActivityType.watching, name = "candlesticks"))
    await bot.wait_until_ready()

#--------------------------------------------- Commands ----------------------------------------------#

# Add an alert for a symbol pair when certain price is crossed
@bot.slash_command(guild_ids = [GUILD_ID], name = "pricealert", description = "Add an alert for a symbol pair price movement")
async def price_alert(ctx, symbol, type, price, delete_when_triggered = "true"):
    symbol = symbol.upper()
    delete_when_triggered = delete_when_triggered.lower()
    if not DataStreamer.checkSymbol(symbol):
        await ctx.respond("That sucks.... I looked everywhere on Binance, but I can't find this symbol pair:cry:")
    elif type not in ("up", "down", "volume"):
        await ctx.respond("Please add a valid type for this alert: up, down, volume")
    elif delete_when_triggered not in ("true", "false"):
        await ctx.respond("Incorrect value for \"delete_when_triggered\". Should be either true or false...")
    else:
        # Get user ID
        uid = ctx.author.id
        AlertLogger.add_alert(uid, symbol, type, price, timeframe = '', volume_multiple = 0, delete = delete_when_triggered)
        await ctx.respond(f"Set an alert for {symbol}!")

# Add a volume breakout alert for certain symbol on chosen timeframe
@bot.slash_command(guild_ids = [GUILD_ID], name = "volumealert", description = "Add a volume breakout alert for a symbol pair on certain timeframe")
async def volume_alert(ctx, symbol, timeframe, volume_multiple, delete_when_triggered = "true"):
    symbol = symbol.upper()
    delete_when_triggered = delete_when_triggered.lower()
    if not DataStreamer.checkSymbol(symbol):
        await ctx.respond("That sucks.... I looked everywhere on Binance, but I can't find this symbol pair:cry:")
    elif not DataStreamer.checkTimeframe(timeframe):
        await ctx.respond("Please add a valid timeframe...")
    elif delete_when_triggered not in ("true", "false"):
        await ctx.respond("Incorrect value for \"delete_when_triggered\". Should be either true or false...")
    else:
        # Get user ID
        uid = ctx.author.id
        AlertLogger.add_alert(uid, symbol, type = "volume", price = 0, timeframe = timeframe, volume_multiple = volume_multiple, delete = delete_when_triggered)
        await ctx.respond(f"Set an alert for {symbol}!")

# Remove alert
@bot.slash_command(guild_ids = [GUILD_ID], name = "removealert", description = "Remove an alert. Get available alerts with \"/getalerts\"")
async def removemalert(ctx, alert):
    uid = ctx.author.id
    alert = json.loads(alert)
    if uid == alert["userid"]:
        try:
            AlertLogger.rm_alert(alert)
            await ctx.respond(f"Alert deleted!")
        except:
            await ctx.respond("An error occured... Did you include the \"{ *alert* }\" (curley brackets) around the alert?")
    else:
        await ctx.respond("Unfortunately you do not have permission to remove this alert (not created by you) :lock:")

# Sends all active alerts for some symbol
@bot.slash_command(guild_ids = [GUILD_ID], name = "getalerts", description = "Get all current alerts for chosen symbol")
async def get_alerts(ctx, symbol):
    symbol = symbol.upper()
    if not symbol in AlertLogger.get_symbols():
        await ctx.respond("There are currently no alerts for this symbol pair. Will you be the first to add one?")
    else:
        alerts = AlertLogger.get_alerts(symbol)
        parsed_alerts = json.dumps(alerts, indent = 4)
        await ctx.respond(f"Active alerts for {symbol}:\n ```json\n{parsed_alerts}\n```\n Copy one of the following if you wish to remove an alert:", delete_after = 30)
        for alert in alerts:
            await ctx.send(f"`{json.dumps(alert)}`")

# Chart symbol pair last 24H
@bot.slash_command(guild_ids = [GUILD_ID], name = "chart", description = "Plot a currency pair 24H back")
async def chart(ctx, symbol):
    symbol = symbol.upper()
    if not DataStreamer.checkSymbol(symbol):
        await ctx.respond("That sucks.... I looked everywhere on Binance, but I can't find this symbol pair:cry:")
    else:
        await ctx.respond(f"Drawing chart for {symbol}...")
        # 5m candles over a span of 24H: 24*60/5 = 288
        candles = DataStreamer.getKlines(symbol, 288)
        chart = Charter(symbol, candles)
        chart_path = chart.createChart()

        # Send chart in given path and delete after done
        with open(chart_path, 'rb') as image:
            img = discord.File(image)
            # TODO reconsider this: await ctx.send(file = img, delete_after = 60)
            image.close()

        os.remove(chart_path)

# Get the value of a certain indicator from at certain symbol pair
@bot.slash_command(guild_ids = [GUILD_ID], name = "indicator", description = "Get the latest value of a certain indicator on a certain timeframe")
async def indicator(ctx, symbol, indicator, window='0', timeframe = '1h'):
    symbol = symbol.upper()
    if not DataStreamer.checkSymbol(symbol):
        await ctx.respond("That sucks.... I looked everywhere on Binance, but I can't find this symbol pair:cry:")
    elif not DataStreamer.checkTimeframe(timeframe):
        await ctx.respond("Whooops, that looks like an incorrect timeframe:alarm_clock: Please check your command!")
    elif window == '0' and indicator != 'bms':
        await ctx.respond(f"Did you add an incorrect window for the indicator? For example rsi **14** or ema **21**.")
    else:
        candles = DataStreamer.getKlines(symbol, 100, timeframe)
        val = TechnicalAnalyzer.do_indicator(indicator, candles, window)
        await ctx.respond(f"Indicator, \"{indicator}\", for symbol, {symbol}, is currently at:\n{val}\n- on {timeframe} timeframe.")

# Get latest TFS from certain coin
@bot.slash_command(guild_ids = [GUILD_ID], name = "tfs", describtion = "Get time of last TFS from symbol")
async def tfs(ctx, symbol):
    symbol = symbol.upper()
    path = "tfs_log.json"

    with open(path, "r") as log_file:
        file = json.load(log_file)

        # Check if a trigger is logged
        if symbol in list(file.keys()):
            latest_trigger = file[symbol]["Time"]
            await ctx.respond(f"Latest trigger for {symbol} was at: {latest_trigger}")
        else:
            await ctx.respond(f"No triggers has been logged for {symbol} yet!!")

        log_file.close()

# For clearing chat
@bot.slash_command(guild_ids = [GUILD_ID], name = "clear", describtion = "Clear the previous, \"n\", bot messages")
async def clear(ctx, amount = 10):
    # First check if user is moderator/admin and has permission to delete messages
    if ctx.author.guild_permissions.administrator:
        await ctx.respond(f"Deleting {amount} messages!")
        channel = bot.get_channel(ids["alerts_channel"])
        await channel.purge(limit = int(amount))
    else:
        await ctx.respond("Unfortunately you do not have permission to use this command :cry:")

# Run bot
bot.run(TOKEN)


import argparse
import sys
import datetime

from pyramid.paster import bootstrap, setup_logging
from sqlalchemy.exc import OperationalError

from .. import models

def setup_models(dbsession):

    # Grupo
    administrador = models.Grupo(nombre='Administrador')
    dbsession.add(administrador)
    cooperativa = models.Grupo(nombre='Cooperativa')
    dbsession.add(cooperativa)
    cliente = models.Grupo(nombre='Cliente')
    dbsession.add(cliente)

    # Menu
    menu1 = models.Menu(nombre='Boletos', url='', grupo=administrador)
    dbsession.add(menu1)
    menu2 = models.Menu(nombre='Pasajes', url='', grupo=administrador)
    dbsession.add(menu2)
    menu3 = models.Menu(nombre='Boletos', url='', grupo=cooperativa)
    dbsession.add(menu3)
    menu4 = models.Menu(nombre='Pasajes', url='', grupo=cooperativa)
    dbsession.add(menu4)
    menu5 = models.Menu(nombre='Boletos', url='', grupo=cliente)
    dbsession.add(menu5)
    menu6 = models.Menu(nombre='Cuentas', url='', grupo=administrador)
    dbsession.add(menu6)
    menu7 = models.Menu(nombre='Cuentas', url='', grupo=cooperativa)
    dbsession.add(menu7)
    menu8 = models.Menu(nombre='Cooperativa', url='', grupo=administrador)
    dbsession.add(menu8)
    menu9 = models.Menu(nombre='Cooperativa', url='', grupo=cooperativa)
    dbsession.add(menu9)

    # Item
    item1 = models.Item(nombre='Comprar boletos', url='#!/inicio', es_menu=False, menu=menu1)
    dbsession.add(item1)
    item2 = models.Item(nombre='Listar boletos comprados', url='#!/mis-boletos', es_menu=False, menu=menu1)
    dbsession.add(item2)
    item_crear = models.Item(nombre='Crear pasaje', url='#!/add-pasaje', es_menu=False, menu=menu2)
    dbsession.add(item_crear)
    item3 = models.Item(nombre='Listar pasajes', url='#!/list-pasajes', es_menu=False, menu=menu2)
    dbsession.add(item3)
    item4 = models.Item(nombre='Comprar boletos', url='#!/inicio', es_menu=False, menu=menu3)
    dbsession.add(item4)
    item5 = models.Item(nombre='Listar boletos comprados', url='#!/mis-boletos', es_menu=False, menu=menu3)
    dbsession.add(item5)
    item_crear = models.Item(nombre='Crear pasaje', url='#!/add-pasaje', es_menu=False, menu=menu4)
    dbsession.add(item_crear)
    item6 = models.Item(nombre='Listar pasajes', url='#!/list-pasajes', es_menu=False, menu=menu4)
    dbsession.add(item6)
    item7 = models.Item(nombre='Comprar boletos', url='#!/inicio', es_menu=False, menu=menu5)
    dbsession.add(item7)
    item8 = models.Item(nombre='Listar boletos comprados', url='#!/mis-boletos', es_menu=False, menu=menu5)
    dbsession.add(item8)
    item9 = models.Item(nombre='Crear cuentas', url='#!/registro', es_menu=False, menu=menu6)
    dbsession.add(item9)
    item10 = models.Item(nombre='Crear cuentas', url='#!/registro', es_menu=False, menu=menu7)
    dbsession.add(item10)
    item11 = models.Item(nombre='Crear cooperativa', url='#!/add-cooperativa', es_menu=False, menu=menu8)
    dbsession.add(item11)
    item12 = models.Item(nombre='Crear cooperativa', url='#!/add-cooperativa', es_menu=False, menu=menu9)
    dbsession.add(item12)
    item13 = models.Item(nombre='Crear unidad', url='#!/add-unidad', es_menu=False, menu=menu8)
    dbsession.add(item13)
    item14 = models.Item(nombre='Crear unidad', url='#!/add-unidad', es_menu=False, menu=menu9)
    dbsession.add(item14)

    # User
    u_administrador = models.User(username='admin',
                                  nombre='Admin',
                                  apellido='Admin',
                                  email='admin@gmail.com',
                                  activo=True,
                                  cod_verificacion=None,
                                  grupo=administrador)
    u_administrador.set_password('admin')
    dbsession.add(u_administrador)
    cooperativa_loja = models.User(username='loja',
                                   nombre='Loja',
                                   apellido='Loja',
                                   email='loja@gmail.com',
                                   activo=True,
                                   cod_verificacion=None,
                                   grupo=cooperativa)
    cooperativa_loja.set_password('loja')
    dbsession.add(cooperativa_loja)
    cooperativa_cariamanga = models.User(username='cariamanga',
                                         nombre='Cariamanga',
                                         apellido='Cariamanga',
                                         email='cariamanga@gmail.com',
                                         activo=True,
                                         cod_verificacion=None,
                                         grupo=cooperativa)
    cooperativa_cariamanga.set_password('cariamanga')
    dbsession.add(cooperativa_cariamanga)
    basic = models.User(username='juan',
                        nombre='Juan',
                        apellido='Perez',
                        email='juanperez@gmail.com',
                        activo=True,
                        cod_verificacion=None,
                        grupo=cliente)
    basic.set_password('juan')
    dbsession.add(basic)

    # Sitio
    loja = models.Sitio(ciudad='Loja', terminal='Av. Isidro Ayora')
    dbsession.add(loja)
    quito = models.Sitio(ciudad='Quito', terminal='Quitumbe')
    dbsession.add(quito)
    cuenca = models.Sitio(ciudad='Cuenca', terminal='Av. España y Sebastian de Benalcazar')
    dbsession.add(cuenca)
    guayaquil = models.Sitio(ciudad='Guayaquil', terminal='Río Daule')
    dbsession.add(guayaquil)

    # Cooperativa
    cooperativa_loja = models.Cooperativa(nombre='Cooperativa Loja', user=cooperativa_loja)
    dbsession.add(cooperativa_loja)
    cooperativa_cariamanga = models.Cooperativa(nombre='Cooperativa Cariamanga', user=cooperativa_cariamanga)
    dbsession.add(cooperativa_cariamanga)

    # Clase
    vip = models.Clase(nombre='VIP', descripcion='Clase VIP')
    dbsession.add(vip)
    normal = models.Clase(nombre='Normal', descripcion='Clase normal')
    dbsession.add(normal)

    # Unidad
    loja_1 = models.Unidad(numero_asientos=45, numero_unidad=1, clase=vip, cooperativa=cooperativa_loja)
    dbsession.add(loja_1)
    cariamanga_1 = models.Unidad(numero_asientos=40, numero_unidad=1, clase=normal, cooperativa=cooperativa_cariamanga)
    dbsession.add(cariamanga_1)
    cariamanga_2 = models.Unidad(numero_asientos=45, numero_unidad=2, clase=vip, cooperativa=cooperativa_cariamanga)
    dbsession.add(cariamanga_2)

    # Pasaje
    loja_quito_1 = models.Pasaje(salida=datetime.datetime.utcnow(),
                               llegada=datetime.datetime.utcnow(),
                               precio=20.5,
                               asientos_disponibles=45,
                               origen=loja,
                               destino=quito,
                               unidad=loja_1)
    dbsession.add(loja_quito_1)
    loja_quito_2 = models.Pasaje(salida=datetime.datetime.utcnow(),
                               llegada=datetime.datetime.utcnow(),
                               precio=20,
                               asientos_disponibles=40,
                               origen=loja,
                               destino=quito,
                               unidad=cariamanga_1)
    dbsession.add(loja_quito_2)
    loja_guayaquil = models.Pasaje(salida=datetime.datetime.utcnow(),
                                   llegada=datetime.datetime.utcnow(),
                                   precio=18,
                                   asientos_disponibles=45,
                                   origen=loja,
                                   destino=guayaquil,
                                   unidad=loja_1)
    dbsession.add(loja_guayaquil)
    loja_cuenca = models.Pasaje(salida=datetime.datetime.utcnow(),
                               llegada=datetime.datetime.utcnow(),
                               precio=8,
                               asientos_disponibles=45,
                               origen=loja,
                               destino=cuenca,
                               unidad=cariamanga_2)
    dbsession.add(loja_cuenca)

    # Boleto
    boleto_1 = models.Boleto(numero_asientos=2, precio_total=10.5, user=basic, pasaje=loja_quito_1)
    dbsession.add(boleto_1)
    boleto_2 = models.Boleto(numero_asientos=3, precio_total=12.5, user=basic, pasaje=loja_guayaquil)
    dbsession.add(boleto_2)
    boleto_3 = models.Boleto(numero_asientos=25, precio_total=15, user=basic, pasaje=loja_cuenca)
    dbsession.add(boleto_3)

def parse_args(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'config_uri',
        help='Configuration file, e.g., development.ini',
    )
    return parser.parse_args(argv[1:])

def main(argv=sys.argv):
    args = parse_args(argv)
    setup_logging(args.config_uri)
    env = bootstrap(args.config_uri)

    try:
        with env['request'].tm:
            dbsession = env['request'].dbsession
            setup_models(dbsession)
    except OperationalError:
        print('''
Pyramid is having a problem using your SQL database.  The problem
might be caused by one of the following things:

1.  You may need to initialize your database tables with `alembic`.
    Check your README.txt for description and try to run it.

2.  Your database server may not be running.  Check that the
    database server referred to by the "sqlalchemy.url" setting in
    your "development.ini" file is running.
            ''')


from stellar_base.address import Address
from stellar_base.utils import AccountNotExistError

class Details:
    def __init__(self, address):
        self.address = address
        self.account = Address(address=self.address)
        try:
            self.account.get()
        except AccountNotExistError:
            self.account = None

    @property
    def check(self):
        return True if self.account else False

    @property
    def get(self):
        if self.account:
            return self.account, self.address, self.balance, self.asset
        else:
            return None

    @property
    def balance(self):
        balance = 0
        try:
            balance = self.account.balances[0]['balance']
        except AttributeError:
            balance = None
        finally:
            return balance

    @property
    def asset(self):
        asset = None
        try:
            asset = self.account.balances[0]['asset_type']
            asset = 'XLM' if asset == 'native' else asset
        except AttributeError:
            asset = None
        finally:
            return asset


# Right off
# https://docs.opencv.org/3.4/da/d97/tutorial_threshold_inRange.html
from __future__ import print_function
import cv2 as cv
import argparse
from pathlib import Path

max_value = 255
max_value_H = 360 // 2
low_H = 0
low_S = 0
low_V = 0
high_H = max_value_H
high_S = max_value
high_V = max_value
window_capture_name = "Video Capture"
window_detection_name = "Object Detection"
low_H_name = "Low H"
low_S_name = "Low S"
low_V_name = "Low V"
high_H_name = "High H"
high_S_name = "High S"
high_V_name = "High V"

def on_low_H_thresh_trackbar(val):
    global low_H
    global high_H
    low_H = val
    low_H = min(high_H - 1, low_H)
    cv.setTrackbarPos(low_H_name, window_detection_name, low_H)

def on_high_H_thresh_trackbar(val):
    global low_H
    global high_H
    high_H = val
    high_H = max(high_H, low_H + 1)
    cv.setTrackbarPos(high_H_name, window_detection_name, high_H)

def on_low_S_thresh_trackbar(val):
    global low_S
    global high_S
    low_S = val
    low_S = min(high_S - 1, low_S)
    cv.setTrackbarPos(low_S_name, window_detection_name, low_S)

def on_high_S_thresh_trackbar(val):
    global low_S
    global high_S
    high_S = val
    high_S = max(high_S, low_S + 1)
    cv.setTrackbarPos(high_S_name, window_detection_name, high_S)

def on_low_V_thresh_trackbar(val):
    global low_V
    global high_V
    low_V = val
    low_V = min(high_V - 1, low_V)
    cv.setTrackbarPos(low_V_name, window_detection_name, low_V)

def on_high_V_thresh_trackbar(val):
    global low_V
    global high_V
    high_V = val
    high_V = max(high_V, low_V + 1)
    cv.setTrackbarPos(high_V_name, window_detection_name, high_V)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Code for Thresholding Operations using inRange tutorial."
    )
    parser.add_argument(
        "image_path",
        help="Path[s] to images",
        nargs="+",
        type=Path,
    )
    args = parser.parse_args()

    cv.namedWindow(window_capture_name)
    cv.namedWindow(window_detection_name)
    cv.createTrackbar(
        low_H_name,
        window_detection_name,
        low_H,
        max_value_H,
        on_low_H_thresh_trackbar,
    )
    cv.createTrackbar(
        high_H_name,
        window_detection_name,
        high_H,
        max_value_H,
        on_high_H_thresh_trackbar,
    )
    cv.createTrackbar(
        low_S_name,
        window_detection_name,
        low_S,
        max_value,
        on_low_S_thresh_trackbar,
    )
    cv.createTrackbar(
        high_S_name,
        window_detection_name,
        high_S,
        max_value,
        on_high_S_thresh_trackbar,
    )
    cv.createTrackbar(
        low_V_name,
        window_detection_name,
        low_V,
        max_value,
        on_low_V_thresh_trackbar,
    )
    cv.createTrackbar(
        high_V_name,
        window_detection_name,
        high_V,
        max_value,
        on_high_V_thresh_trackbar,
    )

    for image_path in args.image_path:
        while True:
            image = cv.imread(str(image_path))

            image_HSV = cv.cvtColor(image, cv.COLOR_BGR2HSV)
            image_threshold = cv.inRange(
                image_HSV, (low_H, low_S, low_V), (high_H, high_S, high_V)
            )

            cv.imshow(window_capture_name, image)
            cv.imshow(window_detection_name, image_threshold)

            (22, 79, 147), (41, 161, 215)  # Image 16
            (21, 15, 134), (66, 255, 255)  # Image 35

            key = cv.waitKey(30)
            is_quit = key == ord("q") or key == 27  # 27 is escape
            is_next = key == ord(" ")

            if is_quit or is_next:
                print(f"==== Final HSVs for {image_path.name} ====")
                print(f"lowH = {low_H}")
                print(f"lowS = {low_S}")
                print(f"lowV = {low_V}")
                print(f"highH = {high_H}")
                print(f"highS = {high_S}")
                print(f"highV = {high_V}")
                print()
                print(
                    f"({low_H}, {low_S}, {low_V}), ({high_H}, {high_S}, {high_V})"
                )
                print("=======================================================")

                if is_quit:
                    print("Quitting")
                    exit(0)
                elif is_next:
                    print("Continuing to next image")
                    break


# -*- coding: utf-8 -*-

if 3>2:
    print('This is true')

hungry = True

if hungry:
    print('feed me')
else:
    print('Not now, im full')

loc = 'Bank'

if loc == 'Auto Shop':
    print('Cars are cool!')
elif loc == "Bank":
    print("You are at the bank")
else:
    print('I do not know much.')

name = 'Sammy'

if name == 'Frankie':
    print('Hello Frankie')
elif name == 'Sammi':
    print('Hello Sammi')
else:
    print('What is your name?')

#While loops will continue to execute until condition

x = 0

while x < 5:
    print(f'The current value of x is {x}')
    x += 1
else:
    print("X is not less than 5")

# Break out of th ecurrent closest loop

mystring = "This one"

for letter in mystring:
    if letter == "a":
        continue
    print(letter)

# Continue: goings to the top of the closest englosing loop

mystring = "This one"

for letter in mystring:
    if letter == "a":
        break
    print(letter)

x = 0

while x < 5:
    if x == 2:
        break
    print(x)
    x += 1
# pass: does nothing at all

# Useful operators

for num in range(0,11,2):
    print(num)

list(range(0,10,2))

index_count = 0
word = 'abcde'
for letter in word:
    print('At index {} the letter is {}'.format(index_count,letter))
    index_count += 1

for index,letter in enumerate(word):
    print(index)
    print(letter)
    print('\n')

mylist1 = [1,2,3]
mylist2 = ['a','b','c']

for item in zip(mylist1, mylist2):
    print(item)

'x' in ['x', 'y', 'z']

'a' in 'a world'

'mykey' in {'mykey' : 355}

d = {'mykey': 345}
345 in d.keys()
345 in d.values()

mylist = [10,20,30]
min(mylist)
max(mylist)

from random import shuffle

mylist = [1,2,3,4,5,6,7,8,9]

random_list = shuffle(mylist)
mylist

from random import randint
randint(0,10)

result = input('Enter a number here: ')
print(result)

float(result)


class Solution(object):
    def letterCasePermutation(self, S):
        """
        :type S: str
        :rtype: List[str]
        """
        res = [""]
        for char in S:
            candi = []
            if char.isalpha():
                candi = [char.lower(), char.upper()]
            else:
                candi = [char]
            temp = [string for string in res]
            res = []
            for string in temp:
                for char in candi:
                    res.append(string + char)
        res = list(set(res))
        return res


num1=int(input("Enter first number :- "))
num2=int(input("Enter second number :- "))
print("Which opertation you want apply 1.add, 2.sub, 3.div")
op=input()
def add():
			c=num1+num2
			print("After Add",c)
def sub():
			c=num1-num2
			print("After sub",c)
def div():
			c=num1/num2
			print("After div",c)
def again():
	print("If you want to perform any other operation")
	print("say Yes or y else NO or n")
	ans=input()
	if ans=="yes" or ans=="y":
		cal()
	else:
		print(" Good Bye")
def cal():

	if op=='1' or op=="add" or op=="1.add":
		add()
	elif op=='2' or op=="sub" or op=="2.sub":
		sub()
	elif op=='3' or op=="div" or op=="3.div":
		div()
	else:

		print("Invalid Operation")
		again()
cal()
again()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan  5 15:18:10 2019

@author: Nazmul
"""
"""1. Autograd"""
# In[ ]:
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
import torch.nn.functional as F
import nltk
import random
import numpy as np
from collections import Counter, OrderedDict
import nltk
from copy import deepcopy
import os
import re
import unicodedata
flatten = lambda l: [item for sublist in l for item in sublist]

from torch.nn.utils.rnn import PackedSequence, pack_padded_sequence
random.seed(1024)
# In[ ]:
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(1,1)
    def forward(self, x):
        x = self.fc1(x)
        return x
# In[ ]:
net = Net()
print(net)
print(list(net.parameters()))
# In[ ]:
input = Variable(torch.randn(1,1,1), requires_grad = True)
print(input)
# In[ ]:
print(list(net.parameters()))
out = net(input)
print(out)
# In[ ]:
def criterion(out, label):
    return (label - out)**2
optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.5)
# In[ ]:
data = [(1,3), (2,6), (3,9), (4,12), (5,15), (6,18)]
# In[ ]:
for epoch in range(100):
    for i, data2 in enumerate(data):
        X, Y = iter(data2)
        X, Y = Variable(torch.FloatTensor([X]), requires_grad=True), Variable(torch.FloatTensor([Y]), requires_grad=False)
        optimizer.zero_grad()
        outputs = net(X)
        loss = criterion(outputs, Y)
        loss.backward()
        optimizer.step()
        if (i % 10 == 0):
            print("Epoch {} - loss: {}".format(epoch, loss.data[0]))
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
x = torch.ones(2,2,requires_grad = True)
x
# In[ ]:
y = x+2
y
# In[ ]:
y.grad_fn
# In[ ]:
z = y*y*3
out = z.mean()
out
# In[ ]:3
a = torch.randn(2,2)
a = ((a*3)/(a-1))
a.requires_grad_(True)
# In[ ]:
out.backward()
# In[ ]:
x.grad
# In[ ]:


import requests
import json
import os
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta
from tqdm import tqdm
import re
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

# eprint RSS
base_url = 'https://eprint.iacr.org/rss/rss.xml'
xml_file = 'eprint.xml'
response = requests.get(base_url)

# last eprint
last_file = 'last.txt'

# Slack APIトークン
SLACK_API_TOKEN = 'xoxb-Slack API Token'
# Slackに投稿するチャンネル名を指定する
SLACK_CHANNEL = "#eprintまとめ"

# 翻訳APIのURL
# [参考：Google翻訳APIを無料で作る方法](https://qiita.com/satto_sann/items/be4177360a0bc3691fdf)
trancerate_url='Google scriptのURL'

## 英文を翻訳APIに流し込む関数
def get_summary(result):
    _params = {'text': f'{result}', 'source': 'en', 'target': 'ja'}
    r = requests.get(trancerate_url, params=_params)
    text_json = r.json()
    out_text = text_json['text']
    return out_text

with open(xml_file, "wb") as file:
    file.write(response.content)
    print("Complete DL rss file!")

with open(last_file, 'r') as file:
    lastnum = file.read()
    lastnum = lastnum.replace("/", "")
maxnum = lastnum

client = WebClient(token=SLACK_API_TOKEN)

tree = ET.parse(xml_file)
root = tree.getroot()

# itemタグの情報を抽出する
for item in tqdm(root.findall(".//item")):

    # ex) 'https://eprint.iacr.org/2023/548' => '2023548'
    eprintnum=re.findall('\d+', item.find("link").text)
    eprintnum = ''.join(eprintnum)

    # last.txtの値よりも大きい場合のみ投稿する
    if eprintnum > lastnum:

        # last.txtの値を更新する
        if maxnum < eprintnum:
            maxnum = eprintnum

        pub_date = item.find("pubDate").text
        pub_date = datetime.strptime(pub_date, "%a, %d %b %Y %H:%M:%S %z").strftime("%Y-%m-%d")

        title = item.find("title").text
        link = item.find("link").text
        description = item.find("description").text
        message = title+"について要約しました！ \n発行日："+ pub_date + "\n" + link + "\n" + get_summary(description)

        try:
            response = client.chat_postMessage(
            channel=SLACK_CHANNEL,
            text=message
            )
            # last.txtの値を更新する
            with open(last_file, 'w') as file:
                file.write(maxnum)
            print("Complete post message!")

        except SlackApiError as e:
            print(f"Error posting message: {e}")


"""
Error model classes for scaling.
"""

from __future__ import annotations

import logging
from math import ceil, exp, log

import numpy as np
from scipy.stats import norm

from dxtbx import flumpy
from iotbx import phil
from scitbx import sparse

from dials.array_family import flex
from dials.util import tabulate

logger = logging.getLogger("dials")

phil_scope = phil.parse(
    """
    error_model = *basic None
        .type = choice
        .help = "The error model to use."
        .expert_level = 1
    basic {
        a = None
          .type = float
          .help = "Used this fixed value for the error model 'a' parameter"
          .expert_level = 2
        b = None
          .type = float
          .help = "Used this fixed value for the error model 'b' parameter"
          .expert_level = 2
        minimisation = *individual regression None
          .type = choice
          .help = "The algorithm to use for basic error model minimisation."
                  "For individual, the a and b parameters are optimised"
                  "sequentially. For regression, a linear fit is made to"
                  "determine both parameters concurrently. If minimisation=None,"
                  "the model parameters are fixed to their initial or given values."
          .expert_level = 3
        min_Ih = 25.0
            .type = float
            .help = "Reflections with expected intensity above this value are to."
                    "be used in error model minimisation."
            .expert_level = 2
        n_bins = 10
            .type = int
            .help = "The number of intensity bins to use for the error model optimisation."
            .expert_level = 2
    }
    reset_error_model = False
        .type = bool
        .help = "If True, the error model is reset to the default at the start"
                "of scaling, as opposed to loading the current error model."
    grouping = individual grouped *combined
        .type = choice
        .help = "This options selects whether one error model is determined"
                "for all sweeps (combined), whether one error model is"
                "determined per-sweep (individual), or whether a custom"
                "grouping should be used. If grouping=grouped, each group"
                "should be specified with the error_model_group=parameter."
        .expert_level = 2
    error_model_group = None
        .type = ints
        .multiple = True
        .help = "Specify a subset of sweeps which should share an error model."
                "If no groups are specified here, this is interpreted to mean"
                "that all sweeps should share a common error model."

    """
)

def calc_sigmaprime(x, Ih_table) -> np.array:
    """Calculate the error from the model."""
    sigmaprime = (
        x[0] * np.sqrt(Ih_table.variances + np.square(x[1] * Ih_table.intensities))
    ) / Ih_table.inverse_scale_factors
    return sigmaprime

def calc_deltahl(Ih_table, n_h, sigmaprime) -> np.array:
    """Calculate the normalised deviations from the model."""
    I_hl = Ih_table.intensities
    g_hl = Ih_table.inverse_scale_factors
    I_h = Ih_table.Ih_values
    prefactor = np.sqrt((n_h - np.full(n_h.size, 1.0)) / n_h)
    delta_hl = prefactor * ((I_hl / g_hl) - I_h) / sigmaprime
    return delta_hl

class ErrorModelRegressionAPM:

    """Parameter manager for error model minimisation using the linear
    regression method.

    Allows refining of just a, just b or both."""

    def __init__(self, model, active_parameters):
        self.model = model
        self.components = {}
        self.active_parameters = active_parameters  # e.g. ["a", "b"]
        self.x = flex.double([])
        n_cumul_params = 0
        for p in active_parameters:
            if p in model.components:
                self.x.extend(model.components[p].parameters)
                self.components.update(
                    {p: {"start_idx": n_cumul_params, "end_idx": len(self.x)}}
                )
                n_cumul_params += 1

    def select_parameters(self, component):
        """Select the subset of self.x corresponding to the component (a string)."""
        start_idx = self.components[component]["start_idx"]
        end_idx = self.components[component]["end_idx"]
        return self.x[start_idx:end_idx]

    def set_param_vals(self, x):
        """Set method for refinement engine access."""
        self.x = x
        for name, component in self.model.components.items():
            if name in self.active_parameters:
                component.parameters = self.select_parameters(name)

    def get_param_vals(self):
        """Get method for refinement engine access."""
        return self.x

    def resolve_model_parameters(self):
        """Update parameters in the model."""
        if self.active_parameters == ["a"]:
            if not self.x[0] > 0:
                raise ValueError(
                    "Error model refinement resulted in a negative value for a^2"
                )
            a = self.x[0] ** 0.5
            b = self.model.parameters[1]
        elif self.active_parameters == ["b"]:
            if not self.x[0] > 0:
                raise ValueError(
                    "Error model refinement resulted in a negative value for b^2"
                )
            a = self.model.parameters[0]
            b = self.x[0] ** 0.5
        else:
            if not self.x[0] > 0:
                raise ValueError(
                    "Error model refinement resulted in a negative value for a^2"
                )
            if not self.x[1] > 0:
                raise ValueError(
                    "Error model refinement resulted in a negative value for b^2"
                )
            a = self.x[0] ** 0.5
            b = self.x[1] ** 0.5 / a
        self.model.update([a, b])

class ErrorModelA_APM:

    """Parameter manager for minimising A component with individual minimizer"""

    def __init__(self, model):
        self.model = model
        self.x = [0.0, model.components["a"].parameters[0]]

    def set_param_vals(self, x):
        """method for refinement engine access"""
        self.x = x

    def get_param_vals(self):
        """method for refinement engine access"""
        return self.x

    def resolve_model_parameters(self):
        """Update parameters in the model."""
        self.model.components["a"].parameters *= self.x[1]

class ErrorModelB_APM:

    """Parameter manager for minimising Bcomponent with individual minimizer"""

    def __init__(self, model):
        self.model = model
        self.x = [model.components["b"].parameters[0]]

    def set_param_vals(self, x):
        """method for refinement engine access"""
        self.x = x
        self.model.components["b"].parameters = flex.double([self.x[0]])
        self.model.binner.update(self.model.parameters)

    def get_param_vals(self):
        """method for refinement engine access"""
        return self.x

    def resolve_model_parameters(self):
        """Update parameters in the model."""
        self.model.components["b"].parameters = flex.double([self.x[0]])

class ErrorModelBinner:

    """A binner for the error model data.

    Data are binned based on Ih, and methods are available for
    calculating bin variances, summation within bins etc."""

    def __init__(self, Ih_table, min_reflections_required=250, n_bins=10):
        self.binning_info = {
            "initial_variances": [],
            "bin_boundaries": [],
            "mean_intensities": np.array([], dtype=float).reshape((0,)),
            "bin_variances": [],
            "refl_per_bin": [],
            "n_reflections": None,
        }
        self.n_bins = n_bins
        self.Ih_table = Ih_table
        self.min_reflections_required = min_reflections_required
        self.n_h = self.Ih_table.calc_nh()
        self.sigmaprime = calc_sigmaprime([1.0, 0.0], self.Ih_table)
        self.summation_matrix = self._create_summation_matrix()
        self.weights = np.array(self.binning_info["mean_intensities"])
        self.delta_hl = calc_deltahl(self.Ih_table, self.n_h, self.sigmaprime)
        self.bin_variances = self.calculate_bin_variances()
        self.binning_info["initial_variances"] = self.binning_info["bin_variances"]

    def update(self, parameters):
        """Update the variances for updated model parameters."""
        self.sigmaprime = calc_sigmaprime(parameters, self.Ih_table)
        self.delta_hl = calc_deltahl(self.Ih_table, self.n_h, self.sigmaprime)
        self.bin_variances = self.calculate_bin_variances()

    def _create_summation_matrix(self):
        """Create a summation matrix to allow sums into intensity bins.

        This routine attempts to bin into bins equally spaced in log(intensity),
        to give a representative sample across all intensities. To avoid
        undersampling, it is required that there are at least 100 reflections
        per intensity bin unless there are very few reflections."""
        n = self.Ih_table.size
        self.binning_info["n_reflections"] = n
        summation_matrix = sparse.matrix(n, self.n_bins)
        Ih = self.Ih_table.Ih_values * self.Ih_table.inverse_scale_factors
        size_order = flex.sort_permutation(flumpy.from_numpy(Ih), reverse=True)
        Imax = Ih.max()
        min_Ih = Ih.min()
        Imin = max(1.0, min_Ih)  # avoid log issues
        spacing = (log(Imax) - log(Imin)) / float(self.n_bins)
        boundaries = [Imax] + [
            exp(log(Imax) - (i * spacing)) for i in range(1, self.n_bins + 1)
        ]
        boundaries[-1] = min_Ih - 0.01
        self.binning_info["bin_boundaries"] = np.array(boundaries)
        self.binning_info["refl_per_bin"] = np.array([], dtype=float).reshape((0,))

        n_cumul = 0
        if Ih.size > 100 * self.min_reflections_required:
            self.min_reflections_required = int(Ih.size / 100.0)
        min_per_bin = min(self.min_reflections_required, int(n / (3.0 * self.n_bins)))
        for i in range(len(self.binning_info["bin_boundaries"]) - 1):
            maximum = self.binning_info["bin_boundaries"][i]
            minimum = self.binning_info["bin_boundaries"][i + 1]
            sel1 = Ih <= maximum
            sel2 = Ih > minimum
            sel = sel1 & sel2
            # isel = sel.iselection()
            n_in_bin = np.count_nonzero(sel)  # isel.size()
            if n_in_bin < min_per_bin:  # need more in this bin
                m = n_cumul + min_per_bin
                if m < n:  # still some refl left to use
                    idx = size_order[m]
                    intensity = Ih[idx]
                    self.binning_info["bin_boundaries"][i + 1] = intensity
                    minimum = self.binning_info["bin_boundaries"][i + 1]
                    sel = sel1 & (Ih > minimum)
                    # isel = sel.iselection()
                    n_in_bin = np.count_nonzero(sel)  # isel.size()
            self.binning_info["refl_per_bin"] = np.append(
                self.binning_info["refl_per_bin"], [n_in_bin]
            )
            for j in np.nonzero(sel)[0]:  # isel:
                summation_matrix[int(j), i] = 1
            n_cumul += n_in_bin
        cols_to_del = []
        for i, col in enumerate(summation_matrix.cols()):
            if col.non_zeroes < min_per_bin - 5:
                cols_to_del.append(i)
        n_new_cols = summation_matrix.n_cols - len(cols_to_del)
        if n_new_cols == self.n_bins:
            for i in range(len(self.binning_info["bin_boundaries"]) - 1):
                maximum = self.binning_info["bin_boundaries"][i]
                minimum = self.binning_info["bin_boundaries"][i + 1]
                sel1 = Ih <= maximum
                sel2 = Ih > minimum
                sel = sel1 & sel2
                self.binning_info["mean_intensities"] = np.append(
                    self.binning_info["mean_intensities"], [np.mean(Ih[sel])]
                )
            return summation_matrix
        new_sum_matrix = sparse.matrix(summation_matrix.n_rows, n_new_cols)
        next_col = 0
        refl_per_bin = np.array([], dtype=float).reshape((0,))
        new_bounds = np.array([], dtype=float).reshape((0,))
        for i, col in enumerate(summation_matrix.cols()):
            if i not in cols_to_del:
                new_sum_matrix[:, next_col] = col
                next_col += 1
                new_bounds = np.append(
                    new_bounds, [self.binning_info["bin_boundaries"][i]]
                )
                refl_per_bin = np.append(
                    refl_per_bin, [self.binning_info["refl_per_bin"][i]]
                )
        self.binning_info["refl_per_bin"] = refl_per_bin
        new_bounds = np.append(new_bounds, [self.binning_info["bin_boundaries"][-1]])
        self.binning_info["bin_boundaries"] = new_bounds
        for i in range(len(new_bounds) - 1):
            maximum = new_bounds[i]
            minimum = new_bounds[i + 1]
            sel1 = Ih <= maximum
            sel2 = Ih > minimum
            sel = sel1 & sel2
            self.binning_info["mean_intensities"] = np.append(
                self.binning_info["mean_intensities"], [np.mean(Ih[sel])]
            )
        return new_sum_matrix

    def calculate_bin_variances(self) -> np.array:
        """Calculate the variance of each bin."""
        sum_deltasq = flumpy.to_numpy(
            flumpy.from_numpy(np.square(self.delta_hl)) * self.summation_matrix
        )
        sum_delta_sq = np.square(
            flumpy.to_numpy(flumpy.from_numpy(self.delta_hl) * self.summation_matrix)
        )
        bin_vars = (sum_deltasq / self.binning_info["refl_per_bin"]) - (
            sum_delta_sq / np.square(self.binning_info["refl_per_bin"])
        )
        self.binning_info["bin_variances"] = bin_vars
        return bin_vars

class BComponent:

    """The basic error model B parameter component"""

    def __init__(self, initial_value=0.02):
        self.parameters = flex.double([initial_value])
        self._n_params = 1

class AComponent:

    """The basic error model A parameter component"""

    def __init__(self, initial_value=1.00):
        self.parameters = flex.double([initial_value])
        self._n_params = 1

class BasicErrorModel:

    """Definition of a basic two-parameter error model."""

    min_reflections_required = 250

    id_ = "basic"

    def __init__(self, a=None, b=None, basic_params=None):

        """
        A basic two-parameter error model s'^2 = a^2(s^2 + (bI)^2)

        If a and b are not given as arguments, the params scope is checked to
        see if a user specified fixed value is set. If no fixed values are given
        then the model starts with the default parameters a=1.0 b=0.02
        """

        self.free_components = []
        self.sortedy = None
        self.sortedx = None
        self.binner = None
        if not basic_params:
            basic_params = phil_scope.fetch().extract().basic
        self.params = basic_params
        self.filtered_Ih_table = None
        if not a:
            a = basic_params.a
            if not a:
                a = 1.0
        if not b:
            b = basic_params.b
            if not b:
                b = 0.02
        self.components = {"a": AComponent(a), "b": BComponent(b)}
        self._active_parameters = []
        # if the parameters have been set in the phil scope, then these are to be fixed
        if not basic_params.a:
            self._active_parameters.append("a")
        if not basic_params.b:
            self._active_parameters.append("b")

    def configure_for_refinement(self, Ih_table, min_partiality=0.4):
        """
        Add data to allow error model refinement.

        Raises: ValueError if insufficient reflections left after filtering.
        """
        self.filtered_Ih_table = self.filter_unsuitable_reflections(
            Ih_table, self.params, min_partiality
        )
        # always want binning info so that can calc for output.
        self.binner = ErrorModelBinner(
            self.filtered_Ih_table, self.min_reflections_required, self.params.n_bins
        )
        # need to calculate sorted deltahl for norm dev plotting (and used by
        # individual a-parameter minimiser)
        self.calculate_sorted_deviations(self.parameters)

        self.binner.update(self.parameters)

    @property
    def active_parameters(self):
        return self._active_parameters

    @property
    def parameters(self):
        """A list of the model parameters."""
        return [
            self.components["a"].parameters[0],
            abs(self.components["b"].parameters[0]),
        ]

    @parameters.setter
    def parameters(self, parameters):
        assert len(parameters) == 2
        self.components["a"].parameters = flex.double([parameters[0]])
        self.components["b"].parameters = flex.double([parameters[1]])

    def finalise(self):
        """Perform any actions after minimisation finished."""
        logger.info(self.binned_variances_summary())

    @property
    def n_refl(self):
        """The number of reflections being used in minimisation"""
        return self.filtered_Ih_table.size

    @classmethod
    def filter_unsuitable_reflections(cls, Ih_table, error_params, min_partiality):
        """Filter suitable reflections for minimisation."""
        return filter_unsuitable_reflections(
            Ih_table,
            min_Ih=error_params.min_Ih,
            min_partiality=min_partiality,
            min_reflections_required=cls.min_reflections_required,
        )

    def calculate_sorted_deviations(self, parameters):
        """Sort the x,y data."""
        sigmaprime = calc_sigmaprime(parameters, self.filtered_Ih_table)
        delta_hl = calc_deltahl(
            self.filtered_Ih_table, self.filtered_Ih_table.calc_nh(), sigmaprime
        )
        central_cutoff = 1.5
        n = delta_hl.size
        self.sortedy = np.sort(delta_hl)
        v1 = norm.cdf(-central_cutoff)
        v2 = norm.cdf(central_cutoff)
        idx_cutoff_min = ceil(
            (v1 * n) - 0.5
        )  # first one within the central cutoff range
        idx_cutoff_max = ceil(
            (v2 * n) - 0.5
        )  # first one above the central cutoff range
        central_n = idx_cutoff_max - idx_cutoff_min
        v = np.linspace(
            start=(idx_cutoff_min + 0.5) / n,
            stop=(idx_cutoff_max + 0.5) / n,
            endpoint=False,
            num=central_n,
        )

        self.sortedx = flumpy.from_numpy(norm.ppf(v))
        self.sortedy = flumpy.from_numpy(self.sortedy[idx_cutoff_min:idx_cutoff_max])

    def update(self, parameters):
        """Update the model with new parameters."""
        self.parameters = parameters
        self.binner.update(parameters)
        self.calculate_sorted_deviations(parameters)

    def update_variances(self, variances, intensities):
        """Use the error model parameter to calculate new values for the variances."""
        new_variance = (self.parameters[0] ** 2) * (
            variances + np.square(self.parameters[1] * intensities)
        )
        return new_variance

    def clear_Ih_table(self):
        """Delete the Ih_table, to free memory."""
        if self.binner:
            self.binner.Ih_table = None

    def __str__(self):
        a = abs(self.parameters[0])
        b = abs(self.parameters[1])
        ISa = f"{1.0 / (b * a):.3f}" if (b * a) > 0 else "Unable to estimate"
        return "\n".join(
            (
                "",
                "Error model details:",
                "  Type: basic",
                f"  Parameters: a = {a:.5f}, b = {b:.5f}",
                "  Error model formula: "
                + "\u03C3"
                + "'"
                + "\xb2"
                + " = a"
                + "\xb2"
                + "("
                + "\u03C3\xb2"
                " + (bI)" + "\xb2" + ")",
                "  estimated I/sigma asymptotic limit: %s" % ISa,
                "",
            )
        )

    def binned_variances_summary(self):
        """Generate a summary of the model minimisation for output."""
        header = [
            "Intensity range (<Ih>)",
            "n_refl",
            "Uncorrected variance",
            "Corrected variance",
        ]
        rows = []
        bin_bounds = [f"{i:.2f}" for i in self.binner.binning_info["bin_boundaries"]]
        for i, (initial_var, bin_var, n_refl) in enumerate(
            zip(
                self.binner.binning_info["initial_variances"],
                self.binner.binning_info["bin_variances"],
                self.binner.binning_info["refl_per_bin"],
            )
        ):
            rows.append(
                [
                    bin_bounds[i] + " - " + bin_bounds[i + 1],
                    str(int(n_refl)),
                    str(round(initial_var, 3)),
                    str(round(bin_var, 3)),
                ]
            )
        return "\n".join(
            (
                "Results of error model refinement. Uncorrected and corrected variances",
                "of normalised intensity deviations for given intensity ranges. Variances",
                "are expected to be ~1.0 for reliable errors (sigmas).",
                tabulate(rows, header),
                "",
            )
        )

def filter_unsuitable_reflections(
    Ih_table, min_Ih, min_partiality, min_reflections_required
):
    """
    Choose reflection groups with n_h > 1, as these have deltas of zero by
    definition and will bias the variance calculations. Also, only use groups
    where <Ih> > 25.0, as the assumptions of normally distributed deltas will
    not hold for low <Ih>."""

    if "partiality" in Ih_table.Ih_table:
        sel = Ih_table.Ih_table["partiality"].to_numpy() > min_partiality
        Ih_table = Ih_table.select(sel)

    n = Ih_table.size
    sum_I_over_var = Ih_table.sum_in_groups(Ih_table.intensities / Ih_table.variances)
    n_per_group = Ih_table.sum_in_groups(np.full(n, 1))
    avg_I_over_var = sum_I_over_var / n_per_group
    sel = avg_I_over_var > 0.85
    Ih_table = Ih_table.select_on_groups(sel)
    n_h = Ih_table.calc_nh()
    scaled_Ih = Ih_table.Ih_values * Ih_table.inverse_scale_factors
    # need a scaled min_Ih, where can reasonably expect norm distribution
    # (use min_Ih=25 by default, sigma ~ 5)
    sel2 = scaled_Ih > min_Ih
    # can't calculate a true deviation for groups of 1
    sel3 = n_h > 1.0
    sel4 = Ih_table.intensities > 0.001
    # don't want to include weaker reflections where the background adds
    # significantly to the variances, as these would no longer be normally
    # distributed and skew the fit.
    Ih_table = Ih_table.select(sel2 & sel3 & sel4)
    n = Ih_table.size
    if n < min_reflections_required:
        raise ValueError(
            "Insufficient reflections (%s < %s) to perform error modelling."
            % (n, min_reflections_required)
        )
    n_h = Ih_table.calc_nh()
    # now make sure any left also have n > 1
    sel = n_h > 1.0
    Ih_table = Ih_table.select(sel)

    #  Filter groups with abnormally high internal variances.
    # For a reasonable quality dataset, if b=0.04, a=1.25, then for large Imax,
    # the ratio of the corrected per-reflection variance to the original is
    # (var'/var)^2 ~= (ab)^2 Imax ~= Imax / 400. So filter any groups where the
    # internal variance is more than 10x what would reasonably be expected after
    # error model correction.
    I = Ih_table.intensities
    mu = Ih_table.Ih_values
    g = Ih_table.inverse_scale_factors
    n_h = Ih_table.sum_in_groups(np.full(Ih_table.size, 1.0))

    group_variances = Ih_table.sum_in_groups(((I / g) - mu) ** 2) / (
        n_h - np.full(n_h.size, 1.0)
    )
    avg_variances = Ih_table.sum_in_groups(Ih_table.variances / (g**2)) / n_h
    ratio = group_variances / avg_variances
    sel = ratio < max(50, (np.max(mu) / 40.0))
    logger.debug(
        f"{sel.size - np.count_nonzero(sel)}/{sel.size} symmetry groups excluded "
        "from error model analysis due to high internal variance"
    )
    Ih_table = Ih_table.select_on_groups(sel)
    n = Ih_table.size
    if n < min_reflections_required:
        raise ValueError(
            "Insufficient reflections (%s < %s) to perform error modelling."
            % (n, min_reflections_required)
        )
    return Ih_table


import time
import numpy as np
import torch
from utils import *
from params import *
from reconstruction import *
import scipy
import cv2
import skimage.measure
from itertools import compress

def lpf_detection(holo,mask,erode_size=20, dilate_size=60, threshold=10, A_min = 1, show_plot=False):
    # mask for low pass filter generated by create_lpf_mask (calculated outside of this function to
    #     optimize processing time)
    # erode size and dilate size are in number of pixels
    # threshold is in raw intensity
    # A_min is in mm^2

    # calculate image FFT
    #img = np.float32(holo.squeeze())
    dft = np.fft.fft2(holo)
    dft_shift = np.fft.fftshift(dft)
    f_ishift = np.fft.ifftshift(dft_shift)

    # apply mask and calculate inverse FFT
    fshift = dft_shift * mask

    proc_im = np.fft.ifft2(fshift)
    proc_im = np.abs(proc_im)

    # apply threshold to create binary image
    proc_im[proc_im < threshold] = 0
    proc_im[proc_im > 0] = 1

    # perform erosion and dilation
    if erode_size > 0:
        eroder = cv2.getStructuringElement(cv2.MORPH_RECT,(erode_size,erode_size));
        proc_im = cv2.morphologyEx(proc_im, cv2.MORPH_ERODE, eroder)

    if dilate_size > 0:
        dilater = cv2.getStructuringElement(cv2.MORPH_RECT,(dilate_size,dilate_size));
        proc_im = cv2.morphologyEx(proc_im, cv2.MORPH_DILATE, dilater)

    # find regions in binary image
    labeled_im = skimage.measure.label(proc_im,connectivity=2)
    regions = skimage.measure.regionprops(labeled_im)
    A = np.array([region.area for region in regions])
    regions = list(compress(regions,A > A_min/((pix_size*1e3)**2)))

    if show_plot:
        plt.figure(4).clf()
        plt.subplot(212)
        plt.imshow(proc_im)

        plt.subplot(211)
        plt.imshow(-holo)

        for region in regions:
            minr, minc, maxr, maxc = region.bbox
            bx = (minc, maxc, maxc, minc, minc)
            by = (minr, minr, maxr, maxr, minr)
            plt.plot(bx,by,'-r',linewidth=2)

    return regions

def create_lpf_mask(holo,keep_frac=0.05):
    # create low pass filter mask, keeping only "keep_frac"
    # fraction of lowest frequencies
    # calculating this once for all holos saves about 0.04 seconds per hologrma

    # e.g., keep_frac = 0.05 keeps 5% of frequencies

    rows, cols = holo.shape
    crow, ccol = int(rows / 2), int(cols / 2)

    mask = np.zeros((rows, cols), np.uint8)
    rr = keep_frac*(rows/2)
    rc = keep_frac*(cols/2)
    center = [crow, ccol]
    x, y = np.ogrid[:rows, :cols]
    mask_area = (x - center[0]) ** 2/rr**2 + (y - center[1]) ** 2/rc**2 <= 1
    mask[mask_area] = 1

    return mask


import os
import spacy
import string

def get_size_of_corpus(filepaths):
    """ Given a list of filepaths, it will return the total number of lines

        Parameters
        ----------
        filepaths : [ str ]
            A list of filepaths

        Returns
        -------
        num_lines : int
            The total number of lines in filepaths
    """

    def blocks(files, size=65536):
        while True:
            b = files.read(size)
            if not b:
                break
            yield b

    num_lines = 0
    for filepath in filepaths:
        with open(filepath, encoding="utf-8") as f:
            num_lines += sum(bl.count("\n") for bl in blocks(f))

    return num_lines

def get_tokens_from_line(line, spacy_instance):
    global PUNCTUATION_TABLE, LEGAL_CHARS_TABLE, LEGAL_CHARS

    # Make the text lowercase and remove the \n
    line = line.lower().strip()

    # Standardize single quotations
    line = (
        line.replace("\u2019", "'")
        .replace("\u0060", "'")
        .replace("\u00B4", "'")
        .replace("\u2018", "'")
        .replace("\u201A", "'")
        .replace("\u201B", "'")
        .replace("\u2039", "'")
        .replace("\u203A", "'")
        .replace("\u275B", "'")
        .replace("\u275C", "'")
        .replace("\u276E", "'")
        .replace("\u276F", "'")
    )

    # Standardize dashes
    line = (
        line.replace("\u00AD", "-")
        .replace("\u2013", "-")
        .replace("\u2014", "-")
        .replace("\u2015", "-")
        .replace("\u2212", "-")
        .replace("\u02D7", "-")
    )

    # Standardize double quotations
    line = (
        line.replace("\u201C", '"')
        .replace("\u201D", '"')
        .replace("\u2033", '"')
        .replace("\u00AB", '"')
        .replace("\u00BB", '"')
        .replace("\u201E", '"')
        .replace("\u201F", '"')
        .replace("\u275D", '"')
        .replace("\u275E", '"')
        .replace("\u301D", '"')
        .replace("\u301E", '"')
        .replace("\u301F", '"')
        .replace("\uFF02", '"')
    )

    # Standardize the ellipses
    line = line.replace("\u2026", "...")

    # Tokenize the text
    tokens = spacy_instance.tokenizer(line)

    # Remove tokens that are spaces, tabs, newlines, etc
    tokens = list(filter(lambda token: not token.is_space, tokens))

    # Extract only the text
    tokens = [token.text for token in tokens]

    # Replace tokens that contain numbers with 'NUM'
    num_vals = []
    new_tokens = []
    for token in tokens:
        new_token = token

        if any(char.isdigit() for char in token):
            new_token = "NUM"
            num_vals.append(token)

        new_tokens.append(new_token)

    tokens = new_tokens

    return tokens, num_vals

def read_transcription_files(filepaths, spacy_instance):
    """ Generate line info from data in a file for a given language

        Parameters
        ----------
        lang : {'en', 'fr'}
            Whether to tokenize the English sentences ('e') or French ('f').
        filenames : sequence
            Only tokenize sentences with matching names. If :obj:`None`, searches
            the whole directory in C-sorted order.

        Yields
        ------
        tokenized, filename, offs : list
            `tokenized` is a list of tokens for a line. `filename` is the source
            file. `offs` is the start of the sentence in the file, to seek to.
            Lines are yielded by iterating over lines in each file in the order
            presented in `filenames`.
    """
    for filepath in filepaths:
        with open(filepath, encoding="utf-8") as f:
            offs = f.tell()
            line = f.readline()
            while line:
                tokens, _ = get_tokens_from_line(line, spacy_instance)

                yield tokens, filepath, offs
                offs = f.tell()
                line = f.readline()

def get_parallel_text(dir_, langs):
    """ Get a list of all files in 'dir_' with a file extension that is in 'langs'

        Parameters
        ----------
        dir_ : str
            A path to the transcription dictionary
        langs : [str]
            A list of file extensions for the parallel texts

        Returns
        -------
        filenames : list
            A list of all parallel texts' file names without the file extension
    """
    # Get a set of files that has the lang file extension
    files = os.listdir(dir_)
    filenames = []
    for lang in langs:
        lang = "." + lang
        lang_filenames = set(
            filename[:-3] for filename in files if filename.endswith(lang)
        )
        filenames.append(lang_filenames)
    del files

    if len(filenames) == 0:
        raise ValueError(
            f"Directory {dir_} contains no transcriptions ending in {lang} "
        )

    # Get the set of files that has the same name
    transcriptions_filenames = filenames[0]
    for lang_filenames in filenames:
        transcriptions_filenames = transcriptions_filenames & lang_filenames

    transcriptions_filenames = sorted(transcriptions_filenames)

    if len(transcriptions_filenames) == 0:
        raise ValueError(
            f"Directory {dir_} contains no common files ending in {lang}."
            f"Are you sure this is the right directory?"
        )

    # Create the output
    parallel_text = []
    for filename in transcriptions_filenames:
        parallel_text.append(tuple([filename + "." + lang for lang in langs]))

    return parallel_text

def get_spacy_instance(lang, spacy_namespace=None):
    """ Returns the correct Spacy instance given the lang ISO.
        If the namespace is provided, it will use the namespace instead

        Parameters
        ----------
        lang : { 'en', 'fr' }
            The lang ISO
        spacy_namespace : str, optional
            The Spacy namespace

        Returns
        -------
        spacy_instance : Spacy
            The Spacy instance with the correct language
    """
    if spacy_namespace is None:
        if lang == "en":
            spacy_namespace = "en_core_web_sm"
        elif lang == "fr":
            spacy_namespace = "fr_core_news_sm"
        else:
            raise Exception("Unknown language: " + lang)

    # For sentence segmentation, we are using dependency parse
    # To use rule-based sentence segmentation, follow https://spacy.io/usage/linguistic-features#sbd-component
    spacy_instance = spacy.load(spacy_namespace)

    return spacy_instance


def DFS_Node(key):
    while key != G:
        distance_level = 0
        Queue = []
        Queue.append((key, distance_level))
        while Queue:
            key, distance_level = Queue.pop(0)
            visit[key-1] = True
            if 1 in Path_list[key-1]:
                for i in range(V):
                    if Path_list[key-1][i] == 1 and visit[i] is False:
                        if i+1 == G:
                            return distance_level+1
                        else:
                            Queue.append((i+1, distance_level+1))

        if not Queue and key != G:
            return 0

T = int(input())
for test_case in range(1, T+1):
    V, E = map(int,input().split())
    Path_list = [[0 for _ in range(V)] for _ in range(V)]
    for i in range(E):
        a, b = map(int,input().split())
        Path_list[a-1][b-1] = 1
        Path_list[b-1][a-1] = 1

    S, G = map(int,input().split())
    visit = [False for _ in range(V)]
    visit[S-1] = True
    key = S

    print('#'+str(test_case), DFS_Node(key))


# -*- coding: utf-8 -*-
"""
Created on Mon Mar  6 19:37:49 2017

@author: Simon
"""
from  scipy import *
from  pylab import *
import scipy.misc as sm
import scipy.sparse as sparse

v = sm.imread('kvinna.jpg', True)

#cut away pixels to have even number of y and x pixels
if len(v[:, 0]) % 2 != 0:
    v = v[1:, :]

if len(v[0, :]) % 2 != 0:
    v = v[:, 1:]

y = len(v[:, 0])
x = len(v[0, :])

"""
Algoritmen tar W*v = y.
Vi önskar konstruera W. Första gör vi v endimensionell och sedan konstruerar
vi en allmän W från denna längd
"""

print(x)
print(y)

v = v.reshape(1, -1)[0]

def createW(n):
	W = zeros([n,n])
	i = 0
	for j in range(int(n/2)):
		W[j, i] = 1/sqrt(2)
		W[j, i+1] = 1/sqrt(2)
		i += 2
	i = 0
	for j in range(int(n/2), n):
		W[j, i] = -1/sqrt(2)
		W[j, i+1] = 1/sqrt(2)
		i += 2
	return W

#override for test
v = array([100, 200, 44, 50, 20, 20, 4, 2])

W = createW(len(v))

#print(W)
print(abs(W.T - inv(W)) <  0.0001)
#print(inv(W))

y = dot(W, v)

print(y)


#pointFile.py

from . import plt, np, random
from ._plotSettFile import plotSett
from . import seed
from .Settings import settings

class point(plotSett):
    def __init__(self, pickFrom = None, x = None, y = None, seed = seed, draw = True):
        super().__init__()

        self.seed = seed
        self.data = [None, None]

        #return True if var is a  number
        pf_isnumber = isinstance(pickFrom, (int, float) )

        #check if x and y are numbers
        xy_arenumber =  ( isinstance(x, (int, float) ) ) and ( isinstance(y, (int, float) ) )

        #shift of variables:pickFrom become x, x become y
        if pf_isnumber == True:
            self.data[0] = pickFrom
            self.data[1] = x

        #no arguments return random coords
        elif pickFrom is None and x is None and y is None:
            self.randomCoords(self.seed)

        #chooce point coords from a geometrical locus
        elif pf_isnumber == False and xy_arenumber == False:
            self.pickFrom = pickFrom.data
            self.randomPoint()

        elif xy_arenumber == True:
            self.data[0] = x
            self.data[1] = y

        """
        #------------------------------------------------------------
        # Get local variables as a dictionary
        local_vars = locals()

        # Convert the dictionary values to a list
        args_list = list(local_vars.values())
        #------------------------------------------------------------
        """

        self.j = 0
        self._color = random.choice(self.colors)
        self.lines = None
        self.tex = None

        self.coords = self.data
        self.data = [ np.array([u]) for u in self.data  ]

        if draw == True:
            self.draw()

    @property
    def x(self):
        return self.data[0]

    @x.setter
    def x(self, value):
        self.data[0] = np.array( [ value ] )
        self.coords[0] = value
        self.lims()
        self.draw()
        self.label(self._name)

    @property
    def y(self):
        return self.data[1]

    @y.setter
    def y(self, value):
        self.data[1] = np.array( [ value ] )
        self.coords[1] = value
        self.lims()
        self.draw()
        self.label(self._name)

    @property
    def equation(self):

        try:
            self.tex.remove()
        except:
            pass

        idx = self.condition_mask()
        data = [self.data[0][idx], self.data[1][idx] ]
        random_index = np.random.randint(len(data[0]))
        shift = (settings.xmax - settings.xmin)/40
        labelx = data[0][random_index] + shift
        labely = data[1][random_index] + shift
        #--------------------

        x = str(round(self.coords[0], 2))
        y = str(round(self.coords[1], 2))
        eq = "(" + x + ";" + y + ")"
        try:
            eq = self._name + eq
        except:
            pass

        if self.j%2 == 0:
            self.tex = self.ax.text(labelx, labely, eq, fontsize = 12, color = self._color, ha="center", va="center")
        self.j += 1

    #coords as a list of two numpy arrays of one element each
    def calc(self):
        pass
        #self.data = [ np.array([u]) for u in self.data  ]

    #it overwrites the .draw method in _plotSett
    def draw(self):
        self.__del__()
        self.lims()
        if self.rotate == False:
            self.calc()

        line = self.ax.scatter( self.data[0], self.data[1], color = self._color, linewidth = self._linewidth)
        self.lines = []
        self.lines.append(line)

    #-----------------------------------------------
    def randomCoords(self, seed):
        self.data[0] = random.uniform(settings.xmin, settings.xmax)
        self.data[1] = random.uniform(settings.xmin, settings.xmax)
        self.seed += 1
        seed = self.seed

    #random Point from a geometrical locus
    def randomPoint(self):
        condition_mask = ( self.pickFrom[1] > settings.xmin) & (self.pickFrom[1] < settings.xmax)
        indices = np.where(condition_mask)
        idx = random.choice(indices[0])
        self.data = [self.pickFrom[0][idx], self.pickFrom[1][idx] ]
    #-------------------------------------------------------------
    def zoom(self):

        a = plt.ginput()

        m = settings.xmin
        M = settings.xmax

        deltaZoom = (M - m)/10

        self.ax.set_xlim( a[0][0] - deltaZoom, a[0][0] + deltaZoom)
        self.ax.set_ylim( a[0][1] - deltaZoom, a[0][1] + deltaZoom)

    def click(self):
        self.__del__()

        b = plt.ginput()
        self.data = [ b[0][0], b[0][1] ]
        self.draw()
        self.label(self._name)

        self.lims()

    def rotation(self, locus = None, angle = 0):
        locus.rotate = True
        a1 = (locus.data[0] - self.data[0])*np.sin(angle)
        locus.data[0] = (locus.data[0] - self.data[0]  )*np.cos(angle) - (locus.data[1] - self.data[1]  )*np.sin(angle) + self.data[0]

        locus.data[1] = a1 + ( locus.data[1] - self.data[1])*np.cos(angle) + self.data[1]

        locus.draw()#, draw = False)
    def __str__(self):

        super().__str__()

        attributes = (
            f"\033[93mClass type:\033[0m point\n"
            f"\nAttributes:\n"
            f"\033[93mcoords:\033[0m [{self.data[0]}, {self.data[1]}] \n"
            f"\033[93mname:\033[0m {self._name}\n"
            f"\033[93mcolor:\033[0m {self._color}\n"
        )

        methods = (
            f"\nMethods:\n"
            f"\033[93mclick()\033[0m\n"
            f"\033[93mrotation(locus, angle = radiants)\033[0m\n"
            f"\033[93merase()\033[0m\n"
        )

        return attributes + methods + self.plotSettings

    def __del__(self):
        super().__del__()
        try:
            self.tex.remove()
        except:
            pass


# 返回元素为字符串的list
# 参数是[100,800]的list
from sympy import *
import numpy as np
import pyperclip

def p6_2_volume_rotate_x_none():
    x = symbols('x')
    #
    # y1 = 4*x; y2 = 4*sqrt(x); xx = solve(y1-y2); d = 4;
    # y1 = 1+sec(5*x); y2 = 3;xx=[-pi/15,pi/15];d=1;
    y1 = x**2/4; y2=1/2*x; xx = solve(y1-y2); d = 0;
    # y1 = 2*sqrt(x); y2 = 0; xx = solve(y1-y2); d = 0;print(xx);xx=[2,xx[0]]
    # y1 = 2*sqrt(25-x**2); y2 = 0; xx = [1, 3]; d = 0;
    # y1 = 2/x; y2 = 0; xx = [1, 5]; d = -1;
    return p6_2_volume_rotate_x(y1,y2,xx,d)

def p6_2_t_fan_2(red_word):
    red_word = list(map(int,red_word))
    result = []
    x = symbols('x')
    #
    y1 = red_word[1]/red_word[0]*x**2; y2 = red_word[2]/red_word[3]*x;
    xx = solve(y1-y2); d = 0;
    return p6_2_volume_rotate_x(y1,y2,xx,d)

def p6_2_x_t_d(red_word):
    red_word = list(map(int,red_word))
    result = []
    x = symbols('x')
    #
    y1 = red_word[1]/x; y2 = red_word[2]; xx = [red_word[3], red_word[4]]; d = red_word[0];
    return p6_2_volume_rotate_x(y1,y2,xx,d)

def p6_2_volume_rotate_x_4sqrt(red_word):
    x = symbols('x')
    #
    y1 = 4*x; y2 = 4*sqrt(x); xx = solve(y1-y2); d = red_word[0];
    return p6_2_volume_rotate_x(y1,y2,xx,d)

def p6_2_volume_rotate_x(y1,y2,xx,d):
    result = []
    x = symbols('x')
    #
    x0 = xx[0]; x1 = xx[1];
    a = pi * ((y1-d)**2 - (y2-d)**2);
    s = integrate(a, (x,x0, x1))
    ls = latex(abs(s)).replace('log','ln')
    result.append(ls)
    return result

if __name__ == '__main__':
    red_word = [4,1,1,2] #1291778,1
    for i in p6_2_t_fan_2(red_word):
    # for i in p6_2_volume_rotate_x_none():
        print(i)


#!/usr/bin/env python3
import sys
import math

sys.setrecursionlimit(1000000)

def solve(N: int, A: "List[int]", B: "List[int]"):
    g = [list() for _ in range(N)]
    visited = [False for _ in range(N)]
    ans = [False for _ in range(N)]
    for i in range(N-1):
        g[A[i]-1].append(B[i]-1)
        g[B[i]-1].append(A[i]-1)

    def dfs(bool, n):
        visited[n] = True
        if bool:
            ans[n] = bool
        bool = not bool
        for i in g[n]:
            if visited[i]:
                continue
            dfs(bool, i)
    dfs(False, 0)
    x = [i+1 for i, b in enumerate(ans) if b]
    y = [i+1 for i, b in enumerate(ans) if not b]
    if len(x) >= math.ceil(N/2):
        print(*x[:math.ceil(N/2)])
    else:
        print(*y[:math.ceil(N/2)])
    return

# Generated by 2.5.0 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [int()] * (N - 1)  # type: "List[int]"
    B = [int()] * (N - 1)  # type: "List[int]"
    for i in range(N - 1):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
    solve(N, A, B)

if __name__ == '__main__':
    main()