import numpy as np
import cv2
from skimage import filters

capL = cv2.VideoCapture('robotL.avi')
capR = cv2.VideoCapture('robotR.avi')
focal_lenght = 567.2  # in pixel
baseline = 92.226  # in mm
dim_kp = 30
h_stripe = 2
max_kp = []
# d4 = 2

# d3 = 2

# d2 = 2

# d1 = 2

# d0 = 2
dist = 3
dist_vect = np.ones((5,), dtype='int') * dim_kp
d_main = ((baseline * focal_lenght) / dist) * 0.001
d_main_object = d_main
d_main_foreground = d_main
dist_ob = dist
dist_fg = dist
print(d_main)
temp_dim = dim_kp
flag = False
n_square = 4
m_square = 4
min_disp = 0
max_disp = 64

if not capL.isOpened():
    print("Error opening video stream or file")

if not capR.isOpened():
    print("Error opening video stream or file")

sift = cv2.xfeatures2d.SIFT_create()

while capL.isOpened() and capR.isOpened():

    retL, frameL = capL.read()
    retR, frameR = capR.read()

    if retL is True and retR is True:
        # Capture frame-by-frame
        # Display the resulting frame
        cv2.rectangle(frameL, (int(frameL.shape[1] / 2) - dim_kp, int(frameL.shape[0] / 2) - dim_kp),
                      (int(frameL.shape[1] / 2) + dim_kp, int(frameL.shape[0] / 2) + dim_kp), 250, 1)
        cv2.rectangle(frameR, (int(frameR.shape[1] / 2) - dim_kp, int(frameR.shape[0] / 2) - dim_kp),
                      (int(frameR.shape[1] / 2) + dim_kp, int(frameR.shape[0] / 2) + dim_kp), 250, 1)
        centerL = frameL[int(frameL.shape[0] / 2) - dim_kp: int(frameL.shape[0] / 2) + dim_kp,
                  int(frameL.shape[1] / 2) - dim_kp:int(frameL.shape[1] / 2) + dim_kp]
        centerR = frameR[int(frameR.shape[0] / 2) - dim_kp: int(frameR.shape[0] / 2) + dim_kp,
                  int(frameR.shape[1] / 2) - dim_kp:int(frameR.shape[1] / 2) + dim_kp]
        total_grayL = cv2.cvtColor(frameL, cv2.COLOR_BGR2GRAY)
        total_intermediateL = cv2.equalizeHist(total_grayL)
        total_finalL = total_intermediateL
        grayL = cv2.cvtColor(centerL, cv2.COLOR_BGR2GRAY)
        intermediateL = cv2.equalizeHist(grayL)

        finalL = cv2.medianBlur(intermediateL, 5)
        # cv2.bilateralFilter(grayL, 5, 3, 3)

        # cv2.equalizeHist(intermediateL)

        # intermediateL

        # cv2.medianBlur(intermediateL, 5)

        # cv2.GaussianBlur(intermediateL, (3, 3), 3)
        grayR = cv2.cvtColor(centerR, cv2.COLOR_BGR2GRAY)
        intermediateR = cv2.equalizeHist(grayR)
        finalR = cv2.medianBlur(intermediateR, 5)
        # cv2.bilateralFilter(grayR, 5, 3, 3)

        # cv2.equalizeHist(intermediateR)

        # intermediateR

        # cv2.medianBlur(intermediateR, 5)
        info_frame = np.empty_like(finalL)
        H = frameL.shape[0]
        L = frameL.shape[1]
        #
        h = finalL.shape[0]
        l = finalL.shape[1]
        #
        off_x_L = (L / 2 - l / 2)
        # int(L/2)
        off_y_L = (H / 2 - h / 2)
        # int(H/2)
        off_x_R = off_x_L + frameL.shape[1]
        off_y_R = off_y_L
        # #     STATE OF ART FOUND OF CV2

        # stereo = cv2.StereoBM_create(numDisparities=16, blockSize=15)

        # disparity = stereo.compute(finalL, finalR)

        # d = disparity/255

        # #disparity = np.uint8(disparity)

        # cv2.imshow('title',disparity/255)

        # cv2.imshow('t1',finalL)

        # print('dentro')

        # center_tempL = frameL[int(frameL.shape[0] / 2) - dim: int(frameL.shape[0] / 2) + dim,

        #           int(frameL.shape[1] / 2) - dim:int(frameL.shape[1] / 2) + dim]

        # center_tempL = copy.deepcopy(centerL)

        # # center_tempR = frameR[int(frameR.shape[0] / 2) - dim: int(frameR.shape[0] / 2) + dim,

        # #           int(frameR.shape[1] / 2) - dim:int(frameR.shape[1] / 2) + dim]

        # center_tempR = copy.deepcopy(centerR)

        #

        # grayL = cv2.cvtColor(centerL, cv2.COLOR_BGR2GRAY)

        # intermediateL = cv2.equalizeHist(grayL)

        # finalL = cv2.medianBlur(intermediateL, 5)

        #

        # grayR = cv2.cvtColor(centerR, cv2.COLOR_BGR2GRAY)

        # intermediateR = cv2.equalizeHist(grayR)

        # finalR = cv2.medianBlur(intermediateR, 5)

        # #     DIVISION IN STRIPES BEFORE COMPUTING THE KEYPOINTS

        # image_stripesL = np.zeros((int(finalL.shape[1]/h_stripe), h_stripe, finalL.shape[0]), dtype='uint8')  # NxHxL where N = n of stripes, H = height of stripes, L = lenght of window

        # image_stripesR = np.zeros((int(finalR.shape[1] / h_stripe), h_stripe, finalR.shape[0]), dtype='uint8')

        # kpL = np.zeros((int(finalL.shape[1]/h_stripe)), dtype='object')

        # desL = np.zeros(int(finalL.shape[1]/h_stripe), dtype='object')

        # imgL = np.zeros((int(finalL.shape[1]/h_stripe), h_stripe, finalL.shape[0]), dtype='uint8')

        #

        # kpR = np.zeros((int(finalR.shape[1]/h_stripe)), dtype='object')

        # desR = np.zeros(int(finalR.shape[1]/h_stripe), dtype='object')

        # imgR = np.zeros((int(finalR.shape[1]/h_stripe), h_stripe, finalL.shape[0]), dtype='uint8')

        # distance = np.zeros((int(finalR.shape[1] / h_stripe), ), dtype='object')

        # maxL = 0

        # maxR = 0

        #

        # sift = cv2.xfeatures2d.SIFT_create()

        #

        # for i in range(int(finalL.shape[1]/h_stripe)):

        #     image_stripesL[i] = finalL[i*h_stripe:(i+1)*h_stripe, :]

        #     image_stripesR[i] = finalR[i * h_stripe:(i + 1) * h_stripe, :]

        #     kpL[i], desL[i] = sift.detectAndCompute(image_stripesL[i], None)

        #     kpR[i], desR[i] = sift.detectAndCompute(image_stripesR[i], None)

        #     try:

        #         distance[i] = np.zeros((desL[i].shape[0], desR[i].shape[0]))

        #         center_tempL[i*h_stripe:(i+1)*h_stripe,:,:] = cv2.drawKeypoints(image_stripesL[i], kpL[i], center_tempL[i], flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

        #         center_tempR[i*h_stripe:(i+1)*h_stripe,:,:] = cv2.drawKeypoints(image_stripesR[i], kpR[i], center_tempR[i], flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

        #         distance[i] = np.array(np.sqrt(np.sum((desL[i][:, np.newaxis, :] - desR[i][np.newaxis, :, :]) ** 2, axis=-1)))

        #     except(AttributeError):

        #         distance[i] = np.array([[1000000]])

        #     # if len(kpL[i]) > maxL:

        #     #     maxL = len(kpL[i])

        #     # if len(kpR[i]) > maxR:

        #     #     maxR = len(kpR[i])

        #

        # totalimageL = np.vstack([center_tempL[i*h_stripe:(i+1)*h_stripe,:,:] for i in range(int(finalL.shape[1]/h_stripe))])

        # totalimageR = np.vstack(

        #     [center_tempR[i * h_stripe:(i + 1) * h_stripe, :, :] for i in range(int(finalR.shape[1] / h_stripe))])

        # kptL = np.empty((sum([len([kpL[i] for i in range(int(finalL.shape[1]/h_stripe))])])), dtype='object')

        # kptR = np.empty((sum([len([kpR[i] for i in range(int(finalR.shape[1] / h_stripe))])])), dtype='object')

        # destL = []

        # destR = []

        # kptL = np.concatenate([kpL[i] for i in range(int(finalL.shape[1]/h_stripe))]).ravel()

        # kptR = np.concatenate([kpR[i] for i in range(int(finalR.shape[1] / h_stripe))]).ravel()

        #

        # destL.append([desL[i] for i in range(int(finalL.shape[1]/h_stripe))])

        # destR.append([desR[i] for i in range(int(finalR.shape[1] / h_stripe))])

        # # for i in range(int(finalL.shape[1] / h_stripe)):

        # distance[i,:,:] = np.array(np.sqrt(np.sum((desL[i][:, np.newaxis, :] - desR[i][np.newaxis, :, :]) ** 2, axis=-1)))

        # cv2.imshow('image_stripesL', totalimageL)

        # cv2.imshow('image_stripesR', totalimageR)

        # imgL = cv2.drawKeypoints(totalimageL, kptL[:], totalimageL, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

        # imgR = cv2.drawKeypoints(totalimageR, kptR[:], totalimageR, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

        # # cv2.imshow("skL", imgL)

        # # cv2.imshow("skR", imgR)

        # #     DETECT THE KPTS IN THE WHOLE IMAGES
        kpL, desL = sift.detectAndCompute(finalL, None)
        kpR, desR = sift.detectAndCompute(finalR, None)
        # draw key points detected

        # img2 = cv2.drawKeypoints(finalL, kp2, finalL, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

        # cv2.line(img2, (0, h_stripe), (img2.shape[1], h_stripe), (255,0,0))

        # cv2.imshow("grayframeL", img2)

        # img1 = cv2.drawKeypoints(finalR, kp1, finalR, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

        # cv2.imshow("grayframeR", img1)
        image_stripesL = np.zeros((int(finalL.shape[1] / h_stripe), h_stripe, finalL.shape[0]),
                                  dtype='uint8')  # NxHxL where N = n of stripes, H = height of stripes, L = lenght of window
        image_stripesR = np.zeros((int(finalR.shape[1] / h_stripe), h_stripe, finalR.shape[0]), dtype='uint8')
        kp_stripesL = []
        kp_stripesR = []
        des_stripesL = []
        des_stripesR = []
        # found, corners = cv2.findChessboardCorners(frameL, (6,8))

        # cv2.drawChessboardCorners(frameL, (6,8), corners, found)

        # if found == True:

        #     pt = (corners[0],corners[-1])

        #     cv2.circle(frameL,(pt[0][0][0],pt[0][0][1]),8,(0,255,0),1)

        #     cv2.circle(frameL,(pt[1][0][0],pt[1][0][1]),8,(0,255,0),1)

        #     l_chess = pt[1][0][0] - pt[0][0][0]

        #     h_chess = pt[1][0][1] - pt[0][0][1]

        #     l_chess_mm = (dist*l_chess)/focal_lenght

        #     h_chess_mm = (dist*h_chess)/focal_lenght

        #     print('ciao', l_chess_mm,h_chess_mm)

        #

        # cv2.imshow('f',frameL)

        # FLANN parameters

        # FLANN_INDEX_KDTREE = 0

        # index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)

        # search_params = dict(checks=50)

        # matches = np.zeros((int(finalL.shape[1] / h_stripe)), dtype='object')

        # good = []

        # ptsL = []

        # ptsR = []

        #

        # flann = cv2.FlannBasedMatcher(index_params, search_params)

        # for i in range(int(finalL.shape[1] / h_stripe)):

        #     if kp_stripesL[i] == 0:

        #         kp_stripesL[i] = []

        #     if kp_stripesR[i] == 0:

        #         kp_stripesR[i] = []

        #     for j in range(len(kp2)):

        #         if i*h_stripe <= kp2[j].pt[1] < (i+1)*h_stripe:

        #             kp_stripesL[i].append(kp2[j])

        #     for j in range(len(kp1)):

        #         if i * h_stripe <= kp1[j].pt[1] < (i + 1) * h_stripe:

        #             kp_stripesR[i].append(kp1[j])
        for i in range(int(finalL.shape[1] / h_stripe)):
            kp_stripesL.append([])
            kp_stripesR.append([])
            des_stripesL.append([])
            des_stripesR.append([])
            for j in range(len(kpL)):
                if i * h_stripe <= kpL[j].pt[1] < (i + 1) * h_stripe:
                    kp_stripesL[i].append(kpL[j])
                    des_stripesL[i].append(desL[j])
            for j in range(len(kpR)):
                if i * h_stripe <= kpR[j].pt[1] < (i + 1) * h_stripe:
                    kp_stripesR[i].append(kpR[j])
                    des_stripesR[i].append(desR[j])
        # print(len(des_stripesL))
        des_stripesL = np.array(des_stripesL)
        kp_stripesL = np.array(kp_stripesL)
        des_stripesR = np.array(des_stripesR)
        kp_stripesR = np.array(kp_stripesR)
        distance = []
        disparity_map = []
        kp_struct = []
        # distance = np.zeros((int(finalR.shape[1] / h_stripe),), dtype='object')

        # distance[i, :, :] = np.array(np.sqrt(np.sum((des_stripesL[i][:, np.newaxis, :] - des_stripesR[i][np.newaxis, :, :]) ** 2, axis=-1)))

        # distance = np.array(np.sqrt(np.sum((des1[:, np.newaxis, :] - des2[np.newaxis, :, :]) ** 2, axis=-1)))
        outimg = np.concatenate((frameL, frameR), axis=1)
        for j in range(len(des_stripesL)):
            des_stripesL[j] = np.array(des_stripesL[j])
            kp_stripesL[j] = np.array(kp_stripesL[j])
            des_stripesR[j] = np.array(des_stripesR[j])
            kp_stripesR[j] = np.array(kp_stripesR[j])
            distance.append([])
            # print(kp_stripesL[j].__len__(), " ", kp_stripesR[j].__len__())
            if kp_stripesL[j].__len__() > 0 and kp_stripesR[j].__len__() > 0:
                distance[j] = np.array(np.sqrt(
                    np.sum((des_stripesL[j][:, np.newaxis, :] - des_stripesR[j][np.newaxis, :, :]) ** 2, axis=-1)))
                ind = tuple(zip(*np.where(distance[j] < 150)))  ### GUARDA QUI!!!!!!!!!!!!!!!
                index = list(ind)
                # print(ind)

                # print(index)
                removed = np.ones(len(ind), dtype='uint8')
                for i in range(len(ind) - 1):
                    check = False
                    if removed[i] == 1:
                        for k in range(i + 1, len(ind)):
                            if ind[i][0] == ind[k][0] or ind[i][1] == ind[k][1]:
                                if distance[j][ind[i]] < distance[j][ind[k]]:
                                    if removed[k] == 1:
                                        # print(ind[k])
                                        index.remove(ind[k])
                                        removed[k] = 0
                                else:
                                    if removed[i] == 1:
                                        # print('ciao', ind[i])
                                        index.remove(ind[i])
                                        removed[i] = 0
                index = tuple(index)
                # print(removed)

                # print('ind after cleaning',ind)

                # print('ind after cleaning',index)
                for i in index:
                    uL = int(kp_stripesL[j][i[0]].pt[0] + off_x_L)
                    uR = int(kp_stripesR[j][i[1]].pt[0] + off_x_R)
                    vL = int(kp_stripesL[j][i[0]].pt[1] + off_y_L)
                    vR = int(kp_stripesR[j][i[1]].pt[1] + off_y_R)
                    disparity = uL - uR
                    # print("(", uL, ", ",  vL, ") ", "(", uR, ", ",  vR, ") ", disparity)
                    kp_struct.append(((uL, vL), (uR, vR)))
                    if disparity + frameL.shape[1] > 0:
                        disparity_map.append(disparity + frameL.shape[1])
                        cv2.circle(outimg, (uL, vL), 3, (255, 0, 0), 1)
                        cv2.circle(outimg, (uR, vR), 3, (255, 0, 0), 1)
                        cv2.line(outimg, (uL, vL), (uR, vR), (255, 0, 0), 1)
            #     cv2.circle(finalL, (int(kp_stripesL[j, i[0]].pt[0]), int(kp_stripesL[j, i[0]].pt[1])), 4, (10 * i, 0, 0), 1)

            #     cv2.circle(finalR, (int(kp_stripesR[j, i[1]].pt[0]), int(kp_stripesR[j, i[1]].pt[1])), 4, (10 * i, 0, 0), 1)

            # temp_match = flann.knnMatch(des_stripesL[j], des_stripesR[j], k=2)
        # matches.append(temp_match)

        # ratio test as per Lowe's paper

        # for i, (m, n) in enumerate(temp_match):

        #     if m.distance < 0.8 * n.distance:

        #         good.append(m)
        n_kp = len(kp_struct)
        # print(n_kp)

        fig = None
        if len(disparity_map) > 2:
            d_main = np.mean(disparity_map)
            # print(d_main)

            # min_disp = d_main - 32

            # max_disp = d_main + 32
            disparity_map = np.array(disparity_map)
            # disparity_map_star = disparity_map < max_disp

            # disparity_map_star = disparity_map > min_disp
            disparity_map_star = np.ma.masked_inside(disparity_map, min_disp, max_disp)
            min_disp = d_main - (d_main / 2)
            max_disp = d_main + (d_main / 2)
            # disp_tot = (disparity_map_star.all() == disparity_map_star1.all())
            disparity_map_star = disparity_map[disparity_map_star.mask]
            std_dev = np.std(disparity_map_star)
            print(std_dev)
            print(2 / dist_ob)
            if std_dev > 0:#(2 / dist_ob):
                val = filters.threshold_otsu(disparity_map_star)
                # print(val)
                d_main_background = np.mean(disparity_map_star[disparity_map_star <= val])
                dist_bg = round(0.001 * focal_lenght * baseline / d_main_background, 2)
                print("d_main_background: ", round(d_main_background, 2), 'distance_background: ', dist_bg, "m")
                d_main_object = np.mean(disparity_map_star[disparity_map_star > val])
                dist_ob = round(0.001 * focal_lenght * baseline / d_main_object, 2)
                print("d_main_object: ", round(d_main_object, 2), 'distance_object: ', dist_ob, "m")
            else:
                d_main_object = np.mean(disparity_map_star)
                dist_ob = round(0.001 * focal_lenght * baseline / d_main_object, 2)
                print("d_main: ", round(d_main_object, 2), 'distance: ', dist_ob, "m")
                flag = False
        else:
            if not flag:
                print("d_main ~ ", round(d_main_object, 2), 'distance ~ ', dist_ob, "m")
            else:
                print("d_main <= ", round(d_main_object, 2), 'distance <= ', dist_ob, "m")
            flag = True

        # cv2.putText(outimg, d_main, (10, 10), cv2.FONT_ITALIC, 2, 255)
        if dist_ob <= 0.8:
            print('Warning: object too close')
        # for i in range(int(min(des_stripesL.__len__(), des_stripesR.__len__()))):

        #     try:

        #         cv2.drawMatchesKnn(finalL, kp_stripesL[i], finalR, kp_stripesR[i], good[i], outimg)

        #         cv2.knn

        #     except(SystemError):

        #         continue

        # kpL = kp_stripesL[4]

        # kpR = kp_stripesR[4]

        # outimg = cv2.resize(outimg, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)

        cv2.imshow("outimg", outimg)
        # n_kp = np.sum(len(kp_struct[:]))

        # max_kp.append(n_kp)

        # d4 = d3

        # d3 = d2

        # d2 = d1

        # d1 = d0

        # d0 = temp_dim

        m = (30 - 60) / 27
        q = 60 - m * 3
        if 128 > d_main_object >= 0:
            if n_kp <= 3:
                temp_dim = 100
            elif 3 < n_kp < 30:
                temp_dim = int(m * n_kp + q)
            else:
                temp_dim = 50

        # dist_vect[4] = dist_vect[3]
        #
        # dist_vect[3] = dist_vect[2]
        #
        # dist_vect[2] = dist_vect[1]
        #
        # dist_vect[1] = dist_vect[0]
        #
        # dist_vect[0] = temp_dim
        for i in range(len(dist_vect) - 1, 0, -1):
            dist_vect[i] = dist_vect[i - 1]
        dist_vect[0] = temp_dim
        dim_kp = int(np.mean(dist_vect))

        # print("n_kp: ", n_kp)

        # good = []

        # pts1 = []

        # pts2 = []

        #

        # # ratio test as per Lowe's paper

        # for i, (m, n) in enumerate(matches):

        #     if m.distance < 0.8 * n.distance:

        #         good.append(m)

        #         pts2.append(kp_stripesL[i][m.trainIdx].pt)

        #         pts1.append(kp_stripesR[i][m.queryIdx].pt)
    #     # # BFMatcher with default params

    #     # bf = cv2.BFMatcher(cv2.NORM_L2)

    #     # matches = bf.knnMatch(des1, des2, k=2)

    #     #

    #     # # Apply ratio test

    #     # good = []

    #     # for m, n in matches:

    #     #     if m.distance < 0.75 * n.distance:

    #     #         good.append([m])

    #

    #     # draw key points detected

    #     img1 = cv2.drawKeypoints(finalR, kp1, finalR, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

    #     cv2.imshow("grayframe1", img1)

    #     # distance = np.zeros((des1.shape[0], des2.shape[0]))

    #     # for i in range(des1.shape[0]-1):

    #     #     for j in range(des2.shape[0]-1):

    #     #         if kp1[i].pt[1] - kp2[j].pt[1] < 0.3 or kp1[i].pt[1] - kp2[j].pt[1] > -0.3:

    #     #             distance[i, j] = np.sqrt(np.sum((des1[i, :] - des2[j, :]) ** 2, axis = -1))

    #

    #     distance = np.array(np.sqrt(np.sum((des1[:, np.newaxis, :] - des2[np.newaxis, :, :]) ** 2, axis=-1)))

    #     #SIFT descriptor of a point is just 128-dimensional vector, so you can simple compute Euclidean distance

    #     between every two and match nearest pairs.

    #

    #     # for k in range(len(kp1)):

    #     #     for z in range(len(kp2)):

    #     #         if kp1[k].angle - kp2[z].angle > 0.5 or kp1[k].angle - kp2[z].angle < -0.5:

    #     #             distance[k, z] = 100000000000

    #     #         if kp1[k].pt[1] - kp2[z].pt[1] > 3 or kp1[k].pt[1] - kp2[z].pt[1] < -3:

    #     #             distance[k, z] = 100000000000

    #

    #     ind = np.unravel_index(np.argmin(distance, axis=None), distance.shape)

    #     print(distance.min())

    #     #ciccio = np.unravel_index(distance<100

    #     ind = tuple(zip(*np.where(distance < 50)))

    #     kpL = []

    #     kpR = []

    #     for i in ind:

    #         if 0.05 > kp2[i[1]].pt[1] - kp1[i[0]].pt[1] > -0.05 and 128 > kp2[i[1]].pt[0] - kp1[i[0]].pt[0] > 0:

    #             kpL.append(kp2[i[1]])

    #             kpR.append(kp1[i[0]])

    #     for i,j in enumerate(kpL):

    #         cv2.circle(centerL, (int(j.pt[0]), int(j.pt[1])), 4, (10*i, 3*i,25*i), 1)

    #     for i, j in enumerate(kpR):

    #         cv2.circle(centerR, (int(j.pt[0]), int(j.pt[1])), 4, (10*i, 3*i,25*i), 1)

    #     cv2.imshow('centerL', centerL)

    #

    #     cv2.imshow('centerR', centerR)

    #     # # create BFMatcher object

    #     #bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)

    #

    #     ## Match descriptors.

    #     #matches = bf.match(des1, des2)

    #

    #     ## Sort them in the order of their distance.

    #     #matches = sorted(matches, key=lambda x: x.distance)

    #     # good = []

    #     # for m, n in matches:

    #     #     if m.distance < 0.2 * n.distance:

    #     #         good.append([m])

    #     # # Draw first 10 matches.

    #     # img4 = np.hstack((centerL, centerR))

    #     # img3 = cv2.drawMatchesKnn(centerL, kp1, centerR, kp2, good, img4, flags=2)

    #

    #     #cv2.imshow('matches', img3)

    #

    #     cv2.imshow('FrameL', frameL)

    #     cv2.imshow('FrameR', frameR)

    # # Press Q on keyboard to  exit

    if cv2.waitKey(25) & 0xFF == ord('q'):
        break
    # if k == 27:  # Esc key to stop

    #     break

    # elif k == -1:  # normally -1 returned,so don't print it

    #     continue

    # else:

    #     print(k)

    if cv2.waitKey(33) == ord('a'):
        outimg = cv2.resize(outimg, None, fx=1.5, fy=1.5, interpolation=cv2.INTER_CUBIC)
        cv2.imshow("stopped_frame", outimg)
        while (True):
            k = cv2.waitKey(33)
            if k == 27:  # Esc key to stop
                break

