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

1.

Program using canvas tag to draw different shapes (circle, triangle,


rectangle).
<!DOCTYPE html>
<html>
<head>
<title>Shapes Drawing</title>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
// Get the canvas element
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

// Draw a circle
ctx.beginPath();
ctx.arc(100, 100, 50, 0, 2 * Math.PI);
ctx.fillStyle = "blue";
ctx.fill();
ctx.closePath();

// Draw a triangle
ctx.beginPath();
ctx.moveTo(200, 100);
ctx.lineTo(250, 200);
ctx.lineTo(150, 200);
ctx.closePath();
ctx.fillStyle = "green";
ctx.fill();

// Draw a rectangle
ctx.fillStyle = "red";
ctx.fillRect(300, 100, 80, 60);
</script>
</body>
</html>

2. External CSS (CSS properties: font, text, color)with suitable example


Certainly! Let’s delve into the world of external CSS and explore how it can

enhance the styling of your web pages. 🎨

External CSS Basics

External CSS allows you to style multiple HTML pages using a single style sheet.
It’s a great way to maintain consistency across your website. Here’s how it works:

1. Create an External CSS File:


o An external CSS file has a .css extension.
o It contains style properties applied to selectors (such as classes, IDs,
and HTML elements).
2. Link the CSS File to Your HTML:
o In your HTML file’s <head> section, use the <link> element with the
rel attribute set to "stylesheet".
o Specify the path to your CSS file using the href attribute.
3. Apply Styles Consistently:
o External CSS ensures a unified design across multiple web pages.

Example 1: Styling a Simple Page

Suppose we have an external CSS file named geeks.css. Let’s style a basic HTML
page:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="geeks.css">
</head>
<body>
<div class="main">
<h1 class="GFG">GeeksForGeeks</h1>
<p id="geeks">A computer science portal for geeks</p>
</div>
</body>
</html>

In geeks.css, we define the following styles:

.main {
text-align: center;
}

.GFG {
font-size: 60px;
color: green;
}

#geeks {
font-size: 25px;
color: skyblue;
}

 The .main class centers the text.


 The .GFG class sets a large font size and green color for the heading.
 The #geeks ID styles the paragraph with a smaller font size and sky blue
color.

Example 2: Creating Styled Cards

Let’s use external CSS to create styled cards:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>External CSS Example</title>
<link rel="stylesheet" href="geeks.css">
</head>
<body>
<h1>GeeksforGeeks</h1>
<p>A computer science portal for geeks.</p>
<div class="geeks">
<h2>HTML</h2>
<p>HTML stands for Hyper Text Markup Language.</p>
</div>
<div class="geeks">
<h2>CSS</h2>
<p>CSS stands for Cascading Style Sheet.</p>
</div>
</body>
</html>

In geeks.css, we define styles for .geeks:

.geeks {
background-color: lightgrey;
color: blue;
}

 The .geeks class sets the background color to light grey and the text color to
blue.
Advantages of External CSS:

 Improved maintainability and code organization.


 Enhanced reusability across multiple HTML files.
 Efficient caching and faster page load times.

3. Any 4 pseudo classes in CSS with example

Certainly! Pseudo-classes in CSS allow you to style elements based on specific


states or conditions. Here are four commonly used pseudo-classes along with
examples:

1. :hover: This pseudo-class targets an element when the user hovers over it.
It’s commonly used for interactive effects like changing link colors when the
mouse is over them.
2. /* Example: Change link color on hover */
3. a:hover {
4. color: #FF00FF; /* Magenta */
5. }

6. :visited: Use this pseudo-class to style visited links differently from


unvisited ones. It’s helpful for maintaining user context.
7. /* Example: Style visited and unvisited links differently */
8. a:visited {
9. color: #00FF00; /* Green */
10.}

11.:active: When an element is actively being clicked or interacted with (such


as a button press), this pseudo-class applies. It’s useful for creating visual
feedback during user interactions.
12./* Example: Change link color when clicked */
13.a:active {
14. color: #0000FF; /* Blue */
15.}

16.:first-child: This pseudo-class selects the first child element of its parent. It’s
handy for styling specific elements within a container.
17./* Example: Style the first <p> element */
18.p:first-child {
19. color: blue;
20.}

4. Semantic element in HTML5

Certainly! In HTML5, semantic elements play a crucial role in structuring web


content. Let’s dive into what they are and why they matter:

1. What Are Semantic Elements?


o Semantic elements are HTML tags that carry inherent meaning,
indicating the type of content they contain.
o Unlike generic <div> and <span> tags used for layout purposes,
semantic elements provide valuable context about the content they
enclose.
o These elements clearly describe their meaning in a human- and
machine-readable way.
2. Examples of Semantic Elements:
o <header>: Represents a header section, typically containing site or
page titles, navigation menus, or introductory content.
o <footer>: Defines a footer section, often containing copyright
information, contact details, or related links.
o <article>: Specifies independent, self-contained content. An article
should make sense on its own and can be distributed independently
from the rest of the website (e.g., blog posts, news articles).
o <section>: Groups related content thematically, often with a
heading. It helps organize content into meaningful blocks (e.g.,
chapters, introduction, contact information).
3. Example Usage:

<section>
<h1>World Wide Fund for Nature (WWF)</h1>
<p>The WWF is an international organization working on environmental
conservation and research.</p>
</section>
<article>
<h2>Google Chrome</h2>
<p>Google Chrome is a popular web browser developed by Google.</p>
</article>

Why Are Semantic Elements Important?

o Accessibility: Semantic elements enhance accessibility for screen


readers and assistive technologies.
o SEO: Search engines use semantic structure to understand content
better, improving search rankings.
o Maintenance: Clear semantics make code easier to read, maintain,
and collaborate on.

