Live Server with NodeJS

The NodeJS live-server package runs a temporary server displaying any HTML/CSS/JS resources in the current folder. It automatically reloads the page in your browser when any of these files change.

  • Verify that Node.js is installed. If you see anything when you run which npm in a terminal, it is. If not, follow the instructions at nodejs.org to install.
  • Install live-server: npm install -g live-server
  • Move your terminal to where your pages live: cd <path-to-content>
  • Start the server: live-server .
  • Open localhost:8080 in a browser.

Disable/Enable Spotlight in Mac OS with Terminal

Disabling Spotlight in MacOS is pretty easy, launch the Terminal and type the following command:

sudo mdutil -a -i off

This tells the Spotlight manager to disable all indexing on all volumes, the command will require your administrative password to execute.

Re-enabling Spotlight in MacOS is just as easy, just reverse the command to:

sudo mdutil -a -i on

Now Spotlight indexing will be back on and work as usual.

How to encode and decode HTML entities with JavaScript

In JavaScript, decoding and encoding HTML entities is a common task when dealing with user-generated content or manipulating strings. These functions can be used to encode and decode HTML entities as there is no built-in method in JavaScript. It’s essential for securing and properly displaying user input in web applications.

Decode HTML-entities

function decodeHTMLEntities(text) {
  var textArea = document.createElement('textarea');
  textArea.innerHTML = text;
  return textArea.value;
}

Decode HTML-entities (JQuery)

function decodeHTMLEntities(text) {
  return $("<textarea/>")
    .html(text)
    .text();
}

Encode HTML-entities

function encodeHTMLEntities(text) {
  var textArea = document.createElement('textarea');
  textArea.innerText = text;
  return textArea.innerHTML;
}

Encode HTML-entities (JQuery)

function encodeHTMLEntities(text) {
  return $("<textarea/>")
    .text(text)
    .html();
}

Increase Your Apple Magic Mouse Speed

Magic Mouse Speed Increse
Increasing the magic mouse speed is incredibly simple using just a few Terminal commands. Here is exactly what you need to do:
  1. Open Terminal (Applications > Utilities > Terminal)
  2. Type this command to see your current mouse speed setting:
defaults read .GlobalPreferences com.apple.mouse.scaling

or

defaults read -g com.apple.mouse.scaling
  1. To increase the speed, enter a new scaling value like so. The default is 3 – try something between 4-12:
defaults write .GlobalPreferences com.apple.mouse.scaling 8

or

defaults write -g com.apple.mouse.scaling 5
  1. When ready, quit Terminal and reboot your Mac for the new setting to take effect.

That’s all there is to it! Once your system boots back up, you’ll instantly notice how much faster and more responsive your mouse movement is.

The reason this works is it overrides the default scaling value set by Apple. They configure the Magic Mouse Speed out of the box to be slower than the maximum speed allowed in System Preferences. But with this quick terminal command, you can boost it well beyond the standard limit.

Create folder and file from string on MacOS

tell application "Finder"
	display dialog "File Name:" default answer ""
	set fileNameWithPath to the text returned of result
	if length of fileNameWithPath = 0 then
		return 0
	end if
	set thisFolder to the target of the front window as alias
	
	set oldDelimiters to AppleScript's text item delimiters
	set AppleScript's text item delimiters to "/"
	set myFolderFileList to every text item of fileNameWithPath
	set AppleScript's text item delimiters to oldDelimiters
	
	set fileName to the last item of myFolderFileList -- get last item
	if length of myFolderFileList > 1 then
		set myFolderList to myFolderFileList's (items 1 thru -2) --remove last item
		
		repeat with folderName in myFolderList
			if length of folderName > 0 then
				if (exists folder folderName of thisFolder) is true then
					set newThisFolder to thisFolder & folderName as text
					set thisFolder to newThisFolder as alias
				else
					set thisFolder to make new folder with properties {name:folderName} at thisFolder
				end if
			end if
		end repeat
	end if
	
	if length of fileName > 0 then
		make new file at thisFolder with properties {name:fileName}
	end if
end tell

Vanilla JavaScript Ajax

JavaScript AJAX (Asynchronous JavaScript and XML) is a technique that gives the ability to send and receive data asynchronously from a web server. AJAX allows you to create rich, responsive user interfaces. It makes it easy to update data on the page without having to reload the entire page. It makes your application more responsive and user-friendly.

I’m going to show you two different ways to make an Ajax request.

1. Using XMLHttpRequest object:

XMLHttpRequest (also known as XHR) object. This object is built into most browsers (even in Internet Explorer) and allows you to send requests and receive responses without having to reload the page.

Get request:

// Create the XMLHttpRequest object.
const xhr = new XMLHttpRequest();
// Initialize the request
xhr.open("GET", 'https://jsonplaceholder.typicode.com/users');
// Send the request
xhr.send();
// Fired once the request completes successfully 
xhr.onload = function(e) {
    // Check if the request was a success
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
    	// Get and convert the responseText into JSON
    	var response = JSON.parse(xhr.responseText);
    	console.log(response);
    }
}

Post request:

