import numpy as np
import scipy
import scipy.sparse.linalg
import scipy.sparse as sparse
from scipy.linalg import expm
from copy import deepcopy

##################################################
#  auxiliary function for time evolution method  #
##################################################
def TEO_two_sites(MPO,t_interval):
    """
    #build the two sites operator
    """
    d = MPO[0].shape[2]
    D = MPO[0].shape[1]
    O = np.zeros((d**2,d**2))
    for i in range(D):
        O += np.kron(MPO[0][0,i,:,:],MPO[-1][i,0,:,:])
    #Build the two sites time evolution operator
    TEO = np.reshape(expm(-t_interval*O),(d,d,d,d))
    return TEO

def TE_two_sites(bonds,vertices,TEO,i,N,d,chi):
    """
      -+THETA+-
       |     |
       +-TEO-+
       |     |

    """
    #coarse grain
    theta = np.einsum("ij,jsk->isk",np.diag(bonds[(i-1)%N][:]),vertices[i][:,:,:])
    theta = np.einsum("isj,jk->isk",theta,np.diag(bonds[i][:]))
    theta = np.einsum("isj,jtk->istk",theta,vertices[(i+1)%N][:,:,:])
    theta = np.einsum("istj,jk->istk",theta,np.diag(bonds[(i+1)%N][:]))

    #multiple operator with wavefunction
    theta = np.einsum("istk,stuv->iuvk",theta,TEO)
    theta = np.reshape(theta,(chi*d,d*chi))

    #svd
    X,Y,Z = np.linalg.svd(theta)

    bonds[i][0:chi] = Y[0:chi]/np.sqrt(np.sum(Y[0:chi]**2))

    X = np.reshape(X[0:chi*d,0:chi],(chi,d,chi))
    vertices[i][:,:,:] = np.tensordot(np.diag(bonds[(i-1)%N][:]**(-1)),X,axes=(1,0))

    Z= np.reshape(Z[0:chi,0:d*chi],(chi,d,chi))
    vertices[(i+1)%N][:,:,:] = np.tensordot(Z,np.diag(bonds[(i+1)%N][:]**(-1)),axes=(2,0))

    return theta
###############################################
#  auxiliary function for variational method  #
###############################################
def OL_update(A, L, B):
    """
    tensor contraction from the left hand side
    +-    +--A-
    L' =  L  |
    +-    +--B-
    """
    Temp = np.einsum("sij,ik->sjk", A, L)
    L_prime = np.einsum("sjk,skl->jl", Temp, B)
    return L_prime

def OL(MPS1, MPS2, index):
    """

    """
    ## initial the left vacuum states
    L_dummy = np.zeros((1,1))
    L_dummy[0] = 1
    L = [L_dummy]
    #build L up to the left of given index
    for i in range(0,index,1):
        L.append(OL_update(MPS1[i], L[-1], MPS2[i]))
    return L

def OR_update(A, R, B):
    """
    tensor contraction from the right hand side
     -+     -A--+
      R' =   |  R
     -+     -B--+
    """
    Temp = np.einsum("sij,jl->sil", A, R)
    R_prime = np.einsum("sil,skl->ik", Temp, B)
    return R_prime

def OR(MPS1, MPS2, index):
    """
    """
    ## initial the right vacuum states
    R_dummy = np.zeros((1,1))
    R_dummy[-1] = 1
    R = [R_dummy]
    #build R up to the right of given index
    for i in range(len(MPS1)-1, index, -1):
        R.append(OR_update(MPS1[i], R[-1], MPS2[i]))
    return R

def overlap(MPS1,MPS2):
    """
    Function the evaluate the expectation value on tow given MPS
    <MPS1|MPS2>
    """
    return OL(MPS1,MPS2,len(MPS1))[-1]

def EL_update(W, A, L, B):
    """
    tensor contraction from the left hand side
    +-    +--A-
    |     |  |
    L' =  L--W-
    |     |  |
    +-    +--B-
    """
    Temp = np.einsum("sij,aik->sajk", A, L)
    Temp = np.einsum("sajk,abst->tbjk", Temp, W)
    L_prime = np.einsum("tbjk,tkl->bjl", Temp, B)
    return L_prime

def EL(MPS1, MPO, MPS2, index):
    """
    """
    ## initial the left vacuum states
    L_dummy = np.zeros((MPO[0].shape[0],1,1))
    L_dummy[0] = 1
    L = [L_dummy]
    #build L up to the left of given index
    for i in range(0,index,1):
        L.append(EL_update(MPO[i], MPS1[i], L[-1], MPS2[i]))
    return L

def ER_update(W, A, R, B):
    """
    tensor contraction from the right hand side
     -+     -A--+
      |      |  |
     -R' =  -W--R
      |      |  |
     -+     -B--+
    """
    Temp = np.einsum("sij,bjl->sbil", A, R)
    Temp = np.einsum("sbil,abst->tail", Temp, W)
    R_prime = np.einsum("tail,tkl->aik", Temp, B)
    return R_prime

def ER(MPS1, MPO, MPS2, index):
    """
    """
    ## initial the right vacuum states
    R_dummy = np.zeros((MPO[-1].shape[1],1,1))
    R_dummy[-1] = 1
    R = [R_dummy]
    #build R up to the right of given index
    for i in range(len(MPO)-1, index, -1):
        R.append(ER_update(MPO[i], MPS1[i], R[-1], MPS2[i]))
    return R

def expectation(MPS1, MPO, MPS2):
    """
    Function the evaluate the expectation value of an MPO on a given MPS
    <MPS1|MPO|MPS2>
    """
    return EL(MPS1,MPO,MPS2,len(MPO))[-1]

def Energy(MPS,MPO):
    """
    Function the evaluate the energy
             <MPS|MPO|MPS>
    Energy = ---------------
               <MPS|MPS>
    """
    E = expectation(MPS,MPO,MPS)
    O = overlap(MPS,MPS)
    return np.asscalar(E/O)

class HamiltonianMultiply(sparse.linalg.LinearOperator):
    """
    Functor to evaluate the Hamiltonian matrix-vector multiply
           +--A--+
           |  |  |
    -M- =  L--W--R
     |     |  |  |
           +-   -+
    """
    def __init__(self, L, W, R):
        self.L = L
        self.W = W
        self.R = R
        self.dtype = np.dtype('d')
        self.req_shape = [W.shape[2], L.shape[1], R.shape[2]]
        self.size = self.req_shape[0]*self.req_shape[1]*self.req_shape[2]
        self.shape = [self.size, self.size]

    def _matvec(self, A):
        M = np.einsum("aij,sik->ajsk", self.L, np.reshape(A, self.req_shape))
        M = np.einsum("ajsk,abst->bjtk", M, self.W)
        M = np.einsum("bjtk,bkl->tjl", M, self.R)
        return M

def coarse_grain_MPO(W, X):
    """
    2-1 coarse-graining of two site MPO into one site
     |     |  |
    -R- = -W--X-
     |     |  |
    """
    return np.reshape(np.einsum("abst,bcuv->acsutv",W,X),
                      [W.shape[0], X.shape[1],
                       W.shape[2]*X.shape[2],
                       W.shape[3]*X.shape[3]])

def product_W(W, X):
    """
    'vertical' product of MPO W-matrices
           |
     |    -W-
    -R- =  |
     |    -X-
           |
    """
    return np.reshape(np.einsum("abst,cdtu->acbdsu", W, X), [W.shape[0]*X.shape[0],
                                                             W.shape[1]*X.shape[1],
                                                             W.shape[2],X.shape[3]])

def product_MPO(M1, M2):
    assert len(M1) == len(M2)
    Result = []
    for i in range(0, len(M1)):
        Result.append(product_W(M1[i], M2[i]))
    return Result

def coarse_grain_MPS(A,B):
    """
    2-1 coarse-graining of two-site MPS into one site
      |     |  |
     -R- = -A--B-
    """
    return np.reshape(np.einsum("sij,tjk->stik",A,B),
                      [A.shape[0]*B.shape[0], A.shape[1], B.shape[2]])

def fine_grain_MPS(A, dims):
    assert A.shape[0] == dims[0] * dims[1]
    Theta = np.transpose(np.reshape(A, dims + [A.shape[1], A.shape[2]]),
                         (0,2,1,3))
    M = np.reshape(Theta, (dims[0]*A.shape[1], dims[1]*A.shape[2]))
    U, S, V = np.linalg.svd(M, full_matrices=0)
    U = np.reshape(U, (dims[0], A.shape[1], -1))
    V = np.transpose(np.reshape(V, (-1, dims[1], A.shape[2])), (1,0,2))
    return U, S, V

def truncate_SVD(U, S, V, m):
    """
    # truncate the matrices from an SVD to at most m states
    """
    m = min(len(S), m)
    trunc = np.sum(S[m:])
    S = S[0:m]
    U = U[:,:,0:m]
    V = V[:,0:m,:]
    return U,S,V,trunc,m

def optimize_one_site(A, B, W, E, F, dir):
    """
    optimize a single site given the MPO matrix W, and tensors E,F
    """
    H = HamiltonianMultiply(E,W,F)
    E,V = sparse.linalg.eigsh(H,1,v0=A,which='SA', tol=1E-8)
    A = np.reshape(V[:,0], H.req_shape)
    if (dir == 'right'):
        M = np.reshape(A,(H.req_shape[1],H.req_shape[0]*H.req_shape[2]))
        U,S,V = np.linalg.svd(M, full_matrices=0)
        A = np.reshape(V, [H.req_shape[1],H.req_shape[0],H.req_shape[2]])
        A = np.transpose(A,(1,0,2))
        US = np.einsum("ij,jk->ik", U, np.diag(S))
        B = np.einsum("sij,jk->sik", B, US)
    elif (dir == 'left'):
        M = np.reshape(A,(H.req_shape[0]*H.req_shape[1],H.req_shape[2]))
        U,S,V = np.linalg.svd(M, full_matrices=0)
        A = np.reshape(U, H.req_shape)
        SV = np.einsum("ij,jk->ik", np.diag(S),V)
        B = np.einsum("ij,sjk->sik", SV, B)
    return E[0], A, B

