Learning Log


About this page

I'm trying to make a compliation of sources that helped me create, finish or fix some of the projects I'm currently working on. Some of these logs contain procedures I've been through as well as some few tips and tricks for tools I use.


The main log contains mostly programming related websites and snippets of code.


There's also one log that I use as a notebook for japanese lessons and stuff.


More projectsYou can visit my main page to know more about the things I'm working on: 16th.me

SSH

SSH

SSH without password from Windows

  1. Create key pair
  2. Copy public key to server
  3. Add private key to client ssh-agent (via PowerShell)

Windows 10 OpenSSH Equivalent of ssh-copy-id

How do I set up SSH so I don't have to type my password?

How to use SSH keys for authentication

Starting ssh-agent on Windows 10 fails: "unable to start ssh-agent service, error :1058"

Open ssh for beginners

NextJSTypeScript

TypeScript

Set types on useState React Hook with TypeScript

What does this error say? Type 'ParsedQs' is not assignable to type 'string'

What is "not assignable to parameter of type never" error in TypeScript?

TypeScript isNan only accepts a number

createContext – An argument for 'defaultValue' was not provided

How to define the type of a named function?

How to pass a React component as prop with TypeScript

How to find the package.json version in JavaScript/TypeScript npm project

NextJS

How to set the HTML lang attribute in Next.js?

TypeScript

TypeScript

TLDR - How to make React Context TypeScript compatible

TypeScriptFastifyHTTP

HTTP

HTTP GET with request body

Fastify

Routes options

TypeScript

Destructuring props in the function parameters using TypeScript

How can I cast NextJS router.query as a number?

FastifyDatabaseJWT

JWT

JWT Authentication Tutorial - Node.js

JSON Web Tokens (JWT) are Dangerous for User Sessions—Here’s a Solution

Database

Build restful API with PostgreSQL and Express

Node Postgres GitHub

Fastify

Validation and Serialization

FastifyTypeScript

TypeScript

using process.env in TypeScript

TypeScript: Property does not exist on type '{}'

Fastify

JWT

GitHub Docs

Plugin

GitHub Docs

Autoload

GitHub Docs

server/index.ts

1import path from "path";
2import fastify from "fastify";
3import autoload from "fastify-autoload";
4
5const server = fastify({ logger: true });
6
7server.register(autoload, {
8  dir: path.join(__dirname, "plugins"),
9});
10server.register(autoload, {
11  dir: path.join(__dirname, "routes"),
12});
13
14server.listen(8080, (err, address) => {
15  if (err) {
16    console.error(err);
17    process.exit(1);
18  }
19  console.log(`Server listening at ${address}`);
20});
1📦server  
2 ┣ 📂plugins  
3 ┃ ┗ 📜auth.ts  
4 ┣ 📂routes  
5 ┃ ┣ 📂auth  
6 ┃ ┃ ┗ 📜index.ts  
7 ┃ ┣ 📂post  
8 ┃ ┃ ┗ 📜index.ts  
9 ┃ ┗ 📂user  
10 ┃ ┃ ┗ 📜index.ts    
11 ┗ 📜index.ts

Mac

Mac

Launch VS Code from command line

Cannot add code to PATH, permission denied

Godot

Godot

How to set stream on AudioStreamPlayer2D

Add Sound and Music! - Godot Tutorial - Now You Know Too

PM2Electron

Electron

How to Setup Electron With React and TailwindCSS

TypeError: match.loader.options.plugins is not a function

Use this instead of video's config

1module.exports = {
2  style: {
3    postcssOptions: {
4      plugins: [require("tailwindcss"), require("autoprefixer")],
5    },
6  },
7};

PM2

Error on reboot PM2 error: Error: spawn node ENOENT

Install node instead of using fnm

rename process using pm2 programmatic api

SEONode

Node

How can I set NODE_ENV=production on Windows?

GitHub cross-env

1"start": "cross-env NODE_ENV=production node ."

SEO

Autogenerate meta tags

Open Graph Docs

GodotCRANPXBrowser

Browser

Creating a Chrome extension with React and TypeScript

How to Write Your Own Browser Extension

Create Chrome Extension in React

ESLint: 'chrome' is not defined (no-undef)

NPX

Error while creating new React app ("You are running create-react-app 4.0.3, which is behind the latest release (5.0.0)")

CRA

'INLINE_RUNTIME_CHUNK' is not recognized as an internal or external command

Change script in package.json from:

1"build": "INLINE_RUNTIME_CHUNK=false react-scripts build",

to:

1"build": "set INLINE_RUNTIME_CHUNK=false react-scripts build",

