Anda di halaman 1dari 240

Judul

Link: https://bit.ly/430jrNv

PEMROGRAMAN WEB x MOBILE UNTUK


SMART IOT, BIG DATA APP & LAINNYA
(Teori & Implementasi)
“Smart & Fast Dev. from Scratch/ Automation to Create App”
Versi 1.01

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

Alhamdulillahhi robbil alamin, puji syukur kehadirat Allah SWT


atas segala rahmat dan karunia-Nya dengan terselesaikannya
penulisan buku ini dengan judul “Pemrograman Web x Mobile Untuk
Smart IoT, Big Data App & Lainnya”. Buku ini mencoba
menggunakan pendekatan sederhana yaitu bagaimana memanfaatkan
Prototype Smart App Template/ Creator atau Software Template /
Generator untuk Pengembangan solusi berbagai kasus real
dikehidupan sehari-hari, dengan cepat, handal dan berkualitas. Hal
tersebut tentunya dengan harapan dapat membantu pembuat program
atau pengembang dalam menyelesaikan project. Di mana nantinya
dapat diarahkan pada Smart App secara general, misal untuk membuat
Smart Web/Mobile App, Smart Big Data App maupun Smart Software
Developer Lainnya. Penulis mengucapkan terimakasih yang sebesar-
besarnya kepada beberapa pihak terkait yang telah membantu baik
secara langsung maupun tidak langsung dalam menyediakan dan
melengkapi materi untuk penyelesaian buku ini:
1. Para penulis artikel di forum, web, blog dan buku yang menjadi
referensi buku ini.
2. Mbak Tria Melia Masdiana Safitri & all tim, yang telah banyak
membantu penulisan dan mengispirasi buku ini. Semoga menjadi
ilmu yang barokah dan bermanfaat. Aamiin. :)
3. Mahasiswa terbaik saya pada semester Genap 2020/2021 MK
Pemrograman Web dan MK lainnya, yaitu Azzara Aji Syahputri,
Muhammad Adib Novan Fanani, I Putu Reditya Permana Putra,
Arief Daffa Abdullah, Kelvin Hendra Wijaya, Firda Adha Cahyanti,
George Alexander Suwito, Safir Rahmahuda Machsun, Ahmad
Kholish Fauzan Shobiry, Nuzulul Athaya, Zildan Isrezki Nurahman
Hernawan, Aldo Friska Darma Putra, Muhammad Fajar Alfath, Putri
Amanda Syafira, Dava Mohammad Hamka, Abi Aryaza, Anggasta
Aji Azhari, Lalu Alfitra Kallatida Muhamad, Syahida Usama Firdaus,
Erland Hilman Fuadi, Michael Stephen Lui, Muhammad Rosyid
Aminuddin, Muhammad Fikri Mustofa Azhari, Faiz Ahmad Sucipto,
Eurico Krisna Wijaya, Ary Muhammad Prayoga, Melati Ayuning
Lestari, Tobing Setyawan.
Semoga kontribusi anda semua menjadi ilmu yang barokah dan
bermanfaat. Aamiin. :). Tidak ada gading yang tak retak, Maka penulis
mohon kritik dan saran untuk perbaikan dan penyempurnaan buku ini.

Malang, 2 Mei 2023


Penulis

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

Gambar 1.1 Sejarah Internet .................................................................... 1


Gambar 1.2 Komponen Internet ............................................................... 1
Gambar 1.3 Perkembangan Teknologi Internet, Web dan Teknologi PC ....... 2
Gambar 1.4 Arsitektur Client-Server ......................................................... 4
Gambar 1.5 Protokol HTTP ....................................................................... 5
Gambar 1.6 Konsep Normaltext vs Hypertext ............................................ 5
Gambar 1.7 Hyperlink vs Hypertext dalam HTML ....................................... 6
Gambar 1.8 Evolusi dari HTTP .................................................................. 6
Gambar 1.9 Ilustrasi Full-Stack Web Development ............................. 7
Gambar 2.1 Struktur Website ................................................................. 11
Gambar 2.2 Pemrograman Web dengan Flask ......................................... 13
Gambar 2.3 Rasmus Lerdorf (Father/Creator of PHP) ............................... 28
Gambar 2.4 Istilah-istilah yang ada pada PHP .......................................... 29
Gambar 3.1 Komparasi GET vs POST vs PUT vs DELETE .............. 41
Gambar 3.2 Contoh Validasi Form .......................................................... 41
Gambar 3.3 Create, Read, Update, Delete (CRUD) ................................... 43
Gambar 3.4 Database ............................................................................ 43
Gambar 3.5 Relational Vs Non-Relational DB ........................................... 44
Gambar 3.6 Ilustrasi beberapa Tools untuk Database NoSQL ................... 45
Gambar 3.7 JavaScript ........................................................................... 46
Gambar 3.8 Tipe Data pada JavaScript .................................................... 47
Gambar 3.9 Conditional Statement ......................................................... 48
Gambar 3.10 JavaScript Library dan Framework ...................................... 55
Gambar 3.11 Alur Kerja AJAX ................................................................. 62
Gambar 4.1 (a) State, (b) Cookies dan (c) Sessions ................................... 71
Gambar 4.2 Authentication dan Authorization ................................... 75
Gambar 4.3 Login dan Signup ........................................................... 77
Gambar 4.4 Login ............................................................................... 77
Gambar 5.1 Ilustrasi Proses File Handling dengan PHP ........................... 80

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.

BAB 1 Intro Pemrograman Web

1.1 Tentang Internet dan Web


1.1.1 Sejarah
Internet adalah jaringan terbesar yang menghubungkan banyak
jaringan di dunia, dan berkomunikasi dengan policy yang disebut
dengan TCP/IP.

Gambar 1.1 Sejarah Internet


Komponen internet terdiri dari tiga hal yaitu, client, server dan
jaringan. Jaringan client server dapat didefinisikan sebagai suatu
arsitektur jaringan komputer dimana client melakukan proses request
data dan server akan memberikan respon berupa data terhadap
request tersebut.

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.

Berikut ini beberapa istilah pada internet yang perlu diketahui.


o TCP (Tranmission Control Protocol), tugasnya adalah
memecah data menjadi potongan berukuran kecil yang
disebut “paket”, dan menggabungkan paket-paket ini ketika
mereka tiba.
o IP (Internet Protocol) digunakan untuk merutekan paket ke
tujuan.
o IP Addressing adalah Alamat IP yang berupa label numerik
yang diberikan atau diset ke perangkat dalam jaringan. Alamat
IP yang popular adalah IPv4, yang menentukan alamat
internet dalam format ###. ###. ###. ###, di mana setiap ###
dapat berjalan dari 0 hingga 255 (28).
o Services (Layanan) dan Port, di mana hubungannya dengan
TCP/IP menentukan banyaknya “channels” yang digunakan
oleh layanan (server) untuk mentransfer data ke/dari client,
saluran ini disebut “port”. Semua layanan internet bekerja di
atas protocol TCP/IP, dan memiliki nomor port dan protokol
khusus mereka sendiri, mislanya Port HTTP adalah ‘80’.
o Domain Name adalah versi label teks dari Alamat IP, dengan
suatu struktur hierarki tertentu. DNS atau Domain Name
Server adalah server yang menyediakan layanan untuk
menerjemahkan antara alamat IP dan nama domain yang
mudah diingat pengguna, misal nama domain
www.google.com, memiliki alamat IP 66.249.89.104.
Perkembangan Teknologi Internet dan Web diikuti juga dengan
Perkembangan Teknologi PC, dan lainnya.

Gambar 1.3 Perkembangan Teknologi Internet, Web dan Teknologi


PC

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.

World Wide Web (www) diperkenalkan 1992 oleh Tim Berners-


Lee yang merupakan layanan untuk akses yang lebih mudah ke
informasi di internet melalui penggunaan GUI. www menggunakan
Hypertext Transfer Protocol (HTTP) yang merupakan protokol
komunikasi standar antara server dan client.
Berikut ini beberapa istilah pada Web.
o Web servers adalah komputer yang menyimpan file halaman
web, dapat berupa satu komputer, atau sekelompok
komputer (misal Linux / Unix menggunakan Apache, dan
Windows menggunakan Internet Information Service (IIS)
serta lainnya.
o Web pages adalah dokumen yang menyimpan informasi,
biasanya ditulis dalam format HyperText Markup Language
(HTML).
o Web Clients adalah komputer yang membaca Web pages.
o Web browser adalah program yang menampilkan halaman
web pada client yang berisi konten (tag Markup HTML, CSS,
dll.) misalnya Chrome, Firefox mengambil halaman web dari
server melalui HTTP request yang berisi URL dari halaman yang
dimaksud.
o Uniform Resource Locator (URL) adalah string yang digunakan
untuk mengidentifikasi sumber resource dari layanan di
internet (yang bukan hanya halaman web, tetapi juga bisa
lainnya).
o HTML, secara sederhana menyediakan pemformatan dan tata
letak teks dan grafik, serta tautan hypertext antar halaman
web.
o Cascading Style Sheet (CSS), memberikan style control, desain
dan pemformatan yang lebih efektif dan powerful.
Client-side juga menjalankan konten web secara dinamis, tetapi
tidak seperti bahasa sisi server, client-side bukanlah server yang
mengeksekusi dan memproses skrip, tetapi client-side hanya yang me-
request. Oleh karenanya, skrip disertakan, misal dalam dokumen
HTML atau XHTML atau ditulis ke file terpisah yang ditauntukan ke
dokumen HTML atau XHTML yang ada.

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.

User yang me-request halaman web dengan skrip tertentu,


maka server mengirimkan dokumen HTML dan skrip ke browser yang
mengeksekusinya dan menyajikan hasil akhir.

Client Side Server Side

Gambar 1.4 Arsitektur Client-Server

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.

1.1.2 Protokol HTTP & Lainnya


HTTP (HyperText Transfer Protocol) adalah protokol yang
mendasari World Wide Web. Dikembangkan oleh Tim Berners-Lee dan
timnya antara 1989-1991, HTTP telah mengalami banyak perubahan,
dengan tetap menjaga kesederhanaan, namun memiliki fleksibilitas
yang tinggi. HTTP telah berevolusi dari protokol awal untuk bertukar
file di lingkungan laboratorium, menjadi labirin Internet modern yang
mendunia, yang dapat membawa gambar, video dalam resolusi tinggi
dan 3D. HTTP merupakan protokol komunikasi standar antara server
dan client.

Gambar 1.5 Protokol HTTP

Berikut ini merupakan perbedaan konsep Normaltext dengan


Hypertext dari HTTP.

Gambar 1.6 Konsep Normaltext vs Hypertext

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.

Di bawah ini merupakan perbedaan Hyperlink dengan Hypertext


dalam HTML.

Gambar 1.7 Hyperlink vs Hypertext dalam HTML


Pada tahun 1989, Tim Berners-Lee saat bekerja di CERN menulis
proposal untuk membangun sistem hypertext melalui Internet.
Awalnya menyebutnya dengan istilah Mesh, kemudian diubah
namanya menjadi World Wide Web selama penerapannya pada tahun
1990. Dibangun di atas protokol TCP dan IP yang terdiri dari 4 blok
bangunan:
1. HTML, adalah suatu format tekstual untuk merepresentasikan
dokumen hypertext.
2. HTTP, adalah suatu protocol sederhana untuk bertukar melalui
akses dokumen-dokumen secara dinamis.
3. Client.
4. Server, dulunya dengan nama httpd.

Gambar 1.8 Evolusi dari HTTP

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.

1.2 Roadmap Belajar Pemrograman Web


1.2.1 Start from the End / Goal dan Your CV
Fokuskan project apa yang akan dibuat atau dijadikan target
pembelajaran dan sesuaikan dengan dasar profil Anda background-
nya apa serta apa kompetensi Anda. Urutan pengembangan web
sangat variatif dan fleksibel, yang dapat dimulai dari pemahaman
tentang cara kerjanya, mampu membedakan antara full-stack, font-
end dan back-end. Kedua terkait percobaan untuk membuat front-end
dasar (Basics: html, css, js. Framework: Django, Flask, React, Laravel,
dll, Styles: Bootstrap, UI material dan Kode Pemrograman). Ketiga
pertimbangkan penggunaan tools tambahan (Kode editor, Server yang
mendukung IaaS untuk DevOps). Keempat percobaan untuk membuat
back-end dasar (DB, dan Kode Pemrograman dengan bahasa tertentu).

Back-End

Front-End
IaaS, dll

Gambar 1.9 Ilustrasi Full-Stack Web Development

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.

1.2.2 Pahami Tips dan Motivasi Survive


Membangun Web App
Strategi yang produktif akan cenderung menghasilkan goal yang
sustain dan produktif juga.
o Berapapun banyak Bug, kesalahan kode program atau error
1M line error atau lebih, hadapi dan jangan takut, gunakan
kata kunci yang tepat pada search engine, chatgpt untuk
mencari solusi atau dengan call friend atau konsultasi dengan
asisten/ instruktur/ guru/ dosen, pastikan sebelum memulai
ngoding awali dengan do’a untuk diri kita, ortu, pengajar,
project Anda dan lainnya serta niat belajar yang baik, hormati
teman, asisten, dan pengajar bukan mengejar nilai semata dan
selalu mencoba mengkondisikan suasana belajar nyaman dan
kondusif meskipun terkadang penuh tantangan.
o Sediakan waktu yang cukup untuk belajar dan non belajar
(untuk diri sendiri, untuk sosialisasi dengan sahabat, saudara,
ayah, ibu kerabat dan keluarga), sesuaikan dengan aktifitas
dan kesibukan masing-masing.
o Belajar secara Bi-directional dari Dasar Teori dan dari Project
besar yang sudah jadi untuk di modifikasi dan dikembangkan.
o Hubungkan project dengan kasus yang lagi tren di Masyarakat
atau dunia usaha, dan mulai mengerjakan dengan hal-hal yang
bagian module terkecil terlebih dahulu.
o Tak ada aplikasi Web/Mobile yang sempurna, untuk
memantapkan ide kreatif misal untuk suatu usulan project
apapun, Anda dapat lakukan tiga cara, Amati yang ada, Tirukan,
lalu Modifikasi atau Kembangkan.
o Gunakan beberapa tool pilihan untuk mengakselerasi
penyelesaian Project, mulai dari IDE untuk Lingkungan
Pengembangan (VSCode, Geany, dll), Untuk Manajemen Hasil
Progress Pengerjaan (Github, Bit Bucket atau lainnya), deploy
di Localhost atau Cloud (Pythonanywhere, Netlify, Vercel,
000webhost, Heroku, AWS Educate dari Kampus Anda dengan
meminta di-invite dosen pengampu Anda / etc) dan lainnya.
o Sering mengasah kemampuan programming, misal dengan
bergabung bersama komunitas Programming Online, misal
Hackerrank, Toki, dan lainnya.
o Aktif membangun track record terbaik dan positif dari project-
project kecil maupun besar dalam bentuk koding open source,

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.

buat buku gratis, dll. dengan mengupload ke Github atau


Linked In atau lainnya sejak di bangku sekolah atau kuliah,
sehingga ke depannya Anda sudah sangat siap untuk melamar
kerja atau membangun wirausaha secara mandiri atau
bersama tim Anda. Dan selain itu track record tersebut juga
akan memudahkan Perusahaan yang Anda lamar untuk
mengetahui profile dan kompetensi Anda.
o Hindari Plagiarisme, respek kepada Author awal penulis kode
program / project dengan mensitasi atau mencantumkan atau
memberikan keterangan di kode program yang Anda gunakan
sebagian atau telah Anda modifikasi dan kembangkan. Anda
juga dapat membangun relasi secara lebih dekat dengan
mengirimkan email kepada Author tersebut, misal minimal
berkenalan dan mengucapkan terimakasih. Selebihnya bisa
juga untuk dicoba diajak untuk Kerjasama.
o Buat jadwal perencanaan penyelesaian Project Web/Mobile
Anda. Saran saya diberikan juga level penyelesaian misal
dengan memberikan level minimal, sedang dan tingginya
seperti apa.
o Apapun kesulitan project-nya, baik dikerjakan secara mandiri
atau dengan tim Anda, kerjakan dengan senang dan Bahagia.
Yakin setelah kesulitan ada kemudahan.

1.3 Tugas Kelompok


1. Jelaskan alur proses dan perbedaan antara client side vs server
side pada Pemrogaman Web dari arsitektur client-server berikut!

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.

2. Jelaskan pengertian, kepanjangan dari istilah-istilah pada


Infrastruktur internet berikut:

Connections (Modem,ISDN, etc)

3. Buatlah video review dengan tema “3 Bahasa Pemrograman


Terbaik untuk Pengembangan Web”!
4. Jelaskan history dan perkembangan dari Internet, Web dan
Teknologi software atau hardware pendukungnya!
5. Jelaskan spesifikasi perbedaan dari alur proses evolusi dari tiap
versi HTTP!

6. Jelaskan makna istilah hypertext pada HTTP dan hypertext pada


HTML!
7. Jelaskan perbedaan dari beberapa istilah berikut:
o HTTP vs HTTPS
o MQTT
o FTP
o SFTP
o CLI
o Bash
o Shell
o Console

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.

BAB 2 Dasar Koding, HTML & CSS

2.1 HTML & CSS


Hyper Text Markup Language (HTML) adalah bahasa yang dapat
digunakan untuk membuat halaman web (markup web), yang dapat
berjalan secara native di setiap browser dan dikelola oleh World Wide
Web Consortium.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
...
</body>
</html>

HTML CSS JavaScript, PHP, etc


The Skeleton The Skin & Clothing The Brains
Gambar 2.1 Struktur Website

Anda dapat membuat struktur situs web dan aplikasi web


dengan teknologi frontend tingkat terendah, yang berfungsi
sebagai dasar untuk style yang dapat ditambahkan dengan CSS dan
fungsionalitas menggunakan JavaScript.

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.

Berikut ini merupakan pengertian dari Tags, Elements, Attributes


pada HTML
• Tag HTML: Bagian awal dan akhir dari suatu elemen HTML, yang
dimulai dengan simbol < dan diakhiri dengan symbol >. Apapun
yang tertulis di dalam < > disebut tag. Contoh: <b> </b>
• Elemen HTML: Elemen yang dibungkus yang merupakan konten di
antara tag. Contoh: <b>This is the content.</b>
• Atribut HTML: untuk mendefinisikan karakter elemen HTML, yang
selalu ditempatkan di tag pembuka sebuah elemen. Dan biasanya
untuk memberikan styling tambahan (atribut) kepada elemen.
Contoh: <p align="center">This is paragraph.</p>
di mana “center” merupakan value dari atribut.

Cascading Style Sheets (CSS) merupakan bahasa style sheet


untuk mengatur beberapa komponen dalam web sehingga lebih
terstruktur dan seragam yang memungkinkan pendekorasian konten,
termasuk tata letak, warna, dan font serta lainnya.
<!DOCTYPE html>
<?php
define('DIR_CSS', 'css/'); //set directory CSS
$namacss = 'style.css';
define('DIR_JS', 'js/'); //set directory JavaScript
$namajs = 'brain.js';
?>
<html lang="en">
<head>
<title>Pert. Ke-3: PHP Dasar </title>
<!-- tempat call resource css, js -->
<link rel="stylesheet" href="<?php echo (DIR_CSS . $namacss); ?>"
type="text/css">
<!-- <link rel="stylesheet" href="css/style.css" type="text/css"> -->
<!-- <?php echo (DIR_CSS . $namacss); echo '<br>' ?> -->

<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.

2.2 Dasar Pemrograman Web dengan


Python (Flask)
Python flask adalah sebuah framework untuk pengembangan
web yang dapat digunakan dalam membuat smart application atau
aplikasi general dengan segala dukungan integrasinya. Meskipun saat
ini termasuk micro-framework, akan tetapi cukup powerfull untuk
membuat web apps baik skala kecil maupun besar. Buktinya, beberapa
perusahaan besar menggunakan Flask untuk sistem mereka.

Gambar 2.2 Pemrograman Web dengan Flask

Kemudian beberapa keunggulan yang ada pada Flask,


diantaranya Terintegrasi untuk dukungan unit testing, proses
debugging & development server yang cepat, Jinja 2 template engine,
Werkzeug yang support Web Server Gateway Interface (WSGI) yaitu
semacam Apache Server tetapi ini menggunakan bahasa
pemrograman Python untuk run Web Apps (Salah satu jenis WSGI
yaitu 'Green Unicorn’ atau disingkat Gunicorn), aman, dokumentasi
cukup lengkap, easy to learn, sweet API dan dukungan penuh untuk

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.

library AI, Machine Learning dan Deep Learning. Langkah-langkah


untuk instalasinya, dapat dipertimbangkan misal menggunakan local
komputer, venv, virtual machice, cloud atau lainnya. Pada bagian ini,
diberikan tahapan detail untuk instalasi Flask pada penyedia layanan
cloud pythonanywhere yang mendukung Platform as a Service (PaaS),
atau cek pada link bit.ly/42b54on dari github.
• Register & setup (pilih yang Free / Gratis)

• Kiks Account > Education (untuk memasukkan misal username


dari dosen pengampu atau trainer Anda)

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.

• Klik Web (Add a new web app)

• Pilih Python versi terbaru, lalu tentukan path untuk workspace


web app project dan klik next

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)

2.2.1 Instalasi Library


Pada proses instalasi library (tambahkan sesuai kebutuhan),
masuk ke menu console > bash dari pythonanywhere,

lalu ketikkan “pip install -r requirements.txt”. Berikut isi dari file


tersebut.
Flask-Cors
Flask-QRcode
PyQRCode
flask_migrate
pyzbar
numba

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.

2.2.2 Dasar Variabel sampai Fungsi


Pada setip koding dasar, dapat langsung dicoba untuk
dimasukkan pada file flask_app.py lalu di klik save, lalu klik icon reload,
tunggu beberapa waktu sampai proses propagasi selesai.

Kemudian dijalankan pada web browser.

#Koding Dasar Flask

# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 19 November 2022
# Semoga Bermanfaat. Aamiin :D
# ====================================
#

from flask import Flask,render_template, Response,redirect,url_for,session,\


request,jsonify
from flask import json, make_response, render_template_string
import sqlite3
from flask_cors import CORS
from io import BytesIO
# import json
import os

app = Flask(__name__, static_folder='static')


CORS(app, resources=r'/api/*')

# app.debug = False
app.secret_key = 'fga^&&*(&^(filkom#BJH#G#VB#Big99nDatakPyICS_ap938255bnUB'

# keterangan:
# "#" adalah untuk comment
# <br> adalah new line
# &nbsp; adalah spasi
# <!-- --> atau <!--- ---> adalah untuk comment

# FrameWeb_atas & FrameWeb_bawah untuk dekorasi web


# agar menjadi Web yang Responsif

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)

# buatlah halaman perkalian


# antara a*b
@app.route('/kali')
def kali():
# membuat perkalian 2 bilangan
a = 10
b = 90
c = a * b

return str(c)

# buatlah tampilan indeks looping 1..10


@app.route('/loop')
def loop():
c = ''
for i in range(10): # i = 0,1,..,9
c +=str(i+1) + ' '

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)

# buatlah tampilan indeks looping 1 sampai 10


# yang ganjil
@app.route('/ganjil')
def ganjil():
c = ''
for i in range(10): # i = 0,1,..,9
if((i+1)%2!=0):
c +=str(i+1) + ' '

return str(c)
# ================ akhir - dasar ke-1 ===============

# ================ awal - dasar ke-2 ================


#

# buat input dari url, untuk penjumlahan misal 2 bilangan


@app.route('/add/<a>/<b>')
def add_ab(a,b):
c = int(a) + float(b)
return 'a + b = ' + str(c)
# return 'a + b = %s' % c
# https://bigdatafga.pythonanywhere.com/add/1/2.5
# hasil => a + b = 3.5

#
# 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)

else: # untuk yang 'GET'


return '''
<html>
<head>
</head>
<body>
<form action="/post_add2" method="post">
Masukkan nilai a = <input type="text" name="a" value="" />
<br>
Masukkan nilai b = <input type="text" name="b" value="" />
<input type="submit" value="Hitung a + b"/>
</form>
</body>
</html>
'''

#
# 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

return render_template('form_add3.html', a_save = a_in, b_save = b_in,


c_save = c)

else: # untuk yang 'GET'


return render_template('form_add3.html')

# isi file templates/form_add3.html


# -------------------------
# <html><head>
# <meta http-equiv="content-type" content="text/html; charset=UTF-8">
# </head>
# <body>
# <form action="/post_add3" method="post">
# Masukkan nilai a = <input type="text" name="a"
{%="" if="" a_save="" is="" defined="" and="" %}=""
value="{{a_save}}" else="" endif="">
# <br>
# Masukkan nilai b = <input type="text" name="b" {%=""
if="" b_save="" is="" defined="" and="" %}="" value="{{b_save}}"
else="" endif="">
# <input type="submit" value="Hitung a + b">
# </form>
# {% if a_save is defined and a_save %}
# <h2>Hasil a + b = {{a_save}} + {{b_save}} = {{c_save}} </h2>
# {% endif %}

# </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()

# start - insert where tabel CloudAI_Air masih kosong


cur.execute('SELECT * FROM CloudAI_Air')
entry = cur.fetchone()

if entry is None:
import numpy as np
import pandas as pd
import os.path

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# Misal skema dataset-nya seperti berikut: => Silahkan dimodifikasi sesuai


case Anda
kolomFitur_X_plus_Target_Y = ['Suhu (X1)','Kelembaban (X2)',
'Curah Hujan (X3)','Angin (X4)','Durasi Air Dlm Menit (Y)']

# set bykData = 3*np.power(10,7)


bykData = 10
bykFitur = len(kolomFitur_X_plus_Target_Y)-1

# Interval atau Variasi nilai fitur


nilaiFitur_Suhu = [17,35]
nilaiFitur_Kelembaban = [70,90]
nilaiFitur_Curah_Hujan = [2,95]
nilaiFitur_Angin = [0,15]
labelTargetY = [0.0,90.0]

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.

# generate isi dataset


content_dataGenerate = np.array([np.arange(bykData)]*(bykFitur+1)).T
df_gen = pd.DataFrame(content_dataGenerate, columns=
kolomFitur_X_plus_Target_Y)

