0% found this document useful (0 votes)
100 views66 pages

PHP & Python Scripting Tasks

Uploaded by

Siddhi Gavhane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views66 pages

PHP & Python Scripting Tasks

Uploaded by

Siddhi Gavhane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

0

Q. 1) Write a PHP script to keep track of number of times the web page has been accessed (Use
Session Tracking).
Ans:-
<?php
session_start();

if(isset($_SESSION['counts'])) {
$_SESSION['counts']++;
} else {

$_SESSION[''counts''] = 1;
}

echo "Number of visits: " . $_SESSION[''counts''];


?>

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

Ans

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
data = pd.read_csv('Position_Salaries.csv')
X = data.iloc[:, 1:2].values
y = data.iloc[:, -1].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
print("Training set - X:")
print(X_train)
print("Training set - y:")
print(y_train)
print("Testing set - X:")
print(X_test)
print("Testing set - y:")
print(y_test)
regressor = LinearRegression()
regressor.fit(X_train, y_train)
1
Q. 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).


[Marks 13]

Color.html
<!DOCTYPE html>

<html>

<body>

<form action="form2.php" method="get">

Enter style :<input type="text" name="style">

Enter size :<input type="text" name="size">

Enter color :<input type="text" name="color">

Enter bgcolor <input type="text" name="bgcolor">

<input type="submit" name="submit" value="submit">

</form>

</body>

</html>

form2.php

<?php

setcookie("style",$_GET['style']);

setcookie("size",$_GET['size']);

setcookie("color",$_GET['color']);
setcookie("bgcolor",$_GET['bgcolor']);

echo "style is ".$_GET['style']."<br>";

echo "size is ".$_GET['size']."<br>";

echo "color is ".$_GET['color']."<br>";

echo "bgcolor is ".$_GET['bgcolor']."<br>";

?>

<html>

<body>

<form action="form3.php" method="get">

<input type="submit" name="submit" value="submit">

</form>

</body>

</html>

form3.php

<html>

<body>

<h3 style="background-color:<?php echo $_COOKIE['bgcolor']; ?>;

font-style:<?php echo $_COOKIE['style']; ?>;

color:<?php echo $_COOKIE['color']; ?>;

font-size:<?php echo $_COOKIE['size']; ?>;

">hello</h3>

</body>

</html>
Q. 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. [Marks 12]

Ans:-

2
Q. 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.[UseSession] [Marks1]

ligin.html

<!DOCTYPE html>

<html lang="en">

<body>

<form action="login.php">

Enter Username<input tyep="text" name="uname"><br>


Enter Password<input type="text" name="pass"><br>

<input type="submit" value="login">

</form>

</body>

</html>

login.php

<?php

session_start();

$uname=$_GET['uname'];

$pass=$_GET['pass'];

$cnt=$_SESSION["cnt"];

if($uname=="abc" && $pass=="12345")

echo "Welcome ".$uname;

else

if($_SESSION['cnt']==3)

echo "You lost chance.....";

$_SESSION['cnt']=0;

else if($cnt<3)

{
echo "incorrect username & password".$_SESSION['cnt'];

$_SESSION['cnt']+=1;

?>

Q. 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.
[Marks 12]

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report

np.random.seed(0)
n_samples = 100
user_id = np.arange(1, n_samples + 1)
gender = np.random.choice(['Male', 'Female'], n_samples)
age = np.random.randint(18, 65, n_samples)
estimated_salary = np.random.normal(50000, 10000, n_samples)
purchased = np.random.choice([0, 1], n_samples)
data = pd.DataFrame({'User ID': user_id, 'Gender': gender, 'Age': age, 'Estimated Salary':
estimated_salary, 'Purchased': purchased})
data['Gender'] = data['Gender'].map({'Female': 0, 'Male': 1})
X = data[['Gender', 'Age', 'Estimated Salary']]
y = data['Purchased']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
logistic_regressor = LogisticRegression()
logistic_regressor.fit(X_train, y_train)
y_pred = logistic_regressor.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
print("Classification Report:")
print(classification_report(y_test, y_pred))
3.
Q. 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]


[Marks 13]

emp.html

<!DOCTYPE html>

<html>

<body>

<form action="emp1.php" method="get">

Enter eno :<input type="text" name="eno">

Enter ename :<input type="text" name="ename">


Enter address :<input type="text" name="address">

<input type="submit" name="submit" value="submit">

</form>

</body>

</html>

emp1.php

<?php

session_start();

$_SESSION['eno']=$_GET['eno'];

$_SESSION['ename']=$_GET['ename'];

$_SESSION['address']=$_GET['address'];

?>

<html>

<body>

<form action="emp2.php" method="get">

Enter Basic :<input type="text" name="e1">

Enter DA :<input type="text" name="e2">

Enter HRA :<input type="text" name="e3">

<input type="submit" name="submit" value="submit">

</form>

</body>

</html>

emp2.php

<?php

$a=$_GET['e1'];
$b=$_GET['e2'];

$c=$_GET['e3'];

session_start();

echo "employee deatails"."<br>";

