0% found this document useful (0 votes)
25 views136 pages

Full Stack

The document is a comprehensive guide for aspiring full stack developers, detailing the training and development process at W3 Engineers Ltd. It covers various topics including web architecture, programming languages, cloud infrastructure, and office etiquette, while emphasizing the company's core values and mission. Additionally, it outlines the internship program and the expectations for interns in terms of productivity, coding practices, and organizational norms.

Uploaded by

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

Full Stack

The document is a comprehensive guide for aspiring full stack developers, detailing the training and development process at W3 Engineers Ltd. It covers various topics including web architecture, programming languages, cloud infrastructure, and office etiquette, while emphasizing the company's core values and mission. Additionally, it outlines the internship program and the expectations for interns in terms of productivity, coding practices, and organizational norms.

Uploaded by

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

9/2/2021 Full stack

Developer Guide
Guidelines to become a full stack
developer

Prepared By
W3 ENGINEERS LTD
Contents
......................................................................................................................................................... 0
Introduction .................................................................................................................................... 4
About W3 .................................................................................................................................... 4
Product and Services .................................................................................................................. 4
Our Products ........................................................................................................................... 4
Our Services............................................................................................................................. 5
Our Values................................................................................................................................... 5
Core Values .............................................................................................................................. 6
Success Stories ......................................................................................................................... 6
Our Team ................................................................................................................................. 7
Work Culture ........................................................................................................................... 7
Training and Development of Intern: ............................................................................................. 8
About Office etiquette, Organization, and office norms ............................................................ 8
Programmers ............................................................................................................................. 10
Mistakes .................................................................................................................................... 10
Productivity ............................................................................................................................... 10
Coding........................................................................................................................................ 11
Web Architecture .......................................................................................................................... 13
The diagram............................................................................................................................... 14
How WWW [Web Addresses] Translates .................................................................................. 15
Monoliths .................................................................................................................................. 15
Overview ................................................................................................................................ 15
Benefits .................................................................................................................................. 16
Drawbacks ............................................................................................................................. 16
Microservices ............................................................................................................................ 17
Overview ................................................................................................................................ 17
Benefits .................................................................................................................................. 17
Drawbacks ............................................................................................................................. 18
Conclusion ............................................................................................................................. 19
Micro frontends ........................................................................................................................ 19
Quick Summary...................................................................................................................... 19
What is Micro-frontend Architecture? .................................................................................. 20
Benefits .................................................................................................................................. 20
Drawbacks ............................................................................................................................. 20
How it works? ........................................................................................................................ 21
Programming languages ............................................................................................................... 21
Frontends .................................................................................................................................. 21
HTML & CSS for responsive web ........................................................................................... 21
HTML5 Basic overview .............................................................................................................. 21
CSS3 Basic overview ............................................................................................................... 23
JavaScript core ....................................................................................................................... 45
NodeJs.................................................................................................................................... 57
Reactive framework............................................................................................................... 69
Backends ................................................................................................................................... 79
RDBMS & No SQL ................................................................................................................... 79
Python.................................................................................................................................... 85
Generative AI and LLM ........................................................................................................ 110
Golang .................................................................................................................................. 110
Cloud Infrastructure.................................................................................................................... 125
Deployment tools and techniques .......................................................................................... 125
Cloud Infrastructure ................................................................................................................ 125
Amazon Web Service (AWS).................................................................................................... 125
EC2 ....................................................................................................................................... 125
VPC ....................................................................................................................................... 126
S3 ......................................................................................................................................... 126
CloudFront ........................................................................................................................... 126
RDS ....................................................................................................................................... 127
NoSQL .................................................................................................................................. 127
Route53 ............................................................................................................................... 128
SQS ....................................................................................................................................... 128
Elastic Beanstalk .................................................................................................................. 128
Elasticsearch ........................................................................................................................ 129
Lambda ................................................................................................................................ 129
CloudFormation ................................................................................................................... 130
Linux (OS) ................................................................................................................................ 130
Docker ..................................................................................................................................... 131
Docker Compose .................................................................................................................. 132
GIT ........................................................................................................................................... 133
IDE ........................................................................................................................................... 134
Automation Tools .................................................................................................................... 134
Introduction

About W3
W3 Engineers Ltd is a fast-paced IT solutions provider that specializes in delivering innovative
solutions and strategies that drive business growth.
Established in 2009, W3 Engineers Ltd has been providing top-tier custom software development,
innovative software products, and cost-effective technical services.
With over a decade of experience in providing technology services, quality software products,
and offshore team management to clients worldwide, we have established a reputation for
excellence in the industry.

Product and Services


Our Products
Our Services

Our Values

Our team thrives on a set of core values that guide us in everything we do. Honesty, integrity,
health and well-being, personal growth, and social responsibility are at the forefront of our
mission. We embrace creativity, innovation, empathy, and compassion in all our actions. And
never forget to appreciate the opportunities and blessings we've been given. Together, these
values allow us to positively impact our community and prioritize the well-being of our families
while continuously growing and learning from our actions and mistakes.

Vision: We strive for technological breakthroughs which will impact human life positively, that's
our vision.

Mission: To cultivate customer relations by providing the best services and solutions at the most
affordable costs.
Core Values

Success Stories
Our Team

Work Culture

About Internship Program


We offer a great internship with the opportunity to get a full-time job upon completion.

Training and Development of Intern


Initial Designation: Intern Software Engineer
Duration of Internship: 6 Month (Evaluation of every month end)
After successful completion of the internship program, the designation will be Junior Software
Engineer with all the full-time employment benefits of W3 Engineers Ltd. (HR Policy)
4-Month Internship Program Overview
 Training under Senior Software Engineers
o A training schedule and trainer names will be provided.
o Training topics will be followed by assignments.
 Assignment-based Learning
o Assignments will cover training topics.
o Evaluation will be based on completed assignments.
 Feedback and Evaluations
o Monthly evaluations will assess both technical and behavioral aspects.
o Feedback will be collected on training and trainers.
 Project Assignments
o Interns will be assigned projects to apply learned skills.
 Learning and Development
o Continuous learning on new topics covered in sessions is required.
o Senior engineers will suggest areas for individual improvement and career paths.
About Office etiquette, Organization, and office norms
1. Appear at the office by 10:00 AM and conclude work by 7:00 PM.
2. Attend the daily scrum meeting at 10:10 AM
3. Submit your work targets before the scrum and provide a status update before 7:00
PM.
4. Verify that you recorded at least 160 hours (about 6 and a half days) in Jira each
month (from the 21st to the 20th of the monthly cycle).
5. Ensure that WorkAny is operational throughout the day.
6. Log your working hours in Jira before leaving the office.
7. Maintain a professional environment and relationships within the office.
Confidential topics such as personal details, salary, appraisals, and relevant subjects
shouldn’t be discussed with colleagues.
8. Do not use personal email/ or any kind of ID for any correspondence within the
office.
9. Refrain from using your office email address/ID for personal activities.
10. Avoid sending code from the office to personal email or storage, and refrain from
uploading it to any private or public repository. This is considered an offense and
may result in legal action.
11. The use of personal pen drives or hard drives is strictly prohibited in the office.
12. GitHub and Google services (except Google Search) are blocked on the office
network. Please avoid attempting to use them with third-party VPNs. If necessary for
work, submit a request for approval for a designated period.
13. Access to office sites outside the office network is restricted. If it is necessary to use
them (i.e.: emergency fix, home office, etc.), please submit a request to obtain VPN
credentials for the specific duration needed.
14. Don't use any pirated software, cracked activations, untrusted browser plugins, etc.
Instead, opt for open-source alternatives with a good reputation and no security
vulnerabilities.
15. Don’t forget to say Hi/Greetings to everyone. This gentle act will keep you in touch
with everybody
16. Be polite to your coworkers. You don’t have to be aggressive to be a talented
person. There is a famous saying that a tree full of fruits always bows down.
17. Wear smart casual attire regularly. You should look clean and smell good to maintain
a good working environment.
18. Smile. It reduces stress and raises the comfort zone among your teammates.
19. For any approval requests or inquiries, please contact your team lead/supervisor.
20. Please adhere to the following practices consistently

Others Office Policy (HR Policy)

 If you need to leave the office premises, kindly notify your supervisor and the HR
department. Ensure to obtain the final confirmation of departure from the HR
department before leaving, as no employee can exit the office without securing this
confirmation.
 All leave requests (Emergency leaves/Planned leaves) should be submitted to the team
lead. Planned leave should be requested at least 7 days earlier to the date of leave and
for emergency leave, employees are bound to notify it before 10:00 AM (on that day).
 Neglecting to communicate your absence on a given day will be considered an "Absent"
status, irrespective of the availability of paid leave entitlements.
 Throughout the internship/probation period, both interns and probation period
employees will not have access to paid leave benefits.
 If you experience an emergency resulting in a late arrival or early departure, please
promptly inform your Lead, PM, and HR to facilitate necessary coordination.
 We have designated lunch break (2:00 PM to 3:00 PM). Our schedule does not include
extended breaks. For prayer sessions and snacks, employees have the flexibility to take
short breaks (Max 15 mins) as needed.
Programmers
"[Programmers] like to think we spend most of our time power typing. “Yeah, I’m being
productive, I’m writing programs!” But we don’t. We spend most of our time looking into the
abyss, saying “My God, what have I done? How am I ever going to make this work?” Once we
figure it out, we forget that we did all of that … A normal person, once they’ve looked into the
abyss, would say I’m done, this is stupid, I’m going to do something else. But not us, because
there’s something wrong with us.” - Douglas Crockford

Mistakes
 Spell mistakes
 Naming things incorrectly
 Incorrect file names. E.g., OS dependent
 Over abstraction. E.g. Over thinking of product
 Messy inheritance. E.g. Vehicle / boat, airplane
 Syntax error. E.g. Not testing or overlook
 Permissions error. E.g. test, development or production mess up
 Memory Hungry Loop. E.g. large datasets?
 Incorrect operators. E.g. >/>=?, &/and?, brackets
 Self-doubt

Productivity
 Hot keys, even in browsers
 Multiple screen/Large Screen
 Proper development environment
 Real time notes and to-do app. E.g. Wunderlist, Evernote/OneNote
 Refactor code. E.g. Think to make it more efficient
 Read/Follow open-source codes
 Automate as much as possible
 Read books
 Re-useable codes, don’t re-invent the wheel rather learn to use

Coding
Prevention is better than the cure!

o My code my responsibility
o For every professional there are some basic rules. E.g.
o Doctor wear aprons
o Accountants have a calculator
o Chefs wears toque
o Easy to understand + Easy to change
o Write codes that expresses
o Don’t overload names or concepts. E.g.
o Same things on multiple names/functions.
o Redundant layers
o No meaningful names
o Careful yourself with dependencies. E.g.
o Singular direction.
o Update will be complex if not.
o Organization forever! E.g.
o Unusable file not to keep
o Redundant directory structure or files should avoid
o Learn and modify to improve
o Commenting
o Don’t make it to tell lies
o Don’t use unless it requires
o But don’t miss it
o Boy Scout rules
o Leave the code to a better way than you found
o Single work principle
o One function do one thing. E.g.
o If we have more argument onto a function possibly it can do multiple things.
o So, it can hard to debug or verify
o Tests
o Integration test
o Unit test
o Development Strategy
o Work in short cycle
o Incremental and Iterative
Web Architecture
The diagram
How WWW [Web Addresses] Translates

Monoliths
Overview
Monolith means composed all in one piece. The Monolithic application describes a single-
tiered software application in which different components combined into a single program
from a single platform. Components can be:
- Authorization
- Presentation
- Business Logic
- Database Layer
- Integrations
Figure: Monolithic Architecture (for E-Commerce Application)
Benefits
 Simple to develop — At the beginning of a project it is much easier to go with
Monolithic Architecture.
 Simple to test. For example, you can implement end-to-end testing by simply launching
the application and testing the UI with Selenium.
 Simple to deploy. You have to copy the packaged application to a server.
 Simple to scale horizontally by running multiple copies behind a load balancer.
Drawbacks
 Maintenance — If Application is too large and complex to understand entirely, it is
challenging to make changes fast and correctly.
 The size of the application can slow down the start-up time.
 You must redeploy the entire application on each update.
 Monolithic applications can also be challenging to scale when different modules have
conflicting resource requirements.
 Reliability — Bug in any module (e.g. memory leak) can potentially bring down the
entire process. Moreover, since all instances of the application are identical, that bug
impact the availability of the entire application
 Regardless of how easy the initial stages may seem; Monolithic applications have
