Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tugas Seleksi IRK Gregorius Dimas Baskara 13519190 #10

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
190 changes: 190 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
from models.sorts import database
from flask import Flask, request, render_template
import io
import csv
import time

app = Flask(__name__)


@app.route("/")
def main():
return "Tugas Seleksi IRK 2021"

@app.route("/sort/selection", methods=["POST"])
def selectionSort():
file = request.files["file"]
column = request.form["column"]
orientation = request.form["orientation"]
stream = io.StringIO(file.stream.read().decode("UTF8"), newline=None)
csv_input = csv.reader(stream)
final_table = [row for row in csv_input]
column_data = [row[int(column)] for row in final_table if len(row) > int(column)]

# Preprocess
numCount = 0
strCount = 0
for data in column_data:
if data.isnumeric():
numCount = numCount + 1
else:
strCount = strCount + 1

if (numCount >= strCount):
column_data = [data for data in column_data if data.isnumeric()]
else:
column_data = [data for data in column_data if not data.isnumeric()]

# Selection Sort
result = []
start_time = time.time()
if (orientation == "ASC"):
while (len(column_data) != 0):
minimum = column_data[0]
for i in range(1,len(column_data)):
if (column_data[i] < minimum):
minimum = column_data[i]
result.append(minimum)
column_data.remove(minimum)
else:
while (len(column_data) != 0):
maximum = column_data[0]
for i in range(1,len(column_data)):
if (column_data[i] > maximum):
maximum = column_data[i]
result.append(maximum)
column_data.remove(maximum)
exec_time = time.time() - start_time

print(result)

params = {
"algorithm": "selection",
"result": ",".join(result),
"exec_time": str(exec_time)
}

mysqldb.postSort(**params)

for i in range(len(final_table)):
if(len(final_table[i]) > int(column) and len(result) > i):
final_table[i][int(column)] = result[i]
if(len(result) <= i and len(final_table[i]) > int(column)):
final_table[i][int(column)] = None

htmlResult = """<html><body><table style="width:100%">"""
for row in final_table:
htmlResult = htmlResult + """<tr>"""
for col in row:
if (col is not None):
htmlResult = htmlResult + """<td>"""
htmlResult = htmlResult + str(col)
htmlResult = htmlResult + """</td>"""
htmlResult = htmlResult + """</tr>"""
htmlResult = htmlResult + """</table></body></html>"""

return htmlResult

@app.route("/sort/insertion", methods=["POST"])
def insertionSort():
file = request.files["file"]
column = request.form["column"]
orientation = request.form["orientation"]
stream = io.StringIO(file.stream.read().decode("UTF8"), newline=None)
csv_input = csv.reader(stream)
final_table = [row for row in csv_input]
column_data = [row[int(column)] for row in final_table if len(row) > int(column)]

# Preprocess
numCount = 0
strCount = 0
for data in column_data:
if data.isnumeric():
numCount = numCount + 1
else:
strCount = strCount + 1

if (numCount >= strCount):
column_data = [data for data in column_data if data.isnumeric()]
else:
column_data = [data for data in column_data if not data.isnumeric()]

# Insertion Sort
result = column_data
start_time = time.time()
if (orientation == "ASC"):
for i in range(1, len(result)):
pivot = result[i]
j = i - 1
while j >= 0 and pivot < result[j] :
result[j + 1] = result[j]
j -= 1
result[j + 1] = pivot
else:
for i in range(1, len(result)):
pivot = result[i]
j = i - 1
while j >= 0 and pivot > result[j] :
result[j + 1] = result[j]
j -= 1
result[j + 1] = pivot
exec_time = time.time() - start_time

params = {
"algorithm": "insertion",
"result": ",".join(result),
"exec_time": str(exec_time)
}

print(result)

mysqldb.postSort(**params)

for i in range(len(final_table)):
if(len(final_table[i]) > int(column) and len(result) > i):
final_table[i][int(column)] = result[i]
if(len(result) <= i and len(final_table[i]) > int(column)):
final_table[i][int(column)] = None

print(final_table)

htmlResult = """<html><body><table style="width:100%">"""
for row in final_table:
htmlResult = htmlResult + """<tr>"""
for col in row:
if (col is not None):
htmlResult = htmlResult + """<td>"""
htmlResult = htmlResult + str(col)
htmlResult = htmlResult + """</td>"""
htmlResult = htmlResult + """</tr>"""
htmlResult = htmlResult + """</table></body></html>"""

return htmlResult


@app.route("/sort/result", methods=["GET"])
def getResult():
if "id" in request.args.keys():
sort_id = request.args["id"]
response = mysqldb.getSort(sort_id)
else:
response = mysqldb.getSort()

response_dict = {
"id": response[0],
"date_time": response[1],
"algorithm": response[2],
"result": response[3],
"exec_time": response[4]
}
return response_dict

if __name__ == "__main__":
mysqldb = database()
if mysqldb.db.is_connected():
print('Connected to MySQL database')

app.run(debug=True)

if mysqldb.db is not None and mysqldb.db.is_connected():
mysqldb.db.close()
38 changes: 38 additions & 0 deletions html/options.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<html>

<body>
<table style="width:100%">
<tr>
<td>3</td>
<td>6</td>
<td>5</td>
</tr>
<tr>
<td>4</td>
<td>4</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>7</td>
</tr>
<tr>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td>3</td>
</tr>
<tr>
<td>4</td>
</tr>
<tr>
<td>5</td>
</tr>
</table>
</body>

</html>
Binary file added models/__pycache__/sorts.cpython-39.pyc
Binary file not shown.
38 changes: 38 additions & 0 deletions models/sorts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from mysql.connector import connect

class database:
def __init__(self):
try:
self.db = connect(host='localhost',
database='sortdb',
user='root',
password='taisanta')
except Exception as e:
print(e)

def postSort(self, **params):
try:
print(params["algorithm"])
cursor = self.db.cursor()
post_query ='''insert into sorts (algorithm, result, exec_time) values ('{0}', '{1}', {2})'''.format(
params["algorithm"], params["result"], params["exec_time"]
)
print(post_query)
cursor.execute(post_query)
self.db.commit()
return "Insert Success"
except Exception as e:
print(e)

def getSort(self, id=None):
try:
cursor = self.db.cursor()
if(id is None):
query ='''select * from sorts order by date_time desc limit 1;'''
else:
query ='''select * from sorts where id = {0};'''.format(id)
cursor.execute(query)
result = cursor.fetchone()
return result
except Exception as e:
print(e)
Loading