0% found this document useful (0 votes)
5 views21 pages

WT&DA

The document contains multiple programming tasks and solutions in PHP and Python, covering topics such as session tracking, linear regression, cookies, user authentication, and AJAX. It includes code snippets for building models, handling user preferences, and manipulating HTML elements with jQuery. The tasks demonstrate practical applications of data handling, user interaction, and machine learning techniques.

Uploaded by

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

WT&DA

The document contains multiple programming tasks and solutions in PHP and Python, covering topics such as session tracking, linear regression, cookies, user authentication, and AJAX. It includes code snippets for building models, handling user preferences, and manipulating HTML elements with jQuery. The tasks demonstrate practical applications of data handling, user interaction, and machine learning techniques.

Uploaded by

S P
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Slip 1)

Q. 1) Write a PHP script to keep track of number of times the web page has been accessed (Use
Session Tracking).

Solution:

<?php

session_start();

if(isset($_SESSION['page_views'])) {

$_SESSION['page_views']++;

} else {

$_SESSION['page_views'] = 1;

echo "Page views: " . $_SESSION['page_views'];

?>

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.

Solution:

import pandas as pd

from sklearn.model_selection import train_test_split

from sklearn.linear_model import LinearRegression

from sklearn.preprocessing import OneHotEncoder

data = {

'Position': ['Intern', 'Associate', 'Manager', 'Director', 'VP',

'CEO'],

'Salary': [30000, 50000, 80000, 120000, 150000, 200000]

df = pd.DataFrame(data)

one_hot_encoder = OneHotEncoder(sparse_output=False)

encoded_positions = one_hot_encoder.fit_transform(df[['Position']])

encoded_positions_df = pd.DataFrame(encoded_positions,

columns=one_hot_encoder.get_feature_names_out(['Position']))

df_encoded = pd.concat([df, encoded_positions_df], axis=1)

1
df_encoded.drop(columns=['Position'], inplace=True)

X = df_encoded.drop(columns=['Salary'])

y = df_encoded['Salary']

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

print("Training data:")

print(X_train)

print(y_train)

print("\nTesting data:")

print(X_test)

print(y_test)

model = LinearRegression()

model.fit(X_train, y_train)

score = model.score(X_test, y_test)

print("\nModel Score:", score)

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

Solution:

<!DOCTYPE html>

<html>

<head>

<title>Change Preferences</title>

</head>

<body>

<?php

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

setcookie('font_style', $_POST['font_style'], time() + (86400 * 30), "/");

setcookie('font_size', $_POST['font_size'], time() + (86400 * 30), "/");

setcookie('font_color', $_POST['font_color'], time() + (86400 * 30), "/");

2
setcookie('bg_color', $_POST['bg_color'], time() + (86400 * 30), "/");

header("Location: {$_SERVER['PHP_SELF']}");

exit;

?>

<h2>Change Preferences</h2>

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

Font Style:

<select name="font_style">

<option value="Arial">Arial</option>

<option value="Times New Roman">Times New Roman</option>

</select><br><br>

Font Size:

<select name="font_size">

<option value="small">Small</option>

<option value="medium">Medium</option>

<option value="large">Large</option>

</select><br><br>

Font Color:

<input type="color" name="font_color"><br><br>

Background Color:

<input type="color" name="bg_color"><br><br>

<input type="submit" value="Set Preferences">

</form>

<?php

if(isset($_COOKIE['font_style']) && isset($_COOKIE['font_size']) && isset($_COOKIE['font_color'])

&& isset($_COOKIE['bg_color'])) {

echo "<h2>Display Preferences</h2>";

echo '<div style="font-family: '.$_COOKIE['font_style'].'; font-size: '.$_COOKIE['font_size'].'; color:

'.$_COOKIE['font_color'].'; background-color: '.$_COOKIE['bg_color'].'; padding: 20px;">';

echo "This is a sample text to display preferences.";

3
echo "</div>";

?>

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

Solution:

import numpy as np

from sklearn.model_selection import train_test_split

from sklearn.linear_model import LinearRegression

experience = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).reshape(-1, 1)

salary = np.array([30000, 35000, 40000, 45000, 50000, 55000, 60000, 65000, 70000, 75000])

X_train, X_test, y_train, y_test = train_test_split(experience, salary, test_size=0.2, random_state=42)

print("Training set:")

print("X_train:", X_train)

print("y_train:", y_train)

print("\nTes ng set:")

print("X_test:", X_test)

print("y_test:", y_test)

model = LinearRegression()

model.fit(X_train, y_train)

new_experience = np.array([11, 12, 13]).reshape(-1, 1)

predicted_salary = model.predict(new_experience)

print("\nPredicted salary for new experiences:", predicted_salary)

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]

Solution:

4
<?php

session_start();

$correct_username = "user";

$correct_password = "pass";

if (!isset($_SESSION['login_attempts'])) {

$_SESSION['login_attempts'] = 0;

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

$_SESSION['login_attempts']++;

$entered_username = $_POST['username'];

$entered_password = $_POST['password'];

if ($entered_username === $correct_username && $entered_password === $correct_password) {

$_SESSION['login_attempts'] = 0;

header("Location: welcome.php");

exit();

} else {

$error_message = "Invalid username or password. Please try again.";

if ($_SESSION['login_attempts'] >= 3) {

$error_message = "Maximum login attempts reached. Please try again later.";

$_SESSION['login_attempts'] = 0;

?>

<!DOCTYPE html>

<html>

<head>

<title>Login</title>

</head>

<body>

<?php if (isset($error_message)) { ?>

5
<p><?php echo $error_message; ?></p>

<?php } ?>

<h2>Login</h2>

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

Username: <input type="text" name="username"><br><br>

Password: <input type="password" name="password"><br><br>

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

</form>

</body>

</html>

2)welcome.php

<!DOCTYPE html>

<html>

<title>Welcome</title>

<h1>Welcome</h1>

</html>

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.

Solution:

import pandas as pd

from sklearn.model_selection import train_test_split

from sklearn.linear_model import LogisticRegression

from sklearn.preprocessing import StandardScaler

from sklearn.metrics import classification_report, confusion_matrix

data = {

'User ID': [1, 2, 3, 4, 5],

'Gender': ['Male', 'Female', 'Male', 'Female', 'Male'],

'Age': [20, 25, 30, 35, 40],

'Estimated Salary': [20000, 30000, 40000, 50000, 60000],

'Purchased': [0, 1, 0, 1, 0]

6
}

df = pd.DataFrame(data)

X = df[['Gender', 'Age', 'Estimated Salary']]

y = df['Purchased']

X = pd.get_dummies(X, drop_first=True)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

scaler = StandardScaler()

X_train = scaler.fit_transform(X_train)

X_test = scaler.transform(X_test)

model = LogisticRegression()

model.fit(X_train, y_train)

y_pred = model.predict(X_test)

print("Confusion Matrix:")

print(confusion_matrix(y_test, y_pred))

print("\nClassification Report:")

print(classification_report(y_test, y_pred))

Slip10)
Q1.Create a HTML fileto insert text before and after a Paragraph using jQuery. [Hint : Use before( )
and after( )]

Solution:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>Insert Text Before and After Paragraph</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>

$(document).ready(function(){

7
// Function to insert text before and after a paragraph

$("#btnInsertText").click(function(){

$("#myParagraph").before("<p>This text is inserted before the paragraph.</p>");

// Insert text after the paragraph

$("#myParagraph").after("<p>This text is inserted after the paragraph.</p>");

});

});

</script>

</head>

<body>

<h2>Insert Text Before and After Paragraph</h2>

<button id="btnInsertText">Insert Text</button>

<p id="myParagraph">This is a paragraph.</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.

TID Items
1 'eggs', 'milk','bread'
2 'eggs', 'apple'
3 'milk', 'bread'
4 'apple', 'milk'
5 'milk', 'apple', 'bread'

Solution:

import pandas as pd

from mlxtend.frequent_patterns import apriori, association_rules

data = {

'TID': [1, 2, 3, 4, 5],

'Items': [['eggs', 'milk', 'bread'], ['eggs', 'apple'], ['milk',

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

'bread']]}

8
df = pd.DataFrame(data)

min_sup = 0.5

frequent_itemsets = apriori(df['Items'].apply(lambda x: ','.join(x)).str.get_dummies(sep=','),

min_support=min_sup, use_colnames=True)

print("Frequent itemsets:")

print(frequent_itemsets)

rules = association_rules(frequent_itemsets,df, metric="lift",min_threshold=1)

print("Association rules:")

print(rules)

Slip11)
Q1.)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 )

