# -*- coding: utf-8 -*-
"""
Created on Fri Jun 14 16:22:58 2019

@author: ahmed
"""

import numpy as np

lamda = 1;

def featureMappping(X1,X2,degree):
    output_feature_vec = np.ones(len(X1))[:,None]
    for i in range(1,7):
        for j in range(i+1):
            new_feature = np.array(X1**(i-j)*X2**j)[:,None]
            output_feature_vec = np.hstack((output_feature_vec,new_feature))
    return output_feature_vec

def sigmoid(X):
    X = 1/(1+np.exp(-X))
    return X

def CostFunm(theta,x,y,reg_param):
    m,n = x.shape
    theta = np.reshape(theta,(n,1))
    y = np.reshape(y,(m,1))
    h = sigmoid(np.dot(x,theta))
    term1 = np.log(h)
    term2 = np.log(1-h)
    term1 = np.reshape(term1,(m,1))
    term2 = np.reshape(term2,(m,1))
    term = y * term1 + (1-y) * term2
    J = -(1/m) * np.sum(term)
    J += (reg_param/(2*m))*np.sum(theta**2)
    return J

def Gradient(theta,x,y,reg_param):
    m,n = x.shape
    theta = np.reshape(theta,(n,1))
    y = np.reshape(y,(m,1))
    h = sigmoid(np.dot(x,theta))
    grad = (1/m)*np.sum(((h-y)*x),axis=0)
    grad = grad[:,None] + (reg_param/m)*theta

    return grad.flatten()  # flatten is very important !!!!!


from sklearn.cluster import DBSCAN
from scipy.cluster import hierarchy

import numpy as np
import random

from bilayer_clusters import euclideanDist

def dbscan_wrapper(arr,L,cutoff):
    edm = euclideanDist.edm(L,arr)
    db = DBSCAN(eps=cutoff, min_samples=2, metric='precomputed', n_jobs=-1)
    #db.fit(edm)
    #labels = db.labels_
    labels = db.fit_predict(edm)

    return labels

def hierarchy_wrapper(arr,L,cutoff):
    edm = euclideanDist.edm(L,arr)
    y = edm[np.triu_indices(edm.shape[0],1)]
    link = hierarchy.linkage(y, method='single')
    cut = hierarchy.cut_tree(link,height=cutoff)
    cut = [y for x in cut for y in x]

    return np.asarray(cut)

def cluster_sizes(labels):
    unique, counts = np.unique(labels, return_counts=True)
    return dict(zip(unique, counts))

def means(hsh):
    singletons = hsh.pop(-1,0.0)
    number_clusters = singletons + len(hsh)

    lst = np.asarray(list(hsh.values()))

    sum_squared = singletons + sum(lst**2)
    sum_cluster = sum(lst) + singletons

    mean = float(sum_cluster)/number_clusters
    mS = float(sum_squared)/sum_cluster

    return mean,mS

def mean_cluster_size(arr,L,cutoff,alg=dbscan_wrapper):
    labels = alg(arr,L,cutoff)
    hsh = cluster_sizes(labels)
    return means(hsh)

def meanRandom(originalArr,L,cutoff,size,iter=10 ,alg=dbscan_wrapper):
    lst = []

    for i in range(iter):
        cluster = randomCluster(size,originalArr)
        lst.append(mean_cluster_size(cluster,L,cutoff))

    lst=list(zip(*lst))

    mean=sum(lst[0])/iter
    mS=sum(lst[1])/iter

    return mean,mS

def normSize(arr,L,cutoff,originalArr,alg=dbscan_wrapper):
    #numerator
    nmean,nmS = mean_cluster_size(arr,L,cutoff)
    #print(nmean,nmS)
    #denominator
    size = len(arr)
    dmean,dmS = meanRandom(originalArr,L,cutoff,size)

    return (nmean/dmean,nmS/dmS)

def randomCluster(siz,arr):
    Nparticles = len(arr)
    idx = np.asarray(random.sample(list(range(Nparticles)),siz))

    cluster = arr[idx,:]

    return cluster


import point
import maille
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import proj3d
import numpy as np

class espace:
    """
    Cette classe permet de définir l'ensemble des points de l'espace
    """
    def __init__(self):
        self.points= []

    def init_points(self,data : list,mode=False):
        """
        A l'aide du jeu de données on place les points
        """
        for i in range(len(data)):
            p = point.point()
            if(mode):
                p.set_xyz(data[i])
            else:
                p.set_angle_dist(data[i])
            self.points.append(p)

    def afficher(self):
        """
        Permet d'afficher à l'aide de matplotlib les points en 3D
        """
        plt.figure(figsize=(100,100))
        axes = plt.axes(projection="3d")

        for i in self.points :
            axes.scatter(i.x,i.y,i.z)

        plt.show()

    def return_xyz(self):
        """
        Retourne le nuage de points au format np.array([np.array([x,y,z]),...])
        afin d'être compatible avec la fonction mesh
        """
        array = np.empty((len(self.points),3))
        for i in range(len(self.points)) :
            array[i][0] = self.points[i].x
            array[i][1] = self.points[i].y
            array[i][2] = self.points[i].z
        return array


import numpy as np

def pressure(dom, s, rho):
    row = np.size(dom, 0)
    col = np.size(dom, 1)

    p = np.zeros((row, col))
    p[:] = np.nan

    g = 9.81
    c = 0
    s = np.square(s)

    for i in range(0, row - 1):
        for j in range(0, col - 1):
            if dom[i, j] != 0:
                p[i, j] = rho * g * (c - (s[i, j] / (2 * g)))
    return p


import eml_toolbox as eml;
import numpy as np
from skimage import filters
import cv2;
import glob;
from matplotlib import pyplot as plt;
from IPython import get_ipython
_ipython = get_ipython();

#%% first close everything:
plt.close("all");

#%% set parameters:
# parameters for performance comparison:
nruns = 3; # number of runs
nloops = 25; # number of loops per run

# define search string to find images:
folder_search_str = "demo_images/*.tif*"
# define image no. in folder to load:
image_no = 6
# define kernel size for filters:
kernel_size = 3;

#%% get content of directory:
image_list = glob.glob(folder_search_str);
image_file = image_list[image_no-1];

#%% Some first output:
print("Processing image: %s\n" % image_file)

#%% load image:
image_data = cv2.imread(image_file,cv2.IMREAD_GRAYSCALE);

# create int16 and float arrays to test impact on filter performance:
image_data_int16 = image_data.astype(np.int16);
image_data_float32 = image_data.astype(np.float32);

# show how much time is consumed by converting array to int16 or float32.
# NOTE: float16 is not supported by cv2!
print("astype(int16): ", end=""); _ipython.magic("timeit -n %i -r %i image_data.astype(np.int16)" % (nloops, nruns));
print("astype(float32): ", end=""); _ipython.magic("timeit -n %i -r %i image_data.astype(np.float32)" % (nloops, nruns));
print("")

# test whether surface-tension image or density image:
check_invert = eml.ed.check_image_invert(image_data)
if(check_invert):
    image_data = eml.ed.invert_image(image_data); # faster than np.invert()!!!

#%% create short lambda functions:
edge_sobel = lambda image_data, kernel_size=-1: eml.ed.filter_sobel(image_data, kernel_size=-1)
edge_laplacian = lambda image_data: eml.ed.filter_laplacian(image_data, kernel_size)
edge_kirsch = lambda image_data: eml.ed.filter_kirsch(image_data)
edge_canny = lambda image_data: cv2.Canny(image_data, 0, 40, L2gradient=True)
edge_sobel_sk = lambda image_data: filters.sobel(image_data);
edge_scharr_sk = lambda image_data: filters.scharr(image_data);
edge_farid_sk = lambda image_data: filters.farid(image_data);

#%% compare performance of different filter routines:
print("sobel (uint8): ", end=""); _ipython.magic("timeit -n %i -r %i edge_sobel(image_data)" % (nloops, nruns));
print("sobel (int16): ", end=""); _ipython.magic("timeit -n %i -r %i edge_sobel(image_data_int16)" % (nloops, nruns));
print("sobel (float32): ", end=""); _ipython.magic("timeit -n %i -r %i edge_sobel(image_data_float32)" % (nloops, nruns));
print("")
print("laplacian (uint8): ", end=""); _ipython.magic("timeit -n %i -r %i edge_laplacian(image_data)" % (nloops, nruns));
print("laplacian (float32): ", end=""); _ipython.magic("timeit -n %i -r %i edge_laplacian(image_data_float32)" % (nloops, nruns));
print("")
print("kirsch (uint8): ", end=""); _ipython.magic("timeit -n %i -r %i edge_kirsch(image_data)" % (nloops, nruns));
print("kirsch (int16): ", end=""); _ipython.magic("timeit -n %i -r %i edge_kirsch(image_data_int16)" % (nloops, nruns));
print("kirsch (float32): ", end=""); _ipython.magic("timeit -n %i -r %i edge_kirsch(image_data_float32)" % (nloops, nruns));
print("")
print("canny: ", end=""); _ipython.magic("timeit -n %i -r %i edge_canny(image_data)" % (nloops, nruns));
print("")
print("skimage sobel (int16) ", end=""); _ipython.magic("timeit -n %i -r %i edge_sobel_sk(image_data_int16)" % (nloops, nruns));
print("skimage sobel (float32): ", end=""); _ipython.magic("timeit -n %i -r %i edge_sobel_sk(image_data_float32)" % (nloops, nruns));
print("skimage sobel: ", end=""); _ipython.magic("timeit -n %i -r %i edge_sobel_sk(image_data)" % (nloops, nruns));
print("")
print("skimage scharr (float32): ", end=""); _ipython.magic("timeit -n %i -r %i edge_scharr_sk(image_data_float32)" % (nloops, nruns));
print("skimage scharr: ", end=""); _ipython.magic("timeit -n %i -r %i edge_scharr_sk(image_data)" % (nloops, nruns));
print("")
print("skimage farid (float32): ", end=""); _ipython.magic("timeit -n %i -r %i edge_farid_sk(image_data_float32)" % (nloops, nruns));
print("skimage farid: ", end=""); _ipython.magic("timeit -n %i -r %i edge_farid_sk(image_data)" % (nloops, nruns));

#%% compare visually:
plt.figure();
plt.subplot(2,1,1);
plt.imshow(image_data, cmap="gray");

# Sobel:
plt.subplot(2,7,8);
plt.imshow(edge_sobel((image_data_int16)), cmap="gray");
plt.title("Sobel");

# Laplacian:
plt.subplot(2,7,9);
plt.imshow(np.abs(edge_laplacian(image_data_int16)), cmap="gray");
plt.title("Laplacian");

# Kirsch:
plt.subplot(2,7,10);
plt.imshow(edge_kirsch(image_data_int16), cmap="gray");
plt.title("Kirsch");

# Canny:
plt.subplot(2,7,11);
plt.imshow(edge_canny(image_data), cmap="gray");
plt.title("Canny");

# Sobel skimage:
plt.subplot(2,7,12);
plt.imshow(edge_sobel_sk(image_data), cmap="gray");
plt.title("Sobel (Skimage)");

# Scharr skimage:
plt.subplot(2,7,13);
plt.imshow(edge_scharr_sk(image_data), cmap="gray");
plt.title("Scharr (Skimage)");

# Farid skimage:
plt.subplot(2,7,14);
plt.imshow(edge_farid_sk(image_data), cmap="gray");
plt.title("Farid (Skimage)");

#%% show plots (if not run within ipython console)
plt.show()


from logging import ERROR
import os
from flask import Flask, request, jsonify, abort
from sqlalchemy import exc
import json
from flask_cors import CORS

from .database.models import db_drop_and_create_all, setup_db, Drink
from .auth.auth import AuthError, requires_auth

app = Flask(__name__)
setup_db(app)
CORS(app)

'''
@TODO uncomment the following line to initialize the datbase
!! NOTE THIS WILL DROP ALL RECORDS AND START YOUR DB FROM SCRATCH
!! NOTE THIS MUST BE UNCOMMENTED ON FIRST RUN
!! Running this funciton will add one
'''
db_drop_and_create_all()

# ROUTES
'''
    Endpoint GET /drinks
'''

@app.route('/drinks', methods={'GET'})
def retrieve_drinks():
    try:
        drinks = Drink.query.order_by(Drink.id).all()
        drinks_short = [drink.short() for drink in drinks]

        results = {
            'success': True,
            'drinks': drinks_short
        }
    except Exception as e:
        print('ERROR', str(e))
        abort(422)

    return jsonify(results)