def optimize_two_sites(A, B, W1, W2, E, F, m, dir):
    """
    two-site optimization of MPS A,B with respect to MPO W1,W2 and
    environment tensors E,F
    dir = 'left' or 'right' for a left-moving or right-moving sweep
    """
    W = coarse_grain_MPO(W1,W2)
    AA = coarse_grain_MPS(A,B)
    H = HamiltonianMultiply(E,W,F)
    E,V = sparse.linalg.eigsh(H,1,v0=AA,which='SA')
    AA = np.reshape(V[:,0], H.req_shape)
    A,S,B = fine_grain_MPS(AA, [A.shape[0], B.shape[0]])
    A,S,B,trunc,m = truncate_SVD(A,S,B,m)
    if (dir == 'left'):
        B = np.einsum("ij,sjk->sik", np.diag(S), B)
    else:
        assert dir == 'right'
        A = np.einsum("sij,jk->sik", A, np.diag(S))
    return E[0], A, B, trunc, m

#############################################
#  auxiliary function for projected method  #
#############################################
def Mu(configuration):
    d =2
    D = 3
    N = len(configuration)
    vertices = []
    vertices.append(np.zeros((d,1,D)))
    for i in range(N-2):
        vertices.append(np.zeros((d,D,D)))
    vertices.append(np.zeros((d,D,1)))
    for index,content in enumerate(configuration):
        vertices[index][content][0][0] = 1
    return vertices

def d_overlap(MPS1,MPS2,index):
    """
    Functor to evaluate the Hamiltonian matrix-vector multiply

    -M-     +--A--+
     |   =  L  |  R
            +-   -+
    """
    L = OL(MPS1, MPS2, index)[-1]
    R = OR(MPS1, MPS2, index)[-1]
    A = MPS1[index]
    M = np.einsum("ij,sik->sjk", L, A)
    M = np.einsum("sjk,kl->sjl", M, R)
    return M

def d_expectation(MPS1,MPO,MPS2,index):
    """
    Functor to evaluate the Hamiltonian matrix-vector multiply
           +--A--+
           |  |  |
    -M- =  L--W--R
     |     |  |  |
           +-   -+
    """
    L = EL(MPS1, MPO, MPS2, index)[-1]
    R = ER(MPS1, MPO, MPS2, index)[-1]
    A = MPS1[index]
    W = MPO[index]
    M = np.einsum("aij,sik->ajsk", L, A)
    M = np.einsum("ajsk,abst->bjtk", M, W)
    M = np.einsum("bjtk,bkl->tjl", M, R)
    return M

def f_mu(mu,MPO,MPS):
    """
    +-+-i-+-+
    | |   | |    +-+-i-+-+
    O-O---O-O - E| |   | |
    | |   | |    +-+MPS+-+
    +-+MPS+-+

    """
    Exp = expectation(mu,MPO,MPS)
    E = Energy(MPS,MPO)
    Over = overlap(mu,MPS)
    B = Exp-E*Over
    return np.asscalar(B)

def D_f_mu(mu,MPO,MPS,i):
    """
    i: the index of configuration
    j: the index of A_i
    """
    D_exp = d_expectation(mu,MPO,MPS,i)
    E = Energy(MPS,MPO)
    D_over = d_overlap(mu,MPS,i)
    C = D_exp-E*D_over
    return C

def Linear_Equation(configurations,MPO,MPS):
    M = len(configurations)
    N = len(MPS)
    Jacobian = np.zeros([M,N],dtype=object)
    g = np.zeros([M,1])
    for i,configuration in enumerate(configurations):
        mu = Mu(configuration)
        g[i] = f_mu(mu,MPO,MPS)
        for j,A in enumerate(MPS):
            Jacobian[i][j] = D_f_mu(mu,MPO,MPS,j)
    return Jacobian,g

def Jacobian_ravel(Jacobian):
    Matrix = []
    shape = []
    for i in range(Jacobian.shape[1]):
        shape.append(Jacobian[0][i].shape)

    for i in range(Jacobian.shape[0]):
        tmp = []
        for j in range(Jacobian.shape[1]):
            tmp.extend(Jacobian[i][j].ravel())
        Matrix.append(tmp)
    return np.array(Matrix),shape

def Jacobian_fold(Jacobian_ravel,shape):
    Jacobian = []
    for i in range(Jacobian_ravel.shape[0]):
        index = 0
        for j in shape:
            A = np.reshape(Jacobian_ravel[i][index:index+np.prod(j)],j)
            Jacobian.append(np.array(A))
            index +=np.prod(j)
    return Jacobian

def MPS_ravel(MPS):
    vector = []
    shape = []
    for i in range(len(MPS)):
        shape.append(MPS[i].shape)
    for i in range(len(MPS)):
        vector.extend(MPS[i].ravel())
    MPS = np.array(vector)[:,None]
    return MPS,shape

def MPS_fold(MPS_ravel,shape):
    MPS = []
    index = 0
    for i,S in enumerate(shape):
        A = np.reshape(MPS_ravel[index:index+np.prod(S)],S)
        MPS.append(np.array(A))
        index +=np.prod(S)
    return MPS

def pmps_step(configurations,MPO,MPS):
    Jacobian,g = Linear_Equation(configurations,MPO,MPS)
    Jacobian = Jacobian_ravel(Jacobian)[0]
    Jacobian_pinv = np.linalg.pinv(Jacobian)
    step = np.dot(Jacobian_pinv,g)
    MPS,shape = MPS_ravel(MPS)
    MPS = MPS-step
    MPS = MPS_fold(MPS,shape)
    return MPS


#Import files
import sys
import serial
import SLMC601V17_RS485_COM_Frames as SLMC_Frames

#Determine determine which port was provided
PORT = sys.argv[1]

#Check that port provided...
#   contains ttyUSB
sizeOfPort = len(PORT)
sizeOfTTY = len("ttyUSB#")
subString = PORT[sizeOfPort-sizeOfTTY:sizeOfPort-1]
if(subString != "ttyUSB"):
    print("Error: Port is not expected USB-RS485")
#   is accessible
usbrs485 = serial.Serial(PORT,baudrate=115200)

#Sums
bytesReadCounter = 0
dataSum = 0

readState = "seekA8"
recvBytes = [0]

def parseBytes(numBytesToRead):

    global readState
    global bytesReadCounter
    global recvBytes

    #Create index
    index = 0

    #For each byte in buffer...
    for index in range(numBytesToRead):
        if(readState == "seekA8"):

                #Reset number of bytes read
                bytesReadCounter = 0

                #If read byte matches first byte of HST REQ frame...
                if(int.from_bytes(recvBytes[index],"little") == int("A8",16)):

                    #Advance valid request state machine
                    readState = "seek11";

        elif(readState == "seek11"):
                #If read byte matches second byte of HST REQ frame...
                if(int.from_bytes(recvBytes[index],"little") == int("11",16)):

                    #Advance valid request state machine
                    readState = "seekCmd";
                else:
                    readState = "badSequence";

        elif(readState == "seekCmd"):
                #If read byte is a valid reqest...
                if(int.from_bytes(recvBytes[index],"little") == int("01",16)):
                    readState = "readAAB"
                elif(int.from_bytes(recvBytes[index],"little") == int("02",16)):
                    readState = "readVTCP"
                elif(int.from_bytes(recvBytes[index],"little") == int("03",16)):
                    readState = "readCBR"
                else:
                    readState = "seekA8"
                    print("Bad Sequence")

        elif(readState == "readAAB"):
                SLMC_Frames.BMS_RET_AAB[3+bytesReadCounter] = int.from_bytes(recvBytes[index],"little")
                bytesReadCounter = bytesReadCounter + 1

                if(bytesReadCounter >= len(SLMC_Frames.BMS_RET_AAB)-3):
                    dataSum = sum(SLMC_Frames.BMS_RET_AAB)
                    if(dataSum & int("1111",2) == 0):
                        print(SLMC_Frames.BMS_RET_AAB)
                    else:
                        print("Bad CRC")
                    readState = "End"

        elif(readState == "readVTCP"):
                SLMC_Frames.BMS_RET_VTCP[3+bytesReadCounter] = int.from_bytes(recvBytes[index],"little");
                bytesReadCounter = bytesReadCounter + 1

                if(bytesReadCounter >= len(SLMC_Frames.BMS_RET_VTCP)-3):
                    dataSum = sum(SLMC_Frames.BMS_RET_VTCP)
                    if(dataSum & int("1111",2) == 0):
                        print(SLMC_Frames.BMS_RET_VTCP)
                    else:
                        print("Bad CRC")
                    readState = "End"

        elif(readState == "readCBR"):
                SLMC_Frames.BMS_RET_CBR[3+bytesReadCounter] = int.from_bytes(recvBytes[index],"little")
                bytesReadCounter = bytesReadCounter + 1

                if(bytesReadCounter >= len(SLMC_Frames.BMS_RET_CBR)-3):
                    dataSum = sum(SLMC_Frames.BMS_RET_CBR)
                    if(dataSum & int("1111",2) == 0):
                        print(SLMC_Frames.BMS_RET_CBR)
                    else:
                        print("Bad CRC")
                    readState = "End"

#While command not completed or reset
while(readState != "End"):

    recvBytes[0] = usbrs485.read(1)

    parseBytes(1)


"""
Window function module
"""

import numpy as np
import lssps._lssps as c

def compute_grid3d(grid, *, pk_fac=None, shot_noise=None):
    """
    Compute 3D window function grid |W(k)|^2
    """

    if grid.mode == 'real-space':
        grid.fft()

    if grid.shifted and not grid.interlaced:
        grid.interlace()

    grid.correct_mas()

    #pk_fac = #nbar_mid*grid_rand.w2_sum/alpha
    #shot_noise = pk_fac*grid_rand.w2_sum

    if pk_fac is None:
        pk_fac = grid.pk_normalisation
    if shot_noise is None:
        shot_noise = grid.shot_noise

    g = grid[:]
    w2_grid = pk_fac*(g*np.conj(g)) - shot_noise

    return w2_grid