echo "eno".$_SESSION['eno']."<br>";

echo "ename".$_SESSION['ename']."<br>";

echo "address".$_SESSION['address']."<br>";

echo "earning deatails"."<br>";

echo "Basic".$_REQUEST['e1']."<br>";

echo "DA".$_REQUEST['e2']."<br>";

echo "HRA".$_REQUEST['e3']."<br>";

$sum=$a+$b+$c;

echo "sum is".$sum;

?>

Q. 2)Build a simple linear regression model for Fish Species Weight Prediction.
[Marks 12]
Ans
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score,mean_squared_error
%matplotlib inline
df=pd.read_csv('/content/sample_data/fish.csv')
df.sample(5)
new_df=df.dropna()
x = np.array(new_df[['TV']])
y = np.array(new_df[['Sales']])
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size = 0.25,random_state=15)
regressor = LinearRegression()
regressor.fit(x_train,y_train)
plt.scatter(x_test,y_test,color="green")
plt.plot(x_train,regressor.predict(x_train),color="red",linewidth=3)
plt.title('Regression(Test Set)')
plt.xlabel('TV')
plt.ylabel('Sales')
plt.show()

4 .

Q. 1) Create XML file named


“Item.xml”with item-name, item-rate, item quantity Store the details of 5

Items of different Types


[Marks13]

<?xml version="1.0" ?>

<item>

<itemname>Book</itemname>

<itemprice>400RS</itemprice>

<quality>4</quality>

<itemname>Fruit</itemname>

<itemprice>500RS</itemprice>
<quality>5</quality>

<itemname>stationary</itemname>

<itemprice>600RS</itemprice>

<quality>6</quality>

<itemname>notebbok</itemname>

<itemprice>200RS</itemprice>

<quality>2</quality>

<itemname>pen</itemname>

<itemprice>50RS</itemprice>

<quality>1</quality>

</item>

Q. 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. [Marks 12]

5
Q. 1) Write PHP script to
read “book.xml” file into simpleXML object. Display attributes and elements .

( simple_xml_load_file() function ) [Marks 13]


book.xml

<?xml version="1.0" ?>

<bookinfo>

<book>

<bookname>xyz</bookname>

<author>rathod</author>

<bookprice>400RS</bookprice>

<quality>4</quality>

</book>

<book>

<bookname>pqr</bookname>

<author>rahane</author>

<bookprice>400RS</bookprice>

<quality>4</quality>

</book>

<book>

<bookname>abc</bookname>

<author>mane</author>

<bookprice>400RS</bookprice>

<quality>4</quality>

</book>
<book>

<bookname>sdf</bookname>

<author>nene</author>

<bookprice>400RS</bookprice>

<quality>4</quality>

</book>

<book>

<bookname>ert</bookname>

<author>khan</author>

<bookprice>400RS</bookprice>

<quality>4</quality>

</book>

</bookinfo>

book.php

<?php

$xml=simplexml_load_file("book.xml") or die("not found");

echo $xml->asXML();

?>

output=

xyz rathod 400RS 4 pqr rahane 400RS 4 abc mane 400RS 4 sdf nene 400RS 4 ert khan 400RS 4

Q. 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.
[Marks 12]

6
Q. 1) Write a PHP script to read
“Movie.xml” file and print all MovieTitle and ActorName of file using
DOMDocument Parser. “Movie.xml” file should contain following
information with at least 5 records with values. MovieInfoMovieNo, MovieTitle, ActorName
,ReleaseYear [Marks 13]

ans:

movie.xml

<?xml version="1.0" encoding="UTF-8"?>


<movieInfo>
<movie>
<movieNo>1</movieNo>
<movieTitle>The Shawshank Redemption</movieTitle>
<ActorName>Tim Robbins</ActorName>
<ReleaseYear>1994</ReleaseYear>
</movie>
<movie>
<movieNo>2</movieNo>
<movieTitle>The Godfather</movieTitle>
<ActorName>Marlon Brando</ActorName>
<ReleaseYear>1972</ReleaseYear>
</movie>

</movieInfo>

movie.php

<?php
// Load the XML file
$doc = new DOMDocument();
$doc->load('movie.xml');

$s = simplexml_import_dom($doc);
foreach ($s->movie as $movie) {

echo "The name of the movie is: " . $movie->movieTitle . "<br>";

echo "The name of the Actor is: " . $movie->ActorName . "<br>";


}
?>

Q. 2)Download the Market basket 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
associationrules.
[Marks 12]

ans: import io

import pandas as pd

import numpy as np

df=pd.read_csv('/srv/www/htdocs/anuja/Market_Basket_Optimisation.csv',header=None)

df.head()

df.fillna(0,inplace=True)

transactions = []

for i in range(0,len(df)):

transactions.append([str(df.values[i,j]) for j in range(0,20) if str(df.values[i,j])!='0'])

from mlxtend.preprocessing import TransactionEncoder

te=TransactionEncoder()

te_array=te.fit(transactions).transform(transactions)

df=pd.DataFrame(te_array,columns=te.columns_)

df
freq_items=apriori(df,min_support=0.01,use_colnames=True)