'''
    Endpoint GET /drinks-detail
'''

@app.route('/drinks-detail', methods={'GET'})
@requires_auth('get:drinks-detail')
def retrieve_drink_detail(payload):
    try:
        drinks = Drink.query.order_by(Drink.id).all()
        drinks_long = [drink.long() for drink in drinks]

        results = {
            'success': True,
            'drinks': drinks_long
        }
    except Exception as e:
        print('ERROR', str(e))
        abort(422)

    return jsonify(results)

'''
    Endpoint POST /drinks
'''

@app.route('/drinks', methods={'POST'})
@requires_auth('post:drinks')
def create_drink(payload):
    try:
        body = request.get_json()
        if 'title' in body and 'recipe' in body:
            new_title = body.get('title')
            new_recipe = body.get('recipe')
        else:
            abort(400)

        drink_check = (
            Drink.query
            .filter(Drink.title == new_title)
            .one_or_none()
        )

        if drink_check:
            raise AuthError({
                'code': 'invalid_title',
                'description': 'Drink title is already in use'
            }, 422)
        else:
            drink = Drink(
                title=new_title,
                recipe=json.dumps([new_recipe])
                )

            drink.insert()

            results = {
                'success': True,
                'drinks': [drink.long()]
            }
    except Exception as e:
        print('ERROR', str(e))
        abort(422)

    return jsonify(results)

'''
    Endpoint PATCH /drinks/<drink_id>
        <drink_id> is the existing Drink id
'''

@app.route('/drinks/<drink_id>', methods={'PATCH'})
@requires_auth('patch:drinks')
def update_drink(payload, drink_id):
    try:
        drink = (
            Drink.query
            .filter(Drink.id == drink_id)
            .one_or_none()
        )
        # ID not found
        if drink is None:
            abort(404)

        # Update Drink
        body = request.get_json()
        if 'title' in body:
            drink.title = body.get('title')
        if 'recipe' in body:
            drink.recipe = json.dumps([body.get('recipe')])

        drink.update()

        results = {
            'success': True,
            'drinks': [drink.long()]
        }

    except Exception as e:
        print('ERROR', str(e))
        abort(422)

    return jsonify(results)

'''
    Endpoint DELETE /drinks/<drink_id>
        <drink_id> is the existing Drink id
'''

@app.route('/drinks/<drink_id>', methods={'DELETE'})
@requires_auth('delete:drinks')
def delete_drink(payload, drink_id):
    try:
        drink = Drink.query.filter(Drink.id == drink_id).one_or_none()
        # ID not found
        if drink is None:
            abort(404)
        # Delete ID
        drink.delete()
        results = {
            'success': True,
            'delete': drink_id
        }
    except Exception as e:
        print('ERROR', str(e))
        abort(422)

    return jsonify(results)

'''
Error handling for unprocessable entity
'''

@app.errorhandler(400)
def bad_request(error):
    return jsonify({
        "success": False,
        "error": 400,
        "message": "bad request"
    }), 400

@app.errorhandler(401)
def unauthorized(error):
    return jsonify({
        "success": False,
        "error": 401,
        "message": "unauthorized"
    }), 401

@app.errorhandler(403)
def forbidden(error):
    return jsonify({
        "success": False,
        "error": 403,
        "message": "forbidden"
    }), 403

@app.errorhandler(404)
def not_found(error):
    return jsonify({
        "success": False,
        "error": 404,
        "message": "resource not found"
    }), 404

@app.errorhandler(422)
def unprocessable(error):
    return jsonify({
        "success": False,
        "error": 422,
        "message": "unprocessable"
    }), 422

@app.errorhandler(500)
def server_error(error):
    return jsonify({
        "success": False,
        "error": 500,
        "message": "internal server error"
    }), 500

@app.errorhandler(AuthError)
def server_error(error):
    return jsonify({
        "success": False,
        "error": error.status_code,
        "message": error.description
    }), error.status_code


import sys
sys.path.insert(0, '/home/fernando/Dropbox/UC/Magister/robot-flautista')
import threading
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5 import QtCore
import pyqtgraph as pg
import lib.ethernet_ip.ethernetip as ethernetip

from utils.cinematica import *
from utils.motor_route import *
from exercises.drivers_connect import AMCIDriver, INPUT_FUNCTION_BITS, VirtualAxis, Musician
#from view_control.plot_window import Window as PlotWindow
from views.simple_plot_window import Ui_MainWindow as PlotWindowView
from pyqtgraph.Qt import QtGui

import matplotlib.pyplot as plt
from time import time
from datetime import datetime
import pandas as pd

