🤺︎ Hi there 👋 Trying what I can !

A Pragmatic software developer.

Curiosità is defined by Micheal J. Geib and Leonardo as “an insatiable curious approach to life and an unrelenting quest for continuous learning.”


Unwinding is hot no-sugar coffee!

Technologies I can’t believe exists today: trpc, hasura and onegraph (graphiql-explorer).

echo Hello world! > /dev/null
cat /dev/null

Benchmarks: React Project Size

# 10 Jul, 2022
vite: 41mb
bun: 70mb
cna: 187mb
cra: 335mb

Jump Starters

Click here




// For example the following text would act as link in vscode: file://./scripts/deployKryptoBird.js

Event Hosting platform

Deleting nested modules?

alias findNodeModules='sudo find . -name 'node_modules' -type d -prune'
alias deleteNestedNodeModules="sudo find . -name 'node_modules' -type d -prune -exec rm -rf '{}' +"

Creating MRE’s

Most Amaizng graphql client library

insomnia vs. postman

What is LOC?


what is sloc?


Add github comment system to your blog

React Giscus Component: Click here



Looks like a good cache library


Get name and emails of all the authors of a git repo from the repository history

git log -s --format='%an %ae'
# %an is for author name
# %ae is for author email
# Read whole docs @
# Inspiration:

Fix cors errors without fixing backend in chrome

Chrome Extension: CORS Unblock

To test if cors get unblocked you can check via that page:




Google maps apis is paid



Tip: Using github to edit repo files on mobile

Use chrome in desktop mode and then you’ll be able to add pictures as well, yo!

react native vs. flutter

Amazing article explaining nextjs’s middleware and netflify’s edge html rewriting

Learn maps and sets

Source: Kyle

Maps are for objects, and sets are for arrays.


Sets store unique values only:

image image image

Array.slice returns a shallow copy: Remeber it



website performance analytics





cli apps with react?






mutation observer

Generating real ssl certificate using letsencrypt on cli


using %s, %f, %d in javascipt



making insecure requests with postman or curl

Case Scenario: Say you are running a flask server via:

flask run --cert=adhoc --host=

so when if try to request from a curl or postman you wont’ see any response bcoz both of these (curl / postman) are not enabled for secure requests.

For curl you can make use ok -k option:

curl -k

For postman:


We can have multiple developer tools open for a single tab as well


This is such a lifesaver from github


Why postgres/mongodb over firebase #jimmy_chae?

Firebase cons: ~Sahil (points I have currently in my mind)



module system nodejs





Browser developer tools


Files and blobs(binary object) in javascript

// text to binary object
const someData = new Blob(["hello world"])
// files
const readmeFile = new File('Run node src/index.js for a friendly greeting.', 'README.txt', { type: 'text/plain' })
const sourceFile = new File('console.log("hello, world")', 'src/index.js', { type: 'text/javascript' })

Filtering merged PR’s on a github repo


ml in action


Source Code for rock-paper-scissor identification code:

Sample try out project on


Q. How does flatten work in Keras ?


Color Depth: @wikipedia

Deal with race conditions easily

let flag = true

setTimeout(() => {
	flag = false
}, 500)

