from numpy import genfromtxt
import csv
import numpy as np
import math
import matplotlib.pyplot as plt
import copy
import random
import torch
from torch import nn
import datetime

def read_csv(filename):
    with open(filename, newline='') as f_input:
        data = []
        i=0
        for row in csv.reader(f_input):
            if i == 0:
                i = 1
                continue
            data.append(list(map(float, row)))
        return data

# Define Model.
class MLP(torch.nn.Module):
    def __init__(self, IDs_len, REGs_len):
            super(MLP, self).__init__()

            self.I_branch = nn.Sequential(
                nn.Linear(IDs_len, 64),
                nn.ReLU()
            )
            self.R_branch = nn.Sequential(
                nn.Linear(REGs_len, 48),
                nn.ReLU()
            )
            self.D_branch = nn.Sequential(
                nn.Linear(31, 48),
                nn.ReLU()
            )
            self.M_branch = nn.Sequential(
                nn.Linear(12, 32),
                nn.ReLU()
            )
            self.Y_branch = nn.Sequential(
                nn.Linear(2, 16),
                nn.ReLU()
            )
            self.T_branch = nn.Sequential(
                nn.Linear(2, 16),
                nn.ReLU()
            )
            ######
            self.time_branch = nn.Sequential(
                nn.Linear(96, 128),
                nn.ReLU(),
                #nn.Dropout(0.5),
                nn.Linear(128, 64),
                nn.ReLU()
            )
            self.DW_branch = nn.Sequential(
                nn.Linear(7, 32),
                nn.ReLU()
                #nn.Dropout(0.5),
                #nn.Linear(64, 32),
                #nn.ReLU()
            )
            #####

            self.main_branch = nn.Sequential(
                nn.Linear(224, 256),
                nn.ReLU(),
                #nn.Dropout(0.2),
                #nn.Linear(512, 128),
                #nn.ReLU(),
                #nn.Dropout(0.2),
                nn.Linear(256, 128),
                nn.ReLU(),
                nn.Linear(128, 32),
                nn.ReLU(),
                nn.Linear(32, 1)
            )

    def forward(self, I, R, D, M, Y, T, DW):

            I_out = self.I_branch(I)
            R_out = self.R_branch(R)

            D_out = self.D_branch(D)
            M_out = self.M_branch(M)
            Y_out = self.Y_branch(Y)
            DW_out = self.DW_branch(DW)

            time_cat = torch.cat((D_out, M_out, Y_out), dim=1)
            time_out = self.time_branch(time_cat)

            T_out = self.T_branch(T)

            out_cat = torch.cat((I_out, R_out, T_out, time_out, DW_out), dim=1)
            output = self.main_branch(out_cat)
            return output

def main():
    # Loading the training and testing data.
    training_data = read_csv("training_data.csv")
    testing_data = read_csv("test_data.csv")

    # Extracting the number of Unique IDs and Regs
    # Test the IDs.
    IDs = []
    REGs = []
    for instance in training_data:
        if not instance[0] in IDs:
            IDs.append(instance[0])
        if not instance[1] in REGs:
            REGs.append(instance[1])
    for instance in testing_data:
        if not instance[0] in IDs:
            IDs.append(instance[0])
        if not instance[1] in REGs:
            REGs.append(instance[1])

    # Getting the Mins and Maxs for each feature.
    Mins = [math.inf, math.inf, math.inf, math.inf, math.inf, math.inf, math.inf]
    Maxs = [0, 0, 0, 0, 0, 0, 0]
    for instance in training_data:
        for k in range(len(instance)):
            if Mins[k] > instance[k]:
                Mins[k] = instance[k]
            if Maxs[k] < instance[k]:
                Maxs[k] = instance[k]
    # Normalize the output feature only.
    training_data_normalized = []
    for instance in training_data:
        normalized_instance = []
        for k in range(len(instance)):
            if k==6:
                normalized_instance.append((instance[k]-Mins[k])/(Maxs[k]- Mins[k]))
            else:
                normalized_instance.append(instance[k])
        training_data_normalized.append(normalized_instance)

    # Split the data into training and validation (In my code, test_data refers to validation data.)
    random.shuffle(training_data_normalized)
    train_data = training_data_normalized[:40000]
    test_data = training_data_normalized[40000:]
    #train_data = []
    #test_data = []
    #random.shuffle(training_data_normalized)
    #for ins in training_data_normalized:
    #    if ins[4] == 2019 and ins[3] > 4 and ins[2] > 20:
    #        test_data.append(ins)
    #    else:
    #        train_data.append(ins)

    batch_size = 64

    # Put training data into Batches.
    train_data_input_batches_I_vec = []
    train_data_input_batches_R_vec = []
    train_data_input_batches_D_vec = []
    train_data_input_batches_M_vec = []
    train_data_input_batches_Y_vec = []
    train_data_input_batches_T_vec = []
    train_data_input_batches_DW_vec = []

    train_data_output_batches = []

    input_batch_I_vec = []
    input_batch_R_vec = []
    input_batch_D_vec = []
    input_batch_M_vec = []
    input_batch_Y_vec = []
    input_batch_T_vec = []
    input_batch_DW_vec = []
    output_batch = []

    for i in range(1, len(train_data)+1):
        I, R, D, M, Y, TRX_T, TRX_C = train_data[i-1]

        ## To be deleted.
        #if TRX_T == 2:
        #    continue
        ##
        # Making one hot vectors.
        I_vec = [0 for j in range(len(IDs))]
        I_vec[IDs.index(I)] = 1
        R_vec = [0 for j in range(len(REGs))]
        R_vec[REGs.index(R)] = 1
        D_vec = [0 for j in range(31)]
        D_vec[int(D)-1] = 1
        M_vec = [0 for j in range(12)]
        M_vec[int(M)-1] = 1
        Y_vec = [0, 0]
        if Y == 2019:
            Y_vec[1] = 1
        else:
            Y_vec[0] = 1
        T_vec = [0,0]
        T_vec[int(TRX_T)-1] = 1

        DW_vec = [0 for j in range(7)]
        d = datetime.datetime(int(Y), int(M), int(D))
        DW_vec[d.weekday()] = 1

        input_batch_I_vec.append(I_vec)
        input_batch_R_vec.append(R_vec)
        input_batch_D_vec.append(D_vec)
        input_batch_M_vec.append(M_vec)
        input_batch_Y_vec.append(Y_vec)
        input_batch_T_vec.append(T_vec)
        input_batch_DW_vec.append(DW_vec)

        output_batch.append(TRX_C)

        if i % batch_size == 0 or i==len(train_data):
            train_data_input_batches_I_vec.append(input_batch_I_vec)
            train_data_input_batches_R_vec.append(input_batch_R_vec)
            train_data_input_batches_D_vec.append(input_batch_D_vec)
            train_data_input_batches_M_vec.append(input_batch_M_vec)
            train_data_input_batches_Y_vec.append(input_batch_Y_vec)
            train_data_input_batches_T_vec.append(input_batch_T_vec)
            train_data_input_batches_DW_vec.append(input_batch_DW_vec)

            train_data_output_batches.append(output_batch)

            input_batch_I_vec = []
            input_batch_R_vec = []
            input_batch_D_vec = []
            input_batch_M_vec = []
            input_batch_Y_vec = []
            input_batch_T_vec = []
            input_batch_DW_vec = []
            output_batch = []

    # Put test data into Batches.
    test_data_input_batches_I_vec = []
    test_data_input_batches_R_vec = []
    test_data_input_batches_D_vec = []
    test_data_input_batches_M_vec = []
    test_data_input_batches_Y_vec = []
    test_data_input_batches_T_vec = []
    test_data_input_batches_DW_vec = []
    test_data_output_batches = []

    input_batch_I_vec = []
    input_batch_R_vec = []
    input_batch_D_vec = []
    input_batch_M_vec = []
    input_batch_Y_vec = []
    input_batch_T_vec = []
    input_batch_DW_vec = []
    output_batch = []

    for i in range(1, len(test_data)+1):
        I, R, D, M, Y, TRX_T, TRX_C = test_data[i-1]

        ## To be deleted.
        #if TRX_T == 2:
        #    continue
        ##

        # Making one hot vectors.
        I_vec = [0 for j in range(len(IDs))]
        I_vec[IDs.index(I)] = 1
        R_vec = [0 for j in range(len(REGs))]
        R_vec[REGs.index(R)] = 1
        D_vec = [0 for j in range(31)]
        D_vec[int(D)-1] = 1
        M_vec = [0 for j in range(12)]
        M_vec[int(M)-1] = 1
        Y_vec = [0, 0]
        if Y == 2019:
            Y_vec[1] = 1
        else:
            Y_vec[0] = 1
        T_vec = [0,0]
        T_vec[int(TRX_T)-1] = 1

        DW_vec = [0 for j in range(7)]
        d = datetime.datetime(int(Y), int(M), int(D))
        DW_vec[d.weekday()] = 1

        input_batch_I_vec.append(I_vec)
        input_batch_R_vec.append(R_vec)
        input_batch_D_vec.append(D_vec)
        input_batch_M_vec.append(M_vec)
        input_batch_Y_vec.append(Y_vec)
        input_batch_T_vec.append(T_vec)
        input_batch_DW_vec.append(DW_vec)

        output_batch.append(TRX_C)

        if i % batch_size == 0 or i==len(test_data):
            test_data_input_batches_I_vec.append(input_batch_I_vec)
            test_data_input_batches_R_vec.append(input_batch_R_vec)
            test_data_input_batches_D_vec.append(input_batch_D_vec)
            test_data_input_batches_M_vec.append(input_batch_M_vec)
            test_data_input_batches_Y_vec.append(input_batch_Y_vec)
            test_data_input_batches_T_vec.append(input_batch_T_vec)
            test_data_input_batches_DW_vec.append(input_batch_DW_vec)

            test_data_output_batches.append(output_batch)

            input_batch_I_vec = []
            input_batch_R_vec = []
            input_batch_D_vec = []
            input_batch_M_vec = []
            input_batch_Y_vec = []
            input_batch_T_vec = []
            input_batch_DW_vec = []

            output_batch = []
    # Make model instance.
    model = MLP(len(IDs), len(REGs))
    # Move to CUDA for faster training.
    if torch.cuda.is_available():
        model = model.cuda()
    # Loss function and optimizer.
    criterion = torch.nn.MSELoss()
    optimizer = torch.optim.Adam(model.parameters(), lr = 0.00035)

    # Training part.
    model.train()
    epochs = 15
    training_losses = []
    testing_losses = []
    for epoch in range(epochs):
        epoch_loss = 0
        for i in range(len(train_data_input_batches_I_vec)):
            x_train_I = torch.cuda.FloatTensor(train_data_input_batches_I_vec[i])
            x_train_R = torch.cuda.FloatTensor(train_data_input_batches_R_vec[i])
            x_train_D = torch.cuda.FloatTensor(train_data_input_batches_D_vec[i])
            x_train_M = torch.cuda.FloatTensor(train_data_input_batches_M_vec[i])
            x_train_Y = torch.cuda.FloatTensor(train_data_input_batches_Y_vec[i])
            x_train_T = torch.cuda.FloatTensor(train_data_input_batches_T_vec[i])
            x_train_DW = torch.cuda.FloatTensor(train_data_input_batches_DW_vec[i])

            y_train = torch.cuda.FloatTensor(train_data_output_batches[i])
            optimizer.zero_grad()
            # Forward pass
            y_pred = model(x_train_I, x_train_R, x_train_D, x_train_M, x_train_Y, x_train_T, x_train_DW)
            # Compute Loss
            loss = criterion(y_pred.squeeze(), y_train)
            # Loss on original data for printing.
            y_orig_train = y_train * (Maxs[6] - Mins[6]) + Mins[6]
            y_orig_pred = y_pred.squeeze() * (Maxs[6] - Mins[6]) + Mins[6]
            orig_loss = torch.sqrt(criterion(y_orig_pred, y_orig_train))
            epoch_loss += orig_loss.data.item()

            # Backward pass
            loss.backward()
            optimizer.step()
        # Compute Loss over test data.
        test_total_loss = 0
        test_total_num = 0
        for j in range(len(test_data_input_batches_I_vec)):
            x_test_I = torch.cuda.FloatTensor(test_data_input_batches_I_vec[j])
            x_test_R = torch.cuda.FloatTensor(test_data_input_batches_R_vec[j])
            x_test_D = torch.cuda.FloatTensor(test_data_input_batches_D_vec[j])
            x_test_M = torch.cuda.FloatTensor(test_data_input_batches_M_vec[j])
            x_test_Y = torch.cuda.FloatTensor(test_data_input_batches_Y_vec[j])
            x_test_T = torch.cuda.FloatTensor(test_data_input_batches_T_vec[j])
            x_test_DW = torch.cuda.FloatTensor(test_data_input_batches_DW_vec[j])

            y_test = torch.cuda.FloatTensor(test_data_output_batches[j])
            y_pred = model(x_test_I, x_test_R, x_test_D, x_test_M, x_test_Y, x_test_T, x_test_DW)

            y_orig_test = y_test * (Maxs[6] - Mins[6]) + Mins[6]
            y_orig_pred = y_pred.squeeze() * (Maxs[6] - Mins[6]) + Mins[6]
            # SQRT for RMSE
            test_loss = (y_orig_pred - y_orig_test)**2
            test_loss = torch.sum(test_loss)
            test_total_loss += test_loss.data.item()
            test_total_num += len(y_pred)
        # Append losses.
        training_losses.append(epoch_loss/ len(train_data_input_batches_I_vec))
        testing_losses.append(test_total_loss / len(test_data_input_batches_I_vec))
        print("Epoch:", epoch, "Train Loss = ", epoch_loss/len(train_data_input_batches_I_vec), "Test Loss = " , math.sqrt(test_total_loss / test_total_num))

    # Preprocess Test data.
    testing_batch_I_vec = []
    testing_batch_R_vec = []
    testing_batch_D_vec = []
    testing_batch_M_vec = []
    testing_batch_Y_vec = []
    testing_batch_T_vec = []
    testing_batch_DW_vec = []

    for i in range(1, len(testing_data)+1):
        I, R, D, M, Y, TRX_T = testing_data[i-1]

        # Making one hot vectors.
        I_vec = [0 for j in range(len(IDs))]
        I_vec[IDs.index(I)] = 1
        R_vec = [0 for j in range(len(REGs))]
        R_vec[REGs.index(R)] = 1
        D_vec = [0 for j in range(31)]
        D_vec[int(D)-1] = 1
        M_vec = [0 for j in range(12)]
        M_vec[int(M)-1] = 1
        Y_vec = [0, 0]
        if Y == 2019:
            Y_vec[1] = 1
        else:
            Y_vec[0] = 1
        T_vec = [0,0]
        T_vec[int(TRX_T)-1] = 1

        DW_vec = [0 for j in range(7)]
        d = datetime.datetime(int(Y), int(M), int(D))
        DW_vec[d.weekday()] = 1

        testing_batch_I_vec.append(I_vec)
        testing_batch_R_vec.append(R_vec)
        testing_batch_D_vec.append(D_vec)
        testing_batch_M_vec.append(M_vec)
        testing_batch_Y_vec.append(Y_vec)
        testing_batch_T_vec.append(T_vec)
        testing_batch_DW_vec.append(DW_vec)

    # Predict values for Testing dataset.
    x_testing_I = torch.cuda.FloatTensor(testing_batch_I_vec)
    x_testing_R = torch.cuda.FloatTensor(testing_batch_R_vec)
    x_testing_D = torch.cuda.FloatTensor(testing_batch_D_vec)
    x_testing_M = torch.cuda.FloatTensor(testing_batch_M_vec)
    x_testing_Y = torch.cuda.FloatTensor(testing_batch_Y_vec)
    x_testing_T = torch.cuda.FloatTensor(testing_batch_T_vec)
    x_testing_DW= torch.cuda.FloatTensor(testing_batch_DW_vec)
    y_pred = model(x_testing_I, x_testing_R, x_testing_D, x_testing_M, x_testing_Y, x_testing_T, x_testing_DW)
    # Reverse normalization.
    Y_values = y_pred * (Maxs[6] - Mins[6]) + Mins[6]

    # Converting the Pytorch Tensor into numpy.
    Y_values = Y_values.cpu().detach().numpy()
    #print(Y_values)
    # Save values into csv file.
    np.savetxt("test_predictions.csv", Y_values, delimiter=",")

