import os
import sqlite3

from pathlib import Path

def default_db(user) -> Path:
    currentdir = os.path.dirname(os.path.abspath(__file__))
    parentdir = os.path.dirname(currentdir)
    db_path = Path(parentdir + f'/dbs/{user}.babel.db')
    return db_path.resolve()

class BabelDatabase:
    def __init__(self, db_name: Path):
        self.__db_name = db_name

    def add_change_request(self, user_account, provider_account,
                           consumer_account, schema_id, perms, p_nonce,
                           p_sig, public_key):
        self.__open_con()
        self.__c.execute(f"INSERT INTO perm_change_requests "
                         f"VALUES (NULL,"
                         f"'{user_account}', "
                         f"'{provider_account}', "
                         f"'{consumer_account}',"
                         f"'{schema_id}',"
                         f"'{perms}',"
                         f"'{p_nonce}',"
                         f"'{p_sig}',"
                         f"'{public_key}',"
                         f"0,"
                         f"NULL,"
                         f"NULL)")

        self.__conn.commit()

        request_id = self.__c.lastrowid

        self.__close_con()

        return request_id

    def update_provider_process_id(self, request_id, provider_process_id):
        self.__open_con()

        self.__c.execute(f"UPDATE perm_change_requests "
                         f"SET provider_process_id='{provider_process_id}' "
                         f"WHERE req_id='{request_id}'")

        self.__conn.commit()
        self.__close_con()

    def update_processed(self, request_id, proof_tx=None):
        self.__open_con()

        self.__c.execute(f"UPDATE perm_change_requests "
                         f"SET processed='1',"
                         f"proof_tx='{proof_tx}' "
                         f"WHERE req_id='{request_id}'")

        self.__conn.commit()
        self.__close_con()

    def get_unprocessed(self, num=10):
        self.__open_con()
        self.__c.execute(f'SELECT * FROM perm_change_requests '
                         f'WHERE processed=0 '
                         f'LIMIT {num}')
        columns = [d[0] for d in self.__c.description]
        res = [dict(zip(columns, row)) for row in self.__c.fetchall()]

        self.__close_con()

        return res

    def get_request_by_id(self, request_id, user_account):
        op_data = None
        self.__open_con()
        self.__c.execute(f'SELECT * FROM perm_change_requests '
                         f"WHERE req_id='{request_id}' "
                         f"AND end_user_account='{user_account}' "
                         f'LIMIT 1')
        columns = [d[0] for d in self.__c.description]
        res = [dict(zip(columns, row)) for row in self.__c.fetchall()]

        self.__close_con()

        if res:
            op_data = res[0]

        return op_data

    def __open_con(self):
        self.__conn = sqlite3.connect(str(self.__db_name))
        self.__c = self.__conn.cursor()

    def __close_con(self):
        self.__conn.close()


from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
from django.http import HttpResponse
from hackaway.scrapper import *
import requests
def index(request):
    return render(request,'hackaway/index.html')

def sanitize(request):
    url=request.POST['url']
    value=request.POST.get('radio',False)
    if value=="low":
        res=safesite(url,"low")
    elif value=="med":
        res=safesite(url,"med")
    elif value=="high":
        res=safesite(url,"high")

    score=seccheck(url)
    res='<script>alert("The security score is:'+str(score)+'.")</script>' + res
    return HttpResponse(res)
    # scrape and sanitize the output
    # send the result to another HTML page

def seccheck(url):
    baseurl="https://api.threatintelligenceplatform.com/v1/malwareCheck?domainName=threatintelligenceplatform.com&apiKey=at_FdlCgOLdAmhuP67o2x88QaE4mqLvc&domainName="
    url=baseurl+url
    res=requests.get(url)
    res=res.json()
    return res['safeScore']

def safecheckwebsite(request):
    url=request.POST['url']
    score=seccheck(url)
    res='<script>alert("The security score is:'+str(score)+'.")</script>' + res
    return HttpResponse(res)


#!/usr/bin/python3

import os, stat, atexit
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
import time
import common

hostName = ""
hostPort = common.WEBSERVER_PORT
FIFO = common.FIFO
logger = common.homeSecurityLogger

serverWasStarted = False
@atexit.register
def exit_handler():
    logger.info("Exit command received. Should close web server")
    if serverWasStarted:
        myServer.server_close()
        logger.info("Web Server Stops - %s:%s" % (hostName, hostPort))
    else:
        logger.info("Web server was not started. Nothing to close")

def writeToPipe(message):
    """
    check whether the named pipe exists and write to it
    Returns number of characters written or False otherwise
    """
    try:
        isFIFO = stat.S_ISFIFO(os.stat(FIFO).st_mode)
        if not isFIFO: raise FileNotFoundError
        logger.debug("Writing {} to IPC pipe".format(message))
        pipe = open(FIFO, 'w')
        count = pipe.write(message)
        logger.debug("Written {} chars to pipe".format(count))
        pipe.close()
        return count
    except FileNotFoundError:
        logger.critical("IPC write failed. File does not exist or is not a pipe")

    return False

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(bytes("Received\r\n", "utf-8"))
        query_components = parse_qs(urlparse(self.path).query)
        if('motion' in query_components):
            logger.info("Motion parameter set in request")
            writeToPipe(common.MOTION_DETECTED_COMMAND)

    def log_message(self, format, *args):
        logger.info("Request from {}:{} - ".format(self.client_address[0], self.client_address[1]) + format%args)

if __name__ == "__main__":
    try:
        myServer = HTTPServer((hostName, hostPort), MyServer)
    except Exception as e:
        logger.critical("Exception was raised while starting server: {}".format(str(e)))
        if not writeToPipe(common.WEBSERVER_FAIL_COMMAND):
            logger.critical("Can't signal fail state. Need to exit")
        exit(1)
    else:
        logger.info("Web Server Starts - %s:%s" % (hostName, hostPort))
        serverWasStarted = True
        if not writeToPipe(common.WEBSERVER_READY_COMMAND):
            logger.critical("Can't signal ready state. Need to exit")
            exit(1)
        try:
            myServer.serve_forever()
        except KeyboardInterrupt:
            pass


import os
import factsbeach

from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()

requires = []

with open('requirements.txt') as f:
    requires = f.read().splitlines()

setup(name='Factsbeach',
      version=factsbeach.__version__,
      description='Factsbeach',
      long_description=README + '\n\n' + CHANGES,
      classifiers=[
        "Programming Language :: Python",
        "Framework :: Pyramid",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
        ],
      author='',
      author_email='',
      url='',
      keywords='factsbeach pyaella',
      packages=find_packages(),
      include_package_data=True,
      package_data={'':[
          '*.mako', '*.yaml', '*.csv',
          '*.sql', '*.css', '*.sass',
          '*.js', '*.rb', '*.txt'
      ]},
      zip_safe=False,
      install_requires=requires,
      tests_require=requires,
      test_suite="factsbeach",
      entry_points="""      [paste.app_factory]
      main = pyaella.server.instance:main
      """,
      )


"""
Author: weiguo_ma
Time: 05.02.2023
Contact: weiguo.m@iphy.ac.cn
"""
import copy

import tensornetwork as tn
import torch as tc

from ErrorInverse import ErrorInverse
from Library.AbstractGate import AbstractGate
from Library.NoiseChannel import NoiseChannel
from Library.realNoise import czExp_channel
from Library.tools import EdgeName2AxisName
from Maps import Maps
from UpdateMAPs import UpdateNODES
from superOperator import SuperOperator

realNoiseTensor = czExp_channel(
	'/Users/weiguo_ma/Python_Program/Quantum_error_mitigation/Noisy quantum circuit with MPDO/data/chi/chi1.mat')

noise = NoiseChannel()
dpcNoiseTensor = noise.dpCTensor
apdeNoiseTensor = noise.apdeCTensor

abX = AbstractGate().x().gate.tensor
XTensor = tc.einsum('ijk, jl -> ilk', dpcNoiseTensor, abX)

abCZ = AbstractGate().cz().gate.tensor

def check_matrixSame(matrix1, matrix2):
	if tc.allclose(matrix1, matrix2):
		print('Same')
	else:
		print('Not Same')

# --------------------- IMPORT BASIC Info ABOVE ---------------------------------------

