/**Display Form using short-code**/ [subscription_form] /**Custom Subscribe Form Style Start**/ #subscribe-form { display: flex; gap: 10px; } #subscribe-form input[type="email"] { width: 100%; height: 40px; padding: 12px; border: 1px solid #ccc; border-radius: 3px; font-size: 16px; flex: 1; } #subscribe-form input:focus,input:hover{ border-color: #3498db; } #subscribe-form button { line-height: 1rem; padding: 10px 20px; border: none; background-color: black; color: white; font-size: 1rem; border-radius: 3px; cursor: pointer; transition: background-color 0.3s; } #subscribe-form button:hover { background-color: #333; } #form-message { margin-top: 10px; font-size: 16px; } #form-message.success { color: green; } #form-message.error { color: red; } @media only screen and (max-width: 600px){ #subscribe-form { flex-wrap: wrap; } #subscribe-form input[type="email"] { width: 100%; } #subscribe-form button { width: 100%; } } /**Custom Subscribe Form Style End**/ /** Form PHP start**/ //**this snippet will going to register user as wordpress subscriber on form submit. /*you can use any snippet plugin or directly add this snippet into your theme function.php file*/ <?php function subscription_form_handler() { $output = ''; // Check if the form is submitted if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['subscribe'])) { if (isset($_POST['email']) && is_email($_POST['email'])) { $email = sanitize_email($_POST['email']); if (email_exists($email)) { $message = 'already_registered'; } else { $username = sanitize_user(explode('@', $email)[0] . '_' . wp_generate_password(4, false)); $password = wp_generate_password(); $user_id = wp_create_user($username, $password, $email); if (is_wp_error($user_id)) { $message = 'subscription_failed'; } else { $user = new WP_User($user_id); $user->set_role('subscriber'); $message = 'subscription_successful'; } } } else { $message = 'invalid_email'; } // Redirect to the same page with the message parameter wp_redirect(add_query_arg('message', $message, get_permalink())); exit; } // Always display the form $output .= ' <form id="subscribe-form" method="post"> <input type="email" name="email" placeholder="E-Mail" required> <button type="submit" name="subscribe">Subscribe</button> </form>'; // Display the message if it exists in the URL parameters if (isset($_GET['message'])) { switch ($_GET['message']) { case 'already_registered': $output .= '<div id="form-message" class="error">Already Registered</div>'; break; case 'subscription_failed': $output .= '<div id="form-message" class="error">Subscription failed.</div>'; break; case 'subscription_successful': $output .= '<div id="form-message" class="success">Subscription successful!</div>'; break; case 'invalid_email': $output .= '<div id="form-message" class="error">Invalid email address.</div>'; break; } } return $output; } add_shortcode('subscription_form', 'subscription_form_handler'); function enqueue_custom_script() { ?> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', function() { const url = new URL(window.location); if (url.searchParams.has('message')) { url.searchParams.delete('message'); window.history.replaceState({}, document.title, url.toString()); } }); </script> <?php } add_action('wp_footer', 'enqueue_custom_script'); ?> /**Form Php End **/
var n = prompt("¿Cuántos estudiantes desea ingresar?") for (var nos = 0; nos < n; nos++) { var nom = prompt("Ingrese el nombre del estudiante " + (nos + 1) + ":") var notas = parseInt(prompt("¿Cuántas notas desea ingresar para " + nom + "?")) var suma = 0 for (var cu = 1; cu <= notas; cu++) { var nts = parseInt(prompt("Ingrese la nota " + cu + " del estudiante " + nom + ":")) suma += nts } var promedio = suma / notas document.write("<hr><strong>El promedio del estudiante " + nom + " es " + promedio + "</strong><br><br>") document.write("<strong> y las notas del estudiante "+nom) for (var i = 1; i <= notas; i++) { document.write(i === notas ? nts : nts + ", ") } document.write("<br><br>") }
class GenericStackLinkedList<T> { private Node<T> top; public GenericStackLinkedList() { this.top = null; } public void push(T item) { Node<T> newNode = new Node<>(item); newNode.next = top; top = newNode; } public T pop() { if (top == null) { System.out.println("Stack Underflow"); return null; } T data = top.data; top = top.next; return data; } public boolean isEmpty() { return top == null; } }
class GenericStackArray<T> { private T[] stackArray; private int top; private int maxSize; @SuppressWarnings("unchecked") public GenericStackArray(int size) { this.maxSize = size; this.stackArray = (T[]) new Object[maxSize]; this.top = -1; } public void push(T item) { if (top < maxSize - 1) { stackArray[++top] = item; } else { System.out.println("Stack Overflow"); } } public T pop() { if (top >= 0) { return stackArray[top--]; } else { System.out.println("Stack Underflow"); return null; } } public boolean isEmpty() { return top == -1; } }
SQL*Plus: Release 10.2.0.1.0 - Production on Tue Apr 16 08:39:43 2024 Copyright (c) 1982, 2005, Oracle. All rights reserved. SQL> create table passenger( 2 2 passenger_ID int primary key, 3 3 Ticket_no INTEGER, 4 4 Name varchar(10), 5 5 DOB date, 6 6 sex char(1),address varchar(50)); SP2-0640: Not connected SQL> connect sys as sysdba Enter password: ERROR: ORA-12154: TNS:could not resolve the connect identifier specified SQL> connect sys as sysdba Enter password: ERROR: ORA-12154: TNS:could not resolve the connect identifier specified SQL> connect sys as sysdba Enter password: Connected. SQL> create user Tharun identified by tharun; User created. SQL> grant dba to Tharun; Grant succeeded. SQL> show user; USER is "SYS" SQL> connect Tharun; Enter password: ERROR: ORA-01017: invalid username/password; logon denied Warning: You are no longer connected to ORACLE. SQL> connect Tharun; Enter password: Connected. SQL> spool 'C:\Users\CVR\Desktop\1252' SQL> create table passenger( 2 2 2 passenger_ID int primary key, 3 3 3 Ticket_no INTEGER, 4 4 4 Name varchar(10), 5 5 5 DOB date, 6 6 6 sex char(1),address varchar(50) 7 ; 2 2 passenger_ID int primary key, * ERROR at line 2: ORA-00904: : invalid identifier SQL> create table passenger( 2 ; * ERROR at line 2: ORA-00904: : invalid identifier SQL> create table passenger( 2 2 passenger_ID int primary key, 3 3 Ticket_no INTEGER, 4 4 Name varchar(10), 5 5 DOB date, 6 6 sex char(1),address varchar(50)); 2 passenger_ID int primary key, * ERROR at line 2: ORA-00904: : invalid identifier SQL> create table passenger( 2 passenger_ID int primary key, 3 Name varchar(20), 4 Ticket_No INTEGER, 5 sex char(1), 6 address varchar(50), 7 source varchar(30), 8 destination varchar(30) NOT NULL, 9 DOB DATE, 10 type varchar(3)); Table created. SQL> insert into passenger(passenger_ID,Name,Ticket_No,type,sex,address,source,destination,DOB) 2 values('e001','tulasi','101','ac','m','Telangana hyderabad bn reddy','JBS','Yamjal',DATE '1980-02-21); ERROR: ORA-01756: quoted string not properly terminated SQL> insert into passenger(passenger_ID,Name,Ticket_No,type,sex,address,source,destination,DOB) 2 values('e001','tulasi','101','ac','m','Telangana hyderabad bn reddy','JBS','Yamjal',DATE '1980-02-21'); values('e001','tulasi','101','ac','m','Telangana hyderabad bn reddy','JBS','Yamjal',DATE '1980-02-21') * ERROR at line 2: ORA-01722: invalid number SQL> insert into passenger(passenger_ID,Name,Ticket_No,type,sex,address,source,destination,DOB) 2 values(001,'tulasi',101,'ac','m','Telanganahyderabadbnreddy','JBS','Yamjal',DATE '1980-02-21'); 1 row created. SQL> insert into passenger(passenger_ID,Name,Ticket_No,type,sex,address,source,destination,DOB) 2 values(002,'snigdha',102,'nac','f','Telanganahyderabadbnreddy','MGBS','BN reddy',DATE '1984-11-26'); 1 row created. SQL> insert into passenger(passenger_ID,Name,Ticket_No,type,sex,address,source,destination,DOB) 2 values(003,'sherley',103,'ac','f','Telanganahyderabadbnreddy','MGBS','Kalwakurthy',DATE '1985-01-01'); 1 row created. SQL> insert into passenger(passenger_ID,Name,Ticket_No,type,sex,address,source,destination,DOB) 2 values(004,'jangaiah',104,'nac','m','Telanganahyderabadbnreddy','kalwakurthy','Srisailam',DATE '1986-09-13'); 1 row created. SQL> describe; Usage: DESCRIBE [schema.]object[@db_link] SQL> describe passenger; Name Null? Type ----------------------------------------- -------- ---------------------------- PASSENGER_ID NOT NULL NUMBER(38) NAME VARCHAR2(20) TICKET_NO NUMBER(38) SEX CHAR(1) ADDRESS VARCHAR2(50) SOURCE VARCHAR2(30) DESTINATION NOT NULL VARCHAR2(30) DOB DATE TYPE VARCHAR2(3) SQL> select passenger_ID FROM passenger 2 WHERE unique(;) 3 ; WHERE unique(;) * ERROR at line 2: ORA-00936: missing expression SQL> select * FROM passenger 2 WHERE UNIQUE(passenger_ID); WHERE UNIQUE(passenger_ID) * ERROR at line 2: ORA-00936: missing expression SQL> select * FROM passenger 2 select * FROM passenger; select * FROM passenger * ERROR at line 2: ORA-00933: SQL command not properly ended SQL> select Name FROM passenger 2 WHERE sex == 'm'; WHERE sex == 'm' * ERROR at line 2: ORA-00936: missing expression SQL> select Name FROM passenger 2 WHERE sex = 'm'; NAME -------------------- tulasi jangaiah SQL> select Ticket_No,Name FROM passenger; TICKET_NO NAME ---------- -------------------- 101 tulasi 102 snigdha 103 sherley 104 jangaiah SQL> ALTER table passenger 2 ADD column timetaken(h); ADD column timetaken(h) * ERROR at line 2: ORA-00904: : invalid identifier SQL> ALTER table passenger 2 ADD column timetaken(h) INTEGER; ADD column timetaken(h) INTEGER * ERROR at line 2: ORA-00904: : invalid identifier SQL> ALTER table passenger 2 ADD column timetaken INTEGER; ADD column timetaken INTEGER * ERROR at line 2: ORA-00904: : invalid identifier SQL> ALTER TABLE passenger 2 ADD timetravel INTEGER; Table altered. SQL> insert into passenger(timetravel) 2 values(12); insert into passenger(timetravel) * ERROR at line 1: ORA-01400: cannot insert NULL into ("THARUN"."PASSENGER"."PASSENGER_ID") SQL> insert into passenger(passenger_ID,Name,Ticket_No,type,sex,address,source,destination,DOB,timetravel) 2 values(001,'tulasi',101,'ac','m','Telanganahyderabadbnreddy','JBS','Yamjal',DATE '1980-02-21',12); insert into passenger(passenger_ID,Name,Ticket_No,type,sex,address,source,destination,DOB,timetravel) * ERROR at line 1: ORA-00001: unique constraint (THARUN.SYS_C004028) violated SQL> select source ,destination FROM passenger; SOURCE DESTINATION ------------------------------ ------------------------------ JBS Yamjal MGBS BN reddy MGBS Kalwakurthy kalwakurthy Srisailam SQL> select Name FROM passenger 2 WHERE DOB > 1985-01-01; WHERE DOB > 1985-01-01 * ERROR at line 2: ORA-00932: inconsistent datatypes: expected DATE got NUMBER SQL> select Name FROM passenger 2 ORDER BY ASC; ORDER BY ASC * ERROR at line 2: ORA-00936: missing expression SQL> select Name FROM passenger 2 ORDER BY Name ASC; NAME -------------------- jangaiah sherley snigdha tulasi SQL> select * FROM passenger 2 WHERE type IN('ac','nac'); PASSENGER_ID NAME TICKET_NO S ------------ -------------------- ---------- - ADDRESS -------------------------------------------------- SOURCE DESTINATION DOB TYP ------------------------------ ------------------------------ --------- --- TIMETRAVEL ---------- 1 tulasi 101 m Telanganahyderabadbnreddy JBS Yamjal 21-FEB-80 ac PASSENGER_ID NAME TICKET_NO S ------------ -------------------- ---------- - ADDRESS -------------------------------------------------- SOURCE DESTINATION DOB TYP ------------------------------ ------------------------------ --------- --- TIMETRAVEL ---------- 2 snigdha 102 f Telanganahyderabadbnreddy MGBS BN reddy 26-NOV-84 nac PASSENGER_ID NAME TICKET_NO S ------------ -------------------- ---------- - ADDRESS -------------------------------------------------- SOURCE DESTINATION DOB TYP ------------------------------ ------------------------------ --------- --- TIMETRAVEL ---------- 3 sherley 103 f Telanganahyderabadbnreddy MGBS Kalwakurthy 01-JAN-85 ac PASSENGER_ID NAME TICKET_NO S ------------ -------------------- ---------- - ADDRESS -------------------------------------------------- SOURCE DESTINATION DOB TYP ------------------------------ ------------------------------ --------- --- TIMETRAVEL ---------- 4 jangaiah 104 m Telanganahyderabadbnreddy kalwakurthy Srisailam 13-SEP-86 nac ; 1 select * FROM passenger 2* WHERE type IN('ac','nac') SQL> ^S^A^A; SP2-0042: unknown command "" - rest of line ignored. SQL> ;HERE type IN('ac','nac') 1 select * FROM passenger 2* WHERE type IN('ac','nac')
#include<stdio.h> int n; int main() { int seq[30],fr[5],pos[5],find,flag,max,i,j,m,k,t,s; int count=1,pf=0,p=0; float pfr; printf("Enter maximum limit of the sequence: "); scanf("%d",&max); printf("\nEnter the sequence: "); for(i=0;i<max;i++) scanf("%d",&seq[i]); printf("\nEnter no. of frames: "); scanf("%d",&n); fr[0]=seq[0]; pf++; printf("%d\t",fr[0]); i=1; while(count<n) { flag=1; p++; for(j=0;j<i;j++) { if(seq[i]==seq[j]) flag=0; } if(flag!=0) { fr[count]=seq[i]; printf("%d\t",fr[count]); count++; pf++; } i++; } printf("\n"); for(i=p;i<max;i++) { flag=1; for(j=0;j<n;j++) { if(seq[i]==fr[j]) flag=0; } if(flag!=0) { for(j=0;j<n;j++) { m=fr[j]; for(k=i;k<max;k++) { if(seq[k]==m) { pos[j]=k; break; } else pos[j]=1; } } for(k=0;k<n;k++) { if(pos[k]==1) flag=0; } if(flag!=0) s=findmax(pos); if(flag==0) { for(k=0;k<n;k++) { if(pos[k]==1) { s=k; break; } } } fr[s]=seq[i]; for(k=0;k<n;k++) printf("%d\t",fr[k]); pf++; printf("\n"); } } pfr=(float)pf/(float)max; printf("\nThe no. of page faults are %d",pf); printf("\nPage fault rate %f",pfr); getch(); } int findmax(int a[]) { int max,i,k=0; max=a[0]; for(i=0;i<n;i++) { if(max<a[i]) { max=a[i]; k=i; } } return k; }
#include<stdio.h> #include<conio.h> void main() { int i, j , k, min, rs[25], m[10], count[10], flag[25], n, f, pf=0, next=1; //clrscr(); printf("Enter the length of reference string -- "); scanf("%d",&n); printf("Enter the reference string -- "); for(i=0;i<n;i++) { scanf("%d",&rs[i]); flag[i]=0; } printf("Enter the number of frames -- "); scanf("%d",&f); for(i=0;i<f;i++) { count[i]=0; m[i]=-1; } printf("\nThe Page Replacement process is -- \n"); for(i=0;i<n;i++) { for(j=0;j<f;j++) { if(m[j]==rs[i]) { flag[i]=1; count[j]=next; next++; } } if(flag[i]==0) { if(i<f) { m[i]=rs[i]; count[i]=next; next++; } else { min=0; for(j=1;j<f;j++) if(count[min] > count[j]) min=j; m[min]=rs[i]; count[min]=next; next++; } pf++; } for(j=0;j<f;j++) printf("%d\t", m[j]); if(flag[i]==0) printf("PF No. -- %d" , pf); printf("\n"); } printf("\nThe number of page faults using LRU are %d",pf); getch(); }
#include<stdio.h> #include<conio.h> int main() { int i, j, k, f, pf=0, count=0, rs[25], m[10], n; printf("\n Enter the length of reference string -- "); scanf("%d",&n); printf("\n Enter the reference string -- "); for(i=0;i<n;i++) scanf("%d",&rs[i]); printf("\n Enter no. of frames -- "); scanf("%d",&f); for(i=0;i<f;i++) m[i]=-1; printf("\n The Page Replacement Process is -- \n"); for(i=0;i<n;i++) { for(k=0;k<f;k++) { if(m[k]==rs[i]) break; } if(k==f) { m[count++]=rs[i]; pf++; } for(j=0;j<f;j++) printf("\t%d",m[j]); if(k==f) printf("\tPF No. %d",pf); printf("\n"); if(count==f) count=0; } printf("\n The number of Page Faults using FIFO are %d",pf); getch(); }
#include<stdio.h> #include<stdlib.h> int mutex=1,full=0,empty=3,x=0; int main() { int n; void producer(); void consumer(); int wait(int); int signal(int); printf("\n 1.Producer \n 2.Consumer \n 3.Exit"); while(1) { printf("\nEnter your choice:"); scanf("%d",&n); switch(n) { case 1: if((mutex==1)&&(empty!=0)) producer(); else printf("Buffer is full"); break; case 2: if((mutex==1)&&(full!=0)) consumer(); else printf("Buffer is empty"); break; case 3: exit(0); break; } } } int wait(int s) { return (--s); } int signal(int s) { return(++s); } void producer() { mutex=wait(mutex); full=signal(full); empty=wait(empty); x++; printf("Producer produces the item %d\n",x); mutex=signal(mutex); } void consumer() { mutex=wait(mutex); full=wait(full); empty=signal(empty); printf("Consumer consumes item %d\n",x); x--; mutex=signal(mutex); }
#include <stdio.h> int main() { int n, m, i, j, k; // Get the number of processes and resources from the user printf("Enter the number of processes: "); scanf("%d", &n); printf("Enter the number of resources: "); scanf("%d", &m); int alloc[n][m], max[n][m], avail[m]; // Get the Allocation Matrix from the user printf("Enter the Allocation Matrix:\n"); for (i = 0; i < n; i++) { printf("Process %d:\n", i); for (j = 0; j < m; j++) { scanf("%d", &alloc[i][j]); } } // Get the Maximum Matrix from the user printf("Enter the Maximum Matrix:\n"); for (i = 0; i < n; i++) { printf("Process %d:\n", i); for (j = 0; j < m; j++) { scanf("%d", &max[i][j]); } } // Get the Available Resources from the user printf("Enter the Available Resources:\n"); for (i = 0; i < m; i++) { scanf("%d", &avail[i]); } int f[n], ans[n], ind = 0; for (k = 0; k < n; k++) { f[k] = 0; } int need[n][m]; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { need[i][j] = max[i][j] - alloc[i][j]; } } int y = 0; for (k = 0; k < n; k++) { for (i = 0; i < n; i++) { if (f[i] == 0) { int flag = 0; for (j = 0; j < m; j++) { if (need[i][j] > avail[j]) { flag = 1; break; } } if (flag == 0) { ans[ind++] = i; for (y = 0; y < m; y++) { avail[y] += alloc[i][y]; } f[i] = 1; } } } } int flag = 1; for (i = 0; i < n; i++) { if (f[i] == 0) { flag = 0; printf("The system is not in a safe state.\n"); break; } } if (flag == 1) { printf("The system is in a safe state.\nSafe sequence is: "); for (i = 0; i < n - 1; i++) { printf("P%d -> ", ans[i]); } printf("P%d\n", ans[n - 1]); } return 0; }
#include <stdio.h> int main() { int n, i, j, temp, sum_wait = 0, sum_turnaround = 0; float avg_wait, avg_turnaround; int priority[20], bt[20], wt[20], tat[20]; printf("Enter the number of processes: "); scanf("%d", &n); // Input burst times and priorities for each process printf("Enter burst times and priorities for each process:\n"); for (i = 0; i < n; i++) { printf("Process %d: ", i + 1); scanf("%d%d", &bt[i], &priority[i]); } // Sort processes based on priority (ascending order) for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if (priority[i] > priority[j]) { temp = priority[i]; priority[i] = priority[j]; priority[j] = temp; temp = bt[i]; bt[i] = bt[j]; bt[j] = temp; } } } // Calculate waiting time for each process wt[0] = 0; // Waiting time for first process is zero for (i = 1; i < n; i++) { wt[i] = wt[i - 1] + bt[i - 1]; sum_wait += wt[i]; } // Calculate turnaround time for each process for (i = 0; i < n; i++) { tat[i] = wt[i] + bt[i]; sum_turnaround += tat[i]; } // Calculate average waiting time and average turnaround time avg_wait = (float)sum_wait / n; avg_turnaround = (float)sum_turnaround / n; // Print process details printf("\nProcess\tBT\tPriority\tWT\tTAT\n"); for (i = 0; i < n; i++) { printf("P%d\t%d\t%d\t\t%d\t%d\n", i + 1, bt[i], priority[i], wt[i], tat[i]); } // Print average waiting time and average turnaround time printf("\nAverage Waiting Time: %.2f\n", avg_wait); printf("Average Turnaround Time: %.2f\n", avg_turnaround); return 0; }
#include <stdio.h> int main() { int n, tq, i, total_time = 0, time = 0, flag = 0; int bt[10], rem_bt[10], wt[10], tat[10]; // Burst times, remaining burst times, waiting times, turnaround times float avg_wt = 0, avg_tat = 0; printf("Enter the number of processes: "); scanf("%d", &n); printf("Enter the burst time for each process:\n"); for (i = 0; i < n; i++) { printf("P[%d]: ", i + 1); scanf("%d", &bt[i]); rem_bt[i] = bt[i]; // Initialize remaining burst time as burst time } printf("Enter the time quantum: "); scanf("%d", &tq); while (1) { flag = 0; for (i = 0; i < n; i++) { if (rem_bt[i] > 0) { flag = 1; // There is a pending process if (rem_bt[i] > tq) { time += tq; rem_bt[i] -= tq; } else { time += rem_bt[i]; wt[i] = time - bt[i]; // Waiting time is current time minus burst time rem_bt[i] = 0; } } } if (flag == 0) // All processes are done break; } printf("\nProcess\tBT\tWT\tTAT\n"); for (i = 0; i < n; i++) { tat[i] = bt[i] + wt[i]; // Turnaround time is burst time plus waiting time avg_wt += wt[i]; avg_tat += tat[i]; printf("P[%d]\t%d\t%d\t%d\n", i + 1, bt[i], wt[i], tat[i]); } avg_wt /= n; avg_tat /= n; printf("\nAverage Waiting Time: %.2f", avg_wt); printf("\nAverage Turnaround Time: %.2f", avg_tat); return 0; }
#include <stdio.h> int main() { int n, i, j, min_bt, time = 0, completed = 0, sum_wait = 0, sum_turnaround = 0; int at[10], bt[10], rt[10], p[10]; // Arrays for arrival times, burst times, remaining times, and process numbers int wait[10], turnaround[10]; // Arrays for waiting times and turnaround times float avg_wait, avg_turnaround; printf("Enter the number of processes: "); scanf("%d", &n); // Input arrival times and burst times for each process for (i = 0; i < n; i++) { printf("Enter the arrival time and burst time for process %d: ", i + 1); scanf("%d%d", &at[i], &bt[i]); rt[i] = bt[i]; // Initialize remaining time as burst time p[i] = i + 1; // Process numbers } // Initialize arrays for waiting and turnaround times for (i = 0; i < n; i++) { wait[i] = 0; turnaround[i] = 0; } printf("\nProcess\tAT\tBT\tWT\tTAT\n"); while (completed != n) { // Find process with minimum remaining time at each time unit min_bt = 9999; // A large number to find the minimum burst time int shortest = -1; // Index of the process with the shortest remaining time for (i = 0; i < n; i++) { if (at[i] <= time && rt[i] > 0 && rt[i] < min_bt) { min_bt = rt[i]; shortest = i; } } if (shortest == -1) { // No process is currently available to execute time++; continue; } rt[shortest]--; // Decrement the remaining time of the shortest process if (rt[shortest] == 0) { // Process is completed completed++; int end_time = time + 1; // Time at which the process completes turnaround[shortest] = end_time - at[shortest]; // Turnaround time wait[shortest] = turnaround[shortest] - bt[shortest]; // Waiting time sum_wait += wait[shortest]; sum_turnaround += turnaround[shortest]; printf("P[%d]\t%d\t%d\t%d\t%d\n", p[shortest], at[shortest], bt[shortest], wait[shortest], turnaround[shortest]); } time++; // Increment time } avg_wait = (float)sum_wait / (float)n; avg_turnaround = (float)sum_turnaround / (float)n; printf("Average waiting time is %.2f\n", avg_wait); printf("Average turnaround time is %.2f\n", avg_turnaround); return 0; }
#include <stdio.h> int main() { int n, i, j, temp, time = 0, count, completed = 0, sum_wait = 0, sum_turnaround = 0, start; float avg_wait, avg_turnaround; int at[10], bt[10], p[10]; // Arrays for arrival times, burst times, and process numbers printf("Enter the number of processes: "); scanf("%d", &n); // Input arrival times and burst times for each process for (i = 0; i < n; i++) { printf("Enter the arrival time and burst time for process %d: ", i + 1); scanf("%d%d", &at[i], &bt[i]); p[i] = i + 1; } // Sort processes by arrival times, and then by burst times for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if (at[i] > at[j] || (at[i] == at[j] && bt[i] > bt[j])) { temp = at[i]; at[i] = at[j]; at[j] = temp; temp = bt[i]; bt[i] = bt[j]; bt[j] = temp; temp = p[i]; p[i] = p[j]; p[j] = temp; } } } printf("\nProcess\tAT\tBT\tWT\tTAT\n"); // Main loop to calculate waiting times and turnaround times while (completed < n) { count = 0; for (i = completed; i < n; i++) { if (at[i] <= time) { count++; } else { break; } } // Sort the ready processes by burst time if (count > 1) { for (i = completed; i < completed + count - 1; i++) { for (j = i + 1; j < completed + count; j++) { if (bt[i] > bt[j]) { temp = at[i]; at[i] = at[j]; at[j] = temp; temp = bt[i]; bt[i] = bt[j]; bt[j] = temp; temp = p[i]; p[i] = p[j]; p[j] = temp; } } } } start = time; time += bt[completed]; printf("P[%d]\t%d\t%d\t%d\t%d\n", p[completed], at[completed], bt[completed], time - at[completed] - bt[completed], time - at[completed]); sum_wait += time - at[completed] - bt[completed]; sum_turnaround += time - at[completed]; completed++; } avg_wait = (float)sum_wait / (float)n; avg_turnaround = (float)sum_turnaround / (float)n; printf("Average waiting time is %.2f\n", avg_wait); printf("Average turnaround time is %.2f\n", avg_turnaround); return 0; }
//FCFS #include<stdio.h> int main(void) { int n,at[10],bt[10],ct[10],tat[10],wt[10],sum,i,j,k; float totaltat=0,totalwt=0; printf("Enter No of processors:"); scanf(" %d",&n); for(i=0;i<n;i++) { printf("Enter the arrival time of processor %d:",i+1); scanf(" %d",&at[i]); } for(i=0;i<n;i++) { printf("Enter the burst time of processor %d:",i+1); scanf(" %d",&bt[i]); } //Calculation of completion times for each processor sum=at[0]; for(j=0;j<n;j++) { sum=sum+bt[j]; ct[j]=sum; } //Calculation of turn around time for(k=0;k<n;k++) { tat[k]=ct[k]-at[k]; totaltat=totaltat+tat[k]; } //Calculation of waiting time for(i=0;i<n;i++) { wt[i]=tat[i]-bt[i]; totalwt=totalwt+wt[i]; } printf("Process\tAT\tBT\tCT\tTAT\tWt\n"); for(i=0;i<n;i++) { printf("\nP%d\t%d\t%d\t%d\t%d\t%d\t\n",i+1,at[i],bt[i],ct[i],tat[i],wt[i]); } printf("average of turn around time:%0.1f\n",totaltat/n); printf("average of waiting time:%0.1f\n",totalwt/n); return 0; }
FCFS-CPU SCHEDULING //FCFS #include<stdio.h> int main(void) { int n,at[10],bt[10],ct[10],tat[10],wt[10],sum,i,j,k; float totaltat=0,totalwt=0; printf("Enter No of processors:"); scanf(" %d",&n); for(i=0;i<n;i++) { printf("Enter the arrival time of processor %d:",i+1); scanf(" %d",&at[i]); } for(i=0;i<n;i++) { printf("Enter the burst time of processor %d:",i+1); scanf(" %d",&bt[i]); } //Calculation of completion times for each processor sum=at[0]; for(j=0;j<n;j++) { sum=sum+bt[j]; ct[j]=sum; } //Calculation of turn around time for(k=0;k<n;k++) { tat[k]=ct[k]-at[k]; totaltat=totaltat+tat[k]; } //Calculation of waiting time for(i=0;i<n;i++) { wt[i]=tat[i]-bt[i]; totalwt=totalwt+wt[i]; } printf("Process\tAT\tBT\tCT\tTAT\tWt\n"); for(i=0;i<n;i++) { printf("\nP%d\t%d\t%d\t%d\t%d\t%d\t\n",i+1,at[i],bt[i],ct[i],tat[i],wt[i]); } printf("average of turn around time:%0.1f\n",totaltat/n); printf("average of waiting time:%0.1f\n",totalwt/n); return 0; } SJF-NON PREEMPTIVE #include <stdio.h> int main() { int n, i, j, temp, time = 0, count, completed = 0, sum_wait = 0, sum_turnaround = 0, start; float avg_wait, avg_turnaround; int at[10], bt[10], p[10]; // Arrays for arrival times, burst times, and process numbers printf("Enter the number of processes: "); scanf("%d", &n); // Input arrival times and burst times for each process for (i = 0; i < n; i++) { printf("Enter the arrival time and burst time for process %d: ", i + 1); scanf("%d%d", &at[i], &bt[i]); p[i] = i + 1; } // Sort processes by arrival times, and then by burst times for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if (at[i] > at[j] || (at[i] == at[j] && bt[i] > bt[j])) { temp = at[i]; at[i] = at[j]; at[j] = temp; temp = bt[i]; bt[i] = bt[j]; bt[j] = temp; temp = p[i]; p[i] = p[j]; p[j] = temp; } } } printf("\nProcess\tAT\tBT\tWT\tTAT\n"); // Main loop to calculate waiting times and turnaround times while (completed < n) { count = 0; for (i = completed; i < n; i++) { if (at[i] <= time) { count++; } else { break; } } // Sort the ready processes by burst time if (count > 1) { for (i = completed; i < completed + count - 1; i++) { for (j = i + 1; j < completed + count; j++) { if (bt[i] > bt[j]) { temp = at[i]; at[i] = at[j]; at[j] = temp; temp = bt[i]; bt[i] = bt[j]; bt[j] = temp; temp = p[i]; p[i] = p[j]; p[j] = temp; } } } } start = time; time += bt[completed]; printf("P[%d]\t%d\t%d\t%d\t%d\n", p[completed], at[completed], bt[completed], time - at[completed] - bt[completed], time - at[completed]); sum_wait += time - at[completed] - bt[completed]; sum_turnaround += time - at[completed]; completed++; } avg_wait = (float)sum_wait / (float)n; avg_turnaround = (float)sum_turnaround / (float)n; printf("Average waiting time is %.2f\n", avg_wait); printf("Average turnaround time is %.2f\n", avg_turnaround); return 0; } SRTF(SJF-PREEMPTIVE) #include <stdio.h> int main() { int n, i, j, min_bt, time = 0, completed = 0, sum_wait = 0, sum_turnaround = 0; int at[10], bt[10], rt[10], p[10]; // Arrays for arrival times, burst times, remaining times, and process numbers int wait[10], turnaround[10]; // Arrays for waiting times and turnaround times float avg_wait, avg_turnaround; printf("Enter the number of processes: "); scanf("%d", &n); // Input arrival times and burst times for each process for (i = 0; i < n; i++) { printf("Enter the arrival time and burst time for process %d: ", i + 1); scanf("%d%d", &at[i], &bt[i]); rt[i] = bt[i]; // Initialize remaining time as burst time p[i] = i + 1; // Process numbers } // Initialize arrays for waiting and turnaround times for (i = 0; i < n; i++) { wait[i] = 0; turnaround[i] = 0; } printf("\nProcess\tAT\tBT\tWT\tTAT\n"); while (completed != n) { // Find process with minimum remaining time at each time unit min_bt = 9999; // A large number to find the minimum burst time int shortest = -1; // Index of the process with the shortest remaining time for (i = 0; i < n; i++) { if (at[i] <= time && rt[i] > 0 && rt[i] < min_bt) { min_bt = rt[i]; shortest = i; } } if (shortest == -1) { // No process is currently available to execute time++; continue; } rt[shortest]--; // Decrement the remaining time of the shortest process if (rt[shortest] == 0) { // Process is completed completed++; int end_time = time + 1; // Time at which the process completes turnaround[shortest] = end_time - at[shortest]; // Turnaround time wait[shortest] = turnaround[shortest] - bt[shortest]; // Waiting time sum_wait += wait[shortest]; sum_turnaround += turnaround[shortest]; printf("P[%d]\t%d\t%d\t%d\t%d\n", p[shortest], at[shortest], bt[shortest], wait[shortest], turnaround[shortest]); } time++; // Increment time } avg_wait = (float)sum_wait / (float)n; avg_turnaround = (float)sum_turnaround / (float)n; printf("Average waiting time is %.2f\n", avg_wait); printf("Average turnaround time is %.2f\n", avg_turnaround); return 0; } ROUND ROBIN PROGRAM #include <stdio.h> int main() { int n, tq, i, total_time = 0, time = 0, flag = 0; int bt[10], rem_bt[10], wt[10], tat[10]; // Burst times, remaining burst times, waiting times, turnaround times float avg_wt = 0, avg_tat = 0; printf("Enter the number of processes: "); scanf("%d", &n); printf("Enter the burst time for each process:\n"); for (i = 0; i < n; i++) { printf("P[%d]: ", i + 1); scanf("%d", &bt[i]); rem_bt[i] = bt[i]; // Initialize remaining burst time as burst time } printf("Enter the time quantum: "); scanf("%d", &tq); while (1) { flag = 0; for (i = 0; i < n; i++) { if (rem_bt[i] > 0) { flag = 1; // There is a pending process if (rem_bt[i] > tq) { time += tq; rem_bt[i] -= tq; } else { time += rem_bt[i]; wt[i] = time - bt[i]; // Waiting time is current time minus burst time rem_bt[i] = 0; } } } if (flag == 0) // All processes are done break; } printf("\nProcess\tBT\tWT\tTAT\n"); for (i = 0; i < n; i++) { tat[i] = bt[i] + wt[i]; // Turnaround time is burst time plus waiting time avg_wt += wt[i]; avg_tat += tat[i]; printf("P[%d]\t%d\t%d\t%d\n", i + 1, bt[i], wt[i], tat[i]); } avg_wt /= n; avg_tat /= n; printf("\nAverage Waiting Time: %.2f", avg_wt); printf("\nAverage Turnaround Time: %.2f", avg_tat); return 0; } PRIORITY PROGRAM #include <stdio.h> int main() { int n, i, j, temp, sum_wait = 0, sum_turnaround = 0; float avg_wait, avg_turnaround; int priority[20], bt[20], wt[20], tat[20]; printf("Enter the number of processes: "); scanf("%d", &n); // Input burst times and priorities for each process printf("Enter burst times and priorities for each process:\n"); for (i = 0; i < n; i++) { printf("Process %d: ", i + 1); scanf("%d%d", &bt[i], &priority[i]); } // Sort processes based on priority (ascending order) for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if (priority[i] > priority[j]) { temp = priority[i]; priority[i] = priority[j]; priority[j] = temp; temp = bt[i]; bt[i] = bt[j]; bt[j] = temp; } } } // Calculate waiting time for each process wt[0] = 0; // Waiting time for first process is zero for (i = 1; i < n; i++) { wt[i] = wt[i - 1] + bt[i - 1]; sum_wait += wt[i]; } // Calculate turnaround time for each process for (i = 0; i < n; i++) { tat[i] = wt[i] + bt[i]; sum_turnaround += tat[i]; } // Calculate average waiting time and average turnaround time avg_wait = (float)sum_wait / n; avg_turnaround = (float)sum_turnaround / n; // Print process details printf("\nProcess\tBT\tPriority\tWT\tTAT\n"); for (i = 0; i < n; i++) { printf("P%d\t%d\t%d\t\t%d\t%d\n", i + 1, bt[i], priority[i], wt[i], tat[i]); } // Print average waiting time and average turnaround time printf("\nAverage Waiting Time: %.2f\n", avg_wait); printf("Average Turnaround Time: %.2f\n", avg_turnaround); return 0; } BANKERS ALGORITHM #include <stdio.h> int main() { int n, m, i, j, k; // Get the number of processes and resources from the user printf("Enter the number of processes: "); scanf("%d", &n); printf("Enter the number of resources: "); scanf("%d", &m); int alloc[n][m], max[n][m], avail[m]; // Get the Allocation Matrix from the user printf("Enter the Allocation Matrix:\n"); for (i = 0; i < n; i++) { printf("Process %d:\n", i); for (j = 0; j < m; j++) { scanf("%d", &alloc[i][j]); } } // Get the Maximum Matrix from the user printf("Enter the Maximum Matrix:\n"); for (i = 0; i < n; i++) { printf("Process %d:\n", i); for (j = 0; j < m; j++) { scanf("%d", &max[i][j]); } } // Get the Available Resources from the user printf("Enter the Available Resources:\n"); for (i = 0; i < m; i++) { scanf("%d", &avail[i]); } int f[n], ans[n], ind = 0; for (k = 0; k < n; k++) { f[k] = 0; } int need[n][m]; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { need[i][j] = max[i][j] - alloc[i][j]; } } int y = 0; for (k = 0; k < n; k++) { for (i = 0; i < n; i++) { if (f[i] == 0) { int flag = 0; for (j = 0; j < m; j++) { if (need[i][j] > avail[j]) { flag = 1; break; } } if (flag == 0) { ans[ind++] = i; for (y = 0; y < m; y++) { avail[y] += alloc[i][y]; } f[i] = 1; } } } } int flag = 1; for (i = 0; i < n; i++) { if (f[i] == 0) { flag = 0; printf("The system is not in a safe state.\n"); break; } } if (flag == 1) { printf("The system is in a safe state.\nSafe sequence is: "); for (i = 0; i < n - 1; i++) { printf("P%d -> ", ans[i]); } printf("P%d\n", ans[n - 1]); } return 0; } PRODUCER-CONSUMER PROBLEM #include<stdio.h> #include<stdlib.h> int mutex=1,full=0,empty=3,x=0; int main() { int n; void producer(); void consumer(); int wait(int); int signal(int); printf("\n 1.Producer \n 2.Consumer \n 3.Exit"); while(1) { printf("\nEnter your choice:"); scanf("%d",&n); switch(n) { case 1: if((mutex==1)&&(empty!=0)) producer(); else printf("Buffer is full"); break; case 2: if((mutex==1)&&(full!=0)) consumer(); else printf("Buffer is empty"); break; case 3: exit(0); break; } } } int wait(int s) { return (--s); } int signal(int s) { return(++s); } void producer() { mutex=wait(mutex); full=signal(full); empty=wait(empty); x++; printf("Producer produces the item %d\n",x); mutex=signal(mutex); } void consumer() { mutex=wait(mutex); full=wait(full); empty=signal(empty); printf("Consumer consumes item %d\n",x); x--; mutex=signal(mutex); } FCFS-PAGE REPLACEMENT ALGORITHM //FIFO PAGE REPLACEMENT ALGORITHM #include<stdio.h> #include<conio.h> int main() { int i, j, k, f, pf=0, count=0, rs[25], m[10], n; printf("\n Enter the length of reference string -- "); scanf("%d",&n); printf("\n Enter the reference string -- "); for(i=0;i<n;i++) scanf("%d",&rs[i]); printf("\n Enter no. of frames -- "); scanf("%d",&f); for(i=0;i<f;i++) m[i]=-1; printf("\n The Page Replacement Process is -- \n"); for(i=0;i<n;i++) { for(k=0;k<f;k++) { if(m[k]==rs[i]) break; } if(k==f) { m[count++]=rs[i]; pf++; } for(j=0;j<f;j++) printf("\t%d",m[j]); if(k==f) printf("\tPF No. %d",pf); printf("\n"); if(count==f) count=0; } printf("\n The number of Page Faults using FIFO are %d",pf); getch(); } 2.LRU PAGE REPLACEMENT ALGORITHM //LRU #include<stdio.h> #include<conio.h> void main() { int i, j , k, min, rs[25], m[10], count[10], flag[25], n, f, pf=0, next=1; //clrscr(); printf("Enter the length of reference string -- "); scanf("%d",&n); printf("Enter the reference string -- "); for(i=0;i<n;i++) { scanf("%d",&rs[i]); flag[i]=0; } printf("Enter the number of frames -- "); scanf("%d",&f); for(i=0;i<f;i++) { count[i]=0; m[i]=-1; } printf("\nThe Page Replacement process is -- \n"); for(i=0;i<n;i++) { for(j=0;j<f;j++) { if(m[j]==rs[i]) { flag[i]=1; count[j]=next; next++; } } if(flag[i]==0) { if(i<f) { m[i]=rs[i]; count[i]=next; next++; } else { min=0; for(j=1;j<f;j++) if(count[min] > count[j]) min=j; m[min]=rs[i]; count[min]=next; next++; } pf++; } for(j=0;j<f;j++) printf("%d\t", m[j]); if(flag[i]==0) printf("PF No. -- %d" , pf); printf("\n"); } printf("\nThe number of page faults using LRU are %d",pf); getch(); } 3.OPTIMAL PAGE REPLACEMENT ALGORITHM //Optimal page replacement #include<stdio.h> int n; int main() { int seq[30],fr[5],pos[5],find,flag,max,i,j,m,k,t,s; int count=1,pf=0,p=0; float pfr; printf("Enter maximum limit of the sequence: "); scanf("%d",&max); printf("\nEnter the sequence: "); for(i=0;i<max;i++) scanf("%d",&seq[i]); printf("\nEnter no. of frames: "); scanf("%d",&n); fr[0]=seq[0]; pf++; printf("%d\t",fr[0]); i=1; while(count<n) { flag=1; p++; for(j=0;j<i;j++) { if(seq[i]==seq[j]) flag=0; } if(flag!=0) { fr[count]=seq[i]; printf("%d\t",fr[count]); count++; pf++; } i++; } printf("\n"); for(i=p;i<max;i++) { flag=1; for(j=0;j<n;j++) { if(seq[i]==fr[j]) flag=0; } if(flag!=0) { for(j=0;j<n;j++) { m=fr[j]; for(k=i;k<max;k++) { if(seq[k]==m) { pos[j]=k; break; } else pos[j]=1; } } for(k=0;k<n;k++) { if(pos[k]==1) flag=0; } if(flag!=0) s=findmax(pos); if(flag==0) { for(k=0;k<n;k++) { if(pos[k]==1) { s=k; break; } } } fr[s]=seq[i]; for(k=0;k<n;k++) printf("%d\t",fr[k]); pf++; printf("\n"); } } pfr=(float)pf/(float)max; printf("\nThe no. of page faults are %d",pf); printf("\nPage fault rate %f",pfr); getch(); } int findmax(int a[]) { int max,i,k=0; max=a[0]; for(i=0;i<n;i++) { if(max<a[i]) { max=a[i]; k=i; } } return k; }
#include <stdio.h> int main() { int n, m, i, j, k; // Get the number of processes and resources from the user printf("Enter the number of processes: "); scanf("%d", &n); printf("Enter the number of resources: "); scanf("%d", &m); int alloc[n][m], max[n][m], avail[m]; // Get the Allocation Matrix from the user printf("Enter the Allocation Matrix:\n"); for (i = 0; i < n; i++) { printf("Process %d:\n", i); for (j = 0; j < m; j++) { scanf("%d", &alloc[i][j]); } } // Get the Maximum Matrix from the user printf("Enter the Maximum Matrix:\n"); for (i = 0; i < n; i++) { printf("Process %d:\n", i); for (j = 0; j < m; j++) { scanf("%d", &max[i][j]); } } // Get the Available Resources from the user printf("Enter the Available Resources:\n"); for (i = 0; i < m; i++) { scanf("%d", &avail[i]); } int f[n], ans[n], ind = 0; for (k = 0; k < n; k++) { f[k] = 0; } int need[n][m]; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { need[i][j] = max[i][j] - alloc[i][j]; } } int y = 0; for (k = 0; k < n; k++) { for (i = 0; i < n; i++) { if (f[i] == 0) { int flag = 0; for (j = 0; j < m; j++) { if (need[i][j] > avail[j]) { flag = 1; break; } } if (flag == 0) { ans[ind++] = i; for (y = 0; y < m; y++) { avail[y] += alloc[i][y]; } f[i] = 1; } } } } int flag = 1; for (i = 0; i < n; i++) { if (f[i] == 0) { flag = 0; printf("The system is not in a safe state.\n"); break; } } if (flag == 1) { printf("The system is in a safe state.\nSafe sequence is: "); for (i = 0; i < n - 1; i++) { printf("P%d -> ", ans[i]); } printf("P%d\n", ans[n - 1]); } return 0; }
$('a[data-scroll]').click(function (e) { e.preventDefault(); //Set Offset Distance from top to account for fixed nav var offset = 10; var target = '#' + $(this).data('scroll'); var $target = $(target); //Animate the scroll to, include easing lib if you want more fancypants easings $('html, body') .stop() .animate( { scrollTop: $target.offset().top - offset, }, 800, 'swing', ); }); //jQuery //jQuery('a[data-scroll]').click(function (e) { // e.preventDefault(); // // Set Offset Distance from top to account for fixed nav // var offset = 10; // var target = '#' + jQuery(this).data('scroll'); // var $target = jQuery(target); // // Animate the scroll to, include easing lib if you want more fancypants easings // jQuery('html, body') // .stop() // .animate( // { // scrollTop: $target.offset().top - offset, // }, // 800, // 'swing', // ); // });
this.$burger = this.$element.find('.header__burger'); this.$navBodyItems = this.$element.find( '.header__popup-menu .col-lg-3.col-md-6.col-12', ); const tl = gsap.timeline(); tl.fromTo( this.$navBodyItems, { opacity: 0, y: -500 }, { opacity: 1, y: 0, duration: 1 }, ); this.$burger.on('click', (event) => { event.preventDefault(); if (tl.reversed()) { tl.play(); } else { tl.reverse(); } });
154.16.195.46
// use while loops when the number of items we are looping over are unknown let items = [ { id: 1, name: "Item 1", price: 10.99 }, { id: 2, name: "Item 2", price: 15.49 }, { id: 3, name: "Item 3", price: 7.99 }, { id: 4, name: "Item 4", price: 12.0 }, { id: 5, name: "Item 5", price: 9.5 }, ]; let i = 0; // counter variable let numberOfItems = items.length ?? 0; // if the number of items is not a number give me 0; console.log(numberOfItems); while (i < items.length) { let { id, name, price } = items[i]; // Destructuring assignment console.log(`ID: ${id}, Name: ${name}, Price: $${price}`); i++; }
CREATE TABLE `user_activity` ( `id` int NOT NULL AUTO_INCREMENT, `username` varchar(150) DEFAULT NULL, `login_time` datetime DEFAULT NULL, `logout_time` datetime DEFAULT NULL, `path_info` varchar(255) DEFAULT NULL, `api_hit` tinyint(1) DEFAULT '0', `response_time` bigint DEFAULT NULL, `ip_address` varchar(45) DEFAULT '', `timestamp` datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=117382 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; CREATE TABLE `user_session` ( `id` int NOT NULL AUTO_INCREMENT, `username` varchar(150) DEFAULT '', `login_time` datetime NOT NULL, `logout_time` datetime DEFAULT NULL, `session_duration_seconds` int DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=98 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
1class ContactForm extends Component 2{ 3 public $name; 4 public $email; 5 6 protected $rules = [ 7 'name' => 'required|min:6', 8 'email' => 'required|email', 9 ]; 10 11 public function updated($propertyName) 12 { 13 $this->validateOnly($propertyName); 14 } 15 16 public function saveContact() 17 { 18 $validatedData = $this->validate(); 19 20 Contact::create($validatedData); 21 } 22}
gcloud compute ssh --zone YOUR_ZONE YOUR_INSTANCE_NAME -- -L 8888:localhost:8888
1<div> 2 <input wire:model="message" type="text"> 3 4 <h1>{{ $message }}</h1> 5</div> //data binding
1public $search = ''; 2public $isActive = true; 3 4public function resetFilters() 5{ 6 $this->reset('search'); 7 // Will only reset the search property. 8 9 $this->reset(['search', 'isActive']); 10 // Will reset both the search AND the isActive property. 11 12 $this->resetExcept('search'); 13 // Will only reset the isActive property (any property but the search property). 14}
1class HelloWorld extends Component 2{ 3 public $message; 4 //initializing properties witht the property 5 public function mount() 6 { 7 $this->message = 'Hello World!'; 8 } 9}
1public $search = ''; 2public $isActive = true; 3 4public function resetFilters() 5{ 6 $this->reset('search'); 7 // Will only reset the search property. 8 9 $this->reset(['search', 'isActive']); 10 // Will reset both the search AND the isActive property. 11 12 $this->resetExcept('search'); 13 // Will only reset the isActive property (any property but the search property). 14}
<script> async function harryPotterStudents() { const res = await fetch('https://hp-api.herokuapp.com/api/characters/students'); const json = await res.json() if (res.ok) { return json } else { throw new Error(json) } } let promise = harryPotterStudents() </script> <h2>Estudiantes de la saga Harry Potter (promesas)</h2> {#await promise} <p>Esperando resultados...</p> {:then students} <p>Total estudiantes: {students.length}</p> {#each students as {name: alt, house, image: src}} {#if src} <h3>{alt} ({house})</h3> <img height="100" {src} {alt} /> {/if} {/each} {:catch error} <p style="color: red">{error.message}</p> {/await}
declare invalid_sal Exception; s employee.sal%type:=&sal; begin if (s<3000) then raise invalid_sal; else insert into employee(sal) values(s); dbms_output.put_line('Record inserted'); end if; Exception when invalid_sal then dbms_output.put_line('sal greater '); end; /
/* * @Author: allen_ * @Date: 2024-05-22 10:45:18 * @Email: zhangxudong_a@aspirecn.com * @LastEditors: allen_ * @LastEditTime: 2024-05-23 15:43:17 * @Description: 水印 * @example: * watermark.set(this.$refs.body, { text: '水印文字', gap: [50, 100], fontSize: 14, color: 'rgba(0, 0, 0, 0.35)'}) */ import html2canvas from 'html2canvas' const watermark = {} /** * @description: 设置水印 * @param {*} sourceBody 需要设置的元素 * @param {*} text 水印文字 * @param {array} gap 水印间距 [上下间距, 左右间距] * @param {*} fontSize 水印文字大小 * @param {*} color 水印字体颜色 * @param {*} zIndex 水印层级 * @param {*} rotate 水印角度 */ const setWatermark = (sourceBody, { text = 'watermark', gap = [100, 120], fontSize = 14, color = 'rgba(0, 0, 0, 0.25)', zIndex = 9999, rotate = -22, custom = null }) => { // @Explain: 生成随机元素 id const id = Math.random() * 10000 + '-' + Math.random() * 10000 + '/' + Math.random() * 10000 if (document.getElementById(id) !== null) { document.body.removeChild(document.getElementById(id)) } let canvasData = null if (!custom) { const can = document.createElement('canvas') can.height = gap[0] // 水印上下间距 can.width = gap[1] // 水印左右间距 const cans = can.getContext('2d') cans.rotate((rotate * Math.PI) / 180) cans.font = fontSize + 'px Microsoft YaHei' cans.fillStyle = color cans.textAlign = 'left' cans.textBaseline = 'Middle' cans.fillText(text, can.width / 20, can.height / 3) canvasData = can.toDataURL('image/png', 1.0) } else { canvasData = custom } const water_div = document.createElement('div') water_div.id = id water_div.className = 'watermark-body' const styleStr = ` background: url(${canvasData}) left top repeat; pointer-events: none; width: 100%; height: 100%; position: absolute; z-index: ${zIndex}; top: 0px; left: 0px; ` water_div.setAttribute('style', styleStr) const partnerStyle = ` ${sourceBody.getAttribute('style') || ''} position: relative; userSelect: none; ` sourceBody.setAttribute('style', partnerStyle) sourceBody.appendChild(water_div) // 防止水印被删除 const observer = new MutationObserver(() => { const wmInstance = document.getElementById(id) if ((wmInstance && wmInstance.getAttribute('style') !== styleStr) || !wmInstance) { // 如果标签在,只修改了属性,重新赋值属性 if (wmInstance) { // 避免一直触发 -- 水印属性修改了 wmInstance.setAttribute('style', styleStr) } else { // observer.disconnect() sourceBody.appendChild(water_div) } } else if (sourceBody.getAttribute('style') !== partnerStyle) { // @Explain: 判断父元素样式是否存在更改 sourceBody.setAttribute('style', partnerStyle) } }) observer.observe(sourceBody, { attributes: true, subtree: true, childList: true }) return id } // @Explain: 为元素设置水印 watermark.set = (sourceBody, opi) => { const domArr = Array.from(document.getElementsByClassName('watermark-body')) for (let i = domArr.length; i--;) { const element = domArr[i] element.remove() } if ((!opi.text && !opi.custom) || !sourceBody) return null if (!(sourceBody instanceof HTMLElement)) { // @Condition: 判断传入的元素是否为dom元素 || VueComponent sourceBody = sourceBody.$el } const id = setWatermark(sourceBody, opi) return id } // @Explain: html2canvas 创建元素 base64 watermark.baseImg = (el, scale = window.devicePixelRatio < 3 ? window.devicePixelRatio : 2) => { return new Promise((resolve) => { html2canvas(el, { useCORS: true, // 【重要】开启跨域配置 scale, allowTaint: true, // 允许跨域图片 backgroundColor: null // 是否设置背景色透明 }).then((canvas) => { const imgData = canvas.toDataURL('img/jpg', 1.0) resolve(imgData) }) }) } // @Explain: 创建水印方法 watermark.create = (text = 'watermark', callback = null, cache = true) => { if (callback && typeof callback === 'function') { // @Condition: 自定义水印元素创建方法 return callback(text, watermark) } // @Explain: 判断缓存创建的水印元素是否存在 if (watermark.cacheEl && cache) { watermark.cacheEl.querySelector('.watermark-user-info').innerText = text return watermark.cacheEl } const div = document.createElement('div') div.style = ` width: 200px; height: 160px; display: flex; align-items: center;` const watermarkDiv = document.createElement('div') watermarkDiv.style = ` width: 210px; height: 48px; display: flex; justify-content: center; align-items: center; flex-wrap: wrap; transform-origin: center; transform: rotate(-35deg);` const img = document.createElement('img') img.style = 'width: 201px;' // if you need image, edit here // img.src = require('@/assets/img/watermark.png') const userInfo = document.createElement('div') userInfo.className = 'watermark-user-info' userInfo.style = ` font-size: 12px; color: rgba(38, 42, 48, 0.1); letter-spacing: 0; font-family: PingFangSC-Regular;` userInfo.innerText = text watermarkDiv.appendChild(img) watermarkDiv.appendChild(userInfo) div.appendChild(watermarkDiv) watermark.cacheEl = div // 缓存水印元素 return div } export default watermark
Things to keep in Mind in Linked List 1) Make sure where to use temp->next1=NULL OR temp!=NULL 2) fast!=NULL && fast->next!=NULL Use this order only else it will give runtime error
import React, { useState, useEffect } from "react"; import axios from "axios"; import { useLocation } from "react-router-dom"; import Slider from "react-slick"; import "slick-carousel/slick/slick.css"; import "slick-carousel/slick/slick-theme.css"; import "bootstrap/dist/css/bootstrap.min.css"; import Header from "../Header.jsx"; import Footer from "../Footer.jsx"; import { FaMapMarkerAlt, FaStar, FaUserMd } from "react-icons/fa"; // Импортируем иконки import doctorImg from "../Assets/dc1.png"; const SpecificClinicPage = () => { const location = useLocation(); const [clinic, setClinic] = useState(null); const [doctors, setDoctors] = useState([]); const [services, setServices] = useState([]); useEffect(() => { const fetchClinic = async () => { try { const id = new URLSearchParams(location.search).get("id"); if (!id) { throw new Error("Clinic ID not provided"); } const response = await axios.get( `http://localhost:8000/clinic?id=${id}` ); setClinic(response.data); const doctorsResponse = await axios.get( `http://localhost:8000/get-clinic-doctors?id=${id}` ); setDoctors(doctorsResponse.data); // Fetch services for the clinic const servicesResponse = await axios.get( `http://localhost:8000/get-clinic-services?id=${id}` ); setServices(servicesResponse.data); } catch (error) { console.error("Error fetching clinic:", error); } }; fetchClinic(); }, [location.search]); const sliderSettings = { dots: true, infinite: true, speed: 500, slidesToShow: 3, slidesToScroll: 1, autoplay: true, autoplaySpeed: 3000, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 2, slidesToScroll: 1, infinite: true, dots: true } }, { breakpoint: 600, settings: { slidesToShow: 1, slidesToScroll: 1 } } ] }; return ( <div style={{ display: "flex", flexDirection: "column", minHeight: "100vh" }}> <Header /> <style>{styles}</style> <div style={{ display: "flex", flexDirection: "column", minHeight: "100vh", backgroundImage: 'url("/clinic1.png")', backgroundSize: "cover", color: "white", }} > <div style={{ marginLeft: "300px", marginTop: "100px" }}> <p style={{ fontSize: "90px", fontWeight: "600", marginRight: "400px", }} > {"clinic.clinic_name"} </p> <p style={{ fontSize: "29px", maxWidth: "900px", fontWeight: "400" }}> {"clinic.description"} </p> <p style={{ fontSize: "34px", fontWeight: "600" }}> <FaMapMarkerAlt /> <strong>Address:</strong> {"clinic.address"} </p> </div> </div> {/* Карусель "Услуги клиники" */} <div style={{ textAlign: "center", marginTop: "60px", marginBottom: "40px" }}> <p style={{ color: "#00145B", fontSize: "60px" }}>Услуги клиники</p> </div> <div className="slider-container"> <Slider {...sliderSettings}> {services.map(service => ( <div className="slider-item" key={service.id}> <div className="service-icons"> {/* Добавляем контейнер для иконок */} <FaUserMd className="icon" /> {/* Иконка доктора */} </div> <h3>{service.name}</h3> <p>{service.description}</p> <button className="service-button">Записаться</button> </div> ))} </Slider> </div> {/* Карусель "Доктора в клинике" */} <div style={{ textAlign: "center", marginTop: "60px", marginBottom: "40px" }}> <p style={{ color: "#00145B", fontSize: "60px" }}>Доктора в клинике</p> </div> <div className="slider-container" style={{ marginBottom: "60px" }}> <Slider {...sliderSettings}> {doctors.map(doctor => ( <div className="slider-item" key={doctor.id}> <img src={doctorImg} alt={doctor.name} style={{ marginLeft: "95px", width: "50%", height: "auto", maxHeight: "200px" }} /> <h3>{doctor.name}</h3> <p>{doctor.type}</p> </div> ))} </Slider> </div> <Footer /> </div> ); }; export default SpecificClinicPage; const styles = ` .slider-container { width: 70%; margin: 0 auto; } .slider-item { text-align: center; padding: 20px; /* border: 1px solid #ddd; Убрали границу */ border-radius: 5px; background-color: #fff; position: relative; /* Добавляем позиционирование */ margin: 0 10px; /* Добавляем отступы для выравнивания расстояния */ box-sizing: border-box; /* Убедимся, что padding и border не влияют на ширину */ } .slider-item h3 { font-size: 24px; color: #00145B; margin-bottom: 10px; } .slider-item p { font-size: 16px; color: #555; margin-bottom: 20px; } .slider-item img { width: 100%; height: auto; max-height: 200px; border-radius: 5px; margin-bottom: 10px; } .service-icons { display: flex; margin-top: 10px; margin-bottom: 10px; } .service-icons .icon { font-size: 60px; color: #33437C; margin-left: 170px; } .service-button { background-color: #2A65FF; color: #fff; border: none; padding: 15px 90px; font-size: 24px; cursor: pointer; transition: background-color 0.3s; margin-top: 20px; } .service-button:hover { background-color: #0043b2; } /* Стили для точек пагинации */ .slick-dots li button:before { margin-top: 10px; font-size: 16px; color: #2A65FF; } .slick-dots li.slick-active button:before { color: #0043b2; } /* Обертка для слайдера */ .slick-slider { margin: 0 auto; padding: 0 20px; } `
// SpecificClinicPage.jsx import React, { useState, useEffect } from "react"; import axios from "axios"; import { useLocation } from "react-router-dom"; import Slider from "react-slick"; import "slick-carousel/slick/slick.css"; import "slick-carousel/slick/slick-theme.css"; import "bootstrap/dist/css/bootstrap.min.css"; import Header from "../Header.jsx"; import Footer from "../Footer.jsx"; import { FaMapMarkerAlt } from "react-icons/fa"; import doctorImg from "../Assets/doctor3.png"; const SpecificClinicPage = () => { const location = useLocation(); const [clinic, setClinic] = useState(null); const [doctors, setDoctors] = useState([]); const [services, setServices] = useState([]); useEffect(() => { const fetchClinic = async () => { try { // Тестовые данные для услуг клиники const testServices = [ { id: 1, name: "Service 1", description: "Description for service 1" }, { id: 2, name: "Service 2", description: "Description for service 2" }, { id: 3, name: "Service 3", description: "Description for service 3" }, ]; // Тестовые данные для докторов в клинике const testDoctors = [ { id: 1, name: "Doctor 1", type: "Type 1" }, { id: 2, name: "Doctor 2", type: "Type 2" }, { id: 3, name: "Doctor 3", type: "Type 3" }, ]; setServices(testServices); setDoctors(testDoctors); } catch (error) { console.error("Error fetching clinic:", error); } }; fetchClinic(); }, []); const sliderSettings = { dots: true, infinite: true, speed: 500, slidesToShow: 3, slidesToScroll: 1, autoplay: true, autoplaySpeed: 3000, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 2, slidesToScroll: 1, infinite: true, dots: true } }, { breakpoint: 600, settings: { slidesToShow: 1, slidesToScroll: 1 } } ] }; return ( <div style={{ display: "flex", flexDirection: "column", minHeight: "100vh" }}> <Header /> <style>{styles}</style> <div style={{ display: "flex", flexDirection: "column", minHeight: "100vh", backgroundImage: 'url("/clinic1.png")', backgroundSize: "cover", color: "white", }} > <div style={{ marginLeft: "300px", marginTop: "100px" }}> <p style={{ fontSize: "90px", fontWeight: "600", marginRight: "400px", }} > {"clinic.clinic_name"} </p> <p style={{ fontSize: "29px", maxWidth: "900px", fontWeight: "400" }}> {"clinic.description"} </p> <p style={{ fontSize: "34px", fontWeight: "600" }}> <FaMapMarkerAlt /> <strong>Address:</strong> {"clinic.address"} </p> </div> </div> <div style={{ textAlign: "center", marginTop: "60px", marginBottom: "40px" }}> <p style={{ color: "#00145B", fontSize: "60px" }}>Услуги клиники</p> </div> <div className="slider-container"> <Slider {...sliderSettings}> {services.map(service => ( <div className="slider-item" key={service.id}> <h3>{service.name}</h3> <p>{service.description}</p> <button className="service-button">Записаться</button> </div> ))} </Slider> </div> <div style={{ textAlign: "center", marginTop: "60px", marginBottom: "40px" }}> <p style={{ color: "#00145B", fontSize: "60px" }}>Доктора в клинике</p> </div> <div className="slider-container" style={{ marginBottom: "60px" }}> <Slider {...sliderSettings}> {doctors.map(doctor => ( <div className="slider-item" key={doctor.id}> <img src={doctorImg} alt={doctor.name} style={{ width: "100%", height: "auto", maxHeight: "200px" }} /> <h3>{doctor.name}</h3> <p>{doctor.type}</p> </div> ))} </Slider> </div> <Footer /> </div> ); }; export default SpecificClinicPage; const styles = ` .slider-container { width: 70%; margin: 0 auto; } .slider-item { text-align: center; padding: 20px; border: 1px solid #ddd; border-radius: 5px; background-color: #fff; } .slider-item h3 { font-size: 24px; color: #00145B; margin-bottom: 10px; } .slider-item p { font-size:16px; color: #555; margin-bottom: 20px; } .slider-item img { width: 100%; height: auto; max-height: 200px; border-radius: 5px; margin-bottom: 10px; } .service-button { background-color: #2A65FF; color: #fff; border: none; border-radius: 5px; padding: 10px 20px; font-size: 16px; cursor: pointer; transition: background-color 0.3s; } .service-button:hover { background-color: #0043b2; } `;
Write a java program to demonstrate the use of bounded type parameters and wild cards arguments. //BoundedType public class BoundedArithematic<T extends Number> { public double add(T a, T b) { return a.doubleValue() + b.doubleValue(); } public double subtract(T a, T b) { return a.doubleValue() - b.doubleValue(); } public double multiply(T a, T b) { return a.doubleValue() * b.doubleValue(); } public double divide(T a, T b) { if (b.doubleValue() == 0) { throw new ArithmeticException("Division by zero is not allowed."); } return a.doubleValue() / b.doubleValue(); } public static void main(String[] args) { BoundedArithematic<Number> calculator = new BoundedArithematic<>(); Integer a = 10; Integer b = 5; System.out.println("Addition: " + calculator.add(a, b)); System.out.println("Subtraction: " + calculator.subtract(a, b)); System.out.println("Multiplication: " + calculator.multiply(a, b)); System.out.println("Division: " + calculator.divide(a, b)); } } == //Wildcard Arguments public class MagicBox<T> { private T item; public void addItem(T item) { this.item = item; System.out.println("Added item to the magic box: " + item); } public T getItem() { return item; } public void processBox(MagicBox<? super Integer> box) { System.out.println("Items in the box are processed["+box.getItem()+"]"); } public static void main(String[] args) { MagicBox<Integer> integerBox = new MagicBox<>(); integerBox.addItem(43); MagicBox<String> stringBox = new MagicBox<>(); stringBox.addItem("Sofiya"); MagicBox<Boolean> booleanBox = new MagicBox<>(); booleanBox.addItem(false); MagicBox<Object> dobubleBox = new MagicBox<>(); dobubleBox.addItem(43.43); integerBox.processBox(integerBox); dobubleBox.processBox(dobubleBox); } } --------------------------------------------------------------------------------------------------------------------- 2.Write a java program that returns the value of pi using the lambda expression. public class PiLambdaExpression{ @FunctionalInterface interface PiValue{ double getPi(); } public static void main(String[] args) { PiValue pi = () -> Math.PI; double p= pi.getPi(); System.out.println("The value of Pi is: " + p); } } --------------------------------------------------------------------------------------------------------------------- 3. Write a java program that takes a string as parameter and calculates the reverse of the string using lambda expression. //ReverseStringLambda public class ReverseStringLambda { @FunctionalInterface interface StringReverser { String reverse(String str); } public static void main(String[] args) { StringReverser reverser = (str) -> new StringBuilder(str).reverse().toString(); String example = "Hello, World!"; String reversed = reverser.reverse(example); System.out.println("Original: " + example); System.out.println("Reversed: " + reversed); } } --------------------------------------------------------------------------------------------------------------------- 4. Write a java program to implement iterators on Array List and Linked List. //ArrayList import java.util.ArrayList; import java.util.Iterator; public class ArrayListIteratorExample { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); Iterator<String> iterator = fruits.iterator(); System.out.println("Using Iterator to traverse through the ArrayList:"); while (iterator.hasNext()) { String fruit = iterator.next(); System.out.println(fruit); } System.out.println("\nUsing for-each loop to traverse through the ArrayList:"); for (String fruit : fruits) { System.out.println(fruit); } iterator = fruits.iterator(); // Reset the iterator while (iterator.hasNext()) { String fruit = iterator.next(); if (fruit.startsWith("B")) { iterator.remove(); // Remove elements that start with "B" } } System.out.println("\nArrayList after removal of elements that start with 'B':"); for (String fruit : fruits) { System.out.println(fruit); } } } == //4.ALinkedList import java.util.LinkedList; import java.util.Iterator; public class LinkedListIteratorExample { public static void main(String[] args) { LinkedList<String> fruits = new LinkedList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); Iterator<String> iterator = fruits.iterator(); System.out.println("Using Iterator to traverse through the LinkedList:"); while (iterator.hasNext()) { String fruit = iterator.next(); System.out.println(fruit); } System.out.println("\nUsing for-each loop to traverse through the LinkedList:"); for (String fruit : fruits) { System.out.println(fruit); } iterator = fruits.iterator(); // Reset the iterator while (iterator.hasNext()) { String fruit = iterator.next(); if (fruit.startsWith("B")) { iterator.remove(); } } System.out.println("\nLinkedList after removal of elements that start with 'B':"); for (String fruit : fruits) { System.out.println(fruit); } } } --------------------------------------------------------------------------------------------------------------------- 5.a) Implement a Generic stack to deal with Integer, Double and String data using user defined arrays and linked lists. //5a)user-defined generic stack import java.util.Scanner; class Node<T> { T data; Node<T> next; public Node(T data) { this.data = data; this.next = null; } } class GenericStackArray<T> { private T[] stackArray; private int top; private int maxSize; @SuppressWarnings("unchecked") public GenericStackArray(int size) { this.maxSize = size; this.stackArray = (T[]) new Object[maxSize]; this.top = -1; } public void push(T item) { if (top < maxSize - 1) { stackArray[++top] = item; } else { System.out.println("Stack Overflow"); } } public T pop() { if (top >= 0) { return stackArray[top--]; } else { System.out.println("Stack Underflow"); return null; } } public boolean isEmpty() { return top == -1; } } class GenericStackLinkedList<T> { private Node<T> top; public GenericStackLinkedList() { this.top = null; } public void push(T item) { Node<T> newNode = new Node<>(item); newNode.next = top; top = newNode; } public T pop() { if (top == null) { System.out.println("Stack Underflow"); return null; } T data = top.data; top = top.next; return data; } public boolean isEmpty() { return top == null; } } public class GenericStackExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); GenericStackArray<Integer> intStackArray = new GenericStackArray<>(5); GenericStackLinkedList<Integer> intStackLinkedList = new GenericStackLinkedList<>(); System.out.println("Enter integers to push into the array stack (enter -1 to stop):"); int num; while (true) { num = scanner.nextInt(); if (num == -1) break; intStackArray.push(num); } System.out.println("Enter integers to push into the linked list stack (enter -1 to stop):"); while (true) { num = scanner.nextInt(); if (num == -1) break; intStackLinkedList.push(num); } System.out.println("Popping from array stack:"); while (!intStackArray.isEmpty()) { System.out.println(intStackArray.pop()); } System.out.println("Popping from linked list stack:"); while (!intStackLinkedList.isEmpty()) { System.out.println(intStackLinkedList.pop()); } } } ===== b) Implement a Generic queue to deal with Interger, Double and String data using user defined arrays and linked lists. //5b)User-defined Generic Queue import java.util.Scanner; class Node<T> { T data; Node<T> next; public Node(T data) { this.data = data; this.next = null; } } class GenericQueueArray<T> { private T[] queueArray; private int front, rear, size, capacity; @SuppressWarnings("unchecked") public GenericQueueArray(int capacity) { this.capacity = capacity; this.queueArray = (T[]) new Object[capacity]; this.front = 0; this.rear = capacity - 1; this.size = 0; } public void enqueue(T item) { if (isFull()) { System.out.println("Queue is full"); return; } rear = (rear + 1) % capacity; queueArray[rear] = item; size++; } public T dequeue() { if (isEmpty()) { System.out.println("Queue is empty"); return null; } T item = queueArray[front]; front = (front + 1) % capacity; size--; return item; } public boolean isEmpty() { return size == 0; } public boolean isFull() { return size == capacity; } } class GenericQueueLinkedList<T> { private Node<T> front, rear; public GenericQueueLinkedList() { this.front = this.rear = null; } public void enqueue(T item) { Node<T> newNode = new Node<>(item); if (isEmpty()) { front = rear = newNode; } else { rear.next = newNode; rear = newNode; } } public T dequeue() { if (isEmpty()) { System.out.println("Queue is empty"); return null; } T item = front.data; front = front.next; if (front == null) { rear = null; } return item; } public boolean isEmpty() { return front == null; } } public class GQueueExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); GenericQueueArray<Integer> intQueueArray = new GenericQueueArray<>(5); GenericQueueLinkedList<Integer> intQueueLinkedList = new GenericQueueLinkedList<>(); System.out.println("Enter integers to enqueue into the array queue (enter -1 to stop):"); int num; while (true) { num = scanner.nextInt(); if (num == -1) break; intQueueArray.enqueue(num); } System.out.println("Enter integers to enqueue into the linked list queue (enter -1 to stop):"); while (true) { num = scanner.nextInt(); if (num == -1) break; intQueueLinkedList.enqueue(num); } System.out.println("Dequeueing from array queue:"); while (!intQueueArray.isEmpty()) { System.out.println(intQueueArray.dequeue()); } System.out.println("Dequeueing from linked list queue:"); while (!intQueueLinkedList.isEmpty()) { System.out.println(intQueueLinkedList.dequeue()); } } } --------------------------------------------------------------------------------------------------------------------- 6. a) Write a java program to implement Generic stack using Array List Collection class. //6a)generic stack using arraylist class GStack<T> { private int maxSize; private T[] stackArray; private int top; public GStack(int size) { maxSize = size; stackArray = createGenericArray(maxSize); top = -1; } @SuppressWarnings("unchecked") private T[] createGenericArray(int size) { return (T[]) new Object[size]; } public void push(T element) { if (isFull()) { throw new StackOverflowError("Stack is full"); } stackArray[++top] = element; } public T pop() { if (isEmpty()) { throw new IllegalStateException("Stack is empty"); } return stackArray[top--]; } public T peek() { if (isEmpty()) { throw new IllegalStateException("Stack is empty"); } return stackArray[top]; } public boolean isEmpty() { return top == -1; } public boolean isFull() { return top == maxSize - 1; } } public class GStackArray { public static void main(String[] args) { GStack<Integer> intStack = new GStack<>(5); intStack.push(10); intStack.push(20); intStack.push(30); int poppedInt = intStack.pop(); System.out.println("Popped integer: " + poppedInt); int topInt = intStack.peek(); System.out.println("Top integer: " + topInt); boolean isIntStackEmpty = intStack.isEmpty(); System.out.println("Is stack of integers empty? " + isIntStackEmpty); boolean isIntStackFull = intStack.isFull(); System.out.println("Is stack of integers full? " + isIntStackFull); GStack<String> stringStack = new GStack<>(3); stringStack.push("Hello"); stringStack.push("World"); String poppedString = stringStack.pop(); System.out.println("Popped string: " + poppedString); String topString = stringStack.peek(); System.out.println("Top string: " + topString); boolean isStringStackEmpty = stringStack.isEmpty(); System.out.println("Is stack of strings empty? " + isStringStackEmpty); boolean isStringStackFull = stringStack.isFull(); System.out.println("Is stack of strings full? " + isStringStackFull); } } --------------------------------------------------------------------------------------------------------------------- 6.b) Write a java program to implement Generic stack using LinkedList Collection class. //6b)generic stack using linked list import java.util.LinkedList; class GStack<T> { private LinkedList<T> stack; public GStack() { stack = new LinkedList<>(); } public void push(T element) { stack.addLast(element); } public T pop() { if (isEmpty()) { throw new IllegalStateException("Stack is empty"); } return stack.removeLast(); } public T peek() { if (isEmpty()) { throw new IllegalStateException("Stack is empty"); } return stack.getLast(); } public boolean isEmpty() { return stack.isEmpty(); } public int size() { return stack.size(); } } public class GStackLinkedList { public static void main(String[] args) { GStack<Integer> intStack = new GStack<>(); intStack.push(10); intStack.push(20); intStack.push(30); int poppedInt = intStack.pop(); System.out.println("Popped integer: " + poppedInt); int topInt = intStack.peek(); System.out.println("Top integer: " + topInt); boolean isIntStackEmpty = intStack.isEmpty(); System.out.println("Is stack of integers empty? " + isIntStackEmpty); GStack<String> stringStack = new GStack<>(); stringStack.push("Hello"); stringStack.push("World"); String poppedString = stringStack.pop(); System.out.println("Popped string: " + poppedString); String topString = stringStack.peek(); System.out.println("Top string: " + topString); boolean isStringStackEmpty = stringStack.isEmpty(); System.out.println("Is stack of strings empty? " + isStringStackEmpty); } } 7.a) Write a Java program to implement Generic queue using ArrayList Collection class. //7a)generic queue using arraylist import java.util.ArrayList; class GenericQueue<T> { private ArrayList<T> queue; public GenericQueue() { queue = new ArrayList<>(); } public void enqueue(T element) { queue.add(element); } public T dequeue() { if (isEmpty()) { throw new IllegalStateException("Queue is empty"); } return queue.remove(0); } public T peek() { if (isEmpty()) { throw new IllegalStateException("Queue is empty"); } return queue.get(0); } public boolean isEmpty() { return queue.isEmpty(); } public int size() { return queue.size(); } } public class GenericQueueExample { public static void main(String[] args) { GenericQueue<Integer> intQueue = new GenericQueue<>(); intQueue.enqueue(10); intQueue.enqueue(20); intQueue.enqueue(30); System.out.println("Dequeued element: " + intQueue.dequeue()); System.out.println("Peeked element: " + intQueue.peek()); System.out.println("Queue size: " + intQueue.size()); GenericQueue<String> stringQueue = new GenericQueue<>(); stringQueue.enqueue("Hello"); stringQueue.enqueue("World"); System.out.println("\nDequeued element: " + stringQueue.dequeue()); System.out.println("Peeked element: " + stringQueue.peek()); System.out.println("Queue size: " + stringQueue.size()); } } 7.b) Write a java program to implement Generic queue using LinkedList Collection class. //7b)generic queue using arraylist import java.util.LinkedList; class GenericQueue<T> { private LinkedList<T> q; public GenericQueue() { q = new LinkedList<>(); } public void enqueue(T element) { q.add(element); } public T dequeue() { if (isEmpty()) { throw new IllegalStateException("Queue is empty"); } return q.remove(0); } public T peek() { if (isEmpty()) { throw new IllegalStateException("Queue is empty"); } return q.get(0); } public boolean isEmpty() { return q.isEmpty(); } public int size() { return q.size(); } } public class GenericQueueLLExample { public static void main(String[] args) { GenericQueue<Integer> intQueue = new GenericQueue<>(); intQueue.enqueue(10); intQueue.enqueue(20); intQueue.enqueue(30); System.out.println("Dequeued element: " + intQueue.dequeue()); System.out.println("Peeked element: " + intQueue.peek()); System.out.println("Queue size: " + intQueue.size()); GenericQueue<String> stringQueue = new GenericQueue<>(); stringQueue.enqueue("Hello"); stringQueue.enqueue("World"); System.out.println("\nDequeued element: " + stringQueue.dequeue()); System.out.println("Peeked element: " + stringQueue.peek()); System.out.println("Queue size: " + stringQueue.size()); } } --------------------------------------------------------------------------------------------------------------------- 8) Write a java program to demonstrate the use of the following Collection classes. a. HashSet //8a)HashSet import java.util.*; import java.util.HashSet; import java.util.Iterator; class Contact { private String name; private String email; public Contact(String name, String email) { this.name = name; this.email = email; } public String getName() { return name; } public String getEmail() { return email; } @Override public String toString() { return "Contact{" + "name='" + name + '\'' + ", email='" + email + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Contact contact = (Contact) o; return name.equals(contact.name) && email.equals(contact.email); } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + email.hashCode(); return result; } } public class HashSetContactDemo { public static void main(String[] args) { HashSet<Contact> contactSet = new HashSet<>(); contactSet.add(new Contact("John", "john@example.com")); contactSet.add(new Contact("Jane", "jane@example.com")); contactSet.add(new Contact("Alice", "alice@example.com")); System.out.println("HashSet of Contacts:"); for (Contact contact : contactSet) { System.out.println(contact); } // Demonstrate contains method Contact searchContact = new Contact("John", "john@example.com"); System.out.println("Contains 'John'? " + contactSet.contains(searchContact)); // Demonstrate isEmpty method System.out.println("Is the HashSet empty? " + contactSet.isEmpty()); System.out.println("Size of the HashSet: " + contactSet.size()); // Demonstrate remove method contactSet.remove(new Contact("Jane", "jane@example.com")); System.out.println("HashSet after removing 'Jane': " + contactSet); // Adding contacts again for further demonstrations contactSet.add(new Contact("Jane", "jane@example.com")); // Demonstrate iteration using iterator System.out.println("Iteration using Iterator:"); Iterator<Contact> iterator = contactSet.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } // Demonstrate toArray method Object[] array = contactSet.toArray(); System.out.print("HashSet as Array: "); for (Object element : array) { System.out.print(element + " "); } System.out.println(); // Demonstrate hashCode method System.out.println("Hash code of the HashSet: " + contactSet.hashCode()); } } ======= b. Linked List //8b)LinkedHashSet import java.util.LinkedHashSet; import java.util.Iterator; public class LinkedHashSetDemo { public static void main(String[] args) { LinkedHashSet<String> lhs= new LinkedHashSet<>(); lhs.add("Apple"); lhs.add("Banana"); lhs.add("Orange"); lhs.add("Grapes"); lhs.add("Watermelon"); System.out.println("LinkedHashSet: " + lhs); System.out.println("Contains 'Banana'? " + lhs.contains("Banana")); System.out.println("Is the LinkedHashSet empty? " + lhs.isEmpty()); System.out.println("Size of the LinkedHashSet: " + lhs.size()); lhs.remove("Orange"); System.out.println("LinkedHashSet after removing 'Orange': " + lhs); lhs.clear(); System.out.println("LinkedHashSet after clearing: " + lhs); lhs.add("Apple"); lhs.add("Banana"); lhs.add("Orange"); System.out.println("Iteration using Iterator:"); Iterator<String> iterator = lhs.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } Object[] array = lhs.toArray(); System.out.print("LinkedHashSet as Array: "); for (Object element : array) { System.out.print(element + " "); } System.out.println(); System.out.println("Hash code of the LinkedHashSet: " + lhs.hashCode()); } } === c. TreeSet //8c)TreeSet import java.util.TreeSet; import java.util.Iterator; import java.util.TreeSet; import java.util.Iterator; class Employee2 implements Comparable<Employee2> { private String name; private int id; public Employee2(String name, int id) { this.name = name; this.id = id; } public String getName() { return name; } public int getId() { return id; } @Override public int compareTo(Employee2 other) { return Integer.compare(this.id, other.id); } @Override public String toString() { return "Employee{" + "name='" + name + '\'' + ", id=" + id + '}'; } } public class TreeSetEmployeeDemo { public static void main(String[] args) { TreeSet<Employee2> treeSet = new TreeSet<>(); treeSet.add(new Employee2("John", 101)); treeSet.add(new Employee2("Jane", 102)); treeSet.add(new Employee2("Alice", 103)); System.out.println("TreeSet of Employees:"); for (Employee2 employee : treeSet) { System.out.println(employee); } Employee2 searchEmployee = new Employee2("John", 101); System.out.println("Contains 'John'? " + treeSet.contains(searchEmployee)); System.out.println("Is the TreeSet empty? " + treeSet.isEmpty()); System.out.println("Size of the TreeSet: " + treeSet.size()); treeSet.remove(new Employee2("Jane", 102)); System.out.println("TreeSet after removing 'Jane': " + treeSet); treeSet.clear(); System.out.println("TreeSet after clearing: " + treeSet); treeSet.add(new Employee2("John", 101)); treeSet.add(new Employee2("Jane", 102)); System.out.println("Iteration using Iterator:"); Iterator<Employee2> iterator = treeSet.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } Object[] array = treeSet.toArray(); System.out.print("TreeSet as Array: "); for (Object element : array) { System.out.print(element + " "); } System.out.println(); System.out.println("Hash code of the TreeSet: " + treeSet.hashCode()); } }--------------------------------------------------------------------------------------------------------------------- 9. Write a java program to create a class called Person with income,age and name as its members. Read set A of persons from a suer and compute the following sets: i) Set B of persons whose age > 60 ii) Set C of persons whose income < 10000 and iii) B and C 9)Person program import java.util.ArrayList; import java.util.List; import java.util.Scanner; class Person { private String name; private int age; private double income; public Person(String name, int age, double income) { this.name = name; this.age = age; this.income = income; } public String getName() { return name; } public int getAge() { return age; } public double getIncome() { return income; } } public class PersonExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); List<Person> setA = new ArrayList<>(); System.out.print("Enter the number of persons: "); int n = scanner.nextInt(); scanner.nextLine(); // consume newline character for (int i = 0; i < n; i++) { System.out.println("Enter details for person " + (i + 1) + ":"); System.out.print("Name: "); String name = scanner.nextLine(); System.out.print("Age: "); int age = scanner.nextInt(); System.out.print("Income: "); double income = scanner.nextDouble(); scanner.nextLine(); // consume newline character Person person = new Person(name, age, income); setA.add(person); } List<Person> setB = new ArrayList<>(); List<Person> setC = new ArrayList<>(); List<Person> setBC = new ArrayList<>(); for (Person person : setA) { if (person.getAge() > 60) { setB.add(person); } if (person.getIncome() < 10000) { setC.add(person); } if (person.getAge() > 60 && person.getIncome() < 10000) { setBC.add(person); } } System.out.println("Set A: "); for (Person person : setA) { System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome()); } System.out.println("\nSet B (age > 60): "); for (Person person : setB) { System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome()); } System.out.println("\nSet C (income < 10000): "); for (Person person : setC) { System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome()); } System.out.println("\nSet B and C (age > 60 and income < 10000): "); for (Person person : setBC) { System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome()); } } } --------------------------------------------------------------------------------------------------------------------- 10. Write a java program to demonstrate the use of the following Collection classes. a. HashMap //10a)HashMap import java.util.HashMap; import java.util.Map; public class HashMapExample{ public static void main(String[] args) { Map<String, Integer> ageMap = new HashMap<>(); ageMap.put("John", 30); ageMap.put("Alice", 25); ageMap.put("Bob", 35); ageMap.put("Eve", 28); System.out.println("Age of John: " + ageMap.get("John")); System.out.println("Age of Alice: " + ageMap.get("Alice")); ageMap.put("John", 32); System.out.println("Updated age of John: " + ageMap.get("John")); String name = "Bob"; if (ageMap.containsKey(name)) { System.out.println(name + " exists in the map."); } else { System.out.println(name + " does not exist in the map."); } ageMap.remove("Eve"); System.out.println("Map after removing Eve: " + ageMap); System.out.println("Iterating over map entries:"); for (Map.Entry<String, Integer> entry : ageMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } ageMap.clear(); System.out.println("Map after clearing: " + ageMap); } } ===== b.LinkedHashMap //10b)LinkedHashMap import java.util.LinkedHashMap; import java.util.Map; public class LinkedHashMapExample{ public static void main(String[] args) { Map<String, Integer> ageMap = new LinkedHashMap<>(); ageMap.put("John", 30); ageMap.put("Alice", 25); ageMap.put("Bob", 35); ageMap.put("Eve", 28); System.out.println("Age of John: " + ageMap.get("John")); System.out.println("Age of Alice: " + ageMap.get("Alice")); ageMap.put("John", 32); System.out.println("Updated age of John: " + ageMap.get("John")); String name = "Bob"; if (ageMap.containsKey(name)) { System.out.println(name + " exists in the map."); } else { System.out.println(name + " does not exist in the map."); } ageMap.remove("Eve"); System.out.println("Map after removing Eve: " + ageMap); System.out.println("Iterating over map entries:"); for (Map.Entry<String, Integer> entry : ageMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } ageMap.clear(); System.out.println("Map after clearing: " + ageMap); } } ==== c.TreeMap //10c)TreeMap import java.util.TreeMap; import java.util.Map; public class TreeMapExample{ public static void main(String[] args) { Map<String, Integer> ageMap = new TreeMap<>(); ageMap.put("John", 30); ageMap.put("Alice", 25); ageMap.put("Bob", 35); ageMap.put("Eve", 28); System.out.println("Age of John: " + ageMap.get("John")); System.out.println("Age of Alice: " + ageMap.get("Alice")); ageMap.put("John", 32); System.out.println("Updated age of John: " + ageMap.get("John")); String name = "Bob"; if (ageMap.containsKey(name)) { System.out.println(name + " exists in the map."); } else { System.out.println(name + " does not exist in the map."); } ageMap.remove("Eve"); System.out.println("Map after removing Eve: " + ageMap); System.out.println("Iterating over map entries:"); for (Map.Entry<String, Integer> entry : ageMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } ageMap.clear(); System.out.println("Map after clearing: " + ageMap); } } --------------------------------------------------------------------------------------------------------------------- 11. Create a class Product(id,name,price,type,rating) and perform the following operations using stream: i) Find all the products having rating between 4 and 5. ii) Find first n products having price > 10000. iii) Find the number of products under each type(map containing type and count) iv) Find average rating of products woth type = “Electronics”. //11)Product stream import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; class Product { private int id; private String name; private double price; private String type; private double rating; public Product(int id, String name, double price, String type, double rating) { this.id = id; this.name = name; this.price = price; this.type = type; this.rating = rating; } public double getRating() { return rating; } public double getPrice() { return price; } public String getType() { return type; } @Override public String toString() { return "Product{" + "id=" + id + ", name='" + name + '\'' + ", price=" + price + ", type='" + type + '\'' + ", rating=" + rating + '}'; } } public class ProductStreamExample { public static void main(String[] args) { List<Product> products = Arrays.asList( new Product(1, "Laptop", 1500.0, "Electronics", 4.5), new Product(2, "Smartphone", 800.0, "Electronics", 4.2), new Product(3, "Watch", 300.0, "Fashion", 3.8), new Product(4, "Headphones", 100.0, "Electronics", 4.8), new Product(5, "Shoes", 50.0, "Fashion", 3.5), new Product(6, "Camera", 2000.0, "Electronics", 4.7) ); // i) Find all the products having rating between 4 and 5 List<Product> productsRatingBetween4And5 = products.stream() .filter(p -> p.getRating() >= 4 && p.getRating() <= 5) .collect(Collectors.toList()); System.out.println("Products with rating between 4 and 5: " + productsRatingBetween4And5); System.out.println(); // ii) Find first n products having price > 1000 int n = 2; List<Product> firstNProductsPriceGreaterThan1000 = products.stream() .filter(p -> p.getPrice() > 1000) .limit(n) .collect(Collectors.toList()); System.out.println("First " + n + " products with price > 1000: " + firstNProductsPriceGreaterThan1000); System.out.println(); // iii) Find the number of products under each type (map containing type and count) Map<String, Long> productCountByType = products.stream() .collect(Collectors.groupingBy(Product::getType, Collectors.counting())); System.out.println("Number of products under each type: " + productCountByType); System.out.println(); // iv) Find average rating of products with type = "Electronics" double averageRatingElectronics = products.stream() .filter(p -> p.getType().equals("Electronics")) .mapToDouble(Product::getRating) .average() .orElse(0.0); System.out.println("Average rating of products with type 'Electronics': " + averageRatingElectronics); } } -------------------------------------------------------------------------------------------------------------------12. Write a Java program to implement Sorted Chain. //12)Sorted Chain class Node<T extends Comparable<T>> { T data; Node<T> next; public Node(T data) { this.data = data; this.next = null; } } public class SortedChain<T extends Comparable<T>> { private Node<T> head; public void insert(T data) { Node<T> newNode = new Node<>(data); if (head == null || head.data.compareTo(data) >= 0) { newNode.next = head; head = newNode; } else { Node<T> current = head; while (current.next != null && current.next.data.compareTo(data) < 0) { current = current.next; } newNode.next = current.next; current.next = newNode; } } public void display() { Node<T> current = head; while (current != null) { System.out.print(current.data + " "); current = current.next; } System.out.println(); } public static void main(String[] args) { SortedChain<Integer> sortedChain = new SortedChain<>(); sortedChain.insert(5); sortedChain.insert(3); sortedChain.insert(7); sortedChain.insert(1); sortedChain.insert(9); System.out.println("Sorted Chain:"); sortedChain.display(); } } --------------------------------------------------------------------------------------------------------------------- 13. Write a java program to implement Separate Chaining //13)SeparateChaining import java.util.LinkedList; class KeyValuePair<K, V> { private K key; private V value; public KeyValuePair(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; } } class SeparateChaining<K, V> { private LinkedList<KeyValuePair<K, V>>[] table; private int capacity; @SuppressWarnings("unchecked") public SeparateChaining(int capacity) { this.capacity = capacity; this.table = new LinkedList[capacity]; for (int i = 0; i < capacity; i++) { table[i] = new LinkedList<>(); } } private int hash(K key) { return Math.abs(key.hashCode() % capacity); } public void put(K key, V value) { int index = hash(key); LinkedList<KeyValuePair<K, V>> list = table[index]; for (KeyValuePair<K, V> pair : list) { if (pair.getKey().equals(key)) { pair = new KeyValuePair<>(key, value); return; } } list.add(new KeyValuePair<>(key, value)); } public V get(K key) { int index = hash(key); LinkedList<KeyValuePair<K, V>> list = table[index]; for (KeyValuePair<K, V> pair : list) { if (pair.getKey().equals(key)) { return pair.getValue(); } } return null; } public void remove(K key) { int index = hash(key); LinkedList<KeyValuePair<K, V>> list = table[index]; for (KeyValuePair<K, V> pair : list) { if (pair.getKey().equals(key)) { list.remove(pair); return; } } } } public class SeparateChainingExample { public static void main(String[] args) { SeparateChaining<String, Integer> map = new SeparateChaining<>(5); map.put("John", 25); map.put("Alice", 30); map.put("Bob", 35); System.out.println("Alice's age: " + map.get("Alice")); System.out.println("Bob's age: " + map.get("Bob")); map.remove("Alice"); System.out.println("Alice's age after removal: " + map.get("Alice")); } } --------------------------------------------------------------------------------------------------------------------- 14. Write a java program to implement Linear Probing. //14)LinearProbing public class LinearProbingHashTable { private String[] keys; private String[] values; private int size; private int capacity; public LinearProbingHashTable(int capacity) { this.capacity = capacity; this.keys = new String[capacity]; this.values = new String[capacity]; this.size = 0; } private int hash(String key) { return key.length() % capacity; } public void put(String key, String value) { if (key == null || value == null) { throw new IllegalArgumentException("Key or value cannot be null."); } int index = hash(key); while (keys[index] != null) { if (keys[index].equals(key)) { values[index] = value; return; } index = (index + 1) % capacity; } keys[index] = key; values[index] = value; size++; } public String get(String key) { int index = hash(key); while (keys[index] != null) { if (keys[index].equals(key)) { return values[index]; } index = (index + 1) % capacity; } return null; } public void display() { for (int i = 0; i < capacity; i++) { if (keys[i] != null) { System.out.println("Key: " + keys[i] + ", Value: " + values[i]); } } } public static void main(String[] args) { LinearProbingHashTable hashTable = new LinearProbingHashTable(10); hashTable.put("John", "Doe"); hashTable.put("Alice", "Smith"); hashTable.put("Bob", "Johnson"); hashTable.put("Charlie", "Brown"); hashTable.display(); System.out.println("Value associated with 'John': " + hashTable.get("John")); System.out.println("Value associated with 'Alice': " + hashTable.get("Alice")); System.out.println("Value associated with 'Bob': " + hashTable.get("Bob")); System.out.println("Value associated with 'Charlie': " + hashTable.get("Charlie")); System.out.println("Value associated with 'Dave': " + hashTable.get("Dave")); // Not found } } 15. Implement BST using Collection API, and use recursive procedures to implement inOrder, preorder and postOrder traversals. //15)BinarySearchTree import java.util.LinkedList; class TreeNode<T extends Comparable<T>> { T data; TreeNode<T> left, right; public TreeNode(T data) { this.data = data; this.left = null; this.right = null; } } public class BinarySearchTree<T extends Comparable<T>> { private TreeNode<T> root; public BinarySearchTree() { this.root = null; } public void insert(T data) { root = insertRec(root, data); } private TreeNode<T> insertRec(TreeNode<T> root, T data) { if (root == null) { root = new TreeNode<>(data); return root; } if (data.compareTo(root.data) < 0) { root.left = insertRec(root.left, data); } else if (data.compareTo(root.data) > 0) { root.right = insertRec(root.right, data); } return root; } public void inorderTraversal() { inorderTraversalRec(root); } private void inorderTraversalRec(TreeNode<T> root) { if (root != null) { inorderTraversalRec(root.left); System.out.print(root.data + " "); inorderTraversalRec(root.right); } } public void preorderTraversal() { preorderTraversalRec(root); } private void preorderTraversalRec(TreeNode<T> root) { if (root != null) { System.out.print(root.data + " "); preorderTraversalRec(root.left); preorderTraversalRec(root.right); } } public void postorderTraversal() { postorderTraversalRec(root); } private void postorderTraversalRec(TreeNode<T> root) { if (root != null) { postorderTraversalRec(root.left); postorderTraversalRec(root.right); System.out.print(root.data + " "); } } public void delete(T data) { root = deleteRec(root, data); } private TreeNode<T> deleteRec(TreeNode<T> root, T data) { if (root == null) return root; if (data.compareTo(root.data) < 0) { root.left = deleteRec(root.left, data); } else if (data.compareTo(root.data) > 0) { root.right = deleteRec(root.right, data); } else { if (root.left == null) return root.right; else if (root.right == null) return root.left; root.data = minValue(root.right); root.right = deleteRec(root.right, root.data); } return root; } private T minValue(TreeNode<T> root) { T minv = root.data; while (root.left != null) { minv = root.left.data; root = root.left; } return minv; } public static void main(String[] args) { BinarySearchTree<Integer> bst = new BinarySearchTree<>(); bst.insert(50); bst.insert(30); bst.insert(20); bst.insert(40); bst.insert(70); bst.insert(60); bst.insert(80); System.out.println("Inorder traversal:"); bst.inorderTraversal(); System.out.println("\nPreorder traversal:"); bst.preorderTraversal(); System.out.println("\nPostorder traversal:"); bst.postorderTraversal(); System.out.println("\nDeleting 20:"); bst.delete(20); System.out.println("Inorder traversal after deletion:"); bst.inorderTraversal(); } } 16. Implement AVL tree using Collection API. //16)AVL TRee import java.util.Comparator; class AVLNode<T extends Comparable<T>> { T data; AVLNode<T> left, right; int height; public AVLNode(T data) { this.data = data; this.left = null; this.right = null; this.height = 1; } } public class AVLTree<T extends Comparable<T>> { private AVLNode<T> root; public AVLTree() { this.root = null; } private int height(AVLNode<T> node) { if (node == null) return 0; return node.height; } private int getBalance(AVLNode<T> node) { if (node == null) return 0; return height(node.left) - height(node.right); } public AVLNode<T> insert(AVLNode<T> node, T data) { if (node == null) return new AVLNode<>(data); if (data.compareTo(node.data) < 0) { node.left = insert(node.left, data); } else if (data.compareTo(node.data) > 0) { node.right = insert(node.right, data); } else { return node; // Duplicate keys not allowed } // Update height of this ancestor node node.height = 1 + Math.max(height(node.left), height(node.right)); // Get the balance factor and perform rotation if needed int balance = getBalance(node); // Left Left Case if (balance > 1 && data.compareTo(node.left.data) < 0) { return rightRotate(node); } // Right Right Case if (balance < -1 && data.compareTo(node.right.data) > 0) { return leftRotate(node); } // Left Right Case if (balance > 1 && data.compareTo(node.left.data) > 0) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && data.compareTo(node.right.data) < 0) { node.right = rightRotate(node.right); return leftRotate(node); } return node; } private AVLNode<T> rightRotate(AVLNode<T> y) { AVLNode<T> x = y.left; AVLNode<T> T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = Math.max(height(y.left), height(y.right)) + 1; x.height = Math.max(height(x.left), height(x.right)) + 1; return x; } private AVLNode<T> leftRotate(AVLNode<T> x) { AVLNode<T> y = x.right; AVLNode<T> T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = Math.max(height(x.left), height(x.right)) + 1; y.height = Math.max(height(y.left), height(y.right)) + 1; return y; } public void insert(T data) { root = insert(root, data); } public void inorderTraversal() { inorderTraversal(root); System.out.println(); } private void inorderTraversal(AVLNode<T> node) { if (node != null) { inorderTraversal(node.left); System.out.print(node.data + " "); inorderTraversal(node.right); } } public static void main(String[] args) { AVLTree<Integer> avlTree = new AVLTree<>(); avlTree.insert(10); avlTree.insert(20); avlTree.insert(30); avlTree.insert(40); avlTree.insert(50); avlTree.insert(25); System.out.println("Inorder traversal:"); avlTree.inorderTraversal(); } }
Write a java program to demonstrate the use of bounded type parameters and wild cards arguments. //BoundedType public class BoundedArithematic<T extends Number> { public double add(T a, T b) { return a.doubleValue() + b.doubleValue(); } public double subtract(T a, T b) { return a.doubleValue() - b.doubleValue(); } public double multiply(T a, T b) { return a.doubleValue() * b.doubleValue(); } public double divide(T a, T b) { if (b.doubleValue() == 0) { throw new ArithmeticException("Division by zero is not allowed."); } return a.doubleValue() / b.doubleValue(); } public static void main(String[] args) { BoundedArithematic<Number> calculator = new BoundedArithematic<>(); Integer a = 10; Integer b = 5; System.out.println("Addition: " + calculator.add(a, b)); System.out.println("Subtraction: " + calculator.subtract(a, b)); System.out.println("Multiplication: " + calculator.multiply(a, b)); System.out.println("Division: " + calculator.divide(a, b)); } } == //Wildcard Arguments public class MagicBox<T> { private T item; public void addItem(T item) { this.item = item; System.out.println("Added item to the magic box: " + item); } public T getItem() { return item; } public void processBox(MagicBox<? super Integer> box) { System.out.println("Items in the box are processed["+box.getItem()+"]"); } public static void main(String[] args) { MagicBox<Integer> integerBox = new MagicBox<>(); integerBox.addItem(43); MagicBox<String> stringBox = new MagicBox<>(); stringBox.addItem("Sofiya"); MagicBox<Boolean> booleanBox = new MagicBox<>(); booleanBox.addItem(false); MagicBox<Object> dobubleBox = new MagicBox<>(); dobubleBox.addItem(43.43); integerBox.processBox(integerBox); dobubleBox.processBox(dobubleBox); } } --------------------------------------------------------------------------------------------------------------------- 2.Write a java program that returns the value of pi using the lambda expression. public class PiLambdaExpression{ @FunctionalInterface interface PiValue{ double getPi(); } public static void main(String[] args) { PiValue pi = () -> Math.PI; double p= pi.getPi(); System.out.println("The value of Pi is: " + p); } } --------------------------------------------------------------------------------------------------------------------- 3. Write a java program that takes a string as parameter and calculates the reverse of the string using lambda expression. //ReverseStringLambda public class ReverseStringLambda { @FunctionalInterface interface StringReverser { String reverse(String str); } public static void main(String[] args) { StringReverser reverser = (str) -> new StringBuilder(str).reverse().toString(); String example = "Hello, World!"; String reversed = reverser.reverse(example); System.out.println("Original: " + example); System.out.println("Reversed: " + reversed); } } --------------------------------------------------------------------------------------------------------------------- 4. Write a java program to implement iterators on Array List and Linked List. //ArrayList import java.util.ArrayList; import java.util.Iterator; public class ArrayListIteratorExample { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); Iterator<String> iterator = fruits.iterator(); System.out.println("Using Iterator to traverse through the ArrayList:"); while (iterator.hasNext()) { String fruit = iterator.next(); System.out.println(fruit); } System.out.println("\nUsing for-each loop to traverse through the ArrayList:"); for (String fruit : fruits) { System.out.println(fruit); } iterator = fruits.iterator(); // Reset the iterator while (iterator.hasNext()) { String fruit = iterator.next(); if (fruit.startsWith("B")) { iterator.remove(); // Remove elements that start with "B" } } System.out.println("\nArrayList after removal of elements that start with 'B':"); for (String fruit : fruits) { System.out.println(fruit); } } } == //4.ALinkedList import java.util.LinkedList; import java.util.Iterator; public class LinkedListIteratorExample { public static void main(String[] args) { LinkedList<String> fruits = new LinkedList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); Iterator<String> iterator = fruits.iterator(); System.out.println("Using Iterator to traverse through the LinkedList:"); while (iterator.hasNext()) { String fruit = iterator.next(); System.out.println(fruit); } System.out.println("\nUsing for-each loop to traverse through the LinkedList:"); for (String fruit : fruits) { System.out.println(fruit); } iterator = fruits.iterator(); // Reset the iterator while (iterator.hasNext()) { String fruit = iterator.next(); if (fruit.startsWith("B")) { iterator.remove(); } } System.out.println("\nLinkedList after removal of elements that start with 'B':"); for (String fruit : fruits) { System.out.println(fruit); } } } --------------------------------------------------------------------------------------------------------------------- 5.a) Implement a Generic stack to deal with Integer, Double and String data using user defined arrays and linked lists. //5a)user-defined generic stack import java.util.Scanner; class Node<T> { T data; Node<T> next; public Node(T data) { this.data = data; this.next = null; } } class GenericStackArray<T> { private T[] stackArray; private int top; private int maxSize; @SuppressWarnings("unchecked") public GenericStackArray(int size) { this.maxSize = size; this.stackArray = (T[]) new Object[maxSize]; this.top = -1; } public void push(T item) { if (top < maxSize - 1) { stackArray[++top] = item; } else { System.out.println("Stack Overflow"); } } public T pop() { if (top >= 0) { return stackArray[top--]; } else { System.out.println("Stack Underflow"); return null; } } public boolean isEmpty() { return top == -1; } } class GenericStackLinkedList<T> { private Node<T> top; public GenericStackLinkedList() { this.top = null; } public void push(T item) { Node<T> newNode = new Node<>(item); newNode.next = top; top = newNode; } public T pop() { if (top == null) { System.out.println("Stack Underflow"); return null; } T data = top.data; top = top.next; return data; } public boolean isEmpty() { return top == null; } } public class GenericStackExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); GenericStackArray<Integer> intStackArray = new GenericStackArray<>(5); GenericStackLinkedList<Integer> intStackLinkedList = new GenericStackLinkedList<>(); System.out.println("Enter integers to push into the array stack (enter -1 to stop):"); int num; while (true) { num = scanner.nextInt(); if (num == -1) break; intStackArray.push(num); } System.out.println("Enter integers to push into the linked list stack (enter -1 to stop):"); while (true) { num = scanner.nextInt(); if (num == -1) break; intStackLinkedList.push(num); } System.out.println("Popping from array stack:"); while (!intStackArray.isEmpty()) { System.out.println(intStackArray.pop()); } System.out.println("Popping from linked list stack:"); while (!intStackLinkedList.isEmpty()) { System.out.println(intStackLinkedList.pop()); } } } ===== b) Implement a Generic queue to deal with Interger, Double and String data using user defined arrays and linked lists. //5b)User-defined Generic Queue import java.util.Scanner; class Node<T> { T data; Node<T> next; public Node(T data) { this.data = data; this.next = null; } } class GenericQueueArray<T> { private T[] queueArray; private int front, rear, size, capacity; @SuppressWarnings("unchecked") public GenericQueueArray(int capacity) { this.capacity = capacity; this.queueArray = (T[]) new Object[capacity]; this.front = 0; this.rear = capacity - 1; this.size = 0; } public void enqueue(T item) { if (isFull()) { System.out.println("Queue is full"); return; } rear = (rear + 1) % capacity; queueArray[rear] = item; size++; } public T dequeue() { if (isEmpty()) { System.out.println("Queue is empty"); return null; } T item = queueArray[front]; front = (front + 1) % capacity; size--; return item; } public boolean isEmpty() { return size == 0; } public boolean isFull() { return size == capacity; } } class GenericQueueLinkedList<T> { private Node<T> front, rear; public GenericQueueLinkedList() { this.front = this.rear = null; } public void enqueue(T item) { Node<T> newNode = new Node<>(item); if (isEmpty()) { front = rear = newNode; } else { rear.next = newNode; rear = newNode; } } public T dequeue() { if (isEmpty()) { System.out.println("Queue is empty"); return null; } T item = front.data; front = front.next; if (front == null) { rear = null; } return item; } public boolean isEmpty() { return front == null; } } public class GQueueExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); GenericQueueArray<Integer> intQueueArray = new GenericQueueArray<>(5); GenericQueueLinkedList<Integer> intQueueLinkedList = new GenericQueueLinkedList<>(); System.out.println("Enter integers to enqueue into the array queue (enter -1 to stop):"); int num; while (true) { num = scanner.nextInt(); if (num == -1) break; intQueueArray.enqueue(num); } System.out.println("Enter integers to enqueue into the linked list queue (enter -1 to stop):"); while (true) { num = scanner.nextInt(); if (num == -1) break; intQueueLinkedList.enqueue(num); } System.out.println("Dequeueing from array queue:"); while (!intQueueArray.isEmpty()) { System.out.println(intQueueArray.dequeue()); } System.out.println("Dequeueing from linked list queue:"); while (!intQueueLinkedList.isEmpty()) { System.out.println(intQueueLinkedList.dequeue()); } } } --------------------------------------------------------------------------------------------------------------------- 6. a) Write a java program to implement Generic stack using Array List Collection class. //6a)generic stack using arraylist class GStack<T> { private int maxSize; private T[] stackArray; private int top; public GStack(int size) { maxSize = size; stackArray = createGenericArray(maxSize); top = -1; } @SuppressWarnings("unchecked") private T[] createGenericArray(int size) { return (T[]) new Object[size]; } public void push(T element) { if (isFull()) { throw new StackOverflowError("Stack is full"); } stackArray[++top] = element; } public T pop() { if (isEmpty()) { throw new IllegalStateException("Stack is empty"); } return stackArray[top--]; } public T peek() { if (isEmpty()) { throw new IllegalStateException("Stack is empty"); } return stackArray[top]; } public boolean isEmpty() { return top == -1; } public boolean isFull() { return top == maxSize - 1; } } public class GStackArray { public static void main(String[] args) { GStack<Integer> intStack = new GStack<>(5); intStack.push(10); intStack.push(20); intStack.push(30); int poppedInt = intStack.pop(); System.out.println("Popped integer: " + poppedInt); int topInt = intStack.peek(); System.out.println("Top integer: " + topInt); boolean isIntStackEmpty = intStack.isEmpty(); System.out.println("Is stack of integers empty? " + isIntStackEmpty); boolean isIntStackFull = intStack.isFull(); System.out.println("Is stack of integers full? " + isIntStackFull); GStack<String> stringStack = new GStack<>(3); stringStack.push("Hello"); stringStack.push("World"); String poppedString = stringStack.pop(); System.out.println("Popped string: " + poppedString); String topString = stringStack.peek(); System.out.println("Top string: " + topString); boolean isStringStackEmpty = stringStack.isEmpty(); System.out.println("Is stack of strings empty? " + isStringStackEmpty); boolean isStringStackFull = stringStack.isFull(); System.out.println("Is stack of strings full? " + isStringStackFull); } } --------------------------------------------------------------------------------------------------------------------- 6.b) Write a java program to implement Generic stack using LinkedList Collection class. //6b)generic stack using linked list import java.util.LinkedList; class GStack<T> { private LinkedList<T> stack; public GStack() { stack = new LinkedList<>(); } public void push(T element) { stack.addLast(element); } public T pop() { if (isEmpty()) { throw new IllegalStateException("Stack is empty"); } return stack.removeLast(); } public T peek() { if (isEmpty()) { throw new IllegalStateException("Stack is empty"); } return stack.getLast(); } public boolean isEmpty() { return stack.isEmpty(); } public int size() { return stack.size(); } } public class GStackLinkedList { public static void main(String[] args) { GStack<Integer> intStack = new GStack<>(); intStack.push(10); intStack.push(20); intStack.push(30); int poppedInt = intStack.pop(); System.out.println("Popped integer: " + poppedInt); int topInt = intStack.peek(); System.out.println("Top integer: " + topInt); boolean isIntStackEmpty = intStack.isEmpty(); System.out.println("Is stack of integers empty? " + isIntStackEmpty); GStack<String> stringStack = new GStack<>(); stringStack.push("Hello"); stringStack.push("World"); String poppedString = stringStack.pop(); System.out.println("Popped string: " + poppedString); String topString = stringStack.peek(); System.out.println("Top string: " + topString); boolean isStringStackEmpty = stringStack.isEmpty(); System.out.println("Is stack of strings empty? " + isStringStackEmpty); } } 7.a) Write a Java program to implement Generic queue using ArrayList Collection class. //7a)generic queue using arraylist import java.util.ArrayList; class GenericQueue<T> { private ArrayList<T> queue; public GenericQueue() { queue = new ArrayList<>(); } public void enqueue(T element) { queue.add(element); } public T dequeue() { if (isEmpty()) { throw new IllegalStateException("Queue is empty"); } return queue.remove(0); } public T peek() { if (isEmpty()) { throw new IllegalStateException("Queue is empty"); } return queue.get(0); } public boolean isEmpty() { return queue.isEmpty(); } public int size() { return queue.size(); } } public class GenericQueueExample { public static void main(String[] args) { GenericQueue<Integer> intQueue = new GenericQueue<>(); intQueue.enqueue(10); intQueue.enqueue(20); intQueue.enqueue(30); System.out.println("Dequeued element: " + intQueue.dequeue()); System.out.println("Peeked element: " + intQueue.peek()); System.out.println("Queue size: " + intQueue.size()); GenericQueue<String> stringQueue = new GenericQueue<>(); stringQueue.enqueue("Hello"); stringQueue.enqueue("World"); System.out.println("\nDequeued element: " + stringQueue.dequeue()); System.out.println("Peeked element: " + stringQueue.peek()); System.out.println("Queue size: " + stringQueue.size()); } } 7.b) Write a java program to implement Generic queue using LinkedList Collection class. //7b)generic queue using arraylist import java.util.LinkedList; class GenericQueue<T> { private LinkedList<T> q; public GenericQueue() { q = new LinkedList<>(); } public void enqueue(T element) { q.add(element); } public T dequeue() { if (isEmpty()) { throw new IllegalStateException("Queue is empty"); } return q.remove(0); } public T peek() { if (isEmpty()) { throw new IllegalStateException("Queue is empty"); } return q.get(0); } public boolean isEmpty() { return q.isEmpty(); } public int size() { return q.size(); } } public class GenericQueueLLExample { public static void main(String[] args) { GenericQueue<Integer> intQueue = new GenericQueue<>(); intQueue.enqueue(10); intQueue.enqueue(20); intQueue.enqueue(30); System.out.println("Dequeued element: " + intQueue.dequeue()); System.out.println("Peeked element: " + intQueue.peek()); System.out.println("Queue size: " + intQueue.size()); GenericQueue<String> stringQueue = new GenericQueue<>(); stringQueue.enqueue("Hello"); stringQueue.enqueue("World"); System.out.println("\nDequeued element: " + stringQueue.dequeue()); System.out.println("Peeked element: " + stringQueue.peek()); System.out.println("Queue size: " + stringQueue.size()); } } --------------------------------------------------------------------------------------------------------------------- 8) Write a java program to demonstrate the use of the following Collection classes. a. HashSet //8a)HashSet import java.util.*; import java.util.HashSet; import java.util.Iterator; class Contact { private String name; private String email; public Contact(String name, String email) { this.name = name; this.email = email; } public String getName() { return name; } public String getEmail() { return email; } @Override public String toString() { return "Contact{" + "name='" + name + '\'' + ", email='" + email + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Contact contact = (Contact) o; return name.equals(contact.name) && email.equals(contact.email); } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + email.hashCode(); return result; } } public class HashSetContactDemo { public static void main(String[] args) { HashSet<Contact> contactSet = new HashSet<>(); contactSet.add(new Contact("John", "john@example.com")); contactSet.add(new Contact("Jane", "jane@example.com")); contactSet.add(new Contact("Alice", "alice@example.com")); System.out.println("HashSet of Contacts:"); for (Contact contact : contactSet) { System.out.println(contact); } // Demonstrate contains method Contact searchContact = new Contact("John", "john@example.com"); System.out.println("Contains 'John'? " + contactSet.contains(searchContact)); // Demonstrate isEmpty method System.out.println("Is the HashSet empty? " + contactSet.isEmpty()); System.out.println("Size of the HashSet: " + contactSet.size()); // Demonstrate remove method contactSet.remove(new Contact("Jane", "jane@example.com")); System.out.println("HashSet after removing 'Jane': " + contactSet); // Adding contacts again for further demonstrations contactSet.add(new Contact("Jane", "jane@example.com")); // Demonstrate iteration using iterator System.out.println("Iteration using Iterator:"); Iterator<Contact> iterator = contactSet.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } // Demonstrate toArray method Object[] array = contactSet.toArray(); System.out.print("HashSet as Array: "); for (Object element : array) { System.out.print(element + " "); } System.out.println(); // Demonstrate hashCode method System.out.println("Hash code of the HashSet: " + contactSet.hashCode()); } } ======= b. Linked List //8b)LinkedHashSet import java.util.LinkedHashSet; import java.util.Iterator; public class LinkedHashSetDemo { public static void main(String[] args) { LinkedHashSet<String> lhs= new LinkedHashSet<>(); lhs.add("Apple"); lhs.add("Banana"); lhs.add("Orange"); lhs.add("Grapes"); lhs.add("Watermelon"); System.out.println("LinkedHashSet: " + lhs); System.out.println("Contains 'Banana'? " + lhs.contains("Banana")); System.out.println("Is the LinkedHashSet empty? " + lhs.isEmpty()); System.out.println("Size of the LinkedHashSet: " + lhs.size()); lhs.remove("Orange"); System.out.println("LinkedHashSet after removing 'Orange': " + lhs); lhs.clear(); System.out.println("LinkedHashSet after clearing: " + lhs); lhs.add("Apple"); lhs.add("Banana"); lhs.add("Orange"); System.out.println("Iteration using Iterator:"); Iterator<String> iterator = lhs.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } Object[] array = lhs.toArray(); System.out.print("LinkedHashSet as Array: "); for (Object element : array) { System.out.print(element + " "); } System.out.println(); System.out.println("Hash code of the LinkedHashSet: " + lhs.hashCode()); } } === c. TreeSet //8c)TreeSet import java.util.TreeSet; import java.util.Iterator; import java.util.TreeSet; import java.util.Iterator; class Employee2 implements Comparable<Employee2> { private String name; private int id; public Employee2(String name, int id) { this.name = name; this.id = id; } public String getName() { return name; } public int getId() { return id; } @Override public int compareTo(Employee2 other) { return Integer.compare(this.id, other.id); } @Override public String toString() { return "Employee{" + "name='" + name + '\'' + ", id=" + id + '}'; } } public class TreeSetEmployeeDemo { public static void main(String[] args) { TreeSet<Employee2> treeSet = new TreeSet<>(); treeSet.add(new Employee2("John", 101)); treeSet.add(new Employee2("Jane", 102)); treeSet.add(new Employee2("Alice", 103)); System.out.println("TreeSet of Employees:"); for (Employee2 employee : treeSet) { System.out.println(employee); } Employee2 searchEmployee = new Employee2("John", 101); System.out.println("Contains 'John'? " + treeSet.contains(searchEmployee)); System.out.println("Is the TreeSet empty? " + treeSet.isEmpty()); System.out.println("Size of the TreeSet: " + treeSet.size()); treeSet.remove(new Employee2("Jane", 102)); System.out.println("TreeSet after removing 'Jane': " + treeSet); treeSet.clear(); System.out.println("TreeSet after clearing: " + treeSet); treeSet.add(new Employee2("John", 101)); treeSet.add(new Employee2("Jane", 102)); System.out.println("Iteration using Iterator:"); Iterator<Employee2> iterator = treeSet.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } Object[] array = treeSet.toArray(); System.out.print("TreeSet as Array: "); for (Object element : array) { System.out.print(element + " "); } System.out.println(); System.out.println("Hash code of the TreeSet: " + treeSet.hashCode()); } }--------------------------------------------------------------------------------------------------------------------- 9. Write a java program to create a class called Person with income,age and name as its members. Read set A of persons from a suer and compute the following sets: i) Set B of persons whose age > 60 ii) Set C of persons whose income < 10000 and iii) B and C 9)Person program import java.util.ArrayList; import java.util.List; import java.util.Scanner; class Person { private String name; private int age; private double income; public Person(String name, int age, double income) { this.name = name; this.age = age; this.income = income; } public String getName() { return name; } public int getAge() { return age; } public double getIncome() { return income; } } public class PersonExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); List<Person> setA = new ArrayList<>(); System.out.print("Enter the number of persons: "); int n = scanner.nextInt(); scanner.nextLine(); // consume newline character for (int i = 0; i < n; i++) { System.out.println("Enter details for person " + (i + 1) + ":"); System.out.print("Name: "); String name = scanner.nextLine(); System.out.print("Age: "); int age = scanner.nextInt(); System.out.print("Income: "); double income = scanner.nextDouble(); scanner.nextLine(); // consume newline character Person person = new Person(name, age, income); setA.add(person); } List<Person> setB = new ArrayList<>(); List<Person> setC = new ArrayList<>(); List<Person> setBC = new ArrayList<>(); for (Person person : setA) { if (person.getAge() > 60) { setB.add(person); } if (person.getIncome() < 10000) { setC.add(person); } if (person.getAge() > 60 && person.getIncome() < 10000) { setBC.add(person); } } System.out.println("Set A: "); for (Person person : setA) { System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome()); } System.out.println("\nSet B (age > 60): "); for (Person person : setB) { System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome()); } System.out.println("\nSet C (income < 10000): "); for (Person person : setC) { System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome()); } System.out.println("\nSet B and C (age > 60 and income < 10000): "); for (Person person : setBC) { System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome()); } } } --------------------------------------------------------------------------------------------------------------------- 10. Write a java program to demonstrate the use of the following Collection classes. a. HashMap //10a)HashMap import java.util.HashMap; import java.util.Map; public class HashMapExample{ public static void main(String[] args) { Map<String, Integer> ageMap = new HashMap<>(); ageMap.put("John", 30); ageMap.put("Alice", 25); ageMap.put("Bob", 35); ageMap.put("Eve", 28); System.out.println("Age of John: " + ageMap.get("John")); System.out.println("Age of Alice: " + ageMap.get("Alice")); ageMap.put("John", 32); System.out.println("Updated age of John: " + ageMap.get("John")); String name = "Bob"; if (ageMap.containsKey(name)) { System.out.println(name + " exists in the map."); } else { System.out.println(name + " does not exist in the map."); } ageMap.remove("Eve"); System.out.println("Map after removing Eve: " + ageMap); System.out.println("Iterating over map entries:"); for (Map.Entry<String, Integer> entry : ageMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } ageMap.clear(); System.out.println("Map after clearing: " + ageMap); } } ===== b.LinkedHashMap //10b)LinkedHashMap import java.util.LinkedHashMap; import java.util.Map; public class LinkedHashMapExample{ public static void main(String[] args) { Map<String, Integer> ageMap = new LinkedHashMap<>(); ageMap.put("John", 30); ageMap.put("Alice", 25); ageMap.put("Bob", 35); ageMap.put("Eve", 28); System.out.println("Age of John: " + ageMap.get("John")); System.out.println("Age of Alice: " + ageMap.get("Alice")); ageMap.put("John", 32); System.out.println("Updated age of John: " + ageMap.get("John")); String name = "Bob"; if (ageMap.containsKey(name)) { System.out.println(name + " exists in the map."); } else { System.out.println(name + " does not exist in the map."); } ageMap.remove("Eve"); System.out.println("Map after removing Eve: " + ageMap); System.out.println("Iterating over map entries:"); for (Map.Entry<String, Integer> entry : ageMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } ageMap.clear(); System.out.println("Map after clearing: " + ageMap); } } ==== c.TreeMap //10c)TreeMap import java.util.TreeMap; import java.util.Map; public class TreeMapExample{ public static void main(String[] args) { Map<String, Integer> ageMap = new TreeMap<>(); ageMap.put("John", 30); ageMap.put("Alice", 25); ageMap.put("Bob", 35); ageMap.put("Eve", 28); System.out.println("Age of John: " + ageMap.get("John")); System.out.println("Age of Alice: " + ageMap.get("Alice")); ageMap.put("John", 32); System.out.println("Updated age of John: " + ageMap.get("John")); String name = "Bob"; if (ageMap.containsKey(name)) { System.out.println(name + " exists in the map."); } else { System.out.println(name + " does not exist in the map."); } ageMap.remove("Eve"); System.out.println("Map after removing Eve: " + ageMap); System.out.println("Iterating over map entries:"); for (Map.Entry<String, Integer> entry : ageMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } ageMap.clear(); System.out.println("Map after clearing: " + ageMap); } } --------------------------------------------------------------------------------------------------------------------- 11. Create a class Product(id,name,price,type,rating) and perform the following operations using stream: i) Find all the products having rating between 4 and 5. ii) Find first n products having price > 10000. iii) Find the number of products under each type(map containing type and count) iv) Find average rating of products woth type = “Electronics”. //11)Product stream import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; class Product { private int id; private String name; private double price; private String type; private double rating; public Product(int id, String name, double price, String type, double rating) { this.id = id; this.name = name; this.price = price; this.type = type; this.rating = rating; } public double getRating() { return rating; } public double getPrice() { return price; } public String getType() { return type; } @Override public String toString() { return "Product{" + "id=" + id + ", name='" + name + '\'' + ", price=" + price + ", type='" + type + '\'' + ", rating=" + rating + '}'; } } public class ProductStreamExample { public static void main(String[] args) { List<Product> products = Arrays.asList( new Product(1, "Laptop", 1500.0, "Electronics", 4.5), new Product(2, "Smartphone", 800.0, "Electronics", 4.2), new Product(3, "Watch", 300.0, "Fashion", 3.8), new Product(4, "Headphones", 100.0, "Electronics", 4.8), new Product(5, "Shoes", 50.0, "Fashion", 3.5), new Product(6, "Camera", 2000.0, "Electronics", 4.7) ); // i) Find all the products having rating between 4 and 5 List<Product> productsRatingBetween4And5 = products.stream() .filter(p -> p.getRating() >= 4 && p.getRating() <= 5) .collect(Collectors.toList()); System.out.println("Products with rating between 4 and 5: " + productsRatingBetween4And5); System.out.println(); // ii) Find first n products having price > 1000 int n = 2; List<Product> firstNProductsPriceGreaterThan1000 = products.stream() .filter(p -> p.getPrice() > 1000) .limit(n) .collect(Collectors.toList()); System.out.println("First " + n + " products with price > 1000: " + firstNProductsPriceGreaterThan1000); System.out.println(); // iii) Find the number of products under each type (map containing type and count) Map<String, Long> productCountByType = products.stream() .collect(Collectors.groupingBy(Product::getType, Collectors.counting())); System.out.println("Number of products under each type: " + productCountByType); System.out.println(); // iv) Find average rating of products with type = "Electronics" double averageRatingElectronics = products.stream() .filter(p -> p.getType().equals("Electronics")) .mapToDouble(Product::getRating) .average() .orElse(0.0); System.out.println("Average rating of products with type 'Electronics': " + averageRatingElectronics); } } -------------------------------------------------------------------------------------------------------------------12. Write a Java program to implement Sorted Chain. //12)Sorted Chain class Node<T extends Comparable<T>> { T data; Node<T> next; public Node(T data) { this.data = data; this.next = null; } } public class SortedChain<T extends Comparable<T>> { private Node<T> head; public void insert(T data) { Node<T> newNode = new Node<>(data); if (head == null || head.data.compareTo(data) >= 0) { newNode.next = head; head = newNode; } else { Node<T> current = head; while (current.next != null && current.next.data.compareTo(data) < 0) { current = current.next; } newNode.next = current.next; current.next = newNode; } } public void display() { Node<T> current = head; while (current != null) { System.out.print(current.data + " "); current = current.next; } System.out.println(); } public static void main(String[] args) { SortedChain<Integer> sortedChain = new SortedChain<>(); sortedChain.insert(5); sortedChain.insert(3); sortedChain.insert(7); sortedChain.insert(1); sortedChain.insert(9); System.out.println("Sorted Chain:"); sortedChain.display(); } } --------------------------------------------------------------------------------------------------------------------- 13. Write a java program to implement Separate Chaining //13)SeparateChaining import java.util.LinkedList; class KeyValuePair<K, V> { private K key; private V value; public KeyValuePair(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; } } class SeparateChaining<K, V> { private LinkedList<KeyValuePair<K, V>>[] table; private int capacity; @SuppressWarnings("unchecked") public SeparateChaining(int capacity) { this.capacity = capacity; this.table = new LinkedList[capacity]; for (int i = 0; i < capacity; i++) { table[i] = new LinkedList<>(); } } private int hash(K key) { return Math.abs(key.hashCode() % capacity); } public void put(K key, V value) { int index = hash(key); LinkedList<KeyValuePair<K, V>> list = table[index]; for (KeyValuePair<K, V> pair : list) { if (pair.getKey().equals(key)) { pair = new KeyValuePair<>(key, value); return; } } list.add(new KeyValuePair<>(key, value)); } public V get(K key) { int index = hash(key); LinkedList<KeyValuePair<K, V>> list = table[index]; for (KeyValuePair<K, V> pair : list) { if (pair.getKey().equals(key)) { return pair.getValue(); } } return null; } public void remove(K key) { int index = hash(key); LinkedList<KeyValuePair<K, V>> list = table[index]; for (KeyValuePair<K, V> pair : list) { if (pair.getKey().equals(key)) { list.remove(pair); return; } } } } public class SeparateChainingExample { public static void main(String[] args) { SeparateChaining<String, Integer> map = new SeparateChaining<>(5); map.put("John", 25); map.put("Alice", 30); map.put("Bob", 35); System.out.println("Alice's age: " + map.get("Alice")); System.out.println("Bob's age: " + map.get("Bob")); map.remove("Alice"); System.out.println("Alice's age after removal: " + map.get("Alice")); } } --------------------------------------------------------------------------------------------------------------------- 14. Write a java program to implement Linear Probing. //14)LinearProbing public class LinearProbingHashTable { private String[] keys; private String[] values; private int size; private int capacity; public LinearProbingHashTable(int capacity) { this.capacity = capacity; this.keys = new String[capacity]; this.values = new String[capacity]; this.size = 0; } private int hash(String key) { return key.length() % capacity; } public void put(String key, String value) { if (key == null || value == null) { throw new IllegalArgumentException("Key or value cannot be null."); } int index = hash(key); while (keys[index] != null) { if (keys[index].equals(key)) { values[index] = value; return; } index = (index + 1) % capacity; } keys[index] = key; values[index] = value; size++; } public String get(String key) { int index = hash(key); while (keys[index] != null) { if (keys[index].equals(key)) { return values[index]; } index = (index + 1) % capacity; } return null; } public void display() { for (int i = 0; i < capacity; i++) { if (keys[i] != null) { System.out.println("Key: " + keys[i] + ", Value: " + values[i]); } } } public static void main(String[] args) { LinearProbingHashTable hashTable = new LinearProbingHashTable(10); hashTable.put("John", "Doe"); hashTable.put("Alice", "Smith"); hashTable.put("Bob", "Johnson"); hashTable.put("Charlie", "Brown"); hashTable.display(); System.out.println("Value associated with 'John': " + hashTable.get("John")); System.out.println("Value associated with 'Alice': " + hashTable.get("Alice")); System.out.println("Value associated with 'Bob': " + hashTable.get("Bob")); System.out.println("Value associated with 'Charlie': " + hashTable.get("Charlie")); System.out.println("Value associated with 'Dave': " + hashTable.get("Dave")); // Not found } } 15. Implement BST using Collection API, and use recursive procedures to implement inOrder, preorder and postOrder traversals. //15)BinarySearchTree import java.util.LinkedList; class TreeNode<T extends Comparable<T>> { T data; TreeNode<T> left, right; public TreeNode(T data) { this.data = data; this.left = null; this.right = null; } } public class BinarySearchTree<T extends Comparable<T>> { private TreeNode<T> root; public BinarySearchTree() { this.root = null; } public void insert(T data) { root = insertRec(root, data); } private TreeNode<T> insertRec(TreeNode<T> root, T data) { if (root == null) { root = new TreeNode<>(data); return root; } if (data.compareTo(root.data) < 0) { root.left = insertRec(root.left, data); } else if (data.compareTo(root.data) > 0) { root.right = insertRec(root.right, data); } return root; } public void inorderTraversal() { inorderTraversalRec(root); } private void inorderTraversalRec(TreeNode<T> root) { if (root != null) { inorderTraversalRec(root.left); System.out.print(root.data + " "); inorderTraversalRec(root.right); } } public void preorderTraversal() { preorderTraversalRec(root); } private void preorderTraversalRec(TreeNode<T> root) { if (root != null) { System.out.print(root.data + " "); preorderTraversalRec(root.left); preorderTraversalRec(root.right); } } public void postorderTraversal() { postorderTraversalRec(root); } private void postorderTraversalRec(TreeNode<T> root) { if (root != null) { postorderTraversalRec(root.left); postorderTraversalRec(root.right); System.out.print(root.data + " "); } } public void delete(T data) { root = deleteRec(root, data); } private TreeNode<T> deleteRec(TreeNode<T> root, T data) { if (root == null) return root; if (data.compareTo(root.data) < 0) { root.left = deleteRec(root.left, data); } else if (data.compareTo(root.data) > 0) { root.right = deleteRec(root.right, data); } else { if (root.left == null) return root.right; else if (root.right == null) return root.left; root.data = minValue(root.right); root.right = deleteRec(root.right, root.data); } return root; } private T minValue(TreeNode<T> root) { T minv = root.data; while (root.left != null) { minv = root.left.data; root = root.left; } return minv; } public static void main(String[] args) { BinarySearchTree<Integer> bst = new BinarySearchTree<>(); bst.insert(50); bst.insert(30); bst.insert(20); bst.insert(40); bst.insert(70); bst.insert(60); bst.insert(80); System.out.println("Inorder traversal:"); bst.inorderTraversal(); System.out.println("\nPreorder traversal:"); bst.preorderTraversal(); System.out.println("\nPostorder traversal:"); bst.postorderTraversal(); System.out.println("\nDeleting 20:"); bst.delete(20); System.out.println("Inorder traversal after deletion:"); bst.inorderTraversal(); } } 16. Implement AVL tree using Collection API. //16)AVL TRee import java.util.Comparator; class AVLNode<T extends Comparable<T>> { T data; AVLNode<T> left, right; int height; public AVLNode(T data) { this.data = data; this.left = null; this.right = null; this.height = 1; } } public class AVLTree<T extends Comparable<T>> { private AVLNode<T> root; public AVLTree() { this.root = null; } private int height(AVLNode<T> node) { if (node == null) return 0; return node.height; } private int getBalance(AVLNode<T> node) { if (node == null) return 0; return height(node.left) - height(node.right); } public AVLNode<T> insert(AVLNode<T> node, T data) { if (node == null) return new AVLNode<>(data); if (data.compareTo(node.data) < 0) { node.left = insert(node.left, data); } else if (data.compareTo(node.data) > 0) { node.right = insert(node.right, data); } else { return node; // Duplicate keys not allowed } // Update height of this ancestor node node.height = 1 + Math.max(height(node.left), height(node.right)); // Get the balance factor and perform rotation if needed int balance = getBalance(node); // Left Left Case if (balance > 1 && data.compareTo(node.left.data) < 0) { return rightRotate(node); } // Right Right Case if (balance < -1 && data.compareTo(node.right.data) > 0) { return leftRotate(node); } // Left Right Case if (balance > 1 && data.compareTo(node.left.data) > 0) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && data.compareTo(node.right.data) < 0) { node.right = rightRotate(node.right); return leftRotate(node); } return node; } private AVLNode<T> rightRotate(AVLNode<T> y) { AVLNode<T> x = y.left; AVLNode<T> T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = Math.max(height(y.left), height(y.right)) + 1; x.height = Math.max(height(x.left), height(x.right)) + 1; return x; } private AVLNode<T> leftRotate(AVLNode<T> x) { AVLNode<T> y = x.right; AVLNode<T> T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = Math.max(height(x.left), height(x.right)) + 1; y.height = Math.max(height(y.left), height(y.right)) + 1; return y; } public void insert(T data) { root = insert(root, data); } public void inorderTraversal() { inorderTraversal(root); System.out.println(); } private void inorderTraversal(AVLNode<T> node) { if (node != null) { inorderTraversal(node.left); System.out.print(node.data + " "); inorderTraversal(node.right); } } public static void main(String[] args) { AVLTree<Integer> avlTree = new AVLTree<>(); avlTree.insert(10); avlTree.insert(20); avlTree.insert(30); avlTree.insert(40); avlTree.insert(50); avlTree.insert(25); System.out.println("Inorder traversal:"); avlTree.inorderTraversal(); } }
import java.util.Scanner; class Node<T> { T data; Node<T> next; public Node(T data) { this.data = data; this.next = null; } } class GenericStackArray<T> { private T[] stackArray; private int top; private int maxSize; @SuppressWarnings("unchecked") public GenericStackArray(int size) { this.maxSize = size; this.stackArray = (T[]) new Object[maxSize]; this.top = -1; } public void push(T item) { if (top < maxSize - 1) { stackArray[++top] = item; } else { System.out.println("Stack Overflow"); } } public T pop() { if (top >= 0) { return stackArray[top--]; } else { System.out.println("Stack Underflow"); return null; } } public boolean isEmpty() { return top == -1; } } class GenericStackLinkedList<T> { private Node<T> top; public GenericStackLinkedList() { this.top = null; } public void push(T item) { Node<T> newNode = new Node<>(item); newNode.next = top; top = newNode; } public T pop() { if (top == null) { System.out.println("Stack Underflow"); return null; } T data = top.data; top = top.next; return data; } public boolean isEmpty() { return top == null; } } public class GenericStackExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); GenericStackArray<Integer> intStackArray = new GenericStackArray<>(5); GenericStackLinkedList<Integer> intStackLinkedList = new GenericStackLinkedList<>(); System.out.println("Enter integers to push into the array stack (enter -1 to stop):"); int num; while (true) { num = scanner.nextInt(); if (num == -1) break; intStackArray.push(num); } System.out.println("Enter integers to push into the linked list stack (enter -1 to stop):"); while (true) { num = scanner.nextInt(); if (num == -1) break; intStackLinkedList.push(num); } System.out.println("Popping from array stack:"); while (!intStackArray.isEmpty()) { System.out.println(intStackArray.pop()); } System.out.println("Popping from linked list stack:"); while (!intStackLinkedList.isEmpty()) { System.out.println(intStackLinkedList.pop()); } } }
import java.util.LinkedList; import java.util.Iterator; public class LinkedListIteratorExample { public static void main(String[] args) { LinkedList<String> fruits = new LinkedList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); Iterator<String> iterator = fruits.iterator(); System.out.println("Using Iterator to traverse through the LinkedList:"); while (iterator.hasNext()) { String fruit = iterator.next(); System.out.println(fruit); } System.out.println("\nUsing for-each loop to traverse through the LinkedList:"); for (String fruit : fruits) { System.out.println(fruit); } iterator = fruits.iterator(); // Reset the iterator while (iterator.hasNext()) { String fruit = iterator.next(); if (fruit.startsWith("B")) { iterator.remove(); } } System.out.println("\nLinkedList after removal of elements that start with 'B':"); for (String fruit : fruits) { System.out.println(fruit); } } }
import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class ListIteratorExample { public static void main(String[] args) { // Creating and populating an ArrayList List<String> arrayList = new ArrayList<>(); arrayList.add("Apple"); arrayList.add("Banana"); arrayList.add("Cherry"); // Creating and populating a LinkedList List<String> linkedList = new LinkedList<>(); linkedList.add("Dog"); linkedList.add("Elephant"); linkedList.add("Frog"); // Iterating over the ArrayList System.out.println("Iterating over ArrayList:"); Iterator<String> arrayListIterator = arrayList.iterator(); while (arrayListIterator.hasNext()) { String item = arrayListIterator.next(); System.out.println(item); } // Iterating over the LinkedList System.out.println("\nIterating over LinkedList:"); Iterator<String> linkedListIterator = linkedList.iterator(); while (linkedListIterator.hasNext()) { String item = linkedListIterator.next(); System.out.println(item); } } }
public class ReverseStringLambda { @FunctionalInterface interface StringReverser { String reverse(String str); } public static void main(String[] args) { StringReverser reverser = (str) -> new StringBuilder(str).reverse().toString(); String example = "Hello, World!"; String reversed = reverser.reverse(example); System.out.println("Original: " + example); System.out.println("Reversed: " + reversed); } }
public class PiLambdaExpression{ @FunctionalInterface interface PiValue{ double getPi(); } public static void main(String[] args) { PiValue pi = () -> Math.PI; double p= pi.getPi(); System.out.println("The value of Pi is: " + p); } }
public class BoundedArithematic<T extends Number> { public double add(T a, T b) { return a.doubleValue() + b.doubleValue(); } public double subtract(T a, T b) { return a.doubleValue() - b.doubleValue(); } public double multiply(T a, T b) { return a.doubleValue() * b.doubleValue(); } public double divide(T a, T b) { if (b.doubleValue() == 0) { throw new ArithmeticException("Division by zero is not allowed."); } return a.doubleValue() / b.doubleValue(); } public static void main(String[] args) { BoundedArithematic<Number> calculator = new BoundedArithematic<>(); Integer a = 10; Integer b = 5; System.out.println("Addition: " + calculator.add(a, b)); System.out.println("Subtraction: " + calculator.subtract(a, b)); System.out.println("Multiplication: " + calculator.multiply(a, b)); System.out.println("Division: " + calculator.divide(a, b)); } } == //Wildcard Arguments public class MagicBox<T> { private T item; public void addItem(T item) { this.item = item; System.out.println("Added item to the magic box: " + item); } public T getItem() { return item; } public void processBox(MagicBox<? super Integer> box) { System.out.println("Items in the box are processed["+box.getItem()+"]"); } public static void main(String[] args) { MagicBox<Integer> integerBox = new MagicBox<>(); integerBox.addItem(43); MagicBox<String> stringBox = new MagicBox<>(); stringBox.addItem("Sofiya"); MagicBox<Boolean> booleanBox = new MagicBox<>(); booleanBox.addItem(false); MagicBox<Object> dobubleBox = new MagicBox<>(); dobubleBox.addItem(43.43); integerBox.processBox(integerBox); dobubleBox.processBox(dobubleBox); } }
CREATE TABLE empc ( emp_id NUMBER PRIMARY KEY, name VARCHAR2(100), hire_date DATE -- other columns ); DECLARE CURSOR emp_cursor IS SELECT empno, ename, hiredate FROM employee WHERE (SYSDATE - hiredate) / 365.25 >= 23; -- Calculate experience in years emp_record emp_cursor%ROWTYPE; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO emp_record; EXIT WHEN emp_cursor%NOTFOUND; INSERT INTO empc (emp_id, name, hire_date) VALUES (emp_record.empno, emp_record.ename, emp_record.hiredate); END LOOP; CLOSE emp_cursor; COMMIT; END; /
create or replace Trigger mytrigger before insert on employee begin dbms_output.put_line('Record inserted '); end; /
DECLARE v_department_id NUMBER := &department_id; -- Accept department number as input BEGIN FOR emp_record IN ( SELECT empno, ename, hiredate, deptno FROM employee WHERE deptno= v_department_id ) LOOP DBMS_OUTPUT.PUT_LINE('Emp ID: ' || emp_record.empno); DBMS_OUTPUT.PUT_LINE('Name: ' || emp_record.ename); DBMS_OUTPUT.PUT_LINE('Hire Date: ' || TO_CHAR(emp_record.hiredate, 'YYYY-MM-DD')); DBMS_OUTPUT.PUT_LINE('Department ID: ' || emp_record.deptno); DBMS_OUTPUT.PUT_LINE('-----------------------------'); END LOOP; END; /
create or replace Trigger mytrigger2 after insert or update on employee begin case when inserting then dbms_output.put_line('Record inserting'); when updating then dbms_output.put_line('record updating'); end case; end; /
declare a integer:=&a; c integer:=0; i integer; begin for i in 1 .. a-1 loop if (mod(a,i)=0) then c:=c+i; end if; end loop; if c=a then dbms_output.put_line('Perfect number'); else dbms_output.put_line('Not Perfect number'); end if; end; /
declare cursor c1 is select * from employee; e employee%rowtype; begin open c1; loop fetch c1 into e; exit when c1%notfound; dbms_output.put_line(e.empno||' ' ||e.ename||' '||e.sal); end loop; end; /
Mon May 27 2024 13:27:16 GMT+0000 (Coordinated Universal Time) https://www.pyramidions.com/android-application-development-company-in-chennai.html
Mon May 27 2024 08:53:57 GMT+0000 (Coordinated Universal Time) https://www.kryptobees.com/axie-infinity-clone-script
@jackwyatt134 ##axieinfinityclonescript#metaversegame #virtualreality
Mon May 27 2024 05:49:55 GMT+0000 (Coordinated Universal Time) https://laravel-livewire.com/docs/2.x/input-validation
Mon May 27 2024 05:03:18 GMT+0000 (Coordinated Universal Time) https://research.google.com/colaboratory/local-runtimes.html
Mon May 27 2024 04:05:18 GMT+0000 (Coordinated Universal Time) https://laravel-livewire.com/docs/2.x/properties
Mon May 27 2024 04:04:51 GMT+0000 (Coordinated Universal Time) https://laravel-livewire.com/docs/2.x/properties
Mon May 27 2024 04:00:08 GMT+0000 (Coordinated Universal Time) https://laravel-livewire.com/docs/2.x/properties
Mon May 27 2024 03:58:04 GMT+0000 (Coordinated Universal Time) https://laravel-livewire.com/docs/2.x/properties