Link: https://bit.ly/430jrNv
Oleh:
Imam Cholissodin
Nurudin Santoso
Randy Cahya Wihandika
Agi Putra Kharisma
Putra Pandu Adikara
Tria Melia Masdiana Safitri
PENGANTAR
Buku ini memberikan penjabaran dari konsep Pemrograman
Web, Mobile sampai pada implementasi dalam bentuk prototype web
atau aplikasi software, mulai dari tentang client server, html, css, form,
DB SQL & No-SQL, JS, State, Operasi file, OOP dan MVC serta
penggunaan Framework Flask, Django, IoT Simulator & lainnya,
dengan mengimplementasikan pada kasus real dengan PHP, Node JS
dan Python, sampai pada proses release Web/Mobile App untuk
berbagai bidang strategis lainnya. Pembaca baik dari mahasiswa,
pengembang, praktisi/ lainnya diharapkan mudah memahami sebagai
dasar untuk membuat kode aplikasi yang powerfull.
Imam Cholissodin
Dosen Pengampu MK Analisis Big Data, Pemrograman Web, dan
Pemrograman Aplikasi Perangkat Bergerak FILKOM UB
2023
Kata Pengantar
ii
Daftar Isi
Judul ..................................................................................................... i
Kata Pengantar ..................................................................................... ii
Daftar Isi ...............................................................................................iii
Daftar Gambar .....................................................................................vii
BAB 1 Intro Pemrograman Web .................................................. 1
1.1 Tentang Internet dan Web ............................................... 1
1.1.1 Sejarah ................................................................. 1
1.1.2 Protokol HTTP & Lainnya .................................... 5
1.2 Roadmap Belajar Pemrograman Web ............................. 7
1.2.1 Start from the End / Goal dan Your CV ............... 7
1.2.2 Pahami Tips dan Motivasi Survive Membangun
Web App .......................................................................... 8
1.3 Tugas Kelompok .............................................................. 9
BAB 2 Dasar Koding, HTML & CSS .......................................... 11
2.1 HTML & CSS.................................................................. 11
2.2 Dasar Pemrograman Web dengan Python (Flask) ........ 13
2.2.1 Instalasi Library .................................................. 16
2.2.2 Dasar Variabel sampai Fungsi ........................... 17
2.2.3 Oop menggunakan Class .................................. 24
2.3 Dasar Pemrograman Web dengan PHP ........................ 28
2.3.1 Variabel .............................................................. 30
2.3.2 Concatenation .................................................... 30
2.3.3 Operator ............................................................. 31
2.3.4 String .................................................................. 32
2.3.5 Array................................................................... 32
2.3.6 Seleksi (if statements) ........................................ 33
2.3.7 Handling data dari form HTML ........................... 34
2.3.8 Perulangan ......................................................... 35
2.3.9 Fungsi ................................................................ 36
2.4 Tugas Kelompok ............................................................ 37
iii
BAB 3 Form, DB SQL/NoSQL & JavaScript (JS) ...................... 39
3.1 Pengantar Tentang Form ............................................... 39
3.2 Metode GET dan POST ................................................. 39
3.3 Validasi form .................................................................. 41
3.4 Implementasi CRUD ...................................................... 43
3.5 Sekilas NoSQL ............................................................... 44
3.6 JavaScript (JS) untuk Dasar Koding Berbasis Node JS 46
3.6.1 Pengantar .......................................................... 46
3.6.2 Dasar-Dasar JS ................................................. 46
3.6.3 JS Library & Framework .................................... 54
3.6.4 JS DOM.............................................................. 58
3.6.5 JS Events ........................................................... 59
3.6.6 JS Functions ...................................................... 60
3.6.7 JS Callbacks ...................................................... 61
3.6.8 JS AJAX & Fetch API ......................................... 62
3.7 Tugas Kelompok ............................................................ 65
BAB 4 State ............................................................................... 71
4.1 Tentang State................................................................. 71
4.2 Cookie ............................................................................ 72
4.3 Session .......................................................................... 73
4.4 Authentication: Login dan logout, vs Authorization ........ 75
4.5 Tugas Kelompok ............................................................ 78
BAB 5 Operasi File, OOP & MVC ............................................. 80
5.1 Pengantar Tentang Operasi File .................................... 80
5.1.1 File upload & download ...................................... 82
5.1.2 Operasi file & direktori ........................................ 85
5.2 Oop menggunakan PHP ................................................ 87
5.3 Konsep dan Pola MVC ................................................... 91
5.4 Tugas Kelompok ............................................................ 96
BAB 6 Framework & Tools ........................................................ 98
6.1 Pengantar Framework ................................................... 98
iv
6.2 Framework Flask, Django dan ExpressJS (Node) ....... 100
6.2.1 Popularitas Framework .................................... 100
6.2.2 Performasi Framework ..................................... 102
6.3 Framework Laravel ...................................................... 106
6.3.1 Instalasi, Konfigurasi di Local & Cloud ............ 106
6.3.2 Routing ............................................................. 114
6.3.3 Artisan .............................................................. 119
6.3.4 Model ............................................................... 120
6.3.5 Relationships ................................................... 122
6.3.6 Views................................................................ 124
6.3.7 Blade ................................................................ 125
6.3.8 Controller.......................................................... 128
6.3.9 Authentication, Middleware, Migration, Request &
CSRF 130
6.4 Konfigurasi Web App dari Local Colab atau Localhost
dengan Framework Streamlit/lainnya dan Tunneling ............. 135
6.4.1 Create Tunneling like Ngrok ............................ 135
6.4.2 Reverse SSH ................................................... 137
6.5 Tugas Kelompok .......................................................... 139
BAB 7 Study Kasus As Project ............................................... 140
7.1 Simple Flask & Django - PHP untuk Optimasi Fungsi . 140
7.1.1 Tentang Case Study ........................................ 140
7.1.2 Snippet Kode Program ..................................... 141
7.2 Operasi CRUD Python Flask – PHP Laravel ( SQLite –
MySQL dan MongoDB Atlas ) ................................................ 166
7.2.1 Tentang Case Study ........................................ 166
7.2.2 Snippet Kode Program ..................................... 166
7.3 Smart Big Data App (Python Web Django + Mobile
Native + CLI + RestFul API) untuk Klasifikasi ........................ 171
7.3.1 Tentang Case Study ........................................ 171
7.3.2 Snippet Kode Program ..................................... 172
7.4 Smart Big Data App (Python Web Django + Mobile Node
Js + RestFul API) untuk Prediksi............................................ 185
v
7.4.1 Tentang Case Study ........................................ 185
7.4.2 Snippet Kode Program ..................................... 185
7.5 Python Web Flask untuk Prediksi ................................ 189
7.5.1 Tentang Case Study ........................................ 189
7.5.2 Snippet Kode Program ..................................... 189
7.6 Prototype Big Data Studio: Jupyter Notebook + PySpark
Multi-Node, dll untuk Hadoop Distribution (edUBig / UBig Apps
Product) .................................................................................. 195
7.6.1 Tentang Case Study ........................................ 195
7.6.2 Snippet Kode Program ..................................... 196
7.7 Pengembangan Web App untuk IoT Simulator x Node-
RED x Node JS ...................................................................... 198
7.7.1 Tentang Case Study ........................................ 198
7.7.2 Snippet Kode Program ..................................... 199
7.8 Pengembangan Web App Node JS untuk Prototipe Full
Stack Apps ............................................................................. 203
7.8.1 Instalasi & Konfigurasi ..................................... 203
7.8.2 Snippet Kode Program ..................................... 204
7.9 Dashboard untuk Integrasi Real-Time Cloud-AI Berbasis
Web dan Pengujian Sistem .................................................... 210
7.9.1 Tentang Case Study ........................................ 210
7.9.2 Snippet Kode Program ..................................... 211
7.10 Pengembangan Prototipe Ai Virtual Programmer
Berbasis Web ......................................................................... 221
7.10.1 Tentang Case Study ...................................... 221
7.10.2 Snippet Kode Program ................................... 222
Daftar Pustaka .................................................................................. 224
Biografi Penulis ................................................................................. 229
vi
Daftar Gambar
vii
Gambar 5.2 Penanganan File dengan PHP ............................................... 80
Gambar 5.3 File Upload ......................................................................... 83
Gambar 5.4 Download ........................................................................... 84
Gambar 5.5 PHP directory Function ........................................................ 85
Gambar 5.6 Gambaran MVC Penyajian ke-1 ............................................ 91
Gambar 5.7 Gambaran MVC Penyajian ke-2 ............................................ 91
Gambar 5.8 MVC Design Pattern ............................................................ 92
Gambar 5.9 Ilustrasi Pola MVC pada Node JS vs Django ................. 92
Gambar 6.1 Django vs Flask vs Laravel vs Others...................................... 98
Gambar 6.2 Taylor Otwell (Founder of Laravel, dirilis pada Juni 2011) ....... 99
Gambar 6.3 CorePHP VS PHP Frameworks............................................... 99
Gambar 6.4 Ilustasi Meme Flask vs Django vs Express Node.js ..... 100
Gambar 6.5 Popularitas antar Framework (Backend) ...................... 101
Gambar 6.6 Performasi antar beberapa Framework (x: jumlah maks.
Request per detik, y: banyaknya Cores dan RAM) .......................... 103
Gambar 6.7 Login ................................................................................ 131
Gambar 6.8 Lupa password .................................................................. 131
Gambar 6.9 Register ............................................................................ 132
Gambar 6.10 Home .......................................................................... 132
Gambar 7.1 Simple Arsitektur Dashboard UI sistem monitoring secara
Real Time IoT Simulator Berbasis Web ........................................... 198
Gambar 7.2 Simple Dashboard Arsitektur untuk Integrasi Real Time
Cloud-AI Berbasis Web .................................................................... 210
Gambar 7.2 Simple Arsitektur untuk Prototipe Ai Virtual Programmer
Berbasis Web ................................................................................... 221
viii
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
DNS
Server
Web Server
Gambar 1.2 Komponen Internet
1
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
2
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
3
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
4
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
5
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
6
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Back-End
Front-End
IaaS, dll
7
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
8
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
9
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
10
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
11
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
<script type="text/javascript"
src="<?php echo DIR_JS; ?>brain.js"></script>
<!-- <?php echo (DIR_JS . $namajs); echo '<br>' ?> -->
<!-- <?php echo (DIR_JS . "brain.js"); echo '<br>' ?> -->
</head>
12
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
13
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
14
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
15
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
• Web App telah ter-setup (ubah http -> https agar lebih secure)
Detail instalasi nantinya dapat dilihat pada sub bab 6.2.1 yang
menggunakan akses dari file kode project dengan link
https://github.com/imamcs19/pyIR.git dari github.
16
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 19 November 2022
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
# app.debug = False
app.secret_key = 'fga^&&*(&^(filkom#BJH#G#VB#Big99nDatakPyICS_ap938255bnUB'
# keterangan:
# "#" adalah untuk comment
# <br> adalah new line
# adalah spasi
# <!-- --> atau <!--- ---> adalah untuk comment
FrameWeb_atas = """
{% extends "extends/base.html" %}
{% block title %}
<title>Web App MatKom Dgn Python</title>
{% endblock title %}
{{ self.title() }}
Home
{{ self.title() }}
<button onclick="window.location.href='/'" class="btn btn-outline btn-rounded btn-
info">
<i class="ti-arrow-left m-l-5"></i>
<span>Back Home</span>
</button> Project 1
{{ self.title() }}
Project 1
{% block content %}
"""
A_a = FrameWeb_atas
17
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
FrameWeb_bawah = """
{% endblock content %}
"""
Z_z = FrameWeb_bawah
@app.route('/')
def hello_world():
return 'Hello Web Apps Using Python Flask'
@app.route('/add')
def add():
# membuat penjumlahan 2 bilangan
a = 10
b = 90
c = a + b
return str(c)
return str(c)
return str(c)
# buatlah tampilan indeks looping 1..10 dengan new line (<br> dari tag html)
@app.route('/loop_new_line')
def loop_new_line():
c = ''
for i in range(10): # i = 0,1,..,9
c +=str(i+1) + '<br>'
return str(c)
return str(c)
# ================ akhir - dasar ke-1 ===============
#
# buat halaman post sekaligus get
# nilai a dan b, lalu ditambahkan
# dengan return kode html dalam flask python Web App
@app.route('/post_add2', methods=["POST", "GET"])
def inputkan_ab():
# membuat penjumlahan 2 bilangan
if request.method == 'POST':
18
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
a_in = float(request.form['a'])
b_in = float(request.form['b'])
c = a_in + b_in
return '''
<html>
<head>
</head>
<body>
<form method="post">
<input type="text" name="a" value="%s" />
<input type="text" name="b" value="%s" />
<input type="submit" value="Hitung a + b"/>
</form>
<h2>Hasil a + b = %s + %s = %s </h2>
</body>
</html>
''' % (a_in, b_in, a_in, b_in, c)
#
# halaman post sekaligus get
# nilai a dan b, lalu ditambahkan
# dengan return file "form_add3.html" dalam folder "mysite/templates", flask python
Web App
@app.route('/post_add3', methods=["POST", "GET"])
def inputkan_ab3():
# membuat penjumlahan 2 bilangan
if request.method == 'POST':
a_in = float(request.form['a'])
b_in = float(request.form['b'])
c = a_in + b_in
# </body></html>
@app.route('/db/<aksi>')
def manipulate_tabel(aksi):
19
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
conn = connect_db()
db = conn.cursor()
if aksi == 'c':
str_info = 'tabel berhasil dibuat :D'
# create tabel
db.execute("""
CREATE TABLE IF NOT EXISTS data_gen
(tipe_run TEXT, date_pembuatan DATETIME,
teks_call_sintaks TEXT,
keterangan TEXT,
date_masa_berlaku DATETIME)
""")
elif aksi== 'd':
str_info = 'tabel berhasil dihapus :D'
# hapus tabel
db.execute("""
DROP TABLE IF EXISTS data_gen
""")
conn.commit()
db.close()
conn.close()
return str_info
#
# Contoh koding dasar operasi CRUD
#
def dasar2_create_database():
conn = connect_db()
cur = conn.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS CloudAI_Air (
id INTEGER PRIMARY KEY AUTOINCREMENT,
suhu_dlm_celcius TEXT,
humidity_kelembaban_dlm_persen TEXT,
precipitation_curah_hujan_dlm_persen TEXT,
wind_angin_dlm_km_per_jam TEXT,
durasi_air_dlm_menit TEXT
)
""")
conn.commit()
conn.close()
def dasar2_generate_data():
"""Generate sintesis atau dummy data untuk percontohan."""
conn = connect_db()
cur = conn.cursor()
if entry is None:
import numpy as np
import pandas as pd
import os.path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
20
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
path = "/home/"+userhome+"/mysite/static/data_contoh"
if not os.path.exists(path):
os.makedirs(path)
url_file_name_data_generate = os.path.join(BASE_DIR,
"static/data_contoh/Data_CloudAI_Air.csv")
df_gen.to_csv(url_file_name_data_generate, encoding='utf-8', index=False)
# Importing the dataset => ganti sesuai dengan case yg anda usulkan
dataset = pd.read_csv(url)
# X = dataset.iloc[:, :-1].values
# y = dataset.iloc[:, 1].values
def pushCSVdatasetToDB(x1,x2,x3,x4,y):
#inserting values inside the created table
cmd = "INSERT INTO CloudAI_Air(suhu_dlm_celcius,
humidity_kelembaban_dlm_persen, precipitation_curah_hujan_dlm_persen,
wind_angin_dlm_km_per_jam, durasi_air_dlm_menit)
VALUES('{}','{}','{}','{}','{}')".format(x1,x2,x3,x4,y)
cur.execute(cmd)
conn.commit()
else:
ket_hasil = 'Tidak dilakukan Insert, karena Tabel tidak kosong'
print(ket_hasil)
conn.commit()
cur.close()
conn.close()
@app.route('/dasar2_crud')
def dasar2_index():
return '<a href="/dasar2_list">Demo Menampilkan List dari Tabel + Support =>
Create, Read, Update, Delete (CRUD)</a>'
@app.route('/dasar2_list')
def dasar2_list():
conn = connect_db()
cur = conn.cursor()
conn.close()
21
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
conn = connect_db()
cur = conn.cursor()
if request.method == 'POST':
item_id = number
item_suhu = request.form['suhu']
item_kelembaban = request.form['kelembaban']
item_hujan = request.form['hujan']
item_angin = request.form['angin']
item_durasi = request.form['durasi']
# suhu_dlm_celcius, humidity_kelembaban_dlm_persen,
precipitation_curah_hujan_dlm_persen, wind_angin_dlm_km_per_jam,
durasi_air_dlm_menit
cur.execute("UPDATE CloudAI_Air SET suhu_dlm_celcius = ?,
humidity_kelembaban_dlm_persen = ?, precipitation_curah_hujan_dlm_persen =
?, wind_angin_dlm_km_per_jam = ?, durasi_air_dlm_menit = ? WHERE id = ?",
(item_suhu, item_kelembaban, item_hujan, item_angin, item_durasi, item_id))
conn.commit()
return redirect('/dasar2_list')
conn.close()
@app.route('/dasar2_delete/<int:number>')
def dasar2_delete(number):
conn = connect_db()
cur = conn.cursor()
conn.commit()
conn.close()
return redirect('/dasar2_list')
if request.method == 'POST':
# item_id = number
item_suhu = request.form['suhu']
item_kelembaban = request.form['kelembaban']
item_hujan = request.form['hujan']
item_angin = request.form['angin']
item_durasi = request.form['durasi']
return redirect('/dasar2_list')
return render_template_string(template_add)
@app.route('/dasar2_add2')
def dasar2_add2():
conn = connect_db()
cur = conn.cursor()
def F2C(f_in):
return (f_in - 32)* 5/9
def Kelvin2C(k_in):
return (k_in-273.15)
22
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# print(nama_kota)
conn.commit()
cur.close()
conn.close()
return redirect('/dasar2_list')
template_list = """
<h2>Menampilkan Data CloudAI Air + Support Create, Read, Update, delete (CRUD)</h2>
<a href="{{ url_for( "dasar2_add" ) }}">Tambah Data</a> |
<a href="{{ url_for( "dasar2_add2" ) }}">Tambah Data dari iot_api (tanpa nilai
Durasi Waktu)</a>
{% if rows %}
<table border="1">
<thead>
<td>No</td>
<td>Suhu (°C)</td>
<td>Kelembaban (%)</td>
<td>Curah Hujan (%)</td>
<td>Kecepatan Angin (Km/Jam)</td>
<td>Durasi Waktu Pengairan / Penyiraman (Menit)</td>
</thead>
template_add = """
23
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
template_edit = """
<h1>Edit Data CloudAI Air</h1>
<form method="POST" action="{{ url_for( "dasar2_edit", number=item[0] ) }}">
Suhu: <input name="suhu" value="{{item[1]}}"/></br>
Kelembaban: <input name="kelembaban" value="{{item[2]}}"/></br>
Curah Hujan: <input name="hujan" value="{{item[3]}}"/></br>
Kecepatan Angin: <input name="angin" value="{{item[4]}}"/></br>
Durasi Waktu Pengairan / Penyiraman: <input name="durasi"
value="{{item[5]}}"/></br>
<button>Simpan Update Data</button></br>
</form>
"""
def connect_db():
import os.path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, "data.db")
# with sqlite3.connect(db_path) as db:
return sqlite3.connect(db_path)
24
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 2 Juni 2020
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
os.environ["PYTHONPATH"] = "/spark-2.4.1-bin-hadoop2.7/python/"
os.environ["PYTHONPATH"] += \
":/spark-2.4.1-bin-hadoop2.7/python/lib/py4j-0.10.7-src.zip"
os.environ["PYTHONPATH"] += ":/content/drive/'My Drive'/'Master Big Data'"
os.environ["PYTHONPATH"] += ":/env/python"
# Cek byk threads tiap core dari CPU Google Colab, biasanya 2
!lscpu | grep 'Thread(s) per core'
# Secara default, Data awal yang ada, tampak dengan nomor atau urutan yang asli
# dari sumber datanya.
# Oleh karena itu, sebelum pengolahan lebih lanjut misal dengan SOM, maka data
# tersebut akan dilakukan pengacakan urutan (shuffling).
# Disini digunakan partisi secara berulang (repartition) untuk mengacak data
# sesuai dengan yang dibutuhkan.
# Besarnya partisi tersebut juga akan menjadi ukuran tingkat leveling
# paralelisme (jumlah tugas (task)) pekerjaan Spark pada data.
# Secara umum, disarankan 2-3 tugas (task) per inti CPU (CPU Core)
# di spark cluster. Jika Anda memiliki 4 core CPU,
# maka sebaiknya memutuskan dengan membuat, misal 8 partisi
# (yaitu dari "4 core CPU" x "2 task").
# shuffling data
# repartitioning to manage level of parallelism
Core_s_per_socket = 1
Thread_s_per_core = 2
#----------------------------------------------------------------------#
%%file com/algfromscratch/som/batch_som.py
25
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
#import pyspark
from pyspark import SparkContext, Row, SQLContext
from pyspark.ml.linalg import Vectors
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import patches as patches
__author__ = 'topsykretts_ReCoverbyNidos'
class SOM:
"""
Implementasi dari algoritma Self Organizing Map (SOM)
"""
def initialize(self):
# random matrik [0;1] dgn ukuran network_dimensions[0] x
# network_dimensions[1], sebanyak num_features
self.net = np.random.random((self.network_dimensions[0], \
self.network_dimensions[1], self.num_features))
if resetWeights:
self.initialize()
self.time_constant = num_epochs / np.log(self.init_radius)
# visualization
if self.num_features == 3:
fig = plt.figure()
else:
fig = None
rdd = df.rdd.cache()
sc = SparkContext.getOrCreate()
26
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
som2.train(scaledData, 20)
Output:
Big thanks to Python Flask, Apache Spark, Machine Learning Nepal, etc. :D
27
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
28
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
29
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<?php
echo "Hi, I'm a PHP script!";
?>
</body>
</html>
2.3.1 Variabel
Variabel adalah simbol atau nama yang mewakili suatu nilai.
Variabel digunakan untuk menyimpan nilai seperti nilai numerik,
karakter, string, atau alamat memori sehingga dapat digunakan pada
bagian manapun dari program ketika dipanggil.
//Anda dapat menggunakan tanda dollar lebih dari satu
$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";
2.3.2 Concatenation
Concatenation ( . ) adalah menggabungkan dua string atau lebih
menjadi satu kesatuan.
30
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
// Menggunakan Concatenation
echo "i"."am"; //output "iam"
echo("<br>");
echo "indo" . "nesia"; //output "indonesia"
echo("<br>");
echo 1 . 9; //output "19"
echo("<br>");
echo 1.9; //output 1.9
echo("<br>");
echo 10+9; //output 19
$a = '12345';
// Contoh lainnya
echo "qwe{$a}rty"; // qwe12345rty, dengan tanda braces
echo "qwe" . $a . "rty"; // qwe12345rty, dengan concatena-
tion
2.3.3 Operator
Operator adalah sesuatu yang identik dengan simbol yang
bagian kecil dari sintaks tertentu untuk melakukan operasi dengan
mengambil satu nilai atau lebih sehingga menghasilkan ekspresi dalam
bentuk nilai lain. Berdasarkan jumlah nilai yang diambil, dibagi menjadi
3, yaitu:
❖ Unary operators hanya mengambil satu nilai, misal ! sebagai
operator logika not atau ++ sebagai operator increment.
❖ Binary operators mengambil dua nilai, seperti operator
aritmatika + (plus) dan - (minus), dan mayoritas operator PHP
masuk dalam kategori ini.
❖ Single ternary operator, ? :, yang mengambil tiga nilai; ini
biasanya disingkat dengan "ternary operator" (yang cara
kerjanya sama dengan operator bersyarat seperti if..elseif).
Arithmetic Operator Logical Operator
+ = Addition && = And
- = Subtraction || = Or
* = Multiplication ! = Not
/ = Division and = And
% = Modulo xor = Xor
** = Exponentiation or = Or
dll.
31
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
2.3.4 String
String adalah karakter yang dirangkai, di mana tiap karakter
tersebut berukuran 1 byte. Hal ini menunjukkan bahwa PHP hanya
mendukung rangkaian stringnya dari kumpulan 256 karakter, dan tidak
menawarkan dukungan Unicode.
//cek string atau tidak
$var1="Pemrograman Web";
echo "\$var1 ada-
lah " . (is_string($var1)? "String" : "Bukan String");
echo '<br>';
$var2=100;
echo "\$var2 ada-
lah " . (is_string($var2)? "String" : "Bukan String");
Output: 6
2.3.5 Array
Array merupakan salah satu bentuk struktur data yang tersusun
dari kumpulan elemen, di mana masing-masing elemen tersebut
diidentifikasi setidaknya satu indeks atau kunci atau lebih jika
multidimensi (2D/ n-Dim), sehingga posisi dari tupel indeksnya
tersusun jelas dan mudah untuk mengaksesnya.
32
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
array(
key => value,
key2 => value2,
key3 => value3,
...
)
Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensi"]["array"]);
33
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
$a = 10; $b = 4;
34
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
proses.php
<html>
<head>
<title>Handling data dari form HTML</title>
</head>
<body>
<?php
$name = $_POST[“myvar”];
echo "Halo, “ . $name;
?>
Concatenation untuk meng-
</body>
</html> gabungkan string
2.3.8 Perulangan
Perulangan for digunakan untuk menjalankan pengulangan blok
kode tertentu dan sudah diketahui dengan pasti berapa kali banyak
perulangannya.
Sintaks for PHP:
Output: 0 1 2 3 4 5 6 7 8 9 10
Output: 2 4 6 8 10
35
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
$value = 10;
$n = (int)($value / 8);
while ($n < 10) {
$n++;
echo "$n\n";
}
Output: 2 3 4 5 6 7 8 9 10
2.3.9 Fungsi
Fungsi adalah bagian kode yang mengambil satu input atau
lebih, dalam bentuk argument-argumen atau parameter dan dapat
melakukan pemrosesan serta mengembalikan suatu nilai atau
keluaran tertentu. Fungsi dapat digunakan berulang kali dengan cukup
memanggil sesuai dengan nama fungsi tersebut dan diberikan input
yang berbeda nilai, sehingga keseluruhan kode program jadi lebih
ringkas.
Sintaks function PHP:
<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
echo "Example function.\n";
return $retval;
}
?>
Output: 0 1 1 2 3 5 8 13 21 34 55
36
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
(a)
(b)
3. Buatlah video dengan membuat modifikasi koding dasar-dasar
Python & PHP dengan tema “Learn Intro Web in -+ 15 minutes”,
mulai dari Variabel, Concatenation, Operator, String, Array, Seleksi
37
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
38
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
39
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
myget.php localhost/myget.php?nama=..&usia=..
1 <html>
2 <body>
3 <form action="" method="get">
4 Nama : <input type="text" name="nama"><br>
5 Usia: <input type="text" name=“usia"><br>
6 <input type="submit">
7 </form>
8 Hi <?php echo $_GET["nama"]; ?><br>
9 Usia Kamu <?php echo $_GET[“usia"]; ?>
10 </body>
11 </html>
POST GET
40
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
41
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
1 <?php
2 if(isset($_POST['form_submit'])) {
3 ..
4 $emailval = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-
]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/';
5 $mob="/^[1-9][0-9]*$/";
6 if($name=="" && $email=="" && $phone=="") :
7 $msg="Please fill all mandatory fields";
8 elseif(!preg_match($emailval, $email)) :
9 $msg="Please enter a valid email";
10 elseif(!preg_match($mob, $phone)) :
11 $msg="Please enter a valid number";
12 else :
13 // Write your insert coding
.. $msg_sucess="Record inserted successfully";
. $msg="";
endif;
}
?>
42
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Create Tabel
1 CREATE TABLE mhs (
2 nim INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
3 nama VARCHAR(100) NOT NULL,
4 semester INT(10) NOT NULL
5 );
43
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Query
1 Create:
2 $sql = "INSERT INTO mhs (nama, semester) VALUES (..,
..)";
3 Read:
4 $sql = "SELECT * FROM mhs WHERE nim = ..";
5 Update:
6 $sql = "UPDATE mhs SET nama=.., semester=.. WHERE nim
=?";
7 Delete:
8 $sql = "DELETE FROM mhs WHERE nim = ?";
44
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
45
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
3.6.1 Pengantar
Dasar-dasar JavaScript terdiri dari Variables, Constants, Data
Type, Objects, Arrays, Funtions, Conditional statements, Loops, Switch
case, dan Print atau Display.
3.6.2 Dasar-Dasar JS
Berikut ini merupkan dasar-dasar dari javascript.
• Variabel adalah nama atau label yang diberikan untuk suatu lokasi
memori yang berfungsi sebagai wadah untuk menyimpan data
sementara.
for (let i = 0; i < 5; i++) {
// i accessible ✔
}
// i not accessible ❌
46
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
let mhs= {
nim: 110,
nama: ‘Brone’,
Ipk: 4,
Motto: ‘Tangguh Bereputasi, Membangun Negeri'
};
47
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
48
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
<script>
const herbalArr = [
{ nama: 'kayu india', warna: 'coklat' },
{ nama: 'kayu putih', warna: 'putih' },
{ nama: 'habatus', warna: 'hitam' }
];
function obat1() {
const adaWarna = herbalArr.some(h => h.warna ==
'putih');
document.write(adaWarna + '<br>');
}
function obat2(herbal) {
if(herbal && herbal.nama){
const flag = herbalArr.some(h => h.nama ==
herbal.nama && h.warna == herbal.warna);
if (flag==true) {
document.write(herbal.nama + '<br>');
} else {
document.write('unknown <br>');
}
}else {
document.write('unknown <br>');
}
}
obat1();
obat2(undefined); obat2(); obat2({});
obat2({nama: 'kayu india', warna: 'coklat'});
</script>
49
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
// do while loop
do {
document.write("Angka " + i + "<br>");
i+=1;
}
while(i < 19);
// for loop
for (i=0;i<10;i++) {
document.write("Angka " + i + "<br>");
}
//Hasil Fnswitch
document.write(Fnswitch(null)+' <br>'); // []
document.write(Fnswitch('merah')); // ['apel', 'tomat']
50
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
function FnMap(warna) {
return buahBaseWarna.get(warna) || [];
}
//Hasil FnMap
document.write(FnMap(null)+' <br>'); // []
document.write(FnMap('merah')); // ['apel', 'tomat']
function Fnobject(warna) {
return buahBaseWarna[warna] || [];
}
//Hasil Fnobject
document.write(Fnobject(null)+' <br>'); // []
document.write(Fnobject('merah')); // ['apel', 'tomat']
51
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
function FnArrayFilter(warna) {
return buahArr.filter(f => f.warna == warna);
}
//Hasil FnArrayFilter
document.write(filterednames.map(f=>f.name)); //
['apel', 'tomat']
document.write(FnArrayFil-
ter(null).map(f=>f.name)+'<br>'); // []
document.write(FnArrayFilter('merah').map(f=>f.name));
// ['apel', 'tomat']
52
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Using document.write():
<!DOCTYPE html>
<html>
<body>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using document.write():
<!DOCTYPE html>
<html>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
alert(5 + 6);
</script>
</body>
</html>
53
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Using console.log():
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
Using window.print():
<!DOCTYPE html>
<html>
<body>
</body>
</html>
54
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
A. JS + CDN Tensorflow.js
CDN sekelompok server yang tersebar di banyak lokasi. Server
ini menyimpan salinan duplikat data sehingga server dapat memenuhi
permintaan data berdasarkan server mana yang paling dekat dengan
pengguna. CDN membuat layanan cepat karena tidak terpengaruh
oleh lalu lintas tinggi. Seperti library online yang disediakan oleh suatu
perusahaan pengembang yang dipasang pada platform server
diberbagai lokasi berdasarkan geografis.
Contoh JS + CDN TensorFlow.js (TF.js), (Demos,
https://imamcs19.github.io/cs-ds/reg/ ):
• Penjumlahan Bilangan
1 <script
2 src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0">
3 </script>
4
5 <input id="myButton1234" type="button" value="Use GPU
6 math" style="visibility:hidden;" onclick="{
7
8 //const myA = tf.scalar(6.1434, 'float32')
9 const myA = tf.tensor1d([10,20,30], 'int32')
10 const myB = tf.scalar(2.1, 'float32')
11 const myResult = tf.add(myA, myB);
12 //document.getElementById('myDiv1234').innerHTML =
13 myResult.dataSync()[0].toFixed(2)
55
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
14
15 let myArray = Array.from(myResult.dataSync());
16 let result2 = myArray.map(a => a.toFixed(2));
17 document.getElementById('myDiv1234').innerHTML = result2
18
19 }"><br><br>
20 <div id='myDiv1234'>...</div><br>
56
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
12 ];
13 const trainY = [
14 1.0,
15 2.76,
16 1.3
17 ];
18
19 const m = tf.variable(tf.scalar(Math.random()));
20 const b = tf.variable(tf.scalar(Math.random()));
21
22 function predict(x) {
23 return tf.tidy(function() {
24 return m.mul(x).add(b);
25 });
26 }
27
28 ..
29
B. jQuery
Berikut ini contoh jQuery click().
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <script
5 src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/
6 jquery.min.js"></script>
7 <script>
8 $(document).ready(function(){
9 $("p").click(function(){
10 $(this).hide();
11 });
12 });
13 </script>
14 </head>
57
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
15 <body>
16
17 <p>If you click on me, I will disappear.</p>
18 <p>Click me away!</p>
19 <p>Click me too!</p>
20
21 </body>
22 </html>
1 <script
2 src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/
3 jquery.min.js"></script>
4 <div id="result" style="border: 1px solid red;">
5 (Klik tombol "Click Me" untuk me-replace teks ini)
6 </div>
7 <input type=button value="Click Me"
8 onClick="change_content('result')">
9
10 <script>
11 function change_content(id) {
12 var string = ‘jQuery - Pemrograman Web';
13 $('#'+id).text(string);
14 }
15 </script>
1 <script
2 src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/
3 jquery.min.js"></script>
4 <p>Clicking on each number will log to console:</p>
5 <div id="div1">1</div>
6 <div id="div2">2</div>
7 <div id="div3">3</div>
8 <div id="div4">4</div>
9 <div id="div5">5</div>
10
11 <script>
12 for(let i=1; i<6; i++) {
13 $("#div" + i).click(function () { alert(i); });
14 }
15 </script>
3.6.4 JS DOM
Javascript DOM (Document Object Model) adalah antarmuka
pemrograman (programing interface) HTML, XML, SVG yang
memungkinkan pengembang memanipulasi konten, struktur, dan
58
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
style situs web secara dinamis dengan menggunakan JS, juga bisa
menggunakan scripting language lainnya.
Misal menggunakan objek document untuk menampilkan “Hi JS
DOM” pada console dengan dapat menggunakan fungsi write seperti
berikut:
>> document.write("Hi JS DOM");
Add elemets
// membuat element b
var bold = document.createElement(“b");
// mengisi kontent elemen
bold.textContent = "Hi JS DOM";
// menambahkan elemen ke dalam tag body
document.body.append(bold);
Document
HTML
head body
p p class = “p2”
My HTML Document
P Tag 1 P Tag 2
3.6.5 JS Events
Javascript memiliki events untuk menyediakan antarmuka
dinamis ke halaman web. Events ini terkait dengan elemen dalam
Document Object Model (DOM).
Event Penjelasan
59
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Contoh onclick
..
<body>
<button onclick="document.getElementById('get_time').in-
nerHTML=Date()">Click Me to get datetime()!</button>
<p id="get_time"></p>
..
3.6.6 JS Functions
JavaScript function adalah blok kode yang dirancang untuk
melakukan tugas tertentu dan dapat dijalankan ketika proses call
dilakukan.
Fungsi Fibonacci
..
<body>
<h2>JavaScript Functions</h2>
<script>
function fibonacci(f) {
var fib = [0, 1];
for(var i=fib.length; i<f; i++) {
fib[i] = fib[i-2] + fib[i-1];
}
return fib;
}
document.getElementById("id").innerHTML = fibonacci(5);
</script>
</body>
..
60
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Hasil keluaran
JavaScript Functions
Contoh Fungsi Fibonacci:
0,1,1,2,3
3.6.7 JS Callbacks
JS callbacks function adalah fungsi yang diteruskan ke fungsi lain
sebagai argumen, yang kemudian dipanggil untuk menyelesaikan
tindakan tertentu.
Berikut ini contoh dari callback.
function sapaan(nama) {
alert('Hello ' + nama);
}
function inputNama(callback) {
var nama = prompt('Masukkan nama Anda.');
callback(nama);
}
inputNama(sapaan);
61
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
..
<body>
<h2>JavaScript Callback</h2>
<h1 id="id"></h1>
<script>
setTimeout(myFunction, 2000);
function myFunction() {
document.getElementById("id").innerHTML = "I love Web Pro-
gramming !!";
}
</script>
</body>
..
62
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
..
63
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
..
<body>
<p id="id">Fetch/ Mengambil suatu file untuk mengubah teks
ini</p>
<script>
fetch (file)
.then(x => x.text())
.then(y => document.getElementById("id").innerHTML = y);
</script>
</body>
..
..
<body>
<p id="id">Fetch/ Mengambil suatu file untuk mengubah teks
ini</p>
<script>
getText("my_fetch.txt");
</body>
..
64
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
65
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
66
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
67
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
68
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
<script>
var val =
document.getElementsByClassName(“id");
console.log(val);
</script>
..
69
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
setInterval(function () {
val[0].style.color = "red";
val[1].style.color = "green";
val[2].style.color = "blue";
val[3].style.color = “orange";
setTimeout(function () {
val[0].style.color = "black";
val[1].style.color = "black";
val[2].style.color = "black";
val[3].style.color = "black";
}, 1000)
}, 2000);
70
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
BAB 4 State
(a)
(b) (c)
71
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
4.2 Cookie
Cookie adalah sebagian informasi terbatas (maks. 1024 byte)
atau file teks kecil yang dapat ditinggalkan situs web di hard disk
pengunjung melalui browser pengguna, untuk membantu melacak
user tersebut dari waktu ke waktu. Data cookie untuk mengingat dan
biasanya berisi sekumpulan informasi singkat tentang login agar user
tidak perlu mengisi data login berkali-kali (dapat login secara otomatis
tanpa mengisi kembali form login), lalu tentang informasi kapan
terakhir mengakses situs, informasi tentang halaman yang dikunjungi
dan lainnya. Data cookie dapat dimodifikasi dan dihapus, namun
Cookie kurang dapat diandalkan dai segi keamanan dibandingkan
dengan Session. Bagaimana untuk mengaktifkan PHP Cookie? PHP
menyediakan fungsi setcookie() untuk create, atau set suatu cookie.
Syntax setcookie(name, value, expiration, path, domain,
secure);
Ket. • name (Required), sebagai nama variable Cookie,
harus string.
• value (Optional/Opt.), nilai atau isi dari variable
Cookie
• expiration (Opt.)
• path (Opt.)
• domain (Opt.)
• secure (Opt.), jika di-set true atau 1, maka cookie
hanya akan support untuk koneksi HTTPS.
72
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Output Awal:
Maaf, cookie tidak ditemukan
Pada Output Awal, cookie belum di-set. Tetapi, ketika kemudian
halaman web pada browser di-refresh, maka cookie akan ter-
set.
Output setelah refresh browser:
Cookie value: Bro PHP
4.3 Session
Sessions adalah states yang disimpan ke server, seperti unique
ID, atau jika pengguna login ke akun mereka. Karena disimpan pada
server, maka Session adalah opsi yang lebih aman dari pada Cookie.
Misal pada aplikasi Facebook, saat pengguna login, aplikasi akan
mengingat siapa mereka hingga mereka log out. Setelah berhasil login,
pengguna memiliki akses ke fitur-fitur khusus seperti mengirim pesan,
mengunggah gambar dan video, bergabung dengan grup, dll. Aplikasi
melacak states tersebut dan menyimpannya sebagai session di server.
Ketika setelah pengguna log out, maka session dihancurkan. Berikut
adalah contoh sederhana start dan store data Session.
Syntax // start session
session_start();
1 <?php localhost/mysessions.php
2 session_start();
3 echo "Hello " . $_SESSION["username"];
4 ?>
1 <?php localhost/mymain.php
2 // start session
3 session_start();
4
73
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
74
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
1 <?php
localhost/mylogin.php
2 session_start();
3 $message="";
4 if(count($_POST)>0) {
5 $con =
6 mysqli_connect('127.0.0.1:3306','root','','admin') or
7 die('Unable To connect');
8 $result = mysqli_query($con,"SELECT * FROM
9 login_user WHERE user_name='" .
10 $_POST["user_name"] . "' and password = '".
11 $_POST["password"]."'");
12 $row = mysqli_fetch_array($result);
13 if(is_array($row)) {
75
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
. $_SESSION["id"] = $row['id'];
. $_SESSION["name"] = $row['name'];
. } else {
. $message = "Invalid Username or Password!";
. }
}
if(isset($_SESSION["id"])) {
header("Location:index.php");
}
?>
<html>
<head>
<title>User Login</title>
</head>
<body>
<form name="frmUser" method="post" action=""
align="center">
<div class="message"><?php if($message!="") { echo
$message; } ?></div>
<h3 align="center">Enter Login Details</h3>
Username:<br>
<input type="text" name="user_name">
<br>
Password:<br>
<input type="password" name="password">
<br><br>
<input type="submit" name="submit" value="Submit">
<input type="reset">
</form>
</body>
</html>
1 <?php
2 session_start(); localhost/index.php
3 ?>
4 <html>
5 <head>
6 <title>User Login</title>
7 </head>
8
9 <body>
10 <?php
11 if($_SESSION["name"]) {
12 ?>
13 Welcome <?php echo $_SESSION["name"]; ?>. Click
. here to <a href=“mylogout.php"
. title="Logout">Logout.
<?php
}else echo "<h1>Please login first .</h1>";
?>
76
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
</body>
</html>
1 <?php
localhost/mylogout.php
2 session_start();
3 unset($_SESSION["id"]);
4 unset($_SESSION["name"]);
5 header("Location:mylogin.php");
6 ?>
77
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Cookies Sessions
Berikan contoh dari study kasus dari suatu Web yang
menggambarkan terkait Cookies vs Sessions!
78
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
79
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
• index.php
• Otherfile.php
Server
• file.txt (read atau
write data)
80
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Output:
81
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
12 <head>
13 <title>Writing a file using PHP</title>
14 </head>
15 <body>
16 <?php
17 $filename = "newfile.txt";
18 $file = fopen( $filename, "r" );
19 if( $file == false ) {
20 echo ( "Error in opening file" );
21 exit();
22 }
23 $filesize = filesize( $filename );
24 $filetext = fread( $file, $filesize );
25
26 fclose( $file );
27
28 echo ( "File size : $filesize bytes" );
29 echo ( "$filetext" );
30 echo("file name: $filename");
31 ?>
32 </body>
33 </html>
Output:
82
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
83
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
15 );
16
17 ..
18
19 // function deletes the topmost output buffer
20 // and all of its contents without sending
21 // anything to the browser.
22 @ob_end_clean();
23
24 ..
25 $file_path = 'files/' . $_REQUEST['filename'];
26 output_file($file_path, '' . $_REQUEST['filename'] . '',
'');
27 ?>
84
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
85
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Output:
.
..
mkdir.txt
rmdir.txt
86
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
87
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Output:
Pemrograman Web dengan PHP
free, $0 /tahun
88
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Output:
Samsung S8
Iphone S7
MI4
90000
65000
15000
89
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Output:
Class A age is 80
Class B age is 50
Class C age is 20
90
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
91
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
92
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 12 Juli 2022 - 3 September 2022
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
# ---------------------------------------------------------------------------
# pada file flask_app.py atau app.py
# ---------------------------------------------------------------------------
import re
import string
import datetime
import joblib
from flask import send_file
from io import BytesIO
# import json
import os
# # untuk CronJob
# from apscheduler.schedulers.background import BackgroundScheduler
from flask_crontab import Crontab
# Ref. modifikasi:
# Big Thanks to,
# https://github.com/piinalpin/absent-qrcode-python
# ==============================================================
#
project_dir = os.path.dirname(os.path.abspath(__file__))
database_file = "sqlite:///{}".format(os.path.join(project_dir,
"static/qr_app/db/database.db"))
app.config["SQLALCHEMY_DATABASE_URI"] = database_file
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
# DB kedua untuk qr_app | misal sebagai sub app dari main app yang ada :D
db_qr = SQLAlchemy(app)
migrate = Migrate(app, db_qr)
93
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# ..
# .
import qrcode
qrcode_img = qrcode.make(student.id)
fname = f'static/img/tmp_qr/qr_code_{student.id}.png'.format(UUID)
buffer = BytesIO()
import os.path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
url_file_name_qrcode = os.path.join(BASE_DIR, fname)
qrcode_img.save(url_file_name_qrcode, format="PNG")
students = Student.getAll()
return render_template("qr_student.html", data=enumerate(students, 1))
# ..
# .
# ---------------------------------------------------------------------------
# pada folder ../static/ misal sebagai untuk disisipkan sub app, yaitu qr_app
# dengan mencoba menggunakan konsep MVC, cek pada susunan tree berikut
# ---------------------------------------------------------------------------
.
├── mysite
│ ├── data.db
│ ├── flask_app.py
│ ├── static
│ │ ├── css
│ │ │ ├── blue-dark.css
│ │ │ ├── font-awesome.min.css
│ │ │ .
│ │ │
│ │ ├── img
│ │ │ ├── conan.jpg
│ │ │ .
│ │ │
│ │ ├── js
│ │ │ ├── bootstrap.min.js
│ │ │ .
│ │ │
│ │ ├── qr_app
│ │ │ ├── templates
│ │ │ ├── __init__.py
│ │ │ ├── controller
│ │ │ │ └── AppController.py
│ │ │ ├── db MVC/MVT/etc
│ │ │ │ └── database.db
│ │ │ └── model
│ │ │ ├── AttendanceModel.py
│ │ │ └── StudentModel.py
│ │ ├── simpan_model_data
│ │ │ └── myModelReg.joblib.pkl
│ │ └── simpan_model_elm
│ │ ├── 16-08-2022-08-38-58--hd-6-fi-4-ft-1_bias.csv
│ │ ├── 16-08-2022-08-38-58--hd-6-fi-4-ft-1_bobot_input.csv
│ │ └── 16-08-2022-08-38-58--hd-6-fi-4-ft-1_bobot_output.csv
│ └── templates
│ ├── 404.html
│ ├── 500.html
│ ├── data_user.html
│ ├── extends
│ │ ├── base.html
│ │ └── base_no_frame.html
│ ├── form_add3.html
│ ├── include
│ │ ├── footer.html
94
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
│ │ ├── left_sidebar.html
│ │ ├── link.html
│ │ ├── preloader.html
│ │ ├── script.html
│ │ └── top_header.html
│ ├── index.html
│ ├── launchpad_menu3.html
│ ├── login.html
│ ├── qr_index.html
│ ├── qr_scan.html
│ ├── qr_scan2.html
│ ├── qr_student.html
│ ├── qrcode.html
│ ├── register.html
│ └── upload.html
├── requirements.txt
.
.
95
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
(a) (b)
Buatlah kode program Python (Flask/Django), PHP dan
ExpressJS (Node JS) untuk membuat sesuai dengan struktur
direktori di samping yang telah nampak terlihat jelas nama
folder dan file-nya!
4. Buatlah implementasi koding Python (Flask/Django), PHP dan
ExpressJS (Node JS) yang melibatkan minimal 6 komponen
OOP berikut, dengan kasus sesuai kreatifitas Anda.
❖ Class, Object, Inheritance, Polimorfisme, Overloading,
Overriding
❖ Abstraksi Data, Constructor, dan Destruktor
5. (a) Jelaskan konsep MVC/MVT dari 2 pendekatan berdasarkan
penyajian berikut, lalu (b) buatlah Web Student App
sederhana yang dilengkapi tabel untuk mengimplementasi
pola MVC/MVT from scratch dari class Mahasiswa dengan
Python (Flask/Django), PHP dan ExpressJS (Node JS)!
96
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Mahasiswa
- NIM
- Nama
- Email
+ simpan()
+ read()
+ update()
+ hapus()
(b)
97
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
98
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Core PHP atau Core Work PHP dibuat mandiri oleh pengembang
atau semacam koding from scratch, sedangkan framework PHP berupa
tools yang disediakan oleh individu atau suatu komunitas atau
perusahaan software yang sudah dalam bentuk package installer atau
semacamnya.
99
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Vs Vs
100
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
• Lalu ketikkan
$ mv -f pyIR/* mysite/
101
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
(a)
(b)
• Selesai :D
102
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
103
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
a. Builtin secara
default atau dapat
membuat secara
a. Install semacam Flask-
mandiri misal dengan
Appbuilder atau dapat
nama “djmyadmin”.
develop secara mandiri
dalam bentuk
b. Pastikan Anda
flaskmyadmin.
telah menonaktifkan
comment pada admin
Menu b. Mendeklarasikan
3 setting yang telah di
Admin dengan app = ..
install pada file
settings.py
c. flask fab create-admin
atau dengan mengakses
c. python
/flaskmyadmin misal untuk
manage.py
otomasi operasi crud
createuseradmin atau
setiap tabel yang dibuat
dengan akses
djmyadmin untuk
membuat user admin
Menggunakan
Menggunakan dekorator
konfigurasi pada
seperti berikut:
urls.py seperti
berikut: @app.route(“/mypage”)
decorator on Views to map
Views dan a route with a function.
from django.urls
Routes
import path
4 serta def @app.route(“/mypage”)
from .import views
Logic def method_mypage():
Handler # menuliskan kode untuk
urlpatterns = [
logika proses yang
path(’/mypage’,
dibutuhkan atau boleh
views.
juga dituliskan
method_mypage),
# urls lainnya dan def mypage():
method yang
104
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
dibutuhkan untuk
membangun logika
proses
]
105
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
106
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Lalu ekstrak misal pada Program Files & setting di Env. var.
> System var. > Path dari Control Panel.
https://getcomposer.org/download/
https://slproweb.com/products/Win32OpenSSL.html
(Install / Setup - OpenSSL), lalu set Path
Composer siap :D
107
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
❖ Install Laravel
Cara 1:
composer global require laravel/installer
laravel new web01
108
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Cara 2:
composer create-project --prefer-dist laravel/laravel web02
109
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
❖ Install Xampp
Sebaiknya menggunakan Xampp yang terbaru. Xampp ini nanti,
misal yang dipakai untuk di-start hanya sebagai DB yaitu mySQL
saja. Karena PHP sudah diinstall mandiri pada slide sebelumnya.
Anda juga sebenarnya dapat menggunakan full PHP & MySQL dari
Xampp.
Setting di Env. var. > System var. > Path pada Control Panel.
110
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
111
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
112
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
IP Public:88
IP Public:7000
cd laravel_project
wget https://raw.githubusercontent.com/imamcs19/Scrap-
ingNothers-toOneDataNothers/master/edubig-pyspark-big-
data-app/.env -O ./.env
docker-compose exec app php artisan config:clear
docker-compose exec app php artisan cache:clear
wget https://raw.githubusercontent.com/imamcs19/Scrap-
ingNothers-toOneDataNothers/master/edubig-pyspark-big-
data-app/AppServiceProvider.php -O ./app/Provid-
ers/AppServiceProvider.php
docker-compose exec app php artisan migrate
113
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
6.3.2 Routing
Routing secara mendasar dapat menerima URI dan closure,
yang menyediakan metode sederhana untuk menentukan rute dan
perilaku aplikasi yaitu dari apa saja yang seharusnya akan dijalankan
pada halaman tersebut tanpa perlu konfigurasi rumit, di mana rute
tersebut akan mengarahkan ke final goal state, yaitu class controller
apa, function-nya apa dan method-nya apa yang akan dijalankan.
Uniform Resource Identifier (URI) menyediakan cara sederhana
untuk mengidentifikasi suatu resource pada aplikasi Web, yaitu hanya
menyediakan Identifier (tanda pengenal bisa berupa nomor seri, URL
atau berupa nama dengan string tertentu), tetapi cara untuk
mengaksesnya tidak menjamin langsung dapat diakses (tersirat),
artinya jika langsung bisa diakses maka URI tersebut dapat disebut
dengan Uniform Resource Locator (URL). Di mana setiap URL pasti
termasuk URI, tetapi tidak sebaliknya. Contoh secara umum, jika Anda
melihat http(s)://, itu adalah URL.
Sedangkan closure adalah anonymous function yang sering
digunakan sebagai metode callback, yaitu dapat digunakan sebagai
parameter atau argumen dalam suatu fungsi lain. Contoh sederhana
Routing, (Edit 1 => Routing basic, Edit 2 => Routing parameters):
Route::get(‘/hai', function () {
return ‘Hai’;
});
114
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
localhost:port/hai Hai
localhost:port/hai/Php Hai Php
115
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Route::get(‘/run', function () {
echo ‘<form method=“POST” action=“run”>’;
echo ‘<input type=“submit”>’;
echo ‘</form>’;
});
localhost:port/run
ini POST
Route::get(‘/run', function () {
echo ‘<form method=“POST” action=“run”>’;
echo ‘<input type=“submit”>’;
echo ‘<input type=“hidden” value=“PUT”
name=“_method”>’;
echo ‘</form>’;
});
localhost:port/run
ini PUT
❖ Rounting Parameters
Route::get(‘/test/{var}', function ($var) { });
Route::get(‘/test/{var?}’, function ($var = ‘var’) {
});
❖ Secure Routes
Route::get(‘/test’, array (’https’, function () { }));
116
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
❖ Route Contraints
Route::get(‘/test/{var1}’, function ($var1) { })
-> where (‘var1’, ‘[0-9]+’);
❖ Named Routes
Route::currentRouteName() ;
Route::get(‘/test/var’, array (’as’ => ‘testvar’,
function () { }));
❖ Sub-Domain Routing
Route::group(array (‘domain’ => ‘{sub}.site.id’),
function () { });
117
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
118
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
6.3.3 Artisan
Artisan merupakan tool yang dapat dijalankan dari Command
Line Interface (CLI).
Beberapa contoh perintah artisan:
//untuk start Laravel server, pada slide ke-9, kita sudah
mencoba jalankan
php artisan serve
119
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
6.3.4 Model
Model adalah class yang digunakan untuk mengakses DB,
sesuai dengan setting DB yang ada pada file .env dan berikut preview
filenya.
Contoh perintah artisan make:model ..:
//untuk membuat model baru yang berhubungan dengan mana-
jemen data
//dengan artisan
php artisan make:model Mahasiswa
120
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Keterangan:
• namespace digunakan untuk menangani crash ketika ada kelas
dengan nama yg sama tetapi lokasinya berbeda.
• use sebagai media memangil class bawaan Laravel yang
berlokasi pada Illuminate\..\Eloquent\.. sebagai fasilitas untuk
class yang baru diciptakan, misal extends atau lainnya.
Cara menjalankan model Mahasiswa yang baru dibuat, misal
untuk search pada tabel mahasiswa dengan nim 2021010001
Route::get(‘mahasiswa', function () {
$mhs = App\Mahasiswa::find(2021010001);
echo ‘<pre>’;
print_r ($mhs);
});
121
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
6.3.5 Relationships
Relationships untuk memanage cara interaksi dari hubungan
atau relasi antar tabel. Contoh relasi antara tabel Mahasiswa dengan
tabel Keminatan (Stream).
122
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
});
Route::get(‘keminatan/{kode_stream}', func-
tion ($kode_stream) {
$keminatan = app\Models\Keminatan::find($kode_stream);
echo '<pre>’;
echo $keminatan->nama_stream.’<br/>’;
echo ’diminati oleh mahasiswa berikut:’;
echo ’<ul>’;
$mahasiswa = $keminatan->mahasiswa;
foreach ($mahasiswa as $mhs){
echo ’<li>’. $mhs->nama.’</li>’;
}
echo ’</ul>’;
});
123
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
6.3.6 Views
Views untuk memanage cara menampilkan suatu halaman
project. Contoh, dalam file web.php ditambahkan script berikut.
Route::get(‘testRoute', function () {
echo ’<html><head><title>Test
Routing</title></head><body>’;
echo ’Laravel test Routing sederhana’;
echo ’</body></html>’;
});
<html>
<head>
<title>Test Routing</title>
</head>
<body>
<h1> Laravel test Routing sederhana </h1>
<p><?php echo $data1 ?></p>
<p><?php echo $data2 ?></p>
</body>
</html>
124
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
6.3.7 Blade
Blade adalah cara Laravel dalam menyederhanakan dalam
penulisan script, misal “<?php echo $data1 ?>” cukup ditulis menjadi
“{{ $data1 }}” dll. Contoh pada dalam file web.php ditambahkan script
berikut.
Route::get(‘testRoute', function () {
$var = array(
‘data1’ => ‘Framework’
‘data2’ => ‘Laravel’
);
return view(‘testRoute’,$var);
});
<html>
<head>
<title>Test Routing Dgn View Blade</title>
</head>
<body>
<h1> Laravel test Routing sederhana </h1>
<p>{{ $data1 }}</p>
<p>{{ $data2 }}</p>
</body>
</html>
125
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
<html>
<head>
<title> Test Routing Dgn View Blade </title>
</head>
<body>
<h1> Laravel test Routing sederhana </h1>
<p><?php echo $data1 ?></p>
<p><?php echo $data2 ?></p>
<?php if($data2==‘Laravel’): ?>
<?php echo ‘Laravel created by Taylor Otwell’ ?>
<?php endif; ?>
</body>
</html>
<html>
<head>
<title> Test Routing Dgn View Blade </title>
</head>
<body>
<h1> Laravel test Routing sederhana </h1>
<p><?php echo $data1 ?></p>
<p><?php echo $data2 ?></p>
<?php if($data2==‘Laravel’): ?>
<?php echo ‘Laravel created by Taylor Otwell’ ?>
<?php endif; ?>
</body>
</html>
126
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
..
<p><?php echo $data2 ?></p>
<ul>
<?php foreach ($mahasiswa as $mhs): ?>
<?php echo ‘<li>’.$mhs->nama.‘</li>’ ?>
<?php endforeach ?>
</ul>
..
testRoute.php
..
<p><?php echo $data2 ?></p>
<ul>
@foreach ($mahasiswa as $mhs)
<li>{{$mhs->nama}}</li>
@endforeach
</ul>
..
testRoute.blade.php
Note: jika terjadi error pada view, coba bersihkan cache view Laravel
dengan peritah “php artisan view:clear”
127
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
6.3.8 Controller
Controller adalah logika kondisi berupa detail proses bisnis /flow
dari aplikasi atau situs web yang dapat diterapkan pada route. Di mana
dengan Controller, maka penempatan setiap script kode akan
diletakkan atau dipindahkan serta dirapikan sesuai dengan detail
spesifikasi to-do nya atau fungsinya.
Contoh pada route keminatan
// menjalankan Controller KeminatanController pada fungsi
Keminatan.
Route::get(‘keminatan/{kode_stream}’, ’KeminatanControl-
ler@Keminatan’);
128
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
129
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
130
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Install nodeJS
131
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
132
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Route::get('rolekhususmhs', function(){
echo 'Halaman ini rolenya khusus utk mahasiswa';
});
Lalu cara untuk men-define level tiap spesifikasi role, misal ada
role mahasiswa, role dosen dll untuk tiap halaman aplikasi, dapat
dengan perintah artisan, misal “php artisan make:middleware
MhsMiddleware”, maka Laravel akan membuatkan file
MhsMiddleware.php pada directory app/Http/Middleware/
Request, Cross-Site Request Forgery (CSRF) digunakan untuk
secure data inputan yang dimasukkan pada suatu form request
berbasis token yang diproses oleh server untuk menangkal serangan
dengan jenis CSRF. Di mana token ini sebagai indetifier ID bahwa form
yang diproses merupakan bagian dari file kode yang ada di sistem.
Contoh menggunakan CSRF:
Use Illuminate\Http\Request;
Route::group([‘middleware’ => ‘web’], function () {
Route::get(‘myform', function () {
return view(‘myform’);
});
Route::post(‘tujuan_myform', function (Request $re-
quest) {
echo $request->input(‘myname’);
echo “<p>”;
});
});
133
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
134
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
135
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
136
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
137
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
138
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
139
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
140
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 7 Juni 2018
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
class myGA():
def dec2bin(x):
return bin(x)[2:] # x int, return as a string
def bin2dec(x):
return int(x, 2) # x string, return as a int
def MyFx(x):
return ((-np.math.pow(x, 2)) + (14 * x)) - 13;
def OneCutPointCrossover(x):
size=np.shape(x)
Pop_Size = int(size[0])
StringLenChromosome = int(size[1])
hasil= np.empty((2,StringLenChromosome)) # inisialisasi
hasilcek= np.empty((2,StringLenChromosome)) # inisialisasi
# berupa array[1x1]
PosisiOneCutPoint_init = myGA.myrandint(mbaris,nkolom,lower,upper)
# copy array
P1=x[IndexP1]
#print(P1)
hasil[0]=x[IndexP1]
hasil=hasil.astype(int)
#print(hasil[0])
hasilcek[0]=x[IndexP1]
hasilcek=hasilcek.astype(int)
#print(hasilcek[0])
P2=x[IndexP2]
#print(P2)
hasil[1]=x[IndexP2]
#print(hasil[1])
hasilcek[1]=x[IndexP2]
141
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
#print(hasilcek[1])
return hasil,hasilcek
def RandomMutasi(x):
size=np.shape(x)
Pop_Size = int(size[0])
StringLenChromosome = int(size[1])
hasil= np.empty((1,StringLenChromosome)) # inisialisasi
# copy array
P1=x[IndexP1]
#print(P1)
hasil=x[IndexP1]
hasil=hasil.astype(int)
#print(hasil)
print(hasil)
return hasil
# shows a list of all todos, and lets you POST to add new tasks
class TodoGApp(Resource):
def get(self):
return TODOS
def post(self):
args = parser.parse_args()
''' args = '{'task': '2,4,0.4,0.6'}' '''
print(".")
print("..")
print("POST Awal dari Web PHP ke WebApp RESTful Api Python:")
print(args)
myvinit = str(args)
print(".")
print("Hasil Ekstrasi POST Awal Web PHP ke WebApp RESTful Api Python:")
print(myvinit[10:len(myvinit)-2])
'''print(args.partition(','))'''
''' print(args.keys().lstrip('{')) '''
todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
todo_id = 'todo%i' % todo_id
myv = myvinit[10:len(myvinit)-2]
itermax,popsize,cr,mr = myv.split(',')
142
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# ..
NilaiDec = myGA.bin2dec(HasilBiner)
print("Hasil Biner2Dec ("+HasilBiner+")= "+str(NilaiDec))
vfinal=vfinal+"^Hasil Biner2Dec ("+HasilBiner+")= "+str(NilaiDec)
print("")
print("1. generate individu")
## 1. generate individu
## random code biner
batasbawahrandd = 0
batasatasrandd = 1
individu = myGA.myrandint(..)
# indek ii=[lowerloop,upperloop]
lowerloop=0 # nilai awal untuk index ii
upperloop=Pop_Size
for ii in range(lowerloop, upperloop):
tempind1 = ''.join(str(individu[ii])) # hasil seperti '[1 0 1 1]'
tempind2 = ''.join(map(str,individu[ii])) # hasil seperti '1011'
# atau = ''.join(map(str,individu[ii,:]))
xtemp =myGA.bin2dec(tempind2)
#..
print()
print("2. Reproduksi (Crossover dan Mutasi)")
## // 2. Reproduksi
# // start proses crossover
print("2.1 Crossover")
# // hitung jumlah offspring atau anak crossover
byk_anak_crossover = int(np.ceil(cr_ * Pop_Size))
print("Banyaknya offspring crossover= "+str(byk_anak_crossover))
HasilCrossover = np.empty((byk_anak_crossover,StringLenChromosome))
# inisialisasi
HasilCrossovercek =
np.empty((byk_anak_crossover,StringLenChromosome)) # inisialisasi
HasilCrossoverTemp = np.empty((2,StringLenChromosome))
HasilCrossoverTempcek = np.empty((2,StringLenChromosome))
HasilCrossover=HasilCrossover.astype(int)
HasilCrossovercek=HasilCrossovercek.astype(int)
loop_anak_crossover = 0
# // membuat offspring crossover sebanyak byk_anak_crossover
for i in range(0,n_crossover):
# //menampung hasil OneCutPointCrossover
143
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
HasilCrossoverTemp,HasilCrossoverTempcek=\
myGA.OneCutPointCrossover(individu)
HasilCrossover[loop_anak_crossover]=HasilCrossoverTemp[0]
HasilCrossovercek[loop_anak_crossover]=HasilCrossoverTempcek[0]
#print("Cek:")
#print(HasilCrossoverTemp)
#print(HasilCrossoverTempcek)
#print(HasilCrossover)
#print(HasilCrossovercek)
loop_anak_crossover = loop_anak_crossover + 1
HasilCrossover[loop_anak_crossover]=HasilCrossoverTemp[1]
HasilCrossovercek[loop_anak_crossover]=HasilCrossoverTempcek[1]
loop_anak_crossover = loop_anak_crossover + 1
HasilMutasi = np.empty((byk_anak_mutasi,StringLenChromosome))
HasilMutasiTemp = np.empty((1,StringLenChromosome))
HasilMutasi=HasilMutasi.astype(int)
IndividuGabungan[0:Pop_Size,:]=individu
IndividuGabungan[Pop_Size:Pop_Size + byk_anak_crossover,:]=\
HasilCrossover
IndividuGabungan[Pop_Size + byk_anak_crossover:\
Pop_Size_induk_dan_anak,:]=HasilMutasi
indicesort=fxIndividuGabungan.ravel().argsort()
for i in range(Pop_Size_induk_dan_anak-1, -1, -1):
#print(str(i)+' '+str(Pop_Size_induk_dan_anak-1-i))
IndividuGabunganSort[i]=\
IndividuGabungan[indicesort[Pop_Size_induk_dan_anak-1-i]]
#print(indicesort[i])
vfinalparam=""
#print(itermax)
144
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
for i in range(1,int(itermax)+1):
# print (i)
if i == int(itermax):
vfinalparam=vfinalparam+str(i)
else:
vfinalparam=vfinalparam+str(i)+"^"
print("")
print(".")
print("Done..! :D")
print("=============================================================")
print(".")
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 2 Mei - 1 Juni 2023
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
import math
import time
import torch
from tqdm import tqdm
import numpy as np
import warnings
warnings.filterwarnings("ignore")
145
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
def objective_function_torch(x):
if x.dim() == 1:
x = x.unsqueeze(0)
dim = x.size(dim=-1)
return hasil
def objective_function_torch_to_sub_7_1(x):
if x.dim() == 1:
x = x.unsqueeze(0)
dim = x.size(dim=-1)
min_bounds_isi_bebas_to_sub_7_1 = 0
max_bounds_isi_bebas_to_sub_7_1 = 200
146
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# ------ start | additional part 0, by Imam CS => repair positions agar dalam
interval init_min_x, init_max_x -----------------------------------
# %% Batas Bawah dan Batas Atas Parameter yang dioptimasi, untuk V ||
velocity
prosentase_V = 0.6
V_SLCcLR_lower = -prosentase_V*init_max_x
V_SLCcLR_upper = prosentase_V*init_max_x
# ------ end | additional part 0, by Imam CS => repair positions agar dalam
interval init_min_x, init_max_x -----------------------------------
curr_iter = 0
pbar = tqdm(total=max_iter)
while curr_iter < max_iter:
# First calculate fitnesses
fitnesses = f(positions)
# print(best_pos, best_val)
# Velocity equation
r1 = torch.rand(size=(n, dim), dtype=torch.float, device=device)
# r1 => random coeff 1 vector
inertia = velocities * w
cognitive = r1 * c1 * (personal_best_pos - positions)
social = r2 * c2 * (best_pos - positions)
147
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
curr_iter += 1
pbar.update(1)
curr_iter = 0
pbar = tqdm(total=max_iter)
while curr_iter < max_iter:
# First calculate fitnesses
fitnesses = f(positions)
# print(best_pos, best_val)
# Velocity equation
r1 = torch.rand(size=(n, dim), dtype=torch.float, device=device)
# r1 => random coeff 1 vector
inertia = velocities * w
cognitive = r1 * c1 * (personal_best_pos - positions)
social = r2 * c2 * (best_pos - positions)
curr_iter += 1
pbar.update(1)
# hyper parameters
w = 0.729 # inertia
c1 = 1.49445 # cognitive (particle)
c2 = 1.49445 # social (swarm)
148
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
print("##### Custom Obj Func dgn PSO-GPU feat Pytorch | f(x) = -x^2 + 14x - 13
#####")
print()
num_dimensions = len(bounds_to_sub_7_1[0])
# print('num_dimensions = ', num_dimensions)
print()
# print('val_best = ', val_best)
# print('pos_best = ', pos_best)
best_position = mydenorm_torch_v2(best_position, \
min_bounds_isi_bebas_to_sub_7_1, max_bounds_isi_bebas_to_sub_7_1, \
bounds_to_sub_7_1, set_device)
print()
print("##### Custom Obj Func dgn myPSO-GPU feat Pytorch | dgn denorm #####")
print("1000 iter; 1000 particles; 7 dim")
149
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
max_iterations = 1000
num_dimensions = len(bounds[0])
# print('num_dimensions = ', num_dimensions)
print()
# print('val_best = ', val_best)
# print('pos_best = ', pos_best)
param_1 = int(param_1)
param_2 = int(param_2)
param_3 = int(param_3)
param_4 = int(param_4)
param_5 = int(param_5)
param_6 = int(param_6)
Output:
Downloading...
From: https://drive.google.com/uc?id=1eJX6-5fwI--dU1hYQOUYeWgWYKCjNOXl
To: /content/drive/My Drive/#Penelitian&Pengmas 2021/Publikasi GreenTech
2021/Koding LSTM utk Manualisasi/KataBijak_new.txt
100% 133/133 [00:00<00:00, 61.5kB/s]
150
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Hasil Ekstrasi POST Awal dari Web PHP/ atau lainnya ke WebApp RESTful Api Py-
thon:
b'{"max_iter":100,"pop_size":80,"cr":0.8,"mr":0.6}'
.
..
====================================================================
Start Solving Case : Max, y = f(x) = -x^2 + 14x – 13, 0 ≤ x ≤ 15 :
====================================================================
Hasil Biner= 1111
StringLen Chromosome= 4
Hasil Biner2Dec (1111)= 15
1. generate individu
Chromosome | x | y=f(x)
================================================
P1: [0 0 1 1] | 3 | 20.0
P2: [0 0 0 1] | 1 | 0.0
P3: [1 0 0 1] | 9 | 32.0
P4: [1 1 0 1] | 13 | 0.0
P5: [0 0 0 0] | 0 | -13.0
P6: [0 0 1 0] | 2 | 11.0
P7: [1 1 1 1] | 15 | -28.0
P8: [1 1 0 0] | 12 | 11.0
P9: [0 1 1 1] | 7 | 36.0
P10: [0 0 1 0] | 2 | 11.0
P11: [0 0 1 0] | 2 | 11.0
P12: [0 1 1 0] | 6 | 35.0
P13: [1 0 1 1] | 11 | 20.0
P14: [1 1 1 1] | 15 | -28.0
P15: [0 0 0 1] | 1 | 0.0
P16: [0 0 0 1] | 1 | 0.0
P17: [0 1 1 1] | 7 | 36.0
P18: [0 0 0 1] | 1 | 0.0
P19: [1 0 0 1] | 9 | 32.0
P20: [1 1 1 1] | 15 | -28.0
P21: [1 1 0 1] | 13 | 0.0
P22: [1 0 0 0] | 8 | 35.0
P23: [0 0 1 1] | 3 | 20.0
P24: [0 1 0 0] | 4 | 27.0
P25: [1 0 0 1] | 9 | 32.0
P26: [0 1 1 1] | 7 | 36.0
P27: [0 0 0 1] | 1 | 0.0
P28: [1 0 0 0] | 8 | 35.0
P29: [1 1 1 0] | 14 | -13.0
P30: [0 1 0 1] | 5 | 32.0
P31: [0 1 0 1] | 5 | 32.0
P32: [0 1 1 1] | 7 | 36.0
P33: [1 1 1 1] | 15 | -28.0
P34: [1 1 1 0] | 14 | -13.0
P35: [1 0 1 0] | 10 | 27.0
P36: [1 0 0 0] | 8 | 35.0
P37: [1 1 0 1] | 13 | 0.0
P38: [0 0 1 0] | 2 | 11.0
P39: [1 0 0 1] | 9 | 32.0
P40: [0 0 1 1] | 3 | 20.0
P41: [1 0 1 0] | 10 | 27.0
P42: [1 0 1 1] | 11 | 20.0
P43: [1 1 0 1] | 13 | 0.0
P44: [1 1 1 1] | 15 | -28.0
P45: [1 0 0 1] | 9 | 32.0
P46: [0 1 1 1] | 7 | 36.0
P47: [0 1 1 0] | 6 | 35.0
P48: [1 0 1 0] | 10 | 27.0
P49: [0 1 1 1] | 7 | 36.0
P50: [1 0 1 0] | 10 | 27.0
P51: [1 1 1 0] | 14 | -13.0
P52: [1 1 1 1] | 15 | -28.0
P53: [0 0 0 0] | 0 | -13.0
P54: [0 0 1 0] | 2 | 11.0
P55: [0 0 0 1] | 1 | 0.0
P56: [1 1 1 0] | 14 | -13.0
P57: [1 1 1 0] | 14 | -13.0
P58: [1 1 1 0] | 14 | -13.0
P59: [0 0 1 1] | 3 | 20.0
P60: [1 0 0 0] | 8 | 35.0
P61: [0 0 0 1] | 1 | 0.0
P62: [0 0 1 0] | 2 | 11.0
P63: [1 0 0 1] | 9 | 32.0
P64: [0 0 1 0] | 2 | 11.0
P65: [0 1 1 1] | 7 | 36.0
P66: [0 0 0 1] | 1 | 0.0
151
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
P67: [1 1 1 0] | 14 | -13.0
P68: [0 1 1 1] | 7 | 36.0
P69: [1 1 0 0] | 12 | 11.0
P70: [1 1 1 0] | 14 | -13.0
P71: [1 1 1 1] | 15 | -28.0
P72: [0 1 0 0] | 4 | 27.0
P73: [1 0 1 1] | 11 | 20.0
P74: [1 1 1 1] | 15 | -28.0
P75: [0 1 1 0] | 6 | 35.0
P76: [0 1 1 0] | 6 | 35.0
P77: [0 1 0 0] | 4 | 27.0
P78: [0 0 0 0] | 0 | -13.0
P79: [0 0 0 0] | 0 | -13.0
P80: [0 0 1 1] | 3 | 20.0
.
Done..! :D
=============================================================
.
[05/Jul/2018 00:37:04] "POST /ga HTTP/1.1" 200 43
Performing system checks...
1. generate individu
Chromosome | x | y=f(x)
================================================
P1: [1 0 0 1] | 9 | 32.0
P2: [1 0 0 1] | 9 | 32.0
P3: [0 0 1 0] | 2 | 11.0
P4: [0 1 1 0] | 6 | 35.0
P5: [0 0 0 0] | 0 | -13.0
P6: [1 0 1 0] | 10 | 27.0
P7: [1 0 1 1] | 11 | 20.0
P8: [0 0 0 1] | 1 | 0.0
P9: [1 1 0 1] | 13 | 0.0
P10: [1 0 1 1] | 11 | 20.0
P11: [1 0 0 0] | 8 | 35.0
P12: [0 0 0 0] | 0 | -13.0
P13: [0 1 1 0] | 6 | 35.0
P14: [1 0 0 1] | 9 | 32.0
P15: [0 1 1 1] | 7 | 36.0
P16: [1 1 0 1] | 13 | 0.0
P17: [0 1 0 1] | 5 | 32.0
P18: [0 0 0 0] | 0 | -13.0
P19: [1 1 1 1] | 15 | -28.0
P20: [0 1 0 1] | 5 | 32.0
P21: [0 0 1 0] | 2 | 11.0
P22: [1 0 1 1] | 11 | 20.0
P23: [1 0 1 0] | 10 | 27.0
P24: [0 0 0 0] | 0 | -13.0
P25: [1 1 0 0] | 12 | 11.0
P26: [1 1 1 0] | 14 | -13.0
P27: [1 1 0 0] | 12 | 11.0
P28: [0 1 0 0] | 4 | 27.0
P29: [0 1 1 1] | 7 | 36.0
P30: [0 0 0 1] | 1 | 0.0
P31: [1 0 1 0] | 10 | 27.0
P32: [1 1 0 1] | 13 | 0.0
P33: [0 1 1 0] | 6 | 35.0
P34: [1 0 1 0] | 10 | 27.0
152
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
P35: [1 1 1 1] | 15 | -28.0
P36: [1 1 0 1] | 13 | 0.0
P37: [0 1 1 0] | 6 | 35.0
P38: [1 0 1 1] | 11 | 20.0
P39: [0 0 1 0] | 2 | 11.0
P40: [0 1 1 1] | 7 | 36.0
P41: [0 0 0 0] | 0 | -13.0
P42: [0 0 0 0] | 0 | -13.0
P43: [1 1 1 1] | 15 | -28.0
P44: [1 0 0 1] | 9 | 32.0
P45: [1 0 0 1] | 9 | 32.0
P46: [1 1 0 1] | 13 | 0.0
P47: [1 1 1 0] | 14 | -13.0
P48: [1 0 0 0] | 8 | 35.0
P49: [0 1 0 0] | 4 | 27.0
P50: [1 1 1 0] | 14 | -13.0
P51: [0 1 0 0] | 4 | 27.0
P52: [0 1 0 0] | 4 | 27.0
P53: [1 0 0 0] | 8 | 35.0
P54: [0 1 0 0] | 4 | 27.0
P55: [0 0 1 0] | 2 | 11.0
P56: [0 0 1 0] | 2 | 11.0
P57: [0 0 0 1] | 1 | 0.0
P58: [0 0 0 1] | 1 | 0.0
P59: [1 0 1 0] | 10 | 27.0
P60: [0 1 1 1] | 7 | 36.0
P61: [1 0 1 0] | 10 | 27.0
P62: [1 0 0 1] | 9 | 32.0
P63: [0 1 0 1] | 5 | 32.0
P64: [0 0 1 0] | 2 | 11.0
P65: [1 0 1 1] | 11 | 20.0
P66: [0 0 0 1] | 1 | 0.0
P67: [1 0 0 0] | 8 | 35.0
P68: [0 0 1 1] | 3 | 20.0
P69: [0 1 0 1] | 5 | 32.0
P70: [0 1 0 0] | 4 | 27.0
P71: [1 1 1 1] | 15 | -28.0
P72: [0 0 0 1] | 1 | 0.0
P73: [1 0 0 0] | 8 | 35.0
P74: [1 0 1 0] | 10 | 27.0
P75: [1 0 1 1] | 11 | 20.0
P76: [0 0 0 0] | 0 | -13.0
P77: [1 0 0 1] | 9 | 32.0
P78: [1 0 1 1] | 11 | 20.0
P79: [1 0 0 0] | 8 | 35.0
P80: [1 1 1 1] | 15 | -28.0
P2=
[1 1 0 0]
PosisiOneCutPoint= 2
Index P1 = 25, Index P2 = 79
P1=
[1 1 0 0]
P2=
[1 0 0 0]
PosisiOneCutPoint= 3
Index P1 = 40, Index P2 = 56
P1=
[0 1 1 1]
P2=
[0 0 1 0]
PosisiOneCutPoint= 1
Index P1 = 39, Index P2 = 64
P1=
[0 0 1 0]
P2=
[0 0 1 0]
PosisiOneCutPoint= 1
Index P1 = 77, Index P2 = 14
153
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
P1=
[1 0 0 1]
P2=
[1 0 0 1]
PosisiOneCutPoint= 2
Index P1 = 24, Index P2 = 16
P1=
[0 0 0 0]
P2=
[1 1 0 1]
PosisiOneCutPoint= 2
Index P1 = 56, Index P2 = 22
P1=
[0 0 1 0]
P2=
[1 0 1 1]
PosisiOneCutPoint= 3
Index P1 = 7, Index P2 = 2
P1=
[1 0 1 1]
P2=
[1 0 0 1]
PosisiOneCutPoint= 2
Index P1 = 70, Index P2 = 2
P1=
[0 1 0 0]
P2=
[1 0 0 1]
PosisiOneCutPoint= 1
Index P1 = 49, Index P2 = 2
P1=
[0 1 0 0]
P2=
[1 0 0 1]
PosisiOneCutPoint= 1
Index P1 = 52, Index P2 = 26
P1=
[0 1 0 0]
P2=
[1 1 1 0]
PosisiOneCutPoint= 2
Index P1 = 55, Index P2 = 35
P1=
[0 0 1 0]
P2=
[1 1 1 1]
PosisiOneCutPoint= 3
Index P1 = 11, Index P2 = 53
P1=
[1 0 0 0]
P2=
[1 0 0 0]
PosisiOneCutPoint= 3
Index P1 = 42, Index P2 = 52
P1=
[0 0 0 0]
P2=
[0 1 0 0]
PosisiOneCutPoint= 2
Index P1 = 62, Index P2 = 42
P1=
[1 0 0 1]
P2=
[0 0 0 0]
PosisiOneCutPoint= 1
Index P1 = 46, Index P2 = 11
P1=
[1 1 0 1]
P2=
154
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
[1 0 0 0]
PosisiOneCutPoint= 2
Index P1 = 29, Index P2 = 7
P1=
[0 1 1 1]
P2=
[1 0 1 1]
PosisiOneCutPoint= 2
Index P1 = 73, Index P2 = 29
P1=
[1 0 0 0]
P2=
[0 1 1 1]
PosisiOneCutPoint= 2
Index P1 = 45, Index P2 = 30
P1=
[1 0 0 1]
P2=
[0 0 0 1]
PosisiOneCutPoint= 3
Index P1 = 68, Index P2 = 64
P1=
[0 0 1 1]
P2=
[0 0 1 0]
PosisiOneCutPoint= 3
Index P1 = 36, Index P2 = 13
P1=
[1 1 0 1]
P2=
[0 1 1 0]
PosisiOneCutPoint= 1
Index P1 = 35, Index P2 = 48
P1=
[1 1 1 1]
P2=
[1 0 0 0]
PosisiOneCutPoint= 2
Index P1 = 39, Index P2 = 13
P1=
[0 0 1 0]
P2=
[0 1 1 0]
PosisiOneCutPoint= 1
Index P1 = 19, Index P2 = 57
P1=
[1 1 1 1]
P2=
[0 0 0 1]
PosisiOneCutPoint= 1
Index P1 = 54, Index P2 = 37
P1=
[0 1 0 0]
P2=
[0 1 1 0]
PosisiOneCutPoint= 2
Index P1 = 47, Index P2 = 62
P1=
[1 1 1 0]
P2=
[1 0 0 1]
PosisiOneCutPoint= 2
Index P1 = 33, Index P2 = 30
P1=
[0 1 1 0]
P2=
[0 0 0 1]
PosisiOneCutPoint= 2
Index P1 = 16, Index P2 = 68
P1=
155
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
[1 1 0 1]
P2=
[0 0 1 1]
PosisiOneCutPoint= 1
Index P1 = 65, Index P2 = 60
P1=
[1 0 1 1]
P2=
[0 1 1 1]
PosisiOneCutPoint= 3
Index P1 = 60, Index P2 = 46
P1=
[0 1 1 1]
P2=
[1 1 0 1]
PosisiOneCutPoint= 3
Index P1 = 31, Index P2 = 68
P1=
[1 0 1 0]
P2=
[0 0 1 1]
PosisiOneCutPoint= 3
Index P1 = 13, Index P2 = 57
P1=
[0 1 1 0]
P2=
[0 0 0 1]
156
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
C48: [0 1 1 1] | 7 | 36.0
C49: [0 1 1 0] | 6 | 35.0
C50: [0 1 0 0] | 4 | 27.0
C51: [1 1 0 1] | 13 | 0.0
C52: [1 0 1 0] | 10 | 27.0
C53: [0 1 0 1] | 5 | 32.0
C54: [0 0 1 0] | 2 | 11.0
C55: [1 1 1 1] | 15 | -28.0
C56: [0 0 0 1] | 1 | 0.0
C57: [1 1 1 1] | 15 | -28.0
C58: [0 0 1 1] | 3 | 20.0
C59: [0 1 1 1] | 7 | 36.0
C60: [1 1 0 1] | 13 | 0.0
C61: [1 0 1 1] | 11 | 20.0
C62: [0 0 1 0] | 2 | 11.0
C63: [0 1 1 1] | 7 | 36.0
C64: [0 0 0 0] | 0 | -13.0
2.2 Mutasi
Banyaknya offspring mutasi= 48
Proses mutasi dilakukan sebanyak = 48
PosisiPointRandom= 3
Index P1 = 5
P1=
[0 0 0 0]
[0 0 1 0]
PosisiPointRandom= 2
Index P1 = 23
P1=
[1 0 1 0]
[1 1 1 0]
PosisiPointRandom= 3
Index P1 = 68
P1=
[0 0 1 1]
[0 0 0 1]
PosisiPointRandom= 2
Index P1 = 77
P1=
[1 0 0 1]
[1 1 0 1]
PosisiPointRandom= 3
Index P1 = 9
P1=
[1 1 0 1]
[1 1 1 1]
PosisiPointRandom= 1
Index P1 = 63
P1=
[0 1 0 1]
[1 1 0 1]
PosisiPointRandom= 2
Index P1 = 61
P1=
[1 0 1 0]
[1 1 1 0]
PosisiPointRandom= 3
Index P1 = 65
P1=
[1 0 1 1]
[1 0 0 1]
PosisiPointRandom= 3
Index P1 = 75
P1=
157
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
[1 0 1 1]
[1 0 0 1]
PosisiPointRandom= 3
Index P1 = 10
P1=
[1 0 1 1]
[1 0 0 1]
PosisiPointRandom= 1
Index P1 = 32
P1=
[1 1 0 1]
[0 1 0 1]
PosisiPointRandom= 3
Index P1 = 11
P1=
[1 0 0 0]
[1 0 1 0]
PosisiPointRandom= 3
Index P1 = 5
P1=
[0 0 0 0]
[0 0 1 0]
PosisiPointRandom= 3
Index P1 = 28
P1=
[0 1 0 0]
[0 1 1 0]
PosisiPointRandom= 2
Index P1 = 72
P1=
[0 0 0 1]
[0 1 0 1]
PosisiPointRandom= 1
Index P1 = 77
P1=
[1 0 0 1]
[0 0 0 1]
PosisiPointRandom= 1
Index P1 = 34
P1=
[1 0 1 0]
[0 0 1 0]
PosisiPointRandom= 2
Index P1 = 69
P1=
[0 1 0 1]
[0 0 0 1]
PosisiPointRandom= 2
Index P1 = 79
P1=
[1 0 0 0]
[1 1 0 0]
PosisiPointRandom= 4
Index P1 = 35
P1=
[1 1 1 1]
[1 1 1 0]
158
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
PosisiPointRandom= 4
Index P1 = 38
P1=
[1 0 1 1]
[1 0 1 0]
PosisiPointRandom= 3
Index P1 = 65
P1=
[1 0 1 1]
[1 0 0 1]
PosisiPointRandom= 3
Index P1 = 9
P1=
[1 1 0 1]
[1 1 1 1]
PosisiPointRandom= 1
Index P1 = 54
P1=
[0 1 0 0]
[1 1 0 0]
PosisiPointRandom= 2
Index P1 = 23
P1=
[1 0 1 0]
[1 1 1 0]
PosisiPointRandom= 1
Index P1 = 52
P1=
[0 1 0 0]
[1 1 0 0]
PosisiPointRandom= 2
Index P1 = 64
P1=
[0 0 1 0]
[0 1 1 0]
PosisiPointRandom= 3
Index P1 = 33
P1=
[0 1 1 0]
[0 1 0 0]
PosisiPointRandom= 4
Index P1 = 71
P1=
[1 1 1 1]
[1 1 1 0]
PosisiPointRandom= 2
Index P1 = 21
P1=
[0 0 1 0]
[0 1 1 0]
PosisiPointRandom= 3
Index P1 = 64
P1=
[0 0 1 0]
[0 0 0 0]
PosisiPointRandom= 4
Index P1 = 56
P1=
[0 0 1 0]
159
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
[0 0 1 1]
PosisiPointRandom= 3
Index P1 = 39
P1=
[0 0 1 0]
[0 0 0 0]
PosisiPointRandom= 3
Index P1 = 52
P1=
[0 1 0 0]
[0 1 1 0]
PosisiPointRandom= 3
Index P1 = 68
P1=
[0 0 1 1]
[0 0 0 1]
PosisiPointRandom= 2
Index P1 = 51
P1=
[0 1 0 0]
[0 0 0 0]
PosisiPointRandom= 2
Index P1 = 17
P1=
[0 1 0 1]
[0 0 0 1]
PosisiPointRandom= 3
Index P1 = 25
P1=
[1 1 0 0]
[1 1 1 0]
PosisiPointRandom= 3
Index P1 = 78
P1=
[1 0 1 1]
[1 0 0 1]
PosisiPointRandom= 1
Index P1 = 80
P1=
[1 1 1 1]
[0 1 1 1]
PosisiPointRandom= 1
Index P1 = 43
P1=
[1 1 1 1]
[0 1 1 1]
PosisiPointRandom= 4
Index P1 = 40
P1=
[0 1 1 1]
[0 1 1 0]
PosisiPointRandom= 3
Index P1 = 17
P1=
[0 1 0 1]
[0 1 1 1]
PosisiPointRandom= 2
160
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Index P1 = 69
P1=
[0 1 0 1]
[0 0 0 1]
PosisiPointRandom= 1
Index P1 = 62
P1=
[1 0 0 1]
[0 0 0 1]
PosisiPointRandom= 2
Index P1 = 70
P1=
[0 1 0 0]
[0 0 0 0]
PosisiPointRandom= 1
Index P1 = 6
P1=
[1 0 1 0]
[0 0 1 0]
PosisiPointRandom= 3
Index P1 = 67
P1=
[1 0 0 0]
[1 0 1 0]
Hasil Mutasi:
M1: [0 0 1 0] | 2 | 11.0
M2: [1 1 1 0] | 14 | -13.0
M3: [0 0 0 1] | 1 | 0.0
M4: [1 1 0 1] | 13 | 0.0
M5: [1 1 1 1] | 15 | -28.0
M6: [1 1 0 1] | 13 | 0.0
M7: [1 1 1 0] | 14 | -13.0
M8: [1 0 0 1] | 9 | 32.0
M9: [1 0 0 1] | 9 | 32.0
M10: [1 0 0 1] | 9 | 32.0
M11: [0 1 0 1] | 5 | 32.0
M12: [1 0 1 0] | 10 | 27.0
M13: [0 0 1 0] | 2 | 11.0
M14: [0 1 1 0] | 6 | 35.0
M15: [0 1 0 1] | 5 | 32.0
M16: [0 0 0 1] | 1 | 0.0
M17: [0 0 1 0] | 2 | 11.0
M18: [0 0 0 1] | 1 | 0.0
M19: [1 1 0 0] | 12 | 11.0
M20: [1 1 1 0] | 14 | -13.0
M21: [1 0 1 0] | 10 | 27.0
M22: [1 0 0 1] | 9 | 32.0
M23: [1 1 1 1] | 15 | -28.0
M24: [1 1 0 0] | 12 | 11.0
M25: [1 1 1 0] | 14 | -13.0
M26: [1 1 0 0] | 12 | 11.0
M27: [0 1 1 0] | 6 | 35.0
M28: [0 1 0 0] | 4 | 27.0
M29: [1 1 1 0] | 14 | -13.0
M30: [0 1 1 0] | 6 | 35.0
M31: [0 0 0 0] | 0 | -13.0
M32: [0 0 1 1] | 3 | 20.0
M33: [0 0 0 0] | 0 | -13.0
M34: [0 1 1 0] | 6 | 35.0
M35: [0 0 0 1] | 1 | 0.0
M36: [0 0 0 0] | 0 | -13.0
M37: [0 0 0 1] | 1 | 0.0
M38: [1 1 1 0] | 14 | -13.0
M39: [1 0 0 1] | 9 | 32.0
M40: [0 1 1 1] | 7 | 36.0
M41: [0 1 1 1] | 7 | 36.0
M42: [0 1 1 0] | 6 | 35.0
M43: [0 1 1 1] | 7 | 36.0
M44: [0 0 0 1] | 1 | 0.0
M45: [0 0 0 1] | 1 | 0.0
M46: [0 0 0 0] | 0 | -13.0
161
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
M47: [0 0 1 0] | 2 | 11.0
M48: [1 0 1 0] | 10 | 27.0
162
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
G78: [1 0 1 1] | 11 | 20.0
G79: [1 0 0 0] | 8 | 35.0
G80: [1 1 1 1] | 15 | -28.0
G81: [0 0 0 0] | 0 | -13.0
G82: [1 1 0 1] | 13 | 0.0
G83: [1 1 0 0] | 12 | 11.0
G84: [1 0 0 0] | 8 | 35.0
G85: [0 1 1 0] | 6 | 35.0
G86: [0 0 1 1] | 3 | 20.0
G87: [0 0 1 0] | 2 | 11.0
G88: [0 0 1 0] | 2 | 11.0
G89: [1 0 0 1] | 9 | 32.0
G90: [1 0 0 1] | 9 | 32.0
G91: [0 0 0 1] | 1 | 0.0
G92: [1 1 0 0] | 12 | 11.0
G93: [0 0 1 1] | 3 | 20.0
G94: [1 0 1 0] | 10 | 27.0
G95: [1 0 1 1] | 11 | 20.0
G96: [1 0 0 1] | 9 | 32.0
G97: [0 1 0 1] | 5 | 32.0
G98: [1 0 0 0] | 8 | 35.0
G99: [0 0 0 1] | 1 | 0.0
G100: [1 1 0 0] | 12 | 11.0
G101: [0 1 1 0] | 6 | 35.0
G102: [1 1 0 0] | 12 | 11.0
G103: [0 0 1 1] | 3 | 20.0
G104: [1 1 1 0] | 14 | -13.0
G105: [1 0 0 0] | 8 | 35.0
G106: [1 0 0 0] | 8 | 35.0
G107: [0 0 0 0] | 0 | -13.0
G108: [0 1 0 0] | 4 | 27.0
G109: [1 0 0 0] | 8 | 35.0
G110: [0 0 0 1] | 1 | 0.0
G111: [1 0 0 0] | 8 | 35.0
G112: [1 1 0 1] | 13 | 0.0
G113: [0 1 1 1] | 7 | 36.0
G114: [1 0 1 1] | 11 | 20.0
G115: [1 0 1 1] | 11 | 20.0
G116: [0 1 0 0] | 4 | 27.0
G117: [1 0 0 1] | 9 | 32.0
G118: [0 0 0 1] | 1 | 0.0
G119: [0 0 1 0] | 2 | 11.0
G120: [0 0 1 1] | 3 | 20.0
G121: [1 1 0 0] | 12 | 11.0
G122: [0 1 1 1] | 7 | 36.0
G123: [1 0 0 0] | 8 | 35.0
G124: [1 1 1 1] | 15 | -28.0
G125: [0 0 1 0] | 2 | 11.0
G126: [0 1 1 0] | 6 | 35.0
G127: [1 0 0 1] | 9 | 32.0
G128: [0 1 1 1] | 7 | 36.0
G129: [0 1 1 0] | 6 | 35.0
G130: [0 1 0 0] | 4 | 27.0
G131: [1 1 0 1] | 13 | 0.0
G132: [1 0 1 0] | 10 | 27.0
G133: [0 1 0 1] | 5 | 32.0
G134: [0 0 1 0] | 2 | 11.0
G135: [1 1 1 1] | 15 | -28.0
G136: [0 0 0 1] | 1 | 0.0
G137: [1 1 1 1] | 15 | -28.0
G138: [0 0 1 1] | 3 | 20.0
G139: [0 1 1 1] | 7 | 36.0
G140: [1 1 0 1] | 13 | 0.0
G141: [1 0 1 1] | 11 | 20.0
G142: [0 0 1 0] | 2 | 11.0
G143: [0 1 1 1] | 7 | 36.0
G144: [0 0 0 0] | 0 | -13.0
G145: [0 0 1 0] | 2 | 11.0
G146: [1 1 1 0] | 14 | -13.0
G147: [0 0 0 1] | 1 | 0.0
G148: [1 1 0 1] | 13 | 0.0
G149: [1 1 1 1] | 15 | -28.0
G150: [1 1 0 1] | 13 | 0.0
G151: [1 1 1 0] | 14 | -13.0
G152: [1 0 0 1] | 9 | 32.0
G153: [1 0 0 1] | 9 | 32.0
G154: [1 0 0 1] | 9 | 32.0
G155: [0 1 0 1] | 5 | 32.0
G156: [1 0 1 0] | 10 | 27.0
G157: [0 0 1 0] | 2 | 11.0
G158: [0 1 1 0] | 6 | 35.0
163
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
G159: [0 1 0 1] | 5 | 32.0
G160: [0 0 0 1] | 1 | 0.0
G161: [0 0 1 0] | 2 | 11.0
G162: [0 0 0 1] | 1 | 0.0
G163: [1 1 0 0] | 12 | 11.0
G164: [1 1 1 0] | 14 | -13.0
G165: [1 0 1 0] | 10 | 27.0
G166: [1 0 0 1] | 9 | 32.0
G167: [1 1 1 1] | 15 | -28.0
G168: [1 1 0 0] | 12 | 11.0
G169: [1 1 1 0] | 14 | -13.0
G170: [1 1 0 0] | 12 | 11.0
G171: [0 1 1 0] | 6 | 35.0
..
.
164
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
nextG65: [1 0 1 0] | 10 | 27.0
nextG66: [0 1 0 0] | 4 | 27.0
nextG67: [0 1 0 0] | 4 | 27.0
nextG68: [1 0 1 0] | 10 | 27.0
nextG69: [0 1 0 0] | 4 | 27.0
nextG70: [1 0 1 0] | 10 | 27.0
nextG71: [1 0 1 0] | 10 | 27.0
nextG72: [1 0 1 0] | 10 | 27.0
nextG73: [0 1 0 0] | 4 | 27.0
nextG74: [1 0 1 0] | 10 | 27.0
nextG75: [0 1 0 0] | 4 | 27.0
nextG76: [1 0 1 0] | 10 | 27.0
nextG77: [1 0 1 0] | 10 | 27.0
nextG78: [1 0 1 0] | 10 | 27.0
nextG79: [0 1 0 0] | 4 | 27.0
nextG80: [0 1 0 0] | 4 | 27.0
.
Done..! :D
=============================================================
.
[05/Jul/2018 00:37:48] "POST /ga HTTP/1.1" 200 43
165
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 5 April 2023
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
template_view = '''
<div class="row">
<div class="col-12">
<div class="white-box">
<div class="card-body">
<form action="/myadmin" method="post">
<h4 class="card-title">Masukkan data yang
akan dibuat</h4>
<h6 class="card-subtitle"></h6>
<button type="button" class="btn btn-info
btn-rounded m-t-10 float-right"
data-toggle="modal"
data-target="#add-contact">Buat Tabel
</button>
166
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
'''
list_none_atau_lainnya = none_atau_lainnya.split("-")
str_none_atau_lainnya = ' '.join(list_none_atau_lainnya)
conn = connect_db()
db = conn.cursor()
if(get_jenis_query == 'edit'):
var1_in_edit = request.form['nama_tabel_edit_'+get_nama_tabel]
var2_in_edit = request.form['teks_sintaks_edit_'+get_nama_tabel]
conn.commit()
elif(get_jenis_query == 'del'):
var1_in_hapus = request.form['nama_tabel_hapus_'+get_nama_tabel]
conn.commit()
elif(get_jenis_query == 'gen'):
var1_in_gen = request.form['nama_tabel_gen_'+get_nama_tabel]
var2_in_gen = request.form['teks_sintaks_tabel_gen_'
+get_nama_tabel]
var3_in_gen = request.form['teks_sintaks_page_gen_'+get_nama_tabel]
"""
db.close()
conn.close()
return redirect(url_for('myadmin'))
else:
# Aksi => Buat, Hapus Tabel data_tabel_myadmin
aksi = 'c'
if aksi == 'c':
conn = connect_db()
db = conn.cursor()
conn.commit()
167
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
conn.commit()
db.execute("""
vacuum
""")
conn.commit()
# return str_info
if request.method == 'POST'
var1_in = request.form['nama_tabel']
var2_in = request.form['teks_sintaks']
getVals_base_filter_var1_in = list(filter(lambda x: x in
filter_var1_in, var1_in))
var1_in = "".join(getVals_base_filter_var1_in).lower()
if aksi_sub == 'c':
# conn = connect_db()
# db = conn.cursor()
conn.commit()
if entry is None:
import numpy as np
import pandas as pd
else:
ket_hasil = 'Tidak dilakukan Insert,
karena Tabel tidak kosong'
conn.commit()
168
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
conn.commit()
db.execute("""
vacuum
""")
conn.commit()
# db.close()
# conn.close()
var_tabel_myadmin_in = c.fetchall()
conn.commit()
db.close()
conn.close()
return render_template_string(A_a+template_view+Z_z,
var1 = var1_in, var2 = var2_in, var_tabel_myadmin =
var_tabel_myadmin_in)
var_tabel_myadmin_in = c.fetchall()
conn.commit()
db.close()
conn.close()
return render_template_string(A_a+template_view+Z_z,
var_tabel_myadmin = var_tabel_myadmin_in)
169
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
170
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
171
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 10 Oktober 2019
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
%%file ./NBMapReduce/NBCDriver.java
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
172
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
System.exit(success ? 0 : 1);
}
}
# ------------------------------------------------------------
%%file ./NBMapReduce/NBCMap.java
import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
for(Entry<String,Double> o_c:outcome_count.entrySet()){
String output_class=o_c.getKey();
for(Entry<String,Integer> i:inputs.entrySet()){
if(!features_count.containsKey(i.getKey()+"|"+output_class))
features_count.put(i.getKey()+"|"+output_class, (double) 0);
}
double output_class_count=o_c.getValue();
double probability=output_class_count/count;
for(Entry<String,Double> f_c:features_count.entrySet()){
if(f_c.getKey().split("\\|")[1].contentEquals(output_class))
probability=probability*(f_c.getValue()/output_class_count);
}
output.put(output_class, probability);
}
for(Entry<String,Double> o:output.entrySet()){
if(o.getValue()>output_value){
output_value=o.getValue();
output_key=o.getKey();
}
}
context.write(new IntWritable(1),new Text(output_key));
}
}
# ------------------------------------------------------------
173
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
!javac -cp
"%HADOOP_HOME%\share\hadoop\common\*;%HADOOP_HOME%\share\hadoop\mapreduce\*"
*.java
# ------------------------------------------------------------
!hdfs dfs -ls .
..
.
!%HADOOP_HOME%/bin/hadoop jar NBMapReduce.jar NBCDriver "Urgent,No,No" \
"./user/ImamCS/nb/input/dataset.txt" \
"./user/ImamCS/nb/output2"
Output:
19/10/11 01:37:33 INFO client.RMProxy: Connecting to ResourceManager at lo-
calhost/127.0.0.1:8050
19/10/11 01:37:34 WARN mapreduce.JobResourceUploader: Hadoop command-line op-
tion parsing not performed. Implement the Tool interface and execute your ap-
plication with ToolRunner to remedy this.
19/10/11 01:37:36 INFO input.FileInputFormat: Total input paths to process : 1
19/10/11 01:37:36 INFO mapreduce.JobSubmitter: number of splits:1
19/10/11 01:37:37 INFO mapreduce.JobSubmitter: Submitting tokens for job:
job_1570732148023_0003
19/10/11 01:37:37 INFO impl.YarnClientImpl: Submitted application applica-
tion_1570732148023_0003
19/10/11 01:37:38 INFO mapreduce.Job: The url to track the job: http://XVisi-
ble-Teams:8088/proxy/application_1570732148023_0003/
19/10/11 01:37:38 INFO mapreduce.Job: Running job: job_1570732148023_0003
19/10/11 01:38:15 INFO mapreduce.Job: Job job_1570732148023_0003 running in
uber mode : false
19/10/11 01:38:15 INFO mapreduce.Job: map 0% reduce 0%
19/10/11 01:38:34 INFO mapreduce.Job: map 100% reduce 0%
19/10/11 01:38:51 INFO mapreduce.Job: map 100% reduce 100%
19/10/11 01:39:02 INFO mapreduce.Job: Job job_1570732148023_0003 completed suc-
cessfully
19/10/11 01:39:03 INFO mapreduce.Job: Counters: 49
File System Counters
FILE: Number of bytes read=18
FILE: Number of bytes written=240657
FILE: Number of read operations=0
FILE: Number of large read operations=0
FILE: Number of write operations=0
HDFS: Number of bytes read=323
HDFS: Number of bytes written=6
HDFS: Number of read operations=6
HDFS: Number of large read operations=0
HDFS: Number of write operations=2 ..
Launched map tasks=1
Launched reduce tasks=1
Data-local map tasks=1
Total time spent by all maps in occupied slots ..
Total time spent by all reduces in occupied slots ..
Total time spent by all map tasks (ms)=15568
Total time spent by all reduce tasks (ms)=15084
Total vcore-milliseconds taken by all map tasks=15568
Total vcore-milliseconds taken by all reduce ..
Total megabyte-milliseconds taken by all map ..
Total megabyte-milliseconds taken by all reduce ..
Map-Reduce Framework
Map input records=10
Map output records=1
Map output bytes=10
Map output materialized bytes=18
Input split bytes=131
Combine input records=0
Combine output records=0
Reduce input groups=1
174
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Hasil klasifikasi:
!hadoop fs -cat ./user/ImamCS/nb/output2/*
Study
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 12 November 2019
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
import json
SPARK_BIN = 'spark-submit'
HADOOP_BIN = 'hadoop'
HADOOP_STREAMING_JAR = ''
#utils
random_name = lambda N : ''.join(random.choice(string.ascii_uppercase +
string.digits + string.ascii_lowercase) for _ in range(N))
letters = string.ascii_letters
return ''.join(random.choice(letters) for i in range(stringLength))
175
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
def run_process(l):
print(' '.join(l))
try:
process = subprocess.Popen(l, stdout=subprocess.PIPE, stderr=\
subprocess.PIPE)
stdout, stderr = [s.decode() for s in process.communicate()]
print(stdout)
print(stderr)
return 0, stdout, stderr
except subprocess.CalledProcessError as e:
stdout, stderr = process.communicate()
print("Program returned exitcode %d" % process.returncode)
print(stderr)
print(stdout)
return process.returncode, stdout, stderr
def parse_output(file):
l = []
cast = lambda x : (int(x[0]), list(map(float, x[1:])))
for row in file:
l.append(cast(row.replace("(", "").replace(")", "").split(",")))
return l
def function_week1(request):
if request.method == 'POST':
import pandas as pd
import numpy as np
dataset = request.FILES['inputDataset']#'E:/../dataset_dump.csv'
persentase_data_training = 90
banyak_fitur = int(request.POST['banyakFitur'])
banyak_hidden_neuron = int(request.POST['banyakHiddenNeuron'])
data_training = data_normalisasi[:int(\
persentase_data_training*len(data_normalisasi)/100)]
data_testing = data_normalisasi[int(\
persentase_data_training*len(data_normalisasi)/100):]
#Training
bobot = np.random.rand(banyak_hidden_neuron, banyak_fitur)
bias = np.random.rand(banyak_hidden_neuron)
h = 1/(1 + np.exp(-(np.dot(data_training[:, :banyak_fitur], \
np.transpose(bobot)) + bias)))
h_plus = np.dot(np.linalg.inv(np.dot(np.transpose(h),h)),np.transpose(h))
output_weight = np.dot(h_plus, data_training[:, banyak_fitur])
#Testing
h = 1/(1 + np.exp(-(np.dot(data_testing[:, :banyak_fitur], \
np.transpose(bobot)) + bias)))
predict = np.dot(h, output_weight)
predict = predict * (maksimum - minimum) + minimum
#MAPE
aktual = np.array(hasil_fitur[int(persentase_data_training*\
len(data_normalisasi)/100):, banyak_fitur])
mape = np.sum(np.abs(((aktual - predict)/aktual)*100))/len(predict)
return render(request, 'week1.html', {
176
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
'y_aktual' : list(aktual),
'y_prediksi' : list(predict),
'mape' : mape
})
else:
return render(request, 'week1.html')
def function_week2_task1(request):
return render(request, 'week21.html')
def function_week2_task2(request):
return render(request, 'week22.html')
def function_week3(request):
# Import library request
import requests
apikey = 'fgredste133559c63e055b23b0dd2dafc698fcfe0768' # --> P. imam,
def function_week4(request):
return render(request, 'week4.html')
def function_week4_task1(request):
if request.method == 'POST':
cwd = os.getcwd()
dir_output = cwd+"/"+random_name(10)+"/"
file_input = dir_output+"input.in"
#clean output
run_process(["rm", "-r", dir_output])
#write to file
run_process(["mkdir", dir_output])
#run hadoop
exitcode, stdout, stdin = run_process([HADOOP_BIN, 'jar',
HADOOP_STREAMING_JAR,'-input', 'file://'+file_input, '-output',
'file://'+dir_output, '-mapper', 'piMapper.py', '-reducer', 'piReducer.py',
'-file', 'hadoop/piMapper.py', 'hadoop/piReducer.py'])
#merge file
result_file = dir_output+"result.txt"
get_merge_local(result_file, dir_output)
#parse output
result = sorted(open(mape_file, "r").read().split("\n"))
mape = [x[2] for x in result]
values = [x[1] for x in result]
def function_week4_task2(request):
return render(request, 'week4.html')
177
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
def function_week5(request):
return render(request, 'week5.html')
def function_week5_task1(request):
if request.method == 'POST':
cwd = os.getcwd()
memory_input = request.FILES['inputDataset'].read()
jumlah_fitur = request.POST['banyakFitur']
jumlah_hidden = request.POST['banyakHiddenNeuron']
dir_output = cwd+"/"+random_name(10)+"/"
file_input = dir_output+"input.in"
activation_function = request.POST['fungsiAktivasi']
#clean output
run_process(["rm", "-r", dir_output])
#write to file
run_process(["mkdir", dir_output])
with open(file_input, "wb", buffering=0) as file:
file.write(memory_input)
file.flush()
os.fsync(file)
del memory_input
#upload file to hdfs (Not Supported)
#run spark
exitcode, stdout, stdin = run_process([SPARK_BIN, 'spark/pyspark_elm.py',
jumlah_fitur, jumlah_hidden, "file://"+file_input, "file://"+dir_output,
activation_function])
#merge file
output_file = dir_output+"result.txt"
mape_file = dir_output+"mape.txt"
get_merge_local(output_file, dir_output+"result")
get_merge_local(mape_file, dir_output+"mape")
#parse output
output = sorted(parse_output(open(output_file)))
aktual = [x[1][0] for x in output]
prediction = [x[1][1] for x in output]
del output
mape = list(map(float,open(mape_file).read().replace("\n", \
" ").strip().split(" ")))
#render
return render(request, 'week51.html', {
'y_aktual' : aktual,
'y_prediksi' : prediction,
'mape' : mape[1],
'mape_train' : mape[0]
})
else:
return render(request, 'week51.html')
def function_week5_task2(request):
if request.method == 'POST':
cwd = os.getcwd()
memory_input = request.FILES['inputDataset'].read()
jumlah_fitur = request.POST['banyakFitur']
#jumlah_hidden = request.POST['banyakHiddenNeuron']
dir_output = cwd+"/"+random_name(10)+"/"
file_input = dir_output+"input.in"
#clean output
run_process(["rm", "-r", dir_output])
#write to file
run_process(["mkdir", dir_output])
with open(file_input, "wb", buffering=0) as file:
178
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
file.write(memory_input)
file.flush()
os.fsync(file)
del memory_input
#run spark
exitcode, stdout, stdin = run_process([SPARK_BIN, 'spark/pyspark_lr.py',\
jumlah_fitur, "file://"+file_input, "file://"+dir_output])
#merge file
output_file = dir_output+"result.txt"
mape_file = dir_output+"mape.txt"
get_merge_local(output_file, dir_output+"result")
get_merge_local(mape_file, dir_output+"mape")
#parse output
output = sorted(parse_output(open(output_file)))
aktual = [x[1][0] for x in output]
prediction = [x[1][1] for x in output]
del output
mape = list(map(float,open(mape_file).read().replace("\n", \
" ").strip().split(" ")))
#render
return render(request, 'week52.html', {
'y_aktual' : aktual,
'y_prediksi' : prediction,
'mape' : mape[1],
'mape_train' : mape[0]
})
else:
return render(request, 'week52.html')
def function_week6(request):
return render(request, 'week6.html')
def function_week7(request):
return render(request, 'week7.html')
def function_week7_task_1(request):
if request.method == 'POST':
cetak = nb_run(request, False)
#render
return render(request, 'week71.html', {
'prediction' : cetak
})
else:
return render(request, 'week71.html')
def function_week7_task_2(request):
if request.method == 'POST':
cwd = os.getcwd()
memory_input = request.FILES['inputDataset'].read()
jumlah_fitur = request.POST['banyakFitur']
jumlah_hidden = request.POST['banyakHiddenNeuron']
dir_output = cwd+"/"+random_name(10)+"/"
file_input = dir_output+"input.in"
activation_function = request.POST['fungsiAktivasi']
#clean output
run_process(["rm", "-r", dir_output])
#write to file
run_process(["mkdir", dir_output])
with open(file_input, "wb", buffering=0) as file:
file.write(memory_input)
file.flush()
os.fsync(file)
del memory_input
179
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
#run spark
exitcode, stdout, stdin = run_process([SPARK_BIN, \
'spark/pyspark_elm_2.py', jumlah_fitur, jumlah_hidden, \
"file://"+file_input, "file://"+dir_output, activation_function])
#merge file
output_file = dir_output+"result.txt"
mape_file = dir_output+"mape.txt"
get_merge_local(output_file, dir_output+"result")
get_merge_local(mape_file, dir_output+"mape")
#parse output
output = sorted(parse_output(open(output_file)))
aktual = [x[1][0] for x in output]
prediction = [x[1][1] for x in output]
del output
mape = list(map(float,open(mape_file).read().replace("\n", \
" ").strip().split(" ")))
#render
return render(request, 'week72.html', {
'y_aktual' : aktual,
'y_prediksi' : prediction,
'mape' : mape[1],
'mape_train' : mape[0]
})
else:
return render(request, 'week72.html')
def company(request):
return render(request, 'week8.html')
# other function
if type_api:
payload = json.loads(request.body)
fitur_1 = payload['fitur_1']
fitur_2 = payload['fitur_2']
fitur_3 = payload['fitur_3']
else:
fitur_1 = request.POST['fitur_1']
fitur_2 = request.POST['fitur_2']
fitur_3 = request.POST['fitur_3']
# merge input
dataInput = fitur_1 + "," + fitur_2 + "," + fitur_3
#run hadoop
exitcode, stdout, stdin = run_process([HADOOP_BIN, 'jar', \
'hadoop/NBMapReduce/NBMapReduce.jar', 'NBCDriver', dataInput, \
'/user/ubuntu/nb-input/dataset.txt', '/user/ubuntu/nb-output/'+output_dir])
#return
180
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
return cetak[1]
@csrf_exempt
def post_api(request):
if request.method == 'POST' :
hasil = nb_run(request)
response = json.dumps({ 'prediksi': hasil })
Output:
(a)
(b)
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 5 Agustus 2020
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
package com.mind.naivebayesapps;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
181
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fitur1 = findViewById(R.id.fitur_1);
fitur2 = findViewById(R.id.fitur_2);
fitur3 = findViewById(R.id.fitur_3);
btnSub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fitur_1 = fitur1.getText().toString();
fitur_2 = fitur2.getText().toString();
fitur_3 = fitur3.getText().toString();
// progress dialog
progressDialog = new ProgressDialog(view.getContext());
progressDialog.setMessage("Loading..."); // Setting Message
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
client = builder.build();
try {
postRequest();
} catch (IOException e) {
e.printStackTrace();
}
}
});
btnKelompok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alertDialogKelompok();
}
});
}
182
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println("no");
String mMessage = e.getMessage();
Log.w("failure Response", e);
@Override
public void onResponse(Call call, Response response) throws
IOException {
mMessage = response.body().string();
System.out.println("ok");
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
//Dismiss the dialog
progressDialog.dismiss();
183
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Output:
184
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id, & Teams
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 10 Oktober 2019
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
185
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
@Component({
selector: 'app-tab1',
templateUrl: 'tab1.page.html',
styleUrls: ['tab1.page.scss']
})
export class Tab1Page {
data: Observable<any>
aktual: any;
prediksi: any;
mape: any;
constructor(public http: HttpClient, public navCtrl: NavController, public
modalController: ModalController) { }
input: string;
input2: string;
input3: string;
click() {
// alternatif deploy apps selain ke heroku dapat dibuat di pythonanywhere
// contoh utk membuat API di pythonanywhere dapat dilihat pada link
// ===========
/*
# cara akses, misal:
http://imamcs.pythonanywhere.com/api/fp/3.0/?a=70&b=3&c=2
@app.route("/api/fp/3.0/", methods=["GET"])
def api():
import os.path
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
url = os.path.join(BASE_DIR, "static/data_contoh/dataset_dump_tiny.csv")
import pandas as pd
import numpy as np
import json
# from django.http import HttpResponse
from flask import Response
a, b, c = request.args.get('a'), request.args.get('b'),
request.args.get('c')
persentase_data_training = int(a)
banyak_fitur = int(b)
banyak_hidden_neuron = int(c)
minimum = int(dataset.min())
maksimum = int(dataset.max())
new_banyak_fitur = banyak_fitur + 1
hasil_fitur = []
for i in range((len(dataset)-new_banyak_fitur)+1):
kolom = []
j = i
while j < (i+new_banyak_fitur):
kolom.append(dataset.values[j][0])
j += 1
hasil_fitur.append(kolom)
hasil_fitur = np.array(hasil_fitur)
# print(hasil_fitur)
data_normalisasi = (hasil_fitur - minimum)/(maksimum - minimum)
data_training = data_normalisasi[:int(
persentase_data_training*len(data_normalisasi)/100)]
data_testing = data_normalisasi[int(
persentase_data_training*len(data_normalisasi)/100):]
# print(data_training)
# Training
is_singular_matrix = True
while(is_singular_matrix):
bobot = np.random.rand(banyak_hidden_neuron, banyak_fitur)
bias = np.random.rand(banyak_hidden_neuron)
186
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
h = 1 / \
(1 + np.exp(-(np.dot(data_training[:, :banyak_fitur],
np.transpose(bobot)) + bias)))
# print("h_plus", h_plus)
output_weight = np.dot(h_plus, data_training[:, banyak_fitur])
# Testing
h = 1 / \
(1 + np.exp(-(np.dot(data_testing[:, :banyak_fitur],
np.transpose(bobot)) + bias)))
predict = np.dot(h, output_weight)
predict = (predict * (maksimum - minimum) + minimum)
# MAPE
aktual = np.array(hasil_fitur[int(
persentase_data_training*len(data_normalisasi)/100):,
banyak_fitur]).tolist()
mape = np.sum(np.abs(((aktual - predict)/aktual)*100))/len(predict)
prediksi = predict.tolist()
# Enable Access-Control-Allow-Origin
response.headers.add("Access-Control-Allow-Origin", "*")
return response
uri = "http://enterumum.pythonanywhere.com/api/fp/3.0/?a=50&b=3&c=2"
try:
uResponse = requests.get(uri)
except requests.ConnectionError:
return "Terdapat Error Pada Koneksi Anda"
Jresponse = uResponse.text
data = json.loads(Jresponse)
return data
*/
// ===========
this.data = this.http.get(url);
this.data.subscribe(data => {
console.log(data)
this.aktual = data.y_aktual
this.prediksi = data.y_prediksi
this.mape = data.mape
this.openModal()
})
// this.openModal()
}
async openModal() {
console.log(this.mape)
const modal = await this.modalController.create({
component: ModalPage,
componentProps: {
"aktual": this.aktual,
187
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
"prediksi": this.prediksi,
"mape": this.mape,
}
});
return await modal.present();
}
}
Output:
188
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 16 Agustus 2021
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
189
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
if request.method == 'POST':
import pandas as pd
import numpy as np
import os.path
dataset = request.files['inputDataset']
persentase_data_training = 90
banyak_fitur = int(request.form['banyakFitur'])
banyak_hidden_neuron = int(request.form['banyakHiddenNeuron'])
dataset = pd.read_csv(dataset, delimiter=';', \
names = ['Tanggal', 'Harga'], usecols=['Harga'])
..
.
#Training
bobot = np.random.rand(banyak_hidden_neuron, banyak_fitur)
bias = np.random.rand(banyak_hidden_neuron)
h = 1/(1 + np.exp(-(np.dot(data_training[:, \
:banyak_fitur], np.transpose(bobot)) + bias)))
h_plus = np.dot(np.linalg.inv(np.dot(np.transpose(h),h)),np.transpose(h))
output_weight = np.dot(h_plus, data_training[:, banyak_fitur])
#Testing
h = 1/(1 + np.exp(-(np.dot(data_testing[:, \
:banyak_fitur], np.transpose(bobot)) + bias)))
#MAPE
aktual = np.array(hasil_fitur[int(persentase_data_training*len(\
data_normalisasi)/100):, banyak_fitur])
else:
return render_template('bigdataApps.html')
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 16 Agustus 2021
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
url = os.path.join(BASE_DIR, "Salary_Data.csv")
dataset = pd.read_csv(url)
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
190
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
return render_template('MybigdataAppsNonPySpark.html',\
y_aktual = list(y_train), y_prediksi = list(y_pred2), mape = mape)
Output:
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 16 Agustus 2021
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
url = os.path.join(BASE_DIR, "Salary_Data.csv")
191
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
import findspark
findspark.init()
sqlcontext = SQLContext(sc)
data = sqlcontext.read.csv(url, header = True, inferSchema = True)
y_pred2 = testSet.select("prediction")
192
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
50 nano findspark.py
51 cp findspark.py /home/imamcs/mysite/
52 cp /home/imamcs/mysite/findspark.py ./
54 cp /home/imamcs/mysite/findspark.py ./
55 nano findspark.py
58 nano ~/.bashrc
59 cp ~/.bashrc /home/imamcs/mysite/
60 cp /home/imamcs/mysite/.bashrc ~/
61 nano ~/.bashrc
62 source ~/.bashrc
64 java --version
74 nano .profile
75 source .profile
77 chmod -R 7777 /home/imamcs/
82 cd ~/.local/lib/python3.7/site-packages
83 cp /home/imamcs/mysite/findspark.py ./
92 source ~/.bashrc
..
.
104 export PYSPARK_PYTHON=python3.7
105 cp /home/imamcs/mysite/.bashrc ~/
106 source ~/.bashrc
107 clear
108 cd
109 pyspark
05:47 ~ $ pyspark
Python 3.9.5 (default, May 27 2021, 19:45:35)
[GCC 9.3.0] on
linux
Type "help", "copyright", "credits" or "license" for more information.
22/08/08 05:47:33 WARN Utils: Your hostname, green-liveconsole15 resolves to a
loopback address: 127.0.0.1; using 10.0.0.57 instead (on interface ens5)
22/08/08 05:47:33 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another ad-
dress
22/08/08 05:47:33 WARN NativeCodeLoader: Unable to load native-hadoop library for
your platform... using builtin-java classes where applicable
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
Setting default log level to
"WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use
setLogLevel(newLevel).
Welcome to
____ __
/ __/__ ___ _____/ /__
_\ \/ _ \/ _ `/ __/ '_/
/__ / .__/\_,_/_/ /_/\_\ version 3.1.2
/_/
193
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Output:
194
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
195
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 19 September 2020
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
---
# ---------------------------------------------------------------------------
# -- Docs: https://github.com/imamcs19/edubig-..docker --
# -- Additional: Zookeeper, Kafka and port - 8501:8501 ..
# ---------------------------------------------------------------------------
version: "3.6"
volumes:
shared-workspace:
name: "hadoop-distributed-file-system"
driver: local
services:
# zookeeper:
# image: wurstmeister/zookeeper
# ports:
# - "2181:2181"
# kafka:
# image: wurstmeister/kafka
# ports:
# - "9092:9092"
# environment:
# KAFKA_ADVERTISED_HOST_NAME: 54.208.1.149
# KAFKA_ZOOKEEPER_CONNECT: 54.208.1.149:2181
# volumes:
# - /var/run/docker.sock:/var/run/docker.sock
jupyterlab:
image: imamcs/ubig1-jupyterlab
container_name: jupyterlab
ports:
- 8888:8888
- 8501:8501
volumes:
- shared-workspace:/opt/workspace
spark-master:
image: imamcs/ubig1-spark-master
container_name: spark-master
ports:
- 8080:8080
- 7077:7077
volumes:
- shared-workspace:/opt/workspace
spark-worker-1:
image: imamcs/ubig1-spark-worker
container_name: spark-worker-1
environment:
- SPARK_WORKER_CORES=1
- SPARK_WORKER_MEMORY=512m
ports:
196
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
- 8081:8081
volumes:
- shared-workspace:/opt/workspace
depends_on:
- spark-master
spark-worker-2:
image: imamcs/ubig1-spark-worker
container_name: spark-worker-2
environment:
- SPARK_WORKER_CORES=1
- SPARK_WORKER_MEMORY=512m
ports:
- 8082:8081
volumes:
- shared-workspace:/opt/workspace
depends_on:
- spark-master
...
197
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
198
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# Tips untuk menambahkan nodes dari third-party, atau yang custom atau lainnya:
# masukkan nama, path dan dependensinya
# dari nodes tambahaan ini pada file ../package.json
# contoh: "node-red-contrib-iot-simulator":
# "file:nodes/iot-device-simulator-1-mqtt/node-red-contrib-iot-simulator",
# "node-red-contrib-mqtt-plus": "file:nodes/node-red-contrib-mqtt-plus",
# "node-red-dashboard": "^3.1.7"
{
"name": "node-red-heroku",
"version": "0.0.2",
"dependencies": {
"feedparser": "^2.2.10",
"https-proxy-agent": "^5.0.1",
"nano": "~10.x",
"node-red": "^2.2.2",
"node-red-contrib-iot-simulator":
"file:nodes/iot-device-simulator-1-mqtt/node-red-contrib-iot-simulator",
"node-red-contrib-mqtt-plus": "file:nodes/node-red-contrib-mqtt-plus",
"node-red-dashboard": "^3.1.7",
"pg": "^8.3.0",
"redis": "~0.10.1",
"when": "~3.x"
}
}
# C:\Users\imamcs\Downloads\fpiot-master>
199
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# untuk trigger hasil virtual sensor IoT simulator dapat menggunakan random
# seperti kode program berikut
@app.route('/gen_suhu')
def gen_suhu():
import random
# misal generate hasil pengamatan suhu dalam
# interval 0 sampai 100 derajat celcius
return {'value': random.randint(0, 100)}
@app.route('/iot_plot')
def iot_plot():
import random
# Generate titik data
my_x_dump = [i for i in range(1, 11)]
my_y1_dump = [random.randint(1, 10) for i in range(10)]
my_y2_dump = [random.randint(1, 10) for i in range(10)]
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="chart"></div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div id="plot"></div>
</div>
<div class="col-md-6">
<div id="plot2"></div>
</div>
</div>
</div>
<script>
//var plot = document.getElementById('plot');
//Plotly.newPlot(plot, {{fig | safe}});
</script>
<script>
// inisialisasi data trace untuk chart
const trace = {
x: [],
y: [],
type: 'scatter',
mode: 'lines',
line: {
200
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
dash: 'dot'
}
};
};
Plotly.extendTraces('chart', update, [0]);
})
.catch(error => console.error(error));
}, 1000);
</script>
</body>
</html>
'''
return render_template_string(my_template_string, fig=fig)
Output :
(a)
201
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
(b)
(c)
202
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
203
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 28 Januari 2023
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
204
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
function Login() {
const dispatch = useDispatch();
const navigate = useNavigate();
sessionStorage.setItem("userId", res.data.userId);
sessionStorage.setItem("password", res.data.password);
localStorage.setItem('mydata', JSON.stringify(res.data));
navigate("/daftarorderan");
}
else if (res.data.statusCode == 400) {
message.error('Terjadi Kesalahan User & Password ');
}
};
handleSubmit(values);
};
return (
<div className='authentication'>
<Row>
<Col lg={8} xs={22}>
<Form layout='vertical' onFinish={onFinish}>
<img src={logo} height='70' width='360' />
<hr />
<h3>Silahkan Login</h3>
<div className='d-flex-justify-content-between-align-items-right'>
<Button htmlType='submit' type='primary'>
Login
</Button>
</div>
</Form>
</Col>
</Row>
205
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
</div>
);
}
Output:
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 28 Januari 2023
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
# ..\api\routes\auserRoute.js
# -----------------------------
const express = require('express');
const router = express.Router();
const {
login,
getLogin,
getUser,
addUser,
editUser,
deleteUser,
} =
require('../controllers/auserController');
router.post('/login', login);
router.get('/get-login', getLogin);
206
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
router.get('/get-all-user', getUser);
router.post('/add-user', addUser);
router.post('/edit-user', editUser);
router.delete('/:id', deleteUser);
module.exports = router;
# ..\api\models\auserModel.js
# -----------------------------
const Sequelize = require('sequelize');
const db = require("../config/db.js");
/*
CREATE TABLE a_users (
userId STRING PRIMARY KEY,
role TEXT,
password TEXT,
name TEXT,
isArchive BOOLEAN,
timestamps STRING
); */
module.exports = Auser;
# ..\api\config\db.js
# -----------------------
const Sequelize = require('sequelize');
const db = new Sequelize({
dialect: "sqlite",
storage: "myapp.db"
});
//Test koneksi ke DB
db.authenticate()
.then(() => console.log('Database Connected dengan Sequelize :D '))
.catch(err => console.log('Error: ', err))
module.exports = db;
# ..\api\controllers\auserController.js
# ---------------------------------------
module.exports = {
login: async (req, res) => {
207
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
try {
const user = await AuserModel.findAndCountAll({
where: {
userId: req.body.userId,
password: req.body.password
}
});
res.json({
statusCode: 200,
role:userVal[0].role,
userId: userVal[0].userId,
name: userVal[0].name,
token
});
} else {
res.json({
statusCode: 400,
});
}
} catch (error) {
res.json({
statusCode: 400,
});
}
},
getLogin: async (req, res) => {
try {
const user = await AuserModel.findAll({$and: [
{userId: req.body.userId},
{password: req.body.password}
]});
res.send(user);
} catch (error) {
res.json({ message: error.message });
}
},
getUser: async (req, res) => {
try {
const user = await AuserModel.findAll({
where: {
isArchive: 1
}
});
res.send(user);
} catch (error) {
res.json({ message: error.message });
}
},
addUser: async (req, res) => {
try {
const newUser = new AuserModel(req.body);
208
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
await newUser.save();
res.send('User Baru Berhasil Ditambah');
} catch (error) {
res.status(400).json(error);
}
},
editUser: async (req, res) => {
try {
await AuserModel.findOneAndUpdate(
{ _id: req.body.usersId },
req.body
);
res.send('User Berhasil Diubah');
} catch (error) {
res.status(400).json(error);
}
},
Output:
209
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
210
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 12 Juli 2022 - 3 September 2022
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
# ---------------------------------------------------------------------------
# kode dalam app.py atau flask_app.py
# ---------------------------------------------------------------------------
@app.route('/menu')
def dash_menu():
return render_template("launchpad_menu.html")
# ---------------------------------------------------------------------------
# kode dalam app.py atau flask_app.py
# ---------------------------------------------------------------------------
@app.route("/api/fp/3.0/", methods=["GET"])
def api():
import os.path
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
url = os.path.join(BASE_DIR, "static/data_contoh/dataset_dump_tiny.csv")
import pandas as pd
import numpy as np
import json
from flask import Response
a, b, c = request.args.get('a'), \
request.args.get('b'),request.args.get('c')
# print(a,' ',b,' ',c)
# bar = request.args.to_dict()
# print(bar)
persentase_data_training = int(a)
banyak_fitur = int(b)
banyak_hidden_neuron = int(c)
# print(persentase_data_training,banyak_fitur,banyak_hidden_neuron)
minimum = int(dataset.min())
maksimum = int(dataset.max())
# print(minimum,maksimum)
new_banyak_fitur = banyak_fitur + 1
hasil_fitur = []
for i in range((len(dataset)-new_banyak_fitur)+1):
kolom = []
j = i
while j < (i+new_banyak_fitur):
kolom.append(dataset.values[j][0])
j += 1
hasil_fitur.append(kolom)
hasil_fitur = np.array(hasil_fitur)
# print(hasil_fitur)
data_normalisasi = (hasil_fitur - minimum)/(maksimum - minimum)
data_training = data_normalisasi[:int(
211
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
persentase_data_training*len(data_normalisasi)/100)]
data_testing = data_normalisasi[int(
persentase_data_training*len(data_normalisasi)/100):]
# print(data_training)
# Training
is_singular_matrix = True
while(is_singular_matrix):
bobot = np.random.rand(banyak_hidden_neuron, banyak_fitur)
#print("bobot", bobot)
bias = np.random.rand(banyak_hidden_neuron)
h = 1 / \
(1 + np.exp(-(np.dot(data_training[:, \
:banyak_fitur], np.transpose(bobot)) + bias)))
#print("h", h)
#print("h_transpose", np.transpose(h))
#print("transpose dot h", np.dot(np.transpose(h), h))
# print("h_plus", h_plus)
output_weight = np.dot(h_plus, data_training[:, banyak_fitur])
# print(output_weight)
# [none,none,...]
# Testing
h = 1 / \
(1 + np.exp(-(np.dot(data_testing[:, \
:banyak_fitur], np.transpose(bobot)) + bias)))
predict = np.dot(h, output_weight)
predict = (predict * (maksimum - minimum) + minimum)
# MAPE
aktual = np.array(hasil_fitur[int(
persentase_data_training*\
len(data_normalisasi)/100):, banyak_fitur]).tolist()
mape = np.sum(np.abs(((aktual - predict)/aktual)*100))/len(predict)
prediksi = predict.tolist()
response = jsonify({'y_aktual': aktual, \
'y_prediksi': prediksi, 'mape': mape})
response.headers.add("Access-Control-Allow-Origin", "*")
return response
# ---------------------------------------------------------------------------
# kode dalam /templates/launchpad_menu.html
# ---------------------------------------------------------------------------
{% extends "extends/base.html" %}
{% block title %}
<title>Web Data App</title>
{% endblock title %}
{{ self.title() }}
Home
{{ self.title() }}
<button onclick="window.location.href='/'" class="btn btn-outline btn-rounded
btn-info">
<i class="ti-arrow-left m-l-5"></i>
<span>Back Home</span>
</button> Project 1
{{ self.title() }}
Launchpad Project 1
{% block content %}
<div class="row">
212
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
<li><a class="simple-ajax-popup-center"
href="pengmas2022">Smart Irigasi |
Estimasi Waktu Pengairan x Cloud-AI</a></li>
<script type="text/javascript"
src="{{ url_for('static', filename =
'js/mylib_tabel_editable/jquery.min.js') }}"></script>
<script type='text/javascript'>
function renderItem(itemData) {
$('#result').append(itemData, ' ');
}
$(function() {
$('.load-api').click(function(){
$("#result").empty();
$.ajax({
url: "/api/fp/3.0/?a=70&b=3&c=2",
type: "get",
dataType: "json",
// success: function(data) {
// data.mape,
// data.y_aktual.forEach(renderItem),
// data.y_prediksi.forEach(renderItem)
// }
success: function(data) {
$('#result').append('Nilai mape = ',
data.mape, ' <br> ');
</script>
213
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
<p id="result"></p>
</fieldset>
</form>
</ul>
</div>
<script src="https://cdnjs.cloud
flare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</div>
</div>
</div>
<div class="col-md-6 col-lg-3 col-sm-6 col-xs-12">
<div class="bg-primary white-box m-b-0">
<ul class="expense-box">
<li><i class="ti-bar-chart text-white"></i>
<div>
<h1 class="text-white m-b-0">Web Apps</h1>
<h4 class="text-white">Filkom UB 2022</h4>
</div>
</li>
</ul>
<img src="{{ url_for('static', filename = 'img/spark-rev2.png') }}"
class="img-responsive" alt="Responsive image">
</div>
<div class="white-box">
<div class="row">
<div class="col-xs-9">
<h2 class="m-b-0 font-medium">Video Log<sup>TM</sup></h2>
<h5 class="text-muted m-t-0">Pelatihan Multi-Culture
Farming dengan Cloud-AI + IoT API & Web App</h5><br>
</div>
<div class="col-xs-3">
<div class="circle circle-md bg-primary pull-right
m-t-10"><i class="ti-bar-chart"></i></div>
</div>
<div class="btn-group btn-block">
<button aria-expanded="false" data-toggle="dropdown"
class="btn btn-block btn-outline btn-rounded
btn-primary dropdown-toggle waves-effect waves-light"
type="button">View Detail <span
class="caret"></span></button>
<ul role="menu" class="dropdown-menu">
<li><a class="popup-youtube btn btn-danger"
href="www.youtube.com/watch?v=Bp49uOYMNrk">
Video Pengmas | Edukasi ke-1</a></li>
214
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
</ul>
</div>
</div>
</div>
</div>
<div class="col-md-6 col-lg-3 col-sm-6 col-xs-12">
<div class="bg-primary white-box m-b-0">
<ul class="expense-box">
<li><i class="ti-server text-white"></i>
<div>
<h1 class="text-white m-b-0">Web Apps</h1>
<h4 class="text-white">Filkom UB 2022</h4>
</div>
</li>
</ul>
<img src="{{ url_for('static', filename = 'img/spark-rev2.png') }}"
class="img-responsive" alt="Responsive image">
</div>
<div class="white-box">
<div class="row">
<div class="col-xs-9">
<h2 class="m-b-0 font-medium">
Profile Tim<sup>®</sup></h2>
</ul>
</div>
</div>
</div>
</div>
</div>
{% endblock content %}
215
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Output:
(a)
(b)
(c)
(d)
216
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 12 Juli 2022 - 3 September 2022
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
# ---------------------------------------------------------------------------
# kode dalam app.py atau flask_app.py
# ---------------------------------------------------------------------------
@app.route("/testView_dari_project2_sbg_fp", methods=['GET', 'POST'])
def testView_dari_project2_sbg_fp():
template_view = '''
<script type="text/javascript" src="{{ url_for('static', filename =
'js/jquery.min.js') }}"></script>
<div class="row">
<div class="col-md-6">
<div class="white-box">
<h3 class="box-title m-b-0">Prediksi Hasil Pengujian
(misal ambil contoh dari topik Project 2 Kel. Anda):
</h3>
<p class="text-muted m-b-30 font-13">
masukkan nilai parameter Anda </p>
<form action="/testView_dari_project2_sbg_fp"
method="post" class="form-horizontal">
<div class="form-group">
<label for="exampleInputuname" class="col-sm-9
control-label">x1 = Suhu badan*</label>
<div class="col-sm-2">
<div class="input-group">
<input type="text" name="var1" {% if
var1 is defined and var1 %}
value="{{var1}}" {% else %} value="" {%
endif %} class="form-control"
id="exampleInputuname"
placeholder="Skor" required="required">
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputuname" class="col-sm-9
control-label">x2 = Intensitas batuk*</label>
<div class="col-sm-2">
<div class="input-group">
<input type="text" name="var2" {% if
var2 is defined and var2 %}
value="{{var2}}" {% else %} value="" {%
endif %} class="form-control"
id="exampleInputuname"
placeholder="Skor" required="required">
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputuname" class="col-sm-9
control-label">x3 = Intensitas interaksi dgn
lingkungan*</label>
<div class="col-sm-2">
<div class="input-group">
<input type="text" name="var3" {% if
var3 is defined and var3 %}
value="{{var3}}" {% else %} value="" {%
endif %} class="form-control"
id="exampleInputuname"
placeholder="Skor" required="required">
</div>
</div>
</div>
<div class="form-group">
217
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
218
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
{% endif %}
</div>
</div>
<div class="col-md-6">
<div class="white-box mt-8 row">
<div class="justify-around bg-white rounded-lg">
<img class="col-md-3 col-xs-12" src="{{ url_for(
'static', filename = 'img/filkom.png') }}"
alt="logo-filkom">
<img class="col-md-3 col-xs-12" src="{{ url_for(
'static', filename = 'img/conan.jpg') }}"
alt="kartun-conan">
</div>
</div>
</div>
</div>
'''
if request.method == 'POST':
import numpy as np
x = np.array ([
[4, 4, 3, 3, 6, 3, 3],
[6, 6, 9, 7, 8, 7, 6],
[4, 7, 9, 7, 3, 6, 4],
[7, 6, 5, 3, 4, 7, 8],
[4, 3, 6, 6, 5, 7, 3],
[6, 4, 5, 6, 2, 7, 3],
[3, 4, 6, 3, 3, 3, 4]])
y = np.array ([
[5, 2],
[8, 3],
[10, 4],
[5, 2],
[5, 2],
[8, 3],
[5, 2]])
var1_in = float(request.form['var1'])
var2_in = float(request.form['var2'])
var3_in = float(request.form['var3'])
var4_in = float(request.form['var4'])
var5_in = float(request.form['var5'])
var6_in = float(request.form['var6'])
var7_in = float(request.form['var7'])
beta = persamaan_beta(x,y)
219
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Output :
(a)
(b)
220
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
221
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 25 Maret 2023
# Semoga Bermanfaat. Aamiin :D
# ====================================
#
.
..
comp_textarea_fields = ''.join([render_template_string(\
comp_textarea_template, \
num=i) for i in range(1, num_comp_textareas+1)])
comp_hidden_fields = ''.join([render_template_string(\
comp_hidden_template, \
num=i) for i in range(1, num_comp_hidden_fields+1)])
comp_file_fields = ''.join([render_template_string(\
comp_file_template, num=i) \
for i in range(1, num_comp_file_fields+1)])
222
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
{% endautoescape %}
<button type="submit" class="btn btn-primary">Kirim</button>
</form>
</div>
'''
return render_template_string(A_a+html_template_string+Z_z, |
fields_to_html_template_string = my_final_fields_gen_in)
Output :
223
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Daftar Pustaka
224
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
225
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
226
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
227
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
228
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
Biografi Penulis
229
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
230
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
231
Cholissodin, I., Santoso, N., Wihandika, R. C., Kharisma, A. P., Adikara, P. P., Safitri, T. M. M., 2023,
Pemrograman Web x Mobile untuk Smart IoT, Big Data App & Lainnya, Fakultas Ilmu Komputer, UB.
232