"""
Sum of the Longest Bloodline of a Tree (Sum of nodes on the longest path from root to leaf node)
Easy Accuracy: 49.91% Submissions: 10024 Points: 2
Given a binary tree of size N. Your task is to complete the function sumOfLongRootToLeafPath(), that find the sum of all nodes on the longest path from root to leaf node.
If two or more paths compete for the longest path, then the path having maximum sum of nodes is being considered.

Examples:

Input : Binary tree:
        4
       / \
      2   5
     / \ / \
    7  1 2  3
      /
     6
Output : 13

        4
       / \
      2   5
     / \ / \
    7  1 2  3
      /
     6

The highlighted nodes (4, 2, 1, 6) above are
part of the longest root to leaf path having
sum = (4 + 2 + 1 + 6) = 13
Input:
The function takes a single argument as input the reference pointer to the root of the binary tree.
There will be T, test cases and for each test case the function will be called separately.

Output:
For each test case print the required sum on a new line.

Constraints:
1<=T<=103
1<=N<=103

Example:
Input:
2
2
1 2 L 1 3 R
7
4 2 L 4 5 R 2 7 L 2 1 R 1 6 L 5 2 L 5 3 R
Output:
4
13
"""

def SumOfLongRootToLeafPath(root, Sum, Len, maxLen, maxSum):

    # if true, then we have traversed a
    # root to leaf path
    if (not root):

        # update maximum Length and maximum Sum
        # according to the given conditions
        if (maxLen[0] < Len):
            maxLen[0] = Len
            maxSum[0] = Sum
        elif (maxLen[0] == Len and
              maxSum[0] < Sum):
            maxSum[0] = Sum
        return

    # recur for left subtree
    SumOfLongRootToLeafPath(root.left, Sum + root.data,
                            Len + 1, maxLen, maxSum)

    # recur for right subtree
    SumOfLongRootToLeafPath(root.right, Sum + root.data,
                            Len + 1, maxLen, maxSum)

def sumOfLongRootToLeafPath(root):
    #:param root: root of the given tree.
    #:RETURN: SUM
    # result = list()
    # result = sumval(root)
    # return result[1]
    if (not root):
        return 0

    maxSum = [-999999999999]
    maxLen = [0]

    # finding the maximum Sum 'maxSum' for
    # the maximum Length root to leaf path
    SumOfLongRootToLeafPath(root, 0, 0, maxLen, maxSum)

    # required maximum Sum
    return maxSum[0]


# Programa que lê o nome e duas notas de vários alunos e guarda tudo em uma lista composta.
# No final, mostre um boletim contendo a média de cada um e permita que o usuário possa mostrar as notas
# de cada aluno individualmente.

boletim = []
cont = 0

while True:
    nome = str(input('Digite o nome do aluno: '))
    nota1 = float(input('Digite a 1ª nota do aluno: '))
    nota2 = float(input('Digite a 2ª nota do aluno: '))
    media = (nota1 + nota2) / 2
    boletim.append([nome, [nota1, nota2], media])
    while True:
        continuar = str(input('Deseja continuar? (S/N)? ')).strip().upper()[0]
        if continuar in 'SN':
            break
        else:
            print('Digite S para sim e N para Não.')
        # end-if-else
    # end-while
    if continuar == 'N':
        break
    # end-if
# end while
print('-=-=-=-=-=BOLETIM-=-=-=-=-=')
print(f'{"Nº":<4}{"Nome":<10}{"Media":>8}')
for i, a in enumerate(boletim):
    print(f'{i}                   {a[0]}                        {a[2]}')
# end for
while True:
    escolha=int(input('Escolha o aluno que deseja ver as notas. 999 para sair: '))
    if escolha == 999:
        print('Fechando o programa. Até mais!')
        break
    else:
        print(f'Aluno(a): {boletim[escolha][0]} - Nota 1: {boletim[escolha][1][0]} - Nota 2: {boletim[escolha][1][1]}')
    # end-if-else
# end-while


from bs4 import BeautifulSoup
import requests
import pymongo
import json

url = 'https://www.bolsamadrid.es/esp/aspx/Mercados/Precios.aspx?indice=ESI100000000&punto=indice'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')

tabla = soup.find(id='ctl00_Contenido_tblAcciones')
filas = tabla.findAll('tr')

empresasDict = {}
hora = {}

for row in filas[1:]:
    datos_html = row.find_all("td")
    datos_fila = list(map(lambda data: data.text, datos_html))

    nombre = datos_fila[0]
    fecha = datos_fila[7]
    hora[str(nombre)] = datos_fila[8]

    empresasDict[str(nombre)] = {
        "nombre": nombre,
        "fecha": fecha,
        "hora": str(hora[str(nombre)]),
        "ultimo": float(datos_fila[1].replace(",", ".")),
        "%dif": float(datos_fila[2].replace(",", ".")),
        "max": float(datos_fila[3].replace(",", ".")),
        "min": float(datos_fila[4].replace(",", ".")),
        "volumen": int(datos_fila[5].replace(".", "")),
        "efectivo": float(datos_fila[6].replace(".", "").replace(",", "."))
    }

client = pymongo.MongoClient("mongodb://admin:password@localhost:7070/bolsa")

db = client["bolsa"]
col = db["empresas"]
col2 = db["datos"]

for key in empresasDict:
    col.insert_one(empresasDict[key])
    col2.insert_one(empresasDict[key])


from fastapi import FastAPI
from .models import Item

app = FastAPI()

def __init__(self):
    pass

# v1=================================================================================================
# http://127.0.0.1:8000/
@app.get('/')
def index():
    return {'hello': 'word'}

# http://127.0.0.1:8000/v1/index
@app.get('/v1/index')
def index():
    return {'name': 'flack'}

# http://127.0.0.1:8000/v1/items/123?q=safdf
@app.get('/v1/items/{item_id}')
def get_items(item_id: int, q: str = None):
    return {'item_id': item_id, 'q': q}

@app.put('/v1/items/{item_id}')
async def update_item(item_id: int, item: Item):
    return {'item_id': item_id, 'item_name': item.name}

@app.get('/v1/user/{uid}')
async def user(uid: str):
    return {
        'uid': uid,
        'name': 'flack',
        'age': 23,
        'address': 'shenzhen',
        'score': 100,
        'work': 10
    }

# async def app(scope, receive, send):
#     assert scope['type'] == 'http'
#
#     await send({
#         'type': 'http.response.start',
#         'status': 200,
#         'headers': [
#             [b'content-type', b'text/plain'],
#         ],
#     })
#     await send({
#         'type': 'http.response.body',
#         'body': b'Hello, world!',
#     })

# async def hello_world(message, channels):
#     content = b'
Hello World
'
#     resp = {
#         'status': 200,
#         'headers': [[b'content-type', b'text/html'], ],
#         'content': content,
#     }
#
#     await channels['reply'].send(resp)

def run():
    print('factory api running...')
    return app

# v1=================================================================================================


import  math
def bisection(function,a,b):
    start=a
    end =b
    if function(a)==0:
        return  a
    if function(b)==0:
        return b
    elif(function(a),function(b)>0):
        print("could n'f find a root")
        return
    else:
        mid=start+(end-start)/2.0
        while abs(start-mid)>10**-7:
            if function(mid)==0:
                return mid
            elif function(mid)*funcion(start)<0:
                end=mid
            else:
                start=mid
            mid=start+(end-start)/2.0
        return mid

def f(x):
    return math.pow(x,3)-2*x -5

if __name__=='__main__':
    print(bisection(f,1,1000))


import sys
import datetime

'''
redshift_utils_helper.py

Utility modules for the amazon-redshift-utils family of tools

Ian Meyers
Amazon Web Services (2017)
'''

debug = False

# emit a single cloudwatch metric with the given dimensions
def put_metric(cw, namespace, metric_name, dimensions, timestamp, value, unit):
    emit_metrics(cw, namespace, [{
        'MetricName': metric_name,
        'Dimensions': dimensions,
        'Timestamp': datetime.datetime.utcnow() if timestamp is None else timestamp,
        'Value': value,
        'Unit': unit
    }])

# emit all the provided cloudwatch metrics consistent with API limits around batching
def emit_metrics(cw, namespace, put_metrics):
    max_metrics = 20
    group = 0
    print("Publishing %s CloudWatch Metrics" % (len(put_metrics)))

    for x in range(0, len(put_metrics), max_metrics):
        group += 1

        # slice the metrics into blocks of 20 or just the remaining metrics
        put = put_metrics[x:(x + max_metrics)]

        if debug:
            print("Metrics group %s: %s Datapoints" % (group, len(put)))
            print(put)
        try:
            cw.put_metric_data(
                Namespace=namespace,
                MetricData=put
            )
        except:
            print('Pushing metrics to CloudWatch failed: exception %s' % sys.exc_info()[1])

def set_search_paths(conn, schema_name, set_target_schema=None, exclude_external_schemas=False):
    get_schemas_statement = '''
        select nspname
        from pg_catalog.pg_namespace
        where nspname ~ '%s'
    ''' % schema_name

    if exclude_external_schemas is True:
        get_schemas_statement += " and nspname not in (select schemaname from svv_external_schemas)"

    # set default search path
    search_path = 'set search_path = \'$user\',public'

    # add the target schema to the search path
    if set_target_schema is not None and set_target_schema != schema_name:
        search_path = search_path + ', %s' % set_target_schema

    # add all matched schemas to the search path - this could be a single schema, or a pattern
    c = conn.cursor()
    c.execute(get_schemas_statement)
    results = c.fetchall()

    for r in results:
        search_path = search_path + ', %s' % r[0]

    if debug:
        print(search_path)

    c = conn.cursor()
    c.execute(search_path)