Solution:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>Student Details</title>

<style>

.red-text {

color: red;

.big-size {

font-size: 18px;

</style>

</head>

<body>

9
<script>

function changeStyle() {

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

var name = nameInput.value.trim();

if (name) {

nameInput.className = "red-text big-size";

} else {

var img = document.getElementById("myImage");

img.width = 300; // Change the size of the image

function displayImageSize() {

var img = document.getElementById("myImage");

alert("Image width: " + img.width + "px, height: " + img.height + "px");

</script>

<h2>Student Details</h2>

<input type="text" id="nameInput" placeholder="Enter student name" onblur="changeStyle()">

<img id="myImage" src="https://via.placeholder.com/300" alt="placeholder image"

onload="displayImageSize()" onmouseover="this.style.border='2px solid blue'"

onmouseout="this.style.border='none'" onclick="displayImageSize()"

onmouseup="this.style.border='none'">

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

TID Items
1 butter, bread, milk
2 butter, flour, milk, sugar
3 butter, eggs, milk, salt

10
4 eggs
5 butter, flour, milk, salt
Solution:

import pandas as pd

from mlxtend.preprocessing import TransactionEncoder

from mlxtend.frequent_patterns import apriori, association_rules

data = {'TID': [1, 2, 3, 4, 5],

'Items': [['butter', 'bread', 'milk'],

['butter', 'flour', 'milk', 'sugar'],

[],

[],

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

df = pd.DataFrame(data)

te = TransactionEncoder()

encoded_data = te.fit_transform(df['Items'])

df_encoded = pd.DataFrame(encoded_data, columns=te.columns_)

print(df_encoded)

min_sup = 0.5

frequent_itemsets = apriori(df_encoded, min_support=min_sup, use_colnames=True)

print("Frequent itemsets:")

print(frequent_itemsets)

association_rules_df = association_rules(frequent_itemsets,df, metric="lift", min_threshold=1)

print("Association rules:")

print(association_rules_df)

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

Solution:

<!DOCTYPE html>

11
<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>Contact Information</title>

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

</head>

<body>

<button id="printBtn">Print Contact Information</button>

<div id="contactTable"></div>

<script>

$(document).ready(function(){

$("#printBtn").click(function(){

$.ajax({

url: 'contact.dat',

type: 'GET',

dataType: 'text',

success: function(data) {

var lines = data.split('\n');

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

table += '<tr><th>Sr No</th><th>Name</th><th>Residence Number</th><th>Mobile

Number</th><th>Address</th></tr>';

for(var line of lines) {

var fields = line.split(',');

table += '<tr>';

for(var field of fields) {

table += '<td>' + field + '</td>';

table += '</tr>';

table += '</table>';

12
$("#contactTable").html(table);

},

error: function() {

$("#contactTable").html("Error occurred while fetching data.");

});

});

});

</script>

</body>

</html>

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.

Solution:

import numpy as np

from sklearn.model_selection import train_test_split

from sklearn.linear_model import LinearRegression

np.random.seed(0)

heights = np.random.normal(loc=170, scale=10, size=100)

weights = 0.5 * heights + np.random.normal(loc=0, scale=5, size=100)

X = heights.reshape(-1, 1)

y = weights

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

print("Training set shapes:")

print("X_train:", X_train.shape)

print("y_train:", y_train.shape)

print("\nTesting set shapes:")

print("X_test:", X_test.shape)

print("y_test:", y_test.shape)

model = LinearRegression()

model.fit(X_train, y_train)

13
train_score = model.score(X_train, y_train)

test_score = model.score(X_test, y_test)

print("\nTraining R^2 score:", train_score)

print("Testing R^2 score:", test_score)

Slip 16)
Q1.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).

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>Book Details</title>

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

<script>

$(document).ready(function(){

$('#bookName').change(function(){

var bookName = $(this).val();

$.ajax({

url: 'books.xml',

dataType: 'xml',

success: function(data){

var bookDetails = '';

$(data).find('book').each(function(){

var title = $(this).find('title').text();

var author = $(this).find('author').text();

var year = $(this).find('year').text();

var price = $(this).find('price').text();

if(title === bookName) {

14
bookDetails += '<tr><td>Title:</td><td>' + title + '</td></tr>';

bookDetails += '<tr><td>Author:</td><td>' + author + '</td></tr>';

bookDetails += '<tr><td>Year:</td><td>' + year + '</td></tr>';

bookDetails += '<tr><td>Price:</td><td>' + price + '</td></tr>';

});

$('#bookDetails').html(bookDetails);

});

});

});

</script>

</head>

<body>

<h2>Select a Book:</h2>

<select id="bookName">

<option value="">Select</option>

<option value="Book 1">Book 1</option>

<option value="Book 2">Book 2</option>

<option value="Book 3">Book 3</option>

</select>

<br><br>

<h2>Book Details:</h2>

<table id="bookDetails" border="1"></table>

</body>

</html>

Q. 2)Consider any text paragraph. Preprocess the text to remove any special characters and digits.
Generate the summary using extractive summarization process

Solution:

import re

15
from nltk.tokenize import sent_tokenize

from collections import Counter

def preprocess_text(text):

text = re.sub(r'\d+', '', text)

text = re.sub(r'[^\w\s]', '', text)

return text

def generate_summary(text, num_sentences=3):

preprocessed_text = preprocess_text(text)

sentences = sent_tokenize(preprocessed_text)

word_freq = Counter(preprocessed_text.split())

sentence_scores = {sentence: sum(word_freq[word] for word in sentence.split()) for sentence in


sentences}

top_sentences = sorted(sentence_scores,
key=sentence_scores.get,reverse=True)[:num_sentences]

summary = ' '.join(top_sentences)

return summary

text = """Natural language processing (NLP) is a subfield of

linguistics, computer science, information

engineering, and artificial intelligence concerned with the

interactions between computers and

human (natural) languages, in particular how to program computers to

process and analyze large

amounts of natural language data. The result is a computer capable of

understanding the contents

of documents, including the contextual nuances of the language within

them. The technology can

then accurately extract information and insights contained in the

documents as well as categorize

and organize the documents themselves. Challenges in natural language

processing frequently

involve speech recognition, natural language understanding, and

natural language generation.

16
NLP technologies are having a profound impact on the way people

interact with computers and

are an important component of the emerging field of artificial

intelligence. They are widely used

in applications such as machine translation, speech recognition,

information retrieval, sentiment

analysis, text summarization, and conversational agents (chatbots)."""

summary = generate_summary(text)

print("Summary:")

print(summary)

Slip17)
Q1)Write a Java Script Program to show Hello Good Morning message onload event using alert
boxand display the Student registration from

Solution:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>Student Registration</title>

<script>

window.onload = function() {

alert("Hello Good Morning");

};

</script>

</head>

<body>

<h1>Student Registration Form</h1>

<form id="registrationForm">

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

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

<label for="email">Email:</label><br>

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

<label for="course">Course:</label><br>

<select id="course" name="course" required>

<option value="Computer Science">Computer Science</option>

<option value="Mathematics">Mathematics</option>

<option value="Physics">Physics</option>

</select><br><br>

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

</form>

</body>

</html>

Q. 2)Consider text paragraph.So, keep working. Keep striving. Never give up. Fall down seven times,
getup eight. Ease is a greater threat to progress than hardship. Ease is a greater threat to progress
thanhardship. So, keep moving, keep growing, keep learning. See you at work.Preprocess the text to
removeany special characters and digits. Generate the summary using extractive summarization
process.

Solution:

import re

import nltk

from nltk.tokenize import sent_tokenize

from sklearn.feature_extraction.text import TfidfVectorizer

from sklearn.metrics.pairwise import linear_kernel

nltk.download('punkt')

text = """So, keep working. Keep striving. Never give up. Fall down seven times, get up eight.

Ease is a greater threat to progress than hardship.

So, keep moving, keep growing, keep learning. See you at work."""

def preprocess_text(text):

text = re.sub(r'[^A-Za-z\s]', '', text)

18
return text.lower()

def extractive_summary(text, num_sentences=2):

sentences = sent_tokenize(text)

processed_text = preprocess_text(text)

tfidf_vectorizer = TfidfVectorizer().fit_transform(sentences)

tfidf_matrix = tfidf_vectorizer.toarray()

cosine_matrix = linear_kernel(tfidf_matrix, tfidf_matrix)

scores = cosine_matrix.sum(axis=1)

ranked_sentences = [sentences[i] for i in np.argsort(scores)[-num_sentences:]]

return '. '.join(ranked_sentences)

cleaned_text = preprocess_text(text)

summary = extractive_summary(text)

print("Cleaned Text:", cleaned_text)

print("Summary:", summary)

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

Solution:

<!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>

<script>

function generateFibonacci() {

let n = parseInt(document.getElementById("number").value);

let fib = [0, 1];

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

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

19
document.getElementById("result").innerText = fib.slice(0, n).join(", ");

</script>

</head>

<body>

<h1>Fibonacci Sequence Generator</h1>

<input type="number" id="number" placeholder="Enter a number" />

<button onclick="generateFibonacci()">Generate Fibonacci</button>

<p id="result"></p>

</body>

</html>

Q. 2)Consider any text paragraph. Remove the stopwords. Tokenize the paragraph to extract words
and sentences. Calculate the word frequency distribution and plot the frequencies. Plot the
wordcloud of the text.

Solution:

import nltk

from nltk.corpus import stopwords

from nltk.tokenize import word_tokenize, sent_tokenize

from nltk.probability import FreqDist

from wordcloud import WordCloud

import matplotlib.pyplot as plt

text_paragraph = """

Natural Language Processing (NLP) is a field of artificial intelligence

that focuses on the interaction between computers and humans through

natural language. The ultimate objective of NLP is to enable computers

to understand, interpret, and generate human language in a way that is

both meaningful and valuable. NLP techniques are used in a variety of

applications, including language translation, sentiment analysis,

text summarization, speech recognition, and more. """

words = word_tokenize(text_paragraph.lower())

stop_words = set(stopwords.words("english"))

20
filtered_words = [word for word in words if word not in stop_words]

sentences = sent_tokenize(text_paragraph)

word_freq = FreqDist(filtered_words)

plt.figure(figsize=(10, 5))

word_freq.plot(20, title='Top 20 Most Common Words')

wordcloud = WordCloud(width=800, height=400,

background_color='white').generate_from_frequencies(word_freq)

plt.figure(figsize=(10, 5))

plt.imshow(wordcloud, interpolation='bilinear')

plt.axis('off')

plt.title('Word Cloud')

plt.show()

21

You might also like