├── LP-1 ├── SPOS │ ├── Assembler │ │ ├── AssemblerPass2 │ │ │ ├── littab.txt │ │ │ ├── symtab.txt │ │ │ ├── intermediate.txt │ │ │ ├── Main.java │ │ │ └── PassII.java │ │ └── AssemblerPass1 │ │ │ ├── poolTab.txt │ │ │ ├── symTab.txt │ │ │ ├── litTab.txt │ │ │ ├── opTab.txt │ │ │ ├── sample.txt │ │ │ ├── OutputTextTry.txt │ │ │ └── Assembler_Pass1.java │ ├── A3_Dynamic Link Library │ │ ├── libJNI.dll │ │ ├── JNI.java │ │ ├── JNI.c │ │ └── JNI_JNI.h │ ├── Synchronization │ │ └── SynchronizationComparison.java │ ├── MemoryManagement │ │ └── MemoryManagement.java │ ├── MacroPass │ │ └── Main.java │ ├── Scheduling │ │ └── Scheduling.java │ └── PageReplacement │ │ └── PageReplacement.java ├── DS │ ├── RPC │ │ ├── rpc_client.PNG │ │ ├── rpc_server.PNG │ │ ├── rpc_client.py │ │ └── rpc_server.py │ ├── Clock Synchronization │ │ ├── ntp.PNG │ │ ├── lamport.PNG │ │ ├── ntp.py │ │ └── lamport.py │ ├── Socket Programming │ │ ├── client.PNG │ │ ├── server.PNG │ │ ├── client.py │ │ └── server.py │ └── Election algorithm │ │ ├── ring_and_bully.PNG │ │ └── ring_and_bully.py ├── IOTES │ ├── HumanCounting.py │ ├── Motion_detection.py │ ├── Temp.py │ ├── capture._single_image.py │ └── eye dection.py └── HCI │ ├── unitConverter1.py │ ├── stickyNotes.py │ ├── colorMatch.py │ ├── calculator.py │ └── ticTacToe.py ├── TE_Computer_2019_Course_22.06.2021.pdf ├── DBMS ├── PL_SQL Areaof circle.txt ├── PL_SQL procedure.txt ├── MongoDB Agregation.txt ├── PL_SQL Cursor.txt ├── MongoDB CRUD.txt ├── PL_SQL Trigger.txt ├── SQL Connectivity.txt ├── BasicSQL8.txt ├── BasicSQL10.txt ├── SQL Joins.txt ├── MongoDB Map Reduce.txt ├── MongoDB Connectivity.txt ├── SQL DDL & DML.txt └── BasicSQL20.txt ├── README.md ├── AIML Honor ├── Ass_2.py ├── Ass_5.py ├── Ass_4.py ├── Ass_3.py └── Ass_1.py └── CNS ├── CNS4.cpp ├── CNS6.cpp ├── SubnetMask.java ├── CNS3.cpp └── Subnet.java /LP-1/SPOS/Assembler/AssemblerPass2/littab.txt: -------------------------------------------------------------------------------- 1 | 5 206 2 | 1 207 3 | 1 213 -------------------------------------------------------------------------------- /LP-1/SPOS/Assembler/AssemblerPass1/poolTab.txt: -------------------------------------------------------------------------------- 1 | 2 | POOL TOTAL LITERALS 3 | 0 1 4 | 1 2 5 | 3 3 -------------------------------------------------------------------------------- /LP-1/SPOS/Assembler/AssemblerPass1/symTab.txt: -------------------------------------------------------------------------------- 1 | 2 | SYMBOL ADDRESS 3 | UP 102 4 | A 109 5 | B 111 6 | C 112 7 | NEXT 102 -------------------------------------------------------------------------------- /LP-1/DS/RPC/rpc_client.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vishwajeet-Londhe/SPPU-CSE-SEM5-Codes/HEAD/LP-1/DS/RPC/rpc_client.PNG -------------------------------------------------------------------------------- /LP-1/DS/RPC/rpc_server.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vishwajeet-Londhe/SPPU-CSE-SEM5-Codes/HEAD/LP-1/DS/RPC/rpc_server.PNG -------------------------------------------------------------------------------- /LP-1/DS/Clock Synchronization/ntp.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vishwajeet-Londhe/SPPU-CSE-SEM5-Codes/HEAD/LP-1/DS/Clock Synchronization/ntp.PNG -------------------------------------------------------------------------------- /LP-1/DS/Socket Programming/client.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vishwajeet-Londhe/SPPU-CSE-SEM5-Codes/HEAD/LP-1/DS/Socket Programming/client.PNG -------------------------------------------------------------------------------- /LP-1/DS/Socket Programming/server.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vishwajeet-Londhe/SPPU-CSE-SEM5-Codes/HEAD/LP-1/DS/Socket Programming/server.PNG -------------------------------------------------------------------------------- /LP-1/SPOS/Assembler/AssemblerPass2/symtab.txt: -------------------------------------------------------------------------------- 1 | A 211 1 2 | LOOP 202 1 3 | B 212 1 4 | NEXT 208 1 5 | BACK 202 1 6 | LAST 210 1 -------------------------------------------------------------------------------- /TE_Computer_2019_Course_22.06.2021.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vishwajeet-Londhe/SPPU-CSE-SEM5-Codes/HEAD/TE_Computer_2019_Course_22.06.2021.pdf -------------------------------------------------------------------------------- /LP-1/DS/Clock Synchronization/lamport.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vishwajeet-Londhe/SPPU-CSE-SEM5-Codes/HEAD/LP-1/DS/Clock Synchronization/lamport.PNG -------------------------------------------------------------------------------- /LP-1/DS/Election algorithm/ring_and_bully.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vishwajeet-Londhe/SPPU-CSE-SEM5-Codes/HEAD/LP-1/DS/Election algorithm/ring_and_bully.PNG -------------------------------------------------------------------------------- /LP-1/SPOS/A3_Dynamic Link Library/libJNI.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vishwajeet-Londhe/SPPU-CSE-SEM5-Codes/HEAD/LP-1/SPOS/A3_Dynamic Link Library/libJNI.dll -------------------------------------------------------------------------------- /LP-1/SPOS/Assembler/AssemblerPass1/litTab.txt: -------------------------------------------------------------------------------- 1 | 2 | Index LITERAL ADDRESS 3 | 1 ='5' 102 4 | 2 ='9' 105 5 | 3 ='8' 106 6 | 4 ='7' 121 7 | 5 ='8' 122 -------------------------------------------------------------------------------- /LP-1/SPOS/Assembler/AssemblerPass1/opTab.txt: -------------------------------------------------------------------------------- 1 | 2 | MNEMONIC OPCODE 3 | MOVER 4 4 | MOVER 4 5 | ADD 1 6 | MOVEM 5 7 | MULT 3 8 | MOVEM 5 9 | MOVEM 5 10 | MOVEM 5 11 | MOVEM 5 12 | DS 1 13 | DC 2 14 | DS 1 -------------------------------------------------------------------------------- /LP-1/SPOS/Assembler/AssemblerPass1/sample.txt: -------------------------------------------------------------------------------- 1 | START 100 2 | MOVER AX,05 3 | MOVER BX,10 4 | UP ADD AX,BX 5 | MOVEM A,='5' 6 | MULT AX,A 7 | ORIGIN UP 8 | LTORG 9 | MOVEM B,='9' 10 | MOVEM C,='8' 11 | LTORG 12 | MOVEM B,='7' 13 | MOVEM C,='8' 14 | A DS 02 15 | B DC 10 16 | C DS 09 17 | NEXT EQU UP 18 | END -------------------------------------------------------------------------------- /LP-1/SPOS/Assembler/AssemblerPass2/intermediate.txt: -------------------------------------------------------------------------------- 1 | (AD,01)(C,200) 2 | (IS,04)(1)(L,1) 3 | (IS,05)(1)(S,1) 4 | (IS,04)(1)(S,1) 5 | (IS,04)(3)(S,3) 6 | (IS,01)(3)(L,2) 7 | (IS,07)(6)(S,4) 8 | (DL,01)(C,5) 9 | (DL,01)(C,1) 10 | (IS,02)(1)(L,3) 11 | (IS,07)(1)(S,5) 12 | (IS,00) 13 | (AD,03)(S,2)+2 14 | (IS,03)(3)(S,3) 15 | (AD,03)(S,6)+1 16 | (DL,02)(C,1) 17 | (DL,02)(C,1) 18 | (AD,02) 19 | (DL,01)(C,1) -------------------------------------------------------------------------------- /DBMS/PL_SQL Areaof circle.txt: -------------------------------------------------------------------------------- 1 | create table circle(Radius number,Area number) 2 | 3 | Declare 4 | rad number; 5 | area number; 6 | Begin 7 | for rad in 5..9 loop 8 | area := 3.14*POWER(rad,2); 9 | insert into circle(Radius,Area) 10 | Values(rad,area); 11 | 12 | END LOOP; 13 | COMMIT; 14 | Dbms_Output.Put_Line('RADIUS | AREA'); 15 | Dbms_Output.Put_Line('_____________'); 16 | for shu in (select Radius,Area from circle) LOOP 17 | Dbms_output.put_line(shu.Radius || ' | ' || shu.Area); 18 | END loop; 19 | END; -------------------------------------------------------------------------------- /LP-1/SPOS/Assembler/AssemblerPass1/OutputTextTry.txt: -------------------------------------------------------------------------------- 1 | (AD,1) (C,100) 2 | 100 (IS,4) (1) (C,05) 3 | 101 (IS,4) (2) (C,10) 4 | 102 (IS,1) (1) (2) 5 | 103 (IS,5) (S,2) (L,1) 6 | 104 (IS,3) (1) (S,2) 7 | (AD,3) (S,1) 8 | (DL,2) (C,5) 9 | 10 | 103 (IS,5) (S,3) (L,2) 11 | 104 (IS,5) (S,4) (L,3) 12 | (DL,2) (C,9) 13 | (DL,2) (C,8) 14 | 15 | 107 (IS,5) (S,3) (L,4) 16 | 108 (IS,5) (S,4) (L,5) 17 | 109 (DL,1) (C,02) 18 | 111 (DL,2) (C,10) 19 | 112 (DL,1) (C,09) 20 | (AD,4) (S,1) 21 | (AD,2) 22 | (DL,2) (C,7) 23 | (DL,2) (C,8) -------------------------------------------------------------------------------- /LP-1/DS/RPC/rpc_client.py: -------------------------------------------------------------------------------- 1 | import xmlrpc.client 2 | 3 | def main(): 4 | # Create an XML-RPC client 5 | proxy = xmlrpc.client.ServerProxy("http://localhost:8000/RPC2") 6 | 7 | # Call remote methods 8 | a = int(input("Enter a : ")) 9 | b = int(input("Enter b : ")) 10 | result_add = proxy.add(a, b) 11 | result_subtract = proxy.subtract(a, b) 12 | 13 | print(f"Addition result: {result_add}") 14 | print(f"Subtraction result: {result_subtract}") 15 | 16 | if __name__ == "__main__": 17 | main() 18 | -------------------------------------------------------------------------------- /LP-1/DS/Clock Synchronization/ntp.py: -------------------------------------------------------------------------------- 1 | import ntplib 2 | from time import ctime 3 | 4 | def sync_ntp_time(server): 5 | try: 6 | c = ntplib.NTPClient() 7 | response = c.request(server, version=3) 8 | local_time = ctime(response.tx_time) 9 | print(f'NTP Server: {server}') 10 | print(f'Local Time synchronized with NTP Server: {local_time}') 11 | except Exception as e: 12 | print(f'Error: {e}') 13 | 14 | def main(): 15 | ntp_server = 'pool.ntp.org' # Replace with a valid NTP server 16 | sync_ntp_time(ntp_server) 17 | 18 | if __name__ == "__main__": 19 | main() 20 | -------------------------------------------------------------------------------- /LP-1/IOTES/HumanCounting.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | bp = 40 4 | count = 0 5 | GPIO.setmode(GPIO.BOARD) 6 | GPI0.setup(5, GPI0.IN) 7 | GPIO.setup(11, GPIO.IN) 8 | GPIO.setup(bp, GPIO.OUT) 9 | while count < 10: 10 | enter = GPIO.input(5) 11 | exit = GPIO.input(11) 12 | if enter == False: 13 | time.sleep(1) 14 | GPIO.output(bp, GPIO.LOW) 15 | time.sleep(1) 16 | elif exit == False and count > 0: 17 | count -= 1 18 | print('Human Exited") 19 | print (count str(count)) 20 | GPIO.output(bp, GPIO.HIGH) 21 | time.sleep(1) 22 | GPIO.output(bp, GPIO.LOW) 23 |    time.sleep(1) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

SPPU TE COMP SEM-V Practical Codes

2 | 3 |

4 | 5 | WhatsApp Channel for Quick Updates 6 | 7 |

