Introduction

Software Engineer is long journey where one of us need to learn and work so hard to pursue. I'm not a person with good memory, working with variety of languages sometimes confused me with their syntax.

So I decided to create my own tech book to note down and summarize all knowledge that I get over the years.

Python: Data Types

↑ top




set


frozenset

fruits = {"Apple", "Banana", "Cherry", "Apple", "Kiwi"}
basket = frozenset(fruits)

print('Unique elements:', basket)

# Add new fruit throws an error!
basket.add("Orange")
print('After adding new element:', basket)

# AttributeError: 'frozenset' object has no attribute 'add'

frozenset is immutable data type and can't add new element


set

fruits = {"Apple", "Banana", "Cherry", "Apple", "Kiwi"}

print('Unique elements:', fruits)

# Add new fruit
fruits.add("Orange")
print('After adding new element:', fruits)

# Size of the set
print('Size of the set:', len(fruits))

>> Size of the set: 7

↑ top




sequence

  • tuple is immutable, list is mutable
  • tuple is faster and consume less memory than list
  • should not define a list in tuple
  • use array to constraint the type of elements stored in the list

tuple

# code to test that tuples are immutable

tuple = (0, 1, 2, 3)
tuple[0] = 4
print(tuple)

# TypeError: 'tuple' object does not support item assignment

tuple is immutable data type and can't add new element


list

# Creating a List with
# the use of Numbers
# code to test that tuples are mutable
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("Original list ", List)

List[3] = 77
print("Example to show mutablity ", List)

# Original list  [1, 2, 4, 4, 3, 3, 3, 6, 5]
# Example to show mutablity  [1, 2, 4, 77, 3, 3, 3, 6, 5]


array

# importing "array" for array creations
import array as arr

# creating an array with integer type
a = arr.array('i', [1, 2, 3])

# creating an array with double type
b = arr.array('d', [2.5, 3.2, 3.3])


↑ top




mapping

  • OrderedDict is a subclass of dict object
  • it maintains the orders of keys as inserted

dict

#Create normal dict
my_dict = {}
my_dict['AA'] = 11
my_dict['BB'] = 22
my_dict['CC'] = 33
my_dict['DD'] = 44

for item in my_dict.items():
   print(item)

# ('AA', 11)
# ('CC', 33)
# ('BB', 22)
# ('DD', 44)


OrderedDict

import collections

#Create ordered dict
my_ord_dict = collections.OrderedDict()
my_ord_dict['AA'] = 11
my_ord_dict['BB'] = 22
my_ord_dict['CC'] = 33
my_ord_dict['DD'] = 44

for item in my_ord_dict.items():
   print(item)

# ('AA', 11)
# ('BB', 22)
# ('CC', 33)
# ('DD', 44)


↑ top




Python: String

↑ top




string interpolation


without format

variable = 'World'
output = f'Hello {variable}!'

# Hello World


using format

template1 = 'Hello {}!'
output1 = template1.format('World')

template2 = 'Hello {variable}!'
output2 = template2.format(variable='World')

template3 = 'Hello {0}!'
output3 = template3.format('World')

# Hello World


↑ top




string concatenation


without format

variable = 'World'
output = f'Hello {variable}!'

# Hello World


using format

template1 = 'Hello {}!'
output1 = template1.format('World')

template2 = 'Hello {variable}!'
output2 = template2.format(variable='World')

template3 = 'Hello {0}!'
output3 = template3.format('World')

# Hello World


↑ top




Python: List

↑ top




string interpolation


without format

variable = 'World'
output = f'Hello {variable}!'

# Hello World


using format

template1 = 'Hello {}!'
output1 = template1.format('World')

template2 = 'Hello {variable}!'
output2 = template2.format(variable='World')

template3 = 'Hello {0}!'
output3 = template3.format('World')

# Hello World


↑ top




Python: OOP

↑ top




self vs cls


  • cls belongs to the class (static method)
  • self refer to instance of class

↑ top




__call__


this method enables to write classes where the instances behave like functions and can be called like a function

class Example:
    def __init__(self):
        print("Instance Created")

    # Defining __call__ method
    def __call__(self):
        print("Instance is called via special method")

# Instance created
e = Example()

# __call__ method will be called
e()

# Instance Created
# Instance is called via special method

↑ top




Javascript: String

↑ top




string interpolation


const variable = "World";
const output = `Hello ${variable}!`;
console.log(output);

// Hello World


↑ top




Javascript: Design Pattern

↑ top




module pattern


In JavaScript, the Module pattern is used to further emulate the concept of classes in such a way that we’re able to include both public/private methods


var personModule = (function () {

    var firstName;
    var lastName;

    return {
        setName(f, l) {
            firstName = f;
            lastName = l;
        },
        getName() {
            return firstName + " " + lastName;
        }
    }

})();

personModule.setName('akash', 'pal')
personModule.getName() //"akash pal"


↑ top




revealing module pattern



var personModule = (function(){
  
  var firstName;
  var lastName;
  
  function setName(f,l){
    firstName = f;
    lastName = l;
  }
  
  function getName(){
    return firstName + " " + lastName;
  }
  
  return{
    setName:setName,
    getName:getName
  }
  
})();

personModule.setName('akash','pal');
personModule.getName(); //"akash pal"


↑ top




Typescript: Best Practices

↑ top




any vs unknown

  • use unknown instead in case don't know type of variable