print(freq_items)

rules=association_rules(freq_items,metric='support',min_threshold=0.01)

rules=rules.sort_values(['support','confidence'],ascending=[False,False])

print(rules)

7
Q. 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) [Marks 13]

<!DOC TYPE HTML>

<HTML>

<head>sum</head>

<body>

<script type="text/java script">

alert("Exam are nearer you have prepared for it!!!!!!!!!!!!!!");

var num1=prompt("enter 1 st number");

var num2=prompt("enter 2 ND number");

var sum=parse Int(num1)+parse Int(num2);

confirm("sum is :"+sum);

</script>
</body>

</HTML>

Q. 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 associationrules.
[Marks12]
import io

import pandas as pd

import numpy as np

df=pd.read_csv('/srv/www/htdocs/anuja/GroceryDataset.csv',header=None)

df.head()

df.fillna(0,inplace=True)

transactions = []

for i in range(0,len(df)):

transactions.append([str(df.values[i,j]) for j in range(0,8) if str(df.values[i,j])!='0'])

from mlxtend.preprocessing import TransactionEncoder

te=TransactionEncoder()

te_array=te.fit(transactions).transform(transactions)

df=pd.DataFrame(te_array,columns=te.columns_)

df

freq_items=apriori(df,min_support=0.1,use_colnames=True)

print(freq_items)

rules=association_rules(freq_items,metric='support',min_threshold=0.1)
rules=rules.sort_values(['support','confidence'],ascending=[False,False])

print(rules)

Q. 1) Write a JavaScript
function to validate username and password for a membership form.

[Marks 13]

username.php

<html>

<body>

<form name="message_login" onsubmit="valid()" method="post">

Username:<input type="text" name="user">

Password:<input type="text" name="pass">

<input type="submit" name="submit" value="submit">

</form>

<script type="text/javascript">
function valid()

var user=document.message_login.user.value;

var pass=document.message_login.pass.value;

if(user==="rutuja " && pass==="1234")

alert("login seccessfully!!!!!!");

else if(user==" " || pass==" ")

alert("empty username and password");

else

alert("invalid");

</script>

</body>

Q. 2)Create your own transactions dataset and apply the above process on
your dataset. [Marks 12]

9
Q. 1)Create a HTML file to insert text before and after a Paragraph
using jQuery. [Hint : Use before( ) and after( )]
[Marks
13]

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"
integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
crossorigin="anonymous"></script>
</head>
<body>
<input type="button" value="before" id="before">
<input type="button" value="after" id="after">
<script>
$(document).ready(function(){
$("#before").click(function(){
$("p").before('<div>before paragraph</div>');
});

$("#after").click(function(){
$("p").after('<div>After paragraph</div>');
});
})
</script>
<p>hello</p>
</body>
</html>

Q. 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.
[Marks 12]

TID Items

1 'eggs', 'milk','bread'

2 'eggs', 'apple'

3 'milk', 'bread'

4 'apple', 'milk'

5 'milk', 'apple', 'bread'

ans:

import pandas as pd

from mlxtend.frequent_patterns import apriori, association_rules

transactions = [['eggs', 'milk','bread'],

['eggs', 'apple'],

['milk', 'bread'],

['apple', 'milk'],

['milk', 'apple', 'bread']]

from mlxtend.preprocessing import TransactionEncoder

te=TransactionEncoder()

te_array=te.fit(transactions).transform(transactions)

df=pd.DataFrame(te_array, columns=te.columns_)
df

freq_items = apriori(df, min_support = 0.5, use_colnames = True)

print(freq_items)

rules = association_rules(freq_items, metric ='support', min_threshold=0.05)

rules = rules.sort_values(['support', 'confidence'], ascending =[False,False])

print(rules)

10
Q. 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, onmousehover, onmouseclick, onmouseup) [Marks 13]

<html>

<head>

<script type="text/javascript">

</script>

</head>

<body>

Enter name :<input type="text" name="name" id="n">

<h2>on click</h2>
<input type="text" name="name" id="n" onClick="asd()">

<h2>on blur</h2>

<input type="text" name="name" id="n" onblur="asd()">

<h2>on load</h2>

<input type="text" name="name" id="n" onload="asd()">

<div id="d"></div>

<script>

function asd()

var a=document.getElementById("n").value;

if(a !=" ")

document.getElementById("n").style.color="red";

document.getElementById("n").style.fontSize="100px";

else

var image=new Image();

image.src="/home/bcs/Pictures/Screenshot from 2024-04-03 13-18-46.png";

document.getElementById("d").appendChild(image);

</script>

</body>
</html>

Q. 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 associationrules. Repeat the
process with different min_sup values. [Marks 12]

TID Items

1 butter, bread, milk

2 butter, flour, milk,


sugar

3 butter, eggs, milk, salt

4 eggs

5 butter, flour, milk,salt

ans

import pandas as pd

from mlxtend.frequent_patterns import apriori, association_rules

