"""
2D Texture Rigger
Author: Brandon Bower

Rigs 2D textures onto an object so that textures can be changed with an attribute to animate the texture.
Select object, then control, before running
"""
import maya.cmds as cmds
import re
from functools import partial

WIDTH = 250 # constant for width of window

def getSurfaceShader(objName):
    '''
    (str) -> list

    gets name of material and shading group attached to object, returns that in a list

    Code by mark_wilkins, found at: https://simplymaya.com/forum/showthread.php?t=3181
    This assumes you want ONLY the shape node at the selected level of the
    hierarchy, for the object whose transform name is passed in as the argument.
    '''
    myShapeNode = cmds.listRelatives(objName, children=True, shapes=True)
    mySGs = cmds.listConnections(myShapeNode[0], type='shadingEngine')
    surfaceShader = cmds.listConnections(mySGs[0] + '.surfaceShader')
    return [surfaceShader[0], mySGs[0]]

def connectTex(p2dTexture, fName):
    '''
    (str, str) -> None
    creates all relevant connections between a place2dTexture node and a file node
    '''
    attrs = ['coverage', 'translateFrame', 'rotateFrame', 'mirrorU', 'mirrorV', 'stagger',\
            'wrapU', 'wrapV', 'repeatUV', 'offset', 'rotateUV', 'noiseUV',\
            'vertexUvOne', 'vertexUvTwo', 'vertexUvThree', 'vertexCameraOne']
    for i in range(len(attrs)):
        cmds.connectAttr(p2dTexture + '.' + attrs[i], fName + '.' + attrs[i], f=True);
    cmds.connectAttr(p2dTexture + '.outUV', fName + '.uv', f=True);
    cmds.connectAttr(p2dTexture + '.outUvFilterSize', fName + '.uvFilterSize', f=True);
    return

def rigHandler(*args):
    '''
    (bool) -> None
    iterates over all texture-relevant ui elements, queries them,
    and sets up the rig with that information
    called by windowCall
    '''
    selectList = cmds.ls(sl=True)
    uiList = cmds.scrollLayout('sub_fields', q=True, ca=True)
    cmds.shadingNode('place2dTexture', asUtility=True, n = 'p2dT')
    cmds.shadingNode('layeredTexture', asTexture=True, n='lT')
    index = 0
    for i in range(0,len(uiList),3): # iterate over list, step by 3 for the 3 info elements of each texture
        path = cmds.button(uiList[i], q=True, l=True)
        if(path == "Select first image in sequence"):
            continue # Skip paths that were not specified
        names = cmds.textField(uiList[i+1], q=True, tx=True)
        enum = cmds.checkBox(uiList[i+2], q=True, v=True)

        fName = 'file_' + str(index)
        cmds.shadingNode('file', asTexture=True, n = fName) # create file node for texture
        connectTex('p2dT', fName) # connect to place2dTexture
        cmds.setAttr(fName + '.fileTextureName', path, type = 'string') # load file
        cmds.setAttr('lT.inputs[' + str(index) + '].blendMode', 1)
        cmds.connectAttr(fName + '.outColor', 'lT.inputs[' + str(index) + '].color', f=True)
        cmds.connectAttr(fName + '.outAlpha', 'lT.inputs[' + str(index) + '].alpha', f=True) # connect nodes, set lT attributes

        pathList = path.split('/')
        texName = pathList.pop() # split-up path, pop off end item, as that is the name of the texture
        path = '/'.join(pathList) + '/' # join path back, to get path to folder
        namesList = names.split(',') # get names for attribute name as well as enum, if relevant
        attrName = namesList[0].strip()
        if (attrName == '' or attrName == "Name Attribute"):
            attrName = 'attr' + str(index + 1) # auto-name for if user didn't input any names
        number = re.findall('[\d]+', texName) # find sequence number
        items = texName.split(number[-1]) # get texture name and file type
        numbSearch = '?' * len(number[-1]) # create string of '?' same length as sequence number
        files = cmds.getFileList(folder=path, filespec=items[0] + numbSearch + items[1]) # all sequence numbers, for length calculations
        fLength = len(files)
        if (enum):
            enumNames = ''
            nLength = len(namesList)
            for j in range(fLength):
                # for loop to set up enum names
                if (j + 1 < nLength and namesList[1] != " separate with comma for Enum"):
                    enumNames += namesList[j + 1].strip() + ':' # user defined names
                else:
                    enumNames += str(j + 1) + ':' # in case user didn't define enough names
            enumNames = enumNames[:-1] # strip off end ':'
            cmds.addAttr(selectList[1], ln=attrName, at='enum', en=enumNames)
            cmds.setAttr(selectList[1] + '.' + attrName, e=True, keyable=True) # create attribute, make it keyable
            for j in range(fLength):
                cmds.setAttr(selectList[1] + '.' + attrName, j)
                cmds.setAttr(fName + '.frameExtension', j + 1)
                cmds.setDrivenKeyframe(fName + '.frameExtension', cd=selectList[1] + '.' + attrName) # set up driven key
        else:
            # create attr, have it drive frameExtension of the file
            cmds.addAttr(selectList[1], ln=attrName, at='long', min=1, max=fLength, dv=1)
            cmds.setAttr(selectList[1] + '.' + attrName, e=True, keyable=True)
            cmds.connectAttr(selectList[1] + '.' + attrName, fName + '.frameExtension', f=True)
        cmds.setAttr(fName + '.useFrameExtension', 1)
        index += 1

    surfShaders = getSurfaceShader(selectList[0])
    if(cmds.checkBox('mnm', q=True, v=True)): # New material
        cmds.duplicate(surfShaders[1], upstreamNodes=True, n=surfShaders[0] + '_copySG') # copy old material
        surfShaders[1] = surfShaders[0] + '_copySG'
        surfShaders[0] = cmds.listConnections(surfShaders[1] + '.surfaceShader')[0] # update list values with new material names
        cmds.select(selectList[0])
        cmds.hyperShade(assign=surfShaders[1]) # assign new material to selsected object
    cmds.setAttr('lT.inputs[' + str(index) + '].blendMode', 0)
    cmds.connectAttr(surfShaders[0] + '.outColor', 'lT.inputs[' + str(index) + '].color', f=True)
    cmds.connectAttr('lT.outColor', surfShaders[1] + '.surfaceShader', f=True) # splice lT between mat and shading group

def findPath(*args):
       '''
       (str, bool) -> None
       Finds path to first image in sequence, updates button label to that path
       called by windowCall
       '''
       multipleFilters = "Compatible files (*.jpg *.jpeg *.png);;jpeg (*.jpeg *.jpg);;png (*.png);;All Files (*.*)"
       fPath = cmds.fileDialog2(cap='First image in sequence', fm=1, ff=multipleFilters, ds=2)
       if(fPath is not None):
           cmds.button(args[0], e=True ,l=fPath[0])
           cmds.button('Rig', e=True, en=True)
       return

def makeButtons(n):
    '''
    (int) -> None (creates ui elements as a side effect)
    recursively calls itself to create needed ui elements
    called by changeHandler
    calls itself recursively
    '''
    if n == 0:
        return
    else:
        pathButton = cmds.button(l='Select first image in sequence', w=WIDTH)
        cmds.button(pathButton, e=True, c=partial(findPath, pathButton))
        cmds.textField(w=WIDTH,\
        ann="If using Enum, separate names with a comma. \n First name written will be used as name of the attribute.",\
        tx="Name Attribute, separate with comma for Enum")
        cmds.checkBox(l='Enum')
        makeButtons(n - 1)
        return

def changeHandler(n):
    '''
    (int) -> None (creates sublayout for buttons created by makeButtons)
    Handles when initial int field is changed
    deletes previous layout
    creats new column or scroll layout, based on number of textures to be rigged
    called by windowCall
    calls makeButtons to create needed ui elements
    '''
    if cmds.scrollLayout('sub_fields', ex=True):
        cmds.deleteUI('sub_fields')
        cmds.window('Rig_Texture_2D', e=True, h=20)
    if (n == 0):
        return
    if (n <= 4):
        cmds.scrollLayout('sub_fields', w=WIDTH+4, h=n*68)
        cmds.window('Rig_Texture_2D', e=True, w=WIDTH+4, h=n*68 + 60)
    else:
        cmds.scrollLayout('sub_fields', w=WIDTH+18, h=240)
    cmds.button('Rig', en=False, edit=True) # Disable rig button
    makeButtons(n)
    return

def windowCall():
    '''
    () -> None
    Creates user interface window
    '''
    if cmds.window('Rig_Texture_2D', ex=True):
        cmds.deleteUI('Rig_Texture_2D')
    cmds.window('Rig_Texture_2D')
    cmds.columnLayout()
    cmds.intField(w=WIDTH/4, cc=changeHandler) # intField to determine number of textures to be rigged
    cmds.checkBox('mnm', l='Make New Material?')
    cmds.button('Rig', en=False, w=WIDTH, c=rigHandler)
    cmds.window('Rig_Texture_2D', e=True, h=20, w=WIDTH)
    cmds.showWindow('Rig_Texture_2D')
    return

def main():
    '''function driver for program'''
    windowCall()
    return

main()


# -*- coding: utf-8 -*-
import os

from flask import Flask, render_template, redirect, url_for, request
from twitter import Twitter, OAuth2, read_bearer_token_file

from .extensions import db
from . import model
from .decorators import requires_auth

def twitter_normal_to_bigger(value):
    return value.replace("_normal.", ".")

def _get_hash_tag_query_param():
    hash_tag = request.args.get("hash_tag")
    if hash_tag is None:
        hash_tag = "#vuls15"
    return hash_tag

def create_app(config=None):
    app = Flask("tweet_wall")
    app.config['MONGODB_DB'] = os.getenv('TW_MONGODB_DB')
    app.config['MONGODB_HOST'] = os.getenv('TW_MONGODB_HOST')

    db.init_app(app)

    app.jinja_env.filters['twitter_normal_to_bigger'] = twitter_normal_to_bigger

    token = read_bearer_token_file(".oauth2_bearer_token")
    twitter = Twitter(auth=OAuth2(bearer_token=token))

    @app.route("/approved")
    @app.route("/index")
    @app.route("/")
    def approved_tweets():
        tweets = model.Tweet.objects(approved=True).order_by("-id_str").all()
        return render_template('public.html', tweets=tweets)

    @app.route("/approve", methods=["GET"])
    @requires_auth
    def approve_tweet_get():
        hash_tag = _get_hash_tag_query_param()
        tweets_twitter = twitter.search.tweets(q=hash_tag)["statuses"]

        tweets_local = model.Tweet.objects(approved=True).all()
        tweets_local_ids = [tweet.id_str for tweet in tweets_local]

        tweets_not_approved = [tweet for tweet in tweets_twitter
                               if tweet["id_str"] not in tweets_local_ids]

        return render_template('approve_tweets.html',
                               tweets=tweets_not_approved)

    @app.route("/approve/<string:id_str>", methods=["POST"])
    @requires_auth
    def approve_tweet_post(id_str):
        tweet = twitter.statuses.show(id=id_str)
        tweet["approved"] = True
        tweet.pop("id")
        model.Tweet.objects(id_str=tweet["id_str"]).update_one(upsert=True,
                                                               **tweet)
        return redirect(url_for('approve_tweet_get'))

    @app.route("/twitter")
    def tweets():
        hash_tag = _get_hash_tag_query_param()
        tweet_search = twitter.search.tweets(q=hash_tag)["statuses"]
        return render_template('public.html', tweets=tweet_search)

    return app


#! /usr/bin/env python

import actionlib
from actionlib_msgs.msg import *
import co_traj_optimizer.msg
from geometry_msgs.msg import *
import math
from motion_planning import *
import rospy
import tf
from tf import TransformListener

Test = False

