from __future__ import print_function
from dvn.utils import get_itk_array,write_itk_imageArray
import numpy as np
from dvn import FCN, VNET, UNET
from dvn import Network as NET
from dvn import losses as ls
import argparse
import os
import keras as K

# Defined global variables here .................................
BLOCK_SIZE = (64, 64, 64)
OVERLAP_SIZE = (5, 5, 5)
SEL_TOP = 50

def norm_data(data):
    data = data - np.min(data)
    data = data * 1.0 / np.max(data)
    return data

def histinfo(data, cfreq):
    bins = np.arange(np.min(data), np.max(data), 10)
    vals, bins = np.histogram(data, bins, density=True)
    acc = 0
    cutoff = np.max(bins)
    cfreq *= sum(vals)
    for i, v in enumerate(vals):
        acc = acc+v
        if acc >= cfreq:
            cutoff = bins[i]
            break

    return data

def processdata(X, hist_cutoff, n_in):
    if n_in == 1:
        data = histinfo(data=X, cfreq=float(hist_cutoff))
        data = norm_data(data=data)
        return data
    else:
        cfs = hist_cutoff.split(' ')
        if len(cfs) == 1:
            cfs = cfs * len(X)
        assert len(X) == len(cfs), 'Number of channels must match with number of histogram cutoffs'
        data = np.zeros(X.shape, dtype=X.dtype)
        for i in range(len(X)):
            data[i] = norm_data(histinfo(data=X[i], cfreq=float(cfs[i])))

        return data

def load_model(filename=None, n_in=1, n_out=2, modelType=0, use_crosshair=False):
    if filename is None:
        modelType = [FCN, VNET, UNET][modelType]
        model = modelType(nlabels=n_out, nchannels=n_in, cross_hair=use_crosshair)
    else:
        filename = os.path.abspath(filename)
        model = NET.load(filename)

    return model

def train_model(model,data_x,data_y,data_mask,batch_size,n_epochs,lr,weighted_cost,initial_epoch=0):
    k = []
    if weighted_cost:
        for l in np.unique(data_y):
            if l != 0:
                k.append(l)
    sgd = K.optimizers.SGD(lr=lr, decay=0, momentum=0, nesterov=False)
    loss = ls.weighted_categorical_crossentropy_with_fpr(classes=len(k)) if weighted_cost else ls.categorical_crossentropy(axis=1)
    model.compile(optimizer=sgd, loss=loss)
    model.fit(x=data_x,y=data_y,epochs=n_epochs,batch_size=batch_size,initial_epoch=initial_epoch)
    return model, lr

def generate_data(inputFn,labelFn,maskFn,preprocess=False,hist_cutoff=[],n_in=1, cube_size=64):
    iFn = []
    lFn = []
    mFn = []
    with open(os.path.abspath(inputFn)) as f:
        iFn = f.readlines()
    iFn = [x.strip() for x in iFn]

    with open(os.path.abspath(labelFn)) as f:
        lFn = f.readlines()
    lFn = [x.strip() for x in lFn]

    if not maskFn is None:
        with open(os.path.abspath(maskFn)) as f:
            mFn = f.readlines()
        mFn = [x.strip() for x in mFn]

    data_x = []
    data_y = []
    data_mask = []

    if not maskFn is None:
        for ifn,lfn,mfn in zip(iFn,lFn,mFn):
            if n_in == 1:
                X = get_itk_array(ifn)
            else:
                ifns = ifn.split('\t')
                assert len(ifns) >= n_in, 'Number of Input files per line should match the number of channels (tab separated!)'
                X = []
                sh = None
                for ii in ifns[:n_in]:
                    x = get_itk_array(ii)
                    assert (sh is None) or sh == x.shape, 'Input files should have the same shape'
                    X.append(x)

        X = np.array(X).astype('float32')
        Y = get_itk_array(lfn)
        M = get_itk_array(mfn)

        assert X.shape[-3:] == Y.shape
        assert X.shape[-3:] == M.shape

        if preprocess:
            X = processdata(X=X, hist_cutoff=hist_cutoff, n_in=n_in)
            data_x.append(X)
        else:
            data_x.append(X)
        data_y.append(Y)
        data_mask.append(M)
    else:
        for ifn,lfn in zip(iFn,lFn):
            if n_in == 1:
                X = get_itk_array(ifn)
            else:
                ifns = ifn.split('\t')
                assert len(ifns) >= n_in, 'Number of Input files per line should match the number of channels (tab separated!)'
                X = []
                sh = None
                for ii in ifns[:n_in]:
                    x = get_itk_array(ii)
                    assert (sh is None) or sh == x.shape, 'Input files should have the same shape'
                    X.append(x)

        X = np.array(X).astype('float32')
        Y = get_itk_array(lfn)

        assert X.shape[-3:] == Y.shape

        if preprocess:
            X = processdata(X=X, hist_cutoff=hist_cutoff, n_in=n_in)
            data_x.append(X)
        else:
            data_x.append(X)

        data_y.append(Y)

    if not maskFn is None:
        return get_bounding_blocks(np.array(data_x, dtype='float32'),np.array(data_y, dtype='int32'),np.array(data_mask, dtype='int32'),cube_size=cube_size)
    else:
        return get_bounding_blocks(np.array(data_x, dtype='float32'),np.array(data_y, dtype='int32'), None, cube_size=cube_size)

def get_bounding_blocks(feats,grd_truth,mask=None,gmt=False,cube_size=64):
    feat_stack = np.array([])
    grd_truth_stack=np.array([])
    mask_stack = np.array([])
    cnt = 0
    BLOCK_SIZE=[cube_size if s > cube_size else s for s in grd_truth.shape[-3:]]

    for vol_ind in range(grd_truth.shape[0]):
        values = []
        indices = []

    for x in np.arange(0,grd_truth.shape[1]-BLOCK_SIZE[0],BLOCK_SIZE[0]-OVERLAP_SIZE[0]):
        for y in np.arange(0,grd_truth.shape[2]-BLOCK_SIZE[1],BLOCK_SIZE[1]-OVERLAP_SIZE[1]):
            for z in np.arange(0,grd_truth.shape[3]-BLOCK_SIZE[2],BLOCK_SIZE[2]-OVERLAP_SIZE[2]):
                data = grd_truth[vol_ind][x:x+BLOCK_SIZE[0],y:y+BLOCK_SIZE[1],z:z+BLOCK_SIZE[2]]

                if gmt:
                    val = np.sum(data==1) + np.sum(data==2)
                else:
                    val = np.sum(data==1)

                values.append(val)
                indices.append((x,y,z))

    values = np.argsort(np.asarray(values))
    fsh = len(feats.shape) == 5
    for ind in values[values.shape[0]-SEL_TOP:]:
        x,y,z = indices[ind]
        if cnt==0:
            if fsh:
                feat_stack = feats[vol_ind:vol_ind+1,:,x:x+BLOCK_SIZE[0],y:y+BLOCK_SIZE[1],z:z+BLOCK_SIZE[2]]
            else:
                feat_stack = feats[vol_ind:vol_ind+1,x:x+BLOCK_SIZE[0],y:y+BLOCK_SIZE[1],z:z+BLOCK_SIZE[2]]

            grd_truth_stack = grd_truth[vol_ind:vol_ind+1,x:x+BLOCK_SIZE[0],y:y+BLOCK_SIZE[1],z:z+BLOCK_SIZE[2]]

            if not mask is None:
                mask_stack = mask[vol_ind:vol_ind+1,x:x+BLOCK_SIZE[0],y:y+BLOCK_SIZE[1],z:z+BLOCK_SIZE[2]]

        else:
            if fsh:
                fs = feats[vol_ind:vol_ind+1,:,x:x+BLOCK_SIZE[0],y:y+BLOCK_SIZE[1],z:z+BLOCK_SIZE[2]]
            else:
                fs = feats[vol_ind:vol_ind+1,x:x+BLOCK_SIZE[0],y:y+BLOCK_SIZE[1],z:z+BLOCK_SIZE[2]]

            feat_stack = np.concatenate([feat_stack,fs])
            grd_truth_stack = np.concatenate([grd_truth_stack,grd_truth[vol_ind:vol_ind+1,x:x+BLOCK_SIZE[0],y:y+BLOCK_SIZE[1],z:z+BLOCK_SIZE[2]]])

            if not mask is None:
                mask_stack = np.concatenate([mask_stack,mask[vol_ind:vol_ind+1,x:x+BLOCK_SIZE[0],y:y+BLOCK_SIZE[1],z:z+BLOCK_SIZE[2]]])

        cnt += 1

    if mask is None:
        return feat_stack,grd_truth_stack
    else:
        return feat_stack,grd_truth_stack,mask_stack