transactions = [[butter, bread, milk ],

[butter, flour, milk,],

[ butter, eggs, milk, ‘salt'],

[butter, flour, milk,salt]]

from mlxtend.preprocessing import TransactionEncoder


te=TransactionEncoder()

te_array=te.fit(transactions).transform(transactions)

df=pd.DataFrame(te_array, columns=te.columns_)

df

freq_items = apriori(df, min_support = 0.6, use_colnames = True)

print(freq_items)

rules = association_rules(freq_items, metric ='support', min_threshold=0.05)

rules = rules.sort_values(['support', 'confidence'], ascending =[False,False])

print(rules)

11
Q. 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 srno, name, residence number, mobile number,
Address. [Enter at least 3 record in contact.dat file] [Marks 13]

<html>

<head>

<style>

span

font-size: 25px;

}
table

color: blueviolet; ;

</style>

<script type="text/javascript" >

function print()

var ob=false;

ob=new XMLHttpRequest();

ob.open("GET","slip12.php?");//emailid="+eid);

ob.send();

ob.onreadystatechange=function()

if(ob.readyState==4 && ob.status==200)

document.getElementById("i").innerHTML=ob.responseText;

}
</script>

</head>

<body>

<center>

<h3>Display the contents of a contact.dat file </h3>


<br><input type="button" value=Print onclick="print()" >

<span id="i"></span>

</center>

</body>

</html>

Dat file : contact.dat

1 Isha 65768798 98765432 Daughter

2 Megha 65235689 87654329 Mother

PHP File: Slip12.php

<?php

$fp = fopen('contact.dat','r');

echo "<table border=1>";

echo "<tr><th>Sr. No.</th><th>Name</th><th>Residence No.</th><th>Mob.


no.</th><th>Relation</th></tr>";

while($row = fscanf($fp,"%s %s %s %s %s"))

echo "<tr>";

foreach($row as $r)

echo "<td>$r</td>";

echo "</tr>";

echo "</table>";
fclose($fp);

?>

Q. 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. [Marks


12]

12
Q. 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!” [Marks


13]

HTML File: server.html

<!DOCTYPE html>

<html>
<head>

<title>AJAX Example</title>

<script>