def bessel_transform(r, k, f, l):
    """
    Compute spherical-Bessel transform
      1/(2 pi^2) \int k^2 dk j_l(kr) f(k)

    Args:
      r (array): output r
      k (array): k of f(k)
      f (array): function f
      l (int):   degree of Bessel function j_l

    """
    result = np.empty_like(r)

    c._window_cquag_bessel_transform(r, k, f, l, result)

    return result


from flask import request
from flask_restx import Resource

from app.main.util.decorator import admin_token_required
from ..service.inventory_service import get_all_inventories, save_new_inventory, get_an_inventory, update_inventory, delete_inventory_method
from ..util.dto import InventoryDto

api = InventoryDto.api
inventory = InventoryDto.inventory
post_inventory = InventoryDto.post_inventory
put_inventory = InventoryDto.put_inventory

@api.route('/')
class InventoryList(Resource):
    @api.doc('list_of_inventories')
    @api.doc(params={'Authorization': {'in': 'header', 'description': 'An authorization token'}})
    @admin_token_required
    @api.marshal_list_with(inventory, envelope='data')
    def get(self):
        return get_all_inventories()

    @api.expect(post_inventory, validate=True)
    @api.response(201, 'Inventory successfully created.')
    @api.doc('create a new inventory')
    @api.doc(params={'Authorization': {'in': 'header', 'description': 'An authorization token'}})
    @admin_token_required
    def post(self):
        """Creates a new Inventory """
        data = request.json
        return save_new_inventory(data=data)

@api.route('/<id>')
@api.doc(params={'Authorization': {'in': 'header', 'description': 'An authorization token'}})
@api.param('id', 'Inventory identifier')
@api.response(404, 'Inventory not found.')
class Inventory(Resource):
    @api.doc('get an inventory')
    @admin_token_required
    @api.marshal_with(inventory)
    def get(self, id):
        """get an inventory given its identifier"""
        _inventory = get_an_inventory(id)
        if not _inventory:
            api.abort(404)
        else:
            return _inventory, 200

    @api.doc('update an inventory')
    @api.doc(params={'Authorization': {'in': 'header', 'description': 'An authorization token'}})
    @api.expect(put_inventory, validate=True)
    @api.response(200, 'Inventory successfully updated.')
    @admin_token_required
    def put(self, id):
        """Update an Inventory """
        _inventory = get_an_inventory(id)
        if not _inventory:
            api.abort(404)
        else:
            data = request.json
            data['id'] = id
            data['store_id'] = _inventory.store_id
            return update_inventory(data=data)

    @api.doc('delete an inventory')
    @api.response(204, 'Inventory successfully deleted.')
    @api.doc(params={'Authorization': {'in': 'header', 'description': 'An authorization token'}})
    @admin_token_required
    def delete(self, id):
        """Delete an inventory given its identifier"""
        _invent = get_an_inventory(id)
        if not _invent:
            api.abort(404)
        else:
            return delete_inventory_method(_invent.id)


import pygame as pg

class Scoreboard:
    """Represents the score in game"""

    def __init__(self, game):
        """Initializes the properties of the scoreboard"""
        self.settings = game.settings
        self.screen = game.screen
        self.screen_rect = self.screen.get_rect()

        self.text_color = (255, 255, 255)
        self.font = pg.font.SysFont('arial', 32)

        self.score_image = None
        self.label = None
        self.score_rect = None
        self.label_rect = None

        self.score = 0
        self.level = 0
        self.high_score = 0

        self.prep_score()

    def increment_score(self, alien_points):
        """Increments the score of the game"""
        self.score += alien_points
        self.prep_score()

    def prep_score(self):
        """Displays score in game"""
        self.label = self.font.render("Score:", True, self.text_color, pg.SRCALPHA)
        score_str = str(self.score)
        self.score_image = self.font.render(score_str, True, self.text_color, pg.SRCALPHA)

        # Display the score at the top right of the screen.
        self.score_rect = self.score_image.get_rect()
        self.label_rect = self.label.get_rect()
        self.score_rect.right = self.screen_rect.right - 20
        self.label_rect.right = self.screen_rect.right - 100
        self.score_rect.top = 20
        self.label_rect.top = 20

    def reset(self):
        """Resets the score of game to zero"""
        self.score = 0
        self.update()

    def update(self):
        """Calls draw() method of scoreboard"""
        self.draw()

    def draw(self):
        """Displays score text on screen"""
        self.screen.blit(self.label, self.label_rect)
        self.screen.blit(self.score_image, self.score_rect)


from .IngestorInterface import IngestorInterface
from .QuoteModel import QuoteModel
from typing import List

import subprocess
import os
import random

class PDFIngest(IngestorInterface):
    """Subclass of IngestorInterface specific for .docx files."""

    ingestMode =['pdf']

    @classmethod
    def parse(cls, path:str) -> List[QuoteModel]:
        """Returns a list of formated quote and author from a .pdf file.

        Subclass of IngestorInterface class.
        Will raise an exception if used for file type other than .pdf.
        Parameters: filepath (str)
        """

        if not cls.can_ingest(path):
            raise Exception('Cannot Ingest Error')

        quotes = []

        tmp_dir = random.randint(0,1000000000000)
        tmp_filename = random.randint(0,1000000000000)
        tmp_file = f'{os.getcwd()}/{tmp_dir}/{tmp_filename}.txt'
        os.mkdir(f'{tmp_dir}')

        call = subprocess.call(
            ['/Applications/xpdf-tools-mac-4.04/bin64/pdftotext',
            '-layout',
            path,
            tmp_file])

        f = open(tmp_file,'r')

        lines = f.readlines()
        for line in lines:
            if len(line.strip())>0:
                q = line.split('-')[0].strip('" ""\n\r').strip()
                a = line.split('-')[1].strip('" ""\n\r').strip()
                quotes.append(QuoteModel(q,a))

        f.close()
        os.remove(tmp_file)
        os.rmdir(f'{tmp_dir}')

        return(quotes)


def main():
    v = open('newOutput-LACounty.csv','r')
    c = v.read()
    v.close()
    w = open('join_blocks_coordinates.csv','r')
    d = w.read()
    w.close()
    c_list = d.split('\n') # list of coords for census bgs
    #print(c_list[-2])
    mod_list = c.split('\n') #job flow
    #print(mod_list[3])
    retStr =''
    inputx1='0'
    inputy1='0'
    inputx2='0'
    inputy2='0'
    #establish points to look at
    SET_BLOCKS = set()
    for a in c_list[1:-1]:
        ln_lst = a.split(',')
        SET_BLOCKS.add(ln_lst[4].strip('"')[:]) # add census block group

    for line in mod_list[1:-1]: #goes through each line in job flow and assigns coordintes
        # print(line)
        line_list = line.strip('\n').split(',')
        #print('t')
        if int(line_list[2]) < 1:
            continue
        elif line_list[0] not in SET_BLOCKS or line_list[1] not in SET_BLOCKS:
            continue
        if int(line_list[2]) > 0:
                #print('test')
            for a in c_list[1:-1]:
                    #print(a)
                ln_lst = a.split(',')
                    #print(ln_lst[4].strip('"')[1:])
                if int(ln_lst[4].strip('"')[:]) == int(line_list[0]):
                    print('match pt 1')
                    inputx1 = ln_lst[0]
                    inputy1 = ln_lst[1]
                elif int(ln_lst[4].strip('"')[:]) == int(line_list[1]):
                    print('match pt 2')
                    inputx2 = ln_lst[0]
                    inputy2 = ln_lst[1]
                #xy coordinate
                #print(line_list)
            lineString = '"LINESTRING('+inputx1+" "+inputy1+", "+inputx2+" "+inputy2+')"'
            line_list.append(lineString)
                #print('p')
            print(','.join(line_list) + '\n')
            retStr += ','.join(line_list) + '\n'
    print(retStr)
    return retStr

retStr = main()
print('t')
b = open('coord_output.csv','w')
b.write(retStr)
b.close()


# -*- coding: utf-8 -*-
__author__ = 'SinGle'
__date__ = '2020/06/26 14:39'

import re

from flask import current_app

from app.lib.Snapshot import Snapshot

def param_handler(params, action):
    if "SNAPSHOTNAME" not in params.keys() or re.search("[\\\\,./\\x20]", params["SNAPSHOTNAME"]):
        snapshot_name = None
    else:
        snapshot_name = params["SNAPSHOTNAME"]

    try:
        schema = re.findall('hdfs://(.*?)/', params["PATH"])[0]
    except IndexError as e:
        current_app.logger.error("IndexError: Failed to get schema from hdfs path! {}".format(e))

    param_doc = {
        "user": params["USER"],
        "schema": schema,
        "path": params["PATH"],
        "snapshot_name": snapshot_name
    }
    if action in ("DIFFER", "RENAME"):
        try:
            param_doc["old_snapshot_name"] = params["OLDSNAPSHOTNAME"]
        except Exception as e:
            current_app.logger.info("OLDSNAPSHOTNAME was not provided!", e)
    if action == "RECOVER":
        try:
            param_doc["filename"] = params["FILENAME"]
        except Exception as e:
            current_app.logger.info("filename was not provided!", e)
    return param_doc

def snapshot_initializer(param_doc):
    snapshot = Snapshot(
        user=param_doc["user"],
        schema=param_doc["schema"],
        path=param_doc["path"],
        snapshot_name=param_doc["snapshot_name"]
    )
    return snapshot


from sys import stdout

class ProgressWriter:
    """
    A utility to show the progress of long processes. A common use case would
    be to initialize, then in the loop, call show_progress() with the index
    of the position in the loop, and then after the loop, call end_progress().
    """

    def __init__(self, prestring, total, should_show):
        """
        :param prestring {string}
        :param total {number}
        :param should_show {boolean}
        """
        self.prestring = prestring
        self.total = total
        self.should_show = should_show
        self.ix = 0

    def increment_progress(self):
        """
        Does nothing if self.should_show is False. Otherwise,
        Shows the progress with self.ix / self.total % complete, then
        increments self.ix by 1.

        Good to call at the begginning of each loop.
        """
        if not self.should_show:
            return
        percent = self.ix / float(self.total) * 100
        stdout.write('\r%s...%.2f%% Complete' % (self.prestring, percent))
        self.ix += 1

    def show_progress(self, count):
        """
        Does nothing if self.should_show is false. Otherwise prints the
        following string:

        {PRESTRING}...{PERCENT}% Complete

        where percent is 100 * count / self.total

        :post Sets self.ix = count
        """
        if not self.should_show:
            return
        self.ix = count
        percent = count / float(self.total) * 100
        stdout.write('\r%s...%.2f%% Complete' % (self.prestring, percent))

    def end_progress(self):
        """
        Does nothing if self.should_show is false. Otherwise prints the
        following string:

        {PRESTRING}...Done
        """
        if not self.should_show:
            return
        stdout.write('\r%s...Done\n' % self.prestring)


