Source: Click here
AWS, AZURE, Cloudflare, Heroku, Render, Vercel cloud pricing comparison.
Official StackOverflow Question Here: Click here
Erlang:
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.
https://www.pageflow.ai/
From ChatGPT: Click here
Source: Click here
Chrome Extension: Click here
Source: Click here
Docs: Click here
TLDR; When you want to share screen from laptop you feel that that:
Source: Click here
In software development, different types of releases denote various stages of development and testing. Here are some common types:
Alpha Release: This is an early version of the software that is typically not feature-complete. It is released to a limited audience, often within the development team, for initial testing and feedback.
Beta Release: A more polished version compared to alpha, beta releases have most features implemented but may still contain bugs. They are released to a larger group of users for broader testing and to gather user feedback.
Gamma Release: Unlike alpha and beta, gamma releases are not as commonly used or standardized in the software development process. The terms alpha and beta are more widely recognized and adopted in industry practices.
Release Candidate (RC): This is a version that is considered feature-complete and stable. If no critical bugs are found during testing, the release candidate becomes the final release.
General Availability (GA) or Release to Manufacturing (RTM): This is the final version of the software that is ready for public use. It has passed all testing phases and is deemed stable for widespread deployment.
Canaray Releases (source): 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.
These terms may vary slightly in usage between different development teams and projects.
Wikipedia: Click here
Erp Serivce used by Zerodha (mentioned in their hello world article on their website):
Refer my notes on other page: Click here
sort_name
by which we can sort via the after
id of the last set of items when we use cursor based paginationFor this we use: sort_name=${doc.name}_{doc._id.toString()}
so this helps us establish cursor based pagination.
Make sure you use website to click below links from mobile (not on github page).
we get completions for aggregate pipelines as well:
TLDR: No (though probably yes if you run adb restart
command)
https://killedbygoogle.com/
TLDR: In backend.
Check my example on Github Repository: - Click here
// Searching books on amazon via a url:
// https://www.amazon.com/s?k=Christine+by+Stephen+King&i=stripbooks-intl-ship
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).
Check this issue’s comment: Click here
Github: Click here
Source: Click here
javascript:(function() {
console.log("Hello, World!");
})();
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.
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.
is
Source: Click here
It is a key ad performance metric used by publishers to monitor the revenue generated from the ads on their site.
~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).
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.
Solution: StackOverflow Answer: Click here
We had to set English US
as the only keyboard in Keyboard Settings
in Settings.
Docs: Click here
Screen Capture - Chrome Extension: Click here
npm i
and npm ci
Source: Click here
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/
Ideally we should have development and staging environments separately. Where “develop” is always stable version of production, and staging is purely tesitng
saucelabs
to test apps in different browserSuggested by damon
Source - https://saucelabs.com/
More official from telegram projects:
Source of below Image: [Click here(https://owasp.org/www-community/HttpOnly)
MDN: Click here
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):
Hiding root from google-pay, etc banking apps(tested on redmi note 5 - 2-april-2023)
Source: Click here
pause
(,) and delay
(;) while dialing callsSource: 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.
js-cookies
bad?Zero-based index
You can share your recorded video simply by that feature:
defer
vs. async
in script tag in htmlSource: Click here
PlanteScale, Pricing: Click here
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)
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
npm run xxx
do?Medium Handle on the author: Click here
Source: Click here
https://gdpr-info.eu/
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
user-signin.dto.ts
in some projects)Source: Click here
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
Moe the better, as much your server can tolerate but be somewhat practical.
Source: Click here
Source: Click here
NO!
Read more on these stackoverflow answers:
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
Amazing:
Source: Click here
https://stackoverflow.com/questions/48958304/pkcs1-and-pkcs8-format-for-rsa-private-key
Source: Click here
Source: Click here
Source: Click here
f5(start)
f10(step)
f11(step inside)
shift+f11(step outside)
ctrl+shift+f5(restart debugger)
shift+f5(stop debugger)
"dependencies": {
"redux-persist-transform-encrypt": "github:shagundev/redux-persist-transform-encrypt"
}
Tip: You can login to mandrillapp.com using mailchimp logged in accound with oauth automatically. :D
https://vercel.com/blog/using-vercel-comments-to-improve-the-next-js-13-documentation
Visit here to try it: https://beta.nextjs.org/docs
https://app.resemble.ai/
Another good seeming opensource project claminng to have good quality of voice cloning:
https://github.com/Urigo/graphql-mesh
https://www.reddit.com/r/ethereum/comments/ybikdd/ai_and_the_blockchain_are_we_living_through_the/
// '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
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.
https://www.google.com/search?q=life+is+awesome
Source: integer overflow (wraparound) can’t be better explained than using this odometer example. 😅
https://blog.codinghorror.com/the-last-responsible-moment/
All function names are in lower camelCase (eg. sendCoin) and all event names are in upper CamelCase (eg. CoinSent). Source
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.
Doesn’t support postgres or mondodb.
Good service for mysql hosting: https://planetscale.com/
https://www.zuddl.com/
alias findNodeModules='sudo find . -name 'node_modules' -type d -prune'
alias deleteNestedNodeModules="sudo find . -name 'node_modules' -type d -prune -exec rm -rf '{}' +"
https://stackoverflow.com/help/minimal-reproducible-example
https://github.com/gqty-dev/gqty
https://gist.github.com/samoshkin/c0a2c0dd85b1d5b02d893a0f6ac0e93c
what is sloc?
React Giscus Component: Click here
Inspiration: https://github.com/simoneb/axios-hooks#manual-requests
https://github.com/isaacs/node-lru-cache
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
Chrome Extension: CORS Unblock
To test if cors get unblocked you can check via that page:
Source: https://developers.google.com/maps/documentation/javascript/get-api-key
Use chrome in desktop mode and then you’ll be able to add pictures as well, yo!
https://youtu.be/3_FcxGCCnUs
https://www.netlify.com/blog/rewrite-html-transform-page-props-in-nextjs/
Source: Kyle
Maps are for objects, and sets are for arrays.
Sets store unique values only:
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
source: https://pagespeed.web.dev/
Source: https://gtmetrix.com/
Github: https://github.com/vadimdemedes/ink
@mdn: https://developer.mozilla.org/en-US/docs/Web/API/console
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:
Firebase cons: ~Sahil (points I have currently in my mind)
Source: https://stackoverflow.com/a/29262643/10012446
// 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' })
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
Q. How does flatten work in Keras ?
Ans. https://stackoverflow.com/questions/44176982/how-does-the-flatten-layer-work-in-keras
Color Depth: @wikipedia
let flag = true
setTimeout(() => {
flag = false
}, 500)
void (async function () {
await new Promise(res => setTimeout(res, 1_000))
console.log('Final:', flag) // Output: false
})()
A flaky test is an analysis of web application code that fails to produce the same result each time the same analysis is run.
https://github.com/readthedocs/readthedocs.org used to make solidity docs.
https://www.monterail.com/blog/flutter-vs-react-native-mobile-development
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
People in this earth is 8 Billion (8.0e+09)
tldr; If a framework is opinionated, it lock or guides you into their way of doing things.
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"
}
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.
scrollTo - MDN scrollIntoView - MDN
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
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!!
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
https://javascript.plainenglish.io/its-2022-don-t-abuse-the-arrow-function-anymore-905862a9c668
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 -
@mdn docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
const { deepStrictEqual:dse } = require('assert');
let a = {x: 10, y: 10}
let b = {x: 10, z: 20}
dse(a,a)
dse(a,b)
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.
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}
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
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
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
Date: 17 Nov, 2021 - Click here
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 ?https://www.descript.com/lyrebird
~ Varun mayy, you can make text to sound of your own voice with that.
Github: https://github.com/PostHog/posthog
Used by Varun Mayyas he tells in this video.
Visit at: https://posthog.com/
https://www.uisources.com/home
~Varun mayya’s frined, src: here-timestamped
https://www.amp-what.com/unicode/search/up%20arrow
https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/Getting_started#anatomy_of_an_html_document
Awesome: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
Src: https://youtu.be/AdNJ3fydeao?t=949
ni
package mangager :LOL:https://github.com/antfu/ni
.gitignore
files for different enviornmentshttps://github.com/github/gitignore
https://github.com/github/gitignore/blob/main/Node.gitignore
Insert at
in arrays in jsvar 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
https://huggingface.co/
https://github.com/huggingface/transformers
Source: https://fullstackopen.com/en/part4/token_authentication#problems-of-token-based-authentication
Source: https://shopify.engineering/how-we-built-hydrogen
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)]))
})
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.
((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 supertestchaijs is assertion library like assert
+ http testing library like supertest
https://www.chaijs.com/plugins/chai-http/
console.log
s?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
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
Youtube: https://www.youtube.com/watch?v=giCx1LPizXU
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);
});
https://github.com/fullstack-hy/part13-notes/tree/part13-2
How to Create & Test your WhatsApp Chatbot (No Coding)
Source: css-tricks
<input inputmode="numeric" type="text" name="creditcard">
npm set-script prepare "husky install"
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
This is magically amazing!!
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.
Source: https://stackoverflow.com/a/64507176/10012446
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.
https://engineering.fb.com/2020/08/24/production-engineering/scaling-services-with-shard-manager
https://stackoverflow.com/questions/34855352/how-in-general-does-node-js-handle-10-000-concurrent-requests
https://www.quora.com/Is-it-possible-for-server-to-handle-around-100-000-requests-per-second-If-so-which-would-you-recommend
express-async-errors
npm packageGo to https://github.com/sahilrajput03/learn-express
Source: https://www.npmjs.com/package/commander
22.7k Github Stars, It has more than 73m weekly downloads(from npmjs.com)
You can do this by mapping port of router ip (probably 192.168.18.1) to public ip in your router settings.
.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.
FYI: To make the env file provided as argument is implemented via dotenv
like this:
flash-runner
npm packageBrowse @ https://www.npmjs.com/package/flash-runner
Github @ https://github.com/sahilrajput03/flash-runner-npm
npm i flash-runner
https://stackoverflow.blog/2021/06/07/most-developers-believe-blockchain-technology-is-a-game-changer-3/
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.
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
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.
https://github.com/tailwindlabs/tailwindcss
Find my own demo app @ https://github.com/sahilrajput03/cssDesignTrail/tree/master/learn-tailwindcss
Its revolutional for me personally!
jest
and react-testing-library
(or enzyme
)Source: https://jestjs.io/docs/tutorial-react
Source: https://academind.com/tutorials/localstorage-vs-cookies-xss . Wanna read about cors from same author ?. Mdn - Restrict access to cookies.
DomPurify
(discovered with Eric) - A library to clean thirdparty html if you want to use that on your website: Github
Browse @ https://codesandbox.io/s/low-db-clone-t4lbln?file=/src/App.js
Lowdb: https://github.com/typicode/lowdb
chokidar
has also a cli versionhttps://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!
TESTED: Works 100%
Also works via terminal as well:
You can close the side navigator have some breathing air:
https://github.com/TypeStrong/typedoc
This is used by kubernetes-client to generated docs for them @ https://github.com/kubernetes-client/javascript
function a(c = 10) {
return c
}
console.log(a(null))
// Output: null
console.log(a())
// Output: 10
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
FYI: Learn about globalThis
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
https://ngrok.com/docs
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
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await…of
Tags: #Parallel execution, #sequential execution, etc.
Print-screen
buttonon keyboard and press ctrl+c (or ctrl+s to save instead) to copy full screen screenshot.https://dev.to/rajeshroyal/how-to-live-reload-node-js-server-along-with-hot-reloading-2im0
a=b=c
in code?let a,b,c
a = b = c = 10
console.log(a,b,c)
// Output: 10 10 10
Find here.
Yes its all there, but that changes in react state are reflected with a delay of like 500ms IMO ~Sahil.
Adding a github submodule
git submodule add "github_url" directory_path
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.
Just use
gclWithSubmodules
# gclWithSubmodules is aliased to `git clone --recurse-submodules -j8'
edited by cacher.
https://stackoverflow.com/a/29975312/10012446
tldr;
You can simply revert the revert commit to undo the revert via git revert <revertCommitShaHere>
. ~Sahil
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
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
https://github.com/gamontal/awesome-katas
https://github.com/ahmdrefat/awesome-koans/blob/master/koans-en.md
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). |
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" />
Source: Q/A
**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!
Source: https://stackoverflow.com/a/8191375/10012446
git submodule update
Source: https://unix.stackexchange.com/a/149048/504112
forever
a npm package to ensure ensure that a script is running foreverhttps://github.com/foreversd/forever#readme
Joke: https://xkcd.com/221/
Math Stackexchange: https://math.stackexchange.com/questions/255610/easy-way-to-generate-random-numbers
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.
# 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.
learn-bash.md#using-select-menus-in-bash
https://www.freeformatter.com/json-to-xml-converter.html#ad-output
https://www.convertjson.com/json-to-xml.htm
https://en.wikipedia.org/wiki/Reverse_psychology
https://en.wikipedia.org/wiki/Testing_effect
https://en.wikipedia.org/wiki/Serverless_computing
https://en.wikipedia.org/wiki/Utility_computing
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.
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 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.
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
https://github.com/memcached/memcached
https://memcached.org/
Website: http://cram.com
Playstore App (free services): Click here
You may login with google simply. It has a playstore app as well.
https://stackoverflow.com/a/17516733/10012446
Src: https://futurestud.io/tutorials/download-files-images-with-axios-in-node-js
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
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”.
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
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.
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}'
alias lsg='ls -a | grep -i'
# Usage:
lsg json
lsg -E '*json'
# NOTE: quotes are important.( double quotes work as well).
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>
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
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 jsfor await (const i of [Promise.resolve(10), Promise.resolve(20), Promise.resolve(30)]){
console.log(await i)
}
# Output:
# 10
# 20
# 30
myFile.asciidoc
Sample: https://github.com/qutebrowser/qutebrowser/blob/master/doc/userscripts.asciidoc
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
fileSource: https://editorconfig.org/
vim: https://github.com/editorconfig/editorconfig-vim#readme
vscode: https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig
Sample I came across:
$ 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
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.
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
npm run
# Source: https://stackoverflow.com/a/59613935/10012446
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!
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
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
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.
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.
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'
Browser @ https://github.com/sahilrajput03/watchAll/blob/main/watchAll.sh
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)
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' } } }
// }
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 🍭
Refer @ node-with-live-testing project.
// Usage:
lgMw(req) // in any route or controller.
// or use as a common middleware:
app.use(logMw)
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.
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.
<MyComp className={['carl', 'barl', 'amaz'].join()}></MyComp>
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)
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!
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!)
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!
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.
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.
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.
git add the_left_out_file
git commit --amend --no-edit
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
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:
curl -D - my_url
to get response headers as well.curl -v my_url
to view the verbosed output that has every minute detail you might want to see to debug anything.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.
#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.
$ 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.
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.
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
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.
curl -s https://checkip.amazonaws.com
# Below works too.
curl checkip.amazonaws.com
// commonjs
const {log: l} = require('console')
l('i love commonjs modules.')
//esm
import {log as l} from 'console'
l('i love esm modules')
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 :)
prettier-write
script to your package.json file using commandnpm 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
Browse at https://asciiflow.com/#/ .
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).
Link to Article docs, Massive different guides for importing to codesandbox directly
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.
.myElement {
position: absolute/relative;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
}
.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;
}
p ~ ul {
background: #ff0000;
/*This will apply to all ul's that are anywhere(not just next to it) after the p tag.*/
}
src: https://codepen.io/sahil-blulabs/pen/jOmrGXg?editors=1010
grid-gap: 0
is not working ??See fix at @ codepen.
Article at https://css-tricks.com/simple-named-grid-areas/ .