sahilrajput03

Feed

Note to me: Please add date for all posts from now on. ~ Thankyou

What’s with the name of k3s?

Source: Click here

image

Cloud Egress Costs

AWS, AZURE, Cloudflare, Heroku, Render, Vercel cloud pricing comparison.

Click here

Temporary policy: Generative AI (e.g., ChatGPT) is banned

Official StackOverflow Question Here: Click here

Erlang, Elixir

Erlang:

9 types of API testing 👇👇

Source: Click here

📌 Smoke Testing ➡️ Purpose: To quickly check if the API is functional. ➡️ Focus: Basic functionality validation. ➡️ Scope: Testing critical paths to ensure that the API is operational without major issues.

📌 Functional Testing ➡️ Purpose: To validate if the API functions as per its documented specifications. ➡️ Focus: Testing specific functionality, input parameters, output results, and business logic. ➡️ Scope: Evaluating the API for various use cases to ensure it meets the defined requirements and expectations.

📌 Integration Testing ➡️ Purpose: To test interactions between multiple APIs or services. ➡️ Focus: Validation of data flow and communication between APIs. ➡️ Scope: Ensuring that APIs can work seamlessly together in an end-to-end scenario, checking if they can exchange data and function collectively.

📌 Regression Testing ➡️ Purpose: To prevent new changes from breaking existing API functionality. ➡️ Focus: Re-running previous test cases to check for any regression or unintended side effects. ➡️ Scope: Verifying that the existing features and behaviors of the API remain intact after making changes or updates.

📌 Load Testing ➡️ Purpose: To assess API performance under expected loads. ➡️ Focus: Measuring response times, throughput, and resource utilization during various load conditions. ➡️ Scope: Testing the scalability of the API and identifying performance bottlenecks or resource limitations.

📌 Stress Testing ➡️ Purpose: To evaluate how the API performs under extreme loads beyond normal usage. ➡️ Focus: Pushing the system to its limits to identify its breaking points. ➡️ Scope: Assessing the robustness and error-handling capabilities of the API under severe stress, helping uncover potential issues.

📌 Security Testing ➡️ Purpose: To identify vulnerabilities and weaknesses in API security. ➡️ Focus: Checking authentication, authorization, data protection, encryption, and other security measures. ➡️ Scope: Protect the API against external threats, such as SQL injection, cross-site scripting (XSS), and unauthorized access.

📌 UI Testing ➡️ Purpose: To validate the interaction between the user interface and APIs. ➡️ Focus: Ensuring that data is displayed correctly in the user interface when accessed through the API. ➡️ Scope: Testing the integration of the API with the front-end components to guarantee a smooth user experience.

📌 Fuzz Testing ➡️ Purpose: To identify vulnerabilities and security issues in the API. ➡️ Focus: Injecting unexpected, invalid, or malicious data to provoke unexpected behavior. ➡️ Scope: Revealing potential vulnerabilities that could be exploited by attackers, such as buffer overflows, injection attacks, and data validation weaknesses.

Generate frontend with code using ChatGPT

https://www.pageflow.ai/

Monolith vs. Microservice example

From ChatGPT: Click here

What is natural language?

image

bug, developer, tester, project manager jokes

Click here

Satya Nadela in 1993

Click here

#Testing, #Tester Jokes

Click here

Bengaluru software engineer hacks IndiGo’s website

Source: Click here

CRM for Gmail

Chrome Extension: Click here

Multiple notificaiton are enabled for all participants in google meet

Source: Click here

image

Companion Mode in google meet

Docs: Click here

TLDR; When you want to share screen from laptop you feel that that:

😍🙂😎🤡 Live brain reading directly via brain scan:

Click here

How many thanksgiving days are there in USA?

image

Stages of Development and Testing

Source: Click here

In software development, different types of releases denote various stages of development and testing. Here are some common types:

These terms may vary slightly in usage between different development teams and projects.

Date: 23 Nov, 2023

Azure vs. AWS for pricing?

Click here

Date: 22 Nov, 2023

Linkedin is owned by Microsoft

Wikipedia: Click here

image

Date: 22 Nov, 2023

Comparison for custom validation libraries for data on backend

Click here

Date: 15 Nov, 2023

Should we maintiain categories in database or in backend database as enums

Click here

What is ERP

Erp Serivce used by Zerodha (mentioned in their hello world article on their website):

image

How can a store documents such that I can fetch them in a particular sequence

Refer my notes on other page: Click here

Date: 2 Nov, 2023

For sorting by name we can add a new field sort_name by which we can sort via the after id of the last set of items when we use cursor based pagination

For this we use: sort_name=${doc.name}_{doc._id.toString()} so this helps us establish cursor based pagination.

Date: 30 Oct, 2023

Make sure you use website to click below links from mobile (not on github page).

hd, fhd (full hd), wqhd?

image

Date: 30 Oct, 2023

FAT32 vs. exfat?

image

Date: 29 Oct, 2023

Opensource AI avatar generator

Bard is fast now

image

Mongodb compass has AI chat assistant as well

image

image

we get completions for aggregate pipelines as well:

image

Date: 26 Oct, 2023

Do adb device ids change after disconnect?

TLDR: No (though probably yes if you run adb restart command)

image

Date: 21 Oct, 2023

Projects killed by google

https://killedbygoogle.com/