df_gen ['Suhu (X1)'] = np.random.randint(nilaiFitur_Suhu[0],


nilaiFitur_Suhu[1], df_gen.shape[0])
df_gen ['Kelembaban (X2)'] = np.random.randint(nilaiFitur_Kelembaban[0],
nilaiFitur_Kelembaban[1], df_gen.shape[0])
df_gen ['Curah Hujan (X3)'] = np.random.randint(nilaiFitur_Curah_Hujan[0],
nilaiFitur_Curah_Hujan[1], df_gen.shape[0])
df_gen ['Angin (X4)'] = np.random.randint(nilaiFitur_Angin[0],
nilaiFitur_Angin[1], df_gen.shape[0])
df_gen ['Durasi Air Dlm Menit (Y)'] = np.round(np.random.uniform(
labelTargetY[0], labelTargetY[1], df_gen.shape[0]),2)

# save dataframe generate ke *.csv


import os
userhome = os.path.expanduser("~").split("/")[-1]

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)

url = os.path.join(BASE_DIR, "static/data_contoh/Data_CloudAI_Air.csv")

# 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()

# CSV_to_SQLite3 dari file dataset


for i in range(0,len(dataset)):
pushCSVdatasetToDB(dataset.iloc[i][0],dataset.iloc[i][1],
dataset.iloc[i][2],dataset.iloc[i][3],dataset.iloc[i][4])

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():

# buat tabel dan generate data dummy


dasar2_create_database()
dasar2_generate_data()

conn = connect_db()
cur = conn.cursor()

cur.execute("SELECT * FROM CloudAI_Air")


rows = cur.fetchall()

conn.close()

return render_template_string(template_list, rows=rows)

@app.route('/dasar2_edit/<int:number>', methods=['GET', 'POST'])


def dasar2_edit(number):

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')

cur.execute("SELECT * FROM CloudAI_Air WHERE id = ?", (number,))


item = cur.fetchone()

conn.close()

return render_template_string(template_edit, item=item)

@app.route('/dasar2_delete/<int:number>')
def dasar2_delete(number):
conn = connect_db()
cur = conn.cursor()

cur.execute("DELETE FROM CloudAI_Air WHERE id = ?", (number,))

conn.commit()
conn.close()

return redirect('/dasar2_list')

@app.route('/dasar2_add', methods=['GET', 'POST'])


def dasar2_add():
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']

cur.execute("""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 (?, ?, ?, ?, ?)""",
(item_suhu, item_kelembaban, item_hujan, item_angin, item_durasi))
conn.commit()

return redirect('/dasar2_list')

return render_template_string(template_add)

@app.route('/dasar2_add2')
def dasar2_add2():
conn = connect_db()
cur = conn.cursor()

# get data dari iot API


import requests
# from datetime import datetime
# import pytz
# Date = str(datetime.today().astimezone(pytz.timezone('Asia/Jakar-
ta')).strftime('%d-%m-%Y %H:%M:%S'))

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.

# list_kota = ['Jakarta','Los Angeles','Chicago','New York City','Toronto','São


Paulo', \
# 'Lagos', 'London', 'Johannesburg', 'Kairo', 'Paris', 'Zurich',
'Istanbul', 'Moskwa', 'Dubai', \
# 'Mumbai','Hong Kong','Shanghai','Singapura','Tokyo','Sydney']
list_kota = ['Malang']

for nama_kota in list_kota:


each_list_link='http://api.weatherapi.com/v1/
current.json?key=to2181c95fd6d746e9a13313232201040 00543&q='+nama_kota
resp=requests.get(each_list_link)

# print(nama_kota)

#http_respone 200 means OK status


if resp.status_code==200:
resp=resp.json()
suhu = resp['current']['temp_c']
curah_hujan = resp['current']['precip_mm']
lembab = resp['current']['humidity']
angin = resp['current']['wind_mph']
else:
# print("Error")
suhu = '-'
curah_hujan = '-'
lembab = '-'
angin = '-'

# print(nama_kota, 'dengan suhu = ', round(float(suhu),2),'°C', end='\n')

cur.execute("""INSERT INTO CloudAI_Air (suhu_dlm_celcius,


humidity_kelembaban_dlm_persen, precipitation_curah_hujan_dlm_persen,
wind_angin_dlm_km_per_jam) VALUES (?, ?, ?, ?)""",
(suhu, lembab, curah_hujan, angin))

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>

{% for row in rows %}