capL.release()
capR.release()
cv2.destroyAllWindows()


import mido
from mido import Message
from mido import MidiFile
from pprint import pprint
import mingus.core.chords as chords
import random
from os import system
import time

outport = mido.open_output()

input1 = mido.get_input_names()[0]
for inp in mido.get_input_names():
    if inp.find('Keystation')>-1:
        input1 = inp

"""
Application:

1. random generate chord and type(ex C, dominant)
2. translate with mingus
3. show on screen
4. wait until correctly pressed(or just one chance and show succes/failure)

New features:
ok- say chord name and correct/failed

ok- consider the chord once n notes are playe(n is the number of notes of the current chord), then say right or wrong

ok- wait until no more notes pressed

- read midi and play it

ok- read midi withotu playing it but stoping until piano plays the current note

- deal with chords

- deal with chord names annotated on midi files (only do this)

"""

degrees = ['C','D','E','F','G','A','B']

root_notes = [
    'C','B#',
    'C#','Db',
    'D',
    'D#','Eb',
    'E','Fb',
    'F','E#',
    'F#','Gb',
    'G',
    'G#','Ab',
    'A','Bbb',
    'A#','Bb',
    'B','Cb']

note = [
    ('C','B#','Dbb'),
    ('C#','B##','Db'),
    ('D','C##','Ebb'),
    ('D#','Eb'),
    ('E','D##','Fb'),
    ('F','E#','Gbb'),
    ('F#','E##','Gb'),
    ('G','F##','Abb'),
    ('G#','Ab'),
    ('A','G##','Bbb'),
    ('A#','Bb'),
    ('B','A##','Cb')]