Date: 20 Oct, 2023

notion?

image

Date: 17 Oct, 2023

Meta Stocks

image

image

Date: 17 Oct, 2023

Should I handle Oauth callback in frontend or backend?

TLDR: In backend.

image

Date: 16 Oct, 2023

Web Components ~ Samaksh

Check my example on Github Repository: - Click here

Date: 15 Oct, 2023

SBI charges fee if you request to check the CIBIL score

image

image

React debugger in vscode

Click here

Click here

image

image

In amazon product details page, the only necessary thing is ASIN number

image

image

Date: 4 Oct, 2023

Producst scraping on amazong.com (#scrape)

// Searching books on amazon via a url:
// https://www.amazon.com/s?k=Christine+by+Stephen+King&i=stripbooks-intl-ship
Date: 4 Oct, 2023

ASIN

Date: 4 Oct, 2023

Click here

Date: 3 Oct, 2023

zero based and one based indexing

image

Date: 29 Sept, 2023

Cursor based pagination vs. Number based pagination?

Prefer number based pagination when you have literally number on your view, i.e, if you have numbers ie., 1,2,3 on your pagination component then it makes sense to make use of number based pagination instead of cursor based pagination because with cursor based pagination we can not get items of a particular page i.e, we can not use skip value to skip some items.

Cursor based pagination is good for messaging where you would load messages continuously only, i.e, there is no skipping of data. (For more info check search for cursor based pagination on my home page of github).

Date: 28 Sept, 2023

❤️ Why CRA is not listed on react.dev docs?

Check this issue’s comment: Click here

Date: 29 Sept, 2023

Integrated end-to-end testing framework written in Node.js and using W3C Webdriver API. Developed at @browserstack

Github: Click here

Date: 22 Sep, 2023

Google Text to speech in Cloud in Action

Source: Click here

Date: 22 Sep, 2023

httpOnly vs. secure cookies, are they same?

image

Date: 22 Sep, 2023

Executing javascript with a bookmark on a page

javascript:(function() {
	console.log("Hello, World!");
})();
Date: 20 Sep, 2023

Choosing b/w NodeJS based cronjobs vs. linux cron jobs

image

image

Date: 14 Sep, 2023

What is typematic?

The initial delay between pressing a key and the start of repetition is called the typematic delay. The time between key repeats once repetition begins is called the typematic rate.

Date: 12 Sep, 2023

Difference between Ionic and Capacitor?

Source: Click here

Capacitor is required to create/package and run your web (Ionic app) as a native Android/iOS app. Without Capacitor, you can only run the Ionic app in a web browser.

Correct, Capacitor is required to use native functionality in your Ionic app like the camera, push notifications, native storage, etc.

Date: 11 Sep, 2023

variable name is

image

Date: 5 Sep, 2023

Gaming Industry revenue is 6 times more than Movie Industry

Source: Click here

image

Date: 4 Sep, 2023

What is OAuth 2? (Postman APIs follows this)

Date: 3 Sep, 2023

Google’s Generative AI is released in India

image

Date: 3 Sep, 2023

cashfree.com - Payments infrastructure for India

Date: 2 Sep, 2023

eCPM?

It is a key ad performance metric used by publishers to monitor the revenue generated from the ads on their site.

Date: 31 Aug, 2023

Click here

Date: 30 Aug, 2023

I can use my mobile github app to login now that I have setup GITHUB 2FA

~Also, I can use my Authenticator (google app) to login into github as well.~ It didn’t work may be its useful to reset my password? (need to verify).

image

Date: 29 Aug, 2023

Check RAM slots used in your laptop

image

Date: 26 Aug, 2023

How many parallel mongodb insert query can I run in parallel with mongoosejs in nodejs?

image

Date: 25 Aug, 2023

How many maximum parallel files/images should I download via nodejs?

image

image

Date: 25 Aug, 2023

Electron vs GTK?

Electron is a desktop application framework developed by GitHub and created by Cheng Zhao. It allows for the development of desktop applications using front- and back-end infrastructure such as HTML, CSS, and JavaScript.

Date: 22 Aug, 2023

1Password

Date: 22 Aug, 2023

GitHub Plans to Roll Out Mandatory 2FA to Strengthen Security - techreport.com

Click here

Date: 23 Aug, 2023

What is MVC pattern?

image

Date: 22 Aug, 2023

What is condenser mic

image

Date: 18 Aug, 2023

What is optimistic updates in UI?

image

image

Ctrl+alt+a, Ctrl+alt+l produces special character in windows 10/11

Solution: StackOverflow Answer: Click here

We had to set English US as the only keyboard in Keyboard Settings in Settings.

Google chrome is removing third party cookies soon (by the end of 2023 probably)

Docs: Click here

Netflix files downloader

Amazing tool to generate a long image for Pull Requests for reviewing over mobile

Screen Capture - Chrome Extension: Click here

Difference b/w npm i and npm ci

Source: Click here

image

Copy folder via adb pull command

# This copies `snaptube` folder from internal disk to local `snaptube` folder
adb pull /sdcard/snaptube

# Push files to device
adb push ./myfile.txt /sdcard/

Should we have “develop” and “staging” deployments in addition to production deployment?

Ideally we should have development and staging environments separately. Where “develop” is always stable version of production, and staging is purely tesitng

Use saucelabs to test apps in different browser

Suggested by damon

Source - https://saucelabs.com/

Telegram Projects on github

More official from telegram projects:

Husky pre-push hooks possible!!

image

image

Cookies read by javascript (Yes they are readable by javascript but httpOnly cookies are not readable by js)?

Source of below Image: [Click here(https://owasp.org/www-community/HttpOnly)

image

Why refresh tokens?

image

Data storage eviction policies in the browser

MDN: Click here

Redmi note 5:

Install magisk on redmi note 5

Requirements: Your phone should have unlocked and have a custom recovery already installed (Orange Fox is a good one).

Source: Click here

Simple process (notes):

  1. Download latest magisk.apk file from here.
  2. rename the file to magisk.apk to magisk.zip and install that zip file from custom recovery.
  3. rename the file magisk.zip to magisk.apk and install that. Not it should be good to go!

Hiding root from google-pay, etc banking apps(tested on redmi note 5 - 2-april-2023)

Source: Click here

Learn using pause (,) and delay (;) while dialing calls

Source: Click here

Source: 2 - Click here

TESTED AND VERIFIED

Say you wanna call 18001234567, and wait for six seconds and then enter extension 901.
Way 1: You can use pause i.e, calling  `18001234567,,,901` would wait for six seconds i.e, 1 comma is for 2 seconds, thus 3 commas for 6 seconds pause and then it'll send 901 extension.

Way 2: You can call `18001234567;,901` now this will prompt you when to send the extension after the call is started. When you press "yes" on the prompt then it'll wait for 2 seconds and send the extension 901.

Is js-cookies bad?

image

Deduping data

image

What is it called when we start numbering enties from 0 instead of 1 ?

Zero-based index

image

Google meet recording wiht tl;dv

You can share your recorded video simply by that feature:

image

Flutter vs. react native, market share?

image

Teach Yourself Computer Science

Click here

Always show tabs in firefox mode in fullscreen

Click here

Twitter Status Updte page is served by atlassian status update page

image

defer vs. async in script tag in html

Source: Click here

image

Capacitor

image

Planetscale - Free MySql database service

PlanteScale, Pricing: Click here

Tracking a variable value change

let a = false

let id = setInterval(() => {
	console.log('checking variable.', a)
	if (a) {
		console.log('value has changed!', a)
		clearInterval(id)
	}
}, 1000)

// Change value of variable a after 4 seconds
setTimeout(() => {
	a = true
}, 4000)

Opening closing & Passing data from Child window to parent window in JavaScript & refreshing main

Click here

popularity vs. active issues

image

image

Npm useful commands

Source: Click here

# get documentation 
npm repo react --no-browser

# get outdate dependencies
npm outdated

# get version history
npm v lodash versions

# The audit command submits a description of the dependencies configured in your project to your default registry and asks for a report of known vulnerabilities.
npm audit

What does npm run xxx do?

Click here

Medium Handle on the author: Click here

Teach coding to kids/students

honeypot?

Source: Click here

image

Detecting if the user is online with JavaScript

Click here

General Data Protection Regulation

https://gdpr-info.eu/

FUN FACT/ Did you know?

The maximum size an individual document can be in MongoDB is 16MB with a nested depth of 100 levels. Edit: There is no max size for an individual MongoDB database.

Source: Click here

Data Transfer Object (for e.g., used in user-signin.dto.ts in some projects)

image

Why are IT companies itching to bring employees back to office when all the work is getting done so smoothly, employees are happy to work extra hours without extra pay?

Source: Click here

committing directly to master is bad practice

Source: https://www.quora.com/I-work-for-a-startup-our-CTO-loves-writing-code-and-he-frequently-commits-bad-code-directly-to-the-master-branch-What-should-I-do

how much salt round value should you use?

Moe the better, as much your server can tolerate but be somewhat practical.

Source: Click here

image

salt breaking by parts

Source: Click here

image

Is salt considered a secret?

NO!

Read more on these stackoverflow answers:

image

Its true that we save salts with the passwords in the database as well i.e., the starting of the password is just the salt used only:

let bc = require('bcryptjs')
let saltRounds = 14 // The higher the saltRounds value, the more time the hashing algorithm takes. 
// Note equal time is taken to verify as well i.e, when we call `compareSync` funciton.
let salt = bc.genSaltSync(saltRounds) // DEFAULT VALUE for salt is 10

console.log('SALT:', salt)

let hash = bc.hashSync('car', salt)
console.log('HASH:', hash)

// Verify
console.log(bc.compareSync('car', hash)) // true

// SAMPLE OUTPUTS:
// SALT: $2a$10$HKfmu6IQUO4B9b/8LcdrVu
// HASH: $2a$10$HKfmu6IQUO4B9b/8LcdrVu9YsuALxHTA0GBUvyj4b2Ia/nB5JlKgm

// SALT: $2a$10$1FIlrxjpmaypBpSKGkScPO
// HASH: $2a$10$1FIlrxjpmaypBpSKGkScPOUFP9HgmFHoDOk.rIK8D.OGX6CoBV2U6

// SALT: $2a$10$uKX.sCX2wIezRsIKcEXK2u
// HASH: $2a$10$uKX.sCX2wIezRsIKcEXK2uQyVBLfznBA571yanO3uGsPWze.jahhe

image

Amazing:

image

end to end security?

Source: Click here

image

keys?

https://stackoverflow.com/questions/48958304/pkcs1-and-pkcs8-format-for-rsa-private-key

Buffers to string and string to buffers?

Source: Click here

image

How to Use Buffers in Node.js

Source: Click here

image

typed arrays in javascript?

Source: Click here

image

image

Using vscode debugger

f5(start)
f10(step)
f11(step inside)
shift+f11(step outside)
ctrl+shift+f5(restart debugger)
shift+f5(stop debugger)

settings.json and keybindings.json of vscode files in windows

image

Installing npm dependency via custom github repo

  "dependencies": {
    "redux-persist-transform-encrypt": "github:shagundev/redux-persist-transform-encrypt"
  }

mandrill, mailchimp

Tip: You can login to mandrillapp.com using mailchimp logged in accound with oauth automatically. :D

Vercel comments in docs is such awesome (currently in Beta docs only)

https://vercel.com/blog/using-vercel-comments-to-improve-the-next-js-13-documentation

Visit here to try it: https://beta.nextjs.org/docs

URI vs. URL

image

Resemble.ai is awesome

https://app.resemble.ai/

Another good seeming opensource project claminng to have good quality of voice cloning:

You can run a stored javascript code on website using a bookmark like that:

image

graphql helper?

https://github.com/Urigo/graphql-mesh

char, decimal, hex, binary

image

industrial revolution?

https://www.reddit.com/r/ethereum/comments/ybikdd/ai_and_the_blockchain_are_we_living_through_the/

Strict more in nodejs

// 'use strict';

// strict mode: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

// strict mode makes it impossible to accidentally create global variables (works in nodejs and browsers{tested with chrome})
// mistypeVarible = 17;   // throws ReferenceErrror in strict mode

let c = {}
Object.defineProperty(c, 'a', {value: 2})
// c.a = 10 // throws error in strict mode: TypeError: Cannot assign to read only property 'a' of object

software enginner seniority?

Intern > SDE1 > SDE2 > (SDE3/TechLead/SD3) > Individual Contributor Intern > SDE1 > SDE2 > (SDE3/TechLead/SD3) > Project Manager

SSE and SDE2 produces most of code for the companies. SDE2 > SSE jump is kind of tough in big companies.

Is vercel completely free?

Mottos of different fields

image

Softwre developer vs. Software engineer

image

Simple js/react/css interview 90 question test

interview-ss

Google search query syntax

https://www.google.com/search?q=life+is+awesome

integer overflow/ wraparound

Source: integer overflow (wraparound) can’t be better explained than using this odometer example. 😅

image

Article - TODO READ

https://blog.codinghorror.com/the-last-responsible-moment/

lower vs. upper camel case?

All function names are in lower camelCase (eg. sendCoin) and all event names are in upper CamelCase (eg. CoinSent). Source

Aritcle with speech listeners

Task running tools

Language Specification of Javascript ECMA

Are github stars a real indicator of how much a npm library is used in the industry?

image

image

Do changing dns makes you anonymoust?

Source: Click here

Here’s a short summary of how DNS works:

Using your ISP’s DNS

In your browser, you type AustinBike.com - Home

Your browser asks your ISP for AustinBike.com - Home

Your ISP uses its DNS server to figure out that the website is at 74.208.236.250

Your ISP goes to 74.208.236.250, gets the page and sends it to your browser.

Using a third party DNS

In your browser, you type AustinBike.com - Home

Your browser asks the third party for the address of AustinBike.com - Home

The third party uses its DNS server to figure out that the website is at 74.208.236.250

The third party tells your browser to ask for 74.208.236.250 which is sent to your ISP.

Your ISP goes to 74.208.236.250, gets the page and sends it to your browser.

(Yeah, I’ve simplified this for the non-tech people, this is not EXACTLY how it works.)

But notice that the last statement for both is exactly the same. This is because everything on the internet is transported via IP addresses. And ISPs store IP addresses, not domain names. If law enforcement ever came knocking on your ISPs door asking what you were up to, they’d hand them a list of IP addresses that your computer asked for, not domains. LE will have tools to do the lookups and complete the list with “human readable” domain names.

If you had a VPN, all of the traffic that you ISP would have would look like this:

Outbound requests: You to VPN

Inbound requests: VPN to You

BUT if law enforcement wanted to know what you were up to, they would go to your VPN provider. If they cooperated the list would be exactly like the list your ISP would hand over above. Some VPN companies do not log requests, some do. If they are not logging they would tell LE that they have nothing to turn over.

Don’t just assume that because you are using a VPN that your traffic is hidden. All you have done is put one more hurdle into the process, not stopped it. A VPN also has to not log the data. Some may say they don’t but could be secretly logging it. You cannot ever be 100% sure that you are safe just because you are using a VPN.

Additionally, if LE really, really wanted to know what you are doing, they could put taps on line at the VPN provider to figure things out without needing their logs. But you’d need to be a pretty bad guy for that, not someone just searching for porn or other questionable content.

An amazing way to store q/a’s in yaml format so that one can parse this data from a file from github

I.e., storing array of arrays in yaml.

Inspiration: Click here

image

ai powerd writing tool

image

Free database,

Doesn’t support postgres or mondodb.

Good service for mysql hosting: https://planetscale.com/

Event Hosting platform

https://www.zuddl.com/

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

https://stackoverflow.com/help/minimal-reproducible-example

Most Amaizng graphql client library

https://github.com/gqty-dev/gqty

insomnia vs. postman

https://gist.github.com/samoshkin/c0a2c0dd85b1d5b02d893a0f6ac0e93c

What is LOC?

image

what is sloc?

image

Add github comment system to your blog

React Giscus Component: Click here

image

image

Looks like a good cache library

Inspiration: https://github.com/simoneb/axios-hooks#manual-requests

https://github.com/isaacs/node-lru-cache

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 @ https://git-scm.com/docs/git-log
# Inspiration: https://stackoverflow.com/a/29876744

Fix cors errors without fixing backend in chrome

Chrome Extension: CORS Unblock

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

image

image

image

Google maps apis is paid

Source: https://developers.google.com/maps/documentation/javascript/get-api-key

image

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

https://youtu.be/3_FcxGCCnUs

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

https://www.netlify.com/blog/rewrite-html-transform-page-props-in-nextjs/

Learn maps and sets

Source: Kyle

Maps are for objects, and sets are for arrays.

image

Sets store unique values only:

image image image

Array.slice returns a shallow copy: Remeber it

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

image

website performance analytics

source: https://pagespeed.web.dev/

image

Source: https://gtmetrix.com/

image

cli apps with react?

Github: https://github.com/vadimdemedes/ink

image

Lol

src

image

mutation observer

Generating real ssl certificate using letsencrypt on cli

image

using %s, %f, %d in javascipt

@mdn: https://developer.mozilla.org/en-US/docs/Web/API/console

image

making insecure requests with postman or curl

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

flask run --cert=adhoc --host=0.0.0.0

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 https://mynotifyservice.ddns.net:5000/

For postman:

image

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

image

This is such a lifesaver from github

image

Why postgres/mongodb over firebase #jimmy_chae?

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

image

image

module system nodejs

Source: https://stackoverflow.com/a/29262643/10012446

image

image

image

Browser developer tools

image

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

image

ml in action

Source: https://youtu.be/VwVg9jCtqaU

Source Code for rock-paper-scissor identification code: https://colab.research.google.com/github/lmoroney/io19/blob/master/Zero%20to%20Hero/Rock-Paper-Scissors.ipynb

Sample try out project on medium.com: https://blog.devcenter.co/developing-a-license-plate-recognition-system-with-machine-learning-in-python-787833569ccd

image

Q. How does flatten work in Keras ?

Ans. https://stackoverflow.com/questions/44176982/how-does-the-flatten-layer-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

https://github.com/readthedocs/readthedocs.org used to make solidity docs.

futter market demand

https://www.monterail.com/blog/flutter-vs-react-native-mobile-development

learn js classes

class Animal {
	static belly = []
	eat() {
		Animal.belly.push('food')
	}
}
let a = new Animal()
a.eat()

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

E.g., 2

let bear = {
	sound: 'roar',
	roar() {
		console.log(this.sound)
	},
}

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

image

image

Source of below code: MDN

const output = void 1;
console.log(output);
// 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 {
  test();
} catch (e) {
  console.log('test function is not defined');
  // expected output: "test function is not defined"
}

bandwidth and throughput?

image

image

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.

Source: https://melvingeorge.me/blog/difference-between-lastchild-and-lastelementchild-element-property-javascript

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

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

image

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)

image

image

dapps

Article - https://blog.itsrakesh.co/what-are-dapps-how-they-are-different-from-normal-apps

Article - https://blog.itsrakesh.co/what-is-blockchain-how-does-it-work

Don’t abuse arrow functions in 2022

https://javascript.plainenglish.io/its-2022-don-t-abuse-the-arrow-function-anymore-905862a9c668

Execute code on tab close

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

// for react, use reference: https://bobbyhadz.com/blog/react-handle-tab-close-event
// amazing blogger: https://bobbyhadz.com/

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

image

@mdn docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event

image

builtin assertion library - nodjs

inspir

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

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.

image

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

Source: https://stackoverflow.com/a/38948889/10012446

I added answer to that question as well, here: https://stackoverflow.com/a/73001807/10012446

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) => {
	res.json('yoy')
})

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.
	log({url})

	let response = await axios.get(url)
	log('GOT DATA IN RESPONSE:', response.data) // 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) => {
	res.json('yoy')
})