void (async function () {
	await new Promise(res => setTimeout(res, 1_000))
	console.log('Final:', flag) // Output: false

flakey testing

A flaky test is an analysis of web application code that fails to produce the same result each time the same analysis is run.

Docs made easy used to make solidity docs.

futter market demand

learn js classes

class Animal {
	static belly = []
	eat() {
let a = new Animal()

console.log(Animal.belly[0]) // food

E.g., 2

let bear = {
	sound: 'roar',
	roar() {

bear.sound = 'grunt'
let bearSound = bear.roar
bearSound() // undefined
bear.roar() // grunt

what is e+ powers?

People in this earth is 8 Billion (8.0e+09)

what are opnionated softwares/frameworks

tldr; If a framework is opinionated, it lock or guides you into their way of doing things.

online timer apps

void usage in javascript



Source of below code: MDN

const output = void 1;
// expected output: undefined

void console.log('expression evaluated');
// expected output: "expression evaluated"

void function iife() {
  console.log('iife is executed');
// expected output: iife is executed

void function test() {
  console.log('test function executed');
try {
} catch (e) {
  console.log('test function is not defined');
  // expected output: "test function is not defined"

bandwidth and throughput?



unsigned means?

Dictionary - unsigned : not having a plus or minus sign, or a bit representing this.

Unsigned Integers (often called “uints”) are just like integers (whole numbers) but have the property that they don’t have a + or - sign associated with them. Thus they are always non-negative (zero or positive). We use uint’s when we know the value we are counting will always be non-negative.

#scroll #scrollto #scrollintoview

scrollTo - MDN scrollIntoView - MDN

s1 s2

Stakoverflows: 1

lastChild vs. lastElementChild

tldr; Use lastElementChild to get html node but use lastChild if you may want the some plain text or comment that is there in the last in that element.


How a system can answer some quetion about working of its own function?

Ans. If its implements a goal tree then it can! Source


Guide: Click here

Tldr: Press ctrl+shift+p and command starting with “Confgiure Recommended Extension..” and now use ctrl+space toggle up the possible extension inputs from your currently installed extension. YO!!

casting laptop screent to tv (chromecast)




Article -

Article -

Don’t abuse arrow functions in 2022

Execute code on tab close

window.addEventListener("beforeunload", (e) => {
  e.returnValue = ""; // this value has to be other than null and undefined.

// for react, use reference:
// amazing blogger:

So when you try to close tab, browser will ask once again like that -


@mdn docs:


builtin assertion library - nodjs


const { deepStrictEqual:dse } = require('assert');
let a = {x: 10, y: 10}
let b = {x: 10, z: 20}

Thats how colors work in nodejs

FYI; In node repl mode, src.

Finally, the optional argument colorize is a boolean that adds ANSI escape codes to the string output. When logged to a terminal window, it should be pretty printed with colors. ~ Same above source page of nodejs docs.


Named arguments for self knowledge - Javascript

let z = (a,b) => console.log({a,b})

z(first=10, second=20) // {a: 10, b: 20}
z(i=10, j=20) // {a: 10, b: 20}

Calling one express route from another route


I added answer to that question as well, here:

Hilarious and Feels stupid to think of this though now.

// @ts-nocheck
const app = require('express')()
const axios = require('axios')
const log = console.log

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

const listener = app.listen(async () => {
	const url = 'http://localhost:' + listener.address().port // IF you are using static port value you do not need `listener.address().port` and simply provide that port value here instead.

	let response = await axios.get(url)
	log('GOT DATA IN RESPONSE:', // yoy

If you are using it general case i.e., STATIC PORT value, you can do it like:

// @ts-nocheck
const app = require('express')()
const axios = require('axios')
const log = console.log

const PORT = 3000
const URL = 'http://localhost:' + PORT
const apiPath = (path) => URL + path

app.get('/a', (req, res) => {

app.listen(PORT, async () => {
	let response = await axios.get(apiPath('/a'))
}) is better than === ? tldr Yes, a little bit.



what venv in python?

chmod +x
python -m venv env
source env/bin/activate
pip install -r requirements.txt

## thats how u use environment variables in python
email = os.environ['EMAIL']
password = os.environ['PASSWORD']

Above is a common setup to start start a python project( that is a flask project though). But in above commands,

# creates the virtualenv, you need to run that only once, its like `node_modules` in node. Source:
python -m venv env

# source (activate) the virtual env in current bash shell
source env/bin/activate



validation in javascript

If using typescript: (9k*)

If using javascript: (17.6k*)

parseInt() vs. Number()

console.log(Number(22.1)) // 22.1
console.log(parseInt(22.1)) // 22

Netlify acquired onegraph

Date: 17 Nov, 2021 - Click here

object to params ?

let a = {car: 10, bar: 20}

// src:
let objectToParams = (obj) => Object.entries(obj).map(([key, val]) => `${key}=${val}`).join('&');

objectToParams(a) // 'car=10&bar=20'

toJSON in JSON.stringify function ?

Read messages and read contacts with pwa


what is it to sleep @5am

mimic your voice with system ?

~ Varun mayy, you can make text to sound of your own voice with that.

All-in-one audio & video editing, as easy as a doc.

Posthog - an opensource analytical tool


Used by Varun Mayyas he tells in this video.

Visit at:

ui sources - has all the screenshots of all the apps

~Varun mayya’s frined, src: here-timestamped

Reducing apk size of react-native apps?

A better and easy way to setup github credentials on local git

Source - Docs - Authenticating with GitHub from Git


Github opensource docs


Source: Click here


Unicode symbols Website

Anatomy of html documents by mdn

Labelled statement in javascript



Awesome ni package mangager :LOL:

Github’s Official .gitignore files for different enviornments

Whats your ping?


Insert at in arrays in js

var arr = []
arr[0] = 'Jani'
arr[1] = 'Hege'
arr[2] = 'Stale'
arr[3] = 'Kai Jim'
arr[4] = 'Borge'

console.log(arr) // Jani,Hege,Stale,Kai Jim,Borge
arr.splice(2, 0, 'Lene')
console.log(arr) // Jani,Hege,Lene,Stale,Kai Jim,Borge

Community version of dalle 1 (free to use completely)

Problem with token based authentication



React server components(still in development though) is used by Hydrogen developers(a shopify framework)


Amazing guide on testing containing objects in an array, works 100%


test('LEARN: array containing an object', () => {
	// src:
	const expected = {name: 'sahil'}
	const received = [{name: 'sahil', lastname: 'rajput'}, {otherObjectsAnyShape: 'Rohit'}]

	// Src:

Arranging date named objects in alphabetical order?

A good exerpt on that problem.

Save the migration code in the file migrations/20211209_00_initialize_notes_and_users.js. Migration file names should always be named alphabetically when created so that previous changes are always before newer changes. One good way to achieve this order is to start the migration file name with the date and a sequence number.

Did you know “We can get the number of parameters defined in its function definition ?

((a) => {}).length // 1
((a, b) => {}).length // 2
((a, b, c) => {}).length //3

Expressjs uses this to identify if the callback you specified has two or three OR four params in its definition and based on that it judges if the middles should be treated as a errorHandler or simple middleware. Yikes!

chai-http is like supertest

chaijs is assertion library like assert + http testing library like supertest

Finally Intellgence as a service goona be paid


Scaling console.logs?

You can print the filename and linenumber of the console.log very easily using some stacktrace hack.

What I made out of this? Click here

# learn:
# src (<< this answer has another link of stackoverflow answer i.e., src of this answer:
# src:

Creating .d.ts files in js/ts ?

Its a myth coz tsc generates this for its own use, but you can write your own for vanilla js projects typechecking as well using // @ts-check comment on top of .js files

Click here

Leadership Principles ~ Sequoya’s memo (src)

vscode cli options


Figjam for online flowcharts/diagramming



In nodejs: We have util.promisify buitin method basically takes a function as an input that follows the common Node.js callback style, i.e., with a (err, value) and returns a version of the same that returns a promise instead of a callback.

import { readFile } from 'node:fs';

let callback =  (err, data) => {
  if (err) throw err;

// Callback Usage:
readFile('/etc/passwd', callback); // OR 
readFile('/etc/passwd', 'utf8', callback);

// Making use of util.promisify
const util = require('node:util');

// Reading the file using a promise & printing its text
const readFileSync = util.promisify(fs.readFile);
readFileSync('./promisify.js', 'utf8') // Reading the same file
   .then((text) => {
// Printing error if any
   .catch((err) => {
      console.log('Error', err);

Why tdd with backend development?

Structure for expressjs + sequelize setup (multi models + controllers setup)

Whatsapp chatbots made easy!

How to Create & Test your WhatsApp Chatbot (No Coding)

Pwa Install prompt?



Most of times apps can be pwa @ playstore:



This is pretty solid(coz it can generate apk{for playstore distributio}, appix{for windows stores} and ios packages as well for ios store ditribution, BUT USING MY OWN WAY OF APK DEVELOPMENT IS BEST ~ IMO ~ SAHIL): image

Using abort controller with react!



FYI-Using builtin abort controller in react-query


set input as numeric in forms?

Source: css-tricks

<input inputmode="numeric" type="text" name="creditcard">

Add a npm script via cli


npm set-script prepare "husky install"

Handling spa with github pages

Source: Stackoverflow Answer, also from github - Github 404 Docs

Demo:, Github:

tldr; 404.htm file: Click here.

And script to be added in index.html file

Source: here

    <script type="text/javascript">
      // Single Page Apps for GitHub Pages
      // MIT License
      // This script checks to see if a redirect is present in the query string,
      // converts it back into the correct url and adds it to the
      // browser's history using window.history.replaceState(...),
      // which won't cause the browser to attempt to load the new url.
      // When the single page app is loaded further down in this file,
      // the correct url will be waiting in the browser's history for
      // the single page app to route accordingly.
      (function(l) {
        if ([1] === '/' ) {
          var decoded ='&').map(function(s) { 
            return s.replace(/~and~/g, '&')
          window.history.replaceState(null, null,
              l.pathname.slice(0, -1) + decoded + l.hash

Proxy and base-code-structure for any possible server-functions library


const target = {};

const handler3 = {
  get(target, prop, receiver) {
    return () => console.log('fun?:', prop)

const proxy3 = new Proxy(target, handler3);

// VM583:5 fun?: a

// VM583:5 fun?: b

Create live expressions


This is magically amazing!!

magic code for edge caching (setting cache headers)

Source:, Code @


Learn: Endpoint caching is possible for get requests only (trpc uses get requests for all requests) and graphql uses post request for all requests so it makes it hard to cache any endpoint request.



What is save-exact in .npmrc ?



write on screen and copy/save the image

Press prtscr and press ctrl+a to select all the area on screen and now you can use pencil(P), arrow(A), line(D) and more tools in flameshot.

chalk usage

Struck at chalk - Error [ERR_REQUIRE_ESM]: require() of ES Module ??


npm uninstall chalk
npm i chalk@4.1.2

now you can use:

const chalk = require('chalk');
console.log('Hello world!')); 


how to do 10k concurrent or millions of RPS (Requests Per Second)



Learn about express-async-errors npm package

Go to

Complete command line solution for nodejs


22.7k Github Stars, It has more than 73m weekly downloads(from

Make you router page available on the public ip address

You can do this by mapping port of router ip (probably to public ip in your router settings.

Using custom environment files i.e., or .env.test

We use them by definig their file path in package.json file. Below project is here. Look for dev and dev2 scripts below and their respective comments as well.


FYI: To make the env file provided as argument is implemented via dotenv like this:


created flash-runner npm package

Browse @

Github @

npm i flash-runner

blockchain ?

programming, scripting, and markup languages?

collaborative work management tool


recent comment backup

Originally posted here.

I am pretty noob js developer but I made something up that solves* this issue. And please don’t critize I just mean to present a solution for curious people by this comment.

* means solving with my own test runner not with jest runner.

flash is my test runner I created few days back, to test this you need below setup:

git clone
cd flash && npm link
cd ..

git clone
cd learning-monogo-and-mongoosejs/mongoosejs-with-hot-flash
npm i && npm link flash
npm start

Now if you edit code in code.js, then you database connection won’t be thrown away but reused thus giving you a lightning fast TDD experience with no connection loosing on running tests while in watch mode.

Why and how I love and hate jest ?

Love: Bcoz its assertion i.e., expect and expect’s docs is open source. So this allows me to use their assertions in my own test runner library. Yikes!


npm i expect
const {expect} = require('expect')
expect('1').toBe('2') // throws error just like jest does!

Hate: Jest’s test runner has no capability to share values and module between tests suites in watch mode. Issue closed here. But it seems that work is going on this issue here.

Q. Anyway what are mockig really useful for like this library nock ? ~ Sahil

What is a/ and b/ in git diff command?



a means before and b means after. You can remember it like when going from a -> b i.e., in chronogical manner ~Sahil.

How come a library like tailwindcss have 56.6 stars on github ?

Find my own demo app @

Its revolutional for me personally!

Testing react apps with jest and react-testing-library (or enzyme)


The one stop solution for the confusion b/w localStorage vs. cookies decision in your website!

Source: . Wanna read about cors from same author ?. Mdn - Restrict access to cookies.

image cookes looks like this


Created a clone of lowdb

Browse @


chokidar has also a cli version

Used by: - A test runnder by typicode.

lowdb rocks (a tool to manage localStorage most beautiful api)


This library is from *typicode who is also creator of json-server, husky, jsonplaceholder and xv and all all of them are his github.*

Find out @

Also, it is also useful with nodejs as it will write to json files on updating the data, yikes!

Yes you can change a variable’s value in the browser debugger as well

TESTED: Works 100%


Also works via terminal as well:


Documentation Generator in Javascript

This is used by kubernetes-client to generated docs for them @

Default values for functions

function a(c = 10) {
	return c

// Output: null

// Output: 10

Ml resources, neural networks

Make apk from a website now!

Deploy website to playstore-

  1. Hybrid web view app using Ionic (but downside is that we would need to )
  2. Use TWA (trusted web activites) REFER MY OWN REPO TO SEE THIS AWESOME WAY.


Startup checkout?

global won’t work good in react project outside of components (see the codesandbox to understand that!)



FYI: Learn about globalThis:

Ngrok docs

What is global in nodejs?

YES, global variables are supported in nodejs!! So this facilitates us to define variables, fucntion in one place and use them in different files without using module.exports at all. Yikes!

global.studentName = 'Kyle'

console.log(`Hello, ${ global.studentName }!`)
// Hello, Kyle!

console.log(`Hello, ${ studentName }!`)
// Hello, Kyle!

// src:

Also you can now access studentName in any module which is loaded after after we define global.studentName variable.

LEARN: nodejs docs:

LEARN: I used this global in my own testing library in tihs file:

Sequnetial execution of aysnc calls


Tags: #Parallel execution, #sequential execution, etc.

Why Flameshot?

live reload browser in sync with backend as well

What is a=b=c in code?

let a,b,c
a = b = c = 10
// Output: 10 10 10

Checkout my login flow diagram with mermaidjs

Find here.

React dev tools show react hooks state!


Yes its all there, but that changes in react state are reflected with a delay of like 500ms IMO ~Sahil.

Git submodules

Adding a github submodule

git submodule add "github_url" directory_path

How to fix submodule shit..?

Problem: If you accidentally did a git add . in any of your github repo where you had some nested repository, then git automatically adds that repository as a submodule to your existing (parent repository) and then you don’t get a live link in your github repo page.

How to FIX

Simply move your nested git repo elsewhere and do a commit to clean it for a while, and then move back the nestedGitRepo back to where it was and add it in proper way, followed by git commit. It looks like that:

mv someNestedGitRepo ../
git add . && git commit -m "Remove submodule."
# Now, move back the nestedGitRepo back to current repo and add it in proper way!
mv ../someNestedRepo .
git submodule add "github_url" directory_path
# Now, you get to commit, and its done!
git add . && git commit -m Fix submodule.

Sources for git submodules

To clone a git repo with all its nested submodules 🚴︎ 🚴︎

Just use

# gclWithSubmodules is aliased to `git clone --recurse-submodules -j8'

edited by cacher.

Using themes with github pages (via jekyll)

Re-add a revert commit?


You can simply revert the revert commit to undo the revert via git revert <revertCommitShaHere>. ~Sahil

What is NAT in vmware, virtualbox and kvm?

Network Address Translation (NAT) is the simplest way of accessing an external network from a virtual machine. Usually, it does not require any configuration on the host network and guest system. For this reason, it is the default networking mode in Oracle VM VirtualBox.

Source: Docs - Virtual Box

Learn programming through test driven process

Go (17.4k stars):

Go by example:

Official Go tour

Official Go Playground:

Source: Hackerrank article

Source: [Golang Tutorial for Beginners Full Go Course by TechWorld with Nana]( (An amazing video to watch for learning all the stuff of go including packaging/module stuff).


Setting size of image in github markdown


![]( =250x250)
![]( | width=100)
<img src="" data-canonical-src="" width="200" height="400" />

kvm wins over virtual box in software market and coz of its performance and robustness

Source: Q/A

ssh to virt-manager’s running container

**FYI: You can add bluetooth device in your kvm container very easily by going to settings and click “Add hardware” and then follow from there to “USB Host Device” option and choose your bluetooth device there. Yo!


Update (i.e., pull) a submodule in a git repo


git submodule update

why shebang is called shebang ?


forever a npm package to ensure ensure that a script is running forever

Random number generation ?


Math Stackexchange:

express js loop holes ?

	return res.status(200).json('ok') // FYI: This is valid json though!
// ^^^^^^^^^^^^^^ this actually sends status code 304 IDK why on earth!

	return res.status(200).send('ok') // FYI: This is valid json though!
// ^^^^^^^^^^^^^^ this actually sends status code 200.

vertical and horizontal pod scaling, what kind of constratins to consider?

# usefule text from:
# Scaling
Scaling can be either horizontal scaling or vertical scaling. Vertical scaling is the act of increasing resources available to a pod or a node. Horizontal scaling is what we most often mean when talking about scaling, increasing the number of pods or nodes. We'll focus on horizontal scaling.

There are multiple reasons for wanting to scale an application. The most common reason is that the number of requests an application receives exceeds the number of requests that can be processed. Limitations are often either the amount of requests that a framework is intended to handle or the actual CPU or RAM.

Figuring out autoscaling with HorizontalPodAutoscalers can be one of the more challening tasks. Choosing which resources to look at and when to scale is not easy. In our case, we only stress the CPU. But your applications may need to scale based on, and take into consideration, a number of resources e.g. network, disk or memory.

Difference between |, |>, > and >- in yaml ?

Key1: >
  Line 1
  LIne 2

# (no newline character after in the end)
Key2: >-
  Line 1
  Line 2

Key3: |
  Line 1
  LINE 2

#  (no newline character after in the end)
Key4: |-
  Line 1
  LINE 2

is converted to json

   "Key1": "Line 1 LIne 2\n",
   "Key2": "Line 1 Line 2",
   "Key3": "Line 1\nLINE 2\n",
   "Key4": "Line 1\nLINE 2"


Proof of convertion trial @

Using select menus in bash

Swithing to terminal to run a bash script or npm command very often?

Consider using a .vscode/tasks.json file (you can autogenerate this file with vscode very easily). I personally use ctrl+alt+r keybinding to launch run tasks, yo!!

	"version": "2.0.0",
	"tasks": [
			"type": "shell",
			// "command": "pwd", // for testing.
			"command": "./fso-part13/curls/",
			"label": "post a note ~Sahil"
			"type": "shell",
			"command": "./fso-part13/curls/",
			"label": "Get a note ~Sahil"
			"type": "shell",
			"command": "./fso-part13/curls/",
			"label": "Reset notes table! ~Sahil"

json to xml converter

What is canaray releases ?

Canary release is a technique to reduce the risk of introducing a new software version in production by slowly rolling out the change to a small subset of users before rolling it out to the entire infrastructure and making it available to everybody.


What is reverse psychology?

retrieval practise

serverless and utility computing




react-router, react-dom or react-router-dom, what the difference?

You can checkout that react-router is a dependency of react-router-dom @ npm’s package page.

FYI: react-router is also a dependency of react-router-native.

react-dom: This package serves as the entry point to the DOM and server renderers for React. It is intended to be paired with the generic React package, which is shipped as react to npm.

what is env cli ?

Linked quest: What is #/usr/bin/env bash or #/usr/bin/env node shebang in various scripts ?

From man env in terminal, I found:

Ans. env - run a program in a modified environment.

type env
# Output:
# env is hashed (/usr/bin/env)

env --help
# Output:
# Usage: env [OPTION]... [-] [NAME=VALUE]... [COMMAND [ARG]...]
# Set each NAME to VALUE in the environment and run COMMAND.
# Mandatory arguments to long options are mandatory for short options too.
#   -i, --ignore-environment  start with an empty environment
#   -0, --null           end each output line with NUL, not newline
#   -u, --unset=NAME     remove variable from the environment
#   -C, --chdir=DIR      change working directory to DIR
#   -S, --split-string=S  process and split S into separate arguments;
#                         used to pass multiple arguments on shebang lines
#       --block-signal[=SIG]    block delivery of SIG signal(s) to COMMAND
#       --default-signal[=SIG]  reset handling of SIG signal(s) to the default
#       --ignore-signal[=SIG]   set handling of SIG signal(s) to do nothing
#       --list-signal-handling  list non default signal handling to stderr
#   -v, --debug          print verbose information for each processing step
#       --help     display this help and exit
#       --version  output version information and exit
# A mere - implies -i.  If no COMMAND, print the resulting environment.
# SIG may be a signal name like 'PIPE', or a signal number like '13'.
# Without SIG, all known signals are included.  Multiple signals can be
# comma-separated.
# GNU coreutils online help: <>
# Full documentation <>
# or available locally via: info '(coreutils) env invocation'

man env
# Output: manual pages!

kubernetes hierarchy

Kubernetes cluster is a group of nodes!

A node can have a list of deployments.

A deployment controls a list of pods.

A pod has a list of containers.

Replicas (.spec.replicas) is no. of replicated pod which will be created.

A kubelet is an agent that runs on each node in the cluster. It makes sure that containers are running in a pod.

what? helps to pick up abnormal activity say if people try to scrap off content from fb, they used this esimation to detect that and ban it.


memcache used by fb earlier

flashcards website


Playstore App (free services): Click here

You may login with google simply. It has a playstore app as well.

send a file with express route

downloading image with axios


bus factor

From Wikipedia, the free encyclopedia

The bus factor is a measurement of the risk resulting from information and capabilities not being shared among team members, derived from the phrase “in case they get hit by a bus”. It is also known as the bus problem, lottery factor, truck factor,[1] bus/truck number, or lorry factor.

In a sentence (from devopsiwthkubernetes): If your files don’t tell Kubernetes and your team what the state should be and instead you run commands that edit the state you are just lowering the bus factor for your cluster and application.

Why do one need a mock testing? : Click here to know.

Getting automated “Product experience insights” using

(free to use)no-Code Website Builder: The Webflow Designer lets you build any website you can imagine with the full power of HTML, CSS, and Javascript in a VISUAL CANVAS. using See customer stories of webflow users.

Schedule your meets with anybody ? Ans. *A perfect solution*:

things i kept doing doing..

I have a habit of looking for the best of best of the articles, courses, blogs, books, materials that I feel sometimes is a time taking process and I don’t follow or kind of forget like the official way of doing things me or anybody else must be doing, i.e., follow official documentation of softwares, libraries, tools, standards, ie., OFFICIAL documentation. One big mistake: “Not able to find the real production ready free template of coreui in previous job is this only”.

using auto-changelog


Sample generated: Click here

Sample (this repository): Click here

Tip: You can use custom template as shown here in docs.

Add below to your package.json file and run npm run changelog to generate a file. It simply generates list of all commit to the target file simply date wise.

    "changelog": "auto-changelog -p --commit-limit false"

FYI (using -p is important else you won’t get commits in your file): -p, --package # use version from package.json as latest release

FYI: If you plan to execute it on npm version script, then you do it like (official docs of auto-changelog):

  "scripts": {
    "version": "auto-changelog -p && git add"

HENCE, whenever you run npm version patch/minor/major, your version script will be run as well. YO

monkeypatching ( or _hot fixes) ?


A monkey patch is a way for a program to extend or modify supporting system software locally (affecting only the running instance of the program).


The term monkey patch seems to have come from an earlier term, guerrilla patch, which referred to changing code sneakily – and possibly incompatibly with other such patches – at runtime. The word guerrilla, homophonous with gorilla (or nearly so), became monkey, possibly to make the patch sound less intimidating.[1]

An alternative etymology is that it refers to “monkeying about” with the code (messing with it).

Despite the name’s suggestion, the “monkey patch” is sometimes the official method of extending a program. For example, web browsers such as Firefox and Internet Explorer used to encourage this, although modern browsers (including Firefox) now have an official extensions system.

get 1 day or some weeks ago git diff


# Get diff for only today
git diff 'HEAD@{1 day ago}'

# Get diff from 3weeks back
git diff 'HEAD@{3 weeks ago}'

cool alias

alias lsg='ls -a | grep -i'
# Usage:
lsg json
lsg -E '*json'
# NOTE: quotes are important.( double quotes work as well).

cool things about kentcdodds that i didn’t know

  1. He is 11th child of his parents.
  2. He listens to podcasts at 3x speed, i.e., he started listening at 1.5x and eventually he came to this point.
  3. His most important philosophy of teaching is caring about retention! What other people learn when he teach is most important, so students don’t forget what he taught.
  4. Anybody can record a question on his website
  5. Listen to kents podcasts on his

Declarative vs. imperative

REMEMBERING SHORTFORM: HI (how->imperative), so declarative must a what.

imperative (dictionary):
1. of vital importance; crucial. E.g., "immediate action was imperative"
2. giving an authoritative command; peremptory.

1. of the nature of or making a declaration.
"declarative statements"
denoting high-level programming languages which can be used to solve problems without requiring the programmer to specify an exact procedure to be followed.

Imperative(HOW): In computer science, imperative programming is a programming paradigm that uses statements that change a program’s state. In much the same way that the imperative mood in natural languages expresses commands, an imperative program consists of commands for the computer to perform. Imperative programming focuses on describing how a program operates. The term is often used in contrast to declarative programming, which focuses on what the program should accomplish without specifying all the details of how the program should achieve the result. Exampe of imperative programming, is like we defined algorithms in explicit steps. ~Sahil

Declarative (WHAT): In computer science, declarative programming is a programming paradigm—a style of building the structure and elements of computer programs—that expresses the logic of a computation without describing its control flow. Many languages that apply this style attempt to minimize or eliminate side effects by describing what the program must accomplish in terms of the problem domain, rather than describe how to accomplish it as a sequence of the programming language primitives (the how being left up to the language’s implementation). This is in contrast with imperative programming, which implements algorithms in explicit steps.

[Google Link][1] [Yahoo link][2]

[1]: "Google - I am hovering text"
[2]: "Yahoo - I am hovering text"

# Above code will produce below html-
<a href="" title="Google - I am hovering text">Google Link</a>
<a href="" title="Yahoo - I am hovering text">Yahoo Link</a>

Dependency injection === highorder function

The very first example in below article that accepts a function as a parameter will serve as depedency injection there. Simple, yah!


expressions are awiated

let a = async () => ({data: "cool"})
console.log(await a().data) // Output: <nothing>
// The reason it doesn't work bcoz we're trying to await the data property of the promise returned by `a()`.

console.log((await a()).data) // Output: 'cool'
// works good enough!

for await syntax in js

for await (const i of [Promise.resolve(10), Promise.resolve(20), Promise.resolve(30)]){
    console.log(await i)
# Output:
# 10
# 20
# 30

filetype myFile.asciidoc


Avoiding nuclear approach to fix a git repository

Pic Credits:

BEWARE: Below give methodology will change your git history and other people’s unpushed work might break after this IMO ~Sahil.

You can remove files/folder from your git history at once using below commands.

git filter-branch --tree-filter 'rm -f <path_to_file>' HEAD
git filter-branch --tree-filter 'rm -rf <path_to_folder>' HEAD
# Source:

# Force pushing all branches in case you need that, but think TWICE before doing that:
git push origin --force --all

.editorconfig file




Sample I came across:

Git diff explained in simple terms

$ cat a
hello sahil
hello bellow

$ cat b
hello messi
hello bellow

######## DIFF SYNTAX ########
$ git diff a b
diff --git a/a b/b
index 87b4ccc..82c725d 100644
--- a/a
+++ b/b
@@ -1,2 +1,2 @@
-hello sahil
+hello messi
 hello bellow

# NOTICE: The - and + signs represents changes while going from source to target i.e., file a to file b.

$ git log --oneline
# Output:
commit5 (HEAD -> main) Add file3.txt
commit4 Add express
commit3 Add react.
commit2 Npm init the project.
commit1 Add two files.
# FYI:
commit0=4b825dc642cb6eb9a060e54bf8d69288fbee4904 # THIS LINE IS NOT SHOWN BUT IS ALWAYS COMMIT0. This is useful when you want to see diff from origin or repo.
# You can set empty variable in bash so that you can reference 0th commit easily.

######## DIFF SYNTAX ########
git diff sourceCommit [targetCommit=HEAD]

git diff commit4
# Shows changed made AFTER commit4 state.
# this can be done otherwise
git diff commit4 commmit5

git diff commitId1 commitId2
# FYI: The - and + signs represents changes while going from source(commitId1) to target(commitId2) i.e., file `a` to file `b`.
# FYI: To see the chronological changes(i.e, + and - signs with respect to real time) you must use the source commitID as commit that you made before target commitId.

# Get the detais of any commmit it'll show you the diff from /dev/null state to the final states of all the files after making the commit.
git show COMMIT_3 # Same as below
git diff commit2 COMMIT_3

git show commit1
# FYI: This shows all the details of that commit, like time/date, author and the diff with source as state before the commit and target as state after the commit.

# What does below command do? (LEAST USEFUL, unless you want to use `git diff HEAD` to view the diff for currently staged changes)
git diff commit3
# Ans: It shows all the changes made after `commit3` to the current staged area or the last commit state.

# FUN FACT: If you use
git diff <lastCommit>
# OR
git diff HEAD
# You will see diff only if you have changes in staged area. (i.e., you changed something and did ```git add .```

# NOTICE IF YOU WANT TO SEE DIFF FROM EMPTY COMMIT(source commit) TO A PARTICULAR COMMIT (target commit), you would need use something like:
# First we need to define the empty commit id (which is same for all git repositories), then we can use ```git diff```: Source:
git diff $empty commit3

#### FUN FACT : FOR THE FIRST COMMIT WE CAN ACHIEVE THE SAME (bcoz there were no changes before that commit) BY:
git diff $empty commit1
# would output same result as below command:
git show commit1

Amazing bootstrapping/scaffolding project templates


# Creates a new folder for the project
degit user/repo my-new-project

# If the second argument is omitted, the repo will be cloned to the current directory.
degit user/repo
degit user/repo#dev       # branch
degit user/repo#1234abcd  # commit hash

# To clone a specific subdirectory instead of the entire repo, just add it to the argument:
degit user/repo/subdirectory

# To clone a single file
degit sahilrajput03/sahilrajput03/

#NOTE: It is required to use explicit file name when cloning a file like we did with above.

in/of in for

let k = [1,2,3]

for (i in k){           // in means index
# Output:

for (i of k){           // of means item itself
# Output:

List all available scripts/commands from package.json file

npm run
# Source:

piping data into nodejs script..

nodemon -x 'ls -l | node test.js'
// code: Source:
var stdin = process.openStdin()

var data = ''

stdin.on('data', function (chunk) {
	data += chunk

stdin.on('end', function () {
	console.log('END DATA')
// output:
total 12
-rwxr-xr-x  1 array array  501 Feb 11 22:31
drwxr-xr-x 10 array array 4096 Jan 27 16:27 jonhoo-config
-rw-r--r--  1 array array  220 Feb 16 03:19 test.js


console.assert ?

let a = 10
let b = 20

console.assert(a == b, 'a is equal to b')
console.log('Hello, world!')

// Output:
// Assertion failed: a is equal to b
// Hello, world!

Trigger an artificial filewrite event for something like nodemon to trigger to restart server ??

Reason: Sometimes you need to make event from another process to restart the nodemon server, in that case simply touch fileWhichAlreadyExists.js command rocks to restart the nodemon server.


Source (what does touch do when file already exists?):

Directory/File structure in Github

TIP: You can download the file via wget, say:

Difference between git reset --hard and git revert <shaHere>

tl;dr: There is a very great significance of using revert instead of git reset coz it preserver all history and its important if you pushed earlier commmit to puclic and want it to be undone(remove) and still don’t want to force push then git revert rocks coz it does exactly that! Read below like for more insights!.

Source: Here.

Get back to previous commit but keep the directory as it is (i.e., only change the commit history and keep the source code as it is)

The key point is that you don’t do

git reset --hard HEAD^
# rather you should do below >>>
git reset HEAD^
# And now your source code is AS IT IS but the last commit is removed from the history.

Set github remote url directly without removing origin url

git remote set-url origin <url>

# A little verbose way?
git remote rm origin
git remote add origin <url>

# FYI: If you try to set url for origin which isn't there already then git throws error:
git remote set-url origin1 <urlHere>
# Output: error: No such remote 'origin1'

My own watch/developement service using inotifywait

Browser @

Check if jre/jdk installed on your system ?


Error lens for kids

Vscode extension.

The arguments keyword in a function:


function func1(a, b, c) {
	// expected output: 1

	// expected output: 2

	// expected output: 3

func1(1, 2, 3)

Src1, Src2

TIP: You can make use of simple json.stringify too (but it won’t be cloured ouput for different type of data, src).

const util = require("util");

let a = { b: { c: { d: { e: "f" } } } };
// Output: { b: { c: { d: [Object] } } }

console.log({ myText: "hello", myNumber: 21, myBoolean: true });

// LEARN: Print any object of any depth.
console.log(util.inspect(a, false, null, true /* enable colors */));
// Output:
// {
//     b: { c: { d: { e: 'f' } } }
// }

Install file as depencdency in nodejs

npm i my-pkg@file:./path-to-my-pkg.js

# Usage in js file:
const logMw = require("log-mw");

# Should work as esm as well IMO (didn't test yet :o  ).
import logMw from "log-mw";

Source 🍭

Custom logging middleware expressjs

Refer @ node-with-live-testing project.

// Usage:
lgMw(req) // in any route or controller.

// or use as a common middleware:

Learning file descriptions, stdin(0), stdoutput(1) and stderr(2) ?

File Descriptor Abbreviation Description
0 STDIN Standard Input
1 STDOUT Standard Output
2 STDERR Standard Error

Example 1:

#Note: We can replace > with 1> as well and it behaves exactly same.

echo I am sahil 2> output1          # One file is created.
cat output1
# Output: --no-output

echo I am sahil > output1             #  One file is created.
cat output1
# Output: I am sahil

echo I am sahil > ouput1 > ouput2     # Two files are created.
cat output1
# Ouput: --no-ouput
cat output2
# Output: I am sahil

echo I am sahil > output1 > output2 2> output3      # Three files are created.
# Output: output1  output2  output3
cat output1 # No contents.
cat output2
# Output: I am sahil
cat output3 # No contents.

echo I am sahil 2> output1 > output2 > output3        # Three files are created.
# Output: output1  output2  output3
cat output1 # No contents.
cat output2 # No contents.
cat output3
# Output: I am sahil

Example 2:

wc doesntexist.txt > output                   # Output: ```cat ouput``` prints nothing.
wc doesntexist.txt 2> output                  # Output: ```cat ouput``` prints ```wc: does: No such file or directory```

wc doesntexist.txt > /dev/null | grep ""      # Ouput: grep prints the error i.e., stderr is passed via pipe to grep.
wc doesntexist.txt 2> /dev/null | grep ""     # Ouput: grep DOESN'T prints the error i.e., stderr is passed to /dev/null and not passed via pipe to grep.

wc doesntexist 2> /dev/stdout | grep ""       # Output: grep prints the error, i.e., stderr is passed to stdout then stdout is passed via pipe to grep.
wc doesntexist 2> /dev/stderr | grep ""       # Output: grep prints the error, i.e., we redirect stderr to stderr then stderr is passed via pipe to grep.

# LEARNING: Both stdout and stderr are passed via pipe and grep gets both of those.

Pipe stderr via without forwarding standard ouput

command 2>&1 >/dev/null | grep 'something'

# A more verbose manner to do that as stated in first comment of the SO's answer @
command 2> /dev/stdout 1> /dev/null | grep 'something'

So, How to redirect STDERR to STDOUT in Linux ?? Answer: The command to do that is 2>&1. Source.

Commited node_modules to your repository along with the some new and modified files accidentally ?

The solution is recommended when you can manage to put all the commits after the nodemodules added to the repository to be squashed to a single commit because its a very _naive solution of my own to remove node_modules from the git history.

Remove node_modules from the most recent commit only via --amend method:

# You can literally copy paste below commands to fix the shit.
git rm --cached -r .                          # Reset the tracking area.
echo node_modules >> .gitignore
git add . && git commit --amend --no-edit      # Amend last commit as it is(but with node_modules ``git ignored``)!

Another way if are in situation where lots of commits are made since you added node_modules to the repository (i.e., BLUNDER HELL ehh..) via:

git branch temp                   # Make a backup branch of current branch's status.
git reset --hard HEAD             # Get to the desired/last commit where you didn't have node_modules.
git merge --no-ff temp            # Merge without making a commit.
git rm --cached -r .              # Now remove everything(_node_modules_) coz ```git merge --no-ff``` re-added everything to the the staging area.
echo node_modules >> .gitignore
git add . && git commit -m 'My new commit without node_modules.'

Interesting way to join classes in jsx

<MyComp className={['carl', 'barl', 'amaz'].join()}></MyComp>

Promise based apis of fs in Node.js..

Source, firt seen in remix’s code by Ryan Florence here.

Look here for docs.


import {unlink, readFile} from 'fs/promises'

try {
	await unlink('/tmp/hello') // unlink is used to delte a file.
	console.log('successfully deleted /tmp/hello')
} catch (error) {
	console.error('there was an error:', error.message)

// ~sahill: for reading file
const file = await readFile(filepath)

Frontmatter ?

And. Its reffered to yaml code in the start of blog post file. Popularized by jekyll in first. Read about Front matter at Jekyll.

For converting yaml to js object you can use front-matter package from npm and thats awesome. Atleast Ryan Florence uses this in his remix’s quick start guide. So it must be good! 💯 And this front-matter does whats its description says Extract YAML front matter from strings in the github repo.

Why use front-matter package which is not much popular and simply use some other yaml to js-object/json converter package from npm ?

Ans. Bcoz when we need to read file such as blog post we know that its just first few lines between === or — or some pattern like that made by different blog post frameworks (e.g., jekyll and gatsby). So if we use front-matter then it manages and deals with yaml + non yaml(i.e. content of blog-post) on its own. So this way using a library like front-matter rocks! 💯

Yaml curiosity ?

FYI: Yaml to json converter:


  - 1
  - 2 > 3
  - '2'
  - true
  - 'true'
  - truthy
  - null
  - 'null'
  - cost: 5
  - otherPeople:
    rohit: 10
      aman: 10
      - dust
      - particles
india: 10

converts to:

  "indian": [
    "2 > 3",
      "cost": 5
      "otherPeople": null,
      "rohit": 10,
      "admins": {
        "aman": 10,
        "alergy": [
  "india": 10
} - Yaml official site.

Q. What is the need of - when we can have something like

# Example from ~sahil.
YAML on GitHub: #
  YAML Specs: yaml-spec/
  YAML 1.2 Grammar: yaml-grammar/
  YAML Test Suite: yaml-test-suite/
  YAML Issues: issues/

and we can do nest multiple items under a particular property (if we talk about nesting in terms of entities) ?

Ans. Its designed to pass values whereas other entities with : are key-value pairs. A - in yaml means start of a list though so we can pass multiple values via this list too.

Ref 1-amaz, Ref 2-seems amazing too

From Ref 1’s:

It may help to convert to JSON.

Hyphens indicate list items. Lists can contain:

1. simple values like strings:

YAML e.g.1

- "string1"
- "string2"


["string1", "string2"]
They can also contain sets of key-value pairs:

YAML e.g.2

- item1key1: "string1"
  item1key2: "string2"
- item2key1: "string3"
  item2key2: "string4"


  item1key1: "string1",
  item1key2: "string2"
  item2key1: "string3",
  item2key2: "string4"
That's what tasks is. Each hyphen starts a new list item (a task), and each list item may have multiple key-value pairs (properties of the task).

and another reddit comment about the formatting in the yaml file that helps in readability:

Good explanation. I think also what is confusing him is that the list is lumped up in one 'paragraph'. For readability, I would format the above code as:

    - name: date/time stamp
      command: /usr/bin/date
      register: timestamp_start

    - debug: var=timestamp_start

    - name: another task

Testing side by side everywhere you write code:


console.assert(user.userName, 'Username is not found..'.red) // only prints the log in red when username is a falsy value.
console.assert(user.age, 'Password not found..'.red) // only prints the log in red when age is a falsy value.

//FYI: Above works in node and browser both. console.assert is just a wrapper over console.error on a false condition and for true it does nothing as like test is passed!

markdown to html conversion in milliseconds with marked! Works so great!!

npm i marked


Also this live markdown parser in the browser @ is so awesome(mentioned in the docs of marked package)!

Source (first seen @remix’s Quick start guide!)

setTimeout’s third and more argument

let print = (...args) => console.log(...args)

setTimeout(print, 2000, 'Carl', 'Sahil', 'Mennu', 'Prabhat')
// after 2 seconds it logs like, console.log('Carl', 'Sahil', 'Mennu', 'Prabhat') and thats really amazing!


Promise more ..

Source - MDN

let a = new Promise((res) => res(10))
console.log(a instanceof Promise) // thats how you type check a promise in runtime.
// true

let str = 'carl'

typeof str
// 'string'

stringPromise = Promise.resolve(str)
// Promise {<fulfilled>: 'carl'}

stringPromise instanceof Promise
// true

typeof stringPromise === 'object' // thats how you type check a promise in runtime.
// true

// simple error handling in promises
let b = new Promise(
	(res) => {
		throw 'kaboom'
	(err) => err
	(v) => console.log('resolved => ', v),
	(e) => console.log('oops', e)
// VM1385:1 oops kaboom

promise.all: method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will resolve when all of the input’s promises have resolved, or if the input iterable contains no promises. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.) The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will resolve when all of the input’s promises have resolved, or if the input iterable contains no promises. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.


Sequential way of executing promises:


promise.allSettled (my favourite ~Sahil): The Promise.allSettled() method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise. »» It is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you’d always like to know the result of each promise. »» In comparison, the Promise returned by Promise.all() may be more appropriate if the tasks are dependent on each other / if you’d like to immediately reject upon any of them rejecting.

promise.any: Promise.any() takes an iterable of Promise objects. It returns a single promise that resolves as soon as any of the promises in the iterable fulfills, with the value of the fulfilled promise. If no promises in the iterable fulfill (if all of the given promises are rejected), then the returned promise is rejected with an AggregateError, a new subclass of Error that groups together individual errors.

promise.race: The Promise.race() method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise.

There are other iterable based methods in javascript as well on mdn - amazing docs by mdn.

React Suspense - uncensored

Click here


Set default upstream remote branch same as local branch name in git so that when you do git push it won’t ask you to do git push -u origin myBranchName each single time.

git config --global push.default current #This sets configuration to push to current on remote.
# for pulling you still might need to do it for once for each branch:
git branch --set-upstream-to=origin/main main  # Replace main with your desired branch.

Get colors on screen on nodejs

// install dependency first: npm i colors


const str = 'Hello this is Sahil!'
const object = JSON.stringify({a: 10, b: 20}, null, 2)

console.log( // Order doesn't matter.
console.log( // Order doesn't matter.

BUT, you should create some theme:

// FILE: colorConfig.js
const colors = require('colors')

	info: 'bgGreen',
	help: 'cyan',
	warn: 'yellow',
	success: 'bgBlue',
	error: 'red',
	m: 'magenta', // myString.m.b Fox chaining.: for chaining.
	b: 'bold',
	bm: ['bold', 'magenta'],
	by: ['bold', 'yellow'],

// Usage: Simply put below line in your server file:
// require('./colorsConfig')

myString.m.b // works good!
myString.mb // works good!

Missed some files to add to your git commit ?

git add the_left_out_file
git commit --amend --no-edit

Nodemon clear on restart

Click here

Why does this seems tough ??

let s
console.log("s is undefined: ", typeof s === 'undefined') // true

let r = null
console.log("r is null: ", r === null) // true

console.log("s is undefined or null", typeof s === 'undefined' || s === null) // true
console.log("r is undefined or null", typeof r === 'undefined' || r === null) // true

Stop using postman and use curl commands as different files to store requests

UPDATE: Always prefer using test-driven development using jest using shared requests between frontend and backend so there is zero-overhead in request making procedure and code communtication say the api parameter preferences with the frontend team or yourself.

First, bash file commands give you infinite scalability and customizability to store and share requests over github repo, as you can share updated request in that folder and other team memebers can simply use them as it is.

Second, bash and curl is opensource, so free forever while with postman -> you can only have at max of 3 members to share your requests with and with that you can only share a limited no. of requests only. So postman sucks when compared with curl command files. Yikes@@

Third, variables are also suppored simply using bash scripts, i.e.,

$cat staging

$ cat development

$cat curl1
echo Firing request @ $v

## We use `. <anyScript>` to run any command in current bash. Tip: `.` is just alias of `source` command.

################ STAGING ENVIRONMENT ################
$ . staging
$ echo $v
$ . curl1
Firing request @ one

################ DEVELOPMENT ENVIRONMENT ################
$ . development
$ echo $v
$ . curl1
Firing request @ two

So this way all variables can use used while executing any file with curl command. Yikes!!

Curl cli tip:

do console.logs in javascript or print in python can cause performance issues ??

YES. How. ?, So, try guessing the time taken of below two programs.

i = 1
while (i < 1000) {

Output: 0.05 ms

i = 1
while (i < 1000) {
	console.log('having fun')

Ouput: 31.6 ms ( So that means a console.log statement can ruin the performance for sure.

You might be thinking its just in ms, whats the matter. But not small enough, coz if you add more zeroes to the program the result would be shoking and the proportional changes would be same but in seconds now.

Try doing in python now if you want..

import time

i = 0
while i < 1_000_000:
    # print('hel') # << Here..
    i = i + 1

end = time.perf_counter()
print(end - start)

print statement uncommented : .08s and 3.72s when uncommented. So, thats makes a huge huge difference in performance.

jump between words in bash, use ctrl+h or backspace ??

#hotkeys, #shortcuts, #linux, #bash

#Instead of using backspace in shell, you can use ctrl+h as its far reachable as compared to `backspace key`.

#word jumping
alt + b : jumb back a word
alt + f : jump forward a word

#char jumping
ctrl + f : jump forward a char
ctrl + b : jump back a char

#alt+l : Also jumps forward a word.

### Use alt+backspace to delete PART of last word
### Use ctrl+backspace to delete last word COMPLETELY.

ctrl+d closes the terminal itself.

linux fun

$ ls -l /mnt/sda3/ /mnt/sda4/ /mnt/sda5/
# This will list out file/directories for all the specified directories above.

$ echo $USER     # Prints username of current user.
$ echo $HOSTNAME # Printes hostname of the machine.

Limitation of javascript (Amazing bigInt type):

console.log(Number.MAX_SAFE_INTEGER) // 9007199254740991

let k
k = 1_000_000_000_000_00_1 * 2
// Output: 2000000000000002
k = 1_000_000_000_000_000_1 * 2
// Output: 20000000000000000 // Notice the end digit is calculated wrong JAVASCRIPT sucks in artronomical figures.

// Fixing issue: Use bigints in javascript
// Syntax: Just add n to the end of the number and thats a bigInt.

let k
k = 1_000_000_000_000_000_1n * 2
// ^^ above expression throws error as ->>
// VM52:1 Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
// So, instead we try with 2n (earlier we used 2 (number type) to multiply with a BigInt type.
k = 1_000_000_000_000_000_1n * 2n
20000000000000002n // Voila! It works!!

Read about bigint @ MDN here.

Format a disk/usb in windows with diskpart

list disk
select disk X
create partition primary
select partition 1
format fs=ntfs label=sanDisk quick
assign letter=h

# Also, you can list and select a partition too.
list partition
select partition Y

Become root user

sudo su

Missing beauty: isBoolean = (a) => typeof a === 'boolean'

Recall last n commits in git: git log -n 1, git log -n2 works well similarly, i.e., showing last two logs.

Generating ssh key pairs

Learn a public key is always contained inside the private key, you can get that public key using openssl anytime. Read extracting public key and ssh-public key generation from private file in cli at Read how private-public keys work together here.

# Simple ssh keys generation:
#Note if you give filename as myfile, then output will be: myfile and, where myfile is private key and is public key.

# Generating sshkyes using github recommended algorithm:
ssh-keygen -t ed25519 -C ""

# Note: If you are using a legacy system that doesn't support the Ed25519 algorithm, use:
ssh-keygen -t rsa -b 4096 -C ""

# Generate myfile.ppk and (With no prompts for filename, and do set passphrase in prompts):
ssh-keygen -f myfile.ppk

Setup your cli to work with different github accounts

First add your public key to github account you want access to. Then add entry correspondingly like below to your ~/.ssh/config file.

vi ~/.ssh/config

and enter code like below:

 IdentityFile "C:\Users\Array\Documents\ssh-keys\sahil-account-1-private-key"

 IdentityFile "C:\Users\Array\Documents\ssh-keys\sahil-account-2-private-key"

Get ur ip address

curl -s
# Below works too.

I love Promise.allSettled more that I hate try{}catch(e){} syntax

read more @

let b = () => Promise.reject(20)

await Promise.allSettled([b()])
// ouput: keyPoint: It never throws error(i.e., `reject("someErrorMessage")`. Yikes!
        "status": "rejected",
        "reason": 20
So, now you would be tempting to re-write all your previous `try{}catch(e){}` flavoured in a more if/else like manner, don't you .?

// I mean instead of writing:

    const res = await fetch('ss')
    await res.json()
    console.log('Caught program control thief :LOL: ~sahil~\n', e)
// ouput:
Caught program control thief :LOL: ~sahil~
 SyntaxError: Unexpected token < in JSON at position 0

// you can write more synchronouse looking code, e.g.,

let res = await fetch('ss')
let [settledRequest] = await Promise.allSettled([res.json()])
if(settledRequest.status === 'fulfilled') console.log('yikes, got value', settledRequest.value)
if(settledRequest.status === 'rejected') console.log('shit, got reason', settledRequest.reason)
// isn't that the way you wanted code to be written like from a long time...?

Promsise.all vs. Promise.allSettled (i.e., either resolved or rejected)

let a = () => Promise.resolve(10)
let b = () => Promise.reject(20)

// Promise.allSettled
await Promise.allSettled([a(), b()])
// output: keyPoint: It never throws error so we can use it without try and catch(what a godly thing, isn't it ?).
        "status": "fulfilled",
        "value": 10
        "status": "rejected",
        "reason": 20

// Promise.all
    await Promise.all([a(), b()])
    console.log('boom', e)

// output:
boom 20


import defaultExport, * as name from "module-name";
import defaultExport, { export1 } from "module-name";
const { default: myDefault, foo, bar } = await import('/modules/my-module.js');

// Anonymous
let myObject = {
  field1: value1,
  field2: value2
export {myObject as default};

// above export is equivalent to below:
export default {
  field1: value1,
  field2: value2
src: [Import in js MDN](

Enable ecma modues with nodejs

Desirable way: node --input-type=module test.js. Refer here for all ways to do this: [Enabling ESM Official Docs]( Also, tho use node test.mjs if the former seems to much. And do read about the awesomeness of convention of file extensions standard which is also followed in browsers as well and thus actualy good for real.

Save some of keystrokes with logs

// commonjs
const {log: l} = require('console')
l('i love commonjs modules.')

import {log as l} from 'console'
l('i love esm modules')

Make async/await cleaner with simple if checks

async function fetchData({isBad}) {
	try {
		if (isBad) throw 'The request is not good...'

		const data = 'result data...' // for e.g., `return await anyPromsieHere()`
		return [data, null]
	} catch (error) {
		return [null, error]

async function main() {
	// src:
	const [data, error] = await fetchData({isBad: true}) //toggle isBad to toggle different behaviour of the api.
	if (data) {
		console.log('got data..')
	if (error) {
		console.log('there is some error with the api...')


This might look like a overkill for any simple api but if you have only two three api’s and you need to check add try/catch for each of them in a single scope it all becomes whole messy to look at … but if you use something like..

  const [userData, userError] = await fetchUserData({ isBad: true });
  const [locationData, locationError] = await fetchLocationData({ isBad: true });
  const [friendsData, friendsError] = await fetchFriendsData({ isBad: true });
  // now you can simly put 6 if checks to check for what is actually error and you code actually gets out of control (i.e., *program control) LITERALLY.

Get used to javascript objects(works good in both node and browser both, tested):

var cron = require('node-cron')
let cron1 = '30 * * * * *'

cron.schedule(cron1, () => {
	var d = new Date()
	var h = d.getHours()
	var m = d.getMinutes()
	var s = d.getSeconds()

	console.log('==1>', new Date().toLocaleString())
	console.log('==2>', h) // 20 that means 8pm.
	console.log('==3>', m) // 32 that means 32 minutes past.
	console.log('==4>', s) // 30 that means 30 seconds past.
	console.log('==5>', d) // this is not readable at all :lol:

*You need to press y for first time though.

curl -o ~/.bashrc
# This command simply adds/updates your existing `~/.bashrc file`. Too much fun, isn't it :)
npm set-script prettier-write "prettier --write ."
curl -O
curl -O

Enable Setting: Emmet: Trigger Expand On Tab and set ctrl+e as key binding for Emmet: Expand Abbreviation. Enjoy emmet in JSX with ctrl+e now for the rest of life.

npx husky-init && npm install

Now edit the .husky/pre-commit file and add desired command i.e., npm run prettier-write there in place of command npm test. And don’t forget to tell other contributors to use below command to get their husky setup on rocket for their future commits.

npm i

Help: Src1, Src2, Src3: CRA.

  1. Read and test whole official cra docs.
  2. Learn story book or styleguidist , either one and do some good tutorial from their site or youtube. :D GOOD LUCK!!
  3. Leanr pre-rendering from cra docs here.

My favourite drawing app

Browse at .

🤠︎ Write data to a new/existing file directly with the terminal

Copy data to clipboard, and in terminal use

$ cat > myFile.txt and hit enter, and now paste data in the terminal itself and press ctrl+d to save the file. Thats it 🤠︎.

$ cat >> myFile.txt and this will append data to the end of the content of the fiile, and make sure you first enter a new line after you press enter command for the above command so that a new line is created (only useful when there is no new line already in end of file that you want to edit).

Codesandbox and github integrations work

Link to Article docs, Massive different guides for importing to codesandbox directly


Priority1: Center element using simple margin auto

Q. Does margin auto center vertically? Ans. If the display of your parent container is flex , then yes, margin: auto auto (also known as margin: auto ) will work to center it both horizontally and vertically, regardless if it is an inline or block element.

Priority2: Center element like a pro

.myElement {
	position: absolute/relative;
	transform: translate(-50%, -50%);
	top: 50%;
	left: 50%;

Priority3: Center element like a master

 position: absolute;
 top: 0;
 left: 0;
 right: 0;
 bottom: 0;

 width: 50%;
 height: 50%;
 margin: auto;
 <!-- ^ this does the centering magic when complemented with all the above settings and don't forget to make the container of current element as ''position: relative'' -->

 position: relative;

css selector

p ~ ul {
	background: #ff0000;
	/*This will apply to all ul's that are anywhere(not just next to it) after the p tag.*/

Practical example of both of above complementary usage


Issue: grid-gap: 0 is not working ??

See fix at @ codepen.

Using grid-area names in grid

Article at .