Slip 1-15 WT and DA


WT and DA

@Slip – 1

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[‘pcount])) { $_SESSION[‘pcount] += 1; } else { $_SESSION[‘pcount] = 1; } Echo “You have visited this page “.$_SESSION[‘pcount].” Time(s).”; ?>

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

Create the Position_Salaries dataset

Data = {‘Position’: [‘CEO’, ‘charman’, ‘director’, ‘Senior Manager’, ‘Junior Manager’, ‘Intern’],
‘Level’: [1, 2, 3, 4, 5, 6],
‘Salary’: [50000, 80000, 110000, 150000, 200000, 250000]}
Df = pd.DataFrame(data)

Identify the independent and target variables

X = df.iloc[:, 1:2].values
Y = df.iloc[:, 2].values

Split the variables into training and testing sets with a 7:3 ratio

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

Print the training and testing sets

Print(“X_train:\n”, X_train)
Print(“y_train:\n”, y_train)
Print(“X_test:\n”, X_test)
Print(“y_test:\n”, y_test)

Build a simple linear regression model

Regressor = LinearRegression()
Regressor.fit(X_train, y_train)

Print the coefficients and intercept

Print(“Coefficients:”, regressor.coef_)
Print(“Intercept:”, regressor.intercept_)

@Slip-2

Q. 1Write 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).

Ans :

Fristpage.html

<!DOCTYPE html> <html> <head> <title>Change preferences</title> </head> <body> <h1>Change preferences</h1> <form action=”secondpage.php” method=”post”> <label for=”fontstyle”>Font Style:</label> <select name=”fontstyle” id=”fontstyle”> <option value=”Arial”>Arial</option> <option value=”Times New Roman”>Times New Roman</option> <option value=”Verdana”>Verdana</option> </select><br><br> <label for=”fontsize”>Font Size:</label> <select name=”fontsize” id=”fontsize”> <option value=”12”>12</option> <option value=”14”>14</option> <option value=”16”>16</option> </select><br><br> <label for=”fontcolor”>Font Color:</label> <input type=”color” name=”fontcolor” id=”fontcolor”><br><br> <label for=”bgcolor”>Background Color:</label> <input type=”color” name=”bgcolor” id=”bgcolor”><br><br> <input type=”submit” name=”submit” value=”Save”> </form> </body> </html>

Secondpage.php

<?php If(isset($_POST[‘submit’])) { $fontstyle = $_POST[‘fontstyle’]; $fontsize = $_POST[‘fontsize’]; $fontcolor = $_POST[‘fontcolor’]; $bgcolor = $_POST[‘bgcolor’]; // Set the cookie values Setcookie(‘fontstyle’, $fontstyle, time()+86400); Setcookie(‘fontsize’, $fontsize, time()+86400); Setcookie(‘fontcolor’, $fontcolor, time()+86400); Setcookie(‘bgcolor’, $bgcolor, time()+86400); // Redirect to the next page Header(‘Location: thirdpage.php’); Exit(); } ?>

Thirdpage.php

<?php // Retrieve the cookie values $fontstyle = isset($_COOKIE[‘fontstyle’]) ? $_COOKIE[‘fontstyle’] : ‘Arial’; $fontsize = isset($_COOKIE[‘fontsize’]) ? $_COOKIE[‘fontsize’] : ‘12’; $fontcolor = isset($_COOKIE[‘fontcolor’]) ? $_COOKIE[‘fontcolor’] : ‘#000000’; $bgcolor = isset($_COOKIE[‘bgcolor’]) ? $_COOKIE[‘bgcolor’] : ‘#FFFFFF’; ?> <!DOCTYPE html> <html> <head> <title>Page with new settings</title> <style type=”text/css”> Body { Font-family: <?php echo $fontstyle ?>; Font-size: <?php echo $fontsize ?>px; Color: <?php echo $fontcolor ?>; Background-color: <?php echo $bgcolor ?>; } </style> </head> <body> <h1>Page with new settings</h1> <p>This is the page with the new settings. The font style is <?php echo $fontstyle ?>, the font size is <?php echo $fontsize ?>px, the font color is <?php echo $fontcolor ?>, and the background color is <?php echo $bgcolor ?>.</p> </body> </html>

Q. 2)Create ‘Salary’ Data set . Build a linear regression model by identifying independent and target
Ariable. Split the variables into training and testing sets and print them. Build a simple linear regression
Del for predicting purchases.