<tr>
<td>{{ loop.index }}</td>
<td>{{row[1]}}</td>
<td>{{row[2]}}</td>
<td>{{row[3]}}</td>
<td>{{row[4]}}</td>
<td>{{row[5]}}</td>
<td>
<a href="{{ url_for( "dasar2_edit", number=row[0] ) }}">Edit</a> |
<a href="{{ url_for( "dasar2_delete", number=row[0] ) }}">Hapus</a>
</td>
</tr>
{% endfor %}
</table>
{% else %}
Empty</br>
{% endif %}
"""

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.

<h1>Tambah Data CloudAI Air</h1>


<form method="POST" action="{{ url_for( "dasar2_add" ) }}">
Suhu: <input name="suhu" value=""/></br>
Kelembaban: <input name="kelembaban" value=""/></br>
Curah Hujan: <input name="hujan" value=""/></br>
Kecepatan Angin: <input name="angin" value=""/></br>
Durasi Waktu Pengairan / Penyiraman: <input name="durasi" value=""/></br>
<button>Simpan Data</button></br>
</form>
"""

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>
"""

# ================ akhir - dasar ke-2 ===============

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)

2.2.3 Oop menggunakan Class


Pada contoh koding sederhana untuk Object oriented
programming (Oop), yaitu diberikan implementasi algoritma SOM
untuk clustering data.

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.

#Koding Dasar Oop (Class SOM), nantinya dapat


disisipkan pada Flask

# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 2 Juni 2020
# Semoga Bermanfaat. Aamiin :D
# ====================================
#

# Konfigurasi pada sistem


os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64"
os.environ["SPARK_HOME"] = "/spark-2.4.1-bin-hadoop2.7"

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 core dari CPU Google Colab


!lscpu | grep 'Core(s) per socket:'

# 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").

# pada paga google Colab ini CPU-nya hanya 1 core, maka,


# partisinya cukup 2 partisi (yaitu dari "1 core CPU" x "2 task")

# shuffling data
# repartitioning to manage level of parallelism
Core_s_per_socket = 1
Thread_s_per_core = 2

# biasanya Thread_s_per_core diset = 2


byk_partisi = Thread_s_per_core*Core_s_per_socket
input_data2 = input_data2.repartition(byk_partisi)
input_data2.show()

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

#-------------- koding Batch SOM Algorithm ----------------------------#

%%file com/algfromscratch/som/batch_som.py

# Sebelum running code ini, pastikan Anda sudah ada


# pada folder "/content/drive/My Drive/Master Big Data"
"""
os.chdir("/content/drive/My Drive")
#!mkdir 'Master Big Data'
os.chdir("/content/drive/My Drive/Master Big Data")
!pwd
"""

# Bagian ini mengharuskan Anda untuk memiliki pengetahuan dasar tentang


# Apache Spark dan konsep-konsep seperti map, reduce, broadcast,
# rdd, dataframe, dll....

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 __init__(self, net_x_dim, net_y_dim, num_features):


self.network_dimensions = np.array([net_x_dim, net_y_dim])
self.init_radius = min(self.network_dimensions[0], \
self.network_dimensions[1])
print('self.network_dimensions[0] = ',self.network_dimensions[0])
print('self.network_dimensions[1] = ',self.network_dimensions[1])

# initialize weight vectors


self.num_features = num_features
self.initialize()

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))

def train(self, df, num_epochs, resetWeights=False):

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()

# for (epoch = 1,..., Nepochs)


for i in range(1, num_epochs + 1):
radius = self.decay_radius(i)
vis_interval = int(num_epochs/10)
if i % vis_interval == 0:
if fig is not None:
self.show_plot(fig, i/vis_interval, i)
print("SOM training epoches %d" % i)
print("neighborhood radius ", radius)
# print(self.net)
print("-------------------------------------")
broadcast_net = sc.broadcast(self.net)

def train_partition_wrapper(x_size, y_size, num_features):


def train_partition(partition_rows):
partition_net = broadcast_net.value
# ..
return train_partition
# ..

for row in part_sum_rdd.collect():


epoch_sum_num += row['num']
epoch_sum_den += row['den']
self.net = epoch_sum_num/epoch_sum_den

if fig is not None:


plt.show()

def show_plot(self, fig, position, epoch):


# setup axes
ax = fig.add_subplot(2, 5, position, aspect="equal")
ax.set_xlim((0, self.net.shape[0] + 1))
ax.set_ylim((0, self.net.shape[1] + 1))
ax.set_title('Ep: %d' % epoch)

# plot mapping cluster data pada rectangles

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.

for x in range(1, self.net.shape[0] + 1):


for y in range(1, self.net.shape[1] + 1):
ax.add_patch(patches.Rectangle((x - 0.5, y - 0.5), 1, 1,
facecolor=self.net[x - 1, y - 1, :],
edgecolor='none'))
"""
import os
os.chdir("/")
!cp -r /content/drive/My\ Drive/Master\ Big\ Data/com /
"""
from com.algfromscratch.som.batch_som import SOM
som2 = SOM(3,3,3)
byk_epoch = 200 # byk iterasi

som2.train(scaledData, 20)

Output:

Big thanks to Python Flask, Apache Spark, Machine Learning Nepal, etc. :D

Link kode program lengkapnya:


https://github.com/imamcs19/FGA-Big-Data-Using-Python-Filkom-x-Mipa-UB-2022
https://github.com/imamcs19/BigData

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.

2.3 Dasar Pemrograman Web dengan


PHP
PHP ditulis dengan bahasa pemrograman C oleh Rasmus Lerdorf
tahun 1994 yang awalnya untuk memantau resume online-nya dan
terkait informasi pribadi. Untuk alasan tersebut, maka PHP awalnya
adalah singkatan dari "Personal Home Page".

Gambar 2.3 Rasmus Lerdorf (Father/Creator of PHP)

Kemudian Lerdorf menggabungkan PHP + Form Interpreter (FI)


miliknya, lalu merilisnya secara publik sebagai PHP/FI (umumnya
disebut PHP 2.0) pada tanggal 8 Juni 1995.
Dua pemrogram, Zeev Suraski dan Andi Gutmans, membangun
kembali inti PHP, merilis hasil yang diperbarui sebagai PHP/FI 2 pada
tahun 1997. Akronim tersebut secara resmi diubah menjadi PHP:
HyperText Preprocessor, sampai saat ini. (Ini adalah contoh akronim
rekursif: di mana akronim itu sendiri ada dalam definisinya).

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.

Gambar 2.4 Istilah-istilah yang ada pada PHP

Simplicity: menjadikan hal yang rumit / komplek menjadi sederhana,


gampang dipahami dan dikerjakan untuk problem solving.

PHP adalah bahasa skrip open source untuk keperluan umum


yang banyak digunakan dan sangat cocok untuk pengembangan web
dan dapat disematkan ke dalam HTML.
• Kode PHP diapit oleh instruksi yang dimulai “<?php” dan diakhiri
dengan “?>” yang memungkinkan Anda untuk masuk dan keluar
dari "mode PHP“.
• Hal yang membedakan PHP dengan JavaScript (JS) sisi client
adalah bahwa kode tersebut dijalankan di server, menghasilkan
HTML yang kemudian dikirim ke client.
• Client sebagai pengguna hanya menerima hasil keluaran dari
menjalankan skrip PHP, tetapi tidak akan dapat mengetahui
atau melihat skrip PHP yang ada pada aplikasi web tersebut,
bahkan pengembang dapat melakukan konfigurasi web server
untuk memproses semua file HTML dengan skrip PHP, sehingga
pengguna benar-benar tidak mengetahui skrip PHP apa yang
Anda miliki.

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";

$a; //Returns Hello


$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Bar
$$$$$a; //Returns a

$$$$$$a; //Returns Hello


$$$$$$$a; //Returns World

//... dan seterusnya ...//

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: $var1 adalah String


$var2 adalah Bukan String

$var="Selamat datang di Pemrograman Web";


$searchchar="a";
$count="0"; //init

for($i="0"; $i<strlen($var); $i+=1){


if(substr($var,$i,1)==$searchchar){
$count=$count+1;
}
}
echo $count;

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.

Sintaks array PHP:

array(
key => value,
key2 => value2,
key3 => value3,
...
)

// Array paling sederhana,


// maka indeknya otomatis
// dimulai dari 0, 1, 2, 3, 4
$array = array(1, 2, 3, 4, 5);
print_r($array);

Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )

// Mencoba Array Multi-Dimensional


$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensi" => array(
"array" => "foo"
)
)
);

var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensi"]["array"]);

Output: string(3) "bar" int(24) string(3) "foo"

2.3.6 Seleksi (if statements)


if, if..elseif, if..elseif..else, merupakan pernyataan bersyarat
yang akan digunakan jika kondisinya memenuhi nilai True untuk
melakukan suatu tindakan yang berbeda berdasarkan kondisi yang
berbeda.

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;

if ($a > $b) {


echo "a lebih besar dari b";
} elseif ($a == $b) {
echo "a sama dengan b";
} else {
echo "a lebih kecil dari b";
}

Output: a lebih besar dari b

if ($a > $b):


echo $a." lebih besar dari ".$b;
elseif ($a == $b): // Note the combination of the words.
echo $a." sama dengan ".$b;
else:
echo $a." tidak lebih besar dari atau sama dengan ".$b;
endif;

Output: 10 lebih besar dari 4

2.3.7 Handling data dari form HTML


Handling data dari form HTML, misal menggunakan metode
POST.
index.php
<html>
<head>
<title>Handling data dari form HTML</title>
</head>
<body>
<form action=“proses.php” method=“post”>
Masukkan nama Anda: <input name=“myvar”
type=“text”>
<input type=“submit”>
</form>
</body>
</html>

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

Fitur PHP yang paling powerful adalah menangani formulir


atau form HTML. Di mana, setiap elemen form akan secara otomatis
tersedia untuk skrip PHP. Misal melibatkan Variabel dari sumber
eksternal seperti contoh di atas.

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:

for (expr1; expr2; expr3)


statement

// menampikan angka 0 sampai 10


for ($angka=0;$angka<=10;$angka++){
echo $angka ." ";
}

Output: 0 1 2 3 4 5 6 7 8 9 10

// menampikan angka 0 sampai 10 dgn increment +2


for ($angka=0;$angka<=10;$angka+=2){
echo $angka ." ";
}

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;
}
?>

// Mencoba Fungsi Rekursif


// misal utk generate deret Bilangan Fibonacci
function fibonacci($n){
if($n == 0 || $n == 1){
return $n;
}else{
return fibonacci($n-1) + fibonacci($n-2);
}
}
$n = 10;
for($i=0;$i<=$n;$i++){
echo fibonacci($i) . "\n";
}

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.

2.4 Tugas Kelompok


1. Jelaskan sejarah singkat dari Python & PHP, mulai dari penemu
sampai pengembangannya untuk Web Apps & Perbedaan HTML,
XHTML hingga pengembangannya sampai saat ini!
2. Jelaskan apa saja ciri khas Python (Flask/Django) vs PHP yang
sekaligus sebagai keunggulannya, untuk pemrograman Web dari
beberapa istilah berikut:

(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.

(if statements), Handling data dari form HTML, Perulangan, Fungsi


dan Class!
4. Pada operator Python & PHP dikelompokkan menjadi berikut:
o Arithmetic operators
o Assignment operators
o Comparison operators
o Increment/Decrement operators
o Logical operators
o String operators
o Array operators
o Conditional assignment operators
Berikan penjelasan minimal 2 dari operator yang ada.
5. Pada pembahasan string, terdapat istilah-istilah berikut:
o single quoted
o double quoted
o heredoc syntax
o nowdoc syntax
Berikan penjelasan terkait perbedaan dari masing-masing istilah di
atas dan berikan contohnya berdasarkan bahasa Python & PHP!

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.

BAB 3 Form, DB SQL/NoSQL &


JavaScript (JS)

3.1 Pengantar Tentang Form


Salah satu fitur PHP yang terbaik adalah dalam cara menangani
form HTML. Konsep dasarnya adalah bahwa setiap elemen pada form
akan secara otomatis tersedia untuk skrip PHP. Berikut adalah contoh
sederhana form HTML tanpa tag khusus apapun.
1 <form action="action.php" method="post">
2 <p>Your name: <input type="text" name="name" /></p>
3 <p>Your age: <input type="text" name="age" /></p>
4 <p><input type="submit" /></p>
5 </form>

Ketika user mengisi form, lalu menekan tombol submit, maka


halaman action.php akan dipanggil. Di file action.php, halaman Web
Anda akan menuliskan misal seperti berikut:
1 Hi <?php echo htmlspecialchars($_POST['name']); ?>.
2 You are <?php echo (int)$_POST['age']; ?> years old.

Output Hi Joe. You are 22 years old.

3.2 Metode GET dan POST


Konsep HTTP POST requests adalah adanya pemberian supply
data dari client ke server pada bagian message body HTML.
Sedangkan, GET requests menyertakan semua data yang diperlukan
melalui URL. Form HTML dapat menggunakan salah satu metode
dengan menetapkan method = "POST" atau method = "GET" (default)
di tag pertama dari <form .. >. Berikut adalah contoh sederhana form
HTML dengan metode POST vs dengan metode GET.
mypost.php localhost/mypost.php
1 <html>
2 <body>
3 <form action="" method="post">
4 Nama : <input type="text" name="nama"><br>
5 Usia: <input type="text" name=“usia"><br>

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.

6 <button type="submit" name="submit">Submit</button>


7 </form>
8 <?php if (isset($_POST["submit"])) : ?>
9 Hi <?php echo $_POST["nama"]; ?><br>
10 Usia Kamu <?php echo $_POST["usia"]; ?>
11 <?php endif; ?>
12 </body>
13 </html>

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>

Tabel Perbedaan Post vs Get

POST GET

Parameter pada Body Parameter pada URL


Value dari variable tidak terlihat Value dari variable terlihat pada
pada URL, sehingga cocok untuk URL, sehingga tidak cocok
mengirimkan data rahasia untuk mengirimkan data
rahasia
Digunakan untuk meng-update Digunakan untuk mengambil
data dokumen
Bagus untuk cache Tidak bagus untuk cache
Tidak diijinkan untuk mengubah Diperbolehkan untuk digunakan
data pada server mengubah data pada server
Value pada variable tidak Value dibatasi dengan panjang
memiliki Batasan ukuran tertentu, biasanya 255 karakter
panjang data yang dikirimkan

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.

(tdk ada max length), karena (ada max length), karena


dikirimkan melalui body HTML ditampilkan di URL.
Dapat menggunakan tipe data Hanya dapat menggunakan tipe
yang beragram, mulai dari data string, karena ditampilkan
string, numerik dan lainnya di URL.

Gambar 3.1 Komparasi GET vs POST vs PUT vs DELETE

3.3 Validasi form


Validasi dapat diartikan melakukan pemeriksaan dari masukan
yang dikirimkan oleh pengguna, di mana validasi yang tersedia pada
PHP dapat dilakukan pada client side maupun server side.

Gambar 3.2 Contoh Validasi Form

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.

Nantinya form validasi ini dapat dikombinasikan dengan JS


semacam Jquery AJAX, dll. Terkait validasi, pastikan design isian form
Anda sesingkat mungkin, di mana isian yang diminta adalah yang
merupakan informasi paling penting saja. Karena banyak orang yang
tidak suka membuang-buang waktu untuk mengisi form yang ribet
(dan banyak isian). Mereka cenderung meninggalkan halaman
sebelum mengambil tindakan apa pun. Sebagian tujuan utama dengan
adanya validasi form, yaitu data yang masuk akan didapati lebih rapi
dan bersih, field form berfungsi sebagaimana yang seharusnya
dimasukkan user dengan mudah & lancar tanpa perilaku atau
kesalahan yang aneh pada saat penginputan field data di form, serta
untuk mengurangi jumlah pengiriman data yang palsu.
Berikut contoh sederhana untuk validasi email.
1 <form name="form" method="post">
2 <label>Name</label>
3 <input type="text" name="name" /><br />
4 <label>Email &nbsp;</label>
5 <input type="text" name="email" /><br />
6 <label>Phone</label>
7 <input type="text" name="phone" /><br />
8 <input type="submit" name="submit" value="submit" />
9 <div class="<?=(@$msg_sucess=="") ? 'error' : 'green' ;
?>">
10 <?php echo @$msg; ?><?php echo @$msg_sucess; ?></div>
11 </form>

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.

3.4 Implementasi CRUD


CRUD adalah singkatan dari Create, Read, Update, dan Delete,
untuk memanipulasi data dasar untuk database (SQL: Tentang ERD,
Composite dll, macam relasi 1 to 1, 1 to many, many to 1, many to
many, maupun NoSQL). Pada contoh pembahasan ini, digunakan
query pada tabel database MySQL misal melakukan operasi create
(dengan insert), read (dengan select), update, dan delete.

Create Read Update Delete

Gambar 3.3 Create, Read, Update, Delete (CRUD)

Sebelum membuat Implementasi CRUD, pastikan Anda telah


membuat database dan juga tabel yang akan kita gunakan.

Gambar 3.4 Database

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 = ?";

3.5 Sekilas NoSQL


NoSQL (Not Only SQL, atau maknanya kurang lebih adalah "tidak
hanya SQL") adalah kelas yang luas dari sistem manajemen basis data
yang di identifikasikan tidak mematuhi aturan pada model sistem
manajemen basis data relasional. Kelebihan NoSQL salah satunya yaitu
dalam membangun aplikasi bisa lebih cepat, tetapi data yang hasus di
simpan menjadi cukup besar yang arahnya nantinya adalah untuk
komputasi Big Data. Di mana NoSQL ini menggunakan konsep CAP.
❖ Konsistensi (Consistency), yaitu semua node atau instance
menampilkan data yang sama pada waktu yang sama.
❖ Ketersediaan (Availability), Jaminan pada setiap permintaan
data, ada informasi tentang apakah berhasil atau tidak.
❖ Partition Tolerance, dapat terus beroperasi, karena adanya
cadangan data yg direplikasi di seluruh node untuk fault
tolerance, misal adanya node yang off.

Gambar 3.5 Relational Vs Non-Relational DB

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.

Ilustrasi beberapa Tools untuk Database NoSQL, seperti


mongoDB, Cassandra, Hbase, Firebase, TiDB dll sebagai berikut.

Gambar 3.6 Ilustrasi beberapa Tools untuk Database NoSQL

Pada Gambar di atas, berdasarkan Teorema CAP, ternyata


penyimpanan data terdistribusi sangat tidak mungkin menyediakan
lebih dari dua fungsionalitas secara bersamaan, pilihannya hanya (CA
atau CP atau AP), Kenapa bisa demikian?
Perbandingan Database (DB) dengan konsep Terdistribusi vs
Terpusat (Centralized).
Distributed Centralized
Terdiri dari beberapa DB files Hanya berupa DB file
pada lokasi yang berbeda-beda tunggal
Akan terus beroperasi dan
Akan terjadi kegagalan atau
mengijinkan beberapa users
kelambatan jika beberapa
untuk akses dan memanipulasi
user mengakses file yg sama
data baik yg sama maupun
secara terus menerus
berbeda
Akses files lebih cepat karena
dikirim dari lokasi terdekat dari Akses file bisa lebih lambat
user
Sekali sistem down, maka
Sistem terus berjalan meski ada
single sistem ada mengalami
sebagian system yang down
kegagalan menyeluruh
harus melakukan sinkronisasi Cukup update atau perbarui
data pada DB seluruh node data pada single sistem

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 JavaScript (JS) untuk Dasar Koding


Berbasis Node JS
JavaScript adalah scripting language, interpreter dan high level
programming yang memungkinkan untuk melakukan pembuatan
konten web baik berupa Update State maupun UI Event secara lebih
dinamis dan interaktif, misal untuk mengontrol multimedia, animasi
gambar, dan lainnya pada aplikasi web atau situs web.

Gambar 3.7 JavaScript

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 ❌

for (var i = 0; i < 5; i++) {


// i accessible ✔
}
// ii accessible ✔

• Konstanta adalah variabel dengan nilai tetap yang tidak berubah


selama waktu proses eksekusi.
const matkul;
matkul =‘Pemrograman Web';

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.

• Tipe Data pada JavaScript

Gambar 3.8 Tipe Data pada JavaScript


• Objek adalah entitas mandiri (standalone) dengan properti dan
tipe datanya sangat mirip dengan objek-objek yang ada dalam
kehidupan nyata. Misal Objek Mahasiswa dengan property, misal
NIM: 110, Nama: Brone, IPK: 4.0, Motto: Tangguh Bereputasi,
Membangun Negeri.
// Berikut contoh deklarasi Objek
// menggunakan JS

let mhs= {
nim: 110,
nama: ‘Brone’,
Ipk: 4,
Motto: ‘Tangguh Bereputasi, Membangun Negeri'
};

• Array adalah struktur data yang berisi list elemen yang


menyimpan banyak nilai dalam satu variabel tunggal.
/* Misal, Daftar MK dlm KRS Mahasiswa dapat dimasukkan
ke dalam array */
let krs=[];
krs=[‘PemWeb’,’RPL’,’JST’,’Jarkom’];

// contoh untuk aksenya elemen pertama


krs[0]

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.

• Fungsi adalah blok kode terorganisir yang secara standar memiliki


input, logic, dan output dalam bentuk return atau non-return, di
mana fungsi ini dapat digunakan kembali dengan value argumen
yang berbeda-beda.
function luas(panjang, lebar) {
return panjang*lebar;
}

Dari contoh tersebut, nama fungsinya “luas”, dan terdapat 2


parameter “panjang” dan “lebar” sebagai argumennya
// contoh untuk memanggil fungsinya
luas(2,3);

• Conditional statement adalah aturan tunggal atau lebih yang


dilakukan jika kondisinya bernilai True.

Gambar 3.9 Conditional Statement

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.

function inventory(barang, jumlah) {


if (!barang) return;
const q = jumlah || 1; // if jumlah barang
// tidak diisi, default dgn 1

document.write('Terdapat '+ q + ' jenis ‘ + barang +


'! <br>');
}

//Hasil jika kondisi ada nilai //null/undefined pada pa-


rameternya
inventory('obat'); // Output, Terdapat 1 jenis obat!

inventory('vaksin', 2); // Output, Terdapat 2 jenis


vaksin!

<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.

• Loop untuk menjalankan perulangan pada blok tertentu sampai


kondisi akhir. Ada tiga macam loop di JS.
// while loop
let i=0;
while(i < 7) {
document.write("Angka " + i + "<br>");
i+=1;
}

// 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>");
}

• Switch statement digunakan untuk melakukan tindakan yang


berbeda berdasarkan kondisi yang berbeda.
function Fnswitch(warna) {
// use switch case untuk search base warna
switch (warna) {
case 'merah':
return ['apel', 'tomat'];
case 'kuning':
return ['pisang', 'melon'];
case 'ungu':
return ['anggur', 'terong'];
default:
return [];
}
}

//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.

// Mengubah Switch statement dengan Map yg punya pair


key value
// =======================================
const buahBaseWarna = new Map()
.set('merah', ['apel', 'tomat'])
.set('kuning', ['pisang', 'melon'])
.set('ungu', ['anggur', 'terong']);

function FnMap(warna) {
return buahBaseWarna.get(warna) || [];
}

//Hasil FnMap
document.write(FnMap(null)+' <br>'); // []
document.write(FnMap('merah')); // ['apel', 'tomat']

// Mengubah Switch statement menjadi object literal


// =======================================
// use object literal untuk search base warna
const buahBaseWarna = {
merah: ['apel', 'tomat'],
kuning: ['pisang', 'melon'],
ungu: ['anggur', 'terong']
};

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.

// Mengubah Switch statement Array.filter


// =======================================
// use Array.filter untuk search base warna
const buahArr = [
{ name: 'apel', warna: 'merah' },
{ name: 'tomat', warna: 'merah' },
{ name: 'pisang', warna: 'kuning' },
{ name: 'melon', warna: 'kuning' },
{ name: 'anggur', warna: 'ungu' },
{ name: 'terong', warna: 'ungu' }
];

function FnArrayFilter(warna) {
return buahArr.filter(f => f.warna == warna);
}

var filterednames = buahArr.filter(function(obj) {


return (obj.warna == 'merah');
});

//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']

• Print atau Display untuk menampilkan hasil output.


❖ Writing into an HTML element, using innerHTML.
❖ Writing into the HTML output using document.write().
❖ Writing into an alert box, using window.alert().
❖ Writing into the browser console, using console.log().
Using innerHTML:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>

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>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>

Using document.write():

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<button type="button" onclick="document.write(5 +


6)">Try it</button>

</body>
</html>

Using window.alert() atau alert:

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<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>

<button onclick="window.print()">Print this page</but-


ton>

</body>
</html>

3.6.3 JS Library & Framework


JavaScript menjadi sangat populer, salah satu alasannya adalah
karena banyaknya JavaScript Library dan Frameworks yang dapat
digunakan dengan mudah, misal seperti berikut:
o Node.js untuk mengembangkan aplikasi web server-side secara
end-to-end hanya dengan JavaScript.
o AngularJS adalah framework web dev.-nya Google yang
menyediakan banyak fitur desain untuk pengembangan aplikasi
modern dengan cepat.
o ReactJS adalah JavaScript framework, di mana pengelola
utamanya yaitu Facebook yang sudah diterapkan pada Aplikasi
Facebook dan Instagram, yang terbukti handal meski dengan
arus akses yang tinggi.
o MeteorJS digunakan untuk pengembangan back-end dengan
lebih cepat.

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.

o jQuery digunakan untuk membuat situs Web menjadi lebih


interaktif.
o TensorFlow.js adalah library untuk pengembangan Machine
Learning (ML) model dalam JavaScript.
o dll.

Gambar 3.10 JavaScript Library dan Framework

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>

CDN juga seperti tempat library online yang disediakan oleh


suatu perusahaan pengembang. Contoh JS + CDN Tensorflow (TF)
untuk beberapa case ( https://imamcs19.github.io/cs-ds/reg/ ):
• Koding Dasar | Menghitung Regresi & Visualisasi
1 <script
2 src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0">
3 </script>
4
5 <input type="button" id="myButton321" style="display:
6 none;" value="Run All" onclick="{
7
8 const trainX = [
9 1.0,
10 4.4,
11 3.1

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);

My HTML Document Document Object Model (DOM)

Document

HTML

head body

title h1 div id = “div1” div id = “div2”

p p class = “p2”
My HTML Document

P Tag 1 P Tag 2

API = DOM + JavaScript

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

onchange suatu elemen HTML telah diubah


onclick user mengklik elemen HTML
onmouseover user menggerakkan mouse ke atas elemen HTML

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.

onmouseout user menjauhkan mouse dari elemen HTML


onkeydown user menekan tombol keyboard
onload browser telah selesai memuat halaman

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>

<p>Contoh Fungsi Fibonacci:</p>


<p id="id"></p>

<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

Tambahan, var vs let


var x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10

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>

<p>Pesan akan muncul setelah 2 detik</p>

<h1 id="id"></h1>

<script>
setTimeout(myFunction, 2000);
function myFunction() {
document.getElementById("id").innerHTML = "I love Web Pro-
gramming !!";
}
</script>

</body>
..

3.6.8 JS AJAX & Fetch API


AJAX = Asynchronous JavaScript And XML bukan suatu bahasa
pemrograman, AJAX mengkombinasikan Objek XMLHttpRequest
(XHR) bawaan browser (untuk request data dari ke web server ke web
browser) + JavaScript dan HTML DOM (untuk menampilkan atau
menggunakan data).

Gambar 3.11 Alur Kerja AJAX

AJAX memungkinkan halaman web diperbarui secara asinkron


dengan, misal berupa; membaca data dari server web setelah halaman

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.

dimuat, bertukar data dengan server web di belakang layer/


background, Lalu mampu update/ memperbarui bagian-bagian dari
halaman web, tanpa memuat ulang seluruh halaman.
..
<body>
<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Con-
tent</button>
</div>

<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>
..

xhr.status, (umumnya) untuk menentukan apakah request ber-


hasil (200) atau tidak. sedangkan xhr.readyState untuk menge-
tahui status permintaan, seperti "belum dikirim" (0),
"selesai dan telah diterima" (4), dll. Server bertanggung
jawab untuk menyediakan keadaan status, sedangkan user agent
menyediakan readyState.

Fetch API interface memungkinkan web browser membuat


HTTP requests ke web server tanpa perlu menggunakan
XMLHttpRequest. Fetch API interface memungkinkan web browser
membuat HTTP requests ke web server tanpa perlu menggunakan
XMLHttpRequest.

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>

let file = "my_fetch.txt"

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");

async function getText(file) {


let x = await fetch(file);
let y = await x.text();
document.getElementById("id").innerHTML = y;
}
</script>

</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.

3.7 Tugas Kelompok


1. Jelaskan fungsionalitas dari beberapa elemen berikut:
• <form> digunakan untuk ..
• action = “..”
• method = “..”
• <input type = “..”
• isset($_POST["submit"]) ubah ke Python (flask / django,
cek contohnya dari sub bab 6.2.1 dari file flask_app.py)
atau Node JS (cek contohnya dari sub bab 7.8.2)
• $_GET["nama"] ubah ke Python (flask / django, cek
contohnya dari sub bab 6.2.1 dari file flask_app.py) atau
Node JS (cek contohnya dari sub bab 7.8.2)
• localhost/myget.php?nama=..&usia=.. ubah ke Python
(flask / django, cek contohnya dari sub bab 6.2.1 dari file
flask_app.py) atau Node JS (cek contohnya dari sub bab
7.8.2)
2. Jelaskan perbedaan antara method Get vs Post! Dan bagaimana
hasil yang dijalankan setelah proses submit Ketika tag form
memiliki action =“” kosong vs action="/contoh_exp_matrix"
(python) atau action = “suatu_skrip_tertentu.php” (php) yang
diisi dengan suatu skrip tertentu?
3. Jelaskan kenapa pada form HTML sampai versi HTML5/XHTML
tidak dibuat mendukung method Put dan Delete, dan apa
perbedaan get vs post vs put vs detele pada Web API?
4. Berikan contoh skrip python (flask/django), node js dan php untuk
koneksi DB ke server dengan 5 cara berikut, dan jelaskan juga
tiap satu baris atau beberapa baris kodenya:
• SQLite
• MongoDB
• MySQLi (object-oriented)
• MySQLi (procedural)
• PDO

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.

5. Perhatikan tabel berikut:

Jelaskan tentang “Pagination” pada bagian yang ditandai


dengan shape biru!
6. Perhatikan tampilan form berikut:

Buat Script HTML dengan atau tanpa mendukung Responsive


Web Design dari form di atas secara dinamis menggunakan JS
DOM integrated dengan file *.csv, yang dapat secara otomatis
mengenerate dan menyimpan dalam format *.html dan *.py
(python flask/django) atau *.php yang mana masing-masing ada
kode sederhana yang digenerate misal dengan menyisipkan,
misal “echo “Hello smart code Web”; ” atau lainnya sesuai
kreatifitas!
Di mana, setiap nama field atau nama parameter beserta tipe
datanya dapat diload dari file *.csv untuk dapat ditambah,
dimodifikasi serta dihapus, dan jika pada file *.csv tersebut field
isiannya ditambah dari JS DOM misal dengan menambah field
Address atau field lainnya, maka akan otomatis aktif elemen scroll
ke bawah pada HTML tersebut khusus hanya pada region yang
berwarna putih.

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.

7. Jelaskan pengertian dari beberapa istilah berikut:


❖ NoSQL
❖ Teorema CAP
8. Sebuntukan Tools atau Software DB yang support untuk
Pengembangan Web
❖ SQL
❖ NoSQL
❖ SQL + NoSQL
9. Perhatikan ilustrasi CAP berikut:

a. Kenapa pada penyimpanan data terdistribusi sangat tidak


mungkin menyediakan lebih dari dua fungsionalitas secara
bersamaan, pilihannya hanya (CA atau CP atau AP), Kenapa
bisa demikian, Jelaskan!
b. Jelaskan Perbandingan Database (DB) dengan konsep
Terdistribusi vs Terpusat (Centralized)?
c. Kenapa NoSQL dinilai sangat cocok juga untuk me-manage
data yang berukuran besar yang nantinya bisa diarahkan ke
Big Data?
10. Jelaskan mengapa membuat aplikasi Web dengan menggunakan
NoSQL bisa lebih cepat dari pada SQL, dan hal apa yang menjadi
keterbatasannya!
11. Buatlah Aplikasi backend Web App sederhana dengan topik
bebas, sesuai dengan kreatifitas Kelompok Anda yang dapat
digunakan untuk melakukan penyimpanan data pada
sqlite/mySQL/MongoBD yang dilengkapi juga dengan CRUD!

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.

12. Jelaskan pada kondisi bagaimana sehingga dibutuhkan untuk


melakukan integrasi data pada SQL ke NoSQL dan sebaliknya!
13. Jika pada aplikasi Web yang skala kecil vs skala enterprise,
manakah yang sebaiknya digunakan, DB SQL atau NoSQL atau
yang support keduanya?
14. Jawablah beberapa pertanyaan berikut!
o Jelaskan sejarah singkat JS, dan siapakah yang
menggagasnya pada tahun berapa?
o Kenapa JavaScript (JS) disebut sebagai High Level
Programming Language?
o Kenapa JavaScript (JS) disebut sebagai interpreter?
o Apakah sama JS dengan Java Programming Language,
jelaskan perbedaannya?
o Jelaskan perbedaan JS Lib. Vs JS Framework dan sebutkan
contoh masing-masing!
o Apakah JS mendukung terminology OOP?
o Sejak kapan JS support pada server side, siapakah
penggagasnya?
15. Dari gambar berikut jelaskan keunggulan JS, jika dibandingkan
dengan Programming lainnya, dan keunggulan dari Aplikasi Web
atau situs Web jika menggunakan JS, bukan hanya HTML dan CSS!

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.

16. Jelaskan Javascript (JS) dari beberapa istilah berikut jika


dihubungkan untuk pengembangan Web App atau Hybrid Web
/Mobile App dan khusus untuk 3 point awal, berikan contoh case
sederhana beserta implementasinya:
o JS standard
o CDN TensorFlow.js
o jQuery
o JS Framework yang support pada client side dan server side
(Node.js) vs Native Script vs lainnya.

17. Berdasarkan contoh koding JS standard dengan atau tanpa CDN,


misal dengan CDN TensorFlow.js, buatlah koding untuk
melakukan komputasi berikut:
o Konversi antar satuan suhu dari Celcius (C), Fahrenheit (F)
dan Reamur (R)
o Operasi Matrik Dasar:
• Transpose, Penjumlahan,
• Perkalian dan Inverse
o Membuat Kalkulator Scientific

18. Perhatikan JS DOM berikut:


..
<body>
<p class=“id">Belajar Form</p>
<p class=“id">Belajar DB MySQL</p>
<p class=“id">Belajar JS</p>
<p class=“id">Belajar Ajax</p>

<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);

Bagaimana hasil yang ditampilkan jika pada “console..” diubah


dengan “setInterval..” di atas!
19. Buatlah Web “Students App” CRUD sederhana yang datanya pada
database sqlite/mysql/mongodb dengan kode python
(flask/django), php / full JS (Lib & Framework Express JS) + HTML
+ CSS, seperti tampilan berikut untuk manage data Mahasiswa
secara dinamis dan interaktif menggunakan konsep full stack!

20. Berikan contoh JS Callback vs Promise berdasarkan timeout!


21. Buatlah auto sender berupa “Scheduled tasks” minimal mampu
mengirimkan pesan secara otomatis 1x dalam 24 jam ke mobile
phone berupa “pesan kondisi cuaca/ notif jadwal kuliah/ lainnya
sesuai kreatifitas Anda” berbasis Web App dengan python
(flask/django), php dan node js yang dihubungkan dengan API /
lainnya, dan berikan contoh penerapannya jika menggunakan
third-party berikut.
o Twilio
o Pushbullet / etc

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

4.1 Tentang State


Umumnya, state management digunakan untuk bagaimana
menyimpan state aplikasi di browser user (dengan cookie), atau di
server itu sendiri (dengan sessions). Di dalam PHP, state management
memungkinkan untuk menyimpan state tertentu dari aplikasi web baik
di server itu sendiri, atau di browser user. Di mana PHP menyediakan
dua teknik berbeda untuk mengelola state dalam aplikasi web, yaitu:
❖ PHP Sessions: Server Side State Management
❖ PHP Cookies: Client Side State Management
State dalam hal ini berarti kemampuan PHP dalam
mempertahankan (seperti menyimpan secara temporary) nilai
variabel tertentu dan melacak (keep track) pengguna yang masuk ke
system pada aplikasi atau situs web.

(a)

(b) (c)

Gambar 4.1 (a) State, (b) Cookies dan (c) Sessions

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.

Berikut adalah contoh sederhana set dan cara akses Cookie.


1 <?php localhost/mycookie.php
2 setcookie(“user”, “Bro PHP”);
3 ?>
4
5 <html>
6 <body>
7 <?php
8 if (!isset($_COOKIE[“user"])){
9 echo “Maaf, cookie tidak ditemukan”;
10 } else{
11 echo “<br/>Cookie value:” . $_COOKIE[“user"];
12 }
13 ?>
14 </body>
15 </html>

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

Delete Cookie, Jika expiration date di-set dengan waktu masa


lalu, maka cookie akan dihapus.
1 <?php
2 // misal dengan set waktu 1 jam sebelumnya
3 setcookie(“user”, “Bro PHP”, time()-3600);
4 ?>

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();

// set varibel session dengan suatu nilai


$_SESSION["session_variable_name"] =
session_variable_value;

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.

5 // set variabel session dengan suatu nilai


6 $_SESSION["username"] = “imamcs";
7 $_SESSION["userID"] = 19;
8 ?>
9
10 <html>
11 <body>
12 <a href=“mysessions.php">Halaman Sessions</a>
13 </body>
14 </html>

Pada contoh di atas, dibuat hyperlink html ke halaman lain,


misal “mysessions.php” yang, akan mendemokan bagaimana sessions
menyimpan data dan dapat digunakan di seluruh halaman. Berikut
adalah contoh Remove data yang disimpan pada Sessions.
1 <?php
2 session_start();
3
4 echo "Hello " . $_SESSION["username"];
5
6 // unset value dari variabel session
7 session_unset();
8
9 // perhatikan hasil output setelah di-unset
10 echo $_SESSION["username"];
11
12 ?>

Berikut adalah contoh Destroy Sessions.


1 <?php
2 session_start();
3
4 echo "Hello " . $_SESSION["username"];
5
6 // session_destroy
7 session_destroy();
8
9 // perhatikan hasil output setelah di-session_destroy
10 echo $_SESSION["username"];
11
12 ?>

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.

4.4 Authentication: Login dan logout, vs


Authorization
Authentication terdiri dari login dan logout, sedangkan
Authorization yaitu terkait dengan siapa yang diijinkan untuk
mengakses apa.

Gambar 4.2 Authentication dan Authorization

Pada Authentication, misal kita siapkan 3 file, yaitu mylogin.php,


index.php, dan mylogout.php. Berikut potongan skripnya:
1 // login_user.sql
2
3 CREATE TABLE `login_user` (
4 `id` int(11) NOT NULL,
5 `name` varchar(60) NOT NULL,
6 `user_name` varchar(20) NOT NULL,
7 `password` varchar(20) NOT NULL
8 ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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>

Gambar 4.3 Login dan Signup

1 <?php
localhost/mylogout.php
2 session_start();
3 unset($_SESSION["id"]);
4 unset($_SESSION["name"]);
5 header("Location:mylogin.php");
6 ?>

Gambar 4.4 Login

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.

4.5 Tugas Kelompok


1. Jelaskan pengertian dari beberapa istilah berikut:
❖ state management vs state
❖ Python Flask/Django, Node JS, dan PHP terkait Sessions vs
Python Flask/Django, Node JS, dan PHP terkait Cookies
2. Perhatikan ilustrasi gambar berikut!

Cookies Sessions
Berikan contoh dari study kasus dari suatu Web yang
menggambarkan terkait Cookies vs Sessions!

3. Buatlah halaman Sign Up/Register dan Auth. (login dan logout)


dengan Python Flask/ Django ( cek contohnya pada sub 6.2.1 dari
file flask_app.py terkait session setelah login/logout ), Node JS
dari MERN to LERN (sqlite + express + react + nodejs) Stack ( cek
contohnya pada sub 7.8.2 ) dan PHP Sessions dengan atau tanpa
Sign In with Facebook/ Twitter/ Gmail.

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.

4. Buatlah Web App sederhana dengan Python (Flask/Django), PHP


dan ExpressJS (Node JS) yang dilengkapi tabel untuk membedakan
Authorization antara Admin dengan user biasa, dengan studi kasus
bebas sesuai dengan kreatifitas Anda!

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.

BAB 5 Operasi File, OOP & MVC

5.1 Pengantar Tentang Operasi File


Dalam mengembangkan aplikasi web, kita sering membutuhkan
pengelolaan data eksternal dari file mulai dari membaca, menulis, dll.
Sehingga operasi file ini sangat penting untuk dipahami. Pada PHP,
Operasi file yang utama adalah create file, membaca isinya, menulis ke
dalam file hingga menambahkan data ke file serta menutup file.

Menampilkan data dari


file atau dengan HTML
Browser
form untuk mengambil
data yang di-inputkan
user untuk ditulis dalam
bentuk file.txt

Kode PHP dapat digunakan


untuk read dan write suatu file

• index.php
• Otherfile.php
Server
• file.txt (read atau
write data)

Gambar 5.1 Ilustrasi Proses File Handling dengan PHP

Gambar 5.2 Penanganan File dengan PHP

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.

Berikut contoh sederhana Reading a file.


1 <html>
2 <head>
3 <title>Reading a file using PHP</title>
4 </head>
5 <body>
6
7 <?php
8 $filename = “file.txt";
9 $file = fopen( $filename, "r" );
10
11 if( $file == false ) {
12 echo ( "Error in opening file" );
13 exit();
14 }
15
16 $filesize = filesize( $filename );
17 $filetext = fread( $file, $filesize );
18 fclose( $file );
19
20 echo ( "File size : $filesize bytes" );
21 echo ( "<pre>$filetext</pre>" );
22 ?>
23
24 </body>
25 </html>

Output:

Berikut contoh sederhana Writing a file.


1 <?php
2 $filename = "/home/user/guest/newfile.txt";
3 $file = fopen( $filename, "w" );
4 if( $file == false ) {
5 echo ( "Error in opening new file" );
6 exit();
7 }
8 fwrite( $file, "This is a simple test\n" );
9 fclose( $file );
10 ?>
11 <html>

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:

5.1.1 File upload & download


Operasi unggah (upload) dan unduh (download) merupakan
bagian yang cukup pokok dalam pengelolaan berkas (files) dalam
interaksi yang dilakukan oleh pengguna aplikasi web. Berikut contoh
sederhana Upload a file.
1 <html>
2 <form enctype="multipart/form-data" action=""
id="wb_Form1" name="form" method="post">
3 <div class="form-group">
4 <input type="file" name="photo" id="photo"
class="file">
5 <div class="input-group col-xs-12">
6 <span class="input-group-addon"><i
class="glyphicon glyphicon-picture"></i></span>
7 <input type="text" class="form-control input-lg"
disabled="" placeholder="Upload Image">
8 <span class="input-group-btn">

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.

9 <button class="browse btn btn-primary input-lg"


type="button"><i class="glyphicon glyphicon-search"></i>
Browse</button>
10 </span>
11 </div>
12 </div>
13 <div class="form-group">
14 <div class="input-group ">
15 <input type="submit" class="btn btn-success"
name="submit" value="Submit">
16 </div>
17 </div>
18 </form>
19 </html>

Gambar 5.3 File Upload

Berikut contoh sederhana Download a file.


1 <?php
2 function output_file($file, $name, $mime_type = '')
3 {
4 if (!is_readable($file))
5 die('File not found!');
6
7 $size = filesize($file);
8 $name = rawurldecode($name);
9 $known_mime_types = array(
10 "pdf" =--> "application/pdf",
11 "txt" => "text/plain",
12 "html" => "text/html",
13 ..
14 "php" => "text/plain"

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 ?>

Gambar 5.4 Download

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.

5.1.2 Operasi file & direktori


PHP juga dapat digunakan untuk memanipulasi direktori untuk
operasi seperti melihat isi direktori, membuat / membuka /
menghapus direktori dan lainnya. Fungsi dasar PHP terkait direktori:
❖ mkdir(): To make new directory.
❖ opendir(): To open directory.
❖ readdir(): To read from a directory after opening it.
❖ closedir(): To close directory with resource-id returned while
opening.
❖ rmdir(): To remove directory.
mkdir($directory_path,$mode,$recursive_flag,$context
);

$ directory_path: menentukan path.


$ mode: Parameter mode menerima nilai oktal untuk mode
aksesibilitas direktori, misal 0777.

Synta $ recursive: Parameter yang memiliki nilai true atau


x false, yang mengizinkan atau menolak untuk membuat
direktori bersarang.

$ context: untuk menentukan spesifik protokol atau


lainnya.

Fungsi mkdir mengembalikan data boolean, yaitu true


Ketika eksekusi berhasil, false sebaliknya.

Gambar 5.5 PHP directory Function

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.

Berikut contoh koding sederhana untuk membuat suatu Listing


Directory Content dengan PHP.
❖ Step 1: Opening directory.
❖ Step 2: Membaca isi direktori untuk di-list satu demi satu
contentnya menggunakan loop di PHP.
1 <?php
2 mkdir("my_dir",0777);
3 /*Creating files into my_dir*/
4 $file_pointer1 = fopen("my_dir/mkdir.txt","x");
5 $file_pointer2 = fopen("my_dir/rmdir.txt","x");
6 fclose($file_pointer1);
7 fclose($file_pointer2);
8 $directory_handle = opendir("my_dir");
9 while($directory_item = readdir($directory_handle)) {
10 echo $directory_item . "<br>";
11 }
12 closedir($directory_handle);
13 ?>

Output:
.
..
mkdir.txt
rmdir.txt

Berikut contoh sederhana Remove Directory dengan PHP.


1 <?php
2 $directory_handle = opendir("my_dir");
3 while($directory_item = readdir($directory_handle)) {
4 @unlink("my_dir/".$directory_item);
5 }
6 closedir($directory_handle);
7 rmdir("my_dir");
8 ?>

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.

5.2 Oop menggunakan PHP


PHP adalah bahasa pemrograman yang skrip-nya dijalankan
secara server-side, untuk pengembangan aplikasi atau situs web
maupun untuk tujuan umum. Pemrograman Berorientasi Objek
menggunakan PHP (PHP OoP), telah ada pada versi PHP5, yang
membantu dalam membangun aplikasi web yang kompleks, mulai dari
skala standard sampai enterprise dan dapat mudah untuk digunakan
kembali untuk proses pengembangan berikutnya maupun ketika
maintenance atau lainnya. Berikut beberapa komponen OoP dalam
PHP:
❖ Class, dapat disebut sebagai cetakan atau template tipe data yang
di-define oleh programmer, yang mencakup fungsi lokal serta data
lokal, untuk membuat banyak instance dalam jenis yang sama-
sama dari satu kelas objek.
❖ Object, Contoh individu yang struktur datanya yang ditentukan
oleh kelas. Objek juga disebut sebagai instance.
❖ Inheritance, Ketika suatu kelas didefinisikan dengan mewarisi
fungsi yang ada dari kelas induk maka hal tersebut disebut dengan
Inheritance. Di mana kelas anak akan mewarisi semua atau
beberapa fungsi dan variabel anggota dari kelas induk.
❖ Polimorfisme, konsep berorientasi objek di mana fungsi yang sama
dapat digunakan untuk tujuan yang berbeda. Misalnya nama
fungsi sama tetapi jumlah argumennya yang berbeda dan dapat
melakukan tugas yang berbeda.
❖ Overloading, merupakan bagian dari jenis polimorfisme di mana
beberapa atau semua operator memiliki implementasi yang
berbeda tergantung pada jenis argumen mereka.
❖ Overriding, memodifikasi metode yang diwariskan. Jadi anda
hanya perlu membuat metode dengan nama yang sama di class
anak yang ingin ditimpa (Overriding).
❖ Abstraksi Data, Representasi data apa pun yang tidak
menunjukkan (di-hidden) detail implementasinya (abstrak). *
Enkapsulasi - mengacu pada konsep di mana programmer
merangkum semua data dan fungsi anggota secara bersama-sama
untuk membentuk suatu objek.

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.

❖ Constructor, mengacu pada jenis fungsi khusus yang akan


dipanggil secara otomatis setiap kali ada pembentukan objek dari
kelas.
❖ Destruktor, mengacu pada jenis fungsi khusus yang akan dipanggil
secara otomatis setiap kali objek dihapus atau keluar dari ruang
lingkup tertentu.
Berikut contoh sederhana class & object.
1 <?php
2 class Koding{
3 public function nama(){
4 echo “Pemrograman Web dengan PHP";
5 }
6 public function lisensi(){
7 echo “free, $0 /tahun";
8 }
9 }
10 //create php object dengan operator new.
11 $obj = new Koding();
12 $obj->nama();
13 $obj->lisensi();
14 ?>

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.

Berikut adalah contoh Calling Member Function.


1 <?php
2 class Mobile {
3 /* Member variables */
4 var $price;
5 var $title;
6 /* Member functions */
7 function setPrice($par){
8 $this->price = $par;
9 }
10 function getPrice(){
11 echo $this->price ."";
12 }
13 function setName($par){
14 $this->title = $par;
15 }
17 }
18 $Samsung = new Mobile();
19 $Xiaomi = new Mobile();
20 $Iphone = new Mobile();
21 $Samsung->setName( "SamsungS8 );
22 $Iphone->setName( "Iphone7s" );
23 $Xiaomi->setName( "MI4" );
24 $Samsung->setPrice( 90000 );
25 $Iphone->setPrice( 65000 );
26 $Xiaomi->setPrice( 15000 );
27
28 // Memanggil fungsi anggota lain
29 $Samsung->getName();
30 $Iphone->getName();
31 $Xiaomi->getName();
32 $Samsung->getPrice();
33 $Iphone->getPrice();
34 $Xiaomi->getPrice();
35 ?>

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.

Berikut contoh sederhana MultiLevel Inheritance.


1 <?php
2 class A {
3 public function myage() {
4 return "age is 80\n";
5 }
6 }
7 class B extends A {
8 public function mysonage() {
9 return "age is 50\n";
10 }
11 }
12 class C extends B {
13 public function mygrandsonage() {
14 return "age is 20\n";
15 }
16 public function myHistory() {
17 echo "Class A " .$this->myage();
18 echo "Class B ".$this-> mysonage();
19 echo "Class C " . $this->mygrandsonage();
20 }
21 }
22 $obj = new C();
23 $obj->myHistory();
24 ?>

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.

5.3 Konsep dan Pola MVC


PHP MVC adalah arsitektur atau pola desain aplikasi yang
memisahkan data aplikasi dan business logic (Model) dari penyajian
(View) berdasarkan interaksi user ke server, sedangkan Controller
untuk menengahi antara model dan view. MVC dapat diilustrasikan
seperti sebuah mobil dan pengemudi, kaca depan mobil sebagai
tampilan (view) yang digunakan pengemudi (pengontrol dengan
Controller) untuk memantau lalu lintas di depan kemudian kecepatan
atau rem (model) tergantung pada apa yang dilihatnya di depan.
Berikut gambaran MVC dengan 2 cara penyajian sebagai pendekatan
untuk mempermudah pemahaman:

Gambar 5.6 Gambaran MVC Penyajian ke-1

Gambar 5.7 Gambaran MVC Penyajian ke-2

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.

MVC Design Pattern adalah pola desain yang paling banyak


digunakan untuk pengembangan aplikasi web dunia saat ini.

Gambar 5.8 MVC Design Pattern


Saat ini telah banyak framework web PHP yang dikembangkan
dengan implementasi pola MVC untuk memudahkan dalam membuat
aplikasi atau situs web.
❖ CI, Laravel, dll
❖ Anda pun dapat membuat mandiri dengan tim suatu
framework web PHP berbasis pola MVC.
Sedangkan untuk framework web Python dengan pola misal
menggunakan pendekatan Model, View dan Template (MVT) seperti
Flask, Django, dll. Berikut ilustrasi perbandingan Pola MVC / MVT pada
Python (terkait pola, hal ini adalah semacam istilah saja yang
sebenarnya di dalam python maupun Node JS web framework juga
dapat menggunakan penamaan dengan label MVC) dan Node JS.

Gambar 5.9 Ilustrasi Pola MVC pada Node JS vs Django

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.

#Koding Simple MVC berbasis Framework Flask


dengan Lib. SQLAlchemy untuk Object-relational
mapping (ORM)

# ============================
# 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
# ---------------------------------------------------------------------------

from flask import Flask,render_template, Response, redirect, \


url_for, session, request, jsonify
from flask import json, make_response, render_template_string
import sqlite3
from flask_cors import CORS

from flask import send_file


from flask_qrcode import QRcode

from requests.packages.urllib3.exceptions import ProtocolError


from collections import OrderedDict
from operator import itemgetter

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

from flask_gtts import gtts

app = Flask(__name__, static_folder='static')


qrcode = QRcode(app)

# Ref. modifikasi:
# Big Thanks to,
# https://github.com/piinalpin/absent-qrcode-python
# ==============================================================
#

from flask_sqlalchemy import SQLAlchemy


from flask_migrate import Migrate

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)

# Operasi untuk migrate


# flask db_qr init
# flask db_qr migrate
# flask db_qr upgrade

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.

from static.qr_app.model.StudentModel import Student


from static.qr_app.model.AttendanceModel import Attendance

# ..
# .

@app.route("/qr_student", methods=["GET", "POST"])


def qr_student():
if request.method == "POST":
name = request.form['name']
nim = request.form['nim']
UUID = str(uuid.uuid4())
qr_code_mark = "static/img/tmp_qr/{}.png".format(UUID)
student = Student(nim=nim, name=name, qr_code=qr_code_mark)
student.save()

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
.
.

205 directories, 1651 files

Link kode program lengkapnya:


https://github.com/imamcs19/FGA-Big-Data-Using-Python-Filkom-x-Mipa-UB-2022

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.

5.4 Tugas Kelompok


1. Jelaskan pengertian dari beberapa istilah berikut:
❖ File Handling
❖ Files modes “r”, “r+”, “w”, “w+”, “a”, “a+”
2. Buat otomasi operasi file dan folder dengan Python, PHP dan
Node JS untuk dapat dilakukan “rename” terhadap:
❖ File
❖ Folder
3. Perhatikan susunan direktori berikut:

(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.

penyajian ke-1 penyajian ke-2


(a)

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.

BAB 6 Framework & Tools

6.1 Pengantar Framework


Django, Flask, Laravel, CI, React, Flutter, Vue adalah sebagian
framework open-source & free untuk membangun aplikasi atau situs
web dengan lebih cepat, stabil & mudah di-maintenance, memiliki
fitur-fitur modern serta menggunakan sintaks masing-masing adalah
Python, PHP dan JS engine yang ekspresif (mudah dipelajari &
dimengerti) dan elegan (simple, sangat rapi dan mengagumkan
terutama yang menggunakan Python engine ketika digunakan sebagai
backend untuk AI, Machine Learning serta Deep Learning-nya).
• Bult-in authorization system
• Great MVC Architecture
• Cache memory integration
• Seamless automation testing
• Simple URL routing setup
• Smooth database migration
• Detail-oriented documentation
• Built-in libraries
• Improve technical vulnerabilities & Higher Security
• Easy Exception Handling
• Easy to Integrated with Other Web Tools
• Community support on Github

Gambar 6.1 Django vs Flask vs Laravel vs Others

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.

Fitur-Fitur Modern & Powerful Pada Laravel sebagai jawaban,


kenapa harus menggunakan Laravel?

Gambar 6.2 Taylor Otwell


(Founder of Laravel, dirilis pada Juni 2011)

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.

Gambar 6.3 CorePHP VS PHP Frameworks


Anda dan tim sebenarnya dapat juga membuat mandiri
framework seperti Taylor Otwell membuat Laravel, Siap?

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.

6.2 Framework Flask, Django dan


ExpressJS (Node)
6.2.1 Popularitas Framework
Framework Flask (atau jika dimemekan jadi teringat superhero
favorite saya masa kecil dulu yaitu Flash dari Marvel :D) untuk saat ini
dinilai sangat baik untuk beginner bahkan sampai expert developer,
mulai dari membangun aplikasi skala kecil dan menengah, micro
service, sampai skala enterprise (Netflix, dll) dengan spesifikasi dan
konfigurasi yang sangat mudah. Karena menghadirkan kemudahan
yang sangat ekstrim dan cepat dalam pengembangan aplikasi web.
Serta dengan dukungan yang luar biasa dari Python engine dengan
Library AI, Machine Learning (ML) dan Deep Learning (DL) yang sangat
powerfull jika dibangdingkan dengan Framework lain yang berbasis
Node.js yang menggunakan JS Engine. Kemudian terkait kemudahan
fitur integrasi Flask dengan Big Data Ecosystem dan juga untuk
membangun Data Science sudah sangat mature.

Vs Vs

Gambar 6.4 Ilustasi Meme Flask vs Django vs Express Node.js

Django adalah framework web yang bersifat free, open-source


dan high-level yang menggunakan bahasa Python untuk
pengembangan yang cepat, praktis dan kemudahan membuat desain
arsitekturnya serta kode yang clean. Framework ini pertama dibuat
pada tahun 2003 dan diperkenalkan mulai pada 2008 oleh dua

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.

pemrogram web, yaitu Adrian Holovaty dan Simon Willison, mereka


bekerja di surat kabar Lawrence Journal-World untuk pengembangan
dalam kemudahan pembuatan aplikasi. Istilah "Django" diambil dari
pemain seni nada terkenal bernama Django Reinhardt.
Sedangkan ExpressJS adalah framework yang berbasis Node.js
dengan resource minimalis dan fleksibel, tetapi mampu menyediakan
fitur-fitur yang robust untuk pengembangan aplikasi web dan mobile.
Terdapat banyak metode utilitas, dukungan middleware, dan
kemudahan membuat API yang cepat dan ringan.

Gambar 6.5 Popularitas antar Framework (Backend)

Pada langkah instalasi, misal pada bagian ini diberikan cara


untuk setup Framework Flask pada penyedia cloud online yang
mendukung IaaS.
• Siapkan link download File Master webapp, misal dari github, lalu
ketikkan

$ git clone https://github.com/imamcs19/pyIR.git

• Lalu ketikkan

$ mv -f pyIR/* mysite/

lalu tekan Reload pada menu Web

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.

• Ketikkan berikut untuk installasi Library yang dibutuhkan

pip install -r ./mysite/requirements.txt

• Coba masuk ke halaman login Web App Anda, misal pada


https://userAnda.pythonanywhere.com

(a)

(b)

• Selesai :D

6.2.2 Performasi Framework


Setiap framework pasti mengharapkan setiap proses di dalam
kinerjanya memiliki waktu tercepat, seperti terkait json, operasi query
pada database, kompatibiltas terhadap middleware (jembatan antar
teknologi) dan kekayaan fitur otomasi serta canggih lainnya. Tetapi ini
hanyalah masalah waktu bagi developer framework untuk mencapai
dan menjadi yang lebih baik. Artinya tidak selalu yang menjadi terbaik
hari ini adalah terbaik di masa depan. Barangkali jika Anda
menemukan respon proses yang lambat atau kesalahan tertentu.
Anda dapat segera menyampaikan ke komunitas framework tersebut
untuk segera diperbaiki oleh tim expert masing-masing.

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.

Gambar 6.6 Performasi antar beberapa Framework (x: jumlah maks.


Request per detik, y: banyaknya Cores dan RAM)

Hasil analisis dari komparasi performasi di atas, sebagiannya


adalah akan ada suatu spesifikasi dari hardware yang membuat sama
performasi semua framework. Perbaikan kinerja tersebut juga dapat
didukung oleh kecanggihan teknologi yang digunakan tim developer
dalam mengembangkan framework mereka masing-masing melalui
kolaborasi kerjasama atau lainnya.

Tabel 6.1 Perbandingan sebagian Fitur Django vs Flask

No Fitur Django Flask


Sudah digunakan juga oleh
Otomasi by ChatGPT, sangat
1 Masih minim
AI direkomendasikan.
It’s Great, sangat lengkap
Library It's Great, sangat juga, karena dari Python,
2 untuk AI, lengkap dari Python, jika dibandingkan dengan
Machine jika dibandingkan dari Node.js, Python lebih
Learning dengan dari Node.js powerfull terkait AI, ML

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.

(ML), dan yang menggunakan JS dan DL dan integrasinya


Deep Engine dengan ekosistem Big
Learning Data.
(DL)

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
]

Pada views (jika ada atau


dibuat),
from . import app
Pada folder views, from flask import request
from from flask import
django.shortcuts render_template
import render
def @app.route(“/mypage”)
method_view(reques def demo():
t):
Templates
var_set=’’’value html code
5 Native atau tempvar=”value_for_
dll untuk render
base String template”
template'’’

return render( return render_template(


request, “index.html”,
‘demo.html’, send_var=var_set)
{‘tempvar’:tempvar}
) atau menggunakan return
render_template_string(st
ring_index_html,
send_var=var_set)

Saat ini masih dinilai


belum cukup stabil
6 Performasi Lebih konsisten
jika request semakin
tinggi

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.

6.3 Framework Laravel


Laravel mengarahkan pengembang dalam pengalaman
membuat aplikasi web sehingga bisa lebih kreatif dan menyenangkan,
yaitu dengan mencoba menghilangkan kesulitan dalam
pengembangan seperti common tasks yang sering digunakan pada
sebagian besar proyek web, seperti authentication, routing, sessions,
dan caching.
6.3.1 Instalasi, Konfigurasi di Local & Cloud
Beberapa tahapan Instalasi dan lainnya (Link Master:
http://bit.ly/3bIj9BC ):
❖ Install Composer, untuk mengelola dependensi Laravel.
Pertama, download composer.phar. Setelah itu, simpan
pada local project direktori atau move ke usr/local/bin untuk
dapat digunakan secara global di sistem Anda. Di Win. OS,
Anda dapat menggunakan Composer Windows installer.
❖ Install Laravel, Install Xampp
❖ Cek Server Requirements
❖ Configuration
❖ Pretty URLs
Berikut ini penjelasan mengenai tahapan installasi yang harus
dilakukan.
❖ Install Composer, untuk mengelola dependensi Laravel. Pertama,
download composer.phar. Setelah itu, simpan pada local project
direktori atau move ke usr/local/bin untuk dapat digunakan secara
global di sistem Anda. Di Win. OS, Anda dapat menggunakan
Composer Windows installer.

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.

Pastikan sudah download PHP:


https://windows.php.net/download/

Lalu ekstrak misal pada Program Files & setting di Env. var.
> System var. > Path dari Control Panel.

https://getcomposer.org/download/

Cek PHP version

https://slproweb.com/products/Win32OpenSSL.html
(Install / Setup - OpenSSL), lalu set Path

Pada file “php.ini-production” di dir. C:\Program Files\php-


8.0.2, ubah menjadi “php.ini”
Lalu didalamnya ubah ;extension_dir = "ext"
menjadi extension_dir = "ext“
Lalu didalamnya ubah ;extension=openssl
menjadi extension=openssl
Lalu didalamnya ubah ;extension=fileinfo
menjadi extension=fileinfo
Lalu didalamnya ubah ;extension=mbstring
menjadi extension=mbstring

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

Buat project Laravel, misal dengan nama “web01” & “web02”

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

Buka Project web01, misal dengan vscode,


Lalu buka Terminal, untuk cek version Laravel, ketikkan
PS C:\Users\Nidos\web01> php artisan

PS C:\Users\Nidos\web01> php artisan serve

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.

Manage MySQL, misal dengan SQLYog / lainnya

Misal dari software Moba Xterm akses ke local komputer atau


remote dari EC2 AWS Educate (Cloud), untuk Install Docker,
ketikkan:
wget https://raw.githubusercontent.com/docker/docker-in-
stall/master/install.sh
sh install.sh
// Instalasi Docker-Compose
sudo apt-get remove docker-compose
sudo curl -L "https://github.com/docker/compose/re-
leases/download/1.26.2/docker-compose-
$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-
compose

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.

Install Portainer untuk GUI Docker


docker volume create portainer_data
docker run -d -p 8000:8000 -p 9001:9000 --name=portainer
--restart=always -v
/var/run/docker.sock:/var/run/docker.sock -v por-
tainer_data:/data portainer/portainer-ce

Install Composer & Buat Project


wget https://raw.githubusercontent.com/shivdevops/PHP-
COMPOSER-INSTALLATION/master/composer.sh
sudo sh ./composer.sh
sudo apt-get install php-xml
composer create-project --prefer-dist laravel/laravel
laravel_project
cd laravel_project
mkdir -p nginx/conf.d mkdir php
wget https://raw.githubusercontent.com/imamcs19/Scrap-
ingNothers-toOneDataNothers/master/edubig-pyspark-big-
data-app/docker-compose.yml
wget https://raw.githubusercontent.com/imamcs19/Scrap-
ingNothers-toOneDataNothers/master/edubig-pyspark-big-
data-app/Dockerfile
wget https://raw.githubusercontent.com/imamcs19/Scrap-
ingNothers-toOneDataNothers/master/edubig-pyspark-big-
data-app/app.conf -O
./nginx/conf.d/app.conf
wget https://raw.githubusercontent.com/imamcs19/Scrap-
ingNothers-toOneDataNothers/master/edubig-pyspark-big-
data-app/local.ini -O
./php/local.ini
docker-compose up -d

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.

Setelah menjalankan “docker-compose up -d”, cek di browser


Anda dengan,

IP Public:88

IP Public:7000

Menghubungkan database ke Laravel, dengan edit file .env laravel

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.

Akses DB mySQL dari Portainer.io pada CLI Container console

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’;
});

Edit 1, file app/Http/routes.php

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.

Route::get(‘/hai/{nama}', function ($nama) {


return ‘Hai ’.$nama;
});

Edit 2, file app/Http/routes.php

localhost:port/hai Hai
localhost:port/hai/Php Hai Php

Ketika di-run pada browser

Contoh beberapa perintah Routing lainnya yang menggunakan


method selain get, yaitu

Method untuk membuat suatu item


Route::post(‘/run', function () {
return ‘ini POST’;
});

Method untuk membaca suatu item


Route::get(‘/run', function () {
return ‘ini GET’;
});

Method untuk update suatu item


Route::put(‘/run', function () {
return ‘ini PUT’;
});

Method untuk menghapus suatu item


Route::delete(‘/run', function () {
return ‘ini DELETE’;
});

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.

Script sederhana untuk melihat hasil outputnya dengan metode


yg berbeda

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

Berikut beberapa kelompok Perintah Routing


❖ Rounting
Route::get(‘/test', function () { });
Route::get(‘/test’, ‘ControllerName@function’);
Route::controller(‘/run’, ’RunController’);

❖ 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]+’);

Route::get(‘/test/{var1}/{var2}’, function ($var1,


$var2) { })
-> where ( array(‘var1’ => ‘[0-9]+’, ‘var2’ => ‘[A-Za-
z]’));

❖ 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.

Berikut contoh implementasi sederhana untuk membuat


“Route Simple” dan “Route dan View”.
❖ Route simple

❖ Route dan View


Route::<jenis method>(<URL>,<proses to do>)

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

//untuk membuat controller baru dengan artisan


php artisan make:controller MyController

dengan perintah diatas, maka Laravel akan membuatkan file


dengan nama MyController.php yang berada pada directory
app/Http/Controllers/
di mana hasil file generate tersebut didalamnya sudah
didefault kode-kode seperti pemanggilan lib., misal
namespace, use/ lainnya untuk memenuhi kebutuhan dasar oleh
Laravel, tinggal ditambahkan beberapa kode tambahan sesuai
dengan kebutuhan pengembang Web.

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.

//untuk membuat model baru yang berhubungan dengan


manajemen data dengan artisan
php artisan make:model MyModel

dengan perintah diatas, maka Laravel akan membuatkan file


dengan nama MyModel.php yang berada pada directory
app/Models/

Factory model dirancang untuk memungkinkan Anda membuat


model “dummy" dengan cepat.

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.

Cara menjalankan model Mahasiswa, misal untuk search pada


tabel mahasiswa dengan nim dinamis
Route::get(‘mahasiswa/{nim}', function ($nim) {
$mhs = App\Mahasiswa::find($nim);
echo ‘<pre>’;
print_r ($mhs->nama);
});

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.

Misal untuk mengetahui nama mahasiswa dengan nama


keminatannya.
Route::get('mahasiswa', function () {
$mahasiswa = app\Models\Mahasiswa::all();
foreach ($mahasiswa as $mhs){
$stream = app\Models\Keminatan::find($mhs-
>kode_stream);
echo $mhs->nama.“, nama keminatan: “.$stream-
>nama_stream.“<br/>";
}

});

Misal untuk menampilkan semua nama mahasiswa dari


keminatan tertentu, bisa menggunakan hasMany yang menyatakan
relasi One-to-Many (1-n) dari tabel Keminatan dan Mahasiswa.
class Keminatan extends Model
{
protected $table = 'keminatan';
public function mahasiswa(){
return $this->hasMany('app\Models\Mahasiswa');
}
}

Set script pada Model Keminatan

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>’;
});

Set script pada Route

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>’;
});

Kemudian, misalkan kita coba menggunakan standard dari


routing lebih lanjut, yaitu dengan membuat misal file testRoute.php
pada directory resources/views/, misal berisi:
<html>
<head><title>Test Routing</title></head>
<body><h1> Laravel test Routing sederhana</h1></body>
</html>

dan pada file web.php, route diubah, misal menjadi,


Route::get(‘testRoute', function () {
return view(‘testRoute’);
});

Kemudian, berikut contoh sederhana untuk membuat variable


berserta value dan memanggilnya pada file testRoute.php pada
directory resources/views/
Route::get(‘testRoute', function () {
$var = array(‘data1’ => ‘Framework’
‘data2’ => ‘Laravel’);
return view(‘testRoute’,$var);
});

<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);
});

Kemudian, pada file testRoute.php pada directory resources/views/,


diubah nama filenya menjadi testRoute.blade.php dan isi script-nya
diubah seperti berikut:
<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>

<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>

Contoh lainnya pada file testRoute.blade.php untuk


menyederhanakan script kondisi:

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>

Contoh lainnya misal untuk menyederhanakan script foreach


untuk menampilkan data dengan dari DB menggunakan Model dari
tabel Mahasiswa. Maka pada route dibuat, misal seperti berikut.
Route::get(‘testRoute', function () {
$var = array(
‘data1’ => ‘Framework’
‘data2’ => ‘Laravel’
‘mahasiswa’ => app\Models\Mahasiswa::all()
);
return view(‘testRoute’,$var);
});

pada dalam file web.php ditambahkan script untuk menampilkan


semua nama mahasiswa

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’);

php artisan make:controller KeminatanController

dengan perintah diatas, maka Laravel akan membuatkan file


dengan nama KeminatanController.php pada directory
app/Http/Controllers/
di mana hasil file generate tersebut didalamnya sudah dide-
fault kode-kode seperti pemanggilan lib., misal namespace,
use/ lainnya untuk memenuhi kebutuhan dasar oleh Laravel,
tinggal ditambahkan beberapa kode tambahan sesuai dengan
kebutuhan pengembang Web.

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.

Contoh script view untuk menampilkan keminatan disertai all


mhs yang mengambilnya, dengan blade
<html>
<head>
<title>List Keminatan dan Mhsnya</title>
</head>
<body>
<h1> {{$keminatan->nama_stream}}</h1><br/>
diminati oleh mahasiswa berikut:
<ul>
@foreach($keminatan->mahasiswa as mhs)
<li>{{$mhs->nama}}</li>
@endforeach
</ul>
</body>
</html> keminatan.blade.php

Dan di bawah adalah kode pada bagian Controller-nya, dengan


konsep MVC, Model terkait Data, View terkait tampilan dan
Controller/ Logic tidak boleh ada penggunaan echo, dan sejenisnya.
use app\Models\Keminatan as Keminatan; //utk mengenalkan
Model
class KeminatanController extends Controller
{
//protected $table = 'keminatan';
public function Keminatan($kode_stream){
$keminatan = Keminatan::find($kode_stream);
$vardata = array(
‘keminatan’ => $keminatan
);
return view(‘keminatan’,$vardata);
}
}

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.

6.3.9 Authentication, Middleware, Migration,


Request & CSRF
Authentication untuk me-manage user login dalam sistem, di
mana Laravel akan mengenerate secara otomatis mulai dari halaman
home, register, dan login dengan peritah “php artisan make:auth”
dalam directory /database/migrations
Untuk mencoba register, maka persiapkan DB untuk
menyimpan hasil register tersebut dalam tabel User pada
“database\migrations\2014_10_12_000000_create_users_table.php

Pada file tersebut, misal ditambahkan


“table->integer('code_user’);”
Hal ini digunakan sebagai percontohan nantinya pada pembahasan
Middleware untuk membuat semacam leveling role hak akses tiap
user.
Lalu untuk mencoba register, login dll, maka jalankan terlebih
dahulu perintah “php artisan migrate”, pastikan isi file konfigurasi
*.env sudah benar, mulai dari nama DB, username, password dan host.
Lakukan langkah berikut.

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.

Pada file “php.ini” di dir. C:\Program Files\php-8.0.2,


didalamnya ubah ;extension=pdo_mysql menjadi exten-
sion=pdo_mysql dan
ubah ;extension=mysqli menjadi extension=mysqli

Install nodeJS

Lalu jalankan perintah


composer require laravel/ui

php artisan migrate

php artisan ui bootstrap--auth


npm install
npm run dev => jalankan 2x, jika ada error

Gambar 6.7 Login

Gambar 6.8 Lupa password

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.

Gambar 6.9 Register

Gambar 6.10 Home

Middleware untuk memberikan role atau batasan hak akses


atau proteksi route terhadap user tertentu.
Contohnya set hak akses hanya untuk mahasiswa
Route::get('rolekhususmhs', function(){
echo 'Halaman ini rolenya khusus utk mahasiswa';
})->middleware('auth');

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.

Ketika middleware(‘auth’) ditambahkan, maka tiap user yang


belum login akan dialihkan ke halaman login. Tetapi jika tidak
ditambahkan, maka pada 127.0.0.1:8000/rolekhususmhs maka akan
muncul hasil echo “Halaman ini rolenya husus untuk mahasiswa”.

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.

Tempatkan route pada group Middleware,


“Route::group([‘middleware’ => ‘web’], function () { ….. ”

Hal ini dikarenakan pengecekan form fungsinya ada dalam


middleware.
<html>
<head>
<title>Form Test CSRF Token</title>
</head>
<body>
<form action=“tujuan_myform” method=“post”>
<input type=“text” name=“myname” placeholder=“Input
Name”>
<input type=“hidden” name=“_mytoken” value=“{{csrf_to-
ken()}}”>
<input type=“submit”>
</form>
</body>
</html>

Lalu coba open form submit pada


http://127.0.0.1:8000/myform untuk menjalakan fungsi csrf_token()
yang disimpan sebagai token aktif untuk secure proses saat submit
form. Berikut contoh script myform.blade.php untuk generate secara
otomatis id yang unik dari fungsi csrf_token() yang disediakan secara
default oleh Laravel. Jika csrf_token() tidak dipanggil, maka akan
muncul error TokenMismatch Exception

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.

6.4 Konfigurasi Web App dari Local


Colab atau Localhost dengan
Framework Streamlit/lainnya dan
Tunneling
6.4.1 Create Tunneling like Ngrok
❖ Jalankan Xampp Anda

❖ Buka MobaXterm, asumsikan Anda sudah memiliki ip public


misal dari AWS, lalu remote AWS Anda sehingga seperti
berikut, lalu Install nginx dan start nginx.

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.

▪ Cara install nginx:


o sudo apt-get update
o sudo apt-get install nginx
▪ Run nginx:
o sudo /etc/init.d/nginx start
o sudo /etc/init.d/nginx restart
▪ Cek di web server nginx telah jalan:
http://52.205.191.97/

❖ Pada /home/mobaxterm, ketikkan


ssh -i /mnt/c/Users/Imacho/Downloads/bc-1.pem -R
8080:localhost:80 ubuntu@ec2-52-205-191-97.compute-
1.amazonaws.com

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.

❖ Cek di web local telah berjalan di server nginx public:

6.4.2 Reverse SSH


❖ Cara melihat Public Key di Computer Local (dlm hal ini
adalah AWS dipakai sebagai komputer localnya)
ubuntu@ip-172-31-88-209:~/.ssh$ cat authorized_keys
ssh-rsa
AAAAB3NzaC1yc2EAAAADAQABAAABAQC6x3Po55G1ShdwoDoQ0rtw
qcrcX/qsKBCNJTuKAsOidphrFh/oQDCgycd50JLGTQfKgVCebh+B
dvqzHdgUSvFRo1Gx6YnSiKQpfW2LMU0a8XeojKVCP+vzoUT5RFEg
3EZb+GYBFkT5g+fU1Qpw+etFCM0Iwqbi-
iomn7z3IRiLPBQwbmM5ClmgLnZH4NspqpdOMno/NPqp3cP2SftN4
+fMUrIgZR2VOdloxNJfNP76ddYC0kMGt62OJmZ2zA-
dWXtZmj76jY7wxK9hnNiKN2WPxQ7SZe+4g9+fcAkI5pdE4SwtUqL
a+zgYneI5XBH06acgJSVmQyaFQ/u1S8N3/wnDQV bc-1

❖ Hasil remote Google Colab, dengan ketikkan


“ssh -p 43022 root@localhost”

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.

❖ Web App Colab using Streamlit


▪ streamlitcmd = 'streamlit run
./mysparknlp_pretrained_pipeline_playground.py &'
▪ get_ipython().system_raw(streamlitcmd)
▪ print("Hasil Web App streamlit, visit ke URL:
http://52.205.191.97:8080 :D")
▪ !ssh -i ~/.ssh/bc-1.pem -R 8080:localhost:8501
ubuntu@52.205.191.97

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.

6.5 Tugas Kelompok


1. Jelaskan sejarah singkat Framework Flask, Django, ExpressJS dan
Laravel, mulai dari penemu sampai versi pengembangannya
hingga saat ini!
2. Jelaskan apa saja yang menjadi keunggulan Laravel dari
beberapa istilah berikut:
• Bult-in authorization system
• Great MVC Architecture
• Cache memory integration
• Seamless automation testing
• Simple URL routing setup
• Smooth database migration
• Detail-oriented documentation
• Built-in libraries
• Improve technical vulnerabilities & Higher Security
• Easy Exception Handling
• Easy to Integrated with Other Web Tools
• Community support on Github
3. Sebutkan beberapa kesulitan umum yang sering kali dialami
pengembang dalam membangun proyek Web yang dapat
mudah diatas menggunakan Framework!
4. Buatlah Project Web App untuk Hospital dengan nama project
“myDokter” sederhana dengan framework minimal 2 (Flask,
Django, ExpressJS, dan Laravel), menggunakan sebagian atau
semua fitur/skema berikut:
• Routing / Path
• Artisan / Builtin / Buat Mandiri
• Model, Relationships, Views / Template
• Blade / Format Transfer untuk Tampilan Data
• Controller / def
• Authentication, yang meliputi Form Login & Form Register
• Flash, Middleware, Migration, dan Request, serta CSRF
• Split web app, menjadi 2 yaitu Client (Frontend), api
(Backend)
• Full stack web app.

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.

BAB 7 Study Kasus As Project

7.1 Simple Flask & Django - PHP untuk


Optimasi Fungsi
7.1.1 Tentang Case Study
Pada fungsi f(x) = -x2 + 14x – 13, dengan interval 0 ≤ x ≤ 15 akan
dilakukan proses pencarian nilai x yang memiliki nilai evaluasi tertinggi
sebagai nilai fitness menggunakan kaidah dari algoritma Genetika.
Variabel x terlebih dahulu dikonversikan dalam bentuk nilai biner,
karena menggunakan pendekatan maksimasi fungsi sederhana.
Kemudian saat proses perhitungan nilai evaluasi, dilakukan proses
decode menjadi nilai basis 10.

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.

7.1.2 Snippet Kode Program

#Koding Framework Flask - PHP untuk Algoritma


Genetika | Prototipe API

# ============================
# 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

# // Menentukan PosisiOneCutPoint secara random


BatasBawahRand = 1; BatasAtasRand = StringLenChromosome - 1
lower=BatasBawahRand; upper=BatasAtasRand
mbaris=1;nkolom=1

# berupa array[1x1]
PosisiOneCutPoint_init = myGA.myrandint(mbaris,nkolom,lower,upper)

# convert array[1x1] ke scalar


PosisiOneCutPoint = int(''.join(map(str,PosisiOneCutPoint_init[0])))
print("PosisiOneCutPoint= " + str(PosisiOneCutPoint))

# // memilih 2 parent secara random


P1=np.empty((1,StringLenChromosome)) # inisialisasi Parent ke-1
P2=np.empty((1,StringLenChromosome)) # inisialisasi Parent ke-2
BatasBawahRand = 0; BatasAtasRand = Pop_Size - 1
flag = True
IndexP1 = 0; IndexP2 = 0
while flag:
IndexP1=myGA.myrandintscalar(BatasBawahRand,BatasAtasRand)
IndexP2=myGA.myrandintscalar(BatasBawahRand,BatasAtasRand)
if IndexP1 !=IndexP2:
flag=False

# // menampilkan hasil induk terpilih


print("P1= ")
print(x[IndexP1])
print("")
print("P2= ")
print(x[IndexP2])

# 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])

# cara 1 // melakukan proses pindah silang P1 dan P2


hasil[0,PosisiOneCutPoint:StringLenChromosome]=\
P2[PosisiOneCutPoint:StringLenChromosome]
hasil[1,PosisiOneCutPoint:StringLenChromosome]=\
P1[PosisiOneCutPoint:StringLenChromosome]

# atau dengan for


# cara 2 // melakukan proses pindah silang P1 dan P2
for i in range(PosisiOneCutPoint,StringLenChromosome):
hasilcek[0][i]=P2[i]
hasilcek[1][i]=P1[i]

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

# // Menentukan PosisiPointRandom secara random


BatasBawahRand = 1; BatasAtasRand = StringLenChromosome
PosisiPointRandom = myGA.myrandintscalar(BatasBawahRand,BatasAtasRand)
print("")
print("PosisiPointRandom= " + str(PosisiPointRandom))

# // memilih 1 parent secara random


P1=np.empty((1,StringLenChromosome)) # inisialisasi 1 Parent
BatasBawahRand = 0; BatasAtasRand = Pop_Size - 1
IndexP1 = myGA.myrandintscalar(BatasBawahRand,BatasAtasRand)

print("Index P1 = " + str(IndexP1 + 1))


# // menampilkan hasil induk terpilih
print("P1= ")
print(x[IndexP1])
print("")

# copy array
P1=x[IndexP1]
#print(P1)
hasil=x[IndexP1]
hasil=hasil.astype(int)
#print(hasil)

# // melakukan proses random mutasi


if(hasil[PosisiPointRandom-1]==0):
hasil[PosisiPointRandom-1]=1
else:
hasil[PosisiPointRandom-1]=0

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.

## //Case : Max, y = f(x) = -x^2 + 14x – 13, 0 ≤ x ≤ 15


Batas_Min = 0
Batas_Max = 15

## //Cek panjang string dari nilai biner Batas_Max

vfinal="" # sebaiknya gunakan append, lalu jsonify


## // get atau setting parameter
Pop_Size = int(popsize)
cr_ = float(cr)
mr_ = float(mr)
HasilBiner = myGA.dec2bin(Batas_Max)
StringLenChromosome = len(HasilBiner)
print(".")
print("..")
print("==============================================================")
print("Start Solving: Max, y = f(x) = -x^2 + 14x – 13, 0 ≤ x ≤ 15 :")
print("==============================================================")
print("Hasil Biner= "+HasilBiner)
print("StringLen Chromosome= "+str(StringLenChromosome))

# ..

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(..)

## Menampilkan hasil generate individu


print(" Chromosome | x | y=f(x) ")
print("================================================")
vfinal=vfinal+"^^"+" Chromosome | x | y=f(x) ^" \
+ "================================================^"

# 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))

# // Proses crossover dilakukan sebanyak (n_crossover)


n_crossover = int(np.ceil(float(byk_anak_crossover / 2)))
# // dibagi 2, krn 1 kali proses crossover akan menghasilkan 2 anak
print("Proses crossover dilakukan sebanyak = " + str(n_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

if (loop_anak_crossover + 1) > byk_anak_crossover:


break

HasilCrossover[loop_anak_crossover]=HasilCrossoverTemp[1]
HasilCrossovercek[loop_anak_crossover]=HasilCrossoverTempcek[1]

loop_anak_crossover = loop_anak_crossover + 1

# // menampilkan hasil crossover


# ..

# // start proses mutasi


print("2.2 Mutasi")
# // hitung jumlah offspring mutasi
byk_anak_mutasi = int(np.ceil(mr_ * Pop_Size))
print("Banyaknya offspring mutasi= "+str(byk_anak_mutasi))

# // Proses mutasi dilakukan sebanyak (n_mutasi)


n_mutasi = byk_anak_mutasi
print("Proses mutasi dilakukan sebanyak = " + str(n_mutasi))

HasilMutasi = np.empty((byk_anak_mutasi,StringLenChromosome))
HasilMutasiTemp = np.empty((1,StringLenChromosome))
HasilMutasi=HasilMutasi.astype(int)

# // membuat offspring mutasi sebanyak byk_anak_mutasi


for i in range(0,n_mutasi):
# //menampung hasil Random Mutasi
HasilMutasiTemp=myGA.RandomMutasi(individu)
#print(HasilMutasiTemp)
if n_mutasi==1:
HasilMutasi[i:]=HasilMutasiTemp
else:
HasilMutasi[i,:]=HasilMutasiTemp

# // membuat penampungan populasi induk dan anak (crossover + mutasi)


Pop_Size_induk_dan_anak =\
Pop_Size + byk_anak_crossover + byk_anak_mutasi
IndividuGabungan =\
np.empty((Pop_Size_induk_dan_anak,StringLenChromosome))
IndividuGabungan=IndividuGabungan.astype(int)
IndividuGabunganSort =\
np.empty((Pop_Size_induk_dan_anak,StringLenChromosome))
IndividuGabunganSort=IndividuGabunganSort.astype(int)
fxIndividuGabungan = np.empty((Pop_Size_induk_dan_anak,1),float)

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

# // Seleksi IndividuGabungan berdasarkan nilai f(x)


NextIndividu = np.empty((Pop_Size,StringLenChromosome))
NextIndividu=NextIndividu.astype(int)

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)+"^"

# vfinal mengambil nilai individu terbaik


# vfinal = float(v1) + float(v2) + float(v3)
vfinal=vfinal+"^"+".^"+"Done..! :D^"+"===========^"+"."

TODOS[todo_id] = {'task': args['task'] + '=' + vfinalparam +"`"+vfinal}

print("")
print(".")
print("Done..! :D")
print("=============================================================")
print(".")

return TODOS[todo_id], 201

#Koding Alternatif untuk Fungsi Optimasi


menggunakan Algoritma Particle Swarm
Optimization (PSO) dengan Pytorch ( support cpu
dan gpu ), nantinya dapat disisipkan pada Flask
atau dikombinasi dengan Spark + gpu / etc :D

# ============================
# 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
# ====================================
#

# Ref. yang dimodifikasi:


# Big Thanks to,
# [0] https://github.com/Pixelatory/PSO-GPU/blob/main/PSO.py
# [1] www.researchgate.net/publication/317706705_Buku_Ajar_Swarm_Intelligence

import math
import time
import torch
from tqdm import tqdm
import numpy as np

import warnings
warnings.filterwarnings("ignore")

set_device = 'cuda' # cuda || cpu

bounds = np.array([[10, 1, 1, 0, 2, 1, 0], [200, 50, 9, 1, 20, 10, 84]])


min_bounds = np.min(bounds[0])
max_bounds = np.max(bounds[1])

# utk case ke-2


bounds_to_sub_7_1 = np.array([[0], [15]])
min_bounds_to_sub_7_1 = np.min(bounds_to_sub_7_1[0])
max_bounds_to_sub_7_1 = np.max(bounds_to_sub_7_1[1])

def mydenorm_torch_v2(params, res_low, res_up, a_bounds, device):

# convert tensor agar support cuda / cpu, dengan variabel device


a_bounds = torch.tensor(a_bounds, device = device)
first = a_bounds[1]-a_bounds[0]
# seconds = torch.tensor(a_bounds[0], device = device)
seconds = a_bounds[0]

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.

params = torch.tensor(params, device = device)

return (((params-res_low)/(res_up-res_low))*first) + seconds

def objective_function_torch_with_denorm(pop, a_min_bounds = 0,


a_max_bounds=200, a_bounds= bounds):
if pop.dim() == 1:
pop = pop.unsqueeze(0)
dim = pop.size(dim=-1)

pop_temp = mydenorm_torch_v2(pop, a_min_bounds, a_max_bounds, \


a_bounds, set_device)

return (10 * dim) + \


torch.sum(torch.pow(pop_temp, 2) - (10 * torch.cos(2 * torch.pi * \
pop_temp)), dim=1).reshape(-1, 1)

def objective_function_torch(x):
if x.dim() == 1:
x = x.unsqueeze(0)
dim = x.size(dim=-1)

hasil = (torch.pow((x[:,0] - 1),2) + torch.pow((x[:,1]-2),2) + \


torch.pow((x[:,2] - 3),2)).reshape(-1, 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)

hasil = (-torch.pow(x[:,0],2) + 14*x[:,0] - 13).reshape(-1, 1)


return -hasil

min_bounds_isi_bebas_to_sub_7_1 = 0
max_bounds_isi_bebas_to_sub_7_1 = 200

def objective_function_torch_to_sub_7_1_with_denorm(pop, a_min_bounds =


min_bounds_isi_bebas_to_sub_7_1, a_max_bounds =
max_bounds_isi_bebas_to_sub_7_1, a_bounds = bounds_to_sub_7_1):
if pop.dim() == 1:
pop = pop.unsqueeze(0)
dim = pop.size(dim=-1)

pop_temp = mydenorm_torch_v2(pop, a_min_bounds, a_max_bounds, a_bounds,\


set_device)

hasil = (-torch.pow(pop_temp[:,0],2) + 14*pop_temp[:,0] - 13).reshape(-1, 1)


return -hasil

# Optimization Test Functions


def rastrigin(pop):
if pop.dim() == 1:
pop = pop.unsqueeze(0)
dim = pop.size(dim=-1)
return (10 * dim) + \
torch.sum(torch.pow(pop, 2) - (10 * \
torch.cos(2 * torch.pi * pop)), dim=1).reshape(-1, 1)

def ackley(pop, a=20, b=0.2, c=2 * math.pi):


if pop.dim() == 1:
pop = pop.unsqueeze(0)
dim = pop.size(dim=-1)
print()
print('pop =', pop)
print('pop[0] =', pop[0])
print('pop[0][0] =', pop[0][0])
print('pop[:, 0] =', pop[:,0])
first = -a * torch.exp(-b * torch.sqrt(1 / dim * \
torch.sum(torch.pow(pop, 2), dim=1)))
second = torch.exp(1 / dim * torch.sum(torch.cos(c * pop), dim=1))

hasil = (first - second + a + math.exp(1)).reshape(-1, 1)


print('type hasil =', type(hasil))
print('shape hasil =', hasil.shape)
print('hasil[0] =', hasil[0])
return hasil

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.

def myPSO(f, max_iter, n, dim, w, c1, c2, init_min_x, init_max_x, device):


# modifikasi dari https://github.com/Pixelatory/PSO-GPU
# oleh: Imam Cholissodin (Imam CS) | Filkom UB

# All the data containers


positions = (init_max_x - init_min_x) * torch.rand(size=(n, dim), \
dtype=torch.float, device=device) + init_min_x

velocities = torch.zeros(size=(n, dim), dtype=torch.float, device=device)


personal_best_pos = torch.rand(size=(n, dim), dtype=torch.float, \
device=device)

personal_bests = float('inf') * torch.ones(size=(n, 1), dtype=torch.float, \


device=device)

best_pos = torch.zeros(size=(1, dim), dtype=torch.float, device=device)


best_val = torch.tensor(float('inf'), dtype=torch.float, device=device)

# ------ 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)

# Update personal best


personal_best_pos = torch.where(fitnesses < personal_bests, positions, |
personal_best_pos)

personal_bests = torch.minimum(fitnesses, personal_bests)

# Update global best


bestSol = torch.min(personal_bests, dim=0)
best_pos = personal_best_pos[bestSol[1]].detach().clone()
best_val = bestSol[0]

# print(best_pos, best_val)

# Velocity equation
r1 = torch.rand(size=(n, dim), dtype=torch.float, device=device)
# r1 => random coeff 1 vector

r2 = torch.rand(size=(n, dim), dtype=torch.float, device=device)


# r2 => random coeff 2 vector

inertia = velocities * w
cognitive = r1 * c1 * (personal_best_pos - positions)
social = r2 * c2 * (best_pos - positions)

# velocity update and constraint


velocities = inertia + cognitive + social

# ------ start | additional part 1, by Imam CS => repair positions agar


dalam interval init_min_x, init_max_x -----------------------------------
# % update kecepatan
# V = (w*V)+(c1*r1*(Pbest-X))+(c2*r2*(Gbest-X))
velocities = torch.clip(velocities,V_SLCcLR_lower,V_SLCcLR_upper)
# ------ end | additional part 1, by Imam CS => repair positions agar
dalam interval init_min_x, init_max_x -----------------------------------

positions += velocities # position update

# ------ start | additional part 2, by Imam CS => repair positions agar


dalam interval init_min_x, init_max_x -----------------------------------
# % update posisi
# X = X + V
positions = torch.clip(positions,init_min_x,init_max_x)
# X = repair_partikel(X).copy()
# ------ start | additional part 2, by Imam CS => repair positions agar
dalam interval init_min_x, init_max_x -----------------------------------

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)

return best_val.item(), best_pos.tolist()[0]

def PSO(f, max_iter, n, dim, w, c1, c2, init_min_x, init_max_x, device):


# All the data containers
positions = (init_max_x - init_min_x) * torch.rand(size=(n, dim), \
dtype=torch.float, device=device) + init_min_x

velocities = torch.zeros(size=(n, dim), dtype=torch.float, device=device)


personal_best_pos = torch.rand(size=(n, dim), dtype=torch.float, \
device=device)

personal_bests = float('inf') * torch.ones(size=(n, 1), dtype=torch.float,\


device=device)

best_pos = torch.zeros(size=(1, dim), dtype=torch.float, device=device)


best_val = torch.tensor(float('inf'), dtype=torch.float, device=device)

curr_iter = 0
pbar = tqdm(total=max_iter)
while curr_iter < max_iter:
# First calculate fitnesses
fitnesses = f(positions)

# Update personal best


personal_best_pos = torch.where(fitnesses < personal_bests, positions,\
personal_best_pos)

personal_bests = torch.minimum(fitnesses, personal_bests)

# Update global best


bestSol = torch.min(personal_bests, dim=0)
best_pos = personal_best_pos[bestSol[1]].detach().clone()
best_val = bestSol[0]

# print(best_pos, best_val)

# Velocity equation
r1 = torch.rand(size=(n, dim), dtype=torch.float, device=device)
# r1 => random coeff 1 vector

r2 = torch.rand(size=(n, dim), dtype=torch.float, device=device)


# r2 => random coeff 2 vector

inertia = velocities * w
cognitive = r1 * c1 * (personal_best_pos - positions)
social = r2 * c2 * (best_pos - positions)

# velocity update and constraint


velocities = inertia + cognitive + social

positions += velocities # position update

curr_iter += 1
pbar.update(1)

return best_val.item(), best_pos.tolist()[0]

def execAlgo(algo, *args):


"""
:param algo: algorithm yang digunakan untuk optimasi
:param args: arguments dari algorithm
:return: hasil
"""
startTime = time.time()
result = algo(*args)
endTime = time.time()
print(f"time: {endTime - startTime}")
return result

# hyper parameters
w = 0.729 # inertia
c1 = 1.49445 # cognitive (particle)
c2 = 1.49445 # social (swarm)

print("##### Custom Obj Func dgn PSO-GPU feat Pytorch #####")

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("10000 iter; 10000 particles; 3 dim")

# dgn PSO dari referensi


best_cost, best_position = PSO(objective_function_torch, 10000, 10000, 3, w,
c1, c2, -5.12, 5.12, 'cuda')
print()
# print('val_best = ', val_best)
# print('pos_best = ', pos_best)

print('pos Gbest = ', best_position)


print()

print("##### Custom Obj Func dgn PSO-GPU feat Pytorch | f(x) = -x^2 + 14x - 13
#####")

print("10000 iter; 10000 particles; 1 dim")

# dgn PSO dari referensi


best_cost, best_position = PSO(objective_function_torch_to_sub_7_1, 10000, \
10000, 1, w, c1, c2, 0, 15, 'cuda')
print()

print('pos Gbest = ', best_position)

print()

print("##### Custom Obj Func dgn PSO-GPU feat Pytorch |


f(x) = -x^2 + 14x - 13 | dgn denorm #####")

print("10000 iter; 10000 particles; 1 dim")

# dgn myPSO, modified by Imam Cholissodin :D


# support dinamis lower dan upper bound tiap hyperparameter + velocity &
# pos clamping

# Define number of particles


num_particles = 1000

# Define maximum number of iterations


max_iterations = 1000

num_dimensions = len(bounds_to_sub_7_1[0])
# print('num_dimensions = ', num_dimensions)

best_cost, best_position = myPSO(\


objective_function_torch_to_sub_7_1_with_denorm, max_iterations, num_particles,
num_dimensions, w, c1, c2, min_bounds_isi_bebas_to_sub_7_1,
max_bounds_isi_bebas_to_sub_7_1, set_device)

print()
# print('val_best = ', val_best)
# print('pos_best = ', pos_best)

print('pos before = ', best_position)

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('cost = ', best_cost)


print('pos after = ', best_position)
print('type pos after = ', type(best_position))

# Fit model with best hyperparameters, misal dari parameter berikut


x_Gbest = best_position.cpu().numpy().astype(float)
x_Gbest = float(x_Gbest)

print('x Gbest = ', x_Gbest)

print()
print("##### Custom Obj Func dgn myPSO-GPU feat Pytorch | dgn denorm #####")
print("1000 iter; 1000 particles; 7 dim")

# dgn myPSO, modified by Imam Cholissodin :D


# support dinamis lower dan upper bound tiap hyperparameter + velocity &
# pos clamping

# Define number of particles


num_particles = 1000

# Define maximum number of iterations

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)

best_cost, best_position = myPSO(objective_function_torch_with_denorm,\


max_iterations, num_particles, num_dimensions, w, c1, c2, min_bounds, \
max_bounds, set_device)

print()
# print('val_best = ', val_best)
# print('pos_best = ', pos_best)

print('pos before = ', best_position)

best_position = mydenorm_torch_v2(best_position, min_bounds, max_bounds, \


bounds, set_device)

print('cost = ', best_cost)


print('pos after = ', best_position)
print('type pos after = ', type(best_position))

# Fit model with best hyperparameters, misal dari parameter berikut


param_1, param_2, param_3, param_4, param_5, param_6, param_7 = \
best_position.cpu().numpy().astype(float)

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)

print('param_1 = ', param_1)


print('param_2 = ', param_2)
print('param_3 = ', param_3)
print('param_4 = ', param_4)
print('param_5 = ', param_5)
print('param_6 = ', param_6)
print('param_7 = ', param_7)

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]

E:\PyWebProject\Flask_n_DjangoPy\tryRESTfulDjango>python manage.py runserver


Performing system checks...

System check identified no issues (0 silenced).


July 05, 2018 - 00:36:19
Django version 2.0.6, using settings 'tryRESTfulDjango.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Performing system checks...

System check identified no issues (0 silenced).


July 05, 2018 - 00:36:34
Django version 2.0.6, using settings 'tryRESTfulDjango.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Performing system checks...

System check identified no issues (0 silenced).


July 05, 2018 - 00:36:57
Django version 2.0.6, using settings 'tryRESTfulDjango.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
.
..
POST Awal dari Web PHP ke WebApp RESTful Api Python dgn Django:
b'{"max_iter":100,"pop_size":80,"cr":0.8,"mr":0.6}'
.

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...

System check identified no issues (0 silenced).


July 05, 2018 - 00:37:37
Django version 2.0.6, using settings 'tryRESTfulDjango.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
.
..
POST Awal dari Web PHP ke WebApp RESTful Api Python dgn Django:
b'{"max_iter":100,"pop_size":80,"cr":0.8,"mr":0.6}'
.
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: [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

2. Reproduksi (Crossover dan Mutasi)


2.1 Crossover
Banyaknya offspring crossover= 64
Proses crossover dilakukan sebanyak = 32
PosisiOneCutPoint= 2
Index P1 = 58, Index P2 = 27
P1=
[0 0 0 1]

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]

Hasil Crossover cara 1:


C1: [0 0 0 0] | 0 | -13.0
C2: [1 1 0 1] | 13 | 0.0
C3: [1 1 0 0] | 12 | 11.0
C4: [1 0 0 0] | 8 | 35.0
C5: [0 1 1 0] | 6 | 35.0
C6: [0 0 1 1] | 3 | 20.0
C7: [0 0 1 0] | 2 | 11.0
C8: [0 0 1 0] | 2 | 11.0
C9: [1 0 0 1] | 9 | 32.0
C10: [1 0 0 1] | 9 | 32.0
C11: [0 0 0 1] | 1 | 0.0
C12: [1 1 0 0] | 12 | 11.0
C13: [0 0 1 1] | 3 | 20.0
C14: [1 0 1 0] | 10 | 27.0
C15: [1 0 1 1] | 11 | 20.0
C16: [1 0 0 1] | 9 | 32.0
C17: [0 1 0 1] | 5 | 32.0
C18: [1 0 0 0] | 8 | 35.0
C19: [0 0 0 1] | 1 | 0.0
C20: [1 1 0 0] | 12 | 11.0
C21: [0 1 1 0] | 6 | 35.0
C22: [1 1 0 0] | 12 | 11.0
C23: [0 0 1 1] | 3 | 20.0
C24: [1 1 1 0] | 14 | -13.0
C25: [1 0 0 0] | 8 | 35.0
C26: [1 0 0 0] | 8 | 35.0
C27: [0 0 0 0] | 0 | -13.0
C28: [0 1 0 0] | 4 | 27.0
C29: [1 0 0 0] | 8 | 35.0
C30: [0 0 0 1] | 1 | 0.0
C31: [1 0 0 0] | 8 | 35.0
C32: [1 1 0 1] | 13 | 0.0
C33: [0 1 1 1] | 7 | 36.0
C34: [1 0 1 1] | 11 | 20.0
C35: [1 0 1 1] | 11 | 20.0
C36: [0 1 0 0] | 4 | 27.0
C37: [1 0 0 1] | 9 | 32.0
C38: [0 0 0 1] | 1 | 0.0
C39: [0 0 1 0] | 2 | 11.0
C40: [0 0 1 1] | 3 | 20.0
C41: [1 1 0 0] | 12 | 11.0
C42: [0 1 1 1] | 7 | 36.0
C43: [1 0 0 0] | 8 | 35.0
C44: [1 1 1 1] | 15 | -28.0
C45: [0 0 1 0] | 2 | 11.0
C46: [0 1 1 0] | 6 | 35.0
C47: [1 0 0 1] | 9 | 32.0

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

Hasil Populasi Gabungan induk dan anak (crossover + mutasi):


G1: [1 0 0 1] | 9 | 32.0
G2: [1 0 0 1] | 9 | 32.0
G3: [0 0 1 0] | 2 | 11.0
G4: [0 1 1 0] | 6 | 35.0
G5: [0 0 0 0] | 0 | -13.0
G6: [1 0 1 0] | 10 | 27.0
G7: [1 0 1 1] | 11 | 20.0
G8: [0 0 0 1] | 1 | 0.0
G9: [1 1 0 1] | 13 | 0.0
G10: [1 0 1 1] | 11 | 20.0
G11: [1 0 0 0] | 8 | 35.0
G12: [0 0 0 0] | 0 | -13.0
G13: [0 1 1 0] | 6 | 35.0
G14: [1 0 0 1] | 9 | 32.0
G15: [0 1 1 1] | 7 | 36.0
G16: [1 1 0 1] | 13 | 0.0
G17: [0 1 0 1] | 5 | 32.0
G18: [0 0 0 0] | 0 | -13.0
G19: [1 1 1 1] | 15 | -28.0
G20: [0 1 0 1] | 5 | 32.0
G21: [0 0 1 0] | 2 | 11.0
G22: [1 0 1 1] | 11 | 20.0
G23: [1 0 1 0] | 10 | 27.0
G24: [0 0 0 0] | 0 | -13.0
G25: [1 1 0 0] | 12 | 11.0
G26: [1 1 1 0] | 14 | -13.0
G27: [1 1 0 0] | 12 | 11.0
G28: [0 1 0 0] | 4 | 27.0
G29: [0 1 1 1] | 7 | 36.0
G30: [0 0 0 1] | 1 | 0.0
G31: [1 0 1 0] | 10 | 27.0
G32: [1 1 0 1] | 13 | 0.0
G33: [0 1 1 0] | 6 | 35.0
G34: [1 0 1 0] | 10 | 27.0
G35: [1 1 1 1] | 15 | -28.0
G36: [1 1 0 1] | 13 | 0.0
G37: [0 1 1 0] | 6 | 35.0
G38: [1 0 1 1] | 11 | 20.0
G39: [0 0 1 0] | 2 | 11.0
G40: [0 1 1 1] | 7 | 36.0
G41: [0 0 0 0] | 0 | -13.0
G42: [0 0 0 0] | 0 | -13.0
G43: [1 1 1 1] | 15 | -28.0
G44: [1 0 0 1] | 9 | 32.0
G45: [1 0 0 1] | 9 | 32.0
G46: [1 1 0 1] | 13 | 0.0
G47: [1 1 1 0] | 14 | -13.0
G48: [1 0 0 0] | 8 | 35.0
G49: [0 1 0 0] | 4 | 27.0
G50: [1 1 1 0] | 14 | -13.0
G51: [0 1 0 0] | 4 | 27.0
G52: [0 1 0 0] | 4 | 27.0
G53: [1 0 0 0] | 8 | 35.0
G54: [0 1 0 0] | 4 | 27.0
G55: [0 0 1 0] | 2 | 11.0
G56: [0 0 1 0] | 2 | 11.0
G57: [0 0 0 1] | 1 | 0.0
G58: [0 0 0 1] | 1 | 0.0
G59: [1 0 1 0] | 10 | 27.0
G60: [0 1 1 1] | 7 | 36.0
G61: [1 0 1 0] | 10 | 27.0
G62: [1 0 0 1] | 9 | 32.0
G63: [0 1 0 1] | 5 | 32.0
G64: [0 0 1 0] | 2 | 11.0
G65: [1 0 1 1] | 11 | 20.0
G66: [0 0 0 1] | 1 | 0.0
G67: [1 0 0 0] | 8 | 35.0
G68: [0 0 1 1] | 3 | 20.0
G69: [0 1 0 1] | 5 | 32.0
G70: [0 1 0 0] | 4 | 27.0
G71: [1 1 1 1] | 15 | -28.0
G72: [0 0 0 1] | 1 | 0.0
G73: [1 0 0 0] | 8 | 35.0
G74: [1 0 1 0] | 10 | 27.0
G75: [1 0 1 1] | 11 | 20.0
G76: [0 0 0 0] | 0 | -13.0
G77: [1 0 0 1] | 9 | 32.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
..
.

Hasil Seleksi untuk Next Generation ke->2:


nextG1: [0 1 1 1] | 7 | 36.0
nextG2: [0 1 1 1] | 7 | 36.0
nextG3: [0 1 1 1] | 7 | 36.0
nextG4: [0 1 1 1] | 7 | 36.0
nextG5: [0 1 1 1] | 7 | 36.0
nextG6: [0 1 1 1] | 7 | 36.0
nextG7: [0 1 1 1] | 7 | 36.0
nextG8: [0 1 1 1] | 7 | 36.0
nextG9: [0 1 1 1] | 7 | 36.0
nextG10: [0 1 1 1] | 7 | 36.0
nextG11: [0 1 1 1] | 7 | 36.0
nextG12: [0 1 1 1] | 7 | 36.0
nextG13: [0 1 1 0] | 6 | 35.0
nextG14: [1 0 0 0] | 8 | 35.0
nextG15: [1 0 0 0] | 8 | 35.0
nextG16: [0 1 1 0] | 6 | 35.0
nextG17: [1 0 0 0] | 8 | 35.0
nextG18: [1 0 0 0] | 8 | 35.0
nextG19: [1 0 0 0] | 8 | 35.0
nextG20: [1 0 0 0] | 8 | 35.0
nextG21: [1 0 0 0] | 8 | 35.0
nextG22: [1 0 0 0] | 8 | 35.0
nextG23: [1 0 0 0] | 8 | 35.0
nextG24: [0 1 1 0] | 6 | 35.0
nextG25: [1 0 0 0] | 8 | 35.0
nextG26: [1 0 0 0] | 8 | 35.0
nextG27: [0 1 1 0] | 6 | 35.0
nextG28: [0 1 1 0] | 6 | 35.0
nextG29: [0 1 1 0] | 6 | 35.0
nextG30: [0 1 1 0] | 6 | 35.0
nextG31: [0 1 1 0] | 6 | 35.0
nextG32: [0 1 1 0] | 6 | 35.0
nextG33: [0 1 1 0] | 6 | 35.0
nextG34: [0 1 1 0] | 6 | 35.0
nextG35: [0 1 1 0] | 6 | 35.0
nextG36: [1 0 0 0] | 8 | 35.0
nextG37: [0 1 1 0] | 6 | 35.0
nextG38: [1 0 0 0] | 8 | 35.0
nextG39: [1 0 0 1] | 9 | 32.0
nextG40: [1 0 0 1] | 9 | 32.0
nextG41: [1 0 0 1] | 9 | 32.0
nextG42: [0 1 0 1] | 5 | 32.0
nextG43: [1 0 0 1] | 9 | 32.0
nextG44: [1 0 0 1] | 9 | 32.0
nextG45: [1 0 0 1] | 9 | 32.0
nextG46: [0 1 0 1] | 5 | 32.0
nextG47: [0 1 0 1] | 5 | 32.0
nextG48: [1 0 0 1] | 9 | 32.0
nextG49: [1 0 0 1] | 9 | 32.0
nextG50: [1 0 0 1] | 9 | 32.0
nextG51: [0 1 0 1] | 5 | 32.0
nextG52: [0 1 0 1] | 5 | 32.0
nextG53: [1 0 0 1] | 9 | 32.0
nextG54: [1 0 0 1] | 9 | 32.0
nextG55: [0 1 0 1] | 5 | 32.0
nextG56: [1 0 0 1] | 9 | 32.0
nextG57: [1 0 0 1] | 9 | 32.0
nextG58: [0 1 0 1] | 5 | 32.0
nextG59: [1 0 0 1] | 9 | 32.0
nextG60: [1 0 0 1] | 9 | 32.0
nextG61: [0 1 0 1] | 5 | 32.0
nextG62: [1 0 0 1] | 9 | 32.0
nextG63: [1 0 0 1] | 9 | 32.0
nextG64: [1 0 1 0] | 10 | 27.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

Link kode program lengkapnya:


https://github.com/imamcs19/pyGA/blob/main/Koding%20Dasar%20Simple%20WebApp%20RESTful%20Py-
thon%20as%20BackEnd%20n%20PHP%20as%20FrontEnd%20untuk%20Algoritma%20Genetika.7z

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.

7.2 Operasi CRUD Python Flask – PHP


Laravel ( SQLite – MySQL dan
MongoDB Atlas )
7.2.1 Tentang Case Study
Pada Web App, operasi utama yang sering digunakan selalu
mengandung Create, Read, Update dan Delete (CRUD). Operasi CRUD
tersebut sangat dibutuhkan pada saat melakukan pengelolaan data
pada database. Kombinasi operasi CRUD dapat digunakan pada
komputasi umum, mulai dari hanya yang berupa sistem informasi
sampai komputasi yang menggunakan AI.

7.2.2 Snippet Kode Program

#Koding CRUD Flask SQLite - untuk General


Purpose

# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 5 April 2023
# Semoga Bermanfaat. Aamiin :D
# ====================================
#

@app.route('/myadmin/', methods = ['GET','POST'])


@app.route('/myadmin/<none_atau_lainnya>', methods = ['GET','POST'])
def myadmin(none_atau_lainnya=None):

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>

<!-- Add Contact Popup Model -->


<div id="add-contact" class="modal fade in"
tabindex="-1" role="dialog"
aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
..
.

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.

'''

if(none_atau_lainnya is not None):

list_none_atau_lainnya = none_atau_lainnya.split("-")
str_none_atau_lainnya = ' '.join(list_none_atau_lainnya)

# get jenis query edit atau del atau run


get_jenis_query = list_none_atau_lainnya[0]
get_nama_tabel = list_none_atau_lainnya[-1]

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]

# update pada Tabel data_tabel_myadmin, pada kolom teks_sintaks


db.execute("UPDATE data_tabel_myadmin SET teks_sintaks = ? WHERE
nama_tabel = ?",(var2_in_edit, var1_in_edit))

conn.commit()

elif(get_jenis_query == 'del'):
var1_in_hapus = request.form['nama_tabel_hapus_'+get_nama_tabel]

# hapus data pada Tabel data_tabel_myadmin, pada kolom nama_tabel


db.execute("DELETE FROM data_tabel_myadmin WHERE nama_tabel =
?",(var1_in_hapus,))

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]

# generate kode @app.route.. untuk flask_app.py


var3_in_gen += """