5. Program to create a server in nodeJS and display server responses on a


web pages

Certainly! Below is a basic example of how to create a simple HTTP server using
Node.js. This server will return an HTML response to the user:

const http = require('http');

// Create a server object


const server = http.createServer((req, res) => {
// Set the response header
res.writeHead(200, {'Content-Type': 'text/html'});

// Send a response
res.end('<html><body><h1>Hello, this is a simple Node.js web
server!</h1></body></html>');
});

// Listen on port 8080


server.listen(8080, () => {
console.log('Server is running at [^1^][1]');
});
In this example:

1. We import the http module.


2. Create a server using the http.createServer() method, which takes a
callback function as an argument. This function will be invoked for each
incoming HTTP request.
3. Inside the callback function, we set the response header to indicate that we
are returning HTML content.
4. We send an HTML response with the message “Hello, this is a simple
Node.js web server!”.

6. What is nodeJS and its working and features

Node.js is an open-source, cross-platform JavaScript runtime environment that


allows you to execute JavaScript code outside of a web browser. Let’s delve into
its working and features:

1. Working of Node.js:
o Backend JavaScript Runtime: Node.js serves as a backend service
where JavaScript runs on the server-side of an application. This
unique feature enables the use of JavaScript both on the frontend
and backend.
o Chrome V8 Engine: Node.js operates on the V8 JavaScript engine
developed by Google. This engine converts JavaScript code into
machine code, making Node.js highly efficient.
o Single-Threaded Event Loop:
 Node.js handles requests using a single thread. However, it
employs the concept of asynchronous non-blocking I/O.
 When a request arrives, Node.js doesn’t block the thread.
Instead, it sends the request to another system (such as a
database) for resolution.
 The event loop picks up completed tasks and executes
associated callback functions.
o Libuv Library:
 Node.js relies on the Libuv library, written in C, for
asynchronous I/O operations.
 Libuv provides access to the underlying operating system, file
system, and networking.
 It implements two crucial features for Node.js:
 Event Loop: Responsible for executing callbacks and
handling network I/O.
 Thread Pool: Manages I/O-bound tasks.
o Event-Driven Architecture:
 Node.js emits events, which the event loop processes.
 Callback functions execute when work (such as fetching data
from a database) completes.
 This architecture ensures that Node.js can handle multiple
concurrent requests without blocking the thread.
2. Features of Node.js:
o Cross-Platform: Node.js runs on OS X, Microsoft Windows, and Linux,
making it versatile.
o Scalability: It’s lightweight and scalable, suitable for building large-
scale applications.
o Non-Blocking I/O: Node.js efficiently handles multiple requests
without blocking the thread.
o Real-Time Applications: Ideal for real-time applications like chat
applications, streaming services, and gaming servers.
o Server-Side Scripting: Node.js simplifies building the backend of web
applications.
o Event-Driven: Node.js leverages an event-driven model for
asynchronous programming.

7. Any 5 modules of NodeJS

Certainly! Node.js, being a powerful runtime environment for server-side


JavaScript, provides a modular system that allows developers to organize their
code into reusable and manageable pieces. Let’s delve into five essential modules
in Node.js:

1. HTTP Module:
o The http module is a core module that enables the creation of HTTP
servers and clients. It allows you to handle incoming HTTP requests
and send responses.
o Example usage:
o const http = require('http');
o http.createServer(function (req, res) {
o res.writeHead(200, { 'Content-Type': 'text/html' });
o res.write('Welcome to this page!');
o res.end();
o }).listen(3000);
o Key functionalities: Creating an HTTP server, handling requests, and
sending responses.
2. Assert Module:
o The assert module provides a set of assertion functions useful for
testing. It helps validate conditions and ensures that assumptions
hold true during development and testing.
o Example usage:
o const assert = require('assert');
o assert.strictEqual(2 + 2, 4, 'Math is still working!');
o Key functionalities: Assertion checks, ensuring correctness.
3. File System (fs) Module:
o The fs module allows interaction with the file system. It provides
methods for reading, writing, and manipulating files and directories.
o Example usage:
o const fs = require('fs');
o fs.readFile('myfile.txt', 'utf8', (err, data) => {
o if (err) throw err;
o console.log(data);
o });
o Key functionalities: Reading/writing files, managing directories.
4. Path Module:
o The path module deals with file paths and directory paths. It provides
utilities for working with file and directory paths in a platform-
independent manner.
o Example usage:
o const path = require('path');
o const fullPath = path.join(__dirname, 'mydir', 'myfile.txt');
o console.log(fullPath);
o Key functionalities: Path manipulation, resolving paths.
5. Process Module:
o The process module provides information and control over the
current Node.js process. It exposes properties and methods related
to the environment, command-line arguments, and process
management.
o Example usage:
o console.log(`Node.js version: ${process.version}`);
o console.log(`Current working directory: ${process.cwd()}`);
o Key functionalities: Accessing environment variables, handling
signals, managing process lifecycle.

Remember that Node.js also supports local modules, which are custom modules
created within your application. These local modules enhance code organization

and reusability by encapsulating related functionality. 🚀🔗

8. Program to show current date and time using user defined modules in
node.JS

Certainly! Below is an example of how you can create a user-defined module in


Node.js to get the current date and time:

1. Create a file called “myfirstmodule.js” with the following content:

// myfirstmodule.js
exports.myDateTime = function () {
return Date();
};

2. Node.js program to use the exported function from the user-defined


module:

// main.js (your main Node.js file)


const myModule = require('./myfirstmodule');
// Get the current date and time using the exported function
const currentDateAndTime = myModule.myDateTime();

// Print the result


console.log(`Current date and time: ${currentDateAndTime}`);

3. Run the program by executing the following command in your terminal:

node main.js

This will display the current date and time. Feel free to adjust the code according
to your needs!

9. Date and time filter in angular with Example

Certainly! In Angular, you can use the date filter to format dates according to
your desired display format. Let’s explore how to use it with some examples:

1. Basic Usage:
o The date filter formats a date to a specified format.
o By default, the format is “MMM d, y” (e.g., Jan 5, 2016).
o You can customize the format using various placeholders.
2. Syntax:
3. {{ date | date : format : timezone }}
o date: The date object, milliseconds, or a datetime string (e.g., “2016-
01-05T09:05:05.035Z”).
o format: Optional. Specifies the desired date format.
o timezone: Optional. Specifies the timezone used for formatting.
4. Common Format Options:
o "yyyy": Year (e.g., 2016)
o "yy": Year (e.g., 16)
o "MMMM": Full month name (e.g., January)
o "MMM": Abbreviated month name (e.g., Jan)
o "dd": Day (e.g., 06)
o "HH": Hour (00-23, e.g., 09)
o "mm": Minute (e.g., 05)
o "ss": Second (e.g., 05)
o "a": AM/PM
o "Z": Timezone (from -1200 to +1200)
5. Examples:
o Display a date in a custom format:
o <p>Date = {{ today | date : "dd.MM.y" }}</p>
o Display a date using a predefined format (e.g., fullDate):
o <p>Date = {{ today | date : "fullDate" }}</p>
o Combine text and a predefined format:
o <p>Date = {{ today | date : "'today is ' MMMM d, y" }}</p>
6. Additional Examples:
o Display a datetime string:
o <p>Date = {{ "2016-01-05T09:05:05.035Z" | date }}</p>

10.Routing in Angular with suitable example

Certainly! In Angular, routing allows you to navigate between different views


(components) within your application. It’s essential for creating single-page
applications (SPAs) where users can move from one part of the app to another
without full page reloads. Let’s dive into the details with a suitable example:

1. What is Angular Routing?


o Routing enables you to move from one part of your Angular
application to another part or from one view to another view.
o The Angular Router handles routing and provides necessary service
providers and directives for navigation.
o Key features of Angular routing include:
 Navigating to specific views via URLs.
 Passing optional query parameters to views.
 Handling back and forward buttons in the browser.
 Dynamically loading views.
 Protecting routes using route guards.
2. Components of Angular Router:
o Router: The Angular Router service enables navigation between
components based on user actions (e.g., clicking links or buttons).
o Route: A route specifies which component to display when a user
clicks a link or enters a URL. It consists of a path and the associated
component.
o Routes: An array of route objects supported by your application.
o RouterOutlet: A directive (<router-outlet>) acts as a placeholder
where the router displays the view associated with the current route.
o RouterLink: A directive that binds an HTML element to a route.
Clicking the element navigates to the specified route.
o RouterLinkActive: A directive for adding/removing classes from an
HTML element based on the currently active route.
o ActivatedRoute: Represents the currently activated route associated
with the loaded component.
o RouterState: Represents the current state of the router, including
the tree of activated routes.
3. Example: Creating an Angular Routing Application: Let’s create a simple
Angular app with routing. Assume we have the following components:
o HomeComponent: Displays home content.
o AboutComponent: Displays information about the app.
o ContactComponent: Shows contact details.

Step 1: Set Up Routes

o Define routes in your app-routing.module.ts:


o const routes: Routes = [
o { path: '', component: HomeComponent },
o { path: 'about', component: AboutComponent },
o { path: 'contact', component: ContactComponent },
o ];

Step 2: Configure Routes

o Import RouterModule and configure routes in your app.module.ts:


o @NgModule({
o imports: [RouterModule.forRoot(routes)],
o exports: [RouterModule],
o })
o export class AppRoutingModule {}

Step 3: Use Router Outlet

o In your app.component.html, add the <router-outlet>:


o <router-outlet></router-outlet>

Step 4: Create Navigation Links

o In your navigation menu or elsewhere, use routerLink to navigate:


o <a routerLink="/">Home</a>
o <a routerLink="/about">About</a>
o <a routerLink="/contact">Contact</a>

Step 5: Implement Components

o Create HomeComponent, AboutComponent, and


ContactComponent.

Now, when users click the links, they’ll navigate to the corresponding
components. The URL will update accordingly.

4. Run the Application:


o Execute ng serve to run your Angular app.
o Open your browser and navigate to http://localhost:4200.

11.Dependency injection in Angular with suitable example

Certainly! Dependency injection (DI) is a fundamental concept in Angular that


allows you to manage dependencies between different parts of your application.
Let’s explore how DI works and provide some suitable examples:

1. Understanding Dependency Injection (DI):


o DI is wired into the Angular framework and enables classes (such as
Components, Directives, Pipes, and Injectables) to configure the
dependencies they need.
o It involves two main roles:
 Dependency Consumer: The class that requires a dependency.
 Dependency Provider: The class that provides the
dependency.
o Angular uses an abstraction called the Injector to facilitate
interaction between consumers and providers.
2. How DI Works:
o When a dependency is requested (e.g., by a component), the injector
checks its registry to see if an instance of that dependency is already
available.
o If not, a new instance is created and stored in the registry.
o Angular creates an application-wide injector (also known as the
“root” injector) during application bootstrap. Additional injectors are
created as needed.
3. Providing Dependencies:
o To make a class injectable, add the @Injectable() decorator to it:
o @Injectable()
o class HeroService {
o // Implementation here
o }
o You can provide a dependency in multiple places:
 Component Level:
 Use the providers field of the @Component decorator to
make the service available to all instances of that
component and other components used in its template:
 @Component({
 selector: 'hero-list',
 template: '...',
 providers: [HeroService]
 })
 class HeroListComponent {}
 Application Level:
 Use the providers field of the ApplicationConfig object
passed to the bootstrapApplication function. The service
becomes available to all components, directives, and
pipes declared in the same NgModule or other
NgModules within the same ModuleInjector:
 export const appConfig: ApplicationConfig = {
 providers: [
 { provide: HeroService },
 ]
 };
 In main.ts:
 bootstrapApplication(appConfig);
4. Example: Let’s say we have a UserService that needs to be injected into a
component. Here’s how you can do it:
5. import { Injectable } from '@angular/core';
6.
7. @Injectable()
8. export class UserService {
9. getUsers() {
10. // Implementation here
11. }
12.}

In your component:

import { Component } from '@angular/core';


import { UserService } from './user.service';

@Component({
selector: 'app-user-list',
template: '...',
providers: [UserService] // Make UserService available to this component
})
export class UserListComponent {
constructor(private userService: UserService) {
// Use userService methods here
}
}

13.Benefits of DI:
o Keeps code flexible, testable, and maintainable.
o Allows easy swapping of dependencies (e.g., mocking services during
testing).
o Promotes separation of concerns.
Remember that DI is a powerful feature in Angular that simplifies managing

dependencies and promotes good software design practices! 😊

12.Typescript with example

Certainly! TypeScript is a superset of JavaScript that adds static typing and other
features to enhance code quality. Let’s dive into TypeScript with some examples:

1. What is TypeScript?
o TypeScript extends JavaScript by introducing a type system.
o It allows you to specify data types for variables, function parameters,
and return values.
o TypeScript code is transpiled to plain JavaScript, making it compatible
with existing JavaScript projects.
2. Example: Basic TypeScript Syntax
o Consider this simple JavaScript function:
o const multiply = (a, b) => {
o return a * b;
o };
o In TypeScript, you can add type annotations:
o const multiply = (a: number, b: number): number => {
o return a * b;
o };
3. Benefits of TypeScript:
o Static Typing: TypeScript ensures that variable types remain
consistent during program execution, reducing bugs.
o Readability: Clear type annotations make code more
understandable.
o Better JavaScript Understanding: Learning TypeScript deepens your
understanding of JavaScript.
4. Example: Using TypeScript in an Angular Component
o Suppose we have an Angular component that displays a user’s name:
o // user.component.ts
o import { Component } from '@angular/core';
o
o @Component({
o selector: 'app-user',
o template: '<p>Hello, {{ userName }}</p>',
o })
o export class UserComponent {
o userName: string = 'John Doe';
o }
o Here, userName is explicitly typed as a string.
5. How to Install TypeScript?
o Install TypeScript globally using npm:
o npm install -g typescript
o Create a .ts file (e.g., my-file.ts) and write TypeScript code.
o Compile TypeScript to JavaScript:
o tsc my-file.ts
o Run the generated JavaScript file (my-file.js).

Remember that TypeScript enhances JavaScript by providing static typing and


other features, making it a powerful tool for building scalable and maintainable

applications! 😊

For more detailed tutorials, you can explore resources like GeeksforGeeks
TypeScript Tutorial1, freeCodeCamp TypeScript Guide2, and W3Schools TypeScript
Tutorial3.

13.Cookies in PHP? Write a program to crate a cookie and delete the created
cookie after 1 hr

In PHP, a cookie is a small piece of data that the web server sends to a user’s
browser. It is stored on the client’s computer and serves various purposes, such
as tracking user behavior, maintaining session information, or remembering user
preferences. Here are the key points about cookies in PHP:

1. Creating a Cookie:
o You can create a cookie using the setcookie() function.
o Syntax: setcookie(name, value, expire, path, domain, secure,
httponly)
o Only the name parameter is required; others are optional.
2. Retrieving a Cookie:
o To retrieve the value of a cookie, use the global variable $_COOKIE.
3. Modifying a Cookie:
o To modify a cookie, set it again using the setcookie() function.
4. Deleting a Cookie:
o To delete a cookie, set its expiration date to the past using
setcookie().
5. Checking if Cookies are Enabled:
o Create a test cookie and count the $_COOKIE array.

6. PHP program that creates a cookie named “user” with a value and an
expiration time of 1 hour. After 1 hour, the cookie will be automatically
deleted:
7. <?php
8. // Create a cookie named "user" with a value and an expiration time of 1
hour
9. $cookie_name = "user";
10.$cookie_value = "John Doe";
11.setcookie($cookie_name, $cookie_value, time() + 3600, "/"); // Expires
after 1 hour
12.
13.// Print a success message
14.echo "Cookie named '$cookie_name' is set with value '$cookie_value' and
will expire after 1 hour.";
15.?>

This program sets a cookie named “user” with the value “John Doe” and
ensures that it will be automatically deleted after 1 hour.

14.PHP code to create and print the values of multidimensional array

Certainly! Below is an example of how to create and print the values of a


multidimensional array in PHP:

<?php
// Example of a multidimensional array
$students = array(
array("John", "Doe", 20),
array("Jane", "Smith", 22),
array("Alice", "Johnson", 21)
);

// Accessing values
echo "First student: " . $students[0][0] . " " . $students[0][1] . " (Age: " .
$students[0][2] . ")\n";
echo "Second student: " . $students[1][0] . " " . $students[1][1] . " (Age: " .
$students[1][2] . ")\n";
echo "Third student: " . $students[2][0] . " " . $students[2][1] . " (Age: " .
$students[2][2] . ")\n";

// Printing the entire array


echo "\nPrinting the entire array:\n";
print_r($students);
?>

In this example:

 We create a multidimensional array called $students with three subarrays,


each representing a student’s first name, last name, and age.
 We access and print specific values from the array.
 Finally, we print the entire array using print_r().

Feel free to modify the array or add more students as needed! 😊

15.PHP code to display employees belongs to computer department and


salary is in between 50000 to 90000 and store found records into the
another table

Certainly! Below is a PHP program that retrieves employees belonging to the


“Computer” department and having salaries between $50,000 and $90,000. It
then stores the found records into another table:
<?php
// Database connection (replace with your actual credentials)
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Retrieve employees from the "employees" table


$sql = "SELECT * FROM employees WHERE department = 'Computer' AND salary
BETWEEN 50000 AND 90000";
$result = $conn->query($sql);

// Create a new table to store the filtered records


$newTableName = "filtered_employees";
$sqlCreateTable = "CREATE TABLE $newTableName (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(255),
emp_salary DECIMAL(10, 2)
)";