Ans:
Import numpy as np
Import pandas as pd
From sklearn.model_selection import train_test_split
From sklearn.linear_model import LinearRegression

Create the Salary dataset

Data = {‘YearsExperience’: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
‘Salary’: [50000, 60000, 70000, 80000, 90000, 100000, 110000, 120000, 130000, 140000]}
Df = pd.DataFrame(data)

Identify the independent and target variables

X = df.iloc[:, 0:1].values
Y = df.iloc[:, 1].values

Split the variables into training and testing sets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

Print the training and testing sets

Print(“X_train:\n”, X_train)
Print(“y_train:\n”, y_train)
Print(“X_test:\n”, X_test)
Print(“y_test:\n”, y_test)

Build a simple linear regression model

Regressor = LinearRegression()
Regressor.fit(X_train, y_train)

Print the coefficients and intercept

Print(“Coefficients:”, regressor.coef_)
Print(“Intercept:”, regressor.intercept_)

@Slip-3

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. [Use Session]

.

Ans:

<?php // Start session Session_start(); // Check if login form has been submitted If(isset($_POST[‘submit’])) { // Get username and password input from user $username = $_POST[‘username’]; $password = $_POST[‘password’]; // Set correct username and password $correct_username = ‘myusername’; $correct_password = ‘mypassword’; // Check if entered username and password are correct If($username == $correct_username && $password == $correct_password) { // Set session variable to mark user as logged in $_SESSION[‘loggedin’] = true; // Redirect user to welcome page Header(‘Location: welcome.php’); Exit; } else { // Decrement login attempts If(isset($_SESSION[‘attempts’])) { $_SESSION[‘attempts’]--; } else { $_SESSION[‘attempts’] = 3; } // Display error message if maximum login attempts exceeded If($_SESSION[‘attempts’] <= 0) { Echo “Maximum login attempts exceeded. Please try again later.”; } else { // Display error message Echo “Invalid username or password. You have “.$_SESSION[‘attempts’].” Attempt(s) left.”; } } } ?>

<!—HTML form for user input 🡪

<form method=”post”> <label for=”username”>Username:</label> <input type=”text” id=”username” name=”username” required><br><br>

<label for=”password”>Password:</label>
<input type=”password” id=”password” name=”password” required><br><br>

<input type=”submit” name=”submit” value=”Log In”>

</form>

Q. 2)Create ‘User’ Data set having 5 columns namely: User ID, Gender, Age, Estimated Salary and urchased. Build a logistic regression model that can predict whether on the given parameter a person will buy a car or not.

Ans:
Import pandas as pd

Data = {‘User ID’: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
‘Gender’: [‘Male’, ‘Male’, ‘Female’, ‘Female’, ‘Male’, ‘Male’, ‘Female’, ‘Female’, ‘Male’, ‘Female’],
‘Age’: [19, 35, 26, 27, 19, 27, 32, 25, 33, 45],
‘Estimated Salary’: [19000, 20000, 43000, 57000, 76000, 58000, 82000, 32000, 69000, 65000],
‘Purchased’: [0, 0, 0, 1, 1, 0, 1, 0, 1, 1]}
Df = pd.DataFrame(data)

From sklearn.model_selection import train_test_split

X = df.iloc[:, 1:4].values
Y = df.iloc[:, 4].values

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
From sklearn.linear_model import LogisticRegression

Lr=LogisticRegression(random_state=0)
Lr.fit(X_train, y_train)

Predict a single observation

Observation = [[0, 30, 87000]]
Prediction = Lr.predict(observation)
Print(prediction)