# debugged the program
import random

guess = ''
# added a tuple to use 'toss' variable as an index
glst = ('tails', 'heads')
# moved tuple from while statement to a variable
while guess not in glst:
	print('Guess the coin toss! Enter heads or tails:')
	guess = input()
toss = random.randint(0, 1) # 0 is tails, 1 is heads
# changed the condition
if glst[toss] == guess:
	print('You got it!')
else:
	print('Nope! Guess again!')
	# fixed typo
	guess = input()
	toss = random.randint(0, 1)
	# again, changed condition
	if glst[toss] == guess:
		print('You got it!')
	else:
		print('Nope. You are really bad at this game.')


import modules
from templates.quick_replies import add_quick_reply
from templates.text import TextTemplate
from templates.button import *

entities = {
    'type':None,
    'choice':None
}

def process(input, entities = None):
    print('process',input,entities)
    output = {}
    if entities['type'] == None:
        message = TextTemplate('嗨，我是土思機器人啦！\n想要我幫你檢查看看，你簽的租賃契約合理嗎？').get_message()
        entities['type'] = 'step1'
        entities['choice'] = True
        message = add_quick_reply(message, '好啊，拿出契約來檢查一下好了！', modules.generate_postback(input,entities))
        entities['choice'] = False
        message = add_quick_reply(message, '不想，我沒有租屋啦', modules.generate_postback(input,entities))

    elif entities['type'] == 'step1':
        entities['type'] = 'step2'
        if entities['choice'] == True:
            message = TextTemplate('開始囉！上面寫的押金是幾個月租金呢？').get_message()
            entities['choice'] = True
            message = add_quick_reply(message, '2個月以下', modules.generate_postback(input,entities))
            entities['choice'] = False
            message = add_quick_reply(message, '2個月以上', modules.generate_postback(input,entities))
        elif entities['choice'] == False:
            message = TextTemplate('那我們無話可說…').get_message()
            entities['choice'] = None

    elif entities['type'] == 'step2':
        entities['type'] = 'step3'
        if entities['choice'] == True:
            message = TextTemplate('太好了，押金最高不可以超過2個月房屋租金的總額。\n也建議要在合約上寫清楚退還時間與方式喔！\n\n下一題，契約裡的租金有寫清楚嗎？').get_message()
            entities['choice'] = True
            message = add_quick_reply(message, '有喔！', modules.generate_postback(input,entities))
            entities['choice'] = False
            message = add_quick_reply(message, '好像….沒有欸？!', modules.generate_postback(input,entities))
        elif entities['choice'] == False:
            message = TextTemplate('什麼?!你知道這樣其實已經超過法律規定的額度了嗎….').get_message()
            entities['choice'] = None

    elif entities['type'] == 'step3':
        entities['type'] = 'step4'
        if entities['choice'] == True:
            message = TextTemplate('讚喔！除了租金的金額外，也應該包括何時給付及付款方式。還有管理費、清潔費或其他費用，也應該盡量寫在合約中。\n\n再來，修繕的責任有寫清楚嗎？').get_message()
            entities['choice'] = True
            message = add_quick_reply(message, '寫得清清楚楚', modules.generate_postback(input,entities))
            entities['choice'] = False
            message = add_quick_reply(message, '疑?!怎麼沒看到…', modules.generate_postback(input,entities))
        elif entities['choice'] == False:
            message = TextTemplate('什麼?!你知道這樣有可能被多收錢嗎…').get_message()
            entities['choice'] = None

    elif entities['type'] == 'step4':
        entities['type'] = 'step5'
        if entities['choice'] == True:
            message = TextTemplate('喔喔喔喔！美賣喔~~~也建議在簽約時，依照實際狀況，逐一討論並載明於租約中，未來比較不會有爭執喔！            \n\n再來，上面有寫到不能報稅嗎？').get_message()
            entities['choice'] = True
            message = add_quick_reply(message, '沒有！', modules.generate_postback(input,entities))
            entities['choice'] = False
            message = add_quick_reply(message, '可…可惡！房東特別寫下來了啦…', modules.generate_postback(input,entities))
        elif entities['choice'] == False:
            message = TextTemplate('什麼?!你知道這樣有可能被多收錢嗎…').get_message()
            entities['choice'] = None

    elif entities['type'] == 'step5':
        entities['type'] = 'step6'
        if entities['choice'] == True:
            message = TextTemplate('太厲害了，恭喜你完成租約的考驗！你的租賃契約寫得很不錯，要記得確保契約內容，權利才會有保障喔！').get_message()
            entities['choice'] = None
        elif entities['choice'] == False:
            message = TextTemplate('什麼?!你知道房東這樣其實是違法的嗎….').get_message()
            entities['choice'] = None

    elif entities['type'] == 'end':
        template = TextTemplate()
        template.set_text('更多詳細內容請看我們整理的懶人包：今天要簽約？教你看到租約一眼就抓到重點')
        text = template.get_text()
        template = ButtonTemplate(text)
        #message = TextTemplate('更多詳細內容請看我們整理的懶人包：今天要簽約？教你看到租約一眼就抓到重點').get_message()
        link = 'https://www.facebook.com/LandToast'
        #template = ButtonTemplate(message)
        template.add_web_url('傳送門', link)
        output['input'] = input
        output['output'] = template.get_message()
        output['success'] = True
        return output

    else:
        output['success'] = False
        return output

    if entities['choice'] == None:
        entities['type'] = None
        message = add_quick_reply(message, '再試一次!',
                                  modules.generate_postback(input,entities))
        entities['type'] = 'end'
        message = add_quick_reply(message, '結束對話',
                                  modules.generate_postback(input,entities))

    output['input'] = input
    output['output'] = message
    output['success'] = True

    return output


import rospy, sys, tf
import moveit_commander
from math import *
from geometry_msgs.msg import PoseStamped
from moveit_commander import MoveGroupCommander, PlanningSceneInterface
from moveit_msgs.msg import PlanningScene, ObjectColor
from moveit_msgs.msg import Grasp, GripperTranslation
from moveit_msgs.msg import MoveItErrorCodes
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
from tf.transformations import quaternion_from_euler
from copy import deepcopy

GROUP_NAME_ARM = 'arm'
GROUP_NAME_GRIPPER = 'gripper'

GRIPPER_FRAME = 'gripper_link'
GRIPPER_JOINT_NAMES = ['gripper_joint']
GRIPPER_EFFORT = [1.0]
GRIPPER_PARAM = '/gripper_controller'

REFERENCE_FRAME = '/base_link'
ARM_BASE_FRAME = '/arm_base_link'