Godot

Interpolation

Detect when interpolation ends

no slow down towards end of lerp /linear_interpolate

Tween

Godot docs

How to animate with Tweens

1tween.connect("tween_completed",self,"custom_method")

GodotNextJSProcreateLinuxMac

Mac

3 Ways to See the Current Folder Path on Mac

How do I determine the current operating system with Node.js

Linux

Install MS Fonts

Locate fonts

1ls /usr/share/fonts

Install Microsoft fonts on Ubuntu

1sudo apt install ttf-mscorefonts-installer

After install refresh font cache files

1sudo fc-cache -vr

Procreate

How to Use Text in Procreate

How To Move Objects In Procreate

# PROCREATE TUTORIAL | How to Install Fonts

NextJS

5 Steps to add Google Analytics to NextJS Application🙌

Godot

Coroutines and signals

1func my_func():
2    yield(button_func(), "completed")
3    print("All buttons were pressed, hurray!")
4
5func button_func():
6    yield($Button0, "pressed")
7    yield($Button1, "pressed")

AudacityDaVinci Resolve

DaVinci Resolve

Delete audio from video

How To Remove Audio From Video In DaVinci Resolve

Audacity

5 Simple Ways To Merge Tracks Into One Track In Audacity How To Remove Background Noise In Audacity

Mac

Mac

Install Homebrew

Homebrew page

1/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Install FNM

GitHub repo

Installing Fast Node Manager (fnm)

First get Homebrew

Then install

1curl -fsSL https://fnm.vercel.app/install | bash -s -- --install-dir "./.fnm" --skip-shell

Then add to .zshrc

1eval "$(fnm env)"

Install Yarn

Getting started

1corepack enable

VS Code

Launch from command line

LinuxGodot

Godot

Get mouse position

Mouse and Input Coordinates

1get_viewport().get_mouse_position()

Mouse visibility

How to hide or disable the mouse cursor?

1Input.set_mouse_mode(Input.MOUSE_MODE_HIDDEN)

Drag N Drop

Smooth Drag N Drop: Godot Guide

Vector Math

Scalar Multiplication

Rect2

Class docs

Class properties

How to get a class property with a string?

Set class property:

1class_instance.set("property_name",value)

Set mouse_filter example:

1$Control.set("mouse_filter", Control.MOUSE_FILTER_IGNORE)

Linux

Eject USB drives / eject command

Samba

Godot

Godot

Center text

BBCode in RichTextLabel

1[center]text[/center]

Node exists

get_node_or_null

Linux

Linux

Moving folder and subfolder to another path

1sudo mv fromPath/ toPath/

https://askleo.com/same-voltage-but-different-amperage/

JSNextJSTMI.JS

TMI.JS

Getting started

NextJS

What's the difference between npm run dev and npm run start in Next.js?

API Routes

API Routes

Understanding how API routes work in Next.js

API in api/example.js

1export default function handler(req, res) {
2  res.status(200).json({ name: 'John Doe' })
3}

Usage

1fetch("/api/example")

Port

How to Set port in next.js

1"scripts": {
2    "dev": "next dev -p 8080", // for dev 
3    "start": "next start -p 8080" // for prod
4},

JS

How to Use Fetch with async/await

SpeechSynthesis

SpeechSynthesis speak docs

SpeechSynthesis voice docs

How To Make Your Computer Speak With JavaScript

speechSynthesis API example gives error

JavaScript speechSynthesis.speak() without user activation is no longer allowed since M71

How to change voice in Speech Synthesis?

Node-cld

GitHub repo

Short strings issue

TinyLD

Way more simple and lightweight and can be used in the browser NPM package

CSSTailwind

Tailwind

Useful to compose custom class styles Extracting component classes with @apply

Font Size

List style

Whitespace

Seems like there is no class to add text-shadow Box-shadow

CSS

Center figure image

Center image into figure

What worked for me

1figure.parent{
2    text-align: center;
3}
4img.child{
5    ...
6}
7figcaption.child{
8    ...
9}

NodeCSSJSObsidianWindows

Windows

How to Get Rid of the Activate Windows Watermark

Obsidian

How to set up iCloud sync in Obsidian mobile to get seamless syncing between your iPhone, iPad & Mac

JS

JavaScript encodeURI()

String.prototype.endsWith()

CSS

\n is not rendering the text in new line

1white-space: pre-line;

Node

FSE Copy sync

FastifyReact

React

Auth context

React GraphQL App (MERNG): #5 Authentication Context

How to use React Context effectively

React query

Mutation side effects

Fastify

fastify-swagger

GitHub Repo

