PHP & Python Scripting Tasks
PHP & Python Scripting Tasks
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;
}
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
Color.html
<!DOCTYPE html>
<html>
<body>
</form>
</body>
</html>
form2.php
<?php
setcookie("style",$_GET['style']);
setcookie("size",$_GET['size']);
setcookie("color",$_GET['color']);
setcookie("bgcolor",$_GET['bgcolor']);
?>
<html>
<body>
</form>
</body>
</html>
form3.php
<html>
<body>
">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">
</form>
</body>
</html>
login.php
<?php
session_start();
$uname=$_GET['uname'];
$pass=$_GET['pass'];
$cnt=$_SESSION["cnt"];
else
if($_SESSION['cnt']==3)
$_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,
emp.html
<!DOCTYPE html>
<html>
<body>
</form>
</body>
</html>
emp1.php
<?php
session_start();
$_SESSION['eno']=$_GET['eno'];
$_SESSION['ename']=$_GET['ename'];
$_SESSION['address']=$_GET['address'];
?>
<html>
<body>
</form>
</body>
</html>
emp2.php
<?php
$a=$_GET['e1'];
$b=$_GET['e2'];
$c=$_GET['e3'];
session_start();
echo "eno".$_SESSION['eno']."<br>";
echo "ename".$_SESSION['ename']."<br>";
echo "address".$_SESSION['address']."<br>";
echo "Basic".$_REQUEST['e1']."<br>";
echo "DA".$_REQUEST['e2']."<br>";
echo "HRA".$_REQUEST['e3']."<br>";
$sum=$a+$b+$c;
?>
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 .
<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 .
<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
echo $xml->asXML();
?>
output=
xyz rathod 400RS 4 pqr rahane 400RS 4 abc mane 400RS 4 sdf nene 400RS 4 ert khan 400RS 4
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
</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) {
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)):
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
<HTML>
<head>sum</head>
<body>
confirm("sum is :"+sum);
</script>
</body>
</HTML>
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)):
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>
<script type="text/javascript">
function valid()
var user=document.message_login.user.value;
var pass=document.message_login.pass.value;
alert("login seccessfully!!!!!!");
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>
TID Items
1 'eggs', 'milk','bread'
2 'eggs', 'apple'
3 'milk', 'bread'
4 'apple', 'milk'
ans:
import pandas as pd
['eggs', 'apple'],
['milk', 'bread'],
['apple', 'milk'],
te=TransactionEncoder()
te_array=te.fit(transactions).transform(transactions)
df=pd.DataFrame(te_array, columns=te.columns_)
df
print(freq_items)
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
<html>
<head>
<script type="text/javascript">
</script>
</head>
<body>
<h2>on click</h2>
<input type="text" name="name" id="n" onClick="asd()">
<h2>on blur</h2>
<h2>on load</h2>
<div id="d"></div>
<script>
function asd()
var a=document.getElementById("n").value;
document.getElementById("n").style.color="red";
document.getElementById("n").style.fontSize="100px";
else
document.getElementById("d").appendChild(image);
</script>
</body>
</html>
TID Items
4 eggs
ans
import pandas as pd
te_array=te.fit(transactions).transform(transactions)
df=pd.DataFrame(te_array, columns=te.columns_)
df
print(freq_items)
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>
function print()
var ob=false;
ob=new XMLHttpRequest();
ob.open("GET","slip12.php?");//emailid="+eid);
ob.send();
ob.onreadystatechange=function()
document.getElementById("i").innerHTML=ob.responseText;
}
</script>
</head>
<body>
<center>
<span id="i"></span>
</center>
</body>
</html>
<?php
$fp = fopen('contact.dat','r');
echo "<tr>";
foreach($row as $r)
echo "<td>$r</td>";
echo "</tr>";
echo "</table>";
fclose($fp);
?>
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
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<script>
function sendRequest() {
if (name == "") {
} else {
xhr.onreadystatechange = function() {
} else {
};
xhr.send();
</script>
</head>
<body>
<h1>AJAX Example</h1>
<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") {
} else {
echo "";
?>
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");
TID Items
4 {Mango , Carrots}
ans:
import pandas as pd
te=TransactionEncoder()
te_array=te.fit(transactions).transform(transactions)
df=pd.DataFrame(te_array, columns=te.columns_)
df
print(freq_items)
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>
<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.";
}
?>
[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)):
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
<!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;
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>
[Marks
12]
17
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fibonacci Numbers</title>
</head>
<body>
<h2>Fibonacci Numbers</h2>
<p id="fibonacciNumbers"></p>
<script>
function printFibonacci() {
var a = 0, b = 1, c;
c = a + b;
a = b;
b = c;
}
document.getElementById("fibonacciNumbers").textContent = output;
</script>
</body>
</html>
. [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'])
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>
:https://www.kaggle.com/nltkdata/movie-review/version/3?select=movie_review.csv
to perform
<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>
20
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]
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>
<tr>
</tr>
</table>
</body>
</html>
[Marks 13]
<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>";
if (!$studentFound) {
echo "<p>No students found for the course: '$course'.</p>";
}
?>
<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
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]
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">
<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(){
$.ajax({
type: "POST",
url: "validate.php",
success: function(response){
$("#message").html(response);
});
});
});
</script>
</head>
<body>
<div id="message"></div>
<label for="name">Name:</label><br>
<label for="age">Age:</label><br>
<label for="nationality">Nationality:</label><br>
</form>
</body>
</html>
//php
<?php
$name = $_POST['name'];
$age = $_POST['age'];
$nationality = $_POST['nationality'];
$message = "";
// Name validation
if (!ctype_upper($name)) {
// Age validation
// Nationality validation
if (strtolower($nationality) != 'indian') {
if ($message == "") {
echo $message;
?>
import pandas as pd
import numpy as np
from sklearn.model_selection
import train_test_split
from sklearn.linear_model import LinearRegression
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)
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. 2 ) Build a simple linear regression model for Car Dataset. [Marks 12]
Ans
import pandas as pd
import numpy as np
from sklearn.model_selection
import train_test_split
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)
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()
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>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
function fibonacci($n){
$fib = [];
$fib[0] = 0;
$fib[1] = 1;
return $fib;
}
function sumOfDigits($number) {
$sum = 0;
return $sum;
$number = $_POST["number"];
echo "<h3>Results:</h3>";
$fibSeries = fibonacci($number);
?>
</body>
</html>
Q. 2 ) Build a logistic regression model for Student Score Dataset. [Marks 12]
ans
import pandas as pd
import numpy as np
from sklearn.model_selection
import train_test_split
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)
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>
<?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");
?>
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)