"""

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()

str_info = 'tabel berhasil dibuat :D'


# create tabel
db.execute("""
CREATE TABLE IF NOT EXISTS data_tabel_myadmin
(id INTEGER PRIMARY KEY AUTOINCREMENT, nama_tabel TEXT,
date_pembuatan DATETIME, teks_sintaks TEXT)
""")

conn.commit()

elif aksi== 'd':


conn = connect_db()
db = conn.cursor()

str_info = 'tabel berhasil dihapus :D'


# hapus tabel
db.execute("""
DROP TABLE IF EXISTS data_tabel_myadmin
""")

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()

# untuk membersihkan semacam cache setelah proses hapus tabel


# conn = connect_db_to_vacuum()
# db = conn.cursor()

db.execute("""
vacuum
""")

conn.commit()

# return str_info

if request.method == 'POST'

var1_in = request.form['nama_tabel']
var2_in = request.form['teks_sintaks']

# untuk mengkondisikan nama tabel tidak boleh ada spasi dan


hanya a-z dan angka
var1_in = " ".join(var1_in.split())
var1_in = var1_in.replace(" ","_").lower()
filter_var1_in =
"_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

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()

# Aksi => Buat, Hapus Tabel dari Tabel data_tabel_myadmin


aksi_sub = 'c'

if aksi_sub == 'c':
# conn = connect_db()
# db = conn.cursor()

str_info = 'tabel berhasil dibuat :D'


# create tabel
db.execute("""
CREATE TABLE IF NOT EXISTS """ + var1_in + """
(kolom2 TEXT, kolom3 DATETIME, kolom4 TEXT)
""")

conn.commit()

"""Mengisi data untuk spesifikasi tabel."""


# conn = connect_db()
# db = conn.cursor()

db.execute("SELECT * FROM data_tabel_myadmin WHERE nama_tabel =


?", (var1_in,))
entry = db.fetchone()

if entry is None:
import numpy as np
import pandas as pd

from datetime import datetime


import pytz
Date = str(datetime.today().astimezone(pytz.
timezone('Asia/Jakarta')).strftime('%d-%m-%Y %H:%M:%S'))

db.execute("""INSERT INTO data_tabel_myadmin (nama_tabel,


date_pembuatan, teks_sintaks) VALUES (?, ?, ?)""",
(var1_in, Date, var2_in))

else:
ket_hasil = 'Tidak dilakukan Insert,
karena Tabel tidak kosong'

conn.commit()

elif aksi_sub== 'd':


# conn = connect_db()
# db = conn.cursor()

str_info = 'tabel berhasil dihapus :D'


# hapus tabel
db.execute("""

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.