if __name__ == '__main__':
    main()


import cv2
import imutils
import matplotlib.pyplot as plt
import numpy as np

def midPoint(ptA, ptB):
	return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5)

def preparedImgForCntr(img):
    # preparing image for contour detction
    gray = cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY)  # converting image to the grayScale to be able to get the Cnt
    gray = cv2.GaussianBlur(gray, (7, 7), 0)  # blurring the image slightly to avoid false lines
    edged = cv2.Canny(gray, 50, 100)  # edge detecting
    edged = cv2.dilate(edged, None, iterations=1)  # it is followed by the erosion process to increase the size of the erroted objects
    edged = cv2.erode(edged, None, iterations=1)  # erasing the noise like the small white and black points
    return edged

def getSqrCoord (img):
    # getting the coordinates of the blue square
    image = preparedImgForCntr(img)
    cnts = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)
    cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
    copy = img.copy()
    square = None
    for c in cnts:
        epsilon = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.015 * epsilon, True)
        if len(approx) == 4: # square has 4-points
            square = approx
            cv2.drawContours(copy, [square], -1, (0, 0, 0), 3)
            cv2.imshow("square", copy)
            square = np.array(square, dtype=np.float32)
            break  # if you found the square, break
    return square

def calcTransMtrx (sourceImg,sqrCoord,startX,startY,step):  # step is the width of the figure
    # compute transformation matrix and apply it
    # newCoord = topLeft, bottomLeft, bottomRight, topRight
    newCoord = np.array([[startX, startY], [startX, startY + step], [startX + step, startY + step], [startX + step, startX]], dtype=np.float32)  # new square coordinates
    transfMatrix = cv2.getPerspectiveTransform(sqrCoord, newCoord) # getting the transformation matrix
    modifiedImg = cv2.warpPerspective(sourceImg, transfMatrix, sourceImg.shape[:2][::-1])  # appying the transformation matrix on the source image

    newCoord = np.array(newCoord, dtype=int)
    return modifiedImg, newCoord

def regionOfInterest(img, vertices):
    mask = np.zeros_like(img)  # a zero matrix with the same size as the original image
    match_mask_color = (255, 255, 255)  # color to be put as a mask
    # cropping the region of interest by drawing a polygon with the passed vertices
    cv2.fillPoly(mask, vertices, match_mask_color)
    masked_image = cv2.bitwise_and(img, mask)
    return masked_image

def cropRegionOfInterest(img, heightFactor, widthFactor):
    height, width, _ = img.shape
    # region_of_interest_vertices = [topLeft,bottomLeft ,topRight, bottomRight]
    RegionOfInterestList = [(width * widthFactor, 0), (width * widthFactor, height), (height * heightFactor, 0),
                            (height * heightFactor, height)]
    imagePrepared = preparedImgForCntr(img)
    croppedImage = regionOfInterest(imagePrepared, np.array([RegionOfInterestList], np.int32))
    return croppedImage

def drawLines(img, lines, thickness=3):
    # If there are no lines to draw, exit.
    if lines is None:
        return
    # Make a copy of the original image.
    img = np.copy(img)
    # Create a blank image that matches the original in size.
    line_img = np.zeros(
        (
            img.shape[0],
            img.shape[1],
            3
        ),
        dtype=np.uint8,
    )
    # Loop over all lines and draw them on the blank image.
    for line in lines:
        for x1, y1, x2, y2 in line:
            cv2.line(line_img, (x1, y1), (x2, y2), [255, 0, 0], thickness)
    # Merge the image with the lines onto the original, we could both functions but, addWeighted is better
    #img = cv2.add(img, line_img)
    img = cv2.addWeighted(img, 0.8, line_img, 1.0, 0.0)
    # Return the modified image.
    return img

def drawHoughLines (img):
    # detecting the lines
    lines = cv2.HoughLinesP(  # this function will return the lines holding line's points instead of rho and theta
        cropRegionOfInterest(img, 4/3, 1/3),
        rho=10,  # the length of the perpendicular line between the origin and the line
        theta=0.01,  # angle with the x-axis clockwise where, the x-axis is at the top of the image
        threshold=200,
        lines=np.array([]),
        minLineLength=170,  # minimum line length
        maxLineGap=10  # the max distance between two lines to treat them as two different lines
    )
    listOfLines = []
    if lines is None:
        raise Exception("No lines found")
    if len(lines) < 2:
        raise Exception("you can't calculate distance with less than two lines")

    print("number of lines:\n", len(lines))
    i = 0
    for line in lines:
        listOfPoints = []
        for x1, y1, x2, y2 in line:
            print("line number:", i, "[ x1:", x1, "x2:", x2, "y1:", y1, "y2:", y2, "]")
            listOfPoints.append(x1)
            listOfPoints.append(y1)
            listOfPoints.append(x2)
            listOfPoints.append(y2)
        listOfLines.append(listOfPoints)
        i += 1
    # drawing the lines
    line_image = drawLines(image, lines)
    print()
    return listOfLines, line_image

def calcDistancebetTwoLines (line1, line2 , Y, scale=1):
    # calc the distance between the 2-lines in the x direction at point Y
    slope1 = (line1[3] - line1[1]) / (line1[2] - line1[0])
    slope2 = (line2[3] - line2[1]) / (line2[2] - line2[0])
    # the value of X at height y
    XOfline1AtY = line1[0] + (Y - line1[1]) / slope1
    XOfline2AtY = line2[0] + (Y - line2[1]) / slope2

    distanceBetMidPoints = abs(XOfline1AtY - XOfline2AtY)
    # actual length is: length / scale
    distanceBetMidPoints /= scale
    return distanceBetMidPoints

def drawDistanceAtY (img, line1, line2, D, Y):
    # drawing the distance in meters at height = Y
    # drawing the contours on the image
    orig = img.copy()
    slope1 = (line1[3] - line1[1]) / (line1[2] - line1[0])
    slope2 = (line2[3] - line2[1]) / (line2[2] - line2[0])
    XOfline1AtY = int(line1[0] + (Y - line1[1]) / slope1)
    XOfline2AtY = int(line2[0] + (Y - line2[1]) / slope2)
    # drawing circles corresponding to the current points
    cv2.circle(orig, (XOfline1AtY, Y), 5, (100, 50, 100), -1)
    cv2.circle(orig, (XOfline2AtY, Y), 5, (100, 50, 100), -1)

    # connecting them with a line
    cv2.line(orig, (XOfline1AtY, Y), (XOfline2AtY, Y), (100, 50, 100), 2)

    (mX, mY) = midPoint((XOfline1AtY, Y), (XOfline2AtY, Y))  # writting the text in the mid distance between the two contours
    writeDistAboveLineBy = 10
    cv2.putText(orig, "{:.2f}m".format(D), (int(mX), int(mY - writeDistAboveLineBy)), cv2.FONT_HERSHEY_SIMPLEX, 0.55,
                (100, 50, 100), 2)

    # returning the output image
    return orig