class Window(QMainWindow, PlotWindowView):
    def __init__(self, app, running, data, t0, x_reference, z_reference, alpha_reference, x_data, z_data, alpha_data, interval=10, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        self.interval = interval
        self.parent = parent
        self.running = running
        self.x_reference = x_reference
        self.z_reference = z_reference
        self.alpha_reference = alpha_reference
        self.x_data = x_data
        self.z_data = z_data
        self.alpha_data = alpha_data
        #self.start_event = start_event
        self.app = app
        self.data = data
        self.curves = [self.graphicsView.plot(pen=pg.mkPen('b', width=1)),
                       self.graphicsView.plot(pen=pg.mkPen('r', width=1, style=QtCore.Qt.DashLine)),
                       self.graphicsView.plot(pen=pg.mkPen('g', width=1)),
                       self.graphicsView.plot(pen=pg.mkPen('w', width=1, style=QtCore.Qt.DashLine)),
                       self.graphicsView.plot(pen=pg.mkPen('c', width=1)),
                       self.graphicsView.plot(pen=pg.mkPen('y', width=1, style=QtCore.Qt.DashLine))]

        #self.x_reference.finish_score_signal.connect(self.stop_action)
        self.startButton.clicked.connect(self.start_action)
        self.stopButton.clicked.connect(self.stop_action)
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(self.interval)
        self.plot_choise = 0
        self.xButton.toggled.connect(self.plot_x)
        self.zButton.toggled.connect(self.plot_z)
        self.alphaButton.toggled.connect(self.plot_alpha)
        self.recordCheckBox.toggled.connect(self.change_record_data)
        self.record_data = False
        self.t0 = t0
        self.t = 0

    def closeEvent(self, a0: QtGui.QCloseEvent):
        '''
        Esta función se ejecuta al cerrar el programa, para terminar todos los threads que están corriendo
        '''
        self.running.clear()
        return super().closeEvent(a0)

    def change_record_data(self, value):
        self.record_data = value

    def plot_x(self, value):
        if value:
            self.plot_choise = 0
        else:
            self.curves[0].setData([], [])
            self.curves[1].setData([], [])

    def plot_z(self, value):
        if value:
            self.plot_choise = 1
        else:
            self.curves[2].setData([], [])
            self.curves[3].setData([], [])

    def plot_alpha(self, value):
        if value:
            self.plot_choise = 2
        else:
            self.curves[4].setData([], [])
            self.curves[5].setData([], [])

    def start_action(self):
        t = time() - self.t0
        self.data.start_saving()
        x = []
        z = []
        alpha = []
        for i in range(len(self.x_data)):
            x.append([self.x_data[i][0] + t, self.x_data[i][1], self.x_data[i][2]])
            z.append([self.z_data[i][0] + t, self.z_data[i][1], self.z_data[i][2]])
            alpha.append([self.alpha_data[i][0] + t, self.alpha_data[i][1], self.alpha_data[i][2]])
        #print(x)
        self.x_reference.merge_ref(x)
        self.z_reference.merge_ref(z)
        self.alpha_reference.merge_ref(alpha)

    def stop_action(self):
        #if self.start_event.is_set():
        filename = "/home/fernando/Dropbox/UC/Magister/robot-flautista/exercises/data/" + datetime.now().strftime("%d-%m-%Y_%H:%M:%S") + ".csv"
        self.data.finish_saving(filename)
        #self.start_event.clear()

    def update(self):
        if self.plot_choise == 0:
            self.curves[0].setData(self.data.times, self.data.x)
            self.curves[1].setData(self.data.times, self.data.x_ref)
        elif self.plot_choise == 1:
            self.curves[2].setData(self.data.times, self.data.z)
            self.curves[3].setData(self.data.times, self.data.z_ref)
        elif self.plot_choise == 2:
            self.curves[4].setData(self.data.times, self.data.alpha)
            self.curves[5].setData(self.data.times, self.data.alpha_ref)

        self.app.processEvents()

class SimpleRecorder:
    """
    Esta clase se encarga de almacenar la historia de las variables medidas. windowWidth dice la cantidad de datos a almacenar e interval el tiempo (en milisegundos) para obtener una muestra.
    """
    def __init__(self, x_driver, z_driver, alpha_driver, x_reference, z_reference, alpha_reference, windowWidth=200, interval=10):
        self.saving = False
        self.x_driver = x_driver
        self.z_driver = z_driver
        self.alpha_driver = alpha_driver
        self.x_reference = x_reference
        self.z_reference = z_reference
        self.alpha_reference = alpha_reference
        self.windowWidth = windowWidth
        self.ref_state = 0
        self.real_state = 0

        self.ref_state_x = x_units_to_mm(self.x_reference.pos)
        self.real_state_x = x_units_to_mm(self.x_driver.motor_position)
        self.ref_state_z = z_units_to_mm(self.z_reference.pos)
        self.real_state_z = z_units_to_mm(self.z_driver.motor_position)
        self.ref_state_alpha = alpha_units_to_angle(self.alpha_reference.pos)
        self.real_state_alpha = alpha_units_to_angle(self.alpha_driver.motor_position)

        self.x_ref = linspace(0,0,self.windowWidth)
        self.x = linspace(0,0,self.windowWidth)
        self.z_ref = linspace(0,0,self.windowWidth)
        self.z = linspace(0,0,self.windowWidth)
        self.alpha_ref = linspace(0,0,self.windowWidth)
        self.alpha = linspace(0,0,self.windowWidth)

        self.times = linspace(0,0,self.windowWidth)

        self.t0 = time()
        self.first_entry = False
        self.t1 = 0

        self.data = pd.DataFrame(columns=['time', 'signal', 'value'])

        self.interval = interval
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(interval)

    def start(self):
        self.timer.start(self.interval)

    def update(self):
        self.ref_state_x = x_units_to_mm(self.x_reference.pos)
        self.vel_state_x = self.x_reference.vel
        self.real_state_x = x_units_to_mm(self.x_driver.motor_position)
        self.ref_state_z = z_units_to_mm(self.z_reference.pos)
        self.vel_state_z = self.z_reference.vel
        self.real_state_z = z_units_to_mm(self.z_driver.motor_position)
        self.ref_state_alpha = alpha_units_to_angle(self.alpha_reference.pos)
        self.vel_state_alpha = self.alpha_reference.vel
        self.real_state_alpha = alpha_units_to_angle(self.alpha_driver.motor_position)

        self.x_ref[:-1] = self.x_ref[1:]                      # shift data in the temporal mean 1 sample left
        self.x_ref[-1] = self.ref_state_x
        self.x[:-1] = self.x[1:]                      # shift data in the temporal mean 1 sample left
        self.x[-1] = self.real_state_x

        self.z_ref[:-1] = self.z_ref[1:]                      # shift data in the temporal mean 1 sample left
        self.z_ref[-1] = self.ref_state_z
        self.z[:-1] = self.z[1:]                      # shift data in the temporal mean 1 sample left
        self.z[-1] = self.real_state_z

        self.alpha_ref[:-1] = self.alpha_ref[1:]                      # shift data in the temporal mean 1 sample left
        self.alpha_ref[-1] = self.ref_state_alpha
        self.alpha[:-1] = self.alpha[1:]                      # shift data in the temporal mean 1 sample left
        self.alpha[-1] = self.real_state_alpha

        self.times[:-1] = self.times[1:]                      # shift data in the temporal mean 1 sample left
        self.times[-1] = time() - self.t0

        if self.saving:
            if self.first_entry:
                self.t1 = self.times[-1]
                self.first_entry = False
            t = self.times[-1] - self.t1
            new_data = pd.DataFrame({'time': [t, t, t, t, t, t, t, t, t], 'signal':['x_ref', 'x', 'z_ref', 'z', 'alpha_ref', 'alpha', 'vel_ref_x', 'vel_ref_z', 'vel_ref_alpha'], 'value': [self.x_ref[-1], self.x[-1], self.z_ref[-1], self.z[-1], self.alpha_ref[-1], self.alpha[-1], self.vel_state_x, self.vel_state_z, self.vel_state_alpha]})
            self.data = self.data.append(new_data, ignore_index = True)

    def start_saving(self):
        self.first_entry = True
        self.data = pd.DataFrame(columns=['time', 'signal', 'value'])
        self.saving = True

    def pause_saving(self):
        self.saving = False

    def resume_saving(self):
        self.saving = True

    def finish_saving(self, file_name):
        self.saving = False
        self.data.to_csv(file_name)

path = "/home/fernando/Dropbox/UC/Magister/robot-flautista/exercises/bumblebee_ejercicio.json"
route = get_route_complete(path, go_back=False)
# for i in range(len(route['x'])):
#     route['x'][i] = x_units_to_mm(route['x'][i])

x = []
z = []
alpha = []
for i in range(len(route['t'])):
    x.append([route['t'][i], route['x'][i], route['x_vel'][i]])
    z.append([route['t'][i], route['z'][i], route['z_vel'][i]])
    alpha.append([route['t'][i], route['alpha'][i], route['alpha_vel'][i]])

# plt.plot(route['t'], route['x_vel'])
# plt.plot(route['t'], route['x'])
# plt.ylabel('X ref')
# plt.xlabel('Time')
# plt.show()

connected = True
# running = threading.Event()
# running.set()
t0 = time()

host = "192.168.2.10"
connections = ["192.168.2.102", "192.168.2.104", "192.168.2.103", "192.168.2.101", "192.168.2.100"]
EIP = ethernetip.EtherNetIP(host)

interval = 0.01

# x_virtual_axis = VirtualAxis(running, interval, t0, verbose=False)
# z_virtual_axis = VirtualAxis(running, interval, t0, verbose=False)
# alpha_virtual_axis = VirtualAxis(running, interval, t0, verbose=False)
# x_virtual_axis.start()
# z_virtual_axis.start()
# alpha_virtual_axis.start()
# #virtual_flow = VirtualFlow(running, interval, t0, verbose=False)

# x_driver = AMCIDriver(EIP, connections[0], running, x_virtual_axis, connected=True, starting_speed=1, verbose=False, input_1_function_bits=INPUT_FUNCTION_BITS['CCW Limit'], virtual_axis_follow_acceleration=50, virtual_axis_follow_deceleration=50, home=True)
# z_driver = AMCIDriver(EIP, connections[1], running, z_virtual_axis, connected=True, starting_speed=1, verbose=False, input_1_function_bits=INPUT_FUNCTION_BITS['CCW Limit'], virtual_axis_follow_acceleration=50, virtual_axis_follow_deceleration=50, home=False)
# alpha_driver = AMCIDriver(EIP, connections[2], running, alpha_virtual_axis, connected=True, starting_speed=1, verbose=False, motors_step_turn=10000, virtual_axis_follow_acceleration=500, virtual_axis_follow_deceleration=500, home=False)
# x_driver.start()
# z_driver.start()
# alpha_driver.start()

host = "192.168.2.10"
connections = ["192.168.2.102", "192.168.2.104", "192.168.2.103", "192.168.2.101", "192.168.2.100"]
event = threading.Event()
event.set()

t0 = time()
pierre = Musician(host, connections, event, home=False, x_connect=True, z_connect=True, alpha_connect=True, fingers_connect=False)
pierre.start()

recorder = SimpleRecorder(pierre.x_driver, pierre.z_driver, pierre.alpha_driver, pierre.x_virtual_axis, pierre.z_virtual_axis, pierre.alpha_virtual_axis, windowWidth=200, interval=10)

app = QApplication(sys.argv)
plotwin = Window(app, event, recorder, t0, pierre.x_virtual_axis, pierre.z_virtual_axis, pierre.alpha_virtual_axis, x, z, alpha, interval=10)
plotwin.show()
recorder.start()

sys.exit(app.exec())


def choose_f():
    print('-----')
    return input('Выберите действие:\n1.Сохранить\n2.Получить\n')

def choose_amount():
    print('-----')
    return input('Выберите действие:\n1.Найти\n2.Получить всех\n')

def show_list(list):
    print('-----')
    i = 0
    while i < len(list):
        row = ''.join(list[i])
        print(row, end='')
        i += 1

def input_surname():
    print('-----')
    return input('Введите фамилию:\n')

def show_one(list):
    print('-----')
    i = 0
    row = ''
    if list == None:
        print('Не существует')
    else:
        while i < len(list):
            row += list[i]
            i += 1
        print('\n' + row)

def input_info():
    print('-----')
    info = ''
    name = input('Введите имя:\n')
    surname = input('Введите фамилию:\n')
    phone_number = input('Введите номер:\n')
    description = input('Добавьте описание:\n')

    info = name + ' /' + surname + ' /' + phone_number + ' /' + description + '\n'

    return info


import time
import asyncio
from unittest.mock import Mock
import pytest
from azure.cognitiveservices.inkrecognizer.aio import InkRecognizerClient

RAISE_ONLINE_TEST_ERRORS = False
URL = ""
CREDENTIAL = Mock(name="FakeCredential", get_token="token")

def online_test(func):
    def wrapper(*args, **kw):
        if URL == "" or isinstance(CREDENTIAL, Mock):
            if RAISE_ONLINE_TEST_ERRORS:
                raise ValueError("Please fill URL and CREDENTIAL before running online tests.")
            else:
                return
        return func(*args, **kw)
    return wrapper

class TestSendRequests:
    @online_test
    @pytest.mark.asyncio
    async def test_recognize_ink_async(self):
        point = Mock(x=0, y=0)
        stroke = Mock(id=0, points=[point], language="python")
        ink_stroke_list = [stroke] * 3
        client = InkRecognizerClient(URL, CREDENTIAL)
        root = await client.recognize_ink(ink_stroke_list)
        assert root is not None


import eel
from typing import List, Tuple
import subprocess
import os
import platform
import sys

import keyboard
import pyautogui
import pystray
from PIL import Image

from searcher import FileSearchEngine
from utils import sortByFolder
import time
import json

# Type defs
StartSize = Tuple[int, int]
StartPos = Tuple[int, int]
SearchFileRet = List[dict]

class SearchApp:
    def __init__(self, host: str, port: str, start_size: StartSize, start_pos: StartPos, root_dir: str, prod: bool = True, search_timeout=5.0):
        """Initialize the search app

        Args:
            host (str): The ipadress to host the app
            port (str): The port to expose
            start_size (StartSize): The size of the main window when starting up
            start_pos (StartPos): The position on the screen when starting the application
            root_dir (str): The root directory where all searches take place
        """
        self.host = host
        self.port = port
        self.startSize = start_size
        self.startPosition = start_pos
        self.root_dir = root_dir
        self.search_timeout = search_timeout
        self.file_search = FileSearchEngine(root_dir, search_timeout)

        # The hotkey to use when opening from the background
        self.hotkey = 'ctrl+shift+space'
        self.hotkey_callback = None
        # Set environment (prod/dev)
        self.prod = prod
        # Tray icon
        self.icon_name = "FileSearcher"
        self.icon = None
        if self.prod:
            if getattr(sys, 'frozen', False):
                self.icon_image_path = os.path.join(
                    sys._MEIPASS, "web\\build\\icon.png")
            else:
                self.icon_image_path = "web\\build\\icon.png"
            print(self.icon_image_path)
        else:
            self.icon_image_path = "web\\public\\icon.png"
        self.icon_image = None

        # Socket handling
        self.open_sockets = None

        # Initialize the app
        if self.prod:
            eel.init('web\\build', [".js", ".jsx", ".html"])
        else:
            eel.init('web\\src', [".js", ".jsx", ".html"])

    # !-- LIFECYCLE METHODS --!

    def show(self):
        """ Show is triggered when the hotkey is pressed so it unbinds the hotkey and shows"""
        # Removes the tray icon
        if self.icon != None:
            self.icon.stop()
        # Unbind the hotkey to avoid conflicts
        keyboard.remove_hotkey(self.hotkey_callback)
        # Show the app
        if self.prod:
            # In production we show the build page
            eel.show('index.html')
        else:
            # In dev we show the dev server
            eel.show({'port': 3000})

    def start(self) -> None:
        """ Start the app, show the window and create all the important bindings. """
        if not self.prod:
            eel.start({'port': 3000}, host=self.host, port=int(self.port), size=self.startSize,
                      blocking=True, close_callback=lambda p, s: self.close_callback(p, s))
        else:
            #eel.start({"file": 'index.html', 'port': 3000}, host=self.host, port=self.port, size=self.startSize, blocking=True, close_callback=lambda p,s: self.close_callback(p,s))
            eel.start('index.html', host=self.host, port=int(self.port), size=self.startSize,
                      blocking=True, close_callback=lambda p, s: self.close_callback(p, s))

    def start_background_process(self, _) -> None:
        """Starts a background process in which we wait for the hotkey to be pressed.
        Note: This method should only be called from self.create_tray_icon()
        Args:
            _ (None): Is required to be passed as in the callback for the icon but is not used
        """
        # Makes the icon visible
        self.icon.visible = True
        # Creates the hotkey and binds self.show() to the trigger
        self.hotkey_callback = keyboard.add_hotkey(
            self.hotkey, lambda: self.show(), suppress=True)

    def close_callback(self, _, sockets):
        """ Runs the background process when the main window is closed """
        # Save the open sockets so we can correctly close them when needed
        self.open_sockets = sockets
        # Start the tray icon which then start the background process
        self.create_tray_icon()

    def quit(self):
        """ Remove hotkeys and make sure all sockets are closed """
        print("Quitting the application")
        # Wrap it in an extra try except because some libaries suppress
        # some errors and try to keep their loop alive
        try:
            try:
                keyboard.remove_all_hotkeys()
            except AttributeError:
                pass
            print("Hotkeys removed")
            # Stop the filewather from the FileSearchEngine
            self.file_search.stop_watcher()
            print("Watchers stopped")
            self.icon.stop()
            print("Removed the icon")
            if not self.open_sockets:
                print("No open sockets")
                self.kill_program()
            # Wait for the sockets to close
            print("Waiting for sockets")
            time.sleep(1)
            self.kill_program()
        except:
            self.kill_program()

    def kill_program(self):
        """ Stops (kills) this program """
        pid = os.getpid()
        if platform.system() == 'Darwin':
            kill_cmd = f"kill -9 {pid}"
        elif platform.system() == "Windows":
            kill_cmd = f"taskkill /F /PID {pid} /T"
        else:
            kill_cmd = f"kill -9 {pid}"
        os.system(kill_cmd)

    def create_tray_icon(self) -> None:
        """ Creates the tray icon and starts the background processes as soon as the icon is created. """
        # Setup the icon
        self.icon = pystray.Icon(self.icon_name, self.load_icon_img(), title=self.icon_name, menu=pystray.Menu(
            pystray.MenuItem(
                "Open FileSearcher",
                lambda: self.show(),  # Shows the application on click
                default=True  # Default action, so this also gets triggered when clicking on the icon itself
            ),
            pystray.MenuItem(
                "Quit",
                lambda: self.quit()  # Quits the application on click
            )
        ))
        # Run the icon and start the background process
        self.icon.run(self.start_background_process)

    # !-- SETTINGS --!

    def update_search_engine(self):
        """ Updates the search engine settings
            Note: it creates a new search engine
        """
        self.file_search = FileSearchEngine(self.root_dir, self.search_timeout)

    def save_settings(self, file_name='settings.json', settings={}) -> None:
        """Save the settings to a file

        Args:
            file_name (str, optional): The file to save the settings to. Defaults to 'settings.json'.
            settings (dict, optional): The settings to save. Defaults to the result of get_settings().
        """
        if len(settings) < 1:
            settings = self.get_settings()
        with open(file_name, 'w') as f:
            json.dump(settings, f)

    @staticmethod
    def load_settings(file_name="settings.json") -> dict:
        """Loads the settings from file_name

        Args:
            file_name (str, optional): The filename pointing to the settings file. Defaults to "settings.json".

        Returns:
            dict: The settings is a dictionary
        """
        if os.path.isfile(file_name):
            with open(file_name, 'r') as f:
                settings = json.load(f)
            return settings

        return {}

    # !-- HELPER METHODS --!

    def load_icon_img(self) -> Image:
        """ Load image loads the icon image into self.icon_image """
        # Check if the given path is actually a file and then load the image
        if os.path.isfile(self.icon_image_path):
            self.icon_image = Image.open(self.icon_image_path)
        return self.icon_image

    # !-- EEL EXPOSED METHODS --!

    @staticmethod
    @eel.expose("search_file")
    def search_file(search_query: str) -> List[dict]:
        """Search file is exposed to the interface and uses FileSearchEngine to search for the given query

        Args:
            search_query (str): The query to search for
        Returns:
            List[dict]: The search results
        """

        # This is a bit hacky, but the method has to be a static method because the javascript
        # does not have access to the class
        # This is if the self.file_search changes for example when the root_dir is changed, we can
        # still access the correct variable
        return sortByFolder(app.file_search.simple_search(search_query, ret_dic=True))

    @staticmethod
    @eel.expose("open_file")
    def open_file(path: str) -> None:
        """open_file is exposed to the interface and opens the file or folder specified in the path argument in the associated application

        Args:
            path (str): The path to the file/folder to open
        """
        # Check which operating system the user uses, because both methods do not work on the other os.
        if platform.system() == 'Darwin':
            # If on mac use the mac open terminal command
            subprocess.call(('open', path))
        elif platform.system() == 'Windows':
            # On windows we can use os.startfile
            os.startfile(path)
        else:
            # Use the linux equivalent of open command
            subprocess.call(('xdg-open', path))

    @staticmethod
    @eel.expose("get_settings")
    def get_settings() -> object:
        """get settings returns the settings of the current app

        Returns:
            Object: Containing the settings.
        """
        settings = {
            "hotkey": app.hotkey,
            "root_dir": app.root_dir,
            "search_timeout": app.search_timeout
        }
        return settings

    @staticmethod
    @eel.expose("update_settings")
    def update_settings(settings: dict) -> str:
        """Save settings saves the settings and calls for a search engine update because it's values may have changed

        Args:
            settings (dict): The settings to update

        Returns:
            str: Error
        """
        error = ""
        # Check if the newly given directory is actually an directory
        if 'root_dir' in settings:
            if os.path.isdir(settings['root_dir']):
                app.root_dir = settings['root_dir']
            else:
                error = "The directory is not valid"
        # Set the hotkey
        if 'hotkey' in settings:
            app.hotkey = settings['hotkey']
        # Set the search timeout
        if 'search_timeout' in settings:
            app.search_timeout = float(settings['search_timeout'])
        # Update the search engine
        app.update_search_engine()
        app.save_settings(settings=settings)
        return error

if __name__ == "__main__":
    # Create the search app
    # Check if there are saved settings
    settings = SearchApp.load_settings('settings.json')
    if 'root_dir' in settings:
        root_dir = settings['root_dir']
    else:
        # If the root_dir is not specified in the settings
        # we default to the root path of the os. (/ for linux & c:/ or d:/ etc for windows)
        root_dir = os.path.abspath(os.sep)

    # Get the screen resolution
    s_w, s_h = pyautogui.size()
    # Define the default width and height of the application
    w, h = 1000, 800
    # Calculate the position where the window should be shown
    pos_w, pos_h = ((s_w/2)-(w/2)), ((s_h/2)+(h/2))
    # Check cmd args to see if we are in dev or prod
    # True if there is an extra arg specified but gets inverted, so extra arg = dev
    prod = not len(sys.argv) == 2
    # Create the app
    try:
        app = SearchApp('localhost', 8080, "3020", (w, h),
                        (pos_w, pos_h), root_dir, prod=prod)
    except FileNotFoundError:
        new_dir = os.path.abspath(os.sep)
        print(
            f'Error: The given root directory could not be found, using {new_dir} instead!')
        app = SearchApp('localhost', 8080, "3020", (w, h),
                        (pos_w, pos_h), new_dir, prod=prod)
    # Automatically update the settings.
    err = app.update_settings(settings)
    if err != '':
        print("Error when updating settings:", err)
    # Start the app
    app.start()  # Blocking
    app.quit()  # Always make sure that the app closes correctly


import logging
import multiprocessing
import os

from apimon.executor.sensors import SensorInterface

class CPUSensor(SensorInterface):
    log = logging.getLogger("apimon.executor.sensor.cpu")

    def __init__(self, config):
        load_multiplier = float(config.get_default('executor',
                                                   'load_multiplier', '2.5'))
        self.max_load_avg = multiprocessing.cpu_count() * load_multiplier

    def isOk(self):
        load_avg = os.getloadavg()[0]

        if load_avg > self.max_load_avg:
            return False, "high system load {} > {}".format(
                load_avg, self.max_load_avg)

        return True, "{} <= {}".format(load_avg, self.max_load_avg)

    def reportStats(self, statsd, base_key: str, zero: bool = False):
        load_avg = int(os.getloadavg()[0] * 100) if not zero else 0
        statsd.gauge(base_key + '.load_average', load_avg)


from django.urls import path, include
from .apiviews import PicturesViewGet,PicturesViewUpdate,PicturesViewDelete

# router = DefaultRouter()
#
# router.register('detail/<int:pk>',PicturesViewGet, basename='pictures-detail')
# router.register('list',PicturesViewGet, basename='pictures-list')
# router.register('update/<int:pk>',PicturesViewUpdate, basename='pictures-update')
# router.register('delete/<int:pk>',PicturesViewDelete, basename='pictures-delete')

urlpatterns = [
    path('picture/detail/<int:pk>',PicturesViewGet.as_view({'get': 'retrieve'})),
    path('pictures/',PicturesViewGet.as_view({'get': 'list','post': 'create'})),
    path('picture/update/<int:pk>',PicturesViewUpdate.as_view({'get': 'retrieve','put': 'update'})),
    path('picture/delete/<int:pk>',PicturesViewDelete.as_view({'get': 'retrieve', 'delete': 'destroy'})),
] # + router.urls


from ClientEvents import *
from ClientRequests import *

# substate=state*10 + 0~9
STATE_AUTO=0
STATE_COMNAV=1
SUBSTATE_COM1=10
SUBSTATE_COM2=11
SUBSTATE_NAV1=12
SUBSTATE_NAV2=13

STATE_GPS=2

STATE_G1000=3
SUBSTATE_FMS=30
SUBSTATE_ALT=31
SUBSTATE_HDG_G1k=32
SUBSTATE_CRS=33
SUBSTATE_MFD=35

STATE_INST=5
SUBSTATE_HDG=50
SUBSTATE_OBS=51

STATE_LIGHT=6

STATE_END=7

# STATE  0~ max 9
# button 0~ max 9

statelabel=['AutoP','COM/NAV','GPS','G1000','','Instr','Light','','reset','quit']

buttonlabels={
    STATE_AUTO:['ap','hdg','nav','apr','rev','alt','','','','nav/gps'],
    STATE_COMNAV:['Com1','Com2','Nav1','Nav2','','audio','audio','audio','audio','stby'],

    STATE_GPS:['nrst','msg', '', '', '', 'dir','menu','clr','ent','clrall'],
    STATE_G1000:['FMS','ALT','HDG', 'CRS','','MFD'],
    STATE_INST:['hdg','obs'],
    STATE_LIGHT:['strobe','nav','taxi','land','panel'],
    }

buttonactions={
    STATE_AUTO:[AP_MASTER, AP_HDG_HOLD, AP_NAV1_HOLD, AP_APR_HOLD, AP_BC_HOLD, AP_ALT_HOLD, EVENT_NONE, EVENT_NONE, EVENT_NONE, TOGGLE_GPS_DRIVES_NAV1,],
    STATE_COMNAV:[EVENT_NONE,EVENT_NONE,EVENT_NONE,EVENT_NONE, EVENT_NONE,
                  COM1_TRANSMIT_SELECT,COM2_TRANSMIT_SELECT,RADIO_VOR1_IDENT_TOGGLE,RADIO_VOR2_IDENT_TOGGLE, EVENT_NONE],

    STATE_GPS :[GPS_NEAREST_BUTTON, GPS_MSG_BUTTON, EVENT_NONE, EVENT_NONE, EVENT_NONE, GPS_DIRECTTO_BUTTON, GPS_MENU_BUTTON, GPS_CLEAR_BUTTON, GPS_ENTER_BUTTON, GPS_CLEAR_ALL_BUTTON],
    STATE_LIGHT:[STROBES_TOGGLE,TOGGLE_NAV_LIGHTS,TOGGLE_TAXI_LIGHTS,LANDING_LIGHTS_TOGGLE,PANEL_LIGHTS_TOGGLE,],

    }

rotarytable={
    # button,  rotate right,  rotate left
    STATE_AUTO:[EVENT_NONE, AP_ALT_VAR_INC, AP_ALT_VAR_DEC],

    STATE_GPS:[GPS_CURSOR_BUTTON, GPS_GROUP_KNOB_INC, GPS_GROUP_KNOB_DEC],
    SUBSTATE_HDG:[EVENT_NONE, HEADING_BUG_INC, HEADING_BUG_DEC],
    SUBSTATE_OBS:[EVENT_NONE, VOR1_OBI_DEC, VOR1_OBI_INC],

    SUBSTATE_COM1:[COM_STBY_RADIO_SWAP, COM_RADIO_WHOLE_INC, COM_RADIO_WHOLE_DEC],
    SUBSTATE_COM2:[COM2_RADIO_SWAP, COM2_RADIO_WHOLE_INC, COM2_RADIO_WHOLE_DEC],
    SUBSTATE_NAV1:[NAV1_RADIO_SWAP, NAV1_RADIO_WHOLE_INC, NAV1_RADIO_WHOLE_DEC],
    SUBSTATE_NAV2:[NAV2_RADIO_SWAP, NAV2_RADIO_WHOLE_INC, NAV2_RADIO_WHOLE_DEC],

    SUBSTATE_FMS:[G1000_PFD_CURSOR_BUTTON, G1000_PFD_GROUP_KNOB_INC,G1000_PFD_GROUP_KNOB_DEC],
    SUBSTATE_ALT:[EVENT_NONE, AP_ALT_VAR_INC, AP_ALT_VAR_DEC],
    SUBSTATE_HDG_G1k:[REQ_HDGBUG_SYNC, HEADING_BUG_INC, HEADING_BUG_DEC],
    SUBSTATE_CRS:[EVENT_NONE, VOR1_OBI_INC, VOR1_OBI_DEC],
    SUBSTATE_MFD:[G1000_MFD_CURSOR_BUTTON, G1000_MFD_GROUP_KNOB_INC,G1000_MFD_GROUP_KNOB_DEC],
    }

rotarytable2={
    # button,  rotate right,  rotate left
    STATE_AUTO:[EVENT_NONE, AP_VS_VAR_INC, AP_VS_VAR_DEC],

    STATE_GPS:[GPS_CURSOR_BUTTON, GPS_PAGE_KNOB_INC, GPS_PAGE_KNOB_DEC],
    SUBSTATE_HDG:[EVENT_NONE, HEADING_BUG_INC, HEADING_BUG_DEC],
    SUBSTATE_OBS:[EVENT_NONE, VOR2_OBI_DEC, VOR2_OBI_INC],

    SUBSTATE_COM1:[COM_STBY_RADIO_SWAP, COM_RADIO_FRACT_INC, COM_RADIO_FRACT_DEC],
    SUBSTATE_COM2:[COM2_RADIO_SWAP, COM2_RADIO_FRACT_INC, COM2_RADIO_FRACT_DEC],
    SUBSTATE_NAV1:[NAV1_RADIO_SWAP, NAV1_RADIO_FRACT_INC, NAV1_RADIO_FRACT_DEC],
    SUBSTATE_NAV2:[NAV2_RADIO_SWAP, NAV2_RADIO_FRACT_INC, NAV2_RADIO_FRACT_DEC],

    SUBSTATE_FMS:[G1000_PFD_CURSOR_BUTTON, G1000_PFD_PAGE_KNOB_INC,G1000_PFD_PAGE_KNOB_DEC],
    SUBSTATE_ALT:[EVENT_NONE, AP_ALT_VAR_INC, AP_ALT_VAR_DEC],
    SUBSTATE_HDG_G1k:[REQ_HDGBUG_SYNC, HEADING_BUG_INC, HEADING_BUG_DEC],
    SUBSTATE_CRS:[EVENT_NONE, VOR2_OBI_INC, VOR2_OBI_DEC],
    SUBSTATE_MFD:[G1000_MFD_CURSOR_BUTTON, G1000_MFD_PAGE_KNOB_INC,G1000_MFD_PAGE_KNOB_DEC],
    }

#request ids
request_ids={
    COM_RADIO_WHOLE_DEC:REQ_COM1_FREQ,
    COM_RADIO_WHOLE_INC:REQ_COM1_FREQ,
    COM_RADIO_FRACT_DEC:REQ_COM1_FREQ,
    COM_RADIO_FRACT_INC:REQ_COM1_FREQ,

    COM2_RADIO_WHOLE_DEC:REQ_COM2_FREQ,
    COM2_RADIO_WHOLE_INC:REQ_COM2_FREQ,
    COM2_RADIO_FRACT_DEC:REQ_COM2_FREQ,
    COM2_RADIO_FRACT_INC:REQ_COM2_FREQ,

    NAV1_RADIO_WHOLE_DEC:REQ_NAV1_FREQ,
    NAV1_RADIO_WHOLE_INC:REQ_NAV1_FREQ,
    NAV1_RADIO_FRACT_DEC:REQ_NAV1_FREQ,
    NAV1_RADIO_FRACT_INC:REQ_NAV1_FREQ,

    NAV2_RADIO_WHOLE_DEC:REQ_NAV2_FREQ,
    NAV2_RADIO_WHOLE_INC:REQ_NAV2_FREQ,
    NAV2_RADIO_FRACT_DEC:REQ_NAV2_FREQ,
    NAV2_RADIO_FRACT_INC:REQ_NAV2_FREQ,

    AP_MASTER:REQ_AP_STATUS,
    AP_HDG_HOLD:REQ_AP_STATUS,
    AP_NAV1_HOLD:REQ_AP_STATUS,
    AP_APR_HOLD:REQ_AP_STATUS,
    AP_BC_HOLD:REQ_AP_STATUS,
    AP_ALT_HOLD:REQ_AP_STATUS,

    }


from contextlib import contextmanager

@contextmanager
def TempTable(path=None, prefix=None, attributes=None, expiration_timeout=None, client=None):
    """Creates temporary table in given path with given prefix on scope enter and \
       removes it on scope exit.

       .. seealso:: :func:`create_temp_table <yt.wrapper.table_commands.create_temp_table>`
    """
    from .cypress_commands import remove
    from .table_commands import create_temp_table

    table = create_temp_table(path, prefix, attributes, expiration_timeout, client=client)
    try:
        yield table
    finally:
        remove(table, force=True, client=client)


import torch
from torch import Tensor, nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair

from ..utils import ext_loader

ext_module = ext_loader.load_ext(
    '_ext', ['correlation_forward', 'correlation_backward'])

class CorrelationFunction(Function):

    @staticmethod
    def forward(ctx,
                input1,
                input2,
                kernel_size=1,
                max_displacement=1,
                stride=1,
                padding=1,
                dilation=1,
                dilation_patch=1):

        ctx.save_for_backward(input1, input2)

        kH, kW = ctx.kernel_size = _pair(kernel_size)
        patch_size = max_displacement * 2 + 1
        ctx.patch_size = patch_size
        dH, dW = ctx.stride = _pair(stride)
        padH, padW = ctx.padding = _pair(padding)
        dilationH, dilationW = ctx.dilation = _pair(dilation)
        dilation_patchH, dilation_patchW = ctx.dilation_patch = _pair(
            dilation_patch)

        output_size = CorrelationFunction._output_size(ctx, input1)

        output = input1.new_zeros(output_size)

        ext_module.correlation_forward(
            input1,
            input2,
            output,
            kH=kH,
            kW=kW,
            patchH=patch_size,
            patchW=patch_size,
            padH=padH,
            padW=padW,
            dilationH=dilationH,
            dilationW=dilationW,
            dilation_patchH=dilation_patchH,
            dilation_patchW=dilation_patchW,
            dH=dH,
            dW=dW)

        return output

    @staticmethod
    @once_differentiable
    def backward(ctx, grad_output):
        input1, input2 = ctx.saved_tensors

        kH, kW = ctx.kernel_size
        patch_size = ctx.patch_size
        padH, padW = ctx.padding
        dilationH, dilationW = ctx.dilation
        dilation_patchH, dilation_patchW = ctx.dilation_patch
        dH, dW = ctx.stride
        grad_input1 = torch.zeros_like(input1)
        grad_input2 = torch.zeros_like(input2)

        ext_module.correlation_backward(
            grad_output,
            input1,
            input2,
            grad_input1,
            grad_input2,
            kH=kH,
            kW=kW,
            patchH=patch_size,
            patchW=patch_size,
            padH=padH,
            padW=padW,
            dilationH=dilationH,
            dilationW=dilationW,
            dilation_patchH=dilation_patchH,
            dilation_patchW=dilation_patchW,
            dH=dH,
            dW=dW)
        return grad_input1, grad_input2, None, None, None, None, None, None

    @staticmethod
    def _output_size(ctx, input1):
        iH, iW = input1.size(2), input1.size(3)
        batch_size = input1.size(0)
        kH, kW = ctx.kernel_size
        patch_size = ctx.patch_size
        dH, dW = ctx.stride
        padH, padW = ctx.padding
        dilationH, dilationW = ctx.dilation
        dilatedKH = (kH - 1) * dilationH + 1
        dilatedKW = (kW - 1) * dilationW + 1

        oH = int((iH + 2 * padH - dilatedKH) / dH + 1)
        oW = int((iW + 2 * padW - dilatedKW) / dW + 1)

        output_size = (batch_size, patch_size, patch_size, oH, oW)
        return output_size

class Correlation(nn.Module):
    r"""Correlation operator

    This correlation operator works for optical flow correlation computation.

    There are two batched tensors with shape :math:`(N, C, H, W)`,
    and the correlation output's shape is :math:`(N, max\_displacement \times
    2 + 1, max\_displacement * 2 + 1, H_{out}, W_{out})`

    where

    .. math::
        H_{out} = \left\lfloor\frac{H_{in}  + 2 \times padding -
            dilation \times (kernel\_size - 1) - 1}
            {stride} + 1\right\rfloor

    .. math::
        W_{out} = \left\lfloor\frac{W_{in}  + 2 \times padding - dilation
            \times (kernel\_size - 1) - 1}
            {stride} + 1\right\rfloor

    the correlation item :math:`(N_i, dy, dx)` is formed by taking the sliding
    window convolution between input1 and shifted input2,

    .. math::
        Corr(N_i, dx, dy) =
        \sum_{c=0}^{C-1}
        input1(N_i, c) \star
        \mathcal{S}(input2(N_i, c), dy, dx)

    where :math:`\star` is the valid 2d sliding window convolution operator,
    and :math:`\mathcal{S}` means shifting the input features (auto-complete
    zero marginal), and :math:`dx, dy` are shifting distance, :math:`dx, dy \in
    [-max\_displacement \times dilation\_patch, max\_displacement \times
    dilation\_patch]`.

    Args:
        kernel_size (int): The size of sliding window i.e. local neighborhood
            representing the center points and involved in correlation
            computation. Defaults to 1.
        max_displacement (int): The radius for computing correlation volume,
            but the actual working space can be dilated by dilation_patch.
            Defaults to 1.
        stride (int): The stride of the sliding blocks in the input spatial
            dimensions. Defaults to 1.
        padding (int): Zero padding added to all four sides of the input1.
            Defaults to 0.
        dilation (int): The spacing of local neighborhood that will involved
            in correlation. Defaults to 1.
        dilation_patch (int): The spacing between position need to compute
            correlation.  Defaults to 1.
    """

    def __init__(self,
                 kernel_size: int = 1,
                 max_displacement: int = 1,
                 stride: int = 1,
                 padding: int = 0,
                 dilation: int = 1,
                 dilation_patch: int = 1) -> None:
        super().__init__()
        self.kernel_size = kernel_size
        self.max_displacement = max_displacement
        self.stride = stride
        self.padding = padding
        self.dilation = dilation
        self.dilation_patch = dilation_patch

    def forward(self, input1: Tensor, input2: Tensor) -> Tensor:
        return CorrelationFunction.apply(input1, input2, self.kernel_size,
                                         self.max_displacement, self.stride,
                                         self.padding, self.dilation,
                                         self.dilation_patch)

    def __repr__(self) -> str:
        s = self.__class__.__name__
        s += f'(kernel_size={self.kernel_size}, '
        s += f'max_displacement={self.max_displacement}, '
        s += f'stride={self.stride}, '
        s += f'padding={self.padding}, '
        s += f'dilation={self.dilation}, '
        s += f'dilation_patch={self.dilation_patch})'
        return s


'''
Write a python program which finds the maximum number from num1 to num2 (num2 inclusive) based on the following rules.

Always num1 should be less than num2
Consider each number from num1 to num2 (num2 inclusive). Populate the number into a list, if the below conditions are satisfied
Sum of the digits of the number is a multiple of 3
Number has only two digits
Number is a multiple of 5
Display the maximum element from the list
In case of any invalid data or if the list is empty, display -1.
'''

def find_max(num1, num2):
    max_num=-1
    # Write your logic here
    max_valid=[]
    initial=num1
    while(num1<=num2 and num1<100):
        temp=list(str(num1))
        temp=map(int,temp)
        if(sum(temp)%3==0 and num1%5==0):
            max_valid.append(num1)
        num1+=1
    if(len(max_valid)==0 or initial==num2):
        return(max_num)
    else:
        return(max(max_valid))

#Provide different values for num1 and num2 and test your program.
max_num=find_max(3,30)
print(max_num)


import logging
import requests
from util.orm import Session
from model import Area
import config
import json
from model.community import Community

db_session = Session()

def fetch_list_pages(db, city_index):
    logging.info('抓取区域列表')
    areas_obj = db.query(Area).filter(
        Area.city_index == city_index,
        Area.insert == 0
    ).all()
    for area in areas_obj:
        page = 1
        while True:
            logging.info(f'正在抓取第{page}页')
            api_url = f'http://m.58.com/xiaoquweb/getXiaoquList/?city={area.area_index}&page={page}'
            res = requests.get(api_url, headers=config.config.headers, timeout=5)
            res.raise_for_status()
            res_json_obj = json.loads(res.content)
            if res_json_obj['code'] == "0":
                page_dto = res_json_obj['data']['pageDTO']
                info_list = res_json_obj['data']['infoList']
                if page_dto['currentPageNo'] > page_dto['totalPage']:
                    break
                for community in info_list:
                    add_community = Community(city_index, area.area_index, community)
                    db.add(add_community)
                    logging.info('新增1条小区信息')
            page += 1
        area.insert = 1
        db.commit()

    logging.info('抓取区域列表数据完毕')
    db.close()

def main(city_index):
    fetch_list_pages(db_session, city_index)

if __name__ == '__main__':
    main(config.config.city_index)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('iwmiproject', '0104_nursery_seed'),
    ]

    operations = [
        migrations.AddField(
            model_name='fertilizermanagement',
            name='nurseryID',
            field=models.ForeignKey(null=True, verbose_name='nurseryID', to='iwmiproject.Nursery', blank=True),
        ),
    ]


