import random
import time

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

gDoWeNeedToInitialize    = True
gVertexToIncomingEdgeList = {}

############################################################################################
######################################### Basic Practices###################################
############################################################################################

def basic_matrix_operation():
    """"Basic matrix operations understanding and practice."""

    print(">> basic_matrix_operation")

    # seeds for reproducibility
    np.random.seed(0)

    x1 = np.random.randint(10, size = 6)      #1x6 matrix
    x2 = np.random.randint(10, size =(3,4))   #3x4 matrix
    x3 = np.random.randint(10, size =(4,4))   #4x4 matrix

    print("x1 ndim: ", x1.ndim)
    print("x2 shape:", x2.shape)
    print("x3 size: ", x3.size)

    # lets learn some slice stuff.
    # x[start:stop:step]
    # default start = 0
    # stop = size of dimenson
    # step = 1
    # x[::-1] means x[0:len:-1]
    # This means it would print the reverese list
    print(x1[::-1])

    print("<< basic_matrix_operation")

def create_adjacency_matrix_helper(fvVerticesCount, fvEdgeList):
    """create_adjacency_matrix_helper"""

    # intialize tvA matrix with fvVerticesCountxfvVerticesCount length
    tvA = np.zeros(shape=(fvVerticesCount,fvVerticesCount))

    # now traverse the graph and update edge connection values if any.
    for  (i,j) in fvEdgeList:
        tvA[i,j] = 1

    return tvA

def create_adjacency_list_helper(fvVerticesCount, fvEdgeList):
    """ create_adjacency_list_helper """

    tvAdjacencyList = {}
    for index in range(0, fvVerticesCount):
        tvAdjacencyList[index]= []

    # let us traverse the graph and insert the data.
    for index in range(0, len(fvEdgeList)):
        tvValue = fvEdgeList[index]
        i = tvValue[0]
        j = tvValue[1]
        tvIndexValueList = tvAdjacencyList[i]
        tvIndexValueList.append(j)
        tvAdjacencyList[i] = tvIndexValueList

    # for index in range(0, fvVerticesCount):
    #     print(str(index) + ": " +  tvAdjacencyList[index].__str__() )

    return tvAdjacencyList

#########
# Graph#1
#########

#            0
#            |
#           \|/
#   1       2
#    \     / \                  8
#     \>3</   \>4               |
#       \     /                \|/
#        \>5</                  9
#          | \                  |
#         \|/   \               |
#          6       \            |
#          |          \         |
#         \|/             \    \|/
#          7                \> 10
#           \                  |
#            \                \|/
#             \                11
#               \              |
#                 \            |
#                    \         |
#                      \       |
#                        \    \|/
#                          \ > 12
#                              |
#                             \|/
#                             13

# Adjacency Matrix representation of above graph in memory

#   [
#   [0  0  1  0  0  0  0  0  0  0  0  0  0  0]
#   [0  0  0  1  0  0  0  0  0  0  0  0  0  0]
#   [0  0  0  1  1  0  0  0  0  0  0  0  0  0]
#   [0  0  0  0  0  1  0  0  0  0  0  0  0  0]
#   [0  0  0  0  0  1  0  0  0  0  0  0  0  0]
#   [0  0  0  0  0  0  1  0  0  0  1  0  0  0]
#   [0  0  0  0  0  0  0  1  0  0  0  0  0  0]
#   [0  0  0  0  0  0  0  0  0  0  0  0  1  0]
#   [0  0  0  0  0  0  0  0  0  1  0  0  0  0]
#   [0  0  0  0  0  0  0  0  0  0  1  0  0  0]
#   [0  0  0  0  0  0  0  0  0  0  0  1  0  0]
#   [0  0  0  0  0  0  0  0  0  0  0  0  1  0]
#   [0  0  0  0  0  0  0  0  0  0  0  0  0  1]
#   [0  0  0  0  0  0  0  0  0  0  0  0  0  0]
#   ]

# Adjacency List representation of above graph in memory

# 0: [2]
# 1: [3]
# 2: [3, 4]
# 3: [5]
# 4: [5]
# 5: [6, 10]
# 6: [7]
# 7: [12]
# 8: [9]
# 9: [10]
# 10: [11]
# 11: [12]
# 12: [13]
# 13: []

def create_graph_into_adjacency_matrix_or_list_one(fvType):
    """" create_graph_into_adjacency_matrix_or_list_one """

    # Number of vertices.
    tvVerticesCount = 14

    # represent a graph relation between the vertices and edge connection
    tvEdges = [(0,2),
               (1,3),
               (2,3), (2,4),
               (3,5),
               (4,5),
               (5,6), (5,10),
               (6,7),
               (7,12),
               (8,9),
               (9,10),
               (10,11),
               (11, 12),
               (12, 13)
               ]

    if(fvType == "matrix"):
        return create_adjacency_matrix_helper(tvVerticesCount, tvEdges)
    elif(fvType == "list"):
        return create_adjacency_list_helper(tvVerticesCount, tvEdges)
    else:
        return None

#########
# Graph#2
#########

#           >0
#          / >/\
#         /  /  \
#        /  /    >1
#       /  /    /
#      /  /   /
#     /  /_ _/_ _ _ _
#     |    /        /
#     2 < /       /
#     /         /
#    /        /
#   /  <----/
#  4 <- - - - - - - - -> 3
# <\                 >/  \
#   \               /      \
#     \            /        \>
#      \          5<- - - - -6
#       \        / <\
#         \     /    \
#         >\  </      \
#          7 / - -- - ->8
#                      >/
#                     /
#                    /
#                   /
#                 </
#                 9

def create_graph_into_adjacency_matrix_or_list_two(fvType):
    """" create_graph_into_adjacency_matrix_or_list_two """

    # Number of vertices.
    tvVerticesCount = 10

    # represent a graph relation between the vertices and edge connection
    tvEdges = [(0,1),(0,4),
               (1,2),
               (2,0),
               (3,4), (3,6),
               (4,0), (4,3), (4,7),
               (5,3), (5,7),
               (6,5),
               (7,4), (7,8),
               (8,5), (8,9),
               (9,8)
               ]

    if(fvType == "matrix"):
        return create_adjacency_matrix_helper(tvVerticesCount, tvEdges)
    elif(fvType == "list"):
        return create_adjacency_list_helper(tvVerticesCount, tvEdges)
    else:
        return None

#########
# Graph#3
#########

#   0---->1
#   |
#   |
#  \|/
#   2----> 4
#   |
#   |
#  \|/
#   3
#

def create_graph_into_adjacency_matrix_or_list_three(fvType):
    """" create_graph_into_adjacency_matrix_or_list_three """

    # Number of vertices.
    tvVerticesCount = 5

    # represent a graph relation between the vertices and edge connection
    tvEdges = [(0,1),(0,2),

               (2,3), (2,4)

               ]

    if(fvType == "matrix"):
        return create_adjacency_matrix_helper(tvVerticesCount, tvEdges)
    elif(fvType == "list"):
        return create_adjacency_list_helper(tvVerticesCount, tvEdges)
    else:
        return None

#########
# Graph#4
#########

#   0----->1        2- - - - - - ->3
#   |               |<\          /
#   |               |    \       /
#  \|/             \|/      \   </
#   4      5        6--------->\> 7
#   |<\           /|\         /  |
#   |   \           |        /   |
#   |    \          |       /    |
#  \|/    \        |<--- /     \|/
#   8----->9       10           11
#

def create_graph_into_adjacency_matrix_or_list_four(fvType):
    """" create_graph_into_adjacency_matrix_or_list_four """

    # Number of vertices.
    tvVerticesCount = 12

    # represent a graph relation between the vertices and edge connection
    tvEdges = [(0,1),(0,4),

               (2,3), (2,6),
               (3,7),
               (4,8),

               (6,7),
               (7,2), (7,10), (7,11),
               (8,9),
               (9,4),
               (10,6)
               ]

    if(fvType == "matrix"):
        return create_adjacency_matrix_helper(tvVerticesCount, tvEdges)
    elif(fvType == "list"):
        return create_adjacency_list_helper(tvVerticesCount, tvEdges)
    else:
        return None

#########
# Graph#5
#########

#       0                 1--------------------
#      /| \             / |                   |
#     /_| _ \ _ _ _ _ _/  |                   |
#   </< |     \           |                   |
#  2    |       \         |                   |
#       |        \> /_ _ _|                   |
#      \|/        4 \                         |
#       3            |                        |
#       | \          |                        |
#       |  \         |_ _ _ _ _ _ _ _         |
#       |   \_ _ _ _ _ _ _ _ _       |        |
#       |                    |       |        |
#      \|/                  \|/      |        |
#       5 ------> 6 -------> 7<------|        |
#                           /|\               |
#                            |_ _ _ _ _ _ _ _ |
#

def create_graph_into_adjacency_matrix_or_list_five(fvType):
    """" create_graph_into_adjacency_matrix_or_list_five """

    # Number of vertices.
    tvVerticesCount = 8

    # represent a graph relation between the vertices and edge connection
    tvEdges = [(0,2),(0,3), (0,4),
               (1,2), (1,7),
               (2,5),
               (3,5),(3,7),
               (4,7),
               (5,6),
               (6,7)

               ]

    if(fvType == "matrix"):
        return create_adjacency_matrix_helper(tvVerticesCount, tvEdges)
    elif(fvType == "list"):
        return create_adjacency_list_helper(tvVerticesCount, tvEdges)
    else:
        return None

class Queue:
    """Queue implementation using list data structures as member. """

    def __init__(self):
        self.ivQueue = []

    def addq(self, fvValue):
        self.ivQueue.append(fvValue)

    def delq(self):
        tvValue = None
        if not self.isEmpty():
            tvValue = self.ivQueue[0]
            self.ivQueue = self.ivQueue[1:]
        return tvValue

    def isEmpty(self):
        return (len(self.ivQueue) == 0)

    def __str__(self):
        return (str(self.ivQueue))

class Stack:
    """Stack implementation using list data structures as member. """

    def __init__(self):
        self.ivStack = []

    def push(self, fvValue):
        self.ivStack.append(fvValue)

    def pop(self):
        tvValue = None
        if not self.isEmpty():
            tvValue = self.ivStack[-1]
            self.ivStack = self.ivStack[0:len(self.ivStack)-1]
        return tvValue

    def top(self):
        tvValue = None
        if not self.isEmpty():
            tvValue = self.ivStack[-1]
        return tvValue

    def isEmpty(self):
        return (len(self.ivStack) == 0)

    def __str__(self):
        return (str(self.ivStack))

def basic_learning_of_queue():
    """ Basic usages of queue data structure."""
    tvQ = Queue()

    for i in range(0,3):
        tvQ.addq(i)
        print(tvQ)

    print(tvQ.isEmpty())

    for i in range(0,3):
        print(tvQ.delq(), tvQ)

    print(tvQ.isEmpty())

def basic_learning_of_stack():
    """ Basic usages of stack data structure."""

    tvS = Stack()

    for index in range(1, 7):
        tvS.push(index)
        print(tvS)

    print(tvS.isEmpty())

    for index in range(1, 7):
        print(tvS.pop(), tvS)

    print(tvS.isEmpty())

def create_graph_into_adjacency_matrix(fvSequence):
    """ choose which graph to use for creating the adjacency matrix to run alogrithms"""

    tvType = "matrix"

    if(fvSequence == 1):
        return (create_graph_into_adjacency_matrix_or_list_one(tvType))
    elif(fvSequence == 2):
        return (create_graph_into_adjacency_matrix_or_list_two(tvType))
    elif(fvSequence == 3):
        return (create_graph_into_adjacency_matrix_or_list_three(tvType))
    elif(fvSequence == 4):
        return (create_graph_into_adjacency_matrix_or_list_four(tvType))
    elif(fvSequence == 5):
        return (create_graph_into_adjacency_matrix_or_list_five(tvType))

def create_graph_into_adjacency_list(fvSequence):
    """ choose which graph to use for creating the adjacency list to run alogrithms"""

    tvType = "list"

    if(fvSequence == 1):
        return (create_graph_into_adjacency_matrix_or_list_one(tvType))
    elif(fvSequence == 2):
        return (create_graph_into_adjacency_matrix_or_list_two(tvType))
    elif(fvSequence == 3):
        return (create_graph_into_adjacency_matrix_or_list_three(tvType))
    elif(fvSequence == 4):
        return (create_graph_into_adjacency_matrix_or_list_four(tvType))
    elif(fvSequence == 5):
        return (create_graph_into_adjacency_matrix_or_list_five(tvType))