#############################################################################################
if __name__ == '__main__':
    if not cv2.useOptimized():
        cv2.setUseOptimized(True)  # setting the optimization to true to decrease the execution time of the code

    # Reading the image
    source = cv2.imread('road_final.jpg')
    cv2.imshow("Source Image", source)

    #  detecting the blue square and saving its coordinates
    sqrCoord = getSqrCoord(source)
    sqWidth = 75  # the real width of the square
    scale = 1  # the scale of the image after modifying the perspective
    scaledWidth = sqWidth * scale  # 1 : 1 scale
    # transforming the image and getting square's new coordinates
    modifiedImage, sqrCoord = calcTransMtrx(source, sqrCoord, 250, 250, scaledWidth)
    cv2.imshow("birdEyeView", modifiedImage)
#############################################################################################
    image = modifiedImage
    # Extracting the lines from the image and creating an image with the lines drawn on it
    lines, line_image = drawHoughLines(image)  # the Hough lines and the new image with lines drawn on it
    line1 = lines[0]
    line2 = lines[1]

    H = 350  # the height to calc and draw the distance at
    distanceBetTwoLines = calcDistancebetTwoLines(line1, line2,H,scale)   # the distance between the 2 lines at height H
    distanceBetTwoLines /= 100.00  # so that the distance is in meters
    dimImage = drawDistanceAtY(image, line1, line2, distanceBetTwoLines, H)  # drawing the distance between the 2 lines at height H
    cv2.imshow("Dimensions", dimImage)
    print('width of the road at height', H, ':', distanceBetTwoLines, "m")
    # printing the Hough lines
    plt.imshow(line_image)
    plt.show()

    cv2.waitKey()


from enum import Enum

from typing_extensions import Final

class GCODE(str, Enum):
    HOME = "G28.2"
    MOVE = "G0"
    DWELL = "G4"
    CURRENT_POSITION = "M114.2"
    LIMIT_SWITCH_STATUS = "M119"
    PROBE = "G38.2"
    ABSOLUTE_COORDS = "G90"
    RELATIVE_COORDS = "G91"
    RESET_FROM_ERROR = "M999"
    PUSH_SPEED = "M120"
    POP_SPEED = "M121"
    SET_SPEED = "G0"
    STEPS_PER_MM = "M92"
    READ_INSTRUMENT_ID = "M369"
    WRITE_INSTRUMENT_ID = "M370"
    READ_INSTRUMENT_MODEL = "M371"
    WRITE_INSTRUMENT_MODEL = "M372"
    SET_MAX_SPEED = "M203.1"
    SET_CURRENT = "M907"
    DISENGAGE_MOTOR = "M18"
    HOMING_STATUS = "G28.6"
    ACCELERATION = "M204"
    WAIT = "M400"
    PIPETTE_RETRACT = "M365.3"
    PIPETTE_DEBOUNCE = "M365.2"
    PIPETTE_MAX_TRAVEL = "M365.1"
    PIPETTE_HOME = "M365.0"
    MICROSTEPPING_B_ENABLE = "M52"
    MICROSTEPPING_B_DISABLE = "M53"
    MICROSTEPPING_C_ENABLE = "M54"
    MICROSTEPPING_C_DISABLE = "M55"
    VERSION = "version"

HOMED_POSITION: Final = {
    "X": 418.0,
    "Y": 353.0,
    "Z": 218.0,
    "A": 218.0,
    "B": 19.0,
    "C": 19.0,
}

Y_BOUND_OVERRIDE: Final = 370

SMOOTHIE_COMMAND_TERMINATOR = "\r\n\r\n"

SMOOTHIE_ACK = "ok\r\nok\r\n"

PLUNGER_BACKLASH_MM = 0.3

LOW_CURRENT_Z_SPEED = 30

CURRENT_CHANGE_DELAY = 0.005

PIPETTE_READ_DELAY = 0.1

Y_SWITCH_BACK_OFF_MM = 28

Y_SWITCH_REVERSE_BACK_OFF_MM = 10

Y_BACKOFF_LOW_CURRENT = 0.8

Y_BACKOFF_SLOW_SPEED = 50

Y_RETRACT_SPEED = 8

Y_RETRACT_DISTANCE = 3

UNSTICK_DISTANCE = 1

UNSTICK_SPEED = 1

DEFAULT_AXES_SPEED = 400

XY_HOMING_SPEED = 80

HOME_SEQUENCE = ["ZABC", "X", "Y"]

AXES = "".join(HOME_SEQUENCE)

DISABLE_AXES = ""
"""Ignore these axis when sending move or home command"""

MOVEMENT_ERROR_MARGIN = 1 / 160  # Largest movement in mm for any step

SEC_PER_MIN = 60

DEFAULT_ACK_TIMEOUT = 5

DEFAULT_EXECUTE_TIMEOUT = 12000

DEFAULT_SMOOTHIE_TIMEOUT = 1

DEFAULT_MOVEMENT_TIMEOUT = 30

SMOOTHIE_BOOT_TIMEOUT = 3

DEFAULT_STABILIZE_DELAY = 0.1

DEFAULT_COMMAND_RETRIES = 3

MICROSTEPPING_GCODES = {
    "B": {
        "ENABLE": GCODE.MICROSTEPPING_B_ENABLE,
        "DISABLE": GCODE.MICROSTEPPING_B_DISABLE,
    },
    "C": {
        "ENABLE": GCODE.MICROSTEPPING_C_ENABLE,
        "DISABLE": GCODE.MICROSTEPPING_C_DISABLE,
    },
}

GCODE_ROUNDING_PRECISION = 3
"""Number of digits after the decimal point for coordinates being sent to Smoothie"""


from pydantic import BaseModel, Field
from kubernetes.client.rest import ApiException

class InputSchema(BaseModel):
    k8s_cli_string: str = Field(
        title='Kubectl Command',
        description='kubectl execute a command in pod',
        default='kubectl exec {pod_name} {command} -n {namespace}'
    )
    pod_name: str = Field(
        title='Pod Name',
        description='Pod Name'
    )
    command: str = Field(
        title='Command',
        description='Command'
    )
    namespace: str = Field(
        title='Namespace',
        description='Namespace'
    )

def k8s_kubectl_exec_command_printer(data: str):
    if data is None:
        print("Error while executing command")
        return

    print (data)

def k8s_kubectl_exec_command(
        handle,
        k8s_cli_string: str,
        pod_name:str,
        command: str,
        namespace: str
        ) -> str:
    """k8s_kubectl_exec_command executes the given kubectl command on the pod

        :type handle: object
        :param handle: Object returned from the Task validate method

        :type k8s_cli_string: str
        :param k8s_cli_string: kubectl exec {pod_name} {command} -n {namespace}.

        :type pod_name: str
        :param pod_name: Pod Name.

        :type command: str
        :param command: Command.

        :type namespace: str
        :param namespace: Namespace.

        :rtype: String, Output of the command in python string format or
        Empty String in case of Error.
    """
    k8s_cli_string = k8s_cli_string.format(pod_name=pod_name, command=command, namespace=namespace)
    result = handle.run_native_cmd(k8s_cli_string)

    if result is None:
        print(
            f"Error while executing command ({k8s_cli_string}) (empty response)")
        return ""

    if result.stderr:
        raise ApiException(f"Error occurred while executing command {k8s_cli_string} {result.stderr}")

    return result.stdout


from authtools.views import LoginRequiredMixin
from django.core.urlresolvers import reverse_lazy
from django.views.generic import ListView, CreateView

from . import models

class HomeView(LoginRequiredMixin, ListView):
    model = models.Expense

    def get_queryset(self):
        return super().get_queryset().filter(user=self.request.user)

    def total(self):
        qs = self.get_queryset()
        return sum(x.amount for x in qs)

class AddView(LoginRequiredMixin, CreateView):
    model = models.Expense
    fields = (
        'timestamp',
        'amount',
        'details',
    )
    success_url = reverse_lazy("home")

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)


import sys
import requests

if __name__ == "__main__":
    order = sys.argv[1].lower()

    user = None
    users = None

    if order == "get_json":
        resp = requests.get("http://localhost:5000/api/users/1")
        user = resp.json()
    elif order == "list_json":
        resp = requests.get("http://localhost:5000/api/users")
        users = resp.json()
    elif order == "create_json":
        body = {
            "name": "Lance Armstrong",
            "occupation": "Cyclist",
            "birthday": "2000-01-01",
        }
        resp = requests.post("http://localhost:5000/api/users/new", json=body)
        user = resp.json()
    elif order == "update_json":
        body = {
            "name": "Bob Barker",
            "occupation": "TV Show Host",
            "birthday": "1923-12-12",
        }
        resp = requests.put("http://localhost:5000/api/users/1", json=body)
        user = resp.json()
    elif order == "delete_json":
        resp = requests.delete("http://localhost:5000/api/users/1")
        user = resp.json()
    else:
        print("Invalid command")
        sys.exit(1)

    print(resp.status_code)
    print(resp.text)

    if user:
        print(user)

    if users:
        print(users)


from tkinter import *
from tkinter import messagebox
from tkinter.filedialog import askopenfilename
from pdf2image import convert_from_path

def pdf2img_converter():
    try:
        # convert_from_path will get the PDF file from the entry widget we created in GUI.
        imgs = convert_from_path(str(entry.get()))
        for i in range(len(imgs)):
            # Saves the images as JPEG File format using .save function
            imgs[i].save('page'+str(i)+'.jpg', 'JPEG')

    # If error or exception is found then it will show the error message box.
    except Exception as e:
        # Prints the exception in console.
        print(e)
        # Shows the result message box saying "No PDF Found"
        messagebox.showinfo("Result", "NO PDF Found")
    else:
        # else if no error found, then it show success message box.
        messagebox.showinfo("Result", "Converted to Image Successfully")

# Function which will browse for pdf file.
def source_filename():
    # configures the state of entry to normal
    entry.configure(state='normal')
    # clears the input in the entry
    entry.delete(0, END)
    # ask for file open with file types only PDF.
    src = askopenfilename(
        title="Choose a File",
        filetypes=[('PDF Files', '.pdf')])
    # Inserts the path of PDF file in the entry
    entry.insert(0, src)
    # again configures the state of entry to disabled.
    entry.configure(state='disabled')

# Creating GUI Window
mainWindow = Tk()
# Title for Window
mainWindow.title("PDF2IMG CONVERTER")
# This will prevent program window to resize.
mainWindow.resizable(width=False, height=False)

# Title Heading for Program Name
titleHeading = Label(mainWindow, text="PDF2IMG CONVERTER", font=("New Times Roman", 20, "italic"))
# .grid is used to place widgets in grid, column and row. We just have to mention row and column value.
titleHeading.grid(row=0, column=0, columnspan=3, padx=10, pady=10)

# Label (Text) for Choosing File.
chooseFileLabel = Label(mainWindow, text="Choose File").grid(row=1, column=0)

