Lab Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 66

Guru Nanak Institutions Technical Campus (Autonomous)

Department of Computer Science & Engineering


(CYBER SECURITY / DATA SCIENCE)

Full Stack Development Lab Manual(22SD0CY02, 22SD0DS02)


II B. Tech CSE (CS / DS), II - Semester
Academic Year 2024-25

Mr. Yawar Ayub

Assistant Professor

Guru Nanak Institutions Technical Campus


(Autonomous) Ibrahimpatnam, R.R District – 501 506, Telangana
VISION

To evolve into a center of excellence in Science & Technology through creative


and innovative practices in teaching- learning, promoting academic
achievement & research excellence to produce internationally accepted
competitive and world class professionals who are psychologically strong and
emotionally balanced imbued with social consciousness and ethical values.

MISSION

To provide high quality academic programmes, training activities, research


facilities and opportunities supported by continuous industry – institute
interaction aimed at employability, entrepreneurship, leadership and research
aptitude among students and contribute to the economic and technological
development of the region, state and nation.
PREREQUISITES
Object Oriented Programming through Java, HTML basics
COURSE OBJECTIVES

 To implement the static web pages using HTML and do client side
validation using javaScript.
 To design and work with databases using java.
 To develop an end to end application using java full stack.
 To introduce Node js implementation for server side Programming.
 To experiment with single page application development using React.
COURSE OUTCOME

 Build a custom website with HTML, CSS, and Bootstrap and little
javaScript.
 Demonstrate Advanced features of JavaScript and learn about JDBC.
 Develop Server Sid implementation using java technologies
 Develop the server-side implementation using Node Js.
 Design a Single Page Application using React.
Weeks:
1. Build a responsive web application for shopping cart with registration, login, catalog and
cart pages using CSS3 features, flex and grid.
2. Make the above web application responsive web application using Bootstrap framework.
3 Use JavaScript for doing client-side validation of the pages implemented in experiment 1
and experiment 2.
4. Explore the features of ES6 like arrow functions, callbacks, promises, async/await.
Implement an application for reading the weather information from openweathermap.org
and display the information in the form of a graph on the web page.
5. Develop a java standlone application that connects with the database(Oracle / mySql) and
perform the CRUD operation on the database tables.
6. Create an xml for the bookstore. Validate the same using both DTD and XSD.
7. Design a controller with servlet that provides the interaction with application developed
in experiment 1 and the database created in experiment 5.
8. Maintaining the transactional history of any user is very important. Explore the various
session tracking mechanism ( Cookies, HTTP Session )
9. Create a custom server using http module and explore the other modules of Node JS like
OS, path, event.
10. Develop an express web application that can interact with REST API to perform CRUD
operations on student data. (Use Postman).
11. For the above application create authorized end points using JWT (JSON Web Token).
12. Create a react application for the student management system having registration, login,
contact, about pages and implement routing to navigate through these pages.
13. Create a service in react that fetches the weather information from
openweathermap.org and the display the current and historical weather information using
graphical representation using chart.js.
14. Create a TODO application in react with necessary component and deploy it into github.
1A. Registration Page

Registration.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="regStyle.css">
<title>User Registration</title>
</head>
<body>
<div class="container">
<form class="registration-form">
<h2>Register</h2>
<label for="username">Username:</label>
<input type="text" id="username" name="username" maxlength="15"
required>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required>

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

<label for="confirm-password">Confirm Password:</label>


<input type="password" id="confirm-password" name="confirm-
password" required>

<label for="dob">Date of Birth:</label>


<input type="date" id="dob" name="dob" required>

<button type="submit">Register</button>
</form>
</div>
</body>
</html>

Registration.css

body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
background-color: #f0f0f0;
}

.container {
width: 300px;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
}

.registration-form {
display: flex;
flex-direction: column;
}

label {
margin-top: 10px;
}

input {
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}

button {
padding: 10px;
background-color: #4caf50;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
}

button:hover {
background-color: #45a049;
}
1B. LOGIN PAGE

Login.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="login.css">
<title>User Login</title>
</head>
<body>
<div class="container">
<!-- Login Form -->
<form class="login-form">
<h2>Login</h2>

<!-- Username Input -->


<label for="username">Username:</label>
<input type="text" id="username" name="username" required>

<!-- Password Input -->


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

<!-- Submit Button -->


<button type="submit">Login</button>
</form>
</div>
</body>
</html>

Login.css

body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
background-color: #f0f0f0;
}

.container {
width: 300px;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
}

.login-form {
display: flex;
flex-direction: column;
}

label {
margin-top: 10px;
}

input {
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}

button {
padding: 10px;
background-color: #4caf50;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
}

button:hover {
background-color: #45a049;
}
1C Catalog Page

Catalog.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="catalog.css">
<title>Product Catalog</title>
</head>
<body>
<div class="container">
<h1>Product Catalog</h1>
<!-- Catalog Content -->
<div class="catalog">

<!-- Product 1 -->


<div class="product">
<img src="product1.jpg" alt="Product 1">
<h3>Product 1</h3>
<p>Description of Product 1. Lorem ipsum dolor sit amet,
consectetur adipiscing elit.</p>
<span>$19.99</span>
<button>Add to Cart</button>
</div>

<div class="product">
<img src="product1.jpg" alt="Product 1">
<h3>Product 1</h3>
<p>Description of Product 1. Lorem ipsum dolor sit amet,
consectetur adipiscing elit.</p>
<span>$19.99</span>
<button>Add to Cart</button>
</div>

<div class="product">
<img src="product1.jpg" alt="Product 1">
<h3>Product 1</h3>
<p>Description of Product 1. Lorem ipsum dolor sit amet,
consectetur adipiscing elit.</p>
<span>$19.99</span>
<button>Add to Cart</button>
</div>