def get_vacations():
        """
        Pull the accounts vacations.
        """
        arequest = requests.get(VACATIONS_URL, headers=HEADERS)
        status_code = str(arequest.status_code)
        if status_code == '401':
            _LOGGER.error("Token expired.")
            return False
        return arequest.json()


from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from rest_framework import authentication
from rest_framework import exceptions
from .hanko import authenticate as hanko_authenticate

User = get_user_model()

def deny(reason):
    raise exceptions.AuthenticationFailed(str(reason))

def extract_token_from_header(header: str) -> str:
    parts = header.split()
    return parts[1] if len(parts) == 2 and parts[0].lower() == "bearer" else None

class HankoAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        authorization = request.headers.get("Authorization")
        if not authorization:
            return None

        token = extract_token_from_header(authorization)
        if not token:
            return deny('No token')

        valid,token_data = hanko_authenticate(token)
        if not valid:
            return deny(token_data)
        if valid:
            if not token_data:
                deny("No data in token")

        hanko_id = token_data.get('sub')

        try:
            user = User.objects.get(hankoprofile__hanko_id = hanko_id)
        except User.DoesNotExist:
            deny('No such user')
        return (user, None)


import gf

DEBUG = False

BYTE_SIZE = 8
CHUNK_SIZE = BYTE_SIZE

class parity:
    def __init__(self, number_of_disk=8):
        self.F = gf.FField(number_of_disk)

    def compute_P(self,list_chunks):
        c = list_chunks[0]
        for x in list_chunks[1:]:
            c = c ^ x
        return c

    def compute_Q(self,list_chunks):
        c = list_chunks[0]
        for i in range(1,len(list_chunks)):
            c = c ^ self.F.Multiply(2**i, list_chunks[i])

        return c

    def recover_one_chunk_with_P(self,remaining_chunks, P_chunk):
        c = P_chunk
        for x in remaining_chunks:
            c = c ^ x

        return c

    def recover_one_chunk_with_Q(self,all_disk_chunks, Q_chunk, missing_chunk_index):
        c = Q_chunk
        for i in range(0,len(all_disk_chunks)):
            if i == missing_chunk_index:
                continue

            c = c ^ self.F.Multiply(2**i, all_disk_chunks[i])

        return self.F.Multiply(self.F.Inverse(2**missing_chunk_index), c)

    def recover_two_chunk(self,all_disk_chunks, P_chunk, Q_chunk, missing_chunk_1, missing_chunk_2):
        A = P_chunk
        B = Q_chunk
        for i in range(0,len(all_disk_chunks)):
            if i in [missing_chunk_1, missing_chunk_2]:
                continue

            A = A ^ all_disk_chunks[i]
            B = B ^ self.F.Multiply(2**i, all_disk_chunks[i])

        D_1 = self.F.Multiply(self.F.Inverse(2**missing_chunk_1 ^ 2**missing_chunk_2), self.F.Multiply(2**missing_chunk_2, A) ^ B)
        D_2 = A ^ D_1
        return D_1,D_2

if (DEBUG):
    TEST_LIST = [0b11111111,0b11110101,0b11110011]
    print(TEST_LIST)

    P = (compute_P(TEST_LIST))
    print("P",P, type(P))
    Q = (compute_Q(TEST_LIST))
    print("Q",Q, type(Q))

    print("Recovered:",recover_one_chunk_with_P(TEST_LIST[:-1], P))
    print("Recovered:",recover_one_chunk_with_Q(TEST_LIST, Q, 1))

    TEST_LIST = [0b11111111,0,0]

    print("Recovered:",recover_two_chunk(TEST_LIST, P, Q, 1, 2))


from sklearn.neighbors import KNeighborsRegressor
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_absolute_error

def knn_regressor(inputs, output):
  k_mae = []
  for k in range(10):
    # Setting testing and training data
    x_train, x_test, y_train, y_test = train_test_split(inputs, output, test_size=0.1, train_size=0.9)

    scaler = StandardScaler()
    x_train = scaler.fit_transform(x_train)
    x_test = scaler.fit_transform(x_test)

    # Instantiating KNN regressor
    knn_regressor = KNeighborsRegressor(n_neighbors=k+1)
    knn_regressor.fit(x_train, y_train)

    # Defining predictions
    y_pred = knn_regressor.predict(x_test)

    # Getting mean absolute error
    mae = mean_absolute_error(y_test, y_pred)
    k_mae.append(mae)

  return k_mae


#! python3
# scraping_xkcd.py - Downloads every single XKCD comic.

import bs4
import os
import requests

url = 'http://xkcd.com'                     # starting url
os.makedirs('xkcd', exist_ok=True)          # store comics in .\xkcd (if the folder already exists, it's fine)
while not url.endswith('#'):                # https://xkcd.com/1/# is the very last page, clicking on 'PREV' button
    print(f'Downloading page {url}...')
    res = requests.get(url)                 # response object - download the page
    res.raise_for_status()                  # doesn't do anything if the download succeded

    soup = bs4.BeautifulSoup(res.text, "html.parser")      # beautifulsoup object from the text of the downloaded page
    comic_elem = soup.select('#comic img')  # select <img> element inside <div> element with id='comic'

    if not comic_elem:
        print('Could not find comic image.')
    else:
        try:
            comic_url = 'http:' + comic_elem[0].get('src')

            # Download the image.
            print(f'Downloading image {comic_url}...')      # example: http: + //imgs.xkcd.com/comics/comic_image.jpg
            res = requests.get(comic_url)                   # response object - download the image
            res.raise_for_status()                          # if the download failed, continue to the 'exception'
        except requests.exceptions.MissingSchema:           # (http or https is missing)

            # FAILED. Get the Prev button's url to continue iterating and try to find a comic again.
            prev_link = soup.select('a[rel="prev"]')[0]      # select <a> element with rel="prev" attribute
            url = 'http://xkcd.com' + prev_link.get('href')  # URL for the next iteration of the WHILE NOT loop
            continue                                         # jump back to the start of the WHILE NOT loop

        # Save the image to .\xkcd.
        image_file = open(os.path.join('xkcd', os.path.basename(comic_url)), 'wb')  # like .\xkcd\comic_image.png
        for chunk in res.iter_content(100000):
            image_file.write(chunk)
        image_file.close()

        # !! this is the end of ELSE clause !!

    # SUCCESS. Get the Prev button's url to continue iterating and find another comic.
    prev_link = soup.select('a[rel="prev"]')[0]
    url = 'http://xkcd.com' + prev_link.get('href')          # URL for the next iteration of WHILE NOT loop

print('Done.')

"""
Errors can be handled with TRY and EXCEPT statements.
The code that could potentially have an error is put in a try clause.
The program execution moves to the start of a following except clause if an error happens.

Selector passed to the select() method - Will match...

soup.select('div') - All elements named <div>.
soup.select('#author') - The element with an id attribute of author.
soup.select('.notice') - All elements that use a CSS class attribute named notice.
soup.select('div span') - All elements named <span> that are within an element named <div>.
soup.select('div > span') - All elements named <span> that are directly within an element named <div>,
                            with no other element in between.
soup.select('input[name]') - All elements named <input> that have a name attribute with any value.
soup.select('input[type="button"]') - All elements named <input> that have an attribute named type with value button.
"""


class node:
    cost = -1
    linhaAntiga = None
    colunaAntiga = None
    linhaNova = None
    colunaNova = None
    pecaComida = None
    def __init__(self,cost,linhaAntiga,colunaAntiga,linhaNova,colunaNova):
        self.cost = cost
        self.linhaAntiga = linhaAntiga
        self.linhaNova = linhaNova
        self.colunaAntiga = colunaAntiga
        self.colunaNova = colunaNova


def final_pose_calc(path_plan):
    base = 0.156

    delta_time = path_plan[0]
    left_vel = path_plan[1]
    right_vel = path_plan[2]
    init_x = path_plan[3]
    init_y = path_plan[4]
    init_theta = path_plan[5]
    if right_vel - left_vel == 0:
        R = math.isinf(float("-inf"))
        omega = 0
    else:
        omega = (right_vel - left_vel)/base
        R = ((right_vel + left_vel)/(right_vel-left_vel))*(base/2)

    ICC = [(init_x - (R*math.sin(init_theta))), (init_y + (R*math.cos(init_theta)))]

    A = np.array([ [ math.cos(omega*delta_time), -math.sin(omega*delta_time), 0],
                   [ math.sin(omega*delta_time), math.cos(omega*delta_time), 0],
                   [0, 0, 1] ])

    B = np.array([ [init_x - ICC[0]],
                   [init_y - ICC[1]],
                   [init_theta] ])

    C = np.array([ [ICC[0]],
                   [ICC[1]],
                   [omega*delta_time] ])

    D = A.dot(B)

    final = sum_matrix(D, C)
    print(final)

def sum_matrix(X,Y):
    result = [[0,0,0],
              [0,0,0],
              [0,0,0]]

    for i in range(len(X)):
# iterate through columns
       for j in range(len(X[0])):
           result[i][j] = X[i][j] + Y[i][j]

    # for r in result:
    #     # print(r)

    return result


import json
from channels.generic.websocket import AsyncWebsocketConsumer
from .models import Message, Group
from asgiref.sync import sync_to_async

class GroupChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.group_id = self.scope['url_route']['kwargs']['group_id']
        self.group = await self.get_group_or_error(self.group_id)
        print("id",self.group_id)

        # Join the group channel
        await self.channel_layer.group_add(
            self.group.name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):
        # Leave the group channel
        await self.channel_layer.group_discard(
            self.group.name,
            self.channel_name
        )

    async def receive(self, text_data):
        data = json.loads(text_data)
        message_content = data['message']
        user = self.scope['user']

        # Create and save the message to the database
        # message = await Message.objects.create(
        #     user=user,
        #     group=self.group,
        #     content=message_content
        # )

        message = await self.save_message_to_database(user,group =self.group, content = message_content)

        # Send the message to the group
        await self.channel_layer.group_send(
            self.group.name,
            {
                'type': 'chat_message',
                'message': message_content,
                'username': user.username,
                'timestamp': message.timestamp.strftime('%Y-%m-%d %H:%M:%S'),
            }
        )

    async def chat_message(self, event):
        await self.send(text_data=json.dumps(event))

    @sync_to_async
    def save_message_to_database(self, user, group, content):
        message = Message.objects.create(
            user=user,
            group=group,
            content=content,
        )
        return message

    @sync_to_async
    def get_group_or_error(self, group_id):
        try:
            group = Group.objects.get(id=group_id)
            print(self.scope['user'])
            if not self.scope['user'].members.filter(id=group.id).exists():
                raise ValueError('You do not have permission to join this group.')
            return group
        except Group.DoesNotExist:
            raise ValueError('Group not found.')


from tkinter import *
import tkinter.ttk as ttk
import math as m
import random as rand

window = Tk()
window.title("Calculator")
TAB_CONTROL = ttk.Notebook(window)

e = Entry(window, width=50, borderwidth=5, relief=RIDGE, fg="white", bg="Black")
e.pack(expand=1, padx=10, pady=15)

TAB1 = ttk.Frame(TAB_CONTROL)
TAB_CONTROL.add(TAB1, text='Standard')
TAB2 = ttk.Frame(TAB_CONTROL)
TAB_CONTROL.add(TAB2, text='Numerals')
TAB_CONTROL.pack(expand=1, fill="both")
TAB3 = ttk.Frame(TAB_CONTROL)
TAB_CONTROL.add(TAB3, text='Trigonometric')
TAB_CONTROL.pack(expand=1, fill="both")

def click(to_print):
    old = e.get()
    e.delete(0, END)
    e.insert(0, old+to_print)
    return

def clear():
    e.delete(0, END)
    return

def bksps():
    current = e.get()
    length = len(current)-1
    e.delete(length, END)

def evaluate():
    try:
        ans = e.get()
        ans = eval(ans)
    except Exception:
        ans = "Syntax Error"

    e.delete(0, END)
    e.insert(0, ans)

def sc(event):
    try:
        key = event.widget
        text = key['text']
        no = e.get()
        result = ''
        if text == 'deg':
            result = str(m.degrees(float(no)))
        if text == 'rad':
            result = str(m.radians(float(no)))
        if text == 'rand':
            result = str(rand.random())
        if text == 'ceil':
            result = str(m.ceil(no))
        if text == 'floor':
            result = str(m.floor(no))
        if text == 'sin':
            result = str(m.sin(float(no)))
        if text == 'cos':
            result = str(m.cos(float(no)))
        if text == 'tan':
            result = str(m.tan(float(no)))
        if text == 'sinh':
            result = str(m.sinh(float(no)))
        if text == 'asin':
            result = str(m.asin(float(no)))
        if text == 'asinh':
            result = str(m.asinh(float(no)))
        if text == 'cos':
            result = str(m.cos(float(no)))
        if text == 'cosh':
            result = str(m.cosh(float(no)))
        if text == 'acos':
            result = str(m.acos(float(no)))
        if text == 'acosh':
            result = str(m.acosh(float(no)))
        if text == 'tan':
            result = str(m.tan(float(no)))
        if text == 'tanh':
            result = str(m.tanh(float(no)))
        if text == 'atan':
            result = str(m.atan(float(no)))
        if text == 'atanh':
            result = str(m.atanh(float(no)))
        if text == 'lg':
            result = str(m.log10(float(no)))
        if text == 'ln':
            result = str(m.log(float(no)))
        if text == '√x':
            result = str(m.sqrt(float(no)))
        if text == 'x!':
            result = str(m.factorial(float(no)))
        if text == '1/x':
            result = str(1/(float(no)))
        if text == 'pi':
            if no == '':
                result = str(m.pi)
            else:
                result = str(float(no) * m.pi)
        if text == 'e':
            if no == '':
                result = str(m.e)
            else:
                result = str(float(no) * m.e)
        if text == '2^':
            if no == '':
                result = "2**"
            else:
                result = str(2**float(no))
        if text == '10^':
            if no == '':
                result = "10**"
            else:
                result = str(10**float(no))
        if text == '^2':
            result = str(float(no)**2)
    except Exception:
        result = "Syntax Error"

    e.delete(0, END)
    e.insert(0, result)

'''------------------------------------------------------------------------------------------------------'''
ac = Button(TAB2, text='C', padx=29, pady=10, relief=RAISED, bg="#C82C0B", fg="White", command=lambda: clear())
bksp = Button(TAB2, text='⌫', padx=24, pady=10, relief=RAISED, bg="#C82C0B", fg="White", command=lambda: bksps())

twopw = Button(TAB2, text='2^', padx=26, pady=10, relief=RAISED, bg="Black", fg="White")
twopw.bind("<Button-1>", sc)
randb = Button(TAB2, text='rand', padx=20, pady=10, relief=RAISED, bg="Black", fg="White")
randb.bind("<Button-1>", sc)
exp = Button(TAB2, text='exp', padx=22, pady=10, relief=RAISED, bg="Black", fg="White", command=lambda: click("e+"))
ceil = Button(TAB2, text='ceil', padx=24, pady=10, relief=RAISED, bg="Black", fg="White")
floor = Button(TAB2, text='floor', padx=20, pady=10, relief=RAISED, bg="Black", fg="white")

square = Button(TAB2, text="^2", padx=26, pady=10, relief=RAISED, bg="Black", fg="White")
square.bind("<Button-1>", sc)
frac = Button(TAB2, text="1/x", padx=23, pady=10, relief=RAISED, bg="Black", fg="White")
frac.bind("<Button-1>", sc)
absb = Button(TAB2, text="|x|", padx=26, pady=10, relief=RAISED, bg="black", fg='white', command=lambda: click("abs("))
e_b = Button(TAB2, text='e', padx=30, pady=10, relief=RAISED, bg="Black", fg="White")
e_b.bind("<Button-1>", sc)
pib = Button(TAB2, text="pi", padx=27, pady=10, relief=RAISED, bg="Black", fg="White")
pib.bind("<Button-1>", sc)

sqrtm = Button(TAB2, text='√x', padx=26, pady=10, relief=RAISED, bg="Black", fg="White")
sqrtm.bind("<Button-1>", sc)
par1st = Button(TAB2, text='(', padx=29, pady=10, relief=RAISED, bg="Black", fg="White", command=lambda: click("("))
par2nd = Button(TAB2, text=')', padx=30, pady=10, relief=RAISED, bg="Black", fg="White", command=lambda: click(")"))
fact = Button(TAB2, text="x!", padx=28, pady=10, relief=RAISED,bg="Black", fg="White")
fact.bind("<Button-1>", sc)
mod = Button(TAB2, text='mod', padx=20, pady=10, relief=RAISED, bg="Black", fg="White", command=lambda: click("%"))

power = Button(TAB2, text='^', padx=29, pady=10, relief=RAISED, bg="Black", fg="White", command=lambda: click("**"))
seven = Button(TAB2, text="7", padx=28, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("7"))
eight = Button(TAB2, text="8", padx=29, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("8"))
nine = Button(TAB2, text="9", padx=29, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("9"))
div = Button(TAB2, text='/', padx=29, pady=10, relief=RAISED, bg="Black", fg="White", command=lambda: click("/"))

tenpw = Button(TAB2, text='10^', padx=23, pady=10, relief=RAISED, bg="Black", fg='white', command=lambda: click("10**"))
tenpw = Button(TAB2, text='10^', padx=23, pady=10, relief=RAISED, bg="Black", fg='white')
tenpw.bind("<Button-1>", sc)
four = Button(TAB2, text="4", padx=28, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("4"))
five = Button(TAB2, text="5", padx=29, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("5"))
six = Button(TAB2, text="6", padx=29, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("6"))
mult = Button(TAB2, text="*", padx=29, pady=10, relief=RAISED, bg="Black", fg="White", command=lambda: click("*"))

lg = Button(TAB2, text='log', padx=24, pady=10, relief=RAISED, bg="Black", fg="White")
lg.bind("<Button-1>", sc)
one = Button(TAB2, text="1", padx=28, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("1"))
two = Button(TAB2, text="2", padx=29, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("2"))
three = Button(TAB2, text="3", padx=29, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("3"))
minus = Button(TAB2, text="-", padx=29, pady=10, relief=RAISED, bg="Black", fg="White", command=lambda: click("-"))

ln = Button(TAB2, text='ln', padx=28, pady=10, relief=RAISED, bg="Black", fg="White")
lg.bind("<Button-1>", sc)
dot = Button(TAB2, text='.', padx=29.5, pady=10, relief=RAISED, bg="Black", fg="White", command=lambda: click("."))
zero = Button(TAB2, text='0', padx=28, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("0"))
equal = Button(TAB2, text='=', padx=28, pady=10, relief=RAISED, bg="Orange", fg="Black", command=lambda: evaluate())
plus = Button(TAB2, text="+", padx=28, pady=10, relief=RAISED, bg="Black", fg="White", command=lambda: click("+"))