if ($conn->query($sqlCreateTable) === TRUE) {


echo "Table $newTableName created successfully.<br>";
} else {
echo "Error creating table: " . $conn->error;
}

// Insert filtered records into the new table


while ($row = $result->fetch_assoc()) {
$empId = $row["emp_id"];
$empName = $row["emp_name"];
$empSalary = $row["salary"];

$sqlInsert = "INSERT INTO $newTableName (emp_id, emp_name, emp_salary)


VALUES ($empId, '$empName', $empSalary)";
$conn->query($sqlInsert);
}

echo "Filtered records inserted into table $newTableName successfully.";

// Close the connection


$conn->close();
?>

Make sure to replace the placeholders (your_username, your_password,


your_database) with your actual database credentials. This program retrieves
employees from the “employees” table, filters them based on department and
salary, and stores the filtered records in a new table called “filtered_employees”.

Remember to adjust the table and column names according to your database

schema! 😊

16.Short note:
 Events in NodeJS
 SPA in Angular
 Super Global Variable in PHP

Certainly! Here are brief notes on each of the requested topics:

1. Events in Node.js:
o Node.js is an asynchronous, event-driven JavaScript runtime.
o The events module in Node.js allows you to work with events.
o Key concepts:
 EventEmitter: A class that emits named events and allows