uMPO = SuperOperator(realNoiseTensor).superOperatorMPO
idealUMPO = SuperOperator(abCZ, noisy=False).superOperatorMPO
idealUMPO2 = copy.deepcopy(idealUMPO)

maps = Maps(superOperatorMPO=uMPO)
uPMPO = UpdateNODES(maps=maps, epoch=10).uPMPO

ErrorInverse = ErrorInverse(idealMPO=idealUMPO, uPMPO=uPMPO, chi=None).EpsilonMinus1

# --------------------- CAL ERROR INVERSE ABOVE ---------------------------------------

for num in range(2):
	tn.connect(ErrorInverse[num][f'Dinner_{num}'], uMPO[num][f'Dphysics_{num}'])
for num in range(2):
	num_ = num + 2
	tn.connect(ErrorInverse[num_][f'inner_{num}'], uMPO[num_][f'physics_{num}'])

contractor = []
for item in ErrorInverse:
	contractor.append(item)
for item in uMPO:
	contractor.append(item)

idealOperator = tn.contractors.auto(contractor,
                                    output_edge_order=[contractor[0]['Dphysics_0'], contractor[1]['Dphysics_1'],
                                                       contractor[2]['physics_0'], contractor[3]['physics_1'],
                                                       contractor[4]['Dinner_0'], contractor[5]['Dinner_1'],
                                                       contractor[6]['inner_0'], contractor[7]['inner_1']])
idealUMPO2 = tn.contractors.auto(idealUMPO2,
                                 output_edge_order=[idealUMPO2[0]['Dphysics_0'], idealUMPO2[1]['Dphysics_1'],
                                                    idealUMPO2[2]['physics_0'], idealUMPO2[3]['physics_1'],
                                                    idealUMPO2[0]['Dinner_0'], idealUMPO2[1]['Dinner_1'],
                                                    idealUMPO2[2]['inner_0'], idealUMPO2[3]['inner_1']])
EdgeName2AxisName(idealUMPO2)

check_matrixSame(idealOperator.tensor, idealUMPO2.tensor)
print(tc.diag(idealOperator.tensor.reshape(16, 16)))
print(tc.diag(idealUMPO2.tensor.reshape(16, 16)))


import argparse
import pickle
import ssl
import os

import torch.optim as optim
import torch.nn as nn
import torchvision
from torch.utils.data import DataLoader, Dataset
import matplotlib.pyplot as plt
import torch
import torchvision.transforms as transforms
import time as t

import vanilla_model as vanilla
import moded_model as moded

def get_output_accuracy(pred, confirmed, top_res=(1,)):
    max_num_results = max(top_res) #get highest result looking for
    data_size = confirmed.size(0)

    pred_values, pred_indx = pred.topk(k=max_num_results, dim=1)
    pred_indx = pred_indx.t()
#   Reshape confirmed indxs
    confirmed_indx_reshape = confirmed.view(1, -1).expand_as(pred_indx)
    answers = pred_indx == confirmed_indx_reshape

    top_res_acc = []
    for k in top_res:
        temp_answers = answers[:k] #limit each image answer to k values
        temp_answers = temp_answers.reshape(-1).float() #flatten to see whats right form ALL images in batch
        temp_answers = temp_answers.float().sum(dim=0, keepdim=True)
        curr_acc = temp_answers/data_size
        top_res_acc.append(curr_acc)
    return top_res_acc
def evaluate_epoch_top1_5(model, data, device, test_loader=None):
    model.eval() #Set to evaluate
    tot_top1_accuracy = 0
    tot_top5_accuracy = 0
    test_tot_top1_accuracy = 0
    test_tot_top5_accuracy = 0
    for imgs, labels in data:
        imgs = imgs.to(device)
        labels = labels.to(device)

        with torch.no_grad():
            output = model(imgs)
        curr_top1, curr_top5 = get_output_accuracy(output, labels, (1, 5))
        tot_top1_accuracy += curr_top1
        tot_top5_accuracy += curr_top5
    avg_test_top5_epoch_acc = 0
    avg_test_top1_epoch_acc = 0
    if test_loader is not None:
        for imgs, labels in test_loader:
            imgs = imgs.to(device)
            labels = labels.to(device)

            with torch.no_grad():
                output = model(imgs)
            curr_top1, curr_top5 = get_output_accuracy(output, labels, (1, 5))
            test_tot_top1_accuracy += curr_top1
            test_tot_top5_accuracy += curr_top5
    avg_test_top5_epoch_acc = test_tot_top5_accuracy / len(test_loader)
    avg_test_top1_epoch_acc = test_tot_top1_accuracy / len(test_loader)
    avg_top5_epoch_acc = tot_top5_accuracy / len(data)
    avg_top1_epoch_acc = tot_top1_accuracy / len(data)

    model.train() #Set to train when returning to function

    return avg_top1_epoch_acc, avg_top5_epoch_acc, avg_test_top1_epoch_acc, avg_test_top5_epoch_acc

def train(n_epochs, optimizer, model, loss_fn, train_loader, scheduler, device,
          decoder_save=None, plot_file=None, pickleLosses = None,
          starting_epoch=1, evaluate_epochs=False, folder='./', store_data=False, test_loader=None):

    model.train()
    total_losses = []
    total_top1_accuracy = []
    total_top5_accuracy = []
    test_total_top1_accuracy = []
    test_total_top5_accuracy = []

    final_loss = 0.0
    t_1 = t.time()
    print("\n=======================================")
    print("Training started at Epoch {}\n".format(starting_epoch))

    # loading_saved pickle data
    # if pickleLosses is not None:
    #     try:
    #         with open(pickleLosses, 'rb') as file:
    #             loaded_losses = pickle.load(file)
    #             (total_losses, content_losses, style_losses) = loaded_losses
    #             print("Loaded saved losses from file successfully: \n{} \n{} \n{}"
    #                   .format(total_losses, content_losses, style_losses))
    #     except Exception as e:
    #         print(f"An error occurred while loading arrays: {str(e)}")

    for epoch in range(starting_epoch, n_epochs + 1):
        print("Starting Epoch: ", epoch)
        # Losses for current epoch
        total_loss = 0.0
        t_2 = t.time()

        for idx, data in enumerate(train_loader):
            t_3 = t.time()
            imgs, labels = data[0].to(device), data[1].to(device)
            optimizer.zero_grad()

            outputs = model(imgs)
            loss = loss_fn(outputs, labels)
            loss.backward()
            optimizer.step()

            total_loss += loss.item()
            print('Batch #{}/{}         Time: {}'.format(idx + 1, len(train_loader), (t.time() - t_3)))

        if decoder_save is not None and (epoch % 50 == 0 or epoch == n_epochs):
            torch.save(model.decoder.state_dict(), decoder_save)
            print("Saved frontend model under name: {}".format(decoder_save))

        scheduler.step(total_loss)
        total_losses.append(total_loss / len(train_loader))
        final_loss = total_loss / len(train_loader)

        # Store loss data in pickled file
        # pickleSave = os.path.join(os.path.abspath(folder), "pickled_dump.pk1")
        # if pickleLosses is not None:
        #     pickleSave = os.path.join(os.path.abspath(folder), pickleLosses)
        # try:
        #     with open(pickleSave, 'wb') as file:
        #         pickle.dump((total_losses, epoch), file)
        #         print("Saved losses to '{}'".format(pickleSave))
        # except Exception as e:
        #     print(f"An error occurred while saving arrays: {str(e)}")

        # Plot loss data each epoch
        if plot_file is not None:
            plot_save = os.path.join(os.path.abspath(folder), plot_file)
            plt.figure(2, figsize=(12, 7))
            plt.clf()
            plt.plot(total_losses, label='Total')
            plt.xlabel('epoch')
            plt.ylabel('loss')
            plt.legend(loc=1)
            plt.savefig(plot_save)

        print('Epoch {}, Training loss {}, Time  {}'.format(epoch, final_loss,(t.time() - t_2)))
        if evaluate_epochs:
            top_1_acc, top_5_acc, test_top_1_acc, test_top_5_acc = evaluate_epoch_top1_5(model, train_loader, device, test_loader=test_loader)
            total_top1_accuracy.append(float(top_1_acc))
            total_top5_accuracy.append(float(top_5_acc))
            print("Accuracy (Training Data) = TOP-1:   {}  |  TOP-5:    {}".format(top_1_acc, top_5_acc))
            if test_loader is not None:
                test_total_top1_accuracy.append(float(test_top_1_acc))
                test_total_top5_accuracy.append(float(test_top_5_acc))
            print("Accuracy (Test Data) = TOP-1:   {}  |  TOP-5:    {}".format(test_top_1_acc, test_top_5_acc))

    print('Total Training loss {}, Time  {}'.format(final_loss, (t.time() - t_1)))

    # if store_data:
    #     filename = os.path.join(os.path.abspath(folder), 'output_results')
    #     print("Length: {}    {}   {}    {}   {}".format(total_top5_accuracy, total_top1_accuracy, test_total_top1_accuracy, test_total_top5_accuracy, total_losses))
    #     try:
    #         with open(filename, 'w') as file:
    #             file.write("Training results for run with the following hyper parameters:\n{}\n".format(arguments))
    #             if train_loader is not None: file.write("Accuracy & loss results per Epoch: (Train_Top 1,  Train_Top 5, "
    #                                                     "Test_Top_1, Test_Train_5,  Loss)\n")
    #             else: file.write("Accuracy & loss results per Epoch: (Top 1,    Top 5,   Loss)\n")
    #             for i in range(n_epochs):
    #                 top_1_item = total_top1_accuracy[i]
    #                 top_5_item = total_top5_accuracy[i]
    #                 test_top_5, test_top_1 = "", ""
    #                 if train_loader is not None:
    #                     test_top_1 = test_total_top1_accuracy[i]
    #                     test_top_5 = test_total_top5_accuracy[i]
    #
    #                 loss = total_losses[i]
    #                 file.write("Epoch {}:  ([{},  {}],   [{},   {}],   {})\n".format(i + 1, top_1_item, top_5_item, test_top_1, test_top_5, loss))
    #             file.close()
    #
    #     except Exception as e:
    #         print(f"An error occurred while loading arrays: {str(e)}")
    return final_loss

