Professional Documents
Culture Documents
Ait Imp
Ait Imp
// 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>
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:
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>
.main {
text-align: center;
}
.GFG {
font-size: 60px;
color: green;
}
#geeks {
font-size: 25px;
color: skyblue;
}
<!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>
.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:
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. }
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.}
<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>
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:
// Send a response
res.end('<html><body><h1>Hello, this is a simple Node.js web
server!</h1></body></html>');
});
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.
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
8. Program to show current date and time using user defined modules in
node.JS
// myfirstmodule.js
exports.myDateTime = function () {
return Date();
};
node main.js
This will display the current date and time. Feel free to adjust the code according
to your needs!
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>
Now, when users click the links, they’ll navigate to the corresponding
components. The URL will update accordingly.
In your component:
@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
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).
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.
<?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";
In this example:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
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
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";
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: " . $conn->connect_error;
exit();
}
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:
References:
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:
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
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
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.
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.
resources15. 🚀
8. What is AOT compilation? What are the advantages of AOT?
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
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.
!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.
div {
width: 320px;
height: 50px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}
Total width = 320px (content width) + 20px (padding) + 10px (border) = 350px
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! 😊📦🎨
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.
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;
}
Here, the same style definitions apply to <h1>, <h2>, and <p> elements1.
Remember that CSS selectors play a crucial role in styling web pages, allowing you