functions (callbacks) to listen for those events.
 Listeners: Functions that subscribe to specific events.
 Emitting Events: You can trigger an event using the emit(event,
[arg1], [arg2], ...) function.
o Example:
o const EventEmitter = require('events');
o const eventEmitter = new EventEmitter();
o
o eventEmitter.on('myEvent', (msg) => {
o console.log(msg);
o });
o
o eventEmitter.emit('myEvent', "First event");
2. SPA (Single Page Application) in Angular:
o An SPA loads a single HTML page and dynamically updates parts of
the page as users interact with the application.
o Benefits:
 Improved user experience (no full page reloads).
 Faster navigation.
 Efficient use of resources.
o Angular supports building SPAs using its router module.
o Example: Angular University’s website is an SPA.
3. Super Global Variable in PHP:
o Superglobals are built-in variables accessible in all scopes (functions,
classes, files).
o Common superglobals:
 $GLOBALS: Access global variables from anywhere.
 $_SERVER: Information about the server and request.
 $_REQUEST: Data sent via HTTP request (GET, POST, and
cookies).
 $_POST: Data sent via POST request.
 $_GET: Data sent via GET request.
 $_FILES: Uploaded file information.
 $_ENV: Environment variables.
 $_COOKIE: Client-side cookies.
 $_SESSION: Server-side session data.