<div class="product">
<img src="product1.jpg" alt="Product 1">
<h3>Product 1</h3>
<p>Description of Product 1. Lorem ipsum dolor sit amet,
consectetur adipiscing elit.</p>
<span>$19.99</span>
<button>Add to Cart</button>
</div>

<div class="product">
<img src="product1.jpg" alt="Product 1">
<h3>Product 1</h3>
<p>Description of Product 1. Lorem ipsum dolor sit amet,
consectetur adipiscing elit.</p>
<span>$19.99</span>
<button>Add to Cart</button>
</div>

<div class="product">
<img src="product1.jpg" alt="Product 1">
<h3>Product 1</h3>
<p>Description of Product 1. Lorem ipsum dolor sit amet,
consectetur adipiscing elit.</p>
<span>$19.99</span>
<button>Add to Cart</button>
</div>

<!-- Product 2 -->


<div class="product">
<img src="product2.jpg" alt="Product 2">
<h3>Product 2</h3>
<p>Description of Product 2. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris.</p>
<span>$29.99</span>
<button>Add to Cart</button>
</div>
<!-- Add more product entries as needed -->

</div>
</div>
</body>
</html>

Catalog.css

body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
background-color: #f0f0f0;
}

.container {
width: 800px;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
}

.catalog {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
}

.product {
border: 1px solid #ccc;
padding: 15px;
border-radius: 8px;
}

img {
//max-width: 100%;
//height: auto;
border-radius: 4px;
}

h2 {
text-align: center;
}

button {
padding: 8px;
background-color: #4caf50;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
}

button:hover {
background-color: #45a049;
}
h1{
position: sticky;
top: 0;
background-color: aqua;
border-radius: 10px;
text-align: center;
}

1D Cart Page
Cart.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="cart.css">
<title>Shopping Cart</title>
</head>
<body>
<div class="container">
<!-- Cart Content -->
<div class="cart">
<h2>Shopping Cart</h2>

<!-- Cart Item 1 -->


<div class="cart-item">
<img src="product1.jpg" alt="Product 1">
<div class="item-details">
<h3>Product 1</h3>
<p>Description of Product 1. Lorem ipsum dolor sit amet,
consectetur adipiscing elit.</p>
<span>$19.99</span>
</div>
<div class="item-actions">
<input type="number" value="1" min="1">
<button>Update</button>
<button>Remove</button>
</div>
</div>

<!-- Cart Item 2 -->


<div class="cart-item">
<img src="product2.jpg" alt="Product 2">
<div class="item-details">
<h3>Product 2</h3>
<p>Description of Product 2. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris.</p>
<span>$29.99</span>
</div>
<div class="item-actions">
<input type="number" value="2" min="1">
<button>Update</button>
<button>Remove</button>
</div>
</div>

<!-- Add more cart item entries as needed -->

<div class="cart-total">
<h3>Total: $49.98</h3>
</div>

<button class="checkout-btn">Proceed to Checkout</button>


</div>
</div>
</body>
</html>
Cart.css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
background-color: #f0f0f0;
}

.container {
width: 800px;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
}

.cart {
display: flex;
flex-direction: column;
}

.cart-item {
display: flex;
border: 1px solid #ccc;
padding: 15px;
margin-bottom: 10px;
border-radius: 8px;
}

img {
max-width: 100px;
height: auto;
margin-right: 10px;
border-radius: 4px;
}

.item-details {
flex-grow: 1;
}

.item-actions {
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 10px;
}

input {
width: 40px;
margin-bottom: 5px;
}

button {
padding: 8px;
margin-left: 5px;
background-color: #4caf50;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
}

button:hover {
background-color: #45a049;
}

.cart-total {
margin-top: 20px;
text-align: right;
}

.checkout-btn {
padding: 10px;
background-color: #4caf50;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
margin-top: 10px;
}

.checkout-btn:hover {
background-color: #45a049
}
Week 2

Make the above web application responsive web application using Bootstrap framework.

2A Registration page

Registration.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css
">
<link rel="stylesheet" href="styles.css">
<title>User Registration</title>
</head>
<body>
<div class="container">
<form class=" row d-flex flex-column align-items-center">
<h2 class="text-center mb-4 col-4">Register</h2>

<div class="form-group col-4">


<label for="username" class="text-center">Username:</label>
<input type="text" class="form-control" id="username"
name="username" required>
</div>

<div class="form-group col-4">


<label for="email">Email:</label>
<input type="email" class="form-control" id="email"
name="email" required>
</div>

<div class="form-group col-4">


<label for="password">Password:</label>
<input type="password" class="form-control" id="password"
name="password" required>
</div>

<div class="form-group col-4">


<label for="confirm-password">Confirm Password:</label>
<input type="password" class="form-control" id="confirm-
password" name="confirm-password" required>
</div>

<div class="form-group col-4">


<label for="dob">Confirm Password:</label>
<input type="date" class="form-control" id="dob"
name="confirm-password" required>
</div>
<div class="form-group col-4">
<button type="submit" class="btn btn-primary w-
100">Register</button>
</div>

</form>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"
></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"><
/script>
</body>
</html>
Login.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css
">
<link rel="stylesheet" href="styles.css">
<title>User Login</title>
</head>
<body>
<div class="container">
<!-- Login Form -->
<form class="login-form d-flex flex-column align-items-center row mt-
5">
<h2 class="text-center col-4 mb-4">Login</h2>

<!-- Username Input -->


<div class="form-group col-4">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username"
name="username" required>
</div>

<!-- Password Input -->


<div class="form-group col-4">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password"
name="password" required>
</div>

<!-- Submit Button -->


<div class="form-group col-4">
<button type="submit" class="btn btn-primary btn-
block">Login</button>
</div>