### For Adjacency Matrix

############################################################################################
###################################### Neighbours(Outgoing)#################################
############################################################################################
def neighboursAMatrix(fvAMatrix, i):
    """ finding out the neighbours from the given Adjacency Matrix and a particular vertex.
    For Adjacency List finding adjacency is just one loopup in the has table."""

    tvNeighboursList =  []

    (tvRows, tvCols) = fvAMatrix.shape

    for ColIndex in range(tvCols):
        if(fvAMatrix[i,ColIndex] == 1):
            tvNeighboursList.append(ColIndex)

    return tvNeighboursList

############################################################################################
################################### IncomingEdges(Incoming) ################################
############################################################################################
def incomingEdgesAMatrix(fvAMatrix, i):
    """ finding out the incomingEdges from the given Adjacency Matrix and a particular vertex.
    It is same as calculating the indegreeVal"""

    tvIncomingEdgeList =  []

    (tvRows, tvCols) = fvAMatrix.shape

    for rowIndex in range(tvRows):
        if(fvAMatrix[rowIndex, i] == 1):
            tvIncomingEdgeList.append(rowIndex)

    return tvIncomingEdgeList

### For Adjacency List

############################################################################################
###################################### Neighbours(Outgoing)#################################
############################################################################################
def neighboursAList(fvAList, i):
    """ finding out the neighbours from the given Adjacency List and a particular vertex.
    For Adjacency List finding adjacency is just one loopup in the has table."""

    tvNeighboursList =  []
    tvNeighboursList = fvAList[i]
    return tvNeighboursList

############################################################################################
################################### IncomingEdges(Incoming) ################################
############################################################################################
def incomingEdgesAlist(fvAList, i):
    """ finding out the incomingEdges from the given Adjacency List and a particular vertex.
    It is same as calculating the indegreeVal"""

    global gDoWeNeedToInitialize, gVertexToIncomingEdgeList

    tvIncomingEdgeList =  []

    # Initialize and calculate only once
    if(gDoWeNeedToInitialize == True):
        for index in range(len(fvAList)):
            gVertexToIncomingEdgeList[index] = []

        for index in range(len(fvAList)):
            tvCurrentIndexNeighbourList = fvAList[index]
            for aNeighbour in range(len(tvCurrentIndexNeighbourList)):
                # if present get current value and then append into the appropriate index of list
                aNeighbourVertexIndexValue = tvCurrentIndexNeighbourList[aNeighbour]
                gVertexToIncomingEdgeList[aNeighbourVertexIndexValue].append(index)

        gDoWeNeedToInitialize = False

    tvIncomingEdgeList = gVertexToIncomingEdgeList[i]
    return tvIncomingEdgeList

############################################################################################
#################### Common Utility For Adjancency Matrix & List############################
############################################################################################

def neighbours(fvAInput, i):
    """ Check out the type of 'fvAInput and then call appropriately. Neighbours means outgoing
    edges from the given node index 'i' """

    tvReturnList = []

    if( isinstance(fvAInput, dict) == True):
        tvReturnList = neighboursAList(fvAInput, i)
    elif( isinstance(fvAInput, np.ndarray) == True):
        tvReturnList = neighboursAMatrix(fvAInput, i)
    return tvReturnList

def incomingEdges(fvAInput, i):
    """ Check out the type of 'fvAInput and then call appropriately.incomingEdges means
    incoming egdes to the given node index 'i' """

    tvReturnList = []

    if( isinstance(fvAInput, dict) == True):
        tvReturnList = incomingEdgesAlist(fvAInput, i)
    elif( isinstance(fvAInput, np.ndarray) == True):
        tvReturnList = incomingEdgesAMatrix(fvAInput, i)
    return tvReturnList

def outdegreeVal(fvAInput, i):
    """ Outdegree value of the given node 'i'"""

    tvLen = 0
    tvLen = neighbours(fvAInput, i)
    return tvLen

def indegreeVal(fvAInput, i):
    """ Indegree value of the given node 'i'"""

    tvLen = 0
    tvLen = incomingEdges(fvAInput, i)
    return tvLen


# 자료 내용 변경

from libs.db.dbconn import getconn

def update_data():
    conn = getconn()
    cur = conn.cursor()
    sql = "update member set name='이몽룡' where mem_num = 104"
    cur.execute(sql)

    conn.commit()
    conn.close()

if __name__=="__main__":
    update_data()


def helpme(n):
    if n=="help":
        print("The following commands are available : add\nsub\nmul\ndiv\nrem\nexp\nfeb\narm\nstarpat\nFor a detailed Help try helpcalc(function_name)")
    else:
        print("Please enter a valid command")
def add(a,b):
    c=a+b
    print(f"The Sum of {a} and {b} is {c}")
def sub(a,b):
    c=a-b
    print(f"The Difference of {a} and {b} is {c}")
def mul(a,b):
    c=a*b
    print(f"The Product of {a} and {b} is {c}")
def div(a,b):
    c=a/b
    print(f"The Quotient of {a} and {b} is {c}")
def rem(a,b):
    c=a%b
    print(f"The Remainder of {a} and {b} is {c}")
def exp(a,b):
    c=a**b
    print(f"The Exponential Value of {a} power {b} is {c}")
def feb(n):
    try:
        a,b=0,1
        while a < n:
            print(a,end=" ")
            a,b=b,a+b
        print()
    except TypeError:
        print("Please enter a valid number")
def arm(a):
    try:
        sum=0
        temp=a
        while temp> 0:
            digit = temp % 10
            sum += digit ** 3
        temp //= 10
        if a == sum:
            print(a,"is an Armstrong Number")
        else:
            print(a,"is not an Armstrong Number")
    except TypeError:
        print("Please enter a valid number")
def starpat(n):
    try:
        for i in range(1,n+1):
            for j in range(1,i+1):
                print("*",end=" ")
            print()
    except TypeError:
        print("Please enter a valid number")
def lcm(x,y):
    try:
        if x > y:
            greater = x
        else:
            greater = y
        while(True):
            if((greater % x == 0) and (greater % y == 0)):
                lcm = greater
                break
            greater += 1
        return lcm
    except TypeError:
        print("Please enter a valid number")
def hcf(x,y):
    try :
        if x > y:
            smaller = y
        else:
            smaller = x
        for i in range(1, smaller+1):
            if((x % i == 0) and (y % i == 0)):
                hcf = i
        return hcf
    except TypeError:
        print("Please enter a valid number")
def sqrt(n):
    try:
        if n<0:
            print("Please enter a valid number")
        else:
            x=n
            while True:
                y=(x+n/x)/2
                if y==x:
                    break
                x=y
            print(f"The Square root of {n} is {x}")
    except TypeError:
        print("Please enter a valid number")
def sumofseries(n):
    try:
        sum=0
        for i in range(1,n+1):
            sum=sum+i
        print(f"The sum of the series is {sum}")
    except TypeError:
        print("Please enter a valid number")
def helpcalc(help):
    if help=="add":
        print("This function adds two numbers")
    elif help=="sub":
        print("This function subtracts two numbers")
    elif help=="mul":
        print("This function multiplies two numbers")
    elif help=="div":
        print("This function divides two numbers")
    elif help=="rem":
        print("This function finds the remainder of two numbers")
    elif help=="exp":
        print("This function finds the exponential value of two numbers")
    elif help=="feb":
        print("This function finds the nth number in the fibonacci series")
    elif help=="arm":
        print("This function checks if a number is an Armstrong number")
    elif help=="starpat":
        print("This function prints a pattern of stars")
    elif help=="lcm":
        print("This function finds the least common multiple of two numbers")
    elif help=="hcf":
        print("This function finds the highest common factor of two numbers")
    elif help=="sqrt":
        print("This function finds the square root of a number")
    elif help=="sumofseries":
        print("This function finds the sum of a series")
    else:
        print("Please enter a valid command")


import io
import requests
import numpy as np
import pandas as pd
from scipy.io import loadmat
import zipfile

# Map of battery to url for data
urls = {
    'RW1': "https://data.nasa.gov/download/ed33-vxp2/application%2Fzip",
    'RW2': "https://data.nasa.gov/download/ed33-vxp2/application%2Fzip",
    'RW3': "https://data.nasa.gov/download/qghr-qkfw/application%2Fzip",
    'RW4': "https://data.nasa.gov/download/qghr-qkfw/application%2Fzip",
    'RW5': "https://data.nasa.gov/download/qghr-qkfw/application%2Fzip",
    'RW6': "https://data.nasa.gov/download/qghr-qkfw/application%2Fzip",
    'RW7': "https://data.nasa.gov/download/ed33-vxp2/application%2Fzip",
    'RW8': "https://data.nasa.gov/download/ed33-vxp2/application%2Fzip",
    'RW9': "https://data.nasa.gov/download/ugxu-9kjx/application%2Fzip",
    'RW10': "https://data.nasa.gov/download/ugxu-9kjx/application%2Fzip",
    'RW11': "https://data.nasa.gov/download/ugxu-9kjx/application%2Fzip",
    'RW12': "https://data.nasa.gov/download/ugxu-9kjx/application%2Fzip",
    'RW13': "https://data.nasa.gov/download/sb48-rsbc/application%2Fzip",
    'RW14': "https://data.nasa.gov/download/sb48-rsbc/application%2Fzip",
    'RW15': "https://data.nasa.gov/download/sb48-rsbc/application%2Fzip",
    'RW16': "https://data.nasa.gov/download/sb48-rsbc/application%2Fzip",
    'RW17': "https://data.nasa.gov/download/tcjd-g74p/application%2Fzip",
    'RW18': "https://data.nasa.gov/download/tcjd-g74p/application%2Fzip",
    'RW19': "https://data.nasa.gov/download/tcjd-g74p/application%2Fzip",
    'RW20': "https://data.nasa.gov/download/tcjd-g74p/application%2Fzip",
    'RW21': "https://data.nasa.gov/download/5uxu-h2h6/application%2Fzip",
    'RW22': "https://data.nasa.gov/download/5uxu-h2h6/application%2Fzip",
    'RW23': "https://data.nasa.gov/download/5uxu-h2h6/application%2Fzip",
    'RW24': "https://data.nasa.gov/download/5uxu-h2h6/application%2Fzip",
    'RW25': "https://data.nasa.gov/download/gah6-q2es/application%2Fzip",
    'RW26': "https://data.nasa.gov/download/gah6-q2es/application%2Fzip",
    'RW27': "https://data.nasa.gov/download/gah6-q2es/application%2Fzip",
    'RW28': "https://data.nasa.gov/download/gah6-q2es/application%2Fzip",
}

cache = {}  # Cache for downloaded data
# Cache is used to prevent files from being downloaded twice