# Entry widget is used to get input from user, in this case we will use it get the PDF file location.
entry = Entry(mainWindow, width=30)
entry.grid(row=1, column=1)

# Button widget for browsing the file explorer and locating file.
btnOpenFile = Button(mainWindow, text="Browse", command=lambda: source_filename())
btnOpenFile.grid(row=1, column=2)

# Button which will convert PDF to Image on click.
btnConvert = Button(mainWindow, text="CONVERT", command=pdf2img_converter, font=("New Times Roman", 12, "bold"))
btnConvert.grid(row=3, column=1, padx=5, pady=5)

# mainloop method is used when you program is ready to run.
# mainloop() is infinite loop which runs until program is not closed
mainWindow.mainloop()


import numpy as np
import time
from sklearn import preprocessing
import os.path
import re
import pandas as pd
import random
from dtw import dtw
from sklearn.cluster import DBSCAN
import matplotlib.pyplot as plt

from autoencoder import AutoEncoder
from lstm_ad import LSTMAD
from lstm_enc_dec_axl import LSTMED
from rnn_ebm import RecurrentEBM

rootdir = "E://760//Project//PhaseI//"

filenamelist = list()

for parent, dirnames, filenames in os.walk(rootdir):
    for filename in filenames:
        if ".txt" in filename:
            filenamelist.append(filename)

result_list = []
anomaly_list = []
data_list = []
split_point_list = []
for index, value in enumerate(filenamelist):
    df = pd.read_csv(rootdir + value, names=['values'])
    data = df.values
    # preprocessing
    min_max_scaler = preprocessing.MinMaxScaler()
    data = min_max_scaler.fit_transform(data)

    split_point = int(re.findall("\d+", value)[1])
    data = data[0:split_point, ]

    # Get the split point of training and test set
    split_point = int(np.floor(0.7 * split_point))
    split_point_list.append(split_point)

    data_list.append(data)

'''
# Get the clusters of 25 datasets
# Use dtw method
distance_matrix = np.zeros((len(data_list),len(data_list)), dtype=float)
a = 0
for i in range(len(data_list)-1):
    for j in range(i+1, len(data_list)):
        if len(data_list[i]) > 20000:
            x = data_list[i][0:20000]
        else:
            x = data_list[i]
        if len(data_list[j]) > 20000:
            y = data_list[j][0:20000]
        else:
            y = data_list[j]

        manhattan_distance = lambda x, y: np.abs(x - y)
        d = dtw(x, y, manhattan_distance)[0]
        distance_matrix[i,j] = d
        distance_matrix[j,i] = d
    a += 1
    print(a)

min_max_scaler = preprocessing.MinMaxScaler()
distance_matrix = min_max_scaler.fit_transform(distance_matrix)

# Use DBSCAN to cluster the distance metric
y_pred = DBSCAN(eps=0.3, min_samples=3, metric='precomputed').fit(distance_matrix)
print()
'''

# List the result labels of clusters
labels = [0,0,0,4,1,1,1,1,1,1,0,0,2,2,0,0,0,2,3,3,3,3,3,4,4]

accuracy_list = []
for kk in range(5):
    result_list = [0] * 25
    for i in range(len(set(labels))):
        index = [k for k, x in enumerate(labels) if x == i]
        data = data_list[index[0]]

        # Add anomaly
        mu = 0
        sigma = 0.8
        anomaly_point = random.randint(split_point_list[index[0]], data.shape[0])
        anomaly_list.append(anomaly_point)
        temp = random.gauss(mu, sigma)
        if 0 <= temp < 0.3 or -0.3 < temp <= 0:
            temp = random.gauss(mu, sigma)
        data[anomaly_point] += temp

        '''
        # Add noise
        # 0.5% noise
        mu = 0
        sigma = 0.3
        noise_amount = int(np.ceil(0.005 * data.shape[0]))
        if noise_amount < 5:
            noise_amount = 5

        for i in range(noise_amount):
            noise_point = random.randint(0, data.shape[0])
            data[noise_point] += random.gauss(mu, sigma)
        '''

        # 2% noise
        mu = 0
        sigma = 0.3
        noise_amount = np.ceil(0.02 * data.shape[0])
        if noise_amount < 20:
            noise_amount = 20

        for ll in range(int(noise_amount)):
            noise_point = random.randint(0, data.shape[0]-2)
            data[noise_point] += random.gauss(mu, sigma)

        # Resplit data
        train = data[0:split_point_list[index[0]], ]
        train = pd.DataFrame(train)
        test = data[split_point_list[index[0]]:data.shape[0], ]
        test = pd.DataFrame(test)

        # Train the DNN models by the basic data
        model = AutoEncoder(num_epochs=40, hidden_size=10)
        model.fit(train)

        error = model.predict(test)
        error = np.abs(error)

        result = np.argmax(error) + split_point_list[index[0]]
        result_list[index[0]] = result

        # Fit the other data in the same clusters
        for j in range(1, len(index)):
            data = data_list[index[j]]

            # Add anomaly
            mu = 0
            sigma = 0.8
            anomaly_point = random.randint(split_point_list[index[j]], data.shape[0] - 1)
            anomaly_list.append(anomaly_point)
            temp = random.gauss(mu, sigma)
            if 0 <= temp < 0.3 or -0.3 < temp <= 0:
                temp = random.gauss(mu, sigma)
            data[anomaly_point] += temp

            '''
            # Add noise
            # 0.5% noise
            mu = 0
            sigma = 0.3
            noise_amount = int(np.ceil(0.005 * data.shape[0]))
            if noise_amount < 5:
                noise_amount = 5

            for i in range(noise_amount):
                noise_point = random.randint(0, data.shape[0])
                data[noise_point] += random.gauss(mu, sigma)
            '''

            '''
            # 2% noise
            mu = 0
            sigma = 0.4
            noise_amount = np.ceil(0.02 * data.shape[0])
            if noise_amount < 20:
                noise_amount = 20

            for i in range(len(noise_amount)):
                noise_point = random.randint(0, data.shape[0])
                data[noise_point] += random.gauss(mu, sigma)
            '''

            # Resplit data
            train = data[0:split_point_list[index[j]], ]
            train = pd.DataFrame(train)
            test = data[split_point_list[index[j]]:data.shape[0], ]
            test = pd.DataFrame(test)

            # Fit the other data in the same
            error = model.predict(test)
            error = np.abs(error)

            result = np.argmax(error) + split_point_list[index[j]]
            result_list[index[j]] = result

    right = 0
    for i in range(len(result_list)):
        if i != 24:
            if result_list[i] in range(anomaly_list[i] - 101, anomaly_list[i] + 101):
                right += 1
        else:
            if result_list[i] in range(anomaly_list[i] - 11, anomaly_list[i] + 11):
                right += 1

    print("The accuracy is: ", right / 25)
    accuracy_list.append(right / 25)

print("The mean accuracy of 20 times is: ", np.mean(accuracy_list))
print("The accuracy variance of 20 times is: ", np.var(accuracy_list))


import turtle
import math
import random
import datetime

def tleft():
    # 左に回転
    my_turtle.left(10)

def tright():
    # 右に回転
    my_turtle.right(10)

def tup():
    # スピードアップ
    global step
    if step <= 10:
        step += 1

def tdown():
    # スピードダウン
    global step
    if step > 0:
        step -= 1

def is_hit(target, turtle):
    # タートルとターゲットの衝突判定
    diff = math.sqrt(
    math.pow(target.xcor()- turtle.xcor(), 2)
             + math.pow(target.ycor() - turtle.ycor(), 2))
    return True if diff < 40 else False

def game():
    global count

    # 壁にぶつかったらタートルを跳ね返す
    if math.fabs(my_turtle.xcor()) >= X_LIMIT:
        angle = 180 - my_turtle.heading()
        my_turtle.setheading(angle)
    if my_turtle.ycor() >= Y_LIMIT:
        angle = 360 - my_turtle.heading()
        my_turtle.setheading(angle)

    my_turtle.forward(step)

    # ターゲットを移動する
    for t in targets:
        t.forward(random.randrange(10))
        t.tilt(3)

        # 壁にぶつかったら反転
        if math.fabs(t.xcor()) > X_LIMIT:
            t.right(180)
            t.forward(10)

        # 衝突チェック
        if is_hit(t, my_turtle):
            # ヒットしたタートルを灰色にしてtargetsから取り除く
            t.color("#EEEEEE")
            targets.remove(t)
            r_text.clear()
            r_text.write(
            f"残りターゲット{len(targets)}",
            font=("helvetica", 24)
            )

    # 経過時間を計算する
    now = datetime.datetime.now()
    etime = now - stime

    # ターゲットが残っていれば経過時間を更新
    if len(targets) > 0:
        sec = etime.seconds + etime.microseconds /1000000
        time_text.clear()
        time_text.write(f"経過時間: {sec:1f}秒",
                        font=("helvetica", 24))
    else :
        time_text.goto(-280, 0)
        time_text.write("ミッション完了!", font=("helvetica", 60))
        screen.update()
        return

    # タートルが下の壁にぶつかったらゲームオーバー
    if my_turtle.ycor() < -Y_LIMIT:
        screen.tracer(1)
        my_turtle.color("red")
        # タートルを震わせる
        for _ in range(10):
            my_turtle.right(15)
            my_turtle.left(15)
        time_text.goto(-300, 0)
        time_text.write("ゲームオーバー", font=("helvetica", 60))
    else :
        # 画面をアップデート
        screen.update()
        screen.ontimer(game, 10)

screen = turtle.Screen()
screen.setup(700, 700)
screen.title("ゲーム")

# タートルを描画する
my_turtle = turtle.Turtle()
my_turtle.shape("turtle")
my_turtle.shapesize(3)
my_turtle.color("red")
my_turtle.penup()

targets = [] # ターゲットを格納するリスト
num_of_targets = 6 # ターゲットの数
colors = ["blue", "green", "black", "purple", "pink", "yellow", "orange"] # ターゲットの色

# ターゲットを描画
for y in range(num_of_targets):
    t = turtle.Turtle()
    t.penup()
    t.color(random.choice(colors))
    t.shape("square")
    t.shapesize(2)
    t.sety(y * 100 - 300)
    t.setx(-300 + random.randrange(3) * 100)
    targets.append(t)

# トレーサーをオフ
screen.tracer(0)

# スタート時間
stime = datetime.datetime.now()

# キーイベント
screen.listen()
screen.onkey(tleft, "Left")
screen.onkey(tright, "Right")
screen.onkey(tup, "Up")
screen.onkey(tdown, "Down")

# 残りターゲット表示テキスト用
r_text = turtle.Turtle()
r_text.penup()
r_text.hideturtle()
r_text.goto(-320, -300)
r_text.write(f"残りターゲット：{len(targets)}", font=("helvetica", 24))

# 経過時間表示テキスト用
time_text = turtle.Turtle()
time_text.penup()
time_text.hideturtle()
time_text.goto(0, -300)

# 経過時間
e_time = 0

# 境界
X_LIMIT = 300
Y_LIMIT = 300

# タートルのループごとの移動距離
step = 3
# タートルの角度
angle = 40
my_turtle.left(angle)

# ゲーム開始
game()
screen.mainloop()


# -*- coding: utf-8 -*-
"""Create instance of vrayscene."""
import os
import json
import appdirs
import requests

from maya import cmds
import maya.app.renderSetup.model.renderSetup as renderSetup