if __name__ == '__main__':

    # ssl._create_default_https_context = ssl._create_unverified_context

    device = 'cpu'
    # Setup parser
    parser = argparse.ArgumentParser()
    parser.add_argument('-dir', '--dir', type=str, required=False, default='./data',
                        help='Directory path to a batch of content images')
    # training options
    parser.add_argument('-e', '--e', type=int, default=50)
    parser.add_argument('-b', '--b', type=int, default=8, help="Batch size")
    parser.add_argument('-l', '--l', help="Encoder.pth", required=True)
    parser.add_argument('-s', '--s', help="Decoder.pth")
    parser.add_argument('-p', '--p', help="decoder.png")
    parser.add_argument('-cuda', '--cuda', default='Y')
    parser.add_argument('-type', '--type', type=int, default=0)

    parser.add_argument('-lr', '--lr', type=float, default=0.001)
    parser.add_argument('-wd', '--wd', type=float, default=0.00001)
    parser.add_argument('-minlr', '--minlr', type=float, default=0.001)
    parser.add_argument('-out', '--out', default=None, help="Output folder to put all files for training run")
    parser.add_argument('-gamma', '--gamma', type=float, default=0.9)
    parser.add_argument('-dataset', '--dataset', type=int, default=1)

    args = parser.parse_args()

    print("Beginning Training for model. Using the following parameters passed (Some default)\n")
    print("")

    if args.type == 0:
        model_type = vanilla
    else:
        model_type = moded

    # Import the dataset & get num of batches
    train_transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
    if args.dataset == 0:
        cifar_dataset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=train_transform)
        cifar_test_dataset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True,
                                                           transform=train_transform)
        cifar_data = DataLoader(cifar_dataset, batch_size=args.b, shuffle=True)
        cifar_test_data = DataLoader(cifar_test_dataset, batch_size=args.b, shuffle=True)
        frontend = model_type.encoder_decoder.frontend_10

    else:
        cifar_dataset = torchvision.datasets.CIFAR100(root='./data', train=True, download=True, transform=train_transform)
        cifar_test_dataset = torchvision.datasets.CIFAR100(root='./data', train=False, download=True, transform=train_transform)
        cifar_data = DataLoader(cifar_dataset, batch_size=args.b, shuffle=True)
        cifar_test_data = DataLoader(cifar_test_dataset, batch_size=args.b, shuffle=True)
        frontend = model_type.encoder_decoder.frontend

    encoder = model_type.encoder_decoder.encoder
    encoder.load_state_dict(torch.load(args.l))

    # Creating folder to store all files made during training
    if args.out != None:
        if os.path.exists(os.path.abspath(args.out)):
            print("Saving all files created to folder '{}'".format(args.out))
        else:
            os.mkdir(args.out)
            print("Created folder {} to save all files made during training".format(args.out))
    else:
        args.out = "./"

    # Set the device (GPU if available, otherwise CPU)
    if torch.cuda.is_available() and args.cuda == 'Y':
        if torch.cuda.device_count() > 1:
            device = torch.device("cuda:1")
        else:
            device = torch.device("cuda:0")
    else:
        device = torch.device("cpu")

    print("Using device: {}".format(device))

    loss_fn = nn.functional.cross_entropy
    model = model_type.model(encoder, frontend)
    model.to(device)

    # Define optimizer and learning rate scheduler
    optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.wd)
    scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', patience=2, verbose=True, factor=0.1,
                                                     min_lr=args.minlr)

    # Train the model
    train(args.e, optimizer, model, loss_fn, cifar_data, scheduler, device, args.s,
          args.p, evaluate_epochs=False, folder=args.out, store_data=True, test_loader=cifar_test_data)


import re
import os
import sys
import time
import numpy
import pickle
import datetime

from pygbe.lspr import main as pygbe

try:
    import pycuda
except ImportError:
    ans = input('PyCUDA not found.  Regression tests will take forever.  Do you want to continue? [y/n] ')
    if ans in ['Y', 'y']:
        pass
    else:
        sys.exit()

mesh = ['512', '2K', '8K', '32K']

def picklesave(test_outputs, file_name):
    with open(file_name,'wb') as f:
        pickle.dump(test_outputs, f, 2)

def mesh_ratio(N):
    """
    Calculates the mesh refinement ratio between consecutive meshes.

    Arguments:
    ----------
    N: list, Number of elements / avg_density in test (depends on what applies).

    Returns:
    --------
    mesh_ratio: list of float, mesh refinement ratio between consequtive meshes.
    """
    mesh_ratio = []
    for i in range(len(N)-1):
        mesh_ratio.append(N[i+1]/N[i])

    return mesh_ratio

def run_convergence(mesh, test_name, problem_folder, param):
    """
    Runs convergence tests over a series of mesh sizes

    Inputs:
    ------
        mesh          : array of mesh suffixes
        problem_folder: str, name of folder containing meshes, etc...
        param         : str, name of param file

    Returns:
    -------
        N         : len(mesh) array, elements of problem.
        iterations: len(mesh) array, number of iterations to converge.
        Cext_0    : len(mesh) array of float, Cross extinction section of the
                    main sphere.
        Time      : len(mesh) array of float, time to solution (wall-time)
    """
    print('Runs convergence')
    N = numpy.zeros(len(mesh))
    iterations = numpy.zeros(len(mesh))
    Cext_0 = numpy.zeros(len(mesh))
    Time = numpy.zeros(len(mesh))

    for i in range(len(mesh)):
        try:
            print('Start run for mesh '+mesh[i])
            results = pygbe(['',
                            '-p', problem_folder + '{}'.format(param),
                            '-c', problem_folder +'{}_{}.config'.format(test_name, mesh[i]),
                            '-o', problem_folder + 'output_{}_{}'.format(test_name, mesh[i]),
                            '{}'.format(problem_folder),], return_results_dict=True)

            N[i] = results['total_elements']
            iterations[i] = results['iterations']
            Cext_0[i] = results.get('Cext_0') #We do convergence analysis in the main sphere
            Time[i] = results['total_time']

        except (pycuda._driver.MemoryError, pycuda._driver.LaunchError) as e:
            print('Mesh {} failed due to insufficient memory.'
                  'Skipping this test, but convergence test should still complete'.format(mesh[i]))
            time.sleep(4)

    mesh_rate = mesh_ratio(N)
    expected_rate = 0

    if all(ratio==mesh_rate[0] for ratio in mesh_rate):
        expected_rate = mesh_rate[0]
    else:
        print('Mesh ratio inconsistency. \nIf you are running a system protein-sensor, remember \n'
                'that we do not refine the protein mesh, since measurements are taken over the sensor. \n'
                'Do not worry about the warning as soon as the refinement in your sensor mesh keeps a constant \n'
                'ratio. \n'
                'If you are running a case of single sensor, the refinement should keep a constant ratio, \n'
                'otherwise convergence will not be computed properly.')

    return(N, iterations, expected_rate, Cext_0, Time)

