# SVM
# Feb.28th

import numpy as np
import matplotlib.pyplot as plt
import scipy.io as scio
import cap
from sklearn import svm

# 导入数据
data = scio.loadmat('ex6data3.mat')['X']
label = scio.loadmat('ex6data3.mat')['y'].reshape(-1)
data_val = scio.loadmat('ex6data3.mat')['Xval']
label_val = scio.loadmat('ex6data3.mat')['yval'].reshape(-1)

# 网格搜索：找到最优的超参数C、gamma
para1 = np.array([0.01, 0.03, 0.1, 0.3, 1, 3, 10, 30, 50, 70, 100])
para2 = np.array([0.01, 0.03, 0.1, 0.3, 1, 3, 10, 30, 50, 70, 100])
ac = np.zeros([para1.shape[0], para2.shape[0]])
max_index = [0, 0]
for i in range(para1.shape[0]):
    for j in range(para2.shape[0]):
        clf = svm.SVC(kernel='rbf', C=para1[i], gamma=para2[j])
        clf.fit(data, label)
        pred_val = clf.predict(data_val)
        ac[i, j] = np.mean(pred_val == label_val)
        if ac[i, j] > ac[max_index[0], max_index[1]]:
            max_index = [i, j]

# SVM
clf = svm.SVC(kernel='rbf', C=para1[max_index[0]], gamma=para2[max_index[1]])
clf.fit(data, label)

# 画出决策边界
xx = np.arange(np.min(data[:, 0]), np.max(data[:, 0]), 0.01)
yy = np.arange(np.min(data[:, 1]), np.max(data[:, 1]), 0.01)
xx, yy = np.meshgrid(xx, yy)
zz = clf.predict(np.column_stack((xx.reshape(-1), yy.reshape(-1))))
zz = zz.reshape(xx.shape)
plt.contour(xx, yy, zz)
cap.plot_original_data(np.column_stack((data, label)))  # 原始样本
plt.show()


#!/usr/bin/env python
from flask.sessions import SecureCookieSessionInterface
from itsdangerous import URLSafeTimedSerializer

class SimpleSecureCookieSessionInterface(SecureCookieSessionInterface):
	# Override method
	# Take secret_key instead of an instance of a Flask app
	def get_signing_serializer(self, secret_key):
		if not secret_key:
			return None
		signer_kwargs = dict(
			key_derivation=self.key_derivation,
			digest_method=self.digest_method
		)
		return URLSafeTimedSerializer(secret_key, salt=self.salt,
		                              serializer=self.serializer,
		                              signer_kwargs=signer_kwargs)

def decodeFlaskCookie(secret_key, cookieValue):
	sscsi = SimpleSecureCookieSessionInterface()
	signingSerializer = sscsi.get_signing_serializer(secret_key)
	return signingSerializer.loads(cookieValue)

# Keep in mind that flask uses unicode strings for the
# dictionary keys

def encodeFlaskCookie(secret_key, cookieDict):
	sscsi = SimpleSecureCookieSessionInterface()
	signingSerializer = sscsi.get_signing_serializer(secret_key)
	return signingSerializer.dumps(cookieDict)

if __name__ == '__main__':
    cookie_names = ["snickerdoodle", "chocolate chip", "oatmeal raisin", "gingersnap", "shortbread", "peanut butter", "whoopie pie", "sugar", "molasses", "kiss", "biscotti", "butter", "spritz", "snowball", "drop", "thumbprint", "pinwheel", "wafer", "macaroon", "fortune", "crinkle", "icebox", "gingerbread", "tassie", "lebkuchen", "macaron", "black and white", "white chocolate macadamia"]
    sessionDict = {"very_auth":"snickerdoodle"}
    mySession = "eyJ2ZXJ5X2F1dGgiOiJzbmlja2VyZG9vZGxlIn0.YuEp2A.LxE6hlFkvcrjbBID2f0Z8JKIXMQ"

    for secret in cookie_names:
        try:
            cookie = decodeFlaskCookie(secret, mySession)
            print(cookie)
            secret = secret
            break
        except:
            pass

    adminSession = {"very_auth":"admin"}
    adminCookie = encodeFlaskCookie(secret, adminSession)
    print(adminCookie)


import abc
import inspect
import json
from typing import Any, Dict, List

class AbstractConfig(abc.ABC):

    def properties(self, enums_as_strings: bool = True) -> Dict[str, Any]:
        """
        :param enums_as_strings: whether to convert enum values to strings, default is True
        :return: a dictionary with all public properties of this object, useful for generic tracking with MLflow
        """
        properties = {}
        for name in self.property_names():
            value = getattr(self, name)
            if enums_as_strings and value is not None and hasattr(value, 'name'):
                properties[name] = value.name
            else:
                properties[name] = value
        return properties

    def property_names(self) -> List[str]:
        result: List[str] = []
        for name in dir(self):
            value = getattr(self, name)
            if not name.startswith('_') and not inspect.ismethod(value):
                result.append(name)
        return result

    @staticmethod
    def _read_config_json_file(config_path: str) -> Dict[str, Any]:
        with open(config_path, 'r') as stream:
            config_dict = json.load(stream)
        return config_dict


oferta = [
    { "nazwa" : "ziemniaki", "cena" : 2.0 },
    { "nazwa" : "migdaly", "cena" : 40.00 },
    { "nazwa" : "maka", "cena" : 4.0 },
    { "nazwa" : "ryz", "cena" : 3.5 },
    { "nazwa" : "woda", "cena" : 1.0 },
    { "nazwa" : "cytryny", "cena" : 8.0 },
    { "nazwa" : "wodka", "cena" : 30.0 }
]

# TUTAJ MA SIE WYPISAC OFERTA SKLEPU
print("###### Oferta: ######")
for produkt in oferta:
    print(f"{produkt['nazwa']:10}: {produkt['cena']:5}")
print()

# pytamy "Co chcesz kupic? "
wybor = input("Co chcesz kupic? ")

# sprawdzenie, czy w ogole taki produkt jest w sklepie

assert len( [ None for p in oferta if p['nazwa'] == wybor ] ) > 0, "Brak produktu w sklepie"

# pytamy "Ile kg?"
waga = float( input("Ile kg? ") )

# podajemy cene

# filtrujemy liste w poszukiwaniu produktu o wybranej nazwie
#print( [ p for p in oferta if p['nazwa'] == wybor ] )

# wyciagamy pierwszy z nich (numer 0)
#print( [ p for p in oferta if p['nazwa'] == wybor ][0] )

# wyciagamy pierwszy z nich (numer 0) a nastepnie jego pole "cena"
# print( [ p for p in oferta if p['nazwa'] == wybor ][0]["cena"] )

cena = [ p for p in oferta if p['nazwa'] == wybor ][0]["cena"]

# alternatywne podejscie, daje ten sam wynik
# cena = [ p['cena'] for p in oferta if p['nazwa'] == wybor ][0]

wartosc = waga * cena
print(f"Do zaplaty: {wartosc}")


#!/usr/bin/env python3
""" Class that inherits from BaseCaching and is a caching system """

from base_caching import BaseCaching

class FIFOCache(BaseCaching):
    """class called fifocache that inherits from basecaching"""

    def __init__(self):
        """initilization class instance
        """
        super().__init__()
        self.cache_item_order_list = []

    def put(self, key, item):
        """the put method that assign to the dictionary key item value."""
        if key and item:
            self.cache_data[key] = item
            """add item value to the self.cache.data"""
            self.cache_item_order_list.append(key)
            """appends key to the self data list"""
            if len(self.cache_data) > self.MAX_ITEMS:
                """checks if line exceeds the number of items allowed"""
                self.cache_data.pop(self.cache_item_order_list[0])
                """removes the older item and assign it to a variable"""
                old_key_list = self.cache_item_order_list.pop(0)
                print("DISCARD: {}".format(old_key_list))

    def get(self, key):
        """get method that returns key of data in cache if present"""
        if key in self.cache_data:
            """checks if key is present in data cache list"""
            return self.cache_data[key]
        else:
            return None


#!/usr/bin/python

import config.config_read as rsd
import io_data.xml_acces_file as xaf
from models.Subject import Subject
import os
import errno
import numpy as np
import nibabel as nib
import numpy.random as rnd
import math
import xml.etree.ElementTree as ET
from random import shuffle

#------------------------------------------------------------------------------------------
# get Subject Info [Age, Sex, MMSE, Global GDS,, Global CDR]
#------------------------------------------------------------------------------------------
def get_meta_data_xml(data_params, subject_ID):
    return xaf.get_Subject_info(data_params, subject_ID)

#------------------------------------------------------------------------------------------
# Function generates a conevntionned name from the config parameters
# -> Example : if factor is 100, dim is 28, max shift is 2, and gaussian blurr is 1.2
# the name will be  => F_28P_F100_MS02_MB12D
#------------------------------------------------------------------------------------------
def get_convention_name(data_params):
    dim_pixel = get_dimensions_patch(data_params)[0]
    path_file = 'F_' + str(dim_pixel) + 'P_F' + str(data_params['factor']) + '_MS' + str(data_params['shift']) + '_MB' + str(data_params['sigma']).replace(".", "") + 'D'
    return path_file

#------------------------------------------------------------------------------------------
# Function comptues the rotation operation
#------------------------------------------------------------------------------------------
def matrix_rotation(mtx):
    transpose = np.transpose(np.transpose(mtx))
    # rotated = list(reversed(zip(*transpose))) # for python 2
    rotated = list(zip(*transpose))[::-1] # for python 3
    return rotated

#------------------------------------------------------------------------------------------
# Function comptues the rotation operation for 3D volume
#------------------------------------------------------------------------------------------
def volume_rotation(data):
    data_holder = np.zeros((data.shape[0], data.shape[1], data.shape[2]))
    for i in range(data.shape[0]): # sag dimension
        data_holder[i, :, :] = list(zip(*np.transpose(np.transpose(data[i, :, :]))))[::-1]
    return data_holder

#------------------------------------------------------------------------------------------
# Function create folder if not exits
#------------------------------------------------------------------------------------------
def create_folder(directory):
    try:
        os.makedirs(directory)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise

#------------------------------------------------------------------------------------------
# Function return numpy array data from Nifty file
#------------------------------------------------------------------------------------------
def nii_to_array(nii_filename, data_type, fix_nan=True):  # get 3d array from the nii image
    img = nib.load(nii_filename)
    np_data = img.get_data().astype(data_type)
    if fix_nan:
        np_data = np.nan_to_num(np_data)
    return np_data

#------------------------------------------------------------------------------------------
# Function generate list of data: for a selected modality and binary classification
# -> Example: if label=AD-NC and modality=DTI we will get a list like:
# -> []
#------------------------------------------------------------------------------------------
def generate_selected_list(label, modal_type):  # ('NC-AD', 'DTI')
    lst_data = []
    list_data_set = ['alz_sMRI_train', 'alz_sMRI_valid', 'alz_sMRI_test', 'alz_MD_train', 'alz_MD_valid', 'alz_MD_test']
    for item in list_data_set:
        if modal_type in item:
            str_ = item + '_' + label
            lst_data.append(str_)
    return lst_data