difficulty to adopting new and advance technologies. Since changes in languages or
frameworks affect an entire application, it requires efforts to thoroughly work with the
app details, hence it is costly considering both time and efforts.
Microservices
Overview
Microservices are an approach to application development in which a large application is built
as a suite of modular services (i.e. loosely coupled modules/components). Each module
supports a specific business goal and uses a simple, well-defined interface to communicate with
other sets of services.
Instead of sharing a single database as in Monolithic application, each microservice has its own
database. Having a database per service is essential if you want to benefit from microservices,
because it ensures loose coupling. Each of the services has its own database. Moreover, a
service can use a type of database that is best suited to its needs.

Figure: Microservices Architecture (for E-Commerce Application)


Benefits
 Microservices Enables the continuous delivery and deployment of large, complex
applications.
 Better testability — services are smaller and faster to test.
 Better deployability — services can be deployed independently.
 It enables you to organize the development effort around multiple teams. Each team is
responsible for one or more single service. Each team can develop, deploy and scale
their services independently of all of the other teams.
 Each microservice is relatively small
 Comfortable for a developer to understand
 The IDE is faster making developers more productive
 The application starts faster, which makes developers more productive, and speeds up
deployments
 Improved fault isolation. For example, if there is a memory leak in one service then only
that service is affected. The other services continue to handle requests. In comparison,
one misbehaving component of a monolithic architecture can bring down the entire
system.
 Microservices Eliminates any long-term commitment to a technology stack. When
developing a new service you can pick a new technology stack. Similarly, when making
major changes to an existing service you can rewrite it using a new technology stack.
Drawbacks
 Developers must deal with the additional complexity of creating a distributed system.

 Developers must implement the inter-service communication mechanism.


 Implementing use cases that span multiple services without using distributed
transactions is difficult.
 Deployment complexity. In production, there is also the operational complexity of
deploying and managing a system comprised of many different service types.
 Increased memory consumption. The microservice architecture replaces N monolithic
application instances with NxM services instances. If each service runs in its Container,
which is usually necessary to isolate the instances, then there is the overhead of M
times as many Containers.
Conclusion

Micro frontends
Quick Summary
The micro-frontend architecture has slowly but gradually gained popularity and has now
become one of the most sought-after frontend development strategies. Developers appreciate
the agility and freedom that comes along with this architecture and organizational stability it
imparts is making life easier for CTOs worldwide. With multiple implementation strategies and
tons of advantages, the micro-frontend architecture seems set to revolutionize frontend
development and scaling.
What is Micro-frontend Architecture?
Micro-frontend architecture is a strategy in which the traditionally monolithic frontend
codebase is split into smaller apps, ideally addressing the various business domains. All these
smaller elements form a seamless frontend interface that delivers top-notch user experience
and is easy to modify and scale.

Benefits
- Design and development flexibility
- Decoupled codebases
- Automation
- Fault isolation
- Scalability
- Faster build time
- Simpler maintenance
- Independent Deployment
- Autonomous team
- Reusability
Drawbacks
- Operational complexities
- Inconsistent user experience
- Poor communication between components
- Larger payloads
How it works?

Programming languages
Frontends

HTML & CSS for responsive web

HTML5 Basic overview

HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and
XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web.
HTML5 is a cooperation between the World Wide Web Consortium (W3C) and the Web Hypertext
Application Technology Working Group (WHATWG).
The new standard incorporates features like video playback and drag-and-drop that have been
previously dependent on third-party browser plug-ins such as Adobe Flash, Microsoft Silverlight,
and Google Gears.
HTML5 Tags

The following section contains a complete list of standard tags belonging to the latest HTML5 and
XHTML 1.1 specifications. All the tags are listed alphabetically.
Ref: https://www.tutorialrepublic.com/html-reference/html5-tags.php

CSS3 Basic overview

CSS (Cascading Style Sheets) consist of a group of formatting rules that you use to control the
layout and appearance of the content on a web page. One really great feature of CSS is that you
can store all the CSS rules in one document and keep that document separate from the HTML
content and link the two together. Then, when you make a change to the CSS that change is
instantly and automatically updated on all the HTML files. Another great feature is that it
“cleans up” the appearance of the code on web pages. In addition, it will speed up browser
loading times.
What CSS gives you is incredible control over the appearance of your page. You can control
properties such as font sizes, bolding, italics, text shadows and color, link color and much more.
And of course, you can go far beyond that with page layout tools, boxes, formatting,
positioning, etc. In CSS3, there are many options, a few which we’ll look at here. These include
animation, gradients, media queries, shadows, transitions, the font-face rule that allows you to
embed fonts on a web page, and more.

What You Can Do with CSS


There are lot more things you can do with CSS.

 You can easily apply same style rules on multiple elements.


 You can control the presentation of multiple pages of a website with a single style sheet.
 You can present the same page differently on different devices.
 You can style dynamic states of elements such as hover, focus, etc. that isn't possible
otherwise.
 You can change the position of an element on a web page without changing the markup.
 You can alter the display of existing HTML elements.
 You can transform elements like scale, rotate, skew, etc. in 2D or 3D space.
 You can create animations and transitions effects without using any JavaScript.
 You can create print friendly version of your web pages.
Advantages of Using CSS
The biggest advantage of CSS is that it allows the separation of style and layout from the
content of the document. Here are some more advantages, why one should start using CSS?

 CSS Save Lots of Time — CSS gives lots of flexibility to set the style properties of an
element. You can write CSS once; and then the same code can be applied to the groups
of HTML elements, and can also be reused in multiple HTML pages.
 Easy Maintenance — CSS provides an easy means to update the formatting of the
documents, and to maintain the consistency across multiple documents. Because the
content of the entire set of web pages can be easily controlled using one or more style
sheets.
 Pages Load Faster — CSS enables multiple pages to share the formatting information,
which reduces complexity and repetition in the structural contents of the documents. It
significantly reduces the file transfer size, which results in a faster page loading.
 Superior Styles to HTML — CSS has much wider presentation capabilities than HTML
and provide much better control over the layout of your web pages. So you can give far
better look to your web pages in comparison to the HTML presentational elements and
attributes.
 Multiple Device Compatibility — CSS also allows web pages to be optimized for more
than one type of device or media. Using CSS the same HTML document can be
presented in different viewing styles for different rendering devices such as desktop, cell
phones, etc.

Ref : https://www.tutorialrepublic.com/css-tutorial/css-get-started.php

What Is A CSS Preprocessor (row CSS, SASS and Stylus)?

What is a CSS Preprocessor?


CSS Preprocessors are tools that extend the functionality of vanilla CSS by adding a wide variety
of logical syntax such as you might see in a normal programming language. Preprocessors take
code written with this new and versatile syntax, and then compile it into traditional CSS that
the browser can work with. The 3 most well-known CSS preprocessors are SASS (or SCSS) LESS
and Stylus. For the purposes of this blog I’ll be only be providing examples of code written in
SASS.
What is Sass?
 Sass stands for Syntactically Awesome Stylesheet
 Sass is an extension to CSS
 Sass is a CSS pre-processor
 Sass is completely compatible with all versions of CSS
 Sass reduces repetition of CSS and therefore saves time
 Sass was designed by Hampton Catlin and developed by Natalie Weizenbaum in 2006
 Sass is free to download and use

What is Stylus?
Stylus is a dynamic stylesheet preprocessor language that is compiled into Cascading Style
Sheets (CSS). Its design is influenced by Sass and LESS. It's regarded as the fourth most used CSS
preprocessor syntax. It was created by TJ Holowaychuk, a former programmer for Node

CSS in itself is devoid of complex logic and functionality which is required to write reusable and
organized code. As a result, a developer is bound by limitations and would face extreme
difficulty in code maintenance and scalability, especially when working on large projects
involving extensive code and multiple CSS stylesheets. This is where CSS Preprocessors come to
the rescue.
A CSS Preprocessor is a tool used to extend the basic functionality of default vanilla CSS through
its own scripting language. It helps us to use complex logical syntax like – variables, functions,
mixins, code nesting, and inheritance to name a few, supercharging your vanilla CSS. By using
CSS Preprocessors, you can seamlessly automate menial tasks, build reusable code snippets,
avoid code repetition and bloating and write nested code blocks that are well organized and
easy to read.
However, browsers can only understand native vanilla CSS code and will be unable to interpret
the CSS Preprocessor syntax. Therefore, the complex and advanced Preprocessor syntax needs
to be first compiled into native CSS syntax which can then be interpreted by the browsers to
avoid cross browser compatibility issues. While different Preprocessors have their own unique
syntaxes, eventually all of them are compiled to the same native CSS code.
Moving forward in the article, we will take a look at the 3 most popular CSS Preprocessors
currently being used by developers around the world i.e Sass, LESS, and Stylus.

Syntax Declaration: Sass vs SCSS

Sass SYNTAX SCSS SYNTAX

 

COMPILED CSS
In both cases, be it Sass or SCSS, the compiled CSS code will be the same –
Syntax Declaration: Stylus
Uses .styl extension. Stylus offers a great deal of flexibility in writing syntax, supports native CSS
as well as allows omission of brackets colons and semicolons. Also, note that Stylus does not
use @ or $ symbols for defining variables. Instead, Stylus uses the assignment operators to
indicate a variable declaration.
Stylus

COMPILED CSS

I
More Information:
SASS docs: http://sass-lang.com/
Stylus docs: http://stylus-lang.com/
CSS Flexbox: A Complete Guide

This guide explains everything about flexbox, focusing on different properties for the flex
container (the parent element) and the flex items (the child elements). It includes various
examples and lifehacks.

CSS flexbox (Flexible Box Layout Module) is a layout module that consists of the flex container
(the parent element) and the flex items (the children elements). The flex items can be
organized as a row or as a column, and the available free space can be distributed between
them in various ways.
With the help of flexbox, you can:
 Automatically scale elements (alter height or width) so that they fill the available space
 Automatically shrink or grow elements to make them fit into the container and prevent
overflow

 Change the order of the items

 Solve the problem of horizontal and vertical centering

 Create columns of the same height

 Create a footer sticking to the bottom of the page

 Design navigation panels

 And more

Flexbox elements can have many properties some of which are set on the flex container and
the others are set on the flex items.
Properties that apply to the flex container:
 align-content
 align-items

 display

 flex-direction

 flex-flow

 flex-wrap

 justify-content

Properties that apply to the flex items:


 align-self
 flex

 flex-basis

 flex-grow

 flex-shrink

 order
How to Create the Flex Container
The display: flex; property applies to the container, makes the container a block element,
and enables the flex layout for all its direct children.

The display: inline-flex; works in the same way. Only it creates a container as an inline
element.
How to Create a Row or Column

If you want to arrange the flex items to look like a row or a column, apply the flex-
direction property to the container.
The flex-direction: row; property will make a horizontal row. The row is the default
value.

If you have more items that can fit in one row and you still want a horizontal layout, the flex-
wrap: wrap; property will come in handy. This way, the flex items will wrap onto multiple
lines inside the flex container. The default value is flex-wrap: nowrap;.
To make a vertical column, apply the flex-direction: column; to the container.
How to Align Elements Horizontally
To define the horizontal alignment of items, use the justify-content property. It may have
one of the following values:
 flex-start: items are packed toward the container’s left side (it’s the default value)
 flex-end: items are packed toward the container’s right side

 center: items are placed in the center

 space-between: items are evenly distributed in the line (the first item is on the left, the
last item on the right)

 space-around: items are evenly distributed in the line with equal space on both sides of
the items. Note that visually the spaces aren’t equal since all the items have equal space
on both sides. The margins of adjacent flex items do not collapse. The first item will
have one unit of space against the container edge, but two units of space between the
next item because that next item has its own spacing that applies

 space-evenly: items are distributed so that the spacing between any two items (and the
space to the edges) is equal
How to Align Elements Vertically
To align flex items vertically, use the align-items, align-content or align-self
properties.
Align-items
To define the vertical alignment of several items, apply the align-items property to the
container. This property may have one of the following values:
 stretch: items are stretched to fill the container, still respecting min-width and max-
width properties (it’s the default value)
 flex-start: items are placed in the top part of the container

 flex-end: items are placed in the bottom part of the container

 center: items are centered in the middle of the container

 baseline: items are aligned such as their baselines align


Align-content
To define the vertical alignment of several lines of items, use the align-content property.
This property has no effect when there is only one line of flex items.
This property only works if two conditions are met:
 The wrap value should be applied to the flex container
 The flex container should be higher than the lines of the flex items

In other words, there must be additional vertical space inside the container, which should be
larger than the sum of all the heights of the rows of elements.
This property may have one of the following values:
 stretch: lines stretch to take up all the available space in the container (it’s the default
value)
 flex-start: lines are placed in the top part of the container

 flex-end: lines are placed in the bottom part of the container

 center: lines are centered in the middle of the container

 space-between: lines are evenly distributed in the container

 space-around: lines are evenly distributed with equal space around each line