Predict multiple observations

Observations = [[0, 30, 87000], [1, 50, 45000], [1, 22, 30000]]
Predictions = Lr.predict(observations)
Print(predictions)

@Slip-4

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

Ans:

Firstpage.php

<?php Session_start(); ?> <!DOCTYPE html> <html> <head> <title>Employee Details</title> </head> <body> <h1>Employee Details</h1> <form method=”POST” action=”Secondpage.php”> <label for=”eno”>Employee No:</label> <input type=”text” id=”eno” name=”eno”><br><br> <label for=”ename”>Employee Name:</label> <input type=”text” id=”ename” name=”ename”><br><br> <label for=”address”>Address:</label> <textarea id=”address” name=”address”></textarea><br><br> <input type=”submit” value=”Next”> </form> </body> </html> <?php // Store employee details in session If(isset($_POST[‘eno’]) && isset($_POST[‘ename’]) && isset($_POST[‘address’])) { $_SESSION[‘eno’] = $_POST[‘eno’]; $_SESSION[‘ename’] = $_POST[‘ename’]; $_SESSION[‘address’] = $_POST[‘address’]; } ?>

Secondpage.php

<?php Session_start(); ?> <!DOCTYPE html> <html> <head> <title>Earnings</title> </head> <body> <h1>Earnings</h1> <form method=”POST” action=”thirdpage.php”> <label for=”basic”>Basic:</label> <input type=”text” id=”basic” name=”basic”><br><br> <label for=”da”>DA:</label> <input type=”text” id=”da” name=”da”><br><br> <label for=”hra”>HRA:</label> <input type=”text” id=”hra” name=”hra”><br><br> <input type=”submit” value=”Next”> </form> </body> </html> <?php // Store earnings in session If(isset($_POST[‘basic’]) && isset($_POST[‘da’]) && isset($_POST[‘hra’])) { $_SESSION[‘basic’] = $_POST[‘basic’]; $_SESSION[‘da’] = $_POST[‘da’]; $_SESSION[‘hra’] = $_POST[‘hra’]; } ?>

Thirdpage.php

<?php Session_start(); // Calculate total earnings $total = $_SESSION[‘basic’] + $_SESSION[‘da’] + $_SESSION[‘hra’]; ?> <!DOCTYPE html> <html> <head> <title>Employee Information</title> </head> <body> <h1>Employee Information</h1> <p><strong>Employee No:</strong> <?php echo $_SESSION[‘eno’]; ?></p> <p><strong>Employee Name:</strong> <?php echo $_SESSION[‘ename’]; ?></p> <p><strong>Address:</strong> <?php echo $_SESSION[‘address’]; ?></p> <p><strong>Basic:</strong> <?php echo $_SESSION[‘basic’]; ?></p> <p><strong>DA:</strong> <?php echo $_SESSION[‘da’]; ?></p> <p><strong>HRA:</strong> <?php echo $_SESSION[‘hra’]; ?></p> <p><strong>Total Earnings:</strong> <?php echo $total; ?></p> </body> </html>

Q. 2)Build a simple linear regression model for Fish Species Weight Prediction.
Ans:

Import pandas as pd
Import random
From sklearn.linear_model import LinearRegression

create the dataset

Fish_species = [‘Tuna’, ‘Salmon’, ‘Trout’, ‘Bass’, ‘Sardine’, ‘Cod’, ‘Mackerel’]
Weights = []

For i in range(50):
Fish_weight = []
For j in range(7):
Weight = random.randint(1, 20)
Fish_weight.append(weight)
Weights.append(fish_weight)

Df = pd.DataFrame(weights, columns=fish_species)

create the linear regression model

X = df.iloc[:, :-1] # independent variables
Y = df.iloc[:, -1] # target variable

Model = LinearRegression()
Model.fit(X, y)

predict the weight of a new fish species

New_fish = [[10, 12, 15, 7, 4, 8]] # example input
Predicted_weight = model.predict(new_fish)
Print(“Predicted weight:”, predicted_weight)