DROP TABLE IF EXISTS """ + var1_in + """


""")

conn.commit()

# untuk membersihkan semacam cache setelah proses hapus tabel


# conn = connect_db_to_vacuum()
# db = conn.cursor()

db.execute("""
vacuum
""")

conn.commit()
# db.close()
# conn.close()

c = db.execute(""" SELECT * FROM data_tabel_myadmin """)

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)

else: # untuk yang 'GET' data awal untuk di send ke /myadmin

c = db.execute(""" SELECT * FROM data_tabel_myadmin """)

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)

Output Python Flask-SQLite:

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.

Output PHP Laravel – MySQL & MongoDB:

Link kode program lengkapnya:


https://github.com/imamcs19/pyIntroMLearn
https://github.com/imamcs19/ScrapingNothers-toOneDataNothers/tree/master/PyPHP

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.

7.3 Smart Big Data App (Python Web


Django + Mobile Native + CLI +
RestFul API) untuk Klasifikasi
7.3.1 Tentang Case Study
Ekosistem integrasi sederhana yang dikembangkan dibuat
untuk menghubungkan antara Framework Web App Django, Mobile
dengan kode Native, Hadoop untuk proses Map Reduce (MR) from
scratch dan Spark (MLlib, RDD atau Spark SQL) dengan kode dari CLI
atau notebook, menggunakan RestFul API. API yang ada dibuat dengan
mengakses hasil run kode pada CLI untuk dipaketkan dalam bentuk
json atau ekstensi lainnya.

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.

7.3.2 Snippet Kode Program

#Koding Map Reduce dengan Hadoop untuk


Algoritma Naïve Bayes Classifier

# ============================
# 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;

public class NBCDriver {


public static void main(String[] args) throws IOException,
InterruptedException, ClassNotFoundException {
Configuration conf=new Configuration();
// The test input for which you want to find the acitivity ..
conf.set("test_input", args[0]);
Job job = new Job(conf);
job.setJarByClass(NBCDriver.class);
job.setJobName("Naive_Bayes_calssifier using Hadoop");
FileInputFormat.setInputPaths(job, new Path(args[1]));
FileOutputFormat.setOutputPath(job, new Path(args[2]));
job.setMapperClass(NBCMap.class);
job.setReducerClass(NBCReduce.class);
job.setMapOutputKeyClass(IntWritable.class);
job.setMapOutputValueClass(Text.class);
job.setOutputKeyClass(IntWritable.class);
job.setOutputValueClass(Text.class);
boolean success = job.waitForCompletion(true);

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;

public class NBCMap extends Mapper<LongWritable, Text, IntWritable, Text>{


public static String output_key;
public static String[] test_input=null;
public static int count=0;
public static HashMap<String,Integer> inputs=new HashMap<String,Integer>();
public static double output_value=Double.NEGATIVE_INFINITY;
public static HashMap<String,Double> output= new HashMap<String,Double>();
public static HashMap<String,Double> outcome_count=
new HashMap<String,Double>();
public static HashMap<String,Double> features_count=
new HashMap<String,Double>();
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
if(test_input==null)
test_input=context.getConfiguration().get("test_input").split("\\,");
String[] input=value.toString().split("\\,");
for(int j=0;j<input.length;j++){
if(j==input.length-1){
if(outcome_count.containsKey(input[j]))
outcome_count.put(input[j], outcome_count.get(input[j])+1);
else
outcome_count.put(input[j], (double) 1);
}
else{
if(input[j].contentEquals(test_input[j])){
if(!inputs.containsKey(j+","+input[j]))
inputs.put(j+","+input[j], 0);
if(features_count.containsKey(j+","+input[j]+"|"
+input[input.length-1]))
features_count.put(j+","+input[j]+"|"+input[input.length-1],
features_count.get(j+","+input[j]+"|"+input[input.length-1])+1);
else
features_count.put(j+","+input[j]+"|"+input[input.length-1],
(double) 1);
}
}
}
++count;
}
public void cleanup(Context context) throws IOException,
InterruptedException{

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.

#jika compile di Win OS | *.java to *.class

!javac -cp
"%HADOOP_HOME%\share\hadoop\common\*;%HADOOP_HOME%\share\hadoop\mapreduce\*"
*.java

#jika compile di Linux OS


#!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.

Reduce shuffle bytes=18


Reduce input records=1
Reduce output records=1
Spilled Records=2
Shuffled Maps =1
Failed Shuffles=0
Merged Map outputs=1
GC time elapsed (ms)=376
CPU time spent (ms)=4527
Physical memory (bytes) snapshot=468930560
Virtual memory (bytes) snapshot=751235072
Total committed heap usage (bytes)=414187520
Shuffle Errors
BAD_ID=0
CONNECTION=0
IO_ERROR=0
WRONG_LENGTH=0
WRONG_MAP=0
WRONG_REDUCE=0
File Input Format Counters
Bytes Read=192
File Output Format Counters
Bytes Written=6

Hasil klasifikasi:
!hadoop fs -cat ./user/ImamCS/nb/output2/*
Study

#Koding views.py dengan Framework Django untuk


run spark-submit dan hadoop bin

# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 12 November 2019
# Semoga Bermanfaat. Aamiin :D
# ====================================
#

from django.shortcuts import render


import string
import random
import os
import shutil
import subprocess

import json

from django.http import HttpResponse


from django.views.decorators.csrf import csrf_exempt

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))

# make random string


def randomString(stringLength):
"""Generate a random string, comb. of lowercase and uppercase letters """

letters = string.ascii_letters
return ''.join(random.choice(letters) for i in range(stringLength))

def get_merge_local(file_out, dir_input):


with open(file_out, 'wb') as outfile:
for filename in os.listdir(dir_input):

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.

if filename == file_out or filename[0] == ".":


continue
with open(dir_input+"/"+filename, 'rb') as readfile:
shutil.copyfileobj(readfile, outfile)

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

# Create your views here.


def index(request):
return render(request, 'index.html')

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'])

dataset = pd.read_csv(dataset, delimiter=';', \


names = ['Tanggal', 'Harga'], usecols=['Harga'])
minimum = int(dataset.min()-10000)
maksimum = int(dataset.max()+10000)
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)
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):]

#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,

# tlg masing" sign up mandiri ke https://openweathermap.org/appid


weather_url = "http://api.openweathermap.org/data/2.5/weather" # get kondisi
#weather_url = "http://api.openweathermap.org/data/2.5/forecast" # get pred
city_name = "Malang"

r = requests.get(weather_url, params={'q': city_name, 'APPID': apikey})


r.url # `requests` help us encode the URL in the correct format
r.status_code # 200 means success
result = r.json()
return render(request, 'week3.html', {
'result': result,
'celcius': result['main']['temp']-273.15
})

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])

with open(file_input, "wb+", buffering=0) as file:


file.write(memory_input)
file.flush()
os.fsync(file)
del memory_input

#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]

#delete output dir


run_process(["rm", "-r", dir_output])
return render(request, 'week41.html', {
'value' : value,
'mapes' : mape,
'mape' : mape[-1]
})
else:
return render(request, 'week41.html')

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])

#Return if error occured


if exitcode :
return render(request, 'Error.html', {
'exitcode' : exitcode,
'stdout' : stdout,
'stdin' : stdin
})

#download file (Not Supported)

#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(" ")))

#delete output dir


run_process(["rm", "-r", dir_output])

#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])

#Return if error occured


if exitcode :
return render(request, 'Error.html', {
'exitcode' : exitcode,
'stdout' : stdout,
'stdin' : stdin
})

#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(" ")))

#delete output dir


run_process(["rm", "-r", dir_output])

#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])

#Return if error occured


if exitcode :
return render(request, 'Error.html', {
'exitcode' : exitcode,
'stdout' : stdout,
'stdin' : stdin
})

#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(" ")))

#delete output dir


run_process(["rm", "-r", dir_output])

#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

def nb_run(request, type_api=True):

# make unique directory


output_dir = randomString(10)

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 if error occured


if exitcode :
cetak = exitcode
else :
cetak = run_process([HADOOP_BIN, 'fs', '-cat' , \
'/user/ubuntu/nb-output/'+output_dir+'/*'])

#delete output dir


run_process([HADOOP_BIN, "fs", "-rm", "-r", \
'/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 })

return HttpResponse(response, content_type='text/json')

Output:

(a)

(b)

#Koding Android MainActivity.java dengan Native


Code untuk Call API Algoritma Naïve Bayes

# ============================
# 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;

public class MainActivity extends AppCompatActivity{

OkHttpClient client = new OkHttpClient();


ProgressDialog progressDialog;
EditText fitur1, fitur2, fitur3;
Button btnSub;
Button btnKelompok;
private static final String url = "http://54.204.185.51:8001/api/naive";
String fitur_1, fitur_2, fitur_3;
String mMessage;
String hasilPredic;
private static final String TAG = "prediksi";

@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= (Button) findViewById(R.id.btnSubmit);


btnKelompok= (Button) findViewById(R.id.btnKelompok);

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);

// Progress Dialog Style Spinner


progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);

OkHttpClient.Builder builder = new OkHttpClient.Builder();


builder.connectTimeout(5, TimeUnit.MINUTES) // connect timeout
.writeTimeout(5, TimeUnit.MINUTES) // write timeout
.readTimeout(5, TimeUnit.MINUTES); // read timeout

client = builder.build();

try {
postRequest();
} catch (IOException e) {
e.printStackTrace();
}
}
});

btnKelompok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alertDialogKelompok();
}
});
}

private void postRequest() throws IOException {


MediaType MEDIA_TYPE = MediaType.parse("application/json");

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.

JSONObject postdata = new JSONObject();


try {
postdata.put("fitur_1", fitur_1);
postdata.put("fitur_2", fitur_2);
postdata.put("fitur_3", fitur_3);
} catch (JSONException e) {
e.printStackTrace();
}

RequestBody body = RequestBody.create(MEDIA_TYPE, postdata.toString());


Request request = new Request.Builder()
.url(url)
.post(body)
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.build();

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);

//Dismiss the dialog


progressDialog.dismiss();
}

@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();

JSONObject json = new JSONObject(mMessage);


hasilPredic = json.getString("prediksi");
} catch (JSONException e) {
e.printStackTrace();
}
alertDialog();
}
});
Log.e(TAG, mMessage);
}
});
}

private void alertDialog() {


AlertDialog.Builder Peringatan = new AlertDialog.Builder(this);
Peringatan.setTitle("Hasil Klasifikasi");
Peringatan
.setMessage(hasilPredic)
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface Peringatan, int id) {
Peringatan.dismiss();
}
}).show();
}

private void alertDialogKelompok() {


AlertDialog.Builder Peringatan = new AlertDialog.Builder(this);
Peringatan.setTitle("All Teams");
Peringatan
.setMessage("1. Imam Cholissodin \n2. Diajeng Sekar Seruni
\n3. Junda Alfiah Zulqornain \n4. Audi Nuermey Hanaf
\n5. Afwan Ghofur \n6. Mikhael Alexander
\n7. Muhammad Ismail Hasan")
.setCancelable(false)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
@Override

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.

public void onClick(DialogInterface Peringatan, int id) {


Peringatan.dismiss();
}
}).show();
}
}

Output:

Link kode program lengkapnya:


https://github.com/imamcs19/Big-Data-App-based-AI-with-or-without-Web-and-Mobile-Interface-by-
RESTful-API-Using-Hadoop-and-Spark

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.

7.4 Smart Big Data App (Python Web


Django + Mobile Node Js + RestFul
API) untuk Prediksi
7.4.1 Tentang Case Study
Integrasi sederhana yang kedua dibuat sebagai contoh untuk
menghubungkan antara API yang dipasang pada Framework Web App
Django, lalu diakses dari client berupa Mobile App yang dibuat dengan
Node JS. Hasil akses API dari format json lalu ditampilkan dalam bentuk
line chart yang membandingkan hasil dari Y aktual vs Y prediksi.

7.4.2 Snippet Kode Program

#Koding Mobile Apps dengan Node JS – Ionic |


tab1.page.ts untuk Prediksi data

# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id, & Teams
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 10 Oktober 2019
# Semoga Bermanfaat. Aamiin :D
# ====================================
#

import { Component, ViewChild } from '@angular/core';


import { debug } from 'util';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { NavController } from '@ionic/angular';

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.

import { ModalController } from '@ionic/angular';


import { ModalPage } from '../modal/modal.page';

@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)

dataset = pd.read_csv(url, delimiter=';', names = ['Tanggal', 'Harga'],


usecols=['Harga'])
dataset = dataset.fillna(method='ffill')

# print("missing value", dataset.isna().sum())

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)))

# cek matrik singular


cek_matrik = np.dot(np.transpose(h), h)
det_cek_matrik = np.linalg.det(cek_matrik)
if det_cek_matrik != 0:
is_singular_matrix = False
else:
is_singular_matrix = True

h_plus = np.dot(np.linalg.inv(cek_matrik), np.transpose(h))

# 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()

response = jsonify({'y_aktual': aktual, 'y_prediksi': prediksi,


'mape': mape})

# Enable Access-Control-Allow-Origin
response.headers.add("Access-Control-Allow-Origin", "*")

return response

# get json data from a url using flask in python


@app.route('/baca_api', methods=["GET"])
def baca_api():
import requests
import json
# uri = "https://api.stackexchange.com/2.0/
users?order=desc&sort=reputation&inname=fuchida&site=stackoverflow"

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
*/
// ===========

//var url = ('https://cors-anywhere.herokuapp.com/3.92.195.0:8000/api&' +


//this.input + '&' + this.input2 + '&' + this.input3);
var url = (' https://imamcs.pythonanywhere.com/api/fp/3.0/?a=' +
this.input + '&b=' + this.input2 + '&c=' + this.input3);

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:

Link kode program lengkapnya (pada no. 5):


https://github.com/imamcs19/Big-Data-App-based-AI-with-or-without-Web-and-Mobile-Interface-by-
RESTful-API-Using-Hadoop-and-Spark

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.

7.5 Python Web Flask untuk Prediksi


7.5.1 Tentang Case Study
Penerapan prediksi data dengan memanfaatkan teknologi PaaS
atau semacam teknologi cloud sangat memudahkan dalam
pengembangan Ekosistem Web App. Pada bagian tahap instalasi
dilakukan beberapa langkah untuk pemasangan Spark dan Hadoop
yang menggunakan versi terbaru pada saat sistem ini dibuat, dari Web
Apache. Pada contoh implementasi sederhana di bawah ini digunakan
algoritma Regresi Linear dari Library PySpark dan Algoritma Extreme
Learning Machine (ELM) dengan Web Framework Flask.

7.5.2 Snippet Kode Program

#Koding Framework Flask – Algoritma Extreme


Learning Machine (ELM) dari Koding From Scratch
untuk Prediksi

# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 16 Agustus 2021
# Semoga Bermanfaat. Aamiin :D
# ====================================
#

@app.route("/bigdataApps", methods=["GET", "POST"])


def bigdataApps():

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)))

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_template('bigdataApps.html', y_aktual = \


list(aktual), y_prediksi = list(predict), mape = mape)

else:
return render_template('bigdataApps.html')

#Koding Framework Flask – Algoritma Regresi Linear


dari Sklearn untuk Prediksi

# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 16 Agustus 2021
# Semoga Bermanfaat. Aamiin :D
# ====================================
#

@app.route("/contohfp2_nonspark", methods=["GET", "POST"])


def contohfp2_nonspark():
import numpy as np
import pandas as pd
import os.path

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.

X_train, X_test, y_train, y_test = train_test_split(X, y, \


test_size = 1/3, random_state = 0)

# Fitting Simple Linear Regression to the Training set


from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)

# Predicting the Test set results


y_pred = regressor.predict(X_test)
y_pred2 = regressor.predict(X_train)

aktual, predict = y_train, y_pred2


mape = np.sum(np.abs(((aktual - predict)/aktual)*100))/len(predict)

return render_template('MybigdataAppsNonPySpark.html',\
y_aktual = list(y_train), y_prediksi = list(y_pred2), mape = mape)

Output:

#Koding Framework Flask – Algoritma Regresi Linear


dari Lib. PySpark untuk Prediksi

# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 16 Agustus 2021
# Semoga Bermanfaat. Aamiin :D
# ====================================
#

@app.route("/contohfp2_spark", methods=["GET", "POST"])


def contohfp2_spark():
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os

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()

from pyspark.sql import SparkSession


spark = SparkSession.builder.appName("Linear Regression Model").getOrCreate()

from pyspark.ml.regression import LinearRegression


from pyspark.ml.linalg import Vectors
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.feature import IndexToString, StringIndexer

from pyspark import SQLContext, SparkConf, SparkContext


from pyspark.sql import SparkSession
sc = SparkContext.getOrCreate()
if (sc is None):
sc = SparkContext(master="local[*]", appName="Linear Regression")
spark = SparkSession(sparkContext=sc)

sqlcontext = SQLContext(sc)
data = sqlcontext.read.csv(url, header = True, inferSchema = True)

from pyspark.ml.feature import VectorAssembler


# mendifinisikan Salary sebagai variabel label/predictor
dataset = data.select(data.YearsExperience, data.Salary.alias('label'))
# split data menjadi 70% training and 30% testing
training, test = dataset.randomSplit([0.7, 0.3], seed = 100)
# mengubah fitur menjadi vektor
assembler = \
VectorAssembler().setInputCols(['YearsExperience',]).setOutputCol('features')
trainingSet = assembler.transform(training)
# memilih kolom yang akan di vektorisasi
trainingSet = trainingSet.select("features","label")

from pyspark.ml.regression import LinearRegression


# fit data training ke model
lr = LinearRegression()
lr_Model = lr.fit(trainingSet)
# assembler : fitur menjadi vektor
testSet = assembler.transform(test)
# memilih kolom fitur dan label
testSet = testSet.select("features", "label")
# fit testing data ke model linear regression
testSet = lr_Model.transform(testSet)
# testSet.show(truncate=False)

from pyspark.ml.evaluation import RegressionEvaluator


evaluator = RegressionEvaluator()
# print(evaluator.evaluate(testSet, {evaluator.metricName: "r2"}))

y_pred2 = testSet.select("prediction")

# r2 sebaiknyaa diubah menjadi mape atau lainnya


return render_template('MybigdataAppsPySpark.html', \
y_aktual = y_pred2.rdd.flatMap(lambda x: x).collect(), y_prediksi = \
y_pred2.rdd.flatMap(lambda x: x).collect(), \
mape = evaluator.evaluate(testSet, {evaluator.metricName: "r2"}))

Konfigurasi dan kode dasar PySpark di Terminal (CLI) Online:


1 tar -xf *.tar -C ./
..
.
21 export SPARK_HOME="/home/imamcs/mysite/spark-3.1.2-bin-hadoop3.2"
23 export PATH=$PATH:$SPARK_HOME/bin:$SPARK_HOME/sbin
24 export PYTHONPATH=$SPARK_HOME/python/lib/py4j-0.10.9-src.zip:$PYTHONPATH
26 export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
27 export PATH=$PATH:$JAVA_HOME:$JAVA_HOME/jre/bin
28 chmod -R 777 /home/imamcs/mysite/*
34 source ~/.bashrc
37 pip3.7 install --user findspark
39 export SPARK_HOME="/home/imamcs/mysite/spark-3.1.2-bin-hadoop3.2"
43 export PATH=$PATH:$SPARK_HOME/bin:$SPARK_HOME/sbin
47 source ~/.bashrc
48 cd /home/imamcs/.local/lib/python3.7/site-packages/

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

------------ Start Log kode dasar 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
/_/

Using Python version 3.9.5 (default, May 27 2021


19:45:35)
Spark context Web UI available at http://ip-10-0-0-57.ec2.internal:4040
Spark context available as 'sc' (master = local[*], app id = local-1659937655425).
SparkSession available as 'spark'.
>>> def add1(x): return
x+1
...
>>> list(map(add1,[1,2,3]))
[2, 3,
4]
>>> def isOdd(x): return x%2==1
...
>>> list(filter(isOdd,
range(1,10)))
[1, 3, 5, 7, 9]
>>> list(range(1,5))
[1, 2, 3, 4]
>>> def add(x,y): return x+y
...
>>> from functools import reduce
>>> re-
duce(add,range(1,5))
10
>>> (lambda x:2*x)(3)
6
>>> list(map(lambda
x:2*x,[1,2,3]))
[2, 4, 6]

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.

>>> list(map(lambda t:t[0],[(1,2),(3,4),(5,6)]))


[1, 3,
5]
>>> reduce(lambda x,y:x+y,[1,2,3])
6
>>> reduce(lambda x,y:x+y,map(lambda t:t[0],[(1,2),(3,4),(5,6)]))
9
>>> a=[(1,2),(3,4),(5,6)]
>>>
>>> list(map(lambda t:t[1],a))
[2, 4, 6]
>>> reduce(lambda x,y:x+y,map(lambda t:t[1],a))
12
>>> reduce(lambda x,y:x+y,filter(isOdd,map(lambda t:t[0],a)))
9
>>> print("cek buku ajar analisis big data hal. 118 - 127 dari link:
http://bit.ly/2FMLnfw")
cek buku ajar analisis big data hal. 118 - 127 dari link: http://bit.ly/2FMLnfw
>>>

Output:

Link kode program lengkapnya:


https://github.com/imamcs19/FGA-Big-Data-Using-Python-Filkom-x-Mipa-UB-2021 &
https://github.com/imamcs19/FGA-Big-Data-Using-Python-Filkom-x-Mipa-UB-2022

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.

7.6 Prototype Big Data Studio: Jupyter


Notebook + PySpark Multi-Node, dll
untuk Hadoop Distribution (edUBig /
UBig Apps Product)
7.6.1 Tentang Case Study
Pengembangan kemudahan dan kecepatan dalam membangun
infrastruktur ekosisten Big Data dalam inisiasi pembuatan Big Data
Studio atau disebut sebagai nama Distro untuk kerangka kerja dalam
membuat Big Data Apps telah dilakukan oleh beberapa developer dari
bidang big data mulai dari Cloudera (CDH), Horton Work (HDP), dan
MapR yang lebih banyak digunakan untuk versi enterprise. Selain itu,
jika dilihat dari bidang pendidikan baik formal maupun nonformal,
banyak pelajar maupun orang awam yang mempelajari tentang big
data merasa kesulitan dalam melakukan proses pembelajaran, apalagi
jika proses pembelajaran dilakukan secara lokal dan lengkap tanpa
server (serverless), atau dengan server cloud yang terbatas.

Pada bagian ini dibahas sebagai contoh pembuatan distro


hadoop sederhana dengan nama 'edUBig' atau "UBig" yang
dimodifikasi dari “André Perez” dengan menambahkan “Additional:
Zookeeper, Kafka & port - 8501:8501 untuk support Streamlit pada
saat dijalankan JupyterLab” yang dibuat dengan menggunakan Docker
dengan tujuan agar lebih mudah untuk dibuat secara mandiri oleh
setiap mahasiswa baik mahasiswa maupun masyarakat umum sebagai
solusi pengembangan yang bagus untuk berbagai bidang, khususnya
untuk level up media pembelajaran Big Data di kelas regular, ToT
maupun di kegiatan pelatihan semacam FGA Big Data Using Python

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.

yang diadakan oleh kominfo pusat kerjasama dengan IBM, AWS


Educate, Cisco Academy beserta beberapa kampus di Indonesia,
termasuk Fakultas Ilmu Komputer (Filkom) UB sejak ± tahun 2019 dan
MIPA UB sejak ± tahun 2022.

7.6.2 Snippet Kode Program

#Koding Build Infrastruktur Big Data - Docker


untuk Edukasi di Kelas dan Pelatihan

# ============================
# 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
...

Penjelasan live di Youtube Channel :D


Link: https://youtu.be/bAOzlUdId44 dan https://youtu.be/jERYNSBfzj0

Link kode program lengkapnya:


https://github.com/imamcs19/edubig-spark-standalone-cluster-and-support-streamlit-port-on-docker

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.

7.7 Pengembangan Web App untuk IoT


Simulator x Node-RED x Node JS
7.7.1 Tentang Case Study
Istilah "IoT" sering dikaitkan dengan Kevin Ashton yang pada
tahun 1997 dan pekerjaannya di Procter and Gamble menggunakan
tag RFID untuk pengelolaan rantai pasok (Azman, 2020) yang mana
terdapat jaringan yang menghubungkan objek fisik dengan internet.
Pada era modern sekarang ini dengan berkembangnya teknologi Cloud
menyebabkan meningkatnya penggunaan dari IoT untuk berbagai
sektor strategis dan menjadi bagian utama untuk memberikan
kemudahan dan manfaat besar pada kegiatan kehidupan sehari-hari.
Perkembangan IoT juga turut mempengaruhi perkembangan
penggunaan komponen IoT dalam bidang robotika untuk
meningkatkan efisiensi dan jangkauan perangkat dari perangkat yang
dibuat. Sedangkan Node-RED seperti yang ditunjukkan pada Gambar 3
adalah tools berbasis web untuk pemrograman visual dengan fungsi
javascript yang dikembangkan oleh IBM untuk menghubungkan
perangkat keras, Application Programming Interface (API), dan service
atau lainnnya dari IoT. Sebelum dilakukan implementasi pada
perangkat yang digunakan perlu melakukan percobaan awal pada
sebuah simulator, dimana lingkungan pada simulator tersebut
dimiripkan dengan kondisi yang ada lingkungan perangkat yang akan
diimplementasikan sehingga dapat menjadi suatu landasan peneliti
dan menghemat biaya atau operasional usaha yang dibutuhkan untuk
mencapai hasil yang optimal dari penelitian.

Gambar 7.1 Simple Arsitektur Dashboard UI sistem monitoring secara


Real Time IoT Simulator Berbasis Web

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.

7.7.2 Snippet Kode Program

#Koding package.json untuk IoT Simulator x Node-


RED berbasis Web

# 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"
}
}

#Langkah-langkah deploy ke heroku (alternatif


deploy bisa ke app.netlify.com atau lainnya untuk
App yang bersifat native), cek detailnya pada link
https://bit.ly/43aYLm3

# Ketikkan “git push heroku master”

# D:\..\fpiot-master>git push heroku master


# Enumerating objects: 96, done.
# Counting objects: 100% (96/96), done.
# Delta compression using up to 4 threads
# Compressing objects: 100% (82/82), done.
# Writing objects: 100% (96/96), 412.75 KiB | 4.17 MiB/s, done.
# Total 96 (delta 4), reused 0 (delta 0), pack-reused 0
# remote: Compressing source files... done.
# remote: Building source:
# ..
# .
# remote: -----> Compressing...
# remote: Done: 80.4M
# remote: -----> Launching...
# remote: Released v3
# remote: https://fpiot-2022.herokuapp.com/ deployed to Heroku
# remote:
# remote: Verifying deploy... done.
# To https://git.heroku.com/fpiot-2022.git
# * [new branch] master -> master

# C:\Users\imamcs\Downloads\fpiot-master>

# Contoh menggunakan Framework Python - Flask


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

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)]

# Membuat figure dari lib. Plotly


fig = {
'data': [
{'x': my_x_dump, 'y': my_y1_dump, \
'type': 'scatter', 'name': 'Line 1'},
{'x': my_x_dump, 'y': my_y2_dump, \
'type': 'scatter', 'name': 'Line 2'}
],
'layout': {
'title': 'Line Chart Statis dengan tipe Lines'
}
}

# Render template dalam bentuk string


my_template_string = '''
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Real-Time IoT Simulator - Sistem Monitoring</title>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/
bootstrap/3.3.7/css/bootstrap.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/
bootstrap.min.js"></script>

</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'
}
};

// deklarasi layout untuk chart


const layout = {
title: 'Real-Time IoT Simulator Monitoring Suhu
(update tiap 1 detik)',
xaxis: { title: 'Waktu' },
yaxis: { title: 'Suhu (Celcius)' }
};

// inisialisasi chart dengan empty trace dan layout


const chart = Plotly.newPlot('chart', [trace], layout);

// akses data api suhu dgn interval tiap detik


setInterval(() => {
fetch('/gen_suhu')
.then(response => response.json())
.then(data => {
// append dari data baru ke dalamtrace
const update = {
x: [[new Date()]],
y: [[data.value]]

};
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)

Link kode program lengkapnya:


github.com/imamcs19/Auto-Ai-Model-Generatif-untuk-Prediksi-Kompleksitas-Waktu-Algoritma-dgn-ELM

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.

7.8 Pengembangan Web App Node JS


untuk Prototipe Full Stack Apps
NodeJS merupakan perangkat teknologi yang terdiri dari
asynchronous event-driven JS runtime environment dan Library
sebagai bahan dasar yang digunakan untuk pengembangan dalam
membuat misal framework (seperti ExpressJS, Flutter, React, Vue, dan
lainnya) untuk kemudahan dalam membuat Web maupun Mobile
Apps baik front-end maupun back-end berbasis bahasa pemrograman
Javascript yang mudah manajemen skalabilitasnya ketika melibatkan
sedikit atau banyak koneksi jaringan, serta mampu auto idle / sleep
ketika tidak ada task yang dikerjakan. Teknologi ini bersifat open-
source dan cross-platform. Meskipun pada prakteknya, beberapa
pengembang melihat pada folder “node_modules” cukup besar
ukurannya, barangkali nanti ke depannya sudah tertanam dalam file
master NojeJS.

7.8.1 Instalasi & Konfigurasi


Pada instalasi, Anda perlu untuk install vs code, Node.js lalu
siapkan kode yang ingin dijalankan. Sebaiknya semua file kode
program telah dipindahkan dari workspace project tanpa
memasukkan folder “node_modules” agar lebih ringan ukurannya.
Berikut langkah-langkah praktis dalam menjalankan aplikasinya.
• Pada sub folder project “\api”
o Ketikkan pada terminal vs code / code server “npm install”
(khusus untuk awal instalasi)

o lalu “npm start”.

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.

• Pada sub folder project “\client”


o Ketikkan pada terminal vs code / code server “npm install”
(khusus untuk awal instalasi)
o lalu “npm start”, tunggu beberapa waktu.

7.8.2 Snippet Kode Program

#Koding Implementasi Login, dll + API | pada


..\client\src\pages\Login.js

# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 28 Januari 2023
# Semoga Bermanfaat. Aamiin :D
# ====================================
#

import React, { useEffect } from 'react';


import { Button, Col, Form, Input, message, Row } from 'antd';
import '../resources/authentication.css';
import axios from 'axios';
import { Link, useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { BASE_URL } from '../constant/axios';
import logo from '../resources/myLogo.png';
import * as Yup from "yup";

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();

// Write function to login


let handleSubmit = async (values) => {

let res = await axios.post(


`${BASE_URL}/api/ausers/login`,
values
);

// If statusCode is 200 then condition wii be true and set token


// and name in sessionStorage and navigate to dashboard
if (res.data.statusCode == 200) {
// res.json(res.data.statusCode)
message.success('values.userId = '+ values.userId +
' values.password = '+ values.password);

message.success('Hello '+res.data.name+' Login Berhasil,


base url = '+`${BASE_URL}`+ ' res.data.token ='+ res.data.token);

sessionStorage.setItem("userId", res.data.userId);
sessionStorage.setItem("password", res.data.password);

localStorage.setItem('mydata', JSON.stringify(res.data));

console.log('res.data.name = ' + res.data.name);


console.log('res.data.token = ' + res.data.token);
console.log('base url = '+`${BASE_URL}`);

navigate("/daftarorderan");

}
else if (res.data.statusCode == 400) {
message.error('Terjadi Kesalahan User & Password ');
}
};

const onFinish = (values) => {


if (!values.userId){
return message.error("ID Pengguna Harus Diisi Bro")
}
if (!values.password){
return message.error("Password Harus Diisi Bro")
}
dispatch({ type: 'showLoading' });

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>

<Form.Item name='userId' label='ID Pengguna'>


<Input />
</Form.Item>
<Form.Item name='password' label='Password'>
<Input type='password' />
</Form.Item>

<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>
);
}

export default Login;

Output:

#Koding Implementasi Login, dll + API | pada


..\api\routes\auserRoute.js
..\api\models\auserModel.js dan
..\api\controllers\auserController.js

# ============================
# 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");

const DataTypes = Sequelize;

/*
CREATE TABLE a_users (
userId STRING PRIMARY KEY,
role TEXT,
password TEXT,
name TEXT,
isArchive BOOLEAN,
timestamps STRING
); */

const Auser = db.define('Ausers',{


userId:{
type: DataTypes.STRING,
primaryKey: true
},
role:{
type: DataTypes.TEXT
},
password:{
type: DataTypes.TEXT
},
name:{
type: DataTypes.TEXT
},
isArchive:{
type: DataTypes.BOOLEAN
},
timestamps:{
type: DataTypes.STRING
},
createdAt:{
type: DataTypes.DATE
},
updatedAt:{
type: DataTypes.DATE
}
},{
freezeTableName: true
});

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
# ---------------------------------------

const AuserModel = require('../models/auserModel');


var {hashPassword, hashCompare,createToken,verifyToken} = require("../auths");

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
}
});

var userVal = await AuserModel.findAll({


where: {
userId: req.body.userId,
password: req.body.password
}
}).then(function(result){
return result;
});

console.log('user.count = ' + user.count +


' userVal[0].name = ' + userVal[0].name);

if (user.count >= 0){


if (user.count == 0){
res.json({
statusCode: 400,
message: "Invalid User or Password",
});
}
else{
console.log('userVal[0].name = ' + userVal[0].name);
let token = await
createToken(userVal[0].userId,userVal[0].name,userVal[0].role )

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);
}
},

deleteUser: async (req, res) => {


try {
await AuserModel.findOneAndUpdate({ _id: req.params.id},
{isArchive: true});

res.send('User Berhasil Dihapus');


} catch (error) {
res.status(400).json(error);
}
},
};

Output:

Link kode program lengkapnya:


https://github.com/imamcs19/nodePy

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.

7.9 Dashboard untuk Integrasi Real-


Time Cloud-AI Berbasis Web dan
Pengujian Sistem
7.9.1 Tentang Case Study
Pengembangan dashborad untuk contoh integrasi secara real-
time teknologi Cloud-AI berbasis web, misal untuk mengakses keadaan
lingkungan dari suhu, kelembaban dan lainnya dari provider API yang
menyediakan data tersebut secara free. Data kondisi lingkungan
tersebut dapat diterapkan metode misal machine learning untuk
prediksi nilai target yang akan datang dengan tujuan tertentu sesuai
kebutuhan, misal dalam hal ini dicoba untuk memberikan
rekomendasi lama waktu pengairan pada tanaman.

Gambar 7.2 Simple Dashboard Arsitektur untuk Integrasi Real Time


Cloud-AI Berbasis Web

Simple dashboard tersebut juga dapat digunakan sebagai


interface pengujian sistem yang berbasis algoritma dari sistem cerdas.
Pada bagian berikut diberikan contoh tampilan pengujian dari model
yang digunakan untuk persiapkan deploy aplikasi agar dapat diuji coba
oleh kalangan yang lebih luas.

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.

7.9.2 Snippet Kode Program

#Koding Simple Dashboard Integrasi Real Time


Cloud-AI Berbasis Web

# ============================
# 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)

dataset = pd.read_csv(url, delimiter=';', \


names = ['Tanggal', 'Harga'], usecols=['Harga'])
#dataset = pd.read_csv(url, usecols=['Close'])
dataset = dataset.fillna(method='ffill')

# print("missing value", dataset.isna().sum())

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))

# cek matrik singular


cek_matrik = np.dot(np.transpose(h), h)
det_cek_matrik = np.linalg.det(cek_matrik)
if det_cek_matrik != 0:
#proceed

#if np.linalg.cond(cek_matrik) < 1/sys.float_info.epsilon:


# i = np.linalg.inv(cek_matrik)
is_singular_matrix = False
else:
is_singular_matrix = True

h_plus = np.dot(np.linalg.inv(cek_matrik), np.transpose(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.

<div class="col-md-6 col-lg-3 col-sm-6 col-xs-12">


<div class="bg-info white-box m-b-0">
<ul class="expense-box">
<li><i class="ti-star 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">Smart App<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-info pull-right m-t-10">
<i class="ti-star"></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-with-form btn btn-success load-api"
href="#test-form-api">Smart Monitoring |
Cuaca x IoT API</a></li>

<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> ');

$('#result').append('Nilai Y Aktual =');


data.y_aktual.forEach(renderItem);
$('#result').append(' <br> ');
$('#result').append('Nilai Y Prediksi = ');
data.y_prediksi.forEach(renderItem);
}
});
});
});

</script>

<form id="test-form-api" class="white-popup-block


mfp-hide">
<h1>Hasil data dari IoT API</h1>
<fieldset style="border:0;">

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>

<li><a class="popup-youtube btn btn-info"


href="pengmas2022_vidEdu2">
Video Pengmas | Edukasi ke-2</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-md-6 col-lg-3 col-sm-6 col-xs-12">
<div class="bg-info white-box m-b-0">
<ul class="expense-box">
<li><i class="ti-star 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">Mitra<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-info pull-right m-t-10">
<i class="ti-star"></i></div>
</div>
<div class="btn-group btn-block">

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.

<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-gmaps btn btn-info"
href="https://maps.google.com/maps?q=
Kauman,+Klojen,+Malang+City,+East+Java">
Peta Pengmas | Mitra ke-1</a></li>

<li><a class="popup-gmaps btn"


href="https://maps.google.com/maps?q=
Dawuhan,+Poncokusumo,+Malang+Regency,+East+Java">
Peta Pengmas | Mitra ke-2</a></li>

</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>&reg;</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-server"></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="simple-ajax-popup-center"
href="pengmas2022_ppt1">Tentang PengMas</a></li>
<li><div id="image-popups">
<a href="{{ url_for('static', filename =
'img/TimDosen.png') }}" data-effect="mfp-zoom-in">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Tim</a>

| <a href="{{ url_for('static', filename =


'img/Desain_Banner-PengMas_2022_v2.0.png') }}"
data-effect="mfp-newspaper">Poster</a></div></li>

</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.

#Koding Simple Dashboard untuk Pengujian Sistem


Cerdas dengan Algoritma Berbasis Web

# ============================
# 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.

<label for="exampleInputuname" class="col-sm-9


control-label">x4 = Pola nafas (sesak atau
tidak)*</label>
<div class="col-sm-2">
<div class="input-group">
<input type="text" name="var4" {% if
var4 is defined and var4 %}
value="{{var4}}" {% 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">x5 = Kondisi kesadaran (sadar
atau tidak)*</label>
<div class="col-sm-2">
<div class="input-group">
<input type="text" name="var5" {% if
var5 is defined and var5 %}
value="{{var5}}" {% 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">x6 = warna cairan hidung (hijau
= 100, kuning = 67, bening = 33)*</label>
<div class="col-sm-2">
<div class="input-group">
<input type="text" name="var6" {% if
var6 is defined and var6 %}
value="{{var6}}" {% 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">x7 = frekuensi buang air
kecil*</label>
<div class="col-sm-2">
<div class="input-group">
<input type="text" name="var7" {% if
var7 is defined and var7 %}
value="{{var7}}" {% else %} value="" {%
endif %} class="form-control"
id="exampleInputuname"
placeholder="Skor" required="required">
</div>
</div>
</div>
<div class="form-group m-b-0">
<div class="col-sm-offset-3 col-sm-9
text-right">
<button type="submit" class="btn
btn-info waves-effect waves-light
m-t-10">Hitung Hasil Prediksi</button>
</div>
</div>
</form>
</div>
</div>
<div class="col-md-6">
<div class="white-box row">
<h3 class="box-title m-b-0">Estimasi hasil prediksinya
adalah </h3>
{% if c_save is defined and c_save %}
<p class="text-5xl font-bold"> nama Cov-19 & Var. baru
(y1) = {{'%0.4f'|format(c_save[0][0]|float)}} (hasil
pembulatannya = {{ c_save_round[0][0]}}) </p>
<p class="text-5xl font-bold"> imunitas tubuh (y2) =
{{'%0.4f'|format(c_save[0][1]|float)}} (hasil
pembulatannya = {{ c_save_round[0][1]}}) </p>

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

def persamaan_beta (x,y):


hasilbeta = np.matmul(np.linalg.inv(np.matmul(\
np.transpose(x),x)),np.matmul(np.transpose(x),y))
return hasilbeta
def y_bar(x_uji,beta):
hasil_y_bar = np.matmul(x_uji, beta)
return hasil_y_bar

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)

# Memasukkan data uji (x_uji)


x_uji = np.array([
[var1_in,var2_in,var3_in,var4_in,var5_in,var6_in,var7_in]
])
hitung_y_bar = y_bar(x_uji,beta)
hitung_y_bar_round = hitung_y_bar.copy()

# Agar angkanya menjadi bulat, maka dibulatkan ke atas


hitung_y_bar_round = np.ceil(hitung_y_bar_round)

# yang nilainya < 0, set = 0


hitung_y_bar_round[hitung_y_bar_round < 0] = 0

return render_template_string(A_a+template_view+Z_z, var1 = var1_in,


var2 = var2_in, var3 = var3_in, var4 = var4_in, var5 = var5_in,
var6 = var6_in, var7 = var7_in, c_save = list(hitung_y_bar),\
c_save_round = list(hitung_y_bar_round))

else: # untuk 'GET'


return render_template_string(A_a+template_view+Z_z)

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)

Link kode program lengkapnya:


https://github.com/imamcs19/fpasd-2022
https://github.com/imamcs19/FGA-Big-Data-Using-Python-Filkom-x-Mipa-UB-2022

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.

7.10 Pengembangan Prototipe Ai Virtual


Programmer Berbasis Web
7.10.1 Tentang Case Study
Komponen penyusun halaman web dapat dirangkum dalam
beberapa poin utama. Beberapa komponen dapat dibuat secara
manual maupun dengan menggunakan suati pendekatan otomasi.
Pada perkembangan teknologi saat ini, hampir semua hal yang
sebelumnya manual, misal sebagian dari tugas programmer (bukan
menggantikan, karena fitrahnya teknologi adalah hanya sebagai
support) dalam dibantu dengan menggunakan komputasi berbasis AI
(algoritma ANN/ lainnya) atau non-AI (hanya if-then biasa atau kode
sederhana lainnya).

Gambar 7.3 Simple Arsitektur untuk Prototipe Ai Virtual Programmer


Berbasis Web

Pada sub ini, diberikan skema prototipe penyusunan halaman


web secara otomatis menggunakan konsep form builder. Elemen data
yang dimasukkan ke dalam varibel bebasnya, yaiut pada input layer
dapat berupa jumlah dari num_comp_inputs, num_comp_textareas,
num_comp_hidden_fields, num_comp_file_fields, rating_art,
opt_framework, opt_db, opt_full_stack, dan lainnya nanti dapat
ditambahkan sesuai kebutuhan kompleksitas isi form halaman web
yang akan diotomasi pembuatannya.

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.

7.10.2 Snippet Kode Program

#Koding Simple Prototipe Ai Virtual Programmer


Berbasis Web

# ============================
# By: Imam Cholissodin | imamcs@ub.ac.id
# Dosen Fakultas Ilmu Komputer (Filkom)
# Universitas Brawijaya (UB)
# Tgl 25 Maret 2023
# Semoga Bermanfaat. Aamiin :D
# ====================================
#

.
..

@app.route('/gen_page_tanpa_db_frontend_backend', methods = ['GET','POST'])


def gen_page_tanpa_db_frontend_backend():

# Set nilai jumlah field yang di-generate


num_comp_inputs = 2
num_comp_textareas = 1
num_comp_hidden_fields = 1
num_comp_file_fields = 1

# siapkan template kode untuk setiap field


comp_input_template = ‘’’<div class="form-group"><label
for="input{{ num }}">Input {{ num }}:</label><input type="text"
class="form-control" id="input{{ num }}"></div>'

comp_textarea_template = '<div class="form-group"><label


for="textarea{{ num }}">Textarea {{ num }}:</label><textarea
class="form-control" id="textarea{{ num }}"></textarea></div>'

comp_hidden_template = '<div class="form-group"><input


type="hidden" class="form-control" id="hidden{{ num }}"></div>'

comp_file_template = '<div class="form-group"><label


for="file{{ num }}">File {{ num }}:</label><input type="file"
class="form-control-file" id="file{{ num }}"></div>'

# generate kode / sintaks html menggunakan list comprehension


comp_input_fields = ''.join([render_template_string(comp_input_template, \
num=i) for i in range(1, num_comp_inputs+1)])

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)])

# concate semua kode / sintaks html


my_final_fields_gen_in = comp_input_fields + comp_textarea_fields + \
comp_hidden_fields + comp_file_fields

# menyiapkan HTML template string untuk ditampilkan hasilnya,


# jgn lupa gunakan "autoescape"
html_template_string = '''
<div class="container">
<h1>Prototipe Ai Virtual Programmer Berbasis Web</h1>
<form action="/gen_page_tanpa_db_frontend_backend" method="POST">
{% autoescape off %}
{{ fields_to_html_template_string }}

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 :

Link kode program lengkapnya:


https://github.com/imamcs19/pyIntroMLearn

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

[1] Ahmed, N., Ahammed, R., Islam, Md.M., Uddin, Md.A.,


Akhter, A., Talukder, Md.A., Paul, B.K., 2021. Machine
learning based diabetes prediction and development of
smart web application. International Journal of Cognitive
Computing in Engineering 2, 229–241.
https://doi.org/10.1016/j.ijcce.2021.12.001
[2] Aksamit, N., 2023. PSO-GPU | A particle swarm
optimizer using the GPU (PyTorch).
[3] Alkhalifa, S., 2020. Launch your own REST API using
Flask & Python in 7 minutes. URL
https://towardsdatascience.com/launch-your-own-rest-
api-using-flask-python-in-7-minutes-c4373eb34239
(accessed 5.27.23).
[4] ateş, I., 2020. Predicting Credit Risk by using PySpark
ML and Docker Part-1. URL https://itnext.io/predicting-
credit-risk-by-using-pyspark-ml-and-docker-part-1-
eef141a50a7e (accessed 6.2.23).
[5] Aufar, A., 2022. Hulk di Dunia Nyata. URL
https://adityaaufar.medium.com/hulk-di-dunia-nyata-
a4b867915bc0 (accessed 5.22.23).
[6] Basílio, B., 2022. backend vs frontend. near partner.
URL https://www.nearpartner.com/wp-
content/uploads/2022/08/backend-vd-frontend.png
(accessed 6.2.23).
[7] Bhagat, K., n.d. UserWise Design System. URL
https://dribbble.com/shots/20080883-UserWise-Design-
System (accessed 6.3.23).
[8] Chan, J., 2021. Learn web development as an absolute
beginner (2021) . Coder Coder. URL https://coder-
coder.com/learn-web-development/ (accessed 5.16.23).
[9] Cholissodin, I., Maghfira, T., 2017. Buku Pemrograman
GPU.
[10] Cholissodin, I., Pambudi, M.P., Dewi, C., 2017.
Geometric time variant particle swarm optimization with
fuzzy — AHP for pomology plant recommendation, in:

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.

2017 International Conference on Advanced Computer


Science and Information Systems (ICACSIS). Presented
at the 2017 International Conference on Advanced
Computer Science and Information Systems (ICACSIS),
pp. 121–126.
https://doi.org/10.1109/ICACSIS.2017.8355021
[11] Cholissodin, I., Riyandani, E., 2016, Analisis Big Data,
Fakultas Ilmu Komputer, Universitas Brawijaya, Malang.
[12] Cholissodin, I., Riyandani, E., 2016. Buku Ajar Swarm
Intelligence.
[13] Cholissodin, I., Safitri, T.M.M., Indriati, I., 2021. Calculus
For Engineering. Filkom UB.
[14] Cholissodin, I., Seruni, D.S., Zulqornain, J.A., Hanafi,
A.N., Ghofur, A., Alexander, M., Hasan, M.I., 2020.
Development of Big Data App for Classification based on
Map Reduce of Naive Bayes with or without Web and
Mobile Interface by RESTful API Using Hadoop and
Spark. JITeCS 5, 302–312.
https://doi.org/10.25126/jitecs.202053233
[15] Cholissodin, I., Supianto, A.A., 2019. Enhancement Full
Open Source Hadoop Distribution Universal Big Data Up
Projects (UBig) From Education To Enterprise, in: 2019
International Conference on Sustainable Information
Engineering and Technology (SIET). Presented at the
2019 International Conference on Sustainable
Information Engineering and Technology (SIET), pp. 90–
93. https://doi.org/10.1109/SIET48054.2019.8986040
[16] Cholissodin, I., Sutrisno, S., Soebroto, A.A., Hasanah,
U., Febiola, Y.I., 2019. AI, Machine Learning & Deep
Learning. Filkom UB.
[17] Cholissodin, I., Syauqy, D., Firmanda, D.A., Aji, I.,
Rahman, E., Harahap, S., Septino, F., 2022.
Pengembangan Auto-AI Model Generatif Analisis
Kompleksitas Waktu Algoritma Untuk Data Multi-Sensor
IoT Pada Node-RED Menggunakan Extreme Learning
Machine. Jurnal Teknologi Informasi dan Ilmu Komputer
9, 1349–1356. https://doi.org/10.25126/jtiik.2022976738

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.

[18] Deshpande, S., 2019, Scala Vs Python Vs R Vs Java -


Which language is better for Spark & Why?.
https://www.knowledgehut.com/blog/programming/scala
-vs-python-vs-r-vs-java diakses 14 Maret 2020.
[19] Dhaduk, H., 2021. Express vs. Django: 10 Indicators to
Choose the True Backend King. Simform - Product
Engineering Company. URL
https://www.simform.com/blog/express-vs-django/
(accessed 5.21.23).
[20] Fandopa, J.A., Santoso, N., 2022. Pengembangan
Sistem Informasi Manajemen Percetakan pada
Gajayana Digital Printing Kota Malang berbasis Website.
Jurnal Pengembangan Teknologi Informasi dan Ilmu
Komputer 6, 5371–5379.
[21] Génio, J., Trifan, A., Neves, A.J.R., 2023. Knowledge
Maps as Support Tool for Managing Scientific
Competences: A Case Study at a Portuguese Research
Institute. Publications 11, 19.
https://doi.org/10.3390/publications11010019
[22] Givehchi, O., Jasperneite, J., 2013, Industrial
Automation Services as part of the Cloud: First
Experiences.
[23] Kaneriya, T., 2020. Node.js vs Django: Key differences,
popularity, use cases and more. Simform - Product
Engineering Company. URL
https://www.simform.com/blog/nodejs-vs-django/
(accessed 6.1.23).
[24] Lin, H. K, Harding, J. A., Chenc, C. I., 2016, A
Hyperconnected Manufacturing Collaboration System
Using the Semantic Web and Hadoop Ecosystem
System. Published by Elsevier B.V. This is an open
access article under the CC BY-NC-ND license.
[25] McLaughlin, K., n.d. Django 5.x Steering Council
Election Results. Django Project. URL
https://www.djangoproject.com/weblog/2023/may/16/dja
ngo-5x-steering-council-election-results/ (accessed
5.21.23).

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.

[26] Mills, D., 2019. Does Marvel Have a Speedster as Fast


as The Flash?. ScreenRant. URL
https://screenrant.com/dc-flash-faster-marvel-comics-
hero/ (accessed 5.22.23).
[27] P., Suk-Jung, 2019. IoT Device Simulator (Node-RED) +
MQTT Broker. URL https://github.com/phyunsj/iot-
device-simulator-1-mqtt (accessed 5.30.23).
[28] Pattamsetti, R. M. R., 2017, Distributed Computing in
Java 9. https:// packtpub.com
[29] Perez, A., 2021. Apache Spark Cluster on Docker (ft. a
JuyterLab Interface). URL
https://towardsdatascience.com/apache-spark-cluster-
on-docker-ft-a-juyterlab-interface-418383c95445
(accessed 6.2.23).
[30] Putra, R.T., Cholissodin, I., Dewi, C., 2018. Klasifikasi
Jenis Audio Berdasarkan Kondisi Psikologi
Menggunakan Kombinasi Algoritme Self Organizing
Maps dan Learning Vector Quantization. Jurnal
Pengembangan Teknologi Informasi dan Ilmu Komputer
2, 2930–2936.
[31] Samal, C., 2019. Build the first Flask Python web app
framework. Analytics Vidhya. URL
https://medium.com/analytics-vidhya/https-medium-
com-chirag6891-build-the-first-flask-python-
e278b52473f3 (accessed 5.27.23).
[32] Saputra, A., 2023. Attendance Using QR Code on Flask
Python 3.
[33] Setuningsih, N., 2018. Henry Cavill Isyaratkan Kembali
Jadi Superman, Si Jagoan Kembali? - Jawa Pos. Henry
Cavill Isyaratkan Kembali Jadi Superman, Si Jagoan
Kembali? - Jawa Pos. URL
https://www.jawapos.com/music-movie/0169118/henry-
cavill-isyaratkan-kembali-jadi-superman-si-jagoan-
kembali (accessed 5.22.23).
[34] Setyawan, G.E., Cholissodin, I., 2019. Development Of
Deep Reinforcement Learning Multi-Agent Framework
Design Using Self-Organizing Map, in: 2019
International Conference on Sustainable Information

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.

Engineering and Technology (SIET). Presented at the


2019 International Conference on Sustainable
Information Engineering and Technology (SIET), pp.
246–250.
https://doi.org/10.1109/SIET48054.2019.8986121
[35] Sevenmojoe, S., 2022. nodered-heroku]. URL
https://github.com/Sevenmojoe/nodered-heroku
(accessed 5.30.23).
[36] Sharma, P., n.d. Flask vs Django in 2022: Which Python
Framework to Choose? Cynoteck. URL
https://cynoteck.com/blog-post/flask-vs-django/
(accessed 5.28.23).
[37] Vadlana, B., Lakshmi Bai, K.J., Gajavelly, K., Vineeth,
P., Sameer, M., Hakeemuddin, S.K., 2022. Virtual Lab
Environment For Programming Using Mean Stack, in:
2022 4th International Conference on Smart Systems
and Inventive Technology (ICSSIT). Presented at the
2022 4th International Conference on Smart Systems
and Inventive Technology (ICSSIT), pp. 1227–1230.
https://doi.org/10.1109/ICSSIT53264.2022.9716538
[38] Vasavi, I., Jayasree, J., Charishma, G., Kranthi, S.,
2022. Blood And Plasma Donation, Management
System with GPS Using MERN Stack, in: 2022
International Conference on Advancements in Smart,
Secure and Intelligent Computing (ASSIC). Presented at
the 2022 International Conference on Advancements in
Smart, Secure and Intelligent Computing (ASSIC), pp.
1–6.
https://doi.org/10.1109/ASSIC55218.2022.10088350
[39] Zhang Q., Cheng L., dan Boutaba, R., 2010, Cloud
computing: state-of-the-art and research challenges.
Journal of Internet Services and Applications, 1(1):7–18.

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

Imam Cholissodin, lahir di Lamongan pada


tanggal 19 Juli 1985, telah menyelesaikan pen-
didikan S2 di Teknik Informatika FTIF ITS Sura-
baya pada Tahun 2011. Sejak Tahun 2012 telah
aktif sebagai dosen pengajar di jurusan Teknik
Informatika Program Teknologi dan Ilmu Kom-
puter (PTIIK), dan Alhamdulillah mulai tahun
2016 telah menjadi Fakultas Ilmu Komputer
(FILKOM) Universitas Brawijaya (UB) Malang
pada beberapa MK, seperti IR, Pengolahan Citra Digital, Probabilitas
dan Statatistika, Grafika Komputer, DSS, AI, Data Mining, Analisis Big
Data, Pemrograman GPU, Algoritma Evolusi, Swarm Intelligence,
Pengenalan Pola, Pemrograman Aplikasi Perangkat Bergerak dan
Pemrograman Web. Di samping mengajar, peneliti juga aktif dalam
Riset Group Sistem Cerdas dan Riset Group Media, Game & Mobile
Technology (MGM) di dalam Laboratorium Riset. Selain itu peneliti juga
melakukan beberapa publikasi pada seminar maupun jurnal nasional
dan internasional (IEEE, Scopus, etc). Riset pada tahun 2015-2018
bersama tim dosen dan mahasiswa berfokus pada “Pengembangan
Sistem Audit Dokumen Lembaga Pemerintahan Menggunakan Stream
Deep Learning Untuk Mendukung Smart Governance” yang
merupakan kombinasi multi-disiplin keilmuan antara DSS, Teknik
Optimasi, Big Data, Machine Learning, Ilmu Administrasi Pemerintahan
serta Information Retrieval (IR). Dan pada tahun 2019 melanjutkan riset
Big Data yang dikolaborasikan dengan bidang Ekonomi bersama tim
dosen dan mahasiswa Fakultas Ekonomi dan Bisnis (FEB) UB bersama
Badan Perencanaan Pembangunan Daerah (BAPPEDA) JATIM
dengan tema “Penyusunan Blue Print Inisiasi Pemanfaatan Open Data
Dalam Perencanaan Pembangunan Daerah” untuk mendukung Smart
Governance terpadu (integrated dengan semua existing sistem dari
berbagai platform) based AI, serta saat ini, tahun 2023 sedang
melanjutkan program doktoral S3 Ilmu Komputer di ITS dengan
promotor (Prof. Dr. Eng. Nanik Suciati, S.Kom, M.Kom) dan co-
promotor (Dr. Eng Darlis Herumurti, S.Kom, M.Kom) yang fokus pada
pengembangan Core Engine AI, ML dan Deep Learning untuk bidang
Bio-Molekuler bersama pakar a.n. Dr. apt. Valentina Yurina, S.Si, M.Si,
yang nantinya di Integrasikan dengan Big Data App as General Library
untuk bahasa pemrograman dan platform OS apapun di bawah payung
penelitian BRIN x UB pada komputasi Backend dan Frontend pada
perangkat desktop, web maupun mobile dan lainnya berbasis local
maupun serverless dengan teknologi cloud computing dalam rangka
membangun dan menghasilkan produk “Smart App” di era Revolusi
Industri 4.0 dan Society 5.0.

Motto: “We Are A Code, We Are The Best Code Of God”.

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.

Nurudin Santoso, lahir di Malang pada tanggal


16 September 1974, menyelesaikan pendidikan
SS1 Teknik Elektro Universitas Brawijaya pada
tahun 1998. Sejak kuliah sangat tertarik dengan
keilmuan rekayasa teknik dan software terutama
teknologi java. Mendapatkan sertifikasi SCJP
(Sun Certified Java Programmer) di tahun 2007.
Dan pada tahun 2011 menyelesaikan pendidikan
S2 di program studi Sistem Komunikasi dan Informasi Teknik Elektro
Universitas Brawijaya. Saat ini sebagai dosen di Fakultas Ilmu
Komputer Universitas Brawijaya Malang. Selain sebagai dosen di
bidang Teknologi Informasi dan Komunikasi, juga menekuni profesi dan
aktif sebagai konsultan “IT dan manajemen” di beberapa perusahaan.
Menekuni dan terus mengembangkan riset di bidang “Software
Engineering” terutama bagaimana menguasai bidang tersebut dengan
mudah dan cepat sehingga menciptakan metode “Grammatical Fast
Track” atau GFT pada tahun 2008. Metode ini merupakan cara yang
cepat dan mudah untuk mencapai kompetensi sebagai programmer
dikarenakan konsep yang diterapkan adalah “Menerjemahkan secara
langsung dunia nyata menjadi dunia software”. Metode ini telah teruji
selama lebih dari 20 tahun dalam menangani permasalahan-
permasalahan industri secara praktis karena prinsip yang diterapkan
yaitu “Software adalah Solusi”. Dan pada tahun 2021 mendirikan suatu
perusahaan yang bergerak di bidang layanan IT dan manajemen yang
diberi nama PT. Lambda Solusi Informatika. Suatu perusahaan yang
terus mengembangkan secara praktis solusi-solusi implementatif pada
skala Enterprise System.

Randy Cahya Wihandika, lahir di Surabaya pada


tanggal 06 Februari tahun 1988, telah berhasil
menyelesaikan studi S1 Teknik Informatika,
Politeknik Elektronika Negeri Surabaya, dengan
tugas akhir yang berjudul “Penyelesaian Puzzle
Sudoku Menggunakan Algoritma Genetika” pada
Tahun 2011. Dan pada tahun 2013
menyelesaikan pendidikan S2 di program studi
Teknik Informatika Institut Teknologi Sepuluh Nopember dengan judul
Tesis “Deteksi Percabangan Trabecular Bone menggunakan Multiscale
COSFIRE Filter pada Identifikasi Osteoporosis”. Saat ini sebagai dosen
di Fakultas Ilmu Komputer Universitas Brawijaya Malang dan sedang
tugas belajar dengan mengambil program Doktoral di Jepang.

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.

Agi Putra Kharisma, lahir di Malang pada


tanggal 30 April 1986. Lulus SMAN 3 Malang
pada tahun 2004 kemudian melanjutkan studi di
Teknik Elektro Universitas Brawijaya dan lulus
tahun 2009. Tahun 2009 - 2010 mulai berkarir di
dunia IT sebagai Auditor IT di Bank
Pembangunan Daerah Jawa Timur. Pada tahun
2010 - 2012 melanjutkan studi di Program
Magister Informatika di Sekolah Tinggi Elektro
dan Informatika Institut Teknologi Bandung (STEI ITB), mengambil
keminatan Rekayasa Perangkat Lunak. Tahun 2013 - sekarang tercatat
sebagai dosen di Departemen Teknik Informatika (DTIF) Fakultas Ilmu
Komputer Universitas Brawijaya (FILKOM UB) dan saat ini menjadi
sekretaris laboratorium Media Game dan Mobile (MGM) FILKOM UB.
Bidang keilmuan utama yang ditekuni dan disebarluaskan meliputi
Rekayasa Perangkat Lunak serta Interaksi Manusia dan Komputer,
khususnya berkaitan dengan User Experience (UX) dan User Interface
(UI). Mata kuliah yang pernah diajarkan antara lain Pemrograman Web,
Rekayasa Perangkat Lunak, Evaluasi Antarmuka dan Pengalaman
Pengguna, dan Pola-Pola Perancangan.

Putra Pandu Adikara, menerima gelar sarjana


dalam Ilmu Komputer, Universitas Brawijaya
pada tahun 2007. Ia bekerja setahun di sebuah
perusahaan IT sebagai web developer dan
memutuskan untuk mengejar passion dalam
pemerolehan informasi, pengolahan bahasa
alami, dan penambangan teks. Dia mulai bekerja
sebagai dosen Ilmu Komputer di Fakultas Matematika dan Ilmu
Pengetahuan Alam, Universitas Brawijaya, Malang sejak 2009 dan
kemudian menjadi dosen Teknik Informatika di Fakultas Ilmu
Komputer, Universitas Brawijaya, Malang. Pada tahun 2015, ia
memperoleh gelar magister di bidang yang sama dari Universitas
Indonesia. Minat penelitiannya termasuk temu kembali/perolehan
informasi (information retrieval), pengolahan bahasa alami (natural
language processing), penambangan teks (text mining), pembelajaran
mesin (machine learning), dan pengolahan citra digital (digital image
processing).

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.

Tria Melia Masdiana Safitri, lahir di Sragen pada


tanggal 05 Juli tahun 1997, telah berhasil
menyelesaikan studi S1 Teknik Informatika,
Fakultas Ilmu Komputer, Universitas Brawijaya
Malang dengan tugas akhir yang berjudul
“Optimasi Kombinasi Bahan Makanan untuk
Mencegah Stunting dengan Menggunakan
Algoritme Genetika ”.

232

Anda mungkin juga menyukai