Align-self
To vertically align individual items, use the align-self property. It applies to the flex items,
not to the flex container. It is useful to override the alignment specified for the flex container
with the help of the align-items property.
The align-self property may have one of the following values (the same ones as in the case
of the align-items property plus auto):
 auto: equals to the value specified in the align-items property for the flex container
(it’s the default value)
 stretch: items are stretched to fill the container, still respecting min-width and max-
width properties

 flex-start: items are placed in the top part of the container

 flex-end: items are placed in the bottom part of the container

 center: items are centered in the middle of the container

 baseline: items are aligned such as their baselines align

How to Change the Order of the Elements


Several properties allow determining the order of the flex items: order, row-reverse,
column-reverse, wrap-reverse.
Order
To customize the order of individual flex items, use the order property. It applies to the flex
items.
By default, all flex items have the order: 0; value. If you specify the value -1 for an element,
it moves toward the start of the line, and the value 1 places it in the end. If multiple flex items
have the same order value, they will be displayed according to the original order.

The default order:

To make the last item first:

To change the order of individual items:


Row-reverse, column-reverse
You can reverse the item order. To arrange flex items in a row right to left, apply the flex-
direction: row-reverse; property to the flex container.

To arrange flex items in a column bottom to top, use the flex-direction: column-
reverse; property.
Instead of flex-direction, you can choose the shorter flex-flow property to apply those
values:

Wrap-reverse
There is also the flex-wrap: wrap-reverse; property that allows wrapping flex items onto
multiple lines from bottom to top.
How to Make the Elements Grow or Shrink
The flexibility of flex items is determined by the flex-basis, flex-grow, and flex-shrink
properties.
Flex-basis
The flex-basis property defines the default size of the flex item before the available space is
distributed. You can set an absolute value (e. g. 200px or 10em), a percentage value (e. g. 50%)
or a keyword (auto, content).

The flex-basis property can be interpreted as the minimum width of the flex item. If you
specify a flex-basis value, it will set the width for the specific item, but depending on other
flex parameters the flex item may become wider (or narrower) than the flex-basis value.
The default value is auto. It retrieves the value of the width property. And the content value is
based on the flex item’s content.
If you do not set a flex-basis value and set the flex-grow value to 0, the element will be
compressed to its minimum size.

Flex-grow
The flex-grow property applies to individual flex items and defines the ability of a flex item to
grow. It dictates what amount of the available space inside the flex container the item should
take up. It accepts a unitless value that serves as a proportion. The default value is 0. Negative
numbers are invalid.
If all items have flex-grow set to 1, the remaining space in the container will be distributed
equally to all children. If the flex-grow value of an item is set to 2, it will get 2 times more pixels
to the original width than other items with the flex-grow value 1.
Flex-shrink
 The flex-shrink property applies to the flex items and indicates how much each
element will be reduced if there is not enough available space. It accepts a unitless value
that serves as a proportion. The default value is 1. The value 0 allows keeping the item’s
original size. Negative numbers are invalid.

Overview of responsive design and media queries

Responsive Web Design - Introduction


Responsive web design makes your web page look good on all devices. Responsive web design uses only HTML
and CSS. Responsive web design is not a program or a JavaScript.

The idea of responsive design is that the product can adapt itself to any reading device the user may use. It’s
more or less like transforming the content into water, mimicking the liquid’s ability to fill any type of glass. This
shows that the old way of creating websites, using fixed positions, is all but dead and buried.

What is CSS Responsive Design?

Web pages can be viewed using many different devices. Your web page should look good and needs to be
interactive, regardless of the device. When you use CSS to resize, hide, shrink and enlarge content to make it look
better, it is called CSS Responsive Design. CSS Responsive Design responds to the needs of the users and the
devices they are using. The layout changes based on the size and capabilities of the device. CSS Responsive Design
ensure that web pages don't leave out information to fit smaller devices, but rather adapt its content to fit any
device such as Desktop, Tablet or Phone.

// Small devices (landscape phones, 576px and up)@media (min-width: 576px) {


... }// Medium devices (tablets, 768px and up)@media (min-width: 768px) { ...
}// Large devices (desktops, 992px and up)@media (min-width: 992px) { ... }//
X-Large devices (large desktops, 1200px and up)@media (min-width: 1200px) {
... }// XX-Large devices (larger desktops, 1400px and up)@media (min-width:
1400px) { ... }

Single breakpoint
@media (min-width: 768px) and (max-width: 991.98px) { ... }

Max-width
// X-Small devices (portrait phones, less than 576px)
@media (max-width: 575.98px) { ... }
// Small devices (landscape phones, less than 768px)
@media (max-width: 767.98px) { ... }
// Medium devices (tablets, less than 992px)
@media (max-width: 991.98px) { ... }
// Large devices (desktops, less than 1200px)
@media (max-width: 1199.98px) { ... }
// X-Large devices (large desktops, less than 1400px)
@media (max-width: 1399.98px) { ... }
JavaScript core

Introduction
JavaScript is the world's most popular programming language.
JavaScript is the mother language of the Web.
JavaScript is easy to learn.
JavaScript is one of the 3 languages all web developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages

JavaScript plays with HTML.


In HTML, JavaScript code is inserted between <script> and </script> tags.
An external script can be referenced in 3 different ways:
 With a full URL (a full web address)
 With a file path (like /js/)
 Without any path
JavaScript can "display" data in different ways:
 Writing into an HTML element, using innerHTML.
 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().
JS Versions
JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
ECMAScript is the official name of the language.
ECMAScript versions have been abbreviated to ES1, ES2, ES3, ES5, and ES6.
Since 2016 new versions are named by year (ECMAScript 2016 / 2017 / 2018).
 The Original JavaScript ES1 ES2 ES3 (1997-1999)
 The First Main Revision ES5 (2009)
 The Second Revision ES6 (2015)
 Yearly Additions (2016, 2017, 2018)
ECMAScript 2015 was the second major revision to JavaScript.
ECMAScript 2015 is also known as ES6 and ECMAScript 6.
JS Object
In JavaScript, almost "everything" is an object.
• Booleans can be objects (if defined with the new keyword)
• Numbers can be objects (if defined with the new keyword)
• Strings can be objects (if defined with the new keyword)
• Dates are always objects
• Maths are always objects
• Regular expressions are always objects
• Arrays are always objects
• Functions are always objects
• Objects are always objects
All JavaScript values, except primitives, are objects.
You can use the typeof operator to find the data type of a JavaScript variable.

A JavaScript object is a collection of named values.

Objects written as name value pairs are similar to:

 Associative arrays in PHP


 Dictionaries in Python
 Hash tables in C
 Hash maps in Java
 Hashes in Ruby and Perl
JavaScript is an object-oriented prototype language.

JS Functions
JavaScript functions are defined with the function keyword.

You can use a function declaration or a function expression.

Self-Invoking Functions
For function parameters:
 Arguments are Passed by Value
 Objects are Passed by Reference

In JavaScript you can define functions as object methods.

In this case the value of this is myObject.


JS Callback
A callback is a function passed as an argument to another function.

JS HTML DOM
With the HTML DOM, JavaScript can access and change all the elements of an HTML document.
The HTML DOM model is constructed as a tree of Objects:
With the object model, JavaScript gets all the power it needs to create dynamic HTML:

 JavaScript can change all the HTML elements in the page


 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page
Example

JS Browser BOM
The window object is supported by all browsers. It represents the browser's window.
All global JavaScript objects, functions, and variables automatically become members of the
window object.
Global variables are properties of the window object.
Global functions are methods of the window object.
Even the document object (of the HTML DOM) is a property of the window object:
window.document.getElementById("header");
is the same as:
document.getElementById("header");
Promise
A Promise in JavaScript is an object that represents the eventual completion (or failure) of an
asynchronous operation and its resulting value. A Promise has three main states:
1. Pending: Initial state, neither fulfilled nor rejected.
2. Fulfilled: Operation completed successfully, resulting in a resolved value.
3. Rejected: Operation failed, resulting in a reason for the failure.

Example with Explanation

Here’s an example of a simple Promise:

let fetchData = new Promise((resolve, reject) => {


// Simulate an asynchronous operation with setTimeout
setTimeout(() => {
const success = true; // change this to false to simulate
rejection

if (success) {
resolve("Data fetched successfully!"); // fulfills the promise
} else {
reject("Failed to fetch data."); // rejects the promise
}
}, 1000);
});

// Handling the promise


fetchData
.then(result => {
console.log(result); // runs if promise is fulfilled
})
.catch(error => {
console.error(error); // runs if promise is rejected
});

Explanation of Each Part

1. Creating a Promise:

let fetchData = new Promise((resolve, reject) => { ... });

The new Promise constructor takes a function with two parameters: resolve (for
success) and reject (for failure).

2. Resolving the Promise:

resolve("Data fetched successfully!");

When the operation is successful, we call resolve(), passing the result. This
moves the promise to the fulfilled state.
3. Rejecting the Promise:

reject("Failed to fetch data.");

If the operation fails, reject() is called with an error message, moving the
promise to the rejected state.

4. Handling the Promise:


• .then(result => { ... }): Called if the promise is fulfilled, receiving the result.
• .catch(error => { ... }): Called if the promise is rejected, receiving the error.

In this example, if success is true, the promise is resolved, and "Data fetched successfully!" is
logged. If success is false, the promise is rejected, and "Failed to fetch data." is logged as an
error.
JS Ajax
AJAX (Asynchronous JavaScript and XML) is a developer's dream, because you can:

 Read data from a web server - after the page has loaded
 Update a web page without reloading the page
 Send data to a web server - in the background
Fetch
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' +
response.statusText);
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There has been a problem with your fetch
operation:', error);
});
Explanation
1. fetch('https://api.example.com/data'): Initiates a request to the given URL. fetch
returns a Promise that resolves to the Response object representing the response to the
request.
2. then(response => { ... }): Processes the response. Here:
• We check if the response status is “ok” (i.e., status code is 200–299).
• If it’s not, we throw an error with response.statusText for debugging.
• If the response is ok, we call response.json() to parse the JSON data.
3. then(data => { ... }): The parsed JSON data is now accessible. Here, we simply log
it with console.log(data).
4. catch(error => { ... }): Catches any error during the fetch process or response
handling. If there’s a network error or if the fetch promise rejects, we log an error message.

JSON
JSON stands for JavaScript Object Notation
JSON is a text format for storing and transporting data
JSON is "self-describing" and easy to understand

It defines an object with 3 properties:

 name
 age
 car
Each property has a value.
Use the JavaScript function JSON.parse() to convert text into a JavaScript object:

Is similar to
Use the JavaScript function JSON.stringify() to convert it into a string.

JSON string must use double quote always.


Browser Storage
Cookies are data, stored in small text files, on your computer.
When a web server has sent a web page to a browser, the connection is shut down, and the
server forgets everything about the user.
Cookies were invented to solve the problem "how to remember information about the user":

 When a user visits a web page, his/her name can be stored in a cookie.
 Next time the user visits the page, the cookie "remembers" his/her name.
More storages are localStorage, sessionStorage.
We can set cookie expiry but localStorage does not have any expiry.
sessionStorage gets cleared when browser closed.
localStorage and sessionStorage did not pass to header on page visits like cookie.
Among them only cookie can be read/written both from frontend JS and backend.
JS Library
jQuery was created in 2006 by John Resig. It was designed to handle Browser Incompatibilities
and to simplify HTML DOM Manipulation, Event Handling, Animations, and Ajax.
For more than 10 years, jQuery has been the most popular JavaScript library in the world.
However, after JavaScript Version 5 (2009), most of the jQuery utilities can be solved with a few
lines of standard JavaScript.
Web API
When JavaScript runs in browser it can't do any OS operation except window.print() method
which open printer window of the OS.
All browsers have a set of built-in Web APIs to support complex operations, and to help
accessing data.
For example, the Geolocation API can return the coordinates of where the browser is located.
JS Class
ECMAScript 2015, also known as ES6, introduced JavaScript Classes.
JavaScript Classes are templates for JavaScript Objects.
If you want to give support for old browsers before 2015 then you have to write all of your
JavaScript code using version ES5.
NodeJs

Introduction
Node.js is an open-source server environment.
Node.js allows you to run JavaScript on the server.
Node.js uses asynchronous programming!
Node.js can generate dynamic page content.
Node.js can create, open, read, write, delete, and close files on the server.
Node.js can collect form data.
Node.js can add, delete, modify data in your database.
Node.js can be used as a Backend system with help of its HTTP package.
Unlike browser JavaScript when program in Node.js try using Latest LTS version of Node and
latest stable version of libraries and you can use latest JS version code without any doubt.