ac.grid(row=1, column=3)
bksp.grid(row=1, column=4)

twopw.grid(row=2, column=0)
randb.grid(row=2, column=1)
exp.grid(row=2, column=2)
ceil.grid(row=2, column=3)
floor.grid(row=2, column=4)

square.grid(row=3, column=0)
frac.grid(row=3, column=1)
absb.grid(row=3, column=2)
e_b.grid(row=3, column=3)
pib.grid(row=3, column=4)

sqrtm.grid(row=4, column=0)
par1st.grid(row=4, column=1)
par2nd.grid(row=4, column=2)
fact.grid(row=4, column=3)
mod.grid(row=4, column=4)

power.grid(row=5, column=0)
seven.grid(row=5, column=1)
eight.grid(row=5, column=2)
nine.grid(row=5, column=3)
div.grid(row=5, column=4)

tenpw.grid(row=6, column=0)
four.grid(row=6, column=1)
five.grid(row=6, column=2)
six.grid(row=6, column=3)
mult.grid(row=6, column=4)

lg.grid(row=7, column=0)
one.grid(row=7, column=1)
two.grid(row=7, column=2)
three.grid(row=7, column=3)
minus.grid(row=7, column=4)

ln.grid(row=8, column=0)
dot.grid(row=8, column=1)
zero.grid(row=8, column=2)
equal.grid(row=8, column=3)
plus.grid(row=8, column=4)

'''------------------------------------------------------------------------------------------------------'''

ac = Button(TAB1, text='C', padx=36.5, pady=15, relief=RAISED, bg="#C82C0B", fg="White", command=lambda: clear())
bksp = Button(TAB1, text='⌫', padx=35, pady=15, relief=RAISED, bg="#C82C0B", fg="White", command=lambda: bksps())

frac = Button(TAB1, text="1/x", padx=33, pady=15, relief=RAISED, bg="Black", fg="White")
frac.bind("<Button-1>", sc)
fact = Button(TAB1, text="x!", padx=35, pady=15, relief=RAISED,bg="Black", fg="White")
fact.bind("<Button-1>", sc)
square = Button(TAB1, text="^2", padx=35, pady=15, relief=RAISED, bg="Black", fg="White")
square.bind("<Button-1>", sc)
sqrtm = Button(TAB1, text='√x', padx=35, pady=15, relief=RAISED, bg="Black", fg="White")
sqrtm.bind("<Button-1>", sc)

seven = Button(TAB1, text="7", padx=38, pady=15, relief=RAISED, bg="Grey", fg="White", command=lambda: click("7"))
eight = Button(TAB1, text="8", padx=37, pady=15, relief=RAISED, bg="Grey", fg="White", command=lambda: click("8"))
nine = Button(TAB1, text="9", padx=38, pady=15, relief=RAISED, bg="Grey", fg="White", command=lambda: click("9"))
div = Button(TAB1, text='/', padx=40, pady=15, relief=RAISED, bg="Black", fg="White", command=lambda: click("/"))

four = Button(TAB1, text="4", padx=38, pady=15, relief=RAISED, bg="Grey", fg="White", command=lambda: click("4"))
five = Button(TAB1, text="5", padx=37, pady=15, relief=RAISED, bg="Grey", fg="White", command=lambda: click("5"))
six = Button(TAB1, text="6", padx=38, pady=15, relief=RAISED, bg="Grey", fg="White", command=lambda: click("6"))
mult = Button(TAB1, text="*", padx=40, pady=15, relief=RAISED, bg="Black", fg="White", command=lambda: click("*"))

one = Button(TAB1, text="1", padx=38, pady=15, relief=RAISED, bg="Grey", fg="White", command=lambda: click("1"))
two = Button(TAB1, text="2", padx=37, pady=15, relief=RAISED, bg="Grey", fg="White", command=lambda: click("2"))
three = Button(TAB1, text="3", padx=38, pady=15, relief=RAISED, bg="Grey", fg="White", command=lambda: click("3"))
minus = Button(TAB1, text="-", padx=40, pady=15, relief=RAISED, bg="Black", fg="White", command=lambda: click("-"))

dot = Button(TAB1, text='.', padx=40, pady=15, relief=RAISED, bg="Black", fg="White", command=lambda: click("."))
zero = Button(TAB1, text='0', padx=37, pady=15, relief=RAISED, bg="Grey", fg="White", command=lambda: click("0"))
equal = Button(TAB1, text='=', padx=38, pady=15, relief=RAISED, bg="Orange", fg="Black", command=lambda: evaluate())
plus = Button(TAB1, text="+", padx=38, pady=15, relief=RAISED, bg="Black", fg="White", command=lambda: click("+"))

ac.grid(row=1, column=2)
bksp.grid(row=1, column=3)

frac.grid(row=2, column=0)
fact.grid(row=2, column=1)
square.grid(row=2, column=2)
sqrtm.grid(row=2, column=3)

seven.grid(row=3, column=0)
eight.grid(row=3, column=1)
nine.grid(row=3, column=2)
div.grid(row=3, column=3)

four.grid(row=4, column=0)
five.grid(row=4, column=1)
six.grid(row=4, column=2)
mult.grid(row=4, column=3)

one.grid(row=5, column=0)
two.grid(row=5, column=1)
three.grid(row=5, column=2)
minus.grid(row=5, column=3)

dot.grid(row=6, column=0)
zero.grid(row=6, column=1)
equal.grid(row=6, column=2)
plus.grid(row=6, column=3)
'''------------------------------------------------------------------------------------------------------'''

sinh = Button(TAB3, text="sinh", padx=29, pady=10, relief=RAISED, bg='black', fg='white')
sinh.bind("<Button-1>", sc)
asin = Button(TAB3, text="asin", padx=29, pady=10, relief=RAISED, bg='black', fg='white')
asin.bind("<Button-1>", sc)
acos = Button(TAB3, text='acos', padx=29, pady=10, relief=RAISED, bg='black', fg='white')
acos.bind("<Button-1>", sc)
atan = Button(TAB3, text='atan', padx=29, pady=10, relief=RAISED, bg='black', fg='white')
atan.bind("<Button-1>", sc)
ac = Button(TAB3, text='C', padx=34, pady=10, relief=RAISED, bg="#C82C0B", fg="White", command=lambda: clear())

cosh = Button(TAB3, text='cosh', padx=27, pady=10, relief=RAISED, bg='black', fg='white')
cosh.bind("<Button-1>", sc)
asinh = Button(TAB3, text='asinh', padx=25, pady=10, relief=RAISED, bg='black', fg='white')
asinh.bind("<Button-1>", sc)
acosh = Button(TAB3, text='acosh', padx=25, pady=10, relief=RAISED, bg='black', fg='white')
acosh.bind("<Button-1>", sc)
atanh = Button(TAB3, text='atanh', padx=25, pady=10, relief=RAISED, bg='black', fg='white')
atanh.bind("<Button-1>", sc)
bksp = Button(TAB3, text='⌫', padx=30, pady=10, relief=RAISED, bg="#C82C0B", fg="White", command=lambda: bksps())

tanh = Button(TAB3, text='tanh', padx=28, pady=10, relief=RAISED, bg='black', fg='white')
tanh.bind("<Button-1>", sc)
degb = Button(TAB3, text='deg', padx=29, pady=10, relief=RAISED, bg='black', fg='white')
degb.bind("<Button-1>", sc)
radb = Button(TAB3, text='rad', padx=31, pady=10, relief=RAISED, bg='black', fg='white')
radb.bind("<Button-1>", sc)
pib = Button(TAB3, text="pi", padx=34, pady=10, relief=RAISED, bg="Black", fg="White")
pib.bind("<Button-1>", sc)
div = Button(TAB3, text='/', padx=36, pady=10, relief=RAISED, bg="Black", fg="White", command=lambda: click("/"))

sin = Button(TAB3, text='sin', padx=32, pady=10, relief=RAISED, bg='black', fg='white')
sin.bind("<Button-1>", sc)
seven = Button(TAB3, text="7", padx=36, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("7"))
eight = Button(TAB3, text="8", padx=36, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("8"))
nine = Button(TAB3, text="9", padx=36, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("9"))
mult = Button(TAB3, text="*", padx=36, pady=10, relief=RAISED, bg="Black", fg="White", command=lambda: click("*"))

cos = Button(TAB3, text='cos', padx=31, pady=10, relief=RAISED, bg='black', fg='white')
cos.bind("<Button-1>", sc)
four = Button(TAB3, text="4", padx=36, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("4"))
five = Button(TAB3, text="5", padx=36, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("5"))
six = Button(TAB3, text="6", padx=36, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("6"))
minus = Button(TAB3, text="-", padx=36, pady=10, relief=RAISED, bg="Black", fg="White", command=lambda: click("-"))

tan = Button(TAB3, text='tan', padx=32, pady=10, relief=RAISED, bg='black', fg='white')
tan.bind("<Button-1>", sc)
one = Button(TAB3, text="1", padx=36, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("1"))
two = Button(TAB3, text="2", padx=36, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("2"))
three = Button(TAB3, text="3", padx=36, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("3"))
plus = Button(TAB3, text="+", padx=35, pady=10, relief=RAISED, bg="Black", fg="White", command=lambda: click("+"))

dot = Button(TAB3, text='.', padx=36, pady=10, relief=RAISED, bg="Black", fg="White", command=lambda: click("."))
zero = Button(TAB3, text='0', padx=36, pady=10, relief=RAISED, bg="Grey", fg="White", command=lambda: click("0"))
equal = Button(TAB3, text='=', padx=36, pady=10, relief=RAISED, bg="Orange", fg="Black", command=lambda: evaluate())