def Cext_analytical(radius, wavelength, diel_out, diel_in):
    """
    Calculates the analytical solution of the extinction cross section.
    This solution is valid when the nano particle involved is a sphere.

    Arguments
    ----------
    radius    : float, radius of the sphere in [nm].
    wavelength: float/array of floats, wavelength of the incident
                electric field in [nm].
    diel_out  : complex/array of complex, dielectric constant inside surface.
    diel_in   : complex/array of complex, dielectric constant inside surface.

    Returns
    --------
    Cext_an   : float/array of floats, extinction cross section.
    """
    wavenumber = 2 * numpy.pi * numpy.sqrt(diel_out) / wavelength
    C1 = wavenumber**2 * (diel_in / diel_out - 1) / (diel_in / diel_out + 2)
    Cext_an = 4 * numpy.pi * radius**3 / wavenumber.real * C1.imag

    return Cext_an

def richardson_extrapolation_lspr(test_result):
    """
    Performs an estimate of the exact solution using
    Richardson extrapolation, given by

    f_ex = (f_1 * f_3 - f_2^2) / (f_3 - 2*f_2+f_1)

    where f_1 is a result from the finest grid and f_3 is from the coarsest.
    The grids f_1, f_2, f_3 should have the same refinement ratio (e.g. 2 -> 4 -> 8)

    Arguments:
    ----------
    test_result:

    Returns:
    --------
    f_ex : float, richardson_extrapolation estimated exact solution.
    """
    #We perform the richardson extrapolation in the main body. The body we
    #meassure
    try:
        Cext_0 = test_result['Cext_0']
    except KeyError:
        print('No results found for main body cross extinction section  \n'
              'Something has gone wrong.')
        sys.exit()

    # Using last 3 meshes asumming the latest is the finner one
    f1 = Cext_0[-1]
    f2 = Cext_0[-2]
    f3 = Cext_0[-3]

    f_ex = (f1 * f3 - f2**2) / (f3 - 2 * f2 + f1)

    return f_ex


from zeroconf import ServiceInfo, Zeroconf
from http.server import SimpleHTTPRequestHandler, HTTPServer
from .shared.node import OSCQueryNode, OSCHostInfo, OSCAccess
import json, threading

class OSCQueryService(object):
    """
    A class providing an OSCQuery service. Automatically sets up a oscjson http server and advertises the oscjson server and osc server on zeroconf.

    Attributes
    ----------
    serverName : str
        Name of your OSC Service
    httpPort : int
        Desired TCP port number for the oscjson HTTP server
    oscPort : int
        Desired UDP port number for the osc server
    """

    def __init__(self, serverName, httpPort, oscPort, oscIp="127.0.0.1") -> None:
        self.serverName = serverName
        self.httpPort = httpPort
        self.oscPort = oscPort
        self.oscIp = oscIp

        self.root_node = OSCQueryNode("/", description="root node")
        self.host_info = OSCHostInfo(serverName, {"ACCESS":True,"CLIPMODE":False,"RANGE":True,"TYPE":True,"VALUE":True},
            self.oscIp, self.oscPort, "UDP")

        self._zeroconf = Zeroconf()
        self._startOSCQueryService()
        self._advertiseOSCService()
        self.http_server = OSCQueryHTTPServer(self.root_node, self.host_info, ('', self.httpPort), OSCQueryHTTPHandler)
        self.http_thread = threading.Thread(target=self._startHTTPServer)
        self.http_thread.start()

    def stop(self):
        self.http_server.shutdown()

    def add_node(self, node):
        self.root_node.add_child_node(node)

    def advertise_endpoint(self, address, value=None, access=OSCAccess.READWRITE_VALUE):
        new_node = OSCQueryNode(full_path=address, access=access)
        if value is not None:
            if not isinstance(value, list):
                new_node.value = [value]
                new_node.type_ = [type(value)]
            else:
                new_node.value = value
                new_node.type_ = [type(v) for v in value]
        self.add_node(new_node)

    def _startOSCQueryService(self):
        oscqsDesc = {'txtvers': 1}
        oscqsInfo = ServiceInfo("_oscjson._tcp.local.", "%s._oscjson._tcp.local." % self.serverName, self.httpPort,
        0, 0, oscqsDesc, "%s.oscjson.local." % self.serverName, addresses=["127.0.0.1"])
        self._zeroconf.register_service(oscqsInfo)

    def _startHTTPServer(self):
        self.http_server.serve_forever()

    def _advertiseOSCService(self):
        oscDesc = {'txtvers': 1}
        oscInfo = ServiceInfo("_osc._udp.local.", "%s._osc._udp.local." % self.serverName, self.oscPort,
        0, 0, oscDesc, "%s.osc.local." % self.serverName, addresses=["127.0.0.1"])

        self._zeroconf.register_service(oscInfo)

class OSCQueryHTTPServer(HTTPServer):
    def __init__(self, root_node, host_info, server_address: tuple[str, int], RequestHandlerClass, bind_and_activate: bool = ...) -> None:
        super().__init__(server_address, RequestHandlerClass, bind_and_activate)
        self.root_node = root_node
        self.host_info = host_info

class OSCQueryHTTPHandler(SimpleHTTPRequestHandler):
    def do_GET(self) -> None:
        if 'HOST_INFO' in self.path:
            self.send_response(200)
            self.send_header("Content-type", "text/json")
            self.end_headers()
            self.wfile.write(bytes(str(self.server.host_info.to_json()), 'utf-8'))
            return
        node = self.server.root_node.find_subnode(self.path)
        if node is None:
            self.send_response(404)
            self.send_header("Content-type", "text/json")
            self.end_headers()
            self.wfile.write(bytes("OSC Path not found", 'utf-8'))
        else:
            self.send_response(200)
            self.send_header("Content-type", "text/json")
            self.end_headers()
            self.wfile.write(bytes(str(node.to_json()), 'utf-8'))

    def log_message(self, format, *args):
        pass