Getting Started
Create your app.js file and add following content.
Node Library
For Node.js npm and yarn are the two most popular package manager.
It creates a package.json in the project directory when install any library like below
npm install express
Node MVC framework
Express JS is a Fast, unopinionated, minimalist web framework for node.
npm install -g express-generator
Install package.json and Run Project
npm install
node app.js or npm start
Install a new plugin and save in package.json
npm install –save express-validator
Install a library globally and Restart project on change
npm install -g nodemon
nodemon
Template Language
https://pugjs.org/api/getting-started.html
https://expressjs.com/en/resources/template-engines.html
Routing
https://expressjs.com/en/guide/routing.html
Node Modules
Use the exports keyword to make properties and methods available outside the
module file.

Frontend development by Node


Now a days Node.js also powers frontend development. Many popular reactive frameworks use
Node.js libraries by import like Node.js and finally compiles it to vanilla JavaScript.
ExpressJS and Unit Test

Step 1: Set Up the Express.js API

1. Initialize a new Node.js project:

mkdir simple-api
cd simple-api
npm init -y

2. Install necessary packages:

npm install express


npm install --save-dev jest supertest

3. Create a simple Express API:


• Create a file named app.js for the main application code.

const express = require('express');


const app = express();
app.use(express.json());

// Define a simple route


app.get('/hello', (req, res) => {
res.status(200).json({ message: 'Hello, World!'
});
});

// Define another route with a parameter


app.get('/greet/:name', (req, res) => {
const name = req.params.name;
res.status(200).json({ message: `Hello, ${name}!`
});
});

// Export the app for testing


module.exports = app;

4. Create the server entry point:


• In index.js, we add the code to listen to the server.

const app = require('./app');


const PORT = 3000;

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

Step 2: Write Unit Tests


1. Create a test file:
• In the root directory, create a __tests__ folder, and inside it, add a file
named app.test.js.

const request = require('supertest');


const app = require('../app');

describe('GET /hello', () => {


it('should respond with "Hello, World!"', async () => {
const response = await request(app).get('/hello');
expect(response.status).toBe(200);
expect(response.body.message).toBe('Hello, World!');
});
});

describe('GET /greet/:name', () => {


it('should respond with a personalized greeting', async
() => {
const name = 'Alice';
const response = await
request(app).get(`/greet/${name}`);
expect(response.status).toBe(200);
expect(response.body.message).toBe(`Hello,
${name}!`);
});
});
Step 3: Run the Tests

1. Update package.json:
• Add a test script to package.json to run Jest.

"scripts": {
"start": "node index.js",
"test": "jest"
}

2. Run the tests:

npm run test

Explanation

1. Express API:
• app.get('/hello'): This route responds with "Hello, World!".
• app.get('/greet/:name'): This route responds with "Hello, <name>!" using
the name provided in the URL.
2. Unit Testing:
• supertest: Used to simulate HTTP requests and test responses.
• describe and it blocks: Jest functions to organize tests. Each it block
represents a single test.
• expect: Checks that the response matches our expectations, such as the
status code and message content.
TypeScript
Key Concepts in TypeScript for Beginners

1. Type Annotations
• TypeScript allows specifying types for variables, function parameters, and
return values, enabling type-checking during development.
• Example:

let username: string = "John";


let age: number = 30;
let isLoggedIn: boolean = true;

2. Interfaces
• Interfaces define the structure of an object, ensuring that objects meet
specific criteria.
• Example:

interface User {
name: string;
age: number;
isAdmin?: boolean; // optional property
}

const user: User = { name: "Alice", age: 25 };

3. Functions and Typing


• Functions in TypeScript allow specifying parameter and return types.
• Example:

function greet(name: string): string {


return `Hello, ${name}`;
}

let greeting = greet("John");

4. Classes and Inheritance


• TypeScript supports object-oriented programming with classes and
inheritance.
• Example:

class Animal {
name: string;

constructor(hello_name: string) {
this.name = hello_name;
}

makeSound(): void {
console.log("Sound...");
}
}

class Dog extends Animal {


makeSound(): void {
console.log("Woof! Woof!");
}
}

const dog = new Dog("Buddy");


dog.makeSound(); // Output: Woof! Woof!

5. Enums
• Enums allow defining a set of named constants, making code more
readable.
• Example:

enum Direction {
Up,
Down,
Left,
Right
}

let move: Direction = Direction.Up;

6. Generics
• Generics enable defining reusable components with variable types.
• Example:
function identity<T>(value: T): T {
return value;
}

let num = identity<number>(5); // returns 5


let str = identity<string>("Hello"); // returns
"Hello"

TypeScript Code Example

Here’s a simple “Hello World” application in TypeScript using Express.

Step 1: Project Setup

1. Initialize the project

mkdir hello-world-app
cd hello-world-app
npm init -y

2. Install dependencies

npm install express


npm install --save-dev typescript @types/node @types/express
ts-node nodemon
3. Initialize TypeScript

npx tsc --init

4. Add start scripts to package.json

"scripts": {
"start": "node dist/index.js",
"build": "tsc",
"dev": "nodemon src/index.ts"
}

Step 2: Create the Code

1. Create the folder structure and main file


• Create a src/ folder.
• Inside src/, create a file called index.ts.
2. Add Hello World Code
src/index.ts

import express, { Request, Response } from 'express';


const app = express();
const PORT = 3000;

app.get('/', (req: Request, res: Response) => {


res.send('Hello, World!');
});

app.listen(PORT, () => {
console.log(`Server is running at
http://localhost:${PORT}`);
});

Step 3: Run the Application

1. Run in Development Mode

npm run dev

2. Test the App


Open a browser or use curl to visit http://localhost:3000 You should see:

Hello, World!
Reactive framework
Core concept
Reactive frameworks, such as Next.js, enable developers to build web applications with virtual
DOM support, streamlining real-time data updates. They offer structured frameworks,
supported by extensive open-source communities.
Few Popular Frameworks
 React
 Vue.js
 Angular

React is the most popular reactive framework due to its flexibility, speed, and vast ecosystem. It
leverages a virtual DOM for optimal performance and enables developers to build dynamic,
data-driven applications without manual DOM manipulation. With its strong open-source
community, React provides constant improvements and support.
Next.js is the best framework for using React to its fullest. It extends React’s capabilities by
adding features like server-side rendering (SSR), static site generation (SSG), and optimized
routing, making it ideal for production-grade applications.
Why React and Next.js Are the Best Combination
React: A powerful library for building responsive, interactive UIs with reusable components and
a vibrant ecosystem.
Next.js: Built on React, it takes the development experience further with support for SSR, API
routes, and automatic code splitting, making your application faster and more SEO-friendly.

Next.js Basics

 Introduction and environment setup


To start a Next.js project, follow these commands:

npx create-next-app my-next-app


cd my-next-app
npm run dev

For more details on setup, visit: Next.js documentation


 Next.js Overview

Next.js is a React-based framework designed to create high-performance, production-


ready web applications. It combines the best of React with powerful features for
rendering, routing, and API handling, enabling developers to create fast and SEO-
optimized applications.

Basic Structure of a Next.js Component

import React from 'react';

function MyComponent() {

return (

<div>

<h1>Hello, Next.js with React!</h1>

</div>

);

export default MyComponent;

For more information:

o https://nextjs.org/learn
o Next.js with TypeScript Tutorial
o https://nextjs.org/docs/pages/api-reference/config/typescript
 Components, Props, and State in Next.js

With Next.js, you leverage React components to build interactive UIs. Components can
be functional or class-based, accepting props for data passing.

Example of a Functional Component with Props

function Greeting({ name }) {


return <h1>Hello, {name}!</h1>;
}

State Management with Hooks


In Next.js, managing component state is essential for interactive applications. React’s
useState hook allows you to add state to your functional components, and it works
seamlessly within Next.js.
import React, { useState } from 'react';

function Counter() {
// Initialize a state variable 'count' with initial value
of 0
const [count, setCount] = useState(0);

return (
<div>
<p>Count: {count}</p>
{/* Update state when the button is clicked */}
<button onClick={() => setCount(count +
1)}>Increment</button>
</div>
);
}

export default Counter;


TSX in Next.js
TSX is used to describe what the UI should look like in Next.js, combining HTML-like
syntax with JavaScript for more intuitive component structure.

Example:
const element = <h1>Hello, {name}</h1>;

Next.js Advanced Concepts


 Built-in TypeScript Support
Next.js has native support for TypeScript. When you create a TypeScript file (.tsx), it
automatically configures the environment to work with TypeScript, streamlining setup
and making it easier to manage types across your app.
 Environment Variables
Next.js allows for secure environment variable management by providing a .env file
support. This makes it simple to add sensitive or environment-specific values (e.g., API
keys, database URLs) to your app without exposing them in the client code.
NEXT_PUBLIC_API_URL=https://api.example.com
 Optimized Bundling and Caching
Next.js automatically optimizes code bundling, eliminating unused code and leveraging
caching strategies to ensure users get fast responses and updates when they’re needed.
With tools like Webpack and Vercel’s infrastructure, Next.js applications can perform
better with little extra effort.
 Internationalization (i18n)
Next.js includes built-in support for internationalization, allowing developers to serve
content in multiple languages and locales without extra setup. It manages locale
detection and routing, making it easier to support global audiences.
 Image Optimization
Next.js offers automatic image optimization, helping improve load times and
performance by serving images in modern formats (like WebP) and at the appropriate
resolutions. This feature is handled by the next/image component and includes lazy
loading, resizing, and more.

import Image from 'next/image';

function HomePage() {
return <Image src="/path/to/image.jpg" alt="Description"
width={500} height={500} />;
}

 Next.js Routing
In Next.js 13 and above, routing has been divided into two main concepts: App Router
and Pages Router. Here’s a breakdown:

1. App Router (New in Next.js 13)

• Directory: Uses a new app directory for defining routes.

• File-based Routing: Each folder in the app directory becomes a route, and
special files within those folders define components for that route.

• Routing Example:

• app/about/page.js → accessible at /about.

• app/products/[id]/page.js → dynamic route accessible at /products/123.

• Features:
• Server Components: By default, components are rendered on the server,
improving SEO and performance.

• Layouts: You can define layout components (layout.js files) that are shared
across different routes.

• Colocation: You can keep styles, components, and assets within the route folder,
making the structure modular.

• API Routes: API routes are typically handled in a separate api folder within the
app directory.

Next.js enables API routes for building backend services within the same app, allowing
easy handling of server-side logic.

Example of an API route:


// app/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: 'Hello, Next.js!' });
}

Details: https://nextjs.org/docs/pages/building-your-application/routing/api-routes

2. Pages Router (Previous Approach)

• Directory: Uses the pages directory for defining routes.

• File-based Routing: Each .js or .jsx file in the pages directory becomes a route.

• Routing Example:

• pages/about.js → accessible at /about.

• pages/products/[id].js → dynamic route accessible at /products/123.

• Features:
• Client-Side Routing: Ideal for Single Page Applications (SPAs) where client-side
interactivity is high.

• No Built-in Layouts: For layouts, you have to use getLayout functions or


manually wrap components, as there’s no built-in support like in the App Router.

Which to Use?

• App Router: For modular, server-rendered apps with layouts and better SEO.
• Pages Router: For simpler, client-rendered applications and legacy projects.
Details: https://nextjs.org/docs/pages/building-your-application/routing
Unit Test and Coverage
Here’s a TypeScript-based guide for setting up unit tests with coverage in a Next.js project using
Jest and React Testing Library.

 Step 1: Set Up Jest and Testing Library

1. Install Dependencies:

npm install --save-dev jest @testing-library/react @testing-


library/jest-dom @testing-library/user-event jest-environment-
jsdom ts-jest @types/jest

2. Add Jest Configuration:


In the project root, create a jest.config.ts file:

// jest.config.ts
import nextJest from 'next/jest';
const createJestConfig = nextJest({ dir: './' });

const customJestConfig = {
testEnvironment: 'jest-environment-jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/$1', // Alias support
},
transform: {
'^.+\\.tsx?$': 'ts-jest', // Use ts-jest for TypeScript files
},
collectCoverage: true,
collectCoverageFrom: ['components/**/*.tsx'],
coverageReporters: ['json', 'lcov', 'text', 'clover'],
};

export default createJestConfig(customJestConfig);

3. Set Up Jest for Next.js:


Create a jest.setup.ts file:

// jest.setup.ts
import '@testing-library/jest-dom/extend-expect';

4. Update package.json for Jest:


In package.json, add scripts:

"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage"
}

Step 2: Create a TypeScript Component and Write a Unit Test

1. Example Component:
Create a simple TypeScript component, Button.tsx:

// components/Button.tsx
import React from 'react';

interface ButtonProps {
onClick: () => void;
label: string;
}