class MoveItDemo:
    def __init__(self):
        # Initialize the move_group API
        moveit_commander.roscpp_initialize(sys.argv)

        rospy.init_node('moveit_demo')

        self.gripper_opened = [rospy.get_param(GRIPPER_PARAM + "/max_opening") ]
        self.gripper_closed = [rospy.get_param(GRIPPER_PARAM + "/min_opening") ]
        self.gripper_neutral = [rospy.get_param(GRIPPER_PARAM + "/neutral") ]

        self.gripper_tighten = rospy.get_param(GRIPPER_PARAM + "/tighten")

        # We need a tf listener to convert poses into arm reference base
        self.tf_listener = tf.TransformListener()

        # Use the planning scene object to add or remove objects
        scene = PlanningSceneInterface()

        # Create a scene publisher to push changes to the scene
        self.scene_pub = rospy.Publisher('planning_scene', PlanningScene, queue_size=10)

        # Create a publisher for displaying gripper poses
        self.gripper_pose_pub = rospy.Publisher('target_pose', PoseStamped, queue_size=10)

        # Create a dictionary to hold object colors
        self.colors = dict()

        # Initialize the move group for the right arm
        arm = MoveGroupCommander(GROUP_NAME_ARM)

        # Initialize the move group for the right gripper
        gripper = MoveGroupCommander(GROUP_NAME_GRIPPER)

        # Get the name of the end-effector link
        end_effector_link = arm.get_end_effector_link()

        # Allow some leeway in position (meters) and orientation (radians)
        arm.set_goal_position_tolerance(0.04)
        arm.set_goal_orientation_tolerance(0.1)

        # Allow replanning to increase the odds of a solution
        arm.allow_replanning(True)

        # Set the right arm reference frame
        arm.set_pose_reference_frame(REFERENCE_FRAME)

        # Allow 5 seconds per planning attempt
        arm.set_planning_time(5)

        # Set a limit on the number of pick attempts before bailing
        max_pick_attempts = 3

        # Set a limit on the number of place attempts
        max_place_attempts = 3
        rospy.loginfo("Scaling for MoveIt timeout=" + str(rospy.get_param('/move_group/trajectory_execution/allowed_execution_duration_scaling')))

        # Give the scene a chance to catch up
        rospy.sleep(2)

        # Give each of the scene objects a unique name
        table_id = 'table'
        box1_id = 'box1'
        box2_id = 'box2'
        target_id = 'target'
        tool_id = 'tool'

        # Remove leftover objects from a previous run
        scene.remove_world_object(table_id)
        scene.remove_world_object(box1_id)
        scene.remove_world_object(box2_id)
        scene.remove_world_object(target_id)
        scene.remove_world_object(tool_id)

        # Remove any attached objects from a previous session
        scene.remove_attached_object(GRIPPER_FRAME, target_id)

        # Give the scene a chance to catch up
        rospy.sleep(1)

        # Start the arm in the "arm_up" pose stored in the SRDF file
        rospy.loginfo("Set Arm: right_up")
        arm.set_named_target('right_up')
        if arm.go() != True:
            rospy.logwarn("  Go failed")
        rospy.sleep(2)

        # Move the gripper to the closed position
        rospy.loginfo("Set Gripper: Close " + str(self.gripper_closed ) )
        gripper.set_joint_value_target(self.gripper_closed)
        if gripper.go() != True:
            rospy.logwarn("  Go failed")
        rospy.sleep(2)

        # Move the gripper to the neutral position
        rospy.loginfo("Set Gripper: Neutral " + str(self.gripper_neutral) )
        gripper.set_joint_value_target(self.gripper_neutral)
        if gripper.go() != True:
            rospy.logwarn("  Go failed")
        rospy.sleep(2)

        # Move the gripper to the open position
        rospy.loginfo("Set Gripper: Open " +  str(self.gripper_opened))
        gripper.set_joint_value_target(self.gripper_opened)
        if gripper.go() != True:
            rospy.logwarn("  Go failed")
        rospy.sleep(2)

        # Set the height of the table off the ground
        table_ground = 0.4

        # Set the dimensions of the scene objects [l, w, h]
        table_size = [0.2, 0.7, 0.01]
        box1_size = [0.1, 0.05, 0.05]
        box2_size = [0.05, 0.05, 0.15]

        # Set the target size [l, w, h]
        target_size = [0.02, 0.005, 0.12]

        # Add a table top and two boxes to the scene
        table_pose = PoseStamped()
        table_pose.header.frame_id = REFERENCE_FRAME
        table_pose.pose.position.x = 0.36
        table_pose.pose.position.y = 0.0
        table_pose.pose.position.z = table_ground + table_size[2] / 2.0
        table_pose.pose.orientation.w = 1.0
        scene.add_box(table_id, table_pose, table_size)

        box1_pose = PoseStamped()
        box1_pose.header.frame_id = REFERENCE_FRAME
        box1_pose.pose.position.x = table_pose.pose.position.x - 0.04
        box1_pose.pose.position.y = 0.0
        box1_pose.pose.position.z = table_ground + table_size[2] + box1_size[2] / 2.0
        box1_pose.pose.orientation.w = 1.0
        scene.add_box(box1_id, box1_pose, box1_size)

        box2_pose = PoseStamped()
        box2_pose.header.frame_id = REFERENCE_FRAME
        box2_pose.pose.position.x = table_pose.pose.position.x - 0.06
        box2_pose.pose.position.y = 0.2
        box2_pose.pose.position.z = table_ground + table_size[2] + box2_size[2] / 2.0
        box2_pose.pose.orientation.w = 1.0
        scene.add_box(box2_id, box2_pose, box2_size)

        # Set the target pose in between the boxes and on the table
        target_pose = PoseStamped()
        target_pose.header.frame_id = REFERENCE_FRAME
        target_pose.pose.position.x = table_pose.pose.position.x - 0.03
        target_pose.pose.position.y = 0.1
        target_pose.pose.position.z = table_ground + table_size[2] + target_size[2] / 2.0
        target_pose.pose.orientation.w = 1.0

        # Add the target object to the scene
        scene.add_box(target_id, target_pose, target_size)

        # Make the table red and the boxes orange
        self.setColor(table_id, 0.8, 0, 0, 1.0)
        self.setColor(box1_id, 0.8, 0.4, 0, 1.0)
        self.setColor(box2_id, 0.8, 0.4, 0, 1.0)

        # Make the target yellow
        self.setColor(target_id, 0.9, 0.9, 0, 1.0)

        # Send the colors to the planning scene
        self.sendColors()

        # Set the support surface name to the table object
        arm.set_support_surface_name(table_id)

        # Specify a pose to place the target after being picked up
        place_pose = PoseStamped()
        place_pose.header.frame_id = REFERENCE_FRAME
        place_pose.pose.position.x = table_pose.pose.position.x - 0.03
        place_pose.pose.position.y = -0.15
        place_pose.pose.position.z = table_ground + table_size[2] + target_size[2] / 2.0
        place_pose.pose.orientation.w = 1.0

        # Initialize the grasp pose to the target pose
        grasp_pose = target_pose

        # Shift the grasp pose by half the width of the target to center it
        grasp_pose.pose.position.y -= target_size[1] / 2.0

        # Generate a list of grasps
        grasps = self.make_grasps(grasp_pose, [target_id], [target_size[1] - self.gripper_tighten])

        # Track success/failure and number of attempts for pick operation
        result = MoveItErrorCodes.FAILURE
        n_attempts = 0

        # Repeat until we succeed or run out of attempts
        while result != MoveItErrorCodes.SUCCESS and n_attempts < max_pick_attempts:
            rospy.loginfo("Pick attempt #" + str(n_attempts))
            for grasp in grasps:
                # Publish the grasp poses so they can be viewed in RViz
                self.gripper_pose_pub.publish(grasp.grasp_pose)
                rospy.sleep(0.2)

                result = arm.pick(target_id, grasps)
                if result == MoveItErrorCodes.SUCCESS:
                    break

            n_attempts += 1
            rospy.sleep(0.2)

        # If the pick was successful, attempt the place operation
        if result == MoveItErrorCodes.SUCCESS:
            rospy.loginfo("  Pick: Done!")
            # Generate valid place poses
            places = self.make_places(place_pose)

            success = False
            n_attempts = 0

            # Repeat until we succeed or run out of attempts
            while not success and n_attempts < max_place_attempts:
                rospy.loginfo("Place attempt #" + str(n_attempts))
                for place in places:
                    # Publish the place poses so they can be viewed in RViz
                    self.gripper_pose_pub.publish(place)
                    rospy.sleep(0.2)

                    success = arm.place(target_id, place)
                    if success:
                        break

                n_attempts += 1
                rospy.sleep(0.2)

            if not success:
                rospy.logerr("Place operation failed after " + str(n_attempts) + " attempts.")
            else:
                rospy.loginfo("  Place: Done!")
        else:
            rospy.logerr("Pick operation failed after " + str(n_attempts) + " attempts.")

        # Return the arm to the "resting" pose stored in the SRDF file (passing through right_up)
        arm.set_named_target('right_up')
        arm.go()

        arm.set_named_target('resting')
        arm.go()

        # Open the gripper to the neutral position
        gripper.set_joint_value_target(self.gripper_neutral)
        gripper.go()

        rospy.sleep(1)

        # Shut down MoveIt cleanly
        moveit_commander.roscpp_shutdown()

        # Exit the script
        moveit_commander.os._exit(0)

    # Get the gripper posture as a JointTrajectory
    def make_gripper_posture(self, joint_positions):
        # Initialize the joint trajectory for the gripper joints
        t = JointTrajectory()

        # Set the joint names to the gripper joint names
        t.joint_names = GRIPPER_JOINT_NAMES

        # Initialize a joint trajectory point to represent the goal
        tp = JointTrajectoryPoint()

        # Assign the trajectory joint positions to the input positions
        tp.positions = joint_positions

        # Set the gripper effort
        tp.effort = GRIPPER_EFFORT

        tp.time_from_start = rospy.Duration(1.0)

        # Append the goal point to the trajectory points
        t.points.append(tp)

        # Return the joint trajectory
        return t

    # Generate a gripper translation in the direction given by vector
    def make_gripper_translation(self, min_dist, desired, vector):
        # Initialize the gripper translation object
        g = GripperTranslation()

        # Set the direction vector components to the input
        g.direction.vector.x = vector[0]
        g.direction.vector.y = vector[1]
        g.direction.vector.z = vector[2]

        # The vector is relative to the gripper frame
        g.direction.header.frame_id = GRIPPER_FRAME

        # Assign the min and desired distances from the input
        g.min_distance = min_dist
        g.desired_distance = desired

        return g

    # Generate a list of possible grasps
    def make_grasps(self, initial_pose_stamped, allowed_touch_objects, grasp_opening=[0]):
        # Initialize the grasp object
        g = Grasp()

        # Set the pre-grasp and grasp postures appropriately;
        # grasp_opening should be a bit smaller than target width
        g.pre_grasp_posture = self.make_gripper_posture(self.gripper_opened)
        g.grasp_posture = self.make_gripper_posture(grasp_opening)

        # Set the approach and retreat parameters as desired
        g.pre_grasp_approach = self.make_gripper_translation(0.01, 0.1, [1.0, 0.0, 0.0])
        g.post_grasp_retreat = self.make_gripper_translation(0.1, 0.15, [0.0, -1.0, 1.0])

        # Set the first grasp pose to the input pose
        g.grasp_pose = initial_pose_stamped

        # Pitch angles to try
        pitch_vals = [0, 0.1, -0.1, 0.2, -0.2, 0.4, -0.4]

        # Yaw angles to try; given the limited dofs of turtlebot_arm, we must calculate the heading
        # from arm base to the object to pick (first we must transform its pose to arm base frame)
        target_pose_arm_ref = self.tf_listener.transformPose(ARM_BASE_FRAME, initial_pose_stamped)
        x = target_pose_arm_ref.pose.position.x
        y = target_pose_arm_ref.pose.position.y

        self.pick_yaw = atan2(y, x)   # check in make_places method why we store the calculated yaw
        yaw_vals = [self.pick_yaw]

        # A list to hold the grasps
        grasps = []

        # Generate a grasp for each pitch and yaw angle
        for yaw in yaw_vals:
            for pitch in pitch_vals:
                # Create a quaternion from the Euler angles
                q = quaternion_from_euler(0, pitch, yaw)

                # Set the grasp pose orientation accordingly
                g.grasp_pose.pose.orientation.x = q[0]
                g.grasp_pose.pose.orientation.y = q[1]
                g.grasp_pose.pose.orientation.z = q[2]
                g.grasp_pose.pose.orientation.w = q[3]

                # Set and id for this grasp (simply needs to be unique)
                g.id = str(len(grasps))

                # Set the allowed touch objects to the input list
                g.allowed_touch_objects = allowed_touch_objects

                # Don't restrict contact force
                g.max_contact_force = 0

                # Degrade grasp quality for increasing pitch angles
                g.grasp_quality = 1.0 - abs(pitch)

                # Append the grasp to the list
                grasps.append(deepcopy(g))

        # Return the list
        return grasps

    # Generate a list of possible place poses
    def make_places(self, init_pose):
        # Initialize the place location as a PoseStamped message
        place = PoseStamped()

        # Start with the input place pose
        place = init_pose

        # A list of x shifts (meters) to try
        x_vals = [0, 0.005, -0.005] #, 0.01, -0.01, 0.015, -0.015]

        # A list of y shifts (meters) to try
        y_vals = [0, 0.005, -0.005, 0.01, -0.01] #, 0.015, -0.015]

        # A list of pitch angles to try
        pitch_vals = [0] #, 0.005, -0.005, 0.01, -0.01, 0.02, -0.02]

        # A list to hold the places
        places = []

        # Generate a place pose for each angle and translation
        for pitch in pitch_vals:
            for dy in y_vals:
                for dx in x_vals:
                    place.pose.position.x = init_pose.pose.position.x + dx
                    place.pose.position.y = init_pose.pose.position.y + dy

                    # Yaw angle: given the limited dofs of turtlebot_arm, we must calculate the heading from
                    # arm base to the place location (first we must transform its pose to arm base frame)
                    target_pose_arm_ref = self.tf_listener.transformPose(ARM_BASE_FRAME, place)
                    x = target_pose_arm_ref.pose.position.x
                    y = target_pose_arm_ref.pose.position.y
                    yaw = atan2(y, x) - self.pick_yaw;
                    # Note that we subtract the yaw we calculated for pick, as the picked object "carries"
                    # with him the orientation of the arm at pickup time. More details in this moveit-users
                    # group thread:  https://groups.google.com/forum/#!topic/moveit-users/-Eie-wLDbu0

                    # Create a quaternion from the Euler angles
                    q = quaternion_from_euler(0, pitch, yaw)

                    # Set the place pose orientation accordingly
                    place.pose.orientation.x = q[0]
                    place.pose.orientation.y = q[1]
                    place.pose.orientation.z = q[2]
                    place.pose.orientation.w = q[3]

                    # Append this place pose to the list
                    places.append(deepcopy(place))

        # Return the list
        return places

    # Set the color of an object
    def setColor(self, name, r, g, b, a=0.9):
        # Initialize a MoveIt color object
        color = ObjectColor()

        # Set the id to the name given as an argument
        color.id = name

        # Set the rgb and alpha values given as input
        color.color.r = r
        color.color.g = g
        color.color.b = b
        color.color.a = a

        # Update the global color dictionary
        self.colors[name] = color

    # Actually send the colors to MoveIt!
    def sendColors(self):
        # Initialize a planning scene object
        p = PlanningScene()

        # Need to publish a planning scene diff
        p.is_diff = True

        # Append the colors from the global color dictionary
        for color in self.colors.values():
            p.object_colors.append(color)

        # Publish the scene diff
        self.scene_pub.publish(p)