class ChairAssemblyActionServer(object):

    def __init__(self, name):
        self.action_name = name
        self.action_server = actionlib.SimpleActionServer(self.action_name, co_traj_optimizer.msg.DemoAction,
                                execute_cb=self.execute_cb, auto_start=False)
        self.action_server.start()
        self.transformer = tf.Transformer(True, rospy.Duration(10.0))
        self.tf = TransformListener()
        self.mp = ChairAssemblyMotionPlanner()

    def execute_cb(self, goal):
        '''
        goal = primitive ID
             = part ID
        '''
        part = goal.partID
        r = rospy.Rate(1)
        success = True

        target_obj_position = ""
        position = None
        orientation = Quaternion(math.sqrt(2)/2, 0, -math.sqrt(2)/2, 0)
        if part == 0:  # Right leg
            target_obj_position = "/ar_marker_3"
            position, _ = self.tf.lookupTransform("/base_link", target_obj_position,
                                    self.tf.getLatestCommonTime(target_obj_position, "/base_link"))
            position = Point(position[0], position[1] - 0.095, position[2] + 0.15)
            # b = tf.TransformBroadcaster()
            # b.sendTransform(position, orientation, rospy.Time(), '/TEST_ar_marker_3', '/base_link')
        elif part == 1:  # Left leg
            target_obj_position = "/ar_marker_7"
            position, _ = self.tf.lookupTransform("/base_link", target_obj_position,
                                    self.tf.getLatestCommonTime(target_obj_position, "/base_link"))
            position = Point(position[0], position[1] + 0.10, position[2] + 0.15)
            # b = tf.TransformBroadcaster()
            # b.sendTransform(position, orientation, rospy.Time(), '/TEST_ar_marker_7', '/base_link')
        elif part == 2:  # Chair base
            target_obj_position = "/ar_marker_5"
            position, _ = self.tf.lookupTransform("/base_link", target_obj_position,
                                    self.tf.getLatestCommonTime(target_obj_position, "/base_link"))
            position = Point(position[0], position[1] + 0.15, position[2] + 0.15)
            # b = tf.TransformBroadcaster()
            # b.sendTransform(position, orientation, rospy.Time(), '/TEST_ar_marker_5', '/base_link')

        if goal.primitiveID == 0:
            # Pick up
            print('position of object at: ', position)
            pose = Pose(position=position, orientation=orientation)
            self.mp.pickup_object(pose)
            if Test:
                print("Target object located at AR tag: ", target_obj_position)
                print(pose)
                print("Executing primitive pickup, ID: ", goal.primitiveID)
        elif goal.primitiveID == 1:
            # Hand off
            print("Handing off")
            position = Point(-0.5, -0.2, 0.4)
            pose = Pose(position=position, orientation=orientation)
            self.mp.handoff_object(pose)
            if Test:
                print("Target object located at AR tag: ", target_obj_position)
                print(pose)
                print("Executing primitive pickup, ID: ", goal.primitiveID)
        elif goal.primitiveID == 2:
            # Stabilize
            pose = Pose(position=position, orientation=orientation)
            self.mp.stabilize(pose)
            if Test:
                print("Target object located at AR tag: ", target_obj_position)
                print(pose)
                print("Executing primitive pickup, ID: ", goal.primitiveID)
        elif goal.primitiveID == 3:
            # Prealign
            position.x = position.x - 0.12
            orientation = Quaternion(0, 1, 0, 0)
            pose = Pose(position=position, orientation=orientation)
            self.mp.prealign(pose)
            if Test:
                print("Target object located at AR tag: ", target_obj_position)
                print(pose)
                print("Executing primitive pickup, ID: ", goal.primitiveID)
        else:
            success = False
            print("NO PRIMITIVES FOUND")
            # raise Exception('Invalid primitive')

        result = co_traj_optimizer.msg.DemoResult()
        result.success = 1
        self.action_server.set_succeeded(result)

if __name__ == '__main__':
    rospy.init_node('demo_server')
    demo = ChairAssemblyActionServer("task_september_demo")
    rospy.spin()


#from socket import NI_NUMERICHOST
#from symbol import yield_arg
#from uuid import NAMESPACE_X500
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
from scipy import stats
import random
import keras
import tensorflow as tf

#copy path of your csv file
df = pd.read_csv(r'C:\Skola\harren\joardata.csv', delimiter=',', header=None)
#data 6 measurements + labelled output (activity)
#adding titles:
df.columns =['Ax', 'Ay', 'Az', 'Gx', 'Gy', 'Gz','Activity']

#All activities: for now we have 3 activities: sitting, standing, walking
print(df.Activity.unique())
#window size and how big step we move our window
n_time_steps = 50
step = 10
segments = []
labels = []
n_features=6

#reshaping our data to arrays for model
for i in range(0,  df.shape[0]- n_time_steps, step):

    xs = df['Ax'].values[i: i + 50]
    ys = df['Ay'].values[i: i + 50]
    zs = df['Az'].values[i: i + 50]
    gx = df['Gx'].values[i: i + 50]
    gy = df['Gy'].values[i: i + 50]
    gz = df['Gz'].values[i: i + 50]

    label = stats.mode(df['Activity'][i: i + 50])[0][0]

    segments.append([xs, ys, zs, gx, gy, gz])

    labels.append(label)
#reshape the segments which is (list of arrays) to a list
reshaped_segments = np.asarray(segments, dtype= np.float32).reshape(-1, n_time_steps, n_features)

labels = np.asarray(pd.get_dummies(labels), dtype = np.float32)

print(reshaped_segments.shape)

#split to train and test data, 80% train 20% test
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(reshaped_segments, labels, test_size = 0.2, random_state = 42)

print(X_train.shape)

#model:
'''''
from keras.models import Sequential
from keras.layers import LSTM, Dense, Flatten, Dropout

model = Sequential()
# RNN layer
model.add(LSTM(units = 128, input_shape = (X_train.shape[1], X_train.shape[2])))
# Dropout layer
model.add(Dropout(0.5))
# Dense layer with ReLu
model.add(Dense(units = 64, activation='relu'))
# Softmax layer
model.add(Dense(y_train.shape[1], activation = 'softmax'))
# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

print(model.summary())

#training on data:
n_epochs=50
batch_size=1024
history = model.fit(X_train, y_train, epochs = n_epochs, validation_split = 0.20, batch_size = batch_size, verbose = 1)

loss, accuracy = model.evaluate(X_test, y_test, batch_size = batch_size, verbose = 1)
print("Test Accuracy :", accuracy)
print("Test Loss :", loss)

'''''


"""
This script is used for C.R.U.D for XML

Made by
@BJARKE ROBERT STØVE ANDERSØN
@CHRISTIAN MARC JØRGENSEN
@MAGNUS SØRENSEN
@THOMAS HENRIKSEN
"""
from xml.dom import minidom
from xml.etree import ElementTree

import os

"""
This method is used for creating the XML file

Parameters:
-toFile (--toFile): inputs the name of the file
"""
def createXml(toFile):

    root = minidom.Document()
    xml = root.createElement('root')
    root.appendChild(xml)
    productChild = root.createElement('test')
    xml_str = root.toprettyxml(indent = "\t")
    path_file = 'XML\_'+ toFile + '.xml'
    with open(path_file, "w") as f:
        f.write(xml_str)