function sendRequest() {

var name = document.getElementById("name").value;

var message = document.getElementById("message");

if (name == "") {

message.innerHTML = "Stranger, please tell me your name!";

} else {

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {

if (this.readyState == 4 && this.status == 200) {

if (this.responseText == "Hello, master !") {

message.innerHTML = "Hello, master !";

} else {

message.innerHTML = name + ", I don't know


you!";

};

xhr.open("GET", "server.php?name=" + name, true);

xhr.send();

</script>

</head>
<body>

<h1>AJAX Example</h1>

<input type="text" id="name" onkeyup="sendRequest()">

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

</body>

</html>

.
PHP File: server php

<?php

$name = $_GET["name"];

if ($name == "") {

echo "";

} else if ($name == "Rohit" || $name == "Virat" || $name == "Dhoni" || $name == "Ashwin" || $name
== "Harbhajan") {

echo "Hello, master !";

} else {

echo "";

?>

Q. 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.
[Marks 12]

13

Q. 1) Create TEACHER table as


follows TEACHER(tno, tname, qualification, salary). Write Ajax program to
select a teachers name and print the selected teachers details [Marks
13]

<!DOCTYPE html>
<html>
<head>
<title>Display Teacher Details</title>
<script type="text/javascript">
function print() {
var n = document.getElementById("n").value;
var x = new XMLHttpRequest();
x.open("GET", "teacher1.php?n=" + n, true);
x.send();
x.onreadystatechange = function() {
if (x.readyState == 4 && x.status == 200) {
document.getElementById("i").innerHTML = x.responseText;
}
}
}
</script>
</head>
<body>
<center>
<h3>Display the teacher detail</h3>
Enter teacher name: <input type="text" name="n" id="n">
<br><br>
<input type="button" value="Print" onclick="print()">
<br><br>
<span id="i"></span>
</center>
</body>
</html>

<?php
$name=$_GET['n'];
$con=pg_connect("host=localhost dbname=postgres user=postgres password=123");

$rs=pg_query($con,"select * from teacher where tname='".$name."'");


if($rs){
while($row=pg_fetch_row($rs)){
echo $row[0]." ".$row[1]." ".$row[2];
}
}
pg_close($con);
?>

Q. 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. [Marks


12]

TID Items

1 {Apple , Mango , Banana}


2 {Mango , Banana , Cabbage ,
Carrots}

3 {Mango , Banana ,Carrots}

4 {Mango , Carrots}

ans:

import pandas as pd

from mlxtend.frequent_patterns import apriori, association_rules

transactions = [[' Apple , Mango , Banana '],

[' Mango , Banana , Cabbage, Carrots '],

[' Mango , Banana ,Carrots '],

[' Mango , Carrots ']]

from mlxtend.preprocessing import TransactionEncoder

te=TransactionEncoder()

te_array=te.fit(transactions).transform(transactions)

df=pd.DataFrame(te_array, columns=te.columns_)

df

freq_items = apriori(df, min_support = 0.5, use_colnames = True)

print(freq_items)

rules = association_rules(freq_items, metric ='support', min_threshold=0.05

rules = rules.sort_values(['support', 'confidence'], ascending =[False,False])

print(rules)
14
Q. 1) Write Ajax program to
fetch suggestions when is user is typing in a textbox. (eg like google
suggestions. Hint create array of suggestions and matching string will be
displayed) [Marks 13]

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Suggestion Box</title>
<script>
function showSuggestions() {
const input = document.getElementById('userInput').value.trim();
const suggestionsContainer = document.getElementById('suggestions');
const suggestions = ['apple', 'banana', 'cherry', 'date', 'grape',
'kiwi', 'lemon', 'mango', 'orange', 'peach'];
suggestionsContainer.innerHTML = '';

if (input.length > 0) {
const words = input.split(/\s+/); // Split input into individual
words
words.forEach(word => {
suggestions.forEach(suggestion => {
if (suggestion.includes(word)) {
suggestionsContainer.innerHTML += `<div
onclick="selectSuggestion('${suggestion}')">${suggestion}</div>`;
}
});
});
}
}
function selectSuggestion(value) {
document.getElementById('userInput').value = value;
document.getElementById('suggestions').innerHTML = '';
}
</script>
</head>
<body>
<h2> Search engine</h2>
<label for="userInput">Start typing:</label>
<input type="text" id="userInput" onkeyup="showSuggestions()">
<div id="suggestions" style="cursor: pointer;"></div>
</body>
</html>

Q. 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. [Marks 12]

Q. 3) Viva [Marks 05]


15
Q. 1) Write Ajax program to get
book details from XML file when user select a book name. Create XML file for
storing details of book(title, author, year, price). [Marks
13]

<?xml version="1.0" encoding="UTF-8"?>


<bookinfo>
<book name="PHP">
<title>PHP</title>
<author>John Doe</author>
<year>2021</year>
<price>39.99</price>
</book>

<book name="java">
<title>java</title>
<author>xyz</author>
<year>2003</year>
<price>12.10</price>
</book>
</bookinfo>

<!DOCTYPE html>
<html>
<head>
<title>Display Teacher Details</title>
<script type="text/javascript">
function print() {
var n = document.getElementById("n").value;
var x = new XMLHttpRequest();
x.open("GET", "bookxml1.php?n=" + n, true);
x.send();
x.onreadystatechange = function() {
if (x.readyState == 4 && x.status == 200) {
document.getElementById("i").innerHTML = x.responseText;
}
}
}
</script>
</head>
<body>
<center>
<h3>Display the Book detail</h3>
Enter Book name: <input type="text" name="n" id="n">

<br><br>
<input type="button" value="Print" onclick="print()">
<br><br>
<span id="i"></span>
</center>
</body>
</html>

<?php
$title = isset($_GET['n']) ? $_GET['n'] : '';

$xml = simplexml_load_file('book.xml');

$bookFound = false;
foreach ($xml->book as $book) {
if (strcasecmp($book->title, $title) == 0) {
echo "Title: " . $book->title . "<br>";
echo "Author: " . $book->author . "<br>";
echo "Year: " . $book->year . "<br>";
echo "Price: $" . $book->price;
$bookFound = true;
break;
}
}

if (!$bookFound) {
echo "Book titled '$title' not found.";
}
?>

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

[Marks12]

Ans:

import io

import pandas as pd

import numpy as np

df=pd.read_csv('/srv/www/htdocs/anuja/GroceryDataset.csv',header=None)

df.head()

df.fillna(0,inplace=True)

transactions = []

for i in range(0,len(df)):

transactions.append([str(df.values[i,j]) for j in range(0,8) if str(df.values[i,j])!='0'])

from mlxtend.preprocessing import TransactionEncoder

te=TransactionEncoder()

te_array=te.fit(transactions).transform(transactions)

df=pd.DataFrame(te_array,columns=te.columns_)

df

freq_items=apriori(df,min_support=0.1,use_colnames=True)

print(freq_items)

rules=association_rules(freq_items,metric='support',min_threshold=0.1)

rules=rules.sort_values(['support','confidence'],ascending=[False,False])

print(rules)
16

Q. 1) Write a Java Script


Program to show Hello Good Morning message onload event using alert box and
display the Student registration from.
[Marks
13]

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Registration Form</title>
<script>
function displayGreeting() {
alert("Hello, Good Morning!");
// Show the form after the user clicks "OK"
document.getElementById("registrationForm").style.display = "block";
}

function validateForm() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var age = document.getElementById("age").value;

if (name === "" || email === "" || age === "") {


alert("Please fill in all fields.");
return false;
}

return true;
}
</script>
</head>
<body onload="displayGreeting()">
<h2>Student Registration Form</h2>
<!-- Initially hide the form -->
<form id="registrationForm" onsubmit="return validateForm()" style="display:
none;">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br>
<label for="age">Age:</label><br>
<input type="number" id="age" name="age"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Q. 2) Consider text paragraph.So, keep working. Keep striving. Never


