#!/usr/bin/env python3
"""
Name: vpc_consistency.py
Description: NXAPI: display inconsistent vpc parameters

Example output when vpc is consistent:

% ./vpc_consistency.py --vault hashicorp --devices cvd_leaf_2 --interface Po11,Po12
192.168.11.103  cvd-1312-leaf        all 22 global vpc params are consistent
192.168.11.103  cvd-1312-leaf        all 7 vni vpc params are consistent
192.168.11.103  cvd-1312-leaf        all 12 vlans vpc params are consistent
192.168.11.103  cvd-1312-leaf        Po11 all 23 interface vpc port-channel params are consistent
192.168.11.103  cvd-1312-leaf        Po12 all 23 interface vpc port-channel params are consistent
%

Example output when vpc po allowed-vlans are mismatched:

% ./vpc_consistency.py --vault hashicorp --devices cvd_leaf_2 --interface Po11,Po12
192.168.11.103  cvd-1312-leaf        all 22 global vpc params are consistent
192.168.11.103  cvd-1312-leaf        all 7 vni vpc params are consistent
192.168.11.103  cvd-1312-leaf        all 12 vlans vpc params are consistent
192.168.11.103  cvd-1312-leaf        Po11 Allowed VLANs
   vpc-param-type: -
   vpc-param-local-val: 1111-1112
   vpc-param-peer-val: 1111
192.168.11.103  cvd-1312-leaf        Po11 Local suspended VLANs
   vpc-param-type: -
   vpc-param-local-val: 1112
   vpc-param-peer-val: -
192.168.11.103  cvd-1312-leaf        Po12 all 23 interface vpc port-channel params are consistent
%
"""
our_version = 109
script_name = "vpc_consistency"

# standard libraries
import argparse
from concurrent.futures import ThreadPoolExecutor

# local libraries
from nxapi_netbox.args.args_cookie import ArgsCookie
from nxapi_netbox.args.args_nxapi_tools import ArgsNxapiTools
from nxapi_netbox.general.log import get_logger
from nxapi_netbox.netbox.netbox_session import netbox, get_device_mgmt_ip
from nxapi_netbox.vault.vault import get_vault
from nxapi_netbox.nxapi.nxapi_vpc_consistency import (
    NxapiVpcConsistencyGlobal,
    NxapiVpcConsistencyVni,
    NxapiVpcConsistencyVlans,
    NxapiVpcConsistencyInterface,
)

def get_parser():
    help_interfaces = "a comma-separated list (no spaces) of port-channel interfaces to test for vpc consistency"
    help_mismatched_labels = "display labels whose number of comma-separated entries differ from the number of values they refer to"

    ex_interfaces = "Example: --interfaces Po1,Po10"
    ex_mismatched_labels = "Example: --mismatched_labels"

    parser = argparse.ArgumentParser(
        description="DESCRIPTION: NXAPI: display inconsistent vpc parameters",
        parents=[ArgsCookie, ArgsNxapiTools],
    )
    default = parser.add_argument_group(title="DEFAULT SCRIPT ARGS")
    mandatory = parser.add_argument_group(title="MANDATORY SCRIPT ARGS")

    parser.add_argument(
        "--version", action="version", version="{} v{}".format("%(prog)s", our_version)
    )

    default.add_argument(
        "--mismatched_labels",
        dest="mismatched_labels",
        required=False,
        action="store_true",
        default=False,
        help="{} {}".format(help_mismatched_labels, ex_mismatched_labels),
    )

    default.add_argument(
        "--interfaces",
        dest="interfaces",
        required=False,
        default=None,
        help="{} {}".format(help_interfaces, ex_interfaces),
    )

    return parser.parse_args()

def get_device_list():
    try:
        return cfg.devices.split(",")
    except:
        log.error(
            "exiting. Cannot parse --devices {}.  Example usage: --devices leaf_1,spine_2,leaf_2".format(
                cfg.devices
            )
        )
        exit(1)

def print_output(futures):
    for future in futures:
        output = future.result()
        if output == None:
            continue
        for line in output:
            print(line)

def show_inconsistent_params(ip, nx, interface=None):
    lines = list()
    if nx.error_reason != None:
        log.error("{} {} error: {}".format(tb.sid, nx.hostname, nx.error_reason))
        return lines
    inconsistent_items = nx.inconsistent_params
    if len(inconsistent_items) == 0:
        if interface == None:
            lines.append(
                "{:<15} {:<20} all {} {} vpc params are consistent".format(
                    ip, nx.hostname, len(nx.info), nx.param_type
                )
            )
        else:
            lines.append(
                "{:<15} {:<20} {} all {} {} vpc port-channel params are consistent".format(
                    ip, nx.hostname, interface, len(nx.info), nx.param_type
                )
            )
    else:
        for item in nx.inconsistent_params:
            if interface == None:
                lines.append(
                    "{:<15} {:<20} {}".format(ip, nx.hostname, item["vpc-param-name"])
                )
            else:
                lines.append(
                    "{:<15} {:<20} {} {}".format(
                        ip, nx.hostname, interface, item["vpc-param-name"]
                    )
                )
            for key in item:
                if key == "vpc-param-name":
                    continue
                lines.append("   {}: {}".format(key, item[key]))
    return lines

def show_mismatched_labels(ip, nx):
    lines = list()
    if cfg.mismatched_labels == False:
        return lines
    if len(nx.mismatched_info) > 0:
        for label in nx.mismatched_info:
            lines.append(
                "{:<15} {:<20} vpc-param-name {}".format(ip, nx.hostname, label)
            )
            lines.append("    labels {}".format(nx.mismatched_info[label]["names"]))
            lines.append("    values {}".format(nx.mismatched_info[label]["params"]))
    return lines

def worker(device, vault):
    ip = get_device_mgmt_ip(nb, device)
    lines = list()
    for class_name in [
        NxapiVpcConsistencyGlobal,
        NxapiVpcConsistencyVni,
        NxapiVpcConsistencyVlans,
    ]:
        nx = class_name(vault.nxos_username, vault.nxos_password, ip, log)
        nx.nxapi_init(cfg)
        nx.refresh()
        if nx.error_reason != None:
            lines.append("{} {} error: {}".format(ip, nx.hostname, nx.error_reason))
            return lines
        lines += show_inconsistent_params(ip, nx)
        lines += show_mismatched_labels(ip, nx)

    if cfg.interfaces == None:
        return lines
    for interface in cfg.interfaces.split(","):
        nx = NxapiVpcConsistencyInterface(
            vault.nxos_username, vault.nxos_password, ip, log
        )
        nx.nxapi_init(cfg)
        nx.interface = interface
        nx.refresh()
        lines += show_inconsistent_params(ip, nx, interface)
    return lines

cfg = get_parser()
log = get_logger(script_name, cfg.loglevel, "DEBUG")
vault = get_vault(cfg.vault)
vault.fetch_data()
nb = netbox(vault)

devices = get_device_list()

executor = ThreadPoolExecutor(max_workers=len(devices))
futures = list()
for device in devices:
    args = [device, vault]
    futures.append(executor.submit(worker, *args))
print_output(futures)


from django.urls import path

from posting.views  import (
    PostingView,
    CategoryView,
    PostingLikeView,
    PostingScrapView
)

urlpatterns = [
    path('', PostingView.as_view()),
    path('/category', CategoryView.as_view()),
    path('/like', PostingLikeView.as_view()),
    path('/scrap', PostingScrapView.as_view())
]


from tqdm import tqdm

# Define constant
SHORT  = 15
MIDDLE = 30
LARGE  = 50

def __clear__(times: int = 11, length: int = 123):
    """
        Clear the previous table toward the terminal
    """
    print()
    for i in range(times + 1):
        if i != times:
            print("\033[F" + ' ' * length, end='')
        else:
            print("\033[F", end = '')
    print("\r")

def __getCutLine__(length: int = 50, width_cell: int = 10, equal_symbol: bool = True) -> str:
    """
        Obtain the cut line

        Arg:    length          - The maximun length of the terminal
                width_cell      - The width of the table cell
                equal_symbol    - If use '=' as the symbol or not
        Ret:    The custom cut line string
    """
    cut_string = "+"
    acc_length = 0
    while True:
        if acc_length == 0:
            if equal_symbol:
                cut_string = cut_string + '=' * (width_cell) + '+'
            else:
                cut_string = cut_string + '-' * (width_cell) + '+'
            acc_length += width_cell
        else:
            if equal_symbol:
                cut_string = cut_string + '=' * (width_cell + 2) + '+'
            else:
                cut_string = cut_string + '-' * (width_cell + 2) + '+'
            acc_length += (width_cell + 2)
        if acc_length >= length - width_cell:
            break
    return cut_string