"""
This method is used for making the XML file more readable

Example of a element:

  <Order nr="10011">
    <Customer>10011</Customer>
  <Time>00:40</Time>
  <ProductOrder Amount="1" Status="Cancel" orderId="10011 Blue phone (6002)">
      <Amount>1</Amount>
    <Product>Blue phone (6002)</Product>
    </ProductOrder>
  </Order>

Parameters:
-elem (--elem): input XML element
-level=0 (--level=0): inputs the level of the element it's on

Return:

-elem (--elem): outputs the element
"""
def indent(elem, level=0):
    i = "\n" + level*"  "
    j = "\n" + (level-1)*"  "
    if len(elem):
        if not elem.text or not elem.text.strip():
           elem.text = i + "  "
        if not elem.tail or not elem.tail.strip():
           elem.tail = i
        for subelem in elem:
           indent(subelem, level+1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = j
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = j
    return elem

"""
This method is used to determined how to save the order

Example:

orderList(time, customer, productOrder((amount, product)))
or
orderList(time, customer, (amount, product))

Parameters:
-orderList (--list): inputs a list that contains raw data of orders
"""
def saveOrder(orderList):
    time = orderList[0]
    customer = str(orderList[1])
    productOrder = orderList[2]
    amount = ''
    product = ''

    if isinstance(productOrder, list): #Checks if the productOrder is a list
        for item in productOrder: #for each productOrder there is in the list
            amount = item[:1] #Splits the item(amount) up to index 1
            product = item[2:] #Splits the item(product) from index 2
            if(product[:2] == 'pc'): #Checks if PC is the first that is listed in product
                #Splits the product from index 3, removes all empty spaces before and after the text, then capitalizes the first letter
                product = product[3:].lstrip().capitalize().rstrip()
                index = len(product)
                if(product[index-8] == 'r' or product[index-8] == 'l'): #Looks for r or l
                    product = product[:index-8] +  product[index-8].upper()+product[index-7:] #Makes r or l capitalized

            found = findOrderXml('ocr', str(customer) + ' ' + product) #Tries to find order in XML file

            if not found:

                saveToXml(time,customer,amount,product) #calls the method saveToXml

    else:
        amount = productOrder[:1] #references the comment in line 92
        product = productOrder[2:].capitalize().rstrip() #references the comment in line 93

        index = len(product)
        if(product[index-8] == 'r' or product[index-8] == 'l'): #references the comment in line 98
           product = product[:index-8] +  product[index-8].upper()+product[index-7:] #references the comment in line 99

        found = findOrderXml('ocr', customer + ' ' + product) #references the comment in line 101

        if not found:
            saveToXml(time,customer,amount,product) #references the comment in line 105

"""
This method is used to saving the XML file

Parameters:
-time (--string): inputs the time
-customer (--int): inputs the customer
-amount (--int): inputs the amount
-product (--string): inputs the product
"""
def saveToXml(time,customer,amount,product):
    path_file = 'XML\_ocr.xml'
    root = ElementTree.parse(path_file).getroot()

    c = ElementTree.Element('Order')

    customerXml = ElementTree.SubElement(c, 'Customer')
    customerXml.text = str(customer)
    c.set('nr',customerXml.text)

    orderTime = ElementTree.SubElement(c, 'Time')
    orderTime.text = str(time)

    productOrder = ElementTree.SubElement(c,'ProductOrder')

    productXml = ElementTree.SubElement(productOrder,'Amount')
    productXml.text = str(amount)
    productXml = ElementTree.SubElement(productOrder,'Product')
    productXml.text = str(product)
    productOrder.set('orderId',customerXml.text +' '+ productXml.text )
    productOrder.set('Status','Waiting' )
    productOrder.set('Amount', str(amount))

    root.insert(0, c)
    tree = ElementTree.ElementTree(indent(root))
    tree.write(path_file, xml_declaration=True, encoding='utf-8')

"""
This method is used for reading the XML file

Parameters:
-toFile (--toFile): inputs the name of the file

Return:
-orderList (--list): outputs a list of orders
"""
def readOrderXml(toFile):
    path_file = 'XML\_'+ toFile + '.xml'
    tree = ElementTree.parse(path_file)
    root = tree.getroot()

    orderList = []

    for order in root.findall('Order'):
        try:
            orderList.append(buildOrder(order))
        except:
            dontdoany = ''
    return orderList

def readXml(toFile):
    path_file = 'XML\_'+ toFile + '.xml'
    tree = ElementTree.parse(path_file)
    root = tree.getroot()
    data = []
    for elem in root.iter('OCR'):
        data.append(elem.text)

    return data

"""
This method is used for finding and changing the status of the given orders

Parameters:
-toFile (--toFile): inputs the name of the file
-orderFind (--string): inputs name of the order
-Status (--string): inputs the status
"""
def changeStatusOnOrderXml(toFile, orderFind,status):
    path_file = 'XML\_'+ toFile + '.xml'
    tree = ElementTree.parse(path_file)
    root = tree.getroot()
    orders = root.findall('.//ProductOrder')

    for order in orders:
        value = order.get('orderId')

        if(orderFind == value ):
            order.set('Status',status)

    tree = ElementTree.ElementTree(indent(root))
    tree.write(path_file, xml_declaration=True, encoding='utf-8')

"""
This method is used for checking if the order is in the XML file

Parameters:
-toFile (--toFile): inputs the name of the file
-orderFind (--string): inputs name of the order

Return:
-find (--bool): outputs true or false
"""
def findOrderXml(toFile, orderFind):
    find = False

    path_file = 'XML\_'+ toFile + '.xml'
    tree = ElementTree.parse(path_file)
    root = tree.getroot()
    orders = root.findall('.//ProductOrder')

    for order in orders:
        value = order.get('orderId')
        if(orderFind == value ):
            find = True

    return find

"""
This method is used to build the list of orders

Return:
-s (--list): outputs a list of orders
"""
def getOrder():
        orderList = readOrderXml('ocr')
        order = []
        for o in orderList:
            status = o[0]
            product = o[4]
            if(status == 'Done' or status == 'Cancel'):
                lala = '2' #does nothing

            else:
                order.append(o)
        if(len(order) == 0): #if there is no order, makes a empty order
            noOrder=[]
            noOrder.append('')
            noOrder.append('000000')
            noOrder.append('')
            noOrder.append('1')
            noOrder.append('No Order')
            order.append(noOrder)
        order = sorted(order, key = lambda i: i[2])
        s = []
        for i in order: #Removes any double orders
             if i not in s:
                 s.append(i)
        return s

"""
This method is used for building the order from the XML file

Parameters:
-order (--list): inputs list of strings

Return:
-data (--list): outputs a full order
"""
def buildOrder(order):
    data = []

    customer = order.find('Customer').text
    if(len(customer)<5):
        int(customer+'fd') #throws a exception
    orderTime = order.find('Time').text
    status = order.findall('ProductOrder')

    for productOrder in status:
        status = productOrder.get('Status')
        amount = productOrder.get('Amount')
        if int(amount):
            amount = amount
        productText = productOrder[1].text
        data.append(status)
        data.append(customer)
        data.append(orderTime)
        data.append(amount)
        data.append(productText)

    return data

Move2x/Move2x - RPA Ver 0.5/script/xmlScript.py


# -*- coding: utf-8 -*-
#usar python3
import numpy as np
from sympy import *
import matplotlib.pyplot as plt
from scipy.signal import lti, bode, lsim, dbode, zpk2tf, tf2zpk, step2, cont2discrete, dstep, freqz, freqs, dlti, TransferFunction
from tc_udemm import sympy_to_lti, lti_to_sympy, plot_argand
from pid_tf import PID_int
from recursive_tf import RecursiveTF

"""
        MicroInverter - Booster stage
        as is a push pull device the duty is doubled
        CCM mode only
        Output:
        Sensed by an optocoupler 3000pts adc @ 350V

"""

##########################################
# Graphics I want to show on the script. #
##########################################
Bode_Analog_Plant = False

Bode_Digital_Plant = False
Poles_Zeros_Digital_Plant = False

Step_Digital_Plant = False
Step_Digital_Plant_Recursive = False

Bode_Digital_Controller = True
Bode_Digital_Plant_Controller_OpenLoop_CloseLoop = True
Poles_Zeros_Digital_CloseLoop = False

Step_Digital_CloseLoop = True

#TF without constant
s = Symbol('s')

# Boost Stage
# From Vinput to Voutput
Lout = 1.8e-3
Rout = 816    #150W on 350V
Cout = 33e-6

# VCC for low-signal graphics
Vinput = 1
# Vinput = 40

#    ---Z1---+--------+
#            |        |
#           Z2       Z3
#            |        |
#    --------+--------+
Z1 = s * Lout
Z2 = 1 / (s * Cout)
Z3 = Rout

# Boost out
print (f'Boost out small signal no opto Vinput = {Vinput}V:')
Transf_Z3_Vinput = (Z2 * Z3 /(Z2 + Z3)) / (Z1 + (Z2 * Z3 /(Z2 + Z3))) * Vinput
Filter_out_sim = Transf_Z3_Vinput.simplify()
print (Filter_out_sim)

# Opamp
# print (f'Filtro T con Opamp en Rsense Vinput = {Vinput}V: ')
# Transf_Z4_Vinput_Opamp = Transf_Z4_Vinput * Amp_gain
# Filter_Opamp_out_sim = Transf_Z4_Vinput_Opamp.simplify()
# print (Filter_Opamp_out_sim)

##################################
# Some checks on the Analog part #
##################################
filter_TF = sympy_to_lti(Filter_out_sim)
if Bode_Analog_Plant == True:
    wfreq = np.arange(2*np.pi, 2*np.pi*100000, 1)
    w, mag_p, phase_p = bode(filter_TF, wfreq)

    fig, (ax1, ax2) = plt.subplots(2,1)
    ax1.semilogx (w/6.28, mag_p, 'b-', linewidth="1")
    # ax1.semilogx (w/6.28, mag_s, 'g-', linewidth="1")
    ax1.set_title(f'Magnitude Input to Output Filter Analog Vinput = {Vinput}V')

    ax2.semilogx (w/6.28, phase_p, 'b-', linewidth="1")
    # ax2.semilogx (w/6.28, phase_s, 'g-', linewidth="1")
    ax2.set_title('Phase')

    plt.tight_layout()
    plt.show()

##########################################
# Conver Plant by zoh over sampling freq #
# so no to affect zeroes and poles       #
##########################################
Fsampling = 24000
Tsampling = 1 / Fsampling

filter_dig_zoh_n, filter_dig_zoh_d, td = cont2discrete((filter_TF.num, filter_TF.den), Tsampling, method='zoh')

#normalized with TransferFunction
print ("Digital Filter Zoh:")
filter_dig_zoh = TransferFunction(filter_dig_zoh_n, filter_dig_zoh_d, dt=td)
print (filter_dig_zoh)

####################################
# Some tests over the digital part #
####################################
if Bode_Digital_Plant == True:
    w, mag_zoh, phase_zoh = dbode(filter_dig_zoh, n = 10000)

    fig, (ax1, ax2) = plt.subplots(2,1)

    ax1.semilogx(w/(2*np.pi), mag_zoh, 'y')
    ax1.set_title(f'Filter Digital Bode ZOH Vinput = {Vinput}V')
    ax1.set_xlabel('Frequency [Hz]')

    ax2.semilogx(w/(2*np.pi), phase_zoh, 'y')
    ax2.set_xlabel('Frequency [Hz]')

    plt.tight_layout()
    plt.show()

########################################
# Poles and Zeros on the Digital Plant #
########################################
if Poles_Zeros_Digital_Plant == True:
    plot_argand(filter_dig_zoh)

##############################
# Step Response verification #
##############################
simulation_time = 0.1
t = np.linspace(0, simulation_time, num=(simulation_time*Fsampling))

if Step_Digital_Plant == True:
    tout, yout_zoh = dstep([filter_dig_zoh.num, filter_dig_zoh.den, td], t=t)
    yout1 = np.transpose(yout_zoh)
    yout0 = yout1[0]
    yout_zoh = yout0[:tout.size]

    fig, ax = plt.subplots()
    ax.set_title('Step Filter Digital ZOH')
    ax.set_ylabel('Plant Voltage')
    ax.set_xlabel('Time [s]')
    ax.grid()

    ax.plot(tout, yout_zoh, 'y')
    # ax.set_ylim(ymin=-20, ymax=100)

    plt.tight_layout()
    plt.show()

##############################################
# Plant Step Response converted to Recursive #
##############################################
if Step_Digital_Plant_Recursive == True:
    # ZOH
    b_planta = np.transpose(filter_dig_zoh.num)
    a_planta = np.transpose(filter_dig_zoh.den)

    vin_plant = np.ones(t.size)
    vout_plant_method2 = np.zeros (t.size)
    recur_planta = RecursiveTF(b_planta, a_planta)
    for i in range(t.size):
        vout_plant_method2[i] = recur_planta.newOutput(vin_plant[i])

    fig, ax = plt.subplots()
    ax.set_title('Step Plant Digital Recursive ZOH')
    ax.set_ylabel('Plant Voltage')
    ax.set_xlabel('Time [s]')
    ax.grid()
    ax.plot(t, vout_plant_method2, 'y')
    plt.tight_layout()
    plt.show()

#####################################
# USED IN CASE OF CUSTOM CONTROLLER #
#####################################
# cont_zeros = [-0.89+0.29j, -0.89-0.29j]
# cont_poles = [0.]
# cont_const = 0.01
# cont_zpk_b, cont_zpk_a = zpk2tf(cont_zeros, cont_poles, cont_const)

# controller_tf = TransferFunction(cont_zpk_b, cont_zpk_a, dt=td)
# print ("Digital Custom Controller:")
# print (controller_tf)

##################################
# USED IN CASE OF PID CONTROLLER #
##################################
"""
    Only for PI dig:
    w0 ~= ki_dig / kp_dig * Fsampling or Fundersampling
    plateau gain ~= 20 log kp_dig

    Only for PD dig:
    w0 ~= kp_dig / kd_dig * Fsampling or Fundersampling
    plateau gain ~= 20 log kp_dig

"""

# kp_dig = 100 / 256
# ki_dig = 1 / 256
# kd_dig = 200 / 256

kp_dig = 50 / 128
ki_dig = 1 / 128
kd_dig = 100 / 128

k1 = kp_dig + ki_dig + kd_dig
k2 = -kp_dig - 2*kd_dig
k3 = kd_dig

b_pid = [k1, k2, k3]
a_pid = [1, -1]

controller_tf = TransferFunction(b_pid, a_pid, dt=td)

b_cont = controller_tf.num
a_cont = controller_tf.den
print("Controller Parameters:")
print(f"b[2]: {b_cont[0]} b[1]: {b_cont[1]} b[0]: {b_cont[2]}")
print(f"a[1]: {a_cont[0]} a[0]: {a_cont[1]}")

if Bode_Digital_Controller == True:
    w, mag, phase = dbode(controller_tf, n = 10000)
    fig, (ax1, ax2) = plt.subplots(2,1)
    ax1.semilogx(w/(2*np.pi), mag, 'c')
    ax1.set_title('Digital Controller')
    ax1.set_ylabel('Amplitude [dB]', color='c')
    ax1.set_xlabel('Frequency [Hz]')

    ax2.semilogx(w/(2*np.pi), phase, 'c')
    ax2.set_ylabel('Phase', color='c')
    ax2.set_xlabel('Frequency [Hz]')

    plt.tight_layout()
    plt.show()

contr_dig = lti_to_sympy(controller_tf)
plant_dig = lti_to_sympy(filter_dig_zoh)
ol_dig = contr_dig * plant_dig

open_loop_dig = sympy_to_lti(ol_dig)
close_loop_dig = sympy_to_lti(ol_dig/(1+ol_dig))

#normalize with TransferFunction
open_loop_dig = TransferFunction(open_loop_dig.num, open_loop_dig.den, dt=td)
close_loop_dig = TransferFunction(close_loop_dig.num, close_loop_dig.den, dt=td)

if Bode_Digital_Plant_Controller_OpenLoop_CloseLoop == True:
    w, mag_ol, phase_ol = dbode(open_loop_dig, n = 100000)
    w, mag_cl, phase_cl = dbode(close_loop_dig, n = 100000)

    fig, (ax1, ax2) = plt.subplots(2,1)
    ax1.semilogx(w/(2*np.pi), mag_ol, 'b')
    ax1.semilogx(w/(2*np.pi), mag_cl, 'c')
    ax1.set_title('Open Loop Blue - Close Loop Cyan')
    ax1.set_ylim(ymin=-50, ymax=50)

    ax2.semilogx(w/(2*np.pi), phase_ol, 'b')
    ax2.semilogx(w/(2*np.pi), phase_cl, 'c')
    ax2.set_title('Phase')
    ax2.set_xlabel('Frequency [Hz]')

    plt.tight_layout()
    plt.show()

if Poles_Zeros_Digital_CloseLoop == True:
    plot_argand(close_loop_dig)

##################################
# Check Close Loop Step Response #
##################################
tout, yout_zoh = dstep([close_loop_dig.num, close_loop_dig.den, td], t=t)
yout1 = np.transpose(yout_zoh)
yout0 = yout1[0]
yout_zoh = yout0[:tout.size]

if Step_Digital_CloseLoop == True:
    fig, ax = plt.subplots()
    ax.set_title('Step Planta Digital Realimentada')
    ax.set_ylabel('Tension del Sensor')
    ax.set_xlabel('Tiempo [s]')
    ax.grid()
    # ax.plot(tout, yout_ef, 'g')
    ax.plot(tout, yout_zoh, 'y')
    # ax.set_ylim(ymin=-20, ymax=100)

    plt.tight_layout()
    plt.show()


#!/usr/bin/python3
''' Query reddit API subreddit to retrieve top 10 hot posts titles'''
import requests

def top_ten(subreddit):
    ''' Query the subreddit for top 10 host posts'''
    url = 'https://api.reddit.com/r/{}/hot'.format(subreddit)
    headers = {
        'User-Agent': 'My User Agent 1.0'
    }

    r = requests.get(url, headers=headers, allow_redirects=False)
    if r.status_code != 200:
        print('None')
        return

    content = r.json()
    data = content['data']

    children = data['children']

    for idx, item in enumerate(children):
        if idx < 10:
            title = item['data']['title']
            print(title)


import numpy as np
import cv2
import pyscreenshot as ImageGrab
import time

# pylint: disable=no-member

def draw_rect(event,x,y,flags,param):
    getArea = param[0]
    if(event == cv2.EVENT_LBUTTONDOWN):
        getArea.draw = True
        getArea.rect[0], getArea.rect[1] = x, y
        getArea.rect[2], getArea.rect[3] = x, y
        getArea.drawRectangle()

    elif (event == cv2.EVENT_MOUSEMOVE):
        if getArea.draw == True:
            getArea.rect[2], getArea.rect[3] = x, y
            getArea.drawRectangle()
    elif(event == cv2.EVENT_LBUTTONUP):
        getArea.draw = False

class GetArea(object):
    rect = [0 ,0 ,100 ,100]
    draw = False

    def drawRectangle(self):
        self.img_out = self.img_orig.copy()
        cv2.rectangle(self.img_out,(self.rect[0],self.rect[1]),(self.rect[2],self.rect[3]),(0,0,255),2)

    def getArea(self,inRect):
        self.rect = inRect
        img_grab = ImageGrab.grab(bbox=(0, 0, 1919, 1079)) #x, y, w, h
        self.img_orig = cv2.cvtColor(np.array(img_grab), cv2.COLOR_RGB2BGR)
        self.drawRectangle()

        cv2.namedWindow("image", cv2.WND_PROP_FULLSCREEN)
        cv2.setWindowProperty("image",cv2.WND_PROP_FULLSCREEN,cv2.WINDOW_FULLSCREEN)

        param = [self]
        cv2.setMouseCallback('image',draw_rect, param)
        cv2.namedWindow('image')

        while(True):
            cv2.imshow("image", self.img_out)
            time.sleep(0.1)
            key = cv2.waitKey(1)
            if key == 27:
                cv2.destroyAllWindows()
                return self.rect.copy()

# pylint: enable=no-member


from django import forms
from django.forms import widgets
from .models import News, Category
from django.core.exceptions import ValidationError
import re

class NewsForm(forms.ModelForm):
    class Meta:
        model = News
        fields = ['title', 'content', 'is_published', 'category']
        widget = {
           'title': forms.TextInput(attrs={'class': 'form-control'}),
           'content': forms.Textarea(attrs={'class': 'form-control', 'row': 5}),
           'category': forms.Select(attrs={'class': 'form-control'}),
        }

    def clean_title(self):
        title = self.cleaned_data['title']
        if re.match(r'\d', title):
            raise ValidationError('Давай без цифр')
        return title


import click
import mlflow
import mlflow.sklearn
import pandas as pd

@click.command("evaluate")
@click.option("--data-path", required=True)
@click.option("--target-path", required=True)
@click.option("--run-id", required=True)
def evaluate(data_path: str, target_path: str, run_id: str):
    data = pd.read_csv(data_path, index_col=0)
    target = pd.read_csv(target_path, index_col=0, squeeze=True)

    pipeline = mlflow.sklearn.load_model(f"runs:/{run_id}/pipeline")
    classifier = mlflow.sklearn.load_model(f"runs:/{run_id}/classifier")

    prepared_data = pipeline.transform(data)

    with mlflow.start_run(run_id=run_id):
        mlflow.sklearn.eval_and_log_metrics(classifier, prepared_data, target, prefix="val_")

if __name__ == '__main__':
    evaluate()


from flask import Flask, request, jsonify
from flask_cors import CORS
import numpy as np
import ast
app = Flask(__name__)
CORS(app)

@app.route('/check',methods=['GET', 'POST'])
def hello():
    data = request.json
    print(data)
    if data['polygon']:

        data=data['polygon']
        polyarr = data['polygonArray']
        # polyarr =np.array(polyarr)
        # print(type(polyarr))
        point = data['point']
        point = point.strip('][').split(',')
        x = int(point[0])
        y = int(point[1])
        # print(polyarr)
        isInside = point_inside_polygon(x,y,polyarr)
        if isInside==True:
            isInside = "True"
        else:
            isInside = "False"
    return jsonify(isInside)

    # print(isInside)

@app.route('/sun',methods=['GET', 'POST'])
def sun():
    data = request.json
    if data['sun']:
        data=data['sun']
        buildarr = data['Buildings']
        buildarr =eval(buildarr)
        point = data['point']
        point = point.strip('][').split(',')
        # print(buildarr)
        n = len(buildarr)
        if n ==1:
            output=exposedToSunSingle(buildarr,point)
        else:
            near=nearestBuilding(buildarr)
            output=exposedToSunMultiple(buildarr,point,near)
    return jsonify(output)

def point_inside_polygon(x,y,poly,include_edges=True):
    poly=eval(poly)
    n = len(poly)
    inside = False

    p1x, p1y = poly[0]
    for i in range(1, n + 1):
        p2x, p2y = poly[i % n]
        if p1y == p2y:
            if y == p1y:
                if min(p1x, p2x) <= x <= max(p1x, p2x):
                    # point is on horisontal edge
                    inside = include_edges
                    break
                elif x < min(p1x, p2x):  # point is to the left from current edge
                    inside = not inside
        else:  # p1y!= p2y
            if min(p1y, p2y) <= y <= max(p1y, p2y):
                xinters = (y - p1y) * (p2x - p1x) / float(p2y - p1y) + p1x

                if x == xinters:  # point is right on the edge
                    inside = include_edges
                    break

                if x < xinters:  # point is to the left from current edge
                    inside = not inside

        p1x, p1y = p2x, p2y

    return inside

def exposedToSunMultiple(arr,sun,near):
    # inde =arr.index(near)
    index_row = [arr.index(row) for row in arr if near in row][0]
    first_build = arr[index_row]
    if index_row == 0:
        sec_build = arr[1]
    sec_build = arr[0]
    exposed = abs(first_build[1][1] - first_build[0][1])
    exposed += abs(first_build[3][0]- first_build[0][0])
    tanTheta = findTheta(first_build,sun)
    diffBuild = sec_build[0][0] - first_build[3][0]
    extra_len = tanTheta*diffBuild
    exposed += extra_len + abs(first_build[0][1])
    exposed += sec_build[3][0] - sec_build[0][0]
    exposed = round(float(exposed),2)
    return exposed

def exposedToSunSingle(arr,sun):
    # print(len(arr))
    first_build = arr[0]

    exposed = abs(first_build[1][1] - first_build[0][1])
    exposed += abs(first_build[3][0]- first_build[0][0])
    exposed = round(float(exposed),2)

    return exposed

def findTheta(first_build,sun):
    side1 = float(sun[1]) + float(abs(first_build[0][1]))
    width1 = abs(float(sun[0])) + first_build[3][0]
    # print(width1)
    tanTheta = side1/width1
    # print(tanTheta)

    return tanTheta

def nearestBuilding(arr):
    near_list = []
    xy = [0,0]
    for i in arr:
        dist = lambda x, y: (x[0]-y[0])**2 + (x[1]-y[1])**2
        a = min(i, key=lambda co: dist(co, xy))
        # print(a)
        near_list.append(a)
    dist = lambda x, y: (x[0]-y[0])**2 + (x[1]-y[1])**2
    a = min(near_list, key=lambda co: dist(co, xy))
    return a

if __name__ == '__main__':
    app.run(debug=True, port=8000)


import argparse
import copy
import functools
import os

from tqdm import tqdm

import torch
import torch.nn as nn
import torch.utils.data as data

import torchvision.transforms as tf
from torchvision.datasets import MNIST, CIFAR10, CIFAR100

import pyro
import pyro.distributions as dist

import tyxe

ROOT = os.environ.get("DATASETS_PATH", "./data")
USE_CUDA = torch.cuda.is_available()
DEVICE = torch.device("cuda") if USE_CUDA else torch.device("cpu")
C10_MEAN = (0.49139968, 0.48215841, 0.44653091)
C10_SD = (0.24703223, 0.24348513, 0.26158784)

def conv_3x3(c_in, c_out):
    return nn.Conv2d(c_in, c_out, kernel_size=3, stride=1, padding=1)

class ConvNet(nn.Sequential):

    def __init__(self):
        super().__init__()
        self.add_module("Conv1_1", conv_3x3(3, 32))
        self.add_module("ReLU1_1", nn.ReLU(inplace=True))
        self.add_module("Conv1_2", conv_3x3(32, 32))
        self.add_module("ReLU1_2", nn.ReLU(inplace=True))
        self.add_module("MaxPool1", nn.MaxPool2d(2, stride=2))

        self.add_module("Conv2_1", conv_3x3(32, 64))
        self.add_module("ReLU2_1", nn.ReLU(inplace=True))
        self.add_module("Conv2_2", conv_3x3(64, 64))
        self.add_module("ReLU2_2", nn.ReLU(inplace=True))
        self.add_module("MaxPool2", nn.MaxPool2d(2, stride=2))

        self.add_module("Flatten", nn.Flatten())

        self.add_module("Linear", nn.Linear(64 * 8 * 8, 512))
        self.add_module("ReLU", nn.ReLU(inplace=True))

        self.add_module("Head", nn.Linear(512, 10))

class FCNet(nn.Sequential):

    def __init__(self):
        super().__init__()
        self.add_module("Linear", nn.Linear(784, 200))
        self.add_module("ReLU", nn.ReLU(inplace=True))
        self.add_module("Head", nn.Linear(200, 1))

def make_mnist_dataloaders(root, train_batch_size, test_batch_size):
    train_loaders = []
    test_loaders = []

    for train, loaders, bs in zip((True, False), (train_loaders, test_loaders), (train_batch_size, test_batch_size)):
        mnist = MNIST(os.path.join(root, "mnist"), train=train, download=True)
        x = mnist.data.flatten(1) / 255.
        y = mnist.targets
        for i in range(5):
            index = y.ge(i * 2) & y.lt((i + 1) * 2)
            loaders.append(data.DataLoader(data.TensorDataset(x[index], y[index].sub(2 * i).float().unsqueeze(-1)),
                                           bs, shuffle=True, pin_memory=USE_CUDA))

    return train_loaders, test_loaders

def make_cifar_dataloaders(root, train_batch_size, test_batch_size):
    train_loaders = []
    test_loaders = []

    c100_means = []
    c100_sds = []
    for train, loaders, bs in zip((True, False), (train_loaders, test_loaders), (train_batch_size, test_batch_size)):
        c10 = CIFAR10(
                os.path.join(root, "cifar10"),
                train=train,
                transform=tf.Compose([tf.ToTensor(),
                tf.Normalize(C10_MEAN, C10_SD)])
            )

        loaders.append(data.DataLoader(c10, bs, shuffle=train, pin_memory=USE_CUDA))

        c100 = CIFAR100(os.path.join(root, "cifar100"), train=train)
        unnormalized_data = torch.from_numpy(c100.data).permute(0, 3, 1, 2).div(255.)  # convert images to torch arrays
        targets = torch.tensor(c100.targets)

        for i in range(5):
            index = targets.ge(i * 10) & targets.lt((i + 1) * 10)

            unnormalized_data_i = unnormalized_data[index]
            if train:
                c100_means.append(unnormalized_data_i.mean((0, 2, 3), keepdims=True))
                c100_sds.append(unnormalized_data_i.std((0, 2, 3), keepdims=True))
            normalized_data_i = (unnormalized_data_i - c100_means[i]) / c100_sds[i]
            targets_i = targets[index] - i * 10

            dataset_i = data.TensorDataset(normalized_data_i, targets_i)
            loaders.append(data.DataLoader(dataset_i, bs, shuffle=train, pin_memory=USE_CUDA))

    return train_loaders, test_loaders

def main(root, dataset, inference, num_epochs=0):
    train_batch_size = 250
    test_batch_size = 1000

    if dataset == "cifar":
        net = ConvNet()
        obs = tyxe.likelihoods.Categorical(-1)
        train_loaders, test_loaders = make_cifar_dataloaders(root, train_batch_size, test_batch_size)
        num_epochs = 60 if not num_epochs else num_epochs
    elif dataset == "mnist":
        net = FCNet()
        obs = tyxe.likelihoods.Bernoulli(-1, event_dim=1)
        train_loaders, test_loaders = make_mnist_dataloaders(root, train_batch_size, test_batch_size)
        num_epochs = 600 if not num_epochs else num_epochs
    else:
        raise RuntimeError("Unreachable")

    net.to(DEVICE)
    if inference == "mean-field":
        prior = tyxe.priors.IIDPrior(dist.Normal(torch.tensor(0., device=DEVICE), torch.tensor(1., device=DEVICE)),
                                     expose_all=False, hide_modules=[net.Head])
        guide = functools.partial(
            tyxe.guides.AutoNormal,
            init_scale=1e-4,
            init_loc_fn=tyxe.guides.PretrainedInitializer.from_net(net, prefix="net")
        )
        test_samples = 8
    elif inference == "ml":
        prior = tyxe.priors.IIDPrior(dist.Normal(0, 1), expose_all=False, hide_all=True)
        guide = None
    else:
        raise RuntimeError("Unreachable")
    bnn = tyxe.VariationalBNN(net, prior, obs, guide)
    n_tasks = len(train_loaders)
    test_errors = torch.ones(n_tasks, n_tasks)

    head_state_dicts = []
    init_head_sd = copy.deepcopy(net.Head.state_dict())
    for i, train_loader in enumerate(train_loaders, 1):
        elbos = []
        net.Head.load_state_dict(init_head_sd)

        pbar = tqdm(total=num_epochs, unit="Epochs", postfix=f"Task {i}")

        def callback(_i, _ii, e):
            elbos.append(e / len(train_loader.sampler))
            pbar.update()

        obs.dataset_size = len(train_loader.sampler)
        optim = pyro.optim.Adam({"lr": 1e-3})
        with tyxe.poutine.local_reparameterization():
            bnn.fit(train_loader, optim, num_epochs, device=DEVICE, callback=callback)

        pbar.close()

        head_state_dicts.append(copy.deepcopy(net.Head.state_dict()))
        for j, (test_loader, head_params) in enumerate(zip(test_loaders, head_state_dicts)):
            net.Head.load_state_dict(head_params)
            err = sum(bnn.evaluate(x.to(DEVICE), y.to(DEVICE), num_predictions=8)[0] for x, y in test_loader)
            test_errors[i-1, j] = err / len(test_loader.sampler)

        print("\t".join(["Error"] + [f"Task {j}" for j in range(1, i+1)]))
        print("\t" + "\t".join([f"{100 * e:.2f}%" for e in test_errors[i-1, :i]]))

        if inference == "mean-field":
            site_names = tyxe.util.pyro_sample_sites(bnn)
            bnn.update_prior(tyxe.priors.DictPrior(bnn.net_guide.get_detached_distributions(site_names)))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--root", default=ROOT)
    parser.add_argument("--dataset", choices=["mnist", "cifar"], required=True)
    parser.add_argument("--inference", choices=["mean-field", "ml"], required=True)
    parser.add_argument("--num-epochs", default=0, required=False, type=int)
    main(**vars(parser.parse_args()))


import io
from collections import Counter

def load_dictionary(file_path):
    with io.open(file_path, 'r', encoding='latin-1') as file:
        dictionary = {word.strip().lower() for word in file}
    return dictionary

def get_letter_frequencies(data):
    total_letters = sum(1 for char in data if char.isalpha())
    letter_counts = Counter(char.lower() for char in data if char.isalpha())
    letter_frequencies = {char: count / total_letters for char, count in letter_counts.items()}
    return letter_frequencies

def decrypt(data, dictionary):
    letter_frequencies = get_letter_frequencies(data)
    decrypted_results = []
    for shift in range(1, 121):
        decrypted_data = ''
        for char in data:
            if char.isalpha():
                if char.islower():
                    decrypted_char = chr((ord(char) - shift - 97) % 26 + 97)
                else:
                    decrypted_char = chr((ord(char) - shift - 65) % 26 + 65)
                decrypted_data += decrypted_char
            else:
                decrypted_data += char

        words = decrypted_data.lower().split()
        word_count = sum(1 for word in words if word in dictionary)
        word_frequency = word_count / len(words) if len(words) > 0 else 0
        letter_frequency = sum(letter_frequencies.get(char.lower(), 0) for char in decrypted_data)
        score = word_frequency * 0.8 + letter_frequency * 0.2
        decrypted_results.append((decrypted_data, shift, score))

    decrypted_results.sort(key=lambda x: x[2], reverse=True)
    return decrypted_results

def main():
    file_path = 'Resources/engmix.txt'  # Replace with the relative file path on your system
    dictionary = load_dictionary(file_path)

    encrypted_data = input("Enter the encrypted data: ")
    results = decrypt(encrypted_data, dictionary)

    print("\nTop 10 Decryption Results:")
    for decrypted_data, shift, score in results[:10]:
        print(f"Shift: {shift:3} | Decrypted Data: {decrypted_data} | Score: {score:.4f}")

    show_all = input("Show all decrypted results? (y/n): ")
    if show_all.lower() == 'y':
        print("\nAll Decryption Results:")
        for decrypted_data, shift, score in results:
            print(f"Shift: {shift:3} | Decrypted Data: {decrypted_data} | Score: {score:.4f}")

if __name__ == "__main__":
    main()


from flask import Flask, jsonify, request
from elasticsearch import Elasticsearch
import face_recognition

app = Flask(__name__)

es = Elasticsearch("http://elasticsearch:9200")

@app.route("/")
def welcome():
    return jsonify({
        'message': 'welcome1'
    })

@app.route("/search", methods=["POST"])
def search():
    image = face_recognition.load_image_file(request.files['file'])
    face_encoding = face_recognition.face_encodings(image)[0]
    query = {
            "script_score": {
                "query" : {
                    "match_all": {}
                },
                "script": {
                    "source": "cosineSimilarity(params.query_vector, 'face_encoding')",
                    "params": {
                        "query_vector":face_encoding.tolist()
                    }
                }
            }
        }
    response = es.search(index='faces', query=query, size=1, source='face_name', min_score=0.93)
    print(response)
    if len(response['hits']['hits']) == 1:
        return jsonify({
            'status': True,
            "face_name": response['hits']['hits'][0]['_source']['face_name'],
            "score": response['hits']['hits'][0]['_score']
        })
    else:
        return jsonify({
            'status': False,
        })

@app.route("/face_register", methods=["POST"])
def face_register():
    image = face_recognition.load_image_file(request.files['file'])
    face_encoding = face_recognition.face_encodings(image)[0]
    doc = {
        'face_name': request.form['name'],
        'face_encoding': face_encoding.tolist()
    }

    es.index(index='faces', document=doc)

    return jsonify({
        'message': 'success'
    })

if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)