app.listen(PORT, async () => {
	let response = await axios.get(apiPath('/a'))
	log('RESPONSE DATA:', response.data)
})

Object.is is better than === ? tldr Yes, a little bit.

Source: https://stackoverflow.com/a/30543212/10012446

image

what venv in python?

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



## 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: https://docs.python.org/3/library/venv.html
python -m venv env

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

nextAuth?

image

validation in javascript

If using typescript: https://github.com/colinhacks/zod (9k*)

If using javascript: https://github.com/jquense/yup (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: https://stackoverflow.com/a/23639793/10012446
let objectToParams = (obj) => Object.entries(obj).map(([key, val]) => `${key}=${val}`).join('&');

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

toJSON in JSON.stringify function ?

sleep

what is it to sleep @5am

mimic your voice with system ?

https://www.descript.com/lyrebird

~ 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.
https://www.descript.com/

Posthog - an opensource analytical tool

Github: https://github.com/PostHog/posthog

Used by Varun Mayyas he tells in this video.

Visit at: https://posthog.com/

ui sources - has all the screenshots of all the apps

https://www.uisources.com/home

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

Reducing apk size of react-native apps?

Unicode symbols Website

https://www.amp-what.com/unicode/search/up%20arrow

Anatomy of html documents by mdn

https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/Getting_started#anatomy_of_an_html_document