#!/usr/bin/env python
import argparse
import atexit
import logging
import os
import shutil
import sys
from pathlib import Path

from checkov.arm.runner import Runner as arm_runner
from checkov.cloudformation.runner import Runner as cfn_runner
from checkov.common.bridgecrew.platform_integration import bc_integration
from checkov.common.bridgecrew.image_scanning.image_scanner import image_scanner
from checkov.common.goget.github.get_git import GitGetter
from checkov.common.runners.runner_registry import RunnerRegistry, OUTPUT_CHOICES
from checkov.common.util.banner import banner as checkov_banner
from checkov.common.util.consts import DEFAULT_EXTERNAL_MODULES_DIR
from checkov.common.util.docs_generator import print_checks
from checkov.common.util.runner_dependency_handler import RunnerDependencyHandler
from checkov.common.util.type_forcers import convert_str_to_bool
from checkov.terraform.runner import Runner as tf_graph_runner
from checkov.helm.runner import Runner as helm_runner
from checkov.kubernetes.runner import Runner as k8_runner
from checkov.logging_init import init as logging_init
from checkov.runner_filter import RunnerFilter
from checkov.serverless.runner import Runner as sls_runner
from checkov.terraform.plan_runner import Runner as tf_plan_runner
from checkov.dockerfile.runner import Runner as dockerfile_runner
from checkov.version import version