import art
import game_data
import random

def higher_lower():
    print(art.logo)
    score = 0
    gameover = False
    while not gameover:
        option_a = random.choice(game_data.data)
        option_b = random.choice(game_data.data)
        while option_a == option_b:
            option_b = random.choice(game_data.data)
        print(f'Compare A: {option_a["name"]}, a {option_a["description"]}, from {option_a["country"]}.')
        #print(f'{option_a["follower_count"]}')
        print(art.vs)
        print(f'Against B: {option_b["name"]}, a {option_b["description"]}, from {option_b["country"]}.')
        #print(f'{option_b["follower_count"]}')
        answer = input('Who has more followers? Type \'A\' or \'B\': ').lower()
        if (option_a['follower_count'] > option_b['follower_count'] and answer == 'a') or (option_b['follower_count'] > option_a['follower_count'] and answer == 'b'):
            score += 1
            print(f'You\'re right! Current score: {score}.')
        else:
            print(f'Sorry, that\'s wrong. Final score: {score}.')
            gameover = True

def main():
    still_play = True
    while still_play:
        higher_lower()
        new_game_answer = input('Do you want to play again? \'y\' or \'n\': ')
        if new_game_answer != 'y':
            still_play = False

main()


from enum import Enum, auto

class ActionPrototype:
    class Type(Enum):
        MOMENTARY = auto()
        CONTINUOUS = auto()