sinh.grid(row=1, column=0)
asin.grid(row=1, column=1)
acos.grid(row=1, column=2)
atan.grid(row=1, column=3)
ac.grid(row=1, column=4)

cosh.grid(row=2, column=0)
asinh.grid(row=2, column=1)
acosh.grid(row=2, column=2)
atanh.grid(row=2, column=3)
bksp.grid(row=2, column=4)

tanh.grid(row=3, column=0)
degb.grid(row=3, column=1)
radb.grid(row=3, column=2)
pib.grid(row=3, column=3)
div.grid(row=3, column=4)

sin.grid(row=4, column=0)
seven.grid(row=4, column=1)
eight.grid(row=4, column=2)
nine.grid(row=4, column=3)
mult.grid(row=4, column=4)

cos.grid(row=5, column=0)
four.grid(row=5, column=1)
five.grid(row=5, column=2)
six.grid(row=5, column=3)
minus.grid(row=5, column=4)

tan.grid(row=6, column=0)
one.grid(row=6, column=1)
two.grid(row=6, column=2)
three.grid(row=6, column=3)
plus.grid(row=6, column=4)

dot.grid(row=7, column=1)
zero.grid(row=7, column=2)
equal.grid(row=7, column=3)

TAB1.mainloop()
TAB2.mainloop()
TAB3.mainloop()
window.mainloop()


#adding the five numbers in list where inputs are given from the user
numbers=[]
for i in range(5):
    num=int(input(f"Enter the {i+1} number: "))
    numbers.append(num)

print(numbers)
# to write into the file
f=open("listNumber.txt","w")
f.write(str(numbers))
f.close()

#to read the file
file=open("listNumber.txt","r")
print("the file have")
print(file.read())
file.close()


"""Grammar for polyhedral terms."""

from functools import reduce
from typing import List, cast

import pyparsing as pp

from pacti.terms.polyhedra.syntax.data import (  # noqa: WPS235, WPS450 too many imported names, _combine_or_append is protected
    PolyhedralSyntaxAbsoluteTerm,
    PolyhedralSyntaxAbsoluteTermList,
    PolyhedralSyntaxAbsoluteTermOrTerm,
    PolyhedralSyntaxEqlExpression,
    PolyhedralSyntaxExpression,
    PolyhedralSyntaxIneqExpression,
    PolyhedralSyntaxOperator,
    PolyhedralSyntaxTermList,
    _combine_or_append,
)

def _parse_only_variable(tokens: pp.ParseResults) -> PolyhedralSyntaxTermList:
    assert len(tokens) == 1
    v = tokens[0]
    assert isinstance(v, str)
    return PolyhedralSyntaxTermList(constant=0, factors={v: 1.0})

def _parse_number_and_variable(tokens: pp.ParseResults) -> PolyhedralSyntaxTermList:
    number = tokens[0]
    assert isinstance(number, float)
    variable_term = tokens[len(tokens) - 1]  # noqa: WPS530 Found implicit negative index
    assert isinstance(variable_term, PolyhedralSyntaxTermList)
    assert variable_term.constant == 0
    for k in variable_term.factors:
        variable_term.factors[k] *= number
    return variable_term

def _parse_term(tokens: pp.ParseResults) -> PolyhedralSyntaxTermList:
    assert len(tokens) == 1
    t0 = tokens[0]
    assert isinstance(t0, pp.ParseResults)
    tl = t0[0]
    if isinstance(tl, PolyhedralSyntaxTermList):
        return tl
    if isinstance(tl, float):
        return PolyhedralSyntaxTermList(constant=tl, factors={})
    raise ValueError(f"_parse_term should involve either a TermList or a float, got: {type(tl)}")

def _parse_first_term(tokens: pp.ParseResults) -> PolyhedralSyntaxTermList:
    assert len(tokens) == 1
    group = tokens[0]
    if len(group) == 2:
        sign = group[0]
        assert isinstance(sign, str)
        tl = group[1]
        assert isinstance(tl, PolyhedralSyntaxTermList)
        if sign == "-":
            return tl.negate()
        return tl
    tl = group[0]
    assert isinstance(tl, PolyhedralSyntaxTermList)
    return tl

def _parse_signed_term(tokens: pp.ParseResults) -> PolyhedralSyntaxTermList:
    assert len(tokens) == 1
    group = tokens[0]
    sign = group[0]
    assert isinstance(sign, str)
    tl = group[1]
    assert isinstance(tl, PolyhedralSyntaxTermList)
    if sign == "-":
        return tl.negate()
    return tl

def _parse_term_list(tokens: pp.ParseResults) -> PolyhedralSyntaxTermList:
    assert len(tokens) == 1
    group = tokens[0]
    return reduce(PolyhedralSyntaxTermList.add, group, PolyhedralSyntaxTermList(constant=0, factors={}))

def _parse_paren_terms(tokens: pp.ParseResults) -> PolyhedralSyntaxTermList:
    assert len(tokens) == 1
    group = tokens[0]
    tl = group[1]
    assert isinstance(tl, PolyhedralSyntaxTermList)
    return tl

def _parse_factor_paren_terms(tokens: pp.ParseResults) -> PolyhedralSyntaxTermList:
    assert len(tokens) == 1
    group = tokens[0]
    f = group[0]
    assert isinstance(f, float)
    pt = group[len(group) - 1]  # noqa: WPS530 Found implicit negative index
    assert isinstance(pt, PolyhedralSyntaxTermList)
    pt.constant *= f
    for k in pt.factors:
        pt.factors[k] *= f
    return pt

def _parse_absolute_term(tokens: pp.ParseResults) -> PolyhedralSyntaxAbsoluteTerm:
    assert len(tokens) == 1
    group = tokens[0]
    if len(group) == 3:
        # group[0] = "|"
        # group[2] = "|"
        term_list = group[1]
        assert isinstance(term_list, PolyhedralSyntaxTermList)
        return PolyhedralSyntaxAbsoluteTerm(term_list=term_list, coefficient=None)

    coefficient = group[0]
    assert isinstance(coefficient, float)
    term_list = group[len(group) - 2]  # noqa: WPS530 Found implicit negative index
    assert isinstance(term_list, PolyhedralSyntaxTermList)
    return PolyhedralSyntaxAbsoluteTerm(term_list=term_list, coefficient=coefficient)

def _parse_signed_abs_term(tokens: pp.ParseResults) -> PolyhedralSyntaxAbsoluteTerm:
    assert len(tokens) == 1
    group = tokens[0]
    sign = group[0]
    assert isinstance(sign, str)
    term = group[1]
    assert isinstance(term, PolyhedralSyntaxAbsoluteTerm)
    if sign == "-":
        term = term.negate()
    return term

def _parse_first_abs_term(tokens: pp.ParseResults) -> PolyhedralSyntaxAbsoluteTerm:
    assert len(tokens) == 1
    group = tokens[0]
    if len(group) == 2:
        symbol = group[0]
        term = group[1]
    else:
        symbol = "+"
        term = group[0]
    assert isinstance(term, PolyhedralSyntaxAbsoluteTerm)
    if symbol == "-":
        term = term.negate()
    return term

def _to_absolute_term_or_term(tokens: pp.ParseResults) -> PolyhedralSyntaxAbsoluteTermOrTerm:
    if isinstance(tokens, PolyhedralSyntaxAbsoluteTerm):
        return tokens
    elif isinstance(tokens, PolyhedralSyntaxTermList):
        return tokens
    raise ValueError(f"Expecting either an AbsoluteTerm or a Term; got: {type(tokens)}")

def _parse_abs_or_term(tokens: pp.ParseResults) -> PolyhedralSyntaxAbsoluteTermOrTerm:
    assert len(tokens) == 1
    group = tokens[0]
    assert len(group) == 1
    tokens = group[0]
    return _to_absolute_term_or_term(tokens)

def _parse_abs_or_terms(tokens: pp.ParseResults) -> PolyhedralSyntaxAbsoluteTermList:
    assert len(tokens) == 1
    group = tokens[0]

    term_list: PolyhedralSyntaxTermList = PolyhedralSyntaxTermList(constant=0)
    absolute_term_list: List[PolyhedralSyntaxAbsoluteTerm] = []

    for term in group:
        if isinstance(term, PolyhedralSyntaxTermList):
            term_list = term_list.add(term)
        elif isinstance(term, PolyhedralSyntaxAbsoluteTerm):
            absolute_term_list = _combine_or_append(absolute_term_list, term)

    return PolyhedralSyntaxAbsoluteTermList(term_list=term_list, absolute_term_list=absolute_term_list)

def _parse_paren_abs_or_terms(tokens: pp.ParseResults) -> PolyhedralSyntaxAbsoluteTermList:
    assert len(tokens) == 1
    group = tokens[0]
    if len(group) == 3:
        atl = group[1]
        assert isinstance(atl, PolyhedralSyntaxAbsoluteTermList)
        return atl
    f = group[0]
    assert isinstance(f, float)
    atl = group[len(group) - 2]  # noqa: WPS530 Found implicit negative index
    assert isinstance(atl, PolyhedralSyntaxAbsoluteTermList)
    atl.term_list.constant *= f
    for k in atl.term_list.factors:
        atl.term_list.factors[k] *= f
    for at in atl.absolute_term_list:
        if at.coefficient is None:
            at.coefficient = f
        else:
            at.coefficient *= f
    return atl