give up. Fall down seven times, get up eight. Ease is a greater threat to
progress than hardship. Ease is a greater threat to progress than hardship. So,
keep moving, keep growing, keep learning. See you at work.Preprocess the text
to remove any special characters and digits. Generate the summary using
extractive summarization process.

[Marks
12]

17

Q. 1) Write a Java Script Program to print Fibonacci numbers on onclick


event. [Marks
13]
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Fibonacci Numbers</title>

</head>

<body>

<h2>Fibonacci Numbers</h2>

<p>Enter the limit:</p>

<input type="number" id="limit">

<button onclick="printFibonacci()">Print Fibonacci</button>

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

<script>

function printFibonacci() {

var limit = parseInt(document.getElementById("limit").value);

var output = "Fibonacci numbers up to " + limit + ": ";

var a = 0, b = 1, c;

output += a + ", " + b;

for (var i = 2; i <= limit; i++) {

c = a + b;

output += ", " + c;

a = b;

b = c;

}
document.getElementById("fibonacciNumbers").textContent = output;

</script>

</body>

</html>

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

. [Marks 12]
ans

import io

import pandas as pd

import numpy as np

df=pd.read_csv('/srv/www/htdocs/rutuja/GroceryDataset.csv',header=None)

df.head()

df.fillna(0,inplace=True)

transactions = []

for i in range(0,len(df)):
transactions.append([str(df.values[i,j]) for j in range(0,8) if str(df.values[i,j])!='0'])

from mlxtend.preprocessing import TransactionEncoder

te=TransactionEncoder()

te_array=te.fit(transactions).transform(transactions)

df=pd.DataFrame(te_array,columns=te.columns_)

df

freq_items=apriori(df,min_support=0.1,use_colnames=True)

print(freq_items)

rules=association_rules(freq_items,metric='support',min_threshold=0.1)

rules=rules.sort_values(['support','confidence'],ascending=[False,False])

print(rules)

18
Q. 1) Write a Java Script Program to validate user name and password on
onSubmit event.

[Marks 13]

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Form Validation</title>
<script>
function validateCredentials() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (password.length < 8) {
alert("Password must be at least 8 characters long.");
return false;
}
return true;
}
function login(){
alert("thanks for registration" )
}
</script>
</head>
<body>
<h2>Login Form</h2>
<form onsubmit=" validateCredentials()">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username" required><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login" onclick="login()">
</form>
</body>
</html>

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


[Marks 12]
19
Q. 1) create a student.xml file containing at least 5 student
information [Marks 13]

<?xml version="1.0" encoding="UTF-8"?>

<students>

<student>

<id>1</id>

<name>John Doe</name>

<age>20</age>

<gender>Male</gender>

<grade>A</grade>

</student>

<student>

<id>2</id>

<name>Jane Smith</name>

<age>21</age>

<gender>Female</gender>

<grade>B</grade>

</student>

<student>
<id>3</id>

<name>Michael Johnson</name>

<age>22</age>

<gender>Male</gender>

<grade>C</grade>

</student>

<student>

<id>4</id>

<name>Emily Davis</name>

<age>19</age>

<gender>Female</gender>

<grade>B+</grade>

</student>

<student>

<id>5</id>

<name>David Wilson</name>

<age>20</age>

<gender>Male</gender>

<grade>A-</grade>

</student>

</students>

Q. 2) Build a simple linear regression model for User Data. [Marks12]


Q. 3) Viva [Marks
05]

20

Q. 1)Add a JavaScript File in


Codeigniter. The Javascript code should check whether a number is positive or
negative.
[Marks 13]

Q. 2)Build a simple linear regression model for User Data.


[Marks 12]

21
Q. 1)Create a table student having attributes(rollno, name, class).
Using codeigniter, connect to the database and insert 5 recodes in
it.
[Marks 13]

Q. 2) Build a simple linear regression model for User Data.


[Marks 12]

22
Q. 1) Create a table student
having attributes(rollno, name, class) containing atleast 5 recodes . Using
codeigniter, display all its records.

[Marks 13

<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8">

<title>Student Records</title>

</head>

<body>

<h2>Student Records</h2>

<table border="1">

<tr>

<th>Roll No</th>

<th>Name</th>

<th>Class</th>

</tr>

<?php foreach ($students as $student): ?>

<tr>

<td><?php echo $student['rollno']; ?></td>

<td><?php echo $student['name']; ?></td>

<td><?php echo $student['class']; ?></td>

</tr>

<?php endforeach; ?>

</table>

</body>

</html>

Q. 2) Consider any text paragraph. Preprocess the text to remove any


special characters and digits.
[Marks 12]
23

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

[Marks 13]

<?xml version="1.0" encoding="UTF-8"?>


<studinfo>
<student >
<rollno>1</rollno>
<name>Nikita</name>
<address>sangamner</address>
<college>sangamner college</college>
<course>bcs</course>
</student>

<student>
<rollno>2</rollno>
<name>pallavi</name>
<address>sangamner</address>
<college>sangamner college</college>
<course>bcs</course>
</student>
<student>
<rollno>3</rollno>
<name>Anuja</name>
<address>sangamner</address>
<college>sangamner college</college>
<course>bcs</course>
</student>
<student>
<rollno>4</rollno>
<name>Rutuja</name>
<address>sangamner</address>
<college>sangamner college</college>
<course>bcom</course>
</student>
</studinfo>