def parse_args():
    parser = argparse.ArgumentParser(description='Train/Finetune a cross-hair filter based FCN on NIFTI volumes')
    parser.add_argument('--inputFns', dest='inputFns', type=str, default='inputs.txt',
                   help='a text file containing a list of names/path of input data for the traning (one example per line) (default: inputs.txt)')
    parser.add_argument('--labelFns', dest='labelFns', type=str, default='labels.txt',
                   help='a text file containing a list of names/path of data label for the traning (one example per line) (default: labels.txt)')
    parser.add_argument('--maskFns', dest='maskFns', type=str, default=None,
                   help='a text file containing a list of names/path of mask data for the traning (one example per line)')
    parser.add_argument('--preprocess', dest='preprocess', action='store_true',
                   help='Whether to apply preprocessing or not (default: False)')
    parser.add_argument('--hist-cutoff', dest='hist_cutoff', type=str, default="0.99",
                   help='Cutoff to use when applying histogram cutoff (default: 0.99)')
    parser.add_argument('--initModel', dest='model', type=str, default=None,
                   help='a path to a model which should be used as a base for the training (default: None)')
    parser.add_argument('--modelType', dest='modelType', type=int, default=0,
                   help='the model type to train (FCN=0, VNET=1, UNET=2) (default: 0)')
    parser.add_argument('--use_crosshair', dest='usecrosshair', action='store_true',
                   help='Whether to use crosshair filters or not (default: False)')
    parser.add_argument('--n_in', dest='n_in', type=int, default=1,
                   help='number of input channels (default: 1)')
    parser.add_argument('--n_out', dest='n_out', type=int, default=2,
                   help='number of prediction classes (default: 2)')
    parser.add_argument('--batch-size', dest='batch_size', type=int, default=1,
                   help='batch size for training (default: None)')
    parser.add_argument('--cs', dest='cube_size', type=int, default=64,
                   help='Size of cube to be used during training (default: 64)')
    parser.add_argument('--epochs', dest='epochs', type=int, default=1,
                   help='number of training epochs (default: 1)')
    parser.add_argument('--save-after', dest='save_after', type=int, default=1,
                   help='number of training epochs after which the model should be saved (default: 1)')
    parser.add_argument('--modelFn', dest='modelFn', type=str, default='model',
                   help='filename for saving trained models. Note .dat will be appended autmatically (default: model)')
    parser.add_argument('--modelFolder', dest='model_folder', type=str, default='',
                   help='folder where models will be saved (default: current working directory)')
    parser.add_argument('--lr', dest='learning_rate', type=float, default=0.01,
                   help='learning rate (default: 0.01)')
    parser.add_argument('--decay', dest='decay', type=float, default=0.99,
                   help='learning rate decay per epoch (default: 0.99)')
    parser.add_argument('--weighted-cost', dest='weighted_cost', action='store_true',
                   help='Whether to use weighted cost or not (default: False)')
    args = parser.parse_args()

    return args

def run():
    args = parse_args()
    n_in = args.n_in
    model = load_model(args.model, args.n_in, args.n_out, args.modelType, args.usecrosshair)
    n_epochs = args.epochs
    batch_size = args.batch_size
    lr = args.learning_rate
    decay = args.decay
    weighted_cost = args.weighted_cost
    model_folder = args.model_folder
    modelFn = args.modelFn
    save_after = args.save_after

    if args.maskFns is None:
        data_x, data_y = generate_data(args.inputFns, args.labelFns, args.maskFns, preprocess=args.preprocess, hist_cutoff=args.hist_cutoff, n_in=args.n_in,cube_size=args.cube_size)
        sh = data_y.shape
        data_y = data_y.reshape((sh[0], 1) + sh[1:])
        if n_in == 1:
            data_x = data_x.reshape((sh[0], 1) + sh[1:])
        data_mask = None
    else:
        data_x, data_y, data_mask = generate_data(args.inputFns, args.labelFns, args.maskFns, preprocess=args.preprocess, hist_cutoff=args.hist_cutoff, n_in=args.n_in, cube_size=args.cube_size)
        sh = data_y.shape
        data_y = data_y.reshape((sh[0], 1) + sh[1:])
        data_mask = data_mask.reshape((sh[0], 1) + sh[1:])
        if n_in == 1:
            data_x = data_x.reshape((sh[0], 1) + sh[1:])

    n_iters = int(n_epochs / save_after)
    iters = [save_after for i in range(n_iters)]

    if n_epochs % save_after > 0:
        iters.append(n_epochs % save_after)

    sh = data_x.shape
    print('..............................')
    print('Training Parameters')
    print('..............................')
    print('learning-rate:',lr)
    print('decay:', decay)
    print('Number of epochs:', n_epochs)
    print('Batch size:', batch_size)
    print('Weighted cost:',weighted_cost)
    print('Base Model:',args.model)
    print('Model save folder:', model_folder)
    print('Model save filename:',modelFn)
    print('save model after every', save_after, 'epoch(s)')
    print('Apply preprocessing:', args.preprocess)
    print('Histogram cutoff:', args.hist_cutoff)
    print('Number of input channels:', args.n_in)
    print('Number of classes:', args.n_out)
    print('Number of Examples Extracted:', sh[0])
    print('Training cube size:', sh[-3:])
    print('...................................................\n \n')

    for i, this_epochs in enumerate(iters):
        model, lr = train_model(model=model,data_x=data_x,data_y=data_y,data_mask=data_mask,batch_size=batch_size,n_epochs=this_epochs,lr=lr,weighted_cost=weighted_cost)
        this_model_fn = os.path.abspath(os.path.join(model_folder,'model'+str(i+1)+'.dat'))
        print('saving model......')
        model.save(this_model_fn)
        lr = lr * decay
        print('.....................................................................')

if __name__ == "__main__":
    run()


"""

    Title: Large Files: One Million Digits.
    Author: Eric Matthes
    Date: 04/22/2023
    Description: "I've always been curious to know if my birthday appears
    anywhere in the digits of pi. Let's use the program we just wrote to find
    out if someone's birthday appears anywhere in the first million digits of
    pi. We can do this by expressing each birthday as a string of digits and
    seeing if that string appears anywhere in pi_string:"

"""

from pathlib import Path

path = Path("C:/Users/Brooke/Documents/buwebdev/python_crash_course/chapter_10/1_reading_from_file/files/pi_million_digits.txt")

contents = path.read_text()

lines = contents.splitlines()

pi_string = ''

for line in lines:

    pi_string += line.lstrip()

birthday = input("Enter your birthday, in the from mmddyy: ")

if birthday in pi_string:

    print("Your birthday appears in the first million digits of pi!")

else:

    print("Your birthday does not appear in the first million digits of pi.")


import schedule
import random
from notifypy import Notify
import time
import threading
import sys
import json

def notify(task):
    tune_number=random.randint(1,17)
    notification=Notify()
    notification.title="Schedule Notifications"
    notification.message=task
    notification.audio=f"tune{tune_number}.wav"
    notification.icon="icon.png"
    notification.send(block=False)

def scheduler():
    while(True):
        n=schedule.idle_seconds()
        schedule.run_pending()

def load_saved_tasks():
    with open("tasks.json","r+") as fp:
        # tasks=json.dump([2,3],fp)
        try:
            tasks=json.loads(fp.read())
            return tasks
        except:return []

def schedule_saved_tasks(saved_tasks):
    for i in saved_tasks:
        task,time=i
        schedule.every().day.at(time).do(notify,task=task)

def main():
    print("-"*50)
    print("Welcome to Schedule Notifier program.\nIf you want to close the program then you can press Q or q any time.")
    print("-"*50)
    saved_tasks=load_saved_tasks()
    schedule_saved_tasks(saved_tasks)
    print("Saved tasks from your last session has been scheduled.")
    print("-"*50)
    print("If you want to add any task to the schedule then please enter the task and it's time separated by @")
    print("-"*50)
    notify_thread=threading.Thread(target=scheduler)
    notify_thread.daemon=True
    notify_thread.start()
    while(True):
        command=input()
        if command=="Q" or command=="q":
            #sys.exit()
            with open("tasks.json","w+") as fp:
                json.dump(saved_tasks,fp)
            break
        task,time=command.split("@")
        time=time.strip()
        schedule.every().day.at(time).do(notify,task=task)
        saved_tasks.append((task,time))
        print("Task Scheduled.")

if __name__=="__main__":
    main()


import os
import requests
from pathlib import Path
from db import fetch_scripts

def download(email,url):
    msg = {'flag':False}
    try:
        res = fetch_scripts.check_client_existance(email)
        if res['flag']:
            dest_folder = str(os.path.join(Path.home(), "Downloads"))
            filename = url.split('/')[-1].replace(" ", "_")  # be careful with file names
            file_path = os.path.join(dest_folder, filename)

            r = requests.get(url, stream=True)
            if r.ok:
                print("saving to", os.path.abspath(file_path))
                with open(file_path, 'wb') as f:
                    for chunk in r.iter_content(chunk_size=1024 * 8):
                        if chunk:
                            f.write(chunk)
                            f.flush()
                            os.fsync(f.fileno())
                msg= {'flag':True,'message':'file downloaded','download_link':url}
            else:  # HTTP status code 4XX/5XX
                msg = {'flag':False,'error':"Download failed: status code {}\n{}".format(r.status_code, r.text)}
        else:
            msg = {'flag':False,'error':'user does not exist'}
    except Exception as e:
        msg = {'flag':False,'error':e}

    return msg


import streamlit as st
import cv2
import face_recognition as frg
import yaml
from utils import recognize, build_dataset
import smtplib
from email.message import EmailMessage
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.text import MIMEText

# Path: code\app.py

st.set_page_config(layout="wide")
#Config
cfg = yaml.load(open('config.yaml','r'),Loader=yaml.FullLoader)
PICTURE_PROMPT = cfg['INFO']['PICTURE_PROMPT']
WEBCAM_PROMPT = cfg['INFO']['WEBCAM_PROMPT']

st.sidebar.title("Settings")

#Create a menu bar
menu = ["Please Upload the Image of Suspect"]
choice = st.sidebar.selectbox("Input type",menu)
#Put slide to adjust tolerance
TOLERANCE = st.sidebar.slider("Tolerance",0.0,1.0,0.5,0.01)
st.sidebar.info("chose tolerance according to the quality of your image .")

#Infomation section
st.sidebar.title("Detected Criminal Information")
name_container = st.sidebar.empty()
id_container = st.sidebar.empty()

name_container.info('Criminal Name: Unnknown')
id_container.success('Criminal ID: Unknown')
if choice == "Please Upload the Image of Suspect":
    st.title("Surveillance app for the Gujarat Police")
    st.write(PICTURE_PROMPT)
    uploaded_images = st.file_uploader("Upload",type=['jpg','png','jpeg'],accept_multiple_files=True)
    if len(uploaded_images) != 0:
        #Read uploaded image with face_recognition
        for image in uploaded_images:
            image = frg.load_image_file(image)
            image, name, id = recognize(image,TOLERANCE)
            name_container.info(f"Criminal Name: {name}")
            id_container.success(f"Criminal ID: {id}")
            st.image(image)
    else:
        st.info("Please upload an image Of Criminal")