"""
URL configuration for medical_appointments project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from .views import home_view, authentication_view, verify_view, register_view, dashboard_view, profile_view, \
    logout_view, service_view, doctors_pediatric_view, success_page_view, make_appointment_view, DoctorCalendarView, \
    patient_appointments_view, doctors_cardiologist_view, doctors_internal_medicine_view, \
    doctors_general_medicine_view, doctors_gastroenterologist_view, doctors_psychologist_view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home_view, name='home-view'),
    path('authentication/', authentication_view, name='authentication-view'),
    path('dashboard/logout/', logout_view, name='logout-view'),
    path('authentication/verify/', verify_view, name='verify-view'),
    path('register/', register_view, name='register-view'),
    path('authentication/verify/dashboard/', dashboard_view, name='dashboard-view'),
    path('profile/', profile_view, name='profile-view'),
    path('service/', service_view, name='service-view'),
    path('doctors_pediatric/', doctors_pediatric_view, name='doctors-pediatric-view'),
    path('doctors_cardiologist/', doctors_cardiologist_view, name='doctors-cardiologist-view'),
    path('doctors_internal_medicine/', doctors_internal_medicine_view, name='doctors-internal-medicine-view'),
    path('doctors_gastroenterologist/', doctors_gastroenterologist_view, name='doctors-gastroenterologist-view'),
    path('doctors_general_medicine/', doctors_general_medicine_view, name='doctors-general-medicine-view'),
    path('doctors_psychologist/', doctors_psychologist_view, name='doctors-psychologist-view'),

    path('doctors_pediatric/<int:doctor_id>/', make_appointment_view, name='make-appointment-view'),
    path('doctors_cardiologist/<int:doctor_id>/', make_appointment_view, name='make-appointment-view'),
    path('doctors_internal_medicine/<int:doctor_id>/', make_appointment_view, name='make-appointment-view'),
    path('doctors_gastroenterologist/<int:doctor_id>/', make_appointment_view, name='make-appointment-view'),
    path('doctors_general_medicine/<int:doctor_id>/', make_appointment_view, name='make-appointment-view'),
    path('doctors_psychologist/<int:doctor_id>/', make_appointment_view, name='make-appointment-view'),

    path('success/', success_page_view, name='success-page-view'),
    path('<int:doctor_id>/calendar/', DoctorCalendarView.as_view(), name='doctor_calendar'),
    path('patient_appointments/', patient_appointments_view, name='patient-appointments-view'),
]


"""Utilities for bigquery workers."""

import json
from typing import Any, Dict, Iterable

from google.cloud import bigquery
from google.cloud.bigquery.schema import SchemaField

def get_schema_field(field_config: Dict[str, Any]) -> SchemaField:
  """Converts a field config into a schema field instance.

  Args:
    field_config: Dictionary of the desired schema configuration.

  Returns:
    An instance of `google.cloud.bigquery.schema.SchemaField`.
  """
  sub_schema = [
      get_schema_field(f) for f in field_config.get('fields', [])
  ]
  return bigquery.schema.SchemaField(
      name=field_config['name'],
      field_type=field_config.get('type', 'STRING'),
      mode=field_config.get('mode', 'NULLABLE'),
      fields=sub_schema)

def parse_bigquery_json_schema(schema: str) -> Iterable[SchemaField]:
  """Parses a JSON encoded BigQuery schema.

  Args:
    schema: String containing the JSON encoded schema.

  Returns:
    A list of parsed field schemas representing the table schema.
  """
  decoded_schema = json.loads(schema)
  table_schema = [get_schema_field(f) for f in decoded_schema]
  return table_schema

def bytes_converter(total_bytes_processed: int) -> str:
  """Converts bytes processed output to different size equivalent.

  Args:
    total_bytes_processed: Integer of bytes processed for query.

  Returns:
    A conversion of bytes expressed in a different file size.
  """
  if total_bytes_processed / 1000 < 1000:
    kilobytes = round(total_bytes_processed / 1000, 2)
    return f'{kilobytes} KB'
  elif total_bytes_processed / (1000 * 1000) < 1000:
    megabytes = round(total_bytes_processed / (1000 * 1000), 2)
    return f'{megabytes} MB'
  elif total_bytes_processed / (1000 * 1000 * 1000) < 1000:
    gigabytes = round(total_bytes_processed / (1000 * 1000 * 1000), 2)
    return f'{gigabytes} GB'
  else:
    terabytes = round(total_bytes_processed / (1000 * 1000 * 1000 * 1000), 2)
    return f'{terabytes} TB'


# sis/context_processors.py
from django.conf import settings
import datetime
from ecwsp.sis.models import MessageToStudent
from ecwsp.administration.models import Configuration

def global_stuff(request):
    try:
        header_image = Configuration.objects.get_or_create(name="Header Logo")[0].file.url
    except:
        header_image = None
    school_name = Configuration.get_or_default('School Name', default="Unnamed School")
    school_color = Configuration.get_or_default('School Color', default="").value

    # Only show messages if user just logged in
    user_messages = None
    if not request.session.get('has_seen_message', False):
        today = datetime.date.today()
        if request.user.groups.filter(name='students'):
            user_messages = MessageToStudent.objects.filter(start_date__lte=today, end_date__gte=today)
        if request.user.groups.filter(name='company') and 'ecwsp.work_study' in settings.INSTALLED_APPS:
            from ecwsp.work_study.models import MessageToSupervisor
            user_messages = MessageToSupervisor.objects.filter(start_date__lte=today, end_date__gte=today)
        request.session['has_seen_message'] = True

    return {
        "header_image": header_image,
        "school_name": school_name,
        "settings": settings,
        "school_color": school_color,
        'user_messages':user_messages,
    }


from flask import Flask, request
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from json import dumps

base = create_engine('sqlite:///Weather.db')

app = Flask(__name__)
api = Api(app)

class AllDates(Resource):

    def get(self, sensor):
        """
        :param sensor:
        :return: json object with all dates from DB
        """
        conn = base.connect()
        query = conn.execute("SELECT timestamp FROM '{table}'".format(table=sensor))
        return {'dates': [i[0] for i in query.cursor.fetchall()]}

class Sensors(Resource):

    def get(self, sensor, time1, time2, limit):
        """

        :param sensor:
        :param time1:
        :param time2:
        :param limit:
        :return: json object with values from choosen sensor and choosen time
        """
        conn = base.connect()
        query = conn.execute(" SELECT * FROM ' {table} ' WHERE (timestamp >= ' {start} '\
                              and timestamp <= ' {end} ') ORDER BY timestamp DESC Limit ' {lim} '"\
                              .format(table=sensor, start=time1, end=time2,lim=limit))
        result = {sensor: [dict(zip(tuple(query.keys()), i)) for i in query.cursor]}
        return result

api.add_resource(Sensors, '/Sensors/<sensor>/<time1>/<time2>/<limit>')
api.add_resource(All_Dates, '/All_Dates/<sensor>')

if __name__ == '__main__':
    app.run(host="0.0.0.0")


# vim: foldmethod=marker foldlevel=2
from hpp.corbaserver.manipulation.baxter import Robot
from hpp.corbaserver.manipulation import ProblemSolver
from hpp.gepetto import PathPlayer
from hpp.gepetto.manipulation import ViewerFactory
from math import sqrt

# Load robot and object. {{{3

# Define classes for the objects {{{4
class Table (object):
  rootJointType = "anchor"
  packageName = 'iai_maps'
  meshPackageName = 'iai_maps'
  urdfName = 'table'
  urdfSuffix = ""
  srdfSuffix = ""

class Box (object):
  rootJointType = "freeflyer"
  packageName = 'hpp-baxter'
  meshPackageName = 'hpp-baxter'
  urdfName = 'box'
  urdfSuffix = ""
  srdfSuffix = ""
  joint = "base_joint"
  handle = "handle"
# 4}}}

Robot.urdfSuffix = ""
robot = Robot ('baxter-manip', 'baxter')
ps = ProblemSolver (robot)
vf = ViewerFactory (ps)

#robot.setRootJointPosition ("baxter" , [-3.2,-3.9, 0.926, 1, 0, 0, 0])
robot.setRootJointPosition ("baxter" , [-0.8,0.8, 0.926, 1, 0, 0, 0])
vf.loadEnvironmentModel (Table, "table")
vf.loadObjectModel (Box, "box1")
vf.loadObjectModel (Box, "box2")

robot.setJointBounds ('box1/base_joint_xyz', [-1,0.5,-1,2,0.6,1.9])
robot.setJointBounds ('box2/base_joint_xyz', [-1,0.5,-1,2,0.6,1.9])
# 3}}}

# Define configurations. {{{3
q_init = robot.getCurrentConfig ()

q0 = q_init [::]
rank = robot.rankInConfiguration ['box1/base_joint_xyz']
q_init [rank:rank+3] = [-0.3, 1.3, 0.76]
rank = robot.rankInConfiguration ['box1/base_joint_SO3']
c = sqrt (2) / 2
q_init [rank:rank+4] = [c, 0, c, 0]
rank = robot.rankInConfiguration ['box2/base_joint_xyz']
q_init [rank:rank+3] = [-0.3, 1.3, 0.76]
rank = robot.rankInConfiguration ['box2/base_joint_SO3']
c = sqrt (2) / 2
q_init [rank:rank+4] = [c, 0, c, 0]

rank = robot.rankInConfiguration ['box1/base_joint_xyz']
q0 [rank:rank+3] = [-0.3, 0.5, 0.76]
rank = robot.rankInConfiguration ['box1/base_joint_SO3']
q0 [rank:rank+4] = [c, 0, -c, 0]
rank = robot.rankInConfiguration ['box2/base_joint_xyz']
q0 [rank:rank+3] = [-0.4, 0.5, 0.76]
rank = robot.rankInConfiguration ['box2/base_joint_SO3']
q0 [rank:rank+4] = [c, 0, -c, 0]

rank = robot.rankInConfiguration ['box1/base_joint_xyz']
q1 = q_init[:]
q1[rank:rank+7] = [ -0.14391940018238783, 1.092383723903555, 0.7460100959532432, 0.44542854851747, 0.5489390643072047, 0.4452361192941091, -0.5495672023684386]
q2 = q0[:]
q2[rank:rank+3] = [ -0.545, 0.268, 0.7460100959532432]
rank = robot.rankInConfiguration ['box2/base_joint_xyz']
q1[rank:rank+7] = [ -0.14391940018238783, 1.092383723903555, 0.7460100959532432, 0.44542854851747, 0.5489390643072047, 0.4452361192941091, -0.5495672023684386]
q2[rank:rank+3] = [ -0.445, 0.268, 0.7460100959532432]

# 3}}}

robot.client.basic.problem.resetRoadmap ()
robot.client.basic.problem.setErrorThreshold (1e-3)
robot.client.basic.problem.setMaxIterations (20)
#ps.selectPathValidation ('Graph-Discretized', 0.05)
ps.selectPathProjector ('Progressive', 0.1)
# ps.selectPathProjector ('Global', 0.2)

# Create constraints. {{{3
from hpp.corbaserver.manipulation import ConstraintGraph
cg = ConstraintGraph (robot, 'graph')

# Create passive DOF lists {{{4
jointNames = dict ()
jointNames['all'] = robot.getJointNames ()
jointNames['baxter'] = list ()
jointNames['baxterRightSide'] = list ()
jointNames['baxterLeftSide']  = list ()
jointNames['box1'] = list ()
jointNames['box2'] = list ()
for n in jointNames['all']:
  if n.startswith ("baxter"):
    jointNames['baxter'].append (n)
    if n.startswith ("baxter/left_"):
      jointNames['baxterLeftSide'].append (n)
    if n.startswith ("baxter/right_"):
      jointNames['baxterRightSide'].append (n)
  elif n.startswith ("box1"):
      jointNames["box1"].append (n)
  elif n.startswith ("box2"):
      jointNames["box2"].append (n)

ps.addPassiveDofs ('box1', jointNames ['box1'])
ps.addPassiveDofs ('box2', jointNames ['box2'])
ps.addPassiveDofs ('baxter', jointNames ['baxter'])
# 4}}}

# Create the grasps {{{4
cg.createGrasp ('grasp1', 'baxter/r_gripper', 'box1/handle2')
cg.createPreGrasp ('pregrasp1', 'baxter/r_gripper', 'box1/handle2')

cg.createGrasp ('grasp2', 'baxter/r_gripper', 'box2/handle2')
cg.createPreGrasp ('pregrasp2', 'baxter/r_gripper', 'box2/handle2')
# 4}}}

# Create placement constraints {{{4
robot.client.manipulation.problem.createPlacementConstraint (
  'box1_on_table', ['box1/box_surface',], ['table/pancake_table_table_top',])
robot.client.manipulation.problem.createPrePlacementConstraint (
  'box1_above_table', ['box1/box_surface',],
  ['table/pancake_table_table_top',], 0.05)
robot.client.manipulation.problem.createPlacementConstraint (
  'box2_on_table', ['box2/box_surface',], ['table/pancake_table_table_top',])
robot.client.manipulation.problem.createPrePlacementConstraint (
  'box2_above_table', ['box2/box_surface',],
  ['table/pancake_table_table_top',], 0.05)
# 4}}}

# Locks joints that are not used for this problem {{{4
lockFingers = ["r_gripper_l_finger",
               "r_gripper_r_finger",
               "l_gripper_l_finger",
               "l_gripper_r_finger",
        ]
for side in ["r", "l", ]:
    ps.createLockedJoint(side + "_gripper_l_finger", "baxter/" + side + "_gripper_l_finger_joint", [ 0.02,])
    ps.createLockedJoint(side + "_gripper_r_finger", "baxter/" + side + "_gripper_r_finger_joint", [-0.02,])

lockHead = ['head_pan',]
ps.createLockedJoint ('head_pan', 'baxter/head_pan',
    [q_init[robot.rankInConfiguration['baxter/head_pan']]])

for n in jointNames["baxterRightSide"]:
    ps.createLockedJoint (n, n, [0,])

for n in jointNames["baxterLeftSide"]:
    ps.createLockedJoint (n, n, [0,])

lockHeadFingersAndLeftSide = lockFingers + lockHead + jointNames["baxterLeftSide"]
# 4}}}

# Create constraints corresponding to each object {{{4
lockBox1 = ps.lockFreeFlyerJoint ("box1/" + Box.joint, 'box1_lock')
lockBox2 = ps.lockFreeFlyerJoint ("box2/" + Box.joint, 'box2_lock')
# 4}}}

# Create gaze constraints {{{4
ps.createPositionConstraint ("gaze1", "baxter/display_joint", "box1/base_joint_xyz", [0,0,0], [0,0,0], [1,0,0])
ps.createPositionConstraint ("gaze2", "baxter/display_joint", "box2/base_joint_xyz", [0,0,0], [0,0,0], [1,0,0])
# 4}}}

# 3}}}

# Create the graph. {{{3

cg.createNode (['grasp2', 'grasp1', 'free'])

cg.setConstraints (node='free', numConstraints=['box1_on_table','box2_on_table'])
cg.setConstraints (node='grasp1', grasps = ['grasp1',])
cg.setConstraints (node='grasp2', grasps = ['grasp2',])

def genGrasp (iBox, lockBox, otherLockBox):
    iStr = str(iBox)
    grasp = 'grasp' + iStr
    edgeBaseName = grasp+'_edge'
    placement = 'box' + iStr + "_on_table"
    box_above_table = 'box' + iStr + "_above_table"

    # Free to right
    cg.createWaypointEdge ('free', grasp, edgeBaseName, nb=3, weight=1,
                           isInNode = 'free', automaticBuilder=True)

    cg.setConstraints (edge = edgeBaseName + '_e0',
                       lockDof = lockBox + otherLockBox)
    cg.graph.setContainingNode (cg.edges[edgeBaseName + "_e0"],
                                cg.nodes["free"])

    cg.setConstraints (node = edgeBaseName + '_n0',
                       pregrasps = ['pre' + grasp,],
                       numConstraints = [placement,])

    cg.setConstraints (edge = edgeBaseName + '_e1',
                       lockDof = lockBox + otherLockBox)

    cg.graph.setContainingNode (cg.edges[edgeBaseName + "_e1"],
                                cg.nodes["free"])

    cg.graph.setShort (cg.edges[edgeBaseName + "_e1"], True)

    cg.setConstraints (node=edgeBaseName + "_n1", grasps = [grasp],
                       numConstraints = [placement,])

    cg.setConstraints (edge=edgeBaseName + '_e2', lockDof = otherLockBox)
    cg.graph.setContainingNode (cg.edges[edgeBaseName + "_e2"], cg.nodes[grasp])
    cg.graph.setShort (cg.edges[edgeBaseName + "_e2"], True)

    cg.setConstraints (node=edgeBaseName + '_n2', grasps = [grasp],
                       numConstraints = [box_above_table,])

    cg.setConstraints (edge=edgeBaseName + '_e3', lockDof = otherLockBox)
    cg.graph.setContainingNode (cg.edges[edgeBaseName + "_e3"], cg.nodes[grasp])
    cg.graph.setShort (cg.edges[edgeBaseName + "_e3"], True)

    # Right to free
    ungraspEdge = 'ungrasp' + iStr
    cg.createWaypointEdge (grasp, 'free', ungraspEdge + '_e3', nb=3, weight=10,
                           isInNode = 'free', automaticBuilder=False)

    # Reuse previous waypoints
    cg.createEdge (grasp, edgeBaseName + '_n2', ungraspEdge + '_e0', -1, grasp)
    cg.createEdge (edgeBaseName + '_n2', edgeBaseName + '_n1',
                   ungraspEdge + '_e1', -1, grasp)
    cg.createLevelSetEdge (edgeBaseName + '_n2', edgeBaseName + '_n1',
                           ungraspEdge + '_ls_e1', -1)
    cg.createEdge (edgeBaseName + '_n1', edgeBaseName + '_n0',
                   ungraspEdge + '_e2', -1, 'free')
    cg.graph.setWaypoint (cg.edges[ungraspEdge + "_e3"], 0,
                          cg.edges[ungraspEdge + "_e0"],
                          cg.nodes[edgeBaseName + "_n2"])
    # cg.graph.setWaypoint (cg.edges[ungraspEdge + "_e3"], 1, cg.edges[ungraspEdge + "_e1"], cg.nodes[edgeBaseName + "_n1"])
    cg.graph.setWaypoint (cg.edges[ungraspEdge + "_e3"], 1,
                          cg.edges[ungraspEdge + "_ls_e1"],
                          cg.nodes[edgeBaseName + "_n1"])

    cg.graph.setWaypoint (cg.edges[ungraspEdge + "_e3"], 2,
                          cg.edges[ungraspEdge + "_e2"],
                          cg.nodes[edgeBaseName + "_n0"])

    cg.setConstraints (edge = ungraspEdge + '_e3',
                       lockDof = lockBox + otherLockBox)

    cg.setConstraints (edge=ungraspEdge + '_e2',
                       lockDof = lockBox + otherLockBox)

    cg.setContainingNode (ungraspEdge + "_e2", "free")
    cg.setShort (ungraspEdge + "_e2", True)

    cg.setConstraints (edge=ungraspEdge + '_e1', lockDof = otherLockBox)
    cg.setContainingNode (ungraspEdge + "_e1", grasp)
    cg.setShort (ungraspEdge + "_e1", True)

    cg.setConstraints (edge=ungraspEdge + '_ls_e1', lockDof = otherLockBox)
    cg.setContainingNode (ungraspEdge + "_ls_e1", grasp)
    cg.setShort (ungraspEdge + "_ls_e1", True)
    cg.setLevelSetFoliation (edge=ungraspEdge + '_ls_e1', condNC=[placement,],
                             paramLJ = lockBox)

    cg.setConstraints (edge=ungraspEdge + '_e0', lockDof = otherLockBox)
    cg.setContainingNode (ungraspEdge + "_e0", grasp)

genGrasp (1, lockBox1, lockBox2)
genGrasp (2, lockBox2, lockBox1)

cg.createEdge ('free', 'free', 'transit', 0, 'free')
cg.setConstraints (edge='transit', lockDof=lockBox1+lockBox2)
cg.createEdge ('grasp1', 'grasp1', 'transfer1', 0, 'grasp1')
cg.setConstraints (edge='transfer1', lockDof=lockBox2)
cg.createEdge ('grasp2', 'grasp2', 'transfer2', 0, 'grasp2')
cg.setConstraints (edge='transfer2', lockDof=lockBox1)

cg.setConstraints (graph = True, lockDof = lockHeadFingersAndLeftSide)
# 3}}}

res = ps.client.manipulation.problem.applyConstraints (cg.nodes['free'], q1)
if not res[0]:
  raise Exception ('Goal configuration could not be projected.')
q1_proj = res [1]

res = ps.client.manipulation.problem.applyConstraints (cg.nodes['free'], q0)
if not res[0]:
  raise Exception ('Goal configuration could not be projected.')
q0_proj = res [1]

res = ps.client.manipulation.problem.applyConstraints (cg.nodes['free'], q2)
if not res[0]:
  raise Exception ('Goal configuration could not be projected.')
q2_proj = res [1]

import datetime as dt
totalTime = dt.timedelta (0)
totalNumberNodes = 0
for i in range (20):
    ps.clearRoadmap ()
    ps.resetGoalConfigs ()
    ps.setInitialConfig (q0_proj)
    ps.addGoalConfig (q2_proj)
    t1 = dt.datetime.now ()
    ps.solve ()
    t2 = dt.datetime.now ()
    totalTime += t2 - t1
    print (t2-t1)
    n = ps.numberNodes ()
    totalNumberNodes += n
    print ("Number nodes: " + str(n))

print ("Average time: " + str ((totalTime.seconds+1e-6*totalTime.microseconds)/20.))
print ("Average number nodes: " + str (totalNumberNodes/20.))

# r = vf.createViewer()
# pp = PathPlayer (robot.client.basic, r)


__author__ = 'brendan'

import main
import pandas as pd
import numpy as np
from datetime import datetime as dt
from matplotlib import pyplot as plt
import random
import itertools
import time
import dateutil
from datetime import timedelta

data = pd.read_csv('raw_data/MACRO_DATA.csv', index_col=0, parse_dates=True)
data.index.name = 'Date'
fix, ax = plt.subplots()
data['US_PCE'].dropna().plot(ax=ax, label='US PCE')
data['UK_CPI'].dropna().plot(ax=ax, label='UK CPI')
data['EUR_CPI'].dropna().plot(ax=ax, label='EUR CPI')
data['JP_CPI'].dropna().plot(ax=ax, label='JP CPI')
plt.legend()
ax.set_title('Inflation')

fig2, ax2 = plt.subplots()
data_uk_gdp_q = pd.DataFrame(pd.read_csv('raw_data/PGDP_CSDB_DS.csv', index_col=0, parse_dates=True).ix[:-8, 0]).astype(float) / 100.0
data_eur_gdp_q = pd.DataFrame(pd.read_csv('raw_data/data.csv', index_col=0, parse_dates=True, skiprows=5).ix[:, 1]).astype(float) / 100.0
data_uk_gdp_q.index = pd.DatetimeIndex(pd.date_range('1956-01-01', '2015-03-31', freq='QS'))
data_uk_gdp_q.index.name = 'Date'
data_eur_gdp_q.index.name = 'Date'
data_uk_gdp_q.columns = ['UK']
data_eur_gdp_q.columns = ['EUR']
print(data_uk_gdp_q)
print(data['US_GDP_Q'])
#data['US_GDP_Q'].dropna().pct_change(periods=4).plot(ax=ax2, label='US')
data_uk_gdp_q['UK'].plot(ax=ax2, label='UK')
data_eur_gdp_q.plot(ax=ax2, label='EUR')
#Xdata['JP_GDP_A'].dropna().pct_change(periods=1).plot(ax=ax2, label='JP')
ax2.set_title('Real GDP Growth')
plt.legend()

fig3, ax3 = plt.subplots()
data['US_ER'].dropna().plot(ax=ax3, label='US')
data['UK_ER'].dropna().plot(ax=ax3, label='UK')
data['GER_ER'].dropna().plot(ax=ax3, label='GER')
data['ITA_ER'].dropna().plot(ax=ax3, label='ITA')
data['FRA_ER'].dropna().plot(ax=ax3, label='FRA')
data['JP_ER'].dropna().plot(ax=ax3, label='JP')
ax3.set_title('Employment Ratio')
plt.legend()

fig4, ax4 = plt.subplots()
data['US_M2'].dropna().pct_change(periods=1).plot(ax=ax4, label='US')
data['UK_M2'].dropna().pct_change(periods=1).plot(ax=ax4, label='UK')
data['GER_M2'].dropna().pct_change(periods=1).plot(ax=ax4, label='GER')
data['ITA_M2'].dropna().pct_change(periods=1).plot(ax=ax4, label='ITA')
data['FRA_M2'].dropna().pct_change(periods=1).plot(ax=ax4, label='FRA')
data['JP_M2'].dropna().pct_change(periods=1).plot(ax=ax4, label='JP')
ax4.set_title('M2 Growth')
plt.legend()
plt.show()


#!/usr/bin/env python

"""Script to run Selenium2Library acceptance tests.