<!DOCTYPE html>
<html>
<head>
<title>Display Teacher Details</title>
<script type="text/javascript">
function print() {
var n = document.getElementById("n").value;
var x = new XMLHttpRequest();
x.open("GET", "stud1.php?n=" + n, true);
x.send();
x.onreadystatechange = function() {
if (x.readyState == 4 && x.status == 200) {
document.getElementById("i").innerHTML = x.responseText;
}
}
}
</script>
</head>
<body>
<center>
<h3>Display the student detail</h3>
Enter course name: <input type="text" name="n" id="n">

<br><br>
<input type="button" value="Print" onclick="print()">
<br><br>
<span id="i"></span>
</center>
</body>
</html>

<?php
$course = isset($_GET['n']) ? $_GET['n'] : '';
$xml = simplexml_load_file('student.xml');
$studentFound = false;

echo "<table border='1'>";


echo "<tr><th>Roll
No</th><th>Name</th><th>Address</th><th>College</th><th>Course</th></tr>";

foreach ($xml->student as $student) {


if (strcasecmp($student->course, $course) == 0) {
$studentFound = true; // Set to true if at least one student is found
echo "<tr>";
echo "<td>{$student->rollno}</td>";
echo "<td>{$student->name}</td>";
echo "<td>{$student->address}</td>";
echo "<td>{$student->college}</td>";
echo "<td>{$student->course}</td>";
echo "</tr>";
}
}

echo "</table>";
if (!$studentFound) {
echo "<p>No students found for the course: '$course'.</p>";
}
?>

Q. 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. [Marks 12]
24
Q. 1) Write a script to create
“cricket.xml” file with multiple elements as shown below: <CricketTeam>
<Team country=”Australia”>
<player>____</player> <runs>______</runs>

<wicket>____</wicket>
</Team>
</CricketTeam>
Write a script to add multiple
elements in “cricket.xml” file of category, country=”India”. [Marks 13]

<?php

$ct=new simplexmlelement("<CricketTeam/>");

$country=$ct->addChild("Team");

$country->addAttribute("country","Austrilia");

$country->addChild("player","dhoni");

$country->addChild("run","1000");

$country->addChild("wickets","1");

$country->addAttribute("country","India");

$country->addChild("player","virat");

$country->addChild("run","1200");

$country->addChild("wickets","2");
$ct->asXML("cricket1.xml");

?>

output=

<CricketTeam>

<Team country="Austrilia">

<player>dhoni</player>

<run>1000</run>

<wickets>1</wickets>

<player>virat</player>

<run>1200</run>

<wickets>2</wickets>

</Team>

</CricketTeam>
Q. 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.. [Marks 12]

26
Q. 1)Create employee table as
follows EMP (eno, ename, designation, salary). Write Ajax program to select the
employees name and print the selected employee’s details. [Marks 13]