8 | 9 | **Join our Telegram channel [here!](https://t.me/SPPU_TE_BE_COMP)** 10 | 11 | **All TE Codes of following subjects available** 12 | 1) CNS 13 | 2) DBMS 14 | 3) LP-1 ( SPOS, IOTES, HCI, DS ) 15 | 4) HONOR AIML 16 | 17 |
18 |

19 | 20 |

21 |
22 | 23 | > ⭐ Click :star: if you like the repo. Pull Requests are highly appreciated. 24 | -------------------------------------------------------------------------------- /LP-1/DS/Socket Programming/client.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | def main(): 4 | host = '127.0.0.1' # Use localhost 5 | port = 8080 6 | 7 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 | client.connect((host, port)) 9 | 10 | message = input("Enter a message to send to the server: ") 11 | 12 | while True: 13 | client.send(message.encode()) 14 | data = client.recv(1024) 15 | print("Received from server: " + data.decode()) 16 | 17 | message = input("Enter another message (or press Enter to exit): ") 18 | if not message: 19 | break 20 | 21 | client.close() 22 | 23 | if __name__ == "__main__": 24 | main() 25 | -------------------------------------------------------------------------------- /LP-1/DS/RPC/rpc_server.py: -------------------------------------------------------------------------------- 1 | from xmlrpc.server import * 2 | 3 | # Create a simple class with some methods 4 | class MathOperations: 5 | def add(self, x, y): 6 | return x + y 7 | 8 | def subtract(self, x, y): 9 | return x - y 10 | 11 | # Restrict to a particular path to avoid arbitrary code execution 12 | class RequestHandler(SimpleXMLRPCRequestHandler): 13 | rpc_paths = ('/RPC2',) 14 | 15 | def main(): 16 | server = SimpleXMLRPCServer(('localhost', 8000), requestHandler=RequestHandler) 17 | server.register_instance(MathOperations()) 18 | 19 | print("RPC Server is listening on port 8000...") 20 | server.serve_forever() 21 | 22 | if __name__ == "__main__": 23 | main() 24 | -------------------------------------------------------------------------------- /AIML Honor/Ass_2.py: -------------------------------------------------------------------------------- 1 | from scipy.stats import skew, kurtosis 2 | import matplotlib.pyplot as plt 3 | import scipy.stats as stats 4 | import pandas as pd 5 | import numpy as np 6 | import warnings 7 | warnings.filterwarnings("ignore") 8 | 9 | x=np.array([60,70,75,80,50,72,78,65,75,92,82,68,71,77,76,84]) 10 | 11 | mean= np.mean(x) 12 | sd = np.std(x,ddof=1) 13 | median = np.median(x) 14 | fit = stats.norm.pdf(x,mean,sd) 15 | plt.hist(x, density = True, color="maroon", ec ="white",) 16 | plt.plot(x,fit,"go:") 17 | plt.title("Math Scores") 18 | plt.xlabel("Marks") 19 | plt.ylabel("Normal Distribution") 20 | 21 | plt.show() 22 | 23 | def skewness(x,mean,sd): 24 | return np.sum((x-mean)**3)/((len(x)-1)*(sd**3)) 25 | 26 | def kurtosis(x,mean,sd): 27 | return np.sum((x-mean)**4)/((len(x)-1)*(sd**4)) 28 | 29 | skewness(x,mean,sd) 30 | kurtosis(x,mean,sd) 31 | -------------------------------------------------------------------------------- /LP-1/IOTES/Motion_detection.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | from imutils.video import VideoStream 4 | from imutils import resize 5 | import RPi.GPIO as GPIO 6 | import time 7 | 8 | Buzzer_pin = 14 9 | GPIO.setmode(GPIO.BCM) 10 | GPIO.setup(Buzzer_pin, GPIO.OUT) 11 | 12 | diff_threshold = 1000000 13 | 14 | vs = VideoStream(src=0).start() 15 | 16 | def getImage(): 17 | im = vs.read() 18 | im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) 19 | im = cv2.blur(im, (20, 20)) 20 | return im 21 | 22 | old_image = getImage() 23 | 24 | while True: 25 | new_image =getImage() 26 | diff = cv2.absdiff(old_image, new_image) 27 | print(diff) 28 | diff_score = np.sum(diff) 29 | if diff_score > diff_threshold: 30 | print(diff_score) 31 | print("Movement Detected") 32 | GPIO.output(Buzzer_pin, GPIO.HIGH) 33 | time.sleep(0.5) 34 | GPIO.output(Buzzer_pin, GPIO.LOW) 35 | time.sleep(0.5) 36 | 37 | old_image= new_image -------------------------------------------------------------------------------- /LP-1/DS/Socket Programming/server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import threading 3 | 4 | # Function to handle a client connection 5 | def handle_client(client_socket): 6 | while True: 7 | data = client_socket.recv(1024) 8 | if not data: 9 | break 10 | client_socket.send(data) 11 | client_socket.close() 12 | 13 | def main(): 14 | host = '127.0.0.1' # Use localhost 15 | port = 8080 16 | 17 | server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 18 | server.bind((host, port)) 19 | server.listen(5) 20 | 21 | print(f"[*] Listening on {host}:{port}") 22 | 23 | while True: 24 | client_socket, addr = server.accept() 25 | print(f"[*] Accepted connection from: {addr[0]}:{addr[1]}") 26 | 27 | # Create a new thread to handle the client 28 | client_handler = threading.Thread(target=handle_client, args=(client_socket,)) 29 | client_handler.start() 30 | 31 | if __name__ == "__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /LP-1/IOTES/Temp.py: -------------------------------------------------------------------------------- 1 | import Adafruit_DHT 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | 6 | GPIO.setmode(GPIO.BOARD) 7 | GPIO.setup(40,GPIO.OUT) 8 | 9 | sensor=Adafruit_DHT.DHT11 10 | 11 | gpio=3 12 | 13 | tt=29 14 | th=60 15 | 16 | for i in range(10): 17 | T,H = Adafruit_DHT.read_retry(sensor,gpio) 18 | time.sleep(2) 19 | if H is not None and T is not None: 20 | print('Temp={0:0.4f}*C Humidity={1:0.04f}%'.format(T,H)) 21 | if H>th: 22 | print('Humidity has crossed its limits') 23 | GPIO.output(40,GPIO.HIGH) 24 | time.sleep(2) 25 | GPIO.output(40,GPIO.LOW) 26 | time.sleep(2) 27 | else: 28 | print('Humidity within its limit') 29 | 30 | if T>tt: 31 | print('Temp has crossed its limits') 32 | 33 | GPIO.output(40,GPIO.HIGH) 34 | time.sleep(2) 35 | GPIO.output(40,GPIO.LOW) 36 | time.sleep(2) 37 | else: 38 | print('Temp within its limit') 39 | 40 | else: 41 | print('error') -------------------------------------------------------------------------------- /LP-1/DS/Clock Synchronization/lamport.py: -------------------------------------------------------------------------------- 1 | class LamportClock: 2 | def __init__(self): 3 | self.clock = 0 4 | 5 | def get_time(self): 6 | return self.clock 7 | 8 | def tick(self): 9 | self.clock += 1 10 | 11 | def main(): 12 | # Create two Lamport clocks 13 | clock1 = LamportClock() 14 | clock2 = LamportClock() 15 | 16 | # Simulate events and clock updates 17 | print(f'Initial Clock 1: {clock1.get_time()}') 18 | print(f'Initial Clock 2: {clock2.get_time()}') 19 | 20 | clock1.tick() 21 | print(f'Clock 1 after tick: {clock1.get_time()}') 22 | 23 | clock2.tick() 24 | print(f'Clock 2 after tick: {clock2.get_time()}') 25 | 26 | # Compare clock values 27 | if clock1.get_time() < clock2.get_time(): 28 | print('Clock 1 is behind Clock 2') 29 | elif clock1.get_time() > clock2.get_time(): 30 | print('Clock 2 is behind Clock 1') 31 | else: 32 | print('Clock 1 and Clock 2 are synchronized') 33 | 34 | if __name__ == "__main__": 35 | main() 36 | -------------------------------------------------------------------------------- /LP-1/IOTES/capture._single_image.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | from picamera import PiCamera 3 | import cv2 4 | 5 | camera = PiCamera() 6 | camera.resolution = (1024, 768) 7 | camera.start_preview() 8 | # Camera warm-up time 9 | sleep(2) 10 | camera.capture('foo.jpg') 11 | camera.stop_preview() 12 | #Now capturing new image which we'll resize 13 | sleep(2) 14 | camera.start_preview() 15 | # Camera warm-up time 16 | sleep(2) 17 | camera.capture('foo_resized.jpg', resize=(320, 240)) 18 | camera.stop_preview() 19 | # to show captured image 20 | sleep(2) 21 | img1 = cv2.imread("foo.jpg") 22 | cv2.imshow("foo_tmp",img1) 23 | cv2.waitKey(0) 24 | cv2.destroyAllWindows() 25 | face_cascade = cv2.CascadeClassifier('/home/pi/.local/lib/python3.5/site-packages/cv2/data/haarcascade_frontalface_default.xml') 26 | img2 = cv2.imread("foo.jpg") 27 | sleep(2) 28 | gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY) 29 | faces = face_cascade.detectMultiScale(gray,1.1,5) 30 | for(x, y, w, h) in faces: 31 | cv2.rectangle(img2, (x,y),(x+w, y+h),(255, 0, 0),2) 32 | cv2.imshow('Faces', img2) 33 | cv2.waitKey(0) -------------------------------------------------------------------------------- /LP-1/SPOS/A3_Dynamic Link Library/JNI.java: -------------------------------------------------------------------------------- 1 | package JNI; 2 | 3 | import java.util.Scanner; 4 | public class JNI { 5 | public native void JniAdd(int no1,int no2); 6 | public native void JniSub(int no1,int no2); 7 | public native void JniMult(int no1,int no2); 8 | public native void JniDiv(double no1,double no2); 9 | public native void JniPow(int no1,int no2); 10 | public native void JniSqrt(int no1); 11 | public native void JniMod(int no1,int no2); 12 | static { System.load("This-PC\\F:\\Practical codes\\LP 1\\A3_Dynamic Link Library\\JNI\\src\\JNI\\libJNI.dll");} 13 | public static void main(String[] args)throws Exception { 14 | int no1,no2; 15 | Scanner in=new Scanner(System.in); 16 | JNI MJ=new JNI(); 17 | System.out.println("JNI using C"); 18 | System.out.print("Enter first number: "); 19 | no1=in.nextInt(); 20 | double no1f=no1; 21 | System.out.print("Enter second number: "); 22 | no2=in.nextInt(); 23 | MJ.JniAdd(no1,no2); 24 | MJ.JniSub(no1,no2); 25 | MJ.JniMult(no1,no2); 26 | MJ.JniDiv((double)no1,(double)no2); 27 | MJ.JniPow(no1,no2); 28 | MJ.JniSqrt(no2); 29 | MJ.JniMod(no1,no2); 30 | 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /LP-1/SPOS/A3_Dynamic Link Library/JNI.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define PI 3.14159265 5 | 6 | JNIEXPORT void JNICALL Java_JNI_JNI_JniAdd 7 | (JNIEnv *e, jobject obj, jint no1, jint no2) 8 | { 9 | int add=no1+no2; 10 | printf("Addition of nos.= %d",add); 11 | } 12 | 13 | JNIEXPORT void JNICALL Java_JNI_JNI_JniSub 14 | (JNIEnv *e, jobject obj, jint no1, jint no2) 15 | { 16 | int sub=no1-no2; 17 | printf("\nSubtraction of nos. is= %d",sub); 18 | } 19 | 20 | JNIEXPORT void JNICALL Java_JNI_JNI_JniMult 21 | (JNIEnv *e, jobject obj, jint no1, jint no2) 22 | { 23 | int mult=no1*no2; 24 | printf("\nMultiplication of nos. is= %d",mult); 25 | } 26 | 27 | 28 | JNIEXPORT void JNICALL Java_JNI_JNI_JniDiv 29 | (JNIEnv *e, jobject obj, jdouble no1, jdouble no2) 30 | { 31 | double div=no1/no2; 32 | printf("\nDivision of nos. is= %.3f",div); 33 | } 34 | 35 | JNIEXPORT void JNICALL Java_JNI_JNI_JniMod 36 | (JNIEnv *e, jobject obj, jint no1, jint no2) 37 | { 38 | printf("\nRemainder is= %.3f",fmod(no1,no2)); 39 | } 40 | 41 | JNIEXPORT void JNICALL Java_JNI_JNI_JniPow 42 | (JNIEnv *e, jobject obj, jint no1, jint no2) 43 | { 44 | printf("\nPower is= %.3f",pow(no1,no2)); 45 | } 46 | 47 | 48 | JNIEXPORT void JNICALL Java_JNI_JNI_JniSqrt 49 | (JNIEnv *e, jobject obj, jint no1) 50 | { 51 | printf("\nSquare root %d is= %.3f",no1,sqrt(no1)); 52 | 53 | } 54 | 55 | -------------------------------------------------------------------------------- /DBMS/PL_SQL procedure.txt: -------------------------------------------------------------------------------- 1 | CREATE TABLE stud_marks(name VARCHAR2(25),total_marks NUMBER) 2 | 3 | CREATE TABLE result(roll_number NUMBER , name VARCHAR2(25), class VARCHAR2(30)) 4 | 5 | CREATE OR REPLACE PROCEDURE proc_grades ( roll_no IN NUMBER, name IN VARCHAR2 ,marks IN NUMBER) 6 | AS 7 | BEGIN 8 | IF (marks<=1500 and marks>=990) THEN 9 | DBMS_OUTPUT.PUT_LINE (roll_no||' - '||name||' : DISTINCTION'); 10 | INSERT INTO result VALUES (roll_no,name,'DISTINCTION'); 11 | ELSIF (marks<=989 and marks>=900) THEN 12 | DBMS_OUTPUT.PUT_LINE (roll_no||' - '||name||' : FIRST CLASS'); 13 | INSERT INTO result VALUES (roll_no,name,'FIRST CLASS'); 14 | ELSIF (marks<=899 and marks>825) THEN 15 | DBMS_OUTPUT.PUT_LINE(roll_no||' - '||name||' : HIGHER SECOND CLASS'); 16 | INSERT INTO result VALUES (roll_no,name,'HIGHER SECOND CLASS'); 17 | ELSE 18 | DBMS_OUTPUT.PUT_LINE (roll_no||' - '||name||' : FAIL'); 19 | INSERT INTO result VALUES (roll_no,name,'FAIL'); 20 | END IF; 21 | INSERT INTO stud_marks VALUES (name,marks); 22 | END proc_grades ; 23 | 24 | BEGIN 25 | proc_grades (54,'SUDARSHAN',1000); 26 | proc_grades (46,'ARYAN ',950); 27 | proc_grades (58,'ARJUN ',1050); 28 | proc_grades (14,'Aanika',995); 29 | proc_grades (19,'Suhani',889); 30 | proc_grades (16,'Kartiki',965); 31 | proc_grades (10,'Shalima',400); 32 | proc_grades (20,'Kusum',777); 33 | END; 34 | 35 | SELECT * FROM stud_marks; 36 | 37 | SELECT * FROM result; -------------------------------------------------------------------------------- /CNS/CNS4.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define ll long long int 4 | using namespace std; 5 | 6 | void Transmission(ll & i, ll & Window_Size, ll & Total_Frame, ll & Total_Transmitted) 7 | { 8 | while(i <= Total_Frame) 9 | { 10 | int z=0; 11 | for(int k = i; k>Total_Frame; 42 | cout<<"Enter the window size : "; 43 | cin>>Window_Size; 44 | ll i=1; 45 | Transmission(i, Window_Size, Total_Frame, Total_Transmitted); 46 | cout<<"Total number of the frames which were sent and resent are : "< 3 | /* Header for class JNI_JNI */ 4 | 5 | #ifndef _Included_JNI_JNI 6 | #define _Included_JNI_JNI 7 | #ifdef __cplusplus 8 | extern "C" { 9 | #endif 10 | /* 11 | * Class: JNI_JNI 12 | * Method: JniAdd 13 | * Signature: (II)V 14 | */ 15 | JNIEXPORT void JNICALL Java_JNI_JNI_JniAdd 16 | (JNIEnv *, jobject, jint, jint); 17 | 18 | /* 19 | * Class: JNI_JNI 20 | * Method: JniSub 21 | * Signature: (II)V 22 | */ 23 | JNIEXPORT void JNICALL Java_JNI_JNI_JniSub 24 | (JNIEnv *, jobject, jint, jint); 25 | 26 | /* 27 | * Class: JNI_JNI 28 | * Method: JniMult 29 | * Signature: (II)V 30 | */ 31 | JNIEXPORT void JNICALL Java_JNI_JNI_JniMult 32 | (JNIEnv *, jobject, jint, jint); 33 | 34 | /* 35 | * Class: JNI_JNI 36 | * Method: JniDiv 37 | * Signature: (II)V 38 | */ 39 | JNIEXPORT void JNICALL Java_JNI_JNI_JniDiv 40 | (JNIEnv *, jobject, jdouble, jdouble); 41 | 42 | /* 43 | * Class: JNI_JNI 44 | * Method: JniPow 45 | * Signature: (II)V 46 | */ 47 | JNIEXPORT void JNICALL Java_JNI_JNI_JniPow 48 | (JNIEnv *, jobject, jint, jint); 49 | 50 | /* 51 | * Class: JNI_JNI 52 | * Method: JniSqrt 53 | * Signature: (I)V 54 | */ 55 | JNIEXPORT void JNICALL Java_JNI_JNI_JniSqrt 56 | (JNIEnv *, jobject, jint); 57 | 58 | /* 59 | * Class: JNI_JNI 60 | * Method: JniMod 61 | * Signature: (II)V 62 | */ 63 | JNIEXPORT void JNICALL Java_JNI_JNI_JniMod 64 | (JNIEnv *, jobject, jint, jint); 65 | 66 | #ifdef __cplusplus 67 | } 68 | #endif 69 | #endif 70 | -------------------------------------------------------------------------------- /CNS/CNS6.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct node 5 | { 6 | int Distance[15]; 7 | int From[15]; 8 | } 9 | Route[10]; 10 | int main() 11 | { 12 | int Distance_Matrix[15][15], Nodes; 13 | cout << "Enter No. of Nodes : "; 14 | cin >> Nodes; 15 | cout << "Enter Distance Matrix : " << endl; 16 | for (int i = 0; i < Nodes; i++) 17 | { 18 | for (int j = 0; j < Nodes; j++) 19 | { 20 | cin >> Distance_Matrix[i][j]; 21 | /* Set distance from i to i as 0 */ 22 | Distance_Matrix[i][i] = 0; 23 | Route[i].Distance[j] = Distance_Matrix[i][j]; 24 | Route[i].From[j] = j; 25 | } 26 | } 27 | int flag; 28 | do 29 | { 30 | flag = 0; 31 | for (int i = 0; i < Nodes; i++) 32 | { 33 | for (int j = 0; j < Nodes; j++) 34 | { 35 | for (int k = 0; k < Nodes; k++) 36 | { 37 | if ((Route[i].Distance[j]) > (Route[i].Distance[k] + Route[k].Distance[j])) 38 | { 39 | Route[i].Distance[j] = Route[i].Distance[k] + Route[k].Distance[j]; 40 | Route[i].From[j] = k; 41 | flag = 1; 42 | } 43 | } 44 | } 45 | } 46 | } 47 | while (flag); 48 | for (int i = 0; i < Nodes; i++) 49 | { 50 | cout << "Router Info for router : " << i + 1 << endl; 51 | cout << "Destination\tNext Hop\tDistance" << endl; 52 | for (int j = 0; j < Nodes; j++) 53 | printf("%d\t%d\t\t%d\n", j+1, Route[i].From[j]+1, Route[i].Distance[j]); 54 | } 55 | return 0; 56 | } -------------------------------------------------------------------------------- /DBMS/PL_SQL Trigger.txt: -------------------------------------------------------------------------------- 1 | create table library( 2 | book_id int primary key, 3 | book_name varchar(25), 4 | author_name varchar(40), 5 | price int 6 | ); 7 | 8 | insert into library(book_id, book_name, author_name, price) 9 | values(1,'early india','ramila thapar',1200); 10 | 11 | insert into library(book_id, book_name, author_name, price) 12 | values(2,'verity','collen hoover',1600); 13 | 14 | insert into library(book_id, book_name, author_name, price) 15 | values(3,'Nelson mandela','Hovely reads',900); 16 | 17 | insert into library(book_id, book_name, author_name, price) 18 | values(4,'everyday gita','sunita pant',1500); 19 | 20 | insert into library(book_id, book_name, author_name, price) 21 | values(5,'b1','a1',2000); 22 | 23 | create table library_audit( 24 | old_book_id int primary key, 25 | old_book_name varchar(25), 26 | old_author_name varchar(40), 27 | old_price int, 28 | operation_type varchar(20) 29 | ); 30 | 31 | create or replace trigger before_library_update 32 | before 33 | update on library 34 | for each row 35 | begin 36 | insert into 37 | library_audit(old_book_id,old_book_name,old_author_name,old_price,operation_type) 38 | values(:OLD.book_id, :OLD.book_name, :OLD.author_name, :OLD.price, 'update'); 39 | end; 40 | 41 | UPDATE Library 42 | SET book_name = 'Gatsby (Updated)', author_name = 'Fitzgerald' 43 | WHERE book_id = 1; 44 | 45 | create or replace trigger before_library_delete 46 | before 47 | delete on library 48 | for each row 49 | begin 50 | insert into 51 | library_audit(old_book_id,old_book_name,old_author_name,old_price,operation_type) 52 | values(:OLD.book_id, :OLD.book_name, :OLD.author_name, :OLD.price, 'delete'); 53 | end; 54 | 55 | DELETE FROM Library WHERE book_id = 2; 56 | 57 | select* from library_audit 58 | 59 | select* from library -------------------------------------------------------------------------------- /DBMS/SQL Connectivity.txt: -------------------------------------------------------------------------------- 1 | package MySql; 2 | 3 | import java.sql.*; 4 | import java.util.Scanner; 5 | 6 | public class MySql { 7 | 8 | public static void main(String[] args) throws Exception { 9 | int n,sno; 10 | String name,telephone,gender; 11 | Scanner in=new Scanner(System.in); 12 | Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/[Database]","[Username]","[password]"); 13 | Statement stmt=con.createStatement(); 14 | PreparedStatement pstm=con.prepareStatement("insert into Personal values(?,?,?,?)"); 15 | PreparedStatement pstm1=con.prepareStatement("delete from Personal where sno=?"); 16 | System.out.print("Enter the no of record you want to insert:"); 17 | n=in.nextInt(); 18 | for(int i=0;i self.id] 32 | if not higher_nodes: 33 | # If no nodes have higher IDs, this node becomes the coordinator 34 | self.coordinator = self.id 35 | print(f"Node {self.id} becomes the coordinator.") 36 | return 37 | for higher_node in higher_nodes: 38 | higher_node.send_bully_election_message() 39 | 40 | def send_bully_election_message(self): 41 | # Sending a Bully election message to higher nodes 42 | print(f"Node {self.id} sends Bully election message.") 43 | time.sleep(1) # Simulate message passing delay 44 | print(f"Node {self.id} received no response, declares itself as coordinator.") 45 | self.coordinator = self.id 46 | 47 | def main(): 48 | nodes = [Node(1), Node(2), Node(3)] # Change the number of nodes as needed 49 | 50 | for node in nodes: 51 | # Each node participates in both Ring and Bully elections 52 | node.start_bully_election(nodes) 53 | node.start_ring_election(nodes) 54 | 55 | if __name__ == "__main__": 56 | main() 57 | -------------------------------------------------------------------------------- /DBMS/BasicSQL8.txt: -------------------------------------------------------------------------------- 1 | CREATE TABLE Cust_Master ( 2 | Cust_no VARCHAR(10) PRIMARY KEY, 3 | Cust_name VARCHAR(100), 4 | Qty_Ordered INT, 5 | Order_date DATE, 6 | Cust_addr VARCHAR(255) 7 | ); 8 | 9 | INSERT INTO Cust_Master (Cust_no, Cust_name, Qty_Ordered, Order_date, Cust_addr) 10 | VALUES ('C1001', 'Vishwajeet', 20, TO_DATE('2024-10-01', 'YYYY-MM-DD'), 'Pune'); 11 | 12 | INSERT INTO Cust_Master (Cust_no, Cust_name, Qty_Ordered, Order_date, Cust_addr) 13 | VALUES ('C1002', 'Samantha', 15, TO_DATE('2024-10-02', 'YYYY-MM-DD'), 'Banglore'); 14 | 15 | INSERT INTO Cust_Master (Cust_no, Cust_name, Qty_Ordered, Order_date, Cust_addr) 16 | VALUES ('C1003', 'Shivani', 30, TO_DATE('2024-10-03', 'YYYY-MM-DD'), 'Manglore'); 17 | 18 | INSERT INTO Cust_Master (Cust_no, Cust_name, Qty_Ordered, Order_date, Cust_addr) 19 | VALUES ('C1004', 'Vaibhavi', 25, TO_DATE('2024-10-04', 'YYYY-MM-DD'), 'Manglore'); 20 | 21 | INSERT INTO Cust_Master (Cust_no, Cust_name, Qty_Ordered, Order_date, Cust_addr) 22 | VALUES ('C1005', 'Sahil', 40, TO_DATE('2024-10-05', 'YYYY-MM-DD'), 'Banglore'); 23 | 24 | INSERT INTO Cust_Master (Cust_no, Cust_name, Qty_Ordered, Order_date, Cust_addr) 25 | VALUES ('C1006', 'Abhi', 18, TO_DATE('2024-10-06', 'YYYY-MM-DD'), 'Manglore'); 26 | 27 | INSERT INTO Cust_Master (Cust_no, Cust_name, Qty_Ordered, Order_date, Cust_addr) 28 | VALUES ('C1007', 'Bhairavi', 22, TO_DATE('2024-10-07', 'YYYY-MM-DD'), 'Manglore'); 29 | 30 | INSERT INTO Cust_Master (Cust_no, Cust_name, Qty_Ordered, Order_date, Cust_addr) 31 | VALUES ('C1008', 'Sujata', 35, TO_DATE('2024-10-08', 'YYYY-MM-DD'), 'Banglore'); 32 | 33 | INSERT INTO Cust_Master (Cust_no, Cust_name, Qty_Ordered, Order_date, Cust_addr) 34 | VALUES ('C1009', 'Shital', 10, TO_DATE('2024-10-09', 'YYYY-MM-DD'), 'Manglore'); 35 | 36 | INSERT INTO Cust_Master (Cust_no, Cust_name, Qty_Ordered, Order_date, Cust_addr) 37 | VALUES ('C1010', 'Sahil', 50, TO_DATE('2024-10-10', 'YYYY-MM-DD'), 'Banglore'); 38 | 39 | SELECT * FROM cust_master; 40 | 41 | SELECT Cust_name 42 | FROM Cust_Master 43 | WHERE Cust_name LIKE '_a%'; 44 | 45 | SELECT Cust_name, Cust_addr 46 | FROM Cust_Master 47 | WHERE Cust_addr LIKE 'M%'; 48 | 49 | SELECT * FROM Cust_Master 50 | WHERE Cust_no IN ('C1002', 'C1005', 'C1007', 'C1008'); 51 | 52 | SELECT Cust_name, Cust_addr 53 | FROM Cust_Master 54 | WHERE Cust_addr IN ('Banglore', 'Manglore'); 55 | 56 | CREATE VIEW Customer_View AS 57 | SELECT Cust_no, Qty_Ordered, Order_date 58 | FROM Cust_Master; -------------------------------------------------------------------------------- /LP-1/IOTES/eye dection.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import picamera 4 | import picamera.array 5 | 6 | def main(): 7 | # Load the face and eye detection cascades 8 | face_cascade = cv2.CascadeClassifier('/home/pi/.local/lib/python3.5/site-packages/cv2/data/haarcascade_frontalface_default.xml') 9 | eye_cascade = cv2.CascadeClassifier('/home/pi/.local/lib/python3.5/site-packages/cv2/data/haarcascade_eye.xml') 10 | # You'll need the XML file for eye detection 11 | 12 | with picamera.PiCamera() as camera: 13 | camera.resolution = (320, 240) 14 | camera.framerate = 15 15 | 16 | with picamera.array.PiRGBArray(camera, size=(320, 240)) as stream: 17 | for frame in camera.capture_continuous(stream, format='bgr', use_video_port=True): 18 | image = frame.array 19 | 20 | # Convert the image to grayscale for face and eye detection 21 | gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 22 | 23 | # Detect faces 24 | faces = face_cascade.detectMultiScale(gray, 1.1, 5) 25 | 26 | for (x, y, w, h) in faces: 27 | cv2.rectangle(image, (x, y), (x+w, y+h), (255, 255, 0), 2) 28 | 29 | # Region of interest in the grayscale image for eyes detection 30 | roi_gray = gray[y:y+h, x:x+w] 31 | # Region of interest in the color image for drawing rectangles around eyes 32 | roi_color = image[y:y+h, x:x+w] 33 | 34 | # Detect eyes within the region of interest (i.e., the detected face) 35 | eyes = eye_cascade.detectMultiScale(roi_gray, 1.03, 5, minSize=(30,30)) 36 | for (ex, ey, ew, eh) in eyes: 37 | cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2) 38 | 39 | # Resize the frame for displaying in a larger window 40 | display_frame = cv2.resize(image, (640, 480)) 41 | 42 | # Display the frame 43 | cv2.imshow('Face and Eye Detection', display_frame) 44 | 45 | # Clear the stream for the next frame 46 | stream.truncate(0) 47 | 48 | # Close the window when 'q' is pressed 49 | if cv2.waitKey(1) & 0xFF == ord('q'): 50 | break 51 | 52 | cv2.destroyAllWindows() 53 | 54 | if __name__ == '__main__': 55 | main() -------------------------------------------------------------------------------- /LP-1/HCI/unitConverter1.py: -------------------------------------------------------------------------------- 1 | #Unit Converter 1 2 | import tkinter as tk 3 | 4 | # Function to perform weight conversion 5 | def convert_weight(): 6 | try: 7 | input_value = float(entry.get()) 8 | from_unit = from_units.get() 9 | to_unit = to_units.get() 10 | 11 | if from_unit == "Kilograms" and to_unit == "Pounds": 12 | result = input_value * 2.20462 13 | elif from_unit == "Pounds" and to_unit == "Kilograms": 14 | result = input_value / 2.20462 15 | elif from_unit == "Kilograms" and to_unit == "Grams": 16 | result = input_value * 1000 17 | elif from_unit == "Grams" and to_unit == "Kilograms": 18 | result = input_value / 1000 19 | elif from_unit == "Pounds" and to_unit == "Ounces": 20 | result = input_value * 16 21 | elif from_unit == "Ounces" and to_unit == "Pounds": 22 | result = input_value / 16 23 | else: 24 | result = input_value 25 | 26 | result_label.config(text=f"Result: {result} {to_unit}", fg="green") 27 | except ValueError: 28 | result_label.config(text="Invalid input", fg="red") 29 | 30 | # Create the main application window 31 | root = tk.Tk() 32 | root.title("Weight Converter") 33 | root.geometry("550x250") 34 | 35 | # Entry widget for input 36 | entry = tk.Entry(root, width=15, font=("Arial", 12), bg="lightyellow", fg="black") 37 | entry.grid(row=0, column=0, padx=10, pady=10) 38 | 39 | # Dropdown menus for unit selection 40 | from_units = tk.StringVar() 41 | from_units.set("Kilograms") 42 | to_units = tk.StringVar() 43 | to_units.set("Pounds") 44 | 45 | from_units_menu = tk.OptionMenu(root, from_units, "Kilograms", "Pounds", "Grams", "Ounces") 46 | to_units_menu = tk.OptionMenu(root, to_units, "Kilograms", "Pounds", "Grams", "Ounces") 47 | 48 | from_units_menu.config(font=("Arial", 12)) 49 | to_units_menu.config(font=("Arial", 12)) 50 | 51 | from_units_menu.grid(row=0, column=1, padx=10, pady=10) 52 | to_units_menu.grid(row=0, column=2, padx=10, pady=10) 53 | 54 | # Convert button 55 | convert_button = tk.Button(root, text="Convert", command=convert_weight, font=("Arial", 12), bg="blue", fg="white") 56 | convert_button.grid(row=0, column=3, padx=10, pady=10) 57 | 58 | # Result label 59 | result_label = tk.Label(root, text="Result:", font=("Arial", 14)) 60 | result_label.grid(row=1, column=0, columnspan=4, padx=10, pady=10) 61 | 62 | # Start the application 63 | root.mainloop() -------------------------------------------------------------------------------- /AIML Honor/Ass_1.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | import seaborn as sns 5 | 6 | # Load Iris dataset 7 | iris = pd.read_csv("https://media.githubusercontent.com/media/neurospin/pystatsml/refs/heads/master/datasets/iris.csv") 8 | 9 | # Check the column names 10 | print("Column names in the dataset:") 11 | print(iris.columns.tolist()) # Print as a list to see the actual names 12 | 13 | # Extract Sepal Length and Sepal Width 14 | # Make sure to use the correct names after checking 15 | sepal_length = iris['sepal_length'] # Update the name if necessary 16 | sepal_width = iris['sepal_width'] # Update the name if necessary 17 | 18 | # Compute Mean 19 | mean_sepal_length = np.mean(sepal_length) 20 | mean_sepal_width = np.mean(sepal_width) 21 | 22 | # Compute Variance 23 | var_sepal_length = np.var(sepal_length, ddof=1) # ddof=1 for sample variance 24 | var_sepal_width = np.var(sepal_width, ddof=1) 25 | 26 | # Compute Standard Deviation 27 | std_sepal_length = np.std(sepal_length, ddof=1) 28 | std_sepal_width = np.std(sepal_width, ddof=1) 29 | 30 | # Compute Covariance 31 | covariance = np.cov(sepal_length, sepal_width)[0, 1] 32 | 33 | # Compute Correlation 34 | correlation = np.corrcoef(sepal_length, sepal_width)[0, 1] 35 | 36 | # Compute Standard Error 37 | n = len(sepal_length) 38 | std_error_sepal_length = std_sepal_length / np.sqrt(n) 39 | std_error_sepal_width = std_sepal_width / np.sqrt(n) 40 | 41 | # Print Results 42 | print(f"Mean Sepal Length: {mean_sepal_length}") 43 | print(f"Mean Sepal Width: {mean_sepal_width}") 44 | print(f"Variance Sepal Length: {var_sepal_length}") 45 | print(f"Variance Sepal Width: {var_sepal_width}") 46 | print(f"Standard Deviation Sepal Length: {std_sepal_length}") 47 | print(f"Standard Deviation Sepal Width: {std_sepal_width}") 48 | print(f"Covariance: {covariance}") 49 | print(f"Correlation: {correlation}") 50 | print(f"Standard Error Sepal Length: {std_error_sepal_length}") 51 | print(f"Standard Error Sepal Width: {std_error_sepal_width}") 52 | 53 | # Plot Distribution of Sepal Length and Sepal Width 54 | plt.figure(figsize=(12, 6)) 55 | 56 | # Distribution plot for Sepal Length 57 | plt.subplot(1, 2, 1) 58 | sns.histplot(sepal_length, kde=True, color='blue') 59 | plt.title('Distribution of Sepal Length') 60 | plt.xlabel('Sepal Length') 61 | 62 | # Distribution plot for Sepal Width 63 | plt.subplot(1, 2, 2) 64 | sns.histplot(sepal_width, kde=True, color='green') 65 | plt.title('Distribution of Sepal Width') 66 | plt.xlabel('Sepal Width') 67 | 68 | plt.tight_layout() 69 | plt.show() 70 | -------------------------------------------------------------------------------- /LP-1/HCI/stickyNotes.py: -------------------------------------------------------------------------------- 1 | #Sticky Notes 2 | import tkinter as tk 3 | from tkinter import messagebox, simpledialog 4 | 5 | def save_note(): 6 | note_text = text_entry.get("1.0", "end-1c") 7 | if note_text.strip(): 8 | with open("notes.txt", "a") as file: 9 | file.write(note_text + "\n") 10 | text_entry.delete("1.0", tk.END) 11 | messagebox.showinfo("Note Saved", "Your note has been saved.") 12 | else: 13 | messagebox.showwarning("Empty Note", "Please enter some text before saving.") 14 | 15 | def view_notes(): 16 | try: 17 | with open("notes.txt", "r") as file: 18 | notes = file.read() 19 | notes_window = tk.Toplevel(root) 20 | notes_window.title("Notes") 21 | notes_text = tk.Text(notes_window, bg="lightyellow", fg="blue") 22 | notes_text.insert(tk.END, notes) 23 | notes_text.pack() 24 | except FileNotFoundError: 25 | messagebox.showwarning("No Notes Found", "There are no notes to display.") 26 | 27 | def clear_notes(): 28 | confirmed = messagebox.askyesno("Confirm", "Are you sure you want to clear all notes?") 29 | if confirmed: 30 | with open("notes.txt", "w") as file: 31 | file.truncate(0) 32 | messagebox.showinfo("Notes Cleared", "All notes have been cleared.") 33 | 34 | def open_specific_note(): 35 | try: 36 | with open("notes.txt", "r") as file: 37 | notes = file.readlines() 38 | 39 | note_index = simpledialog.askinteger("Open Note", "Enter the note number you want to open:", minvalue=1, maxvalue=len(notes)) 40 | 41 | if note_index: 42 | note_index -= 1 # Adjust to 0-based index 43 | note = notes[note_index] 44 | notes_window = tk.Toplevel(root) 45 | notes_window.title(f"Note {note_index + 1}") 46 | notes_text = tk.Text(notes_window, bg="lightyellow", fg="blue") 47 | notes_text.insert(tk.END, note) 48 | notes_text.pack() 49 | except FileNotFoundError: 50 | messagebox.showwarning("No Notes Found", "There are no notes to display.") 51 | 52 | root = tk.Tk() 53 | root.title("Note-taking App") 54 | 55 | # Text Entry 56 | text_entry = tk.Text(root, height=10, width=40, bg="lightblue", fg="black") 57 | text_entry.pack(pady=10) 58 | 59 | # Buttons 60 | save_button = tk.Button(root, text="Save Note", command=save_note, bg="green", fg="white") 61 | view_button = tk.Button(root, text="View Notes", command=view_notes, bg="orange", fg="white") 62 | clear_button = tk.Button(root, text="Clear Notes", command=clear_notes, bg="red", fg="white") 63 | open_button = tk.Button(root, text="Open Note", command=open_specific_note, bg="purple", fg="white") 64 | 65 | save_button.pack() 66 | view_button.pack() 67 | clear_button.pack() 68 | open_button.pack() 69 | 70 | root.mainloop() 71 | -------------------------------------------------------------------------------- /LP-1/SPOS/Assembler/AssemblerPass2/Main.java: -------------------------------------------------------------------------------- 1 | package Assembler.AssemblerPass2; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.FileReader; 5 | import java.io.FileWriter; 6 | import java.io.IOException; 7 | import java.util.HashMap; 8 | 9 | 10 | public class Main 11 | { 12 | public static void main(String[] Args) throws IOException 13 | { 14 | BufferedReader b1 = new BufferedReader(new FileReader("E:\\Coding\\TE_SEM_V\\SPOS\\TE_SPOS\\src\\Assembler.AssemblerPass2\\intermediate.txt")); 15 | BufferedReader b2 = new BufferedReader(new FileReader("E:\\Coding\\TE_SEM_V\\SPOS\\TE_SPOS\\src\\Assembler.AssemblerPass2\\symtab.txt")); 16 | BufferedReader b3 = new BufferedReader(new FileReader("E:\\Coding\\TE_SEM_V\\SPOS\\TE_SPOS\\src\\Assembler.AssemblerPass2\\littab.txt")); 17 | FileWriter f1 = new FileWriter("Pass2.txt"); 18 | HashMap symSymbol = new HashMap(); 19 | HashMap litSymbol = new HashMap(); 20 | HashMap litAddr = new HashMap(); 21 | String s; int symtabPointer=1,littabPointer=1,offset; 22 | while((s=b2.readLine())!=null) 23 | { String word[]=s.split("\t\t\t"); 24 | symSymbol.put(symtabPointer++,word[1]); 25 | } 26 | while((s=b3.readLine())!=null) 27 | { String word[]=s.split("\t\t"); 28 | litSymbol.put(littabPointer,word[0]); 29 | litAddr.put(littabPointer++,word[1]); 30 | } 31 | while((s=b1.readLine())!=null) 32 | { 33 | if(s.substring(1,6).compareToIgnoreCase("IS,00")==0) 34 | { f1.write("+ 00 0 000\n"); } 35 | else if(s.substring(1,3).compareToIgnoreCase("IS")==0) 36 | { f1.write("+ "+s.substring(4,6)+" "); 37 | if(s.charAt(9)==')') 38 | { 39 | f1.write(s.charAt(8)+" "); 40 | offset=3; 41 | } 42 | else 43 | { 44 | f1.write("0 "); 45 | offset=0; 46 | } 47 | if(s.charAt(8+offset)=='S') 48 | f1.write(symSymbol.get(Integer.parseInt(s.substring(10+offset,s.length()-1)))+"\n"); 49 | else f1.write(litAddr.get(Integer.parseInt(s.substring(10+offset,s.length()-1)))+"\n"); 50 | } 51 | else if(s.substring(1,6).compareToIgnoreCase("DL,01")==0) 52 | { 53 | String s1=s.substring(10,s.length()-1),s2=""; 54 | for(int i=0;i<3-s1.length();i++) 55 | s2+="0"; 56 | s2+=s1; 57 | f1.write("+ 00 0 "+s2+"\n"); 58 | } 59 | else{ 60 | f1.write("\n"); 61 | } 62 | } 63 | f1.close(); 64 | b1.close(); 65 | b2.close(); 66 | b3.close(); 67 | } 68 | } -------------------------------------------------------------------------------- /DBMS/BasicSQL10.txt: -------------------------------------------------------------------------------- 1 | CREATE SEQUENCE owner_seq START WITH 1 INCREMENT BY 1; 2 | 3 | CREATE SEQUENCE property_seq START WITH 1 INCREMENT BY 1; 4 | 5 | CREATE TABLE OWNERS ( 6 | OwnerNo INT PRIMARY KEY, 7 | OwnerName VARCHAR2(100), 8 | Phno VARCHAR2(15) 9 | ); 10 | 11 | CREATE TABLE PROPERTIES ( 12 | Pno INT PRIMARY KEY, 13 | Type VARCHAR2(50), 14 | Sq_Ft_Area INT, 15 | Rent DECIMAL(10, 2), 16 | Address VARCHAR2(255), 17 | Status VARCHAR2(50), 18 | OwnerNo INT, 19 | CONSTRAINT fk_owner FOREIGN KEY (OwnerNo) REFERENCES OWNERS(OwnerNo) 20 | ); 21 | 22 | INSERT INTO OWNERS (OwnerNo, OwnerName, Phno) 23 | VALUES (owner_seq.NEXTVAL, 'Vishwajeet', '8459652020'); 24 | 25 | INSERT INTO OWNERS (OwnerNo, OwnerName, Phno) 26 | VALUES (owner_seq.NEXTVAL, 'Ranjeet', '7058580091'); 27 | 28 | INSERT INTO OWNERS (OwnerNo, OwnerName, Phno) 29 | VALUES (owner_seq.NEXTVAL, 'Aditi', '6787667876'); 30 | 31 | INSERT INTO OWNERS (OwnerNo, OwnerName, Phno) 32 | VALUES (owner_seq.NEXTVAL, 'Akanksha', '8977757587'); 33 | 34 | -- Inserting properties with property_seq for Pno and using owner_seq for OwnerNo 35 | INSERT INTO PROPERTIES (Pno, Type, Sq_Ft_Area, Rent, Address, Status, OwnerNo) 36 | VALUES (property_seq.NEXTVAL, '1BHK', 600, 10000, 'Kothrud', 'Not Rented', 1); 37 | 38 | INSERT INTO PROPERTIES (Pno, Type, Sq_Ft_Area, Rent, Address, Status, OwnerNo) 39 | VALUES (property_seq.NEXTVAL, '2BHK', 800, 15000, 'Kothrud', 'Rented', 2); 40 | 41 | INSERT INTO PROPERTIES (Pno, Type, Sq_Ft_Area, Rent, Address, Status, OwnerNo) 42 | VALUES (property_seq.NEXTVAL, '1BHK', 650, 12000, 'Kothrud', 'Not Rented', 3); 43 | 44 | INSERT INTO PROPERTIES (Pno, Type, Sq_Ft_Area, Rent, Address, Status, OwnerNo) 45 | VALUES (property_seq.NEXTVAL, '3BHK', 1200, 25000, 'Kothrud', 'Rented', 4); 46 | 47 | INSERT INTO PROPERTIES (Pno, Type, Sq_Ft_Area, Rent, Address, Status, OwnerNo) 48 | VALUES (property_seq.NEXTVAL, '1BHK', 550, 9000, 'Kothrud', 'Not Rented', 1); 49 | 50 | INSERT INTO PROPERTIES (Pno, Type, Sq_Ft_Area, Rent, Address, Status, OwnerNo) 51 | VALUES (property_seq.NEXTVAL, '2BHK', 900, 18000, 'Kothrud', 'Not Rented', 2); 52 | 53 | SELECT * FROM OWNERS; 54 | SELECT * FROM PROPERTIES; 55 | 56 | SELECT * 57 | FROM PROPERTIES 58 | WHERE Type = '1BHK' 59 | AND Address = 'Kothrud' 60 | AND Status = 'Not Rented'; 61 | 62 | SELECT P.* 63 | FROM PROPERTIES P 64 | JOIN OWNERS O ON P.OwnerNo = O.OwnerNo 65 | WHERE O.OwnerName = 'Gopal'; 66 | 67 | SELECT OwnerNo, MIN(Sq_Ft_Area) AS SmallestPropertyArea 68 | FROM PROPERTIES 69 | GROUP BY OwnerNo; 70 | 71 | SELECT * 72 | FROM PROPERTIES 73 | WHERE Address = 'Kothrud' 74 | ORDER BY Rent DESC; 75 | 76 | CREATE OR REPLACE VIEW OwnerProperties AS 77 | SELECT O.OwnerName, P.Pno, P.Type, P.Address, P.Rent 78 | FROM PROPERTIES P 79 | JOIN OWNERS O ON P.OwnerNo = O.OwnerNo; 80 | 81 | SELECT OwnerName 82 | FROM OWNERS 83 | WHERE OwnerName LIKE '%ee%'; 84 | 85 | SELECT Pno, Type, Address, Rent, Status 86 | FROM PROPERTIES 87 | WHERE Rent > 15000 AND Rent < 22000; 88 | 89 | SELECT DISTINCT Type 90 | FROM PROPERTIES; -------------------------------------------------------------------------------- /LP-1/SPOS/Assembler/AssemblerPass2/PassII.java: -------------------------------------------------------------------------------- 1 | package Assembler.AssemblerPass2; 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | 6 | public class PassII { 7 | public static void main(String[] args) throws IOException { 8 | //Creating file object to read data from 3 txt files 9 | BufferedReader br = new BufferedReader(new FileReader("E:\\Coding\\TE_SEM_V\\SPOS\\TE_SPOS\\src\\Assembler\\AssemblerPass2\\intermediate.txt")); 10 | BufferedReader b2 = new BufferedReader(new FileReader("E:\\Coding\\TE_SEM_V\\SPOS\\TE_SPOS\\src\\Assembler\\AssemblerPass2\\symtab.txt")); 11 | BufferedReader b3 = new BufferedReader(new FileReader("E:\\Coding\\TE_SEM_V\\SPOS\\TE_SPOS\\src\\Assembler\\AssemblerPass2\\littab.txt")); 12 | 13 | //Creating file writer object 14 | FileWriter fw = new FileWriter("P2.txt"); 15 | 16 | //Map the pointer and the symbol/literal addresses 17 | HashMap symSymbol = new HashMap(); 18 | HashMap litSymbol = new HashMap(); 19 | HashMap litAddr = new HashMap(); 20 | int symtabPointer=1,littabPointer=1; 21 | String line,s; 22 | 23 | //Mapping symbol addresses with symbol ptr 24 | while((s=b2.readLine())!=null) 25 | { 26 | String word[]=s.split("\t\t\t"); 27 | symSymbol.put(symtabPointer++,word[1]); 28 | } 29 | 30 | //Mapping literal addresses with literal ptr 31 | while((s=b3.readLine())!=null) 32 | { 33 | String word[]=s.split("\t\t"); 34 | litSymbol.put(littabPointer,word[0]); 35 | litAddr.put(littabPointer++,word[1]); 36 | } 37 | 38 | //Reading intermediate code 39 | while((line=br.readLine())!=null){ 40 | //Skipping processing of Assembler Directives 41 | if(line.contains("AD")) { 42 | fw.write("\n"); 43 | continue; 44 | } 45 | //Processing imperative statements 46 | else if(line.contains("IS")){ 47 | if(line.contains("IS,00")) 48 | fw.write("+ 00 0 000\n"); 49 | else 50 | fw.write("+ " + line.substring(4,6) + " " + line.charAt(8) + " "); 51 | if(line.contains("(S,")){ 52 | fw.write(symSymbol.get(Integer.parseInt(line.substring(13,14)))+"\n"); 53 | } 54 | else if(line.contains("(L,")){ 55 | fw.write(litAddr.get(Integer.parseInt(line.substring(13,14)))+"\n"); 56 | } 57 | } 58 | //Process DS statement 59 | else if(line.contains("DL,01")){ 60 | fw.write("+ 00 0 00" + line.charAt(10) + "\n"); 61 | } 62 | else if(line.contains("DL,02")){ 63 | fw.write("\n"); 64 | } 65 | } 66 | fw.close(); 67 | br.close(); 68 | b2.close(); 69 | b3.close(); 70 | } 71 | } -------------------------------------------------------------------------------- /DBMS/SQL Joins.txt: -------------------------------------------------------------------------------- 1 | create table inst 2 | ( 3 | inst_id number(10), 4 | inst_name varchar2(20), 5 | inst_salary number(20) 6 | ) 7 | 8 | create table department 9 | ( 10 | dept_id number(10), 11 | dept_name varchar2(20), 12 | inst_id number(20) 13 | ) 14 | 15 | INSERT INTO inst VALUES(1,'Vishwajeet',50000) 16 | 17 | INSERT INTO inst VALUES(2,'Sahil',51000) 18 | 19 | INSERT INTO inst VALUES(3,'Apurva',52000) 20 | 21 | INSERT INTO inst VALUES(4,'Rutuja',55000) 22 | 23 | INSERT INTO inst VALUES(5,'Shivam',40000) 24 | 25 | INSERT INTO inst VALUES(6,'Hemali',30000) 26 | 27 | INSERT INTO inst VALUES(7,'Anushka',60000) 28 | 29 | INSERT INTO inst VALUES(8,'Rituja',40000) 30 | 31 | INSERT INTO inst VALUES(9,'Omkar',45000) 32 | 33 | INSERT INTO inst VALUES(10,'Varad',50000) 34 | 35 | INSERT INTO inst VALUES(11,'Shreya',20000) 36 | 37 | INSERT INTO inst VALUES(12,'Krishna',45000) 38 | 39 | INSERT INTO inst VALUES(13,'Radha',30000) 40 | 41 | Select * from inst 42 | 43 | INSERT INTO department VALUES(111,'Computer',1) 44 | 45 | INSERT INTO department VALUES(222,'IT',2) 46 | 47 | INSERT INTO department VALUES(333,'Electrical',3) 48 | 49 | INSERT INTO department VALUES(444,'Mechanical',4) 50 | 51 | INSERT INTO department VALUES(555,'Civil',5) 52 | 53 | INSERT INTO department VALUES(666,'AIML',6) 54 | 55 | INSERT INTO department VALUES(777,'AIDS',7) 56 | 57 | INSERT INTO department VALUES(888,'ECE',8) 58 | 59 | INSERT INTO department VALUES(999,'ENTC',9) 60 | 61 | Select * from department 62 | 63 | Select * from inst INNER JOIN department ON inst.inst_id=department.inst_id 64 | 65 | Select * from inst LEFT JOIN department ON inst.inst_id=department.inst_id 66 | 67 | Select * from department LEFT JOIN inst ON inst.inst_id=department.inst_id 68 | 69 | Select * from department RIGHT JOIN inst ON inst.inst_id=department.inst_id 70 | 71 | Select * from department FULL JOIN inst ON inst.inst_id=department.inst_id 72 | 73 | select inst_name from inst where inst_salary=(select max(inst_salary) from inst) 74 | 75 | select inst_name from inst where inst_id in (select inst_id from department) 76 | 77 | create view inst_view as select inst_name,inst_salary from inst where inst_salary>50000 78 | 79 | select * from inst_view 80 | 81 | UPDATE inst_view SET inst_salary=55000 WHERE inst_name='Sakshi' 82 | 83 | select * from inst_view 84 | 85 | CREATE OR REPLACE view inst_view AS SELECT inst_id,inst_name,inst_salary FROM inst WHERE inst_salary >40000 86 | 87 | select * from inst_view 88 | 89 | select distinct dept_name 90 | from department 91 | 92 | select avg(inst_salary) 93 | from inst 94 | 95 | select count(inst_name) 96 | from inst,department 97 | where dept_name='IT' 98 | 99 | select count(inst_id) 100 | from department 101 | where dept_name='IT' 102 | 103 | select sum(inst_salary) 104 | from department,inst 105 | where dept_name='Computer' 106 | 107 | select sum(inst_salary) 108 | from inst,department -------------------------------------------------------------------------------- /DBMS/MongoDB Map Reduce.txt: -------------------------------------------------------------------------------- 1 | db.customer.insertMany([ 2 | { name: "Alice", emailID: "alice@example.com", profession: "Engineer", gender: "Female", bill_amount: 3000 }, 3 | { name: "Bob", emailID: "bob@example.com", profession: "Business", gender: "Male", bill_amount: 7000 }, 4 | { name: "Charlie", emailID: "charlie@example.com", profession: "Doctor", gender: "Male", bill_amount: 4500 }, 5 | { name: "David", emailID: "david@example.com", profession: "Engineer", gender: "Male", bill_amount: 5500 }, 6 | { name: "Eva", emailID: "eva@example.com", profession: "Lawyer", gender: "Female", bill_amount: 6000 }, 7 | { name: "Brian", emailID: "brian@example.com", profession: "Business", gender: "Male", bill_amount: 12000 }, 8 | { name: "Sophia", emailID: "sophia@example.com", profession: "Teacher", gender: "Female", bill_amount: 2000 } 9 | ]); 10 | 11 | db.customer.mapReduce( 12 | function() { emit(this.gender, 1); }, 13 | function(key, values) { return Array.sum(values); }, 14 | { out: "gender_count" } 15 | ); 16 | 17 | // View the results 18 | db.gender_count.find(); 19 | 20 | db.customer.mapReduce( 21 | function() { emit(this.profession, 1); }, 22 | function(key, values) { return Array.sum(values); }, 23 | { out: "profession_count" } 24 | ); 25 | 26 | // View the results 27 | db.profession_count.find(); 28 | 29 | db.customer.mapReduce( 30 | function() { 31 | if (this.bill_amount > 5000) { 32 | emit(this.name, { emailID: this.emailID, profession: this.profession, gender: this.gender, bill_amount: this.bill_amount }); 33 | } 34 | }, 35 | function(key, values) { return values[0]; }, 36 | { out: "high_bill_customers" } 37 | ); 38 | 39 | // View the results 40 | db.high_bill_customers.find(); 41 | 42 | db.customer.remove({ name: "Alice" }); 43 | 44 | db.customer.insert({ name: "Alice", emailID: "alice@example.com", profession: "Engineer", gender: "Female", bill_amount: 3500 }); 45 | 46 | db.customer.mapReduce( 47 | function() { 48 | if (this.name.startsWith('B')) { 49 | emit(this.name, { emailID: this.emailID, profession: this.profession, gender: this.gender, bill_amount: this.bill_amount }); 50 | } 51 | }, 52 | function(key, values) { return values[0]; }, 53 | { out: "name_starts_with_b" } 54 | ); 55 | 56 | // View the results 57 | db.name_starts_with_b.find(); 58 | 59 | db.customer.mapReduce( 60 | function() { 61 | if (this.profession === "Business") { 62 | emit(this.name, { emailID: this.emailID, profession: this.profession, gender: this.gender, bill_amount: this.bill_amount }); 63 | } 64 | }, 65 | function(key, values) { return values[0]; }, 66 | { out: "business_profession_customers" } 67 | ); 68 | 69 | // View the results 70 | db.business_profession_customers.find(); 71 | 72 | db.customer.mapReduce( 73 | function() { emit(this.bill_amount, { name: this.name, emailID: this.emailID, profession: this.profession, gender: this.gender }); }, 74 | function(key, values) { return values[0]; }, 75 | { out: "sorted_by_bill_amount" } 76 | ); 77 | 78 | // View the results in descending order 79 | db.sorted_by_bill_amount.find().sort({ _id: -1 }); -------------------------------------------------------------------------------- /DBMS/MongoDB Connectivity.txt: -------------------------------------------------------------------------------- 1 | package MongoDB; 2 | 3 | import java.util.Scanner; 4 | 5 | import com.mongodb.*; 6 | 7 | 8 | public class MongoDB { 9 | public static void Stringdata(String data,DBCollection table) { 10 | DBCursor cursor=table.find(); 11 | if(cursor.hasNext()) { 12 | while(cursor.hasNext()) { 13 | String Strdata=(String)cursor.next().get(data); 14 | if(data=="Name") { 15 | System.out.print(data+" :"+Strdata+"\t\t\t"); 16 | } 17 | else { 18 | System.out.print(data+":"+Strdata+"\t"); 19 | } 20 | } 21 | System.out.println(" "); 22 | } 23 | else { 24 | System.out.print(""); 25 | } 26 | } 27 | 28 | public static void Intdata(String data,DBCollection table) { 29 | DBCursor cursor=table.find(); 30 | if(cursor.hasNext()) { 31 | while(cursor.hasNext()) { 32 | int dataint=(Integer)cursor.next().get(data); 33 | System.out.print(data+" :"+dataint+"\t\t\t\t"); 34 | } 35 | System.out.println(" "); 36 | } 37 | else { 38 | System.out.print(""); 39 | } 40 | } 41 | 42 | public static void main(String[] args) throws Exception { 43 | MongoClient mongo=new MongoClient("localhost",27017); 44 | System.out.println("Connected to the database successfully"); 45 | 46 | Scanner sc=new Scanner(System.in); 47 | int n,age=0; 48 | String name=" ",mobileno=" ",ans=" ",ans1=" "; 49 | 50 | do { 51 | DB db=mongo.getDB("Info"); 52 | DBCollection table=db.createCollection("Personal",null); 53 | System.out.println("Enter the no of record you want to insert:"); 54 | n=sc.nextInt(); 55 | for(int i=1;i<=n;i++) { 56 | BasicDBObject info= new BasicDBObject(i); 57 | System.out.println("Enter Data"+(i)); 58 | System.out.print("Enter name:"); 59 | name=sc.next(); 60 | info.put("Name",name); 61 | System.out.print("Enter age:"); 62 | age=sc.nextInt(); 63 | info.put("Age",age); 64 | System.out.print("Enter Mobile Number:"); 65 | mobileno=sc.next(); 66 | info.put("Mobile Number",mobileno); 67 | table.insert(info); 68 | } 69 | System.out.println("Insert Operation"); 70 | Stringdata("Name", table); 71 | Stringdata("Mobile Number", table); 72 | Intdata("Age", table); 73 | 74 | System.out.print("Enter the no of record you want to delete:"); 75 | n=sc.nextInt(); 76 | for(int i=1;i<=n;i++) { 77 | BasicDBObject info= new BasicDBObject(i); 78 | System.out.println("Enter Data"+(i)); 79 | System.out.print("Enter name:"); 80 | name=sc.next(); 81 | info.put("Name",name); 82 | table.remove(info); 83 | } 84 | 85 | System.out.println("Delete Operation"); 86 | Stringdata("Name", table); 87 | Stringdata("Mobile Number", table); 88 | Intdata("Age", table); 89 | System.out.println("Do yo want to drop database: "); 90 | ans=sc.next(); 91 | if(ans.equals("y")||ans.equals("Y")){ 92 | db.dropDatabase(); 93 | System.out.println("Database Droped "); 94 | } 95 | System.out.println("Do you want to continue:"); 96 | ans1=sc.next(); 97 | }while(ans1.equals("y")||ans1.equals("Y")); 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /LP-1/HCI/colorMatch.py: -------------------------------------------------------------------------------- 1 | #Color Match Game 2 | import tkinter as tk 3 | import tkinter.messagebox 4 | import random 5 | 6 | class ColorMatchGame: 7 | def __init__(self, master): 8 | self.master = master 9 | self.master.title("Color Match Game") 10 | self.score = 0 11 | self.wrong_attempts = 0 12 | self.colors = ["red", "green", "blue", "yellow", "purple", "orange"] 13 | 14 | self.label = tk.Label(self.master, text="Match the color:") 15 | self.label.pack() 16 | 17 | self.score_label = tk.Label(self.master, text=f"Score: {self.score}", font=("Helvetica", 14)) 18 | self.score_label.pack() 19 | 20 | self.attempts_label = tk.Label(self.master, text=f"Wrong Attempts: {self.wrong_attempts}", font=("Helvetica", 14)) 21 | self.attempts_label.pack() 22 | 23 | self.match_label = tk.Label(self.master, text="", font=("Helvetica", 24)) 24 | self.match_label.pack() 25 | 26 | self.color_buttons_frame = tk.Frame(self.master) 27 | self.color_buttons_frame.pack() 28 | 29 | self.color_buttons = [] 30 | for color in self.colors: 31 | button = tk.Button(self.color_buttons_frame, text=color, bg=color, command=lambda c=color: self.check_color(c)) 32 | button.pack(side=tk.LEFT, padx=10, pady=10) 33 | self.color_buttons.append(button) 34 | 35 | self.start_again_button = tk.Button(self.master, text="Start Again", command=self.start_again) 36 | self.start_again_button.pack() 37 | 38 | self.show_random_color() 39 | 40 | def show_random_color(self): 41 | random_color = random.choice(self.colors) 42 | self.match_label.config(text=random_color, fg=random.choice(self.colors)) 43 | 44 | def check_color(self, selected_color): 45 | current_color = self.match_label.cget("text") 46 | if selected_color == current_color: 47 | self.score += 1 48 | self.wrong_attempts = 0 49 | self.score_label.config(text=f"Score: {self.score}") 50 | else: 51 | self.wrong_attempts += 1 52 | self.score -= 1 53 | self.attempts_label.config(text=f"Wrong Attempts: {self.wrong_attempts}") 54 | self.score_label.config(text=f"Score: {self.score}") 55 | 56 | if self.wrong_attempts == 3: 57 | self.game_over() 58 | 59 | self.show_random_color() 60 | 61 | def game_over(self): 62 | for button in self.color_buttons: 63 | button.config(state=tk.DISABLED) 64 | self.match_label.config(text="Game Over", fg="red") 65 | self.start_again_button.config(state=tk.NORMAL) 66 | tkinter.messagebox.showinfo("Game Over", f"Your final score: {self.score}") 67 | 68 | def start_again(self): 69 | for button in self.color_buttons: 70 | button.config(state=tk.NORMAL) 71 | self.score = 0 72 | self.wrong_attempts = 0 73 | self.score_label.config(text=f"Score: {self.score}") 74 | self.attempts_label.config(text=f"Wrong Attempts: {self.wrong_attempts}") 75 | self.start_again_button.config(state=tk.DISABLED) 76 | self.show_random_color() 77 | 78 | if __name__ == "__main__": 79 | root = tk.Tk() 80 | game = ColorMatchGame(root) 81 | game.show_random_color() 82 | root.mainloop() -------------------------------------------------------------------------------- /DBMS/SQL DDL & DML.txt: -------------------------------------------------------------------------------- 1 | CREATE TABLE world_cricket( 2 | player_jersey_no INT, 3 | player_name VARCHAR2(50), 4 | player_desc VARCHAR2(50), 5 | team_name VARCHAR2(30), 6 | ipl_team_name VARCHAR2(20), 7 | PRIMARY KEY (player_jersey_no) 8 | ); 9 | 10 | INSERT INTO world_cricket VALUES(45, 'Rohit', 'opening batsman', 'India', 'MI'); 11 | 12 | INSERT INTO world_cricket VALUES(18, 'Virat', '1st down batsman', 'India', 'RCB'); 13 | 14 | INSERT INTO world_cricket VALUES(93, 'Bumrah', 'fast bowler', 'India', 'MI'); 15 | 16 | INSERT INTO world_cricket VALUES(17, 'AB Devilliers', 'WK-Batter', 'South Africa', 'RCB'); 17 | 18 | INSERT INTO world_cricket VALUES(10, 'David Miller', '5th down batter', 'South Africa', 'GT'); 19 | 20 | INSERT INTO world_cricket VALUES(333, 'Chris Gayle', 'opening batsman', 'West Indies', 'PBK'); 21 | 22 | INSERT INTO world_cricket VALUES(49, 'Steve Smith', '2nd down batter', 'Australia', 'RR'); 23 | 24 | INSERT INTO world_cricket VALUES(22, 'Kane Williamson', '3rd down batter', 'New Zealand', 'GT'); 25 | 26 | INSERT INTO world_cricket VALUES(55, 'Ben Stokes', '4th down batter', 'England', 'CSK'); 27 | 28 | INSERT INTO world_cricket VALUES(24, 'Kevin Pietersen', '1st down batter', 'England', 'DC'); 29 | 30 | CREATE TABLE coach( 31 | coach_name VARCHAR2(20), 32 | coach_role VARCHAR2(20), 33 | PRIMARY KEY (coach_role) 34 | ); 35 | 36 | INSERT INTO coach VALUES ('Vikram Rathour', 'Batting Coach'); 37 | 38 | INSERT INTO coach VALUES ('Gautam Gambhir', 'Head Coach'); 39 | 40 | INSERT INTO coach VALUES ('Jonty Rhodes', 'Fielding Coach'); 41 | 42 | INSERT INTO coach VALUES ('Wasim Akram', 'Bowling Coach'); 43 | 44 | INSERT INTO coach VALUES ('Kamlesh Jain', 'Physio'); 45 | 46 | INSERT INTO coach VALUES ('Rajal Arora', 'Media Manager'); 47 | 48 | CREATE TABLE players_and_their_salaries ( 49 | player_name VARCHAR2(20), 50 | team_name VARCHAR2(20), 51 | player_salary VARCHAR2(7) NOT NULL, 52 | PRIMARY KEY (player_name) 53 | ); 54 | 55 | -- Inserting data into players_and_their_salaries 56 | INSERT INTO players_and_their_salaries VALUES ('Rohit Sharma', 'MI', '16cr'); 57 | 58 | INSERT INTO players_and_their_salaries VALUES ('Virat Kohli', 'RCB', '15cr'); 59 | 60 | INSERT INTO players_and_their_salaries VALUES ('Bumrah', 'MI', '10cr'); 61 | 62 | INSERT INTO players_and_their_salaries VALUES ('Ben Stokes', 'CSK', '12cr'); 63 | 64 | INSERT INTO players_and_their_salaries VALUES ('Chris Gayle', 'PBK', '2cr'); 65 | 66 | INSERT INTO players_and_their_salaries VALUES ('AB Devilliers', 'RCB', '14cr'); 67 | 68 | INSERT INTO players_and_their_salaries VALUES ('David Miller', 'GT', '5cr'); 69 | 70 | -- Selecting all data from world_cricket table 71 | SELECT * FROM world_cricket; 72 | 73 | -- Selecting all data from coach table 74 | SELECT * FROM coach; 75 | 76 | -- Selecting all data from players_and_their_salaries table 77 | SELECT * FROM players_and_their_salaries; 78 | 79 | -- Creating a view for MI team players 80 | CREATE VIEW view_emp AS 81 | SELECT player_name, team_name 82 | FROM world_cricket 83 | WHERE ipl_team_name = 'MI'; 84 | 85 | -- Selecting data from view 86 | SELECT * FROM view_emp; 87 | 88 | -- Altering coach table to add rank_id column 89 | ALTER TABLE coach 90 | ADD rank_id NUMBER(5); 91 | 92 | DELETE FROM world_cricket 93 | WHERE player_jersey_no = 18; 94 | 95 | - Selecting all data from coach table after alteration 96 | SELECT * FROM coach; 97 | 98 | -- Dropping the coach table 99 | DROP TABLE coach; -------------------------------------------------------------------------------- /DBMS/BasicSQL20.txt: -------------------------------------------------------------------------------- 1 | CREATE TABLE CUSTOMERS ( 2 | CNo NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 3 | Cname VARCHAR2(50) NOT NULL, 4 | Ccity VARCHAR2(50), 5 | CMobile VARCHAR2(15) UNIQUE 6 | ); 7 | 8 | CREATE TABLE ITEMS ( 9 | INo NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 10 | Iname VARCHAR2(50) NOT NULL, 11 | Itype VARCHAR2(50) CHECK (Itype IN ('Stationary', 'Electronics', 'Grocery')), 12 | Iprice NUMBER(10, 2) CHECK (Iprice > 0), 13 | Icount NUMBER CHECK (Icount >= 0) 14 | ); 15 | 16 | CREATE TABLE PURCHASE ( 17 | PNo NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 18 | Pdate DATE NOT NULL, 19 | Pquantity NUMBER CHECK (Pquantity > 0), 20 | CNo NUMBER REFERENCES CUSTOMERS(CNo), 21 | INo NUMBER REFERENCES ITEMS(INo) 22 | ); 23 | 24 | INSERT INTO CUSTOMERS (Cname, Ccity, CMobile) VALUES ('Gopal', 'Mumbai', '9876543210'); 25 | INSERT INTO CUSTOMERS (Cname, Ccity, CMobile) VALUES ('Maya', 'Delhi', '9988776655'); 26 | INSERT INTO CUSTOMERS (Cname, Ccity, CMobile) VALUES ('Rahul', 'Pune', '9123456789'); 27 | INSERT INTO CUSTOMERS (Cname, Ccity, CMobile) VALUES ('Nisha', 'Mumbai', '9876501234'); 28 | 29 | INSERT INTO ITEMS (Iname, Itype, Iprice, Icount) VALUES ('Notebook', 'Stationary', 500, 100); 30 | INSERT INTO ITEMS (Iname, Itype, Iprice, Icount) VALUES ('Pen', 'Stationary', 20, 300); 31 | INSERT INTO ITEMS (Iname, Itype, Iprice, Icount) VALUES ('Laptop', 'Electronics', 55000, 10); 32 | INSERT INTO ITEMS (Iname, Itype, Iprice, Icount) VALUES ('Calculator', 'Stationary', 800, 50); 33 | INSERT INTO ITEMS (Iname, Itype, Iprice, Icount) VALUES ('Rice', 'Grocery', 50, 200); 34 | INSERT INTO ITEMS (Iname, Itype, Iprice, Icount) VALUES ('Marker', 'Stationary', 450, 150); 35 | 36 | INSERT INTO PURCHASE (Pdate, Pquantity, CNo, INo) VALUES (TO_DATE('2024-11-01', 'YYYY-MM-DD'), 5, 1, 1); 37 | INSERT INTO PURCHASE (Pdate, Pquantity, CNo, INo) VALUES (TO_DATE('2024-11-05', 'YYYY-MM-DD'), 2, 2, 3); 38 | INSERT INTO PURCHASE (Pdate, Pquantity, CNo, INo) VALUES (TO_DATE('2024-11-07', 'YYYY-MM-DD'), 10, 1, 2); 39 | INSERT INTO PURCHASE (Pdate, Pquantity, CNo, INo) VALUES (TO_DATE('2024-11-10', 'YYYY-MM-DD'), 3, 3, 4); 40 | 41 | -- 1. List all stationary items with price between 400/- to 1000/- 42 | SELECT * FROM ITEMS 43 | WHERE Itype = 'Stationary' AND Iprice BETWEEN 400 AND 1000; 44 | 45 | -- 2. Change the mobile number of customer “Gopal” 46 | UPDATE CUSTOMERS 47 | SET CMobile = '9999999999' 48 | WHERE Cname = 'Gopal'; 49 | 50 | -- 3. Display the item with maximum price 51 | SELECT * FROM ITEMS 52 | WHERE Iprice = (SELECT MAX(Iprice) FROM ITEMS); 53 | 54 | -- 4. Display all purchases sorted from the most recent to the oldest 55 | SELECT * FROM PURCHASE 56 | ORDER BY Pdate DESC; 57 | 58 | -- 5. Count the number of customers in every city 59 | SELECT Ccity, COUNT(*) AS CustomerCount 60 | FROM CUSTOMERS 61 | GROUP BY Ccity; 62 | 63 | -- 6. Display all purchased quantity of Customer Maya 64 | SELECT P.Pquantity, I.Iname 65 | FROM PURCHASE P 66 | JOIN CUSTOMERS C ON P.CNo = C.CNo 67 | JOIN ITEMS I ON P.INo = I.INo 68 | WHERE C.Cname = 'Maya'; 69 | 70 | -- 7. Display list of customers whose name ends with 'a' 71 | SELECT * FROM CUSTOMERS 72 | WHERE Cname LIKE '%a'; 73 | 74 | -- 8. Create a view which shows Iname, Price, and Count of all stationary items in descending order of price 75 | CREATE VIEW StationaryItemsView AS 76 | SELECT Iname, Iprice, Icount 77 | FROM ITEMS 78 | WHERE Itype = 'Stationary' 79 | ORDER BY Iprice DESC; 80 | 81 | -- To view the contents of StationaryItemsView 82 | SELECT * FROM StationaryItemsView; -------------------------------------------------------------------------------- /CNS/SubnetMask.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class SubnetMask 4 | { 5 | public static void main(String[] args) 6 | { 7 | Scanner scan = new Scanner(System.in); 8 | String IP = new String(); 9 | int Mask=0,Default=0; 10 | System.out.print("Enter IP_Address : "); 11 | IP = scan.nextLine(); 12 | System.out.print("Enter Mask : "); 13 | Mask = scan.nextInt(); 14 | String[] Split_IP = IP.split("\\."); 15 | System.out.println(Split_IP[0]+" "+Split_IP[1]+" "+Split_IP[2]+" "+Split_IP[3]+" "); 16 | int First = Integer.parseInt(Split_IP[0]); 17 | if(First>=0&&First<=127) 18 | { 19 | System.out.println("CLASS A"); 20 | Default = 8; 21 | } 22 | else if(First>127&&First<=191) 23 | { 24 | System.out.println("CLASS B"); 25 | Default=16; 26 | } 27 | else if(First>191&&First<=223) 28 | { 29 | System.out.println("CLASS C"); 30 | Default=24; 31 | } 32 | else if(First>223) 33 | { 34 | System.out.println("CLASS D"); 35 | Default=32; 36 | } 37 | String Binary_IP = new String(); 38 | String Default_Mask = new String(); 39 | for(int i=0;i<4;i++) 40 | { 41 | Binary_IP = Binary_IP + appendZeroes(Integer.toBinaryString(Integer.parseInt(Split_IP[i]))); 42 | } 43 | System.out.println("IP in binary : "+Binary_IP); 44 | System.out.print("Default Mask : "+Default_Mask); 45 | for(int i=0;i<32;i++) 46 | { 47 | if(i", lambda event, text=button_text: self.keyPress(text)) 38 | self.tag_bind(text, "", lambda event, text=button_text: self.keyPress(text)) 39 | 40 | def hoverColor(self, item, button, color): 41 | if color == "#D0CECE": hover_color = "#E7E6E6" 42 | elif color == "#FFC000": hover_color = "#FFD966" 43 | elif color == "#262626": hover_color = "#595959" 44 | else: hover_color = "white" 45 | self.tag_bind(item, "", lambda event: self.itemconfigure(button, fill=hover_color)) 46 | self.tag_bind(item, "", lambda event: self.itemconfigure(button, fill=color)) 47 | 48 | def keyPress(self,text): 49 | if text=="C": calculator_screen.configure(text=0, font=("Arial",40)) 50 | elif text=="+/-": calculator_screen["text"] = -int(calculator_screen.cget("text")) 51 | elif text=="=": calculator_screen.equate() 52 | else: calculator_screen.appendText(str(text)) 53 | 54 | if calculator_screen.winfo_reqwidth() > 325: 55 | calculator_screen["font"] = ("Arial", int(calculator_screen.cget("font")[-2:]) - 3) 56 | 57 | class CalculatorScreen(tk.Message): 58 | def __init__(self, root): 59 | super().__init__(master=root,text=0,background=root.cget("background"),foreground="white",width=325,font=("arial",40),anchor="e",pady=0,padx=34) 60 | 61 | def appendText(self,text): 62 | operators = ("/","x","-","+","=") 63 | eqn = self.cget("text") 64 | if eqn == "0": self["text"] = text 65 | elif text in operators and eqn[-1:] in operators : self["text"] = f"{eqn[:-1]}{text}" 66 | else: self["text"] += text 67 | 68 | def equate(self): 69 | try: 70 | ans = eval(self.cget("text").replace("x","*").replace("%","*(1/100)")) 71 | self["text"] = ans 72 | self["font"] = ("Arial", 40) 73 | except: 74 | pass 75 | 76 | root = tk.Tk() 77 | root.title("Calculator") 78 | root.geometry("325x550") 79 | root.resizable(False, False) 80 | root.configure(background = "#202020") 81 | 82 | keypad = KeyPad(root) 83 | keypad.pack(fill="both",side="bottom",pady=(15,0)) 84 | 85 | calculator_screen = CalculatorScreen(root) 86 | calculator_screen.pack(fill="x",side="bottom") 87 | 88 | root.mainloop() -------------------------------------------------------------------------------- /LP-1/HCI/ticTacToe.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | 3 | # Define a class for the Tic Tac Toe game 4 | class TicTacToe: 5 | def __init__(self, master): 6 | # Initialize the game window 7 | self.master = master 8 | self.master.title("Tic Tac Toe") 9 | 10 | # Keep track of the current player (either "X" or "O") 11 | self.current_player = "X" 12 | 13 | # Initialize the game board as an empty 3x3 array 14 | self.board = [ 15 | ["", "", ""], 16 | ["", "", ""], 17 | ["", "", ""] 18 | ] 19 | 20 | # Create the buttons for the game board 21 | self.buttons = [] 22 | for row in range(3): 23 | button_row = [] 24 | for col in range(3): 25 | # Each button has a command that calls the handle_click method 26 | button = tk.Button( 27 | self.master, 28 | text="", 29 | font=("Helvetica", 30), 30 | width=3, 31 | height=1, 32 | command=lambda row=row, col=col: self.handle_click(row, col) 33 | ) 34 | # Position the button in the game grid 35 | button.grid(row=row, column=col, sticky="nsew") 36 | button_row.append(button) 37 | self.buttons.append(button_row) 38 | 39 | def handle_click(self, row, col): 40 | # Check if the clicked cell is empty 41 | if self.board[row][col] == "": 42 | # Update the board and the button text with the current player's symbol 43 | self.board[row][col] = self.current_player 44 | self.buttons[row][col].config(text=self.current_player) 45 | # Check if the current player has won or the game is tied 46 | if self.check_win() or self.check_tie(): 47 | # If so, call the game_over method 48 | self.game_over() 49 | else: 50 | # If not, switch to the other player's turn 51 | self.switch_player() 52 | 53 | def switch_player(self): 54 | # Alternate between "X" and "O" after each move 55 | if self.current_player == "X": 56 | self.current_player = "O" 57 | else: 58 | self.current_player = "X" 59 | 60 | def check_win(self): 61 | # Check if any row has three of the same symbol in a row 62 | for i in range(3): 63 | if self.board[i][0] == self.board[i][1] == self.board[i][2] != "": 64 | return True 65 | # Check if any column has three of the same symbol in a row 66 | if self.board[0][i] == self.board[1][i] == self.board[2][i] != "": 67 | return True 68 | # Check if the diagonal from top-left to bottom-right has three of the same symbol 69 | if self.board[0][0] == self.board[1][1] == self.board[2][2] != "": 70 | return True 71 | # Check if the diagonal from top-right to bottom-left has three of the same symbol 72 | if self.board[2][0] == self.board[1][1] == self.board[0][2] != "": 73 | return True 74 | # If no winning combination is found, return False 75 | return False 76 | 77 | def check_tie(self): 78 | # Check if all cells are filled 79 | for i in range(3): 80 | for j in range(3): 81 | if self.board[i][j] == "": 82 | return False 83 | # If all cells are filled and no one has won, the game is tied 84 | return True 85 | 86 | def game_over(self): 87 | # Disable all buttons and display a message announcing the winner 88 | for row in self.buttons: 89 | for button in row: 90 | button.config(state="disabled") 91 | if self.check_win(): 92 | winner = self.current_player 93 | message = f"Player {winner} wins!" 94 | else: 95 | message = "It's a tie!" 96 | # Create a label to display the game-over message 97 | msg_label = tk.Label(self.master, text=message, font=("Helvetica", 20)) 98 | msg_label.grid(row=3, column=0, columnspan=3) 99 | 100 | # Create the main window and start the game 101 | root = tk.Tk() 102 | game = TicTacToe(root) 103 | root.mainloop() -------------------------------------------------------------------------------- /CNS/CNS3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int i,j,k,l; 7 | int Frame_Size; 8 | cout<<"Enter the frame size : "; 9 | cin>>Frame_Size; 10 | 11 | int Frame[20]; 12 | cout<<"\nEnter the Frame : "; 13 | for(i=0;i>Frame[i]; 16 | } 17 | 18 | int Generator_Size; 19 | cout<<"Enter the generator size : "; 20 | cin>>Generator_Size; 21 | 22 | int Generator[20]; 23 | cout<<"Enter the Generator : "; 24 | for(i=0;i>Generator[i]; 27 | } 28 | 29 | cout<<"\n**************Sender's Side*************"; 30 | cout<<"\nFrame : "; 31 | for(i=0;i= Generator[j]) 66 | { 67 | for(j=0,k=i;j= Generator[j]) 127 | { 128 | for(j=0,k=i;j buffer = new LinkedList<>(); 7 | int capacity = 5; 8 | final Object mutex = new Object(); 9 | 10 | public void produce() throws InterruptedException { 11 | int value = 0; 12 | while (true) { 13 | synchronized (mutex) { 14 | while (buffer.size() == capacity) { 15 | mutex.wait(); // Wait if buffer is full 16 | } 17 | buffer.add(value); 18 | System.out.println("Producer produced: " + value); 19 | value++; 20 | mutex.notify(); // Notify consumer 21 | } 22 | Thread.sleep(1000); 23 | } 24 | } 25 | 26 | public void consume() throws InterruptedException { 27 | while (true) { 28 | synchronized (mutex) { 29 | while (buffer.isEmpty()) { 30 | mutex.wait(); // Wait if buffer is empty 31 | } 32 | int val = buffer.removeFirst(); 33 | System.out.println("Consumer consumed: " + val); 34 | mutex.notify(); // Notify producer 35 | } 36 | Thread.sleep(1000); 37 | } 38 | } 39 | } 40 | 41 | 42 | class ProducerConsumerWithSemaphore { 43 | LinkedList buffer = new LinkedList<>(); 44 | int capacity = 5; 45 | Semaphore empty = new Semaphore(5); // Semaphore for empty slots 46 | Semaphore full = new Semaphore(0); // Semaphore for full slots 47 | Semaphore mutex = new Semaphore(1); // Semaphore for mutual exclusion 48 | 49 | public void produce() throws InterruptedException { 50 | int value = 0; 51 | while (true) { 52 | empty.acquire(); // Wait for an empty slot 53 | mutex.acquire(); // Lock the buffer 54 | buffer.add(value); 55 | System.out.println("Producer produced: " + value); 56 | value++; 57 | mutex.release(); // Unlock the buffer 58 | full.release(); // Signal that buffer is not empty 59 | Thread.sleep(1000); 60 | } 61 | } 62 | 63 | public void consume() throws InterruptedException { 64 | while (true) { 65 | full.acquire(); // Wait for a full slot 66 | mutex.acquire(); // Lock the buffer 67 | int val = buffer.removeFirst(); 68 | System.out.println("Consumer consumed: " + val); 69 | mutex.release(); // Unlock the buffer 70 | empty.release(); // Signal that buffer is not full 71 | Thread.sleep(1000); 72 | } 73 | } 74 | } 75 | 76 | public class SynchronizationComparison { 77 | 78 | public static void main(String[] args) throws InterruptedException { 79 | // Test for Mutex 80 | ProducerConsumerWithMutex pcMutex = new ProducerConsumerWithMutex(); 81 | Thread producerMutex = new Thread(() -> { 82 | try { 83 | pcMutex.produce(); 84 | } catch (InterruptedException e) { 85 | Thread.currentThread().interrupt(); 86 | } 87 | }); 88 | 89 | Thread consumerMutex = new Thread(() -> { 90 | try { 91 | pcMutex.consume(); 92 | } catch (InterruptedException e) { 93 | Thread.currentThread().interrupt(); 94 | } 95 | }); 96 | 97 | // Test for Semaphore 98 | ProducerConsumerWithSemaphore pcSemaphore = new ProducerConsumerWithSemaphore(); 99 | Thread producerSemaphore = new Thread(() -> { 100 | try { 101 | pcSemaphore.produce(); 102 | } catch (InterruptedException e) { 103 | Thread.currentThread().interrupt(); 104 | } 105 | }); 106 | 107 | Thread consumerSemaphore = new Thread(() -> { 108 | try { 109 | pcSemaphore.consume(); 110 | } catch (InterruptedException e) { 111 | Thread.currentThread().interrupt(); 112 | } 113 | }); 114 | 115 | System.out.println("Running Producer-Consumer with Mutex..."); 116 | producerMutex.start(); 117 | consumerMutex.start(); 118 | Thread.sleep(10000); 119 | 120 | System.out.println("Running Producer-Consumer with Semaphore..."); 121 | producerSemaphore.start(); 122 | consumerSemaphore.start(); 123 | Thread.sleep(10000); 124 | } 125 | } -------------------------------------------------------------------------------- /CNS/Subnet.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.net.InetAddress; 3 | 4 | class Subnet 5 | { 6 | public static void main(String args[]) 7 | { 8 | Scanner sc= new Scanner(System.in); 9 | System.out.print("Enter IP Address : "); 10 | String IP=sc.nextLine(); 11 | 12 | String Split_IP[] = IP.split("\\."); 13 | 14 | String Split_Binary_IP[]= new String[4]; 15 | String Binary_IP = ""; 16 | for(int i=0;i<4;i++) 17 | { 18 | Split_Binary_IP[i]=appendZeroes(Integer.toBinaryString(Integer.parseInt(Split_IP[i]))); 19 | Binary_IP+=Split_Binary_IP[i]; 20 | } 21 | System.out.println("The Binary Ip Address : "+Binary_IP); 22 | 23 | System.out.print("Enter Number of Address : "); 24 | int No_Bits=sc.nextInt(); 25 | int Bits=(int)Math.ceil(Math.log(No_Bits)/Math.log(2)); 26 | System.out.println("The Number of Bits Required : "+Bits); 27 | int Mask=32-Bits; 28 | int Total_Address=(int)Math.pow(2,Bits); 29 | System.out.println("Subnet Mask : "+Mask); 30 | 31 | int First_Binary_IP[]=new int[32]; 32 | for(int i=0;i<32;i++) 33 | { 34 | 35 | First_Binary_IP[i]=(int)Binary_IP.charAt(i)-48; 36 | } 37 | for(int i=31;i>31-Bits;i--) 38 | { 39 | 40 | First_Binary_IP[i] &=0; 41 | } 42 | String First_IP[]={"","","",""}; 43 | for(int i=0;i<32;i++) 44 | { 45 | First_IP[i/8]=new String(First_IP[i/8]+First_Binary_IP[i]); 46 | } 47 | int First_Offset=0; 48 | int IP_Address[]=new int[4]; ; 49 | System.out.print("GROUP-1 \n The First Address : "); 50 | for(int i=0;i<4;i++) 51 | { 52 | System.out.print(IP_Address[i]=First_Offset=Integer.parseInt(First_IP[i],2)); 53 | if(i!=3) 54 | System.out.print("."); 55 | } 56 | System.out.println(); 57 | 58 | int Last_Binary_IP[]=new int [32]; 59 | for(int i=0;i<32;i++) 60 | { 61 | 62 | Last_Binary_IP[i]=(int)Binary_IP.charAt(i)-48; 63 | } 64 | for(int i=31;i>31-Bits;i--) 65 | { 66 | 67 | Last_Binary_IP[i]|= 1; 68 | } 69 | String Last_IP[]={"","","",""}; 70 | for(int i=0;i<32;i++) 71 | { 72 | Last_IP[i/8]=new String(Last_IP[i/8]+Last_Binary_IP[i]); 73 | } 74 | int IP_Last[]=new int[4]; 75 | System.out.print("The Last Address : "); 76 | for(int i=0;i<4;i++) 77 | { 78 | System.out.print(IP_Last[i]=Integer.parseInt(Last_IP[i],2)); 79 | if(i!=3) 80 | System.out.print("."); 81 | } 82 | System.out.println(); 83 | System.out.print("How many Subnets you need to form : "); 84 | int Scount=sc.nextInt(); 85 | for(int j=1;j= size) return j; // Return the first available block index 83 | return -1; // Return -1 if no suitable block found 84 | } 85 | 86 | // Best Fit: Find the smallest block that can fit the process 87 | private static int findBlockBestFit(int[] blocks, boolean[] flag, int size) { 88 | int idx = -1; 89 | for (int j = 0; j < blocks.length; j++) 90 | if (!flag[j] && blocks[j] >= size && (idx == -1 || blocks[j] < blocks[idx])) idx = j; // Choose the smallest available block 91 | return idx; 92 | } 93 | 94 | // Worst Fit: Find the largest block that can fit the process 95 | private static int findBlockWorstFit(int[] blocks, boolean[] flag, int size) { 96 | int idx = -1; 97 | for (int j = 0; j < blocks.length; j++) 98 | if (!flag[j] && blocks[j] >= size && (idx == -1 || blocks[j] > blocks[idx])) idx = j; // Choose the largest available block 99 | return idx; 100 | } 101 | 102 | // Next Fit: Allocate memory sequentially, starting from where the last allocation ended 103 | private static void nextFitAllocation(int[] processes, int[] blocks, int[] display) { 104 | int total = Arrays.stream(blocks).sum(), sum = 0, idx = 0; // Initialize sum and start index 105 | boolean[] flag = new boolean[blocks.length]; // To track allocated blocks 106 | 107 | for (int i = 0;i= processes[i]) { 112 | sum += processes[i]; // Add process memory to sum 113 | blocks[blockIdx] -= processes[i]; // Reduce block size 114 | display[blockIdx] = i; // Store allocated process 115 | flag[blockIdx] = true; // Mark block as allocated 116 | idx = (blockIdx + 1) % blocks.length; // Update the last allocated block index 117 | allocated = true; 118 | break; 119 | } 120 | } 121 | if (!allocated) { 122 | System.out.println("No suitable block found for process with size: " + processes[i]); 123 | } 124 | } 125 | printAllocation(display, blocks, sum, total); // Print allocation and efficiency 126 | } 127 | 128 | // Print the final allocation and calculate the efficiency 129 | private static void printAllocation(int[] display, int[] blocks, int sum, int total) { 130 | System.out.println("\nProcess Allocation in Blocks:"); 131 | for (int i = 0; i < display.length; i++) { 132 | System.out.println("B" + (i + 1) + "\t" + (display[i] == -1 ? "0" : "P" + (display[i] + 1))); // Print allocated processes 133 | } 134 | System.out.println("\nEfficiency: " + (sum * 100.0) / total + "%"); // Print efficiency as a percentage 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /LP-1/SPOS/MacroPass/Main.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | 3 | Design Suitable data structure and implements Pass-I and Pass-II of a two pass macro processor. The output of Pass-I 4 | (MNT,MDT and Intermediate code file without any macro definitions) should be input for Pass-II. 5 | 6 | *******************************************************************************/ 7 | import java.io.*; 8 | 9 | class MDT { 10 | String value; //Store Macro Definition 11 | 12 | MDT(String value) { 13 | this.value = value; 14 | } 15 | } 16 | 17 | class MNT { 18 | String macName; //To Store The Macro Name 19 | int mdtc; //Macro Definition Table Counter 20 | 21 | MNT(String macName, int mdtc) { 22 | this.macName = macName; 23 | this.mdtc = mdtc; 24 | } 25 | } 26 | 27 | class ArgList { //Keeps track of arguments passed to Macro 28 | String formalParam; 29 | 30 | ArgList(String formalParam) { 31 | this.formalParam = formalParam; 32 | } 33 | } 34 | 35 | public class Main { 36 | public static void main(String[] args) { 37 | BufferedReader br1 = null; 38 | BufferedWriter bw1 = null; 39 | try { 40 | br1 = new BufferedReader(new FileReader("input.txt")); 41 | bw1 = new BufferedWriter(new FileWriter("Output1.txt")); 42 | 43 | // Define fixed sizes for arrays 44 | int maxSize = 100; // Assuming a maximum of 100 entries for simplicity 45 | 46 | //Initialisation of arrays 47 | MDT[] mdtArray = new MDT[maxSize]; 48 | MNT[] mntArray = new MNT[maxSize]; 49 | ArgList[] argArray = new ArgList[maxSize]; 50 | 51 | String line; 52 | boolean macroStart = false, macroEnd = false, fillArgList = false; 53 | int mdtCnt = 0, mntCnt = 0, argListCnt = 0; //Points to the next location where values should be stored 54 | 55 | while ((line = br1.readLine()) != null) { 56 | line = line.replaceAll(",", " "); 57 | String[] tokens = line.split("\\s+"); 58 | MDT currentMDT = new MDT(""); 59 | 60 | for (int i = 0; i < tokens.length; i++) { 61 | if (tokens[i].equalsIgnoreCase("MEND")) { 62 | currentMDT.value += "\t" + tokens[i]; 63 | mdtArray[mdtCnt] = currentMDT; 64 | macroEnd = true; 65 | mdtCnt++; 66 | } 67 | else if (tokens[i].equalsIgnoreCase("MACRO")) { 68 | macroStart = true; 69 | macroEnd = false; 70 | } 71 | else if (!macroEnd) { 72 | if (macroStart) { //True if it's start of macro 73 | mntArray[mntCnt] = new MNT(tokens[i], mdtCnt); //Passing macro name and index as arguments 74 | mntCnt++; 75 | macroStart = false; 76 | fillArgList = true; 77 | } 78 | else if (fillArgList) { 79 | while (i < tokens.length) { 80 | currentMDT.value += "\t" + tokens[i]; 81 | if (tokens[i].matches("&[a-zA-Z]+") || tokens[i].matches("&[a-zA-Z]+[0-9]+")) { 82 | argArray[argListCnt] = new ArgList(tokens[i]); 83 | argListCnt++; 84 | } 85 | i++; 86 | } 87 | fillArgList = false; 88 | } else { 89 | if (tokens[i].equalsIgnoreCase("START") || tokens[i].matches("[0-9]+")) { 90 | continue; 91 | } 92 | 93 | if (tokens[i].matches("[a-zA-Z]+") || tokens[i].matches("[a-zA-Z]+[0-9]+") || tokens[i].matches("[0-9]+")) { 94 | currentMDT.value += "\t" + tokens[i]; 95 | } 96 | if (tokens[i].matches("&[a-zA-Z]+") || tokens[i].matches("&[a-zA-Z]+[0-9]+")) { 97 | for (int j = 0; j < argListCnt; j++) { 98 | if (tokens[i].equals(argArray[j].formalParam)) { 99 | currentMDT.value += "\t&" + (j + 1); 100 | } 101 | } 102 | } 103 | } 104 | } else { 105 | bw1.write(tokens[i] + "\t"+"\n"); 106 | } 107 | } 108 | if (!currentMDT.value.isEmpty() && !macroEnd) { 109 | mdtArray[mdtCnt] = currentMDT; 110 | mdtCnt++; 111 | } 112 | } 113 | 114 | // Close the input file 115 | br1.close(); 116 | 117 | // Output MNT 118 | bw1.close(); 119 | bw1 = new BufferedWriter(new FileWriter("MNT.txt")); 120 | System.out.println("\n\t********MACRO NAME TABLE**********"); 121 | System.out.println("\n\tINDEX\tNAME\tMDTC"); 122 | for (int i = 0; i < mntCnt; i++) { 123 | System.out.println("\t" + i + "\t" + mntArray[i].macName + "\t" + mntArray[i].mdtc); 124 | bw1.write("\t" + i + "\t" + mntArray[i].macName + "\t" + mntArray[i].mdtc + "\n"); 125 | } 126 | bw1.close(); 127 | 128 | // Output ARGUMENT LIST 129 | bw1 = new BufferedWriter(new FileWriter("ARG.txt")); 130 | System.out.println("\n\n\t********ARGUMENT LIST**********"); 131 | System.out.println("\n\tINDEX\tNAME"); 132 | for (int i = 0; i < argListCnt; i++) { 133 | System.out.println("\t" + i + "\t" + argArray[i].formalParam); 134 | bw1.write("\t" + i + "\t" + argArray[i].formalParam + "\n"); 135 | } 136 | bw1.close(); 137 | 138 | // Output MDT 139 | bw1 = new BufferedWriter(new FileWriter("MDT.txt")); 140 | System.out.println("\n\t********MACRO DEFINITION TABLE**********"); 141 | System.out.println("\n\tINDEX\t\tSTATEMENT"); 142 | for (int i = 0; i < mdtCnt; i++) { 143 | System.out.println("\t" + i + "\t" + mdtArray[i].value); 144 | bw1.write("\t" + i + "\t" +mdtArray[i].value + "\n"); 145 | } 146 | bw1.close(); 147 | 148 | } catch (IOException e) { 149 | e.printStackTrace(); 150 | } finally { 151 | try { 152 | if (br1 != null) br1.close(); 153 | if (bw1 != null) bw1.close(); 154 | } catch (IOException e) { 155 | e.printStackTrace(); 156 | } 157 | } 158 | } 159 | } -------------------------------------------------------------------------------- /LP-1/SPOS/Scheduling/Scheduling.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Process { 4 | int id, arrivalTime, burstTime, remainingTime, priority, waitingTime, turnaroundTime, completionTime; 5 | 6 | public Process(int id, int arrivalTime, int burstTime, int priority) { 7 | this.id = id; 8 | this.arrivalTime = arrivalTime; 9 | this.burstTime = burstTime; 10 | this.remainingTime = burstTime; 11 | this.priority = priority; 12 | } 13 | } 14 | 15 | public class Scheduling { 16 | 17 | public static void main(String[] args) { 18 | Scanner sc = new Scanner(System.in); 19 | 20 | // Input the number of processes 21 | System.out.print("Enter number of processes: "); 22 | int n = sc.nextInt(); 23 | 24 | Process[] processes = new Process[n]; 25 | for (int i = 0; i < n; i++) { 26 | System.out.println("Enter arrival time, burst time and priority (for Priority Scheduling) for Process " + (i + 1) + ": "); 27 | int arrivalTime = sc.nextInt(); 28 | int burstTime = sc.nextInt(); 29 | int priority = sc.nextInt(); 30 | processes[i] = new Process(i + 1, arrivalTime, burstTime, priority); 31 | } 32 | 33 | // Menu for scheduling algorithms 34 | System.out.println("Choose a CPU Scheduling Algorithm:"); 35 | System.out.println("1. FCFS\n2. SJF (Preemptive)\n3. Priority (Non-preemptive)\n4. Round Robin (Preemptive)"); 36 | System.out.print("Enter your choice: "); 37 | int choice = sc.nextInt(); 38 | 39 | switch (choice) { 40 | case 1: 41 | FCFS(processes); 42 | break; 43 | case 2: 44 | SJFPreemptive(processes); 45 | break; 46 | case 3: 47 | PriorityNonPreemptive(processes); 48 | break; 49 | case 4: 50 | System.out.print("Enter time quantum for Round Robin: "); 51 | int quantum = sc.nextInt(); 52 | RoundRobin(processes, quantum); 53 | break; 54 | default: 55 | System.out.println("Invalid choice."); 56 | break; 57 | } 58 | 59 | sc.close(); 60 | } 61 | 62 | // First Come First Serve (FCFS) 63 | public static void FCFS(Process[] processes) { 64 | int currentTime = 0; 65 | Arrays.sort(processes, Comparator.comparingInt(p -> p.arrivalTime)); 66 | for (Process p : processes) { 67 | if (currentTime < p.arrivalTime) { 68 | currentTime = p.arrivalTime; 69 | } 70 | p.waitingTime = currentTime - p.arrivalTime; 71 | currentTime += p.burstTime; 72 | p.turnaroundTime = p.waitingTime + p.burstTime; 73 | p.completionTime = currentTime; 74 | } 75 | printResults(processes, "FCFS"); 76 | } 77 | 78 | // Shortest Job First (Preemptive) 79 | public static void SJFPreemptive(Process[] processes) { 80 | int currentTime = 0, completed = 0; 81 | Process current = null; 82 | Arrays.sort(processes, Comparator.comparingInt(p -> p.arrivalTime)); 83 | PriorityQueue pq = new PriorityQueue<>(Comparator.comparingInt(p -> p.remainingTime)); 84 | 85 | while (completed < processes.length) { 86 | for (Process p : processes) { 87 | if (p.arrivalTime <= currentTime && p.remainingTime > 0) { 88 | pq.add(p); 89 | } 90 | } 91 | 92 | if (!pq.isEmpty()) { 93 | current = pq.poll(); 94 | current.remainingTime--; 95 | currentTime++; 96 | 97 | if (current.remainingTime == 0) { 98 | completed++; 99 | current.completionTime = currentTime; 100 | current.turnaroundTime = current.completionTime - current.arrivalTime; 101 | current.waitingTime = current.turnaroundTime - current.burstTime; 102 | } 103 | } else { 104 | currentTime++; 105 | } 106 | } 107 | 108 | printResults(processes, "SJF (Preemptive)"); 109 | } 110 | 111 | // Priority Scheduling (Non-preemptive) 112 | public static void PriorityNonPreemptive(Process[] processes) { 113 | int currentTime = 0, completed = 0; 114 | Process current = null; 115 | Arrays.sort(processes, Comparator.comparingInt(p -> p.arrivalTime)); 116 | PriorityQueue pq = new PriorityQueue<>(Comparator.comparingInt(p -> p.priority)); 117 | 118 | while (completed < processes.length) { 119 | for (Process p : processes) { 120 | if (p.arrivalTime <= currentTime && p.remainingTime > 0) { 121 | pq.add(p); 122 | } 123 | } 124 | 125 | if (!pq.isEmpty()) { 126 | current = pq.poll(); 127 | current.waitingTime = currentTime - current.arrivalTime; 128 | currentTime += current.burstTime; 129 | current.turnaroundTime = current.waitingTime + current.burstTime; 130 | current.completionTime = currentTime; 131 | current.remainingTime = 0; 132 | completed++; 133 | } else { 134 | currentTime++; 135 | } 136 | } 137 | 138 | printResults(processes, "Priority (Non-preemptive)"); 139 | } 140 | 141 | // Round Robin (Preemptive) 142 | public static void RoundRobin(Process[] processes, int quantum) { 143 | int currentTime = 0, completed = 0; 144 | Queue queue = new LinkedList<>(); 145 | Arrays.sort(processes, Comparator.comparingInt(p -> p.arrivalTime)); 146 | 147 | int i = 0; 148 | while (completed < processes.length) { 149 | while (i < processes.length && processes[i].arrivalTime <= currentTime) { 150 | queue.add(processes[i]); 151 | i++; 152 | } 153 | 154 | if (!queue.isEmpty()) { 155 | Process current = queue.poll(); 156 | int execTime = Math.min(current.remainingTime, quantum); 157 | current.remainingTime -= execTime; 158 | currentTime += execTime; 159 | 160 | if (current.remainingTime == 0) { 161 | completed++; 162 | current.completionTime = currentTime; 163 | current.turnaroundTime = current.completionTime - current.arrivalTime; 164 | current.waitingTime = current.turnaroundTime - current.burstTime; 165 | } else { 166 | queue.add(current); 167 | } 168 | } else { 169 | currentTime++; 170 | } 171 | } 172 | 173 | printResults(processes, "Round Robin"); 174 | } 175 | 176 | // Helper method to print the results 177 | public static void printResults(Process[] processes, String algorithm) { 178 | System.out.println("\n" + algorithm + " Scheduling Results:"); 179 | System.out.println("Process ID\tArrival Time\tBurst Time\tPriority\tCompletion Time\tTurnaround Time\tWaiting Time"); 180 | double totalWaitingTime = 0, totalTurnaroundTime = 0; 181 | for (Process p : processes) { 182 | totalWaitingTime += p.waitingTime; 183 | totalTurnaroundTime += p.turnaroundTime; 184 | System.out.println(p.id + "\t\t" + p.arrivalTime + "\t\t" + p.burstTime + "\t\t" + p.priority + "\t\t" + 185 | p.completionTime + "\t\t" + p.turnaroundTime + "\t\t" + p.waitingTime); 186 | } 187 | System.out.println("Average Waiting Time: " + (totalWaitingTime / processes.length)); 188 | System.out.println("Average Turnaround Time: " + (totalTurnaroundTime / processes.length)); 189 | } 190 | } -------------------------------------------------------------------------------- /LP-1/SPOS/PageReplacement/PageReplacement.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class PageReplacement { 4 | 5 | private static Scanner sc = new Scanner(System.in); 6 | 7 | static abstract class CommonUtils { 8 | protected int[][] result; 9 | protected LinkedList pagesReference; 10 | protected int hits; 11 | protected int faults; 12 | 13 | public CommonUtils(){ 14 | hits = faults = 0; 15 | pagesReference = new LinkedList<>(); 16 | System.out.print("Enter the no.of numbers in the page reference string: "); 17 | int prs = sc.nextInt(); 18 | for(int x = 0; x < prs; x++){ 19 | System.out.print("Enter the number: "); 20 | int n = sc.nextInt(); 21 | pagesReference.add(n); 22 | } 23 | System.out.print("Enter the no.of frames: "); 24 | int f = sc.nextInt(); 25 | result = new int[f][prs]; 26 | for(int x = 0; x < result.length; x++){ 27 | for(int y= 0; y < result[0].length; y++){ 28 | result[x][y] = -1; 29 | } 30 | } 31 | } 32 | 33 | public abstract void performAlgorithm(); 34 | 35 | public void showResult(){ 36 | for(int x = 0; x < result.length; x++){ 37 | for(int y = 0; y < result[0].length; y++){ 38 | System.out.print(result[x][y] + " "); 39 | } 40 | System.out.println(); 41 | } 42 | System.out.println("No.of hits: " + hits); 43 | System.out.println("No.of faults: " + faults); 44 | } 45 | } 46 | 47 | static class FIFO extends CommonUtils { 48 | private Queue numQueue; 49 | 50 | public FIFO(){ 51 | numQueue = new LinkedList<>(); 52 | } 53 | 54 | public void performAlgorithm(){ 55 | int j = 0; 56 | while(!pagesReference.isEmpty()){ 57 | int num = pagesReference.removeFirst(); 58 | boolean isFault = true; 59 | boolean isInserted = false; 60 | for(int x = 0; x < result.length; x++){ 61 | if(result[x][j] == -1){ 62 | isFault = true; 63 | faults++; 64 | result[x][j] = num; 65 | isInserted = true; 66 | break; 67 | } 68 | else if(result[x][j] == num){ 69 | isFault = false; 70 | hits++; 71 | break; 72 | } 73 | } 74 | if(isFault && isInserted){ 75 | numQueue.add(num); 76 | } 77 | else if(isFault){ 78 | faults++; 79 | numQueue.add(num); 80 | int n = numQueue.remove(); 81 | for(int x = 0; x < result.length; x++){ 82 | if(result[x][j] == n){ 83 | result[x][j] = num; 84 | break; 85 | } 86 | } 87 | } 88 | j++; 89 | if(j < result[0].length) { 90 | for (int x = 0; x < result.length; x++) { 91 | result[x][j] = result[x][j-1]; 92 | } 93 | } 94 | } 95 | } 96 | } 97 | 98 | static class LRU extends CommonUtils { 99 | private Deque pageSequenceRecord; 100 | 101 | public LRU(){ 102 | pageSequenceRecord = new LinkedList<>(); 103 | } 104 | 105 | 106 | @Override 107 | public void performAlgorithm() { 108 | int j = 0; 109 | while(!pagesReference.isEmpty()){ 110 | int num = pagesReference.remove(); 111 | boolean isFault = true; 112 | boolean isInserted = false; 113 | for(int x = 0; x < result.length; x++){ 114 | if(result[x][j] == -1){ 115 | isFault = true; 116 | faults++; 117 | result[x][j] = num; 118 | isInserted = true; 119 | break; 120 | } 121 | else if(result[x][j] == num){ 122 | isFault = false; 123 | hits++; 124 | break; 125 | } 126 | } 127 | if(isFault && isInserted){ 128 | pageSequenceRecord.addLast(num); 129 | } 130 | else if(!isFault){ 131 | pageSequenceRecord.remove(num); 132 | pageSequenceRecord.addLast(num); 133 | } 134 | else { // isFault and !isInserted. 135 | int n = pageSequenceRecord.removeFirst(); 136 | for(int x = 0; x < result.length; x++){ 137 | if(result[x][j] == n){ 138 | result[x][j] = num; 139 | break; 140 | } 141 | } 142 | pageSequenceRecord.addLast(num); 143 | faults++; 144 | } 145 | j++; 146 | if(j < result[0].length) { 147 | for (int x = 0; x < result.length; x++) { 148 | result[x][j] = result[x][j-1]; 149 | } 150 | } 151 | } 152 | } 153 | } 154 | 155 | static class OPT extends CommonUtils { 156 | 157 | @Override 158 | public void performAlgorithm() { 159 | int j = 0; 160 | while(!pagesReference.isEmpty()) { 161 | int num = pagesReference.remove(); 162 | boolean isFault = true; 163 | boolean isInserted = false; 164 | for (int x = 0; x < result.length; x++) { 165 | if (result[x][j] == -1) { 166 | isFault = true; 167 | faults++; 168 | result[x][j] = num; 169 | isInserted = true; 170 | break; 171 | } else if (result[x][j] == num) { 172 | isFault = false; 173 | hits++; 174 | break; 175 | } 176 | } 177 | if (isFault && !isInserted) { 178 | int maxPageRefEleIdx = -1; 179 | int resultEleIdx = -1; 180 | for (int x = 0; x < result.length; x++) { 181 | int ele = result[x][j]; 182 | if(!pagesReference.contains(ele)){ 183 | result[x][j] = num; 184 | break; 185 | } 186 | else{ 187 | int i = pagesReference.indexOf(ele); 188 | if(maxPageRefEleIdx <= i){ 189 | maxPageRefEleIdx = i; 190 | resultEleIdx = x; 191 | } 192 | } 193 | } 194 | if(resultEleIdx != -1){ 195 | result[resultEleIdx][j] = num; 196 | } 197 | faults++; 198 | } 199 | j++; 200 | if (j < result[0].length) { 201 | for (int x = 0; x < result.length; x++) { 202 | result[x][j] = result[x][j - 1]; 203 | } 204 | } 205 | } 206 | } 207 | } 208 | 209 | public static void main(String[] args){ 210 | 211 | System.out.println("*********************************** FIFO *******************************************"); 212 | FIFO f = new FIFO(); 213 | f.performAlgorithm(); 214 | f.showResult(); 215 | 216 | System.out.println("*********************************** LRU *******************************************"); 217 | LRU l = new LRU(); 218 | l.performAlgorithm(); 219 | l.showResult(); 220 | 221 | System.out.println("*********************************** OPT *******************************************"); 222 | OPT o = new OPT(); 223 | o.performAlgorithm(); 224 | o.showResult(); 225 | 226 | } 227 | 228 | } -------------------------------------------------------------------------------- /LP-1/SPOS/Assembler/AssemblerPass1/Assembler_Pass1.java: -------------------------------------------------------------------------------- 1 | package Assembler.AssemblerPass1; 2 | import java.io.*; //Import classes regarding file operations 3 | import java.util.ArrayList; 4 | 5 | //Define Data Structure for Symbol Table & Literal Table. 6 | class Tables{ 7 | String name; 8 | int address; 9 | Tables(String name, int address){ 10 | this.name = name; 11 | this.address = address; 12 | } 13 | } 14 | 15 | //[OPTIONAL] Define Data Structure for Pooltable 16 | class Pooltable{ 17 | int first, total_literals; 18 | Pooltable(int f, int tl){ 19 | first = f; 20 | total_literals = tl; 21 | } 22 | } 23 | 24 | public class Assembler_Pass1 { 25 | //Define a function to search keywords from Symbol table and literal table 26 | public static int search(String token, String[] list) { 27 | for(int i=0;i list) { 33 | for(int i=0;i already_processed = new ArrayList<>(); 57 | String line; 58 | 59 | try{ 60 | BufferedReader br = new BufferedReader(new FileReader("src\\Assembler\\AssemblerPass1\\sample.txt")); 61 | BufferedWriter bw = new BufferedWriter(new FileWriter("src\\Assembler\\AssemblerPass1\\OutputTextTry.txt")); 62 | Boolean start = false, end = false, ltorg = false, fill_addr = false,flag=false; 63 | int total_symb=0,total_ltr=0,optab_cnt=0,pooltab_cnt=0,loc=0,temp,pos,d; 64 | 65 | //Start reading ALP source code 66 | while((line=br.readLine())!=null && !end) { 67 | line=line.replaceAll(",", " "); 68 | System.out.println(line); 69 | //Spilt words in each line of source program. 70 | String[] words = line.split(" "); 71 | ltorg = fill_addr = false; 72 | //STEP 3 - Location Counter Processing. 73 | if (loc != 0 && !ltorg) { 74 | //STEP 3.1 - As no locations are processed for Assembler Directives,we just print that LC block as blank. 75 | if(line.contains("START") || line.contains("END") ||line.contains("ORIGIN") ||line.contains("EQU") || line.contains("LTORG")){ 76 | bw.write("\n "); 77 | } 78 | //STEP 3.2 - For Declarative statement processing of LC depends upon memory word allocated so we process it while Symbol Processing 79 | else if (line.contains("DS") || line.contains("DC")) { 80 | flag = true; 81 | bw.write("\n" + String.valueOf(loc)); 82 | } 83 | //STEP 3.3 - For Imperative Statements simply increment LC by 1; 84 | else bw.write("\n" + String.valueOf(loc++)); 85 | } 86 | 87 | //Now we will process extracted word from line 88 | for (int i = 0; i < words.length; i++) { 89 | pos = -1; 90 | if (start == true) { 91 | loc = Integer.parseInt(words[i]); 92 | start = false; 93 | } 94 | //STEP 4 - Assembler Directives Processing. 95 | switch (words[i]) { 96 | //STEP 4.1 - For Start just print Intermediate Code and update the start flag. 97 | case "START": 98 | start = true; 99 | pos = 1; 100 | bw.write("\t(AD," + pos + ")"); 101 | break; 102 | //STEP 4.2 - For End just print Intermediate Code and update the end flag. 103 | case "END": 104 | end = true; 105 | pos = 2; 106 | bw.write("\t(AD," + pos + ")"); 107 | //We need to process all literals 108 | for (temp = 0; temp < total_ltr; temp++) 109 | if (literal_table[temp].address == 0) { 110 | literal_table[temp].address = loc; //Assign the ongoing line address to literals 111 | bw.write("\n\t(DL,2)\t(C," + literal_table[temp].name.charAt(2) + ")"); //Print the Intermediate Code for literals 112 | loc++; 113 | } 114 | //PoolTable Processing [OPTIONAL] 115 | if (pooltab_cnt == 0) 116 | poolTab[pooltab_cnt++] = new Pooltable(0, temp); 117 | else { 118 | poolTab[pooltab_cnt] = new Pooltable(poolTab[pooltab_cnt - 1].first + poolTab[pooltab_cnt - 1].total_literals, total_ltr - poolTab[pooltab_cnt - 1].first - 1); 119 | pooltab_cnt++; 120 | } 121 | break; 122 | //STEP 4.3 - When ORIGIN is encountered, LC is sent to provided symbol's address in operand field. 123 | case "ORIGIN": 124 | pos = 3; 125 | bw.write("\t(AD," + pos + ")"); 126 | //Search for given symbol in the operand field. 127 | pos = search(words[++i], symbol_table, total_symb); 128 | bw.write("\t(S," + (pos + 1) + ")"); 129 | //Update LC to given symbol's Address. 130 | loc = symbol_table[pos].address; 131 | break; 132 | //STEP 4.4 - When EQU is encountered, LC is set to address of symbol given in the operand field. 133 | case "EQU": 134 | pos = 4; 135 | bw.write("\t(AD," + pos + ")"); 136 | String prev_word = words[i-1]; //Store new symbol (this symbol is in the label field) 137 | int pos1 = search(prev_word, symbol_table, total_symb); 138 | //Get address of symbol provided in the operand field 139 | pos = search(words[++i], symbol_table, total_symb); 140 | //Set address of new symbol as same as address of Operand Symbol 141 | symbol_table[pos1].address = symbol_table[pos].address; 142 | bw.write("\t(S," + (pos + 1) + ")"); 143 | break; 144 | //STEP 4.5 - (IMP) Literals Processing. 145 | case "LTORG": 146 | ltorg = true; 147 | pos = 5; 148 | //We need to process all literals occured before LTORG statement, so we use total_ltr to maintain count of literals 149 | for (temp = 0; temp < total_ltr; temp++) 150 | if (literal_table[temp].address == 0) { 151 | literal_table[temp].address = loc; //Assign the ongoing line address to literals 152 | bw.write("\t(DL,2)\t(C," + literal_table[temp].name.charAt(2) + ")\n"); //Print the Intermediate Code for literals 153 | loc++; 154 | } 155 | //PoolTable Processing [OPTIONAL] 156 | if (pooltab_cnt == 0) 157 | poolTab[pooltab_cnt++] = new Pooltable(0, temp); 158 | else { 159 | poolTab[pooltab_cnt] = new Pooltable(poolTab[pooltab_cnt - 1].first + poolTab[pooltab_cnt - 1].total_literals, total_ltr - poolTab[pooltab_cnt - 1].first - 1); 160 | pooltab_cnt++; 161 | } 162 | break; 163 | } 164 | //STEP 5 - Processing Imperative Statements. 165 | if (pos == -1) { 166 | //STEP 5.1 - Checke whether given word is an mnemonic by checking OP Table. 167 | pos = search(words[i], impr); 168 | int r = search(words[i],regs); 169 | //STEP 5.2 - If given word found in OP Table then it is an Imperative Statement 170 | if (pos != -1) { 171 | bw.write("\t(IS," + pos + ")");//Print Intermediate Code for Imperative Statement. 172 | op_table[optab_cnt++] = new Tables(words[i], pos); //Upate its entry in MOT 173 | } 174 | //STEP 6 - Declarative Statement Processing. 175 | else { 176 | //Check whether word is DS or DC 177 | pos = search(words[i], decl); 178 | //if word is DS or DC 179 | if (pos != -1) { 180 | bw.write("\t(DL," + (pos + 1) + ")"); 181 | op_table[optab_cnt++] = new Tables(words[i], pos+1); 182 | fill_addr = true; 183 | } 184 | //STEP 7 - (IMP) SYMBOL PROCESSING. 185 | //STEP 7.1 - Check label field of source code by checking i==0 or not and has any symbol. 186 | else if (i==0 && words[i].matches("[a-zA-Z]+") && r==-1) { 187 | //Check whether symbol is already present in Symbol Table 188 | pos = search(words[i], symbol_table, total_symb); 189 | System.out.println("TS" + total_symb); 190 | //If new symbol encountered process it. 191 | if (pos == -1) { 192 | //Assign a temp variable for helping in assigning LC to symbol without disturbing orginal LC. 193 | if(flag==false){ 194 | d = --loc; 195 | ++loc; 196 | flag = false; 197 | } 198 | else d = loc; 199 | //STEP 7.2 - Update Entry in Symbol Table. 200 | symbol_table[total_symb++] = new Tables(words[i], (d)); 201 | //STEP 7.3 - Update LC as per the rules. 202 | if(words[i+1].matches("DS")){ 203 | loc += Integer.parseInt(words[2]); //For DS increment LC by given operand value 204 | } 205 | else if(line.contains("DC")) loc++; //For DC increment LC simply by 1. 206 | pos = search(words[i], already_processed); 207 | if(pos==-1){ 208 | already_processed.add(words[i]); 209 | System.out.println(already_processed); 210 | pos = search(words[i], already_processed); 211 | } 212 | // bw.write("\t(S," + total_symb + ")"); //Write its intermediate code 213 | // pos = total_symb; 214 | } 215 | } 216 | else if(words[i].matches("[a-zA-Z]+") && r==-1){ 217 | System.out.println("Words : " + words[i]); 218 | pos = search(words[i], already_processed); 219 | if(pos==-1){ 220 | already_processed.add(words[i]); 221 | System.out.println(already_processed); 222 | pos = search(words[i], already_processed); 223 | } 224 | 225 | bw.write("\t(S," + (pos+1) + ")"); //Write its intermediate code 226 | pos = total_symb; 227 | } 228 | } 229 | } 230 | //STEP 8 - Registers, Constants and Literal's IC Printing 231 | if (pos == -1) { 232 | pos = search(words[i], regs); 233 | if(pos!=-1) 234 | bw.write("\t("+(pos+1)+")"); 235 | else{ 236 | if(words[i].matches("='\\d+'")){ 237 | literal_table[total_ltr++] = new Tables(words[i],0); 238 | bw.write("\t(L,"+total_ltr+")"); 239 | } 240 | else if(words[i].matches("\\d+") || words[i].matches("\\d+H") || words[i].matches("\\d+h")) 241 | bw.write("\t(C,"+words[i]+")"); 242 | } 243 | } 244 | } 245 | } 246 | br.close(); 247 | bw.close(); 248 | 249 | BufferedWriter sw = new BufferedWriter(new FileWriter("src\\Assembler\\AssemblerPass1\\symTab.txt")); 250 | sw.write("\nSYMBOL\tADDRESS\n"); 251 | for(int i=0;i