outer_registry = None

logging_init()
logger = logging.getLogger(__name__)
checkov_runner_module_names = ['cfn', 'tf', 'k8', 'sls', 'arm', 'tf_plan', 'helm']
checkov_runners = ['cloudformation', 'terraform', 'kubernetes', 'serverless', 'arm', 'terraform_plan', 'helm', 'dockerfile']

# Check runners for necessary system dependencies.
runnerDependencyHandler = RunnerDependencyHandler(checkov_runner_module_names, globals())
runnerDependencyHandler.validate_runner_deps()

def run(banner=checkov_banner, argv=sys.argv[1:]):
    parser = argparse.ArgumentParser(description='Infrastructure as code static analysis')
    add_parser_args(parser)
    args = parser.parse_args(argv)

    # bridgecrew uses both the urllib3 and requests libraries, while checkov uses the requests library.
    # Allow the user to specify a CA bundle to be used by both libraries.
    bc_integration.setup_http_manager(args.ca_certificate)

    # Disable runners with missing system dependencies
    args.skip_framework = runnerDependencyHandler.disable_incompatible_runners(args.skip_framework)

    runner_filter = RunnerFilter(framework=args.framework, skip_framework=args.skip_framework, checks=args.check, skip_checks=args.skip_check,
                                 download_external_modules=convert_str_to_bool(args.download_external_modules),
                                 external_modules_download_path=args.external_modules_download_path,
                                 evaluate_variables=convert_str_to_bool(args.evaluate_variables), runners=checkov_runners)
    if outer_registry:
        runner_registry = outer_registry
        runner_registry.runner_filter = runner_filter
    else:
        runner_registry = RunnerRegistry(banner, runner_filter, tf_graph_runner(), cfn_runner(), k8_runner(), sls_runner(),
                                         arm_runner(), tf_plan_runner(), helm_runner(),dockerfile_runner())
    if args.version:
        print(version)
        return

    if args.bc_api_key == '':
        parser.error('The --bc-api-key flag was specified but the value was blank. If this value was passed as a secret, you may need to double check the mapping.')
    elif args.bc_api_key:
        logger.debug(f'Using API key ending with {args.bc_api_key[-8:]}')

        if args.repo_id is None:
            parser.error("--repo-id argument is required when using --bc-api-key")
        if len(args.repo_id.split('/')) != 2:
            parser.error("--repo-id argument format should be 'organization/repository_name' E.g "
                         "bridgecrewio/checkov")

        source = os.getenv('BC_SOURCE', 'cli')
        source_version = os.getenv('BC_SOURCE_VERSION', version)
        logger.debug(f'BC_SOURCE = {source}, version = {source_version}')
        try:
            bc_integration.setup_bridgecrew_credentials(bc_api_key=args.bc_api_key, repo_id=args.repo_id,
                                                        skip_fixes=args.skip_fixes,
                                                        skip_suppressions=args.skip_suppressions,
                                                        source=source, source_version=source_version, repo_branch=args.branch)
            excluded_paths = bc_integration.get_excluded_paths()
            runner_filter.excluded_paths = excluded_paths
        except Exception as e:
            logger.error('An error occurred setting up the Bridgecrew platform integration. Please check your API token and try again.', exc_info=True)
            return
    else:
        logger.debug('No API key found. Scanning locally only.')

    guidelines = {}
    if not args.no_guide:
        guidelines = bc_integration.get_guidelines()
    if args.check and args.skip_check:
        parser.error("--check and --skip-check can not be applied together. please use only one of them")
        return
    if args.list:
        print_checks(framework=args.framework)
        return
    external_checks_dir = get_external_checks_dir(args)
    url = None

    if args.directory:
        exit_codes = []
        for root_folder in args.directory:
            file = args.file
            scan_reports = runner_registry.run(root_folder=root_folder, external_checks_dir=external_checks_dir,
                                               files=file, guidelines=guidelines, bc_integration=bc_integration)
            if bc_integration.is_integration_configured():
                bc_integration.persist_repository(root_folder)
                bc_integration.persist_scan_results(scan_reports)
                url = bc_integration.commit_repository(args.branch)

            exit_codes.append(runner_registry.print_reports(scan_reports, args, url))

        exit_code = 1 if 1 in exit_codes else 0
        return exit_code
    elif args.file:
        scan_reports = runner_registry.run(external_checks_dir=external_checks_dir, files=args.file,
                                           guidelines=guidelines, bc_integration=bc_integration)
        if bc_integration.is_integration_configured():
            files = [os.path.abspath(file) for file in args.file]
            root_folder = os.path.split(os.path.commonprefix(files))[0]
            bc_integration.persist_repository(root_folder)
            bc_integration.persist_scan_results(scan_reports)
            url = bc_integration.commit_repository(args.branch)
        return runner_registry.print_reports(scan_reports, args, url)
    elif args.docker_image:
        if args.bc_api_key is None:
            parser.error("--bc-api-key argument is required when using --docker-image")
            return
        if args.dockerfile_path is None:
            parser.error("--dockerfile-path argument is required when using --docker-image")
            return
        if args.branch is None:
            parser.error("--branch argument is required when using --docker-image")
            return
        image_scanner.scan(args.docker_image, args.dockerfile_path)
    else:
        print(f"{banner}")

        bc_integration.onboarding()