</form>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"
></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"><
/script>
</body>
</html>

Catalog.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css
">
<link rel="stylesheet" href="styles.css">
<title>Product Catalog</title>
</head>
<body>
<div class="container">
<h1 style="text-align: center;">Catalog</h1>
<!-- Catalog Content -->
<div class="d-flex flex-wrap justify-content-center ">

<!-- Product 1 -->


<div class="card m-1 " style="width: 30%;">
<img src="product1.jpg" alt="Product 1" class="card-img-top">
<div class="card-body">
<h5 class="card-title">Product 1</h5>
<p class="card-text">Description of Product 1. kdlfjak k
dkdkdk Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<span class="badge badge-primary">$19.99</span>
<a href="#" class="btn btn-success btn-block mt-2">Add to
Cart</a>
</div>
</div>

<!-- Product 2 -->


<div class="card m-1" style="width: 30%;">
<img src="product1.jpg" alt="Product 1" class="card-img-top">
<div class="card-body">
<h5 class="card-title">Product 1</h5>
<p class="card-text">Description of Product 1. Lorem ipsum
dolor sit amet, consectetur adipiscing elit.</p>
<span class="badge badge-primary">$19.99</span>
<a href="#" class="btn btn-success btn-block mt-2">Add to
Cart</a>
</div>
</div>

<div class="card m-1 " style="width: 30%;">


<img src="product1.jpg" alt="Product 1" class="card-img-top">
<div class="card-body">
<h5 class="card-title">Product 1</h5>
<p class="card-text">Description of Product 1. Lorem ipsum
dolor sit amet, consectetur adipiscing elit.</p>
<span class="badge badge-primary">$19.99</span>
<a href="#" class="btn btn-success btn-block mt-2">Add to
Cart</a>
</div>
</div>

<div class="card m-1" style="width: 30%;">


<img src="product1.jpg" alt="Product 1" class="card-img-top">
<div class="card-body">
<h5 class="card-title">Product 1</h5>
<p class="card-text">Description of Product 1. Lorem ipsum
dolor sit amet, consectetur adipiscing elit.</p>
<span class="badge badge-primary">$19.99</span>
<a href="#" class="btn btn-success btn-block mt-2">Add to
Cart</a>
</div>
</div>

<div class="card m-1" style="width: 30%;">


<img src="product1.jpg" alt="Product 1" class="card-img-top">
<div class="card-body">
<h5 class="card-title">Product 1</h5>
<p class="card-text">Description of Product 1. Lorem ipsum
dolor sit amet, consectetur adipiscing elit.</p>
<span class="badge badge-primary">$19.99</span>
<a href="#" class="btn btn-success btn-block mt-2">Add to
Cart</a>
</div>
</div>

<div class="card m-1" style="width: 30%;">


<img src="product1.jpg" alt="Product 1" class="card-img-top">
<div class="card-body">
<h5 class="card-title">Product 1</h5>
<p class="card-text">Description of Product 1. Lorem ipsum
dolor sit amet, consectetur adipiscing elit.</p>
<span class="badge badge-primary">$19.99</span>
<a href="#" class="btn btn-success btn-block mt-2">Add to
Cart</a>
</div>
</div>

<div class="card m-1" style="width: 30%;">


<img src="product1.jpg" alt="Product 1" class="card-img-top">
<div class="card-body">
<h5 class="card-title">Product 1</h5>
<p class="card-text">Description of Product 1. Lorem ipsum
dolor sit amet, consectetur adipiscing elit.</p>
<span class="badge badge-primary">$19.99</span>
<a href="#" class="btn btn-success btn-block mt-2">Add to
Cart</a>
</div>
</div>
<!-- Add more product entries as needed -->
</div>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"
></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"><
/script>
</body>
</html>

Cart.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css
">
<link rel="stylesheet" href="styles.css">
<title>Shopping Cart</title>
</head>
<body>
<div class="container">
<!-- Cart Content -->
<div class="cart">
<h2 class="text-center mb-4">Shopping Cart</h2>

<!-- Cart Item 1 -->


<div class="cart-item">
<img src="product1.jpg" alt="Product 1" class="cart-item-
image">
<div class="item-details">
<h3>Product 1</h3>
<p>Description of Product 1. Lorem ipsum dolor sit amet,
consectetur adipiscing elit.</p>
<span>$19.99</span>
</div>
<div class="item-actions row ">

<input type="number" value="1" min="1" class="col-1 m-2


form-control quantity-input">
<button class="btn btn-info update-btn
m-2">Update</button>
<button class="btn btn-danger remove-btn
m-2">Remove</button>
</div>
</div>

<!-- Cart Item 2 -->


<div class="cart-item">
<img src="product2.jpg" alt="Product 2" class="cart-item-
image">
<div class="item-details">
<h3>Product 2</h3>
<p>Description of Product 2. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris.</p>
<span>$29.99</span>
</div>
<div class="item-actions row">
<input type="number" value="2" min="1" class="col-1 m-2
form-control quantity-input">
<button class="btn btn-info update-btn
m-2">Update</button>
<button class="btn btn-danger remove-btn
m-2">Remove</button>
</div>
</div>

<!-- Add more cart item entries as needed -->

<div class="cart-total">
<h3>Total: $49.98</h3>
</div>

<a href="#" class="btn btn-success checkout-btn">Proceed to


Checkout</a>
</div>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"
></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"><
/script>
</body>
</html>

Week 3

3 Use JavaScript for doing client-side validation of the pages implemented in experiment 1 and
experiment 2.