from openpype.hosts.maya.api import (
    lib,
    plugin
)
from openpype.settings import (
    get_system_settings,
    get_project_settings
)

from openpype.lib import requests_get
from openpype.pipeline import (
    CreatorError,
    legacy_io,
)
from openpype.modules import ModulesManager

class CreateVRayScene(plugin.Creator):
    """Create Vray Scene."""

    label = "VRay Scene"
    family = "vrayscene"
    icon = "cubes"

    _project_settings = None

    def __init__(self, *args, **kwargs):
        """Entry."""
        super(CreateVRayScene, self).__init__(*args, **kwargs)
        self._rs = renderSetup.instance()
        self.data["exportOnFarm"] = False
        deadline_settings = get_system_settings()["modules"]["deadline"]

        manager = ModulesManager()
        self.deadline_module = manager.modules_by_name["deadline"]

        if not deadline_settings["enabled"]:
            self.deadline_servers = {}
            return
        self._project_settings = get_project_settings(
            legacy_io.Session["AVALON_PROJECT"])

        try:
            default_servers = deadline_settings["deadline_urls"]
            project_servers = (
                self._project_settings["deadline"]["deadline_servers"]
            )
            self.deadline_servers = {
                k: default_servers[k]
                for k in project_servers
                if k in default_servers
            }

            if not self.deadline_servers:
                self.deadline_servers = default_servers

        except AttributeError:
            # Handle situation were we had only one url for deadline.
            # get default deadline webservice url from deadline module
            self.deadline_servers = self.deadline_module.deadline_urls

    def process(self):
        """Entry point."""
        exists = cmds.ls(self.name)
        if exists:
            return cmds.warning("%s already exists." % exists[0])

        use_selection = self.options.get("useSelection")
        with lib.undo_chunk():
            self._create_vray_instance_settings()
            self.instance = super(CreateVRayScene, self).process()

            index = 1
            namespace_name = "_{}".format(str(self.instance))
            try:
                cmds.namespace(rm=namespace_name)
            except RuntimeError:
                # namespace is not empty, so we leave it untouched
                pass

            while(cmds.namespace(exists=namespace_name)):
                namespace_name = "_{}{}".format(str(self.instance), index)
                index += 1

            namespace = cmds.namespace(add=namespace_name)

            # add Deadline server selection list
            if self.deadline_servers:
                cmds.scriptJob(
                    attributeChange=[
                        "{}.deadlineServers".format(self.instance),
                        self._deadline_webservice_changed
                    ])

            # create namespace with instance
            layers = self._rs.getRenderLayers()
            if use_selection:
                print(">>> processing existing layers")
                sets = []
                for layer in layers:
                    print("  - creating set for {}".format(layer.name()))
                    render_set = cmds.sets(
                        n="{}:{}".format(namespace, layer.name()))
                    sets.append(render_set)
                cmds.sets(sets, forceElement=self.instance)

            # if no render layers are present, create default one with
            # asterix selector
            if not layers:
                render_layer = self._rs.createRenderLayer('Main')
                collection = render_layer.createCollection("defaultCollection")
                collection.getSelector().setPattern('*')

    def _deadline_webservice_changed(self):
        """Refresh Deadline server dependent options."""
        # get selected server
        from maya import cmds
        webservice = self.deadline_servers[
            self.server_aliases[
                cmds.getAttr("{}.deadlineServers".format(self.instance))
            ]
        ]
        pools = self.deadline_module.get_deadline_pools(webservice)
        cmds.deleteAttr("{}.primaryPool".format(self.instance))
        cmds.deleteAttr("{}.secondaryPool".format(self.instance))
        cmds.addAttr(self.instance, longName="primaryPool",
                     attributeType="enum",
                     enumName=":".join(pools))
        cmds.addAttr(self.instance, longName="secondaryPool",
                     attributeType="enum",
                     enumName=":".join(["-"] + pools))

    def _create_vray_instance_settings(self):
        # get pools
        pools = []

        system_settings = get_system_settings()["modules"]

        deadline_enabled = system_settings["deadline"]["enabled"]
        muster_enabled = system_settings["muster"]["enabled"]
        muster_url = system_settings["muster"]["MUSTER_REST_URL"]

        if deadline_enabled and muster_enabled:
            self.log.error(
                "Both Deadline and Muster are enabled. " "Cannot support both."
            )
            raise CreatorError("Both Deadline and Muster are enabled")

        self.server_aliases = self.deadline_servers.keys()
        self.data["deadlineServers"] = self.server_aliases

        if deadline_enabled:
            # if default server is not between selected, use first one for
            # initial list of pools.
            try:
                deadline_url = self.deadline_servers["default"]
            except KeyError:
                deadline_url = [
                    self.deadline_servers[k]
                    for k in self.deadline_servers.keys()
                ][0]

            pool_names = self.deadline_module.get_deadline_pools(deadline_url)

        if muster_enabled:
            self.log.info(">>> Loading Muster credentials ...")
            self._load_credentials()
            self.log.info(">>> Getting pools ...")
            try:
                pools = self._get_muster_pools()
            except requests.exceptions.HTTPError as e:
                if e.startswith("401"):
                    self.log.warning("access token expired")
                    self._show_login()
                    raise CreatorError("Access token expired")
            except requests.exceptions.ConnectionError:
                self.log.error("Cannot connect to Muster API endpoint.")
                raise CreatorError("Cannot connect to {}".format(muster_url))
            pool_names = []
            for pool in pools:
                self.log.info("  - pool: {}".format(pool["name"]))
                pool_names.append(pool["name"])

            self.data["primaryPool"] = pool_names

        self.data["suspendPublishJob"] = False
        self.data["priority"] = 50
        self.data["whitelist"] = False
        self.data["machineList"] = ""
        self.data["vraySceneMultipleFiles"] = False
        self.options = {"useSelection": False}  # Force no content

    def _load_credentials(self):
        """Load Muster credentials.

        Load Muster credentials from file and set ``MUSTER_USER``,
        ``MUSTER_PASSWORD``, ``MUSTER_REST_URL`` is loaded from presets.

        Raises:
            CreatorError: If loaded credentials are invalid.
            AttributeError: If ``MUSTER_REST_URL`` is not set.

        """
        app_dir = os.path.normpath(appdirs.user_data_dir("pype-app", "pype"))
        file_name = "muster_cred.json"
        fpath = os.path.join(app_dir, file_name)
        file = open(fpath, "r")
        muster_json = json.load(file)
        self._token = muster_json.get("token", None)
        if not self._token:
            self._show_login()
            raise CreatorError("Invalid access token for Muster")
        file.close()
        self.MUSTER_REST_URL = os.environ.get("MUSTER_REST_URL")
        if not self.MUSTER_REST_URL:
            raise AttributeError("Muster REST API url not set")

    def _get_muster_pools(self):
        """Get render pools from Muster.

        Raises:
            CreatorError: If pool list cannot be obtained from Muster.

        """
        params = {"authToken": self._token}
        api_entry = "/api/pools/list"
        response = requests_get(self.MUSTER_REST_URL + api_entry,
                                params=params)
        if response.status_code != 200:
            if response.status_code == 401:
                self.log.warning("Authentication token expired.")
                self._show_login()
            else:
                self.log.error(
                    ("Cannot get pools from "
                     "Muster: {}").format(response.status_code)
                )
                raise CreatorError("Cannot get pools from Muster")
        try:
            pools = response.json()["ResponseData"]["pools"]
        except ValueError as e:
            self.log.error("Invalid response from Muster server {}".format(e))
            raise CreatorError("Invalid response from Muster server")

        return pools

    def _show_login(self):
        # authentication token expired so we need to login to Muster
        # again to get it. We use Pype API call to show login window.
        api_url = "{}/muster/show_login".format(
            os.environ["OPENPYPE_WEBSERVER_URL"])
        self.log.debug(api_url)
        login_response = requests_get(api_url, timeout=1)
        if login_response.status_code != 200:
            self.log.error("Cannot show login form to Muster")
            raise CreatorError("Cannot show login form to Muster")


from django import forms

from .models import ColorPickerImageHolder

# В этом разделе создаются формы для html-страниц

# Создаем класс формы, который связан с моделью ColorPickerImageHolder из базы данных

class ImageUploadForm(forms.ModelForm):
    class Meta:

        # Связываем данную форму с моделью ColorPickerImageHolder из базы данных
        # Берем поля модели за основу формы

        model = ColorPickerImageHolder

        # Отображаем только следующие поля модели

        fields = ("image_title", "image_file", )

        # Видоизменяем поля модели в поля формы и добавляем стороние атрибуты

        widgets = {

            # Текстовое поле

            "image_title": forms.TextInput(
                attrs={'type': 'text', 'class': 'form-control mt-1', 'placeholder': 'Название изображения',
                       'name': 'image_title',
                       'required': 'required'}),

            # Поле выбора файлов

            "image_file": forms.ClearableFileInput(
                attrs={'type': 'file', 'class': 'form-control mt-2', 'name': 'image-for-color-picker-path',
                       'accept': 'image/png, image/jpeg',
                       'required': 'required'}),

        }


#!/usr/bin/env python3
import cgi
import cgitb
import sys
import sqlite3
cgitb.enable()

def get_24hour(hour, period):
    """
    Converts 12-hour time string to 24-hour
    :param hour: string
    :param period: either 'AM' or 'PM' string
    :return: 24-hour string
    """
    if period == "PM":
        if hour != "12":
            return str(int(hour) + 12)
    elif hour == "12":
            return '0'
    return hour

def check_duration(duration):
    """
    Sanitizes input from text box
    :param duration: Text box input
    :return: Sanitized duration or error message
    """
    if not duration:
        return "empty"
    if len(duration) > 3:
        return "bad length"
    try:
        int(duration)
    except ValueError:
        return "not int"
    if int(duration) < 0 or int(duration) > 300:
        return "out of range"
    return duration

# SQLITE database
DATABASE = '/tmp/waterings.db'

# Print header
print('Content-type: text/html\r\n\r\n')
sys.stdout.flush()