const Button: React.FC<ButtonProps> = ({ onClick, label }) => {


return (
<button onClick={onClick}>
{label}
</button>
);
};

export default Button;

2. Write a Test for the Component:


Create a test file for Button.tsx under a __tests__ folder:

// components/__tests__/Button.test.tsx
import { render, screen, fireEvent } from '@testing-library/react';
import Button from '../Button';

describe('Button Component', () => {


it('renders the button with the label', () => {
render(<Button label="Click Me" onClick={() => {}} />);
expect(screen.getByText('Click Me')).toBeInTheDocument();
});

it('calls onClick when clicked', () => {


const handleClick = jest.fn();
render(<Button label="Click Me" onClick={handleClick} />);
fireEvent.click(screen.getByText('Click Me'));
expect(handleClick).toHaveBeenCalledTimes(1);
});
});
Step 3: Run the Tests

Run the tests with the following command:

npm test

This will execute your tests, and you should see the results in the terminal.

Step 4: Set Up Code Coverage

1. Run Coverage Report:


Run the following command to generate a coverage report:

npm run test:coverage

2. View Coverage Report:


You’ll see a summary in the terminal. Additionally, an HTML report is created in the coverage
folder; open coverage/lcov-report/index.html in your browser for a detailed report.
Frameworks and UI Libraries for Next.js
o Next.js UI: https://nextui.org/docs/frameworks/nextjs Next.js UI: Offering a
beautiful and adaptable system design for an enhanced user experience.
https://nextui.org/docs/frameworks/nextjs
o Material-UI: Implements Material Design in React.
o Chakra UI: Customizable, accessible React components.
o Tailwind CSS: A utility-first CSS framework for seamless styling.
o React Bootstrap: Bootstrap components built specifically for React.
o Gatsby: A React-based static site generator for performance-oriented
applications.
Combining React with Next.js offers a powerful approach to building dynamic, scalable, and
SEO-friendly applications. With Next.js as a foundation, you can make the most of React’s
flexibility and create robust applications with advanced performance optimizations and
backend integrations.

Backends

OpenAPI (Swagger)
OpenAPI (Swagger) specification with explanations for a sample REST API:

Sample API: Hotel Booking API

Purpose: Manage hotel bookings, rooms, and customers.

openapi: 3.0.3
info:
title: Hotel Booking API
description: An API for managing hotel bookings, rooms, and
customers.
version: 1.0.0
servers:
- url: https://api.hotelbooking.com/v1
description: Production server
- url: https://sandbox.hotelbooking.com/v1
description: Sandbox server for testing
tags:
- name: Bookings
description: Operations related to hotel bookings
- name: Rooms
description: Operations related to rooms management
- name: Customers
description: Customer operations
paths:
/bookings:
get:
summary: Get all bookings
description: Returns a list of all bookings with details.
tags:
- Bookings
parameters:
- name: startDate
in: query
description: Filter bookings from this start date.
required: false
schema:
type: string
format: date
- name: endDate
in: query
description: Filter bookings up to this end date.
required: false
schema:
type: string
format: date
responses:
'200':
description: List of bookings retrieved successfully.
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Booking'
'400':
description: Invalid query parameters.
'500':
description: Server error.
post:
summary: Create a new booking
description: Adds a new booking for a customer.
tags:
- Bookings
requestBody:
description: Booking details to be created.
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/NewBooking'
responses:
'201':
description: Booking created successfully.
content:
application/json:
schema:
$ref: '#/components/schemas/Booking'
'400':
description: Invalid input data.
'500':
description: Server error.

components:
schemas:
Booking:
type: object
properties:
id:
type: string
format: uuid
description: Unique identifier for the booking.
customerId:
type: string
format: uuid
description: Customer ID associated with the booking.
roomId:
type: string
format: uuid
description: Room ID for the booking.
checkInDate:
type: string
format: date
description: Check-in date for the booking.
checkOutDate:
type: string
format: date
description: Check-out date for the booking.
NewBooking:
type: object
properties:
customerId:
type: string
format: uuid
description: Customer ID associated with the booking.
roomId:
type: string
format: uuid
description: Room ID to book.
checkInDate:
type: string
format: date
description: Check-in date.
checkOutDate:
type: string
format: date
description: Check-out date.

responses:
NotFound:
description: Resource not found.
content:
application/json:
schema:
type: object
properties:
message:
type: string
example: Resource not found.

Key Elements:

1. openapi: Specifies the OpenAPI version being used (3.0.3 in this case).
2. info: Metadata about the API, including title, description, and version.
3. servers: Lists the available servers where the API is hosted (production and
sandbox).
4. tags: Categories for grouping endpoints.
5. paths: Defines each endpoint (/bookings here), including:
• HTTP methods (get, post).
• summary and description: Brief and detailed explanations of the operation.
• parameters: Input parameters such as query, path, or headers.
• requestBody: Data sent to the API (for POST or PUT requests).
• responses: Defines possible responses with status codes.
6. components: Contains reusable schemas and response definitions:
• schemas: Define the structure of objects (e.g., Booking, NewBooking).
• responses: Common responses, e.g., “NotFound.”

Reference:
https://swagger.io/

RDBMS & No SQL


RDBMS: Relational databases accessed with SQL (Structured Query Language) were developed
in the 1970s with a focus on reducing data duplication as storage was much more costly than
developer time.
o MySQL/MariaDB
o PostgreSQL
o Oracle
o MSSQL
All of above databases are available as a scalable service called AWS RDS
NOSQL: NoSQL (“non-SQL” or “not only SQL”) databases were developed in the late 2000s with
a focus on scaling, fast queries, allowing for frequent application changes, and making
programming simpler for developers. One of the most frequently cited drawbacks of NoSQL
databases is that they don’t support ACID (atomicity, consistency, isolation, durability)
transactions across multiple documents. To address these use cases MongoDB added support
for multi-document ACID transactions in the 4.0 release and extended them in 4.2 to span
sharded clusters.
21. MongoDB
22. AWS DynamoDB
23. SOLR
24. Elasticsearch/OpenSearch
25. Aerospike
Elasticsearch is also available in AWS as a service. Kibana is a developer guy for Elasticsearch.
Every popular programming language like PHP, Python, Go, Node.js and many frameworks have
database driver for these SQL and NOSQL databases.
It is recommended to install your local databases using docker.
Example: https://hub.docker.com/_/mongo
Python

Python Core
Basics
How to Install Python IDE
Step-1) To download and install Python, visit the official website of Python
https://www.python.org/downloads/ and choose your version
Step 2) Once the download is completed, run the .exe file to install Python. Now click on Install
Now.
What is a Variable in Python?
A Python variable is a reserved memory location to store values. In other words, a variable in a
python program gives data to the computer for processing
Python Variable Types
Every value in Python has a datatype. Different data types in Python are Numbers, List, Tuple,
Strings, Dictionary, etc. Variables in Python can be declared by any name or even alphabets like
a, aa, abc, etc.
How to Declare and use a Variable
a = 100
print(a)
Re-declare a Variable
f=0
print f
f = 'guru99'
print f
Python String Concatenation and Variable
a="Guru"
b = 99
print(a+str(b))
Python Variable Types: Local & Global

There are two types of variables in Python, Global variable and Local variable. When
you want to use the same variable for rest of your program or module you declare it
as a global variable, while if you want to use the variable in a specific function or
method, you use a local variable while Python variable declaration.
# Declare a variable and initialize it
f = 101
print f
# Global vs. local variables in functions
def someFunction():
# global f
f = 'I am learning Python'
print f
someFunction()
print f
Data Structure
Lists
Lists are very similar to arrays. They can contain any type of variable, and they can contain as
many variables as you wish. Example
mylist = []
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist[0]) # prints 1
print(mylist[1]) # prints 2
print(mylist[2]) # prints 3

# prints out 1,2,3


for x in mylist:
print(x)

Dictionary
A Dictionary in Python is the unordered and changeable collection of data values that
holds key-value pairs
Dict = {'Tim Cook': 18,'Charlie':12,'Tiffany':22,'Robert':25} print (Dict['Tiffany'])
Updating Dictionary
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Dict.update({"Sarah":9})
Delete Keys from the dictionary
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
del Dict ['Charlie']
Tuples
Tuples are used to store multiple items in a single variable.
A tuple is a collection which is ordered and unchangeable
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Conditional Loops
Conditions
Python uses boolean logic to evaluate conditions. The boolean values True and False are
returned when an expression is compared or evaluated. For example:
x=2
print(x == 2) # prints out True
print(x == 3) # prints out False
print(x < 3) # prints out True

The "and" and "or" boolean operators allow building complex boolean expressions, for
example:
name = "John"
age = 23
if name == "John" and age == 23:
print("Your name is John, and you are also 23 years old.")

if name == "John" or name == "Rick":


print("Your name is either John or Rick.")

The "in" operator could be used to check if a specified object exists within an iterable object
container, such as a list:
name = "John"
if name in ["John", "Rick"]:
print("Your name is either John or Rick.")

Loops
There are two types of loops in Python, for and while.
For loops iterate over a given sequence. Here is an example:
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
While loops repeat as long as a certain boolean condition is met. For example:
count = 0
while count < 5:
print(count)
count += 1
break is used to exit a for loop or a while loop, whereas continue is used to skip the current
block, and return to the "for" or "while" statement. A few examples:
for (i=0; i<10; i+=2)
for x in range(10, 2)
Functions
Functions are a convenient way to divide your code into useful blocks, allowing us to order our
code, make it more readable, reuse it and save some time. Also functions are a key way to
define interfaces so programmers can share their code.
Functions in python are defined using the block keyword "def", followed with the function's
name as the block's name. For example:
def my_function(name: string) -> tuple:
return "Hello From My Function!"+str(1)

Functions may also receive arguments (variables passed from the caller to the function). For
example:
def my_function_with_args(username, greeting):
print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))

Functions may return a value to the caller, using the keyword- 'return'. For example:
def sum_two_numbers(a, b=5):
return a + b
sum_two_numbers(1, 5)
How do you call functions in Python?
def my_function():
print("Hello From My Function!")
my_function()
def hello_world(a, *tuple, **dict):
hello_world(a=“name”, 1, 2, 4, name=”alex”, roll=19):
tuple=(1, 2, 4) dict={“name”: “alex”, “roll”=19}
File Handling
In Python, there is no need for importing external library to read and write files. Python
provides an inbuilt function for creating, writing, and reading files.
How to Create a Text File in Python
Step 1) Open the .txt file
f= open("guru99.txt","w+")
Step 2) Enter data into the file
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
Step 3) Close the file instance
f.close()

How to Read Files in Python

You can read a file in Python by calling .txt file in a “read mode”(r).
Step 1) Open the file in Read mode
f=open("guru99.txt", "r")

Step 2) We use the mode function in the code to check that the file is in open mode. If yes, we
proceed ahead
if f.mode == 'r':
Step 3) Use f.read to read file data and store it in variable content for reading files in Python
contents =f.read()
with open(“file.txt”, “r”) as f:
f.readlines()
here..
Classes and Objects
Objects are an encapsulation of variables and functions into a single entity. Objects get their
variables and functions from classes. Classes are essentially a template to create your objects.
A very basic class would look something like this:
class MyClass:
“””
variable = "blah"

def function(self):
print("This is a message inside the class.")
“””
To access the variable inside of the newly created object "myobjectx" you would do the
following:
class MyClass:

variable = "blah"

def __int__(self, text):


self.variable=text

def function(self):
print("This is a message inside the class.")

myobjectx = MyClass(“hello”)
myobjectx.variable

To access a function inside of an object you use notation similar to accessing a variable:
myobjectx.function()
Modules
Modules in Python are simply Python files with a .py extension. The name of the module will be
the name of the file. A Python module can have a set of functions, classes or variables defined
and implemented. In the example above, we will have two files, we will have:
draw/
draw /game.py
draw /draw_a_game.py
draw /__init__.py

from game import Game


game = Game()

from draw import game

Modules are imported from other modules using the import command. In this example, the
game.py script may look something like this:

We may also use the import * command to import all objects from a specific module, like this:
from draw import *
def main():
result = play_game()
draw_game(result)

References
 https://www.learnpython.org/
 https://www.guru99.com/python-tutorials.html
 https://docs.python.org/3.9/tutorial/index.html
Web Frameworks
Django
Why Django? Key Advantage of Django
Here are the main advantages of Django:

 Django is easy to set up and run. It offers a variety of options to get started
 It provides a ready-to-use user interface for administrative activities
 It enables multilingual websites by using its built-in internationalization system
 Django helps you to provide end-to-end application testing
 Helps you to document your API with an HTML output
 REST Framework has rich support for several authentication protocols