Registration.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
box-sizing: border-box;
background-color: azure;
}
.container{
width: 400px;
margin: auto;
border: 2px solid red;
margin-top: 30px;

}
form div input{
width: 100%;
height: 1.5rem;
padding: 3px 7px;
}
form div{
margin-bottom: 10px;
font-size: 1.25rem;
}
form button{
width: 100%;
margin-bottom: 10px;
background-color: aqua;
padding: 5px;
border: none;
}

</style>
</head>
<body>
<div class="container">
<form>
<div>
<label>Email</label><br>
<input type="text" placeholder="Email" id="email"/>
</div>

<div>
<label>Password</label><br>
<input type="password" placeholder="password" id="password"/>
</div>

<div>
<label>Confirm Password</label><br>
<input type="password" placeholder="password"
id="confirmPassword" />
</div>

<div>
<label>Phone No</label><br>
<input type="text" placeholder="Phone No." id="phone"/>
</div>
<div>
<label>Date of Birth</label><br>
<input type="date" placeholder="Date of Birth" id="dob" /><br>
</div>
<i id="error" style="color: red;"></i>

<button type="submit" onclick="register(event)" >Submit</button>


</form>
</div>
<script >
function register(event){
event.preventDefault();
let email = document.getElementById('email').value;
let password = document.getElementById('password').value;
let confirmPassword = document.getElementById('confirmPassword').value;
let dob = document.getElementById('dob').value;
let phone = document.getElementById('phone').value;
let error = document.getElementById('error');
let pattern = /^[^\s@]+\.@[^@]+$/;

if(email == "" || password == "" || confirmPassword=="" || dob=="" ||


phone==""){
error.innerText = "All fields are compulsory";
}else{
if(password != confirmPassword){
error.innerText = "Password and confirm Password should be same";
}else{
if(!pattern.test(email)){
error.innerText = "Enter correct email";
}else{
error.innerText = "Good to go";
}
}
}
}
</script>
</body>
</html>
Login.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
box-sizing: border-box;
background-color: azure;
}
.container{
width: 400px;
margin: auto;
border: 2px solid red;
margin-top: 30px;

}
form div input{
width: 100%;
height: 1.5rem;
padding: 3px 7px;
}
form div{
margin-bottom: 10px;
font-size: 1.25rem;
}
form button{
width: 100%;
margin-bottom: 10px;
background-color: aqua;
padding: 5px;
border: none;
}

</style>
</head>
<body>
<div class="container">
<form>
<div>
<label>Email</label><br>
<input type="text" placeholder="Email" id="email"/>
</div>

<div>
<label>Password</label><br>
<input type="password" placeholder="password" id="password"/>
</div>

<i id="error" style="color: red;"></i>

<button type="submit" onclick="register(event)" >Submit</button>


</form>
</div>
<script >
function register(event){
event.preventDefault();
let email = document.getElementById('email').value;
let password = document.getElementById('password').value;

let error = document.getElementById('error');


let pattern = /^[^\s@]+\.@[^@]+$/;

if(email == "" || password == "" ){


error.innerText = "All fields are compulsory";
}else{
if(!pattern.test(email)){
error.innerText = "Enter correct email";
}else{
error.innerText = "Good to go";
}
}
}

</script>
</body>
</html>
Week 4

4. Explore the features of ES6 like arrow functions, callbacks, promises, async/await. Implement an
application for reading the weather information from openweathermap.org and display the
information in the form of a graph on the web page.

arrowFunction.js

<!-- An arrow function in JavaScript is a concise way to write anonymous


functions. It was introduced in ECMAScript 6 (ES6) and provides a more compact
syntax compared to traditional function expressions. -->

// Traditional function expression


function add(a, b) {
return a + b;
}
// Arrow function
const addArrow = (a, b) => {
return a + b;
};

// Shorter syntax for single-line functions with implicit return


const multiply = (a, b) => a * b;

console.log(add(2, 3)); // Output: 5


console.log(addArrow(2, 3)); // Output: 5
console.log(multiply(2, 3)); // Output: 6

Asynchronous Operation
<!--
In JavaScript, an asynchronous operation is a task that operates
independently of the main program flow, allowing other operations to proceed
while it executes.
-- Asynchronous operations are commonly used for tasks that involve
waiting for external events, such as fetching data from a server, reading a
file, or waiting for user input.
-- Asynchronous operations in javascript are typically managed using
mechanisms such as callbacks, Promises and async/await.

-- Asynchronous operations in javascript are typically managed using


mechanism such as:
1. Callbacks
2. Promises.
3. Async/Await
-->

<!--
1. Callbacks: They are fundamental concept in javaScript, especially in
asynchronous programming. They allow us to specify what should happen after an
asnchronous operation completes, ensuring that code execution continues
smoothly even when waiting for non-blocking tasks like fetching data from a
server or reading a file.
-- callbacks are commonly used in scenarios where the order of execution
is not guaranteed, such as event handling or asynchronous I/O operations.
2. Syntax: The syntax for using callbacks involves defining a function and
passing it as an argument. The receiving function executes the callback at
some point, typically after completing its task.
3. Nested callbacks and callback hell:
-- callbacks can be nested to handle multiple asynchronous operations
sequentially. However,nesting callbacks too deeply can lead to a phenomenon
known as callback hell, making code difficult to read and maintain.
-->
Callback.html

<!--
callback is a function that is passed as an argument to another function
and is intended to be called at a later time, typically after some
asynchronous operation completes or a certain condition is met. Callback
function allow for asynchronous programming, enabling code to execute non-
blocking operations and handle responses when they become available
-->

<script>
function doSomethingAsync(callback){
setTimeout(
function(){
var result = "async operation";
callback(result)
},2000
);
}
function callbackfnc(result){
console.log(result);
}
doSomethingAsync(callbackfnc);
</script>

Promise.html