def add_parser_args(parser):
    parser.add_argument('-v', '--version',
                        help='version', action='store_true')
    parser.add_argument('-d', '--directory', action='append',
                        help='IaC root directory (can not be used together with --file).')
    parser.add_argument('-f', '--file', action='append',
                        help='IaC file(can not be used together with --directory)')
    parser.add_argument('--external-checks-dir', action='append',
                        help='Directory for custom checks to be loaded. Can be repeated')
    parser.add_argument('--external-checks-git', action='append',
                        help='Github url of external checks to be added. \n you can specify a subdirectory after a '
                             'double-slash //. \n cannot be used together with --external-checks-dir')
    parser.add_argument('-l', '--list', help='List checks', action='store_true')
    parser.add_argument('-o', '--output', nargs='?', choices=OUTPUT_CHOICES,
                        default='cli',
                        help='Report output format')
    parser.add_argument('--no-guide', action='store_true',
                        default=False,
                        help='do not fetch bridgecrew guide in checkov output report')
    parser.add_argument('--quiet', action='store_true',
                        default=False,
                        help='in case of CLI output, display only failed checks')
    parser.add_argument('--compact', action='store_true',
                        default=False,
                        help='in case of CLI output, do not display code blocks')
    parser.add_argument('--framework', help='filter scan to run only on a specific infrastructure code frameworks',
                        choices=checkov_runners + ["all"],
                        default='all')
    parser.add_argument('--skip-framework', help='filter scan to skip specific infrastructure code frameworks. \n'
                                                 'will be included automatically for some frameworks if system dependencies are missing.',
                        choices=checkov_runners,
                        default=None)
    parser.add_argument('-c', '--check',
                        help='filter scan to run only on a specific check identifier(allowlist), You can '
                             'specify multiple checks separated by comma delimiter', default=None)
    parser.add_argument('--skip-check',
                        help='filter scan to run on all check but a specific check identifier(denylist), You can '
                             'specify multiple checks separated by comma delimiter', default=None)
    parser.add_argument('-s', '--soft-fail',
                        help='Runs checks but suppresses error code', action='store_true')
    parser.add_argument('--bc-api-key', help='Bridgecrew API key')
    parser.add_argument('--docker-image', help='Scan docker images by name or ID. Only works with --bc-api-key flag')
    parser.add_argument('--dockerfile-path', help='Path to the Dockerfile of the scanned docker image')
    parser.add_argument('--repo-id',
                        help='Identity string of the repository, with form <repo_owner>/<repo_name>')
    parser.add_argument('-b', '--branch',
                        help="Selected branch of the persisted repository. Only has effect when using the --bc-api-key flag",
                        default='master')
    parser.add_argument('--skip-fixes',
                        help='Do not download fixed resource templates from Bridgecrew. Only has effect when using the --bc-api-key flag',
                        action='store_true')
    parser.add_argument('--skip-suppressions',
                        help='Do not download preconfigured suppressions from the Bridgecrew platform. Code comment suppressions will still be honored. '
                             'Only has effect when using the --bc-api-key flag',
                        action='store_true')
    parser.add_argument('--download-external-modules',
                        help="download external terraform modules from public git repositories and terraform registry",
                        default=os.environ.get('DOWNLOAD_EXTERNAL_MODULES', False))
    parser.add_argument('--external-modules-download-path',
                        help="set the path for the download external terraform modules",
                        default=DEFAULT_EXTERNAL_MODULES_DIR)
    parser.add_argument('--evaluate-variables',
                        help="evaluate the values of variables and locals",
                        default=True)
    parser.add_argument('-ca', '--ca-certificate',
                        help='custom CA (bundle) file', default=None)

def get_external_checks_dir(args):
    external_checks_dir = args.external_checks_dir
    if args.external_checks_git:
        git_getter = GitGetter(args.external_checks_git[0])
        external_checks_dir = [git_getter.get()]
        atexit.register(shutil.rmtree, str(Path(external_checks_dir[0]).parent))
    return external_checks_dir

if __name__ == '__main__':
    exit(run())


from datetime import datetime
from OFS.Folder import Folder
from Acquisition import Explicit
from Products.MyBlog import blog

def test_catalog():
    folder = Folder()
    catalog = blog._create_catalog(folder)

    class Dummy(Explicit):
        def __init__(self, title, date):
            self.title = title
            self.date = date

    dummy = Dummy("dummy title", datetime(2018, 1, 1))
    dummy = dummy.__of__(folder)
    catalog.catalog_object(dummy, "/this/is/dummy")
    result = catalog({"title": "dummy title"})
    assert len(catalog) == 1
    assert len(result) == 1
    assert result[0].title == "dummy title"
    assert list(catalog) == []


#!/usr/bin/env python

# -*- encoding: utf-8 -*-

# @Author  :   wangtao

# @Contact :   wangtao090620@gmail.com

# @Time    :   2019-12-10 13:17

# 思路：动态规划问题， grid[i][j] += min(grid[i - 1][j], grid[i][j - 1])

# grid[i][j]表示到达第i行第j列元素路径最小和，等于上一次的最小与第i-1行和j-1列路径的最小值的和

class Solution:
    def minPathSum(self, grid):
        m, n = len(grid), len(grid[0])

        for i in range(1, m):
            grid[i][0] += grid[i - 1][0]  # 初始化第一列

        print(grid)

        for i in range(1, n):
            grid[0][i] += grid[0][i - 1]  # 初始化第1行

        print(grid)

        for i in range(1, m):
            for j in range(1, n):
                grid[i][j] += min(grid[i - 1][j], grid[i][j - 1])
        return grid[-1][-1]

if __name__ == '__main__':
    aar = [
        [1, 3, 1],
        [1, 5, 1],
        [4, 2, 1]
    ]
    Solution().minPathSum(aar)


class cal1:
    n1=n2=n3=0
    def setdata(self,n1,n2,n3):
        self.n1= n1
        self.n2= n2
        self.n3= n3

    def display(self):
        total = n1 + n2 + n3
        print(n1,'+',n2,'+',n3,"=",total)

calc = cal1()
n1 = int(input("enter first nunber :"))
n2 = int(input("enter second number :"))
n3= int(input("enter third number :"))
calc.setdata(n1,n2,n3)
calc.display()


from colorama import init, Fore
import random

# Kode # alg labyrint

# definer variabler til lab
cell = "c"
wall = "w"

# Definer lab

def init_maze(width, height):
    maze = []
    for i in range(0,height):
        line = []
        for j in range(0, width):
            line.append('u')
        maze.append(line)
    return maze

# print og skap lab

# størrelse
height=11
width=27

def print_maze(maze):
    for i in range(0,len(maze)):
        for j in range(0,len(maze[0])):
            if maze [i][j] == 'u':
                print(Fore.WHITE,f'{maze[i][j]}')
            elif maze[i][j] == 'c':
                print(Fore.GREEN, f'{maze[i][j]}', end="")
            else:
                print(Fore.RED, f'{maze[i][j]}', end="")
        print('\n')

print(maze)

#starting points
starting_height = int(random.random()*height)
starting_width = int(random.random()*width)

# kan ikke starte på enden av lab

if starting_height == 0:
    starting_height += 1
if starting_height == height-1:
    starting_height -= 1
if starting_width == 0:
    starting_width += 1
if starting_width == width-1:
    starting_width -= 1