Labelled statement in javascript

Awesome: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label

Src: https://youtu.be/AdNJ3fydeao?t=949

Awesome ni package mangager :LOL:

https://github.com/antfu/ni

Github’s Official .gitignore files for different enviornments

https://github.com/github/gitignore

https://github.com/github/gitignore/blob/main/Node.gitignore

Whats your ping?

image

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)

https://huggingface.co/

https://github.com/huggingface/transformers

Problem with token based authentication

Source: https://fullstackopen.com/en/part4/token_authentication#problems-of-token-based-authentication

image

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

Source: https://shopify.engineering/how-we-built-hydrogen

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

Source: https://codewithhugo.com/jest-array-object-match-contain/

test('LEARN: array containing an object', () => {
	// src: https://jestjs.io/docs/expect#expectarraycontainingarray
	const expected = {name: 'sahil'}
	const received = [{name: 'sahil', lastname: 'rajput'}, {otherObjectsAnyShape: 'Rohit'}]

	// Src: https://codewithhugo.com/jest-array-object-match-contain/
	expect(received).toEqual(expect.arrayContaining([expect.objectContaining(expected)]))
})

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

https://www.chaijs.com/plugins/chai-http/

Finally Intellgence as a service goona be paid

image

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 https://stackoverflow.com/a/14172822/10012446 (<< this answer has another link of stackoverflow answer i.e., src of this answer: https://stackoverflow.com/questions/11386492/accessing-line-number-in-v8-javascript-chrome-node-js)
# src: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack


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)