notes = { i:note[i%12]  for i in range(128) }

chord_types = {
'major': [4,3],
'minor': [3,4],
'': [4,3,4],
'7':[4,3,3],
'm7':[3,4,3],
'7b5':[3,3,4],
'dim7':[3,3,3]
}

def find_real_note(note_name):

    if isinstance(note_name,str):
        for n in note:
            for synonime in n:
                if synonime == note_name:
                    return n
    elif isinstance(note_name,tuple):
        """
            Stupid assumption, if it is a tuple, it'sa real note already
        """
        return note_name

    return None

def find_note_position(real_note):

    if isinstance(real_note,str):
        real_note = find_real_note(real_note)

    return note.index(real_note)

def choose_random_chord():

    root = root_notes[random.randint(0,len(root_notes)-1)]

    chord_types_keys = list(chord_types.keys())
    chord_type = chord_types[chord_types_keys[random.randint(0,len(chord_types_keys)-1)]]

    final_chord = [root,]

    # find position of root
    current_note = root
    #final_chord.append(find_real_note(current_note))
    posi = find_note_position(current_note)

    for interval in chord_type:
        # add semitones to find next note
        posi = (posi + interval) % len(note)

        # update curernt note
        current_note = note[posi]
        final_chord.append(current_note)

    return final_chord

def parse_chord(a_chord):
    """
    PENDING:
    - compute semitones between notes of the chord
    - according to the semitones between the previous note
    and the previous note first name(ex C,D#)
    choose the current note (ex if C -> E, if B -> D#

    establish some priority:
    1. first I,III,V,VII
    2. then II,IV,VI
    """

    #print(a_chord)

    root = a_chord[0][0]

    foundi = degrees.index(root[0])
    ld = len(degrees)
    the_degrees = [
                    degrees[foundi],
                    degrees[(foundi+2)%ld],
                    degrees[(foundi+4)%ld],
                    degrees[(foundi+6)%ld],
                    ]
    #print(the_degrees)

    parsed_chord = [a_chord[0]]

    for i in range(1,len(a_chord)):
        #print("match",the_degrees[i]," in",a_chord[i])
        for synonym in a_chord[i]:
            if synonym.lower()[0] == the_degrees[i].lower():
                parsed_chord.append(synonym)
                break

    return chords.determine(parsed_chord), parsed_chord

def match_chord(pressed_notes, thechord):

    # convert to real chord
    thechord2 = [ thechord[i] if i>0 else find_real_note(thechord[i]) for i in range(len(thechord)) ]

    #print("real chord", thechord2)

    # sort the pressed notes by note value ascending
    pressed_notes.sort(key=lambda x: x[0])
    pressed_notes2 = [t[1] for t in pressed_notes]
    #print("presset notes", pressed_notes2)

    match = True
    for i in range(len(thechord2)):

        #print(i, len(pressed_notes2), i+1, pressed_notes2[i], thechord2[i])
        if len(pressed_notes2)<i+1:
            match = False
            break
        elif pressed_notes2[i] != thechord2[i]:
            match = False
            break

    return match

def say_chord(chordname, stop=True, restart=True):
    print(chordname)
    if isinstance(chordname, str):
        my_say(chordname.replace('b',' flat ').replace('#',' sharp '), stop=stop, restart=restart)
    elif isinstance(chordname[0],str):
        my_say(chordname[0].replace('b',' flat ').replace('#',' sharp '), stop=stop, restart=restart)
    else:
        my_say(chordname, stop=stop, restart=restart)

def my_say(text, stop=True, restart=True):
    if stop:
        system('./config.sh stop')

    system('say '+text)
    waiting = (len(text) / 7 )
    time.sleep(1+waiting)
    if restart:
        system('./config.sh start')

# my_say(" First test")
# my_say(" This is my very first test. You should see config.sh appear later than before")
# my_say(" And now it should appear much faster")

def wait_for_chord(inport, thechord, chord_name, parsed_chord):
    #print(parsed_chord)
    print(chord_name)
    if len(chord_name)>0: say_chord(chord_name[0])

    pressed_notes = []
    times_up = False
    correct_answer = False
    for msg in inport:
        if 'note' not in dir(msg):
            continue

        if msg.is_meta:
            continue

        current_note = notes[msg.note]
        if msg.velocity > 0 :
            pressed_notes.append((msg.note,current_note))
        else:
            foundi = pressed_notes.index((msg.note,current_note))
            if foundi > -1:
                pressed_notes.pop(foundi)

        if len(pressed_notes) == len(thechord):
            #time.sleep(2)
            times_up = True

            print(pressed_notes, thechord)
            if match_chord(pressed_notes, thechord):
                correct_answer = True

        if times_up:
            if len(pressed_notes)==0:
                if correct_answer:
                    print("Correct!", parsed_chord )
                    my_say('Correct', restart=False)
                else:
                    print("Failed", parsed_chord )
                    my_say('Failed', restart=False)

                say_chord(' '.join(parsed_chord), stop=False)
                break

def chord_training():

    with mido.open_input(input1) as inport:
        while(True):
            thechord = choose_random_chord()
            chord_name, parsed_chord = parse_chord(thechord)
            wait_for_chord(inport,thechord,chord_name, parsed_chord)

def wait_until_correct_input(msg):
    with mido.open_input(input1) as inport:
        thechord = [(notes[msg.note])]
        print(thechord)
        chord_name, parsed_chord = notes[msg.note][0],[notes[msg.note][0]]
        wait_for_chord(inport, thechord,chord_name, parsed_chord)

#chord_training()

print("output:")
outputs = mido.get_output_names()
selected_output = [ out for out in outputs if out.find('Midi Through')>-1 ]
print(selected_output[0])
port = mido.open_output(selected_output[0])

mid = MidiFile('../muss_2.mid')
for msg in mid.play():
    #print(msg.time)
    #time.sleep(msg.time)
    if not msg.is_meta and 'note' in dir(msg):
        #print(dir(msg))
        print(msg)
        #port.send(msg)
        wait_until_correct_input(msg)


from flask import *
import os, commands, time, hashlib

app = Flask(__name__)

@app.route('/')
def index():
	return render_template('editor.html')

@app.route('/process', methods = ['GET', 'POST'])
def process():
	if request.method == 'POST':
		codes = request.form['codes']
		# bulid a file in /tmp/ and write inside
		outname = hashlib.md5(str(time.time())).hexdigest()
		filename = outname + '.cpp'
		os.system('touch /tmp/' + filename)
		f = open('/tmp/' + filename, 'w')
		f.write(codes)
		f.close()
		# compile
		c_result = commands.getoutput('g++ -o /tmp/' + outname + ' /tmp/' + filename)
		c_result = c_result.replace('/tmp/' + filename, 'your cpp')
		os.system('rm /tmp/' + filename)
		if c_result == '':
			return commands.getoutput('/tmp/' + outname)
		else:
			return c_result


import gym
from agent.mountain_car import MountainCarAgent
import pickle

experiment_path = '../results/mountain-car-experiment-1'
episode_count = 10
max_steps = 200
discount = 0.99
max_plan_steps = 1000
plan_tol = 1e-5