maze[starting_height][starting_width] = cell
walls = []
walls.append([starting_height-1, starting_width])
walls.append([starting_height, starting_width-1])
walls.append([starting_height, starting_width+1])
walls.append([starting_height+1, starting_width])

maze[starting_height-1][starting_width] = wall
maze[starting_height][starting_width-1] = wall
maze[starting_height][starting_width+1] = wall
maze[starting_height+1][starting_width] = wall

# vanskelig delen av algoritmen
# While there are walls in the list pick a random wall from the list

while walls:
    rand_walls = walls[int(random.random()*len(walls))-1]


"""Plot quantile MC standard error."""
import numpy as np
import xarray as xr

from ..data import convert_to_dataset
from ..stats import mcse
from .plot_utils import (
    xarray_var_iter,
    _scale_fig_size,
    default_grid,
    get_coords,
    filter_plotters_list,
    get_plotting_function,
    matplotlib_kwarg_dealiaser,
)
from ..rcparams import rcParams
from ..utils import _var_names

def plot_mcse(
    idata,
    var_names=None,
    coords=None,
    errorbar=False,
    figsize=None,
    textsize=None,
    extra_methods=False,
    rug=False,
    rug_kind="diverging",
    n_points=20,
    ax=None,
    rug_kwargs=None,
    extra_kwargs=None,
    text_kwargs=None,
    backend=None,
    backend_kwargs=None,
    show=None,
    **kwargs
):
    """Plot quantile or local Monte Carlo Standard Error.

    Parameters
    ----------
    idata : obj
        Any object that can be converted to an az.InferenceData object
        Refer to documentation of az.convert_to_dataset for details
    var_names : list of variable names, optional
        Variables to be plotted.
    coords : dict, optional
        Coordinates of var_names to be plotted. Passed to `Dataset.sel`
    errorbar : bool, optional
        Plot quantile value +/- mcse instead of plotting mcse.
    figsize : tuple, optional
        Figure size. If None it will be defined automatically.
    textsize: float, optional
        Text size scaling factor for labels, titles and lines. If None it will be autoscaled based
        on figsize.
    extra_methods : bool, optional
        Plot mean and sd MCSE as horizontal lines. Only taken into account when
        ``errorbar=False``.
    rug : bool
        Plot rug plot of values diverging or that reached the max tree depth.
    rug_kind : bool
        Variable in sample stats to use as rug mask. Must be a boolean variable.
    n_points : int
        Number of points for which to plot their quantile/local ess or number of subsets
        in the evolution plot.
    ax: axes, optional
        Matplotlib axes or bokeh figures.
    rug_kwargs : dict
        kwargs passed to rug plot.
    extra_kwargs : dict, optional
        kwargs passed to ax.plot for extra methods lines.
    text_kwargs : dict, optional
        kwargs passed to ax.annotate for extra methods lines labels. It accepts the additional
        key ``x`` to set ``xy=(text_kwargs["x"], mcse)``
    backend: str, optional
        Select plotting backend {"matplotlib","bokeh"}. Default "matplotlib".
    backend_kwargs: bool, optional
        These are kwargs specific to the backend being used. For additional documentation
        check the plotting method of the backend.
    show : bool, optional
        Call backend show function.
    **kwargs
        Passed as-is to plt.hist() or plt.plot() function depending on the value of `kind`.

    Returns
    -------
    axes : matplotlib axes or bokeh figures

    References
    ----------
    * Vehtari et al. (2019) see https://arxiv.org/abs/1903.08008

    Examples
    --------
    Plot quantile Monte Carlo Standard Error.

    .. plot::
        :context: close-figs

        >>> import arviz as az
        >>> idata = az.load_arviz_data("centered_eight")
        >>> coords = {"school": ["Deerfield", "Lawrenceville"]}
        >>> az.plot_mcse(
        ...     idata, var_names=["mu", "theta"], coords=coords
        ... )

    """
    mean_mcse = None
    sd_mcse = None
    text_x = None
    text_va = None

    if coords is None:
        coords = {}
    if "chain" in coords or "draw" in coords:
        raise ValueError("chain and draw are invalid coordinates for this kind of plot")

    data = get_coords(convert_to_dataset(idata, group="posterior"), coords)
    var_names = _var_names(var_names, data)

    probs = np.linspace(1 / n_points, 1 - 1 / n_points, n_points)
    mcse_dataset = xr.concat(
        [mcse(data, var_names=var_names, method="quantile", prob=p) for p in probs], dim="mcse_dim"
    )

    plotters = filter_plotters_list(
        list(xarray_var_iter(mcse_dataset, var_names=var_names, skip_dims={"mcse_dim"})),
        "plot_mcse",
    )
    length_plotters = len(plotters)
    rows, cols = default_grid(length_plotters)

    (figsize, ax_labelsize, titlesize, xt_labelsize, _linewidth, _markersize) = _scale_fig_size(
        figsize, textsize, rows, cols
    )
    kwargs = matplotlib_kwarg_dealiaser(kwargs, "plot")
    kwargs.setdefault("linestyle", "none")
    kwargs.setdefault("linewidth", _linewidth)
    kwargs.setdefault("markersize", _markersize)
    kwargs.setdefault("marker", "_" if errorbar else "o")
    kwargs.setdefault("zorder", 3)

    extra_kwargs = matplotlib_kwarg_dealiaser(extra_kwargs, "plot")
    extra_kwargs.setdefault("linestyle", "-")
    extra_kwargs.setdefault("linewidth", _linewidth / 2)
    extra_kwargs.setdefault("color", "k")
    extra_kwargs.setdefault("alpha", 0.5)
    if extra_methods:
        mean_mcse = mcse(data, var_names=var_names, method="mean")
        sd_mcse = mcse(data, var_names=var_names, method="sd")

        text_kwargs = matplotlib_kwarg_dealiaser(text_kwargs, "text")
        text_x = text_kwargs.pop("x", 1)
        text_kwargs.setdefault("fontsize", xt_labelsize * 0.7)
        text_kwargs.setdefault("alpha", extra_kwargs["alpha"])
        text_kwargs.setdefault("color", extra_kwargs["color"])
        text_kwargs.setdefault("horizontalalignment", "right")
        text_va = text_kwargs.pop("verticalalignment", None)

    mcse_kwargs = dict(
        ax=ax,
        plotters=plotters,
        length_plotters=length_plotters,
        rows=rows,
        cols=cols,
        figsize=figsize,
        errorbar=errorbar,
        rug=rug,
        data=data,
        probs=probs,
        kwargs=kwargs,
        extra_methods=extra_methods,
        mean_mcse=mean_mcse,
        sd_mcse=sd_mcse,
        text_x=text_x,
        text_va=text_va,
        text_kwargs=text_kwargs,
        rug_kwargs=rug_kwargs,
        extra_kwargs=extra_kwargs,
        idata=idata,
        rug_kind=rug_kind,
        _markersize=_markersize,
        _linewidth=_linewidth,
        xt_labelsize=xt_labelsize,
        ax_labelsize=ax_labelsize,
        titlesize=titlesize,
        backend_kwargs=backend_kwargs,
        show=show,
    )

    if backend is None:
        backend = rcParams["plot.backend"]
    backend = backend.lower()

    if backend == "bokeh":
        mcse_kwargs.pop("kwargs")
        mcse_kwargs.pop("text_x")
        mcse_kwargs.pop("text_va")
        mcse_kwargs.pop("text_kwargs")
        mcse_kwargs.pop("xt_labelsize")
        mcse_kwargs.pop("ax_labelsize")
        mcse_kwargs.pop("titlesize")

    # TODO: Add backend kwargs
    plot = get_plotting_function("plot_mcse", "mcseplot", backend)
    ax = plot(**mcse_kwargs)
    return ax


import datetime
import json
import os
import re

from hoshino import Service, priv, typing
from nonebot import MessageSegment

sv = Service("刻印", enable_on_default=True, visible=True)

def trans_alias(alias) -> str:
    """转换别名"""
    with open(
        os.path.join(os.path.dirname(__file__), "alias.json"), "r", encoding="utf8"
    ) as f:
        data = json.load(f)
        f.close()
    for k in data:
        if alias == k or alias in data[k]:
            return k
    raise KeyError(f"没有找到{alias}的数据，请检查输入")

@sv.on_prefix(("刻印"))
async def show_buff(bot, ev):
    msg = ev.message.extract_plain_text().strip()
    if not msg:
        return
    try:
        valkyrie = trans_alias(msg)
    except KeyError as e:
        await bot.send(ev, f"{e}\n如果确定没输错,请联系管理员添加别名.")
        return
    ms = MessageSegment.text("未更新")
    select_im = []
    for im in os.listdir(os.path.join(os.path.dirname(__file__), "image")):
        if im.startswith(valkyrie):
            select_im.append(os.path.join(os.path.dirname(__file__), "image", im))
    images = MessageSegment.text("")
    for im in select_im:
        images = images + MessageSegment.image(f"file:///{im}")
    ctime = os.path.getctime(select_im[0])
    if ctime < 1657763146:
        await bot.send(ev, images+ms)
    else:
        await bot.send(ev,images)
        return

@sv.on_prefix("刻印别名添加")
async def add_alias(bot, ev: typing.CQEvent):
    if not priv.check_priv(ev, priv.SU):
        return
    msg = str(ev.message.extract_plain_text())
    try:
        valkyrie, alias = re.split(":|：", msg)
    except:
        return
    try:
        valkyrie = trans_alias(valkyrie)
    except:
        return
    with open(
        os.path.join(os.path.dirname(__file__), "alias.json"), "r", encoding="utf8"
    ) as f:
        data = json.load(f)
    assert isinstance(data, dict)
    with open(
        os.path.join(os.path.dirname(__file__), "alias.json"), "w", encoding="utf8"
    ) as f:
        alias_data = set(data[valkyrie])
        alias_data.add(alias)
        data.update({valkyrie: list(alias_data)})
        json.dump(data, f, ensure_ascii=False, indent=4)
    await bot.send(ev, f"{valkyrie}别名:{alias}更新完成。\n当前记录的别名如下\n{alias_data}")
    with open(
        os.path.join(os.path.dirname(__file__), "record.txt"), "a+", encoding="utf8"
    ) as rec:
        rec.write(
            f"{ev.user_id}:{ev.group_id},{valkyrie}-{alias}   {datetime.datetime.today()}\n"
        )
        rec.close()

if __name__ == "__main__":
    pass


import pytest

from vyper.compiler import compile_code
from vyper.exceptions import InvalidType, TypeMismatch

good_list = [
    # basic test
    """
@external
def foo(a: uint256, b: uint256) -> uint256:
    return a if a > b else b
    """,
    """
@external
def foo():
    a: bool = (True if True else True) or True
    """,
    # different locations:
    """
b: uint256

@external
def foo(x: uint256) -> uint256:
    return x if x > self.b else self.b
    """,
    # different kinds of test exprs
    """
@external
def foo(x: uint256, t: bool) -> uint256:
    return x if t else 1
    """,
    """
@external
def foo(x: uint256) -> uint256:
    return x if True else 1
    """,
    """
@external
def foo(x: uint256) -> uint256:
    return x if False else 1
    """,
    # more complex types
    """
@external
def foo(t: bool) -> DynArray[uint256, 1]:
    return [2] if t else [1]
    """,
    # TODO: get this working, depends #3377
    #    """
    # @external
    # def foo(t: bool) -> DynArray[uint256, 1]:
    #    return [] if t else [1]
    #    """,
    """
@external
def foo(t: bool) -> (uint256, uint256):
    a: uint256 = 0
    b: uint256 = 1
    return (a, b) if t else (b, a)
    """,
]

@pytest.mark.parametrize("code", good_list)
def test_ternary_good(code):
    assert compile_code(code) is not None