#------------------------------------------------------------------------------------------
# Function:
#------------------------------------------------------------------------------------------
def generate_selected_label_list(label):  # ('NC-AD', '')
    lst_data = []
    list_data_set = ['alz_sMRI_train', 'alz_sMRI_valid', 'alz_sMRI_test', 'alz_MD_train', 'alz_MD_valid', 'alz_MD_test']
    for item in list_data_set:
        str_ = item + '_' + label
        lst_data.append(str_)
    return lst_data

#------------------------------------------------------------------------------------------
# Function: split binary classification groups
#------------------------------------------------------------------------------------------
def split_lists_to_binary_groups(lists):
    three_way_labels = list(rsd.get_label_binary_codes()['AD-MCI-NC'].keys())  # {'AD': 0, 'MCI': 1, 'NC': 2}
    # bin_labels = {'10': three_way_labels[1] + '-' + three_way_labels[0], '12': three_way_labels[1] + '-' + three_way_labels[2], '20': three_way_labels[2] + '-' + three_way_labels[0]}
    bin_labels = {'01': three_way_labels[0] + '-' + three_way_labels[1], '12': three_way_labels[1] + '-' + three_way_labels[2], '02': three_way_labels[0] + '-' + three_way_labels[2]}
    bin_groups = {'01': [], '12': [], '02': []}
    for item in lists:
        if item[0] == three_way_labels[0]:
            bin_groups['01'].append(item)
            bin_groups['02'].append(item)
        if item[0] == three_way_labels[1]:
            bin_groups['01'].append(item)
            bin_groups['12'].append(item)
        if item[0] == three_way_labels[2]:
            bin_groups['12'].append(item)
            bin_groups['02'].append(item)
    return {bin_labels[k]: bin_groups[k] for k in ('01', '12', '02')}

##
def split_mri_dti(item_list):
    mri_list = [(i[0], i[1], i[3]) for i in item_list]
    dti_list = [(i[0], i[2], i[3]) for i in item_list]
    return mri_list, dti_list

##
def get_dimensions_patch(data):
    hipp = data['hipp_left']
    padding_size = int(data['padding_size'])
    shift_param = int(data['shift'])
    new_hipp = (
        int(hipp[0]) - 1 - shift_param - padding_size, int(hipp[1]) - 1 - shift_param + padding_size,
        int(hipp[2]) - 1 - shift_param - padding_size, int(hipp[3]) - 1 - shift_param + padding_size,
        int(hipp[4]) - 1 - shift_param - padding_size, int(hipp[5]) - 1 - shift_param + padding_size)
    return (new_hipp[1] - new_hipp[0], new_hipp[3] - new_hipp[2], new_hipp[5] - new_hipp[4])

#------------------------------------------------------------------------------------------
# generates Augmentation parameters (not randomly) to avoid same params
# -> version 1: overfitting !!!!
#------------------------------------------------------------------------------------------

def generate_augm_params(max_blur, max_shift):
    import numpy.random as rnd
    while True:
        shift_x = rnd.randint(-max_shift, max_shift + 1)
        shift_y = rnd.randint(-max_shift, max_shift + 1)
        shift_z = rnd.randint(-max_shift, max_shift + 1)
        blur_sigma = float(rnd.randint(1000)) / 1000 * max_blur
        if shift_x + shift_y + shift_z + blur_sigma > 0:  # ???
            return shift_x, shift_y, shift_z, blur_sigma

#------------------------------------------------------------------------------------------
# generates Augmentation parameters (not randomly) to avoid same params
# -> NB: pour eviter : overfitting
#------------------------------------------------------------------------------------------
def generate_augmentation_parameters_list_v2(max_blur, max_shift):
    res = []
    if max_blur is not None and max_shift is not None:
        L = [round(x*0.100, 2) for x in range(0, (int(max_blur * 10) + 1))]
        for idx in range(len(L)):
            for i in range(-max_shift, max_shift + 1):
                for j in range(-max_shift, max_shift + 1):
                    for k in range(-max_shift, max_shift + 1):
                        res.append([(i, j, k, L[idx])])

    return res

#------------------------------------------------------------------------------------------
# generate parameters (x, y, z, k.k) for each subject
# -> overfitting !!!!
#------------------------------------------------------------------------------------------

def generate_augm_lists(dirs_with_labels, new_size, max_blur, max_shift, default_augm_params=None):
    # pas d'augmentation
    if new_size is None or len(dirs_with_labels) == new_size:  # ?
        return [dwl + [default_augm_params] for dwl in dirs_with_labels]

    # for avoid similar augmentation
    local_param_list = generate_augmentation_parameters_list_v2(max_blur, max_shift)
    shuffle(local_param_list)
    augm_coeff = int(math.floor(new_size / len(dirs_with_labels)))
    res = []
    i = 0
    for dwl in dirs_with_labels:
        res.append(dwl + [(0, 0, 0, 0.0)])
        i += 1
        # for _ in range(augm_coeff - 1):
            # print("i : ", i)
            # res.append(dwl + local_param_list[i])
            # i += 1
    #print("-->", dirs_with_labels[0][0], augm_coeff, len(dirs_with_labels), len(res), i)
    while i < new_size:
        ridx = rnd.randint(len(dirs_with_labels))
        dwl = dirs_with_labels[ridx]
        res.append(dwl + local_param_list[i])
        i += 1
    # for x in res:
    #     print(x[0], x[3])
    return res

#------------------------------------------------------------------------------------------
# generate list dataset with aumentation parameters
# EXP: ['AD', 'path/to/MRI/', (x,y,z, a.b)] for each subject
#------------------------------------------------------------------------------------------

def generate_augm_lists_v2(dirs_with_labels, new_size, max_blur, max_shift, default_augm_params=None):
    # pas d'augmentation
    if new_size is None or len(dirs_with_labels) == new_size or max_blur == 0 or max_shift == 0:  # ?
        return [dwl + [default_augm_params] for dwl in dirs_with_labels]

    augm_coeff = int(math.floor(new_size / len(dirs_with_labels)))
    res = []
    local_param_list = generate_augmentation_parameters_list_v2(max_blur, max_shift)
    shuffle(local_param_list)
    for dwl in dirs_with_labels:
        res.append(dwl + [(0, 0, 0, 0.0)])
        for _ in range(augm_coeff - 1):
            res.append(dwl + local_param_list.pop())
        local_param_list = generate_augmentation_parameters_list_v2(max_blur, max_shift)
        shuffle(local_param_list)
    for _ in range(new_size - len(dirs_with_labels) * augm_coeff):
        ridx = rnd.randint(len(dirs_with_labels))
        dwl = dirs_with_labels[ridx]
        res.append(dwl + local_param_list.pop())
    return res

def get_dimensions_cubes_HIPP(data):
    crp_l = data['hipp_left']
    crp_r = data['hipp_right']
    padding_size = int(data['padding_size'])
    shift_param = int(data['shift'])
    #
    #[int(crp_l[i]) - 1 - shift_param - padding_size, int(crp_l[i+1]) - 1 - shift_param + padding_size \
     #   for i in range(0, 6, 2)]
    new_crp_l = (
        int(crp_l[0]) - 1 - shift_param - padding_size, int(crp_l[1]) - 1 - shift_param + padding_size,
        int(crp_l[2]) - 1 - shift_param - padding_size, int(crp_l[3]) - 1 - shift_param + padding_size,
        int(crp_l[4]) - 1 - shift_param - padding_size, int(crp_l[5]) - 1 - shift_param + padding_size)
    new_crp_r = (int(crp_r[0]) - 1 - shift_param - padding_size, int(crp_r[1]) - 1 - shift_param + padding_size,
                 int(crp_r[2]) - 1 - shift_param - padding_size, int(crp_r[3]) - 1 - shift_param + padding_size,
                 int(crp_r[4]) - 1 - shift_param - padding_size, int(crp_r[5]) - 1 - shift_param + padding_size)
    return new_crp_l, new_crp_r

def get_dimensions_cubes_PPC(data):
    crp_l = data['ppc_left']
    crp_r = data['ppc_right']
    padding_size = int(data['padding_size'])
    shift_param = int(data['shift'])
    new_crp_l = (
        int(crp_l[0]) - 1 - shift_param - padding_size, int(crp_l[1]) - 1 - shift_param + padding_size,
        int(crp_l[2]) - 1 - shift_param - padding_size, int(crp_l[3]) - 1 - shift_param + padding_size,
        int(crp_l[4]) - 1 - shift_param - padding_size, int(crp_l[5]) - 1 - shift_param + padding_size)
    new_crp_r = (int(crp_r[0]) - 1 - shift_param - padding_size, int(crp_r[1]) - 1 - shift_param + padding_size,
                 int(crp_r[2]) - 1 - shift_param - padding_size, int(crp_r[3]) - 1 - shift_param + padding_size,
                 int(crp_r[4]) - 1 - shift_param - padding_size, int(crp_r[5]) - 1 - shift_param + padding_size)
    return new_crp_l, new_crp_r

#
def split_list(liste, number_ele):
    return liste[:number_ele], liste[number_ele:]

def getSubjectByID(data_params, subjectID):
    subjectEle = xaf.get_Subject_info(data_params, subjectID) #[ID, Date, Class, Age, Sex, MMSE]
    return Subject(*subjectEle)


import numpy as np
import matplotlib.pyplot as plt

from PIL import Image
Image.effect_mandelbrot((512, 512), (-3, -2.5, 2, 2.5), 100).show()

np.warnings.filterwarnings("ignore")

def complex_matrix(xmin, xmax, ymin, ymax, pixel_density):
    re = np.linspace(xmin, xmax, int((xmax - xmin) * pixel_density))
    im = np.linspace(ymin, ymax, int((ymax - ymin) * pixel_density))
    return re[np.newaxis, :] + im[:, np.newaxis] * 1j

def is_stable(c, num_iterations):
    z = 0
    for _ in range(num_iterations):
        z = z ** 2 + c
    return abs(z) <= 2

c = complex_matrix(-2, 0.5, -1.5, 1.5, pixel_density=512)
image = Image.fromarray(~is_stable(c, num_iterations=20))
#image.show()


# 525. Contiguous Array