env = gym.make('MountainCar-v0')
agent = MountainCarAgent(env.action_space, env.observation_space, discount)

env.monitor.start(experiment_path)
for i in range(episode_count):
    observation = env.reset()
    for j in range(max_steps):
        if i == 0:
            action = env.action_space.sample()
        else:
            action = agent.act(observation)
        result, _, done, _ = env.step(action)
        agent.add_transition(observation, action, result)
        observation = result
        if done:
            break
    agent.model()
    agent.plan(max_plan_steps, plan_tol)
env.monitor.close()

with open(experiment_path + '/agent.pickle', 'wb') as file:
    pickle.dump(agent, file, pickle.HIGHEST_PROTOCOL)


# -*- coding: utf-8 -*-
import requests, json
from requests.exceptions import ConnectionError
import tokens

#  Метод для корректной обработки строк в кодировке UTF-8 как в Python 3, так и в Python 2
import sys

if sys.version_info < (3,):
    def u(x):
        try:
            return x.encode("utf8")
        except UnicodeDecodeError:
            return x
else:
    def u(x):
        if type(x) == type(b''):
            return x.decode('utf8')
        else:
            return x

# --- Входные данные ---
#  Адрес сервиса Keywords для отправки JSON-запросов (регистрозависимый)

CampaignsURL = 'https://api-sandbox.direct.yandex.com/json/v5/keywords'
#CampaignsURL = 'https://api.direct.yandex.com/json/v5/keywords'

# --- Подготовка, выполнение и обработка запроса ---
#  Создание HTTP-заголовков запроса
headers = {"Authorization": "Bearer " + tokens.token,  # OAuth-токен. Использование слова Bearer обязательно
           "Accept-Language": "ru",  # Язык ответных сообщений
           }

LimitedBy = 10000

# Создание тела запроса
body = {"method": "get",  # Используемый метод.
        "params": {"SelectionCriteria": {
                        "CampaignIds":[""],
                        },
                   "FieldNames": [
                        "Id", "Keyword", "AdGroupId", "CampaignId",# "Status", "State", "Bid",
                        ],  # Имена параметров, которые требуется получить.
                    "Page": {
                       "Limit": (long),
                        "Offset": (LimitedBy)
                    }
                  },
        }

# Кодирование тела запроса в JSON
jsonBody = json.dumps(body, ensure_ascii=False).encode('utf8')

# Выполнение запроса
try:
    result = requests.post(CampaignsURL, jsonBody, headers=headers)

    # Отладочная информация
    # print("Заголовки запроса: {}".format(result.request.headers))
    # print("Запрос: {}".format(u(result.request.body)))
    # print("Заголовки ответа: {}".format(result.headers))
    # print("Ответ: {}".format(u(result.text)))
    # print("\n")

    # Обработка запроса
    if result.status_code != 200 or result.json().get("error", False):
        print("Произошла ошибка при обращении к серверу API Директа.")
        print("Код ошибки: {}".format(result.json()["error"]["error_code"]))
        print("Описание ошибки: {}".format(u(result.json()["error"]["error_detail"])))
        print("RequestId: {}".format(result.headers.get("RequestId", False)))
    else:
#        print("RequestId: {}".format(result.headers.get("RequestId", False)))
#        print("Информация о баллах: {}".format(result.headers.get("Units", False)))

# Put all keywords in 1 list
        kw_list = []
        for campaign in result.json()["result"]["Keywords"]:
            kw_list.append(campaign['Keyword'])

# Вывод списка
#        print("Amount: ", len(kw_list))
        print(kw_list)

        print("{}, {}, {}".format(
                campaign['Keyword'],
                campaign["CampaignId"],
                campaign['AdGroupId'],
#               campaign['Status'],
#               campaign['State'],
#               campaign['Bid'],
                ))

        if result.json()['result'].get('LimitedBy', False):
            # Если ответ содержит параметр LimitedBy, значит,  были получены не все доступные объекты.
            # В этом случае следует выполнить дополнительные запросы для получения всех объектов.
            # Подробное описание постраничной выборки - https://tech.yandex.ru/direct/doc/dg/best-practice/get-docpage/#page
            print ("Limit {}".format(result.json()['result']['LimitedBy']))
            print("Получены не все доступные объекты.")

# Обработка ошибки, если не удалось соединиться с сервером API Директа
except ConnectionError:
    # В данном случае мы рекомендуем повторить запрос позднее
    print("Произошла ошибка соединения с сервером API.")

# Если возникла какая-либо другая ошибка
except:
    # В данном случае мы рекомендуем проанализировать действия приложения
    print("Произошла непредвиденная ошибка.")


import matplotlib.pyplot as plt
import scipy.special as special
import numpy as np

def step_fun(point, a, b, deltaX, N, x, K, m, sigma):
    # массив для хранения количества xi, попавших в интервал
    sum = []
    # массив выборочных вероятностей
    F = [0]
    # массив для хранения координат по оси Х
    fx = [a]
    for q in range(K):
        sum.append(0)
        # правая граница интервала
        b = a + (q + 1) * deltaX
        fx.append(b)
        for i in range(len(x)):
            # если xi попадает в интервал, то добавляем в массив сумм
            if a <= x[i] < b:
                sum[q] += 1
        F.append(sum[q] / N)
    # строим ступенчатую диаграмму и показываем графики
    plt.step(fx, F)
    if point == 0:
        plt.title("Равномерное распределение")
        fx_even(a, b, x)
    elif point == 1:
        plt.title("Нормальное распределение")
        fx_gauss(x, m, sigma)
    elif point == 2:
        plt.title("Распределение Рэлея")
        fx_rayleigh(x, sigma)
    plt.show()

# функция равномерного распределения
def fx_even(a, b, fx):
    fy = []
    for i in range(len(fx)):
        fy.append(((fx[i] - a) / (b - a)))
    plt.plot(fx, fy, color='r')

# функция гаусовского распределения
def fx_gauss(fx, m, sigma):
    fy = []
    for i in range(len(fx)):
        fy.append((1 / 2) * (1 + special.erf((fx[i] - m) / (np.sqrt(2 * sigma**2)))))
    plt.plot(fx, fy, color='r')

# функция рэлеевского распределения
def fx_rayleigh(fx, sigma):
    fy = []
    for i in range(len(fx)):
        fy.append(1 - np.exp(-1 * (fx[i] ** 2) / (2 * sigma ** 2)))
    plt.plot(fx, fy, color='r')


from app import db
from flask import render_template, url_for, flash, redirect, request
from app.courses.forms import CourseCreationForm , EnrollmentKeyForm
from flask_login import current_user, login_required
from app.models import User, Lecture ,Tutor, Student, Course
from werkzeug.urls import url_parse
from app.courses import courses
import random
import string

def randStr(chars = string.ascii_uppercase + string.digits, N=10):
	return ''.join(random.choice(chars) for _ in range(N))

@courses.route('/create-course' ,methods = ['GET','POST'])
@login_required
def create_course():
    form = CourseCreationForm()
    if form.validate_on_submit():
        course = Course(course_code=form.course_code.data,name=form.name.data,venue=form.venue.data,start_time=form.start_time.data,end_time=form.end_time.data,\
            day=form.day.data, key=form.key.data, number_of_tutors=form.number_of_tutors.data, lecturer=current_user.lecture)
        course.lecturer = current_user.lecture
        db.session.add(course)
        db.session.commit()
        return redirect(url_for('courses.my_courses'))
    return render_template('courses/create_course.html',title='Create a course',form=form)

# This function should allow the lecturer to create a new session for any of the courses
# they are lecturing
@courses.route('/create_session', methods = ['GET', 'POST'])
@login_required
def create_session():
    form = SessionRegForm(current_user.lecture.course)
    if form.validate_on_submit():
        session = Session(course = form.course.data, session_start = form.start_time.data, session_end = form.end_time.data, session_date = form.date.data)
        db.session.add(session)
        db.session.commit()
        return redirect(url_for('courses.view_sessions'))
    return render_template('courses/create_session.html',title='Create a session', form=form)

A = ["Session1", "Session2"]
B = ["Session Course", "Date", "start_time", "end_time"]
# Lecturer side
# This function should display the sesions created by the current lecturer
# A nd B are mockup items to test the view
@courses.route('/view_sessions')
@login_required
def view_session():
    return render_template('courses/view_sessions.html',title='View sessions', A=A, B=B)

A = ["Session1", "Session2"]
B = ["Session Course", "Date", "start_time", "end_time", "OTP"]
# This fuunction should search if there are sessions for the current
# tutor by checking if the are not any sessions available for the courses
# the tutor is registered for. When the tutor has an OTP already just reload page.
#
@courses.route('/view_sessions_tutor')
@login_required
def view_sessions_tutor():
    form =  GenerateOTP()
    return render_template('courses/view_sessions_tutor.html',title='View sessions', A=A, B=B, form=form)

@courses.route('/my-courses')
@login_required
def my_courses():
    return render_template('courses/my_courses.html',title='My courses')

@courses.route('/explore')
@login_required
def explore():
    courses = Course.query.all()
    return render_template('courses/explore.html', title='explore courses', courses=courses)

@courses.route('/apply')
@login_required
def apply():
    courses = Course.query.all()
    return render_template('courses/apply.html', title='apply for a courses', courses=courses)

@courses.route('/<course_code>')
@login_required
def show_course_details(course_code):
    course = Course.query.filter_by(course_code=course_code).first_or_404()
    return render_template('courses/show_course_details.html',title='course details', course=course)

@courses.route('/enroll/<course_code>' , methods=['GET','POST'])
@login_required
def enroll_in_a_course(course_code):
    form = EnrollmentKeyForm()
    course = Course.query.filter_by(course_code=course_code).first_or_404()
    if form.validate_on_submit():
        if current_user.student:
            current_user.student.enrolled_courses.append(course)
            db.session.commit()
            return redirect(url_for('student.student_home'))
        elif current_user.tutor:
            current_user.tutor.enrolled_courses.append(course)
            db.session.commit()
            return redirect(url_for('tutor.tutor_courses'))
    if request.method == "GET":
        form.course_code.data = course_code
    return render_template('courses/enroll.html',title=f'enroll in {course_code}' , form=form , course_code=course_code)

@courses.route('/course/<course_code>' , methods=['POST', 'GET'])
@login_required
def edit_course_details(course_code):
    form = CourseCreationForm()
    course = Course.query.filter_by(course_code=course_code).first_or_404()
    if form.validate_on_submit():
        course.course_code = form.course_code.data
        course.name = form.name.data
        course.venue = form.venue.data
        course.start_time = form.start_time.data
        course.end_time = form.end_time.data
        course.day = form.day.data
        course.number_of_tutors = form.number_of_tutors.data
        course.key = form.key.data
        db.session.commit()
        return redirect(url_for('courses.show_course_details', course_code=course_code))
    elif request.method == "GET":
        form.course_code.data = course.course_code
        form.name.data = course.name
        form.venue.data = course.venue
        form.number_of_tutors.data = course.number_of_tutors
        form.key.data = course.key
        form.start_time.data = course.start_time
        form.end_time.data = course.end_time
        form.day.data = course.day
        form.key.data = course.key
    return render_template('courses/create_course.html', title = 'Edit course details', form = form)


#
# Solution to Project Euler problem 151