with st.sidebar.form(key='my_form'):
    submit_button = st.form_submit_button(label='REBUILD DATASET')
    if submit_button:
        with st.spinner("Rebuilding dataset..."):
            build_dataset()
        st.success("Dataset has been reset")


"""
Python compatibility functions.
"""
import sys
import os
import warnings
from typing import Any, Callable

# ------------------------------------------------------------------------------
# Python 2/3 compatibility
fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()

def relpath(path: str, start: str = os.curdir) -> str:
    """Return a relative version of a path"""
    try:
        return os.path.relpath(path, start)
    except ValueError:
        return path

# convert_with_2to3():
# support for running 2to3 over config files
def convert_with_2to3(filepath: str) -> str:
    from lib2to3.refactor import RefactoringTool, get_fixers_from_package
    from lib2to3.pgen2.parse import ParseError
    fixers = get_fixers_from_package('lib2to3.fixes')
    refactoring_tool = RefactoringTool(fixers)
    source = refactoring_tool._read_python_source(filepath)[0]
    try:
        tree = refactoring_tool.refactor_string(source, 'conf.py')
    except ParseError as err:
        # do not propagate lib2to3 exceptions
        lineno, offset = err.context[1]
        # try to match ParseError details with SyntaxError details
        raise SyntaxError(err.msg, (filepath, lineno, offset, err.value))
    return str(tree)

def execfile_(filepath: str, _globals: Any, open: Callable = open) -> None:
    with open(filepath, 'rb') as f:
        source = f.read()

    # compile to a code object, handle syntax errors
    filepath_enc = filepath.encode(fs_encoding)
    try:
        code = compile(source, filepath_enc, 'exec')
    except SyntaxError:
        # maybe the file uses 2.x syntax; try to refactor to
        # 3.x syntax using 2to3
        source = convert_with_2to3(filepath)
        code = compile(source, filepath_enc, 'exec')
        warnings.warn('Support for evaluating Python 2 syntax is deprecated '
                      'and will be removed in sphinx-intl 4.0. '
                      'Convert %s to Python 3 syntax.',
                      source=filepath)
    exec(code, _globals)


import pickle
import sys

from Algorithms.Trees.base import (BinaryTreeNode, create_bst,
                                   display_level_order)

MARKER = sys.maxsize

def serialize(node, stream):
    if not node:
        stream.dump(MARKER)
        return
    stream.dump(node.data)
    serialize(node.left, stream)
    serialize(node.right, stream)

def deserialize(stream):
    try:
        data = pickle.load(stream)
        if data == MARKER:
            return None

        node = BinaryTreeNode(data)
        node.left = deserialize(stream)
        node.right = deserialize(stream)
        return node
    except pickle.UnpicklingError:
        return None

arr = [100, 50, 200, 25, 75, 125, 350]
root = create_bst(arr)
display_level_order(root)
output = open("data.tmp", "wb")
p = pickle.Pickler(output)
serialize(root, p)
output.close()
input2 = open("data.tmp", "rb")
root_deserialized = deserialize(input2)
print("Result:")
display_level_order(root_deserialized)


# -*- coding: utf-8 -*-
from odoo import models, fields, api, _ # type: ignore
import logging

logger = logging.getLogger(__name__)

class SubmittedTestVariable(models.Model):
    _name = 'terralab.submittedtestvariable'
    _inherit = ['mail.thread']
    _description = 'TerraLab Submitted Test Variable'

    submitted_sample = fields.Many2one('terralab.submittedsample', 'Submitted Sample', track_visibility='onchange') # Every Submitted Test Variable is attached to a specific Submitted Sample
    submitted_test = fields.Many2one('terralab.submittedtest', 'Submitted Test', track_visibility='onchange') # Every Submitted Test Variable is attached to a specific Submitted Test
    test_variable_type = fields.Many2one('terralab.testvariabletype', 'Test Variable Type', track_visibility='onchange') # Every Submitted Test Variable is a specific Test Variable Type
    order = fields.Many2one('sale.order', 'Order', track_visibility='onchange') # Submitted Test Variable is always attached to an Order
    order_name = fields.Char(compute='_get_order_fields', store=True, track_visibility='onchange')
    order_terralab_status = fields.Char(compute='_get_order_fields', store=True, track_visibility='onchange')
    num = fields.Integer(compute='_get_num', store=True, track_visibility='onchange')
    value = fields.Char(track_visibility='onchange')
    name = fields.Char(compute='_get_name', store=True, translate=True, track_visibility='onchange')

    @api.depends('test_variable_type')
    def _get_num(self):
        for item in self:
            if item.test_variable_type:
                item.num = item.test_variable_type.num
            else:
                item.num = None

    @api.depends('submitted_test', 'test_variable_type', 'value')
    def _get_name(self):
        for item in self:
            if item.submitted_test and item.test_variable_type:
                # This is ugly, sorry.
                for submitted_test in item.submitted_test:
                    for submitted_test_id, submitted_test_name in submitted_test.name_get():
                        item.name = '%s %s' % (submitted_test_name, item.test_variable_type.name)
            else:
                item.name = ''

    @api.depends('order', 'order.name', 'order.terralab_status')
    def _get_order_fields(self):
        for item in self:
            if item.order:
                item.order_name = item.order.name
                item.terralab_status = item.order.terralab_status
            else:
                item.order_name = ''
                item.terralab_status = ''

    # What's the next required action for this submitted_test variable?
    def compute_terralab_next_action(self, order_terralab_status):
        if order_terralab_status in ('submitted', 'accepted', 'rejected'):
            if self.value == '' or self.value == False:
                return _('Add value for submitted test variable %s') % (self.name)
        # No action required for this test variable
        return ''

    # When this variable is modified, pass on the chatter message to the Order object
    def _message_log(self, *args, **kwargs):
        ret = super(SubmittedTestVariable, self)._message_log(*args, **kwargs)
        logger.info('MESSAGE LOG VARIABLE %s %s %s' % (ret, args, kwargs))

        # Add more info about the variable to the chatter message (by default, field_desc is just "Value")
        submitted_sample = None
        submitted_test = None
        submitted_test_variable = None
        for item in self:
            submitted_test_variable = item
            submitted_sample = item.submitted_sample
            submitted_test = item.submitted_test

        newargs = dict(kwargs)
        if submitted_sample and submitted_test and submitted_test_variable:
            if 'tracking_value_ids' in newargs:
                for tracking_value in newargs['tracking_value_ids']:
                    if len(tracking_value) >= 3:
                        attrs = tracking_value[2]
                        if 'field_desc' in attrs:
                            attrs['field_desc'] = '%s / %s / Variable %s %s' % (submitted_sample.name, submitted_test.test_type.name, submitted_test_variable.num, attrs['field_desc'])
            logger.info('MESSAGE LOG NEWARGS %s' % (newargs))

        for item in self:
            if hasattr(item.order, '_message_log'):
                item.order._message_log(*args, **newargs)

        return ret


# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information

project = 'NDEV - Python BlizzardAPI'
copyright = '2023, NDEV'
author = 'NDEV'
release = '0.1.2'

# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration

extensions = [
    'sphinx_rtd_theme',
]

templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output

html_theme = 'sphinx_rtd_theme'
html_static_path = ['_static']

# -- Options for HTMLHelp output ---------------------------------------------
html_theme_options = {
    'analytics_id': 'G-6KGK4YPZRT',  #  Provided by Google in your dashboard
    'analytics_anonymize_ip': False,
}


from app.Model.Model import Model

class Product(Model):
    def __init__(self, json=None, pk=None):
        self.id = 0
        self.barcode = None
        self.barcodeInner = None
        self.description1 = None
        self.description2 = None
        self.description3 = None
        self.description4 = None
        self.height = 0
        self.internalID = None
        self.brand = None
        self.depth = 0
        self.weight = 0
        self.volume = 0
        self.isKitted = None
        self.isPriceTaxInclusive = None
        self.productCondition = None
        self.keyProductID = None
        self.keySellUnitID = None
        self.keyTaxcodeID = None
        self.kitProductsSetPrice = None
        self.name = None
        self.productCode = None
        self.productName = None
        self.productSearchCode = None
        self.averageCost = None
        self.drop = None
        self.packQuantity = None
        self.sellUnits = None
        self.stockLowQuantity = 0
        self.stockQuantity = 0
        self.width = 0
        self.categoryList = None  # store category object
        self.priceList = None  # store price object
        self.sellUnitsIdList = None  # sell the SellUnitIds (new table)
        self.imageList = []  # List to store the images associated with the product
        self.supplierOrganizationId = None
        self.price = None
        super().__init__(json, pk)

    @staticmethod
    def table_name():
        return 'products'

    @staticmethod
    def fields_mapping():
        return {
            'id': 'id',
            'barcode': 'barcode',
            'barcodeInner': 'barcodeInner',
            'description1': 'description1',
            'description2': 'description2',
            'description3': 'description3',
            'description4': 'description4',
            'height': 'height',
            'internalId': 'internalID',
            'internalID': 'internalId',
            'brand': 'brand',
            'depth': 'depth',
            'weight': 'weight',
            'width': 'width',
            'volume': 'volume',
            'isKitted': 'isKitted',
            'isPriceTaxInclusive': 'isPriceTaxInclusive',
            'productCondition': 'productCondition',
            'keyProductID': 'keyProductId',
            'keyProductId': 'keyProductID',
            'keySellUnitID': 'keySellUnitID',
            'keyTaxcodeId': 'keyTaxcodeID',
            'keyTaxcodeID': 'keyTaxcodeId',
            'kitProductsSetPrice': 'kitProductsSetPrice',
            'productCode': 'productCode',
            'name': 'productName',
            'productName': 'name',
            'productSearchCode': 'productSearchCode',
            'averageCost': 'averageCost',
            'drop': 'productDrop',
            'productDrop': 'drop',
            'packQuantity': 'packQuantity',
            'selfLowQuantity': 'selfLowQuantity',
            'stockLowQuantity': 'stockLowQuantity',
            'stockQuantity': 'stockQuantity',
            'supplierOrganizationId': 'supplierOrganizationId'
        }

    def basic_dict(self):
        return {
            'id': self.id,
            'barcode': self.barcode,
            'name': self.name,
            'productCode': self.productCode,
            'price': self.price,
            'image': [image.__dict__ for image in self.imageList]
        }

    def json(self):
        if self.imageList is not None:
            self.imageList = [image.__dict__ for image in self.imageList]

        return super().json()