Figjam for online flowcharts/diagramming

Youtube: https://www.youtube.com/watch?v=giCx1LPizXU

Promisification

https://javascript.info/promisify

https://www.tutorialspoint.com/node-js-util-promisify-method

https://nodejs.org/api/util.html#utilpromisifyoriginal

https://nodejs.org/api/fs.html#filehandlereadfileoptions

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;
  console.log(data);
}

// 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) => {
      console.log(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)

https://github.com/fullstack-hy/part13-notes/tree/part13-2

Whatsapp chatbots made easy!

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

set input as numeric in forms?

Source: css-tricks

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

Add a npm script via cli

Source

npm set-script prepare "husky install"

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

image

const target = {};

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

const proxy3 = new Proxy(target, handler3);

proxy3.a()
// VM583:5 fun?: a

proxy3.b()
// VM583:5 fun?: b

Create live expressions

image

This is magically amazing!!

magic code for edge caching (setting cache headers)

Source: https://trpc.io/docs/, Code @ https://github.com/KATT/typescript.careers

Source: https://youtu.be/-_GZJ3xwYOw

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.

image

image

What is save-exact in .npmrc ?

Source: https://stackoverflow.com/a/64507176/10012446

image

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.

todo-read

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

  1. https://stackoverflow.com/questions/34855352/how-in-general-does-node-js-handle-10-000-concurrent-requests

  2. https://www.quora.com/Is-it-possible-for-server-to-handle-around-100-000-requests-per-second-If-so-which-would-you-recommend