def compute():
	ans = get_expected_singles((1,), {}) - 2
	return "{:.6f}".format(ans)

def get_expected_singles(state, memo):
	if state not in memo:
		result = 0.0
		if len(state) > 0:
			for i in range(len(state)):
				tempstate = list(state)
				sheet = state[i]
				del tempstate[i]
				for j in range(sheet + 1, 6):
					tempstate.append(j)
				tempstate.sort()
				result += get_expected_singles(tuple(tempstate), memo)
			result /= len(state)
			if len(state) == 1:
				result += 1.0
		memo[state] = result
	return memo[state]

if __name__ == "__main__":
	print(compute())


str1=input().split(' ')
L=int(str1[0])
T=int(str1[1])
O=int(str1[2])
color=[]
for i in range(L+1):
    color.append(1)
for i in range(O):
    str2=input().split(' ')
    if str2[0]=='C':
        for j in range(int(str2[1]),int(str2[2])+1):
            color[j]=int(str2[3])
    elif str2[0]=='P':
        ans=[]
        for j in range(int(str2[1]),int(str2[2])+1):
            ans.append(color[j])
        for m in range(len(ans)):
            for n in range(m+1,len(ans)):
                if ans[m]==ans[n]:
                    ans[n]=0
        count=0
        for i in range(len(ans)):
            if ans[i]!=0:
                count=count+1
        print(count)


from core.utils import parse_args, setup_determinism
from core.utils import build_loss_func, build_optim
from core.utils import build_scheduler, load_checkpoint
from core.config import get_cfg_defaults
from core.dataset import build_dataloader
from core.model import build_model, train_loop, valid_model, test_model
from core.model import valid_model_macro

from torch.utils.tensorboard import SummaryWriter
from torch.cuda.amp import GradScaler
import torch.nn as nn

import os

import torch.multiprocessing

torch.multiprocessing.set_sharing_strategy("file_system")

# SET UP GLOBAL VARIABLE
scaler = GradScaler()

def main(cfg, args):
    # Setup logger
    sum_writer = SummaryWriter(f"test2")

    # Declare variables
    best_metric = 0
    start_epoch = 0
    mode = args.mode

    # Setup folder
    if not os.path.isdir(cfg.DIRS.WEIGHTS):
        os.mkdir(cfg.DIRS.WEIGHTS)

    # Load Data
    trainloader = build_dataloader(cfg, mode="train")
    validloader = build_dataloader(cfg, mode="valid")
    testloader = build_dataloader(cfg, mode="test")

    # Define model/loss/optimizer/Scheduler
    model = build_model(cfg)
    # model = nn.DataParallel(model)
    loss = build_loss_func(cfg)
    optimizer = build_optim(cfg, model)
    scheduler = build_scheduler(args, len(trainloader), cfg)
    # Load model checkpoint
    model, start_epoch, best_metric = load_checkpoint(args, model)

    if cfg.SYSTEM.GPU:
        model = model.cuda()

    # Run Script
    if mode == "train":
        for epoch in range(start_epoch, cfg.TRAIN.EPOCHES):
            train_loss = train_loop(
                cfg,
                epoch,
                model,
                trainloader,
                loss,
                scheduler,
                optimizer,
                scaler,
                sum_writer,
            )
            best_metric = valid_model(
                cfg,
                mode,
                epoch,
                model,
                validloader,
                loss,
                sum_writer,
                best_metric=best_metric,
            )

    elif mode == "valid":
        valid_model(
            cfg, mode, 0, model, validloader, loss, sum_writer, best_metric=best_metric
        )
    elif mode == "test":
        test_model(cfg, mode, model, testloader, loss)

if __name__ == "__main__":
    # Set up Variable
    seed = 10

    args = parse_args()
    cfg = get_cfg_defaults()

    if args.config != "":
        cfg.merge_from_file(args.config)

    # Set seed for reproducible result
    setup_determinism(seed)

    main(cfg, args)


import asyncio
import random
from typing import Dict, List, Optional, Tuple, Union

import aiohttp

sources = [
    "http://w3.usf.edu/FreeAssociation/AppendixA/Cue_Target_Pairs.A-B",
    "http://w3.usf.edu/FreeAssociation/AppendixA/Cue_Target_Pairs.C",
    "http://w3.usf.edu/FreeAssociation/AppendixA/Cue_Target_Pairs.D-F",
    "http://w3.usf.edu/FreeAssociation/AppendixA/Cue_Target_Pairs.G-K",
    "http://w3.usf.edu/FreeAssociation/AppendixA/Cue_Target_Pairs.L-O",
    "http://w3.usf.edu/FreeAssociation/AppendixA/Cue_Target_Pairs.P-R",
    "http://w3.usf.edu/FreeAssociation/AppendixA/Cue_Target_Pairs.S",
    "http://w3.usf.edu/FreeAssociation/AppendixA/Cue_Target_Pairs.T-Z"
]
"""
Details:
http://w3.usf.edu/FreeAssociation/AppendixA/index.html

0  CUE     Normed Word
1  TARGET  Response to Normed Word
2  NORMED? Is Response Normed?
3  #G      Group size
4  #P      Number of Participants Producing Response
5  FSG     Forward Cue-to-Target Strength
6  BSG     Backward Target-to-Cue Strength
7  MSG     Mediated Strength
8  OSG     Overlapping Associate Strength
9  #M      Number of Mediators
10 MMIA    Number of Non-Normed Potential Mediating Associates
11 #O      Number of Overlaping Associates
12 OMIA    Number of Non-Normed Overlapping Associates
13 QSS     Cue: Set Size
14 QFR     Cue: Frequency
15 QCO     Cue: Concreteness
16 QH      Cue is a Homograph?
17 QPS     Cue: Part of Speech
18 QMC     Cue: Mean Connectivity Among Its Associates
19 QPR     Cue: Probability of a Resonant Connection
20 QRSG    Cue: Resonant Strength
21 QUC     Cue: Use Code
22 TSS     Target: Set Size
23 TFR     Target: Frequency
24 TCON    Target: Concreteness
25 TH      Target is a Homograph?
26 TPS     Target: Part of Speech
27 TMC     Target: Mean Connectivity Among Its Associates
28 TPR     Target: Probability of a Resonant Connection
29 TRSG    Target: Resonant Strength
30 TUC     Target: Use Code

Parts of Speech
N   Noun
V   Verb
AJ  Adjective
AD  Adverb
P   Pronoun
PP  Preposition
I   Interjection
C   Conjunction
"""

class association:
    def __init__(self, data: List[str]):
        self.cue = data[0]
        self.target = data[1]
        self.FSG = float(data[5])
        self.QPS = data[17]
        self.TPS = data[26]

    def __str__(self):
        return f"{self.cue} ({self.QPS}) -> {self.target} ({self.TPS}): {self.FSG}"

    def __repr__(self):
        return f"association({self.__str__()})"

def _parseResponse(response: str, assocData: Dict[str, List[str]], posData: Dict[str, List[str]]):
    passedCSVHeader = False
    for _line in response.splitlines():
        if not _line.startswith("<") and _line.strip() != "":
            if not passedCSVHeader:
                passedCSVHeader = True
                continue
            # _line = _line.replace("¥", "0")
            linedata = _line.split(",")
            linedata = [i.strip() for i in linedata]
            assoc = association(linedata)
            if assoc.QPS not in posData:
                posData[assoc.QPS] = []

            if assoc.cue in assocData:
                assocData[assoc.cue].append(assoc)
            else:
                assocData[assoc.cue] = [assoc]
                # First time we've encountered this cue, so add it to the POS data as well
                posData[assoc.QPS].append(assoc.cue)

async def _loadURL(url: str, assocData: Dict[str, List[str]], posData: Dict[str, List[str]], session: aiohttp.ClientSession):
    print(f"{url}: Downloading")
    response = await session.get(url)
    print(f"{url}: Parsing")
    _parseResponse(await response.text(), assocData, posData)
    print(f"{url}: Done")

async def load() -> Tuple[Dict[str, List[association]], Dict[str, List[str]]]:
    """
    Does all the loading of data.
    Returns two dictionaries: (associations, pos)

    Associations contains the associations for every word.
    POS contains a dict of parts of speech and every cue found that matches.
    """
    _assocs: Dict[str, List[association]] = {}
    _pos: Dict[str, List[str]] = {}
    session = aiohttp.ClientSession()
    await asyncio.gather(*[_loadURL(url, _assocs, _pos, session) for url in sources])
    return (_assocs, _pos)

assocData, posData = asyncio.run(load())
print("Finished loading word associations")

def getAssociations(cue: str, pos: Optional[str] = None) -> List[association]:
    """
    Gets the associations for a given part of speech (see above).
    If pos is None, all parts of speech will be accepted.
    """
    if cue.upper() not in assocData:
        return []
    associations: List[association] = []
    for assoc in assocData[cue.upper()]:
        if pos is None or assoc.TPS == pos.upper():
            associations.append(assoc)
    return associations

class cumulativeAssociation:
    def __init__(self, target: str, TPS: str, cues: Dict[str, float] = {}):
        self.target = target
        self.TPS = TPS
        self.cues = cues

    @property
    def FSG(self) -> float:
        return sum(self.cues.values())

    def __str__(self):
        return f"{self.target} ({self.TPS}): {self.FSG} {self.cues}"

    def __repr__(self):
        return f"cumulativeAssociation({self.__str__()})"

def getCumulativeAssociations(cues: List[str], pos: Optional[str] = None) -> List[cumulativeAssociation]:
    associations: Dict[str, cumulativeAssociation] = {}
    for cue in cues:
        cAssocs = getAssociations(cue.upper(), pos)
        for cAssoc in cAssocs:
            if cAssoc.target in associations:
                associations[cAssoc.target].cues[cAssoc.cue] = cAssoc.FSG
            else:
                associations[cAssoc.target] = cumulativeAssociation(
                    cAssoc.target, cAssoc.TPS, {cAssoc.cue: cAssoc.FSG})
    return list(associations.values())

def randWeightedAssociation(cue: Union[str, List[str]], pos: Optional[str] = None) -> Union[association, cumulativeAssociation]:
    if isinstance(cue, str):
        associations = getAssociations(cue.upper(), pos)
    else:
        associations = getCumulativeAssociations(cue, pos)
    if len(associations) == 0:
        return None
    return random.choices(associations, [assoc.FSG for assoc in associations])[0]

def randUnweightedAssociation(cue: Union[str, List[str]], pos: Optional[str] = None) -> Union[association, cumulativeAssociation]:
    if isinstance(cue, str):
        associations = getAssociations(cue.upper(), pos)
    else:
        associations = getCumulativeAssociations(cue, pos)
    if len(associations) == 0:
        return None
    return random.choice(associations)

def randomWord(pos: Optional[str] = None) -> str:
    """
    Selects a random word of a given part of speech (see above).
    If pos is None, all parts of speech will be accepted.
    """
    if pos is None:
        return random.choice(random.choices(posData, [len(s) for s in posData.values()])[0])
    elif pos not in posData or len(posData[pos]) == 0:
        return None
    else:
        return random.choice(posData[pos])


# -*- coding: utf-8 -*-

from openerp import fields, models, api, _
from openerp.exceptions import ValidationError