<!--
Promises in Javascript are objects used to represent the eventual
completion or failure of an asynchronous operation.
-- They represent a value that may be available now, in the future, or
never. They are commonly used to manage async tasks such as fetching data from
a server, reading files, or executing long running computations without
blocking the execution thread.

-- There are three states a promise can be in:


1. Pending : initial state, neither fulfilled nor rejected.
2. Fulfilled : The operation completed successfully and the promise has a
value.
3. Rejected : The operation failed, and the promise has a reason for the
failure.

--The "then" method is used to handle the fulfilled state of the promise.
-- The catch method is used to handle the rejected state
-->

<script>
function fetchData(){
return new Promise(
(resolve,reject)=>{
setTimeout(() => {
const data = "This is my data";
const result = true;
if(result){
resolve(data);
}else{
reject(new Error("failed to fetch"));
}
}, 2000);
}
);
}
fetchData()
.then((data)=> console.log(data))
.catch((error)=> console.log(error))
</script>

Weather.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!-- Include Moment.js library -->
<script
src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></
script>
<!-- Include Moment.js adapter for Chart.js -->
<script
src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment"></script>
</head>
<body>
<div style="width: 1000px; height: 500px;">

<input type="text" id="city" >


<button onclick="fetchData()">Forecast</button>
<canvas id="chart" ></canvas>
</div>
<script>
const apiKey = "961b9bbbbd20811e513270fd35cebf86";
async function fetchData(){
const cityValue = document.getElementById("city").value.trim();
const url = `https://api.openweathermap.org/data/2.5/forecast?q=$
{cityValue}&appid=${apiKey}`;
try{
const data = await fetch(url);
const dataValue = await data.json();
displayChart(dataValue);
}catch(error){
console.log("error is "+error);
}
}
function displayChart(val){
console.log(val);
const data = val.list.map((item)=>{
return{
timestamp: item.dt * 1000,
temperature: item.main.temp -273.15,
}
})
console.log(data);
const ts = data.map((item)=> new Date(item.timestamp));
const temps = data.map((item) => item.temperature);
console.log("my timestamps"+ts);
console.log(temps);
const ctx = document.getElementById('chart').getContext('2d');
const weatherChart = new Chart(ctx,{
type:'line',
data:{
labels:ts,
datasets:[{
label:'Temperature (°C)',
data:temps,
borderColor:'blue',
fill:false,
}]
},
options:{
scales:{
x:{
type:'time',
time:{
unit: 'hour',
displayFormats:{
hour: 'MMM D, h a'
}
}
},
y: {
title:{
display:true,
text:"Temperature (°C)"
}
}
}
}
});
}
</script>
</body>
</html>

Week 5

5. Develop a java standlone application that connects with the database(Oracle / mySql) and
perform the CRUD operation on the database tables.

import java.sql.*;