if __name__ == "__main__":
    MoveItDemo()


import asyncio
import os
import datetime
import discord
from discord import channel
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext, cog_ext
from discord_slash.utils.manage_commands import create_option, create_choice
from core.classes import CogExtension

class System(CogExtension):

    @cog_ext.cog_slash(  # ping: 偵測延遲毫秒
        name="ping", description="監測 Bot 和 Discord 之間的連線延遲。")
    async def ping(self, ctx: SlashContext):
        embed = discord.Embed(color=0x21e828, timestamp=datetime.datetime.utcnow())
        embed.set_author(name="MinatoBot",
                        icon_url="https://i.imgur.com/EvyjjO9.jpg")
        embed.add_field(name="Ping", value=f"**{round(self.bot.latency*1000)}** ms", inline=False)
        await ctx.send(embed=embed)

    @commands.command()  # bc: 指定頻道廣播
    async def bc1(self, ctx, ch: int, *, msg):
        channel = self.bot.get_channel(ch)
        await channel.send(f"{msg}")
        await ctx.send(f"在 {channel.mention} 廣播訊息成功。")

    @cog_ext.cog_slash(
        name="bc",
        description="在指定頻道進行廣播。",
        options=[
            create_option(
                name="channel",
                description="傳送訊息的頻道。",
                option_type=7,
                required=True
            ),
            create_option(
                name="message",
                description="訊息。",
                option_type=3,
                required=True
            )
        ]
    )
    async def bc(self, ctx: SlashContext, channel, message):
        await channel.send(f"{message}")
        await ctx.send(f"在 {channel.mention} 廣播訊息成功。")

    @commands.Cog.listener()  # こんあくあ～！
    async def on_message(self, msg):
        if msg.content.startswith("こんあくあ") and msg.author != self.bot.user:
            await msg.channel.send("こんあくあ～！")

def setup(bot):
    bot.add_cog(System(bot))


"""Program to List, Create, Add, Edit, Delete contacts and save to a JSON file"""

import json

class CreateContact:
    """"""

    def __init__(self, fname, lname, phone): #constructor
        self.fname = fname
        self.lname = lname
        self.phone = phone

    def create_new_contact(self):
        contact_data = {}
        contact_data['fname'] = self.fname
        contact_data['lname'] = self.lname
        contact_data['phone'] = self.phone
        print("new contact added")
        print(contact_data)
        print(type(contact_data))
        return contact_data
        # print("Details:", self.fname, self.lname, self.phone)

def create_contact():
    """Function to create a new contact and add to contacts list."""

    new_contact_list = []
    phone_number_list = []

    print("Enter Details")
    fname = input("Enter first name:")
    lname = input("Enter last name:")
    choice = input("Add number?(Y/N):")

    while choice == 'y' or choice == 'Y':

        number_type = input("Enter type: ")
        number = input("Enter phone number: ")

        contact_dict = {}
        contact_dict['type'] = number_type
        contact_dict['value'] = number
        phone_number_list.append(contact_dict)
        print("Contact added")
        choice = input("Add number?(Y/N):")

    new_contact = CreateContact(fname, lname, phone_number_list)
    new_contact_data = new_contact.create_new_contact()

    try:
        contact_file_object = open("contact.json", "r")
        data_list = contact_file_object.read()
        data_list = json.loads(data_list)

        contact_file_object.close()
        print(data_list)
    except:
        print("no data")
        data_list = []

    data_list.append(new_contact_data)
    print(data_list)

    return data_list # New contact data.

def main_contact_function():
    """Main function to display actions to be performed on contacts list.
    """
    try:
        contact_file_object = open("contact.json", "r")
        data_list = contact_file_object.read()
        data_list = json.loads(data_list)

        contact_file_object.close()
    except:
        print("no data")
        data_list = []

    print("Contacts App\n")

    choice = 0
    choice_list = [1, 2, 3, 4]
    new_contact_list = []

    while choice not in choice_list:
        print("Choose Action\n\t1.Create new contact\n\t2.List Contacts\n\t3.Edit a contact\n\t4.Delete Contact\n\t5.Search a contact\n\t6.Exit")
        choice = int(input("Enter option: "))
        print(f"Choice : {choice}")

        if choice == 1:
            print("1.Create Contact")
            new_contact_details = create_contact()
            print(new_contact_details)
            new_contact_list.append(new_contact_details)

            json_object = json.dumps(new_contact_list, indent = 4)
            print(json_object)

            # Writing to sample.json
            with open("contact.json", "w") as outfile:
                outfile.write(json_object)
            outfile.close()
            choice = 0

        elif choice == 2:
            contact_file_object = open("contact.json","r")
            data_list = contact_file_object.read()
            data_list = json.loads(data_list)
            contact_file_object.close()
            print("2.List Contacts")
            new_list = sorted(data_list, key=lambda item: item['fname'])
            print("data:")
            for i in new_list:
                print(f"\n{i['fname']} {i['lname']}\t", end="")
                for multiple_number in i['phone']:
                    print(f"{multiple_number['type']}-{multiple_number['value']}\t", end="\t")
            print()
            choice = 0

        elif choice == 3:
            print("3.Edit a contact")
            contact_file_object = open("contact.json","r")
            data_list = contact_file_object.read()
            data_list = json.loads(data_list)
            contact_file_object.close()
            user_input_fname = input("Enter the name of the contact you wish to edit: ")
            data = [item for item in data_list if item["fname"] == f"{user_input_fname}"][0]
            print(data)
            choice = input("Edit data?(Y\\N):")
            if choice == 'y' or choice == 'y':
                # data_list.remove(data)
                # if choice == 'y' or choice == 'y':
                    sub_choice_list = [1, 2, 3]
                    sub_choice = 0
                    sub_choice = int(input("Choose from 1.fname, 2.lname, 3.phone, 4.exit number to edit\n \
                    (choose: 1/2/3/4):"))
                    while sub_choice in sub_choice_list[:3]:
                        if sub_choice == 1:
                            data["fname"] = input("Enter first name")
                            temp_data = data
                            data_list.remove(temp_data)
                            data_list.append(data)
                            json_object = json.dumps(data_list, indent = 4)
                            with open("contact.json", "w") as outfile:
                                outfile.write(json_object)
                            outfile.close()

                        elif sub_choice == 2:
                            data["lname"] = input("Enter last name")
                            temp_data = data
                            data_list.remove(temp_data)
                            data_list.append(data)
                            json_object = json.dumps(data_list, indent = 4)
                            with open("contact.json", "w") as outfile:
                                outfile.write(json_object)
                            outfile.close()

                        elif sub_choice == 3:
                            temp_data = data
                            index = 1
                            print("type:")
                            for items in data:
                                number_type = [number_type for number_type in data['phone']]
                            for i in number_type:
                                print(index, ".", i)
                                index += 1
                            phone_type_choice = int(input("Choose number(by index):"))
                            print("index = ", phone_type_choice)
                            phone_type_choice -= 1

                            print("Edit or Delete")

                            try:
                                while phone_type_choice >= 0 and phone_type_choice < index:
                                    print("hello")
                                    phone_data = number_type[phone_type_choice]
                                    print("hello")
                                    print(phone_data)
                                    type_or_value = int(input("change 1.Type, 2.Number"))
                                    if type_or_value == 1:
                                        temp_phone_data = phone_data
                                        phone_data['type'] = input("Enter new type")
                                        number_type.remove(temp_phone_data)
                                        number_type.append(phone_data)
                                        print(data)
                                        data_list.remove(temp_data)
                                        data_list.append(data)
                                        json_object = json.dumps(data_list, indent = 4)
                                        with open("contact.json", "w") as outfile:
                                            outfile.write(json_object)
                                        outfile.close()
                                        break
                                    elif type_or_value == 2:
                                        temp_phone_data = phone_data
                                        phone_data['value'] = input("Enter new number")
                                        number_type.remove(temp_phone_data)
                                        number_type.append(phone_data)
                                        print(data)
                                        data_list.remove(temp_data)
                                        data_list.append(data)
                                        json_object = json.dumps(data_list, indent = 4)
                                        with open("contact.json", "w") as outfile:
                                            outfile.write(json_object)
                                        outfile.close()
                                        break
                            except IndexError:
                                print("No phone number found")

                        elif sub_choice not in sub_choice_list:
                            break
                        sub_choice = int(input("Choose from 1.fname, 2.lname, 3.phone,\
                             4.exit number to edit\n\
                    (choose: 1/2/3/4):"))

                    print("yes1")
            choice = 0

        elif choice == 4:
            print("DELETE")
            contact_file_object = open("contact.json","r")
            data_list = contact_file_object.read()
            data_list = json.loads(data_list)
            contact_file_object.close()
            print("Delete data by name:")
            user_input_fname = input()
            data = [item for item in data_list if item["fname"] == f"{user_input_fname}"][0]
            print(data)
            data_list.remove(data)
            print(data_list)
            json_object = json.dumps(data_list, indent = 4)
            print(json_object)

            # Writing to sample.json
            with open("contact.json", "w") as outfile:
                outfile.write(json_object)
            outfile.close()
            choice = 0

        # Contact Search.
        elif choice == 5:
            contact_file_object = open("contact.json","r")
            data_list = contact_file_object.read()
            data_list = json.loads(data_list)
            contact_file_object.close()
            print("Search data by name:")
            user_input_fname = input()
            data = [item for item in data_list if item["fname"] == f"{user_input_fname}"]
            print(data)
            choice = 0

        elif choice == 6:
            break