class HrExpenseExpense(models.Model):
    _inherit = 'hr.expense.expense'

    level_id = fields.Many2one(
        'level.validation',
        string='Validation Level',
        track_visibility='onchange',
        copy=False,
    )
    approver_ids = fields.Many2many(
        'res.users',
        'hr_approver_rel', 'expense_id', 'user_id',
        string='Approver',
        track_visibility='onchange',
        copy=False,
    )
    approve_permission = fields.Boolean(
        string='Approve Permission',
        compute='_compute_approve_permission',
    )
    state = fields.Selection(
        selection=[
            ('draft', 'New'),
            ('cancelled', 'Refused'),
            ('confirm', 'Waiting Approval'),
            ('validate', 'Waiting Validate'),
            ('accepted', 'Approved'),
            ('done', 'Waiting Payment'),
            ('paid', 'Paid'),
        ],
    )

    @api.multi
    def action_check_approval(self):
        self.ensure_one()
        amount = self.amount
        doctype = ''
        if self.is_employee_advance:
            doctype = 'employee_advance'
        elif self.is_advance_clearing:
            doctype = 'employee_clearing'
        elif not self.is_advance_clearing and not self.is_employee_advance:
            doctype = 'employee_expense'

        levels = self.env['level.validation'].search([
            ('operating_unit_id', '=', self.operating_unit_id.id),
            ('doctype', 'like', doctype),
        ]).sorted(key=lambda r: r.level)

        if not levels:
            raise ValidationError(_("This operating unit does not "
                                    "set approver."))
        levels_lt_amount = levels.filtered(
            lambda r: r.limit_amount < amount)
        levels_gt_amount = levels.filtered(
            lambda r: r.limit_amount >= amount)

        if levels_gt_amount:
            target_levels = levels_lt_amount + levels.filtered(
                lambda r: r.level == min(levels_gt_amount.mapped('level')))
        else:
            target_levels = levels_lt_amount
            if not target_levels.filtered(
                    lambda r: r.limit_amount >= amount):
                raise ValidationError(_("Amount is over "
                                        "maximum limited amount."))

        if self.approver_ids and self.env.user not in self.approver_ids:
            raise ValidationError(_("Your user is not allow to "
                                    "approve this document."))
        if target_levels:
            if self.level_id:
                min_level = min(filter(
                        lambda r: r >= self.level_id.level,
                        target_levels.mapped('level')))
                target_level = target_levels.filtered(
                    lambda r: r.level == min_level + 1)
                if target_level:
                    self.write({
                        'level_id': target_level.id,
                        'approver_ids': [
                            (6, 0, target_level.user_ids.ids)
                        ],
                    })
                else:
                    self.write({
                        'level_id': False,
                        'approver_ids': False,
                    })
            else:
                if not self.level_id and not self.approver_ids:
                    target_level = target_levels.filtered(
                        lambda r: r.level == min(target_levels.mapped('level'))
                    )
                    self.write({
                        'level_id': target_level.id,
                        'approver_ids': [
                            (6, 0, target_level.user_ids.ids)
                        ],
                    })
        return True

    @api.depends('approver_ids')
    def _compute_approve_permission(self):
        for order in self:
            order.approve_permission = bool(self.env.user in order.approver_ids)

    @api.multi
    def action_validated(self):
        self.ensure_one()
        return self.write({'state': 'validate'})

    @api.multi
    def expense_accept(self):
        self.ensure_one()
        res = super(HrExpenseExpense, self).expense_accept()
        product_lines = self.env['hr.expense.line'].search([
            ('expense_id', '=', self.id)
        ]).mapped('product_id')
        hr_category_id = self.env['product.category'].search([
            ('name', 'like', 'HR Products'),
        ])
        hr_product = product_lines.filtered(
            lambda r: r.categ_id == hr_category_id
        )
        group_hr = self.env.ref('base.group_hr_manager')
        if hr_product and self.env.user not in group_hr.users:
            raise ValidationError(_("Your user is not allowed to "
                                    "validate this document."))
        return res


# time complexity O(n^2), space complexity O(n)

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        ab = {}
        for i, num in enumerate(nums):
            if num not in ab: ab[num] = []
            ab[num].append(i)

        for _, items in ab.items():
            if any([abs(i - j) <= k for i in items for j in items if i != j]): return True
        return False


#Reverse Cipher
#This will take a users inputted text and reverse it showing each output from the while loop
message = input('Enter message: ')
translated = ''

i = len(message) - 1
while i >= 0:
        translated = translated + message[i]
        print(i, message[i], translated)
        i = i - 1

print(translated)


import acm

def get_time_series_values(ts_name, recaddr1=None, recaddr2=None, date=None):
    """Return the time-series entities that match the provided parameters."""

    tsSpec = acm.FTimeSeriesDvSpec[ts_name]
    if tsSpec:
        # creating the select cmd
        cmd = "timeSeriesDvSpecification={0}".format(tsSpec.Oid())
        if recaddr1:
            cmd = "{0} and recordAddress1={1}".format(cmd, recaddr1)
        if recaddr2:
            cmd = "{0} and recordAddress2={1}".format(cmd, recaddr2)
        if date:
            cmd = "{0} and storageDate='{1}'".format(cmd, date)

        ts = acm.FTimeSeriesDv.Select(cmd)
        return ts
    else:
        return None

def remove_time_series_values(ts_name, recaddr1=None, recaddr2=None, date=None):
    """Remove the time-series entities that match the provided parameters.

    Returns the number of removed entities.
    """

    removed_ts = 0
    existing_ts = get_time_series_values(ts_name, recaddr1, recaddr2, date)

    if existing_ts:
        removed_ts = len(existing_ts)
        for t in existing_ts:
            t.Delete()
    return removed_ts

def add_time_series_value(ts_name, recaddr1, recaddr2, date, dv):
    """Create a denominated time-series entry.

    Args:
        ts_name: Time series name (string)
        recaddr1: Record address value (int)
        recaddr2: Record address value (int)
        date: Storage date of a time series (date)
        dv: An FDenominatedVaue object (FDenominatedValue)

    Returns:
        Function returns existing or newly created FTimeSeriesDv object.

    Raises:
        ValueError: An error when time series spec is not defined
    """

    ts_spec = acm.FTimeSeriesDvSpec[ts_name]
    if ts_spec:
        existing_ts = get_time_series_values(ts_name, recaddr1, recaddr2, date)
        if len(existing_ts) == 1:
            return existing_ts.First()

        ts = acm.FTimeSeriesDv()
        ts.TimeSeriesDvSpecification(ts_spec)
        ts.RecordAddress1(recaddr1)
        ts.RecordAddress2(recaddr2)
        ts.StorageDate(date)
        ts.DvValue(dv.Number())
        ts.DvDate(dv.DateTime())
        try:
            ts.DvCurrency(dv.Unit())
        except TypeError:
            # suppress the error if it's not possible
            # to convert the unit to FCurrency
            pass
        ts.Commit() # don't catch exceptions, this should be done by the caller
        return ts
    else:
        raise ValueError('Time-series {0} has not been defined.'.format(ts_name))

def update_time_series_value(ts_name, recaddr1, recaddr2, date, dv):
    """Creates or updates time-series entity.

    Args:
        ts_name: Time series name (string)
        recaddr1: Record address value (int)
        recaddr2: Record address value (int)
        date: Storage date of a time series (date)
        dv: An FDenominatedVaue object (FDenominatedValue)
    """

    existing_ts = get_time_series_values(ts_name, recaddr1, recaddr2, date)

    if len(existing_ts) == 1:
        ts = existing_ts.First()
        ts_clone = ts.Clone()

        ts_clone.StorageDate(date)
        ts_clone.DvValue(dv.Number())
        ts_clone.DvDate(dv.DateTime())
        try:
            ts_clone.DvCurrency(dv.Unit())
        except TypeError:
            # suppress the error if it's not possible
            # to convert the unit to FCurrency
            pass
        ts.Apply(ts_clone)
        try:
            ts.Commit()
        except RuntimeError:
            # supress update colission or deadlocked on lock
            # resources with another process error
            pass
        return ts
    else:
        return add_time_series_value(ts_name, recaddr1, recaddr2, date, dv)


import stds
from termcolor import colored

def recursive_selection(x):
    if x == 1:
        stds.tcp_scan()
    elif x == 2:
        stds.syn_scan()
    elif x == 3:
        stds.udp_scan()
    elif x == 4:
        stds.ack_scan()
    elif x == 5:
        stds.window_scan()
    elif x == 6:
        stds.fin_scan()
    elif x == 7:
        pass
    else:
        print('invalid choice')
        recursive_number()

def recursive_number():
    try:
        sel = int(input())
        recursive_selection(sel)
    except ValueError:
        print('wrong input')
        recursive_number()

print(colored('Just Another Port Scanner', 'magenta', attrs=['bold']))
print(colored('by a547b343', 'green', attrs=['bold']))
print()

scantypes = {
    'TCP scan' : 1,
    'SYN scan' : 2,
    'UDP scan': 3,
    'ACK scan': 4,
    'WINDOW scan': 5,
    'FIN scan': 6,
    'other' : 7,
}

other = {
    'XMAS scan' : 1,
    'NULL scan' : 2,
    'PROTOCOL scan': 3,
    'PROXY scan': 4,
    'IDLE scan': 5,
    'CAT scan': 6,
    'ICMP scan' : 7,
}

print('---------------------------')
print()

recursive_number()


from PIL import Image
from bs4 import BeautifulSoup
import os
import requests

if not os.path.exists(os.path.abspath('pages/')):
    os.mkdir(os.path.abspath('pages/'))

if not os.path.exists(os.path.abspath('frames/')):
    os.mkdir(os.path.abspath('frames/'))

now_pages = 300

for i in range(2, now_pages + 1):
    url = 'http://skyboxcomic.com/'
    url_comics = 'http://skyboxcomic.com/comics/'

    path = os.path.abspath('pages/' + str(i) + '.jpg')

    print('Viewing:', i)

    if not os.path.exists(path):  # don't download if we have already page
        url_r = requests.get(url_comics + str(i))
        bs = BeautifulSoup(url_r.content)
        print('Downloading:', i, url + bs.find_all('img', {'id': 'comicimage'})[0]['src'])  # human readable
        r = requests.get(url + bs.find_all('img', {'id': 'comicimage'})[0]['src'], stream=True)  # get file stream
        with open(path, 'wb') as f:  # copy paste from stackoverflow, download file
            for chunk in r.iter_content(chunk_size=2048):
                if chunk:
                    f.write(chunk)
                else:
                    print(chunk)

num = 0

for j in range(2, now_pages + 1):
    image = '{}.jpg'.format(j)
    im = Image.open(os.path.abspath('pages/' + image))
    count = im.size[1] // 338

    # frames = []  # for gifs

    print('Working page:', image, 'Frames done:', num)

    for i in range(count):
        frame_path = os.path.abspath('frames/' + str(num) + '.jpg')
        if not os.path.exists(frame_path):
            box = (0, i * 338, im.size[0], (i + 1) * 338)
            region = im.crop(box)
            region = region.resize((region.size[0], region.size[1]))
            region.save(frame_path, quality=90)
        num += 1
        # region = region.convert(mode='P', palette=Image.ADAPTIVE)  # for gifs
        # frames.append(region)  # for gifs

    # frames[0].save('animation.gif', append_images=frames[1:], save_all=True, duration=250, loop=0)  # for gifs


import logging
import random
import string

from accounts.models import Customer
from django.db import IntegrityError, models
from products.models import Product