def _parse_first_or_addl_paren_abs_or_terms(  # noqa: WPS231
    tokens: pp.ParseResults,
) -> PolyhedralSyntaxAbsoluteTermList:
    assert len(tokens) == 1
    group = tokens[0]

    if len(group) == 2:
        symbol = group[0]
        term = group[1]
    else:
        symbol = "+"
        term = group[0]

    term_list: PolyhedralSyntaxTermList = PolyhedralSyntaxTermList(constant=0)
    absolute_term_list: List[PolyhedralSyntaxAbsoluteTerm] = []

    if isinstance(term, PolyhedralSyntaxTermList):
        term_list = term_list.add(term)
        if symbol == "-":
            term_list = term_list.negate()
    elif isinstance(term, PolyhedralSyntaxAbsoluteTerm):
        if symbol == "-":
            term = term.negate()
        absolute_term_list = _combine_or_append(absolute_term_list, term)
    elif isinstance(term, PolyhedralSyntaxAbsoluteTermList):
        if symbol == "-":
            term = term.negate()
        current = PolyhedralSyntaxAbsoluteTermList(term_list=term_list, absolute_term_list=absolute_term_list).add(term)
        term_list = current.term_list
        absolute_term_list = current.absolute_term_list

    return PolyhedralSyntaxAbsoluteTermList(term_list=term_list, absolute_term_list=absolute_term_list)

def _parse_multi_paren_abs_or_terms(tokens: pp.ParseResults) -> PolyhedralSyntaxAbsoluteTermList:
    assert len(tokens) == 1
    group = tokens[0]

    term_list: PolyhedralSyntaxTermList = PolyhedralSyntaxTermList(constant=0)
    absolute_term_list: List[PolyhedralSyntaxAbsoluteTerm] = []

    for term in group:
        if isinstance(term, PolyhedralSyntaxTermList):
            term_list = term_list.add(term)
        elif isinstance(term, PolyhedralSyntaxAbsoluteTerm):
            absolute_term_list = _combine_or_append(absolute_term_list, term)
        elif isinstance(term, PolyhedralSyntaxAbsoluteTermList):
            current = PolyhedralSyntaxAbsoluteTermList(term_list=term_list, absolute_term_list=absolute_term_list).add(
                term
            )
            term_list = current.term_list
            absolute_term_list = current.absolute_term_list

    return PolyhedralSyntaxAbsoluteTermList(term_list=term_list, absolute_term_list=absolute_term_list)

def _parse_equality_expression(tokens: pp.ParseResults) -> PolyhedralSyntaxExpression:
    assert len(tokens) == 1
    group = tokens[0]
    lhs = group[0]
    assert group[1] in {"==", "="}
    rhs = group[2]
    if isinstance(lhs, PolyhedralSyntaxTermList) & isinstance(rhs, PolyhedralSyntaxTermList):
        return PolyhedralSyntaxEqlExpression(lhs=lhs, rhs=rhs)  # (VS-Code) # type: ignore
    raise ValueError(f"lhs and rhs should be PolyhedralSyntaxTermList, got: {type(lhs)}, {type(rhs)}")

def _parse_expression_sides(op: PolyhedralSyntaxOperator, tokens: pp.ParseResults) -> PolyhedralSyntaxExpression:
    sides: List[PolyhedralSyntaxAbsoluteTermList] = []
    for s in tokens.asList():
        if isinstance(s, PolyhedralSyntaxAbsoluteTermList):
            sides.append(s)
    return PolyhedralSyntaxIneqExpression(operator=op, sides=sides)

def _parse_leq_expression(tokens: pp.ParseResults) -> PolyhedralSyntaxExpression:
    assert len(tokens) == 1
    group = tokens[0]
    assert group[1] == "<="
    return _parse_expression_sides(PolyhedralSyntaxOperator.leq, group)

def _parse_geq_expression(tokens: pp.ParseResults) -> PolyhedralSyntaxExpression:
    assert len(tokens) == 1
    group = tokens[0]
    assert group[1] == ">="
    return _parse_expression_sides(PolyhedralSyntaxOperator.geq, group)

def _parse_expression(tokens: pp.ParseResults) -> PolyhedralSyntaxExpression:
    assert len(tokens) == 1
    group = tokens[0]
    e = group[0]
    if isinstance(e, PolyhedralSyntaxExpression):
        return e
    raise ValueError(f"Expected an Expression, got: {type(e)}")

# Grammar rules

# Produces a float
floating_point_number = (
    pp.Combine(
        pp.Or([pp.Word(pp.nums) + pp.Optional("." + pp.Optional(pp.Word(pp.nums))), "." + pp.Word(pp.nums)])
        + pp.Optional(pp.CaselessLiteral("E") + pp.Optional(pp.oneOf("+ -")) + pp.Word(pp.nums))
    )
    .set_parse_action(lambda t: float(t[0]))  # noqa: WPS348
    .set_name("floating_point_number")  # noqa: WPS348
)

# Basic arithmetic operations
plus, minus, mult, div = map(pp.Literal, "+-*/")

# Using infixNotation to manage precedence of operations
arithmetic_expr = pp.infixNotation(
    floating_point_number,
    [
        (mult | div, 2, pp.opAssoc.LEFT, lambda s, l, t: t[0][0] * t[0][2] if t[0][1] == "*" else t[0][0] / t[0][2]),
        (plus | minus, 2, pp.opAssoc.LEFT, lambda s, l, t: t[0][0] + t[0][2] if t[0][1] == "+" else t[0][0] - t[0][2]),
    ],
)

paren_arith_expr = pp.Group(pp.Suppress("(") + arithmetic_expr + pp.Suppress(")")).setParseAction(lambda t: t[0][0])

variable = pp.Word(pp.alphas, pp.alphanums + "_").set_name("variable")
symbol = pp.oneOf("+ -").set_name("symbol")

# Define a forward declaration for parenthesized terms
paren_terms = cast(pp.Forward, pp.Forward().set_name("paren_terms"))

# Define term options with corresponding parse actions

# Produces a PolyhedralSyntaxTermList
only_variable = variable.set_parse_action(_parse_only_variable)

# Produces a PolyhedralSyntaxTermList
number_and_variable = ((floating_point_number ^ paren_arith_expr) + pp.Optional("*") + variable).set_parse_action(
    _parse_number_and_variable
)

# Produces a float
only_number = floating_point_number ^ paren_arith_expr

# Add support for parenthesized terms
# Produces a PolyhedralSyntaxTermList
only_variable |= paren_terms

# Produces a PolyhedralSyntaxTermList
number_and_variable |= pp.Group(
    (floating_point_number ^ paren_arith_expr) + pp.Optional("*") + paren_terms
).set_parse_action(_parse_factor_paren_terms)

# Produces a PolyhedralSyntaxTermList
only_number |= paren_terms

# Produces a PolyhedralSyntaxTermList
term = pp.Group(only_variable | number_and_variable | only_number).set_parse_action(_parse_term).set_name("term")

# Produces a PolyhedralSyntaxTermList
first_term = (
    pp.Group(pp.Optional(symbol, default="+") + term).set_parse_action(_parse_first_term).set_name("first_term")
)

# Produces a PolyhedralSyntaxTermList
signed_term = pp.Group(symbol + term).set_parse_action(_parse_signed_term).set_name("signed_term")

# Produces a PolyhedralSyntaxTermList
terms = pp.Group(first_term + pp.ZeroOrMore(signed_term)).set_parse_action(_parse_term_list).set_name("terms")

# Define the rule for parenthesized terms
# Produces a PolyhedralSyntaxTermList
paren_terms <<= pp.Group("(" + terms + ")").set_parse_action(_parse_paren_terms).set_name("paren_terms_contents")

# Produces an PolyhedralSyntaxAbsoluteTerm
abs_term = (
    pp.Group(pp.Optional((floating_point_number ^ paren_arith_expr) + pp.Optional("*")) + "|" + terms + "|")
    .set_parse_action(_parse_absolute_term)  # noqa: WPS348
    .set_name("abs_term")  # noqa: WPS348
)

# Produces an PolyhedralSyntaxAbsoluteTerm
signed_abs_term = (
    pp.Group(symbol + abs_term)
    .set_parse_action(_parse_signed_abs_term)  # noqa: WPS348
    .set_name("signed_abs_term")  # noqa: WPS348
)

# Produces an PolyhedralSyntaxAbsoluteTerm
first_abs_term = (
    pp.Group(pp.Optional(symbol, default="+") + abs_term)
    .set_parse_action(_parse_first_abs_term)  # noqa: WPS348
    .set_name("first_abs_term")  # noqa: WPS348
)

# Produces an PolyhedralSyntaxAbsoluteTermOrTerm
first_abs_or_term = (
    pp.Group(first_abs_term | first_term)
    .set_parse_action(_parse_abs_or_term)  # noqa: WPS348
    .set_name("first_abs_or_term")  # noqa: WPS348
)

# Produces an PolyhedralSyntaxAbsoluteTermOrTerm
addl_abs_or_term = (
    pp.Group(signed_abs_term | signed_term)
    .set_parse_action(_parse_abs_or_term)  # noqa: WPS348
    .set_name("addl_abs_or_term")  # noqa: WPS348
)

# Produces an PolyhedralSyntaxAbsoluteTermList
abs_or_terms = (
    pp.Group(first_abs_or_term + pp.ZeroOrMore(addl_abs_or_term))
    .set_parse_action(_parse_abs_or_terms)  # noqa: WPS348
    .set_name("abs_or_terms")  # noqa: WPS348
)