Q. 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.""" Preprocess
the text to remove any special characters and digits. Generate the summary
using extractive summarization
process.
[Marks 12]

27
Q.1) Create web Application that contains Voters details and check
proper validation for (name, age, and nationality), as Name should be in upper
case letters only, Age should not be less than 18 yrs and Nationality should be
Indian.(use HTML-AJAX-PHP) [Marks 13]
Ans:
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Voter Registration</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

$("#submit-btn").click(function(){

var name = $("#name").val();

var age = $("#age").val();

var nationality = $("#nationality").val();

$.ajax({

type: "POST",

url: "validate.php",

data: {name: name, age: age, nationality: nationality},

success: function(response){

$("#message").html(response);

});

});

});

</script>

</head>
<body>

<h2>Voter Registration Form</h2>

<div id="message"></div>

<form id="voter-form" action="#" method="post">

<label for="name">Name:</label><br>

<input type="text" id="name" name="name" required><br>

<label for="age">Age:</label><br>

<input type="number" id="age" name="age" required><br>

<label for="nationality">Nationality:</label><br>

<input type="text" id="nationality" name="nationality" required><br><br>

<input type="button" id="submit-btn" value="Submit">

</form>

</body>

</html>

//php

<?php

$name = $_POST['name'];

$age = $_POST['age'];

$nationality = $_POST['nationality'];

$message = "";

// Name validation

if (!ctype_upper($name)) {

$message .= "Name should be in upper case letters only.<br>";


}

// Age validation

if ($age < 18) {

$message .= "Age should not be less than 18 years.<br>";

// Nationality validation

if (strtolower($nationality) != 'indian') {

$message .= "Nationality should be Indian.<br>";

// Check if any validation errors occurred

if ($message == "") {

$message = "Validation successful. Voter details registered!";

echo $message;

?>

Q. 2 ) Build a simple linear regression model for Car Dataset. [Marks


12]

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

from sklearn.model_selection

import train_test_split
from sklearn.linear_model import LinearRegression

from sklearn.metrics import

r2_score,mean_squared_error %matplotlib inline

df = pd.read_csv('C:/rutuja /car_data.csv')

df.sample(5)

print(df.shape)

print(df['Make'].value_counts())

X = np.array(new_df[['Engine HP']])

y = np.array(new_df[['MSRP']])

print(X.shape)

X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.25,random_state=15)

plt.scatter(X_train,y_train,color="blue")

plt.plot(X_train,regressor.predict(X_train),color="red",linewidth=3)

plt.title('Regression(training Set)')

plt.xlabel('HP')

plt.ylabel('MSRP')

plt.show()

Q. 3) Viva [Marks 05]


28
Q. 1)Write a PHP script using
AJAX concept, to check user name and password are valid or Invalid (use database to store user name
and password).
[Marks 13]

Q. 2 ) Build a simple linear regression model for Car Dataset. [Marks 12]

Ans

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

from sklearn.model_selection

import train_test_split

from sklearn.linear_model import LinearRegression

from sklearn.metrics import

r2_score,mean_squared_error %matplotlib inline

df = pd.read_csv('C:/rutuja /car_data.csv')

df.sample(5)

print(df.shape)

print(df['Make'].value_counts())

X = np.array(new_df[['Engine HP']])

y = np.array(new_df[['MSRP']])

print(X.shape)

X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.25,random_state=15)

plt.scatter(X_train,y_train,color="blue")

plt.plot(X_train,regressor.predict(X_train),color="red",linewidth=3)
plt.title('Regression(training Set)')

plt.xlabel('HP')

plt.ylabel('MSRP')

plt.show()

Q. 3) Viva [Marks 05]

29
Q. 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.)
[Marks 13]
ans

<!DOCTYPE html>

<html>
<head>

<title>Number Operations</title>

</head>

<body>

<h2>Number Operations</h2>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Enter a number: <input type="number" name="number" required><br><br>

<input type="submit" name="submit" value="Submit">

</form>

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Function to generate Fibonacci series

function fibonacci($n){

$fib = [];

$fib[0] = 0;

$fib[1] = 1;

for ($i = 2; $i < $n; $i++) {

$fib[$i] = $fib[$i - 1] + $fib[$i - 2];

return $fib;
}

// Function to find sum of digits

function sumOfDigits($number) {

$sum = 0;

while ($number > 0) {

$sum += $number % 10;

$number = (int)($number / 10);

return $sum;

$number = $_POST["number"];

echo "<h3>Results:</h3>";

// Display Fibonacci series

echo "<p>Fibonacci Series up to $number: ";

$fibSeries = fibonacci($number);

echo implode(", ", $fibSeries) . "</p>";

// Display sum of digits

echo "<p>Sum of digits of $number: " . sumOfDigits($number) . "</p>";

?>
</body>

</html>

Q. 2 ) Build a logistic regression model for Student Score Dataset. [Marks 12]

ans

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

from sklearn.model_selection

import train_test_split

from sklearn.linear_model import LinearRegression

from sklearn.metrics import

r2_score,mean_squared_error %matplotlib inline

data = pd.read_csv("C:\rutuja \Student_Score.csv")

x = dataset.iloc[:, [2,3]].values

y = dataset.iloc[:, 4].values

x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.25,random_state=0)

logistic_regression= LogisticRegression() logistic_regression.fit(x_train,y_train)

print('Accuracy: ',metrics.accuracy_score(y_test, y_pred))

plt.show()

30
Q.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_Autor>

<Book_Price> [Marks13] BookCategory.xml

<?php

$bookstore=new SimpleXMLElement("<BookStore/>");

$Book=$bookstore->addChild("Book");

$Book->addChild("Book_title","Yoga");

$Book->addChild("Book_author","abc");

$Book->addChild("Book_Price","500");

$Book=$bookstore->addChild("Book");

$Book->addChild("Book_title","Story");

$Book->addChild("Book_author","xyz");

$Book->addChild("Book_Price","400");

$Book=$bookstore->addChild("Book");

$Book->addChild("Book_title","Technical");

$Book->addChild("Book_author","sai");

$Book->addChild("Book_Price","1000");

$bookstore->asXML("BookCategory.xml");
?>

Q. 2 ) Create the dataset . transactions = [['eggs', 'milk','bread'],


['eggs', 'apple'], ['milk', 'bread'], ['apple', 'milk'], ['milk', 'apple',
'bread']] .
Convert the categorical values into numeric format.Apply the apriori
algorithm on the above dataset to generate the frequent itemsets and
association rules.
[Marks 12]

ans
import pandas as pd
from mlxtend.frequent_patterns import apriori, association_rules
transactions = [['eggs', 'milk','bread'],
['eggs', 'apple'],
['milk', 'bread'],
['apple', 'milk'],
['milk', 'apple', 'bread']]
from mlxtend.preprocessing import TransactionEncoder
te=TransactionEncoder()
te_array=te.fit(transactions).transform(transactions)
df=pd.DataFrame(te_array, columns=te.columns_)
df
freq_items = apriori(df, min_support = 0.5, use_colnames = True)
print(freq_items)

You might also like