· 6 months ago · Mar 26, 2025, 03:30 PM
1Slip No: 1
2Q.1) Write a PHP script to keep track of number of times the web page has been accessed (Use Session Tracking).
3Solution:
4<?php
5session_start();
6if (!isset($_SESSION['page_views'])) {
7 $_SESSION['page_views'] = 0;
8}
9$_SESSION['page_views']++;
10echo "Page accessed " . $_SESSION['page_views'] . " times.";
11?>
12
13Q.2) Create 'Position_Salaries' Data set. Build a linear regression model by identifying independent and target variable. Split the variables into training and testing sets, then divide the training and testing sets into a 7:3 ratio, respectively and print them. Build a simple linear regression model.
14Solution:
15import pandas as pd
16from sklearn.model_selection import train_test_split
17from sklearn.linear_model import LinearRegression
18
19data = {'Position_Level': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
20 'Salary': [45000, 50000, 60000, 80000, 110000, 150000, 200000, 300000, 500000, 1000000]}
21df = pd.DataFrame(data)
22X = df[['Position_Level']]
23y = df['Salary']
24X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
25print("X_train:\n", X_train, "\nX_test:\n", X_test, "\ny_train:\n", y_train, "\ny_test:\n", y_test)
26model = LinearRegression()
27model.fit(X_train, y_train)
28print("Slope:", model.coef_, "Intercept:", model.intercept_)
29
30Slip No: 2
31Q.1) Write a PHP script to change the preferences of your web page like font style, font size, font color, background color using cookie. Display selected setting on next web page and actual implementation (with new settings) on third page (Use Cookies).
32Solution:
33<!-- page1.php -->
34<form method="post" action="page2.php">
35 Font Style: <input type="text" name="font_style"><br>
36 Font Size: <input type="text" name="font_size"><br>
37 Font Color: <input type="text" name="font_color"><br>
38 Background Color: <input type="text" name="bg_color"><br>
39 <input type="submit" value="Set Preferences">
40</form>
41
42<!-- page2.php -->
43<?php
44if ($_SERVER["REQUEST_METHOD"] == "POST") {
45 setcookie("font_style", $_POST['font_style'], time() + 3600);
46 setcookie("font_size", $_POST['font_size'], time() + 3600);
47 setcookie("font_color", $_POST['font_color'], time() + 3600);
48 setcookie("bg_color", $_POST['bg_color'], time() + 3600);
49 echo "Preferences set: " . $_POST['font_style'] . ", " . $_POST['font_size'] . ", " .
50 $_POST['font_color'] . ", " . $_POST['bg_color'];
51 echo "<br><a href='page3.php'>Go to Page 3</a>";
52}
53?>
54
55<!-- page3.php -->
56<?php
57echo "<style>body { font-family: " . $_COOKIE['font_style'] . "; font-size: " .
58 $_COOKIE['font_size'] . "px; color: " . $_COOKIE['font_color'] . "; background-color: " .
59 $_COOKIE['bg_color'] . "; }</style>";
60echo "Page with new settings!";
61?>
62
63Q.2) Create 'Salary' Data set. Build a linear regression model by identifying independent and target variable. Split the variables into training and testing sets and print them. Build a simple linear regression model for predicting purchases.
64Solution:
65import pandas as pd
66from sklearn.model_selection import train_test_split
67from sklearn.linear_model import LinearRegression
68
69data = {'Years_Experience': [1, 2, 3, 4, 5], 'Salary': [30000, 35000, 40000, 45000, 50000]}
70df = pd.DataFrame(data)
71X = df[['Years_Experience']]
72y = df['Salary']
73X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
74print("X_train:\n", X_train, "\nX_test:\n", X_test, "\ny_train:\n", y_train, "\ny_test:\n", y_test)
75model = LinearRegression()
76model.fit(X_train, y_train)
77print("Slope:", model.coef_, "Intercept:", model.intercept_)
78
79Slip No: 3
80Q.1) Write a PHP script to accept username and password. If in the first three chances, username and password entered is correct then display second form with "Welcome message" otherwise display error message. [Use Session]
81Solution:
82<?php
83session_start();
84if (!isset($_SESSION['attempts'])) $_SESSION['attempts'] = 0;
85$correct_username = "admin";
86$correct_password = "12345";
87
88if ($_SERVER["REQUEST_METHOD"] == "POST") {
89 $_SESSION['attempts']++;
90 if ($_POST['username'] == $correct_username && $_POST['password'] == $correct_password && $_SESSION['attempts'] <= 3) {
91 echo "<h2>Welcome, " . $_POST['username'] . "!</h2><form><input type='submit' value='Proceed'></form>";
92 session_destroy();
93 } elseif ($_SESSION['attempts'] <= 3) {
94 echo "Incorrect. Attempt " . $_SESSION['attempts'] . " of 3.";
95 } else {
96 echo "Error: Max attempts exceeded.";
97 session_destroy();
98 }
99}
100?>
101<form method="post">
102 Username: <input type="text" name="username"><br>
103 Password: <input type="password" name="password"><br>
104 <input type="submit" value="Login">
105</form>
106
107Q.2) Create 'User' Data set having 5 columns namely: User ID, Gender, Age, Estimated Salary and Purchased. Build a logistic regression model that can predict whether on the given parameter a person will buy a car or not.
108Solution:
109import pandas as pd
110from sklearn.model_selection import train_test_split
111from sklearn.linear_model import LogisticRegression
112from sklearn.preprocessing import LabelEncoder
113
114data = {'User ID': range(1, 11), 'Gender': ['M', 'F', 'M', 'F', 'M', 'F', 'M', 'F', 'M', 'F'],
115 'Age': [19, 35, 26, 27, 19, 27, 32, 25, 35, 20], 'Estimated Salary': [19000, 20000, 43000, 57000, 76000, 58000, 84000, 150000, 33000, 65000],
116 'Purchased': [0, 0, 0, 1, 1, 0, 1, 1, 0, 1]}
117df = pd.DataFrame(data)
118df['Gender'] = LabelEncoder().fit_transform(df['Gender'])
119X = df[['Gender', 'Age', 'Estimated Salary']]
120y = df['Purchased']
121X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
122model = LogisticRegression()
123model.fit(X_train, y_train)
124print("Accuracy:", model.score(X_test, y_test))
125
126Slip No: 4
127Q.1) Write a PHP script to accept Employee details (Eno, Ename, Address) on first page. On second page accept earning (Basic, DA, HRA). On third page print Employee information (Eno, Ename, Address, Basic, DA, HRA, Total) [Use Session]
128Solution:
129<!-- page1.php -->
130<?php session_start(); ?>
131<form method="post" action="page2.php">
132 Eno: <input type="text" name="eno"><br>
133 Ename: <input type="text" name="ename"><br>
134 Address: <input type="text" name="address"><br>
135 <input type="submit" value="Next">
136</form>
137
138<!-- page2.php -->
139<?php
140session_start();
141if ($_SERVER["REQUEST_METHOD"] == "POST") {
142 $_SESSION['eno'] = $_POST['eno'];
143 $_SESSION['ename'] = $_POST['ename'];
144 $_SESSION['address'] = $_POST['address'];
145}
146?>
147<form method="post" action="page3.php">
148 Basic: <input type="text" name="basic"><br>
149 DA: <input type="text" name="da"><br>
150 HRA: <input type="text" name="hra"><br>
151 <input type="submit" value="Next">
152</form>
153
154<!-- page3.php -->
155<?php
156session_start();
157if ($_SERVER["REQUEST_METHOD"] == "POST") {
158 $total = $_POST['basic'] + $_POST['da'] + $_POST['hra'];
159 echo "Eno: " . $_SESSION['eno'] . "<br>Ename: " . $_SESSION['ename'] . "<br>Address: " .
160 $_SESSION['address'] . "<br>Basic: " . $_POST['basic'] . "<br>DA: " . $_POST['da'] .
161 "<br>HRA: " . $_POST['hra'] . "<br>Total: " . $total;
162 session_destroy();
163}
164?>
165
166Q.2) Build a simple linear regression model for Fish Species Weight Prediction.
167Solution:
168import pandas as pd
169from sklearn.model_selection import train_test_split
170 it'sfrom sklearn.linear_model import LinearRegression
171
172data = {'Length': [25, 30, 35, 40, 45], 'Weight': [200, 300, 400, 500, 600]}
173df = pd.DataFrame(data)
174X = df[['Length']]
175y = df['Weight']
176X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
177model = LinearRegression()
178model.fit(X_train, y_train)
179print("Slope:", model.coef_, "Intercept:", model.intercept_)
180
181Slip No: 5
182Q.1) Create XML file named "Item.xml" with item-name, item-rate, item quantity Store the details of 5 Items of different Types
183Solution:
184<!-- Item.xml -->
185<?xml version="1.0" encoding="UTF-8"?>
186<Items>
187 <Item><item-name>Laptop</item-name><item-rate>50000</item-rate><item-quantity>10</item-quantity></Item>
188 <Item><item-name>Mouse</item-name><item-rate>500</item-rate><item-quantity>50</item-quantity></Item>
189 <Item><item-name>Keyboard</item-name><item-rate>1000</item-rate><item-quantity>30</item-quantity></Item>
190 <Item><item-name>Monitor</item-name><item-rate>15000</item-rate><item-quantity>15</item-quantity></Item>
191 <Item><item-name>Printer</item-name><item-rate>8000</item-rate><item-quantity>5</item-quantity></Item>
192</Items>
193
194Q.2) Use the iris dataset. Write a Python program to view some basic statistical details like percentile, mean, std etc. of the species of 'Iris-setosa', 'Iris-versicolor' and 'Iris-virginica'. Apply logistic regression on the dataset to identify different species (setosa, versicolor, verginica) of Iris flowers given just 4 features: sepal and petal lengths and widths.. Find the accuracy of the model.
195Solution:
196import pandas as pd
197from sklearn.datasets import load_iris
198from sklearn.model_selection import train_test_split
199from sklearn.linear_model import LogisticRegression
200
201iris = load_iris()
202df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
203df['Species'] = iris.target
204df['Species'] = df['Species'].map({0: 'Iris-setosa', 1: 'Iris-versicolor', 2: 'Iris-virginica'})
205for species in df['Species'].unique():
206 print(f"\n{species}:\n", df[df['Species'] == species].describe())
207X = df[iris.feature_names]
208y = df['Species']
209X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
210model = LogisticRegression(max_iter=200)
211model.fit(X_train, y_train)
212print("Accuracy:", model.score(X_test, y_test))
213
214Slip No: 6
215Q.1) Write PHP script to read "book.xml" file into simpleXML object. Display attributes and elements. ( simple_xml_load_file() function )
216Solution:
217<!-- book.xml -->
218<?xml version="1.0" encoding="UTF-8"?>
219<Books>
220 <Book id="1"><title>Python Basics</title><author>John Doe</author><price>500</price></Book>
221 <Book id="2"><title>PHP Guide</title><author>Jane Smith</author><price>600</price></Book>
222</Books>
223
224<?php
225$xml = simplexml_load_file("book.xml");
226foreach ($xml->Book as $book) {
227 echo "Book ID: " . $book['id'] . "<br>Title: " . $book->title . "<br>Author: " .
228 $book->author . "<br>Price: " . $book->price . "<br><br>";
229}
230?>
231
232Q.2) Create the following dataset in python & Convert the categorical values into numeric format. Apply the apriori algorithm on the above dataset to generate the frequent itemsets and association rules. Repeat the process with different min_sup values.
233Solution:
234import pandas as pd
235from mlxtend.frequent_patterns import apriori, association_rules
236
237data = {'TID': [1, 2, 3, 4, 5], 'Items': [['Bread', 'Milk'], ['Bread', 'Diaper', 'Beer', 'Eggs'],
238 ['Milk', 'Diaper', 'Beer', 'Coke'], ['Bread', 'Milk', 'Diaper', 'Beer'], ['Bread', 'Milk', 'Diaper', 'Coke']]}
239df = pd.DataFrame(data)
240items = set(item for sublist in df['Items'] for item in sublist)
241encoded_df = pd.DataFrame({item: [1 if item in row else 0 for row in df['Items']] for item in items})
242for min_sup in [0.4, 0.6]:
243 frequent_itemsets = apriori(encoded_df, min_support=min_sup, use_colnames=True)
244 rules = association_rules(frequent_itemsets, metric="confidence", min_threshold=0.7)
245 print(f"\nmin_sup = {min_sup}:\nFrequent Itemsets:\n", frequent_itemsets, "\nRules:\n", rules)
246
247Slip No: 8
248Q.1) Write a JavaScript to display message 'Exams are near, have you started preparing for?' (usealert box ) and Accept any two numbers from user and display addition of two number.(Use Prompt and confirm box)
249Solution:
250<script>
251alert("Exams are near, have you started preparing for?");
252let num1 = parseInt(prompt("Enter first number:"));
253let num2 = parseInt(prompt("Enter second number:"));
254if (confirm("Do you want to see the sum?")) {
255 document.write("Sum: " + (num1 + num2));
256}
257</script>
258
259Q.2) Download the groceries dataset. Write a python program to read the dataset and display its information. Preprocess the data (drop null values etc.) Convert the categorical values into numeric format. Apply the apriori algorithm on the above dataset to generate the frequent itemsets and association rules.
260Solution:
261import pandas as pd
262from mlxtend.frequent_patterns import apriori, association_rules
263
264df = pd.read_csv('groceries.csv') # Replace with actual path
265print(df.info())
266df.dropna(inplace=True)
267transactions = df['items'].str.split(',').apply(lambda x: pd.Series(1, index=x)).fillna(0)
268frequent_itemsets = apriori(transactions, min_support=0.05, use_colnames=True)
269rules = association_rules(frequent_itemsets, metric="confidence", min_threshold=0.7)
270print("Frequent Itemsets:\n", frequent_itemsets, "\nRules:\n", rules)
271
272Slip No: 9
273Q.1) Write a JavaScript function to validate username and password for a membership form.
274Solution:
275<script>
276function validateForm() {
277 let username = document.getElementById("username").value;
278 let password = document.getElementById("password").value;
279 if (username.length < 5) {
280 alert("Username must be at least 5 characters.");
281 return false;
282 }
283 if (password.length < 8) {
284 alert("Password must be at least 8 characters.");
285 return false;
286 }
287 alert("Validation successful!");
288 return true;
289}
290</script>
291<form onsubmit="return validateForm()">
292 Username: <input type="text" id="username"><br>
293 Password: <input type="password" id="password"><br>
294 <input type="submit" value="Submit">
295</form>
296
297Q.2) Create your own transactions dataset and apply the above process on your dataset.
298Solution:
299import pandas as pd
300from mlxtend.frequent_patterns import apriori, association_rules
301
302data = {'TID': [1, 2, 3, 4, 5], 'Items': [['eggs', 'milk', 'bread'], ['eggs', 'apple'],
303 ['milk', 'bread'], ['apple', 'milk'], ['milk', 'apple', 'bread']]}
304df = pd.DataFrame(data)
305items = set(item for sublist in df['Items'] for item in sublist)
306encoded_df = pd.DataFrame({item: [1 if item in row else 0 for row in df['Items']] for item in items})
307for min_sup in [0.4, 0.6]:
308 frequent_itemsets = apriori(encoded_df, min_support=min_sup, use_colnames=True)
309 rules = association_rules(frequent_itemsets, metric="confidence", min_threshold=0.7)
310 print(f"\nmin_sup = {min_sup}:\nFrequent Itemsets:\n", frequent_itemsets, "\nRules:\n", rules)
311
312Slip No: 10
313Q.1) Create a HTML fileto insert text before and after a Paragraph using jQuery. [Hint : Use before( ) and after( )]
314Solution:
315<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
316<p id="myPara">This is a paragraph.</p>
317<script>
318$(document).ready(function() {
319 $("#myPara").before("<b>Before Text</b><br>");
320 $("#myPara").after("<br><i>After Text</i>");
321});
322</script>
323
324Q.2) Create the following dataset in python & Convert the categorical values into numeric format. Apply the apriori algorithm on the above dataset to generate the frequent itemsets and association rules. Repeat the process with different min_sup values.
325Solution:
326import pandas as pd
327from mlxtend.frequent_patterns import apriori, association_rules
328
329data = {'TID': [1, 2, 3, 4, 5], 'Items': [['butter', 'bread', 'milk'], ['butter', 'flour', 'milk', 'sugar'],
330 ['butter', 'eggs', 'milk', 'salt'], ['eggs'], ['butter', 'flour', 'milk', 'salt']]}
331df = pd.DataFrame(data)
332items = set(item for sublist in df['Items'] for item in sublist)
333encoded_df = pd.DataFrame({item: [1 if item in row else 0 for row in df['Items']] for item in items})
334for min_sup in [0.4, 0.6]:
335 frequent_itemsets = apriori(encoded_df, min_support=min_sup, use_colnames=True)
336 rules = association_rules(frequent_itemsets, metric="confidence", min_threshold=0.7)
337 print(f"\nmin_sup = {min_sup}:\nFrequent Itemsets:\n", frequent_itemsets, "\nRules:\n", rules)
338
339Slip No: 11
340Q.1) Write a Javascript program to accept name of student, change font color to red, font size to 18 if student name is present otherwise on clicking on empty text box display image which changes its size (Use onblur, onload, onmouseover, onmouseclick, onmouseup)
341Solution:
342<input type="text" id="name" onblur="checkName()">
343<img id="img" src="image.jpg" style="display:none;">
344<script>
345function checkName() {
346 let name = document.getElementById("name").value;
347 let img = document.getElementById("img");
348 if (name) {
349 document.body.style.color = "red";
350 document.body.style.fontSize = "18px";
351 img.style.display = "none";
352 } else {
353 img.style.display = "block";
354 img.onmouseover = () => img.style.width = "200px";
355 img.onmouseup = () => img.style.width = "100px";
356 }
357}
358</script>
359
360Q.2) Create 'heights-and-weights' Data set . Build a linear regression model by identifying independent and target variable. Split the variables into training and testing sets and print them. Build a simple linear regression model for predicting purchases.
361Solution:
362import pandas as pd
363from sklearn.model_selection import train_test_split
364from sklearn.linear_model import LinearRegression
365
366data = {'Height': [150, 160, 170, 180, 190], 'Weight': [50, 60, 70, 80, 90]}
367df = pd.DataFrame(data)
368X = df[['Height']]
369y = df['Weight']
370X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
371model = LinearRegression()
372model.fit(X_train, y_train)
373print("Slope:", model.coef_, "Intercept:", model.intercept_)
374
375Slip No: 12
376Q.1) Write AJAX program to read contact.dat file and print the contents of the file in a tabular format when the user clicks on print button. Contact.dat file should contain smo, name, residence number, mobile number, Address. [Enter at least 3 record in contact.dat file]
377Solution:
378<button onclick="loadData()">Print</button>
379<div id="result"></div>
380<script>
381function loadData() {
382 let xhr = new XMLHttpRequest();
383 xhr.open("GET", "contact.dat", true);
384 xhr.onreadystatechange = function() {
385 if (xhr.readyState == 4 && xhr.status == 200) {
386 let lines = xhr.responseText.split('\n');
387 let table = "<table border='1'><tr><th>Sno</th><th>Name</th><th>Residence</th><th>Mobile</th><th>Address</th></tr>";
388 lines.forEach(line => {
389 let [sno, name, res, mob, addr] = line.split(',');
390 table += `<tr><td>${sno}</td><td>${name}</td><td>${res}</td><td>${mob}</td><td>${addr}</td></tr>`;
391 });
392 table += "</table>";
393 document.getElementById("result").innerHTML = table;
394 }
395 };
396 xhr.send();
397}
398</script>
399*contact.dat*: 1,John,12345,98765,Addr1\n2,Jane,54321,56789,Addr2\n3,Tom,11111,22222,Addr3
400
401Q.2) Download nursery dataset from UCI. Build a linear regression model by identifying independent and target variable. Split the variables into training and testing sets and print them. Build a simple linear regression model for predicting purchases.
402Solution:
403import pandas as pd
404from sklearn.model_selection import train_test_split
405from sklearn.linear_model import LinearRegression
406
407df = pd.read_csv('nursery.csv') # Replace with actual path
408X = df[['some_numeric_column']] # Adjust based on actual dataset
409y = df['target_column'] # Adjust based on actual dataset
410X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
411model = LinearRegression()
412model.fit(X_train, y_train)
413print("Slope:", model.coef_, "Intercept:", model.intercept_)
414
415Slip No: 13
416Q.1) Write AJAX program where the user is requested to write his or her name in a text box, and the server keeps sending back responses while the user is typing. If the user name is not entered then the message displayed will be, "Stranger, please tell me your name!". If the name is Rohit, Virat, Dhoni, Ashwin or Harbhajan, the server responds with "Hello, master !". If the name is anything else, the message will be ", I don't know you!"
417Solution:
418<input type="text" id="name" onkeyup="checkName()">
419<div id="response"></div>
420<script>
421function checkName() {
422 let name = document.getElementById("name").value;
423 let xhr = new XMLHttpRequest();
424 xhr.open("POST", "server.php", true);
425 xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
426 xhr.onreadystatechange = function() {
427 if (xhr.readyState == 4 && xhr.status == 200) {
428 document.getElementById("response").innerHTML = xhr.responseText;
429 }
430 };
431 xhr.send("name=" + name);
432}
433</script>
434
435<!-- server.php -->
436<?php
437$name = $_POST['name'];
438if (empty($name)) echo "Stranger, please tell me your name!";
439elseif (in_array($name, ["Rohit", "Virat", "Dhoni", "Ashwin", "Harbhajan"])) echo "Hello, master!";
440else echo "$name, I don't know you!";
441?>
442
443Q.2) Create the following dataset in python & Convert the categorical values into numeric format. Apply the apriori algorithm on the above dataset to generate the frequent itemsets and association rules. Repeat the process with different min_sup values.
444Solution:
445import pandas as pd
446from mlxtend.frequent_patterns import apriori, association_rules
447
448data = {'TID': [1, 2, 3, 4], 'Items': [['Apple', 'Mango', 'Banana'], ['Mango', 'Banana', 'Cabbage', 'Carrots'],
449 ['Mango', 'Banana', 'Carrots'], ['Mango', 'Carrots']]}
450df = pd.DataFrame(data)
451items = set(item for sublist in df['Items'] for item in sublist)
452encoded_df = pd.DataFrame({item: [1 if item in row else 0 for row in df['Items']] for item in items})
453for min_sup in [0.5, 0.75]:
454 frequent_itemsets = apriori(encoded_df, min_support=min_sup, use_colnames=True)
455 rules = association_rules(frequent_itemsets, metric="confidence", min_threshold=0.7)
456 print(f"\nmin_sup = {min_sup}:\nFrequent Itemsets:\n", frequent_itemsets, "\nRules:\n", rules)
457
458Slip No: 14
459Q.1) Write a Java Script Program to print Fibonacci numbers on onclick event.
460Solution:
461<button onclick="printFibonacci()">Print Fibonacci</button>
462<div id="result"></div>
463<script>
464function printFibonacci() {
465 let n = prompt("Enter number of terms:");
466 let a = 0, b = 1, fib = [a, b];
467 for (let i = 2; i < n; i++) {
468 let next = a + b;
469 fib.push(next);
470 a = b;
471 b = next;
472 }
473 document.getElementById("result").innerHTML = fib.join(", ");
474}
475</script>
476
477Q.2) Consider any text paragraph. Remove the stopwords. Tokenize the paragraph to extract words and sentences. Calculate the word frequency distribution and plot the frequencies. Plot the wordcloud of the text.
478Solution:
479import nltk
480from nltk.corpus import stopwords
481from nltk.tokenize import word_tokenize, sent_tokenize
482from collections import Counter
483import matplotlib.pyplot as plt
484from wordcloud import WordCloud
485
486nltk.download('punkt')
487nltk.download('stopwords')
488text = "This is a sample text. It has multiple sentences. This text is for testing."
489stop_words = set(stopwords.words('english'))
490words = word_tokenize(text.lower())
491words = [w for w in words if w not in stop_words]
492sentences = sent_tokenize(text)
493freq = Counter(words)
494plt.bar(freq.keys(), freq.values())
495plt.show()
496wordcloud = WordCloud().generate(' '.join(words))
497plt.imshow(wordcloud)
498plt.axis("off")
499plt.show()
500
501Slip No: 18
502Q.1) Write a Java Script Program to validate user name and password on onSubmit event.
503Solution:
504<form onsubmit="return validate()">
505 Username: <input type="text" id="username"><br>
506 Password: <input type="password" id="password"><br>
507 <input type="submit" value="Submit">
508</form>
509<script>
510function validate() {
511 let username = document.getElementById("username").value;
512 let password = document.getElementById("password").value;
513 if (username.length < 5 || password.length < 8) {
514 alert("Username must be 5+ chars, Password 8+ chars.");
515 return false;
516 }
517 alert("Success!");
518 return true;
519}
520</script>
521
522Q.2) Download the movie_review.csv dataset from Kaggle by using the following link :https://www.kaggle.com/nltkdata/movie-review/version/3?select=movie review.csv to perform sentiment analysis on above dataset and create a wordcloud.
523Solution:
524import pandas as pd
525from nltk.sentiment import SentimentIntensityAnalyzer
526from wordcloud import WordCloud
527import matplotlib.pyplot as plt
528import nltk
529
530nltk.download('vader_lexicon')
531df = pd.read_csv('movie_review.csv') # Replace with actual path
532sia = SentimentIntensityAnalyzer()
533df['sentiment'] = df['text'].apply(lambda x: sia.polarity_scores(x)['compound'])
534wordcloud = WordCloud().generate(' '.join(df['text']))
535plt.imshow(wordcloud)
536plt.axis("off")
537plt.show()
538
539Slip No: 19
540Q.1) create a student.xml file containing at least 5 student information
541Solution:
542<!-- student.xml -->
543<?xml version="1.0" encoding="UTF-8"?>
544<Students>
545 <Student><id>1</id><name>John</name><course>CS</course></Student>
546 <Student><id>2</id><name>Jane</name><course>IT</course></Student>
547 <Student><id>3</id><name>Tom</name><course>CS</course></Student>
548 <Student><id>4</id><name>Lisa</name><course>IT</course></Student>
549 <Student><id>5</id><name>Mike</name><course>CS</course></Student>
550</Students>
551
552Q.2) Consider text paragraph. "Hello all, Welcome to Python Programming Academy. Python Programming Academy is a nice platform to learn new programming skills. It is difficult to get enrolled in this Academy. "Remove the stopwords.
553Solution:
554import nltk
555from nltk.corpus import stopwords
556from nltk.tokenize import word_tokenize
557
558nltk.download('punkt')
559nltk.download('stopwords')
560text = "Hello all, Welcome to Python Programming Academy. Python Programming Academy is a nice platform to learn new programming skills. It is difficult to get enrolled in this Academy."
561stop_words = set(stopwords.words('english'))
562words = word_tokenize(text.lower())
563filtered = [w for w in words if w not in stop_words]
564print("Filtered Words:", filtered)
565
566Slip No: 20
567Q.1) Write a PHP script to create student.xml file which contains student roll no, name, address, college and course. Print students detail of specific course in tabular format after accepting course as input.
568Solution:
569<?php
570if ($_SERVER["REQUEST_METHOD"] == "POST") {
571 $xml = new DOMDocument("1.0");
572 $root = $xml->createElement("Students");
573 $xml->appendChild($root);
574 $students = [
575 ["roll" => 1, "name" => "John", "address" => "Addr1", "college" => "XYZ", "course" => "CS"],
576 ["roll" => 2, "name" => "Jane", "address" => "Addr2", "college" => "ABC", "course" => "IT"],
577 ["roll" => 3, "name" => "Tom", "address" => "Addr3", "college" => "XYZ", "course" => "CS"]
578 ];
579 foreach ($students as $s) {
580 $student = $xml->createElement("Student");
581 foreach ($s as $key => $value) {
582 $elem = $xml->createElement($key, $value);
583 $student->appendChild($elem);
584 }
585 $root->appendChild($student);
586 }
587 $xml->save("student.xml");
588
589 $course = $_POST['course'];
590 $xml = simplexml_load_file("student.xml");
591 echo "<table border='1'><tr><th>Roll</th><th>Name</th><th>Address</th><th>College</th><th>Course</th></tr>";
592 foreach ($xml->Student as $student) {
593 if ($student->course == $course) {
594 echo "<tr><td>$student->roll</td><td>$student->name</td><td>$student->address</td><td>$student->college</td><td>$student->course</td></tr>";
595 }
596 }
597 echo "</table>";
598}
599?>
600<form method="post">
601 Course: <input type="text" name="course"><br>
602 <input type="submit" value="Show Students">
603</form>
604
605Q.2) Consider the following dataset : https://www.kaggle.com/datasets/datasnaek/youtubenew?select=INvideos.csv Write a 🙂Python script for the following : i. Read the dataset and perform data cleaning operations on it. ii. ii. Find the total views, total likes, total dislikes and comment count.
606Solution:
607import pandas as pd
608
609df = pd.read_csv('INvideos.csv') # Replace with actual path
610df.dropna(inplace=True)
611print("Total Views:", df['views'].sum())
612print("Total Likes:", df['likes'].sum())
613print("Total Dislikes:", df['dislikes'].sum())
614print("Total Comments:", df['comment_count'].sum())
615
616Slip No: 24
617Q.1) Write a script to create "cricket.xml" file with multiple elements as shown below:
618 <CricketTeam>
619 <Team country="Australia">
620 <player> </player>
621 <runs> </runs>
622 <wicket> </wicket>
623 </Team>
624 </CricketTeam>
625Write a script to add multiple elements in "cricket.xml" file of category, country="India".
626Solution:
627<?php
628$xml = new DOMDocument("1.0");
629$root = $xml->createElement("CricketTeam");
630$xml->appendChild($root);
631$team = $xml->createElement("Team");
632$team->setAttribute("country", "Australia");
633$root->appendChild($team);
634$xml->save("cricket.xml");
635
636// Add India team
637$xml = simplexml_load_file("cricket.xml");
638$team = $xml->addChild("Team");
639$team->addAttribute("country", "India");
640$team->addChild("player", "Virat");
641$team->addChild("runs", "5000");
642$team->addChild("wicket", "10");
643$xml->asXML("cricket.xml");
644echo "India team added!";
645?>
646
647Q.2) Consider the following dataset : https://www.kaggle.com/datasets/seungguini/youtube-commentsfor-covid19-relatedvideos?select=covid_2021_1.csv Write a Python script for the following : i. Read the dataset and perform data cleaning operations on it. ii. ii. Tokenize the comments in words. iii. Perform sentiment analysis and find the percentage of positive, negative and neutral comments.
648Solution:
649import pandas as pd
650from nltk.sentiment import SentimentIntensityAnalyzer
651import nltk
652
653nltk.download('vader_lexicon')
654df = pd.read_csv('covid_2021_1.csv') # Replace with actual path
655sia = SentimentIntensityAnalyzer()
656df['sentiment'] = df['comments'].apply(lambda x: sia.polarity_scores(x)['compound'])
657positive = len(df[df['sentiment'] > 0]) / len(df) * 100
658negative = len(df[df['sentiment'] < 0]) / len(df) * 100
659neutral = len(df[df['sentiment'] == 0]) / len(df) * 100
660print(f"Positive: {positive}%, Negative: {negative}%, Neutral: {neutral}%")
661
662Slip No: 25
663Q.1) Write a PHP script for the following: Design a form to accept a number from the user. Perform the operations and show the results. 1) Fibonacci Series. 2) To find sum of the digits of that number. (Use the concept of self processing page.)
664Solution:
665<?php
666if ($_SERVER["REQUEST_METHOD"] == "POST") {
667 $num = $_POST['number'];
668 // Fibonacci
669 $fib = [0, 1];
670 for ($i = 2; $i < $num; $i++) {
671 $fib[] = $fib[$i-1] + $fib[$i-2];
672 }
673 echo "Fibonacci Series: " . implode(", ", array_slice($fib, 0, $num)) . "<br>";
674 // Sum of digits
675 $sum = array_sum(str_split($num));
676 echo "Sum of digits: $sum";
677}
678?>
679<form method="post">
680 Number: <input type="number" name="number"><br>
681 <input type="submit" value="Calculate">
682</form>
683
684Q.2) Build a logistic regression model for Student Score Dataset.
685Solution:
686import pandas as pd
687from sklearn.model_selection import train_test_split
688from sklearn.linear_model import LogisticRegression
689
690data = {'Hours': [2, 3, 4, 5, 6], 'Score': [50, 60, 70, 80, 90], 'Pass': [0, 0, 1, 1, 1]}
691df = pd.DataFrame(data)
692X = df[['Hours', 'Score']]
693y = df['Pass']
694X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
695model = LogisticRegression()
696model.fit(X_train, y_train)
697print("Accuracy:", model.score(X_test, y_test))
698
699Slip No: 29
700Q.1) Create a XML file which gives details of books available in "Bookstore" from following categories. 1) Yoga 2) Story 3) Technical and elements in each category are in the following format <Book> <Book_Title> <Book_Title> <Book_Author> <Book_Author> <Book_Price> <Book_Price> </Book>
701Solution:
702<!-- bookstore.xml -->
703<?xml version="1.0" encoding="UTF-8"?>
704<Bookstore>
705 <Book category="Yoga">
706 <Book_Title>Yoga Basics</Book_Title>
707 <Book_Author>Swami Ji</Book_Author>
708 <Book_Price>300</Book_Price>
709 </Book>
710 <Book category="Story">
711 <Book_Title>Short Tales</Book_Title>
712 <Book_Author>Jane Doe</Book_Author>
713 <Book_Price>200</Book_Price>
714 </Book>
715 <Book category="Technical">
716 <Book_Title>Python Guide</Book_Title>
717 <Book_Author>John Smith</Book_Author>
718 <Book_Price>500</Book_Price>
719 </Book>
720</Bookstore>
721
722Q.2) Consider the following dataset : https://www.kaggle.com/datasets/datasnaek/youtubenew?select=INvideos.csv Write a Python script for the following : i. Read the dataset and perform data cleaning operations on it. ii. Find the total views, total likes, total dislikes and comment count.
723Solution:
724import pandas as pd
725
726df = pd.read_csv('INvideos.csv') # Replace with actual path
727df.dropna(inplace=True)
728print("Total Views:", df['views'].sum())
729print("Total Likes:", df['likes'].sum())
730print("Total Dislikes:", df['dislikes'].sum())
731print("Total Comments:", df['comment_count'].sum())