Features of Django
Below are the features of Django: 10 Behavioral Interview Questions and Answers

 Helps you to define patterns for the URLs in your application


 Simple but powerful URL system
 Built-in authentication system
 Object-oriented programming language database which offers best in class data storage
and retrieval
 Automatic admin interface feature allows the functionality of adding, editing and
deleting items. You can customize the admin panel as per your need.
 Cache framework comes with multiple cache mechanisms.
ô
Django Architecture
MVC Pattern:
When talking about applications which provide UI (web or desktop), we usually talk about MVC
architecture. MVC pattern is based on Model, View, and Controller.
The Model defines the data structure and takes to care for querying the database.
The View defines what data should be presented and returns an HTTP response.
The Controller is that part of the application that handles the user interaction.

Components of Django Commented [S1]: Make Calibri, and 12 as font size, check
DB Section @Arif
Form:
Django has a powerful form library which handles rendering forms as HTML. The library
helps in validating submitted data and converting it to Python types.
Authentication:
It handles user accounts, groups, cookie-based user sessions, etc.
Admin:
It reads metadata in your models to provide a robust interface which can be used to
manage content on your site.
Internationalization:
Django provides support for translating text into various languages, locale-specific
formatting of dates, times, numbers, and timezones.
Security:
Django provides safeguard against the following attacks:
 Cross-Site Request Forgery (CSRF)
 Cross-site scripting
 SQL injection
 Clickjacking
 Remote code execution

Django Basics
Install Django by giving following command-pip install django
Creating a Project
To initiate a project of Django on Your PC, open Terminal and Enter the following command
django-admin startproject projectName
A New Folder with name projectName will be created. To enter in the project using terminal
enter command cd projectName
Now run, python manage.py runserver
To create a basic app in your Django project you need to go to directory containing manage.py
and from there enter the command: python manage.py startapp projectApp
To consider the app in your project you need to specify your project name in INSTALLED_APPS
list as follows in settings.py:

INSTALLED_APPS = [
'projectApp'
]
Now in the list of URL patterns, you need to
specify app name for including your app urls.
Here is the code for it –
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
# Enter the app name in following syntax for
this to work
path('', include("projectApp.urls")),
]

Django Views
Django views are divided into two major categories: -
 Function-Based Views
 Class-Based Views
Function based view Example –
Let’s Create a function-based view list view to display instances of a model. Let’s create a view
and template for the same. In geeks/views.py,
Class-based views are simpler and efficient to manage than function-based views. A function-
based view with tons of lines of code can be converted into class-based views with few lines
only. This is where Object-Oriented Programming comes into impact.

Django Models
A Django model is the built-in feature that Django uses to create tables, their fields, and various
constraints. In short, Django Models is the SQL of Database one uses with Django
Basics of a model include –

 Each model is a Python class that subclasses django.db.models.Model.


 Each attribute of the model represents a database field.
 With all of this, Django gives you an automatically-generated database-access API;

Whenever we create a Model, Delete a Model, or update anything in any of models.py of our
project. We need to run two commands makemigrations and migrate
So when we run, Python manage.py makemigrations
SQL Query to create above Model as a Table is created and Python manage.py migrate
creates the table in the database.

Django Forms
When one creates a Form class, the most important part is defining the fields of the form. Each
field has custom validation logic, along with a few other hooks.
Django handles three distinct parts of the work involved in forms:

 preparing and restructuring data to make it ready for rendering


 creating HTML forms for the data
 receiving and processing submitted forms and data from the client
Example

Render Django Forms


Django form fields have several built-in methods to ease the work of the developer but
sometimes one needs to implement things manually for customizing User Interface(UI). A form
comes with 3 in-built methods that can be used to render Django form fields.

 {{ form.as_table }} will render them as table cells wrapped in <tr> tags


 {{ form.as_p }} will render them wrapped in <p> tags
 {{ form.as_ul }} will render them wrapped in <li> tags
Example forms in views

Example forms in template


Django Templates
Templates are the third and most important part of Django’s MVT Structure. A template in
Django is basically written in HTML, CSS, and Javascript in a .html file

Create a template in templates/list_view.html,

Django CLI
Django provides a mechanism to create custom management commands that can be executed
via the manage.py script. These commands can be used for tasks like data processing,
maintenance scripts, or any application-specific logic.
Custom Management Commands
1. Set Up the Directory Structure
Custom commands are stored in the management/commands directory inside an app.

2. Create the Custom Command File


Create a file in the commands directory, e.g., your_command.py.
3. Write the Command Code
The custom command must subclass BaseCommand from django.core.management.
from django.core.management.base import BaseCommand
class Command(BaseCommand): help = 'Description of what the command does'

def add_arguments(self, parser):

parser.add_argument('arg_name', type=str, help='Description of the argument')

def handle(self, *args, **options):

arg_value = options['arg_name']

self.stdout.write(f'Processing argument: {arg_value}')

# Add your custom logic here

4. Add Arguments (Optional)


Arguments can be defined using the add_arguments method.
• Positional arguments: Required arguments.
• Optional arguments: Use -- for optional flags.
Example:
def add_arguments(self, parser):

parser.add_argument('required_arg', type=int, help='Required positional


argument')

parser.add_argument('--optional_arg', type=str, help='Optional named


argument')

5. Implement the handle Method


This is where the command’s logic resides. Access arguments using options.
def handle(self, *args, **options):

self.stdout.write(self.style.SUCCESS('Command executed successfully'))

self.stderr.write('An error message if needed')

6. Run the Command


Execute the custom command using manage.py.
python manage.py your_command arg_value --optional_arg=value
Example: Populating Dummy Data
Command: populate_data.py
from django.core.management.base import BaseCommand from your_app.models import
YourModel

class Command(BaseCommand): help = 'Populates the database with dummy data'


def handle(self, *args, **options):

YourModel.objects.create(name="Dummy Data")

self.stdout.write(self.style.SUCCESS('Dummy data created successfully!'))

Run the command:


python manage.py populate_data
Tips
1. Logging: Use self.stdout.write for normal output and self.stderr.write for error
messages.
2. Testing: Test commands thoroughly to avoid accidental data corruption.
3. Reusability: Keep commands modular and reusable by abstracting logic into functions or
classes.
Reference https://docs.djangoproject.com/en/5.1/howto/custom-management-commands/
References
 https://www.geeksforgeeks.org/django-tutorial/
 https://docs.djangoproject.com/en/
 https://www.tutorialspoint.com/django/index.htm
Flask
What is Flask
Flask is a web framework that provides libraries to build lightweight web applications in python.
It is based on WSGI toolkit and jinja2 template engine. Flask is considered as a micro
framework.
def render(name, list):
return “””
<html>
<title>{name}</title>
…{%for element in list%}
</html>
“””
Features of Flask
Here, are important features of Flask
 Integrated support for unit testing.
 RESTful request dispatching.
 Uses a Jinja2 template engine.
 It is based on Werkzeug toolkit.
 Support for secure cookies (client-side sessions).
 Extensive documentation.
 Google app engine compatibility.
 APIs are nicely shaped and coherent
 Easily deployable in production

First Flask Application


Write the following lines of code and save to a file named as script.py.

Flask App Routing


App routing is used to map the specific URL with the associated function that is intended to
perform some task. Example
Flask URL Building
The url_for() function is used to build a URL to the specific function dynamically. The first
argument is the name of the specified function, and then we can pass any number of keyword
argument corresponding to the variable part of the URL.
Example:
Flask HTTP Methods
HTTP is the hypertext transfer protocol which is considered as the foundation of the data
transfer in the world wide web. All web frameworks including flask need to provide several
HTTP methods for data communication.
The methods are given in the following
• GET
• HEAD
• POST
• PUT
• DELETE
POST method example

route(“/login”, methods=[“GET”, “POST”])


Flask Templates
Flask provides us the render_template() function which can be used to render the external HTML
file to be returned as the response from the view function.
Consider the following example.
message.html
script.py

Flask Redirect and Errors


Flask class provides the redirect() function which redirects the user to some specified URL with
the specified status code. Example

@app.route('/validate', methods = ["POST", “GET”])

def validate():

if request.method == 'POST' and request.form['pass'] == 'jtp':

return redirect(url_for("success"))

return redirect(url_for("login"))
The abort() function is used to handle the cases where the errors are involved in the requests
from the client side, such as bad requests, unauthorized access and many more. Example:

@app.route('/validate', methods = ["POST"])

def validate():

if request.method == 'POST' and request.form['pass'] == 'jtp':

return redirect(url_for("success"))

else:

abort(401)

Flask WTF
WTF stands for WT Forms which is intended to provide the interactive user interface for the
user. The WTF is a built-in module of the flask which provides an alternative way of designing
forms in the flask web applications.
Install flask WTF pip install flask-wtf
Example:

Flask Unit Testing and Code Coverage


Introduction to Python Unit Tests

Unit testing is a method of testing individual units of code (functions, methods, or classes) in
isolation. Python provides the built-in unittest module for this purpose, but frameworks like
pytest are also popular.

Step 1: Set Up a Flask Application

Create a simple Flask application.

File: app.py

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/')
def home():
return jsonify({'message': 'Welcome to Flask!'})

@app.route('/add', methods=['POST'])
def add():
data = request.get_json()
result = data['a'] + data['b']
return jsonify({'result': result})

if __name__ == '__main__':
app.run(debug=True)
Step 2: Write Unit Tests for the Flask Application

Create a test file where you’ll write test cases for your Flask app.

File: test_app.py

import unittest
from app import app

class FlaskAppTests(unittest.TestCase):

def setUp(self):
# Set up a test client
self.app = app.test_client()
self.app.testing = True

def test_home(self):
response = self.app.get('/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json, {'message': 'Welcome to
Flask!'})

def test_add(self):
response = self.app.post('/add', json={'a': 2, 'b': 3})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json['result'], 5)

def test_add_invalid_data(self):
response = self.app.post('/add', json={'a': 'two', 'b': 3})
self.assertNotEqual(response.status_code, 200) # Should
handle invalid input gracefully

if __name__ == '__main__':
unittest.main()

Step 3: Run the Unit Tests

Run the test file in your terminal:

python -m unittest test_app.py

Step 4: Set Up Code Coverage

1. Install the coverage library:

pip install coverage

2. Run the tests with coverage:

coverage run -m unittest test_app.py

3. Generate a coverage report:

coverage report
4. To create an HTML report for better visualization:

coverage html

Open htmlcov/index.html in your browser.

Step 5: Improve Code Coverage

Identify untested parts of your application and write additional tests to cover them.

Automating Tests with Pytest

Switch to pytest for a more concise syntax:


1. Install pytest:

pip install pytest

2. Rename test_app.py to follow pytest conventions (e.g., keep the file name as
test_*.py).
3. Run tests:

pytest --cov=app --cov-report=html

Step 6: Best Practices for Flask Unit Tests


1. Isolate Tests: Each test should be independent.
2. Use Fixtures: For setting up and tearing down resources.
3. Mock External Calls: Use libraries like unittest.mock to mock external
dependencies.
4. Test Edge Cases: Ensure your application handles unexpected inputs gracefully.
References
 https://www.javatpoint.com/flask-tutorial
 https://flask.palletsprojects.com/en/2.0.x/
 https://www.tutorialspoint.com/flask/index.htm

Generative AI and LLM

Golang
Course Brief Time: 8 hours
Setup Environment
 Installation: https://golang.org/doc/install
 IDE:
o Goland (Activator)
o VSCode with Go Extension
 Prepare Workspace
o Create go workspace directory inside your home directory
 Windows: C:/Users/name/go/src
 Mac/Ubuntu: $HOME/go/src
o Few important commands
 Set GOPATH:
 Windows: SET GOPATH=C:/Users/<name>/go/bin
 Mac/Ubuntu: export GOPATH=$HOME/go/bin
 Get Go Path: go env GOPATH
 Set GOBIN:
 Windows: SET GOBIN=C:/Users/<name>/go/bin
 Mac/Ubuntu: export GOBIN=$HOME/go/bin
 Check Go environment variables: go env
 Run go program: go run main.go
 Build go program: go build main.go

More details: https://www.tutorialspoint.com/go/go_environment.htm


Golang Basics
 Why Golang: Go language is a programming language initially developed at Google in
the year 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is a statically-typed
language having syntax similar to that of C. It provides garbage collection, type safety,
dynamic-typing capability, many advanced built-in types such as variable length arrays
and key-value maps. It also provides a rich standard library. The Go programming
language was launched in November 2009 and is used in some of the Google's
production systems.
 Golang structure and syntax:
A Go program basically consists of the following parts −
o Package Declaration
o Import Packages
o Functions
o Variables
o Statements and Expressions
o Comments
Let us look at a simple code that would print the words "Hello World" −
package main
import "fmt"
func main() {
/* This is my first sample program. */
fmt.Println("Hello, World!")
}

 Data types: In the Go programming language, data types refer to an extensive system
used for declaring variables or functions of different types. The type of a variable
determines how much space it occupies in storage and how the bit pattern stored is
interpreted.
o Boolean types: They are boolean types and consists of the two predefined
constants: (a) true (b) false
o Numeric types: They are again arithmetic types and they represents a) integer
types or b) floating point values throughout the program.
o String types: A string type represents the set of string values. Its value is a
sequence of bytes. Strings are immutable types that is once created, it is not
possible to change the contents of a string. The predeclared string type is string.
o Derived types: They include (a) Pointer types, (b) Array types, (c) Structure types,
(d) Union types and (e) Function types f) Slice types g) Interface types h) Map
types i) Channel Types
More details: https://www.tutorialspoint.com/go/go_data_types.htm

 Variables: A variable is nothing but a name given to a storage area that the programs