Tests are executed using Robot Framework and results verified automatically
afterwards using `robotstatuschecker` tool. The tool can be installed using
`pip install robotstatuschecker` and more information about it can be found
from https://github.com/robotframework/statuschecker/. Notice that initially
some tests fail.

Usage:

  run_tests.py interpreter browser [options]

Arguments:

  interpreter:  Any Python interpreter supported by the library (e.g. `python`,
                `jython`, `c:\\Python27\\python.exe`)
  browser:      Any browser supported by the library (e.g. `chrome`, `firefox`)
  options:      Additional command line options passed to Robot Framework

Examples:

  run_tests.py python chrome
  run_tests.py jython c:\\Python35\\python.exe --test "Click element"
"""

from __future__ import print_function

from contextlib import contextmanager
import os
import sys
import subprocess

from robot import rebot_cli
try:
    import robotstatuschecker
except ImportError:
    sys.exit('Required `robotstatuschecker` not installed.\n'
             'Install it with `pip install robotstatuschecker`.')

import env
from run_unit_tests import run_unit_tests

ROBOT_OPTIONS = [
    '--doc', 'Selenium2Library acceptance tests with {browser}',
    '--outputdir', env.RESULTS_DIR,
    '--variable', 'BROWSER:{browser}',
    '--variable', 'PY_VERSION:{py_version}',
    '--report', 'NONE',
    '--log', 'NONE',
    '--loglevel', 'DEBUG',
    '--pythonpath', os.pathsep.join([env.SRC_DIR, env.TEST_LIBS_DIR]),
]
REBOT_OPTIONS = [
    '--outputdir', env.RESULTS_DIR,
    '--critical', 'regression',
    '--noncritical', 'inprogress',
    '--noncritical', 'known issue {browser}',
]

def unit_tests():
    print('Running unit tests')
    failures = run_unit_tests()
    if failures:
        print('\nUnit tests failed! Not running acceptance tests.')
        sys.exit(failures)

def acceptance_tests(interpreter, browser, options):
    if not os.path.exists(env.RESULTS_DIR):
        os.mkdir(env.RESULTS_DIR)
    with http_server():
        execute_tests(interpreter, browser, options)
    failures = process_output(browser, options)
    if failures:
        print('\n{} critical test{} failed.'
              .format(failures, 's' if failures != 1 else ''))
    else:
        print('\nAll critical tests passed.')
    sys.exit(failures)

@contextmanager
def http_server():
    serverlog = open(os.path.join(env.RESULTS_DIR, 'serverlog.txt'), 'w')
    process = subprocess.Popen(['python', env.HTTP_SERVER_FILE, 'start'],
                               stdout=serverlog, stderr=subprocess.STDOUT)
    try:
        yield
    finally:
        subprocess.call(['python', env.HTTP_SERVER_FILE, 'stop'])
        process.wait()
        serverlog.close()

def execute_tests(interpreter, browser, cli_options):
    runner = [interpreter, '-m', 'robot.run']
    options = [opt.format(browser=browser,
                          py_version=interpreter + sys.version[:3])
               for opt in ROBOT_OPTIONS]
    if env.TRAVIS:
        options.extend(get_travis_conf(browser))
    command = runner + options + cli_options + [env.ACCEPTANCE_TEST_DIR]
    log_start(command)
    syslog = os.path.join(env.RESULTS_DIR, 'syslog.txt')
    # Running tests as an external process, not using `robot_cli`, to allow
    # using different interpreter that is used for running this script.
    subprocess.call(command, env=dict(os.environ, ROBOT_SYSLOG_FILE=syslog))

def get_travis_conf(browser):
    conf = [
        '--variable', 'SAUCE_USERNAME:{}'.format(env.SAUCE_USERNAME),
        '--variable', 'SAUCE_ACCESS_KEY:{}'.format(env.SAUCE_ACCESS_KEY)
    ]
    if browser == 'firefox':
        conf.extend([
            '--variable',
            'REMOTE_URL:http://{}:{}@ondemand.saucelabs.com:80/wd/hub'.format(
                env.SAUCE_USERNAME, env.SAUCE_ACCESS_KEY
            )
        ])
    else:
        conf.extend([
            '--variable',
            'DESIRED_CAPABILITIES:build:{0}-{1},tunnel-identifier:{0}'.format(
                env.TRAVIS_JOB_NUMBER, browser
            )
        ])
    return conf

def log_start(command_list):
    command = subprocess.list2cmdline(command_list)
    for hidden in [env.SAUCE_USERNAME, env.SAUCE_ACCESS_KEY]:
        if hidden:
            command = command.replace(hidden, '*' * len(hidden))
    print()
    print('Starting test execution with command:')
    print(command)

def process_output(browser, cli_options):
    print('Verifying results...')
    output = os.path.join(env.RESULTS_DIR, 'output.xml')
    robotstatuschecker.process_output(output, verbose=False)
    options = [opt.format(browser=browser) for opt in REBOT_OPTIONS]
    try:
        rebot_cli(options + cli_options + [output])
    except SystemExit as exit:
        return exit.code

if __name__ == '__main__':
    if len(sys.argv) < 3 or '--help' in sys.argv:
        sys.exit(__doc__)
    unit_tests()
    acceptance_tests(interpreter=sys.argv[1],
                     browser=sys.argv[2].lower(),
                     options=sys.argv[3:])


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 24 14:57:13 2019

@author: user
"""