main_contact_function()


# External Packages
from fastapi import APIRouter
from fastapi import Request
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.templating import Jinja2Templates
from khoj.utils.rawconfig import TextContentConfig, OpenAIProcessorConfig, FullConfig

# Internal Packages
from khoj.utils import constants, state

import json

# Initialize Router
web_client = APIRouter()
templates = Jinja2Templates(directory=constants.web_directory)

VALID_TEXT_CONTENT_TYPES = ["org", "markdown", "pdf", "plaintext"]

# Create Routes
@web_client.get("/", response_class=FileResponse)
def index(request: Request):
    return templates.TemplateResponse("index.html", context={"request": request, "demo": state.demo})

@web_client.get("/chat", response_class=FileResponse)
def chat_page(request: Request):
    return templates.TemplateResponse("chat.html", context={"request": request, "demo": state.demo})

if not state.demo:

    @web_client.get("/config", response_class=HTMLResponse)
    def config_page(request: Request):
        default_full_config = FullConfig(
            content_type=None,
            search_type=None,
            processor=None,
        )
        current_config = state.config or json.loads(default_full_config.json())

        successfully_configured = {
            "pdf": False,
            "markdown": False,
            "org": False,
            "image": False,
            "github": False,
            "notion": False,
            "plaintext": False,
            "enable_offline_model": False,
            "conversation_openai": False,
            "conversation_gpt4all": False,
        }

        if state.content_index:
            successfully_configured.update(
                {
                    "pdf": state.content_index.pdf is not None,
                    "markdown": state.content_index.markdown is not None,
                    "org": state.content_index.org is not None,
                    "image": state.content_index.image is not None,
                    "github": state.content_index.github is not None,
                    "notion": state.content_index.notion is not None,
                    "plaintext": state.content_index.plaintext is not None,
                }
            )

        if state.processor_config and state.processor_config.conversation:
            successfully_configured.update(
                {
                    "conversation_openai": state.processor_config.conversation.openai_model is not None,
                    "conversation_gpt4all": state.processor_config.conversation.gpt4all_model.loaded_model is not None,
                }
            )

        return templates.TemplateResponse(
            "config.html",
            context={
                "request": request,
                "current_config": current_config,
                "current_model_state": successfully_configured,
            },
        )

    @web_client.get("/config/content_type/github", response_class=HTMLResponse)
    def github_config_page(request: Request):
        default_copy = constants.default_config.copy()
        default_github = default_copy["content-type"]["github"]  # type: ignore

        default_config = TextContentConfig(
            compressed_jsonl=default_github["compressed-jsonl"],
            embeddings_file=default_github["embeddings-file"],
        )

        current_config = (
            state.config.content_type.github
            if state.config and state.config.content_type and state.config.content_type.github
            else default_config
        )

        current_config = json.loads(current_config.json())

        return templates.TemplateResponse(
            "content_type_github_input.html", context={"request": request, "current_config": current_config}
        )

    @web_client.get("/config/content_type/notion", response_class=HTMLResponse)
    def notion_config_page(request: Request):
        default_copy = constants.default_config.copy()
        default_notion = default_copy["content-type"]["notion"]  # type: ignore

        default_config = TextContentConfig(
            compressed_jsonl=default_notion["compressed-jsonl"],
            embeddings_file=default_notion["embeddings-file"],
        )

        current_config = (
            state.config.content_type.notion
            if state.config and state.config.content_type and state.config.content_type.notion
            else default_config
        )

        current_config = json.loads(current_config.json())

        return templates.TemplateResponse(
            "content_type_notion_input.html", context={"request": request, "current_config": current_config}
        )

    @web_client.get("/config/content_type/{content_type}", response_class=HTMLResponse)
    def content_config_page(request: Request, content_type: str):
        if content_type not in VALID_TEXT_CONTENT_TYPES:
            return templates.TemplateResponse("config.html", context={"request": request})

        default_copy = constants.default_config.copy()
        default_content_type = default_copy["content-type"][content_type]  # type: ignore

        default_config = TextContentConfig(
            compressed_jsonl=default_content_type["compressed-jsonl"],
            embeddings_file=default_content_type["embeddings-file"],
        )

        current_config = (
            state.config.content_type[content_type]
            if state.config and state.config.content_type and state.config.content_type[content_type]  # type: ignore
            else default_config
        )
        current_config = json.loads(current_config.json())

        return templates.TemplateResponse(
            "content_type_input.html",
            context={
                "request": request,
                "current_config": current_config,
                "content_type": content_type,
            },
        )

    @web_client.get("/config/processor/conversation/openai", response_class=HTMLResponse)
    def conversation_processor_config_page(request: Request):
        default_copy = constants.default_config.copy()
        default_processor_config = default_copy["processor"]["conversation"]["openai"]  # type: ignore
        default_openai_config = OpenAIProcessorConfig(
            api_key="",
            chat_model=default_processor_config["chat-model"],
        )

        current_processor_openai_config = (
            state.config.processor.conversation.openai
            if state.config
            and state.config.processor
            and state.config.processor.conversation
            and state.config.processor.conversation.openai
            else default_openai_config
        )
        current_processor_openai_config = json.loads(current_processor_openai_config.json())

        return templates.TemplateResponse(
            "processor_conversation_input.html",
            context={
                "request": request,
                "current_config": current_processor_openai_config,
            },
        )


import unittest
import json
from unittest.mock import patch, mock_open

from models.club_model import Club
import repository.club as club_repo

class ClubRepoTest(unittest.TestCase):

    @patch("repository.club.filename_club", new='tests/test.json')
    def test_load_clubs_should_return_list_of_club_obj(self):
        with patch.object(Club, '__init__', return_value=None):
            outcome = club_repo.load_clubs()
            self.assertIsInstance(outcome, list)
            for c in outcome:
                self.assertIsInstance(c, Club)

    @patch("repository.club.get_clubs.all_clubs", new=[])
    @patch("repository.club.load_clubs")
    def test_get_clubs_should_call_load_clubs_if_all_club_var_is_empty_list(self, mock_load_clubs):
        club_repo.get_clubs()
        mock_load_clubs.assert_called_once()

    @patch("repository.club.get_clubs.all_clubs", new=[{'foo': 'bar'}])
    @patch("repository.club.load_clubs")
    def test_get_clubs_should_not_call_load_clubs_if_all_club_var_is_not_empty_list(self, mock_load_clubs):
        club_repo.get_clubs()
        mock_load_clubs.assert_not_called()

    @patch("repository.club.get_clubs.all_clubs", new=[{'foo': 'bar'}])
    def test_get_clubs_should_return_all_clubs_list(self):
        outcome = club_repo.get_clubs()
        self.assertEqual(outcome, [{'foo': 'bar'}])

    @patch("repository.club.load_clubs")
    def test_update_json_should_write_data_in_file(self, mock_load_clubs):
        m = mock_open()
        with patch("builtins.open", m, create=True):
            to_write = {'name': 'placeholder',
                        'points': '10',
                        'email': 'ex@plc.np'}
            club_repo.update_clubs_in_json(to_write)
            handle = m()
            handle.write.assert_called_once()

if __name__ == '__main__':
    unittest.main()