Example video

Using create-fastify-app

1const options = {
2   // Swagger options
3}
4
5module.exports = async function (fastify, opts) {
6  // Place here your custom code!
7  ...
8
9  fastify.register(require("fastify-swagger"), options);
10
11  // Do not touch the following lines
12  ...
13};

TailwindLive2DProcreate

Procreate

How To Duplicate In Procreate | Layers, Objects, and Selections

How to mirror on Procreate

Live2D

Procreate PSD layers to Live2D take up entire canvas

Create a new layer in Photoshop/Photopea and join it with one from Procreate to avoid layers using the entire canvas size

Tailwind

Hide element

Visibility

Align items

Justify center

Space evenly

Spacing between elements

Gap

Translate

Round corners

Breakpoints

Tailwind

Tailwind

Create Next App

[Tailwind Just in Time Tutorial #5 - Tailwind JIT with Next.js](Tailwind Just in Time Tutorial #5 - Tailwind JIT with Next.js)

Tailwind Docs

Autocompletion in VS Code

Check the output view Language server was not running because of unsupported VS Code version. I had to update.

PM2WindowsDiscord JS

Discord JS

Play music command

How To Make A Discord Bot - Music Bot Advanced (2021)

Used libraries

Windows

What Is a Shortcut Virus and How Do You Remove It?

Command Prompt: 11 basic commands you should know (cd, dir, mkdir, etc.)

Change drive in de CMD

1d:

PM2

Configuration file

HTTPJSWindowsLinuxSSHPM2

PM2

How to add dates to pm2 error logs?

SSH

ssh -L forward multiple ports

Linux

get back to the previous location after 'cd' command?

1cd -

Windows

Boot drive to regular USB drive

Wipe it clean How to Wipe a Hard Drive or SSD: Format a PC Drive to Erase All Data

Use Disk Managment > Right click on partition > Change Drive Letter to read as regular drive

JS

Get the extension of a filename using JavaScript

1const getExtension = str => {str.slice(str.lastIndexOf("."))};

HTTP

Status codes

SambaWindowsSSHVS CodePM2

PM2

Persistent applications: Startup Script Generator

How do I delete/flush pm2 logs for only one app?

Can pm2 run an 'npm start' script

VS Code

Remote Development using SSH

Port forwarding section

SSH

Forward port and run in background

Could be useful later: Multiplexing

Windows

Kill tasks

Is there a command in Windows like ps -aux in UNIX?

1tasklist
1taskkill /f /pid <PID>

Samba

Only show shares the logged in user has permissions for

/etc/samba/smb.conf

1[share]
2...
3access based share enum = yes

How do I restart the Samba service?

1sudo service smbd reload

PuttyFastifyPM2GitDiscord JSAxiosJSTampermonkeyLinux

Linux

Samba

How can I set up Samba shares to only be accessed by certain users?

How to connect to Linux Samba shares from Windows 10

Add SSD

Share an external USB drive via Samba on your Raspberry Pi

Kill specific process

Article

About eth0, lo, wlan0

Article

Troubleshooting node app

Add port to ufw

Allow node on Windows firewall

Tampermonkey

How To Install, Use And Write A Userscript

Trying to load jquery into tampermonkey script

Making requests from a script is different from regular browser apps. Tampermonkey has ### GM_xmlhttpRequest

Use Axios and TM

GitHub

JS

Simulate pressing [enter] key on input text

How to simulate a click with JavaScript?

How to execute a function when page has fully loaded?

How to pass arguments to addEventListener listener function?

Add function to scroll event with optimization for requestAnimationFrame: MDN

How to Throttle Scroll Events

Axios

Send auth header

Discord JS

Discord.js sending a message to a specific channel

Git

Git stash

PM2

PM2 Process Management Quick Start

List processes

1pm2 list

By default, all logs are saved into $HOME/.pm2/logs.

Docs

Fastify

Log address

1fastify.listen(8081, function (err, address) {
2  if (err) {
3    console.log('err', err)
4    fastify.log.error(err)
5    process.exit(1)
6  }
7  console.log(address)
8  fastify.log.info(`server listening on ${address}`)
9})

GitHub issue

Putty

SSH Port Forwarding

CLI

1ssh -v -L 8081:127.0.0.1:8081 user@host

Connection to port 8081 forwarding to 127.0.0.1 port 8081 requested.

Discord BotVS CodeLinux

Linux

Ubuntu

Desktop to CLI

How to boot into command line on Ubuntu or Debian

Enable SSH

How to Enable SSH on Ubuntu 20.04

Install git

Atlassian Tutorials

Troubleshooting

After trying the commands for github this message appeared

1E: Failed to fetch http://archive.raspberrypi.org/debian/dists/buster/InRelease  
2E: Some index files failed to download. They have been ignored, or old ones used instead.

I found this to work: Add nameserver

1sudo nano /etc/resolv.conf
1nameserver 8.8.8.8

then sudo apt upgrade

FNM

Alternative to nvm GitHub repo

Run process on background

Choosen answer: How to run node.js app forever when console is closed?

First answer's upstart seems to be maintanance-mode only Docs

More about nohup instead of upstart

Kill a process

How to stop a nohup job that is using for loop in bash?

Create a File with Touch Command

1touch test.txt

Install MongoDB on Raspberry Pi

Really good resource to setup Mongo

Tutorial

The instructions above have mostly been taken from Install MongoDB Community Edition on Ubuntu

Fix Connection refused

Mongod complains that there is no /data/db folder

MongoDB.service failed with result exit-code

Connect remotely

How To Configure Remote Access for MongoDB on Ubuntu 20.04

VS Code

Remote SSH

Extension

Discord Bot

Install Canvas

GitHub repo

Run sudo apt-get install build-essential libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev and then yarn

MongooseEmmetNext JSPrime React

Prime React

Getting Started with NextJS and PrimeReact

Next JS

Authentication in next

Docs

Blog post

Emmet

Multiple class names

Mongoose

select on Model.create

TL;DR: use destructuring instead

select specific fields in Model.create

FormikAxiosMongooseFastify

Fastify

Auth

Fastify authentication strategy

Shorthand declarations

1fastify.get(path, [options], handler)

Mongoose

Create and then populate

1let user = await User.create({ ... })
2user = await user.populate('company')

Axios

Attach auth header to all requests

1import axios from 'axios';
2
3const fetchClient = () => {
4  const defaultOptions = {
5    baseURL: process.env.REACT_APP_API_PATH,
6    method: 'get',
7    headers: {
8      'Content-Type': 'application/json',
9    },
10  };
11
12  // Create instance
13  let instance = axios.create(defaultOptions);
14
15  // Set the AUTH token for any request
16  instance.interceptors.request.use(function (config) {
17    const token = localStorage.getItem('token');
18    config.headers.Authorization =  token ? `Bearer ${token}` : '';
19    return config;
20  });
21
22  return instance;
23};
24
25export default fetchClient();

Ejecting interceptors

GitHub

1const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
2axios.interceptors.request.eject(myInterceptor);

CORS

StackOverflow

1headers: {"Access-Control-Allow-Origin": "*"}

Formik

React Bootstrap and Formik

Next JSReactFastifyNode JS

Node JS

Fetch async

1const getData = async () => {
2  const res = await fetch("https://opentdb.com/api.php?amount=10");
3
4  const data = await res.json();
5
6  console.log(data);
7};
8
9getData();

Paths

NodeJS Docs

1const notes = '/users/joe/notes.txt'
2
3path.dirname(notes) // /users/joe
4path.basename(notes) // notes.txt
5path.extname(notes) // .txt

How to log an object in Node.js

1console.log(JSON.stringify(obj, null, 2))

Fastify

CORS

GitHub Repo

React

React Query

Initial setup

Next JS

Env variables

Documentation

Raspberry Pi

Raspberry Pi

Building a Raspberry-Pi Storage Server with OpenMediaVault

Install command

Node JSPackage JSONRegexDiscordJSRaspberry Pi

Raspberry Pi

How to Connect a Hard Drive to Raspberry Pi (And Why You Should)

How to set up Samba file sharing on a Raspberry Pi

DiscordJS

Have discord.js bot send TTS Message?

Regex

Test if regex is on a string: MDN

Package JSON

How can I run multiple npm scripts in parallel?

Node JS

How to create a directory if it doesn't exist using Node.js

node-fs-extra copySync

Fastify

Fastify

Fastify Tutorial (better than Express?)

Create with boilerplate

1npm init fastify

Add autocompletion

1/**
2 *  @param {import('fastify').FastifyInstance} fastify
3 */

Raspberry Pi

Raspberry Pi

I Turned A Raspberry Pi Into A Node.js Web Server

HTMLAudio

Audio

How to Set Audio Levels for Video

HTML

Forms

Code example:

1<form action="#" id="form">
2  <fieldset>
3    <legend>Form inputs</legend>
4
5    <label for="name">Name</label>
6    <input type="text" id="name" name="name" />
7
8    <label for="phone">Tel</label>
9    <input type="tel" id="phone" name="phone" />
10
11    <label for="email">Email</label>
12    <input type="email" id="email" name="email" />
13
14    <label for="date">Date</label>
15    <input type="date" id="date" name="date" />
16
17    <label for="number">Number</label>
18    <input type="number" id="number" name="number" min="0" max="10" />
19
20    <hr />
21
22    <label>
23      <input type="radio" name="option" value="option1" />
24      Option 1
25    </label>
26    <label>
27      <input type="radio" name="option" value="option2" checked />
28      Option 2
29    </label>
30    <label>
31      <input type="radio" name="option" value="option3" />
32      Option 3
33    </label>
34
35    <hr />
36
37    <label for="select">Select</label>
38    <select name="select" id="select">
39      <option selected>Select one...</option>
40      <option value="option1">Option 1</option>
41      <option value="option2">Option 2</option>
42      <option value="option3">Option 3</option>
43    </select>
44
45    <hr />
46
47    <textarea
48      name="textarea"
49      id="textarea"
50      cols="30"
51      rows="10"
52      placeholder="Type in here..."
53    ></textarea>
54
55    <hr />
56
57    <label>
58      <input type="checkbox" value="true" name="checkbox" checked />
59      Opt in
60    </label>
61
62    <br />
63  </fieldset>
64
65  <button type="submit">Submit</button>
66</form>

Log form data to console

Using FormData Objects Effectively

1const formElement = document.getElementById("form");
2
3formElement.addEventListener("submit", handleForm);
4
5function handleForm(event) {
6  event.preventDefault();
7  let form = event.target;
8
9  let formData = new FormData(form);
10
11  for (let key of formData.keys()) {
12    console.log(key, formData.get(key));
13  }
14}

Parse FormData to JSON

How to convert FormData (HTML5 object) to JSON

1JSON.stringify(Object.fromEntries(formData));

NodeVirtualBox

VirtualBox

Fullscreen

Use fullscreen

Exit fullscreen mode

Node

Download images

image-downloader

1import download from "image-downloader"
2
3const url = "http://someurl.com/image.jpg"
4const dest = "/path/to/dest"
5
6 download.image({ url, dest })
7    .then(({ filename }) => {
8        console.log("Saved to", filename)
9    })
10    .catch((err) => console.error(err))

Godot

Godot

Get immediate parent

1get_owner()

Get sprite dimension

1sprite.texture.get_width()
2sprite.texture.get_height()

Node JSGodot

Godot

_unhandled_input vs _input

InputEvent docs

Default arguments

Change cursor via script

1Input.set_default_cursor_shape(Input.CURSOR_ARROW)

Connect to self via script instead of editor

1func _ready():
2    connect("mouse_entered",self,"_on_mouse_entered")
3    
4func _on_mouse_entered():
5    print("_on_mouse_entered")

InputEvent trigger only on pressed or released instead of both

1func _unhandled_input(event):
2    if event is InputEventMouseButton:
3        if event.button_index == BUTTON_LEFT:
4            if event.pressed:
5                print("Left button was clicked at ", event.position)
6            else:
7                print("Left button was released")

Node JS

Take screenshots

Mongo

Mongo

Associations

1import mongoose from "mongoose";
2
3const modelName = "myModel";
4
5const schema = new mongoose.Schema({
6  field: {
7    type: mongoose.Schema.Types.ObjectId,
8    ref: refModelName,
9  },
10});
11
12const Model = mongoose.model(modelName, schema);

Query with populated values instead of reference

1Model.findById(ID).populate(refModelName).exec();

CSSNext JSGodot

Godot

Check if is debug or build environment

How to use the Input Map

Next JS

Hashbanging in NextJS

CSS

Add scroll offset

Documentation

1html {
2 scroll-padding-top: 4rem;
3}

HTMLObsidianBootstrap

Bootstrap

Using dropdowns

Obsidian

How to convert text to link on paste

HTML

Ruby Text

Documentation

Visual example:

明日 (Ashita)

Code example:

1<ruby>
2    明日 <rp>(</rp><rt>Ashita</rt><rp>)</rp>
3</ruby>

Node

Node

1import { readFile } from "fs/promises";
2
3const path = new URL("index.html", import.meta.url);
4
5let template = await readFile(path, "utf-8");
6
7const data = {
8 title: "Learn Node JS",
9 body: "This is the final HTML",
10};
11
12for (const [k, v] of Object.entries(data)) {
13 template = template.replace(`{${k}}`, v);
14}
15
16console.log(template);

Import fs/promises to get the promise version of the file system utils

Use new URL() instead of join and import.meta.url instead of __dirname

Using await on the top level is one of the new features in Node