can manipulate. Each variable in Go has a specific type, which determines the size and
layout of the variable's memory, the range of values that can be stored within that
memory, and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character.
It must begin with either a letter or an underscore. Upper and lowercase letters are
distinct because Go is case-sensitive.
o Static Type Declaration: var x float64
o Dynamic Type Declaration / Type Inference: y := 42
o Mixed Variable Declaration: var a, b, c = 3, 4, "foo"
 Constants: Constants are treated just like regular variables except that their values
cannot be modified after their definition. Example: const LENGTH int = 10
 Operators: An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. Go language is rich in built-in operators
and provides the following types of operators:
o Arithmetic Operators: +, -, *, /, %, ++, --
o Relational Operators: ==, !=, >, <, >=, <=,
o Logical Operators: &&, ||, !
o Bitwise Operators: &, |, ^, <<, >>
o Assignment Operators: =, +=, -=, *=, /=, %=, <<=, >>=, &=, |=, ^=1
o Miscellaneous Operators:
 &: return address
 *: return pointer
 Array:
package main
import "fmt"
func main() {
var theArray [3]string
theArray[0] = "India"
theArray[1] = "Canada"
theArray[2] = "Japan"
fmt.Println(theArray)

x := [5]int{10, 20, 30, 40, 50}


fmt.Println(x[0], x[1], x[2], x[3], x[4])
}

 Slice: Slices looks like array in golang but it is a bit flexible and powerful than array.
Array is fixed but slice is variable. Slices can be resized using the built-in append
function.
var theArray [3]string // Array
var theArray []string // Slice
var intSlice = make([]int, 10) // Slice

Slice example:
package main
import (
"fmt"
"reflect"
)
func main() {
var intSlice = make([]int, 10) // when length and
capacity is same
var strSlice = make([]string, 10, 20) // when length and
capacity is different
fmt.Printf("intSlice \tLen: %v \tCap: %v\n", len(intSlice),
cap(intSlice))
fmt.Println(reflect.ValueOf(intSlice).Kind())
fmt.Printf("strSlice \tLen: %v \tCap: %v\n", len(strSlice),
cap(strSlice))
fmt.Println(reflect.ValueOf(strSlice).Kind())
}

Length is the current number of element and capacity is the number of elements a slice
can store.
More details: https://www.golangprograms.com/go-language/slices-in-golang-
programming.html

 Map: A map is a data structure that provides you with an unordered collection of
key/value pairs (maps are also sometimes called associative arrays in Php, hash tables in
Java, or dictionaries in Python). Maps are used to look up a value by its associated key.
You store values into the map based on a key.
package main
import "fmt"
func main() {
var employee = make(map[string]int)
employee["Mark"] = 10
employee["Sandy"] = 20
fmt.Println(employee)

employeeList := make(map[string]int)
employeeList["Mark"] = 10
employeeList["Sandy"] = 20
fmt.Println(employeeList)
}

More details: https://www.golangprograms.com/go-language/golang-maps.html

 Structs: Structs are the only way to create concrete user-defined types in Golang. Struct
types are declared by composing a fixed set of unique fields. Structs can improve
modularity and allow to create and pass complex data structures around the system.
You can also consider Structs as a template for creating a data record, like an employee
record or an e-commerce product.
Struct with primitive data type:
package main
import "fmt"
type rectangle struct {
length float64
breadth float64
color string
}
func main() {
fmt.Println(rectangle{10.5, 25.10, "red"})
}

More details: https://www.golangprograms.com/go-language/struct.html

 JSON struct, marshal and unmarshal: We can create a struct for JSON data. The JSON
data can be encoded and decoded with a defined struct in the following way.
package main
import (
"fmt"
"encoding/json"
)
type Employee struct {
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
City string `json:"city"`
}
func main() {

json_string := ` {
"firstname": "Rocky", "lastname":
"Sting", "city": "London" }`
emp1 := new(Employee)
json.Unmarshal([]byte(json_string), emp1)
fmt.Println(emp1.FirstName, emp1.LastName, emp1.City)

emp2 := new(Employee)
emp2.FirstName = "Ramesh"
emp2.LastName = "Soni"
emp2.City = "Mumbai"
jsonStr, _ := json.Marshal(emp2)
fmt.Printf("%s\n", jsonStr)
}

 Decision making:
Decision making with if, else and else if:
package main
import ("fmt")
func main() {
x := 100
if x == 50 {
fmt.Println("Germany")
} else if x == 100 {
fmt.Println("Japan")
} else {
fmt.Println("Canada")
}
}

Decision making with switch and case:


package main
import (
"fmt"
"time"
)
func main() {
switch today := time.Now(); {
case today.Day() < 5:
fmt.Println("Clean your house.")
case today.Day() <= 10:
fmt.Println("Buy some wine.")
case today.Day() > 15:
fmt.Println("Visit a doctor.")
case today.Day() == 25:
fmt.Println("Buy some food.")
default:
fmt.Println("No information available for that day.")
}
}

 Loop:
package main
import "fmt"
func main() {
for k := 1; k <= 10; k++ {
fmt.Println(k)
}
k = 1
for k <= 10 {
fmt.Println(k)
k++
}
for k := 1; ; k++ {
fmt.Println(k)
if k == 10 {
break
}
}
}

 Range:
package main
import "fmt"
func main() {
// Example 1
strDict := map[string]string{"Japan": "Tokyo", "China":
"Beijing", "Canada": "Ottawa"}
for index, element := range strDict {
fmt.Println("Index :", index, " Element :", element)
}
// Example 2
for key := range strDict {
fmt.Println(key)
}
// Example 3
for _, value := range strDict {
fmt.Println(value)
}
}

 Function: func keyword has been used to declare a function in golang. We can return
multiple variable from a function in golang.
package main
import "fmt"
// SimpleFunction prints a message
func SimpleFunction() {
fmt.Println("Hello World")
}
func main() {
SimpleFunction()
}

More details: https://www.golangprograms.com/go-language/functions.html

 Interface: An Interface is an abstract type. Interface describes all the methods of a


method set and provides the signatures for each method.
package main
import "fmt"
// Employee is an interface for printing employee details
type Employee interface {
PrintName(name string)
PrintSalary(basic int, tax int) int
}
// Emp user-defined type
type Emp int
// PrintName method to print employee name
func (e Emp) PrintName(name string) {
fmt.Println("Employee Id:\t", e)
fmt.Println("Employee Name:\t", name)
}
// PrintSalary method to calculate employee salary
func (e Emp) PrintSalary(basic int, tax int) int {
var salary = (basic * tax) / 100
return basic - salary
}
func main() {
var e1 Employeee1 = Emp(1)
e1.PrintName("John Doe")
fmt.Println("Employee Salary:", e1.PrintSalary(25000, 5))
}

More details: https://www.golangprograms.com/go-language/interface.html

 Scope: In golang a variable declared inside main function is a local variable, outside of
main is a global variable and a variable/function outside of main with capital character
can be accessed from any other package.
package main
import "fmt"

var g int // global variable


var Y int // global variable which can be accessed from other
packages

// global function which can be called from other


packages func Count() {
return 5
}
func main() {
var a, b int // local variable
}

 Goroutine: Goroutine is one of the powerful features of Golang. It allows to execute


program with concurrency. Multithreading is way easier with goroutine. New goroutines
are created by the go statement.

package main

import (
"fmt"
"time"
)

func concurrentFunc(label string) {


fmt.Println(label)
time.Sleep(1 * time.Second)
}

func main() {
go concurrentFunc("First process")
go concurrentFunc("Second process")
go concurrentFunc("Third process")
time.Sleep(1 * time.Second) // to wait
main function
}

More details: https://www.golangprograms.com/goroutines.html

 Channel: Go provides a mechanism called a channel that is used to share data between
goroutines. When you execute a concurrent activity as a goroutine a resource or data
needs to be shared between goroutines, channels act as a conduit(pipe) between the
goroutines and provide a mechanism that guarantees a synchronous exchange.
A channel is created by the make function, which specifies the chan keyword and a
channel's element type.
Unbuffered := make(chan int) // Unbuffered channel
buffered := make(chan int, 10)// Buffered channel

Example:
package main

import (
"fmt"
)

func concurrentFunc(label string, data chan string) {


data <- label + " has been completed"
}

func main() {
data := make(chan string)
go concurrentFunc("First process", data)
message := <-data
fmt.Println(message)
}

More details: https://www.golangprograms.com/go-language/channels.html

 Type casting:
 Structure (convert string to int): intVar, err := strconv.Atoi(strVar)
More details: https://www.golangprograms.com/go-language/integer-float-string-
boolean.html

 Error handling: Go programming provides a pretty simple error handling framework


with inbuilt error interface type
result, err:= Sqrt(-1)

if err != nil {
fmt.Println(err)
}
 HTTP request:
Get request:
package main

import (
"io/ioutil"
"log"
"net/http"
)

func main() {
resp, err :=
http.Get("https://jsonplaceholder.typicode.com/posts")
if err != nil {
log.Fatalln(err)
}
//We Read the response body on the line below.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
//Convert the body to type string
sb := string(body)
log.Printf(sb)
}

POST Request:
package main

import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"net/http"
)

func main() {
//Encode the data
postBody, _ := json.Marshal(map[string]string{
"name": "Toby",
"email": "[email protected]",
})
responseBody := bytes.NewBuffer(postBody)
//Leverage Go's HTTP Post function to make request
resp, err := http.Post("https://postman-echo.com/post",
"application/json", responseBody)
//Handle Error
if err != nil {
log.Fatalf("An Error Occured %v", err)
}
defer resp.Body.Close()
//Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
sb := string(body)
log.Printf(sb)
}
Golang Assignment
 Develop a REST API with POST request for user registration with following fields: First
Name, Last Name, Email, Phone, Password, Date of birth
o Use PostgreSQL to store those data
o Use appropriate data type
o Store password hash instead of direct string
o Implement appropriate form validation
o API should return JSON including success with user id or error with message
 Develop a REST API with POST request to upload user image with following fields: image
and user id
 Implement a login API with Email and Password with GET request.
 All the API should work under separate goroutine
Web Frameworks
Beego is a RESTful HTTP framework for the rapid development of Go applications including
APIs, web apps and backend services with integrated Go specific features such as interfaces and
struct embedding.
Beego architecture:

File structure:
Setup environment: https://www.golangprograms.com/golang/beego-setup-installation/
GET and POST request: https://www.golangprograms.com/golang/beego-get-post-routing/
Routing: https://www.golangprograms.com/golang/beego-route-contoller-get-method/
Template parsing: https://beego.me/docs/mvc/view/view.md

Web Framework Assignment


Develop a movie listing website based on TMDB API. The website should include the following
features:

 Develop a homepage with a banner and three horizontal sections: Popular, Trending
and TV series. Each item should show horizontal list of movie images and title receives
from API.
 Implement movie details page with movie image, title, star rating, details and play
trailer feature
 Develop a REST API in Golang to store favorite movies in DB
 Implement API to add movies into favorite list
 Show list of favorite movies in a new page
Cloud Infrastructure
Deployment tools and techniques
Cloud Infrastructure
The collection of hardware and software elements needed to enable cloud computing. It includes
computing power, networking, and storage, as well as an interface for users to access their Commented [S2]: Make Calibri, and 12 as font size, check
virtualized resources, without direct active management by the user. DB Section @Rajib Biswas

Cloud computing has created the opportunity for organizations to access the data storage and
computing capabilities that they require, on an as-needed basis and with a significantly reduced
up-front cost, instead of establishing their own on-premise IT infrastructure. Some of the top
cloud service providers

 Amazon Web Service (AWS)


 Microsoft Azure
 Google Cloud Platform (GPC)
 IBM Cloud
 Oracle
 VMware