Learn about express-async-errors npm package

Go to https://github.com/sahilrajput03/learn-express

Complete command line solution for nodejs

Source: https://www.npmjs.com/package/commander

22.7k Github Stars, It has more than 73m weekly downloads(from npmjs.com)

Make you router page available on the public ip address

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

Using custom environment files i.e., .env.dev 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.

image

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

image

created flash-runner npm package

Browse @ https://www.npmjs.com/package/flash-runner

Github @ https://github.com/sahilrajput03/flash-runner-npm

npm i flash-runner

blockchain ?

https://stackoverflow.blog/2021/06/07/most-developers-believe-blockchain-technology-is-a-game-changer-3/

programming, scripting, and markup languages?

collaborative work management tool

image

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 https://github.com/sahilrajput03/flash
cd flash && npm link
cd ..

git clone https://github.com/sahilrajput03/learning-monogo-and-mongoosejs
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!

I.e.,

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?

Source: https://stackoverflow.com/a/6764988/10012446

tldr;

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 ?

https://github.com/tailwindlabs/tailwindcss

Find my own demo app @ https://github.com/sahilrajput03/cssDesignTrail/tree/master/learn-tailwindcss

Its revolutional for me personally!

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

Source: https://jestjs.io/docs/tutorial-react

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

Source: https://academind.com/tutorials/localstorage-vs-cookies-xss . Wanna read about cors from same author ?. Mdn - Restrict access to cookies.

image

google.com cookes looks like this

image

Created a clone of lowdb

Browse @ https://codesandbox.io/s/low-db-clone-t4lbln?file=/src/App.js

Lowdb: https://github.com/typicode/lowdb

chokidar has also a cli version

https://github.com/open-cli-tools/chokidar-cli

Used by: https://github.com/typicode/xv - A test runnder by typicode.

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

Docs: https://github.com/typicode/lowdb

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 @ https://stackblitz.com/edit/react-fjnkr5?file=src%2FApp.js

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%