import os
import skimage.io
import skimage.transform
import numpy as np
from keras.layers import Conv2D,Input,Dense,GlobalAveragePooling2D,Dropout,Activation,BatchNormalization
from keras.optimizers import SGD
from keras.models import Model
from sklearn.cross_validation import train_test_split
import matplotlib.pyplot as plt;
from skimage.color import gray2rgb
from skimage.filters import threshold_niblack
from keras.applications.vgg16 import VGG16
from keras.applications.vgg19 import VGG19
from PIL import Image
# ori data path
data_path = '850nm'
#data_path = 'Finger Vein Database'
# target data path
dae_path = '1'

X = []
y = []
h = os.listdir(data_path)
count = 0
for filename in h:
    im = skimage.io.imread(os.path.join(data_path,filename))
    resized_img = skimage.transform.resize(im, (224, 224),mode='reflect')
    img = resized_img.flatten()
    img = img[np.newaxis,:]
    if count == 0 :
        X = img
        count = 1
    else:
        X = np.vstack((X,img))
    label = filename.replace('.bmp', '').split('_')
    y = np.append(y,label[0])
print (X.shape)
print (y.shape)
print ("Complicate!")

X = np.reshape(X, (len(X),224, 224))
X = gray2rgb(X)
def conbine_img(x,y):
    comb_x = []
    comb_y = []
    count = 0
    for i in range(len(x)):
        if i == (len(x)-1):
            break;
        else:
            for j in range(len(x)-i-1):
                ori_img = x[i]
                compare_img = x[j+i+1]