public class MysqlCon2 {


static final String DB_URL = "jdbc:mysql://localhost:3306/secondyear";
static final String USER = "root";
static final String PASS = "root";

private static Connection connection;


private static Statement statement;
private static ResultSet resultSet;

public static void main(String[] args) {


try {
// Open a connection
connection = DriverManager.getConnection(DB_URL, USER, PASS);

// Execute CRUD operations


createRecord();
readRecords();
updateRecord();
deleteRecord();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close connections
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

}
private static void createRecord() throws SQLException{
statement = connection.createStatement();
String sql = "INSERT INTO table student(Roll,StudentName,Address) values
('124','tahir','balgarden')";
int rowsAffected = statement.executeUpdate(sql);
System.out.println("Record created successfully and rows affected is
"+rowsAffected);
}

private static void readRecords() throws SQLException{


statement = connection.createStatement();
String sql = "select * from student";
resultSet = statement.executeQuery(sql);
System.out.println("our record is :");
while(resultSet.next()){
int id = resultSet.getInt("Roll");
String name = resultSet.getString("StudentName");
String address = resultSet.getString("Address");
// ... (add more columns as needed)

// Display the data


System.out.println("Student Roll: " + id + ", Name: " +
name+", Address: "+address);

}
}
private static void updateRecord() throws SQLException {
statement = connection.createStatement();
String sql = "UPDATE student SET StudentName='new_value' WHERE
StudentName='yawar'";
int rowsAffected = statement.executeUpdate(sql);
System.out.println("Record updated successfully and rows affected
"+rowsAffected);
}

private static void deleteRecord() throws SQLException {


statement = connection.createStatement();
String sql = "DELETE FROM student WHERE Roll='124'";
int rowsAffected = statement.executeUpdate(sql);
System.out.println("Record deleted successfully and rows affected
"+rowsAffected);
}
}

Week 6

6. Create a custom server using http module and explore the other modules of Node JS like OS,
path, event.

http.js

/*
The 'http" module in Node.js provides functionality to create HTTP servers
and make HTTP requests. It allows developers to handle incoming HTTP requests
and generate HTTP RESPONSES.
- The 'http.createServer()' method is used to create an HTTP server. It
takes a callback function as an argument, which will be invoked each time a
request is made to the server.
- This callback function receives two arguments: "request" and "response".
Developers can process the incoming requests and send an appropriate responses
back to the client within this callback

- The 'request' and 'response' objects passed to the callback function


provide various properties and methods to interact with the incoming request
and outgoing response, respectively.

After creating the http server, developers need to specify which port the
server should listen on for incoming requests. This is achieved using
'server.listen()' method, which takes a port number and an optional callback
function as an argument.
*/

const http = require('http');

const server = http.createServer((req,res)=>{


// Handle incoming request
// Send response back to client
res.writeHead(200,{'Content-Type':'text/plain'});
res.end("hii everyone");
});

const Port = 3000;


server.listen(Port, () => {
console.log(`server is running on port${Port}`)
});

Os.js

const os = require('os');

console.log('Cpu architecture:',os.arch());
console.log('Total memory (GB):',(os.totalmem)/(1024*1024*1024));
console.log('Free memory(bytes):', os.freemem()/(1024*1024*1024));
console.log("host name(bytes):",os.hostname());
console.log("platform",os.platform());
console.log("type",os.type());

event.js

/*
Node js provides the core functionality for events through the
EventEmitter class.
- EventEmitter : This is the foundation for event-driven programming in
Node.js
- We create instance of EventEmitter to emit events and
listen for them
*/

// we use the emit() method to trigger the event


// we use the on() method to attach a listener function to an event. This
listener function will be called whenver the specified event is emitted.

const EventEmitter = require('events');


const myEmitter = new EventEmitter();

myEmitter.on('myEvent',(data)=>{
console.log('event triggered with data',data)
});
myEmitter.emit('myEvent',"Helloworld");

Week 7:

Develop an express web application that can interact with REST API to perform CRUD operations on
student data. (Use Postman).

App.js

const express = require('express');


const bodyParser = require('body-parser');
const app = express();
const Port = 3000;
//Sample data
let students = [
{id:1, name:"yawar", course:"data science"},
{
id:2, name:"shashi", course:"cyber-Security"
}
]

app.use(bodyParser.json());

// get all students


app.get('/students',(req,res)=>{
res.json(students);
});

//get student data by id


app.get("/students/:id",(req,res)=>{
const id = parseInt(req.params.id);
console.log(id);
const student = students.find((item)=> item.id === id);
if(!student){
return res.status(404).json({error:'student not found'});
}
res.json(student);
});

// Create a new student


app.post('/students',(req,res)=>{
const {name,course} = req.body;

if(!name || !course){
return res.status(404).json({error:"name and course are required"});
}
const id = students.length + 1;
console.log(id);
const newStudent = {id,name,course};
students.push(newStudent);
res.status(201).json(newStudent);

})

app.listen(Port,()=>{
console.log("server is running");
});

// Update a student by ID
app.put('/students/:id',(req,res)=>{
const id = parseInt(req.params.id);
const {name, course}=req.body;
const student = students.find((student)=> student.id === id);
if(!student){
return res.status(404).json({ error:"no such student found"});

}
student.name = name;
student.course = course;
res.json(student);
})

app.delete("/students/:id",(req,res)=>{
const id = parseInt(req.params.id);
const index = students.findIndex((student)=>student.id===id);
if(!index){
return res.status(404).json({error:"no such id found"});
}
students.splice(index,1);
res.status(204);
})

Week 8

8. For the above application create authorized end points using JWT (JSON Web Token).

const express = require('express');


const jwt = require('jsonwebtoken');

const app = express();


const PORT = process.env.PORT || 3000;
const ACCESS_TOKEN_SECRET = 'your_secret_key';
// middle ware to handle json data
app.use(express.json());

// Dummy user data (Replace with a real database in production)


const users = [
{ id: 1, username: 'admin', password: 'adminpassword' } // password is
"adminpassword"
];

// Function to validate user credentials


function authenticateUser(username, password) {
const user = users.find(u => u.username === username);
if (!user) return false;
else if(user.password === password) return true;

// Function to generate JWT token


function generateAccessToken(username) {
return jwt.sign(username, ACCESS_TOKEN_SECRET, { expiresIn: '15m' });
}

// Middleware to verify JWT token


function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
console.log(authHeader);
const token = authHeader && authHeader.split(' ')[1];
console.log(token);
if (token == null)
{ console.log("yaha nahi aya");
return res.sendStatus(401);}
console.log("yahi par ahi");
jwt.verify(token, ACCESS_TOKEN_SECRET, (err, user) => {
if (err){
console.log(err);
return res.sendStatus(403);
}
req.user = user;
next();
});
}

// Endpoint for user login and token generation


app.post('/api/login', (req, res) => {
const { username, password } = req.body;
const isValid = authenticateUser(username, password);
if (isValid) {
const accessToken = generateAccessToken({ username });
res.json({ accessToken });
} else {
res.status(401).json({ error: 'Invalid username or password' });
}
});
//Headers:
// Key: Authorization
// Value: Bearer <token> (replace <token> with the actual JWT token)
// Protected endpoint requiring JWT authentication
app.get('/api/protected', authenticateToken, (req, res) => {
res.json({ message: 'You are authorized to access this endpoint' });
});

// Start the server


app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

Week 9

Create a react application for the student management system having registration, login, contact,
about pages and implement routing to navigate through these pages.

Folder structure

--student-management-system

--public

--index.html
--src

--components

--About.css

--About.js

--Contact.css

--Contact.js

--Login.css

--Login.js

--LoginNav.js

--Navbar.js

--Navbar.css

--Registration.css

--Registration.js

--App.css

--App.js

--index.js

--index.css

Public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>

Src/About.css

.about-container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}

.about-content {
font-size: 16px;
display: flex;
flex-direction: column;
align-items: center;
}

.profile-image {
border-radius: 50%; /* Make the image rounded */
width: 150px; /* Adjust the width as needed */
height: 150px; /* Adjust the height as needed */
object-fit: cover; /* Ensure the image covers the entire area */
align-items: center;
}

.about-content p {
margin-bottom: 20px;
}

Src/About.js

import React from 'react';


import './About.css'; // Import CSS file for About component
import profileImage from '../assets/profile-image.jpeg'; // Import the image
file
import Navbar from './Navbar';

const About = () => {


return (
<>
<Navbar />
<div className="about-container">
<h2>About Me</h2>
<div className="about-content">
<img src={profileImage} alt="Profile" className="profile-image" />
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed
faucibus nunc vitae elit pulvinar, quis hendrerit
nulla condimentum. Nulla facilisi. In hac habitasse platea dictumst.
Nulla facilisi. Vestibulum sollicitudin
sit amet est eu placerat. Phasellus malesuada odio eget justo
efficitur, vitae varius magna vestibulum. Ut
interdum consectetur tellus, nec lobortis libero hendrerit id.
</p>
<p>
Donec eu nunc ut risus malesuada sollicitudin. Sed auctor arcu id
nibh dignissim, nec malesuada lacus feugiat.
Nulla sit amet bibendum lacus. Integer suscipit tincidunt tortor, id
scelerisque mauris feugiat vel. Aliquam
quis libero in purus varius feugiat. Integer condimentum ac mauris
et convallis. Curabitur tristique dui nec
magna tempus varius. Vestibulum interdum posuere felis, nec placerat
enim posuere et. Proin sed felis
hendrerit, convallis justo non, fermentum odio. Nulla facilisi.
</p>
</div>
</div>
</>

);
}

export default About;

Src/Contact.css
.contact-container {
max-width: 400px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
.contact-form {
display: flex;
flex-direction: column;
}

.form-group {
margin-bottom: 15px;
}

label {
font-weight: bold;
}

input[type="text"],
input[type="email"],
textarea {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}

textarea {
resize: vertical; /* Allow vertical resizing */
}

button {
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
padding: 10px 15px;
cursor: pointer;
}

button:hover {
background-color: #0056b3;
}

Contact.js

import React from 'react';


import './Contact.css'; // Import CSS file for Contact component
import Navbar from './Navbar';

const Contact = () => {


return (
<>
<Navbar />
<div className="contact-container">
<h2>Contact Me</h2>
<form className="contact-form">
<div className="form-group">
<label htmlFor="name">Name:</label>
<input type="text" id="name" name="name" />
</div>
<div className="form-group">
<label htmlFor="email">Email:</label>
<input type="email" id="email" name="email" />
</div>
<div className="form-group">
<label htmlFor="message">Message:</label>
<textarea id="message" name="message" rows="4"></textarea>
</div>
<button type="submit">Send Message</button>
</form>
</div>
</>

);
}

export default Contact;

src/Login.css

*{
box-sizing: border-box;
}
.login-container {
max-width: 400px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}

.login-form {
display: flex;
flex-direction: column;
}

.form-group {
margin-bottom: 15px;
}
label {
font-weight: bold;
}

input[type="email"],
input[type="password"] {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}

button {
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
padding: 10px 15px;
cursor: pointer;
}

button:hover {
background-color: #0056b3;
}

Src/Login.js

import React, { useState } from 'react';


import './Login.css'; // Import CSS file for Login component
import LoginNav from './LoginNav';
import About from './About';

const Login = () => {


const [submit,setSubmit] =useState(false);
return (
<>{!submit?(
<div>
<LoginNav />
<div className="login-container">
<h2>Login</h2>
<form onSubmit={(e)=>{
e.preventDefault();
setSubmit(true);
}} className="login-form">
<div className="form-group">
<label htmlFor="email">Email:</label>
<input type="email" id="email" name="email" />
</div>
<div className="form-group">
<label htmlFor="password">Password:</label>
<input type="password" id="password" name="password" />
</div>
<button type="submit">Login</button>
</form>
</div>
</div>
):(<div>
<About />
</div>)}

</>

);
}

export default Login;

src/LoginNav.js

import {Link} from 'react-router-dom';


const LoginNav = ()=>{
return(
<div>
<ul>
<li><Link to="/registration">Registration</Link></li>
<li><Link to="/login">Login</Link></li>
</ul>
</div>
);
}
export default LoginNav

src/Navbar.css

.navbar{
display: flex;
margin: 10px;
list-style-type: none;
text-align: center;

}
.navbar li{
margin: 10px;
background-color: aqua;
padding: 5px 10px;
border-radius: 10px;
color: brown;
font-size: 1.25rem;

Src/Navbar.js

import React from 'react';


import { Link } from 'react-router-dom';
import "./Navbar.css";

const Navbar = () => {


return (
<nav>
<ul className='navbar'>

<li><Link to="/contact">Contact</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
</nav>
);
}

export default Navbar;

Registration.css

.registration-container {
max-width: 400px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}

.registration-form {
display: flex;
flex-direction: column;
}

.form-group {
margin-bottom: 15px;
}
label {
font-weight: bold;
}

input[type="text"],
input[type="email"],
input[type="password"],
input[type="date"] {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}

button {
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
padding: 10px 15px;
cursor: pointer;
}

button:hover {
background-color: #0056b3;
}

Registration.js

import React, { useState } from 'react';


import './Registration.css';
import LoginNav from './LoginNav';
import About from './About';

const Registration = () => {


const [submit,setSubmit]=useState(false);

return (
<>{
!submit? (<div>
<LoginNav />
<div className="registration-container">
<h2>Registration</h2>
<form onSubmit={()=> setSubmit(true)}className="registration-form">
<div className="form-group">
<label htmlFor="name">Name:</label>
<input type="text" id="name" name="name" />
</div>
<div className="form-group">
<label htmlFor="email">Email:</label>
<input type="email" id="email" name="email" />
</div>
<div className="form-group">
<label htmlFor="password">Password:</label>
<input type="password" id="password" name="password" />
</div>
<div className="form-group">
<label htmlFor="confirmPassword">Confirm Password:</label>
<input type="password" id="confirmPassword" name="confirmPassword"
/>
</div>
<div className="form-group">
<label htmlFor="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" />
</div>
<button type="submit">Register</button>
</form>
</div>
</div> ):(
<div>
<About/>
</div>
)

</>

);
}

export default Registration;

App.css
.App {
text-align: center;
}

.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}

.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}

.App-link {
color: #61dafb;
}

@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

App.js
import React from 'react';
import { BrowserRouter, Route, Routes } from 'react-router-dom';

import Registration from './components/Registration';


import Login from './components/Login';
import Contact from './components/Contact';
import About from './components/About';

function App() {
return (
<BrowserRouter>

<Routes>
<Route path="/" element={<Login />} />
<Route path="/about" element={<About />} />
<Route path="/login" element={<Login />} />
<Route path="/contact" element={<Contact />} />
<Route path="/registration" element={<Registration />} />
</Routes>
</BrowserRouter>
);
}

export default App;


Week 10

Create a service in react that fetches the weather information from openweathermap.org and the
display the current and historical weather information using graphical representation using chart.js.

Folder Structure

--weather-app

--public

--index.html

--src

--App.js

--CurrentWeather.css

--CurrentWeather.js

--HistoricalWeather.js

--index.css

--index.js

Public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>

</body>
</html>

Src/App.js

import React from 'react';


import './App.css';
import CurrentWeather from './CurrentWeather';
import HistoricalWeather from './HistoricalWeather';

function App() {
return (
<div className="App">
<h1>Weather App</h1>
<CurrentWeather />
<HistoricalWeather />
</div>
);
}

export default App;

src/CurrentWeather.css

.currentWeather{
width: 800px;
height: 600px;
}

Src/CurrentWeather.js

import React, { useState, useEffect } from 'react';


import Chart from 'chart.js/auto';
import './CurrentWeather.css';
const apiKey = "961b9bbbbd20811e513270fd35cebf86";

const CurrentWeather = () => {


const [weatherData, setWeatherData] = useState(null);
const cityValue="hyderabad";

useEffect(() => {
fetchCurrentWeather();
}, []);

const fetchCurrentWeather = async () => {


try {
const response = await
fetch(`https://api.openweathermap.org/data/2.5/weather?
q=hyderabad&appid=961b9bbbbd20811e513270fd35cebf86&units=metric`);
if (!response.ok) {
throw new Error('Failed to fetch current weather data');
}
const data = await response.json();
setWeatherData(data);
createChart(data);
} catch (error) {
console.error(error.message);
}
};

const createChart = (data) => {


const ctx =
document.getElementById('currentWeatherChart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Temperature', 'Humidity', 'Pressure'],
datasets: [{
label: 'Current Weather',
data: [
data.main.temp,
data.main.humidity,
data.main.pressure
],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
};

return (
<div className='currentWeather'>
<h2>Current Weather</h2>
{weatherData &&
<canvas id="currentWeatherChart" width="400" height="200"></canvas>
}
</div>
);
};

export default CurrentWeather;

src/HistoricalWeather.js

import React, { useState, useEffect } from 'react';


import Chart from 'chart.js/auto';
const apiKey = "961b9bbbbd20811e513270fd35cebf86";

const HistoricalWeather = () => {


const [weatherData, setWeatherData] = useState(null);

useEffect(() => {
fetchHistoricalWeather();
}, []);

const fetchHistoricalWeather = async () => {


try {
const response = await
fetch(`https://history.openweathermap.org/data/2.5/history/city?
q=London,UK&appid=${apiKey}`);
if (!response.ok) {
throw new Error('Failed to fetch historical weather data');
}
const data = await response.json();
console.log(data);
setWeatherData(data);
createChart(data);
} catch (error) {
console.error(error.message);
}
};

const createChart = (data) => {


const ctx =
document.getElementById('historicalWeatherChart').getContext('2d');
new Chart(ctx, {
type: 'line',
data: {
labels: data.list.map(entry => new Date(entry.dt *
1000).toLocaleTimeString()),
datasets: [{
label: 'Temperature',
data: data.list.map(entry => entry.dt),
borderColor: 'rgba(255, 99, 132, 1)',
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderWidth: 1,
fill: true
}]
},
options: {
scales: {
y: {
beginAtZero: false
}
}
}
});
};

return (
<div>
<h2>Historical Weather</h2>

{weatherData &&
<canvas id="historicalWeatherChart" width="400" height="200"></canvas>
}
</div>
);
};
export default HistoricalWeather;

index.css

body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto',
'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

Src/index.js

import React from 'react';


import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Week11

Create a TODO application in react with necessary component and deploy it into github.

--Todo

--public

--index.html

--src

--App.css

--App.js

--index.css

--index.js

--Todo.js
Public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>

</body>
</html>

Src/App.css

.App {
text-align: center;
}

.App-logo {
height: 40vmin;
pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {


.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}

.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}

.App-link {
color: #61dafb;
}

@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

App.js

import './App.css';
import Todo from './Todo';

function App() {
return (
<div className="App">
<Todo />
</div>
);
}

export default App;

src/index.js

import React from 'react';


import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Src/Todo.js

import React, { useState } from 'react';

const Todo = () => {


const [todos, setTodos] = useState([]);
const [inputValue, setInputValue] = useState('');

const handleInputChange = (event) => {


setInputValue(event.target.value);
};

const handleAddTodo = () => {


if (inputValue.trim() !== '') {
setTodos([...todos, inputValue]);
setInputValue('');
}
};

const handleDeleteTodo = (index) => {


const updatedTodos = todos.filter((_, i) => i !== index);
setTodos(updatedTodos);
};

return (
<div>
<h1>TODO List</h1>
<input
type="text"
value={inputValue}
onChange={handleInputChange}
placeholder="Enter a new todo"
/>
<button onClick={handleAddTodo}>Add Todo</button>
<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo}
<button onClick={() => handleDeleteTodo(index)}>Delete</button>
</li>
))}
</ul>
</div>
);
};

export default Todo;

You might also like