@Slip-5

Q. 1) Create XML file named “Item.xml”with item-name, item-rate, item quantity Store the details of 5
Items of different Types.

Ans:

Item.xml
<items>
<item type=”Electronics”>
<name>Television</name>
<rate>500</rate>
<quantity>10</quantity>
</item>
<item type=”Clothing”>
<name>Shirt</name>
<rate>50</rate>
<quantity>20</quantity>
</item>
<item type=”Grocery”>
<name>Rice</name>
<rate>40</rate>
<quantity>30</quantity>
</item>
<item type=”Books”>
<name>Harry Potter and the Philosopher’s Stone</name>
<rate>20</rate>
<quantity>50</quantity>
</item>
<item type=”Sports”>
<name>Football</name>
<rate>100</rate>
<quantity>5</quantity>
</item>
</items>

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.
Ans:

Import pandas as pd
From sklearn.datasets import load_iris
From sklearn.linear_model import LogisticRegression
From sklearn.model_selection import train_test_split
From sklearn.metrics import accuracy_score

load the iris dataset

Iris = load_iris()

create a dataframe from the dataset

Df = pd.DataFrame(iris.data, columns=iris.feature_names)
Df[‘target’] = iris.target

view basic statistical details of the different species

Print(“Statistical details of Iris-setosa:”)
Print(df[df[‘target’]==0].describe())

Print(“Statistical details of Iris-versicolor:”)
Print(df[df[‘target’]==1].describe())

Print(“Statistical details of Iris-virginica:”)
Print(df[df[‘target’]==2].describe())

split the data into training and testing sets

X = df.iloc[:,:-1]
Y = df.iloc[:, -1]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

fit a logistic regression model

Logreg = LogisticRegression()
Logreg.fit(X_train, y_train)

make predictions on the test set

Y_pred = logreg.predict(X_test)

calculate the accuracy of the model

Accuracy = accuracy_score(y_test, y_pred)
Print(“Accuracy of the logistic regression model:”, accuracy)

@Slip-6

Q. 1) Write PHP script to read “book.xml” file into simpleXML object. Display attributes and elements .
( simple_xml_load_file() function )
.
Ans:

<?php // Load the XML file into a SimpleXML object $xml = simplexml_load_file(“book.xml”); // Display the attributes and elements of the SimpleXML object Echo “Book attributes: <br>”; Echo “ISBN: “ . $xml[‘isbn’] . “<br>”; Echo “Publisher: “ . $xml[‘publisher’] . “<br>”; Echo “<br>”; Echo “Book elements: <br>”; Echo “Title: “ . $xml->title . “<br>”; Echo “Author: “ . $xml->author . “<br>”; Echo “Description: “ . $xml->description . “<br>”; ?>

Book.xml file

<?xml version=”1.0”?>

<book isbn=”978-3-16-148410-0” publisher=”Example Publisher”>

<title>Example Book</title> <author>John Doe</author> <description>This is an example book.</description> </book>

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
Te process with different min_sup values.
TID={1:[“bread”,”milk”],2=[“bread”,”diaper”,”beer”,”eggs”],3=[“milk”,”diaper”,”beer”,”coke”],4=[“bread”,”milk”,”diaper”,”beer”],5=[“bread”,”milk”,”diaper”,”coke”]}

Ans:
Import pandas as pd
From mlxtend.preprocessing import TransactionEncoder
From mlxtend.frequent_patterns import apriori, association_rules

create the dataset

TID = {1:[“bread”,”milk”],2:[“bread”,”diaper”,”beer”,”eggs”],3:[“milk”,”diaper”,”beer”,”coke”],4:[“bread”,”milk”,”diaper”,”beer”],5:[“bread”,”milk”,”diaper”,”coke”]}
Transactions = []
For key, value in TID.items():
Transactions.append(value)

convert the categorical values into numeric format

Te = TransactionEncoder()
Te_ary = te.fit_transform(transactions)
Df = pd.DataFrame(te_ary, columns=te.columns_)