import os, sys, re
import subshifter

root_dir = sys.argv[1]

default = ""
shift = ""
sub_format = ".ass"
eps_format = ".mkv"

while True:
    default = input("Use default? (.ass/.mkv) (y/n): ")
    if(default.lower() == "y"):
        break
    elif(default.lower() == "n"):
        sub_format = input("Input file format of subtitles: ")
        eps_format = input("Input file format of episodes: ")
        break
    else:
        print("Please follow the prompt.")

while True:
    shift = input("Please input how much to shift (end with ms/f for milliseconds/frames, i.e. 24f): ")
    if re.match("\A[\d]*(.?[\d]+|[\d]*)(f|ms)$", shift):
        break
    else:
        print("Please follow the prompt.")

def rename_files():
    subs = []
    eps = []
    for root, dirs, files in os.walk(root_dir, topdown=True):
        dirs.clear()
        for file in files:
            ext = os.path.splitext(file)[1]
            if ext == sub_format or ext == ("." + sub_format):
                subs.append(file)
            elif ext == eps_format or ext == ("." + eps_format):
                eps.append(file)
    subs.sort()
    eps.sort()
    print(len(subs))
    if len(subs) != len(eps):
        print("Amount of subtitles do not match amount of episodes! Subs = {0}, Eps = {1}".format(len(subs), len(eps)))
        return
    for sub, eps in zip(subs,eps):
        sub_name, sub_ext = os.path.splitext(sub)
        eps_name, eps_ext = os.path.splitext(eps)
        os.rename(os.path.join(root, sub), os.path.join(root, eps_name + sub_ext))
        subshifter.shift(os.path.join(root, eps_name + sub_ext), os.path.join(root, eps), shift)

rename_files()
os.system("pause")


import webbrowser

class Movie():
    """Stores information about a film.
    Attributes:
        title (str): Title of movie
        storyline (str): Tag-line for movie
        poster_image_url (str): URL to movie poster
        trailer_youtube_url (str): URL to movie trailer
    """

    def __init__(self, movie_title, movie_storyline, poster_image_url,
                 trailer_youtube):
        self.title = movie_title
        self.storyline = movie_storyline
        self.poster_image_url = poster_image_url
        self.trailer_youtube_url = trailer_youtube

    def show_trailer(self):
        webbrowser.open(self.trailer_youtube_url)


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

#Time O(N2) | Space O(N)
def threeNumberSum(array, targetSum):
    # Write your code here.
	array.sort()
	result = []
	for i in range(len(array)):
		left = i+1
		right = len(array) - 1
		while left < right:
			currSum = array[i] + array[left] + array[right]
			if currSum == targetSum:
				result.append([array[i], array[left], array[right]])
				left += 1
				right -= 1
			elif currSum < targetSum:
				left += 1
			else:
				right -= 1
	return result

if __name__ == '__main__':
	array = [12, 3, 1, 2, -6, 5, -8, 6]
	targetSum = 0
	result = threeNumberSum(array, targetSum)
	print(result)


from msteams_webhooks.buttons import OpenURLButton
from msteams_webhooks.cards import ReceiptCard
from msteams_webhooks.containers import ReceiptFact, ReceiptItem

def test_receipt_card() -> None:
    payload = {
        "contentType": "application/vnd.microsoft.card.receipt",
        "content": {
            "title": "John Doe",
            "total": "$ 90.95",
            "items": [
                {
                    "title": "Data Transfer",
                    "price": "$ 38.45",
                    "quantity": "368",
                    "image": {
                        "url": "https://github.com/amido/azure-vector-icons/raw/master/renders/traffic-manager.png"
                    },
                },
                {
                    "title": "App Service",
                    "price": "$ 45.00",
                    "quantity": "720",
                    "image": {
                        "url": "https://github.com/amido/azure-vector-icons/raw/master/renders/cloud-service.png"
                    },
                },
            ],
            "facts": [
                {"key": "Order Number", "value": "1234"},
                {"key": "Payment Method", "value": "VISA 5555-****"},
            ],
            "tax": "$ 7.50",
            "buttons": [
                {
                    "type": "openUrl",
                    "title": "More information",
                    "value": "https://azure.microsoft.com/en-us/pricing/",
                    "image": "https://account.windowsazure.com/content/6.10.1.38-.8225.160809-1618/aux-pre/images/offer-icon-freetrial.png",
                }
            ],
        },
    }
    items = [
        ReceiptItem(
            title="Data Transfer",
            price="$ 38.45",
            quantity=368,
            image="https://github.com/amido/azure-vector-icons/raw/master/renders/traffic-manager.png",
        ),
        ReceiptItem(
            title="App Service",
            price="$ 45.00",
            quantity=720,
            image="https://github.com/amido/azure-vector-icons/raw/master/renders/cloud-service.png",
        ),
    ]
    facts = [
        ReceiptFact(key="Order Number", value="1234"),
        ReceiptFact(key="Payment Method", value="VISA 5555-****"),
    ]
    button = OpenURLButton(
        url="https://azure.microsoft.com/en-us/pricing/",
        title="More information",
        image="https://account.windowsazure.com/content/6.10.1.38-.8225.160809-1618/aux-pre/images/offer-icon-freetrial.png",
    )
    card = ReceiptCard(
        title="John Doe",
        items=items,
        facts=facts,
        total="$ 90.95",
        tax="$ 7.50",
        buttons=[button],
    )
    assert card.serialize() == payload


import random
import math

class MiniCalculator:
    @staticmethod
    def random_maker1():
        operation = ['+', '-', '*']
        symbol = random.choice(operation)
        first_operand = random.randint(2, 9)
        second_operand = random.randint(2, 9)
        print(f'{first_operand} {symbol} {second_operand}')
        return f'{first_operand} {symbol} {second_operand}'

    @staticmethod
    def calculate_result(random_word):
        while True:
            ans = input()
            if ans.isdigit():
                ans = int(ans)
                if eval(random_word) == ans:
                    return "Right!"
                else:
                    return "Wrong!"
            elif ans.lstrip('-').isdigit():
                ans = int(ans)
                if eval(random_word) == ans:
                    return "Right!"
                else:
                    return "Wrong!"
            else:
                print("Incorrect format.")

    def main(self):
        count = 0
        mark = 0
        while True:
            rand = self.random_maker1()
            st = self.calculate_result(rand)
            if st == 'Right!':
                mark = mark + 1
            print(st)
            count = count + 1
            if count == 5:
                break
        print(f'Your mark is {mark} / 5')
        return f'{mark}/5'

class DifficultCalculator:
    @staticmethod
    def random_maker2():
        number = random.randint(11, 29)
        print(number)
        return number

    @staticmethod
    def check_result(num):
        while True:
            ans = input()
            if ans.isdigit():
                ans = int(ans)
                if num ** 2 == ans:
                    return "Right!"
                else:
                    return "Wrong!"
            else:
                print('Wrong format! Try again.')

    def main(self):
        count = 0
        mark = 0
        while True:
            rand = self.random_maker2()
            st = self.check_result(rand)
            if st == 'Right!':
                mark = mark + 1
            print(st)
            count = count + 1
            if count == 5:
                break
        print(f'Your mark is {mark} / 5')
        return f'{mark}/5'

def start():
    while True:
        print("Which level do you want? Enter a number:")
        print("1 - simple operations with numbers 2-9")
        print("2 - integral squares of 11-29")
        choice = int(input())
        if choice not in [1, 2]:
            print("Incorrect format.")
        else:
            break
    if choice == 1:
        calc = MiniCalculator()
        ans = calc.main()
        print("Would you like to save your result to the file? Enter yes or no.")
        choice = input()
        if choice in ['Yes', 'YES', 'yes', 'y']:
            name = input('What is your name?')
            with open('results.txt', 'a', encoding='UTF-8') as result:
                result.write(f'{name}: {ans} in level 1 (simple operations with numbers 2-9).')
            print("The results are saved in 'results.txt'.")
    elif choice == 2:
        calc = DifficultCalculator()
        ans = calc.main()
        print("Would you like to save your result to the file? Enter yes or no.")
        choice = input()
        if choice in ['Yes', 'YES', 'yes', 'y']:
            name = input('What is your name?')
            with open('results.txt', 'a', encoding='UTF-8') as result:
                result.write(f'{name}: {ans} in level 2 (integral squares of 11-29).')
            print("The results are saved in 'results.txt'.")

start()


# 2342. Max Sum of a Pair With Equal Sum of Digits
# https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/

class Solution:
    def maximumSum(self, nums):
        '''
        d=defaultdict(list)
        for i in nums:
            s=reduce(lambda x,y:(int(x)+int(y)),list(str(i)))
            d[int(s)].append(i)
        ans=-1
        for i in d:
            if len(d[i])>1:
                d[i].sort()
                ans=max(ans,d[i][-1]+d[i][-2])
        return ans
        '''

        def digitsum(i):
            res=0
            while i>0:
                res+=i%10
                i//=10
            return res

        d={}
        ans=-1
        for i in nums:
            s=digitsum(i)
            if s not in d:
                d[s]=i
            else:
                ans=max(ans,d[s]+i)
                d[s]=max(d[s],i)
        return ans

Weekly Contest/Weekly Contest 302/2_Max Sum of a Pair With Equal Sum of Digits.py