class Solution(object):
    def findMaxLength(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        result=0
        index={0:-1}
        count=0
        for i in range(len(nums)):
            count=count+ (1 if nums[i]==0 else -1)
            if count in index:
                result=max(result, i-index[count])
            else:
                index[count]=i
        return result


#!/usr/bin/env python
#-*- coding: utf-8 -*-
# Author: (sandysuehe@gmail.com)
#########################################################################
# Created Time: 2018-10-25 13:50:33
# File Name: atoi.py
# Description: atoi
# LintCode: https://www.lintcode.com/problem/string-to-integer-atoi/
# 注意: sys.maxint = 9223372036854775807
#########################################################################
def atoi(strs):
    import sys
    maxint = sys.maxint
    minint = -sys.maxint-1
    if not strs:
        return 0

    flag = 1
    num = 0
    i = 0
    n = len(strs)

    while i < n and strs[i] == " ":
        i += 1

    if strs[i] in ("+", "-"):
        if strs[i] == "-":
            flag = -1
        else:
            flag = 1

    while i < n and strs[i].isdigit():
        if num > maxint/10 or (num == maxint/10 and int(strs[i])>7):
            if flag == 1:
                return maxint
            else:
                return minint
        num = 10 * num + int(strs[i])
        i += 1

    return num * flag
# vim: set noexpandtab ts=4 sts=4 sw=4 :


import vosk
import sys
import os
import wave
import json
import re
from pprint import pprint
import numpy as np

infile = 'output_file.wav'

model = vosk.Model("vosk-model-small-ru-0.22")
spk_model = vosk.SpkModel('vosk-model-spk-0.4')

def cosine_dist(x, y):
    nx = np.array(x)
    ny = np.array(y)
    return 1 - np.dot(nx, ny) / np.linalg.norm(nx) / np.linalg.norm(ny)

wf = wave.open(infile, "rb")
rcgn_fr = wf.getframerate() * wf.getnchannels()
rec = vosk.KaldiRecognizer(model, rcgn_fr, spk_model)
rec.SetSpkModel(spk_model)
wf.rewind()
result = ''
last_n = False
# read_block_size = 4000
read_block_size = wf.getnframes()

while True:
    data = wf.readframes(read_block_size)
    if len(data) == 0:
        break

    if rec.AcceptWaveform(data):
        res = json.loads(rec.Result())

        if res['text'] != '':
            result += f" {res['text']}"
            if read_block_size < 200000:
                print(res['text'] + " \n")

            last_n = False
        elif not last_n:
            result += '\n'
            last_n = True

# res = json.loads(rec.Result())
# print(res)
# result += f" {res['text']}"
# pprint(result)


from utils_queue import Queue

class _Node:
    __slots__ = '_val', '_left', '_right'
    def __init__(self, val, left=None, right=None):
        self._val = val
        self._left = left
        self._right = right

class BinaryTree:
    __slots__ = '_root'
    def __init__(self, root=None):
        self._root = root

    def preorder_traversal(self, node):
        if node:
            print(node._val, end=' ')
            self.preorder_traversal(node._left)
            self.preorder_traversal(node._right)

    def inorder_traversal(self, node):
        if node:
            self.inorder_traversal(node._left)
            print(node._val, end=' ')
            self.inorder_traversal(node._right)

    def postorder_traversal(self, node):
        if node:
            self.postorder_traversal(node._left)
            self.postorder_traversal(node._right)
            print(node._val, end=' ')

    def levelorder_traversal(self, node_list):
        if not len(node_list):
            return
        new_node_list = []
        for node in node_list:
            if not node:
                continue
            print(node._val, end=' ')
            new_node_list.append(node._left)
            new_node_list.append(node._right)
        self.levelorder_traversal(new_node_list)

    def levelorder_traversal_queue(self):
        queue = Queue()
        if self._root:
            queue.enqueue(self._root)
        while not queue.is_empty():
            node = queue.dequeue()
            if node:
                print(node._val, end=' ')
                queue.enqueue(node._left)
                queue.enqueue(node._right)

    def node_count(self, node):
        c = 0
        if node:
            c += 1
            c += self.node_count(node._left)
            c += self.node_count(node._right)
        return c

    def level(self, node):
        if node:
            left_height = self.level(node._left)
            right_height = self.level(node._right)
            return max(left_height, right_height) + 1
        return 0

    def height(self, node):
        return self.level(node) - 1

"""
    Tree structure:
                        1

            2                       3

    4               5       6               7
"""

node4 = _Node(4)
node5 = _Node(5)

node6 = _Node(6)
node7 = _Node(7)

node2 = _Node(2, node4, node5)
node3 = _Node(3, node6, node7)

node1 = _Node(1, node2, node3)

bt = BinaryTree(node1)

print('Preorder traversal')
bt.preorder_traversal(bt._root)
print('\nInorder traversal')
bt.inorder_traversal(bt._root)
print('\nPostorder traversal')
bt.postorder_traversal(bt._root)
print('\nLevelorder traversal')
bt.levelorder_traversal([bt._root])
print('\nLevelorder traversal queue')
bt.levelorder_traversal_queue()
print('\nNode count: ')
print(bt.node_count(bt._root))
print('Height: ')
print(bt.height(bt._root))

"""
    Another tree structure
                                1

                    2                       3

            4                                           6
"""

node_4 = _Node(4)
node_2 = _Node(2, left=node_4)

node_6 = _Node(6)
node_3 = _Node(3, right=node_6)

node_1 = _Node(1, node_2, node_3)

bt_ = BinaryTree(node_1)

print('\nPreorder traversal')
bt_.preorder_traversal(bt_._root)
print('\nInorder traversal')
bt_.inorder_traversal(bt_._root)
print('\nPostorder traversal')
bt_.postorder_traversal(bt_._root)
print('\nLevelorder traversal')
bt_.levelorder_traversal([bt_._root])
print('\nLevelorder traversal queue')
bt_.levelorder_traversal_queue()
print('\nNode count: ')
print(bt_.node_count(bt_._root))
print('Height: ')
print(bt_.height(bt_._root))


import numpy as np
import torch
from ray.serve.gradio_integrations import GradioServer
from transformers import DistilBertForSequenceClassification, DistilBertTokenizer
from scipy.special import softmax
from scipy.stats import entropy
import matplotlib.pyplot as plt
import gradio as gr
import ray

model_name = "distilbert-base-uncased-finetuned-sst-2-english"

np.set_printoptions(suppress=True)

entropy_threshold = 0.693

mapper = ['negative', 'positive']
NEUTRAL_SENTIMENT = 'neutral'

class SentimentClassifier:
    def __init__(self, model, tokenizer):
        self.model = model
        self.tokenizer = tokenizer

    def handle(self, inputs):
        encoded_input = self.tokenizer(inputs, padding=True, truncation=True, return_tensors="pt")
        with torch.no_grad():
            output = self.model(**encoded_input).logits
        scores = output.detach().numpy()
        probabilities = softmax(scores, axis=1)
        results = []
        for probs in probabilities:
            if entropy(probs) > entropy_threshold:
                results.append(NEUTRAL_SENTIMENT)
                continue
            results.append(mapper[np.argmax(probs)])
        return results

@ray.remote
class SentimentAnalyzer:
    def __init__(self):
        self.classifier = SentimentClassifier(
            DistilBertForSequenceClassification.from_pretrained(model_name),
            DistilBertTokenizer.from_pretrained(model_name),
        )

    def analyze_cue(self, cue):
        return self.classifier.handle(cue)

    def analyze_dialog(self, dialog):
        results = []
        for speaker, cues in dialog.items():
            speaker_results = self.analyze_cue(cues)
            results.append((speaker, speaker_results))
        return results

def calculate_sentiment_ratios(dialog):
    speakers = []
    positive_ratios = []
    negative_ratios = []
    neutral_ratios = []
    for speaker, cues in dialog:
        total = len(cues)
        positive_ratio = cues.count('positive') / total if total > 0 else 0
        negative_ratio = cues.count('negative') / total if total > 0 else 0
        neutral_ratio = cues.count('neutral') / total if total > 0 else 0
        speakers.append(speaker)
        positive_ratios.append(positive_ratio)
        negative_ratios.append(negative_ratio)
        neutral_ratios.append(neutral_ratio)
    return speakers, positive_ratios, negative_ratios, neutral_ratios

def convert_text_to_dict(text):
    result_dict = {}
    lines = text.split('\n')
    for line in lines:
        if line.strip() != '':
            key, value = line.split(':')
            key = key.strip()
            value = value.strip()
            if key in result_dict:
                result_dict[key].append(value)
            else:
                result_dict[key] = [value]
    return result_dict

def gradio_sentiment_builder():
    sentiment_analyzer = SentimentAnalyzer.remote()

    def model(text):
        results = ray.get(sentiment_analyzer.analyze_dialog.remote(convert_text_to_dict(text)))
        speakers, positive_ratios, negative_ratios, neutral_ratios = calculate_sentiment_ratios(results)
        ratios = {
            'Positive': positive_ratios,
            'Negative': negative_ratios,
            'Neutral': neutral_ratios
        }

        x = np.arange(len(speakers))
        width = 0.25
        multiplier = 0

        fig, ax = plt.subplots(layout='constrained')

        for attribute, measurement in ratios.items():
            offset = width * multiplier
            rects = ax.bar(x + offset, measurement, width, label=attribute)
            ax.bar_label(rects, padding=3)
            multiplier += 1

        ax.set_ylabel('Frequency')
        ax.set_title('Sentiment distribution over speakers')
        ax.set_xticks(x + width, speakers)
        ax.legend(loc='upper left', ncols=3)
        ax.set_ylim(0, 1.1)

        return fig

    return gr.Interface(
        fn=model,
        inputs=gr.Textbox(lines=20),
        outputs="plot",
        description="Enter the dialog cues and analyze the sentiment ratios for each speaker.",
        examples=["""a: Hello, my friend
b: Hello, bro"""],
        x='Speakers',
        y=['Positive', 'Negative', 'Neutral'],
        type='bar',
        labels=['Positive', 'Negative', 'Neutral']
    )

app = GradioServer.options().bind(
    gradio_sentiment_builder
)


import time
import threading
import os
import logging
logging.basicConfig(format='%(message)s', level=logging.INFO)

'''
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')
'''

def main():
    logging.info('Server on')
    logging.info('Enter commands...')
    while(True):
        cmd = input()

        try:
            val = int(cmd)
        except:
            val = None

        if(val):
            t = threading.Thread(target=sleeper, args=[val])
            t.start()

        else:
            fileName = cmd + '.py'
            t = threading.Thread(target=fileTrigger, args=[fileName])
            t.start()

def sleeper(seconds):
    logging.info(f'sleeping {seconds} second(s)')
    time.sleep(seconds)
    logging.info(f'Done sleeping')

def fileTrigger(fileName):
    os.system(fileName)

if __name__ == '__main__':
    main()


import h5py
import sys

last = int(sys.argv[1])

f = h5py.File('west.h5', 'r')['summary']

walltime = f['walltime'][0:last].sum()
aggtime = f['n_particles'][0:last].sum()

print("walltime: ", walltime, "seconds")
print("aggtime: ", aggtime, "units")


#!/usr/bin/python3
""" Unit test Place """
import unittest
import models
import os
from models.place import Place

class TestPlace(unittest.TestCase):
    """ Test for class Place"""

    def testing_executable_file(self):
        '''test files's permisssion'''
        # Check for read access
        read_true = os.access('models/place.py', os.R_OK)
        self.assertTrue(read_true)
        # Check for write access
        write_true = os.access('models/place.py', os.W_OK)
        self.assertTrue(write_true)
        # Check for execution access
        exec_true = os.access('models/place.py', os.X_OK)
        self.assertTrue(exec_true)

    def testing_init_Place(self):
        """test if an object is an type Place"""
        my_object = Place()
        self.assertIsInstance(my_object, Place)

    def testing_id(self):
        """ test that id is unique """
        my_objectId0 = Place()
        my_objectId1 = Place()
        self.assertNotEqual(my_objectId0.id, my_objectId1.id)

    def testing_str(self):
        '''check str format'''
        my_strobject = Place()
        dictt = my_strobject.__dict__
        string0 = "[Place] ({}) {}".format(my_strobject.id, dictt)
        string1 = str(my_strobject)
        self.assertEqual(string0, string1)

    def testing_save(self):
        """ check if date update when save """
        object_upd = Place()
        first_update = object_upd.updated_at
        object_upd.save()
        second_update = object_upd.updated_at
        self.assertNotEqual(first_update, second_update)

    def testing_to_dict(self):
        '''check if dic format returs a dict with class place, iso format.'''
        my_modell = Place()
        my_dict_modell = my_modell.to_dict()
        self.assertIsInstance(my_dict_modell, dict)
        for key, value in my_dict_modell.items():
            flag = 0
            if my_dict_modell['__class__'] == 'Place':
                flag += 1
            self.assertTrue(flag == 1)
        for key, value in my_dict_modell.items():
            if key == 'created_at':
                self.assertIsInstance(value, str)
            if key == 'updated_at':
                self.assertIsInstance(value, str)

if __name__ == '__main__':
    unittest.main()


def validate_min_rows_number(
    min_rows: int, current_rows: int, item_type: str = "File", raise_error: bool = True
):

    err_msg = f"{item_type} doesn't have the minimum number of rows: {min_rows}"

    if current_rows < min_rows:
        if raise_error:
            raise ValueError(err_msg)
        else:
            return err_msg

    return True


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 23 15:15:05 2021

@author: qichen
"""
from aiida.plugins import DataFactory, CalculationFactory
from aiida.engine import workfunction, submit, calcfunction
from aiida.orm import Code, SinglefileData, Int, Float, Str, Bool, List, Dict, ArrayData, XyData, SinglefileData, FolderData, RemoteData
import aiida
import os

aiida.load_profile()

def submit_single_calc(temps):
    code = Code.get_from_string('uppasd_dev@uppasd_local')
    builder = code.get_builder()
    dmdata = SinglefileData(
        file=os.path.join(os.getcwd(), "input_files2", 'dmdata'))
    jij = SinglefileData(
        file=os.path.join(os.getcwd(), "input_files2", 'jij'))
    momfile = SinglefileData(
        file=os.path.join(os.getcwd(), "input_files2", 'momfile'))
    posfile = SinglefileData(
        file=os.path.join(os.getcwd(), "input_files2", 'posfile'))
    qfile = SinglefileData(
        file=os.path.join(os.getcwd(), "input_files2", 'qfile'))

    # inpsd.dat file selection
    simid = Str('SCsurf_T')
    ncell = Str('128 128 1')
    BC = Str('P         P         0 ')
    cell = Str('''1.00000 0.00000 0.00000
    0.00000 1.00000 0.00000
    0.00000 0.00000 1.00000''')
    do_prnstruct = Int(2)
    maptype = Int(2)
    SDEalgh = Int(1)
    Initmag = Int(3)
    ip_mode = Str('Q')
    qm_svec = Str('1   -1   0 ')
    qm_nvec = Str('0  0  1')
    mode = Str('S')
    temp = Float(temps)
    damping = Float(0.500)
    Nstep = Int(5000)
    timestep = Str('1.000d-15')
    qpoints = Str('F')
    plotenergy = Int(1)
    do_avrg = Str('Y')

    r_l = List(list=[
        f'coord.{simid.value}.out',
        f'qm_minima.{simid.value}.out',
        f'qm_sweep.{simid.value}.out',
        'qpoints.out',
        f'totenergy.{simid.value}.out',
        f'averages.{simid.value}.out',
        'fort.2000',
        'inp.{simid.value}.yaml',
        'qm_restart.{simid.value}.out',
        'restart.{simid.value}.out'
    ])

    # set up calculation
    inpsd = Dict()
    inpsd.set_attribute('simid', simid)
    inpsd.set_attribute('ncell', ncell)
    inpsd.set_attribute('BC', BC)
    inpsd.set_attribute('cell', cell)
    inpsd.set_attribute('do_prnstruct', do_prnstruct)
    inpsd.set_attribute('maptype', maptype)
    inpsd.set_attribute('SDEalgh', SDEalgh)
    inpsd.set_attribute('Initmag', Initmag)
    inpsd.set_attribute('ip_mode', ip_mode)
    inpsd.set_attribute('qm_svec', qm_svec)
    inpsd.set_attribute('qm_nvec', qm_nvec)
    inpsd.set_attribute('mode', mode)
    inpsd.set_attribute('temp', temp)
    inpsd.set_attribute('damping', damping)
    inpsd.set_attribute('Nstep', Nstep)
    inpsd.set_attribute('timestep', timestep)
    inpsd.set_attribute('qpoints', qpoints)
    inpsd.set_attribute('plotenergy', plotenergy)
    inpsd.set_attribute('do_avrg', do_avrg)
    #inpsd.set_attribute()
    builder.code = code
    builder.dmdata = dmdata
    builder.jij = jij
    builder.momfile = momfile
    builder.posfile = posfile
    builder.qfile = qfile
    builder.inpsd = inpsd
    builder.retrieve_list_name = r_l
    builder.inpsd_dat_exist = Int(0)
    builder.metadata.options.resources = {'num_machines': 1}
    builder.metadata.options.max_wallclock_seconds = 120
    builder.metadata.options.input_filename = 'inpsd.dat'
    builder.metadata.options.parser_name = 'UppASD_core_parsers'
    builder.metadata.label = 'Demo_for_temp_{}'.format(int(temps.value))
    builder.metadata.description = 'Test Demo_for_temp_{} for UppASD-AiiDA'.format(
        int(temps.value))
    submit(builder)

@workfunction
def multi_temp(temp_list):
    for t in temp_list.attributes['list']:
        submit_single_calc(Float(t))

temp_list = List(list=list(range(0, 30, 10)))

multi_temp(temp_list)


import logging
import os
import platform
import sys
import time
import traceback

from selenium import webdriver

from ccdl import (Binb2, ComicAction, ComicEarthstar, ComicLinkInfo,
                  ComicWalker, Ganma)
from ccdl.utils import SiteReaderLoader

if not os.path.exists("log"):
    os.makedirs("log")

log_file_path = "log/{}.log".format(time.strftime("%Y-%m-%d"))
fh = logging.FileHandler(filename=log_file_path, encoding="UTF-8")
logging.basicConfig(
    handlers=[fh], format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("CCDL")

if 'Linux' in platform.platform().split('-'):
    executable_path = './chromedriver'
elif 'Windows' in platform.platform().split('-'):
    executable_path = './chromedriver.exe'
else:
    logger.error("platform not win or linux")
    raise ValueError("os")

if __name__ == "__main__":
    driver = None
    is_exist = os.path.exists(executable_path)
    print("\n源碼: https://github.com/vircoys/ccdl")
    if is_exist:
        print("\n如需登入（含*）請提前在程式啟動的瀏覽器中登入，並加載目標url（任意標籤頁）！\n")
        driver = webdriver.Chrome(executable_path=executable_path)
    else:
        print("\n由於未在程式所在目錄發現chromedriver，部分基於selenium採集的站點將無法進行。")
        print("您可於 http://npm.taobao.org/mirrors/chromedriver/ 下載\n")

    print("\n>>>>>>>>輸入exit退出<<<<<<<<\n")

    while True:
        url = input("url: ")

        if url == 'exit':
            print('Bye~')
            time.sleep(0.5)
            if driver:
                driver.quit()
            sys.exit()

        link_info = ComicLinkInfo(url)

        reader = SiteReaderLoader(link_info, driver)
        if reader is not None:
            try:
                reader.downloader()
            except Exception as e:
                logger.error(traceback.format_exc())
                print("下載失敗! \n" + traceback.format_exc())
        else:
            print("not supported")
            continue


from fastapi import FastAPI
from .routes import router as api_router
from app_python.core.tasks import create_start_app_handler, create_stop_app_handler

def get_app():
    """Function creates app with all the routes and settings we need"""
    app = FastAPI()

    # start and shutdown event handlers
    app.add_event_handler("startup", create_start_app_handler(app))
    app.add_event_handler("shutdown", create_stop_app_handler(app))

    # include all routes
    app.include_router(api_router, prefix="")
    return app

# Create app
app = get_app()


import alexnet
import torch
import urllib
import os
from models import *
import torchvision
from PIL import Image
from torchvision import transforms
import torch.optim as optim
import torch.nn as nn
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
import model
import pickle
from copy import copy
from copy import deepcopy
#hyperparam
batch_size = 4
epoch = 25

#Data augmentation
preprocess = transforms.Compose(
    [
    transforms.ToTensor(),
    transforms.Resize(256),
    transforms.RandomCrop(224),
    transforms.RandomHorizontalFlip(),
    transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
    ]
)

eval_preprocess = transforms.Compose([
    transforms.ToTensor(),
    transforms.Resize(256),
    transforms.RandomCrop(224),
    transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))])

#Download CIFAR10
full_train_dataset = torchvision.datasets.CIFAR10(root='/root/labs/data',
                                           train=True,
                                           download=True)

#split train , validate set =
train_dataset, val_dataset = torch.utils.data.random_split(full_train_dataset, [40000, 10000])
train_dataset.dataset = copy(full_train_dataset)
train_dataset.dataset.transform = preprocess

val_dataset.dataset.transform = eval_preprocess
print(type(train_dataset.dataset.data))

test_dataset = torchvision.datasets.CIFAR10(root='/root/labs/data',
                                          train=False,
                                          transform=eval_preprocess)

#Dataloader
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
                                           batch_size=batch_size,
                                           shuffle=True,
                                           num_workers=4)

valid_loader = torch.utils.data.DataLoader(dataset=val_dataset,
                                           batch_size=batch_size,
                                           shuffle=False,
                                           num_workers=4)

test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
                                          batch_size=batch_size,
                                          shuffle=False,num_workers=4)

device = torch.device("cuda:2" if torch.cuda.is_available() else "cpu")
print('Using device', device)

resnet = ResSENet18()
resnet = resnet.to(device)
# Make optimizer and Loss function
criterion_2 = nn.CrossEntropyLoss()
params_to_update_2 = resnet.parameters()
optimizer_2 = optim.Adam(params_to_update_2, lr=0.001)

dataloaders = { 'train': train_loader, 'val': valid_loader }
print(resnet.eval())
file = "restSEnet18-25epoch"
best_model2, val_acc_history2, loss_acc_history2 = model.train_model(resnet, dataloaders, criterion_2, optimizer_2, epoch,file)

#saving
with open(f"/root/labs/loss/{file}.pk",'wb') as f:
    pickle.dump((val_acc_history2,loss_acc_history2),f)

#Test model
#Testing Accuracy
correct = 0
total = 0
with torch.no_grad():
    for data in tqdm(test_loader,desc="Testing"):
        images, labels = data[0].to(device), data[1].to(device)
        outputs = best_model2(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()
    acc = 100 * correct / total
print('Accuracy on test images: %d %%' % (100 * correct / total))


from apiclient import discovery
from datetime import date, datetime, timedelta as td
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.errors import HttpError
from django.apps import apps
from django.db import models, IntegrityError
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.urls import reverse
from django.utils import timezone
from core.utils import make_slug
from core.tasks import send_mail_task
from academics.models import Course
from people.models import Staff, Student
from people.tasks import pop_update_task
from semesters.models import Semester
from core.tasks import send_sms_task
from .tasks import (activate_task, end_task, drop_task,
    enrollment_notification_task, cancel_class_task)

class Site(models.Model):

    code = models.CharField(max_length=2)

    name = models.CharField(max_length=50)

    street_address = models.CharField(
        max_length=60,
        verbose_name="Street Address",
    )
    city = models.CharField(
        max_length=30,
    )
    state = models.CharField(
        max_length=2,
        default="LA"
    )
    zip_code = models.CharField(
        max_length=10,
    )

    def __str__(self):
        return(self.name)

class Section(models.Model):

    ESL = 'ELL'
    CCR = 'CCR'
    TRANS = 'TRANS'
    ADMIN = 'ADMIN'
    ELEARN = 'ELRN'
    PROGRAM_CHOICES = (
        (ESL, 'ELL'),
        (CCR, 'CCR'),
        (ADMIN, 'Admin'),
        (ELEARN, 'eLearn'),
        (TRANS, 'Transitions')
    )

    title = models.CharField(max_length=50)

    semester = models.ForeignKey(
        Semester,
        models.PROTECT,
        related_name='sections',
        null=True,
        blank=True
    )
    teacher = models.ForeignKey(
        Staff,
        models.PROTECT,
        related_name='classes',
        null=True,
        blank=True
    )
    course = models.ForeignKey(
        Course,
        models.PROTECT,
        related_name='sections',
        null=True,
        blank=True
    )
    g_suite_id = models.CharField(
        max_length=20,
        blank=True
    )

    g_suite_link = models.CharField(
        max_length=100,
        blank=True
    )

    site = models.ForeignKey(
        Site,
        models.PROTECT,
        related_name='sections',
        null=True,
        blank=True
    )

    room = models.CharField(
        max_length=20,
        blank=True
    )
    program = models.CharField(
        max_length=5,
        choices=PROGRAM_CHOICES,
        null=True,
        blank=True
    )
    starting = models.DateField(null=True, blank=True)
    ending = models.DateField(null=True, blank=True)
    seats = models.IntegerField(null=True, blank=True)
    start_time = models.TimeField()
    end_time = models.TimeField()
    WRU_ID = models.IntegerField(null=True, blank=True)
    monday = models.BooleanField(default=False)
    tuesday = models.BooleanField(default=False)
    wednesday = models.BooleanField(default=False)
    thursday = models.BooleanField(default=False)
    friday = models.BooleanField(default=False)
    saturday = models.BooleanField(default=False)
    sunday = models.BooleanField(default=False)
    slug = models.CharField(unique=True, max_length=5, default=make_slug)

    def __str__(self):
        s = str(self.site.code)
        n = str(self.title)
        t = str(self.teacher)
        d = self.get_days_str()
        b = self.start_time.strftime('%I:%M%p')
        try:
            sem = "({0})".format(str(self.semester.id))
        except ObjectDoesNotExist:
            sem = ''
        items = [s, n, t, d, b, sem]
        return "|".join(items)

    def get_absolute_url(self):
        return reverse('sections:class detail', kwargs={'slug': self.slug})

    def get_all_students(self):
        return self.students.all()

    def get_students(self):
        return self.students.exclude(status='D')

    def get_active(self):
        return self.students.filter(status='A')

    def get_dropped(self):
        return self.students.filter(status='D')

    def get_completed(self):
        return self.students.filter(status='C')

    def get_waiting(self):
        return self.students.filter(status='W').order_by('created')

    def get_withdrawn(self):
        return self.students.filter(status='R')

    def open_seats(self):
        a = self.get_active().count()
        w = self.get_waiting().count()
        students = a + w
        if self.seats:
            return self.seats - students
        return None

    @property
    def is_full(self):
        try:
            return self.open_seats() < 1
        except TypeError:
            return True

    @property
    def over_full(self):
        return self.get_waiting().count() > 12

    @property
    def start_date(self):
        if self.starting is not None:
            return self.starting
        else:
            return self.semester.start_date

    @property
    def end_date(self):
        if self.ending is not None:
            return self.ending
        else:
            return self.semester.end_date

    def begin(self):
        for student in self.get_active():
            activate_task.delay(enrollment_id=student.id)

    def end(self):
        for student in self.get_active():
            end_task.delay(enrollment_id=student.id)

    def roster_to_classroom(self):

        scopes = [
            'https://www.googleapis.com/auth/classroom.rosters',
            'https://www.googleapis.com/auth/classroom.profile.emails'
        ]
        credentials = ServiceAccountCredentials._from_parsed_json_keyfile(
            keyfile_dict=settings.KEYFILE_DICT,
            scopes=scopes
        )
        shane = credentials.create_delegated('greenbean@elearnclass.org')
        http_auth = shane.authorize(Http())
        service = discovery.build('classroom', 'v1', http=http_auth)

        roster = service.courses().students().list(
            courseId=self.g_suite_id,
        ).execute()
        if 'students' in roster:
            rostered_emails = [
                x['profile'].get('emailAddress').lower()
                for x
                in roster['students']
                if x['profile'].get('emailAddress')
            ]
            token = roster.get('nextPageToken')
            while token is not None:
                roster = service.courses().students().list(
                    courseId=self.g_suite_id,
                    pageToken=token
                ).execute()
                current_emails = [
                    x['profile'].get('emailAddress')
                    for x
                    in roster['students']
                    if x['profile'].get('emailAddress')
                ]
                rostered_emails.extend(current_emails)
                token = roster.get('nextPageToken')
        else:
            rostered_emails = []
        print("{1} roster: {0}".format(rostered_emails, self.title))

        Elearn = apps.get_model('coaching', 'ElearnRecord')

        active_students = self.students.filter(status='A')
        active_emails = [
            elearn.g_suite_email.lower()
            for elearn
            in Elearn.objects.filter(
                student__classes__in=active_students
            )
        ]
        print("{1} active: {0}".format(active_emails, self.title))
        inactive_emails = [
            email
            for email
            in rostered_emails
            if email not in active_emails
        ]
        print("{1} inactive: {0}".format(inactive_emails, self.title))
        new_emails = [
            email
            for email
            in active_emails
            if email not in rostered_emails
            and email != ''
        ]
        print("{1} new: {0}".format(new_emails, self.title))
        def drop_callback(request_id, response, exception):
            if exception is not None:
                print("Error removing {0} from course:{1}".format(
                    request_id,
                    exception
                ))
            else:
                print("User {0} removed successfully".format(request_id))

        drop_batch = service.new_batch_http_request(callback=drop_callback)
        for email in inactive_emails:
            request = service.courses().students().delete(
                courseId=self.g_suite_id,
                userId=email
            )
            drop_batch.add(request, request_id=email)
        drop_batch.execute()

        def add_callback(request_id, response, exception):
            if exception is not None:
                print("Error adding {0} to course: {1}".format(
                    request_id,
                    exception
                ))
            else:
                print("User {0} added successfully".format(
                    response.get('profile').get('emailAddress')))

        batch_list = [
            new_emails[i:i + 50]
            for i
            in range(0, len(new_emails), 50)
        ]
        for email_batch in batch_list:
            batch = service.new_batch_http_request(callback=add_callback)
            for email in email_batch:
                s = {
                    "userId": email
                }
                request = service.courses().students().create(
                    courseId=self.g_suite_id,
                    body=s
                )
                batch.add(request, request_id=email)
            batch.execute()

    def g_suite_attendance(self):
        scopes = ['https://www.googleapis.com/auth/classroom.coursework.students']

        credentials = ServiceAccountCredentials._from_parsed_json_keyfile(
            keyfile_dict=settings.KEYFILE_DICT,
            scopes=scopes
        )

        shane = credentials.create_delegated('greenbean@elearnclass.org')
        http_auth = shane.authorize(Http())
        service = discovery.build('classroom', 'v1', http=http_auth)
        raw = {}
        print("Starting", self.title)
        for student in self.get_all_students():
            try:
                if student.student.elearn_record.g_suite_email:
                    print("Fetching", student.student)
                    raw[student] = service.courses(
                    ).courseWork().studentSubmissions().list(
                        courseId=self.g_suite_id,
                        states='RETURNED',
                        courseWorkId='-',
                        userId=student.student.elearn_record.g_suite_email
                    ).execute()
                    print(
                        "Fetched",
                        len(raw[student].get('studentSubmissions', [])),
                        "records"
                    )
            except ObjectDoesNotExist:
                print(student.student, "has no elearn record. Skipping...")
        for key, value in raw.items():
            subs = value.get('studentSubmissions')
            if subs is not None:
                print('Creating attendance for', key.student)
                for sub in subs:
                    try:
                        a = Attendance.objects.create(
                            enrollment=key,
                            attendance_date=datetime.strptime(
                                sub['creationTime'].split('T')[0],
                                "%Y-%m-%d"
                            ).date(),
                            time_in=key.section.start_time,
                            time_out=key.section.start_time,
                            attendance_type='P',
                            att_hours=sub.get('assignedGrade', 0),
                            online=True,
                        )
                        print(a)
                    except IntegrityError:
                        print("Duplicate attendance found. Skipping....")
        print("Finished with", self.title)

    def get_g_suite_link(self):
        scopes = ['https://www.googleapis.com/auth/classroom.courses']

        credentials = ServiceAccountCredentials._from_parsed_json_keyfile(
            keyfile_dict=settings.KEYFILE_DICT,
            scopes=scopes
        )

        shane = credentials.create_delegated('greenbean@elearnclass.org')
        http_auth = shane.authorize(Http())
        service = discovery.build('classroom', 'v1', http=http_auth)

        course = service.courses().get(id=self.g_suite_id).execute()
        self.g_suite_link = course.get('alternateLink')
        self.save()

    # Drops active students with 2 absences and fills their spots with waitlisted students in enrollment order
    def waitlist_update(self):
        dropped = []
        added = []
        for student in self.get_active():
            if student.waitlist_drop():
                dropped.append(str(student.student))
        for student in self.get_waiting():
            if student.add_from_waitlist():
                added.append(str(student.student))
        self.begin()
        if len(dropped) > 0:
            if self.teacher.email:
                send_mail_task.delay(
                    "Delgado Adult Ed Dropped Student Notice | {section} - {day}".format(section=self.title, day=timezone.now().date()),
                    "Hi {teacher},\n"
                    "In accordance with our attendance policy, "
                    "we have dropped the following students from {section}:\n"
                    "{drop}\n"
                    "We have also added the following waitlisted "
                    "students to your active roster:\n"
                    "{add}\n"
                    "All these students listed have been notified "
                    "by email that their status has changed.\n"
                    "Consider calling these newly added students to be sure "
                    "they are aware of the change. Thanks".format(
                        section=self.title,
                        teacher=self.teacher.first_name,
                        drop=dropped,
                        add=added),
                    "admin@dccaep.org",
                    [self.teacher.email, "adulted@dcc.edu"],
                )

    def enforce_attendance(self):
        for student in self.get_active():
            drop_task.delay(enrollment_id=student.id)

    def attendance_reminder(self, send_mail=True):
        today = timezone.now()
        last_week = timezone.now() - td(days=7)
        att_count = Attendance.objects.filter(
            attendance_date__lt=today,
            attendance_date__gte=last_week,
            attendance_type='X',
            enrollment__section=self,
            enrollment__status='A'
        ).count()
        try:
            teacher = self.teacher
            email = teacher.email
        except ObjectDoesNotExist:
            email = ''
        sent = False
        if send_mail and att_count > 0 and email:
                send_mail_task.delay(
                    "Delgado Adult Ed Attendance Reminder {day}".format(day=timezone.now().date()),
                    "Hi {teacher} \n"
                    "\n"
                    "Your attendance for {section} is incomplete.\n"
                    "By updating your attendance in a timely way, "
                    "we are able to ensure that students comply "
                    "with program attendance and testing policies.\n\n"
                    "Please update or check your attendance for accuracy as soon as possible.".format(
                        section=self.title,
                        teacher=self.teacher.first_name
                    ),
                    "admin@dccaep.org",
                    [self.teacher.email],
                )
                sent = True
        return (att_count, sent)

    def get_days(self):
        days = []
        day_map = [
            ('monday', 'M', 0),
            ('tuesday', 'T', 1),
            ('wednesday', 'W', 2),
            ('thursday', 'R', 3),
            ('friday', 'F', 4),
            ('saturday', 'Sa', 5),
            ('sunday', 'Su', 6)
        ]
        for day in day_map:
            field = self._meta.get_field(day[0])
            if getattr(self, field.name):
                days.append(day)
        return days

    def get_days_str(self):
        days = self.get_days()
        days_str = []
        for day in days:
            field = self._meta.get_field(day[0])
            if getattr(self, field.name):
                days_str.append(day[1])
        return "".join(days_str)
    get_days_str.short_description = "Days"

    def get_days_names(self):
        days = [s[0].title() for s in self.get_days()]
        if len(days) > 1:
            out = ", ".join(days[:-1]) +" and "+days[-1]
        elif len(days) == 1:
            out = days[0]
        else:
            out = ""
        return out

    def get_class_dates(self):
        weekdays = [i[2] for i in self.get_days()]
        if self.starting is not None:
            start = self.starting
        else:
            start = self.semester.start_date
        if self.ending is not None:
            end = self.ending
        else:
            end = self.semester.end_date
        class_dates = []
        date_range = end - start
        for j in range(date_range.days + 1):
            d = start + td(days=j)
            if d.weekday() in weekdays:
                class_dates.append(d)
        return class_dates

    def get_daily_attendance_rate(self):
        days = len(self.get_class_dates())
        rates = []
        if self.students.all().count() > 0:
            att_matrix = [
                [att.attendance_type for att in student.attendance.all()]
                for student
                in self.students.all()
            ]
            days_range = min(days, max([len(row) for row in att_matrix]))
            daily_matrix = [
                [row[i] if len(row) > i else 'X' for row in att_matrix]
                for i
                in range(days)
            ]
            rates = [
                "{:.0%}".format(
                    round(len([att for att in row if att =='P']) / len(row), 2)
                )
                if len(row) > 0 else 0
                for row
                in daily_matrix
            ]
        return rates

class Enrollment(models.Model):

    ACTIVE = 'A'
    WAITING = 'W'
    WITHDRAWN = 'R'
    DROPPED = 'D'
    COMPLETED = 'C'
    STATUS_CHOICES = (
        (ACTIVE, 'Active'),
        (WAITING, 'Waitlist'),
        (WITHDRAWN, 'Withdrawn'),
        (DROPPED, 'Dropped'),
        (COMPLETED, 'Completed'),
    )
    student = models.ForeignKey(
        Student,
        models.CASCADE,
        related_name='classes'
    )
    section = models.ForeignKey(
        Section,
        models.PROTECT,
        related_name='students'
    )
    creator = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        models.PROTECT,
        related_name='enrollment_records'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='A'
    )
    modified_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        models.PROTECT,
        related_name='modified_enrollments',
        null=True
    )
    created = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now=True)
    schedule_sent = models.BooleanField(default=False)

    class Meta:
        unique_together = ('student', 'section')

    def __str__(self):
        name = self.student_name()
        section = self.class_name()
        return name + ": enrolled in " + section

    def get_absolute_url(self):
        return reverse('sections:enrollment detail', kwargs={'pk': self.pk})

    def student_name(self):
        name = self.student.__str__()
        return name

    def class_name(self):
        name = self.section.title
        return name

    def times_attended(self):
        return self.attendance.filter(attendance_type='P').count()

    def times_absent(self):
        return self.attendance.filter(attendance_type='A').count()

    def last_attended(self):
        return self.attendance.filter(attendance_type='P').latest('attendance_date').attendance_date

    def get_attendance(self):
        return self.attendance.order_by('attendance_date')

    def total_hours(self):
        hours = sum([att.hours for att in self.attendance.filter(attendance_type='P')])
        return round(hours, 2)

    def get_skill_masteries(self):
        masteries = apps.get_model('academics', 'SkillMastery').objects.filter(
            student=self.student,
            skill__in=self.section.course.skills.all()
        )
        return masteries

    # Creates related attendance objects for student enrollment with correct dates and pending status
    def activate(self):
        dates = self.section.get_class_dates()
        created_dates = self.attendance.dates('attendance_date', 'day')
        new_dates = [x for x in dates if x not in created_dates]
        online = self.section.program == 'ELRN' or self.section.site.code == 'OL'
        for day in new_dates:
            a = Attendance.objects.create(
                enrollment=self,
                attendance_date=day,
                time_in=self.section.start_time,
                time_out=self.section.end_time,
                online=online
            )
            a.save()
        if self.section.course is not None:
            sm = apps.get_model('academics', 'SkillMastery')
            for skill in self.section.course.skills.all():
                if sm.objects.filter(skill=skill, student=self.student).count() == 0:
                    sm.objects.create(
                        skill=skill,
                        student=self.student,
                        certifier=self.section.teacher,
                        cert_date=dates[0]
                    )

    # Drops students who have missed first two class periods
    def waitlist_drop(self):
        absent = self.times_absent()
        present = self.times_attended()
        needs_test = False
        if self.student.testing_status() == "Test Needed":
            needs_test = True
        if absent > 1 and present < 1 and needs_test:
            self.status = "D"
            self.save()
            if self.student.email:
                send_mail_task.delay(
                    subject="We're sorry {student}, but you've been dropped from {section}".format(
                        student=self.student.first_name,
                        section=self.section.title),
                    message="According to our attendance policy, "
                    "students who miss the first two class periods "
                    "are dropped to make room for waitlisted students.\n"
                    "Please stop by our main office or call "
                    "504-671-5434 for more information.",
                    from_email="enrollment_robot@elearnclass.org",
                    recipient_list=[self.student.email],
                )
            return True
        return False

    # Adds students to active roster if class space exists
    def add_from_waitlist(self):
        if not self.section.is_full:
            self.status = 'A'
            self.save()
            if self.student.email:
                send_mail_task.delay(
                    subject="Good News! You've been added to {section}".format(
                        section=self.section.title
                    ),
                    message="""Hi {student} \n"
                    The wait is over!  A seat is open in {teacher}'s {section}.
                    Please visit {site},  Room {room} on {days} at {start_time} to begin class.
                    If you have any questions, please call the office at 504-671-5434.
                    """.format(
                            student=self.student.first_name,
                            teacher=self.section.teacher.first_name,
                            site = self.section.site.name,
                            room = self.section.room,
                            days = self.sections.get_days_names(),
                            start_time = self.section.start_time,
                            section=self.section.title
                        ),
                    from_email="enrollment_robot@elearnclass.org",
                    recipient_list=[self.student.email],
                )
            return True
        return False

    # Check attendance for attendance policy compliance - change enrollment status if needed
    def attendance_drop(self):
        absences = self.times_absent()
        policy = self.section.semester.allowed_absences
        if absences > policy:
            self.status = 'D'
            self.save()
            if self.student.email:
                send_mail_task.delay(
                    subject="We're sorry {student}, but you've been dropped from {section}".format(
                        student=self.student.first_name,
                        section=self.section.title),
                    message="According to our program's attendance policy, "
                    "students who miss a class more than 4 times "
                    "will be dropped from that class. "
                    "You're still part of our program, you're just dropped from this class.\n"
                    "Please stop by our main office or call "
                    "504-671-5434 for more information.",
                    from_email="enrollment_robot@elearnclass.org",
                    recipient_list=[self.student.email]
                )
            return True
        else:
            return False

    def welcome_email(self):
        try:
            g_suite_email = self.student.elearn_record.g_suite_email
        except ObjectDoesNotExist:
            g_suite_email = ''
        emails = [g_suite_email, self.student.email]
        recipients = [email for email in emails if email != '']
        if len(recipients) > 0:
            send_mail_task.delay(
                subject="Delgado Adult Education - Welcome to the new session! ¡Bienvenido a la nueva sesión!",
                message="",
                html_message="<p>Dear Students,</p><p>We are excited to have you back "
                "online with us for another session. If you’re joining us for the first "
                "time, welcome!</p><p>As an update, classes are live now. You can login "
                "to <a href='http://classroom.google.com'>Google Classroom</a> to get "
                "started with your new classes.</p><p><strong>How to login</strong><br>"
                "You can use your school account to login to Google Classroom: "
                "<strong>{g_suite_email}</strong></p><p><strong>Questions?</strong><br>"
                "If you have any questions, including how to reset your password, "
                "please reach out to your teachers or coach. You can also email our help "
                "desk anytime at <a href='mailto:coach@elearnclass.org'>coach@elearnclass.org"
                "</a></p><p>We look forward to working with you this session</p><p>"
                "Be safe and stay healthy!</p><p>All the very best,<br>Delgado Adult "
                "Education Program</p><hr>"
                "<p>Queridos estudiantes,</p><p>Estamos emocionados de tenerles nuevamente en"
                " línea con nosotros para otra sesión. Si te unes a nosotros por la primera "
                "vez, ¡Bienvenido!</p><p>Las clases están en vivo ahora. Puede iniciar su sesión en "
                "<a href='http://classroom.google.com'>Google Classroom</a> para comenzar con sus "
                "nuevas clases.</p><p><strong>Cómo iniciar sesión</strong><br>"
                "Puede usar su cuenta del colegio para iniciar sesión en Google Classroom: "
                "<strong>{g_suite_email}</strong></p><p><strong>Preguntas?</strong><br>"
                "Si tiene alguna pregunta, incluido cómo restablecer su contraseña, comuníquese "
                "con sus maestros o entrenador. También puede enviar un correo electrónico a "
                "nuestro servicio de asistencia en cualquier momento a "
                "<a href='mailto:coach@elearnclass.org'>coach@elearnclass.org"
                "</a></p><p>Esperamos con interés trabajar con usted en esta sesión.</p><p>"
                "¡Esté seguro y manténgase saludable!</p><p>Todo lo mejor,<br>Programa de "
                "educación para adultos Delgado</p>".format(g_suite_email=g_suite_email),
                from_email="enrollment_robot@elearnclass.org",
                recipient_list=recipients,
            )

    def save(self, *args, **kwargs):
        mod = timezone.now().date()
        if self.section.starting is not None:
            start = self.section.starting
        else:
            start = self.section.semester.start_date
        if self.section.ending is not None:
            end = self.section.ending
        else:
            end = self.section.semester.end_date
        if mod > start and mod < end and self.status is not self.COMPLETED:
            status = self.get_status_display()
            enrollment_notification_task.delay(self.id, status)
        super(Enrollment, self).save(*args, **kwargs)

class Attendance(models.Model):

    PRESENT = 'P'
    ABSENT = 'A'
    PENDING = 'X'
    CANCELLED = 'C'
    TYPE_CHOICES = (
        (PRESENT, 'Present'),
        (ABSENT, 'Absent'),
        (PENDING, '-----'),
        (CANCELLED, 'Cancelled'),
    )
    enrollment = models.ForeignKey(
        Enrollment,
        models.CASCADE,
        related_name='attendance'
    )
    attendance_type = models.CharField(
        max_length=1,
        choices=TYPE_CHOICES,
        default='X'
    )
    attendance_date = models.DateField()
    time_in = models.TimeField(
        blank=True,
        null=True
    )
    time_out = models.TimeField(
        blank=True,
        null=True
    )
    att_hours = models.FloatField(
        blank=True,
        null=True
    )
    online = models.BooleanField(
        default=False)
    notes = models.CharField(
        max_length=80,
        blank=True,
    )

    class Meta:
        ordering = ['attendance_date', ]
        unique_together = ('enrollment', 'attendance_date', 'att_hours')

    def __str__(self):
        s = str(self.enrollment.student)
        d = self.attendance_date.strftime('%Y-%m-%d')
        t = self.get_attendance_type_display()
        return " | ".join([d, s, t])

    def get_absolute_url(self):
        return reverse(
            'sections:single attendance',
            kwargs={
                'slug': self.enrollment.section.slug,
                'pk': self.pk
            }
        )

    @property
    def hours(self):
        if self.att_hours is not None:
            return self.att_hours
        else:
            if self.attendance_type == 'P':
                d1 = datetime.combine(self.attendance_date, self.time_in)
                d2 = datetime.combine(self.attendance_date, self.time_out)
                delta = d2 - d1
                hours = delta.total_seconds() / 3600
                return float("{0:.2f}".format(hours))
            return 0

    @property
    def enrolled_hours(self):
        d1 = datetime.combine(self.attendance_date, self.time_in)
        d2 = datetime.combine(self.attendance_date, self.time_out)
        delta = d2 - d1
        hours = delta.total_seconds() / 3600
        return float("{0:.2f}".format(hours))

    def save(self, *args, **kwargs):
        super(Attendance, self).save(*args, **kwargs)
        if self.attendance_type == 'P':
            pop_update_task.delay(self.enrollment.student.id, self.attendance_date)

class Message(models.Model):

    title = models.CharField(
        max_length=100
    )

    sections = models.ManyToManyField(
        Section,
    )

    message = models.CharField(
        max_length=160
    )

    sent = models.DateTimeField(
        blank=True,
        null=True
    )

    class Meta:
        ordering = ["title"]

    def __str__(self):
        return self.title

    def send_message(self):
        sections = self.sections.all()
        students = apps.get_model('people', 'Student').objects.filter(
            classes__section__in=sections
        ).distinct()
        for student in students:
            send_sms_task.delay(
                dst=student.phone,
                message=self.message
            )
        self.sent = timezone.now()
        self.save()

class Cancellation(models.Model):

    section = models.ForeignKey(
            Section,
            models.PROTECT,
            related_name = 'cancellations',
        )

    cancellation_date = models.DateField()

    cancelled_by = models.ForeignKey(
            settings.AUTH_USER_MODEL,
            models.PROTECT,
            related_name = 'cancellations'
    )

    notification_sent = models.BooleanField(
        default=False
    )

    send_notification = models.BooleanField(
        default=False
    )

    def __str__(self):
        date = self.cancellation_date.strftime('%Y-%m-%d')
        return "|".join([date, self.section.__str__()])


'''
VIEW FILE

A simple prototype of a TV controller in Python
'''

import tkinter as tk
from tkinter import ttk, messagebox
import pult_C as p_C

class C_view:
    def __init__(self, cont):
        '''
        :param cont: controller
        '''
        self.cont = cont(self)

    def show(self):
        '''
        Building and displaying the user's workspace
        '''

        # creates a workspace
        self.root = tk.Tk()
        self.root.title('Pult')

        # center the window
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        self.root.geometry(f'250x600+{(screen_width // 2) - 125}+{(screen_height // 2) - 300}')
        self.root.grid()
        self.root.grid_columnconfigure(0, weight=1)

        # creates the styles
        s = ttk.Style()
        s.configure('B.TButton', font=('', 15), width=10)
        s.configure('CH.TButton', font=('', 15), width=4)
        s.configure('num.TButton', font=('', 15), width=4)
        s.configure('Num.TLabel', font=('', 25), width=10, anchor=tk.N)
        s.configure('Txt.TLabel', font=('', 25), width=10, relief='solid', anchor=tk.N)
        s.configure('CH.TLabel', width=5, height=10, relief='solid', anchor=tk.N)

        # Creates the main geometry
        fr = ttk.Frame(self.root)
        fr.grid()

        # Labels for showing the result
        self.lb_n = ttk.Label(fr, style='Num.TLabel', text='---')
        self.lb_n.grid(row=0, pady=5, columnspan=3)
        self.lb_name = ttk.Label(fr, style='Txt.TLabel', text='---')
        self.lb_name.grid(row=1, pady=5, columnspan=3)

        # Control buttons
        ON_bt = ttk.Button(fr, text='ON/OFF', style='B.TButton', command=lambda: self.cont.start())
        ON_bt.grid(row=3, pady=5, columnspan=3)

        bt1 = ttk.Button(fr, text='1', style='num.TButton', command=lambda: self.cont.set(1))
        bt1.grid(row=4, column=0, pady=5, padx=5)
        bt2 = ttk.Button(fr, text='2', style='num.TButton', command=lambda: self.cont.set(2))
        bt2.grid(row=4, column=1, pady=5, padx=5)
        bt3 = ttk.Button(fr, text='3', style='num.TButton', command=lambda: self.cont.set(3))
        bt3.grid(row=4, column=2, pady=5, padx=5)

        bt4 = ttk.Button(fr, text='4', style='num.TButton', command=lambda: self.cont.set(4))
        bt4.grid(row=5, column=0, pady=5, padx=5)
        bt5 = ttk.Button(fr, text='5', style='num.TButton', command=lambda: self.cont.set(5))
        bt5.grid(row=5, column=1, pady=5, padx=5)
        bt6 = ttk.Button(fr, text='6', style='num.TButton', command=lambda: self.cont.set(6))
        bt6.grid(row=5, column=2, pady=5, padx=5)

        bt7 = ttk.Button(fr, text='7', style='num.TButton', command=lambda: self.cont.set(7))
        bt7.grid(row=6, column=0, pady=5, padx=5)
        bt8 = ttk.Button(fr, text='8', style='num.TButton', command=lambda: self.cont.set(8))
        bt8.grid(row=6, column=1, pady=5, padx=5)
        bt9 = ttk.Button(fr, text='9', style='num.TButton', command=lambda: self.cont.set(9))
        bt9.grid(row=6, column=2, pady=5, padx=5)

        # at the moment it's impossible to turn on the channel with the #10+ by number
        bt0 = ttk.Button(fr, text='0', style='num.TButton', command=lambda: self.cont.set(0), state='disabled')
        bt0.grid(row=7, column=1, pady=5, padx=5)

        ch_lb = ttk.Label(fr, style='CH.TLabel')
        ch_lb.grid(row=8, column=0, pady=5, padx=5, rowspan=2)
        bt_next = ttk.Button(ch_lb, text='CH+', style='CH.TButton', command=self.cont.next)
        bt_next.grid(row=8, pady=5, padx=5)
        bt_back = ttk.Button(ch_lb, text='CH-', style='CH.TButton', command=self.cont.prev)
        bt_back.grid(row=9, pady=5, padx=5)

        # No volume yet
        vol = ttk.Label(fr, style='CH.TLabel')
        vol.grid(row=8, column=2, pady=5, padx=5, rowspan=2)
        bt_vol_m = ttk.Button(vol, text='V+', style='CH.TButton', state='disabled')
        bt_vol_m.grid(row=8, column=0, pady=5, padx=5)
        bt_vol_l = ttk.Button(vol, text='V-', style='CH.TButton', state='disabled')
        bt_vol_l.grid(row=9, column=0, pady=5, padx=5)

        # Empty label for geometry
        lb_emp = ttk.Label(fr, style='Num.TLabel', text='')
        lb_emp.grid(row=10, pady=5, columnspan=3)

        # Entry form for setting channels by number or name
        chan = tk.StringVar()
        self.p_e = tk.Entry(fr, width=11, font=('', 25, 'bold'), textvariable=chan, justify='center')
        self.p_e.grid(row=11, pady=5, columnspan=3)
        inp_bt = ttk.Button(fr, text='OK', style='B.TButton', command=lambda: self.cont.find(chan.get()))
        inp_bt.grid(row=12, pady=5, columnspan=3)

        self.root.mainloop()

    def msg(self, info):
        '''
        error message
        '''
        messagebox.showerror(title='Error', message=info)

    def update(self, ch, num):
        '''
        View updating method
        :param ch: current channel name
        :param num: current channel number
        '''
        self.lb_name['text'] = ch
        self.lb_n['text'] = num

    def stop(self):
        self.root.destroy()

# Connecting to the controller
sony = C_view(p_C.Controller)

# starting
sony.show()


#!/usr/bin/python
# -*- coding: utf-8 -*-
#File Name: parameter_comparison.py

#**************************************************************************************************************
#*  AUTHOR IDENTITY:
#*-------------------------------------------------------------------------------------------------------------
#*  Full Name:                        Last Name                            Company
#*-------------------------------------------------------------------------------------------------------------
#*  Mac Tien Truong                     Truong                             Hitachi
#
#*  REVISION HISTORY
#*-------------------------------------------------------------------------------------------------------------
#*  Verion                            Date            Auhor               Description
#*-------------------------------------------------------------------------------------------------------------
#*  1.0.                             2020-Mar-24      Truong            Compare parameters from configuration Obj
#*                                                                      to get the common paramters and individual
#*                                                                      parents of each SIP
#*
#**************************************************************************************************************/
import os
import sys
from Tool.lib import common
from Tool import parameter_creation as PAR_CR

#============================= Get the common configuration of provided modue in all SIPs ======================
#===============================================================================================================
def getCommonParametersOfTwoSIP(SIP1_Obj, SIP2_Obj, common_Obj):
    """This function is used to get the common parameters of 2 provided SIPs"""

    #Define local variables here
    l_SIP1_Obj = SIP1_Obj
    l_SIP2_Obj = SIP2_Obj
    l_containerObj = common_Obj

    for l_each_ecu_SIP1 in l_SIP1_Obj.ecuc_container_list:
        for l_each_ecu_SIP2 in l_SIP2_Obj.ecuc_container_list:
            if(l_each_ecu_SIP1.ecu_container_name == l_each_ecu_SIP2.ecu_container_name):
                l_new_ecu_obj = PAR_CR.EcucContainerObj()
                l_new_ecu_obj.ecu_node_deep = l_each_ecu_SIP1.ecu_node_deep
                l_new_ecu_obj.ecu_container_name = l_each_ecu_SIP1.ecu_container_name
                l_new_ecu_obj.node_Description = l_each_ecu_SIP1.node_Description
                l_new_ecu_obj.number_of_parameters = l_each_ecu_SIP1.number_of_parameters
                l_new_ecu_obj.number_of_subcontainer = l_each_ecu_SIP1.number_of_subcontainer
                l_new_ecu_obj.parameters_list = []
                l_new_ecu_obj.sub_container_list = []
                for l_eac_parameter_SIP1 in l_each_ecu_SIP1.parameters_list:
                    for l_eac_parameter_SIP2 in l_each_ecu_SIP2.parameters_list:
                        if(l_eac_parameter_SIP1.parameter_name == l_eac_parameter_SIP2.parameter_name):
                            l_new_pare_ojb = PAR_CR.parameterObj()
                            l_new_pare_ojb.parameter_list_value = []
                            l_new_pare_ojb.parameter_deep = l_eac_parameter_SIP1.parameter_deep
                            l_new_pare_ojb.parameter_name = l_eac_parameter_SIP1.parameter_name
                            l_new_pare_ojb.parameter_description = l_eac_parameter_SIP1.parameter_description
                            l_new_pare_ojb.parameter_type = l_eac_parameter_SIP1.parameter_type
                            l_new_pare_ojb.parameter_list_value = l_eac_parameter_SIP1.parameter_list_value
                            l_new_pare_ojb.parameter_max = l_eac_parameter_SIP1.parameter_max
                            l_new_pare_ojb.parameter_min = l_eac_parameter_SIP1.parameter_min
                            l_new_pare_ojb.parameter_default = l_eac_parameter_SIP1.parameter_default
                            l_new_ecu_obj.parameters_list.append(l_new_pare_ojb)

                l_containerObj.ecuc_container_list.append(l_new_ecu_obj)
                for l_each_subContainer_SIP1 in l_each_ecu_SIP1.sub_container_list:
                    for l_each_subContainer_SIP2 in l_each_ecu_SIP2.sub_container_list:
                        l_new_container = PAR_CR.containerObj()
                        l_new_container.ecuc_container_list = []
                        l_new_container.number_of_ecuc_containers = 0
                        l_new_container.container_deep = l_each_ecu_SIP1.ecu_node_deep + 1
                        getCommonParametersOfTwoSIP(l_each_subContainer_SIP1, l_each_subContainer_SIP2, l_new_container)
                        if(len(l_new_container.ecuc_container_list) != 0):
                            l_new_ecu_obj.sub_container_list.append(l_new_container)
                break

    return()

#======================= Get the individual configuration of provided modue in selected SIP ====================
#===============================================================================================================
def getIndividualParametersOfSIP(Search_SIP_Obj, common_Obj, individual_obj):
    """This function is used to get the individual parameters of module in selected SIP that compare to common configuration """

    l_Search_SIP_Obj = Search_SIP_Obj
    l_common_Obj = common_Obj
    l_individual_obj = individual_obj

    for l_each_ecu_search_SIP in l_Search_SIP_Obj.ecuc_container_list:
        l_new_ecu_obj = PAR_CR.EcucContainerObj()
        l_new_ecu_obj.ecu_node_deep = l_each_ecu_search_SIP.ecu_node_deep
        l_new_ecu_obj.ecu_container_name = l_each_ecu_search_SIP.ecu_container_name
        l_new_ecu_obj.node_Description = l_each_ecu_search_SIP.node_Description
        l_new_ecu_obj.number_of_parameters = l_each_ecu_search_SIP.number_of_parameters
        l_new_ecu_obj.number_of_subcontainer = l_each_ecu_search_SIP.number_of_subcontainer
        l_new_ecu_obj.parameters_list = []
        l_new_ecu_obj.sub_container_list = []
        l_ecu_found = False
        for l_each_ecu_common_obj in l_common_Obj.ecuc_container_list:
            if(l_each_ecu_search_SIP.ecu_container_name == l_each_ecu_common_obj.ecu_container_name):
                l_ecu_found = True
                break
        if(l_ecu_found == False):
            #In case the sub-container does not have in common object
            #print("======= Note: This container/sub-container below is not contained in common configuration ========")
            #print(l_each_ecu_search_SIP.ecu_container_name)
            l_new_ecu_obj.parameters_list= l_each_ecu_search_SIP.parameters_list
            l_new_ecu_obj.sub_container_list = l_each_ecu_search_SIP.sub_container_list
            l_individual_obj.ecuc_container_list.append(l_new_ecu_obj)
        else:
            #If found then search its parameters
            for l_each_search_para in l_each_ecu_search_SIP.parameters_list:
                l_para_found = False
                for l_each_common_para in l_each_ecu_common_obj.parameters_list:
                    if(l_each_search_para.parameter_name == l_each_common_para.parameter_name):
                        l_para_found = True
                        break
                #Add the parameter that is not stored in the common object to individual object
                if (l_para_found == False):
                    l_new_pare_ojb = PAR_CR.parameterObj()
                    l_new_pare_ojb.parameter_list_value = []
                    l_new_pare_ojb.parameter_deep = l_each_search_para.parameter_deep
                    l_new_pare_ojb.parameter_name = l_each_search_para.parameter_name
                    l_new_pare_ojb.parameter_description = l_each_search_para.parameter_description
                    l_new_pare_ojb.parameter_type = l_each_search_para.parameter_type
                    l_new_pare_ojb.parameter_list_value = l_each_search_para.parameter_list_value
                    l_new_pare_ojb.parameter_max = l_each_search_para.parameter_max
                    l_new_pare_ojb.parameter_min = l_each_search_para.parameter_min
                    l_new_pare_ojb.parameter_default = l_each_search_para.parameter_default
                    l_new_ecu_obj.parameters_list.append(l_new_pare_ojb)

            l_individual_obj.ecuc_container_list.append(l_new_ecu_obj)
            #Continue to search in the sub-containers
            for l_each_search_sub in l_each_ecu_search_SIP.sub_container_list:
                for l_each_common_sub in l_each_ecu_common_obj.sub_container_list:
                    l_new_container = PAR_CR.containerObj()
                    l_new_container.ecuc_container_list = []
                    l_new_container.number_of_ecuc_containers = 0
                    l_new_container.container_deep = l_each_ecu_search_SIP.ecu_node_deep + 1
                    getIndividualParametersOfSIP(l_each_search_sub, l_each_common_sub, l_new_container)
                    l_new_ecu_obj.sub_container_list.append(l_new_container)

    return()


import tensorflow as tf
import numpy as np
import random
import os
from make_sets import Setmaker as SM
class Hyperparameters:
    INPUT_LAYER = 43
    HIDDEN_LAYER = 100 #Modify??
    OUTPUT_LAYER = 3
    NUM_EPOCHS = 10000
    #NUM_EPOCHS = 1
    BATCH_NUMBER = 240
    LEARNING_RATE = 0.1
    VALIDATION_NUMBER = 30
    TEST_NUMBER = 30

class Information:
    INPUT_DIMENSIONS = 43
    INPUT_TIME_DIV = 0.125
    INPUT_SECTORS = 8
    SAMPLE_RATE = 4096

summed_loss =0
reported_sum_loss = 0
set_maker = SM()
HYP = Hyperparameters()
prediction_dictionary = {0:"inhale", 1:"exhale", 2:"unknown"}

W_In = tf.Variable(tf.random_normal(shape = [HYP.INPUT_LAYER,HYP.HIDDEN_LAYER], stddev = 0.1, mean = 0 ),name = "W_In")#note: this used to have a mean of zero, so check that
W_Hidd =tf.Variable(tf.random_normal(shape = [HYP.HIDDEN_LAYER,HYP.HIDDEN_LAYER], stddev = 0.1, mean =0  ),name = "W_Hidd")
W_Out =tf.Variable(tf.random_normal(shape = [HYP.HIDDEN_LAYER,HYP.OUTPUT_LAYER], stddev = 0.1, mean = 0),name = "W_Out")

B_In = tf.Variable(tf.zeros(HYP.HIDDEN_LAYER),name = "B_In")
B_Hidd = tf.Variable(tf.zeros(HYP.HIDDEN_LAYER), name = "B_Hidd")
B_Out = tf.Variable(tf.zeros(HYP.OUTPUT_LAYER), name = "B_Out")

with tf.name_scope("placeholders"):
    X = tf.placeholder(shape=[1,HYP.INPUT_LAYER],name = "input_placeholder",dtype = tf.float32)
    Y = tf.placeholder(shape=[1,HYP.OUTPUT_LAYER],name = "one_hot_labels_placeholder",dtype = tf.int8)
    last_hidd = tf.placeholder(shape=[1,HYP.HIDDEN_LAYER],name = "previous_hidden_layer_placeholder", dtype = tf.float32)

#with tf.device("/device:GPU:0"):
with tf.name_scope("input_propagation"):
    hidd_layer = tf.matmul(X,W_In)
    hidd_layer = tf.add(hidd_layer,B_In)

with tf.name_scope("hidden_propagation"):
    propagated_prev_hidd_layer = tf.matmul(last_hidd,W_Hidd)
    propagated_prev_hidd_layer = tf.add(propagated_prev_hidd_layer,B_Hidd)
    concat_hidd_layer = tf.add(hidd_layer,propagated_prev_hidd_layer)
    concat_hidd_layer = tf.sigmoid(concat_hidd_layer,name = "hidden_layer_propagation")
    next_hidd_layer = concat_hidd_layer

with tf.name_scope("logit_output"):
    output_logit = tf.matmul(concat_hidd_layer,W_Out)
    output_logit = tf.add(output_logit, B_Out)

with tf.name_scope("prediction_and_loss"):
    output_prediction = tf.nn.softmax(output_logit, name = "output")
    loss = tf.nn.softmax_cross_entropy_with_logits(logits = output_logit,labels=Y,name = "sparse_softmax_loss_function")
    total_loss = tf.reduce_mean(loss)
with tf.name_scope("train"):
    optimizer = tf.train.AdagradOptimizer(learning_rate=HYP.LEARNING_RATE).minimize(total_loss)

with tf.name_scope("summaries_and_saver"):

    tf.summary.histogram("W_Hidd", W_Hidd)
    tf.summary.histogram("W_In", W_In)
    tf.summary.histogram("W_Out", W_Out)

    tf.summary.histogram("B_Hidd", B_Hidd)
    tf.summary.histogram("B_In", B_In)
    tf.summary.histogram("B_Out", B_Out)

    tf.summary.scalar("Loss_at_sample",total_loss)

    summary_op = tf.summary.merge_all()
    saver = tf.train.Saver()

with tf.Session() as sess:
    tf.train.write_graph(sess.graph_def, 'GraphV2/GRAPHS/', 'graph.pbtxt')