# Produces an PolyhedralSyntaxAbsoluteTermList
paren_abs_or_terms = (
    pp.Group(pp.Optional((floating_point_number ^ paren_arith_expr) + pp.Optional("*")) + "(" + abs_or_terms + ")")
    .set_parse_action(_parse_paren_abs_or_terms)  # noqa: WPS348
    .set_name("paren_abs_or_terms")  # noqa: WPS348
)

# Produces an PolyhedralSyntaxAbsoluteTermList
first_paren_abs_or_terms = (
    pp.Group(pp.Optional(symbol, default="+") + paren_abs_or_terms | first_abs_or_term)
    .set_parse_action(_parse_first_or_addl_paren_abs_or_terms)  # noqa: WPS348
    .set_name("first_paren_abs_or_terms")  # noqa: WPS348
)

# Produces an PolyhedralSyntaxAbsoluteTermList
addl_paren_abs_or_terms = (
    pp.Group(symbol + paren_abs_or_terms | addl_abs_or_term)
    .set_parse_action(_parse_first_or_addl_paren_abs_or_terms)  # noqa: WPS348
    .set_name("addl_paren_abs_or_terms")  # noqa: WPS348
)

# Produces an PolyhedralSyntaxAbsoluteTermList
multi_paren_abs_or_terms = (
    pp.Group(first_paren_abs_or_terms + pp.ZeroOrMore(addl_paren_abs_or_terms))
    .set_parse_action(_parse_multi_paren_abs_or_terms)  # noqa: WPS348
    .set_name("multi_paren_abs_or_terms")  # noqa: WPS348
)

equality_operator = pp.Or([pp.Literal("=="), pp.Literal("=")])

# Produces an PolyhedralSyntaxExpression
equality_expression = (
    pp.Group(terms + equality_operator + terms)
    .set_parse_action(_parse_equality_expression)  # noqa: WPS348
    .set_name("equality_expression")  # noqa: WPS348
)

# Produces an PolyhedralSyntaxExpression
leq_expression = (
    pp.Group(multi_paren_abs_or_terms + pp.OneOrMore("<=" + multi_paren_abs_or_terms))
    .set_parse_action(_parse_leq_expression)  # noqa: WPS348
    .set_name("leq_expression")  # noqa: WPS348
)

# Produces an PolyhedralSyntaxExpression
geq_expression = (
    pp.Group(multi_paren_abs_or_terms + pp.OneOrMore(">=" + multi_paren_abs_or_terms))
    .set_parse_action(_parse_geq_expression)  # noqa: WPS348
    .set_name("geq_expression")  # noqa: WPS348
)

# Produces an PolyhedralSyntaxExpression
expression = (
    pp.Group(equality_expression | leq_expression | geq_expression)
    .set_parse_action(_parse_expression)  # noqa: WPS348
    .set_name("expression")  # noqa: WPS348
)


def marketYesterdayDF(token='', version=''):
    '''This returns previous day adjusted price data for whole market

    https://iexcloud.io/docs/api/#previous-day-prices
    Available after 4am ET Tue-Sat

    Args:
        symbol (string); Ticker to request
        token (string); Access token
        version (string); API version

    Returns:
        DataFrame: result
    '''
    x = marketYesterday(token, version)
    data = []
    for key in x:
        data.append(x[key])
        data[-1]['symbol'] = key
    df = pd.DataFrame(data)
    _toDatetime(df)
    _reindex(df, 'symbol')
    return df


"""
Simple training loop; Boilerplate that could apply to any arbitrary neural network,
so nothing in this file really has anything to do with GPT specifically.
"""

import time
from collections import defaultdict

import torch
from torch.utils.data.dataloader import DataLoader

from utils.min_gpt_utils import CfgNode

class Trainer:

    @staticmethod
    def get_default_config():
        C = CfgNode()
        # device to train on
        C.device = 'auto'
        # dataloder parameters
        C.num_workers = 4
        # optimizer parameters
        C.max_iters = None
        C.batch_size = 64
        C.learning_rate = 3e-4
        C.betas = (0.9, 0.95)
        C.weight_decay = 0.1  # only applied on matmul weights
        C.grad_norm_clip = 1.0
        return C

    def __init__(self, config, model, train_dataset, val_dataset, save_weights_path=None):
        self.config = config
        self.model = model
        self.optimizer = None
        self.train_dataset = train_dataset
        self.val_dataset = val_dataset
        self.save_weights_path = save_weights_path  # string where to save weights i.e. "best_model_path.pth"
        self.callbacks = defaultdict(list)

        # determine the device we'll train on
        if config.device == 'auto':
            self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
        else:
            self.device = config.device
        self.model = self.model.to(self.device)
        print("running on device", self.device)

        # variables that will be assigned to trainer class later for logging and etc
        self.iter_num = 0
        self.iter_time = 0.0
        self.iter_dt = 0.0

    def add_callback(self, onevent: str, callback):
        self.callbacks[onevent].append(callback)

    def set_callback(self, onevent: str, callback):
        self.callbacks[onevent] = [callback]

    def trigger_callbacks(self, onevent: str):
        for callback in self.callbacks.get(onevent, []):
            callback(self)

    def run(self, log_level=0):
        model, config = self.model, self.config

        # set up the optimizer
        self.optimizer = model.configure_optimizers(config)

        # set up the dataloader
        train_loader = DataLoader(
            self.train_dataset,
            sampler=torch.utils.data.RandomSampler(self.train_dataset, replacement=True, num_samples=int(1e10)),
            shuffle=False,
            # pin_memory=True,
            batch_size=config.batch_size,
            num_workers=config.num_workers,
        )

        # set up the validation dataloader
        val_loader = DataLoader(
            self.val_dataset,
            shuffle=False,
            batch_size=config.batch_size,
            num_workers=config.num_workers,
        )

        model.train()
        self.iter_num = 0
        self.iter_time = time.time()
        data_iter = iter(train_loader)

        best_val_loss = float('inf')
        epochs_without_improvement = 0

        while True:

            # fetch the next batch (x, y) and re-init iterator if needed
            try:
                batch = next(data_iter)
            except StopIteration:
                data_iter = iter(train_loader)
                batch = next(data_iter)
            batch = [t.to(self.device) for t in batch]
            x, y = batch

            # forward the model
            logits, self.loss = model(x, y)

            # backprop and update the parameters
            model.zero_grad(set_to_none=True)
            self.loss.backward()
            torch.nn.utils.clip_grad_norm_(model.parameters(), config.grad_norm_clip)
            self.optimizer.step()

            # Validation
            if self.iter_num % config.val_interval == 0:
                if log_level:
                    tnow = time.time()
                    self.iter_dt = tnow - self.iter_time
                    self.iter_time = tnow
                    print(f"iter_dt {self.iter_dt * 1000:.2f}ms; iter {self.iter_num}: train loss {self.loss.item():.5f}")

                model.eval()  # Set the model to evaluation mode
                with torch.no_grad():
                    val_losses = []
                    for val_batch in val_loader:
                        val_batch = [t.to(self.device) for t in val_batch]
                        val_x, val_y = val_batch
                        val_logits, val_loss = model(val_x, val_y)
                        val_losses.append(val_loss.item())
                    average_val_loss = sum(val_losses) / len(val_losses)
                    if log_level:
                        print("avg val loss: ", average_val_loss)

                # Update the best validation loss and check for improvement
                if average_val_loss < best_val_loss:
                    best_val_loss = average_val_loss
                    epochs_without_improvement = 0
                    # Save the model weights
                    if self.save_weights_path:
                        torch.save(model.state_dict(), self.save_weights_path)
                else:
                    epochs_without_improvement += 1

                # Terminate if validation loss doesn't improve for a certain number of epochs
                if epochs_without_improvement >= config.patience:
                    break

                model.train()  # set model back to train

            # iter termination conditions
            self.iter_num += 1

            if config.max_iters is not None and self.iter_num >= config.max_iters:
                break


import ifaddr

adapters = ifaddr.get_adapters(include_unconfigured=True)

for adapter in adapters:
        print("IPs of network adapter " + adapter.nice_name)
        for ip in adapter.ips:
            if ip.is_IPv4:
                addr = ip.ip.split(".")
                addr[len(addr) - 1] = "51"
                addr1 = ".".join(addr)
                print("IPv4: " + addr1)


def detect_anomaly(self):
    """
    Detect anomalies in the timeseries data for the submetrics specified in the config file. Identified anomalies are
    stored in self.anomalies as well as written to .anomalies.csv file to be used by the client charting page. Anomaly
    detection uses the luminol library (http://pypi.python.org/pypi/luminol)
    """
    if not self.anomaly_detection_metrics or len(self.anomaly_detection_metrics) <= 0:
      return
    for submetric in self.anomaly_detection_metrics:
      csv_file = self.get_csv(submetric)
      if naarad.utils.is_valid_file(csv_file):
        detector = anomaly_detector.AnomalyDetector(csv_file)
        anomalies = detector.get_anomalies()
        if len(anomalies) <= 0:
          return
        self.anomalies[submetric] = anomalies
        anomaly_csv_file = os.path.join(self.resource_directory, self.label + '.' + submetric + '.anomalies.csv')
        with open(anomaly_csv_file, 'w') as FH:
          for anomaly in anomalies:
            FH.write(",".join([str(anomaly.anomaly_score), str(anomaly.start_timestamp), str(anomaly.end_timestamp), str(anomaly.exact_timestamp)]))
            FH.write('\n')


#!/usr/bin/env python
# -*- coding: utf8 -*-

import os
import sys
sys.path.append(os.path.abspath(".."))

from speclib.loaders import loadUser, loadPythonSyntaxFile

dataPath = r"/lscr_paper/allan/data/Telefon/userfiles"
userList = os.listdir(dataPath)