# -*- coding: utf-8 -*-
"""
Created on Tue Feb  1 10:02:02 2022

Takes a text file of floats and gives max absolute value.

@author: Lab User
"""

def getPGA(PATHIN):
    with open(PATHIN,'r') as f:
        data = [float(val) for val in f]
        PGA = max(data, key=abs)
    return PGA

PATH = r"C:/Users/Lab User/OneDrive/Documents/OpenSees/9st_mrf_mwc/GMs_Full_Suite/"
FILE = "LaGrande_002EW.txt"
PGA = getPGA(PATH+FILE)


import logging
import dendropy as dpy
from pyparsing import Suppress, SkipTo, Word, Regex, Literal, OneOrMore, \
    Group, LineEnd, CharsNotIn, nums, alphanums, ParseException

logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())

FLOAT = Word(nums + '.-').setParseAction(lambda x: float(x[0]))
INT = Word(nums).setParseAction(lambda x: int(x[0]))
WORD = Word(alphanums + '_')
SPACEDWORD = Word(alphanums + ' _')

class PhymlParser(object):
    """
    Simple phyml result parser. Assumes one of the standard models
    for nucleotide analyses.
    """

    def __init__(self):
        self.MODEL_LABEL = Regex(r'Model of.*substitution:\s+')
        self.ALPHA_LABEL = Regex(r'Gamma shape parameter:\s+')
        self.LNL_LABEL = Regex(r'Log-likelihood:\s+')
        self.F_LABEL = Regex(r'f\(([ACGT])\)=\s+')
        self.R_LABEL = Regex(r'[ACGT]\s+<->\s+[ACGT]\s+')
        self.TSTV_LABEL = Regex(r'Transition/transversion ratio.*:\s+')
        self.model = Suppress(SkipTo(self.MODEL_LABEL)) + \
                     Suppress(self.MODEL_LABEL) + WORD
        self.lnl = Suppress(SkipTo(self.LNL_LABEL)) + \
                   Suppress(self.LNL_LABEL) + FLOAT
        self.alpha = Suppress(SkipTo(self.ALPHA_LABEL)) + \
                     Suppress(self.ALPHA_LABEL) + FLOAT
        self.common = self.model + self.lnl + self.alpha
        self.tstv = OneOrMore(Suppress(SkipTo(self.TSTV_LABEL)) +
                              Suppress(self.TSTV_LABEL) + FLOAT)
        self.freq = OneOrMore(
            Suppress(SkipTo(self.F_LABEL)) + Suppress(self.F_LABEL) + FLOAT)
        self.rates = OneOrMore(
            Suppress(SkipTo(self.R_LABEL)) + Suppress(self.R_LABEL) + FLOAT)
        self.gtr_specific = Group(self.freq) + Group(self.rates)
        self.hky_specific = Group(self.tstv) + Group(self.freq)

    def parse(self, filename):
        model = None
        alpha = None
        lnl = None
        freq = None
        rates = None

        with open(filename) as fl:
            s = fl.read()

        try:
            model, lnl, alpha = self.common.parseString(s).asList()

        except ParseException as err:
            logger.error(err)

        if model == 'JC69':
            freq = [0.25, 0.25, 0.25, 0.25]
            rates = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

        elif model == 'K80':
            freq = [0.25, 0.25, 0.25, 0.25]
            try:
                tstv = self.tstv.parseString(s).asList()
            except ParseException as err:
                logger.error(err)

            rates = [1.0, tstv[0], 1.0, 1.0, tstv[0], 1.0]

        elif model == 'F81':
            try:
                freq = self.freq.parseString(s).asList()
            except ParseException as err:
                logger.error(err)
            rates = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

        elif model == 'F84' or model == 'HKY85' or model == 'TN93':
            parser = Group(self.tstv) + Group(self.freq)
            try:
                tstv, freq = parser.parseString(s).asList()
            except ParseException as err:
                logger.error(err)
            if model == 'TN93':
                rates = [1.0, tstv[0], 1.0, 1.0, tstv[1], 1.0]
            else:
                rates = [1.0, tstv[0], 1.0, 1.0, tstv[0], 1.0]

        elif model == 'GTR':
            parser = Group(self.freq) + Group(self.rates)
            try:
                freq, rates = parser.parseString(s).asList()
            except ParseException as err:
                logger.error(err)

        return model, alpha, lnl, freq, rates

    def to_dict(self, stats_filename, tree_filename):
        model, alpha, lnl, freq, rates = self.parse(stats_filename)
        try:
            with open(tree_filename) as treefl:
                nwk_tree = treefl.read().rstrip()
                tree = dpy.Tree.get(data=nwk_tree, schema='newick')
        except IOError as err:
            logger.error(err)
            return

        result = {'likelihood': lnl,
                  'alpha': alpha,
                  'frequencies': freq,
                  'rates': rates,
                  'model': model,
                  'tree': tree}
        return result