# Bool indicating if command was successful
success = False
# Connect to database and run SQL command
conn = sqlite3.connect(DATABASE)
form = cgi.FieldStorage()
day = form.getvalue('day')
if isinstance(day, list) and len(day) > 0:
    for d in day:
        hour = get_24hour(form.getvalue('hour'), form.getvalue('period'))
        minute = form.getvalue('minute')
        duration = check_duration(form.getvalue('duration'))
        if duration == "empty":
            print('
ERROR: Duration must be set
')
            print('
<form action="/schedule_watering.html"><input type="Submit" value="Return"/></form>')
            quit()
        if duration == "bad length" or duration == "out of range":
            print('
ERROR: Duration can only be in range of 1 to 300 minutes
')
            print('
<form action="/watering_schedule.html"><input type="Submit" value="Return"/></form>')
            quit()
        elif duration == "not int":
            print('
ERROR: Input is not an integer
')
            print('
<form action="/watering_schedule.html"><input type="Submit" value="Return"/></form>')
            quit()
        cur = conn.execute('INSERT INTO waterings (day, hour, minute, duration) VALUES (?, ?, ?, ?)',
                           (d, hour, minute, duration))
        if cur.rowcount == 1:
            success = True
elif not day:
    print('
ERROR: Must enter a day
')
    print('
<form action="/schedule_watering.html"><input type="Submit" value="Return"/></form>')
    quit()
else:
    hour = get_24hour(form.getvalue('hour'), form.getvalue('period'))
    minute = form.getvalue('minute')
    duration = check_duration(form.getvalue('duration'))
    if duration == "empty":
        print('
ERROR: Duration must be set
')
        print('
<form action="/schedule_watering.html"><input type="Submit" value="Return"/></form>')
        quit()
    elif duration == "bad length" or duration == "out of range":
        print('
ERROR: Duration can only be in range of 1 to 300 minutes
')
        print('
<form action="/schedule_watering.html"><input type="Submit" value="Return"/></form>')
        quit()
    elif duration == "not int":
        print('
ERROR: Input is not an integer
')
        print('
<form action="/schedule_watering.html"><input type="Submit" value="Return"/></form>')
        quit()
    cur = conn.execute('INSERT INTO waterings (day, hour, minute, duration) VALUES (?, ?, ?, ?)',
                       (day, hour, minute, duration))
    if cur.rowcount == 1:
        success = True
conn.commit()
conn.close()

if success:
    print('
Watering has been added to schedule
')
else:
    print('
ERROR: Not able to add watering to schedule
')

print('
<form action="/schedule_watering.html"><input type="Submit" value="Add another watering to schedule"/></form>')
print('
<form action="/cgi-bin/watering_schedule.py"><input type="Submit" value="Return to schedule"/></form>')


import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation, rc
from shapely.geometry import Point, LineString
from HamSandwich.GeomUtils import *

def prepare_axis(min_x=-10,max_x=10,min_y=-10,max_y=10):
    plt.grid(True,which='major')
    ax = plt.gca()
    min_x = int(min_x)
    max_x = int(max_x)
    min_y = int(min_y)
    max_y = int(max_y)
    ax.set_xlim(min_x,max_x)
    ax.set_ylim(min_y,max_y)
    plt.xticks(np.arange(min(np.array(ax.get_xlim())), max(np.array(ax.get_xlim()))+1, 1.0))
    plt.yticks(np.arange(min(np.array(ax.get_ylim())), max(np.array(ax.get_ylim()))+1, 1.0))
    plt.axhline(0, color='black')
    plt.axvline(0, color='black')

def plot_line(L, linestyle='--', color='b'):
    """Add line to axis

    Arguments:
        L {GeomUtils.Line}
    """
    axes = plt.gca()
    x_vals = np.array(axes.get_xlim())
    y_vals = L.b + L.m * x_vals
    plt.plot(x_vals, y_vals, ls=linestyle, color=color)

def plot_vertical_line(x, linestyle=':', color='g', linewidth=2):
    """Plot vertical line on axis

    Arguments:
        x {int} -- X coordinate
    """
    plt.axvline(x=x, ls=linestyle, color=color, linewidth=linewidth)

def plot_line_segment(L, linestyle='-', color='b'):
    """Add line segment to axis

    Arguments:
        L {GeomUtils.LineSegment}
    """
    plt.plot([L.p1.x,L.p2.x],[L.p1.y,L.p2.y], ls=linestyle, color=color, linewidth=4)

def plot_point(P, marker='o', color='b',size=5):
    """Add point to axis

    Arguments:
        P {shapely.geometry Point}
    """
    plt.plot(P.x,P.y, marker=marker, color=color,markersize=size)

def plot_interval(I, linestyle=':', color='g'):
    plot_vertical_line(I.l, linestyle=linestyle, color=color, linewidth=2)
    plot_vertical_line(I.r, linestyle=linestyle, color=color, linewidth=2)

def plot_points_and_duals(ham_instance,x=0.5):
    for p,d in zip(ham_instance.red_points, ham_instance.red_duals):
        plot_point(p, color='r')
        plt.draw()
        plt.pause(x)
        plot_line(d, color='r')
        plt.draw()
        plt.pause(x)
    if ham_instance.extra_red:
        plot_point(ham_instance.extra_red, color='r')
        plt.draw()
        plt.pause(x)
        plot_line(compute_dual_line(ham_instance.extra_red), color='r')
        plt.draw()
        plt.pause(x)
    for p,d in zip(ham_instance.blue_points, ham_instance.blue_duals):
        plot_point(p, color='b')
        plt.draw()
        plt.pause(x)
        plot_line(d, color='b')
        plt.draw()
        plt.pause(x)
    if ham_instance.extra_blue:
        plot_point(ham_instance.extra_blue, color='b')
        plt.pause(x)
        plot_line(compute_dual_line(ham_instance.extra_blue), color='b')
        plt.pause(x)

def plot_point_set(ham_instance,x=0.5):
    for p in ham_instance.red_points:
        plot_point(p, color='r')
        plt.draw()
        plt.pause(x)
    if ham_instance.extra_red:
        plot_point(ham_instance.extra_red, color='r')
        plt.pause(x)
    for p in ham_instance.blue_points:
        plot_point(p, color='b')
        plt.draw()
        plt.pause(x)
    if ham_instance.extra_blue:
        plot_point(ham_instance.extra_blue, color='b')
        plt.pause(x)


from __future__ import (
    annotations,
)

import hashlib
import hmac
from io import (
    BytesIO,
)
from typing import (
    Generic,
)

from btctoy.codec import (
    encode_base58_checksum,
)
from btctoy.crypto.prime import (
    is_prime,
)
from btctoy.crypto.types import (
    FieldElementT,
)

# Secp256k1 ECDSA parameters
# https://en.bitcoin.it/wiki/Secp256k1

EC_A = 0
EC_B = 7
EC_PRIME = 2**256 - 2**32 - 2**9 - 2**8 - 2**7 - 2**6 - 2**4 - 2**0
G_X = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798
G_Y = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8
G_ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141

def is_on_elliptic_curve(
    x: FieldElementT, y: FieldElementT, a: FieldElementT, b: FieldElementT
) -> bool:
    return y**2 == x**3 + a * x + b

def hash160(s: bytes) -> bytes:
    """sha256 followed by ripemd160"""
    return hashlib.new("ripemd160", hashlib.sha256(s).digest()).digest()

def hash256(s: bytes) -> bytes:
    """two rounds of sha256"""
    return hashlib.sha256(hashlib.sha256(s).digest()).digest()

class ModularFieldInteger:
    value: int
    prime: int

    def __init__(self, value: int, prime: int) -> None:
        if is_prime(prime) is False:
            raise ValueError(f"{prime} is not a prime integer")
        self.value = value % prime
        self.prime = prime

    def __repr__(self) -> str:
        return f"F_{self.prime}({self.value})"

    def __eq__(self, other: ModularFieldInteger) -> bool:
        if other is None:
            return False
        return self.value == other.value and self.prime == other.prime

    def __ne__(self, other: ModularFieldInteger) -> bool:
        # this should be the inverse of the == operator
        return not (self == other)

    def __add__(self, other: ModularFieldInteger) -> ModularFieldInteger:
        if self.prime != other.prime:
            raise TypeError("Cannot add two numbers in different Fields")
        value = (self.value + other.value) % self.prime
        return self.__class__(value, self.prime)

    def __sub__(self, other: ModularFieldInteger) -> ModularFieldInteger:
        if self.prime != other.prime:
            raise TypeError("Cannot subtract two numbers in different Fields")
        value = (self.value - other.value) % self.prime
        return self.__class__(value, self.prime)

    def __mul__(self, other: ModularFieldInteger) -> ModularFieldInteger:
        if self.prime != other.prime:
            raise TypeError("Cannot multiply two numbers in different Fields")
        value = (self.value * other.value) % self.prime
        return self.__class__(value, self.prime)

    def __pow__(self, exponent: int) -> ModularFieldInteger:
        n = exponent % (self.prime - 1)
        value = pow(self.value, n, self.prime)
        return self.__class__(value, self.prime)

    def __truediv__(self, other: ModularFieldInteger) -> ModularFieldInteger:
        if self.prime != other.prime:
            raise TypeError("Cannot divide two numbers in different Fields")
        value = (self.value * pow(other.value, self.prime - 2, self.prime)) % self.prime
        return self.__class__(value, self.prime)

    def __rmul__(self, coefficient: int) -> ModularFieldInteger:
        value = (self.value * coefficient) % self.prime
        return self.__class__(value=value, prime=self.prime)

class EllipcCurvePoint(Generic[FieldElementT]):
    x: FieldElementT
    y: FieldElementT
    a: FieldElementT
    b: FieldElementT

    def __init__(
        self,
        x: FieldElementT | None,
        y: FieldElementT | None,
        a: FieldElementT,
        b: FieldElementT,
    ) -> None:
        self.a = a
        self.b = b
        self.x = x
        self.y = y

        # x being None and y being None represents the point at infinity
        # Check for that here since the equation below won't make sense
        # with None values for both.
        if self.x is None and self.y is None:
            return

        if self.x is None or self.y is None:
            raise ValueError("Coordinates should both be None, or both be FieldElement")

        if is_on_elliptic_curve(x, y, a, b) is False:
            raise ValueError(f"({x}, {y}) is not on the elliptic curve")

    def __eq__(self, other: EllipcCurvePoint[FieldElementT]) -> bool:
        return (
            self.x == other.x
            and self.y == other.y
            and self.a == other.a
            and self.b == other.b
        )

    def __ne__(self, other: EllipcCurvePoint[FieldElementT]) -> bool:
        # this should be the inverse of the == operator
        return not (self == other)

    def __repr__(self) -> str:
        if self.x is None:
            return "ECP(infinity)"
        elif isinstance(self.x, ModularFieldInteger):
            return f"ECP({self.x.value}, {self.y.value})_{ self.a.value}_{self.b.value}_F_{self.x.prime}"
        return f"ECP({self.x}, {self.y})_{self.a}_{self.b}".format(
            self.x, self.y, self.a, self.b
        )

    def __add__(
        self, other: EllipcCurvePoint[FieldElementT]
    ) -> EllipcCurvePoint[FieldElementT]:
        if self.a != other.a or self.b != other.b:
            raise TypeError(
                "Points {}, {} are not on the same curve".format(self, other)
            )
        # Case 0.0: self is the point at infinity, return other
        if self.x is None:
            return other
        # Case 0.1: other is the point at infinity, return self
        if other.x is None:
            return self

        # Case 1: self.x == other.x, self.y != other.y
        # Result is point at infinity
        if self.x == other.x and self.y != other.y:
            return self.__class__(None, None, self.a, self.b)

        # Case 2: self.x ≠ other.x
        # Formula (x3,y3)==(x1,y1)+(x2,y2)
        # s=(y2-y1)/(x2-x1)
        # x3=s**2-x1-x2
        # y3=s*(x1-x3)-y1
        if self.x != other.x:
            s = (other.y - self.y) / (other.x - self.x)
            x = s**2 - self.x - other.x
            y = s * (self.x - x) - self.y
            return self.__class__(x, y, self.a, self.b)

        # Case 4: if we are tangent to the vertical line,
        # we return the point at infinity
        # note instead of figuring out what 0 is for each type
        # we just use 0 * self.x
        if self == other and self.y == 0 * self.x:
            return self.__class__(None, None, self.a, self.b)

        # Case 3: self == other
        # Formula (x3,y3)=(x1,y1)+(x1,y1)
        # s=(3*x1**2+a)/(2*y1)
        # x3=s**2-2*x1
        # y3=s*(x1-x3)-y1
        if self == other:
            s = (3 * self.x**2 + self.a) / (2 * self.y)
            x = s**2 - 2 * self.x
            y = s * (self.x - x) - self.y
            return self.__class__(x, y, self.a, self.b)

    def __rmul__(self, coefficient: int) -> EllipcCurvePoint[FieldElementT]:
        # Implementation of fast scalar product
        coef = coefficient
        current = self
        result = self.__class__(None, None, self.a, self.b)
        while coef:
            if coef & 1:
                result += current
            current += current
            coef >>= 1
        return result

class S256Integer(ModularFieldInteger):
    def __init__(self, value: int, prime: int = EC_PRIME) -> None:
        if prime != EC_PRIME:
            raise ValueError(
                f"S256Integer only supports EC_PRIME={EC_PRIME:x} as prime"
            )
        super().__init__(value=value, prime=prime)

    def __repr__(self) -> str:
        return f"{self.value:064x}"

    def sqrt(self) -> ModularFieldInteger:
        return self ** ((EC_PRIME + 1) // 4)

A = S256Integer(EC_A)
B = S256Integer(EC_B)

class S256Point(EllipcCurvePoint[ModularFieldInteger]):
    def __init__(
        self,
        x: int | S256Integer | None,
        y: int | S256Integer | None,
        a: S256Integer = A,
        b: S256Integer = B,
    ) -> None:
        if a != A:
            raise ValueError(f"S256Integer only supports A={A} for a")
        if b != B:
            raise ValueError(f"S256Integer only supports B={B} for b")
        super().__init__(
            x=None if x is None else S256Integer(x) if isinstance(x, int) else x,
            y=None if y is None else S256Integer(y) if isinstance(x, int) else y,
            a=A,
            b=B,
        )

    def __repr__(self) -> str:
        if self.x is None:
            return "S256Point(infinity)"
        else:
            return f"S256Point({self.x}, {self.y})"

    def __rmul__(self, coefficient: int) -> S256Point:
        coef = coefficient % G_ORDER
        return super().__rmul__(coef)

    def verify(self, z: int, sig: Signature) -> bool:
        s_inv = pow(sig.s, G_ORDER - 2, G_ORDER)
        u = z * s_inv % G_ORDER
        v = sig.r * s_inv % G_ORDER
        total = u * G + v * self
        return total.x.value == sig.r

    def sec(self, compressed: bool = True) -> bytes:
        """returns the binary version of the SEC format"""
        # TODO implementer la fonction
        if compressed:
            # if compressed, starts with b'\x02' if self.y.value is even, b'\x03' if self.y is odd
            # then self.x.value
            # remember, you have to convert self.x.value and self.y.value to binary (some_integer.to_bytes(32, 'big'))
            if self.y.value % 2 == 0:
                return b"\x02" + self.x.value.to_bytes(32, "big")
            else:
                return b"\x03" + self.x.value.to_bytes(32, "big")
            # pass
        else:
            # if non-compressed, starts with b'\x04' followod by self.x and then self.y
            return (
                b"\x04"
                + self.x.value.to_bytes(32, "big")
                + self.y.value.to_bytes(32, "big")
            )
            _# pass

    def hash160(self, compressed: bool = True) -> bytes:
        return hash160(self.sec(compressed))

    def address(self, compressed: bool = True, testnet: bool = False) -> str:
        h160 = self.hash160(compressed)
        if testnet:
            prefix = b"\x6f"
        else:
            prefix = b"\x00"
        return encode_base58_checksum(prefix + h160)

    @classmethod
    def parse(cls, sec_bin: bytes) -> S256Point:
        """returns a Point object from a SEC binary (not hex)"""
        # TODO completer la fonction qui décode ce qui est encodé dans sec()
        pass

G = S256Point(
    G_X,
    G_Y,
)

class Signature:
    r: int
    s: int

    def __init__(self, r: int, s: int) -> None:
        self.r = r
        self.s = s

    def __repr__(self) -> str:
        return f"Signature(r={self.r}, s={self.s})"

    def der(self) -> bytes:
        rbin = self.r.to_bytes(32, byteorder="big")
        # remove all null bytes at the beginning
        rbin = rbin.lstrip(b"\x00")

        if rbin[0] & 0x80:
            rbin = b"\x00" + rbin
        result = bytes([2, len(rbin)]) + rbin  # <1>
        sbin = self.s.to_bytes(32, byteorder="big")
        sbin = sbin.lstrip(b"\x00")
        if sbin[0] & 0x80:
            sbin = b"\x00" + sbin
        result += bytes([2, len(sbin)]) + sbin
        return bytes([0x30, len(result)]) + result

    @classmethod
    def parse(cls, signature_bin: bytes) -> Signature:
        s = BytesIO(signature_bin)
        compound = s.read(1)[0]
        if compound != 0x30:
            raise SyntaxError("Bad Signature")
        length = s.read(1)[0]
        if length + 2 != len(signature_bin):
            raise SyntaxError("Bad Signature Length")
        marker = s.read(1)[0]
        if marker != 0x02:
            raise SyntaxError("Bad Signature")
        rlength = s.read(1)[0]
        r = int.from_bytes(s.read(rlength), "big")
        marker = s.read(1)[0]
        if marker != 0x02:
            raise SyntaxError("Bad Signature")
        slength = s.read(1)[0]
        s = int.from_bytes(s.read(slength), "big")
        if len(signature_bin) != 6 + rlength + slength:
            raise SyntaxError("Signature too long")
        return cls(r, s)

class PrivateKey:
    secret: int
    point: S256Point

    def __init__(self, secret: int) -> None:
        self.secret = secret
        self.point = secret * G

    def hex(self) -> str:  # noqa: A003
        return f"{self.secret:064x}"

    def sign(self, z: int) -> Signature:
        k = self.deterministic_k(z)
        r = (k * G).x.value
        k_inv = pow(k, G_ORDER - 2, G_ORDER)
        s = (z + r * self.secret) * k_inv % G_ORDER
        if s > G_ORDER / 2:
            s = G_ORDER - s
        return Signature(r, s)

    def deterministic_k(self, z: int) -> int:
        k = b"\x00" * 32
        v = b"\x01" * 32
        if z > G_ORDER:
            z -= G_ORDER
        z_bytes = z.to_bytes(32, "big")
        secret_bytes = self.secret.to_bytes(32, "big")
        s256 = hashlib.sha256
        k = hmac.new(k, v + b"\x00" + secret_bytes + z_bytes, s256).digest()
        v = hmac.new(k, v, s256).digest()
        k = hmac.new(k, v + b"\x01" + secret_bytes + z_bytes, s256).digest()
        v = hmac.new(k, v, s256).digest()
        while True:
            v = hmac.new(k, v, s256).digest()
            candidate = int.from_bytes(v, "big")
            if candidate >= 1 and candidate < G_ORDER:
                return candidate
            k = hmac.new(k, v + b"\x00", s256).digest()
            v = hmac.new(k, v, s256).digest()

    def wif(self, compressed: bool = True, testnet: bool = False) -> str:
        secret_bytes = self.secret.to_bytes(32, "big")
        if testnet:
            prefix = b"\xef"
        else:
            prefix = b"\x80"
        if compressed:
            suffix = b"\x01"
        else:
            suffix = b""
        return encode_base58_checksum(prefix + secret_bytes + suffix)


from django import forms

from .models import *
from .widget import *
from django.utils.translation import gettext_lazy as _

class EngagementForm(forms.ModelForm):
    class Meta:
        model = Engagement

        fields = ['provider', 'parent', 'start_date',
                  'time_code', 'fye', 'type']

        widgets = {
            'fye': DatePickerInput,
            'start_date': DatePickerInput
        }

class EditEngagementForm(forms.ModelForm):
    class Meta:
        model = Engagement

        fields = ['provider', 'parent', 'start_date',
                  'time_code', 'budget_hours', 'fye', 'type', 'srg_id']

        widgets = {
            'fye': DatePickerInput,
            'start_date': DatePickerInput
        }

class CompleteEngagementForm(forms.ModelForm):
    class Meta:
        model = Engagement

        fields = ['is_complete']

        labels = {
            'is_complete': _('Is Complete')
        }

class AssignmentForm(forms.ModelForm):
    class Meta:
        model = Assignments

        fields = ['engagement', 'assignee']

class TimeForm(forms.ModelForm):
    class Meta:
        model = Time

        fields = ['date', 'hours', 'time_type_id', 'note']

        labels = {
            'date': _('Date'),
            'hours': _('Hours'),
            'time_type_id': _('Type'),
            'note': _('Note')
        }

        widgets = {
            'note': forms.Textarea(attrs={'rows': 5, 'cols': 40}),
            'date': DatePickerInput()
        }

class EditTimeForm(forms.ModelForm):
    class Meta:
        model = Time

        fields = ['engagement', 'date', 'hours', 'note']

        labels = {
            'engagement': _('Engagement'),
            'date': _('Date'),
            'hours': _('Hours'),
            'note': _('Note')
        }

        widgets = {
            'note': forms.Textarea(attrs={'rows': 5, 'cols': 40}),
            'date': DatePickerInput()
        }

class NewTimeCodeForm(forms.ModelForm):
    class Meta:
        model = Timecode

        fields = ['time_code', 'time_code_desc', 'time_code_hours']

        labels = {
            'time_code': _('Time Code'),
            'time_code_desc': _('Description'),
            'time_code_hours': _('Hours Budget')
        }

        widgets = {
            'time_code': forms.TextInput(attrs={'size': 5}),
            'time_code_desc': forms.TextInput(attrs={'size': 75}),
            'time_code_hours': forms.TextInput(attrs={'size': 5})
        }

class EditTimeCodeForm(forms.ModelForm):
    class Meta:
        model = Timecode

        fields = ['time_code_desc', 'time_code_hours']

        labels = {
            'time_code_desc': _('Description'),
            'time_code_hours': _('Hours Budget')
        }

        widgets = {
            'time_code_desc': forms.TextInput(attrs={'size': 75}),
            'time_code_hours': forms.TextInput(attrs={'size': 5})
        }

class TodoForm(forms.ModelForm):
    class Meta:
        model = Todolist

        fields = ['todo_date', 'anticipated_hours', 'note']

        labels = {
            'todo_date': _('Start Date'),
            'anticipated_hours': _('Expected Hours'),
            'note': _('Note')
        }

        widgets = {
            'note': forms.Textarea(attrs={'rows': 5, 'cols': 40}),
            'todo_date': DatePickerInput()
        }

class ExpenseForm(forms.ModelForm):
    class Meta:
        model = Expense

        fields = ['expense_category', 'expense_amount']

        labels = {
            'engagement': _('Engagement'),
            'expense_category': _('Category'),
            'expense_amount': _('Amount')
        }


import numpy as np
from joblib import Parallel, delayed
from scipy.interpolate import interp1d
from scipy.special import erf, erfinv
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import FLOAT_DTYPES, check_array, check_is_fitted

class GaussRankScaler(BaseEstimator, TransformerMixin):
    """Transform features by scaling each feature to a normal distribution.
    Parameters
        ----------
        epsilon : float, optional, default 1e-4
            A small amount added to the lower bound or subtracted
            from the upper bound. This value prevents infinite number
            from occurring when applying the inverse error function.
        copy : boolean, optional, default True
            If False, try to avoid a copy and do inplace scaling instead.
            This is not guaranteed to always work inplace; e.g. if the data is
            not a NumPy array, a copy may still be returned.
        n_jobs : int or None, optional, default None
            Number of jobs to run in parallel.
            ``None`` means 1 and ``-1`` means using all processors.
        interp_kind : str or int, optional, default 'linear'
           Specifies the kind of interpolation as a string
            ('linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic',
            'previous', 'next', where 'zero', 'slinear', 'quadratic' and 'cubic'
            refer to a spline interpolation of zeroth, first, second or third
            order; 'previous' and 'next' simply return the previous or next value
            of the point) or as an integer specifying the order of the spline
            interpolator to use.
        interp_copy : bool, optional, default False
            If True, the interpolation function makes internal copies of x and y.
            If False, references to `x` and `y` are used.
        Attributes
        ----------
        interp_func_ : list
            The interpolation function for each feature in the training set.
    """

    def __init__(
        self,
        epsilon=1e-4,
        copy=True,
        n_jobs=None,
        interp_kind="linear",
        interp_copy=False,
    ):
        self.epsilon = epsilon
        self.copy = copy
        self.interp_kind = interp_kind
        self.interp_copy = interp_copy
        self.fill_value = "extrapolate"
        self.n_jobs = n_jobs
        self.bound = 1.0 - self.epsilon

    def fit(self, X, y=None):
        """Fit interpolation function to link rank with original data for future scaling
        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            The data used to fit interpolation function for later scaling along the features axis.
        y
            Ignored
        """
        X = check_array(
            X, copy=self.copy, estimator=self, dtype=FLOAT_DTYPES, force_all_finite=True
        )

        self.interp_func_ = Parallel(n_jobs=self.n_jobs)(
            delayed(self._fit)(x) for x in X.T
        )
        return self

    def _fit(self, x):
        x = self.drop_duplicates(x)
        rank = np.argsort(np.argsort(x))
        factor = np.max(rank) / 2.0 * self.bound
        scaled_rank = np.clip(rank / factor - self.bound, -self.bound, self.bound)
        return interp1d(
            x,
            scaled_rank,
            kind=self.interp_kind,
            copy=self.interp_copy,
            fill_value=self.fill_value,
        )

    def transform(self, X, copy=None):
        """Scale the data with the Gauss Rank algorithm
        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            The data used to scale along the features axis.
        copy : bool, optional (default: None)
            Copy the input X or not.
        """
        check_is_fitted(self, "interp_func_")

        copy = copy if copy is not None else self.copy
        X = check_array(
            X, copy=copy, estimator=self, dtype=FLOAT_DTYPES, force_all_finite=True
        )

        X = np.array(
            Parallel(n_jobs=self.n_jobs)(
                delayed(self._transform)(i, x) for i, x in enumerate(X.T)
            )
        ).T
        return X

    def _transform(self, i, x):
        clipped = np.clip(self.interp_func_[i](x), -self.bound, self.bound)
        return erfinv(clipped)

    def inverse_transform(self, X, copy=None):
        """Scale back the data to the original representation
        Parameters
        ----------
        X : array-like, shape [n_samples, n_features]
            The data used to scale along the features axis.
        copy : bool, optional (default: None)
            Copy the input X or not.
        """
        check_is_fitted(self, "interp_func_")

        copy = copy if copy is not None else self.copy
        X = check_array(
            X, copy=copy, estimator=self, dtype=FLOAT_DTYPES, force_all_finite=True
        )

        X = np.array(
            Parallel(n_jobs=self.n_jobs)(
                delayed(self._inverse_transform)(i, x) for i, x in enumerate(X.T)
            )
        ).T
        return X

    def _inverse_transform(self, i, x):
        inv_interp_func = interp1d(
            self.interp_func_[i].y,
            self.interp_func_[i].x,
            kind=self.interp_kind,
            copy=self.interp_copy,
            fill_value=self.fill_value,
        )
        return inv_interp_func(erf(x))

    @staticmethod
    def drop_duplicates(x):
        is_unique = np.zeros_like(x, dtype=bool)
        is_unique[np.unique(x, return_index=True)[1]] = True
        return x[is_unique]


#!/usr/bin/env python
# coding: utf-8

# In[1]:

import numpy as np
import pandas as pd
from scipy.stats import  binom
from scipy.stats import  poisson

# In[2]:

def combinations(n, k):
    return (np.math.factorial(n)/(np.math.factorial(k)*np.math.factorial(n-k)))

# In[3]:

p1 = binom.pmf(0,5000,0.0004)

# In[4]:

p2 = binom.pmf(2,5000,0.0004)

# In[5]:

lam = 5000*0.0004

# In[6]:

p3 = poisson.pmf(0,lam)

# In[7]:

p4 = poisson.pmf(2,lam)

# In[8]:

print('Вероятность, что ни одна из них не перегорит в первый день (binom) =',p1)

# In[9]:

print('Вероятность, что ни одна из них не перегорит в первый день (poisson) =',p3)

# In[10]:

print('Вероятность, что перегорят ровно две (binom) =',p2)

# In[11]:

print('Вероятность, что перегорят ровно две (poisson) =',p4)


def euclid_minus(x,y):
    while (y):
        if x>y:
            x,y=y,x-y
        else: x,y=y-x,x
    return x

def euclid_div(x,y):
    while(y):
        x,y=y,x%y
    return x

def chance(a,b):
    from fractions import Fraction
    cnt=0
    for i in range(a+1,b+1):
        res=[]
        for j in range(1,i+1):
            if i%j==0:
                res.append(j)
        if len(res)%2==1:
            cnt+=1
    f=Fraction(cnt,b-a)
    print("%d/%d"%(f.numerator,f.denominator))

def print_time(x,y,n):
    t=1
    while t//x+t//y<n:
        t+=1
    return t

def printTime(x,y,n):
    timeX=[x*i for i in range(1,n+1)]
    timeY=[y*i for i in range(1,n+1)]
    time=sorted(timeX+timeY)
    print(time[n-1])


import base64
import logging
import os
import subprocess
import sys
import tempfile
import unittest

from PIL import Image
from PIL import ImageChops

import z3c.rml.tests
from z3c.rml import rml2pdf

LOG_FILE = os.path.join(os.path.dirname(__file__), 'render.log')

def gs_command(path):
    return ('gs', '-q', '-sNOPAUSE', '-sDEVICE=png256',
            '-sOutputFile=%s[Page-%%d].png' % path[:-4],
            path, '-c', 'quit')

class RMLRenderingTestCase(unittest.TestCase):

    def __init__(self, inPath, outPath):
        self._inPath = inPath
        self._outPath = outPath
        unittest.TestCase.__init__(self)

    def setUp(self):
        import z3c.rml.tests.module
        sys.modules['module'] = z3c.rml.tests.module
        sys.modules['mymodule'] = z3c.rml.tests.module

    def tearDown(self):
        del sys.modules['module']
        del sys.modules['mymodule']

        from z3c.rml.document import LOGGER_NAME
        for handler in logging.getLogger(LOGGER_NAME).handlers:
            if handler.baseFilename == LOG_FILE:
                handler.close()

        if os.path.exists(LOG_FILE):
            os.remove(LOG_FILE)

    def runTest(self):
        rml2pdf.go(self._inPath, self._outPath)

class ComparePDFTestCase(unittest.TestCase):

    level = 2

    def __init__(self, basePath, testPath):
        self._basePath = basePath
        self._testPath = testPath
        unittest.TestCase.__init__(self)

    def assertSameImage(self, baseImage, testImage):
        base_file = open(baseImage, 'rb')
        test_file = open(testImage, 'rb')
        base_image = Image.open(base_file)
        base = base_image.getdata()
        test_image = Image.open(test_file)
        test = test_image.getdata()

        has_diff = True
        for i in range(len(base)):
            # Stop at first difference
            if (base[i] - test[i]) != 0:
                break
        else:
            has_diff = False

        if has_diff and 'SHOW_IMAGE_DIFF' in os.environ:
            test_image.show()
            base_image.show()
            differ = ImageChops.subtract(test_image, base_image)
            differ.show()
            differ2 = ImageChops.subtract(base_image, test_image)
            differ2.show()
            # output the result as base64 for travis debugging
            if 'SHOW_DIFF_DEBUG' in os.environ:
                print(base64.b64encode(differ.tobytes()))
                print(base64.b64encode(differ2.tobytes()))

        if has_diff and 'SHOW_DIFF_DEBUG' in os.environ:
            print()
            print(os.system("gs --version"))

            base_file.seek(0)
            print(baseImage)
            print(base64.b64encode(base_file.read()))
            print(self._basePath)
            with open(self._basePath, 'rb') as base_pdf:
                print(base64.b64encode(base_pdf.read()))

            test_file.seek(0)
            print(testImage)
            print(base64.b64encode(test_file.read()))
            print(self._testPath)
            with open(self._testPath, 'rb') as test_pdf:
                print(base64.b64encode(test_pdf.read()))

        base_file.close()
        test_file.close()

        if has_diff:
            self.fail(
                'Image is not the same: %s' % os.path.basename(baseImage))

    def runTest(self):
        # Convert the base PDF to image(s)
        status = subprocess.Popen(gs_command(self._basePath)).wait()
        if status:
            return
        # Convert the test PDF to image(s)
        status = subprocess.Popen(gs_command(self._testPath)).wait()
        if status:
            return
        # Go through all pages and ensure their equality
        n = 1
        while True:
            baseImage = self._basePath[:-4] + '[Page-%i].png' % n
            testImage = self._testPath[:-4] + '[Page-%i].png' % n
            if os.path.exists(baseImage) and os.path.exists(testImage):
                self.assertSameImage(baseImage, testImage)
            else:
                break
            n += 1

class CompareFileTestCase(unittest.TestCase):

    def __init__(self, testPath, contains):
        self._testPath = testPath
        self._contains = contains
        unittest.TestCase.__init__(self)

    def runTest(self):
        with open(self._testPath, 'rb') as io:
            contents = io.read()

            if self._contains not in contents:
                self.fail(
                    'PDF file does not contain: %s' % self._contains
                )

def test_suite():
    if False:
        # Debug info
        import pkg_resources
        print("Environment\n===========")
        print("reportlab:")
        print(pkg_resources.get_distribution('reportlab').version)
        print("ghostscript:")
        os.system("gs --version")

    suite = unittest.TestSuite()
    here = os.path.dirname(z3c.rml.tests.__file__)
    inputDir = os.path.join(here, 'input')
    outputDir = tempfile.mkdtemp('z3c.rml-output')
    print(f'output dir: {outputDir}')
    expectDir = os.path.join(here, 'expected')
    for filename in os.listdir(inputDir):
        if not filename.endswith(".rml"):
            continue

        inPath = os.path.join(inputDir, filename)
        outPath = os.path.join(outputDir, filename[:-4] + '.pdf')
        expectPath = os.path.join(expectDir, filename[:-4] + '.pdf')

        # ** Test RML to PDF rendering **
        # Create new type, so that we can get test matching
        TestCase = type(filename[:-4], (RMLRenderingTestCase,), {})
        case = TestCase(inPath, outPath)
        suite.addTest(case)
        # ** Test PDF rendering correctness **
        TestCase = type('compare-' + filename[:-4], (ComparePDFTestCase,), {})
        case = TestCase(expectPath, outPath)
        suite.addTest(case)

        if filename == 'printScaling.rml':
            TestCase = type('compare-file-' + filename[:-4],
                            (CompareFileTestCase,), {})
            case = TestCase(outPath, b'/PrintScaling /None')
            suite.addTest(case)

    return suite