class tqdm_table(tqdm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.max_length = 100
        self.prev_lines = -1

    def set_table_setting(self, max_length: int = 100):
        """
            Assign the setting of this object

            Arg:    max_length  - The maximun length of the terminal
        """
        self.max_length = max_length

    def set_table_info(self, mapping: dict):
        """
            Set the table information

            Arg:    mapping     - The key-value pair you want to form the table
        """
        key_string = ""
        val_string = ""
        table_string = []
        key_list = sorted(mapping.keys())

        # Clear the previous table information toward stdout
        if self.prev_lines > 0:
            __clear__(self.prev_lines, self.max_length)

        # Determine the width of cell
        if max([max(len(str(val)), len(key)) for key, val in mapping.items()]) <= 15:
            width_length = SHORT
        elif max([max(len(str(val)), len(key)) for key, val in mapping.items()]) <= 30:
            width_length = MIDDLE
        else:
            width_length = LARGE

        # Collect the lines of keys and values
        for key in key_list:
            val = mapping[key]
            single_max_length = max(len(key), len(str(val)))
            if len(key_string) + single_max_length + 2 < self.max_length:
                if width_length == SHORT:
                    key_string += '{:>15} | '.format(key)
                    val_string += '{:>15} | '.format(val)
                elif width_length == MIDDLE:
                    key_string += '{:>30} | '.format(key)
                    val_string += '{:>30} | '.format(val)
                else:
                    key_string += '{:>50} | '.format(key)
                    val_string += '{:>50} | '.format(val)
            else:
                table_string.append(key_string)
                table_string.append(val_string)
                if width_length == SHORT:
                    key_string = '{:>15} | '.format(key)
                    val_string = '{:>15} | '.format(val)
                elif width_length == MIDDLE:
                    key_string = '{:>30} | '.format(key)
                    val_string = '{:>30} | '.format(val)
                else:
                    key_string = '{:>50} | '.format(key)
                    val_string = '{:>50} | '.format(val)

        # Accumulate the rest information if there are some information rest
        if len(key_string) > 0 or len(val_string) > 0:
            table_string.append(key_string)
            table_string.append(val_string)

        # Transfer the containing of queue into string
        cut_string_small = __getCutLine__(length=max([len(_) for _ in table_string]), width_cell=width_length, equal_symbol=False)
        cut_string_large = __getCutLine__(length=max([len(_) for _ in table_string]), width_cell=width_length, equal_symbol=True)
        print_string = cut_string_large
        for i in range(len(table_string) // 2):
            print_string = print_string + '\n' + table_string[2*i] + '\n' + cut_string_small + '\n' + table_string[2*i+1] + '\n' + cut_string_large
        self.prev_lines = 2 * (len(table_string) + 1)

        # Write into tqdm
        self.write(print_string)


'''
Exercise 3: Write a program to prompt for a score between 0.0 and
1.0. If the score is out of range, print an error message. If the score is
between 0.0 and 1.0, print a grade using the following table

>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
'''

# Function to calculate the score.
def cal_grade(score):
    if score >= 0.9:
        print("Grade: A")
    elif score >= 0.8:
        print("Grade: B")
    elif score >= 0.7:
        print("Grade: C")
    elif score >= 0.6:
        print("Grade: D")
    else:
        print("Grade: F")
try:
    score = float(input("Enter your score: "))
    cal_grade(score)
except:
    print("Please input a number between 0.0 and 1.0")


from copy import copy
class Poly:

    def __init__(self,*terms):
        # __str__ uses the name self.terms for the dictionary of terms
        # So __init__ should build this dictionary from terms
        self.terms = {}
        if terms==None:
            self.terms={0:0}
        for term in terms:
            assert type(term[0]) in (int,float)
            assert type(term[1])==int and term[1]>=0
            if term[1] in self.terms:
                if term[0]!=0:
                    raise AssertionError
            if term[0]!=0:
                self.terms[term[1]]=term[0]

        # Fill in the rest of this method, using *terms to intialize self.terms

    # I have written str(...) because it is used in the bsc.txt file and
    #   it is a bit subtle to get correct. Notice that it assumes that
    #   every Poly object stores a dict whose keys are powers and whose
    #   associated values are coefficients. This function does not depend
    #   on any other method in this class being written correctly.
    def __str__(self):
        def term(c,p,var):
            return (str(c) if p == 0 or c != 1 else '') +\
                   ('' if p == 0 else var+('^'+str(p) if p != 1 else ''))
        if len(self.terms) == 0:
            return '0'
        else:
            return ' + '.join([term(c,p,'x') for p,c in sorted(self.terms.items(),reverse=True)]).replace('+ -','- ')

    def __repr__(self):
        results=[]
        for k,v in self.terms.items():
            results.append(str((v,k)))
        return 'Poly({})'.format(','.join(results))

    def __len__(self):
        return max(self.terms) if len(self.terms)>0 else 0

    def __call__(self,arg):
        results=0
        for k,v in self.terms.items():
            results+=v*(arg)**k
        return results

    def __iter__(self):
        for k in sorted(self.terms,reverse=True):
            yield(self.terms[k],k)

    def __getitem__(self,index):
        if type(index)==int and index>=0:
            return self.terms[index] if index in self.terms else 0
        raise TypeError

    def __setitem__(self,index,value):
        if type(index)==int and index>=0:
            if value==0:
                if index in self.terms:
                    del self.terms[index]
                else:
                    pass
            else:
                self.terms[index]=value
        else:
            raise TypeError

    def __delitem__(self,index):
        if type(index)==int and index>=0:
            if index in self.terms:
                del self.terms[index]
        else:
            raise TypeError

    def _add_term(self,c,p):
        if type(p)==int and p>=0 and type(c) in (int,float):
            if p not in self.terms and c!=0:
                self.terms[p]=c
            else:
                if p in self.terms:
                    if self.terms[p]+c!=0:
                        self.terms[p]=self.terms[p]+c
                    else:
                        del self.terms[p]
        else:
            raise TypeError

    def __add__(self,right):
        values=[[v,k] for k,v in self.terms.items()]
        if type(right) in (int,float):
            for value in values:
                if value[1]==0:
                    if value[0]+right!=0:
                        value[0]=value[0]+right
                    else:
                        values.remove(value)
        elif type(right)==Poly:
            for k,v in right.terms.items():
                if k in [value[1] for value in values]:
                    for value in values:
                        if value[1]==k:
                            if value[0]+right.terms[k]!=0:
                                value[0]=value[0]+right.terms[k]
                            else:
                                values.remove(value)
                else:
                    values.append((v,k))
        else:
            raise TypeError
        results=[str(value) for value in values]
        return eval('Poly({})'.format(','.join(results)))

    def __radd__(self,left):
        values=[[v,k] for k,v in self.terms.items()]
        if type(left) in (int,float):
            for value in values:
                if value[1]==0:
                    if value[0]+left!=0:
                        value[0]=value[0]+left
                    else:
                        values.remove(value)
        elif type(left)==Poly:
            for k,v in left.terms.items():
                if k in [value[1] for value in values]:
                    for value in values:
                        if value[1]==k:
                            if value[0]+left.terms[k]!=0:
                                value[0]=value[0]+left.terms[k]
                            else:
                                values.remove(value)
                else:
                    values.append((v,k))
        else:
            raise TypeError
        results=[str(value) for value in values]
        return eval('Poly({})'.format(','.join(results)))

    def __mul__(self,right):
        values=[[v,k] for k,v in self.terms.items()]
        if type(right) in (int,float):
            if right==0:
                return 0
            else:
                for value in values:
                    value[0]=right*value[0]
        results=[str(value) for value in values]
        if type(right)==Poly:
            temp=[]
            for k,v in right.terms.items():
                for value in values:
                    if k+value[1] in [t[1] for t in temp]:
                        for t in temp:
                            if t[1]==k+value[1]:
                                temp.append((v*value[0]+t[0],t[1]))
                                temp.remove(t)
                    else:
                        temp.append((v*value[0],k+value[1]))
        results=[str(i) for i in temp]
        return eval('Poly({})'.format(','.join(results)))

    def __rmul__(self,left):
        values=[[v,k] for k,v in self.terms.items()]
        if type(left) in (int,float):
            if left==0:
                return 0
            for value in values:
                value[0]=left*value[0]
        results=[str(value) for value in values]
        return eval('Poly({})'.format(','.join(results)))

    def __eq__(self,right):
        if type(right) in (int,float):
            if len(self.terms)==1 and 0 in self.terms:
                return self.terms[0]==right
            else:
                return False
        elif type(right)==Poly:
            results=True
            for k,v in right.terms.items():
                if k not in self.terms and v!=0:
                    return False
                results=results*(self.terms[k]==right.terms[k])
            return results
        raise TypeError

if __name__ == '__main__':
    # Some simple tests; you can comment them out and/or add your own before
    # the driver is called.
#     print('Start simple tests')
#     p = Poly((3,2),(-2,1), (4,0))
#     print('  For Polynomial: 3x^2 - 2x + 4')
#     print('  str(p):',p)
#     print('  repr(p):',repr(p))
#     print('  len(p):',len(p))
#     print('  p(2):',p(2))
#     print('  list collecting iterator results:',[t for t in p])
#     print('  p+p:',p+p)
#     print('  p+2:',p+2)
#     print('  p*p:',p*p)
#     print('  p*2:',p*2)
#     print('End simple tests\n')
#     p[2] = 0
#     print(str(p))
#     p[10] = 0
#     p1 = Poly((1,1),(2,0))
#     p2 = Poly((3,2),(2,1),(1,0))
#     p3 = Poly((3,5),(-2,2),(-4,0))
#     print(p1+p2)
#     print(p2+p3)
#     print(p1+p3)
#     p3*2
    import driver
    #driver.default_show_exception=True
    #driver.default_show_exception_message=True
    #driver.default_show_traceback=True
    driver.driver()

ics 33/solutions/ile2 solutions/Lab 1/JiangYu/poly.py


from __future__ import absolute_import
import os
from setuptools import setup, find_packages

# Utility function to read the README file.
# Used for the long_description.  It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name='pyswf',
    version='1.5.4',
    description='SWF Parsing Utilities',
    long_description=read('README.md'),
    keywords = "swf parser parsing decompile utilities",

    author='Tim Knip',
    author_email='tim@floorplanner.com',
    url='https://github.com/timknip/pyswf',

    install_requires = ["lxml>=3.3.0", "Pillow>=2.3.0", "pylzma>=0.4.6", "six"],
    packages=find_packages(),
    license = "MIT",
    classifiers=[
        "Development Status :: 4 - Beta",
        "Topic :: Utilities",
        "License :: OSI Approved :: MIT License",
    ],
)


from sklearn.datasets import load_breast_cancer
from sklearn.datasets import load_wine
from E2 import sammon
from E1 import bkmeans
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
from scipy.cluster.hierarchy import linkage
from scipy.cluster.hierarchy import dendrogram

sammons_maxiter = 100
e = 0.001
A = 0.3

# Figure 1
fig1, axs1 = plt.subplots(3, 3, figsize=(10, 10))
print(f"Max iter set to {sammons_maxiter}. It might take a total of {sammons_maxiter*3} to run the code. Each iteration takes approx 0.5-2 seconds.")
for i in range(3):
    if i == 0:
        datasetX, datasetLabels = load_breast_cancer().data, load_breast_cancer().target
        dataset_name = 'Breast Cancer Dataset'
    elif i == 1:
        datasetX, datasetLabels = load_wine().data, load_wine().target
        dataset_name = 'Wine Dataset'
    elif i == 2:
        diabetesData = np.genfromtxt('csv_result-diabetes.csv', delimiter=',', skip_header=1)
        datasetX, datasetLabels = diabetesData[:, :-1], diabetesData[:, -1]
        dataset_name = 'Diabetes Dataset'

    for j in range(3):
        if j == 0:
            print(f"Computing sammon mapping for {dataset_name} ({i+1}/3)")
            result = sammon(datasetX, sammons_maxiter, e, A)
            plot_title = 'Sammon Mapping'
        elif j == 1:
            pca = PCA(n_components=2)
            result = pca.fit_transform(datasetX)
            plot_title = 'PCA'
        elif j == 2:
            tsne = TSNE(n_components=2)
            result = tsne.fit_transform(datasetX)
            plot_title = 't-SNE'

        axs1[i, j].scatter(result[:, 0], result[:, 1], c=datasetLabels, s=5)
        axs1[i, j].set_title(f'{dataset_name} - {plot_title}')

plt.tight_layout()

fig, axes = plt.subplots(3, 3, figsize=(10, 10))

for i in range(3):
    if i == 0:
        datasetX, datasetLabels = load_breast_cancer().data, load_breast_cancer().target
        dataset_name = 'Breast Cancer Dataset'
    elif i == 1:
        datasetX, datasetLabels = load_wine().data, load_wine().target
        dataset_name = 'Wine Dataset'
    elif i == 2:
        diabetesData = np.genfromtxt('csv_result-diabetes.csv', delimiter=',', skip_header=1)
        datasetX, datasetLabels = diabetesData[:, :-1], diabetesData[:, -1]
        dataset_name = 'Diabetes Dataset'

    pca = PCA(n_components=2)
    X_pca = pca.fit_transform(datasetX)

    for j in range(3):
        ax = axes[i, j]
        if j == 0:
            bkmeans_result = bkmeans(X_pca, 2, 30)
            c = bkmeans_result
            algorithm_name =  'bk means'
        elif j == 1:
            kmeans_result = KMeans(n_init = 10, n_clusters=2, random_state=0).fit_predict(X_pca)
            c = kmeans_result
            algorithm_name =  'classic k means'
        elif j == 2:
            hierarchical_result = linkage(X_pca, method='ward')
            dendro = dendrogram(hierarchical_result, ax=ax)
            c = datasetLabels
            algorithm_name =  'hierarchical'

        ax.scatter(X_pca[:, 0], X_pca[:, 1], c=c)
        ax.set_title(f'{dataset_name} - {algorithm_name}')

plt.tight_layout()
plt.show()


"""
This class is used to cause object-like behavior in non-OOP libraries or enhance polymorphism in objects.
It does so by saving any repetitive parameter in its attributes and passing it into any function that can accept them.
For a demo, see example.py
@author Ben Hsieh
"""
import inspect

class ClassEmulator:
    def __init__(self, target_class, **kwargs):
        """
        Creates a target_class emulator and stores any function parameter as self attributes.

        Parameters
        ----------
        target_class: class or object
            The target to emulate. Can be anything with its own library of functions.
        **kwargs: any key=value
            Any additional parameters to store and use in target_class's functions.
        """
        self.__target_class = target_class
        self.__reference_objects = []
        self.save_params(**kwargs)

    def save_params(self, **kwargs):
        """
        Stores any parameter you may want to pass into functions as class attributes.

        Parameters
        ----------
        **kwargs: any key=value
            Any parameter to store and use in target_class's functions.
        """
        for key, value in kwargs.items():
            self.__setattr__(key, value)

    def save_reference_object(
        self, reference_object, copy_attributes: bool = False
    ) -> None:
        """
        Saves an object from which we can look up attributes.
        Newer references' attributes will overwrite older references' attributes.
        Self attributes will overwrite any reference object attributes.
        If copy_attributes, the reference object's attributes are copied to self attributes, and the reference object is then discarded.
        """
        if copy_attributes:
            reference_object_attributes = reference_object.__dict__
            self.save_params(**reference_object_attributes)

        else:
            self.__reference_objects.append(reference_object)

    def __getattr__(self, function_name):
        """
        Runs the named function with any stored applicable parameter and any parameter the user passes in.
        """
        def run_named_function(*args, **kwargs):
            # identifies the target function
            target_function = getattr(self.__target_class, function_name)

            # identifies all parameters the target function uses
            target_function_parameters = [
                parameter
                for i, parameter in enumerate(target_function.__code__.co_varnames)
                if i > 0 or parameter != "obj"  # TODO check if other non-parameters could be referenced
            ]

            # acquires all stored parameters
            stored_parameters = {}
            for reference_object in self.__reference_objects:
                for key, value in reference_object.__dict__.items():
                    stored_parameters[key] = value
            for key, value in self.__dict__.items():
                if not any(
                    key == reserved_name
                    for reserved_name in [
                        "_ClassEmulator__target_class",
                        "_ClassEmulator__reference_objects",
                    ]
                ):
                    stored_parameters[key] = value

            # finds all stored parameters parameters that are acceptable to the target function
            named_parameters = {
                key: value
                for key, value in stored_parameters.items()
                if "kwargs" in target_function_parameters
                or key in target_function_parameters
            }

            # removes all stored parameters that overlap with kwargs
            number_of_positional_parameters = len(args)
            try:
                is_class_method = self.__target_class.__name__ == target_function.__self__.__name__
                if is_class_method:
                    number_of_positional_parameters += 1
            except AttributeError:
                pass
            positional_parameters_used = target_function_parameters[:number_of_positional_parameters]
            named_parameters = {
                key: value
                for key, value in named_parameters.items()
                if key not in positional_parameters_used
            }

            # makes user input kwargs count
            named_parameters.update(kwargs)

            # run the target function and return the output
            return target_function(*args, **named_parameters)

        return run_named_function


def main():
    # List comprehensions
    # [ <expression> for item in list if <conditional>] syntax
    # creating a list based on an existing list
    # the if part act as a filter (if True it includes, False omittes)
    #
    my_comp_list = [x for x in range(1,10) if x % 2 == 0]
    print(my_comp_list)

    # calling a function in the expression slot.
    # x is defined to be [0, 1, 2, 3, 4, 5, 6, 7]
    # where some_function() is being called for every item in that list
    my_comp_list_2 = [some_function(x) for x in range(8)]
    print(my_comp_list_2)

    # creating a matrix using nested list comprehension
    # [[j for j in num_of_column] for i in [num_of_row]]
    # better coding style than making a matrix with a nested for loop
    my_comp_list_3 = [[j for j in range(3)] for i in range(10)]
    print(my_comp_list_3)

    # flatten the matrix into a one dimentional list
    print([value for sublist in my_comp_list_3 for value in sublist])

    # Set comprehensions are just like lists but with {}
    # "s % 2 == 1" is the same as "s % 2" where it only sorts the odds
    my_comp_set = [s for s in range(1, 5) if s % 2]
    print(my_comp_set)

    # Dictionary Comprehension
    # it takes a key and a value
    my_comp_dict = {x: x**2 for x in (2, 4, 6)}
    print(my_comp_dict)

def some_function(a):
    return (a + 5) / 2

if __name__ == '__main__':
    main()


"""
Import 'OktaPasswordHealth.csv' and sort users into internal and external
groups.
"""

import csv

print("\nWhat is your fully qualified domain name?")
DOMAIN = input('> ')

INTERNAL_USERS = []
EXTERNAL_USERS = []

def write_csv(csv_file, lst):
    """Write results to a csv."""
    with open(csv_file, 'w') as out_csvfile:
        writer = csv.writer(out_csvfile)
        writer.writerow(['email'])
        for email in lst:
            writer.writerow([email])

with open('OktaPasswordHealth.csv', 'r') as in_csvfile:
    READER = csv.DictReader(in_csvfile)
    for row in READER:
        user_email = row['Login']
        if user_email.endswith(DOMAIN):
            INTERNAL_USERS.append(user_email)
        else:
            EXTERNAL_USERS.append(user_email)

write_csv('internal_users.csv', INTERNAL_USERS)
write_csv('external_users.csv', EXTERNAL_USERS)
print("'internal_users.csv' and 'external_users.csv' exported successfully\n")


from lightcurvetools import *

# should do a smooth-and-subtract operation on the test lightcurve, show a plot,
# and save the smoothed lc

testfile = 'testdata/lc_xrt_alldata.dat'
testlc = readlightcurve(testfile)
testlc.label = 'original'
testlc.stats()
sigma_HW = 2.355/2
wid = round(20/sigma_HW)
smoothlc = smoothlightcurve(testlc, wid)
smoothlc.label = 'smoothed'
sublc = subtractlightcurve(testlc, smoothlc)
sublc.label = 'subtracted'
plotlightcurve([testlc, smoothlc, sublc])
sublc.write('testwrite.dat')


import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from datetime import datetime
from BaseTest import BaseTest
from Helper import Helper
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from Utilities.config import Utilities
from selenium.webdriver.support.color import Color
import time

@pytest.mark.usefixtures("user")
@pytest.mark.usefixtures("setup")
@pytest.mark.usefixtures("env")
@pytest.mark.migration
@pytest.mark.singapore
@pytest.mark.uk
@pytest.mark.usa
@pytest.mark.sandoz
@pytest.mark.eg
@pytest.mark.global_site
@pytest.mark.de
@pytest.mark.at
@pytest.mark.ph
@pytest.mark.ch
@pytest.mark.ch_fr
@pytest.mark.fr
@pytest.mark.za
@pytest.mark.malaysia
@pytest.mark.es
@pytest.mark.pt
@pytest.mark.tw
@pytest.mark.jp
@pytest.mark.lv
@pytest.mark.it
@pytest.mark.ar
@pytest.mark.fi
@pytest.mark.kr
@pytest.mark.br
@pytest.mark.cn
@pytest.mark.scn
@pytest.mark.hu
@pytest.mark.biome
@pytest.mark.foundation
@pytest.mark.ie
@pytest.mark.gr
@pytest.mark.dk
# @pytest.mark.no
@pytest.mark.ca
# @pytest.mark.se
@pytest.mark.tr
# @pytest.mark.cz
@pytest.mark.ru
# @pytest.mark.rs
@pytest.mark.ro
@pytest.mark.co
@pytest.mark.sk
@pytest.mark.ve
#@pytest.mark.id
@pytest.mark.bd
@pytest.mark.be
@pytest.mark.au
@pytest.mark.pl
class Test_NewsArchive(BaseTest):

    # @pytest.mark.malaysia
    # def test_ARC_2586_NewsArchive_get_newsArchive(self):

    #     self.driver.get(self.env)
    #     self.newsPage.launch_newsArchive(self.env_name)

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_bannerImage(self):

        """
        Checks banner image in news archive page.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        if len(self.driver.find_elements(*self.newsPage.banner_img_css)) > 0:
            assert len(self.basePage.get_elemet_attribute(self.newsPage.banner_img_css, "src")) > 0

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_pattern(self):

        """
        Checks pattern in news archive page.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        assert "patterns" in self.basePage.get_css_property(self.newsPage.pattern_css, "background-image")

    # Already covered in test_breadcrumb
    # def test_ARC_2586_NewsArchive_breadcrumbs(self):

    #     self.driver.get(self.env)
    #     if self.env_name == "france":
        #    self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
        #    self.basePage.press_button(self.newsRoomPage.link_btn_css)
        # else:
        #    self.newsPage.launch_newsArchive(self.env_name)
    #     breadcrumb_items, breadcrumb_first_arrow_element, breadcrumb_second_arrow_element= self.newsPage.breadcrumb_ele()

    #     assert len(breadcrumb_items) == 3
    #     assert ">" in breadcrumb_first_arrow_element
    #     assert ">" in breadcrumb_second_arrow_element

    #     assert "#656565" == self.basePage.get_css_color(self.newsPage.news_archive_last_child_breadcrumb_color_css, "color")

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_search_bar_button(self):

        """
        Checks search bar and button in news archive page.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        search_bar, search_btn = self.newsPage.search_bar_and_btn()
        assert search_bar == True
        assert search_btn == True

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_default_view(self):

        """
        Checks default view - grid view and list.svg icon in news archive page.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        assert "arctic_grid_view" in self.basePage.get_elemet_attribute(self.newsPage.news_page_view_css, "class")
        assert "list.svg" in self.basePage.get_css_property(self.newsPage.view_toggle_icon, "background")

    # This is disabled in all sites now
    # def test_ARC_2586_NewsArchive_calendar_from_to(self):

    #     if self.env_name == "france":
    #        self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
    #        self.basePage.press_button(self.newsRoomPage.link_btn_css)
    #     else:
    #        self.newsPage.launch_newsArchive(self.env_name)
    # #     assert len(self.basePage.get_element_text(self.newsPage.from_date_xpath)) > 0
    #     assert len(self.basePage.get_element_text(self.newsPage.to_date_xpath)) > 0

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_all_topics_grey_color(self):

        """
        Checks All topics is greyed out by default in news archive page.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        all_topics_text_status, hex_code= self.newsPage.all_topics_grey_color()
        assert all_topics_text_status == True
        assert "#f1f1f1" in hex_code

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_pagination_num(self):

        """
        Checks pagination numbers are correctly displayed.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        current_page_num , page_num = self.newsPage.pagination_number()
        assert current_page_num == page_num

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_right_hand_rail(self):

        """
        Checks if there is no right hand rail.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        assert len(self.driver.find_elements(*self.newsPage.right_hand_rail_xpath)) == 0

    # Already covered in test_breadcrumb
    # def test_ARC_2586_NewsArchive_first_second_level_breadcrumbs(self):

    #     self.driver.get(self.env)
    #     if self.env_name == "france":
        #    self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
        #    self.basePage.press_button(self.newsRoomPage.link_btn_css)
        # else:
        #    self.newsPage.launch_newsArchive(self.env_name)
    #     breadcumb_anchor_url_list, breadcumb_anchor_current_url_list = self.newsPage.check_all_breadcrumb_url()
    #     for breadcumb_anchor_url, breadcumb_anchor_current_url in zip(breadcumb_anchor_url_list, breadcumb_anchor_current_url_list):
    #         assert breadcumb_anchor_url in breadcumb_anchor_current_url

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_pagination(self):

        """
        Checks pagination is working as expected or not.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        if len(self.driver.find_elements(self.newsPage.pagination_heading_xpath[0], self.newsPage.pagination_heading_xpath[1])) > 0:
            num_content_page,pagination_heading, page_content_list = self.newsPage.pagination_validation()
            if num_content_page == 12 and pagination_heading > 0 :
                page_count_len = len(page_content_list)
                while page_count_len > 0:
                    assert len(page_content_list) > 0
                    page_count_len = page_count_len - 1

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_menuTabs_viewEmpty(self):

        """
        Checks menu tabs are getting greyed out or not and if under any menu tab, no content is there,
        It should display No Result Found.
        """

        empty_list = []
        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        hex_color_list, empty_list = self.newsPage.grey_menu_verify()

        hex_color_list_len = len(hex_color_list)

        while hex_color_list_len > 0:

            assert "#f1f1f1" in hex_color_list[hex_color_list_len-1]
            hex_color_list_len = hex_color_list_len - 1

    # def test_ARC_2586_NewsArchive_viewEmpty(self):

    #     self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        empty_list_len = len(empty_list)
        if empty_list_len > 0:
            if "view-empty" in empty_list[empty_list_len-1]:
                assert "view-empty" in empty_list[empty_list_len-1]
                empty_list_len = empty_list_len - 1

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_listview(self):

        """
        Checks the following :-
        1. list.svg icon.
        2. list view button.
        3. Default view.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        list_icon,list_view_btn,grid_view  = self.newsPage.list_view()

        assert "list.svg" in list_icon
        assert list_view_btn == True
        assert "arctic_grid_view" in grid_view

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_gridView(self):

        """
        Checks the following :-
        1. grid.svg icon.
        2. grid view button.
        3. view is in list view.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        grid_icon,grid_view_btn,list_view  = self.newsPage.grid_view()

        assert "grid.svg" in grid_icon
        assert grid_view_btn == True
        assert "arctic_list_view" in list_view

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_randomText_search_url(self):

         """
         Checks the searched text is coming in the url.
         """

         self.driver.get(self.env)
         if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
         else:
           self.newsPage.launch_newsArchive(self.env_name)
         searched_keyword = self.newsPage.verify_search_result()
         current_url = self.driver.current_url
         assert searched_keyword in current_url

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_randomText_search_keyword(self):

        """
        Checks searched keyword is coming in the text box while changing the tabs.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        searched_keyword_list = self.newsPage.verify_searchText_with_Tabs()
        for search_keyword in searched_keyword_list:
            assert search_keyword == self.newsPage.test_data

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_randomText_greyMenu_verify(self):

        """
        After searching some keyword, It checks tabs are getting greyed out or not.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        hex_color_list = self.newsPage.grey_menu_verify_with_Tabs()
        for hex_color in hex_color_list:
            assert "#f1f1f1" == hex_color

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_randomText_menuTab_url(self):

         """
         Checks menu tab name is coming in the url.
         """

         self.driver.get(self.env)
         if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
         else:
           self.newsPage.launch_newsArchive(self.env_name)
         tab_href_list, selected_tab_url_list = self.newsPage.verify_menuTab_url()
         for tab_href, selected_tab_url in zip(tab_href_list, selected_tab_url_list):
            assert tab_href in selected_tab_url

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_randomText_searchKeyword_url(self):

        """
        Checks searched keyword is coming in the url while changing tabs.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        searched_keyword,selected_tab_url_list = self.newsPage.verify_searchText_with_url()
        for url in selected_tab_url_list:
            assert searched_keyword in url

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_pagination_front_arrow_back_arrow(self):

        """
        Checks front and back pagination arrow is working.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        if len(self.driver.find_elements(self.newsPage.pagination_heading_xpath[0], self.newsPage.pagination_heading_xpath[1])) > 0:
            num_content_page,pagination_heading,page_one_contents, page_zero_contents = self.newsPage.pagination_front_arrow_back_arrow_validation()
            if num_content_page == 12 and pagination_heading > 0 :
                assert len(page_one_contents) > 0
                assert len(page_zero_contents) > 0

   #  @pytest.mark.malaysia
   #  def test_ARC_2586_NewsArchive_key_release_language_tab(self):

   #      """
   #      Checks language dropdown is coming under key release dropdown.
   #      """

   #      self.driver.get(self.env)
   #      if self.env_name == "france":
   #         self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
   #         self.basePage.press_button(self.newsRoomPage.link_btn_css)
   #      else:
   #         self.newsPage.launch_newsArchive(self.env_name)
   #      if self.env_name == "global":
   #          language_tab_txt = self.newsPage.key_releases(self.env_name)
   #          assert "Language" in language_tab_txt

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_media_release_language_tab(self):

        """
        Checks language dropdown is coming under media release dropdown and dates are coming in descending order.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        desc_sort = self.newsPage.media_release(self.env_name)
        assert desc_sort == True
      #   if self.env_name == "global":
      #       assert "Language" in language_tab_txt

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_randomText_verification(self):

        """
        Checks after searching a keyword, the keyword is coming in the search box or not and all topics is getting greyed out or not.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        searched_keyword = self.newsPage.verify_search_result()
        assert searched_keyword == self.newsPage.test_data
        all_topics_text_status, hex_code = self.newsPage.all_topics_grey_color()
        assert all_topics_text_status == True
        assert "#f1f1f1" in hex_code

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_content_validation(self):

        """
        Checks if content is there in newsw archive page.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        contents = self.basePage.get_elements(self.newsPage.content_pages_css)
        assert len(contents) > 0

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_search_results(self):

        """
        Checks searched input is coming in the searched result or not.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        content_title = self.newsPage.search_results()
        for title in content_title:
            if self.newsPage.test_data_novartis in title:
                assert self.newsPage.test_data_novartis in title
                break

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_verify_filters(self):

        """
        Checks Filters are working or not.
        """

        media_release_list = ['key release', 'media release']
        featured_news_list = ['pulse update', 'statement','featured news']
        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        menu_tab_list , tab_label_list = self.newsPage.verify_filters()

        for filter_name,tab_label in zip(menu_tab_list , tab_label_list):
            if filter_name == "media releases" and self.env_name == 'global':
                for tab in tab_label:
                    assert tab in media_release_list
            elif filter_name == "key releases" and self.env_name == 'global':
                for tab in tab_label:
                    assert tab in media_release_list
            elif filter_name == "featured news" and self.env_name == 'global':
                for tab in tab_label:
                    assert tab  in featured_news_list
            elif filter_name == "statements" and self.env_name == 'global':
                for tab in tab_label:
                    assert tab  in featured_news_list
            elif filter_name == "pulse updates" and self.env_name == 'global':
                for tab in tab_label:
                    assert tab  in featured_news_list
            elif filter_name == "statement" and self.env_name == 'biome':
                for tab in tab_label:
                    assert tab  in featured_news_list
            elif filter_name == "statements" and self.env_name == 'usa':
                for tab in tab_label:
                    assert tab  in featured_news_list
            elif filter_name == "statement" and self.env_name == 'foundation':
                for tab in tab_label:
                    assert tab  in featured_news_list
            else :
                for label in tab_label :
                    assert label in filter_name

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_banner_title(self):

        """
        Checks if banner title is displaying.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        if self.env_name == "global":
            assert self.basePage.is_displayed(self.newsPage.banner_text_css) == True

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_key_release_text(self):

        """
        Checks key release text is there above search bar.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        if self.env_name == "global":
            assert self.basePage.is_displayed(self.newsPage.key_releases_text_xpath) == True
            assert "Key Releases" in self.basePage.get_element_text(self.newsPage.key_releases_text_xpath)

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_menu_ellipse(self):

        """
        Checks ellipse is displayed.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        if self.env_name == "global":
            visible_element = self.driver.find_elements(*self.newsPage.visible_element_xpath)
            if len(visible_element) == 7 :
                assert self.basePage.is_displayed(self.newsPage.ellipses_xpath) == True

    @pytest.mark.malaysia
    def test_ARC_2586_NewsArchive_ellipses_validation(self):

        """
        Checks any element is there inside ellipse.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        if self.env_name == "global":
            if self.basePage.is_displayed(self.newsPage.ellipses_xpath):
                self.basePage.press_button(self.newsPage.ellipses_xpath)
                elements =  self.driver.find_elements(*self.newsPage.non_visible_ellipses_xpath)
                assert len(elements) > 0

    @pytest.mark.malaysia
    def  test_ARC_2586_NewsArchive_ellipses_element_greyed_out(self):

        """
        Checks while clicking any element in ellipse, that element should greyed out.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)
        if self.env_name == "global":
             if self.basePage.is_displayed(self.newsPage.ellipses_xpath):
                self.basePage.press_button(self.newsPage.ellipses_xpath)
                non_visible_element_text = self.basePage.get_element_text(self.newsPage.non_visible_ellipses_xpath)
                self.basePage.press_button(self.newsPage.non_visible_ellipses_xpath)
                length = len(self.driver.find_elements(*self.newsPage.visible_element_xpath))
                element = self.driver.find_element(By.CSS_SELECTOR,f'ul#block-newsarchivenavigation>li:nth-child({length}) > a')
                value_of_css = element.value_of_css_property('background-color')
                hex = Color.from_string(value_of_css).hex
                assert '#f1f1f1' == hex
                assert non_visible_element_text == element.text

    def test_ARC_2586_NewsArchive_grey_bg_only_one_tab(self):

        """
        Checks only tab is getting greyed out at a time.
        """

        self.driver.get(self.env)
        if self.env_name == "france":
           self.homePage.mega_menu_landing_page(self.env_name,self.homePage.mega_menu_news_xpath,'news')
           self.basePage.press_button(self.newsRoomPage.link_btn_css)
        else:
           self.newsPage.launch_newsArchive(self.env_name)

        first_tab_color, second_tab_color = self.newsPage.menu_tab_one_grey_bg()
        assert "#000000" == first_tab_color
        assert "#f1f1f1" == second_tab_color


from tkinter import *
import time
import threading
from tkinter.ttk import *

def start_download():
    GB = 100
    download = 0
    speed = 1
    while download < GB:
        time.sleep(0.05)
        download += speed
        percent.set(str(int(download/GB*100)) + "%")
        text.set(str(download) + "/" + str(GB) + " GB completed")
        bar['value'] = (download/GB)*100
        window.update_idletasks()

def download():
    t = threading.Thread(target=start_download)
    t.start()

window = Tk()

percent = StringVar()
text = StringVar()

bar = Progressbar(window, orient=HORIZONTAL, length=300)
bar.pack(pady=10)

percentLabel = Label(window, textvariable=percent).pack()
taskLabel = Label(window, textvariable=text).pack()

button = Button(window, text="Download", command=download).pack()

window.mainloop()


#! /usr/bin/python

# import sys
import os
import time

if __name__ == '__main__':

    numsOfProducers = [ 5]
    numsOfConsumers = [ 5]

    Ns = [5, 50, 100]

    for prNum, conNum in zip(numsOfProducers, numsOfConsumers):

        for N in Ns:

            print("producers: ", prNum, " consumers: ", conNum, " N: ", N)

            if os.fork() == 0:
                os.execl("./wrapper","wrapper" ,str(prNum), str(conNum), str(N) )
            else:
                os.wait()

            # verifySolution(prNum)

            with open("consumerFile.txt", "r") as conF:
                consumerLines = conF.readlines()

                for conLine in consumerLines:
                    print(conLine, end = "")

            time.sleep(0.5)


from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.db.models.signals import post_save
from django.conf import settings

class User(AbstractUser):
	is_teacher = models.BooleanField(default = False)
	is_student = models.BooleanField(default = False)

	def __Str__(self):
		return self.username

#class Teacher(models.Model):
#	user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True)
#
#class Student(modesl.Model):
#	user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True)

class Doubt(models.Model):
	questions = models.TextField(max_length = 200)
	picture = models.ImageField(blank = True, null = True, upload_to='images')
	student = models.ForeignKey(User, related_name = 'student',  on_delete = models.CASCADE)
	teacher = models.ForeignKey(User, related_name = 'teacher',  on_delete = models.CASCADE)

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)


hx711_reference_unit = 226
load_threshold = 1000 # g
loop_interval = 0.1
camera_device = "/dev/video0"
photo_format = "width=1920,height=1080"
photo_count = 4
reset_timeout = 300 # sec
tmpdir = "/tmp"
debug = True

# remote
bot_token="BOT_TOKEN"
channel_id=CHANNEL_ID


# Faça um programa que lê um número inteiro n. E verifique se n é um número par, se não for pedir para inserir outro número até que seja par. Use while.

#usando um laço infinito para o programa continuar executando
while True:

    n = int(input("Digite um número: "))  #para While com true, usar o print dentro do laço

    if n % 2 != 0:                        #Se o numero digitado seja impar o programa continua executando (True)
        print("Digite um numero par")

    else:                                 #se o número for par entra o break e o programa para a execução
        break


import numpy as np

# some useful constants:
edges = (N,S,E,W) = list(range(4))

def lonlat2cart( lons, lats, rad=1.):
    """Convert longitude/latitude to cartesian coordinates.

    Args:
        lons (numpy 2-d array): longitude ("x") values (decimal degrees).
        lats (numpy 2-d array): latitude ("y") values (decimal degrees).
        rad (float): nominal sphere radius (default=1. returns cartesian
            coordinates on the unit sphere).

    Returns:
        cart (numpy 3-d array): cartesian coordinates on the sphere.  Rows and
            columns are arranged according to the input lons/lats arrays, while
            along the third axis, the 0, 1, and 2 indices correspond to the x, y
            and z components, respectively.

    Raises:
        ValueError: If input lons and lats matrix dimensions are not equal.

    """

    if lons.ndim!=2 or lats.ndim!=2 or lons.shape!=lats.shape:
        raise ValueError('lons and lats must be two-dimensional matrices of equal size.')

    dims = list(lons.shape)
    dims.append(3)
    cart = np.zeros(dims)
    cart[:,:,0] = np.cos(np.radians(lons))*np.cos(np.radians(lats)) # x
    cart[:,:,1] = np.sin(np.radians(lons))*np.cos(np.radians(lats)) # y
    cart[:,:,2] = np.sin(np.radians(lats))                          # z

    return cart

def nearest(lon,lat,lons,lats,geod):
    """Determine indices of, and distance to, nearest lon/lat point.

    Args:
        lon (float): Longitude of search origin
        lat (float): Latitude of search origin
        lons (numpy 2-d array): Matrix of longitude values used in the nearest
            neighbour search.
        lats (numpy 2-d array): Matrix of latitude values used in the nearest
            neighbour search.
        geod (pyproj.Geod object): Geod to be used as basis for distance
            calculations.

    Returns:
        i (int): Zeros-based row index of nearest neighbour.
        j (int): Zeros-based colum index of nearest neighbour.
        dist (float): Great circle distance from (lon,lat) to
            (lons(i,j), lats(i,j))

    Raises:
        ValueError: If input lons and lats matrix dimensions are not
            equal.
    """

    if lons.ndim!=2 or lats.ndim!=2 or lons.shape!=lats.shape:
        raise ValueError('lons and lats must be two-dimensional matrices of equal size.')

    i,j,dist = -1,-1,1.e10

    it = np.nditer(lons,flags=['multi_index'])
    while not it.finished:
        (fwd_az,back_az,distance) = geod.inv(
            lon,lat,
            lons[it.multi_index[0],it.multi_index[1]],
            lats[it.multi_index[0],it.multi_index[1]])
        if distance<dist:
            i,j,dist = it.multi_index[0],it.multi_index[1],distance
        it.iternext()

    return i,j,dist

def squad_uarea( cart):
    """Compute quadrilateral surface areas for cartesian array of corner points
    on the unit sphere.

    Args:
        cart (numpy array): 3-d array (m x n x 3) of cartesian x,y,z corner
            points on the unit sphere (for every (i,j), (x,y,z) = (i,j,0),
            (i,j,1), (i,j,2)).

    Returns:
        areas (numpy array): 2-d array (n-1 x m-1) of cell areas.

    Note:
        One of many possible approaches, the algorithm implemented here is based
        on Girard's spherical excess formula, with direct calculation of angles
        using the spherical law of cosines.  Note that, due to numerical
        round-off, its results can be inaccurate for small angles/areas (edge
        lengths less than roughly 5km on the scaled sphere).  In such cases,
        pquad_uarea is recommended.

    """

    # only because some geometries are poorly conditioned:
    import warnings
    warnings.filterwarnings("ignore")

    area = np.zeros((np.size(cart,0)-1,np.size(cart,1)-1))

    for x_idx in np.arange(np.size(cart,0)-1):
        for y_idx in np.arange(np.size(cart,1)-1):

            # quadrilateral corners in counterclockwise direction:
            ptA = cart[x_idx  ,y_idx  ,:]
            ptB = cart[x_idx+1,y_idx  ,:]
            ptC = cart[x_idx+1,y_idx+1,:]
            ptD = cart[x_idx  ,y_idx+1,:]

            # interior angles of first subtriangle:
            at,bt,ct = ptA, ptB, ptC
            ca,cb,cc = np.dot(bt,ct), np.dot(at,ct), np.dot(at,bt)
            sa,sb,sc = np.sin(np.arccos(ca)), np.sin(np.arccos(cb)), np.sin(np.arccos(cc))
            A1 = np.arccos((ca-cb*cc)/(sb*sc))
            B1 = np.arccos((cb-ca*cc)/(sa*sc))
            C1 = np.arccos((cc-ca*cb)/(sa*sb))

            # interior angles of second subtriangle:
            at,bt,ct = ptA, ptC, ptD
            ca,cb,cc = np.dot(bt,ct), np.dot(at,ct), np.dot(at,bt)
            sa,sb,sc = np.sin(np.arccos(ca)), np.sin(np.arccos(cb)), np.sin(np.arccos(cc))
            A2 = np.arccos((ca-cb*cc)/(sb*sc))
            B2 = np.arccos((cb-ca*cc)/(sa*sc))
            C2 = np.arccos((cc-ca*cb)/(sa*sb))

            # area:
            area[x_idx,y_idx] = A1+B1+C1 + A2+B2+C2 - 2*np.pi

    return area

def pquad_uarea( cart):
    """ Compute planar quadrilateral (faceted) areas for cartesian array of
    corner points on the unit sphere.

    Args:
        cart (numpy array): 3-d array (m x n x 3) of cartesian x,y,z corner
            points on the unit sphere (for every (i,j), (x,y,z) = (i,j,0),
            (i,j,1), (i,j,2)).

    Returns:
        areas (numpy array): 2-d array (n-1 x m-1) of cell areas.

    Note:
        The algorithm implemented here computes areas using edge vector cross
        products and is recommented for small angles/areas (edge lengths less
        than roughly 5km on the scaled sphere).  If areas are larger,
        squad_uarea is recommended.

    """

    area = np.zeros((np.size(cart,0)-1,np.size(cart,1)-1))

    for x_idx in np.arange(np.size(cart,0)-1):
        for y_idx in np.arange(np.size(cart,1)-1):

            # quadrilateral corners in counterclockwise direction:
            ptA = cart[x_idx  ,y_idx  ,:]
            ptB = cart[x_idx+1,y_idx  ,:]
            ptC = cart[x_idx+1,y_idx+1,:]
            ptD = cart[x_idx  ,y_idx+1,:]

            # edge vectors:
            ab = ptB-ptA
            ac = ptC-ptA
            ad = ptD-ptA

            area[x_idx,y_idx] = 0.5 * np.linalg.norm(np.cross(ab,ac)+np.cross(ac,ad))

    return area


# 给你 n 个非负整数 a1，a2，...，an，每个数代表坐标中的一个点 (i, ai) 。
# 在坐标内画 n 条垂直线，垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。
# 找出其中的两条线，使得它们与 x 轴共同构成的容器可以容纳最多的水。

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """

        l = 0
        r = len(height) - 1
        maxarea = 0

        while (l < r):
            maxarea = max(maxarea, (r - l) * min(height[l], height[r]))

            if height[r] < height[l]:
                r = r - 1
            else:
                l = l + 1

        return maxarea

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

a = Solution()
print(a.maxArea(height))


# import statements

import nltk
import sys
import pandas as pd
import re
from nltk import pos_tag
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.tokenize import word_tokenize, sent_tokenize
from sqlalchemy import create_engine

# download necessary NLTK data
nltk.download(['punkt', 'wordnet'])
nltk.download('stopwords')

def load_data(messages_filepath, categories_filepath):
  """
  Load the data containing the messages and the
  categories, and merge on the common column 'id'
  Returns a single pandas Dataframe.

  Keyword arguments:
  messages_filepath -- filepath (including file name)
                       of the file containing the messages
  categories_filepath -- filepath (including file name)
                         of the file containing the message
                         categories
  """
  messages = pd.read_csv(messages_filepath, encoding='UTF-8')
  categories = pd.read_csv(categories_filepath, encoding='UTF-8')
  return messages.merge(categories, on=['id'])

def clean_data(df):
  """
  Parse the single 'categories' column into the 36 distinct
  message category columns, name the resulting columns, and
  clean the values, removing the category name from the cells
  and leaving only the numeric categorical value.

  Remove true duplicate rows.

  Returns a cleaned Dataframe.

  Keyword argument:
  df -- Dataframe requiring cleaning.
  """
  categories_new = df['categories'].str.split(pat=';', expand=True)
  row = categories_new.iloc[0,:]
  category_colnames = list(row.apply(lambda x: x[:-2]))
  categories_new.columns = category_colnames
  for column in categories_new:
    # set each value to be the last character of the string
    categories_new[column] = categories_new[column].str.slice(-1)

    # convert column from string to numeric
    categories_new[column] = categories_new[column].astype(int)

  df.drop(columns=['categories'], inplace=True)

  df = pd.concat([df, categories_new], axis=1)

  # drop duplicates
  df.drop_duplicates(inplace=True)
  return df

def save_data(df, database_filename):
  """
  Save cleaned Dataframe to a SQL Database table.

  Keyword arguments:
  df -- Cleaned Dataframe for export
  database_filename -- name of the database in which
                       table will be saved
  """
  engine = create_engine('sqlite:///' + database_filename)
  df.to_sql('messages_and_categories', engine, index=False)

def main():
  """
  Executes following functions:

  1) load_data(messages_filepath, categories_filepath)
  2) clean_data(df)
  3) save_data(df, database_filename)
  """
  if len(sys.argv) == 4:

      messages_filepath, categories_filepath, database_filepath = sys.argv[1:]

      print('Loading data...\n    MESSAGES: {}\n    CATEGORIES: {}'
            .format(messages_filepath, categories_filepath))
      df = load_data(messages_filepath, categories_filepath)

      print('Cleaning data...')
      df = clean_data(df)

      print('Saving data...\n    DATABASE: {}'.format(database_filepath))
      save_data(df, database_filepath)

      print('Cleaned data saved to database!')

  else:
      print('Please provide the filepaths of the messages and categories '\
            'datasets as the first and second argument respectively, as '\
            'well as the filepath of the database to save the cleaned data '\
            'to as the third argument. \n\nExample: python process_data.py '\
            'disaster_messages.csv disaster_categories.csv '\
            'DisasterResponse.db')

if __name__ == '__main__':
    main()


import os
import torch
import wandb
import argparse
import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedKFold
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, roc_auc_score, average_precision_score, balanced_accuracy_score

os.environ["CUDA_DEVICE_ORDER"] = 'PCI_BUS_ID'
os.environ["CUDA_VISIBLE_DEVICES"] = '0'

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--layer_1', help='layer 1 size', type=int, default=50, required=True)
    parser.add_argument(
        '--layer_2', help='layer 2 size', type=int, default=50, required=True)
    parser.add_argument(
        '--layer_3', help='layer 3 size', type=int, default=50, required=True)
    parser.add_argument(
        '--lr', help='Learning Rate', type=float, default=0.01, required=True)
    parser.add_argument(
        '--weight_decay', help='Weight Decay', type=float, default=0.9, required=True)
    parser.add_argument(
        '--momentum', help='Weight Decay', type=float, default=0.9, required=True)
    parser.add_argument(
        '--no_epoch', help='Number of Epochs', type=int, default=1000, required=True)
    args = parser.parse_args()
    return args

class Model(torch.nn.Module):
    def __init__(self, layer_1, layer_2, layer_3):
        super(Model, self).__init__()
        self.lin1 = torch.nn.Linear(12, layer_1)
        self.lin2 = torch.nn.Linear(layer_1, layer_2)
        self.lin3 = torch.nn.Linear(layer_2, layer_3)
        self.lin4 = torch.nn.Linear(layer_3, 1)
        self.selu = torch.nn.SELU()

    def forward(self, x):
        x = self.selu(self.lin1(x))
        x = self.selu(self.lin2(x))
        x = self.selu(self.lin3(x))
        x = self.lin4(x)
        return x

def load_data():
    cd = os.getcwd()
    x_eicu = pd.read_csv(cd+'../data/x_eicu.csv')
    y_eicu = pd.read_csv(cd+'../data/y_eicu.csv')
    mimic = pd.read_csv(cd+'../data/mimic.csv')
    assert np.all(x_eicu['patientunitstayid'].to_numpy() == y_eicu['patientunitstayid'].to_numpy())
    feature_list = ['lactate', 'oobventday1', 'eyes', 'motor', 'verbal', 'albumin_x',
                    'age', 'creatinine_x', 'BUN', 'PT - INR', 'WBC x 1000', 'meanbp']
    feature_list_mimic = ['Lactate', 'firstdayvent', 'gcseyes', 'gcsmotor', 'gcsverbal', 'Albumin',
                          'Age', 'Creatinine', 'BUN', 'INR', 'WBC', 'MAP']
    x_eicu = x_eicu[feature_list].to_numpy()
    y_eicu = y_eicu['actualicumortality'].to_numpy()
    x_mimic = mimic[feature_list_mimic].to_numpy()
    y_mimic = mimic['Mortality'].to_numpy()
    x = np.vstack((x_eicu, x_mimic))
    y = np.hstack((y_eicu, y_mimic))
    return x, y

def main():
    wandb.init(project='mortality-tool-newfeats')
    args = parse_args()
    x, y = load_data()
    kfold = StratifiedKFold(n_splits=10)
    logits_all = []
    labels_all = []
    counter = 1
    for train_index, test_index in kfold.split(x, y):
        x_train, y_train = x[train_index], y[train_index]
        x_test, y_test = x[test_index], y[test_index]
        imputer = IterativeImputer()
        scaler = StandardScaler()
        x_train = scaler.fit_transform(imputer.fit_transform(x_train))
        x_test = scaler.transform(imputer.transform(x_test))
        x_train, y_train = torch.from_numpy(x_train).float().to('cuda:0'), torch.from_numpy(y_train).float().to('cuda:0')
        model = Model(args.layer_1, args.layer_2, args.layer_3)
        criterion = torch.nn.BCEWithLogitsLoss(pos_weight=torch.tensor([14.80], device='cuda:0'))
        optimizer = torch.optim.SGD(model.parameters(), lr=args.lr, weight_decay=args.weight_decay, momentum=args.momentum, nesterov=True)
        model.train()
        model.to('cuda:0')
        for epoch in range(args.no_epoch):
            optimizer.zero_grad()
            outputs = model.forward(x_train)
            loss = criterion(outputs, y_train.view(-1, 1))
            loss.backward()
            optimizer.step()
        model.eval()
        outputs = model.forward(torch.from_numpy(x_test).float().to('cuda:0'))
        logits = torch.sigmoid(outputs).detach().cpu().numpy()
        logits_all.append(logits.reshape(-1))
        labels_all.append(y_test)
        print('Iter {}/10 done'.format(counter))
        counter += 1
    logits_all = np.hstack(logits_all)
    labels_all = np.hstack(labels_all)
    tn, fp, fn, tp = confusion_matrix(labels_all, np.round(logits_all)).ravel()
    accuracy = (tp + tn) / (tp + tn + fp + fn)
    precision = tp / (tp + fp)
    sensitivity = tp / (tp + fn)
    specificity = tn / (tn + fp)
    roc_auc = roc_auc_score(labels_all, logits_all)
    prc_auc = average_precision_score(labels_all, logits_all)
    balanced_acc = balanced_accuracy_score(labels_all, np.round(logits_all))
    pos_likelihood_ratio = sensitivity / (1 - specificity)
    neg_likelihood_ratio = (1 - sensitivity) / specificity
    class_names = ['ALIVE', 'EXPIRED']
    wandb.log({'accuracy': accuracy, 'precision': precision, 'sensitivity': sensitivity, 'specificitiy': specificity,
               'roc_auc': roc_auc, 'prc_auc': prc_auc, 'balanced_accuracy': balanced_acc,
               'neg_likelihood_ratio': neg_likelihood_ratio, 'pos_likelihood_ratio': pos_likelihood_ratio})

if __name__ == '__main__':
    main()


import sqlite3
import sys

from PyQt6.QtWidgets import QApplication, QLabel, QWidget, QGridLayout, \
    QLineEdit, QPushButton, QMainWindow, QTableWidget, QTableWidgetItem, QDialog, \
    QVBoxLayout, QComboBox, QToolBar, QStatusBar, QMessageBox

from PyQt6.QtGui import QAction, QIcon

from PyQt6.QtCore import Qt

# Database connection class
class DatabaseConnection:
    def __init__(self, database_file="database.db"):
        self.database_file = database_file

    def connect(self):
        # Establish connection to database and create cursor
        connection = sqlite3.connect(self.database_file)
        cursor = connection.cursor()

        # return connection and cursor, destructure variables in creation of instances
        return connection, cursor

    def close_connection(self, connection, cursor):

        # Commit changes to db and close connections, refresh app table
        return connection.commit(), cursor.close(), connection.close(), student_management_sys.load_data()

# App Main Window class
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Student Management System")
        self.setMinimumSize(600, 400)

        # Menu items
        file_menu_item = self.menuBar().addMenu("&File")
        utility_menu_item = self.menuBar().addMenu("&Utility")
        help_menu_item = self.menuBar().addMenu("&Help")

        # Add student menu item and action with toolbar icon binding to action
        add_student_action = QAction(QIcon("icons/add.png"), "Add Student", self)
        add_student_action.triggered.connect(self.insert)
        file_menu_item.addAction(add_student_action)

        # About menu item and action
        about_action = QAction("About", self)
        help_menu_item.addAction(about_action)
        about_action.triggered.connect(self.about)

        # SEARCH item and action with toolbar icon binding to action
        search_action = QAction(QIcon("icons/search.png"), "Search", self)
        search_action.triggered.connect(self.search)
        utility_menu_item.addAction(search_action)

        # Toolbar widget and elements, toolbar is also movable
        toolbar = QToolBar()
        toolbar.setMovable(True)
        self.addToolBar(toolbar)
        toolbar.addAction(add_student_action)
        toolbar.addAction(search_action)

        # Statusbar widget and elements
        self.statusbar = QStatusBar()
        self.setStatusBar(self.statusbar)

        # QTableWidget attributes
        self.table = QTableWidget()
        self.table.setColumnCount(4)
        self.table.setHorizontalHeaderLabels(("Id", "Name", "Course", "Mobile"))

        # To hide default vertical numbers not associated with SQL database
        self.table.verticalHeader().setVisible(False)

        # Detect if cell is clicked
        self.table.cellClicked.connect(self.cell_clicked)

        # Set a center layout widget to QTableWidget instance
        self.setCentralWidget(self.table)

    # Cell clicked method
    def cell_clicked(self):
        # Edit button
        edit_button = QPushButton("Edit Record")
        edit_button.clicked.connect(self.edit)

        # Delete button
        delete_button = QPushButton("Delete Record")
        delete_button.clicked.connect(self.delete)

        # Find children of statusbar widgets and remove appending children
        # Prevent duplications of widgets for every cell click
        children = self.findChildren(QPushButton)
        if children:
            for child in children:
                self.statusbar.removeWidget(child)

        # Add widgets after cell is clicked
        self.statusbar.addWidget(edit_button)
        self.statusbar.addWidget(delete_button)

    # Load SQL Database data in PyQt
    def load_data(self):
        # Connect SQL database
        connection, cursor = DatabaseConnection().connect()
        results = connection.execute("SELECT * FROM students")

        # Initialize table number to 0
        self.table.setRowCount(0)

        # Iterate through row numbers
        for row_number, row_data in enumerate(results):

            # Every index insert a row cell with a row number
            self.table.insertRow(row_number)

            # Iterate through column numbers
            for column_number, column_data in enumerate(row_data):

                # Every index of a row number and column number add column data
                self.table.setItem(row_number, column_number, QTableWidgetItem(str(column_data)))

        # Close the database connection
        connection.close()

    # Insert new data method call
    def insert(self):
        dialog = InsertDialog()
        dialog.exec()

    def search(self):
        search_dialog = SearchDialog()
        search_dialog.exec()

    def edit(self):
        edit_dialog = EditDialog()
        edit_dialog.exec()

    def delete(self):
        delete_dialog = DeleteDialog()
        delete_dialog.exec()

    def about(self):
        about_dialog = AboutDialog()
        about_dialog.exec()

# Dialog Attributes for Insert
class InsertDialog(QDialog):
    def __init__(self):
        super().__init__()

        # Set Window Attributes
        self.setWindowTitle("Insert Student Data")
        self.setFixedWidth(300)
        self.setFixedHeight(300)

        layout = QVBoxLayout()

        # Add Student Name widget
        self.student_name = QLineEdit()
        self.student_name.setPlaceholderText("Name")
        layout.addWidget(self.student_name)

        # Add Course ComboBox widget
        self.course_name = QComboBox()
        courses = ["Biology", "Math", "Astronomy", "Physics"]
        self.course_name.addItems(courses)
        layout.addWidget(self.course_name)

        # Add Mobile Number widget
        self.mobile_number = QLineEdit()
        self.mobile_number.setPlaceholderText("Mobile Number")
        layout.addWidget(self.mobile_number)

        # Submit button
        submit_btn = QPushButton("Register")
        submit_btn.clicked.connect(self.add_student)
        layout.addWidget(submit_btn)

        self.setLayout(layout)

    # Add Student method
    def add_student(self):
        # Reference to field values stored in variables
        name = self.student_name.text()
        course = self.course_name.itemText(self.course_name.currentIndex())
        mobile = self.mobile_number.text()

        # Connect to database and create cursor
        connection, cursor = DatabaseConnection().connect()

        # Use the cursor to destructure and INSERT reference variables into related db columns
        cursor.execute("INSERT INTO students (name, course, mobile) VALUES (?, ?, ?)",
                       (name, course, mobile))

        # Commit changes, Close connection to database and cursor
        DatabaseConnection().close_connection(connection, cursor)

        # Close window after entry
        self.close()

# Dialog Attributes for Search
class SearchDialog(QDialog):
    def __init__(self):
        super().__init__()

        # Set Window Attributes
        self.setWindowTitle("Search Student")
        self.setFixedWidth(300)
        self.setFixedHeight(300)

        search_layout = QVBoxLayout()

        # Search Student Name widget
        self.search_student_name = QLineEdit()
        self.search_student_name.setPlaceholderText("Name")
        search_layout.addWidget(self.search_student_name)

        # Search button
        search_btn = QPushButton("Search")
        search_btn.clicked.connect(self.search_student)
        search_layout.addWidget(search_btn)

        self.setLayout(search_layout)

    # Search Student method
    def search_student(self):
        # Reference to field values stored in variables
        name = self.search_student_name.text()

        # Connect to database and create cursor
        connection, cursor = DatabaseConnection().connect()

        # Select all fields that contained query of student name in database
        result = cursor.execute("SELECT * FROM students WHERE name = ?", (name, ))
        rows = list(result)
        print(rows)

        # Select all fields in Main window table and find match of student name
        items = student_management_sys.table.findItems(name, Qt.MatchFlag.MatchFixedString)

        # Highlight all names that match query and print item row to console
        for item in items:
            print(item)
            student_management_sys.table.item(item.row(), 1).setSelected(True)

        # Close cursor and connection to db
        cursor.close()
        connection.close()

        # Close dialog after search
        self.close()

# Dialog Attributes for Edit
class EditDialog(QDialog):
    def __init__(self):
        super().__init__()

        # Set Window Attributes
        self.setWindowTitle("Update Student Data")
        self.setFixedWidth(300)
        self.setFixedHeight(300)

        layout = QVBoxLayout()

        # Get table row and column of student to edit
        index = student_management_sys.table.currentRow()

        # Get ID from selected Row
        self.student_id = student_management_sys.table.item(index, 0).text()

        # Get student name
        student_name = student_management_sys.table.item(index, 1).text()

        # Get Course name
        course_name = student_management_sys.table.item(index, 2).text()

        # Get Mobile number
        mobile_number = student_management_sys.table.item(index, 3).text()

        # Add Student Name widget
        self.student_name = QLineEdit(student_name)
        self.student_name.setPlaceholderText("Name")
        layout.addWidget(self.student_name)

        # Add Course ComboBox widget
        self.course_name = QComboBox()
        courses = ["Biology", "Math", "Astronomy", "Physics"]
        self.course_name.addItems(courses)
        self.course_name.setCurrentText(course_name)
        layout.addWidget(self.course_name)

        # Add Mobile Number widget
        self.mobile_number = QLineEdit(mobile_number)
        self.mobile_number.setPlaceholderText("Mobile Number")
        layout.addWidget(self.mobile_number)

        # Submit button
        submit_btn = QPushButton("Update")
        submit_btn.clicked.connect(self.update_student)
        layout.addWidget(submit_btn)

        self.setLayout(layout)

    # Update method
    def update_student(self):
        connection, cursor = DatabaseConnection().connect()

        # Destructure table rows and UPDATE with new values from references in edit fields
        cursor.execute("UPDATE students SET name = ?, course = ?, mobile = ? WHERE id = ?",
                       (self.student_name.text(),
                        self.course_name.itemText(self.course_name.currentIndex()),
                        self.mobile_number.text(), self.student_id))

        # Commit changes, Close connection to database and cursor
        DatabaseConnection().close_connection(connection, cursor)

        # Close dialog after update
        self.close()

# Dialog Attributes for Delete
class DeleteDialog(QDialog):
    def __init__(self):
        super().__init__()

        # Set Window Attributes
        self.setWindowTitle("Delete Student Data")

        layout = QGridLayout()
        confirmation = QLabel("Are you sure you want to delete?")
        yes = QPushButton("Yes")
        no = QPushButton("No")

        layout.addWidget(confirmation, 0, 0, 1, 2)
        layout.addWidget(yes, 1, 0)
        layout.addWidget(no, 1, 1)
        self.setLayout(layout)

        yes.clicked.connect(self.delete_student)
        no.clicked.connect(self.close)

    # Delete Method
    def delete_student(self):
        # Connect to database
        connection, cursor = DatabaseConnection().connect()

        # Get table row and column of student to edit
        index = student_management_sys.table.currentRow()

        # Get ID from selected Row
        student_id = student_management_sys.table.item(index, 0).text()

        # Execute SQL DELETE query using student ID
        cursor.execute("DELETE FROM students WHERE id = ?", (student_id, ))

        # Commit changes, Close connection to database and cursor
        DatabaseConnection().close_connection(connection, cursor)

        # Create a message box to relay deletion was successful
        confirmation_widget = QMessageBox()
        confirmation_widget.setWindowTitle("Success")
        confirmation_widget.setText("The Record Deleted Successfully!")
        confirmation_widget.exec()

        # Close delete dialog window
        self.close()

# About Inheriting from 'QMessageBox' simple child version of a QDialog
class AboutDialog(QMessageBox):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("About")

        # Content for about section
        content = "I built this academic management app as I learned PyQt6 and it's component libraries. " \
                  "I used object oriented architecture to keep my code organized and scalable." \
                  " A SQL database was used store records and 'CRUD' methods were used to managed it's contents."

        # Use set text to content
        self.setText(content)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    student_management_sys = MainWindow()
    student_management_sys.show()
    student_management_sys.load_data()
    sys.exit(app.exec())


def adress_book():
    a = {}
    while True:
        print("Имя - ")
        name = input()
        if name != "q":
            print("Номер - ")
            phone = input()
            if (phone[0] == "+" and phone[2] == "-" and phone[6] == "-"
                    and phone[10] == "-" and phone[13] == "-"):
                if phone[1:].replace("-", "").isdigit():
                    a[name] = phone
        else:
            break
    return a

print(adress_book())


# -*- coding: utf-8 -*-
"""
Created on Wed May  6 15:04:40 2020

@author: Rijk

Scipy signal sos filter toolbox test
"""

import numpy as np
from scipy import signal
import matplotlib.pyplot as plt

plt.close('all')

b, a = signal.butter(4, 100, 'low', analog=True)
w, h = signal.freqs(b, a)

plt.figure()
plt.semilogx(w, 20 * np.log10(abs(h)))

plt.title('Butterworth filter frequency response')
plt.xlabel('Frequency [radians / second]')
plt.ylabel('Amplitude [dB]')
plt.margins(0, 0.1)
plt.grid(which='both', axis='both')
plt.axvline(100, color='green') # cutoff frequency
#plt.show()

t = np.linspace(0, 1, 1000, False)  # 1 second
sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1.plot(t, sig)
ax1.set_title('10 Hz and 20 Hz sinusoids')
ax1.axis([0, 1, -2, 2])

sos = signal.butter(10, 15, 'hp', fs=1000, output='sos')
filtered = signal.sosfilt(sos, sig)

ax2.plot(t, filtered)
ax2.set_title('After 15 Hz high-pass filter')
ax2.axis([0, 1, -2, 2])
ax2.set_xlabel('Time [seconds]')
plt.tight_layout()
plt.show()

# Compare FFT before and after
fft_before  = np.fft.fft(sig)
fft_after   = np.fft.fft(filtered)

sample_time = np.mean(np.diff(t))
f           = np.fft.fftfreq(len(t), sample_time)
half        = int(len(t)/2)
plt.figure()
plt.plot(f[1:half], fft_before[1:half], label='Original')
#plt.plot(f[1:half], fft_after[1:half], label='Filtered')
plt.legend()

## Measurement data filter
#f_axis = 1.12
#nyquist_f = f_axis
#
## Define filter
#lower_f = 0.025
#upper_f = 0.065
#bandpass_f = 2*np.pi * np.array([lower_f, upper_f]) / nyquist_f
#butter_low  = signal.butter(2, lower_f, btype='lowpass', output='sos')
#butter_high  = signal.butter(2, upper_f, btype='lowpass', output='sos')
#
#b, a = signal.butter(2, bandpass_f, btype='bandstop', output='ba')
#w, h = signal.freqz(b, a)
#
#plt.figure()
#plt.plot(w, 20 * np.log10(abs(h)))

Measurements/20200324 WO3196dev9/Hydrogen R_T correction/0324_1904_WO3196dev9_H2ToAir/signal_toolbox_test.py