// Create the XMLHttpRequest object.
const xhr = new XMLHttpRequest();
// Initialize the request
xhr.open("POST", 'https://jsonplaceholder.typicode.com/users', true);
// Set content type
xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8');
// Send the request with data to post
xhr.send(
    JSON.stringify({
        name : "Jon Doe",
        username : "jon-doe",
        email : 'jon-doe@unknown.com'
    })
);
// Fired once the request completes successfully 
xhr.onload = function(e) {
    // Check if the request was a success
    if (this.readyState === XMLHttpRequest.DONE && this.status === 201) {
    	// Get and convert the responseText into JSON
    	var response = JSON.parse(xhr.responseText);
    	console.log(response);
    }
}

2. Using fetch() method:

fetch() method is the newer, easier, and best method to make Ajax requests. The fetch() method returns a promise that can be used to handle the response data. Though, this method won’t work on old browsers like Internet Explorer.

Get request:

// Create and Send the request
var fetch_status;
fetch('https://jsonplaceholder.typicode.com/userssss', {
    method: "GET",
    headers: {
        "Content-type": "application/json;charset=UTF-8"
    }
})
.then(function (response) {
    // Save the response status in a variable to use later.
    fetch_status = response.status;
    // Handle success
    // eg. Convert the response to JSON and return
    return response.json();
}) 
.then(function (json) {
    // Check if the response were success
    if (fetch_status == 200) {
        // Use the converted JSON
        console.log(json);
    }
})
.catch(function (error){
    // Catch errors
    console.log(error);
}); 

Post request:

// Create and Send the request
var fetch_status;
fetch('https://jsonplaceholder.typicode.com/users', {
    method: "POST",
    // Set the headers
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    // Set the post data
    body: JSON.stringify({
        name : "Jon Doe",
        username : "jon-doe",
        email : 'jon-doe@unknown.com'
    })
})
.then(function (response) {
    // Save the response status in a variable to use later.
    fetch_status = response.status;
    // Handle success
    // eg. Convert the response to JSON and return
    return response.json();
}) 
.then(function (json) {
    // Check if the response were success
    if (fetch_status == 201) {
        // Use the converted JSON
        console.log(json);
    }
})
.catch(function (error){
    // Catch errors
    console.log(error);
}); 

In the above snippets, once the fetch() method’s request is successfully executed on the server, the first then() method converts the response data info a JavaScript object. Then, in the second then() method, we can use the object to do whatever we want to do. If there were any errors encountered in the chain, it would pass into the catch() method.

Setup x11vnc server with systemd auto start up

The reason I use x11vnc is that it connects to the existing graphical session. Most other vnc servers will spawn an entirely new graphical session. While that is super cool, I don’t want that feature. This is for remote support, where I want the user and the supporter to share the same session. I use the ‘-auth guess’ to have x11vnc guess the XAUTHORITY file‐name and use it appropriately. This avoids the annoying hard coding of gdm, lightdm, xdm or specific users .Xauthority.

Install x11vnc
# apt-get install x11vnc

The following should work for any distro that uses systemd, just the apt bits are Debian specific.

Generate the password and store it under etc so no users can change this password, only root. You can do this under your users home so that its not managed by root. In my case I didn’t want the user to be able to change or accidentally delete the password.
# sudo x11vnc -storepasswd /etc/x11vnc.pwd

edit (create new) the following file
use whatever text editor you prefer, here I use vi
# sudo nano /etc/systemd/system/x11vnc.service

And add the following, making any changes you want to the x11vnc ExecStart
See the man page for explanations of the switches

[Unit]
Description=Start x11vnc at startup.
After=multi-user.target

[Service]
Type=simple
ExecStart=/usr/bin/x11vnc -auth guess -forever -loop -noxdamage -repeat -rfbauth /etc/x11vnc.pwd -rfbport 5900 -shared -o /var/log/x11vnc.log

[Install]
WantedBy=multi-user.target

Now enable the above, start it and verify its running and listening properly
# systemctl enable x11vnc
# systemctl start x11vnc
# netstat -pat
tcp 0 0 0.0.0.0:5900 0.0.0.0:* LISTEN 2806/x11vnc

Now that the server is all setup lets move onto the client
apt-get install tigervnc-viewer
vncviewer [remote host ip or hostname]

Bulk Convert Images with ImageMagick

To bulk convert images with ImageMagick in a terminal, you need to install ImageMagick to your MAC OS. you can install it from here. After installing you need to add these bash functions to your .zshrc or .bash file. Then you are able to use these functions throughout the terminal.

Bulk Convert Images Functions:

# Convert .svg
convertsvgto(){
	EXT=$1;
	if [[ -z "$EXT" ]]; then
		EXT="jpg";
	fi
	for file in *.svg; do echo "Converting ${file%.*} Image to $EXT"; convert $file "${file%.*}"."$EXT"; done;
	echo "Convert Successful..."
}

# Contert .webp
convertwebpto(){
	EXT=$1;
	if [[ -z "$EXT" ]]; then
		EXT="jpg";
	fi
	for file in *.webp; do echo "Converting ${file%.*} Image to $EXT"; convert $file "${file%.*}"."$EXT"; done;
	echo "Convert Successful..."
}

To convert images go to your images folder and open the terminal. Type these commands. You can change the file format as you want

Bulk Convert Images Usage:

convertsvgto jpg
convertwebpto png