image

Also works via terminal as well:

image

You can close the side navigator have some breathing air:

image

Documentation Generator in Javascript

https://github.com/TypeStrong/typedoc

This is used by kubernetes-client to generated docs for them @ https://github.com/kubernetes-client/javascript

Default values for functions

function a(c = 10) {
	return c
}

console.log(a(null))
// Output: null

console.log(a())
// Output: 10

Ml resources, neural networks

Startup checkout?

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

Source: https://codesandbox.io/s/globalandglobalthis-o262ir?file=/src/App.js

image

FYI: Learn about globalThis: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis

Ngrok docs

https://ngrok.com/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: https://stackoverflow.com/a/66293366/10012446

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

LEARN: nodejs docs: https://nodejs.org/api/globals.html#globals_global

LEARN: I used this global in my own testing library in tihs file: https://github.com/sahilrajput03/learn-express/blob/main/testing-with-my-testing-library/tests/_setup_test_globals.js#L30-L36

Sequnetial execution of aysnc calls

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await…of

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

Why Flameshot?

live reload browser in sync with backend as well

https://dev.to/rajeshroyal/how-to-live-reload-node-js-server-along-with-hot-reloading-2im0

What is a=b=c in code?

let a,b,c
a = b = c = 10
console.log(a,b,c)
// Output: 10 10 10

Checkout my login flow diagram with mermaidjs

Find here.

React dev tools show react hooks state!

image

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
# gclWithSubmodules is aliased to `git clone --recurse-submodules -j8'

edited by cacher.

Using themes with github pages (via jekyll)

Re-add a revert commit?

https://stackoverflow.com/a/29975312/10012446

tldr;

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): https://quii.gitbook.io/learn-go-with-tests/

Go by example: https://quii.gitbook.io/learn-go-with-tests/

Official Go tourhttps://go.dev/tour/welcome/1

Official Go Playground: go.dev/play

Source: Hackerrank article

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

image

Setting size of image in github markdown

Source: https://gist.github.com/uupaa/f77d2bcf4dc7a294d109

![](https://gyazo.com/eb5c5741b6a9a16c692170a41a49c858.png =250x250)
![](https://gyazo.com/eb5c5741b6a9a16c692170a41a49c858.png | width=100)
<img src="https://camo.githubusercontent.com/..." data-canonical-src="https://gyazo.com/eb5c5741b6a9a16c692170a41a49c858.png" 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!

image

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

Source: https://stackoverflow.com/a/8191375/10012446

git submodule update

why shebang is called shebang ?

Source: https://unix.stackexchange.com/a/149048/504112

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

https://github.com/foreversd/forever#readme

Random number generation ?

Joke: https://xkcd.com/221/

Math Stackexchange: https://math.stackexchange.com/questions/255610/easy-way-to-generate-random-numbers

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: https://devopswithkubernetes.com/part-3/3-gke-features
# 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"
}

Source: https://stackoverflow.com/a/3790497/10012446

Proof of convertion trial @ https://www.convertjson.com/yaml-to-json.htm

Using select menus in bash

learn-bash.md#using-select-menus-in-bash

json to xml converter

What is reverse psychology?

https://en.wikipedia.org/wiki/Reverse_psychology

retrieval practise

https://en.wikipedia.org/wiki/Testing_effect

serverless and utility computing

https://en.wikipedia.org/wiki/Serverless_computing

https://en.wikipedia.org/wiki/Utility_computing

firebase

At: console.firebase.google.com

Pricing: https://firebase.google.com/pricing

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: <https://www.gnu.org/software/coreutils/>
# Full documentation <https://www.gnu.org/software/coreutils/env>
# 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?

https://en.wikipedia.org/wiki/Recursive_Bayesian_estimation 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.

Src: https://www.youtube.com/watch?v=xFFs9UgOAlE

memcache used by fb earlier

https://github.com/memcached/memcached

https://memcached.org/

flashcards website

Website: http://cram.com

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

https://stackoverflow.com/a/17516733/10012446

downloading image with axios

Src: https://futurestud.io/tutorials/download-files-images-with-axios-in-node-js

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 https://www.hotjar.com/

(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 https://webflow.com/. See customer stories of webflow users.

Schedule your meets with anybody ? Ans. *A perfect solution*: https://calendly.com/app/signup

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

Source: https://www.npmjs.com/package/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 CHANGELOG.md 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 CHANGELOG.md 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 CHANGELOG.md"
  }

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

monkeypatching ( or _hot fixes) ?

Source: https://en.wikipedia.org/wiki/Monkey_patch

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).

Etymology

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

Source: https://stackoverflow.com/a/9658178/10012446

# 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 kentcdodds.com
  5. Listen to kents podcasts on his https://kentcdodds.com/chats/04.

Declarative vs. imperative

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

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

declarative
1. of the nature of or making a declaration.
"declarative statements"
2. (COMPUTING)
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]: https://google.com "Google - I am hovering text"
[2]: https://yahoo.com "Yahoo - I am hovering text"

# Above code will produce below html-
<a href="https://google.com" title="Google - I am hovering text">Google Link</a>
<a href="https://yahoo.com" 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!

Source: https://blog.openreplay.com/dependency-injection-in-node-js-higher-order-routing-with-express

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

