1-2

1-2 SI base units

An Imgur Image
In the above image it displayed the base units of seven quantities.

1
2
// The SI unit of force, called the newton (N), is defined in terms of SI base units as:
1 N = 1 kg * m/s^2

SI prefixes

An Image of SI prefixes

  • We can write for example a typical eletrical power plant, 1.3 * 10^9 watts, as 1.3 gigawatts or 1.3 GW
  • Another example we can write a time interval of size of often ecountered in nuclear physics, 2.35 * 10^-9, as 2.35 nanoseconds or 2.35 ns

1-1

1-1 Physical Quantities, standards, and Units

The laws of physics are expressed in terms of many differnt quantities:

  • mass, length, time, force, speed, density, resistence, temperature, luminous intensity, magnetic field strength, and many more.

    video sample

Each of these terms has a precise meaning, they form part of a commong language that others physicists and other scientists use to communicate with, For example:

  • When a physicist uses a term such as “kinetic energy”, the others understand what is meant.
    There must be agreement about the units used to express their values, it is impossible for scientist to communicate their results withoug agreements.

    Another example

    If a measurement of length is quoted as 4.3 meters, it means that the measured length is 4.3 times as long as the value accepted for a standard length defined to be “one meter”.

Measurement standard

Length and time were once regarded as fundamental quantities with their individual established standards; the measurement standard for speed (=length/time) could then be derived in terms of those standards.

DevOps-req

Gradle

[] Gradle
A reliable build too is needed for your DevOps tool stack

Git

[x] git
Used in the software industry and is popular DevOps toop

Jenkins

[In progress] Jenkins
Go-to automation tool of Devops

Bamboo

[] Bamboo
The automation of te delivery pipeline couldb be achieved by both. Cons: Intruction of the pipeline can not be save

Docker

[x] docker
It is a container platform which are used to deploy products

Kubernetes

[] kubernetes
The containerized application’s deployment, scaling, and management could be automated by an open-source system

Puppet Enterprise

[] Puppet Enter prise
A configuration management platform which is also cross-platform
infrastructure could be managed by the Puppet tool

Ansible

[] Ansible
Similar to Chef and Puppet, a configuration management tool

Nagios

[] Nagios
A DevOps monitoring tool, problems could be found and fixed with Nagios tool

Raygun

[] Raygun
It is a platform which reports crash and monitors errors.

namePipe

Creating a Named Pipe

  • At the other functions, you’ll normally see that they all accomodate either a numerical port number or a string descriped as a pipe:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17

    export function onError(error) {
    if (error.syscall !== 'listen') {
    throw error;
    }
    const bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;
    switch (error.code) {
    case 'EACCES':
    console.error(`${bind} requires elevated privileges`);
    process.exit(1);
    break;
    default;
    throw error;
    }
    }

expressTemplate

Express Templates

Pug is a templating engine for Express.
Templating engines are used to remove the cluttering of our server code with HTML, concatenating strings wildly to existing HTML templates.
Pug is a very powerful templating engine which has a variety of features including filters, includes, inheritance, interpolation, etc.

Architecting

Architecting an Express application in the MVC paradigm

Express doesn’t enforce an opinion on how you should structure the Model, View, and Controller (MVC) modules of your application, or whether you should follow any kind of MVC paradigm at all.
The controller acceps inputs or requests from the user, converting that intocommands sent to the model.
The model contains data, logic, and rules which the application operatates.
The view is used to present the results to the user.

As we learned in the previous chapter, the blank application created by the Express generator provides two aspects of the MVC model:

  • The views directory contains template files, controlling the display portion, corresponding to the view.
  • The routes directory contains code implementing the URLs recognized by the application and coordinates the data manipulation required to generate the response to each URL.
  • This corresponds to the controller.

The approach we’ll use is to create a models directory as a sibling of the views and routes directories.
The models directory will hold modules to handle data storage and other code that we might call business logic.
The API of the modules in the models directory will provide functions to create, read, update, or delete data items-a Create, Read, Update, and Delete/Destroy(CRUD) model

asyncAndExpress

Intergrating async functions with Express router functions

There are two problems that need to be addressed that are related to asynchrous coding in JavaScript.
The first is the pyramid of doom, an unwieldily nested callback structure.
The second is the invonvenience of where results and errors are delivered inan asynchronous callback.

1
2
3
4
5
6
7
8
db.query('SELECT ..etc..', function(err, resultSet) {
if (err) {
// Instead, errors arrive here
} else {
// Instead, results arrive here
}
});
// We WANT the errors or results to arrive here

The goal here is to avoid blocking tthe event loop with a long operation.
Deferring the processing of results or errors using callback functionsis an excellent solutionand is the founding idiom of Node.js.