interface IUser {
    id: number;
    name: string;
}

interface IAdminUser extends IUser{
    token: string;
}

function isAdminUser(object: unknown): object is IAdminUser {
  if (object !== null && typeof object === "object") {
    return "token" in object;
  }

  return false;
}

async function fetchUser() {
    const response = await fetch('https://api');
    
    // bad
    const badUser: any = await response.json();
    
    // good
    const goodUser: unknown = await response.json();
}

↑ top




Typescript: Generic

↑ top




default type parameter

there is no longer a need to pass a type to the ResultType generic parameter when calling the fetchApi function

async function fetchApi<ResultType = Record<string, any>>(path: string): Promise<ResultType> {
    const response = await fetch(`https://example.com/api${path}`);
    return response.json();
}

const data = await fetchApi('/users')

console.log(data.a)

↑ top




type parameter constraints

To make sure the calling code is always going to pass an object to your function

function stringifyObjectKeyValues<T extends Record<string, any>>(obj: T) {
    return Object.keys(obj).reduce((acc, key) => ({
        ...acc,
        [key]: JSON.stringify(obj[key])
    }), {} as { [K in keyof T]: string })
}

↑ top




Typescript: Type

↑ top




omit

to create a new type to exclude the specific property from existing type

interface Person {
  name: string;
  age: number;
  address: string;
}

// Exclude the 'address' property from the 'Person' type
type PersonWithoutAddress = Omit<Person, 'address'>;

// Usage
const person: PersonWithoutAddress = {
  name: 'John',
  age: 30,
};

↑ top




pick

to create a new type by picking the specific property from existing type

interface Person {
  name: string;
  age: number;
  email: string;
}

type PersonNameAndAge = Pick<Person, 'name' | 'age'>;

const person: PersonNameAndAge = {
  name: 'John',
  age: 30,
};

↑ top




parameters

a utility to obtain the parameter types of a function or constructor as a tuple type

function greet(name: string, age: number): void {
  console.log(`Hello, ${name}! You are ${age} years old.`);
}

type GreetParams = Parameters<typeof greet>; // [string, number]

const params: GreetParams = ['Alice', 25];
greet(...params); // Hello, Alice! You are 25 years old.

↑ top




returnType

a utility to extracts and represents the return type of function

function greet(): string {
  return 'Hello!';
}

type GreetReturnType = ReturnType<typeof greet>;
// The type GreetReturnType is inferred as string

const greeting: GreetReturnType = greet();
// The variable greeting is inferred as string

function add(a: number, b: number): number {
  return a + b;
}

type AddReturnType = ReturnType<typeof add>;
// The type AddReturnType is inferred as number

const sum: AddReturnType = add(5, 3);
// The variable sum is inferred as number

↑ top




Vue: Vuex

↑ top




vuex-flow

Vuex-flow

↑ top




PHP: String

↑ top




string interpolation


without printf

$variable = "World";
$output = `Hello ${variable}!`;
echo $output

# Hello World


using printf

$variable = "World";
$template = "Hello %s!";
$output = printf(template, $variable);
echo $output

# Hello World


↑ top




tree

tree

tree

tree

tree

tree

tree

Encryption

encoding transforms data into another format using a schema that publicly available so that it can easily be revered

encryption transforms data into another format in such a way that only specific individual can reverse the transformation


encryption techniques

  • symmetric encryption: private-key cryptography
  • asymmetric encryption: public-key cryptography

asymmetric encryption

  • private key to kept secret
  • public key to be shared

asymmetric algorithm

  • AES
  • DES
  • RSA

asymmetric use case

  • SSH
  • TLS
  • Bitcoin

↑ top




JWT

jwt is a string made up of three parts, separated by dots, and serialized using base64

header (token type, algorithm used to sign the token)
payload (iss, exp, sub, aud)
signature

↑ top




jwt types


jwt has two kinds of token:

  • id token used for application
  • access token used for protect api

↑ top




jwt authentication


  • OAuth 2.0 is authorization framework and uses Access Token and Refresh Token.
  • OpenID Connect(ODDC) is identity protocol to performs user authentication. OIDC uses ID Tokens

invalidate token:

  • creating a blacklist: using redis to create blacklist token
  • introduce refresh token

refresh token can be stored in local storage

how to secure refresh token:

  • Automatic Reuse Detection
  • Introduce lifetime expiration ( absolute lifetime & inactivity lifetime)

Steps to validate access token:

  • perform standard JWT validation
  • verify token audience claims
  • verify permission (scopes)

↑ top




Command

↑ top




general command

eval command


This is equivalent to running the command ls -l directly on the command line.

x="ls -l"
eval $x

source command


source command is used to execute commands from a script file in the current shell environment, rather than starting a new shell, so any changes made to the environment will persist after the script is finished running.

source myscript.sh

similar ways to execute shell script file:

  • sh scriptname.sh : This method will run the script regardless of the user's default shell
  • bash scriptname.sh : This command runs the script using the bash shell
  • ./scriptname.sh : need to provide executed permission for the script (chmod +x scriptname.sh)
  • ./scriptname : if the script has execute permission and it has the appropriate shebang line, you can run it just by typing its name

↑ top




mac os


  • open -a application: open app on mac by terminal
  • lauchctl [stop|list]: stop or list out all running services

↑ top




networking


  • netstat -a: list down all listening port
  • telnet [ip:port]: ping ip with specified port

↑ top