SPPU Sample Question
1. What is SVG ? explain any two components of SVG with suitable example

Certainly! SVG stands for Scalable Vector Graphics. It’s a format used to create
vector-based graphics on the web. Let me break down the components of SVG
and provide examples for each:

1. Basic Shapes:
o SVG allows you to create basic shapes such as rectangles, circles,
ellipses, lines, polygons, and more.
o For instance, here’s an example of a yellow circle with a green
border:
o <svg width="100" height="100"
xmlns="http://www.w3.org/2000/svg">
o <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4"
fill="yellow" />
o </svg>
o You can experiment with different shapes and attributes using SVG.
2. Text and Text Paths:
o SVG lets you include text in your graphics.
o Here’s an example of rotating each letter of the word “SVG” using
the rotate attribute:
o <svg width="200" height="50"
xmlns="http://www.w3.org/2000/svg">
o <text x="10" y="30" font-family="Arial" font-size="20" fill="blue">
o <tspan x="10" dy="0">S</tspan>
o <tspan x="30" dy="0" rotate="30">V</tspan>
o <tspan x="50" dy="0" rotate="60">G</tspan>
o </text>
o </svg>
o You can also create text along a path using the <textPath> element.

Remember that SVG is an open standard, and its graphics are defined in XML
format. Feel free to explore more SVG elements and create your own scalable

graphics! 😊

If you’d like to learn more, you can refer to the W3Schools SVG Tutorial or the
MDN Web Docs SVG Introduction.12

2. Write a PHP script for retrieving top 10 records from the database. Assume
suitable data.

Certainly! Below is a PHP script that retrieves the top 10 records from a MySQL
database and displays them in an HTML table:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gfg";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_errno) {
echo "Failed to connect to MySQL: " . $conn->connect_error;
exit();
}

$sql = "SELECT * FROM student LIMIT 10";


$result = $conn->query($sql);
$row = [];

if ($result->num_rows > 0) {
$row = $result->fetch_all(MYSQLI_ASSOC);
}
?>