user = userList[121]

user = loadUser(user, dataFilter=("call", "gps"))
for k, v in user.items():
    print(k, len(v), sep=":  ")


import re

id_pattern = r'\s[A-Z]{3}[0-9]{7}'
age_pattern = r'Age :'
name_pattern = r'Name :'
parent_list = ["Mother's Name :","Husband's Name :","Father's Name :","Husband's  ",
"Mother's  ","Father's  "]
house_pattern = r'House No :'
gender_list = ["Age :","Gender :"]
number_pattern = r'\s[0-9]{1,3}\s'

def read_text(file_name):
	text_list = []
	file = open(file_name,'r')
	for line in file:
		text_list.append(line)
	return text_list

def content_detect(text_line):
	flag_list = []
	father_flag = False
	id_flag = False
	age_flag = False
	house_flag = False
	name_flag =  False
	content = []
	if "Age :" in text_line and ("Sex :" in text_line or "Gender :" in text_line):
		new_flag = 1
	else:
		new_flag = 0
	if len(re.findall(id_pattern,text_line))>1:
		start_flag = 1
	else:
		start_flag = 0
	if len(re.findall(id_pattern,text_line))>1:
		id_flag = True
		content = first_line(text_line)
	if len(re.findall(age_pattern,text_line))>1:
		age_flag = 	True
		content = age_parse(text_line)
	if len(re.findall(house_pattern,text_line))>1:
		house_flag = True
		content = house_parse(text_line)
	if len(re.findall(name_pattern,text_line))>1:
		name_flag = True
		content = name_parse(text_line)
	for i in parent_list:
		if i in text_line:
			father_flag = True
			content = gurdian_parse(text_line)
	return start_flag,new_flag,[father_flag ,id_flag ,age_flag ,house_flag ,name_flag],content

def first_line(line1):
	pan_list = re.findall(id_pattern,line1)
	count_list = re.findall(number_pattern,line1)
	return [{"id_":count_list},{"voter_ids":pan_list}]

def age_parse(line):
	age_list = []
	gender_ = []
	for seg in re.split(age_pattern,line):
		if len(seg)>2:
			for i in gender_list:
				sp_ =seg.split(i)
				if len(sp_)>1:
					print(sp_[0],sp_[1])
					age_list.append(sp_[0])
					gender_.append(sp_[1])
	return [{"age":age_list},{"gender":gender_}]

def house_parse(line):
	house_list = []
	for i in re.split(house_pattern,line):
		if len(i)>2:
			house_list.append(i)
	return [{"house":house_list}]

def name_parse(line):
	name_list = []
	for i in re.split(name_pattern,line):
		if len(i)>2:
			name_list.append(i)
	return [{"name":name_list}]

def gurdian_parse(line):
	gurdian_list = []
	for seg in line.split("         "):
		if len(seg)>1:
			for i in parent_list:
				sp = seg.split(i)
				if len(sp)>1:
					d = {i:sp[1]}
					gurdian_list.append(d)
	return [{"gurdian":gurdian_list}]

def segment_parse(text_):
	content_seg = []
	segment_list = []
	seg_parse = []
	parse_seg_list = []
	for i in text_:
		start_flag,endflag,flag_list,content = content_detect(str(i))
		if any(flag_list) and start_flag==1:
			content_seg = []
			seg_parse = []
			content_seg.append(i)
			seg_parse.append(content)
		if any(flag_list) and (start_flag==0 and endflag==0):
			content_seg.append(i)
			seg_parse.append(content)
		if any(flag_list) and endflag==1:
			content_seg.append(i)
			seg_parse.append(content)
			segment_list.append(content_seg)
			parse_seg_list.append(seg_parse)
	return segment_list,parse_seg_list

def parse_segment(segment_list):
	new_segments = []
	for seg in segment_list:
		seg_dict = voter_mat(seg)
		new_segments.append(seg_dict)
	return new_segments

if __name__ == '__main__':
	file_name = "./data/sample_pdf.txt"
	text_ = read_text(file_name)
	segs,parsed_list = segment_parse(text_)


#!/usr/bin/python

import mmap
import qsys_addr
import qsys_spi

# serial port registers
h00 = 0x00      # read only register
h00_UNLOCK  = 5 # out of lock condition
h00_ALCHI   = 4 # ACL too high flag (resonator amplitude too high)
h00_ALCLO   = 3 # ACL too low flag (resonator amplitude too low)
h00_LOCK    = 2 # lock condition
h00_THI     = 1 # high voltage clamp flag
h00_TLO     = 0 # low voltage clamp flag

h01 = 0x01
h01_default = 0x04
h01_x       = 0     # bit-wise mask for the STAT output of h00
h01_x_msk   = 0x3F

h02 = 0x02
h02_default = 0x0E
h02_PDALL   = 7     # full chip power down. active high. default: 0
h02_PDPLL   = 6     # powers down REF, REFO, R_DIV, PFD, CPUMP, N_DIV. default: 0
h02_PDVCO   = 5     # powers down VCO, N_DIV. default: 0
h02_PDOUT   = 4     # powers down O_DIV, RF output buffer. default: 0
h02_PDREF0  = 3     # powers down REFO. default: 1
h02_MTCAL   = 2     # mutes output during calibration. default: 1
h02_OMUTE   = 1     # mutes RF output. default: 1
h02_POR     = 0     # for power-on reset. default: 0

h03 = 0x03
h03_default     = 0x30
h03_BD          = 4     # B divider, used to clock digital calibration circuitry. default: 0x03
h03_BD_msk      = 0x0F
h03_RD_MSB      = 0     # R divider 2-bit MSB. default for only the MSB: 0x00
h03_RD_MSB_msk  = 0x03

h04 = 0x04
h04_default     = 0x01
h04_RD_LSB      = 0     # R divider 8-bit LSB. default for only the LSB: 0x01
h04_RD_LSB_msk  = 0xFF

h05 = 0x05
h05_default     = 0x00
h05_ND_MSB      = 0     # N divider 8-bit MSB. default for only the MSB: 0x00
h05_ND_MSB_msk  = 0xFF

h06 = 0x06
h06_default     = 0xFA
h06_ND_LSB      = 0     # N divider 8-bit LSB. default for only the LSB: 0xFA
h06_ND_LSB_msk  = 0xFF

h07 = 0x07
h07_default     = 0x21
h07_ALCEN       = 7     # always enable ALC (override). default: 1
h07_ALCMON      = 6     # enable ALC monitor for status flags only. default: 0
h07_ALCCAL      = 5     # auto enable ALC during CAL operation. default: 1
h07_ALCULOK     = 4     # enable ALC when PLL unlocked. default: 0
h07_CAL         = 1     # start VCO calibration (auto clears). default: 0
h07_LKEN        = 0     # PLL lock indicator enable. default: 1

h08 = 0x08
h08_default     = 0xF9
h08_BST         = 8     # REF buffer boost current. default: 1
h08_FILT        = 5     # REF input buffer filter. default: 0x03
h08_FILT_msk    = 0x03
h08_RFO         = 3     # RF output power. default: 0x03
h08_RFO_msk     = 0x03
h08_OD          = 0     # Output divider value. default: 1
h08_OD_msk      = 0x07

h09 = 0x09
h09_default     = 0x9B
h09_LKWIN       = 6     # PLL lock indicator window. default: 0x02
h09_LKWIN_msk   = 0x03
h09_LKCT        = 4     # PLL lock cycle count. default: 0x01
h09_LKCT_msk    = 0x03
h09_CP          = 0     # Charge pump output current. default: 0x0B
h09_CP_msk      = 0x0F

h0A = 0x0A
h0A_default     = 0xE4
h0A_CPCHI       = 7     # Charge pump enable hi voltage output clamp. default: 1
h0A_CPCLO       = 6     # Charge pump enable low voltage output clamp. default: 1
h0A_CPMID       = 5     # Charge pump bias to mid-rail. default: 1
h0A_CPINV       = 4     # Charge pump invert phase. default: 1
h0A_CPWIDE      = 3     # Charge pump extend pulse width. default: 0
h0A_CPRST       = 2     # Charge pump three-state. default: 1
h0A_CPUP        = 1     # Charge pump pump up only. default: 0
h0A_CPDN        = 0     # Charge pump pump down only. default: 0

h0B = 0x0B              # read only register
h0B_REV         = 5     # rev code
h0B_REV_msk     = 0x07
h0B_PART        = 0     # part code. 0x04 for LTC6946-4
h0B_PART_msk    = 0x1F

RD              = 1
WR              = 0

def spi_rd(addr):
    with open( "/dev/mem", "r+" ) as f:
        # memory-map the file starting with the lightweight axi bus offset and the span of the h2f_lwaxi_master_span
        mem = mmap.mmap( f.fileno(), qsys_addr.lwaxi_span, offset = qsys_addr.lwaxi_ofst )

        # reading the data from the SPI
        spival = (addr << 1 + RD) << 8
        mem.seek( qsys_addr.lwaxi_plldds_spi_addr + qsys_spi.SPI_TXDATA_offst )
        mem.write( spival.to_bytes( 4, 'little' ) )
        mem.seek( qsys_addr.lwaxi_plldds_spi_addr + qsys_spi.SPI_RXDATA_offst )
        data = mem.read( 4 )  # read the data in byte format
        dataint = int.from_bytes( data, byteorder = 'little' )

        mem.close()  # close the map
    return dataint

def rd_chip():
    dat     = spi_rd(h0B)
    rev     = dat & (h0B_REV_msk << h0B_REV)
    part    = dat & (h0B_PART_msk << h0B_PART)
    return rev,part