#                img = np.zeros((1,224,224,2))
                img = ori_img + compare_img
                img = img.reshape([1,224,224,3])
                if count == 0 :
                    comb_x = img
                    count = 1
                else :
                    comb_x = np.vstack((comb_x,img))
                if y[i] == y[j+i+1] :
                    comb_y.append(1)
                else :
                    comb_y.append(0)
    return comb_x,comb_y

c = X[:60]
d = y[:60]
Comb_x,Comb_y = conbine_img(c,d)

#
#X_train, X_test, y_train, y_test = train_test_split(Comb_x, Comb_y)
#
#
#base_model = VGG16(weights='imagenet', include_top=False)
base_model = VGG19(weights='imagenet', include_top=False)

x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(2048, activation='relu')(x)
x = Dropout(0.25)(x)
predictions = Dense(1, activation='sigmoid')(x)
model = Model(input=base_model.input, output=predictions)

model.compile(optimizer=SGD(lr=0.001,momentum=0.9), loss='binary_crossentropy',metrics=['accuracy'])
history = model.fit(Comb_x,Comb_y,epochs=320,
                    nb_epoch=20,
                    validation_data=(Comb_x,Comb_y))
model_save = os.path.join('roc/sensors_SDU','SDU_'+model_name+'_'+str(Epochs)+'.h5')
model.save(model_save)


 #Asynchronous  database operation

import asyncio
import asyncpg

async def connect_to_database():
    connection = await asyncpg.connect(
        host='localhost',
        database='shivam',
        user='postgres',
        password='',    #yaha apka pswrd daliyeeeeeeeeeeeeeeeeeeeeeeeeeeeee
        port=5432
    )
    return connection

async def create_table(connection):
    # Example query to create a table
    create_table_query = """
    CREATE TABLE IF NOT EXISTS users (
        id serial PRIMARY KEY,
        username VARCHAR(50) UNIQUE NOT NULL,
        email VARCHAR(100) UNIQUE NOT NULL
    )
    """
    await connection.execute(create_table_query)

async def insert_data(connection):
    insert_data_query = """
    INSERT INTO users (username, email) VALUES ($1, $2)
    """
    await connection.execute(insert_data_query, 'shivam', 'shivam@gmail.com')

async def fetch_data(connection):
    fetch_data_query = """
    SELECT * FROM users
    """
    result = await connection.fetch(fetch_data_query)
    print("Fetched data from the database:")
    for row in result:
        print(row)

async def main():
    try:
        connection = await connect_to_database()

        await create_table(connection)

        await insert_data(connection)

        await fetch_data(connection)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        await connection.close()

asyncio.run(main())