<!DOCTYPE html>
<html>
<head>
<style>
td, th {
border: 1px solid black;
padding: 10px;
margin: 5px;
text-align: center;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>Name</th>
<th>Branch</th>
<th>Roll Number</th>
</tr>
</thead>
<tbody>
<?php
if (!empty($row)) {
foreach ($row as $rows) {
?>
<tr>
<td><?php echo $rows['name']; ?></td>
<td><?php echo $rows['branch']; ?></td>
<td><?php echo $rows['roll_no']; ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
</body>
</html>

<?php
mysqli_close($conn);
?>

In this script:

 Replace the database credentials ($servername, $username, $password,


and $dbname) with your actual database details.
 The query SELECT * FROM student LIMIT 10 retrieves the top 10 records
from the student table.
 The retrieved data is displayed in an HTML table with columns for name,
branch, and roll number.

Feel free to adapt this script to your specific use case! 😊

References:

1. GeeksforGeeks: How to retrieve data from MySQL database using PHP


2. TutsMake: How to Fetch and Display Data From Database in PHP in Table
3. Stack Overflow: Retrieve the top 10 from the database

3. Write a PHP program to display all the records of ”employee ” database from
the personal table #assume table has 10 records with following fields eid,
name ,address, pin , phone , email .
Certainly! To display all the records from the “employee” database table, you can
follow these steps using PHP and MySQL:

1. Create a MySQL Database Connection in PHP: First, create a file named


db.php and include the following code to establish a connection with your
MySQL database. Replace the placeholders ($host, $username, $password,
and $dbname) with your actual database credentials:
2. <?php
3. $host = 'localhost';
4. $username = 'root';
5. $password = '';
6. $dbname = 'my_db'; // Replace with your actual database name
7.
8. $conn = mysqli_connect($host, $username, $password, $dbname);
9. if (!$conn) {
10. die('Could not connect to MySQL server: ' . mysqli_error());
11.}
12.?>
13.Fetch Data from the Database and Display in an HTML Table: Next, create
a new PHP file (e.g., display_records.php) and use the following code to
retrieve data from the “employee” table and display it in an HTML table:
14.<!DOCTYPE html>
15.<html lang="en">
16.<head>
17. <meta charset="utf-8">
18. <meta name="viewport" content="width=device-width, initial-scale=1,
shrink-to-fit=no">
19. <title>Employee Records</title>
20. <!-- Include Bootstrap CSS -->
21. <link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.
min.css">
22.</head>
23.<body>
24. <div class="container mt-4">
25. <h2>Employee Records</h2>
26. <table class="table table-bordered">
27. <thead>
28. <tr>
29. <th>EID</th>
30. <th>Name</th>
31. <th>Address</th>
32. <th>Pin</th>
33. <th>Phone</th>
34. <th>Email</th>
35. </tr>
36. </thead>
37. <tbody>
38. <?php
39. // Fetch data from the "employee" table
40. $query = "SELECT * FROM employee";
41. $result = mysqli_query($conn, $query);
42.
43. while ($row = mysqli_fetch_assoc($result)) {
44. echo "<tr>";
45. echo "<td>{$row['eid']}</td>";
46. echo "<td>{$row['name']}</td>";
47. echo "<td>{$row['address']}</td>";
48. echo "<td>{$row['pin']}</td>";
49. echo "<td>{$row['phone']}</td>";
50. echo "<td>{$row['email']}</td>";
51. echo "</tr>";
52. }
53. ?>
54. </tbody>
55. </table>
56. </div>
57. <!-- Include Bootstrap JS -->
58. <script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></
script>
59. <script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min
.js"></script>
60.</body>
61.</html>
62.Access the Displayed Records: Save the above code in a file (e.g.,
display_records.php) and place it in your web server’s directory. Access the
file through your browser (e.g., http://localhost/display_records.php) to
see the employee records displayed in a table.

Remember to adjust the database credentials and table name according to your
actual setup. If you need additional features (such as search or pagination), you

can enhance the code further. 😊

For more details, you can refer to the following resources:

 How to Fetch and Display Data From Database in PHP in Table


 Employee Record Management System in PHP and MySQL12
 Simple Employee Records System using PHP with Source Code 3
 How to Search Employee data from Database using PHP4
 Display Data in an HTML Table Using PHP & MySQL5

Feel free to explore these resources for more insights! 🚀

4. What do you mean by Asynchronous API?

An asynchronous API is an application programming interface that allows you to


send multiple queries concurrently and intelligently manage the connections
between services without waiting for an immediate response. Let’s delve into the
details:

1. Synchronous APIs vs. Asynchronous APIs:


o Synchronous APIs typically use HTTP or HTTPS for transport. In this
case, the client sends a request to the server, and the server
responds with an HTTP or HTTPS message. It’s a unidirectional
communication.
o Asynchronous APIs, on the other hand, tend to use bidirectional
protocols like HTTP/2. With bidirectional communication, the client
and server can maintain their connection, sending and receiving data
as needed. Imagine it as follows: synchronous requests pull data
from a server, while asynchronous requests ask the server to push
the latest data to the client.
o When you make a synchronous request, your application waits until
it receives the response. In contrast, an asynchronous request allows
your application to continue processing other instructions while
waiting for the API server’s response.
o If a resource, service, or datastore isn’t immediately available when
you make the request, an asynchronous API can use a callback (such
as a webhook) to notify your application when the resource becomes
ready1.
2. Use Cases for Asynchronous APIs:
o Microservices: Asynchronous API requests are well-suited for
microservices architecture. When you configure your application’s
internal and external services to communicate asynchronously, they
can send messages to each other without needing to be available
simultaneously. Message brokers often handle these requests.
Instead of polling for new information, services can subscribe to
relevant events and receive push updates.
o Event-Driven Architecture: Event-driven communication relies on
the publish-subscribe pattern between services. Event producers
share events with services, allowing them to react to specific events
without waiting for synchronous responses1.
o Chat Applications: An example of an asynchronous API is a chat
application, where messages can be sent and received without
blocking the user interface2.

In summary, asynchronous APIs provide flexibility, scalability, and efficient


communication between services, making them valuable in various scenarios.
Remember, though, that not all API architectures fit neatly into the synchronous

or asynchronous labels, as some APIs may exhibit hybrid behavior 1. 🚀

5. Why use Node.js?


Certainly! Node.js is a powerful and versatile JavaScript runtime environment that
has gained immense popularity in recent years. Here are some compelling
reasons why you might want to use Node.js:

1. JavaScript Everywhere: Node.js allows you to run JavaScript code outside


of a web browser. This means you can use the same language for both
client-side and server-side development. If you’re already familiar with
JavaScript, transitioning to Node.js will be relatively smooth 1.
2. High Performance and Scalability: Node.js is built on Chrome’s V8 engine,
which makes it highly performant. Its event-driven, non-blocking I/O model
allows for efficient handling of concurrent connections. This makes it ideal
for building real-time applications, APIs, and microservices 1.
3. Rich Ecosystem: Node.js has a vibrant ecosystem with a plethora of
libraries and frameworks. For instance, you can use Express.js for building
web applications, Socket.io for real-time communication, and Mongoose
for working with MongoDB. These tools make development faster and
more efficient2.
4. Fast Execution: Node.js leverages Google’s innovative technologies and the
event loop to execute code quickly. It’s particularly well-suited for
applications that require high-speed data processing or real-time
interactions1.
5. Native JSON Support: Node.js allows you to work with data in native JSON
(object notation) format. This is especially useful when dealing with
databases or APIs that use JSON as their data interchange format 1.

In summary, Node.js provides a seamless way to build scalable, efficient, and real-
time applications using JavaScript. Whether you’re a beginner developer or an

experienced coder, it’s definitely worth exploring! 😊1324

6. Explain callback in Node.js.

Certainly! In Node.js, a callback is a fundamental concept used for handling


asynchronous operations. Let me break it down for you:

1. What is a Callback?
o A callback is a function that is passed as an argument to another
function. It gets executed after a specific task or operation
completes.
o Callbacks are essential for handling asynchronous tasks like file
reading, database operations, or API requests in Node.js.
2. Why Use Callbacks?
o Node.js is designed to be non-blocking and efficient. It allows
multiple tasks to run concurrently without waiting for each other to
finish.
o Callbacks enable this asynchronous behavior by allowing code
execution to continue while tasks run in the background.
o When a task completes, the associated callback function is invoked.
3. Example: Reading a File
o Suppose you want to read a file in Node.js. You can do it
synchronously (blocking) or asynchronously (non-blocking).
o Synchronous (Blocking) Code:
o const fs = require("fs");
o const fileData = fs.readFileSync("inputfile1.txt");
o console.log(fileData.toString());
o console.log("End of Program execution");
 In this example, readFileSync reads the file synchronously,
blocking program execution until completion.
o Asynchronous (Non-blocking) Code:
o const fs = require("fs");
o fs.readFile("inputfile1.txt", (err, fileData) => {
o if (err) return console.error(err);
o console.log(fileData.toString());
o });
o console.log("End of Program execution");
 Here, readFile reads the file asynchronously. The callback
function executes when the file read operation finishes.
4. Summary:
o Callbacks allow Node.js to handle multiple tasks efficiently without
waiting for each operation to conclude.
o They are crucial for managing asynchronous behavior and enabling
non-blocking I/O operations.

For more details, you can refer to the following resources:


 Node Callback Concept - GeeksforGeeks
 Understanding the Callback Pattern in Node.js: A Comprehensive Guide -
Medium
 What is a callback function in Node? - GeeksforGeeks
 Node.js - Callbacks Concept - Online Tutorials Library
 How Callbacks Work in Node.js - freeCodeCamp.org12345

7. How does an Angular application work?

Angular, one of the most popular and widely used frameworks, provides a ton of
built-in features straight out of the box. Let’s dive into how an Angular application
works behind the scenes:

1. Entry Point:
o When you create an Angular application using the command ng new
appName, Angular looks for the entry point. The entry point is
defined in the angular.json file under the main property. Typically, it
points to main.ts.
o The main.ts file creates a browser environment and loads the main
module using
platformBrowserDynamic().bootstrapModule(AppModule). The
default module loaded is AppModule, but you can change it to any
other module1.
2. App Module (AppModule):
o The AppModule (usually defined in app.module.ts) contains all the
declarations of components, services, and other modules required by
the application.
o The bootstrap property of AppModule references the component
used to bootstrap the application. For example, if AppComponent is
the component used for bootstrapping, it will be specified in the
bootstrap property1.
3. Component Initialization:
o Angular looks into the AppComponent and initializes it. The
app.component.ts file contains the AppComponent.
o Every component has three key properties:
 selector: Used for accessing the component.
 template or templateUrl: Contains the view (HTML) of the
component.
1
 style or styleUrls: Contains styles for the view .
4. Component Lifecycle:
o Once initialized, the component goes through its lifecycle hooks, such
as ngOnInit, ngOnChanges, and ngAfterViewInit.
o These hooks allow you to perform actions at specific points during
the component’s lifecycle.
5. Rendering and Change Detection:
o Angular’s change detection mechanism keeps track of changes to
data and updates the view accordingly.
o When data changes (due to user interaction or other factors),
Angular re-renders the affected parts of the view.
6. Dependency Injection (DI):
o Angular uses DI to manage dependencies between components,
services, and other parts of the application.
o Services are injected into components, allowing them to share data
and functionality.
7. Routing and Lazy Loading:
o Angular provides a powerful routing system for navigating between
different views.
o Lazy loading allows you to load specific parts of your application only
when needed, improving performance.
8. Real DOM vs. Virtual DOM:
o Angular uses a virtual DOM (VDOM) to optimize rendering. Changes
are first applied to the VDOM, and then the real DOM is updated only
where necessary.

In summary, Angular combines declarative templates, dependency injection, and


a powerful component-based architecture to create robust single-page
applications. It’s a full-fledged framework that provides clear guidance on
structuring your application and managing its behavior234. If you’re interested in
diving deeper, you can explore the official Angular documentation or other

resources15. 🚀
8. What is AOT compilation? What are the advantages of AOT?

Ahead-of-Time (AOT) compilation is a process used in Angular applications to


convert Angular HTML and TypeScript code into efficient JavaScript code during
the build phase. Here are the key advantages of using AOT compilation:

1. Faster Rendering:
o With AOT, the browser downloads a pre-compiled version of the
application. This means that the browser can immediately render the
application without waiting for runtime compilation.
o In contrast, Just-in-Time (JIT) compilation, which compiles the
application in the browser at runtime, can introduce a delay before
rendering.
2. Fewer Asynchronous Requests:
o The AOT compiler inlines external HTML templates and CSS style
sheets directly into the application JavaScript. As a result, there are
no separate AJAX requests for these source files.
o This reduction in AJAX requests leads to faster loading times and a
more responsive user experience.
3. Smaller Angular Framework Download Size:
o When an application is already compiled using AOT, there’s no need
to download the Angular compiler separately. The Angular compiler
itself constitutes a significant portion of the framework.
o By omitting the compiler download, the overall application payload
size is dramatically reduced.
4. Early Detection of Template Errors:
o The AOT compiler detects and reports template binding errors during
the build step, before users encounter them in the browser.
o This early error detection helps developers identify and fix issues
before deploying the application.
5. Enhanced Security:
o AOT compiles HTML templates and components into JavaScript files
during the build process, long before they are served to the client.
o Since there are no client-side HTML or JavaScript evaluations, the risk
of injection attacks is minimized.
In summary, AOT compilation improves performance, reduces bundle size,
enhances security, and provides better error handling compared to JIT
compilation123. If you’re working with Angular, leveraging AOT can lead to a more

efficient and secure application. 🚀

9. What is the Box model in CSS? Which CSS properties are a part of it?

Explore

The CSS box model is a fundamental concept in web design and layout. It
describes how HTML elements are modeled in browser engines and how their
dimensions are derived from CSS properties1. Let’s break down the different parts
of the box model:

1. Content: This is where the actual text and images appear within the
element.
2. Padding: The padding clears an area around the content. It provides space
between the content and the border.
3. Border: The border surrounds the padding and content. It can be styled
with different colors, widths, and styles.
4. Margin: The margin clears an area outside the border. It defines the space
between elements.

Here’s a visual representation of the box model:

!Box Model

When setting the width and height properties of an element, it’s essential to
understand how the box model works. Keep in mind that when you set the width
and height, you’re specifying the dimensions of the content area. To calculate the
total width and height of an element, you must also consider the padding and
borders.

For example, suppose we have the following CSS rules:

div {
width: 320px;
height: 50px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}

The calculation for the total width would be:

 Content width: 320px


 Left padding + right padding: 20px (10px + 10px)
 Left border + right border: 10px (5px + 5px)

Total width = 320px (content width) + 20px (padding) + 10px (border) = 350px

Similarly, the total height calculation would be:

 Content height: 50px


 Top padding + bottom padding: 20px (10px + 10px)
 Top border + bottom border: 10px (5px + 5px)
Total height = 50px (content height) + 20px (padding) + 10px (border) = 80px

Remember that the margin property affects the total space the box occupies on
the page, but it’s not included in the actual size of the box. The box’s total width
and height stop at the border.

In summary, the CSS box model allows us to control the dimensions and spacing
of elements, making it a crucial concept for web designers and developers 2. If
you’d like to practice, try setting the width of a <div> element to 200px in the
exercise below:

<style>
div {
/* Set the width to 200px */
width: 200px;
}
</style>
<body>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.</div>
</body>

Feel free to experiment and explore the box model further! 😊📦🎨

10. What are the different types of Selectors in CSS?

Certainly! CSS selectors allow you to target specific HTML elements for styling.
Let’s explore the different types of CSS selectors:

1. Element Selector: This selects HTML elements based on their name. For
example:
2. p {
3. text-align: center;
4. color: red;
5. }
In this example, all <p> elements on the page will be center-aligned with
red text1.

6. ID Selector: It uses the id attribute of an HTML element to select a specific


element. IDs are unique within a page. For instance:
7. #para1 {
8. text-align: center;
9. color: red;
10.}

This rule applies to the HTML element with id="para1"1.

11.Class Selector: Selects elements with a specific class attribute. You can use
it like this:
12..center {
13. text-align: center;
14. color: red;
15.}

All HTML elements with class="center" will be red and center-aligned1. You
can also specify that only specific elements should be affected by a class,
like so:

p.center {
text-align: center;
color: red;
}

In this case, only <p> elements with class="center" will be styled1.

16.Universal Selector: The * selects all HTML elements on the page:


17.* {
18. text-align: center;
19. color: blue;
20.}

This rule affects every HTML element1.


21.Group Selector: You can group selectors to minimize code repetition. For
example:
22.h1, h2, p {
23. text-align: center;
24. color: red;
25.}

Here, the same style definitions apply to <h1>, <h2>, and <p> elements1.

26.Attribute Selector: Selects elements based on an attribute or attribute


value. For instance:
27.a[href^="https://"] {
28. /* Styles for links starting with "https://" */
29.}

This targets links with href attributes starting with "https://"2.

Remember that CSS selectors play a crucial role in styling web pages, allowing you

to create visually appealing designs! 😊🎨

You might also like