Types of Cloud Infrastructure
 SaaS : Software as a Service
 PaaS : Platform as a Service
 IaaS : Infrastructure as a Service

Amazon Web Service (AWS)


Amazon Web Services (AWS) is the cloud-based Infrastructure as a service provider, a
subsidiary by Amazon.com, provides on-demand cloud computing platforms, on a paid
subscription basis. Provides services like Virtual machines, servers, storage, load balancers,
networks, security and so on. Below are some services that we will use for different purposes
for our projects.
EC2
ECC – Elastic Compute Cloud. A service that provides secure, resizable compute capacity in the
cloud. It’s Secure and resizable compute capacity in the cloud. Launch applications when
needed without upfront commitments. Amazon EC2 provides a wide selection of instance types
optimized to fit different use cases. Instance types comprise varying combinations of CPU,
memory, storage, and networking capacity (T4g, T3, T3a, T2, M6g, M6i, M5, M5a, M5n, M5zn,
M4, A1, C4 C5 C5n, R4, R5a, G3 G4 P2 P3, I3 I3en D2 H1 etc.).
EC2 comes with following additional services:
 Instances
 Images
 Elastic Block Storage
 Network & Security
 Load Balancing
 Auto Scaling

VPC
A virtual private cloud (VPC) is a virtual network dedicated to one AWS account. It’s logically
isolated from other virtual networks in AWS. One can lunch AWS resources under the VPC he
has. Under VPC you will get other related service like Subnet, Route Tables, Internet Gateways,
Elastic IPs, Network ACLs, Security Groups etc.

S3
Simple Storage Service - This is an object Storage Service, provides data availability, stability,
security and performance. Durability 99.999999999 % (11 9’s) and grows automatically with
your needs, pay as you use policy. Keeps copy of data on multiple devices on multiple zones.
The total volume of data and number of objects you can store are unlimited. Individual Amazon
S3 objects can range 0 bytes to 5TB.
Types: (Provides configurable life cycle policy)
 S3 Standard
 S3 Intelligent-Tiering
 S3 IA (Infrequent Access)
 S3 One Zone-IA
 Amazon Glacier
 S3 Glacier Deep Archive

CloudFront
CDN service that securely delivers data, videos, application, and APIs to customers globally with
low latency, high transfer speeds. CloudFront is directly connected with all AWS services /
Global infrastructure. Works as a caching server near you.
Currently AWS has a Global network of 230+ Points of Presence – 218 Edge Location & 12
Regional Edge Caches.
Some benefit:
ô Makes content delivery faster for static web content.
ô Provides encrypted communication.
ô DDoS protection with layer 3 & 4.
ô Application layer protection.
Indirect:

 Reduce load capacity in host server.


 Increase uptime.
 Not directly communicating to the server, which increase the server security.

RDS
Amazon Relational Database Service (Amazon RDS), a managed service which makes it easy to
set up, operate, and scale a relational database in the cloud. It reduces administration tasks
such as hardware provisioning, database setup, patching and backups. It frees you to focus on
your applications so you can give them the fast performance, high availability, security and
compatibility they need. Aws RDS provides you with six familiar database engines to choose
from.
o Amazon Aurora
o PostgreSQL
o MySQL,
o MariaDB
o Oracle Database
o SQL Server
NoSQL
NoSQL databases (aka "not only SQL") are non-tabular, and store data differently than
relational tables.
NoSQL database have the following facilities:

 Flexibility: NoSQL databases generally provide flexible schemas that enable faster and
more iterative development. The flexible data model makes NoSQL databases ideal for
semi-structured and unstructured data.
 Scalability: NoSQL databases are generally designed to scale out by using distributed
clusters of hardware instead of scaling up by adding expensive and robust servers. Some
cloud providers handle these operations behind-the-scenes as a fully managed service.
 High-performance: NoSQL database are optimized for specific data models and access
patterns that enable higher performance than trying to accomplish similar functionality
with relational databases.
 Highly functional: NoSQL databases provide highly functional APIs and data types that
are purpose built for each of their respective data models.
AWS provides different types of NoSQL database.

 Key-value: Amazon DynamoDB


 Document: Amazon DocumentDB
 Graph: Amazon Neptune
 In-memory: Amazon ElastiCache
 Search: Amazon Elasticsearch Service

Route53
AWS Route 53: is a scalable & highly available Domain Name System (DNS) web service. Its
easily routes traffic to all its pointed services as well as route users to infrastructure outside of
AWS.
Key Features:
• Domain Registration
• Resolver
• Traffic flow
• Latency based routing
• DNS Failover
• Health checks and monitoring
• ELB, S3 integration

SQS
Simple Queue Service
A fully managed message queuing service that enables you to decouple and scale microservices,
distributed systems, and serverless applications.
With SQS one can send, store, and receive messages between software components at any
volume, without losing messages or requiring other services to be available.
Queue Types:
 Standard queue.
 FIFO

Elastic Beanstalk
Elastic Beanstalk, one can quickly deploy and manage applications in the AWS Cloud without
having to learn about the infrastructure that runs those applications. Elastic Beanstalk reduces
management complexity without restricting choice or control. You simply upload your
application, and Elastic Beanstalk automatically handles the details of capacity provisioning, load
balancing, scaling, and application health monitoring. Elastic Beanstalk supports applications
developed in Go, Docker, Java, .NET, Node.js, PHP, Python, and Ruby.

Elasticsearch
Elasticsearch is an open-source, RESTful, distributed search and analytic engine built on Apache
Lucene.
Elasticsearch usages a data structure called an inverted index, which is allows to allow very fast
full-text search. An inverted index lists every unique world that appears in any documents all of
the documents each word occurs in.
Known as ELK (Elasticsearch, Logstash, Kibana).
Why use Elasticsearch?
 Elasticsearch is free
 Elasticsearch is fast
 Elasticsearch is distributed by nature
o Elasticsearch comes with a wide set of features
 The Elastic Stack simplifies data ingest, visualization, and reporting.
Elasticsearch used for.

 Application search
 Website search
 Logging and log analytics
 Geospatial data analysis and visualization
 Security analytics
 Business analytics

Lambda
AWS Lambda is a serverless computing service provided by Amazon Web Services (AWS).
Lambda lets you run code without provisioning or managing servers. Lambda runs your code on
a high-availability compute infrastructure and performs all of the administration of the
compute resources, including server and operating system maintenance, capacity provisioning
and automatic scaling, code monitoring and logging.
AWS Lambda natively supports Java, Go, PowerShell, Node.js, C#, Python, and Ruby code, and
provides a Runtime API which allows you to use any additional programming languages to
author your functions.
CloudFormation
CloudFormation - Infrastructure as Code, is a service that gives an easy way to create a
collection of related AWS and third-party resources, and provision and manage them in an
orderly and predictable fashion. You can create templates using YAML or JSON for the service
or application architectures you want and have, AWS CloudFormation use those templates for
quick and reliable provisioning of the services or applications (called “stacks”). You can also
easily update or replicate the stacks as needed.

Linux (OS)
Linux is a Unix-like, open source and community-developed operating system. An operating
system is the software that directly manages a system’s hardware and resources, like CPU,
memory, and storage. Some popular Linux distribution

 Ubuntu
 Fedora
 CentOS
 Linux Mint Cinnamon
 Debian GNU/Linux
Linux terminal is the place where one will run commands. Some basic commands to learn:

 cd/cd ~: Go to home directory


 cd folder_Name: go to directory
 cd .. : go back one directory
 ls: List file
 date: Shows the current date time
 cat: View the contents of the file
 free -m: Display free & used memory
 top: Display and manage the top processes
 head: Display file contents (default is first 10 lines)
 tail: Display file contents (default is last 10 lines)
 less: Brouse through a text file
 pwd: Print current working directory
 mkdir: Create Directory
 rm: Remove file/folder
 cp: Copy file/folder
 mv: Move file/folder
 zip: Zip files
 unzip: Unzip file
 grep: Search for pattern in file
 locate: Find files and directories by name
 find: find for files
 ssh: Connect to a host securely
 scp: Secure copy
 apt/yum: manage packages
 man: Read a man page
 clear: clear screen
 vim/nano: edit files

Docker
Docker is a software platform that allows you to build, test, and deploy applications quickly, it’s
use OS-level virtualization to deliver software in packages called containers & they are isolated
from one another and bundle their own software, libraries and configuration files; they can
communicate with each other through well-defined channels. The software that hosts the
containers is called Docker Engine.
Some basic docker command:
# Pull an image from a registry
docker pull myimage:1.0
# Re-tag a local image with a new image name and tag
docker tag myimage:1.0 myrepo/myimage:2.0
# Push an image to a registry
docker push myrepo/myimage:2.0
# Build an image from the Dockerfile in the current directory and tag the image
docker build -t myimage:version .
# List all images that are locally stored with the Docker Engine
docker image ls
# Delete an image from the local image store
docker image rm alpine:3.4
# Run a container from the Alpine version 3.9 image, name the running container “web” and
expose port #5000 externally, mapped to port 80 inside the container.
docker container run --name web -p 5000:80 alpine:3.9
# Stop a running container
docker container stop web
# List only active containers
docker ps
# List all containers
docker ps -a
# Stop a container
docker stop [container-name|container-id]
# List the networks
docker network ls
# List the running containers (add --all to include stopped containers)
docker containerName/ID ls
# Delete all running and stopped containers
docker container rm -f $(docker ps -aq)
# Print the last 100 lines of a container’s logs
docker container logs --tail 100 containerName/ID
# Print the container’s logs (use -f to follow)
docker container logs containerName/ID

Docker Compose
Docker Compose is a tool for running multi-container applications on Docker defined using the
Compose file format. A Compose file is written using YAML, which used to define how the one or
more containers that make up your application are configured. Once you have a Compose file,
you can create and start your application with a single command: docker-compose up.
Compose is basically a three-step process:
 Define your app’s environment with a Dockerfile so it can be reproduced anywhere.
 Define the services that make up your app in docker-compose.yml so they can be run
together in an isolated environment.
 Run docker-compose up, which bring your app to live.
Below is an example of docker-compose file.
version: '3'
services:
web:
image: nginx
db:
image: mysql
ports:
- "3306:3306"
environment:
- MYSQL_ROOT_PASSWORD=password
- MYSQL_USER=user
- MYSQL_PASSWORD=password
- MYSQL_DATABASE=demodb
GIT
Open-Source Distributed Version Control System, is a tool used for source code management,
able to tracking changes in any set of files, used for coordinating work among programmers for
collaboratively developing source code during software development.
Some git command that we use very frequently:
## Clone a project
git clone [URL]
## Pull a branch
git pull
## downloads commit, files, and refs from a remote repository into your local repo.
git fetch
## lists all the files that have to be committed
git status
## list the version history for the current branch
git log
## list branch
git branch
## check all remote branch
git branch -a
## to create a new branch
git branch branchName
## to delete a branch
git branch -d branchName
## switch from one branch to another.
git checkout branchName
## Create a new branch and switch to it.
git checkout -b branchName
## push your update to remote
git add .
git commit -m "messages"
git push
## push a new local branch to remote
git push -u origin branchName
## merge a branch
git merge branchName
## diff of what is changed but not staged
git diff
## diff of what is staged but not yet committed
git diff --staged
IDE
An integrated Development environment (IDE) is software for building applications that
combines common developer tools into a single graphical user interface (GUI). Typically
consists of:

 Source code editor


 Local build automation
 Debugger
IDE popularity depends on:

 The number of supported languages.


 Supported operating systems.
 Automation features.
 Impact on system performance.
 Plugin & extension.
Some popular IDE:

 Visual Studio / VS Code


 Eclipse
 JetBrains
 GoLand
 PyCharm
 WebStorm
 NetBeans

Automation Tools
Automation Software is an application that has functionalities to develop, manage, and monitor
automated processes for IT enterprise. IT processes are scattered across multiple environments,
tools, and technologies, this is a difficult task to manage. Automation software is used for
automating repetitive tasks and manual processes so that there will be cost savings and reduced
human errors. These tools have features to monitor and manage distributed IT environments.
Top automation software
1. Ansible
2. Terraform
3. Jenkins
4. Chef
5. Puppet
Let’s see the key difference between Ansible vs Terraform
Ansible Terraform

Ansible is a configuration management tool. Terraform is an infrastructure provisioning


tool.

Ansible is procedural. Terraform is declarative.

Can deploy apps on the top of infrastructure. Can deploy Load balancers, VPCs, etc.

With Ansible, you need to dictate each step Terraform can carry out all steps to present
to achieve the end result. the final output, once given the end
instruction.

Maintains all components in working Considered ideal for conserving the


condition and repairs an issue instead of environment in a steady state.
replacing the entire infrastructure.

Mutable infrastructure. Immutable infrastructure.

You might also like