class RaxmlParser(object):
    def __init__(self):
        self.ALPHA_LABEL = Regex(r'alpha\[\d+\]:')
        self.LNL_LABEL = Literal('Final GAMMA-based Score of best tree')
        self.FRQ_LABEL = Regex(r'Base frequencies: (?=\d+)') ^ \
                         Regex(r'ML estimate base freqs\[\d+\]:')
        self.NAMES_LABEL = Regex(r'Partition: \d+ with name:\s+')
        self.RATES_LABEL = Regex(r'rates\[\d+\].+?:')
        self.MODEL_LABEL = Literal('Substitution Matrix:')
        self.alpha = OneOrMore(Suppress(SkipTo(self.ALPHA_LABEL)) +
                               Suppress(self.ALPHA_LABEL) + FLOAT)
        self.lnl = Suppress(SkipTo(self.LNL_LABEL)) + \
                   Suppress(self.LNL_LABEL) + FLOAT
        self.frq = OneOrMore(Group(Suppress(SkipTo(self.FRQ_LABEL)) +
                                   Suppress(self.FRQ_LABEL) + OneOrMore(FLOAT)))
        self.names = OneOrMore(
            Suppress(SkipTo(self.NAMES_LABEL)) + Suppress(self.NAMES_LABEL) +
            CharsNotIn('\n') + Suppress(LineEnd()))
        self.rates = OneOrMore(
            Group(Suppress(SkipTo(self.RATES_LABEL)) +
                  Suppress(self.RATES_LABEL) + OneOrMore(FLOAT)))
        self.model = Suppress(SkipTo(self.MODEL_LABEL)) + \
                     Suppress(self.MODEL_LABEL) + WORD

        MODEL_LABEL = Literal('Substitution Matrix:')
        SCORE_LABEL = Literal('Final GAMMA  likelihood:')
        BOOT_SCORE_LABEL = Literal('Final ML Optimization Likelihood:')
        DESC_LABEL = Literal('Model Parameters of Partition')
        NAME_LEADIN = Literal(', Name:')
        DATATYPE_LEADIN = Literal(', Type of Data:')
        ALPHA_LEADIN = Literal('alpha:')
        TREELENGTH_LEADIN = Literal('Tree-Length:')
        RATES_LABEL = Regex(r'rate \w <-> \w:')
        FREQS_LABEL = Regex(r'freq pi\(\w\):')

        likelihood = Suppress(SkipTo(SCORE_LABEL)) + Suppress(
            SCORE_LABEL) + FLOAT
        boot_likelihood = Suppress(SkipTo(BOOT_SCORE_LABEL)) + Suppress(
            BOOT_SCORE_LABEL) + FLOAT
        description = Suppress(SkipTo(DESC_LABEL)) + Suppress(
            DESC_LABEL) + INT + Suppress(
            NAME_LEADIN) + SPACEDWORD + Suppress(DATATYPE_LEADIN) + WORD
        treelen = Suppress(SkipTo(TREELENGTH_LEADIN)) + Suppress(
            TREELENGTH_LEADIN) + FLOAT

        alpha = Suppress(SkipTo(ALPHA_LEADIN)) + Suppress(ALPHA_LEADIN) + FLOAT

        rates = OneOrMore(
            Group(Suppress(SkipTo(RATES_LABEL)) + Suppress(
                RATES_LABEL) + OneOrMore(FLOAT)))
        freqs = OneOrMore(
            Group(Suppress(SkipTo(FREQS_LABEL)) + Suppress(
                FREQS_LABEL) + OneOrMore(FLOAT)))

        # output of running different set of raxml analysis
        self.TC_STOCHBI_LABEL = Literal(
            'Tree certainty under stochastic bipartition '
            'adjustment for this tree:')
        self.RTC_STOCHBI_LABEL = Literal(
            'Relative tree certainty under stochastic bipartition adjustment for this tree:')
        self.TCA_STOCHBI_LABEL = Literal(
            'Tree certainty including all conflicting bipartitions (TCA) under '
            'stochastic bipartition adjustment for this tree:')
        self.RTCA_STOCHBI_LABEL = Literal(
            'Relative tree certainty including all conflicting bipartitions (TCA) '
            'under stochastic bipartition adjustment for this tree:')
        self.TC_UNIBI_LABEL = Literal(
            'Tree certainty under uniform bipartition '
            'adjustment for this tree:')
        self.RTC_UNIBI_LABEL = Literal('Relative tree certainty under uniform '
                                       'bipartition adjustment for this tree:')
        self.TCA_UNIBI_LABEL = Literal(
            'Tree certainty including all conflicting bipartitions (TCA) under '
            'uniform bipartition adjustment for this tree:')
        self.RTCA_UNIBI_LABEL = Literal(
            'Relative tree certainty including all conflicting bipartitions (TCA) '
            'under uniform bipartition adjustment for this tree:')

        self.tc_stochbi = Suppress(SkipTo(self.TC_STOCHBI_LABEL)) + Suppress(
            self.TC_STOCHBI_LABEL) + FLOAT
        self.rtc_stochbi = Suppress(SkipTo(self.RTC_STOCHBI_LABEL)) + Suppress(
            self.RTC_STOCHBI_LABEL) + FLOAT
        self.tca_stochbi = Suppress(SkipTo(self.TCA_STOCHBI_LABEL)) + Suppress(
            self.TCA_STOCHBI_LABEL) + FLOAT
        self.rtca_stochbi = Suppress(
            SkipTo(self.RTCA_STOCHBI_LABEL)) + Suppress(
            self.RTCA_STOCHBI_LABEL) + FLOAT
        self.tc_unibi = Suppress(SkipTo(self.TC_UNIBI_LABEL)) + Suppress(
            self.TC_UNIBI_LABEL) + FLOAT
        self.rtc_unibi = Suppress(SkipTo(self.RTC_UNIBI_LABEL)) + Suppress(
            self.RTC_UNIBI_LABEL) + FLOAT
        self.tca_unibi = Suppress(SkipTo(self.TCA_UNIBI_LABEL)) + Suppress(
            self.TCA_UNIBI_LABEL) + FLOAT
        self.rtca_unibi = Suppress(SkipTo(self.RTCA_UNIBI_LABEL)) + Suppress(
            self.RTCA_UNIBI_LABEL) + FLOAT

        # Use these for flag 'a' option
        self.boot_likelihood = boot_likelihood
        self.freqs = freqs
        self.rates = rates
        self.alpha = alpha
        self.name = description
        self.treelen = treelen

        self._dash_f_e_parser = (Group(OneOrMore(self.model)) +
                                 likelihood +
                                 Group(OneOrMore(Group(
                                     description + alpha + Suppress(
                                         TREELENGTH_LEADIN) +
                                     Suppress(FLOAT) + Group(
                                         OneOrMore(rates)) + Group(
                                         OneOrMore(freqs))))))

    def parse(self, filename, f_flag=None):
        with open(filename) as fl:
            s = fl.read()
        if f_flag == None:
            try:
                alphas = self.alpha.parseString(s).asList()
            except ParseException as err:
                logger.error(err)
                alphas = [None]
            try:
                freqs = self.frq.parseString(s).asList()
            except ParseException as err:
                logger.error(err)
                freqs = [None]
            try:
                names = self.names.parseString(s).asList()
            except ParseException as err:
                logger.error(err)
                names = [None]
            try:
                rates = self.rates.parseString(s).asList()
            except ParseException:
                rates = None
            try:
                lnl = self.lnl.parseString(s).asList()
            except ParseException as err:
                logger.error(err)
                lnl = [0]

            return alphas, freqs, names, rates, lnl
        elif f_flag == 'i':
            try:
                tc_stochbi = self.tc_stochbi.parseString(s).asList()[0]
            except ParseException as err:
                logger.error(err)
                tc_stochbi = [None]
            try:
                rtc_stochbi = self.rtc_stochbi.parseString(s).asList()[0]
            except ParseException as err:
                logger.error(err)
                rtc_stochbi = [None]
            try:
                tca_stochbi = self.tca_stochbi.parseString(s).asList()[0]
            except ParseException as err:
                logger.error(err)
                tca_stochbi = [None]
            try:
                rtca_stochbi = self.rtca_stochbi.parseString(s).asList()[0]
            except ParseException as err:
                logger.error(err)
                rtca_stochbi = [None]
            try:
                tc_unibi = self.tc_unibi.parseString(s).asList()[0]
            except ParseException as err:
                logger.error(err)
                tc_unibi = [None]
            try:
                rtc_unibi = self.rtc_unibi.parseString(s).asList()[0]
            except ParseException as err:
                logger.error(err)
                rtc_unibi = [None]
            try:
                tca_unibi = self.tca_unibi.parseString(s).asList()[0]
            except ParseException as err:
                logger.error(err)
                tca_unibi = [None]
            try:
                rtca_unibi = self.rtca_unibi.parseString(s).asList()[0]
            except ParseException as err:
                logger.error(err)
                rtca_unibi = [None]

            return tc_unibi, rtc_unibi, tca_unibi, rtca_unibi, tc_stochbi, \
                   rtc_stochbi, tca_stochbi, rtca_stochbi

        elif f_flag == 'a':
            try:
                model = self.model.parseString(s).asList()
            except ParseException:
                model = None
            try:
                alphas = self.alpha.parseString(s).asList()
            except ParseException as err:
                logger.error(err)
                alphas = [None]
            try:
                freqs = self.freqs.parseString(s).asList()
            except ParseException as err:
                logger.error(err)
                freqs = [None]
            try:
                name = self.name.parseString(s).asList()
            except ParseException as err:
                logger.error(err)
                name = [None]
            try:
                rates = self.rates.parseString(s).asList()
            except ParseException:
                rates = None
            try:
                likelihood = self.boot_likelihood.parseString(s).asList()
            except ParseException:
                likelihood = None
            try:
                treelength = self.treelen.parseString(s).asList()
            except ParseException:
                treelength = None
            return model, treelength, alphas, freqs, name, rates, likelihood

    def _dash_f_e_to_dict(self, info_filename, tree_filename):
        """
        Raxml provides an option to fit model params to a tree,
        selected with -f e.
        The output is different and needs a different parser.
        """
        with open(info_filename) as fl:
            models, likelihood, partition_params = self._dash_f_e_parser.parseFile(
                fl).asList()

        with open(tree_filename) as fl:
            nwk_tree = fl.read().rstrip()
            tree = dpy.Tree.get(data=nwk_tree, schema='newick')

        d = {'likelihood': likelihood, 'tree': tree, 'partitions': {}}

        for model, params in zip(models, partition_params):
            subdict = {}
            index, name, _, alpha, rates, freqs = params
            subdict['alpha'] = alpha
            subdict['name'] = name
            subdict['rates'] = rates
            subdict['frequencies'] = freqs
            subdict['model'] = model
            d['partitions'][index] = subdict

        return d

    def _dash_f_i_to_dict(self, info_filename, tree_filename):
        """
        Raxml provides an option to fit model params to a tree,
        selected with -f i.
        The output is different and needs a different parser.
        """
        tc_unibi, rtc_unibi, tca_unibi, rtca_unibi, tc_stochbi, rtc_stochbi, tca_stochbi, rtca_stochbi = self.parse(
            info_filename, 'i')

        with open(tree_filename) as fl:
            nwk_tree = fl.read().rstrip()
            tree = dpy.Tree.get(data=nwk_tree, schema='newick')

        d = {'tree': tree, 'tc_unibi': tc_unibi, 'rtc_unibi': rtc_unibi,
             'tca_unibi': tca_unibi,
             'rtca_unibi': rtca_unibi, 'tc_stochbi': tc_stochbi,
             'rtc_stochbi': rtc_stochbi, 'tca_stochbi': tca_stochbi,
             'rtca_stochbi': rtca_stochbi}

        return d

    def _dash_f_a_to_dict(self, info_filename, tree_filename):
        """
        Raxml provides an option to fit model params to a tree,
        selected with -f a.
        The output is different and needs a different parser.
        """
        model, treelength, alphas, freqs, name, rates, likelihood = self.parse(
            info_filename, f_flag='a')

        bs_tree_filename = tree_filename.replace('bestTree',
                                                 'bipartitionsBranchLabels')
        try:
            with open(bs_tree_filename) as fl:
                nwk_tree = fl.read().rstrip()
                tree = dpy.Tree.get(data=nwk_tree, schema='newick')
        except IOError as err:
            logger.error('No tree file - raxml analysis failed')
            return

        result = {'likelihood': likelihood,
                  'model': model,
                  'treelength': treelength,
                  'part_name': name[1],
                  'alpha': alphas,
                  'rates': rates,
                  'frequences': freqs,
                  'bs_tree': nwk_tree,
                  'tree': tree}

        return result

    def to_dict(self, info_filename, tree_filename, dash_f=None):
        """
        Parse raxml output and return a dict
        Option dash_f_e=True will parse the output of a raxml -f e run,
        which has different output
        """
        if dash_f == 'e':
            return self._dash_f_e_to_dict(info_filename, tree_filename)
        elif dash_f == 'i':
            return self._dash_f_i_to_dict(info_filename, tree_filename)
        elif dash_f == 'a':
            return self._dash_f_a_to_dict(info_filename, tree_filename)
        else:
            return self._to_dict(info_filename, tree_filename)

    def _to_dict(self, info_filename, tree_filename):
        alpha, freqs, names, rates, lnl = self.parse(info_filename)
        try:
            with open(tree_filename) as fl:
                nwk_tree = fl.read().rstrip()
                tree = dpy.Tree.get(data=nwk_tree, schema='newick')
        except IOError as err:
            logger.error('No tree file - raxml analysis failed')
            return
        n_parts = len(alpha)
        assert len(freqs) == n_parts
        assert len(names) == n_parts
        if rates != None:
            assert len(rates) == n_parts

        result = {'likelihood': lnl[0],
                  'partitions': {},
                  'tree': tree}

        for i in range(n_parts):
            subdict = {'alpha': alpha[i], 'frequencies': freqs[i],
                       'name': names[i]}
            if rates != None:
                subdict['rates'] = rates[i]
            result['partitions'][i] = subdict

        return result

class IqtreeParser(object):
    def __init__(self):
        """
        Put stuff here (regex etc.)
        """

    def parse(self, filename):
        """
        Extract based on strings defined in __init__
        """

    def to_dict(self, tree_filename):

        """
        Add stuff for results dictionary here
        """

        try:
            with open(tree_filename) as fl:
                tree = fl.read()
        except IOError as err:
            logger.error(err)
            return

        tree = tree.rstrip()
        result = {'tree': tree}

        return result