"""backend URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.1/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.urls import include
from django.urls import path
from rest_framework_nested import routers

from . import views

router = routers.SimpleRouter(trailing_slash=False)
router.register(r"sessions", views.SessionsViewSet)

sessions_router = routers.NestedSimpleRouter(router, r"sessions", lookup="session")
sessions_router.register(
    r"conflicts", views.SessionConflictsViewSet, basename="session-conflicts"
)
sessions_router.register(
    r"changes", views.SessionChangesViewSet, basename="session-changes"
)
sessions_router.register(
    r"deployments", views.SessionDeploymentsViewSet, basename="session-deployments"
)
sessions_router.register(
    r"files", views.SessionFilesViewSet, basename="session-files",
)
sessions_router.register(
    r"branches", views.SessionBranchesViewSet, basename="session-branches"
)
sessions_branches_router = routers.NestedSimpleRouter(
    sessions_router, r"branches", lookup="session_branch"
)
sessions_branches_router.register(
    r"files", views.SessionBranchesFilesViewSet, basename="session-branch-files"
)

urlpatterns = [
    path("", include(router.urls)),
    path("", include(sessions_router.urls)),
    path("", include(sessions_branches_router.urls)),
    path(r"supported_features", views.get_supported_features),
    path(r"supported_validators", views.get_supported_validators),
]


from delfin.api import common
from delfin.api import extensions
from delfin.api.v1 import access_info
from delfin.api.v1 import alert_source
from delfin.api.v1 import alerts
from delfin.api.v1 import controllers
from delfin.api.v1 import disks
from delfin.api.v1 import filesystems
from delfin.api.v1 import ports
from delfin.api.v1 import qtrees
from delfin.api.v1 import quotas
from delfin.api.v1 import shares
from delfin.api.v1 import storage_pools
from delfin.api.v1 import storages
from delfin.api.v1 import volumes
from delfin.api.v1 import storage_hosts
from delfin.api.v1 import storage_host_initiators
from delfin.api.v1 import storage_host_groups
from delfin.api.v1 import port_groups
from delfin.api.v1 import volume_groups
from delfin.api.v1 import masking_views

class APIRouter(common.APIRouter):

    ExtensionManager = extensions.ExtensionManager

    def _setup_routes(self, mapper):
        mapper.redirect("", "/")

        self.resources['storages'] = storages.create_resource()
        mapper.resource("storage", "storages",
                        controller=self.resources['storages'],
                        member={'sync': 'POST'})

        mapper.connect("storages", "/storages/sync",
                       controller=self.resources['storages'],
                       action="sync_all",
                       conditions={"method": ["POST"]})

        mapper.connect("storages", "/storages/{id}/capabilities",
                       controller=self.resources['storages'],
                       action="get_capabilities",
                       conditions={"method": ["GET"]})

        self.resources['access_info'] = access_info.create_resource()
        mapper.connect("storages", "/storages/{id}/access-info",
                       controller=self.resources['access_info'],
                       action="show",
                       conditions={"method": ["GET"]})

        mapper.connect("storages", "/storages/{id}/access-info",
                       controller=self.resources['access_info'],
                       action="update",
                       conditions={"method": ["PUT"]})

        mapper.connect("storages", "/access-infos",
                       controller=self.resources['access_info'],
                       action="show_all",
                       conditions={"method": ["GET"]})

        self.resources['alert_sources'] = alert_source.create_resource()
        mapper.connect("storages", "/storages/{id}/snmp-config",
                       controller=self.resources['alert_sources'],
                       action="put",
                       conditions={"method": ["PUT"]})
        mapper.connect("storages", "/storages/{id}/snmp-config",
                       controller=self.resources['alert_sources'],
                       action="show",
                       conditions={"method": ["GET"]})
        mapper.connect("storages", "/storages/{id}/snmp-config",
                       controller=self.resources['alert_sources'],
                       action="delete",
                       conditions={"method": ["DELETE"]})
        mapper.connect("storages", "/snmp-configs",
                       controller=self.resources['alert_sources'],
                       action="show_all",
                       conditions={"method": ["GET"]})

        self.resources['alerts'] = alerts.create_resource()
        mapper.connect("storages", "/storages/{id}/alerts/{sequence_number}",
                       controller=self.resources['alerts'],
                       action="delete",
                       conditions={"method": ["DELETE"]})

        mapper.connect("storages", "/storages/{id}/alerts",
                       controller=self.resources['alerts'],
                       action="show",
                       conditions={"method": ["GET"]})

        mapper.connect("storages", "/storages/{id}/alerts/sync",
                       controller=self.resources['alerts'],
                       action="sync",
                       conditions={"method": ["POST"]})

        self.resources['storage-pools'] = storage_pools.create_resource()
        mapper.resource("storage-pool", "storage-pools",
                        controller=self.resources['storage-pools'])

        self.resources['volumes'] = volumes.create_resource()
        mapper.resource("volume", "volumes",
                        controller=self.resources['volumes'])

        self.resources['controllers'] = controllers.create_resource()
        mapper.resource("controller", "controllers",
                        controller=self.resources['controllers'])

        self.resources['ports'] = ports.create_resource()
        mapper.resource("port", "ports",
                        controller=self.resources['ports'])

        self.resources['disks'] = disks.create_resource()
        mapper.resource("disk", "disks",
                        controller=self.resources['disks'])

        self.resources['filesystems'] = filesystems.create_resource()
        mapper.resource("filesystems", "filesystems",
                        controller=self.resources['filesystems'])

        self.resources['qtrees'] = qtrees.create_resource()
        mapper.resource("qtrees", "qtrees",
                        controller=self.resources['qtrees'])

        self.resources['quotas'] = quotas.create_resource()
        mapper.resource("quotas", "quotas",
                        controller=self.resources['quotas'])

        self.resources['shares'] = shares.create_resource()
        mapper.resource("shares", "shares",
                        controller=self.resources['shares'])

        self.resources['storage_host_initiators'] \
            = storage_host_initiators.create_resource()
        mapper.connect("storages", "/storages/{id}/storage-host-initiators",
                       controller=self.resources['storage_host_initiators'],
                       action="show",
                       conditions={"method": ["GET"]})

        self.resources['storage_hosts'] = storage_hosts.create_resource()
        mapper.connect("storages", "/storages/{id}/storage-hosts",
                       controller=self.resources['storage_hosts'],
                       action="show",
                       conditions={"method": ["GET"]})

        self.resources['storage_host_groups'] \
            = storage_host_groups.create_resource()
        mapper.connect("storages", "/storages/{id}/storage-host-groups",
                       controller=self.resources['storage_host_groups'],
                       action="show",
                       conditions={"method": ["GET"]})

        self.resources['port_groups'] \
            = port_groups.create_resource()
        mapper.connect("storages", "/storages/{id}/port-groups",
                       controller=self.resources['port_groups'],
                       action="show",
                       conditions={"method": ["GET"]})

        self.resources['volume_groups'] \
            = volume_groups.create_resource()
        mapper.connect("storages", "/storages/{id}/volume-groups",
                       controller=self.resources['volume_groups'],
                       action="show",
                       conditions={"method": ["GET"]})

        self.resources['masking_views'] \
            = masking_views.create_resource()
        mapper.connect("storages", "/storages/{id}/masking-views",
                       controller=self.resources['masking_views'],
                       action="show",
                       conditions={"method": ["GET"]})


import sys
import numpy as np
import cv2

def main():
    source_window = "source_image"
    gray_window = "gray"
    otsu_window = "otsu_threshold"
    edge_window = "edge"

    gray_img = cv2.imread(sys.argv[1], cv2.IMREAD_GRAYSCALE)

    threshold1 = 0
    threshold2 = 100
    edge_img = cv2.Canny(gray_img, threshold1, threshold2)
    cv2.imshow(edge_window, edge_img)

    ret, otsu_img = cv2.threshold(gray_img, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY_INV)
    cv2.imshow(otsu_window, otsu_img)

    contours, hierachy = cv2.findContours(otsu_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # print(contours)
    cv2.drawContours(gray_img, contours, -1, (0,255,0), 3)
    cv2.imshow(gray_window, gray_img)

    # cv2.imshow("test", findCon_img)

    cv2.waitKey(0)

    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()


from django.utils import timezone
from .models import Post, IP
from django.shortcuts import render, get_object_or_404, redirect
from .forms import PostForm, Login
from django.contrib.auth.decorators import login_required, PermissionDenied, user_passes_test
import json
from datetime import timedelta
from django.utils.timezone import now
from django.http import JsonResponse
from django.core import serializers
from django.http import HttpResponse
from django.db.models import Q
from django.contrib import messages
from flask import request
from django.contrib.auth.models import User

def get_ip(request):
    try:
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(",")[0]
        else:
            ip = request.META.get("REMOTE_ADDR")
    except:
        ip = ""
    return ip

@login_required
def post_list(request):
    last_ip = IP.objects.filter(User=request.user).latest('entr_date')
    form = Login(request.POST)
    if form.is_valid():
        new_ip = form.save(commit=False)
        new_ip.User = request.user
        new_ip.entr_date = timezone.now()
        new_ip.ip_address = get_ip(request)
        this_ip = IP.objects.filter(User=request.user).latest('entr_date')
        if this_ip != last_ip:
            messages.warning(request, 'Indirizzo ip diverso dal precedente.')
        new_ip.save()
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
    return render(request, 'blog/post_list.html', {'posts': posts})

@login_required
def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    return render(request, 'blog/post_detail.html', {'post': post})

@login_required
def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.writeOnChain()
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm()
    return render(request, 'blog/post_edit.html', {'form': form})

@login_required
def post_edit(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm(instance=post)
    return render(request, 'blog/post_edit.html', {'form': form})

def superuser_only(function):
    def _inner(request):
        if not request.user.is_superuser:
            raise PermissionDenied
        return function(request)
    return _inner

@login_required
def delete_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        post.delete()
        return redirect('post_list')
    return render(request, 'blog/delete.html', {'post': post})

@superuser_only
def info_superuser(request):
    n = {}
    users_id = User.objects.all().values_list('id', flat=True)
    for x in users_id:
        posts = Post.objects.filter(author=x)
        n[x] =  len(posts)
    return render(request, 'blog/info_superuser.html', {'n': n})

@superuser_only
def last_hour_post(request):
    dt = now()
    PostsLastHour = Post.objects.filter(published_date__range=(dt-timedelta(hours=1), dt))
    post_1h = serializers.serialize('json',PostsLastHour)
    return HttpResponse(post_1h, content_type="text/json-comment-filtered")

@superuser_only
def search_str(request):
    template = 'blog/info_superuser.html'
    query = request.GET.get('q')
    results_title = Post.objects.filter(Q(title__icontains=query))
    results_text = Post.objects.filter(Q(text__icontains=query))
    n = len(results_text) + len(results_title)
    return HttpResponse(n)