Sample: https://github.com/qutebrowser/qutebrowser/blob/master/doc/userscripts.asciidoc

Avoiding nuclear approach to fix a git repository

Pic Credits: https://xkcd.com/1597/

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: https://stackoverflow.com/a/43762489/10012446

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

.editorconfig file

Source: https://editorconfig.org/

vim: https://github.com/editorconfig/editorconfig-vim#readme

vscode: https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig

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 EXAMPLE 0:
git diff commit4
# Shows changed made AFTER commit4 state.
# this can be done otherwise
git diff commit4 commmit5


# GIT EXAMPLE 1:
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.


# GIT EXAMPLE 2:
# 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 EXAMPLE 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.

# GIT EXAMPLE 4:
# 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.

# GIT EXAMPLE 5:
# 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 .```


# GIT EXAMPLE 6:
# 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: https://stackoverflow.com/a/25064285/10012446
empty=4b825dc642cb6eb9a060e54bf8d69288fbee4904
git diff $empty commit3

# GIT EXAMPLE 6a (COPY OF 6):
#### 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

Source: https://github.com/Rich-Harris/degit

# 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/README.md README.md

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

in/of in for

let k = [1,2,3]

for (i in k){           // in means index
    console.log(i)
}
# Output:
0
1
2


for (i of k){           // of means item itself
    console.log(i)
}
# Output:
1
2
3

List all available scripts/commands from package.json file

npm run
# Source: https://stackoverflow.com/a/59613935/10012446

piping data into nodejs script..

nodemon -x 'ls -l | node test.js'
// code: Source: https://stackoverflow.com/a/16351842/10012446
var stdin = process.openStdin()

var data = ''

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

stdin.on('end', function () {
	console.log('DATA:')
	console.log(data)
	console.log('END DATA')
})
// output:
DATA:
total 12
-rwxr-xr-x  1 array array  501 Feb 11 22:31 echo-with-colors.sh
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

END DATA

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: https://stackoverflow.com/a/49772236/10012446

Source (what does touch do when file already exists?): https://unix.stackexchange.com/a/427240/504112

Directory/File structure in Github

github.com/userName/repoName/tree/branchName/directoryPathHere
e.g., https://github.com/sahilrajput03/learning_rust/tree/master/Lesson1/mouse

github.com/userName/repoName/blob/branchName/filePathHere
e.g., https://github.com/sahilrajput03/learning_rust/blob/master/Lesson1/mouse/mod.rs

TIP: You can download the file via wget, say:
wget https://github.com/sahilrajput03/learning_rust/blob/master/Lesson1/mouse/mod.rs

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 @ https://github.com/sahilrajput03/watchAll/blob/main/watchAll.sh

Check if jre/jdk installed on your system ?

Source

The arguments keyword in a function:

Src.

function func1(a, b, c) {
	console.log(arguments[0])
	// expected output: 1

	console.log(arguments[1])
	// expected output: 2

	console.log(arguments[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" } } } };
console.log(a);
// 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:
app.use(logMw)

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.
ls
# 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.
ls
# 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 @ https://stackoverflow.com/a/2342841/10012446
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.

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.

i.e.,

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: onlineyamltools.com

Example:

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

converts to:

{
  "indian": [
    1,
    "2 > 3",
    "2",
    true,
    "true",
    "truthy",
    null,
    "null",
    {
      "cost": 5
    },
    {
      "otherPeople": null,
      "rohit": 10,
      "admins": {
        "aman": 10,
        "alergy": [
          "dust",
          "particles"
        ]
      }
    }
  ],
  "india": 10
}

yaml.org - Yaml official site.

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

# Example from https://yaml.org ~sahil.
YAML on GitHub: # github.com/yaml/
  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"

In JSON:

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

YAML e.g.2

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

In JSON:

[{
  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:

tasks:
    - 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:

require('colors')

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

@npm: https://www.npmjs.com/package/marked

Also this live markdown parser in the browser @ https://marked.js.org/demo/ 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!

Source

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
)
b.then(
	(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.

image

Sequential way of executing promises:

image

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

Git

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.

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
v=one

$ cat development
v=two

$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
one
$ . curl1
Firing request @ one

################ DEVELOPMENT ENVIRONMENT ################
$ . development
$ echo $v
two
$ . 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
console.time()
while (i < 1000) {
	i++
}
console.timeEnd()

Output: 0.05 ms

i = 1
console.time()
while (i < 1000) {
	i++
	console.log('having fun')
}
console.timeEnd()

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`.
ctrl+h

#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

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


# 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.

Get ur ip address

curl -s https://checkip.amazonaws.com
# Below works too.
curl checkip.amazonaws.com

Save some of keystrokes with logs

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

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

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 https://raw.githubusercontent.com/sahilrajput03/my_bin/master/files/.bashrc-windows/.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 https://raw.githubusercontent.com/sahilrajput03/my_bin/master/files/.prettierrc.js
curl -O https://raw.githubusercontent.com/sahilrajput03/my_bin/master/files/.prettierignore

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 https://asciiflow.com/#/ .

🤠︎ 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

Comments

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

.myEl{
 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'' -->
}

.container{
 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

src: https://codepen.io/sahil-blulabs/pen/jOmrGXg?editors=1010

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

See fix at @ codepen.

Using grid-area names in grid

Article at https://css-tricks.com/simple-named-grid-areas/ .