class FasttreeParser(object):
    def __init__(self):
        """
        Put stuff here (regex etc.)
        """
        self.tree = None
        self.likelihood = None

    def parse(self, tree, other):
        """
        Extract based on strings defined in __init__
        """
        self.tree = dpy.Tree.get(data=tree.rstrip(), schema='newick')
        for line in other.split('\n'):
            if 'Optimize all lengths:' in line:
                self.likelihood = float(line.split()[-3])

    def to_dict(self):

        """
        Add stuff for results dictionary here
        """
        result = {'tree': self.tree,
                  'likelihood': self.likelihood}

        return result

class GuenomuParser(object):
    def __init__(self):
        self.best_topology = None
        self.species_trees = None

    def parse(self, filename):
        """
        Extract based on strings defined in __init__
        """
        try:
            self.species_trees = dpy.TreeList.get(path=filename[0],
                                                  schema='nexus')
        except IOError as err:
            logger.error("problem reading species tree file\n" + err)
            return
        try:
            self.best_topology = \
            dpy.TreeList.get(path=filename[1], schema='nexus')[
                0]  # first tree is most frequent (unrooted)
        except IOError as err:
            logger.error("problem reading unrooted species tree file\n" + err)
            return

    def to_dict(self, filenames):
        """
        Add stuff for results dictionary here
        """
        self.parse(filenames)
        result = {
            'best_topology': self.best_topology,
            'species_trees': self.species_trees,
        }
        return result


# 1337. 矩阵中战斗力最弱的 K 行
# 给你一个大小为 m * n 的矩阵 mat，矩阵由若干军人和平民组成，分别用 1 和 0 表示。
# 请你返回矩阵中战斗力最弱的 k 行的索引，按从最弱到最强排序。
# 如果第 i 行的军人数量少于第 j 行，或者两行军人数量相同但 i 小于 j，那么我们认为第 i 行的战斗力比第 j 行弱。
# 军人 总是 排在一行中的靠前位置，也就是说 1 总是出现在 0 之前。

def kWeakestRows(mat: [[int]], k: int) -> [int]:
    strength = {}
    counter = 0
    for row in mat:
        strength[counter] = sum(row)
        counter += 1
    result = list(strength.keys())
    result.sort(key=lambda x: strength[x])
    return result[0: k]

kWeakestRows([[1,1,0,0,0],
 [1,1,1,1,0],
 [1,0,0,0,0],
 [1,1,0,0,0],
 [1,1,1,1,1]], 3)

1337. 矩阵中战斗力最弱的 K 行.py


# Add the root path of the dmrgpy library
import os ; import sys ; sys.path.append(os.getcwd()+'/../../../src')

import numpy as np
import matplotlib.pyplot as plt
from dmrgpy import parafermionchain
n = 3
pc = parafermionchain.Parafermionic_Chain(n,Z=3) # create the chain
pc.test_ED()

h = 0
for i in range(n):
  for j in range(n):
      h = h + pc.N[i]*pc.N[j]*np.random.random()
      h = h + pc.Sig[i]*pc.Sig[j]*np.random.random()
      h = h + 1j*pc.Sig[i]*pc.Sigd[j]*np.random.random()
      h = h + pc.Tau[i]*pc.Tau[j]*np.random.random()
      h = h + 1j*pc.Tau[i]*pc.Taud[j]*np.random.random()

h = h + h.get_dagger() # Make the Hamiltonian Hermitian
pc.set_hamiltonian(h) # set the Hamiltonian
pc.maxm = 60
pc.kpmmaxm = 60
print(pc.gs_energy(mode="DMRG"))
print(pc.gs_energy(mode="ED"))

print(pc.get_excited(mode="ED",n=10))

ops = pc.Chi + pc.Psi
no = 10

def rando():
    o = ops[np.random.randint(len(ops))]
    return o #+ o.get_dagger()

name = [rando(),rando()]
delta = 1e-1
(e1,d1) = pc.get_dynamical_correlator(name=name,mode="ED",submode="INV",
        delta=delta)
(e2,d2) = pc.get_dynamical_correlator(name=name,mode="ED",submode="KPM",
        delta=delta)
(e0,d0) = pc.get_dynamical_correlator(name=name,mode="DMRG",submode="KPM",
        delta=delta)

plt.plot(e0,d0.real,color="red",label="DMRG")
plt.scatter(e2,d2.real,color="green",label="ED-KPM")
plt.plot(e1,d1.real,color="blue",label="ED-INV")
plt.legend()
plt.show()


# -*- coding: utf-8 -*-
import logging
from functools import partial
from os import getenv
from urllib.parse import quote

import pytest
import requests
from asynctest import MagicMock
from requests.auth import HTTPBasicAuth

from cabbage import AmqpConnection, AsyncAmqpRpc

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(name)s: %(message)s')

TEST_RABBITMQ_HOST = getenv('TEST_RABBITMQ_HOST', 'localhost')

class Management:
    def __init__(self, url, vhost):
        self.base_url = f'{url}/api/'
        self.vhost = vhost
        self.request_params = dict(
            auth=HTTPBasicAuth('guest', 'guest'),
            headers={'content-type': 'application/json'},
        )

    def _call(self, http_method, *args, **kwargs):
        args = map(partial(quote, safe=''), args)
        result = requests.request(http_method,
                                  self.base_url + '/'.join(args),
                                  **{**self.request_params, **kwargs})
        if result.text:
            return result.json()

    def get_queue(self, name):
        return self._call('get', 'queues', self.vhost, name)

    def get_consumers(self):
        return self._call('get', 'consumers', self.vhost)

    def get_exchanges(self):
        return self._call('get', 'exchanges', self.vhost)

    def put_vhost(self):
        self._call('put', 'vhosts', self.vhost)
        self._call('put', 'permissions', self.vhost, 'guest', json={'configure': '.*', 'write': '.*', 'read': '.*'})

    def delete_vhost(self):
        self._call('delete', 'vhosts', self.vhost)

    def publish(self, exchange, routing_key, data):
        self._call('post', 'exchanges', self.vhost, exchange or 'amq.default', 'publish',
                   json={'properties': {}, 'routing_key': routing_key, 'payload': data, 'payload_encoding': 'string'})

TEST_VHOST = 'cabbage_test'

@pytest.fixture(scope='session')
def management():
    """Wrapper for RabbitMQ Management Plugin API."""
    return Management(f'http://{TEST_RABBITMQ_HOST}:15672', vhost=TEST_VHOST)

@pytest.yield_fixture(scope='function', autouse=True)
def vhost_environment(management: Management):
    management.put_vhost()
    yield
    management.delete_vhost()

@pytest.fixture
async def rpc(event_loop):
    """Ready-to-work RPC connected to RabbitMQ in Docker."""
    connection = AmqpConnection(hosts=[(TEST_RABBITMQ_HOST, 5672)], virtualhost=TEST_VHOST,
                                loop=event_loop)
    rpc = AsyncAmqpRpc(connection=connection)
    await rpc.connect()
    yield rpc
    await rpc.stop()

@pytest.fixture
async def rpc_with_specified_callback_exchange(event_loop, request):
    """Ready-to-work RPC connected to RabbitMQ with specified callback exchange"""
    connection = AmqpConnection(hosts=[(TEST_RABBITMQ_HOST, 5672)], virtualhost=TEST_VHOST,
                                loop=event_loop)
    rpc = AsyncAmqpRpc(connection=connection, callback_exchange=request.param)
    rpc._on_response = MagicMock()
    await rpc.connect()
    yield rpc
    await rpc.stop()


start = True
start1 = True
start2 = True
while start:
    jam = int(input("Kegiatan Di Mulai (Jam 0-23) => "))
    if jam >= 0 and jam <= 23:
        start = False
    else:
        print("Masukkan Dengan Benar")
while start1:
    menit = int(input("Kegiatan Di Mulai (Menit 0-59) => "))
    if menit >= 0 and menit <= 59:
        start1 = False
    else:
        print("Masukkan Dengan Benar")

while start2:
    durasi = int(input("Durasi Kegiatan (Menit) => "))
    if durasi >= 0:
        start2 = False
    else:
        print("Salah Goblok")

print("="*40)
print("Kegiatan Di Mulai Pukul = ",jam,":",menit,"\nDurasi kegiata = ",durasi,"Menit")
menit_akhir = menit + durasi
if menit_akhir >= 60:
    menit = menit_akhir - 60
    jam += 1
    while  menit >= 60:
        menit = menit - 60
        jam += 1

    if jam >= 24:
        jam = jam - 24

print("Kegiatan Berakhir pukul =",jam,":",menit)
print("="*40)


import numpy as np

def heavy(x):
    """
        Fonction d'Heaviside
    """
    if x>0 :
        return 1
    else :
        return 0

def handy_resc_eg(X,t,delta,k):
    """
        Modèle HANDY remis à l'échelle dans le cas d'une société égalitaire (n'a qu'un seul type de population)
    """
    xc,y,w = X
    xct = xc + 3*(xc*w/(xc)-xc)*heavy(xc-w)
    yt = 0.5*y*(100-y)-delta*y*xc
    wt = delta*y*xc-5*(xc)+5*(xc-w)*heavy(xc-w)
    return np.array((xct,yt,wt))

def jacob (X,delta):
    x,y,w = X
    if ((x-w)>0):
        return np.array(([-2,0,3],[-delta*y,50-y-delta*x,0],[delta*y,delta*x,-5]))
    else:
        return np.array(([1,0,0],[-delta*y,0,50-y-delta*x,0],[delta*y-5,delta*x,0]))

# CONSTANTES
betac = 3E-2
betae = 3E-2
gama = 1E-2
lamba = 100
k = 1
s = 5E-4
rho = 5E-3
alpham = 1E-2
alphaM = 7E-2
xc0 = 100
xe0 = 25
y0 = lamba
w0 = 0
eta = (alphaM-betac)/(alphaM-alpham)
chiM = gama/(eta*s)*lamba**2/4
delta_opt = 6.67E-6
delta_opt2 = 8.33E-6

delta_resc  = delta_opt/(rho*(betac-alpham))
delta_resc_2  = delta_opt2/(rho*(betac-alpham))
xc0_resc = xc0*rho
xe0_resc = xe0*rho*k
chiM_resc = gama/2*lamba/delta_resc