class FunctionAction(ActionPrototype):
    def __init__(self, callback, _type: ActionPrototype.Type = ActionPrototype.Type.MOMENTARY):
        super().__init__()
        self.callback = callback
        self.type = _type

    def call(self, args, kwargs):
        self.callback(*args, **kwargs)


# ----------------------------------
import streamlit as st
import plotly.express as px
import altair as alt
import pandas as pd

# ----------------------------------

def main():
    st.title('내 앱 대시보드')
    df1 = pd.read_csv('data/lang_data.csv')
    st.dataframe(df1)
    st.write( df1.shape )

    ### 멀티셀렉트를 이용해 언어를 선택하게 하고 그거와 관련된 차트 그려보기

    # 컬럼에 뭐 있는지 확인
    # print( df1.columns )
    # 슬라이싱 이용해서 week 빼기
    print( df1.columns[ 1: ] )

    # 변수에 저장
    lang_list = df1.columns[ 1: ]

    # 유저에게 언어 선택 받기
    choice_list = st.multiselect('언어를 선택하세요', lang_list)

    # 프린트해서 확인
    print(choice_list)

    #@@
    # 유저가 아무것도 선택 안했을때 처리하기
    if len(choice_list) > 0 :  # 데이터가 있다면

        # 유저가 선택한 리스트만 가져와 변수에 넣고 표 보여주기
        choice_df = df1[ choice_list ]
        st.dataframe(choice_df)

        ## 스트림릿이 제공하는 라인차트
        # 각 행의 데이터를 y, 행 정보를 x축
        st.line_chart(choice_df)

        ## 스트림릿이 제공하는 영역차트
        #
        st.area_chart(choice_df)

    ### 아무것도 선택 안했을때 차트영역등이 빈공간으로 나오지 않게 하기
    # 조건문이 필요
    # 위치가 중요
    #@@ 위치에 집어넣으면 됨.

    ### 아이리스 데이터 ---------------------------------------
    df2 = pd.read_csv('data/iris.csv')

    ## 스트림릿이 제공하는 바 차트
    df3 = df2[ ['sepal_length', 'sepal_width'] ]
    st.bar_chart(df3)

    ## Altair 이용
    chart = alt.Chart(df2).mark_circle().encode(
        x = 'petal_length', y = 'petal_width', color = 'species')

    st.altair_chart(chart)

    ### 로케이션 데이터 ----------------------------------------

    ## 스트림릿의 map차트
    df4 = pd.read_csv('data/location.csv', index_col = 0)
    print(df4)

    # zoom = 5 : 숫자가 작을수록 멀리서 보는것. 숫자만 적어도 됨.
    st.map(df4, zoom = 5)

    ### 프로그램 언어 데이터
    df5 = pd.read_csv('data/prog_languages_data.csv', index_col = 0)
    st.dataframe(df5)

    # plotly 의 pie 차트 ( 파이차트 - 비율을 보고 싶을때)
    fig1 = px.pie(df5, 'lang', 'Sum', title=' 각언어별 비율') # 차트 영역 만들기
    # df5 : 가져올 데이터, 'lang': 어떤거에대해 그릴꺼냐, 'Sum': 수치 뭘로할까
    st.plotly_chart(fig1)

    # plotly 의 bar 차트
    # fig2 = px.bar()
    df6 = df5.sort_values('Sum', ascending = False)
    fig2 = px.bar(df6, x = 'lang', y = 'Sum')
    st.plotly_chart(fig2)

if __name__ == '__main__':
    main()


from django.urls import path

from . import views
urlpatterns = [
    path('', views.index, name="index"),
    path('session/', views.session, name="login"),
    path('files/', views.get_file_list, name="file_list"),
    path('file/', views.upload, name="upload"),
    path('file/<str:file_id>/', views.download, name="download"),
    path('post/', views.post, name="post"),
    path('post/all/', views.getall, name="getall")
]


# -*- coding: utf-8 -*-
"""
Unittests for views
"""
import datetime
import os

from django.core.files import File
from django.test import TestCase
from django.test.utils import override_settings
from mock import Mock, patch

from fuuk.people.models import Agency, Article, Attachment, Author, Course, Grant, Human, Person, Thesis