fail_list = [
    (  # bad test type
        """
@external
def foo() -> uint256:
    return 1 if 1 else 2
    """,
        InvalidType,
    ),
    (  # bad test type: constant
        """
TEST: constant(uint256) = 1
@external
def foo() -> uint256:
    return 1 if TEST else 2
    """,
        InvalidType,
    ),
    (  # bad test type: variable
        """
TEST: constant(uint256) = 1
@external
def foo(t: uint256) -> uint256:
    return 1 if t else 2
    """,
        TypeMismatch,
    ),
    (  # mismatched body and orelse: literal
        """
@external
def foo() -> uint256:
    return 1 if True else 2.0
    """,
        TypeMismatch,
    ),
    (  # mismatched body and orelse: literal and known type
        """
T: constant(uint256) = 1
@external
def foo() -> uint256:
    return T if True else 2.0
    """,
        TypeMismatch,
    ),
    (  # mismatched body and orelse: both variable
        """
@external
def foo(x: uint256, y: uint8) -> uint256:
    return x if True else y
    """,
        TypeMismatch,
    ),
    (  # mismatched tuple types
        """
@external
def foo(a: uint256, b: uint256, c: uint256) -> (uint256, uint256):
    return (a, b) if True else (a, b, c)
    """,
        TypeMismatch,
    ),
    (  # mismatched tuple types - other direction
        """
@external
def foo(a: uint256, b: uint256, c: uint256) -> (uint256, uint256):
    return (a, b, c) if True else (a, b)
    """,
        TypeMismatch,
    ),
]

@pytest.mark.parametrize("code,exc", fail_list)
def test_functions_call_fail(code, exc):
    with pytest.raises(exc):
        compile_code(code)


import re

#expfa is non deterministic
#Accept state:q3
class RULE:
    def __init__(self, dict):
        self.transition = dict
    def __getitem__(self ,input):
        for key, val in self.transition.items():
            if(key==input):
                return val
            if(re.match(key, input)):
                return val
        raise KeyError

class NFA:
    def __init__(self,initial, dict, final_state):
        self.start = initial
        self.rule = dict
        self.final = final_state
    def __getitem__(self ,input):
        return self.rule[input]

    def accepts(self, string):
        state = self.start
        banned = ["break", "const", "case", "catch", "continue", "default",
              "delete", "else", "false", "finally", "for", "function",
              "if", "let", "null", "return", "switch", "throw", "try",
              "true", "var","while", " ", "do"]
        if string in banned:
            return False
        if string == "":
            return False
        try:
            i=0
            while(i<len(string)):

                state = self[state][string[i]]
                i+=1
            return state == 'q1'
        except KeyError:
            return False
    def add_rule(self,state, rule):#ADD
        self.rule.update({state: rule})

def varNFA(string):
    state = 'q0'
    nfa = {'q0': RULE({'[A-Za-z]':'q1'}),
           'q1': RULE({'[A-Za-z0-9_]':'q1'})
           }
    fnfa =  NFA('q0',nfa, ['q0'])

    return fnfa.accepts(string)

def intNFA(string):
    final_state = ['q1', 'q2', 'q5']
    state = 'q0'
    nfa = {'q0':RULE({'[0-9]':'q1'}),
            'q1':RULE({'[0-9]':'q1', '.':'q2', 'e':'q3'}),
            'q2':RULE({'[0-9]':'q2', '[eE]':'q3'}),
            'q3':RULE({'[0-9]':'q5', '\+|\-':'q4'}),
            'q4':RULE({'[0-9]':'q5'}),
            'q5':RULE({'[0-9]':'q5'})
            }
    try:
        for i in range(len(string)):
            state= nfa[state][string[i]]

        return state in final_state
    except KeyError:
        return False

def transformstring(string):
    for i in range(len(string)):

        """
def opNFA(array):
    NFA = {'q0':{r'[\+]':'q+', ''
                }
           }"""

operator = []
ifop = ['?']
elseop = [':']
#log op can be and calc op can be excahnged
logical_operator = ['==','>','>=','<','<=','&&', '||','??','===','!==',]
calc_operator = ['+','&', '|','^', '/', '**','<<','*','%','>>','-','>>>']
assign_operator = ['+=', '=', '&=', '|=', '^=','/=', '**=','<<=','&&=', '||=','*=','??=','%=','>>=','-=','>>>=']
prefix_operator = ['!', '~', '+', '-','--','++']
comma = [',']

def classifying_operator(string):
    operator = []
    ifop = ['?']
    elseop = [':']
    #log op can be and calc op can be excahnged
    logical_operator = ['==','>','>=','<','<=','&&', '||','??','===','!==','!=']
    calc_operator = ['+','&', '|','^', '/', '**','<<','*','%','>>','-','>>>']
    assign_operator = ['+=', '&=', '|=', '^=','/=', '**=','<<=','&&=', '||=','*=','??=','%=','>>=','-=','>>>=']
    prefix_operator = ['!', '~', '+', '-','--','++']
    equal_operator = ["="]
    ambigue = ['+','-']
    operator = logical_operator+ifop+elseop+calc_operator+assign_operator+prefix_operator+equal_operator
    result = []
    store = ''
    for i in string:

        if store+i in operator:
            store+=i
            continue
        else:
            if (store != ''):
                if i in ambigue:
                    result.append('opAmb')
                else:
                    if store in logical_operator+calc_operator:
                        result.append('opExp')
                    elif store in prefix_operator:
                        result.append('opPrec')
                    elif store in assign_operator:
                        result.append('opAssignment')
                    elif store in ifop:
                        result.append('opif')
                    elif store in elseop:
                        result.append('opels')
                    elif store in equal_operator:
                        result.append('equal')

            if i in operator:
                store=i
            else:
                store = ''
                result.append(i)
    return result

def transformstring(string):
    ignore = False
    result = []
    stop = ''
    for i in string:
        #Kasus dalam string
        if ignore:
            if(i == stop):
                ignore = False
            continue

        # Kasus luar string
        if i == "'" or i == '"':
            stop = i
            ignore = True
        if ignore:
            result.append('benang')
        else:
            result.append(i)

    return result

def PreProcess(array):
    # JANGAN GANTI MENJADI BANNED TERMINAL
    #F.S.
    #1. Turn all funct,obj,var name as fariabel
    #2. Turn all integer float in any kind of form as angka
    #3. Classificate operator
    #4. Turn all string to setring
    #5. remove whitespase
    banned = ["break", "const", "case", "catch", "continue", "default",
              "delete", "else", "false", "finally", "for", "function",
              "if", "let", "null", "return", "switch", "throw", "try",
              "true", "var","while"]
    temp1 = []
    temp2 = []
    for i in array:
        if varNFA(i):

            temp1.append('variabel')
        else:
            temp1.append(i)
    #2. Transform number
    for i in temp1:
        if intNFA(i):## masih salah
            temp2.append('angka')
        else:
            temp2.append(i)

    #3. Class Op
    temp2 = classifying_operator(temp2)

    #4. String
    temp2 = transformstring(temp2)

    #5. White Space
    while ' ' in temp2:
        temp2.remove(' ')
    while '\n' in temp2:
        temp2.remove('\n')
    return temp2


print("Задача 34:  Винни-Пух попросил Вас посмотреть, есть ли в его стихах ритм.")
print("Введите песню")
song = input()
volwes = ['а', 'о', 'э', 'е', 'и', 'ы', 'у', 'ё', 'ю', 'я']
parts = song.split()
itog = list()
for item in parts:
    k = 0
    for letter in item:
        if letter in volwes:
            k += 1
    itog.append(k)
if len(set(itog)) == 1:
    print('Парам пам-пам :)')
else:
    print('Пам парам :(')

print("Задача 36: Напишите функцию, которая принимает в качестве аргумента функцию, вычисляющую элемент по номеру строки и столбца.")

from math import log10

def printOperationTable(operation, numRows=9, numColumns=9):
    if operation(1,1)==2:
        print(1,end='\t')

    colSize = int(log10(operation(numRows+1, numColumns+1)))+2

    for row in range(1, numRows+1):
        for column in range(1, numColumns+1):
            if operation(1,1)==2:
                column=column-1
            print("{:>{}}".format(operation(row,column), colSize), end='\t')
        print()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
from matplotlib.pyplot import figure, plot, xlabel, ylabel, legend, show
from sklearn.model_selection import train_test_split
import sklearn.linear_model as lm
from toolbox_02450 import confmatplot, dbplotf
from sklearn.model_selection import StratifiedKFold
from scipy.stats import zscore

from data_preProcessing_interval_normalize import *

Y = zscore(X,0)
# Normalize and compute PCA (UNCOMMENT to experiment with PCA preprocessing)
U,S,V = np.linalg.svd(Y,full_matrices=False)
V = V.T
#Components to be included as features
k_pca = 8
X = X @ V[:,0:k_pca]
N, M = X.shape

# K-fold crossvalidation with stratified folds
K = 5
CV_1 = StratifiedKFold(K, shuffle=False)
# J-fold crossvalidation with stratified folds
J = 3
CV_2 = StratifiedKFold(J, shuffle=False)

# train models
n_train = [0.001, 0.01, 0.1, 1, 10, 100]
# n_train = ["9", "10", "11", "12", "13", "14"]

Error_test = np.empty(K)
clf_list = list()
k=0

err_test = np.ones(J)*np.inf
clf_para = list()
clf_parameter_list = list()
clf_best_para = list()
err_inner_loop = []
err_para_loop = []
gen_err = np.zeros(K)*np.nan
best_est = []
y_test_outer = []
x_test_outer = []
for train_index, test_index in CV_1.split(X, y):
    X_train = X[train_index, :]
    y_train = y[train_index]
    X_test = X[test_index, :]
    y_test = y[test_index]
    j = 0
    for train_index_2, test_index_2 in CV_2.split(X_train, y_train):
        X_train_2 = X_train[train_index_2, :]
        y_train_2 = y_train[train_index_2]
        X_test_2 = X_train[test_index_2, :]
        y_test_2 = y_train[test_index_2]

        for i in n_train:
            # extract training and test set for current CV fold
            logit_classifier = lm.LogisticRegression(C=i)
            logit_classifier.fit(X_train_2, y_train_2)
            Y_est = logit_classifier.predict(X_test_2)
            mis_classified = np.sum(logit_classifier.predict(X_train_2) != y_train_2)
            relative_error = mis_classified / len(y_train_2)
            clf_parameter_list.append(10+i)
            err_para_loop.append(relative_error)

        #Best performing model from innner loop
        best_index = np.argmin(err_para_loop)
        clf_best_para.append(clf_parameter_list[best_index])
        err_inner_loop.append(err_para_loop[best_index])
        j+=1

    #Refit the best performing model
    best_index = np.argmin(err_inner_loop)
    logit_classifier = lm.LogisticRegression(C=clf_best_para[best_index])
    logit_classifier.fit(X_train, y_train)
    y_est = logit_classifier.predict(X_test)
    y_test_outer.append(y_test)
    x_test_outer.append(X_test)
    clf_list.append(logit_classifier)
    best_est.append(y_est)
    mis_classified = np.sum(y_est != y_test)
    relative_error = mis_classified / len(y_test)
    gen_err[k] = relative_error
    k += 1
# show confusion matrix for model training using K-fold cross validation
best_index = gen_err.argmin()
figure()
confmatplot(best_est[best_index], y_test_outer[best_index])
print("The mean generalization error is {0}".format(np.mean(gen_err)))

#
#
#
# #show confusion matrix for model testing using Leave one out cross validation
# figure(1)
# Y_est2 = clf_list[best_index].predict(X_test)
# confmatplot(Y_test,Y_est2)
# show()
#
# Decision boundaries for the multinomial regression model

def nevallog(xval):
    return np.argmax(clf_list[best_index].predict_proba(xval),1)

if k_pca == 2:
    figure()
    dbplotf(x_test_outer[best_index], y_test_outer[best_index] ,nevallog,'auto')
    show()


"""
This program is a simple encryption tool.
The encryption is made by mirroring the letters on the alphabet and
shifting the numbers by some quantity (3 by default). Spaces translate
to %, $, # or &. Other characters remain the same.

Author: Miguel Sapage
"""

from save import *
from encrypt import Encrypt
from decrypt import Decrypt
from choice import Choice

def main():
	choose = Choice() #Encrypt or decrypt
	choice = choose.interact()

	if choice == 'encrypt':
		msg = input('Message to encrypt: ')

		save = SaveEncryption() #Copy to clipboard, save to text file or both
		save_choice = save.interact()

		encrypt = Encrypt(msg)
		result = encrypt.output_msg()

		if save_choice == 'copy':
			save.copy_to_clipboar(result)
		elif save_choice == 'file':
			save.save_to_file(result)
		elif save_choice == 'both':
			save.copy_to_clipboar(result)
			save.save_to_file(result)
	elif choice == 'decrypt':
		encrypted_msg = input('Message to decrypt: ')

		decrypt = Decrypt(encrypted_msg)
		decrypted_msg = decrypt.output_msg()

		save = SaveDecryption(decrypted_msg)
		save.save_to_hidden_file()

main()