apply the apriori algorithm with different min_sup values

Min_sup_values = [0.2, 0.4, 0.6]
For min_sup in min_sup_values:
Frequent_itemsets = apriori(df, min_support=min_sup, use_colnames=True)
Rules = association_rules(frequent_itemsets, metric=”confidence”, min_threshold=0.7)
Print(“Min_sup:”, min_sup)
Print(“Frequent Itemsets:”)
Print(frequent_itemsets)
Print(“Association Rules:”)
Print(rules)

@Slip-7

Q. 1) Write a PHP script to read “Movie.xml” file and print all MovieTitle and ActorName of file using
OMDocument Parser. “Movie.xml” file should contain following information with at least 5 records
Wth values. M vieInfoMovieNo, MovieTitle, ActorName ,ReReleaseYear.
Ans:

Php file

<?php // Load the XML file $xml = new DOMDocument(); $xml->load(‘Movie.xml’); // Get all the movie nodes $movies = $xml->getElementsByTagName(‘MovieInfo’); // Loop through each movie node and print the movie title and actor name Foreach ($movies as $movie) { Echo “Movie Title: “ . $movie->getElementsByTagName(‘MovieTitle’)[0]->textContent . “, “; Echo “Actor Name: “ . $movie->getElementsByTagName(‘ActorName’)[0]->textContent . “<br>”; } ?>

XML file

<?xml version=”1.0”?> <MovieList> <MovieInfo> <MovieNo>1</MovieNo> <MovieTitle>The Shawshank Redemption</MovieTitle> <ActorName>Tim Robbins</ActorName> <ReleaseYear>1994</ReleaseYear> </MovieInfo> <MovieInfo> <MovieNo>2</MovieNo> <MovieTitle>The Godfather</MovieTitle> <ActorName>Marlon Brando</ActorName> <ReleaseYear>1972</ReleaseYear> </MovieInfo> <MovieInfo> <MovieNo>3</MovieNo> <MovieTitle>The Dark Knight</MovieTitle> <ActorName>Christian Bale</ActorName> <ReleaseYear>2008</ReleaseYear> </MovieInfo> <MovieInfo> <MovieNo>4</MovieNo> <MovieTitle>The Godfather: Part II</MovieTitle> <ActorName>Al Pacino</ActorName> <ReleaseYear>1974</ReleaseYear> </MovieInfo> <MovieInfo> <MovieNo>5</MovieNo> <MovieTitle>12 Angry Men</MovieTitle> <ActorName>Henry Fonda</ActorName> <ReleaseYear>1957</ReleaseYear> </MovieInfo> </MovieList>

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 association
Rules. .

Ans:

Import pandas as pd
From mlxtend.preprocessing import TransactionEncoder
From mlxtend.frequent_patterns import apriori, association_rules

read the dataset

Df = pd.read_csv(‘Market_Basket_Optimisation.csv’, header=None)

drop null values

Df.dropna(inplace=True)

convert categorical values to numeric using one-hot encoding

Te = TransactionEncoder()
Te_ary = te.fit(df.values).transform(df.values)
Df = pd.DataFrame(te_ary, columns=te.columns_)

generate frequent itemsets using apriori algorithm

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

generate association rules from frequent itemsets

Rules = association_rules(frequent_itemsets, metric=”lift”, min_threshold=1)

display information

Print(“Original Dataset:\n”)
Print(df.head())
Print(“\nFrequent Itemsets:\n”)
Print(frequent_itemsets)
Print(“\nAssociation Rules:\n”)
Print(rules)

@Slip-8

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)
AAAns:
// Display message using alert box
Alert(‘Exams are near, have you started preparing for?’);

// Accept two numbers from user using prompt and confirm boxes
Let num1 = prompt(‘Enter first number:’);
Let num2 = prompt(‘Enter second number:’);
Let confirmMsg = Are you sure you want to add ${num1} and ${num2}?;

// Show conf