@override_settings(LANGUAGE_CODE='en')
class TestArticleList(TestCase):
    def setUp(self):
        Article.objects.create(title='Perpetum mobile still running', type="ARTICLE", year="2013")
        Article.objects.create(title='White holes: Theory and observation', type="BOOK", year="2005")
        Article.objects.create(title='New type of black hole discovered', type="ARTICLE", year="2005")
        Article.objects.create(title='Report on a new warpdrive prototype', type="ARTICLE", year="2005")
        Article.objects.create(title='Some really old book on something we do not remember', type="BOOK", year="2003")
        # These shouldn't get counted
        Article.objects.create(title='Black hole types', type="POSTER", year="2002")
        Article.objects.create(title='Humble beginnings of the Warpdrives.', type="TALK", year="2001")
        Article.objects.create(title='Jumpgates are reality!', type="INVITED", year="2000")

    def test_basic(self):
        response = self.client.get('/people/articles/')
        self.assertContains(response, 'Year', count=1)
        self.assertEqual(response.context['year'], 2013)
        self.assertQuerysetEqual(response.context['years'], ['2013', '2005', '2003'])
        self.assertQuerysetEqual(response.context['object_list'], ['<Article: Perpetum mobile still running>'])

    def test_2005(self):
        response = self.client.get('/people/articles/2005/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['year'], 2005)
        self.assertQuerysetEqual(response.context['object_list'],
                                 ['<Article: New type of black hole discovered>',
                                  '<Article: Report on a new warpdrive prototype>',
                                  '<Article: White holes: Theory and observation>'])

    def test_1999(self):
        response = self.client.get('/people/articles/1999/')
        self.assertEqual(response.status_code, 404)

@override_settings(LANGUAGE_CODE='en')
class TestGrantList(TestCase):
    def setUp(self):
        # This method is being overridden because GrantList uses date.today().year in get_queryset
        # Mock date.today().year
        date_mock = Mock()
        date_mock.today.return_value = datetime.date(2013, 1, 1)
        patcher = patch('fuuk.people.views.date', date_mock)
        self.addCleanup(patcher.stop)
        self.datetime_mock = patcher.start()

        # Prepare an author
        person = Person.objects.create(first_name="Test", last_name="Person")
        # Prepare agency
        agency = Agency.objects.create(name="GA", shortcut="GA")
        # Running
        Grant.objects.create(title='Perpetum mobile', start="1990", end="2014", number="1",
                             author=person, agency=agency, annotation="An annotation")
        Grant.objects.create(title='White holes', start="2000", end="2013", number="2",
                             author=person, agency=agency, annotation="An annotation")
        # Finished
        Grant.objects.create(title='Black holes', start="1990", end="2012", number="3", author=person,
                             agency=agency, annotation="An annotation")
        Grant.objects.create(title='Warp drive', start="2000", end="2011", number="4", author=person,
                             agency=agency, annotation="An annotation")
        # Too old to be included
        Grant.objects.create(title='Jumpgate', start="1990", end="2000", number="5", author=person, agency=agency,
                             annotation="An annotation")
        # Just started
        Grant.objects.create(title='Fancy new grant', start="2013", end="2020", number="6", author=person,
                             agency=agency, annotation="An annotation")

    def test_basic(self):
        response = self.client.get('/people/grants/')
        self.assertContains(response, 'Current grants', count=1)
        self.assertContains(response, 'Ended grants', count=1)
        self.assertQuerysetEqual(response.context['object_list'],
                                 ['<Grant: Fancy new grant>', '<Grant: Perpetum mobile>', '<Grant: White holes>'])
        self.assertQuerysetEqual(response.context['grants_finished'],
                                 ['<Grant: Black holes>', '<Grant: Warp drive>'])

class TestGrantDetail(TestCase):
    def setUp(self):
        # Prepare an author
        person = Person.objects.create(first_name="Test", last_name="Person")
        # Prepare agency
        agency = Agency.objects.create(name="GA", shortcut="GA")
        # Prepare a grant with ids 1 and 2
        self.a = Grant.objects.create(start="2000", end="2001", agency=agency, number="1", author=person,
                                      title="Testing grant", annotation="An annotation")
        self.b = Grant.objects.create(start="2001", end="2005", agency=agency, number="2", author=person,
                                      title="Second grant", annotation="An annotation")

    def test_basic(self):
        response = self.client.get(('/people/grants/%s/' % self.a.id))
        self.assertContains(response, 'Testing grant', count=1)

    def test_second(self):
        response = self.client.get(('/people/grants/%s/' % self.b.id))
        self.assertContains(response, 'Second grant', count=1)

    def test_none(self):
        response = self.client.get('/people/grants/3000/')
        self.assertEqual(response.status_code, 404)

@override_settings(LANGUAGE_CODE='en')
class TestThesesList(TestCase):
    def setUp(self):
        # Prepare an author
        person = Person.objects.create(first_name="Test", last_name="Person")
        Thesis.objects.create(title='Theoretical calculations of white holes', type='BC', year=2001, author=person,
                              defended=True)
        Thesis.objects.create(title='Jumpgates limitations', type='MGR', year=2002, author=person, defended=True)
        Thesis.objects.create(title='Wow I have finished my PhD really fast', type='PHD', year=2002, author=person,
                              defended=True)
        # Should not get counted
        Thesis.objects.create(title="Not so good", type='RNDR', year=2003, author=person)
        Thesis.objects.create(title="Professor's thesis", type='PROF', year=2004, author=person)

    def test_basic(self):
        response = self.client.get('/people/theses/')
        self.assertContains(response, 'By thesis type', count=1)
        self.assertQuerysetEqual(response.context['object_list'], [])
        self.assertEqual(len(response.context['types']), 3)
        self.assertQuerysetEqual(response.context['years'], ['2002', '2001'])

    def test_year(self):
        response = self.client.get('/people/theses/?year=2002')
        self.assertContains(response, 'Theses defended in year 2002', count=1)
        self.assertEqual(response.context['year'], '2002')
        self.assertQuerysetEqual(response.context['object_list'], ['<Thesis: Wow I have finished my PhD really fast>',
                                                                   '<Thesis: Jumpgates limitations>'])

    def test_type(self):
        response = self.client.get('/people/theses/?type=BC')
        self.assertEqual(response.context['type'], 'BC')
        self.assertContains(response, 'Defended bachelor theses', count=1)
        self.assertQuerysetEqual(response.context['object_list'], ['<Thesis: Theoretical calculations of white holes>'])

@override_settings(LANGUAGE_CODE='en')
class TestThesisDetail(TestCase):
    def setUp(self):
        # Prepare an author
        human = Human.objects.create(nickname='Person_Test')
        person = Person.objects.create(first_name="Test", last_name="Person", human=human)
        self.a = Thesis.objects.create(type='BC', year=2000, author=person, title='Test thesis')
        self.b = Thesis.objects.create(type='BC', year=2000, author=person, title='Defended test thesis',
                                       defended=True)

    def test_basic(self):
        response = self.client.get(('/people/thesis/id=%s/' % self.a.id))
        self.assertContains(response, 'Test thesis', count=1)
        self.assertContains(response, 'Test Person', count=1)
        self.assertNotContains(response, 'Keywords')

    def test_defended(self):
        response = self.client.get(('/people/thesis/id=%s/' % self.b.id))
        self.assertContains(response, 'Defended test thesis', count=1)
        self.assertContains(response, 'Keywords', count=1)

class TestCourseList(TestCase):
    def setUp(self):
        Course.objects.create(name='Testing course', code='AA001')
        Course.objects.create(name='Second course', code='AA002')

    def test_basic(self):
        response = self.client.get('/people/courses/')
        self.assertContains(response, 'Testing course', count=1)
        self.assertQuerysetEqual(response.context['object_list'],
                                 ['<Course: Testing course>', '<Course: Second course>'], ordered=False)

class TestDownloadList(TestCase):
    def setUp(self):
        course = Course.objects.create(name='Course with attachment', code='AA001')
        Course.objects.create(name='Course without attachment', code='AA002')
        a_file = open(os.path.join(os.path.dirname(__file__), 'test_views.py'))
        Attachment.objects.create(course=course, title='The attachment', file=File(a_file))

    def test_basic(self):
        response = self.client.get('/people/downloads/')
        self.assertContains(response, 'Course with attachment', count=1)
        self.assertContains(response, 'The attachment', count=1)
        self.assertNotContains(response, 'Course without attachment')

@override_settings(LANGUAGE_CODE='en')
class TestPeopleList(TestCase):
    def setUp(self):
        human = Human.objects.create(nickname='Bachelor_Test')
        Person.objects.create(type='BC', first_name='Test', last_name='Bachelor', human=human)
        human = Human.objects.create(nickname='Magister_Test')
        Person.objects.create(type='MGR', first_name='Test', last_name='Magister', human=human)
        human = Human.objects.create(nickname='Doctoral_Test')
        Person.objects.create(type='PHD', first_name='Test', last_name='Doctoral', human=human)
        human = Human.objects.create(nickname='Staff_Test')
        Person.objects.create(type='STAFF', first_name='Test', last_name='Staff', human=human)
        human = Human.objects.create(nickname='Other_Test')
        Person.objects.create(type='OTHER', first_name='Test', last_name='Other', human=human)
        human = Human.objects.create(nickname='Grad_Test')
        Person.objects.create(type='GRAD', first_name='Test', last_name='Graduate', human=human)
        human = Human.objects.create(nickname='Student_Test')
        Person.objects.create(type='STUDENT', first_name='Test', last_name='Student', human=human)
        human = Human.objects.create(nickname='Retired_Test')
        Person.objects.create(type='STAFF', first_name='Test', last_name='Retired', human=human,
                              is_active=False)
        human = Human.objects.create(nickname='Other_InactiveTest')
        Person.objects.create(type='OTHER', first_name='Test', last_name='Alsoretired', human=human,
                              is_active=False)
        # These shouldn't get included
        human = Human.objects.create(nickname='Bachelor_Inactive')
        Person.objects.create(type='BC', first_name='FalseTest', last_name='Bachelor', human=human,
                              is_active=False)
        human = Human.objects.create(nickname='Magister_Inactive')
        Person.objects.create(type='MGR', first_name='FalseTest', last_name='Magister', human=human,
                              is_active=False)
        human = Human.objects.create(nickname='Doctoral_Inactive')
        Person.objects.create(type='PHD', first_name='FalseTest', last_name='Doctoral', human=human,
                              is_active=False)
        human = Human.objects.create(nickname='Grad_Inactive')
        Person.objects.create(type='GRAD', first_name='FalseTest', last_name='Graduate', human=human,
                              is_active=False)
        human = Human.objects.create(nickname='Student_Inactive')
        Person.objects.create(type='STUDENT', first_name='FalseTest', last_name='Student', human=human,
                              is_active=False)

    def test_phd(self):
        response = self.client.get('/people/phd/')
        self.assertNotContains(response, 'Test Bachelor')
        self.assertNotContains(response, 'Test Magister')
        self.assertNotContains(response, 'Test Student')
        self.assertContains(response, 'Test Doctoral', count=1)
        self.assertNotContains(response, 'Test Staff')
        self.assertNotContains(response, 'Test Graduate')
        self.assertNotContains(response, 'Test Other')
        self.assertNotContains(response, 'Test Retired')
        self.assertNotContains(response, 'FalseTest')
        self.assertQuerysetEqual(response.context['object_list'], ['<Person: Doctoral Test (PhD. student)>'])
        self.assertEqual(response.context['title'], 'PhD. students')

    def test_staff(self):
        response = self.client.get('/people/staff/')
        self.assertNotContains(response, 'Test Bachelor')
        self.assertNotContains(response, 'Test Magister')
        self.assertNotContains(response, 'Test Student')
        self.assertNotContains(response, 'Test Doctoral')
        self.assertContains(response, 'Test Staff', count=1)
        self.assertNotContains(response, 'Test Graduate')
        self.assertNotContains(response, 'Test Other')
        self.assertNotContains(response, 'Test Retired')
        self.assertNotContains(response, 'FalseTest')
        self.assertQuerysetEqual(response.context['object_list'], ['<Person: Staff Test (Academic staff)>'])
        self.assertEqual(response.context['title'], 'Academic staff')

    def test_other(self):
        response = self.client.get('/people/other/')
        self.assertNotContains(response, 'Test Bachelor')
        self.assertNotContains(response, 'Test Magister')
        self.assertNotContains(response, 'Test Student')
        self.assertNotContains(response, 'Test Doctoral')
        self.assertNotContains(response, 'Test Staff')
        self.assertNotContains(response, 'Test Graduate')
        self.assertContains(response, 'Test Other', count=1)
        self.assertNotContains(response, 'Test Retired')
        self.assertQuerysetEqual(response.context['object_list'], ['<Person: Other Test (Other staff)>'])
        self.assertNotContains(response, 'FalseTest')
        self.assertEqual(response.context['title'], 'Other staff')

    def test_students(self):
        response = self.client.get('/people/students/')
        self.assertContains(response, 'Test Bachelor', count=1)
        self.assertQuerysetEqual(response.context['bachelors'], ['<Person: Bachelor Test (Bc. student)>'])
        self.assertContains(response, 'Test Magister', count=1)
        self.assertQuerysetEqual(response.context['object_list'], ['<Person: Magister Test (Mgr. student)>'])
        self.assertContains(response, 'Test Student', count=1)
        self.assertQuerysetEqual(response.context['students'], ['<Person: Student Test (Student)>'])
        self.assertNotContains(response, 'Test Doctoral')
        self.assertNotContains(response, 'Test Staff')
        self.assertNotContains(response, 'Test Graduate')
        self.assertNotContains(response, 'Test Other')
        self.assertNotContains(response, 'Test Retired')
        self.assertNotContains(response, 'FalseTest')

    def test_graduates(self):
        response = self.client.get('/people/graduates/')
        self.assertNotContains(response, 'Test Bachelor')
        self.assertNotContains(response, 'Test Magister')
        self.assertNotContains(response, 'Test Student')
        self.assertNotContains(response, 'Test Doctoral')
        self.assertNotContains(response, 'Test Staff')
        self.assertContains(response, 'Test Graduate', count=1)
        self.assertNotContains(response, 'Test Other')
        self.assertNotContains(response, 'Test Retired')
        self.assertQuerysetEqual(response.context['object_list'], ['<Person: Graduate Test (Graduate student)>'])
        self.assertNotContains(response, 'FalseTest')
        self.assertEqual(response.context['title'], 'Graduate students')

    def test_retired(self):
        response = self.client.get('/people/retired/')
        self.assertNotContains(response, 'Test Bachelor')
        self.assertNotContains(response, 'Test Magister')
        self.assertNotContains(response, 'Test Student')
        self.assertNotContains(response, 'Test Doctoral')
        self.assertNotContains(response, 'Test Staff')
        self.assertNotContains(response, 'Test Graduate')
        self.assertNotContains(response, 'Test Other')
        self.assertContains(response, 'Test Retired', count=1)
        self.assertContains(response, 'Test Alsoretired')
        self.assertQuerysetEqual(response.context['object_list'], ['<Person: Alsoretired Test (Other staff)>',
                                                                   '<Person: Retired Test (Academic staff)>'])
        self.assertNotContains(response, 'FalseTest')
        self.assertEqual(response.context['title'], 'Former members')
        self.assertTemplateUsed(response, 'people/retired_list.html')

@override_settings(LANGUAGE_CODE='en')
class TestPersonalPages(TestCase):
    def setUp(self):
        # Testing person
        H1 = Human.objects.create(nickname='Person_test')
        P1 = Person.objects.create(type='STAFF', first_name='Test', last_name='Person', human=H1)
        # Inactive version of previous
        Person.objects.create(type='PHD', first_name='Test', last_name='Person', human=H1, is_active=False)
        # False person
        H2 = Human.objects.create(nickname='False_person')
        P2 = Person.objects.create(type='SATFF', first_name='False', last_name='Person', human=H2)
        Thesis.objects.create(type='PHD', author=P1, title='Ongoing PHD', year=2000)
        Thesis.objects.create(type='MGR', author=P1, title='Finished MGR', year=2000,
                              defended=True)
        Thesis.objects.create(type='BC', author=P1, title='Finished BC', year=1997,
                              defended=True)
        # Articles
        A1 = Article.objects.create(type="ARTICLE", year="2013", title='First article')
        A2 = Article.objects.create(type="BOOK", year="2005", title='Newest trends in writing django tests')
        A3 = Article.objects.create(type="ARTICLE", year="2005", title='False article')
        A4 = Article.objects.create(type="ARTICLE", year="2005", title='It is hard to come up with some funny thing...')
        Article.objects.create(type="BOOK", year="2003", title='My first book')
        # Author join
        Author.objects.create(person=P1, article=A1, order=1)
        Author.objects.create(person=P1, article=A2, order=1)
        Author.objects.create(person=P1, article=A4, order=2)
        Author.objects.create(person=P2, article=A3, order=1)
        # Students
        H3 = Human.objects.create(nickname='Student_test')
        Person.objects.create(type='BC', first_name='Test', last_name='Student', human=H3,
                              advisor=P1)
        H4 = Human.objects.create(nickname='Student_false')
        Person.objects.create(type='BC', first_name='False', last_name='Student', human=H4,
                              advisor=P2)
        H5 = Human.objects.create(nickname='Student_finished')
        Person.objects.create(type='BC', first_name='Finished', last_name='Student', human=H5,
                              advisor=P1, is_active=False)
        # Courses
        self.course1 = Course.objects.create(name='Testing course', code='AA001')
        self.course1.lectors.add(P1)
        Course.objects.create(name='False course', code='FF001').lectors.add(P2)
        # Grants
        # Prepare agency
        agency = Agency.objects.create(name="GA", shortcut="GA")
        # Prepare a grant with ids 1 and 2
        self.grant1 = Grant.objects.create(start="2000", end="2001", agency=agency, number="1", author=P1,
                                           title="Testing grant", annotation="An annotation")
        Grant.objects.create(start="2001", end="2005", agency=agency, number="2", author=P2,
                             title="False grant", annotation="An annotation")

    def test_nonexistent(self):
        response1 = self.client.get('/Person_nonexistent/')
        self.assertContains(response1, 'File not found', status_code=404)
        response2 = self.client.get('/Person_nonexistent/papers/')
        self.assertContains(response2, 'File not found', status_code=404)
        response3 = self.client.get('/Person_nonexistent/courses/')
        self.assertContains(response3, 'File not found', status_code=404)
        response4 = self.client.get('/Person_nonexistent/students/')
        self.assertContains(response4, 'File not found', status_code=404)
        response5 = self.client.get('/Person_nonexistent/grants/')
        self.assertContains(response5, 'File not found', status_code=404)

    def test_detail(self):
        response = self.client.get('/people/person/Person_test/')
        self.assertContains(response, 'Test Person', count=1)
        self.assertContains(response, 'Ongoing PHD', count=1)
        self.assertContains(response, 'Finished MGR', count=1)
        self.assertQuerysetEqual(response.context['theses'], ['<Thesis: Finished MGR>', '<Thesis: Finished BC>'])
        self.assertQuerysetEqual(response.context['theses_ongoing'], ['<Thesis: Ongoing PHD>'])

    def test_articles(self):
        response = self.client.get('/people/person/Person_test/papers/')
        self.assertContains(response, 'First article', count=1)
        self.assertNotContains(response, 'False article')
        articles = ['<Article: First article>',
                    '<Article: It is hard to come up with some funny thing...>',
                    '<Article: Newest trends in writing django tests>']
        self.assertQuerysetEqual(response.context['publications'], articles)
        self.assertQuerysetEqual(response.context['publications_first'],
                                 ['<Article: First article>', '<Article: Newest trends in writing django tests>'])

    def test_students(self):
        response = self.client.get('/people/person/Person_test/students/')
        self.assertContains(response, 'Test Student', count=1)
        self.assertContains(response, 'Finished Student', count=1)
        self.assertNotContains(response, 'False Student')

    def test_courses(self):
        response = self.client.get('/people/person/Person_test/courses/')
        self.assertContains(response, 'Testing course', count=1)
        self.assertNotContains(response, 'False course')

    def test_courses_practical(self):
        # New testing person
        H3 = Human.objects.create(nickname='Person_practical')
        P3 = Person.objects.create(type='STAFF', first_name='Test', last_name='Practical', human=H3)
        # Prepare a course with P3 as practical
        self.course1.practical_lectors.add(P3)
        response = self.client.get('/people/person/Person_practical/courses/')
        self.assertContains(response, 'Testing course', count=1)

    def test_grants(self):
        response = self.client.get('/people/person/Person_test/grants/')
        self.assertContains(response, 'Testing grant', count=1)
        self.assertNotContains(response, 'False grant')

    def test_grants_coauthor(self):
        # New testing person
        H3 = Human.objects.create(nickname='Person3_test')
        P3 = Person.objects.create(type='STAFF', first_name='Test', last_name='Coauthor', human=H3)
        # Prepare a grant with P3 as coauthor
        self.grant1.co_authors.add(P3)
        response = self.client.get('/people/person/Person3_test/grants/')
        self.assertContains(response, 'Testing grant', count=1)

@override_settings(LANGUAGE_CODE='en')
class TestEmptyDatabase(TestCase):
    def test_articles(self):
        # Should return 404
        response = self.client.get('/people/articles/')
        self.assertEqual(response.status_code, 404)

    def test_grants(self):
        # Should show empty page
        response = self.client.get('/people/grants/')
        self.assertContains(response, 'suggestion or more information', count=1)

    def test_people(self):
        # All of these should return empty page with the basic title
        response = self.client.get('/people/staff/')
        self.assertContains(response, '<h1>Academic staff</h1>', count=1, html=True)
        response = self.client.get('/people/phd/')
        self.assertContains(response, '<h1>PhD. students</h1>', count=1, html=True)
        response = self.client.get('/people/students/')
        self.assertContains(response, '<h1>Students</h1>', count=1, html=True)
        response = self.client.get('/people/other/')
        self.assertContains(response, '<h1>Other staff</h1>', count=1, html=True)
        response = self.client.get('/people/retired/')
        self.assertContains(response, '<h1>Former members</h1>', count=1, html=True)
        response = self.client.get('/people/graduates/')
        self.assertContains(response, '<h1>Graduate students</h1>', count=1, html=True)

    def test_theses(self):
        # Returns empty page
        response = self.client.get('/people/theses/')
        self.assertContains(response, 'suggestion or more information', count=1)

    def test_courses(self):
        # Returns empty page
        response = self.client.get('/people/courses/')
        self.assertContains(response, 'suggestion or more information', count=1)

    def test_downloads(self):
        # Returns empty page
        response = self.client.get('/people/downloads/')
        self.assertContains(response, 'suggestion or more information', count=1)


from django.db import models

# Create your models here.

class Microservice(models.Model):
    # 微服务表

    on_off_choice = (
        ("开", "开"),
        ("关", "关"),
    )
    # 微服务开关枚举

    dingding_on_off_choice = (
        ("开", "开"),
        ("关", "关"),
    )
    # 钉钉开关枚举

    e_mail_on_off_choice = (
        ("开", "开"),
        ("关", "关"),
    )
    # 邮件开关枚举

    microservice_name = models.CharField(
        max_length=50, verbose_name="微服务名称",
        help_text="请输入微服务名称", db_index=True)
    # 微服务名称，并创建索引，必填
    swagger_address = models.CharField(
        max_length=255, verbose_name="swagger地址",
        help_text="请输入swagger地址", default="",
        blank=True, null=True, )
    # swagger地址
    microservice_on_off = models.CharField(
        choices=on_off_choice, max_length=11,
        blank=True, null=True, help_text="请选择开关",
        verbose_name="微服务开关", default="开")
    # 微服务开关
    dingding_on_off = models.CharField(
        choices=dingding_on_off_choice, max_length=11,
        blank=True, null=True, help_text="请选择开关",
        verbose_name="钉钉开关", default="关")
    # 钉钉开关
    e_mail_on_off = models.CharField(
        choices=e_mail_on_off_choice, max_length=11,
        blank=True, null=True, help_text="请选择开关",
        verbose_name="邮件开关", default="关")
    # 邮件开关
    microservice_introduce = models.CharField(
        max_length=255, verbose_name="微服务简介", help_text="请输入微服务简介",
        blank=True, null=True)
    # 微服务简介，选填
    create_time = models.DateTimeField(
        auto_now_add=True, blank=True, null=True, verbose_name="创建时间")
    # 创建时间
    update_time = models.DateTimeField(
        auto_now=True, blank=True, null=True, verbose_name="修改时间")

    # 修改时间

    class Meta:
        db_table = "microservice"
        verbose_name = "微服务列表"
        verbose_name_plural = "微服务列表"

    def __str__(self):
        return self.microservice_name

class Case(models.Model):
    # 用例表

    case_on_off_choice = (
        ("开", "开"),
        ("关", "关"),
    )
    # 用例开关枚举

    dingtalk_on_off_choice = (
        ("开", "开"),
        ("关", "关"),
    )
    # 钉钉开关枚举

    mailbox_on_off_choice = (
        ("开", "开"),
        ("关", "关"),
    )
    # 邮件开关枚举

    case_microservice = models.ForeignKey(
        Microservice, on_delete=models.CASCADE,
        verbose_name="微服务", related_name="microservices",
        help_text="请选择微服务")
    # 外键，关联微服务id
    case_name = models.CharField(
        max_length=50, verbose_name="用例名称",
        help_text="请输入用例名称", db_index=True)
    # 用例名称，并创建索引，必填
    case_on_off = models.CharField(
        choices=case_on_off_choice, max_length=11,
        blank=True, null=True, help_text="请选择开关",
        verbose_name="用例开关", default="开")
    # 用例开关
    dingtalk_on_off = models.CharField(
        choices=dingtalk_on_off_choice, max_length=11,
        blank=True, null=True, help_text="请选择开关",
        verbose_name="钉钉开关", default="关")
    # 钉钉开关
    mailbox_on_off = models.CharField(
        choices=mailbox_on_off_choice, max_length=11,
        blank=True, null=True, help_text="请选择开关",
        verbose_name="邮件开关", default="关")
    # 邮件开关
    create_time = models.DateTimeField(
        auto_now_add=True, blank=True, null=True, verbose_name="创建时间")
    # 创建时间
    update_time = models.DateTimeField(
        auto_now=True, blank=True, null=True, verbose_name="修改时间")

    # 修改时间

    class Meta:
        db_table = "case"
        verbose_name = "用例列表"
        verbose_name_plural = "用例列表"

    def __str__(self):
        return self.case_name

class Step(models.Model):
    # 步骤表

    step_on_off_choice = (
        ("开", "开"),
        ("关", "关"),
    )
    # 步骤开关枚举

    mode_choice = (
        ("GET", "GET"),
        ("POST", "POST"),
        ("PUT", "PUT"),
        ("DELETE", "DELETE"),
        ("PATCH", "PATCH"),
    )
    # 请求方式枚举
    # 第一个元素是存储在数据库里面的值
    # 第二个元素是页面显示的值

    step_case = models.ForeignKey(
        Case, on_delete=models.CASCADE,
        verbose_name="用例名称", related_name="step_key",
        help_text="请选择用例")
    # 外键，关联用例id
    step_name = models.CharField(
        max_length=50, verbose_name="步骤名称",
        help_text="请输入步骤名称", db_index=True)
    # 步骤名称，并创建索引，必填
    step_on_off = models.CharField(
        choices=step_on_off_choice, max_length=11,
        blank=True, null=True, help_text="请选择开关",
        verbose_name="步骤开关", default="开")
    # 步骤开关
    request_mode = models.CharField(
        choices=mode_choice, max_length=11,
        verbose_name="请求方式", default="GET",
        help_text="请选择请求方式")
    # 请求方式，必填
    api = models.CharField(
        max_length=255, verbose_name="接口路径", help_text="请输入接口路径")
    # 接口路径，必填
    body = models.TextField(
        verbose_name="请求体", blank=True, null=True,
        help_text="请输入json格式的请求体", default="")
    # 请求体，选填
    headers = models.TextField(
        verbose_name="请求头", blank=True, null=True,
        help_text="请输入json格式的请求头", default='{"Content-Type":"application/json;charset=UTF-8"}')
    # 请求头，选填
    query_string = models.TextField(
        verbose_name="请求参数", blank=True, null=True,
        help_text="请输入json格式的请求参数", default="")
    # 请求参数，选填
    expected_time = models.FloatField(
        max_length=8, verbose_name="预期的响应时间",
        blank=True, null=True,
        default=3.0, help_text="请输入预期的响应时间，单位：秒")
    # 预期的响应时间，选填
    expected_code = models.IntegerField(
        verbose_name="预期的响应代码", help_text="请输入预期的响应代码",
        default=200)
    # 预期的响应代码，必填
    expected_result = models.TextField(
        verbose_name="预期的响应结果", help_text="请输入json格式的预期的响应结果",
        default="")
    # 预期的响应结果，必填
    regular = models.TextField(
        verbose_name="正则", blank=True, null=True,
        help_text="请输入正则（变量名与表达式）", default="")
    # 正则，选填
    create_time = models.DateTimeField(
        auto_now_add=True, blank=True, null=True, verbose_name="创建时间")
    # 创建时间
    update_time = models.DateTimeField(
        auto_now=True, blank=True, null=True, verbose_name="修改时间")

    # 修改时间

    class Meta:
        db_table = "step"
        verbose_name = "步骤列表"
        verbose_name_plural = "步骤列表"

    def __str__(self):
        return self.step_name

class RunningResults(models.Model):
    # 运行结果表

    pass_status_choice = (
        ("是", "是"),
        ("否", "否"),
    )

    running_results_step = models.ForeignKey(
        Step, on_delete=models.CASCADE,
        verbose_name="步骤名称", related_name="running_key",
        help_text="请选择步骤")
    # 外键，关联步骤id
    pass_status = models.CharField(
        choices=pass_status_choice, max_length=11,
        blank=True, null=True, default="",
        verbose_name="是否通过", db_index=True)
    # 是否通过，并创建索引
    fail_reason = models.TextField(
        verbose_name="失败原因", default="",
        blank=True, null=True)
    # 失败原因
    run_time = models.DateTimeField(
        auto_now_add=True, verbose_name="运行时间",
        blank=True, null=True, db_index=True)
    # 运行时间
    actual_time = models.FloatField(
        max_length=8, verbose_name="实际的响应时间（秒）",
        blank=True, null=True, db_index=True)
    # 实际的响应时间
    actual_code = models.IntegerField(
        verbose_name="实际的响应代码",
        blank=True, null=True)
    # 实际的响应代码
    actual_result = models.TextField(
        verbose_name="实际的响应结果",
        blank=True, null=True, default="")

    # 实际的响应结果

    class Meta:
        db_table = "running_results"
        verbose_name = "运行结果列表"
        verbose_name_plural = "运行结果列表"

    def __str__(self):
        return self.pass_status

    def actual_result_ellipsis(self):
        if len(str(self.actual_result)) > 20:
            return "{}......".format(str(self.actual_result[0:20]))
        else:
            return self.actual_result

    actual_result_ellipsis.short_description = "实际的响应结果"
    actual_result_ellipsis.allow_tags = True

class EnvironmentConfiguration(models.Model):
    # 环境配置表

    environment_configuration_microservice = models.OneToOneField(
        Microservice, on_delete=models.CASCADE,
        verbose_name="微服务", related_name="microservice_environment",
        help_text="请选择微服务")
    # 外键，关联微服务id
    domain_name = models.CharField(
        max_length=255, verbose_name="域名",
        help_text="请输入域名", db_index=True)
    # 域名，并创建索引，必填
    webhook = models.CharField(
        max_length=255, verbose_name="钉钉Webhook",
        help_text="请输入钉钉Webhook", db_index=True)
    # 钉钉机器人Webhook，并创建索引，必填
    secret = models.CharField(
        max_length=255, verbose_name="密钥",
        help_text="请输入密钥", db_index=True)
    # 密钥，并创建索引，必填
    recipient_email = models.CharField(
        max_length=255, verbose_name="收件人邮箱",
        help_text="请输入收件人邮箱", db_index=True)
    # 收件人邮箱，并创建索引，必填
    create_time = models.DateTimeField(
        auto_now_add=True, blank=True, null=True, verbose_name="创建时间")
    # 创建时间
    update_time = models.DateTimeField(
        auto_now=True, blank=True, null=True, verbose_name="修改时间")

    # 修改时间

    class Meta:
        db_table = "environment_configuration"
        verbose_name = "环境配置列表"
        verbose_name_plural = "环境配置列表"

    def __str__(self):
        return self.domain_name


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

import tensorflow
import tensorflow_hub as hub
from tensorflow.keras.layers import Conv1D
from tensorflow.keras.layers import LSTM, Bidirectional
from tensorflow.keras.layers import Dense, Flatten, MaxPooling1D, Input, Activation, concatenate
from tensorflow.keras.models import Sequential, Model
from sklearn.preprocessing import OneHotEncoder
from tensorflow.keras.layers import Dropout, BatchNormalization, Reshape
from sklearn.utils import resample
from sklearn.utils import shuffle
from tensorflow.keras.models import load_model
from sklearn.preprocessing import LabelEncoder
from tensorflow.keras.utils import to_categorical

print("Loading Features and Labels \n\n")

######################
## Train Set ##
######################

train = pd.read_csv("Merged_Train_OG.csv")
print(train.shape)
train = train.sample(frac=1)

feature1 = train.iloc[:, 0:512]
feature2 = train.iloc[:, 512:1024]

print(feature1.shape, feature2.shape)

train_x_f1 = np.array(feature1)
train_x_f2 = np.array(feature2)

labels = train.iloc[:, 1024:1025]

encoder = LabelEncoder()
encoder.fit(labels)
labels = encoder.transform(labels)
labels = to_categorical(labels)

train_y = labels

######################
## Validation ##
######################

val = pd.read_csv("Merged_Val_OG.csv")

print(val.shape)
val = val.sample(frac=1)

feature1_val = val.iloc[:, 0:512]
feature2_val = val.iloc[:, 512:1024]

print(feature1_val.shape, feature2_val.shape)

val_x_f1 = np.array(feature1_val)
val_x_f2 = np.array(feature2_val)

labels_val = val.iloc[:, 1024:1025]

encoder = LabelEncoder()
encoder.fit(labels_val)
labels_val = encoder.transform(labels_val)
labels_val = to_categorical(labels_val)

val_y = labels_val

print("Training Model TALOS Merge \n\n")

input1 = Input(shape=(None, 512))
inner = Conv1D(128, 1, padding='same', name='conv1',
               kernel_initializer='he_normal')(input1)
inner = BatchNormalization()(inner)
inner = Dropout(0.5)(inner)
inner = Activation('relu')(inner)
inner1 = MaxPooling1D(pool_size=1, name='max1')(inner)

inner = Conv1D(128, 1, padding='same', name='conv1',
               kernel_initializer='he_normal')(inner1)
inner = BatchNormalization()(inner)
inner = Dropout(0.5)(inner)
inner = Activation('relu')(inner)
inner1 = MaxPooling1D(pool_size=1, name='max1')(inner)

inner = Conv1D(512, 1, padding='same', name='conv1',
               kernel_initializer='he_normal')(inner1)
inner = BatchNormalization()(inner)
inner = Dropout(0.5)(inner)
inner = Activation('relu')(inner)
inner1 = MaxPooling1D(pool_size=1, name='max1')(inner)

inner = Conv1D(512, 1, padding='same', name='conv1',
               kernel_initializer='he_normal')(inner1)
inner = BatchNormalization()(inner)
inner = Dropout(0.5)(inner)
inner = Activation('relu')(inner)
inner1 = MaxPooling1D(pool_size=1, name='max1')(inner)

inner = Conv1D(768, 1, padding='same', name='conv1',
               kernel_initializer='he_normal')(inner1)
inner = BatchNormalization()(inner)
inner = Dropout(0.5)(inner)
inner = Activation('relu')(inner)
inner1 = MaxPooling1D(pool_size=1, name='max1')(inner)

input2 = Input(shape=(None, 512))
inner2 = Conv1D(128, 1, padding='same', name='conv1',
                kernel_initializer='he_normal')(input2)
inner2 = BatchNormalization()(inner2)
inner2 = Dropout(0.5)(inner2)
inner2 = Activation('relu')(inner2)
inner2 = MaxPooling1D(pool_size=1, name='max1')(inner2)

inner2 = Conv1D(128, 1, padding='same', name='conv1',
                kernel_initializer='he_normal')(inner2)
inner2 = BatchNormalization()(inner2)
inner2 = Dropout(0.5)(inner2)
inner2 = Activation('relu')(inner2)
inner2 = MaxPooling1D(pool_size=1, name='max1')(inner2)

inner2 = Conv1D(512, 1, padding='same', name='conv1',
                kernel_initializer='he_normal')(inner2)
inner2 = BatchNormalization()(inner2)
inner2 = Dropout(0.5)(inner2)
inner2 = Activation('relu')(inner2)
inner2 = MaxPooling1D(pool_size=1, name='max1')(inner2)

inner2 = Conv1D(512, 1, padding='same', name='conv1',
                kernel_initializer='he_normal')(inner2)
inner2 = BatchNormalization()(inner2)
inner2 = Dropout(0.5)(inner2)
inner2 = Activation('relu')(inner2)
inner2 = MaxPooling1D(pool_size=1, name='max1')(inner2)

inner2 = Conv1D(768, 1, padding='same', name='conv1',
                kernel_initializer='he_normal')(inner2)
inner2 = BatchNormalization()(inner2)
inner2 = Dropout(0.5)(inner2)
inner2 = Activation('relu')(inner2)
inner2 = MaxPooling1D(pool_size=1, name='max1')(inner2)

x = concatenate([input1, input2])

x = Dense(1024, activation='relu')(x)
x = BatchNormalization()(x)
x = Dropout(0.5)(x)
x = Dense(1024, activation='relu')(x)
x = BatchNormalization()(x)
x = Dropout(0.5)(x)
x = Dense(1024, activation='relu')(x)

x = Dense(3, activation='softmax')(x)

model = Model(inputs=[input1, input2], outputs=x)
model.compile(loss='binary_crossentropy',
              optimizer='adam',  metrics=['accuracy'])

train_x_f1 = np.array(train_x_f1).reshape(
    (train_x_f1.shape[0], 1, train_x_f1.shape[1]))
train_x_f2 = np.array(train_x_f2).reshape(
    (train_x_f2.shape[0], 1, train_x_f2.shape[1]))
train_y = np.array(train_y).reshape((train_y.shape[0], 1, train_y.shape[1]))
val_x_f1 = np.array(val_x_f1).reshape(
    (val_x_f1.shape[0], 1, val_x_f1.shape[1]))
val_x_f2 = np.array(val_x_f2).reshape(
    (val_x_f2.shape[0], 1, val_x_f2.shape[1]))
val_y = np.array(val_y).reshape((val_y.shape[0], 1, val_y.shape[1]))

history = model.fit([train_x_f1, train_x_f2], train_y,
                    epochs=5, shuffle=True, validation_data=([val_x_f1, val_x_f2], val_y))

print("Model Trained \n\n")

model.save("TV_Model")

print("Model Saved \n\n")