from django.http import HttpResponse, Http404
from django.shortcuts import render, get_object_or_404
from .models import Movie  # importando os models

# Create your views here.

def index(request):
    # SELECT * FROM movies_movie
    movies = Movie.objects.all()

    render(request, 'index.html', {'movies': movies})

    # SELECT * FROM movies_movie WHERE
    # Movie.objects.filter(release_year=1984)

    # return HttpResponse("Hello World")

    return render(request, 'index.html', {'movies': movies})

def detail(request, movie_id):
    # try:
    #     movie = Movie.objects.get(pk=movie_id)
    #     return render(request, 'movies/detail.html', {'movie': movie})
    # except Movie.DoesNotExist:
    #     raise Http404()

    movie = get_object_or_404(Movie, pk=movie_id)
    return render(request, 'movies/detail.html', {'movie': movie})


"""Alert panes inspired by Bootstrap Alerts.

This example was originally created to show how to create custom Bootstrap Alerts.
The Alerts have now been contributed to Panel. You can find the reference example
[here](https://panel.holoviz.org/reference/panes/Alert.html).
"""
import panel as pn
from awesome_panel.express.testing import TestApp
from awesome_panel_extensions.site import site

APPLICATION = site.create_application(
    url="bootstrap-alerts",
    name="Bootstrap Alerts",
    author="Marc Skov Madsen",
    description="Demonstrates the look and feel of the Panel Alerts",
    description_long=__doc__,
    thumbnail="test_bootstrap_alerts.png",
    resources={
        "code": "awesome_panel_express_tests/test_bootstrap_alerts.py",
    },
    tags=["Bootstrap"],
)

def test_info_alert():
    """
    We can show an InfoAlert

    - Blue Div with normal and bold text
    - Full width by default
    - With a nice bottom margin
    """
    return TestApp(
        test_info_alert,
        pn.pane.Alert("This is an **Info Alert**!"),
        sizing_mode="stretch_width",
    )

def test_warning_alert():
    """We can show a Warning Alert

    - Yellow Div with normal and bold text
    - Full width by default
    - With a nice bottom margin
    """
    return TestApp(
        test_warning_alert,
        pn.pane.Alert("This is a **Warning Alert**!", alert_type="warning"),
        sizing_mode="stretch_width",
    )

def test_error_alert():
    """We can show an Error Alert

    - Red Div with normal and bold text
    - Full width by default
    - With a nice bottom margin
    """
    return TestApp(
        test_error_alert,
        pn.pane.Alert("This is an **Error Alert**!", alert_type="danger"),
        sizing_mode="stretch_width",
    )

@site.add(APPLICATION)
def view() -> pn.Column:
    """Wraps all tests in a Column that can be included in the Gallery or served independently

    Returns:
        pn.Column -- A Column containing all the tests
    """
    pn.config.sizing_mode = "stretch_width"
    main = [
        APPLICATION.intro_section(),
        test_info_alert(),
        test_error_alert(),
        test_warning_alert(),
    ]
    return pn.template.FastListTemplate(title="Test Bootstrap Alerts", main=main)

if __name__.startswith("bokeh"):
    view().servable()


class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """

        # array is sorted and garunteed 1 answer
        # 2 pointers Binary Search
        p1 = 0
        p2 = len(numbers) - 1

        while p1 <= p2:
            _sum = numbers[p1] + numbers[p2]

            if _sum < target:
                p1 = p1 + 1
            if _sum > target:
                p2 = p2 - 1
            if _sum == target:
                return [p1 + 1, p2 + 1]


import pygame, math, sys
from time import sleep
pygame.init()

X = 900
Y = 650

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREY = (200, 200, 200)
ORANGE = (200, 100, 50)
RED = (255,0,0)
RED_2 = (237,41,57)
GREEN = (0,255,0)
TRANS = (1, 1, 1)

font = pygame.font.SysFont("Arial", 12)
font2 = pygame.font.SysFont("Arial BOLD", 24)
screen = pygame.display.set_mode((X, Y))
clock = pygame.time.Clock()
pop = 7

background2 = pygame.image.load('background2_forces.jpg')
background3 = pygame.image.load('background3_forces.jpg')

horiz_plane = pygame.image.load("horiz_plane.png")
horiz_plane = pygame.transform.scale(horiz_plane,(60,60))

class Slider():
    def __init__(self, name, maxi, mini, pos, unit):
        self.val = (maxi+mini)/2  # start value
        self.maxi = maxi  # maximum at slider position right
        self.mini = mini  # minimum at slider position left
        self.xpos = X/2-40  # x-location on screen
        self.x_max = self.xpos+80
        self.ypos = pos
        self.surf = pygame.surface.Surface((165, 50))
        self.hit = False  # the hit attribute indicates slider movement due to mouse interaction
        self.unit = unit

        self.txt_surf = font.render(name, 1, BLACK)
        self.txt_rect = self.txt_surf.get_rect(center=(50, 15))

        # Static graphics - slider background #
        pygame.draw.rect(self.surf, GREY, [0, 0, 165, 50], 3)
        pygame.draw.rect(self.surf, ORANGE, [10, 10, 80, 10], 0)
        pygame.draw.rect(self.surf, WHITE, [10, 30, 80, 5], 0)

        self.surf.blit(self.txt_surf, self.txt_rect)  # this surface never changes

        # dynamic graphics - button surface #
        self.button_surf = pygame.surface.Surface((20, 20))
        self.button_surf.fill(TRANS)
        self.button_surf.set_colorkey(TRANS)
        pygame.draw.circle(self.button_surf, BLACK, (10, 10), 6, 0)
        pygame.draw.circle(self.button_surf, ORANGE, (10, 10), 4, 0)

    def draw(self):
        # static
        surf = self.surf.copy()
        # dynamic
        pos = (10+int((self.val-self.mini)/(self.maxi-self.mini)*80), 33)
        self.button_rect = self.button_surf.get_rect(center=pos)
        surf.blit(self.button_surf, self.button_rect)
        self.button_rect.move_ip(self.xpos, self.ypos)
        # screen
        mouseX,mouseY=pygame.mouse.get_pos()
        screen.blit(surf, (self.xpos, self.ypos))
        value = font.render("= "+str(round(self.val,2))+self.unit,False,WHITE)
        screen.blit(value,(self.xpos+100,self.ypos+15))

    def move(self):
        self.val = (pygame.mouse.get_pos()[0] - self.xpos - 10) / 80 * (self.maxi - self.mini) + self.mini
        if self.val < self.mini:
            self.val = self.mini
        if self.val > self.maxi:
            self.val = self.maxi

def start_button_display():
    mousex, mousey = pygame.mouse.get_pos()
    if 10 <= mousex <= 10+50 and  75 <= mousey <= 75+25 and pygame.mouse.get_pressed():
        pygame.draw.rect(screen, GREEN, [10-pop/2, 75-pop/2, 50+pop, 25+pop])
        pygame.draw.rect(screen, WHITE, (10, 75, 50, 25))
        return True
    pygame.draw.rect(screen, GREEN, [10-pop/2, 75-pop/2, 50+pop, 25+pop])
    return False

def plane_startup(planeY,count,component):
    if count == 0: #BASE CASE
        return planeY

    if count % 2 ==1:
        planeY-=5
    else:
        planeY+=5
    count-=1
    screen.blit(horiz_plane,(X/2,Y-100+planeY))
    pygame.display.update()
    if component == 'Vertical':
        screen.blit(background2,(0,0))
    elif component == 'Horizontal':
        screen.blit(background3,(0,0))
    sleep(.05)
    return plane_startup(planeY,count,component)

def call_sliders(slides,component):
    DisplayList=[]
    planeX=X/2
    planeY=plane_startup(0,20, component)
    while True:
        if component == 'Vertical':
            force_gravity = slides[0].val*9.8
            a=(force_gravity - slides[1].val)/slides[0].val
            if start_button_display() and a>0:
                return_list=[]
                for i in range(len(slides)):
                    return_list.append(slides[i].val)
                return return_list
            elif a<=0:
                pygame.draw.rect(screen, RED, [10-pop/2, 75-pop/2, 50+pop, 25+pop])
                static_text = font2.render('Impossible Acceleration value ', False, WHITE)
                static_text2 = font.render('Adjust Air Resistance or Mass!', False, RED_2)
                screen.blit(static_text,(X/2-120+70-30, Y/2+140+30-5))
                screen.blit(static_text2,(X/2-120+50, Y/2+150+30))

        elif component == 'Horizontal':
            force_friction = slides[0].val*9.8*slides[2].val
            a=(slides[1].val - force_friction)/slides[0].val
            if start_button_display() and a>0:
                return_list=[]
                for i in range(len(slides)):
                    return_list.append(slides[i].val)
                return return_list
            elif a<=0:
                pygame.draw.rect(screen, RED, [10-pop/2, 75-pop/2, 50+pop, 25+pop])
                static_text = font2.render('Impossible Acceleration value ', False, WHITE)
                static_text2 = font.render('Adjust Mass, Coef or Applied Force!', False, RED_2)
                screen.blit(static_text,(X/2-120+70-30, Y/2+140+30-5))
                screen.blit(static_text2,(X/2-120+50, Y/2+150+30))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                for s in slides:
                    if s.button_rect.collidepoint(pos):
                        s.hit =  True
            elif event.type == pygame.MOUSEBUTTONUP:
                for s in slides:
                    s.hit = False

        for s in slides:
            if s.hit:
                s.move()

        pygame.display.update()

        if component == 'Vertical':
            screen.blit(background2,(0,0))
        elif component == 'Horizontal':
            screen.blit(background3,(0,0))
        planeX+=1
        if planeX-120>X: planeX=0-120
        screen.blit(horiz_plane,(planeX,Y-100))
        for s in slides:
            s.draw()