Example of db.query as an async function

1
2
3
4
5
6
async function dbQuery(params) {
const resultSet = await db.query('SELECT ..etc..');
// results and errors land here
return resultSet;
}

Rewriting it as an async functon:

1
2
3
4
5
6
7
8
9
10
11
12
13
router.get('/path/to/something', async (req, res, next) => {
try {
const data1 = await doSomething(req.query.arg1, req.query.arg2);
const data2 = await doAnotherThing(req.query.arg3,
req.query.arg2, data1);
const data3 = await somethingCompletelyDifferent(req.query.arg1,
req.query.arg42);
const data4 = await doSomethingElse();
res.render('page', { data1, data2, data3, data4 });
} catch(err) {
next(err);
}
});

Other than try/catch, this example is very clean compared to its earlier forms, both as a callback pyramid and as a Promise chain.
The await keyword looks for a Promise. Therefore, doSomething and the other functions are expected to return a Promise, and await manges its resolution.
We need to know that await manages the asynchronous execution and the resolution of the Promises, more importantly each statement with an await keyword executes asynchrounously.

The try/catch structure is needed for integration with Express.

Promises

Promises and error handling in Express router functions

1
2
3
4
5
6
7
8
9
app.get('/', (req, res) => {
fs.readFile('/does-not-exist', (err, data) => {
if (err) throw new Error(err);
// do something with data, like
res.send(data);
});
});
/* This is an example of the error indicator landing in an invonvenient place in the call back function.
*/

Express doesn’t handle the promise. In this example, the error is lost; the caller would never receive a response and nobody would know why.

It is important to reliably catch any errors and respond to the caller with the results or errors.
To understand this better, let’s rewrite the pyramid of doom
example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//This is rewritten using a Promise chain, rather than nested callbacks.

router.get('/path/to/something', (req, res, next) => {
let data1, data2, data3, data4;
doSomething(req.query.arg1, req.query.arg2)
.then(_data1 => { //.then is an invokes of Async
data1 = _data1;
return doAnotherThing(req.query.arg3, req.query.arg2, data1);
})
.then(_data2 => {
data2 = _data2;
return somethingCompletelyDifferent(req.query.arg1, req.query.arg42);
})
.then(_data3 => {
data3 = _data3;
return doSomethingElse();
})
.then(_data4 => {
data4 = _data4;
res.render('page', {data1, data2, data3, data4 });
})
.catch(err => { next(err); });
});

sample1

Overview

A Promise is either in an unresolved or resolved state. We create using
new Promise, and initially, it is in the unresolved state.
The Promise object transitions to the resolved, where either its resolve or reject functions are called.

1
2
3
4
5
6

Promise objects can be in one of three states:
Pending: This is the initial state, which is neither fulfilled nor rejected.
Fulfilled: This is the final state, where it executes successfully and produces a result.
Rejected: This is the final state, where execution fails.

We generate a Promise in the following way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function asyncFunction(arg1, arg2) {
return new Promise((resolve, reject) => {
//perform some task or computation that's asynchronous
// for any error detected:
if (errorDetected) return reject(dataAboutError);
// When the task is finished
resolve(theResult);
});
};

/* This is the pattern that we use when promisfying an asynchronous function
that use callbacks */

function readFile(filename) {
return new Promise((resolve, reject) => {
fs.readFile(filename, (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
};

asyncFunction(ar1, arg2)
.then(result) => {
// the operation succeeded
// do somethgin with the result
return newResult;
})
.catch(err => {
//an error occurred
});

sample

Undestanding of function async

The async library is a collection of functions for various asynchronous patterns.
It was originally completely implemented around the callback function paradigm.
Async is a utility module which provides straight-forward, powwerful functions for working with asynchronous javaScipt.
It can be used for Node.js or even used directly for browser.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// use with Node-style callbacks...
var async = require("async");
// implement Async call in loop
var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
var configs = {};

async.forEachOf(obj, (value, key, callback) => {
fs.readFile(__dirname + value, "utf8", (err, data) => {
if(err) return callback(err);
try {
configs[key] = JSON.parse(data); //converting data into object
} catch (e) {
return callback(e);
}
callback();
});
}, err => {
if (err) console.error(err.message);
// configs is now a map(calls function in a array, in order) of JSON data
doSomethingWith(configs);
});
1
2
3
4
5
6
7
8
9
10
11
var async = require("async");

// ...or ES2017 async functions
async.mapLimit(urls, 5, async function(url) {
const response = await fetch(url)
return response.body
}, (err, results) => {
if (err) throw err
// results is now an array of the response bodies
console.log(results)
})