logger = logging.getLogger(__name__)
CODE_LENGTH = 4
SAVE_CODE_ATTEMPTS = 20

class Code(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    code = models.CharField(max_length=7, unique=True)
    create_date = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.code

    def generate_code(self):
        """ Generate random string from template
            [0-9a-b]-[0-9a-b]-[0-9a-b]-[0-9a-b]
        """
        # deside if it number or char
        characters = []
        for i in range(CODE_LENGTH):
            char = ""
            if random.randint(0, 1):
                char = random.choice(string.ascii_lowercase)
            else:
                char = str(random.randint(0, 9))
            if not char:
                raise ValueError()

            characters.append(char)
        return "-".join(characters)

    def save(self, *args, **kwargs):
        """ Overriden save method
            make an attempt to save generated code and if there
            not unique code - try generate new code
        """
        if not self.pk:
            attempt = 0
            while True:
                self.code = self.generate_code()
                try:
                    super().save(*args, **kwargs)
                except IntegrityError as e:
                    if "unique_constraint" in e.message.lower():
                        if attempt < SAVE_CODE_ATTEMPTS:
                            continue
                        else:
                            logger.error(
                                "Unable to create discount code",
                                "Maximum attempts count exceed",
                            )
                            raise IntegrityError(e)
                    else:
                        logging.error("Unable to create discount code", e)
                        raise IntegrityError(e)
                else:
                    break
        else:
            super().save(*args, **kwargs)


import pygame
import os
import time

pygame.init()
size = width, height = 1000, 700
screen = pygame.display.set_mode(size)
screen.fill((255, 255, 255))
all_sprites = pygame.sprite.Group()
fishes = pygame.sprite.Group()
shark = pygame.sprite.Group()
ontime = 0
running = True
clock = pygame.time.Clock()
speed = 10

def load_image(name, colorkey=None):
    fullname = os.path.join('data', name)
    image = pygame.image.load(fullname).convert()
    if colorkey is not None:
        if colorkey == -1:
            colorkey = image.get_at((0, 0))
        image.set_colorkey(colorkey)
    else:
        image = image.convert_alpha()
    return image

fon = pygame.transform.scale(load_image('background.jpg'), (width, height))
screen.blit(fon, (0, 0))

def cut_sheet(self, sheet, columns, rows, frames):
    self.rect = pygame.Rect(0, 0, sheet.get_width() // columns,
                            sheet.get_height() // rows)
    for j in range(rows):
        for i in range(columns):
            frame_location = (self.rect.w * i, self.rect.h * j)
            frames.append(sheet.subsurface(pygame.Rect(
                frame_location, self.rect.size)))

player = 0

class Sharky(pygame.sprite.Sprite):
    def __init__(self, x, y):
        global player
        super().__init__(all_sprites)
        self.swimframes = []
        self.moveframes = []
        self.eatframes = []
        self.rect = pygame.Rect((0, 0), (207, 85))
        for i in range(1, 6):
            sheet = load_image(f'bluesharkswim(' + str(i) + ').png', colorkey=-1)
            self.swimframes.append(sheet.subsurface(pygame.Rect(
                (0, 0), sheet.get_rect().size)))
        for i in range(1, 11):
            sheet = load_image(f'bluesharkmove' + str(i) + '.png', colorkey=-1)
            self.moveframes.append(sheet.subsurface(pygame.Rect(
                (0, 0), sheet.get_rect().size)))
        cut_sheet(self, load_image('bluesharkeat.png', colorkey=-1), 2, 1, self.eatframes)
        self.add(shark)
        self.cur_frame = 0
        self.image = self.swimframes[self.cur_frame]
        self.rect = self.rect.move(x, y)
        player = self
        self.count = 0
        self.mask = pygame.mask.from_surface(self.image)
        self.mov = 0

    def update(self):
        self.count += 1
        if self.count == 25:
            self.cur_frame = (self.cur_frame + 1) % len(self.swimframes)
            if self.mov == 9:
                self.image = pygame.transform.flip(self.swimframes[self.cur_frame], 90, 0)
            else:
                self.image = self.swimframes[self.cur_frame]
            self.count = 0

    def movement(self, dir):
        if dir == -1:
            self.image = self.moveframes[self.mov]
            self.mov += 1
        elif dir == 1:
            self.image = self.moveframes[self.mov]
            self.mov -= 1

class Fish(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__(all_sprites)
        self.add(fishes)
        self.swimframes = []
        cut_sheet(self, load_image('yellowfishswim.png', colorkey=-1), 6, 1, self.swimframes)
        self.cur_frame = 0
        self.image = self.swimframes[self.cur_frame]
        self.rect = self.rect.move(x, y)
        self.count = 0
        self.mask = pygame.mask.from_surface(self.image)

    def update(self):
        self.count += 1
        if pygame.sprite.collide_mask(self, player):
            if player.mov <= 4:
                player.image = player.eatframes[0]
                player.image = player.eatframes[1]
            else:
                player.image = pygame.transform.flip(player.eatframes[0], 90, 0)
                player.image = pygame.transform.flip(player.eatframes[1], 90, 0)
            self.kill()
            for i in range(len(player.swimframes)):
                player.swimframes[i] = pygame.transform.smoothscale(player.swimframes[i],
                                                                    (player.swimframes[i].get_width(),
                                                                     player.swimframes[i].get_height()))

        if self.count == 20:
            self.cur_frame = (self.cur_frame + 1) % len(self.swimframes)
            self.image = self.swimframes[self.cur_frame]
            self.count = 0

speed = 100
motion = 'STOP'
Sharky(200, 200)
direct = 1
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                motion = 'LEFT'
            elif event.key == pygame.K_RIGHT:
                motion = 'RIGHT'
            elif event.key == pygame.K_UP:
                motion = 'UP'
            elif event.key == pygame.K_DOWN:
                motion = 'DOWN'
        elif event.type == pygame.MOUSEBUTTONDOWN:
            Fish(event.pos[0], event.pos[1])
        elif event.type == pygame.KEYUP:
            if event.key in [pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_DOWN]:
                motion = 'STOP'

    if motion == 'LEFT':
        if player.mov < 9:
            player.movement(-1)
        else:
            player.rect.x -= 3
    elif motion == 'RIGHT':
        if player.mov > 0:
            player.movement(1)
        else:
            player.rect.x += 3
    elif motion == 'DOWN':
        player.rect.y += 3
    elif motion == 'UP':
        player.rect.y -= 3

    screen.blit(fon, (0, 0))
    all_sprites.draw(screen)
    all_sprites.update()
    pygame.display.flip()
    clock.tick(speed)


# from db_init import g.db, Base
from sqlalchemy import Table, Column, Integer, Text, ForeignKey, String, Boolean
from sqlalchemy.orm import relationship, backref, make_transient, class_mapper
import datetime
import re
from flask import g
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import event
from utils.validators import validators

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

# this event is called whenever an attribute
# on a class is instrumented
@event.listens_for(Base, 'attribute_instrument')
def configure_listener(class_, key, inst):
    if not hasattr(inst.property, 'columns'):
        return
    # this event is called whenever a "set"
    # occurs on that instrumented attribute

    @event.listens_for(inst, "set", retval=True)
    def set_(instance, value, oldvalue, initiator):
        validator = validators.get(inst.property.columns[0].type.__class__)
        if validator:
            return validator(value)
        else:
            return value

class PRBase:
    def __init__(self):
        self.query = g.db.query_property()

    def save(self):
        g.db.add(self)
        g.db.flush()
        return self

    def attr(self, dictionary):
        for k in dictionary:
            setattr(self, k, dictionary[k])
        return self

    def detach(self):
        g.db.expunge(self)
        make_transient(self)
        self.id = None
        return self

    def expunge(self):
        g.db.expunge(self)
        return self

    def get_client_side_dict(self, fields='id'):
        return self.to_dict(fields)

    @classmethod
    def get(cls, id):
        return g.db().query(cls).get(id)

# TODO: OZ by OZ:**kwargs should accept lambdafunction for fields formattings
    def to_dict(self, *args, prefix=''):
        ret = {}

        req_columns = {}
        req_relationships = {}

        for arguments in args:

            for argument in re.compile('\s*,\s*').split(arguments):
                columnsdevided = argument.split('.')
                column_names = columnsdevided.pop(0)
                for column_name in column_names.split('|'):
                    if len(columnsdevided) == 0:
                        req_columns[column_name] = True
                    else:
                        if column_name not in req_relationships:
                            req_relationships[column_name] = []
                        req_relationships[column_name].append(
                            '.'.join(columnsdevided))

        columns = class_mapper(self.__class__).columns
        realations = {a: b for (a, b) in class_mapper(self.__class__).
            relationships.items()}

        get_key_value = lambda o: o.strftime('%c') if isinstance(
            o, datetime.datetime) else o
        for col in columns:
            if col.key in req_columns or '*' in req_columns:
                ret[col.key] = get_key_value(getattr(self, col.key))
                if col.key in req_columns:
                    del req_columns[col.key]
        if '*' in req_columns:
            del req_columns['*']

        if len(req_columns) > 0:
            columns_not_in_relations = list(set(req_columns.keys()) -
                                            set(realations.keys()))
            if len(columns_not_in_relations) > 0:
                raise ValueError(
                    "you requested not existing attribute(s) `%s%s`" % (
                        prefix, '`, `'.join(columns_not_in_relations),))
            else:
                raise ValueError("you requested for attribute(s) but "
                                 "relationships found `%s%s`" % (
                    prefix, '`, `'.join(set(realations.keys()).
                                        intersection(
                            req_columns.keys())),))

        for relationname, relation in realations.items():
            if relationname in req_relationships or '*' in \
                    req_relationships:
                if relationname in req_relationships:
                    nextlevelargs = req_relationships[relationname]
                    del req_relationships[relationname]
                else:
                    nextlevelargs = req_relationships['*']
                related_obj = getattr(self, relationname)
                if relation.uselist:
                    ret[relationname] = [
                        child.to_dict(*nextlevelargs,
                                      prefix=prefix + relationname + '.'
                                      ) for child in
                                         related_obj]
                else:
                    ret[relationname] = None if related_obj is None else related_obj.to_dict(*nextlevelargs, prefix=prefix + relationname + '.')

        if '*' in req_relationships:
            del req_relationships['*']

        if len(req_relationships) > 0:
            relations_not_in_columns = list(set(
                req_relationships.keys()) - set(columns))
            if len(relations_not_in_columns) > 0:
                raise ValueError(
                    "you requested not existing relation(s) `%s%s`" % (
                        prefix, '`, `'.join(relations_not_in_columns),))
            else:
                raise ValueError("you requested for relation(s) but "
                                 "column(s) found `%s%s`" % (
                    prefix, '`, `'.join(set(columns).intersection(
                        req_relationships)),))

        return ret

        # @staticmethod
        # def searchResult(collection, convert_item = lambda item: item.dict()):
        #     ret = {}
        #     for x in collection:
        #         ret[x.id] = convert_item(x)
        #
        #     return ret


"""REST_API_Project URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/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, path
from rest_framework import routers
from REST_API_App import views

router = routers.DefaultRouter()
router.register(r'shops', views.ShopsViewSet)
router.register(r'category', views.CategoryViewSet)
router.register(r'product', views.ProductViewSet)
router.register(r'media', views.MediaViewSet)

urlpatterns = [
    path('', include(router.urls)),
    # path(r'^api/(?P<id>\w{0,50})/$', views.FetchAPIData.as_view(), name='FetchAPIData'),
    path('api/product', views.FetchAPIData.as_view(), name='FetchAPIData'),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))

]


from opengever.base.interfaces import IRoleAssignmentReportsStorage
from opengever.base.role_assignments import ASSIGNMENT_VIA_PROTECT_DOSSIER
from opengever.base.role_assignments import ASSIGNMENT_VIA_SHARING
from opengever.base.role_assignments import RoleAssignmentManager
from opengever.base.storage import STATE_IN_PROGRESS
from opengever.base.storage import STATE_READY
from opengever.nightlyjobs.provider import NightlyJobProviderBase
from plone import api
from zope.component.hooks import getSite
from zope.component.hooks import setSite
import gc

class NightlyRoleAssignmentReports(NightlyJobProviderBase):

    def __init__(self, context, request, logger):
        super(NightlyRoleAssignmentReports, self).__init__(context, request, logger)

        self.storage = IRoleAssignmentReportsStorage(self.context)
        self.catalog = api.portal.get_tool('portal_catalog')

    def __iter__(self):
        return iter([el for el in self.storage.list() if el['state'] == STATE_IN_PROGRESS])

    def __len__(self):
        return len([el for el in self.storage.list() if el['state'] == STATE_IN_PROGRESS])

    def collect_garbage(self, site):
        # In order to get rid of leaking references, the Plone site needs to be
        # re-set in regular intervals using the setSite() hook. This reassigns
        # it to the SiteInfo() module global in zope.component.hooks, and
        # therefore allows the Python garbage collector to cut loose references
        # it was previously holding on to.
        setSite(getSite())

        # Trigger garbage collection for the cPickleCache
        site._p_jar.cacheGC()

        # Also trigger Python garbage collection.
        gc.collect()

        # (These two don't seem to affect the memory high-water-mark a lot,
        # but result in a more stable / predictable growth over time.
        #
        # But should this cause problems at some point, it's safe
        # to remove these without affecting the max memory consumed too much.)

    def run_job(self, job, interrupt_if_necessary):
        principalid = job['principal_id']
        reportid = job['report_id']
        items = []

        # if Anonymous or Authenticated have View permission,
        # no other users are set in allowedRolesAndUsers
        brains = self.catalog.unrestrictedSearchResults(
            sort_on='path',
            portal_type=['opengever.dossier.businesscasedossier',
                         'opengever.repository.repositoryfolder',
                         'opengever.repository.repositoryroot'],
            allowedRolesAndUsers=[u'user:{}'.format(principalid), 'Authenticated', 'Anonymous'])

        self.logger.info("Complete report %r" % reportid)

        for i, brain in enumerate(brains):
            if i % 5000 == 0:
                self.collect_garbage(self.context)
            obj = brain.getObject()
            assignments = RoleAssignmentManager(obj).get_assignments_by_principal_id(principalid)
            manual_assignments = [
                assignment for assignment in assignments
                if assignment.cause in [ASSIGNMENT_VIA_SHARING,
                                        ASSIGNMENT_VIA_PROTECT_DOSSIER]]
            if manual_assignments:
                roles = filter(lambda r: r != 'Owner', manual_assignments[0].roles)
                if roles:
                    items.append({'UID': obj.UID(), 'roles': roles})

        report_data = {'state': STATE_READY, 'items': items}
        self.storage.update(reportid, report_data)


import FWCore.ParameterSet.Config as cms

###########################################################
#identification stuff                                     #
###########################################################
eIdBase = cms.PSet(
    #Need to put in the variable values.
    detain=cms.double(99.),
    delphi= cms.double(99.),
    sieie= cms.double(99.),
    hoe=cms.double(99.),
    d0vtx=cms.double(-1.),
    dzvtx=cms.double(-1.),
    ooemoop=cms.double(99.),
    dist=cms.double(0.0),
    dcot=cms.double(0.0),
    hasConv=cms.double(-1.),
    nmisHit=cms.double(99.)
    )

##########################################################################
##usePfIso=True) iso1=chHadIso;iso2=neHadIso;iso3=gamIso;iso4=combIso    #
##else iso1=tkIso;iso2=ecalIso;iso3=hcalIso;iso4=combIso                 #
##########################################################################
eIsoBase = cms.PSet(
    iso1 = cms.double(9999.),
    iso2 = cms.double(9999.),
    iso3 = cms.double(9999.),
    iso4 = cms.double(9999.)
    )

#######################################
#Base Electron Selector Configuration #
#######################################
eSelBase = cms.PSet(
    ptx= cms.double(20),
    etax= cms.double(2.4),
    ##Identification
    idBrl = eIdBase,
    idEcp = eIdBase,
    ##Isolation: Detector Based Rel Iso.
    coneRad= cms.double(0.3),
    usePfIso= cms.bool(True),
    useCombIso = cms.bool(True),
    useRelIso= cms.bool(True),
    rhoCorr  = cms.bool(True),
    isoBrl = eIsoBase,
    isoEcp = eIsoBase
    )

#####################################
#Some Over Fastidiousness           #
#####################################

#non-combined relative detector based iso
eSelBaseWithNonCombRelDetIso = eSelBase.clone()

#non-combined absolute detector based iso
eSelBaseWithNonCombAbsDetIso = eSelBase.clone()
eSelBaseWithNonCombAbsDetIso.useRelIso= cms.bool(False)

#combined relative detector based iso
eSelBaseWithCombRelDetIso = eSelBaseWithNonCombRelDetIso.clone()
eSelBaseWithCombRelDetIso.useCombIso = cms.bool(True)

#combined absoulte detector based iso
eSelBaseWithCombAbsRelDetIso = eSelBaseWithCombRelDetIso.clone()
eSelBaseWithCombAbsRelDetIso.useRelIso = cms.bool(True)


import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    url(r'^$', 'core.views.index'),
    url(r'^search$', 'core.views.search'),
    url(r'^manager$', 'core.views.event_manager'),
    url(r'^mobile', include('mobile.urls')),

    #url(r'^', include('events.urls')),
    url(r'^', include('talks.urls')),

    url(r'^talks$', 'talks.views.talk_list'),
    url(r'^speakers$', 'core.views.speaker_list'),

    url(r'^', include('engagements.urls')),
    url(r'^', include('core.urls')),
    url(r'^', include('locations.urls')),
    url(r'^', include('blog.urls')),
    url(r'^feedback/', include('feedback.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    #url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
    url(r'^grappelli/', include('grappelli.urls')),
    url('^markdown/', include( 'django_markdown.urls')),
)

if settings.DEBUG:
    urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


#!/usr/bin/env python3

"""
A class-based system for rendering html.
"""

# This is the framework for the base class
#  --- Step1-------------------
class Element(object):
    tag = "html"
    ind = '   '

    def __init__(self, content=None, **kwargs):
        if content is None:
            self.contents = []
        else:
            self.contents = [content]
        print("contents is:", self.contents)
        self.kwargs = kwargs
        print("kwargs are", self.kwargs)
    def append(self, new_content):
        self.contents.append(new_content)

    def render(self, file_out, cur_ind=''):
        # loop through the list of contents:
        open_tag = ["<{}".format(self.tag)]     #added in step 4
        open_tag.append(">\n")                  #added in step 4
        file_out.write("".join(open_tag))        #added in step 4
#        file_out.write("<{}>\n".format(self.tag)) # over written in step4
        for k, v in self.kwargs.items():
            file_out.write(' {}="{}"'.format(k, v))
        file_out.write('>\n')
        for content in self.contents:
            try:
                content.render(file_out, f'{cur_ind}{self.ind}')
            except AttributeError:
                file_out.write(f'{cur_ind}{self.ind}{str(content)}\n')
        file_out.write(f'{cur_ind}</{self.tag}>\n')

    def add_attrs(self, file_out, cur_ind):
        """Add attributes."""
        file_out.write(f'{cur_ind}<{self.tag}')
        for k, v in self.attrs.items():
            file_out.write(' {}="{}"'.format(k, v))

 #  --- Step2-------------------
class Html(Element):     #Common practice of Cap_1 for classes and subclasses
    tag = "html"

    def render(self, file_out, cur_ind=''):
        file_out.write(f'{cur_ind}<!DOCTYPE html>\n')
        super().render(file_out, cur_ind)

class Body(Element):   #entire contents of an html page subclass
    tag = "body"

class P(Element):   #paragraph element subclass
    tag = "p"

#  --- Step3-/-Step4------------------
class Head(Element):     #Common practice of Cap_1 for classes and subclasses
    tag = "head"

class OneLineTag(Element):
    tag = "oneliner"
    def render(self, file_out, cur_ind='', **kwargs):   # Introduce key wordarguments
#    def render(self, file_out):    # Updated above
        def append(self, content, cur_ind):
            raise NotImplementedError
        file_out.write("<{}>".format(self.tag))

        for k, v in self.kwargs.items():    # extract Attributes for test
            file_out.write(' {}="{}"'.format(k, v))
        file_out.write('>\n')

        file_out.write(self.contents[0])
        file_out.write("</{}>\n".format(self.tag))
#        file_out.write('\t<' + self.tag +'>' + self.content[0] + '</' + self.tag + 'v>\n')
#          Note: compression above is equivelant of render class detail above

class Title(Element):
    tag = "title"

#  --- Step5---Self Closing Tag, line Break-/horizontal rule---------------

class SelfClosingTag(Element):

    def __init__(self, content=None, **kwargs):
        if content is not None:
            raise TypeError("SelfClosingTag can not contain any content")
        super().__init__(content=content, **kwargs)

    def append(self, *args):
        raise TypeError("You can not add content to a SelfClosingTag")

    def render(self, file_out, cur_ind='', **kwargs):
        file_out.write(cur_ind + f'<{self.tag}')
        for k, v in self.kwargs.items():
            file_out.write(' {}="{}"'.format(k, v))
        file_out.write(' />\n')

class Hr(SelfClosingTag):   # horizontal rule
    tag = "hr"

class Br(SelfClosingTag):   # line break
    tag = "br"

#  --- Step6---Link---------------

class A(Element):  # 'Not sure how to include second content "link" in report
    tag = 'a'
    def __init__(self, link, content=None, **kwargs):
        super().__init__(content, **kwargs)

    def render(self, file_out, cur_ind='', **kwargs):  # could not get _Open/_Close_tag to work
        file_out.write(cur_ind + f'<{self.tag}')
        for k, v in self.kwargs.items():
            file_out.write(' {}="{}"'.format(k, v))
        file_out.write(' />\n')

#  --- Step7---list elements---------------

class Ul(Element):
    tag = "u_list"

class Li(Element):
    tag = "l_elem"

#class Header(OneLineTag): #Note: "Header" from instrutions. "H" to match run file
class H(OneLineTag):
    def __init__(self, level, content):
        super().__init__(content)
        self.tag = f'h{level}'

#  --- Step8---DOC Type---------------
#  insert above:  file_out.write(f'{cur_ind}<!DOCTYPE html>\n')
#  ----------------------------------
class Meta(SelfClosingTag):  #Note: Required to address character set
    def __init__(self, charset):
        self.tag = 'meta' + ' charset="' + charset + '"'
        Element.__init__(self)

#  --- Step9---adding Indentation--------------