def load_data(batt_id: str) -> tuple:
    """
    .. versionadded:: 1.3.0

    Loads data for one or more batteries from NASA's PCoE Dataset, '11. Randomized Battery Usage Data Set'
    https://www.nasa.gov/content/prognostics-center-of-excellence-data-set-repository

    Args:
        batt_id (str): Battery name from dataset (RW1-28)

    Raises:
        ValueError: Battery not in dataset (should be RW1-28)

    Returns:
        tuple[dict, list[pd.DataFrame]]: Data and description as a tuple (description, data), where the data is a list of pandas DataFrames such that data[i] is the data for run i, corresponding with details[i], above. The columns of the dataframe are ('relativeTime', 'current' (amps), 'voltage', 'temperature' (°C)) in that order.

    Raises:
        ValueError: Battery id must be a string or int
        ConnectionError: Failed to download data. This may be because of issues with your internet connection or the datasets may have moved. Please check your internet connection and make sure you're using the latest version of prog_models.
    """
    if isinstance(batt_id, int):
        # Convert to string
        batt_id = 'RW' + str(batt_id)
    if not isinstance(batt_id, str):
        raise ValueError('Battery ID must be a string')

    if batt_id not in urls:
        raise ValueError('Unknown battery ID: {}'.format(batt_id))

    url = urls[batt_id]

    if url not in cache:
        # Download data
        try:
            response = requests.get(url, allow_redirects=True)
        except requests.exceptions.RequestException:  # handle chain of errors
            raise ConnectionRefusedError("Data download failed. This may be because of issues with your internet connection or the datasets may have moved. Please check your internet connection and make sure you're using the latest version of prog_models. If the problem persists, please submit an issue on the prog_models issue page (https://github.com/nasa/prog_models/issues) for further investigation.")

        # Unzip response
        try:
            cache[url] = zipfile.ZipFile(io.BytesIO(response.content))
        except zipfile.BadZipFile:
            # In this case the url may have been forwarded to another page
            raise ConnectionRefusedError("Data unzip failed- The site may be down or the datasets may have moved. Please try again later and make sure you're using the latest version of prog_models. If the problem persists, please submit an issue on the prog_models issue page (https://github.com/nasa/prog_models/issues) for further investigation.")

    f = cache[url].open(f'{cache[url].infolist()[0].filename}Matlab/{batt_id}.mat')

    # Load matlab file
    result = loadmat(f)['data']

    # Reformat
    desc = {
        'procedure': str(result['procedure'][0, 0][0]),
        'description': str(result['description'][0, 0][0]),
        'runs':
        [
            {
                'type': str(run_type[0]),
                'desc': str(desc[0]),
                'date': str(date[0])
            } for (run_type, desc, date) in zip(result['step'][0, 0]['type'][0], result['step'][0, 0]['comment'][0], result['step'][0, 0]['date'][0])
        ]
    }

    result = result['step'][0, 0]
    result = [
        pd.DataFrame(
            np.array([
                result[key][0, i][0] for key in ('relativeTime', 'current', 'voltage', 'temperature')
            ], np.float64).T,
            columns=('relativeTime', 'current', 'voltage', 'temperature')
        ) for i in range(result.shape[1])
    ]
    for r in result:
        r.set_index('relativeTime')

    return desc, result

def clear_cache() -> None:
    """Clears the cache of downloaded data"""
    cache.clear()


#brailleDisplayDrivers/lilli.py
#A part of NonVisual Desktop Access (NVDA)
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
#Copyright (C) 2008-2011 Gianluca Casalino <gianluca@spazioausili.net>, Alberto Benassati <benassati@cavazza.it>

from logHandler import log
from ctypes import *
import inputCore
import wx
import braille

try:
	lilliDll=windll.LoadLibrary("brailleDisplayDrivers\\lilli.dll")
except:
	lilliDll=None

lilliCellsMap=[]
KEY_CHECK_INTERVAL = 50

LILLI_KEYS = [
	"", "F1", "F2", "F3", "F4",  "F5", "F6", "F7", "F8", "F9", "F10", "LF", "UP", "RG", "DN", "",
	"", "SF1", "SF2", "SF3", "SF4",  "SF5", "SF6", "SF7", "SF8", "SF9", "SF10", "SLF", "SUP", "SRG", "SDN", "",
	"", "LF1", "LF2", "LF3", "LF4",  "LF5", "LF6", "LF7", "LF8", "LF9", "LF10", "LLF", "LUP", "LRG", "LDN", "",
	"", "SLF1", "SLF2", "SLF3", "SLF4",  "SLF5", "SLF6", "SLF7", "SLF8", "SLF9", "SLF10", "SLLF", "SLUP", "SLRG", "SLDN", "SFDN", "SFUP",
	"route"
]

def convertLilliCells(cell):
	newCell = ((1<<6 if cell & 1<<4 else 0) |
		(1<<5 if cell & 1<<5  else 0) |
		(1<<0 if cell & 1<<6  else 0) |
		(1<<3 if cell & 1<<0  else 0) |
		(1<<2 if cell & 1<<1  else 0) |
		(1<<1 if cell & 1<<2  else 0) |
		(1<<7 if cell & 1<<3  else 0) |
		(1<<4 if cell & 1<<7  else 0))
	return newCell

class BrailleDisplayDriver(braille.BrailleDisplayDriver):
	name = "lilli"
	# Translators: Name of a braille display.
	description = _("MDV Lilli")

	@classmethod
	def check(cls):
		return bool(lilliDll)

	def  __init__(self):
		global lilliCellsMap
		super(BrailleDisplayDriver, self).__init__()
		lilliCellsMap=[convertLilliCells(x) for x in xrange(256)]
		if (lilliDll.Init408USB()):
			self._keyCheckTimer = wx.PyTimer(self._handleKeyPresses)
			self._keyCheckTimer.Start(KEY_CHECK_INTERVAL)
		else:
			raise RuntimeError("No display found")

	def terminate(self):
		super(BrailleDisplayDriver, self).terminate()
		try:
			self._keyCheckTimer.Stop()
			self._keyCheckTimer = None
		except:
			pass
		lilliDll.Close408USB()

	def _get_numCells(self):
		return 40

	def _handleKeyPresses(self):
		while True:
			try:
				key=lilliDll.ReadBuf()
			except:
				pass
			if not key: break
			if (key <= 64) or ((key >= 257) and (key <= 296)):
				self._onKeyPress(key)

	def _onKeyPress(self, key):
		try:
			if (key >= 257) and (key <= 296):
				inputCore.manager.executeGesture(InputGesture(LILLI_KEYS[65],key-256))
			elif (key <= 64):
				inputCore.manager.executeGesture(InputGesture(LILLI_KEYS[key],0))
		except inputCore.NoInputGestureAction:
			pass

	def display(self, cells):
		cells="".join(chr(lilliCellsMap[x]) for x in cells)
		lilliDll.WriteBuf(cells)

	gestureMap = inputCore.GlobalGestureMap({
		"globalCommands.GlobalCommands": {
			"braille_routeTo": ("br(lilli):route",),
			"braille_scrollBack": ("br(lilli):LF",),
			"braille_previousLine": ("br(lilli):UP",),
			"braille_nextLine": ("br(lilli):DN",),
			"braille_scrollForward": ("br(lilli):RG",),
			"kb:shift+tab": ("br(lilli):SLF",),
			"kb:tab": ("br(lilli):SRG",),
			"kb:alt+tab": ("br(lilli):SDN",),
			"kb:alt+shift+tab": ("br(lilli):SUP",),
		}
	})

class InputGesture(braille.BrailleDisplayGesture):

	source = BrailleDisplayDriver.name

	def __init__(self, command, argument):
		super(InputGesture, self).__init__()
		self.id = command
		if (command == LILLI_KEYS[65]):
			self.routingIndex = argument


# -*- coding: utf-8 -*-
"""
Created on Mon Aug 31 11:21:45 2020

@author: djrzyz
"""

import pandas as pd
import win32com.client as win32
import time
from os import listdir
from datetime import datetime
from datetime import datetime, timedelta
import io
from os import path

fileLocation , filename,  sheetname = '', '', ''
expiring =[]

def read_excel(fileLocation,filename,sheetname):
    has_content=False
    df_allert_data=pd.read_excel(fileLocation+"\\"+filename, sheet_name=sheetname) # read the files that has cotent expiry dates.
    df_allert_data.dropna(axis=0,subset=['Expire Date'])
    df_allert_data['Expire Date']=pd.to_datetime(df_allert_data['Expire Date'])
    df_allert_data.dropna(axis=0,subset=['Expire Date'],inplace=True)
    for index_number in df_allert_data.index:
        if datetime.today() < df_allert_data['Expire Date'].iloc[index_number]:
           df_allert_data.drop([index_number], inplace=True)
           df_allert_data.sort_values(by=['Expire Date'],ascending=False ,inplace=True, ignore_index=True )
           df_allert_data.index = df_allert_data.index + 1
    return df_allert_data

def send_email(expiring, df_allert_data ):
    html = """\
<html>
  <head></head>
  <body>
    {0}
  </body>
</html>
""".format(df_allert_data[['Description', 'Station', 'Expire Date']].to_html())
    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = '' # receiving person's email ID
    mail.Subject = 'Q-Alert expired reminder: '+'('+datetime.today().strftime('%m-%d-%Y')+')'
    mail.Body = 'Hi all, \n The following list items have reached expiration date.'
    mail.HTMLBody = html #this field is optional

    # To attach a file to the email (optional):
    # attachment  = "Path to the attachment"
    # mail.Attachments.Add(attachment)

    mail.Send()

df_allert_data=read_excel(fileLocation, filename,sheetname)
send_email(expiring, df_allert_data )


import argparse
import os
import struct

from PIL import Image

ap = argparse.ArgumentParser(description='convert images for gfxutils')

ap.add_argument('input', type=argparse.FileType('rb'), help='input image')
ap.add_argument('output', type=argparse.FileType('wb'), help='output file')
ap.add_argument(
    '-o',
    '--output-type',
    default='h',
    choices=('h', 'gfx'),
    help='output format, either c for C code or gfx for raw data '
    '(default "c")',
    metavar='type',
    dest='otype',
)
ap.add_argument(
    '-n',
    '--name',
    default='image',
    help='name of C variable, only makes sense when output type is h '
    '(default "image")',
    metavar='name',
    dest='name',
)

args = ap.parse_args()

def rgb565(rgb):
    r, g, b = rgb
    return ((r & 0xF8) << 8) + ((g & 0xFC) << 3) + (b >> 3)

data = bytes()

with args.input as f:
    with Image.open(f).convert('RGB') as im:
        data += struct.pack('<HH', im.width, im.height)
        for i in range(im.width):
            for j in range(im.height):
                data += struct.pack('<H', rgb565(im.getpixel((i, j))))

with args.output as f:
    if args.otype == 'gfx':
        f.write(data)
    elif args.otype == 'h':
        name = args.name.encode()
        f.write(b'const unsigned char ')
        f.write(name)
        f.write(b'_data[%i] = {\n' % len(data))
        for i in range(0, len(data), 16):
            f.write(b'    ')
            for b in data[i : i + 16]:
                f.write(b'0x%02X' % b)
                f.write(b', ')
            f.write(b'\n')
        f.write(b'};\n')
        with open(os.path.splitext(f.name)[0] + '.h', 'wb') as h:
            macro = b'_' + name.upper() + b'_H'
            h.write(b'#ifndef ')
            h.write(macro)
            h.write(b'\n#define ')
            h.write(macro)
            h.write(b'\nextern const unsigned char ')
            h.write(name)
            h.write(b'_data[%i];\n#define ' % len(data))
            h.write(name)
            h.write(b' ((gfxutils_image_t *)')
            h.write(name)
            h.write(b'_data)\n#endif\n')


import json
import pytest
import types

from tests.support.inline import inline
from tests.support.asserts import assert_error, assert_success

alert_doc = inline("")
frame_doc = inline("
frame")
one_frame_doc = inline("" % frame_doc)
two_frames_doc = inline("" % one_frame_doc)

# TODO(ato): 7.1 Get

def test_get_current_url_no_browsing_context(session, create_window):
    # 7.2 step 1
    session.window_handle = create_window()
    session.close()

    result = session.transport.send("GET", "session/%s/url" % session.session_id)

    assert_error(result, "no such window")

def test_get_current_url_alert_prompt(session):
    # 7.2 step 2
    session.url = alert_doc

    result = session.transport.send("GET", "session/%s/url" % session.session_id)

    assert_error(result, "unexpected alert open")

def test_get_current_url_matches_location(session):
    # 7.2 step 3
    url = session.execute_script("return window.location.href")
    assert session.url == url

def test_get_current_url_payload(session):
    # 7.2 step 4-5
    session.start()

    result = session.transport.send("GET", "session/%s/url" % session.session_id)

    assert result.status == 200
    assert isinstance(result.body["value"], basestring)

def test_get_current_url_special_pages(session):
    session.url = "about:blank"

    result = session.transport.send("GET", "session/%s/url" % session.session_id)

    assert_success(result, "about:blank")

# TODO(ato): This test requires modification to pass on Windows
def test_get_current_url_file_protocol(session):
    # tests that the browsing context remains the same
    # when navigated privileged documents
    session.url = "file:///"

    result = session.transport.send("GET", "session/%s/url" % session.session_id)

    assert_success(result, "file:///")

# TODO(ato): Test for http:// and https:// protocols.
# We need to expose a fixture for accessing
# documents served by wptserve in order to test this.

def test_set_malformed_url(session):
    result = session.transport.send("POST",
                                    "session/%s/url" % session.session_id,
                                    {"url": "foo"})

    assert_error(result, "invalid argument")

def test_get_current_url_after_modified_location(session):
    session.execute_script("window.location.href = 'about:blank#wd_test_modification'")

    result = session.transport.send("GET", "session/%s/url" % session.session_id)

    assert_success(result, "about:blank#wd_test_modification")

def test_get_current_url_nested_browsing_context(session, create_frame):
    session.url = "about:blank#wd_from_within_frame"
    session.switch_frame(create_frame())

    result = session.transport.send("GET", "session/%s/url" % session.session_id)

    assert_success(result, "about:blank#wd_from_within_frame")

def test_get_current_url_nested_browsing_contexts(session):
    session.url = two_frames_doc
    top_level_url = session.url

    outer_frame = session.find.css("iframe", all=False)
    session.switch_frame(outer_frame)

    inner_frame = session.find.css("iframe", all=False)
    session.switch_frame(inner_frame)

    assert session.url == top_level_url


from datetime import timedelta

from pyflink.table import (
    StreamTableEnvironment,
    Table as NativeFlinkTable,
    TableDescriptor as NativeFlinkTableDescriptor,
)

from feathub.common.exceptions import FeathubException
from feathub.common.types import Timestamp, String
from feathub.feature_tables.sources.datagen_source import (
    DataGenSource,
    RandomField,
    SequenceField,
)
from feathub.processors.flink.flink_types_utils import to_flink_schema
from feathub.processors.flink.table_builder.source_sink_utils_common import (
    define_watermark,
)

def get_table_from_data_gen_source(
    t_env: StreamTableEnvironment, data_gen_source: DataGenSource
) -> NativeFlinkTable:
    flink_schema = to_flink_schema(data_gen_source.schema)

    # Define watermark if the kafka_source has timestamp field
    if data_gen_source.timestamp_field is not None:
        flink_schema = define_watermark(
            t_env,
            flink_schema,
            data_gen_source.max_out_of_orderness,
            data_gen_source.timestamp_field,
            data_gen_source.timestamp_format,
            data_gen_source.schema.get_field_type(data_gen_source.timestamp_field),
        )

    table_descriptor_builder = NativeFlinkTableDescriptor.for_connector(
        "datagen"
    ).schema(flink_schema)

    table_descriptor_builder.option(
        "rows-per-second", str(data_gen_source.rows_per_second)
    )

    if data_gen_source.number_of_rows is not None:
        table_descriptor_builder.option(
            "number-of-rows", str(data_gen_source.number_of_rows)
        )

    for field, field_config in data_gen_source.field_configs.items():
        if isinstance(field_config, RandomField):
            table_descriptor_builder.option(f"fields.{field}.kind", "random")
            if field_config.minimum is not None:
                table_descriptor_builder.option(
                    f"fields.{field}.min", str(field_config.minimum)
                )
            if field_config.maximum is not None:
                table_descriptor_builder.option(
                    f"fields.{field}.max", str(field_config.maximum)
                )
            if data_gen_source.schema.get_field_type(field) == Timestamp:
                table_descriptor_builder.option(
                    f"fields.{field}.max-past",
                    f"{field_config.max_past // timedelta(milliseconds=1)} ms",
                )
            if data_gen_source.schema.get_field_type(field) == String:
                table_descriptor_builder.option(
                    f"fields.{field}.length", str(field_config.length)
                )
        elif isinstance(field_config, SequenceField):
            table_descriptor_builder.option(f"fields.{field}.kind", "sequence")
            if field_config.start is not None:
                table_descriptor_builder.option(
                    f"fields.{field}.start", str(field_config.start)
                )
            if field_config.end is not None:
                table_descriptor_builder.option(
                    f"fields.{field}.end", str(field_config.end)
                )
        else:
            raise FeathubException(f"Unknown field config type {type(field_config)}.")

    return t_env.from_descriptor(table_descriptor_builder.build())


n=int(input())
f=0
for i in range(1,n):
  if(n%i)==0:
    f=i
if f>1:
  print('yes')
elif n==1:
  print('no')
else:
  print('no')


import pyHook,pythoncom,sys,logging

file_log = 'C:/log.txt'

def onkeyboard(event):
	logging.basicConfig(filename=file_log,level=logging.DEBUG,forame='%(message)s')
	chr(event.Ascii)
	logging.log(10,chr(event.Ascii))
	return True

hooks_manger = pyHook.HookManager()
hooks_manger.keyDown = onkeyboard
hooks_manger.HookKeyboard()
pythoncom.PumpMessages()


from django.contrib.auth import get_user_model
from django.test import Client, TestCase
from django.urls import reverse
from places.models import Place

User = get_user_model()

class TestsView(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.user = User.objects.create_user(username='MIHA')
        cls.places = Place.objects.create(
            name='Тестовое название',
            latitude=56.825053189709,
            longitude=60.5994881210587,
            comment='Тестовый коммент',
        )
        cls.templates_pages_names = {
            reverse('places:profile'): 'user/profile.html',
            reverse('places:map'): 'user/map.html',
        }

    def setUp(self):
        # Создаем авторизованный клиент
        self.authorized_client = Client()
        self.authorized_client.force_login(self.user)

    def test_pages_uses_correct_template(self):
        """URL-адрес использует соответствующий шаблон."""
        for reverse_name, template in self.templates_pages_names.items():
            with self.subTest(reverse_name=reverse_name):
                response = self.authorized_client.get(reverse_name)
                self.assertTemplateUsed(response, template)

    def test_profile_show_correct_context(self):
        response = self.authorized_client.get(reverse('places:profile'))
        first_object = response.context['page_obj'][0]
        name = first_object.name
        author = first_object.author
        comment = first_object.comment
        latitude = first_object.latitude
        longitude = first_object.longitude
        self.assertEqual(name, 'Тестовое название')
        self.assertEqual(author, self.user)
        self.assertEqual(comment, 'Тестовый коммент')
        self.assertEqual(latitude, 56.825053189709)
        self.assertEqual(longitude, 60.5994881210587)


import json
import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes import client, config
from kubernetes.client import ApiClient

def __get_kubernetes_client(bearer_token,api_server_endpoint):
    try:
        configuration = kubernetes.client.Configuration()
        configuration.host = api_server_endpoint
        configuration.verify_ssl = False
        configuration.api_key = {"authorization": "Bearer " + bearer_token}
        client.Configuration.set_default(configuration)
        with kubernetes.client.ApiClient(configuration) as api_client:
    # Create an instance of the API class
            api_instance1 = kubernetes.client.CoreV1Api(api_client)
        return api_instance1

    except ApiException as e:
        print("Error getting kubernetes client:\n{}".format(e.body))
        print("TYPE :{}".format(type(e)))
        return None

def __format_data_for_pod(client_output):
        temp_dict={}
        temp_list=[]
        json_data=ApiClient().sanitize_for_serialization(client_output)
        if len(json_data["items"]) != 0:
            for ns in json_data["items"]:
                temp_dict={
                    "namespace": ns["metadata"]["name"]

                }
                temp_list.append(temp_dict)
        return temp_list

def get_namespaces(cluster_details,namespace="default",all_namespaces=True):

    try:
        if all_namespaces is True:

            client_api= __get_kubernetes_client(
                bearer_token=cluster_details["bearer_token"],
                api_server_endpoint=cluster_details["api_server_endpoint"],
                )
            res=client_api.list_namespace()

            data=__format_data_for_pod(res)
            return data
        else:
            return []
    except Exception as e:
        return []


"""
46. Permutations

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
"""

def my_timer(func):
    import time
    def wrapper(*args, **kwargs):
        t1 = time.perf_counter()
        result = func(*args, **kwargs)
        t2 = time.perf_counter() - t1
        s = int(t2)
        ms = int(t2*10**3)
        us = int(t2*10**6)
        dt = "{}.{}.{}s".format(s, ms, us)
        print('{0} ran in : {1}'.format(func.__name__, dt))
        return result
    return wrapper

class Solution(object):
    def perm(self, nums, start, result):
        n = len(nums)
        if start == n-1:
            result.append(nums)
            return
        for j in range(start, n):
            nums[j], nums[start] = nums[start], nums[j] #swapping the elements
            # nums[:] = nums.copy() i.e, just makes the duplicate of the current array
            self.perm(nums[:], start+1, result)

    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """

        ans=[]
        self.perm(nums,0, ans)

        return ans

"""
Runtime: 28 ms, faster than 66.23% of Python online submissions for Permutations.
Memory Usage: 12.7 MB, less than 6.00% of Python online submissions for Permutations.
"""

@my_timer
def test_case(*args, **kwargs):
    ans = Solution().permute(*args, **kwargs)
    print("Input: {0}".format(*args))
    print("Output: {0}".format(ans))

if __name__ == "__main__":
    test_case([1,2,3])


# nlantau, 2021-12-30

from typing import *

class Solution:
    def reverseString2(self, s: List[str]) -> None:
        """
        Recursive
        Do not return anything, modify s in-place instead.
        While this works, s is not modified in-place...
        """
        if len(s) == 0 or len(s) == 1:
            return s
        return [s[-1]] + self.reverseString(s[:-1])

    def reverseString(self, s: List[str]) -> None:
        """
        Iterative
        Do not return anything, modify s in-place instead.
        Two-pointer approach... ?
        """
        start = 0
        end = len(s) - 1

        while start < end:
            # swap start with end
            s[start], s[end] = s[end], s[start]
            start += 1
            end -= 1

"""
Notes:
Wanted to do it recursively, but ended up with iterative.
375 ms (super-slow), 18.8 MB, 10.24% better memory usage...
"""

if __name__ == "__main__":
    s = ['h','e','l','l','o']
    Solution().reverseString(s)
    print(s)


# -*- coding: utf-8 -*-
"""
Created on Wed Apr 15 22:54:40 2020

@author: alexi
"""

#https://codeforces.com/problemset/problem/296/A --- Alexis Galvan

def yaroslav():

    length = int(input())
    array = list(map(int, input().split()))

    if len(array) == 1:
        return 'YES'

    dic = {}

    if len(array) % 2 == 0:
        for i in range(len(array)):
            if array[i] not in dic:
                dic[array[i]] = 1
            else:
                dic[array[i]] += 1
                if dic[array[i]] > (len(array)/2):
                    return 'NO'
    else:
        for i in range(len(array)):
            if array[i] not in dic:
                dic[array[i]] = 1
            else:
                dic[array[i]] += 1
                if dic[array[i]] == (int(len(array)/2))+2:
                    return 'NO'

    return 'YES'

A = yaroslav()
print(A)


n, c = map(int, input().split())

grid = []
for _ in range(c):
    grid.append(input())

def bfs(y, x, wb):
    global count
    count += 1
    check[y][x] = 1
    for i in range(4):
        ny = y + dy[i]
        nx = x + dx[i]
        if 0 <= ny < c and 0 <= nx < n:
            if grid[ny][nx] == wb and check[ny][nx] == 0:
                bfs(ny, nx, wb)

check = [[0] * n for _ in range(c)]

dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
w, b = 0, 0
for i in range(c):
    for j in range(n):
        if check[i][j] == 0:
            count = 0
            bfs(i, j, grid[i][j])
            if grid[i][j] == 'W':
                w += count * count
            else:
                b += count * count

print(w, b)


__author__ = 'koorosh'
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

alpha = 12
Tf = 2 * np.pi
# State Matrix
def RHS(X, t=0.0):
    x1, x2 = X
    x1dot = x2
    x2dot = -(0.01 + alpha / 100) * x2 - x1 - alpha / 10 * x1**3 + np.sin(3*t)
    return [x1dot, x2dot]

t = np.linspace(0.0, Tf, 5000)
sol = odeint(RHS, [0, 0], t)
x = sol[:, 0]

# State Matrix
tFloquet = np.linspace(0.0, 2*np.pi, 100)
def A(Y, t=0.0):
    y1, y2, y3 = Y
    x10 = 0.12494 * np.sin(3 * t)
    y1dot = y2
    y2dot = -(0.01 + alpha / 100) * y2 - (1 + 0.3 * alpha * x10**2) * y1
    y3dot = 0
    return [y1dot, y2dot, y3dot]

sol1 = odeint(A, [1, 0, 0], tFloquet)
sol2 = odeint(A, [0, 1, 0], tFloquet)
sol3 = odeint(A, [0, 0, 1], tFloquet)
# sol1 = odeint(A, [1, 0, 0], t)
# sol2 = odeint(A, [0, 1, 0], t)
# sol3 = odeint(A, [0, 0, 1], t)

PHI = np.array([sol1[-1, :], sol2[-1, :], sol3[-1, :]])
# PHI = np.array([sol1[-1, :], sol2[-1, :]])
eigenValue = np.linalg.eigvals(PHI)
print(eigenValue)
print(np.abs(eigenValue))


from typing import List
from .models import Event
from django import forms

class DateInput(forms.DateInput):
    input_type = 'date'

class BaseForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].widget.attrs['class'] = 'form-control'

class Eventform(BaseForm):
    class Meta:
        model = Event
        fields = (
            'name',
            'description',
            'event_date',
            'featured_image'
        )
        widgets = {
            'event_date': DateInput()
        }


"""Add user skills and achievements.

Revision ID: c757a5632f69
Revises: e74ff40a1b2a
Create Date: 2023-02-03 15:56:04.620150

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'c757a5632f69'
down_revision = 'e74ff40a1b2a'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('user_achievements',
    sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
    sa.Column('key', sa.String(length=64), nullable=False),
    sa.Column('user_id', sa.Integer(), nullable=False),
    sa.Column('from_year', sa.Integer(), nullable=True),
    sa.Column('from_month', sa.Integer(), nullable=True),
    sa.Column('to_year', sa.Integer(), nullable=True),
    sa.Column('to_month', sa.Integer(), nullable=True),
    sa.Column('achievement', sa.String(length=210), nullable=False),
    sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('user_skills',
    sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
    sa.Column('user_id', sa.Integer(), nullable=False),
    sa.Column('skill', sa.String(length=21), nullable=True),
    sa.Column('added_at', sa.DateTime(), nullable=False),
    sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

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


import sys
inputs = sys.stdin.readline

N = int(input())
nums = [int(input()) for _ in range(N)]
plus,minus,zero,one = [],[],0,0
for num in nums:
    if num > 1:
        plus.append(num)
    elif num == 0:
        zero += 1
    elif num == 1:
        one += 1
    else:
        minus.append(num)

plus.sort(reverse=True)
minus.sort()
ans = 0
i = 0
# 양수는 다 곱한다
# 홀수면 마지막 값만 더한다
while i < len(plus):
    if i == len(plus)-1:
        ans += plus[i]
        break
    else:
        ans += (plus[i]*plus[i+1])
        i += 1
    i += 1

ans += one  # 일은 다 더한다

i = 0
# 음수는 다 곱한다
# 홀수면 마지막값은 0이 있으면 0,
# 없으면 더한다
while i < len(minus):
    if i == len(minus) - 1:
        if zero == 0:
            ans += minus[i]
        break
    else:
        ans += (minus[i] * minus[i + 1])
        i += 1
    i += 1

print(ans)


from django.test import TestCase, override_settings

from ...context_processors.global_config import global_config

class TestContextProcessorGlobalConfig(TestCase):
    def test_global_config(self):
        """
        Return settings in config object
        """
        results = global_config({})
        self.assertEqual(results['SITE_URL'], 'http://example.com')
        self.assertTrue('ANALYTICS' not in results)

    @override_settings(ANALYTICS=1234)
    def test_global_config_analytics(self):
        """
        Return analytics settings in config object
        """
        results = global_config({})
        self.assertEqual(results['ANALYTICS'], 1234)


# -*- coding: utf-8 -*-
# @Time    : 2020/8/31
# @Author  : Lafe
# @Email   : wangdh8088@163.com
# @File    : vis_datasets.py

import os
import os.path as osp
import cv2
import numpy as np
from tqdm import tqdm

def loopshow(res, savep=None):
    if len(res) == 0:
        return False
    ind = 0
    if savep is not None:
        os.makedirs(savep, exist_ok=True)

    while True:
        cv2.imshow('img', res[ind])
        # cv2.imshow("raw, fake, enmap", np.concatenate(res, axis=1))
        k = cv2.waitKey(0)
        if k == ord('d'):
            ind += 1
        elif k == ord('a'):
            ind -= 1
        elif k == ord('q'):
            cv2.destroyAllWindows()
            raise TypeError(" ****** STOP *********")
        elif k == ord('s'):
            savep_img = f'{savep}/{ind}.png'
            cv2.imwrite(savep_img, res[ind])
            print(' * save in:', savep_img)
        if ind >= len(res):
            ind = 0

def check_txt_list_add_root(root_dir, txt_f):
    img_dirs = list()
    mask_dirs = list()
    for line in open(txt_f):
        img_dir, mask_dir = line[:-1].split(' ')[0:2] # 后边可能包含 h, w
        if not img_dir.endswith('jpg') or not mask_dir.endswith('png'):
            print("error bug :%s " % img_dir)
            print("error bug :%s " % mask_dir)
            continue
        i = os.path.join(root_dir, img_dir)
        m = os.path.join(root_dir, mask_dir)
        img_dirs.append(i)
        mask_dirs.append(m)
    return img_dirs, mask_dirs

def create_clamap(root, txt_f, savep):
    os.makedirs(savep, exist_ok=True)

    img_path, mpath = check_txt_list_add_root(root, txt_f)
    vis = []
    for ind, (imgname, maskname) in enumerate(tqdm(zip(img_path, mpath), total=len(img_path))):
        img = cv2.imread(imgname)
        mask = cv2.imread(maskname) * 120
        try:
            img, mask = [cv2.resize(i, (512, 512), interpolation=cv2.INTER_NEAREST) for i in [img, mask]]
            color_map = (img * 0.5 + (0, 120, 0)).astype(np.uint8)
            fg = np.where(mask==0, (img*0.7).astype(np.uint8), color_map)

            # **** save image ****
            basename = osp.basename(imgname)
            img_savep = osp.join(savep, basename)
            cv2.imwrite(img_savep, fg)
        except:
            continue

    # loopshow(vis)

def vis_datasets(root, txt_f):
    img_path, mpath = check_txt_list_add_root(root, txt_f)
    vis = []
    for ind, (imgname, maskname) in enumerate(tqdm(zip(img_path, mpath), total=len(img_path))):
        img = cv2.imread(imgname)
        mask = cv2.imread(maskname) * 120
        if ind > 100:
            break
        try:
            img, mask = [cv2.resize(i, (512, 512), interpolation=cv2.INTER_NEAREST) for i in [img, mask]]
            color_map = (img * 0.5 + (0, 120, 0)).astype(np.uint8)
            fg = np.where(mask==0, (img*0.7).astype(np.uint8), color_map)
            vis.extend([img, mask, fg])
        except:
            continue

    loopshow(vis)

if __name__ == '__main__':
    # savep = '/data1/datasets_lafe/mask/CelebA/celebA_skin_clamap'
    savep = '/data1/datasets_lafe/mask/skin_segm/skin_mask/ATR/ATR_skin_clamap'
    # root = '/data1/datasets_lafe/mask/human_alpha/id_crop'
    # txt_f = '/data1/datasets_lafe/mask/human_alpha/layouts/mt_alpha_train.txt'
    #root = '/data1/datasets_lafe/mask/id_human_mt'
    # root = '/data1/datasets_lafe/mask/CelebA'
    root = '/data1/datasets_lafe/mask/skin_segm'
    # txt_f = '/data1/datasets_lafe/mask/coco_lip_mosaic/layouts/precise_03/precise_03_right_train.txt'
    # txt_f = '/data1/datasets_lafe/mask/coco_lip_mosaic/layouts/split_data_precise/unprecise_02_right.txt'
    # txt_f = '/data1/datasets_lafe/mask/CelebA/layout_mt/skin/celebA_skin.txt'
    txt_f = '/data1/datasets_lafe/mask/skin_segm/skin_mask/layouts/ATR.txt'
    # txt_f = '/data1/datasets_lafe/mask/id_human_mt/layouts/id_human_train.txt'
    # txt_f = '/data1/datasets_lafe/mask/skin_segm/skin_mask/layouts/ATR_train.txt'
    # txt_f = '/data1/datasets_lafe/mask/CelebA/layout_mt/mt_CelebA-HQ.txt'
    # vis_datasets(root, txt_f)
    create_clamap(root, txt_f, savep)


import random
import numpy as np
import pymc3 as pm
import theano.tensor as Tht
from netcal.metrics import ECE
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score, log_loss
import warnings
warnings.filterwarnings('once')
def sigmoid(m, b, X):
    #Z = np.dot(row, self.Ws)
    return 1 / (1 + np.exp(-np.dot(X, m)-b))

class BayesianCoeffLogisticRegression():
    def __init__(self, tolerance = 1e-5):
        random.seed(0)

    def transform_data(self, X):
        return self.scaler.transform(X)

    def fit(self, X_train, y_train):
		#compute the mean, and standard deviation for feature preprocessing (Gelman, 2008)
        #print(X_train.shape)
        if X_train.ndim == 1:
            X_train = X_train.reshape(-1, 1)
        self.scaler = StandardScaler()
        self.scaler.fit(X_train)
		#to transform data to have standard deviation of 0.5 (Gelman, 2008)
        self.scaler.var_ *= 4
        X_train = self.transform_data(X_train)

        samples = 1000
        with pm.Model() as _:
		    # betas
            alpha = pm.Cauchy('alpha', 0., 10)
            betas = []
            for i in range(X_train.shape[1]):
                betas.append(pm.Cauchy('beta' + str(i), 0., 2.5))
            #beta = pm.Cauchy('beta', 0., 2.5)
		    # logit
            logit_p =  alpha# + beta * X_train)
            for i in range(X_train.shape[1]):
                logit_p += betas[i] * X_train[:, i]#.append(pm.Cauchy('beta' + str(i), 0., 2.5))
            p = Tht.exp(logit_p) / (1 + Tht.exp(logit_p))
		    # likelihood
            _ = pm.Binomial('likelihood', n = 1, p = p, observed = y_train)
		    # inference
            start = pm.find_MAP()
            #step  = pm.NUTS(scaling = start)
            #trace = pm.sample(samples, step, progressbar=False, chains=2, cores=1)
            #summary = pm.summary(trace)['mean']
        self.b_map  = start['alpha']; self.a_map  = []
        for i in range(X_train.shape[1]):
            self.a_map.append(start['beta'+str(i)])
        self.a_map = np.array(self.a_map)
        #self.a_mmse = summary[0]; 		 self.b_mmse = summary[1]

    def predict_proba(self, X, mode = 'map'):
        if X.ndim == 1:
            X = X.reshape(-1, 1)
        X = self.transform_data(X)
        if mode == 'map':
            self.a = self.a_map; self.b = self.b_map
        else:
            self.a = self.a_mmse; self.b = self.b_mmse
        preds_probs = sigmoid(self.a, self.b, X)
        return preds_probs#np.squeeze(preds_probs)

    def predict(self, X, threshold = 0.5, mode = 'map'):
        return self.predict_proba(X, mode = mode) >= threshold

    def predict_logloss(self, X, y, mode = 'map'):
        preds_probs = self.predict_proba(X, mode = mode)
        return log_loss(y, preds_probs, labels = [0, 1])

    def predict_accuracy(self, X, y, threshold = 0.5, mode = 'map'):
        return accuracy_score(y, self.predict(X, threshold = threshold, mode = mode))

    def predict_ece(self, X, y, mode = 'map', bins = 10):
        ece = ECE(bins)
        calibrated_score = ece.measure(self.predict_proba(X, mode = mode), y)
        return calibrated_score

    def predict_ece_logloss(self, X, y, bins = 10, mode = 'map'):
        preds_probs = self.predict_proba(X, mode = mode)
        #print(preds_probs, preds_probs.shape)
        ece = ECE(bins)
        calibrated_score = ece.measure(preds_probs, y)
        #print(y, preds_probs)
        return calibrated_score, log_loss(y, preds_probs, labels = [0, 1])


"""_user_upd

Revision ID: c9ae720d5a53
Revises: bc81c684458b
Create Date: 2022-10-27 06:06:53.942527

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = "c9ae720d5a53"
down_revision = "bc81c684458b"
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("users", "is_blocked")
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column(
        "users",
        sa.Column(
            "is_blocked",
            sa.BOOLEAN(),
            autoincrement=False,
            nullable=True,
            comment="Заблокирован?",
        ),
    )
    # ### end Alembic commands ###


#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 18 18:39:03 2018

@author: imad
"""

import ConfigParser

config = ConfigParser.RawConfigParser()

# When adding sections or items, add them in the reverse order of
# how you want them to be displayed in the actual file.
# In addition, please note that using RawConfigParser's and the raw
# mode of ConfigParser's respective set functions, you can assign
# non-string values to keys internally, but will receive an error
# when attempting to write to a file or when you get it in non-raw
# mode. SafeConfigParser does not allow such assignments to take place.
config.add_section('Generate_Senders')
config.set('Generate_Senders', 'num_senders', '3')

config.add_section('Mapping')
config.set('Mapping', 'tasks_indices', '0, 2, 6, 8, 10, 12')

config.add_section('Mesh')
config.set('Mesh', 'verbose', 'False')
config.set('Mesh', 'verticalNode2', '49, 50, 51, 52, 53, 54, 55, 56, 57,58, 59, 60, 61, 62, 63, 64')
config.set('Mesh', 'verticalNode1', '0, 2, 4, 6, 14, 16, 18, 20, 28, 30, 32, 34, 42, 44, 46, 48')
config.set('Mesh', 'vcs', '4,4')
config.set('Mesh', 'bufferDepth', '16, 16')
config.set('Mesh', 'y', '7, 4')
config.set('Mesh', 'x', '7, 4')
config.set('Mesh', 'z', '2')
config.set('Mesh', 'filename', 'mesh.xml')

# Writing our configuration file to 'example.cfg'
with open('general_config.cfg', 'wb') as configfile:
    config.write(configfile)


# -------------------------------------
# Using UTF-8
# Last Modified Date: 2023/6/29
# Python 8x8 Image block functions
# Clark Pu
# -------------------------------------

import basemath
import math

# s must be a 8x8 matrix
# Discrete Cosine Transform
def fdct(s):
    S = basemath.zero(8,8)
    for u in range(0,8):
        if u == 0:
            Cu = math.sqrt(1/2)
        else:
            Cu = math.sqrt(2/2)
        for v in range(0,8):
            if v == 0:
                Cv =  math.sqrt(1/2)
            else:
                Cv = math.sqrt(2/2)
            unit = 0
            for x in range(0,8):
                for y in range(0,8):
                    unit += s[y][x] * math.cos(((2*x + 1) * u * math.pi) / 16) * math.cos(((2*y + 1) * v * math.pi) / 16)
            S[v][u] = (1/4) * Cu * Cv * unit
    return S

# Discrete Cosine Transform
def idct(S):
    s = basemath.zero(8,8)
    for x in range(0,8):
        for y in range(0,8):
            unit = 0
            for u in range(0,8):
                for v in range(0,8):
                    if u == 0:
                        Cu = math.sqrt(1/2)
                    else:
                        Cu = math.sqrt(2/2)
                    if v == 0:
                        Cv =  math.sqrt(1/2)
                    else:
                        Cv = math.sqrt(2/2)
                    unit += S[v][u] * Cu * Cv * math.cos(((2*x + 1) * u * math.pi) / 16) * math.cos(((2*y + 1) * v * math.pi) / 16)
            s[y][x] = (1/4) *  unit
    return s

# z must be a 8x8 matrix
def zigzag_scan(z):
    x = 0
    y = 0
    i = 0
    zigzag_list = [0] * 64
    direction = 1
    is_edge = False
    zigzag_list[0] = z[0][0]
    while True:
        if x == 0 or x == 7:
            y += 1
            is_edge = True
        elif y == 0 or y == 7:
            x += 1
            is_edge = True

        if is_edge:
            is_edge = False
            direction = - direction
            i += 1
            zigzag_list[i] = z[x][y]

        if x == 7 and y == 7:
            return zigzag_list

        i += 1
        x -= direction
        y += direction
        zigzag_list[i] = z[x][y]

# block_list must be an integer list. EHUFCO EHUFSI tables are list, explained in itu-t81
def huffman_encode(block_list, DC_EHUFCO, DC_EHUFSI, AC_EHUFCO, AC_EHUFSI):

    # reverse if it is negtive
    def get_value(value):
        value_bin = ''
        if value != 0: # not empty
            if value < 0:
                for bit in bin(value)[2:]:
                    if bit == '1':
                        value_bin += '0'
                    else:
                        value_bin += '1'
            else:
                value_bin = bin(value)[2:]
        # print(value_bin) #Debug
        return value_bin

    # Look for the DC code
    def DC_code(value):
        length = len(value)
        code = bin(DC_EHUFCO[length])[2:]
        size = DC_EHUFSI[length]
        code = '0' * (size - len(code)) + code
        # print(code) #Debug
        return code

    # Look for the AC code
    def AC_code(zero_counter, value):
        length = (zero_counter << 4) + len(value) # EHUFCO[ZERO/VALUE]
        code = bin(AC_EHUFCO[length])[2:]
        size = AC_EHUFSI[length]
        code = '0' * (size - len(code)) + code
        # print(code) #Debug
        return code

    # DC code
    value = get_value(block_list[0])
    result = DC_code(value) + value

    # AC code
    zero_counter = 0
    for index in range(1,len(block_list)):
        if block_list[index] == 0:
            zero_counter += 1
        else:
            while zero_counter > 15: # zeros over than 15
                zero_counter -= 16
                result += AC_code(15,get_value(0)) # AC Luma EHUFCO[F/0]
            value = get_value(block_list[index])
            result += AC_code(zero_counter, value) + value
            zero_counter = 0

    # EOB
    result += AC_code(0,get_value(0)) # AC Luma EHUFCO[0/0]
    return result

# input should be integer
def rgb2ycbcr(red, green, blue):
    luminance        =  0.257 * red + 0.564 * green + 0.098 * blue + 16
    blue_chrominance = -0.148 * red - 0.291 * green + 0.439 * blue + 128
    red_chrominance  =  0.439 * red - 0.368 * green - 0.071 * blue + 128
    return [int(luminance), int(blue_chrominance), int(red_chrominance)]


print("\n# ---------- RECIBIR CONTENIDO POR LA URL-------------------------------\n")
"""
>
<
"""
from flask import Flask
from flask import request

app = Flask(__name__)  #dice que nuestra app apunte a Flask

"""
Los programas en flask se llaman app

Las routes son las carpetas de la app:
    app/route/route  -- aqui se ve como la app sería la dirección ip y las routes cada una de las carpetas separadas por /
    http://127.0.0.1:5000/login/user

    app.route("/")
    app.route("/home")

    http://127.0.0.1:5000/home  -- ese

@app.route("/")        #crea una ruta, donde va a ir esta app. Cada py podrá ir en una ruta.
def hello():           #se ejecutará cuando se ponga 127.0.0.1:5000/
    return "Hey World! q pacha"
"""

@app.route("/images")  #asocia la función hello_images con 127.0.0.1:5000/images
def hello_images():    #se ejecutará cuando se ponga 127.0.0.1:5000/images
    return "Hello Images"

print("\n# ---------- QUERY STRING, RECIBIR CONTENIDO POR LA URL CON LAS VARIABLES--------------------------------\n")

""" ejemplo de como se ponen las variables en la url:
1270.0.01:5000/?variable1=2&variable2=b

ejemplo:
1270.0.01:5000/?nombre_url=alvaro&apellido_url=rodriguez
"""
@app.route("/")  #asocia la función hello_images con 127.0.0.1:5000/
@app.route("/<nombre>/<apellido>")  #asocia las variables de la funcion con la url, con esto se puede poner directamente en la url: http://127.0.0.1:5000/alvaro/rodri
def recibir_datos(nombre="invitado", apellido='vacio'):    #se ejecutará cuando se ponga 127.0.0.1:5000/images

    # recibe el nombre que se mete por la url. Si no se recibe nada por defecto pone Invitado
    return "Hello {} {}".format(nombre, apellido)

#EJEMPLO1 de suma pasando por url los campos y los valores
#http://127.0.0.1:5000\suma1?num1=5&num2=3
@app.route("/suma1")
def suma1(num1 = 0, num2 = 0):
    num1 = request.args.get('num1', num1)
    num2 = request.args.get('num2', num2)

    resultado = int(num1) + int(num2)
    return "{} mas {} es igua a {}".format(num1, num2, resultado)

print("\n# ---------- QUERY STRING, RECIBIR CONTENIDO POR LA URL SIN USAR LAS VARIABLES EN LA URL --------------------------------\n")
"""EJEMPLO2 de suma SIN pssar por url los campos y los valores

    http://127.0.0.1:5000/suma2/5/3
"""
@app.route("/suma/<num1>/<num2>")
@app.route("/suma/<int:num1>/<int:num2>")  #otra manera para que autoconvierta en int los numeros
@app.route("/sumar/<int:num1>/<int:num2>")  #admite varios routes para que llamen a una misma funcion
def suma2(num1 = 0, num2 = 0):

    #resultado = int(num1) + int(num2)
    resultado = num1 + num2   #si hemos puesto el int en el "app.route pues no nos hace falta el int en cada campo
    return "{} mas {} es igua a {}".format(num1, num2, resultado)

if  __name__ == "__main__":
    app.run(debug = True)  # con ésto se actualiza constantemente nuestra app en el servidor
    #app.run()  # con esto no se actualiza. Tendremos que parar el servidor y volver a arrancar


# Display a image and allow zooming in and out and scrolling

import os, sys
sys.path.insert(0, os.path.abspath(os.path.join("..")))

import tilewindow

import tkinter as tk
import tkinter.ttk as ttk
import tkinter.filedialog
import PIL.Image

root = tk.Tk()
tilewindow.util.stretch(root, rows=[1], columns=[0])

frame = ttk.Frame(root)
tilewindow.util.stretch(frame, [0], [0])
frame.grid(sticky=tk.NSEW, row=1)

image_widget = tilewindow.Image(frame)
image_widget.grid(row=0, column=0, sticky=tk.NSEW)
xscroll, yscroll = image_widget.make_scroll_bars(frame)
yscroll.grid(row=0, column=1, sticky=tk.NS)
xscroll.grid(row=1, column=0, sticky=tk.EW)

filename = tkinter.filedialog.askopenfilename(parent=root, filetypes=[("PNG file", "*.png"),
    ("JPEG file", "*.jpg"), ("Other PIL supported file", "*.*")])
image = PIL.Image.open(filename)
image_widget.set_image(image, allow_zoom=True)

xscroll.set_to_hide()
yscroll.set_to_hide()

frame = ttk.Frame(root)
frame.grid(sticky=tk.NSEW, row=0)
def no_zoom():
    image_widget.zoom = 1.0
ttk.Button(frame, text="Restore zoom", command=no_zoom).grid(row=0, column=0)
def zoom():
    w, h = image_widget.size
    zw = w / image.width
    zh = h / image.height
    image_widget.zoom = min(zw, zh)
ttk.Button(frame, text="Zoom to window", command=zoom).grid(row=0, column=1)

root.mainloop()


from tree import Tree
from copy import deepcopy
import sys

sys.setrecursionlimit(10000)

class AVL(Tree):
    def __init__(self, key, val=None, size=1, height=1):
        super().__init__(key=key, val=val, size=size)
        self.height = height

    def insert(self, key, val=None):
        if key is None:
            raise Exception(f"Pass None as Key, key")
        if val is None:
            val = key
        if self is None:
            return AVL(key=key, val=val, size=1)
        if key < self.key:
            self.left = AVL.insert(self.left, key, val)
        elif key > self.key:
            self.right = AVL.insert(self.right, key, val)
        else:
            self.value = val
        l_height = self.left.height if self.left else 0
        r_height = self.right.height if self.right else 0
        self.height = max(l_height, r_height) + 1
        tmp_size = 1
        if self.left:
            tmp_size += self.left.size
        if self.right:
            tmp_size += self.right.size
        self.size = tmp_size
        balance = self.get_balance()
        if not -2 < balance < 2:
            self.rebalance_tree(balance)
        return self

    def delete(self, key):
        if self is None:
            raise Exception(f"This node does not exists, that means that key: {key} does not exist in this tree")
        if self.key > key:
            self.left = AVL.delete(self.left, key)
        elif self.key < key:
            self.right = AVL.delete(self.right, key)
        else:
            if self.right is None:
                return self.left
            if self.left is None:
                return self.right
            tmp = deepcopy(self)
            self.rebuild_node(AVL._min(tmp.right))
            self.right = AVL._delete_min(tmp.right)
            self.left = tmp.left
        l_height = self.left.height if self.left else 0
        r_height = self.right.height if self.right else 0
        self.height = max(l_height, r_height) + 1
        self.size = 1
        must_rebalance_subtree = False
        if self.left:
            self.size += self.left.size
            must_rebalance_subtree = True
        if self.right:
            self.size += self.right.size
            must_rebalance_subtree = True
        balance = self.get_balance()
        if not -2 < balance < 2:
            self.rebalance_tree(balance)
        if must_rebalance_subtree:
            update_height(self)
            rebalance_subtree(self)
        return self

    def get_balance(self):
        l_height = self.left.height if self.left else 0
        r_height = self.right.height if self.right else 0
        return r_height - l_height

    def rebalance_tree(self, root_balance):
        if root_balance > 2:
            self.right.rebalance_tree(root_balance - 1)
        if root_balance < -2:
            self.left.rebalance_tree(root_balance + 1)
        if root_balance == 2:
            if self.right.get_balance() == -1:
                new_child = right_rotation(self.right)
                self.right = new_child
            new_self = left_rotation(self)
            self.rebuild_node(new_self)
        else:
            if self.left.get_balance() == 1:
                new_child = left_rotation(self.left)
                self.left = new_child
            new_self = right_rotation(self)
            self.rebuild_node(new_self)

    def rebuild_node(self, node):
        super().rebuild_node(node)
        self.height = node.height

def right_rotation(node):
    old_root = deepcopy(node)
    old_branch = deepcopy(node.left)
    old_leaf = deepcopy(node.left.right)
    node, node.right, node.right.left = old_branch, old_root, old_leaf
    update_height(node)
    update_size(node)
    return node

def left_rotation(node):
    old_root = deepcopy(node)
    old_branch = deepcopy(node.right)
    old_leaf = deepcopy(node.right.left)
    node, node.left, node.left.right = old_branch, old_root, old_leaf
    update_height(node)
    update_size(node)
    return node

def update_height(node):
    if node.left:
        update_height(node.left)
    if node.right:
        update_height(node.right)
    if not node.left and not node.right:
        node.height = 1
        return
    l_height = node.left.height if node.left else 0
    r_height = node.right.height if node.right else 0
    node.height = max(l_height, r_height) + 1

def update_size(node):
    if node.left:
        update_size(node.left)
    if node.right:
        update_size(node.right)
    if not node.left and not node.right:
        node.size = 1
        return
    l_size = node.left.size if node.left else 0
    r_size = node.right.size if node.right else 0
    node.size = l_size + r_size + 1

def rebalance_subtree(root):
    if not root.left and not root.right:
        return
    balance = root.get_balance()
    if not -2 < balance < 2:
        root.rebalance_tree(balance)
    if root.left:
        rebalance_subtree(root.left)
    if root.right:
        rebalance_subtree(root.right)


from openerp.osv import fields, osv
from openerp.tools.translate import _

class pos_shop(osv.osv):
    _name = 'pos.shop'

    _columns = {
        'name': fields.char('Shop Name', required=True),
        'company_id':fields.many2one('res.company', 'Company', required=True),
        'currency_id':fields.many2one('res.currency', 'Currency'),
        'config_ids': fields.one2many('pos.config', 'shop_id', 'POS Devices', readonly=True),
        'stock_location_id': fields.many2one('stock.location', 'Stock Location', domain=[('usage', '=', 'internal')]),
        'pricelist_id': fields.many2one('product.pricelist','Pricelist'),
        'journal_id' : fields.many2one('account.journal', 'Sale Journal', domain=[('type', '=', 'sale')]),
        'address': fields.char('Address'),
        'hotline': fields.char('Hotline'),
        'email': fields.char('Email'),
    }

    def _default_sale_journal(self, cr, uid, context=None):
        company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
        res = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'sale'), ('company_id', '=', company_id)], limit=1, context=context)
        return res and res[0] or False

    def _default_pricelist(self, cr, uid, context=None):
        res = self.pool.get('product.pricelist').search(cr, uid, [('type', '=', 'sale')], limit=1, context=context)
        return res and res[0] or False

    def _get_default_location(self, cr, uid, context=None):
        wh_obj = self.pool.get('stock.warehouse')
        user = self.pool.get('res.users').browse(cr, uid, uid, context)
        res = wh_obj.search(cr, uid, [('company_id', '=', user.company_id.id)], limit=1, context=context)
        if res and res[0]:
            return wh_obj.browse(cr, uid, res[0], context=context).lot_stock_id.id
        return False

    def _get_default_company(self, cr, uid, context=None):
        company_id = self.pool.get('res.users')._get_company(cr, uid, context=context)
        return company_id

    _defaults = {
        'journal_id': _default_sale_journal,
        'stock_location_id': _get_default_location,
        'company_id': _get_default_company,
        'pricelist_id': _default_pricelist,
    }

class pos_config(osv.osv):
    _inherit = 'pos.config'

    _columns = {
        'shop_id':fields.many2one('pos.shop', 'Shop', required=True),
        'udi': fields.char('Unique Device Indentifier', help="Restrict this Point of Sale to a physical device"),
    }


from textwrap import fill
from tkinter import *
from tkinter import ttk
from tkinter.simpledialog import askstring
from turtle import bgcolor
from Model_db import *

class View_db(Tk):

    def __init__(self, controller_db):
        super().__init__()
        self.model_db = Model_db()
        self.controller_db = controller_db
        #main window
        self.minsize(300, 500) #sellest väiksemaks ei saa akent teha
        self.resizable(True, True)
        self.title('Words CRUD')

        #frames
        self.first_frame = self.frame_1()
        self.r_canvas = self.results_canvas()
        self.b_canvas = self.buttons_canvas()

        #widgets
        self.view_values()

        #buttons
        self.delete_button()
        self.update_button()
        self.insert_button()

    def main(self):
        self.mainloop()

    def frame_1(self):
        frame = Frame(self)
        frame.pack(expand = True, fill='both', pady=10)
        return frame

    def frame_2(self):
        frame = Frame(self)
        frame.pack(expand = True, fill='both', pady=10)
        return frame

    def results_canvas(self):
        canvas = Canvas(self.first_frame)
        canvas.place(relx=0.5, anchor=N)
        return canvas

    def buttons_canvas(self):
        canvas = Canvas(self.first_frame)
        canvas.place(relx=0.5, rely=1.0, anchor=S) #all keskel
        return canvas

    def view_values(self):
        set = self.model_db.connection.execute('select id,word,category from words')
        keys = list(map(lambda x: x[0], set.description)) #võtab päringust välja tulba pealkirjad
        bi = 1
        self.i = 1
        self.var = IntVar()
        self.set=set.fetchall() # peab vahepeal fetchall tegema, muidu teine for loop ei tööta (tühi)
        #aken peab olema selline, et ei saaks klikkida mujal, kui rb ja nupud
        self.heading_word = Entry(self.r_canvas,relief=RAISED, bg='#F1F1F1', justify=CENTER)
        self.heading_word.grid(row=0,column=1)
        self.heading_word.insert(END,keys[1].capitalize())
        self.heading_category = Entry(self.r_canvas,relief=RAISED, bg='#F1F1F1', justify=CENTER)
        self.heading_category.grid(row=0,column=2)
        self.heading_category.insert(END,keys[2].capitalize())
        self.heading_word.config(state=DISABLED, disabledforeground='black') # värvi peab tagasi mustaks ka muutma, disabled peab pärast tekstisisestust olema
        self.heading_category.config(state=DISABLED, disabledforeground='black')

        for value in self.set:
            #print(value[0])
            self.rb = Radiobutton(self.r_canvas, variable = self.var, value=value[0],
                                   command=lambda:self.controller_db.view_button_id())  # siin tehakse radiobutton, mille külge pannakse var'ga db võetud id,
                                                                                #valides toimub controllerisse selle id saatmine
            self.rb.grid(row=bi, column=0)
            bi += 1

        for r in self.set:   #for loop nimetuste lugemiseks ja kuvamiseks
            self.e = Entry(self.r_canvas, bd=0, bg='#F1F1F1', justify=CENTER)
            self.e2= Entry(self.r_canvas, bd=0, bg='#F1F1F1', justify=CENTER)
            self.e.grid(row=self.i, column=1)
            self.e2.grid(row=self.i, column=2)
            self.e.insert(END,r[1])
            self.e.configure(state=DISABLED, disabledforeground='black') # disabledbackgroundi vaja ka vahetada!!! muidu hall
            self.e2.insert(END,r[2])
            self.e.config(state=DISABLED, disabledforeground='black')
            self.e2.config(state=DISABLED, disabledforeground='black')
            self.i += 1

    def delete_button(self):
        b = Button(self.b_canvas, text='Delete', command=lambda:self.controller_db.delete_value(), state=DISABLED) # Delete ja Update peavad alguses olema disabletud, sest kui radiobutton pole valitud, pole midagi kustutada
        b.grid(row=0, column=0, padx = 5, pady = 5)
        return b

    def update_button(self):
        b = Button(self.b_canvas, text='Update', command=lambda:self.controller_db.update_value(), state=DISABLED)
        b.grid(row = 0, column = 1, padx = 5, pady = 5)
        return b

    def insert_button(self):
        b = Button(self.b_canvas, text='Insert', command=lambda:self.controller_db.ask_value())
        b.grid(row = 0, column = 2, padx = 5, pady = 5)
        return b


from tkinter import *
from tkinter import ttk,messagebox
import pymysql
from pymysql import cursors

class Oc:
    def __init__(self,root):
        self.root = root
        self.root.title("Protocole accouchement OC")
        self.root.geometry("1220x690+50+10")
        self.root.resizable(width='False',height='False')

        frame_oc = Frame(self.root,bg='#7a1f5c')
        frame_oc.place(x=0,y=0,width=1220,height=690)

        #formulaire oc ------------------------------------------
        identite = LabelFrame(frame_oc,bg='#7a1f5c',font=("Arial",12),bd=0)
        dateoc = Label(identite,text="Date",font=("Arial",11),bg='#7a1f5c',fg='white')
        dateoc.grid(row=0,column=0)
        self.champ_dateoc = Entry(identite)
        self.champ_dateoc.grid(row=0,column=1)
        heureoc = Label(identite,text="Heure",font=("Arial",11),bg='#7a1f5c',fg='white')
        heureoc.grid(row=0,column=2)
        self.champ_heureoc = Entry(identite)
        self.champ_heureoc.grid(row=0,column=3)
        nom = Label(identite,text="Nom et Prenom",font=("Arial",11),bg='#7a1f5c',fg='white')
        nom.grid(row=2,column=0)
        self.champ_nom = Entry(identite)
        self.champ_nom.grid(row=2,column=1)
        age = Label(identite,text="Age",font=("Arial",11),bg='#7a1f5c',fg='white')
        age.grid(row=2,column=2)
        self.champ_age = Entry(identite)
        self.champ_age.grid(row=2,column=3)
        indication = Label(identite,text="Indication et diagnostic",font=("Arial",11),bg='#7a1f5c',fg='white')
        indication.grid(row=2,column=4)
        self.champ_indication = Entry(identite,width=100)
        self.champ_indication.grid(row=2,column=5)
        anesthesie = Label(identite,text="Type d'anesthesie",font=("Arial",11),bg='#7a1f5c',fg='white')
        anesthesie.grid(row=4,column=0)
        self.champ_anesthesie = ttk.Combobox(identite)
        self.champ_anesthesie["values"]=("ag","alr","l")
        self.champ_anesthesie.current(0)
        self.champ_anesthesie.grid(row=4,column=1)
        identite.grid(sticky='nw',padx=20,pady=10)

        intervention = LabelFrame(frame_oc,text="Intervention",labelanchor='nw',bg='#7a1f5c',font=("Arial",12),bd=0)
        self.champ_intervention = Entry(intervention,width=190)
        self.champ_intervention.grid(row=0)
        intervention.grid(sticky='wn',padx=20,pady=20,ipadx=20,ipady=10)

        parametre = LabelFrame(frame_oc,bg='#7a1f5c',font=("Arial",12),bd=0)
        ta = Label(parametre,text="TA",font=("Arial",11),bg='#7a1f5c',fg='white')
        ta.grid(row=0,column=0)
        self.champ_ta = Entry(parametre)
        self.champ_ta.grid(row=0,column=1)
        fc = Label(parametre,text="FC",font=("Arial",11),bg='#7a1f5c',fg='white')
        fc.grid(row=0,column=2)
        self.champ_fc = Entry(parametre)
        self.champ_fc.grid(row=0,column=3)
        diurese = Label(parametre,text="Diiurese",font=("Arial",11),bg='#7a1f5c',fg='white')
        diurese.grid(row=0,column=4)
        self.champ_diurese = Entry(parametre)
        self.champ_diurese.grid(row=0,column=5)
        saignement = Label(parametre,text="Saignement",font=("Arial",11),bg='#7a1f5c',fg='white')
        saignement.grid(row=0,column=6)
        self.champ_saignement = Entry(parametre)
        self.champ_saignement.grid(row=0,column=7)
        drain = Label(parametre,text="Drain",font=("Arial",11),bg='#7a1f5c',fg='white')
        drain.grid(row=0,column=8)
        self.champ_drain = Entry(parametre)
        self.champ_drain.grid(row=0,column=9)
        check_list = Label(parametre,text="Check list",font=("Arial",11),bg='#7a1f5c',fg='white')
        check_list.grid(row=0,column=10)
        self.champ_check_list = ttk.Combobox(parametre,state='readonly')
        self.champ_check_list["values"]=("oui","non")
        self.champ_check_list.current(0)
        self.champ_check_list.grid(row=0,column=11)
        parametre.grid(sticky='w',padx=20,pady=10)

        cat = LabelFrame(frame_oc,text="CAT post operatoire",labelanchor='nw',bg='#7a1f5c',font=("Arial",12),bd=0)
        self.champ_cat = Entry(cat,width=190)
        self.champ_cat.grid()
        cat.grid(sticky='ws',padx=20,pady=10,ipadx=10,ipady=5)

        operateur = LabelFrame(frame_oc,bg='#7a1f5c',font=("Arial",12),bd=0)
        nom_operateur = Label(operateur,text="Nom de l'operateur/Aide",font=("Arial",11),bg='#7a1f5c',fg='white')
        nom_operateur.grid(row=0,column=0)
        self.champ_nom_operateur = Entry(operateur,width=100)
        self.champ_nom_operateur.grid(row=0,column=1)
        nom_anesth_inf = Label(operateur,text="Nom de l'Anesthesiste/infirmier de bloc",font=("Arial",11),bg='#7a1f5c',fg='white')
        nom_anesth_inf.grid(row=2,column=0)
        self.champ_anesth_inf = Entry(operateur,width=100)
        self.champ_anesth_inf.grid(row=2,column=1)
        operateur.grid(sticky='sw',padx=20,pady=10)

        valider_boutton = Button(frame_oc,text="Enregistrer",command=self.ajout_oc,font=("Arial",11),bg='white',fg='#7a1f5c')
        valider_boutton.grid(sticky='s',padx=20,pady=10)

    def ajout_oc(self):
        con = pymysql.connect(host="localhost",user="root",password="",database="magesti")
        cur = con.cursor()
        cur.execute("insert into oc (date_oc,heure,nom,age,indication,anesthesie,intervention,ta,fc,diurese,saignement,drain,lists,cat,operateur,infirmier) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
                    (
                        self.champ_dateoc.get(),
                        self.champ_heureoc.get(),
                        self.champ_nom.get(),
                        self.champ_age.get(),
                        self.champ_indication.get(),
                        self.champ_anesthesie.get(),
                        self.champ_intervention.get(),
                        self.champ_ta.get(),
                        self.champ_fc.get(),
                        self.champ_diurese.get(),
                        self.champ_saignement.get(),
                        self.champ_drain.get(),
                        self.champ_check_list.get(),
                        self.champ_cat.get(),
                        self.champ_nom_operateur.get(),
                        self.champ_anesth_inf.get()
                     ))
        con.commit()
        self.reinitialiser()
        con.close()
        messagebox.showinfo("Succés","enregistrée avec succé")

    def reinitialiser(self):
        self.champ_dateoc.delete(0,END),
        self.champ_heureoc.delete(0,END),
        self.champ_nom.delete(0,END),
        self.champ_age.delete(0,END),
        self.champ_indication.delete(0,END),
        self.champ_anesthesie.delete(0,END),
        self.champ_intervention.delete(0,END),
        self.champ_ta.delete(0,END),
        self.champ_fc.delete(0,END),
        self.champ_diurese.delete(0,END),
        self.champ_saignement.delete(0,END),
        self.champ_drain.delete(0,END),
        self.champ_check_list.delete(0,END),
        self.champ_cat.delete(0,END),
        self.champ_nom_operateur.delete(0,END),
        self.champ_anesth_inf.delete(0,END)

#affichage -----------------------
root = Tk()
obj = Oc(root)
root.mainloop()


import numpy
from PIL import Image
import cv2

def median_filter(data, filter_size):
    temp = []
    indexer = filter_size // 2
    data_final = []
    data_final = numpy.zeros((len(data),len(data[0])))

    for i in range(len(data)):

        for j in range(len(data[0])):

            for z in range(filter_size):
                if i + z - indexer < 0 or i + z - indexer > len(data) - 1:
                    for c in range(filter_size):
                        temp.append(0)
                else:
                    if j + z - indexer < 0 or j + indexer > len(data[0]) - 1:
                        temp.append(0)
                    else:
                        for k in range(filter_size):
                            temp.append(data[i + z - indexer][j + k - indexer])

            temp.sort()
            data_final[i][j] = temp[len(temp) // 2]
            temp = []
    return data_final

def main():

    print ("Please wait a little bit ...")
    img = cv2.imread('Pikachu.jpg')

    b, g, r = cv2.split(img)
    arr = numpy.array(b)/255
    Blue = median_filter(arr, 3)

    arr = numpy.array(g)/255
    Green = median_filter(arr, 3)

    arr = numpy.array(r)/255
    Red = median_filter(arr, 3)

    filteredImage = cv2.merge((Blue, Green, Red))

    cv2.namedWindow('Filtered Image')
    cv2.imshow('Filtered Image', filteredImage)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

main()


import os
import argparse
from tqdm import tqdm
from fmengine.modeling.llama.hf_interface import to_hf_model

def convert_to_hf_format(args):
    print(args)
    if args.step == "all":
        steps = os.listdir(args.in_model_path)
        for step in steps:
            if os.path.isdir(
                os.path.join(args.in_model_path, step)
            ) and not os.path.exists(os.path.join(args.out_model_path, step)):
                to_hf_model(
                    in_model_path=args.in_model_path,
                    model_family=args.base_model,
                    out_model_path=os.path.join(args.out_model_path, step),
                    step=step,
                    is_lora_tuned=args.is_lora_tuned,
                )
    else:
        to_hf_model(
            in_model_path=args.in_model_path,
            model_family=args.base_model,
            out_model_path=args.out_model_path,
            step=args.step,
            is_lora_tuned=args.is_lora_tuned,
        )

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--in-model-path", type=str, required=True)
    parser.add_argument("--out-model-path", type=str, required=True)
    parser.add_argument("--base-model", type=str, required=True)
    parser.add_argument("--step", type=str, default="all")
    parser.add_argument("--is-lora-tuned", action="store_true", default=False)
    args = parser.parse_args()
    convert_to_hf_format(args)


# -*- coding: utf-8 -*-
"""
Created on Sat Apr  7 15:38:58 2018

@author: ankit
"""
import pandas as pd
import ast
import jellyfish as jf
#import numpy as np

basePath = 'C:\\MyStuff\\ASU\\Spring_2018\\NLP\\Project\\Clinical_NLP\\Dataset\\'

seqList = pd.read_csv(basePath + 'allClinicalNotesSeqCount_withoutEn2Et.csv', header = None)
seqList = seqList[1:]

headerMapDict = {'admission_date':'a',
 'allergies_and_adverse_reactions':'b',
 'chief_complaint':'c',
 'history_present_illness':'d',
 'review_of_systems':'e',
 'past_medical_history':'f',
 'social_history':'g',
 'family_history':'h',
 'physical_examination':'i',
 'assessment':'j',
 'laboratory_and_radiology_data':'k',
 'diagnoses':'l',
 'findings':'m',
 'hospital_course':'n',
 'medications':'o',
 'discharge_condition':'p',
 'activity':'q',
 'discharge_instructions':'r',
 'history_source':'s',
 'follow_up':'t',
 'assessment_and_plan':'u'}

def getSeqLen(seqList):
    seqListofList = ast.literal_eval(seqList)
    return len(seqListofList)

def getSeqList(seqList):
    seqListofList = ast.literal_eval(seqList)
    return seqListofList

print(seqList[2].max())
seqList['Seqlen'] = seqList[1].apply(getSeqLen)
#seqStr = str(maxSeqLen)
#print(seqList.loc[seqList[1] == seqStr][2])

seqListNew = seqList[seqList['Seqlen']>1]

top100ValDf = seqListNew[seqListNew[2] >= 100]
below100ValDf = seqListNew[seqListNew[2] < 100]

top100List = top100ValDf[1].tolist()
top100List = [ast.literal_eval(x) for x in top100List]

below100List = below100ValDf[1].tolist()
below100List = [ast.literal_eval(x) for x in below100List]

def getEditDistance(inp):
    global top10MapStr
    return [ jf.damerau_levenshtein_distance(x,inp) for x in top10MapStr]

def getCharRep(inp):
    return headerMapDict[inp]

def getMinList(inp):
    return min(inp)

top100MapStr = list(map(lambda x : ''.join(list(map(getCharRep,x))),top100List))
below100MapStr = list(map(lambda x : ''.join(list(map(getCharRep,x))),below100List))

editDist = list((map(getEditDistance,below100MapStr)))

# =============================================================================
# top10ValDf = seqListNew[seqListNew[2] >= 3000]
# below10ValDf = seqListNew[seqListNew[2] < 3000]
#
# top10List = top10ValDf[1].tolist()
# top10List = [ast.literal_eval(x) for x in top10List]
#
# below10List = below10ValDf[1].tolist()
# below10List = [ast.literal_eval(x) for x in below10List]
#
# top10MapStr = list(map(lambda x : ''.join(list(map(getCharRep,x))),top10List))
# below10MapStr = list(map(lambda x : ''.join(list(map(getCharRep,x))),below10List))
#
# editDist10 = list((map(getEditDistance,top10MapStr)))
#
# =============================================================================

editDistMin = list((map(getMinList,editDist)))

minCount = sum(x > 5 for x in editDistMin)

minCountIdx = [x > 5 for x in editDistMin]

below100ValDf['EditDistMin'] = minCountIdx

toRemoveDF = below100ValDf.loc[below100ValDf['EditDistMin'] == True]


class ronaldo:
    speacial = "Long Ranger"
    def __init__(self, shoot, pace):
        self.shoot = shoot
        self.pace = pace
    def det(self):
        return "Shoot: {}, Pace: {}, Specialaty: {}".format(self.shoot, self.pace, self.speacial)

class ronadojr(ronaldo):
        speacial = "Flair"
        def __init__(self, shoot, pace):
            super().__init__(shoot, pace)

class ronado2jr(ronadojr):
        # speacial = "Vision"
        def __init__(self, shoot, pace):
            super().__init__(shoot, pace)

p1 = ronaldo(93, 89)
print(p1.det())
p2 = ronadojr(82, 81)
print(p2.det())
p3 = ronado2jr(78, 76)
print(p3.det())

p2.speacial = "Attacking runner"
print(p2.det())

print(p3.det())