Josh A. Young
Software Engineer

Code Snippets

Below, I have listed some common code snippets that I commonly go back to reference. Maybe you will find some of these useful. I update these routinely and add new ones as I run across them.

Ansible

Ping Command:

  ansible all --key-file ~/.ssh/my_private_key -i inventory -m ping

Run gather facts command:

  ansible all -m gather_facts --limit 192.168.1.100

Become sudo first:

  ansible all -m apt -a update_cache=true --become --ask-become-pass

Run a playbook:

  ansible-playbook --ask-become-pass playboo.yml

ASDF

  • List versions of plugin installed
  asdf list nodejs
  • Show Current Plugins with the Global Version
  asdf current
  • Reshim Note:
    • After running a asdf reshim [plugin] (i.e. asdf reshim nodejs), you might need to reload or shutdown and reopen your terminal for it to properly take affect.

Bash

Services Running on Port

  sudo lsof -i tcp:3000

If/Else

  if [ expression ]
    ...
  then
    ...
  else
    ...
  fi

Assign Variable (spacing is important)

  the_var="a string"
  echo $the_var

Show a process running on a particular port

  netstat -na | grep -i LISTEN | grep '2000\|3000'

Text

Keyboard Shortcuts for Quote Marks

KeyDescriptionWindowsMacHTML
Ellipsisalt+0133option+;…
Opening Single Apostrophealt+0145option+]‘
Closing Single Apostrophealt+0146option+shift+]’
Opening Double Quotealt+0147option+[“
Closing Double Quotealt+0148option+shift+[”
En Dashalt+0150Option + dash–
Em Dashalt+0151Option + Shift + dash—

Curl

Get HTTP Response

  curl -I example.com

Get Just Response Code

  curl -s -o /dev/null -w "%{http_code}" example.com

Curl POST

curl --data "information=to&send=to the server" http://example.com

Blazor

Bundler

Install a different version of bundler

  gem install bundler -v 1.0.10

Run bundle with a different version:

  bundle _2.0.15_ install

C#

Install .NET Package from Command Line

dotnet add package PackageName -v 0.1-pre -s https://url/path/nuget/v3/index.json

Empty IEnumerable

  Enumerable.Empty<XElement>();

Static Instance

  public class MyStaticInstance
  {
    // Our static instantiation:
    public static MyStaticInstance Instance { get; } = new MyStaticInstance();

    // Prevents new instantiations from being possible:
    private MyStaticInstance() { }
  }

Test for Property Changed with xUnit

  Assert.PropertyChanged(viewModel, nameof(viewModel.MyProperty), () => {
    anotherProperty.Title = "new title";
  });

Invoke Property Change Event After List's Add()

  MyListOfValues.Add("an item");
  PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(MyListOfValues)));

Unused variable

  • For an unused variable (in a loop for instance), you can use an underscore _.

Property vs Field

  • A property is a field that has an implicit getter and setter set for it. This getter/setter is setup using the get; and set;. Usually this manifests itself as a public getter that returns a private field. Here is an example:
    • public string Name { get; set; };
  • A field in C# does not have a backing field and has no getter or setter set for it. Here is an example:
    • public string Name;

Prefer Named Arguments:

  public void FullName(string first, string last)
  {

  }

  // Call method like this:
  fullName(first: "Joe", last: "Smith");

  // Not like this:
  fullName("Joe", "Smith");

CSS

Switch to box sizing

html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

Clear Floats

.clearfix:after {
  content: "";
  display: block;
  clear: both;
  height: 0;
  visibility: hidden;
}

Margin/Padding Shorthand

//top right bottom left:
margin(or padding): 10px 20px 10px 20px;

//top/bottom left/right:
margin(or padding): 10px 20px;

//top left/right bottom:
margin(or padding): 10px 20px 10px;

Dev Tools

Chrome

Output selected element in console
$0
Logging:
console.log('test string');
Log Variable as an Object:
console.dir(paragraph);
Log an object as a table:
console.table(all_animals);

Docker

Show containers
docker-compose ps
List all Images
docker image ls -a
List all Containers
docker container ls -a
List all Volumes
docker volume ls
Start containers in docker-compose
docker-compose up
Kill Dangling Docker Process:
docker-compose down docker rm -fv $(docker ps -aq) sudo lsof -i -P -n | grep 5432
Stop a container
docker stop [container name]
Stop Running Containers
docker container stop $(docker container list -q)
Stop All Running Containers
docker container ps -q | xargs docker container stop
Prune System - use caution with this
docker system prune -a
Delete All Images (be careful!)
docker image ls -q -a | xargs docker image rm -f
Delete All Containers (be careful!)
docker container ps -q -a | xargs docker container rm
Delete All Volumes (be careful!)
docker volume ls -q | xargs docker volume rm
Copy File from Container to Host
docker cp container_name:/path/to/file/on/container.txt /path/on/host/
Detach from a Running Container
Ctrl+P then Ctrl+Q
Re-attach to a Running Container
docker attach [container id]
Show Mounts
docker inspect -f "{{ .Mounts }}" [container id]
Show Docker Stats
docker stats
Start a container
docker start [container name]
Docker `exec` vs `attach`
`exec` creates a new instance of the container and connects to it. `attach` connects to the currently running instance.
Connect to a running container
docker exec -it [image name] /bin/bash
Spin up and Build
docker-compose up --build
Boot Up Detached
docker-compose up -d
Run, Build, and Detach
docker-compose up --build -d
Run a Service and Expose the Ports
docker-compose run --service-ports dev rails server -b 0.0.0.0
Docker compose - bust the cache
docker-compose build --no-cache
Run a single image through compose
docker-compose run dev rails server -b 0.0.0.0
Spin up container
Start a Single Service via Docker Compose
docker-compose up -d service_name
docker restart $(docker ps -q)
Copy file from host to container
docker cp file.txt container_id:/file.txt
Copy file from container to host
docker cp container_id:/file.txt file.txt
Force the Re-creation of Container
docker-compose up --force-recreate
Restart All Containers
docker-compose up
Turn off container
docker-compose down
List running containers
docker-compose ps
Attach to running container
docker exec -it [container name] /bin/bash
Delete all Images
docker image ls -q -a | xargs docker image rm -f
Delete all Container
docker container ps -q -a | xargs docker container rm
Delete all Volumes
docker volume ls -q | xargs docker volume rm
Add Linux User to Docker Group (allows docker use without `sudo`)
sudo usermod -aG docker $USER

HTML5

Unicode/Emojis

You can get the unicode emoji's from this page: emoji list. All you have to do is remove the 'U+' from the first part of the code and replace it with '&#x'. End the unicode string with a semicolon. For example, to use the smiley emoji, change it from: U+1F600 to '&#x1F600;'. To use a unicode character with the css 'before' or 'after' sudo-selector, remove the 'U+' from and replace it with '\'. So for the css ':before' or ':after', it would be '\1F600'. Of course, to use unicode on your site, you have to have the utf8 tag in your site header:

<meta charset="utf-8" />

Reference

Code Pen

See the Pen UTF8 by Josh Young (@joshayoung) on CodePen.

HTML5 Doctype

<!DOCTYPE html>

Tags

  • <cite> - cite a source
  • <kdb> - text entered from a keyboard (i.e. cd, pwd)
  • <pre> - preserves white space in html output
  • <var> - used for outputting a variable in html
  • <del> - show removed text (sometimes styled with strike-through mark)

HTTP

200
Success
301
Moved
403
Forbidden
404
Not Found

UFW

UFW by default will allow all outgoing connections but deny any incoming connections.

  # Show firewall status/rules:
  ufw status

  # Enable firewall
  ufw enable

Application Profiles

  # Show all application profiles:
  ufw app list

  # Show which ports/protocols a rule will enable:
  ufw app info 'OpenSSH'

Set default egress/ingress rules

  # Deny egress and ingress:
  ufw default deny outgoing
  ufw default deny incoming

Open Up Ports

  # Allow HTTP Service:

  ufw allow http

  # or:

  ufw allow 80/tcp
  # or allow application profile (nginx, apache, etc):
  ufw allow 'Nginx HTTP'

  # Allow a specific port:
  ufw allow 8080/tcp

  # Allow a specific IP:
  sudo ufw allow from 192.168.3.100

  # Limit to one port:
  sudo ufw allow from 192.168.3.100 to any port 80

  # Allow the whole subnet:
  ufw allow from 192.168.3.0/24 to any port 80

Close Ports/Delete Rules

  # Close port 80
  ufw deny 80/tcp

  # Deny from specific IP:
  ufw deny from 192.168.3.100

  # Deny IP and Port:
  ufw deny from 192.168.3.100 to any port 80

  # Delete HTTP rule:
  ufw delete allow www
  # or:
  ufw delete allow 80/tcp

Firewalld

Firewalld is manipulating iptables behind the scene. Firewalld does have extended features in comparison to just using iptables. In the future iptables will be replaced with nftables. Firewalld will also serve as a font-end for nftables.

Default Zones

  • block - ingress rejected, egress allowed
  • dmz - for DMZ servers
  • drop - ingress dropped, egress allowed
  • external - use when you have NAT masquerading
  • home - other machines trusted
  • internal - use when server is a router/gateway machine
  • public - other machines untrusted
  • trusted - connections accepted and machines trusted
  • work - other machines trusted

Firewalld Main Commands

  # Show all zones:
  firewall-cmd --get-zones

  # Show active zones:
  firewall-cmd --get-active-zones

  # Show default zone:
  firewall-cmd --get-default-zone

  # Show all services:
  firewall-cmd --get-services

Change Zones/Interfaces

Each network inteface can be assigned to a different zone.

  # Change 'eth0' to 'work' zone:
  firewall-cmd --zone=work --change-interface=eth0

Show Current Settings

  # List current settings on 'public' zone:
  sudo firewall-cmd --zone=public --list-all

  # Show open ports:
  sudo firewall-cmd --zone=public --list-ports

Open Ports/Services

Without --permanent, the firewall rule will take affect but will not persist after a reboot.

  # Open port 80:
  firewall-cmd --permanent --zone=public --add-port=80/tcp

  # Add FTP Service:
  firewall-cmd --permanent --zone=public --add-service=ftp

  # Reload the firewall for these to take affect:
  firewall-cmd --reload

Remove Service/Port

  # Remove the open port:
  firewall-cmd --zone=public --remove-port=80/tcp

  # Remove the service:
  firewall-cmd --zone=public --remove-service=ftp

  # Add the '--permanent' flag to make the removal permanent:
  firewall-cmd --zone=public --remove-port=80/tcp --permanent
  firewall-cmd --zone=public --remove-service=ftp --permanent

Gatsby

Starting Local Server

  gatsby develop
  # or
  npm run develop

Java

Build a Jar:

  mvn package
  java -jar target/my_jar_name.jar

Interface Naming

  • When you have more than one interface use a name that corresponds to the domain.
  • When you have only one interface, name the interface "name" + "Impl".

Git

Set a Different Author for a Repository

  • git config --local user.email email@example.com

Reset the Previous' Commit's Email Address

  • git reset HEAD~1
    git commit --amend --author="First Last <email@example.com>" --no-edit
    git push --force-with-lease
    

Contributing to an open source project

  1. Fork the project on github.
  2. Create a feature branch: git checkout -b "feature-branch-name".
  3. Commit changes to your feature branch: git commit -am "commit message".
  4. Push the feature branch up: git push origin feature-branch-name.
  5. Creating a PR from this branch will open up a PR in the forked repo.

Copy Contents from One Branch to a New Branch:

  • git checkout -b my_new_branch_name my_old_branch_name

Pull Down / Commit to a Remote PR:

  1. Copy the remote branch name in the PR list (i.e. 'thebrnm:master')
  • Remove the :master off the end.
  1. git remote add thebrnm git@github.com:thebrnm/the_repo.git
  • In this case 'origin' started as: git@github.com:thebrnm/the_repo.git
  1. git fetch thebrnm
  2. git checkout -b thebrnm-master thebrnm/master
  3. git commit -am "My Commit Message"
  4. git push thebrnm HEAD:master

Remove File from Repo, and File System

This will remove the file from your repo, and the filesystem.

  git rm file_name

Push up tags:

 git push --follow-tags

Remove File from Repo, not File System

This will remove the file from your repo, but not from the file system.

  git rm --cached file_name

Remove Folder from Repo, and File System

This will remove the directory from your repo, and the filesystem.

  git rm -rvf file_name

Remove Folder from Repo, not File System

This will remove the directory from your repo, but not from the file system.

  git rm -r --cached my_folder_name

Show Contents of Commit

  git show [commit hash]

Change Base Branch

  git rebase --onto new_branch old_branch branch_you_are_moving

Turn off the pager

Add --no-pager to a command

Restore a Deleted File

  git checkout [removed commit]^ -— [path to flle]

Restore a Deleted File Before Commit

  git reset
  git checkout -- /path/to/deleted/file.txt

Delete Branches

  # Delete a local branch:
  git branch -d my_local_branch

  # Delete a remote branch:
  git push origin --delete my_remote_branch

Show which Remote Branch

This shows which remote branch you are tracking and how far behind your local version is from the remote.

  git branch -vv

Push changes, then revert locally

This will allow you to push up a feature branch and then revert your local changes to see the diff.

  git push origin my_feature_branch

  # Revert changes so you can see the diff (locally):
  git reset HEAD~

HEAD

HEAD is the most recent commit on your present branch.

Checkout Previous Commit

This will put you in a detached HEAD state.

  git checkout [hash of previous commit]

Checkout Remote Branch

  git fetch origin
  git checkout -b my_branch_name orgin/my_branch_name

  # or:

  git fetch
  git checkout my_branch_name

  # if we have local branch with same name do
  # this to prevent conflicts with the local branch:

  git fetch origin
  git checkout --track origin/my_branch_name

Git Reset

  git reset --soft HEAD^3

  "'mixed' is the default if you run `git reset`:
  git reset --mixed HEAD^3

  git reset --hard HEAD^3
  • --soft (keeps staged changes)
  • --mixed (changes present, not staged)
  • --hard (does not preserve uncommitted changes)

Edit Commit Message

  git commit --amend

Revert a file to state at previous commit

  git checkout -- my_file.txt

Commit Messages

Try to use present tense for your commit message (i.e. "Add new class for students" not: "Added new class for students")

  git commit -m "Correct site map"

Pick Files to Stash

  git stash -p

Show File in Stash

  git stash show stash@{0}

Checkout a file that is stashed

  git checkout stash@{0} -- path/to/file

Revert Uncommitted Changes

Leaving out the `stash@{2} variable below will run the stash command on top stash on the stack.

  git stash apply stash@{1}
  git stash drop stash@{2}

Retrieve a stashed file

  git checkout [name of stash] -- [filename]

Stash all files (including files in .gitignore)

  git stash --all

Stash tracked and untracked files

  git stash save --include-untracked

Revert One File

  git checkout -- path/to/file.txt

Show Files in Commit

  git diff-tree --no-commit-id --name-only -r [commit hash]

Show Diff in Staged Files

  git diff --staged

Rename a Local Branch

  git branch -m &lt;oldname&gt; &lt;newname&gt;

Move Remote PR Branch Locally

  git fetch origin pull/ID/head:BRANCHNAME

Saves Current Changes with Stash

  git stash
  or:
  git stash save "Name for the stash"

Files in stash

  git stash list --stat

Show files in stash

  git stash show stash@{2}

Remove all stashes

  git stash clear

Restores Most Recently Stashed Changes

This command will run git stash apply and then git stash drop.

  git stash pop

List Stashes

  git stash list

Restore Specific Stash

  git stash pop stash@{3}

Create and switch to branch

  git checkout -b new_branch_name

Show Remote Branches

  git branch -r

Delete local branch

  git branch -d local_branch_name

Git Tags

  # show all tags
  git tag
  # checks out the code with this tag
  git checkout [name of tag]
  # adds a tag
  git tag -a [tag name] -m tag description]
  # pushes tags
  git push --tags

Show Diffs

  git diff HEAD^ (parent)
  git diff HEAD^^ (grandparent)
  git diff HEAD~6 (six commits ago)

Compare Commits

  git diff HEAD^..HEAD
  git diff 58786f..98f7f0
  git diff master another_branch

Stop tracking in Repo

  git rm --cached errors.txt

Remove one file from git add

  git reset HEAD &lt;file&gt;

Remove files added with git add .

  git reset

Restore a deleted file

  # First find the hash:
  git reflog
  git log --walk-reflogs (more detail)

  # Then:
  git reset --hard 7980f
  # or:
  git reset --hard HEAD@{1}

  # Create a new branch with reflog hash:
  git branch [new branch name] 890fs4
  or:
  git branch [new branch name] HEAD@{1}

Clone a local repo as a backup

  git clone local_repo local_repo_backup

Rewrite History

Once a file is added to git (after the commit) it is permanently in the repo. The only way to remove it is to rewrite history. However, do this with extreme care! Make a backup of your code first with clone.

  git filter-branch --tree-filter 'rm -f old_file.sh -- --all'

  # or you can just remove the file from the repo:
  git filter-branch --index-filter 'git rm --cached --ignore-unmatch old_file.sh'

  # Sometimes when you re-write you will get empty commits, to delete these do:
  git filter-branch -f --prune-empty -- --all

Commit Order Differences

Order from top to bottom:

  git log (newest to oldest)
  git rebase -i HEAD~3 (oldest to newest)

Roll back previous commit (preserving file changes)

  git reset --soft HEAD~1
  or
  git reset --soft HEAD^

Cherry Pick

  git cherry-pick 97589f

  # Edit Commit:
  git cherry-pick --edit 987df0

  # Combine two commits:
  git cherry-pick --no-commit 9876f 78979f
  git commit -m "Combine two commits"

Add file to last commit

  git add newfile.sh
  git commit --amend -m "Add file to repo"
  or:
  git commit --amend --no-edit

Roll back previous commit (discarding file changes)

  git reset --hard HEAD~1
  # or:
  git reset --hard HEAD^
  # or the two previous  commits:
  git reset --hard HEAD^^

Add Remote

  git push -u origin master
  git push -u [the name] [the branch]
  # After using '-u', you can use use `git push` next time:
  git push

Revert a Commit

  git revert [the commit hash you want to revert]

How Git Pull Works

When you run git pull, you are actually performing a series of commands:

  • Updates the local origin/master branch by fetching updates from the origin with: git fetch.
  • Then the newly updated local origin/master is merged into the local master with: git merge origin/master.

Therefore, just running a git fetch will pull down all of the updated code from the origin, but it will not merge any of this with the local master.

Rebase (run from feature branch)

  git rebase master

Interactive Rebase (the last 4 commits)

Using 'squash' will combine this commit in with the previous commit.

  git rebase -i HEAD~4

GitHub

Quick Search Menu:

  • CMD/CTRL + K

Close an Issue With a Commit

You can add a number to your commit message to close that particular commit. I have included an example commit below.

Addressing the problems with the latency. Closes #4.

JavaScript

Capitalize Function

var cap = function (str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
};

Destructuring

// Object Destructuring:
let foods = {
  vegetable: "spinach",
  fruit: "apple",
  nut: "almond",
};
const { vegetable, fruit } = foods;

// Array Destructuring:
let dirty_dozen = [
  "Strawberries",
  "Spinach",
  "Nectarines",
  "Apples",
  "Peaches",
  "Pears",
  "Cherries",
  "Grapes",
  "Celery",
  "Tomatoes",
  "Sweet bell peppers",
  "Potatoes",
];

const [one_item] = dirty_dozen;

Only display content when JavaScript is enabled

document.getElementsByTagName("body")[0].className += " js";
/* Only set when JavaScript is enabled in browser: */
body.js .only-js {
  border: 1px solid #a0a0a0;
  display: block;
  ...;
}

ES2015 Function Syntax

const output_log = () => {
  alert("This is an example.");
};
const add_nums = (x, y) => {
  return x + y;
};

Detect Keyboard Input

See the Pen Detect Keyboard Input by Josh (@joshayoung) on CodePen.

Basic Class Structure

  var Shape = function(sides) {
    this.sides = sides;
  }

  Shape.prototype.area = function() {
    calculate ...
  }

  var square = new Shape(4);

Immediately Invoked Function Expression (IIFE)

  (function() {
  ...executed immediately
  })();

String Object vs Literal

A string literal is immutable.

// String Object:
typeof new String(); // 'object'
var str = new String("Hello");
str.x = "World";
console.log(str.x); // Outputs 'World'

// String Literal:
typeof ""; // 'string'

Laravel

Basic Migration

  php artisan make:migration the_users_table --create=users

Refresh Auto Load Files

  composer dump-autoload

Run the Migrations

  php artisan migrate

Open Laravel Shell

  php artisan tinker

Create the Model along with the Migration

  php artisan make:model User -m

Create Controller

  php artisan make:controller UserController

Create Model, Controller, and Migration

  php artisan make:model User -mc

Create Resoureful Controller

  php artisan make:controller UsersController -r

FreeBSD

Troubleshooting ZPool Drive Errors

  zpool status
  glabel status
  camcontrol devlist
  geom disk list

  # Grep for info on the drive in question:
  dmesg | grep ^da1 | less

  # Find the serial on the drive in question:
  camcontrol identify da1 | grep serial

Edit Hostname

  # Edit:
  vi /etc/rc.conf

  # Rename references to old hostname:
  vi /etc/hosts

  # Set the hostname
  hostname your-new-hostname

  reboot

Shutdown Server

  poweroff
  # or
  shutdown -p now

Show Version

  freebsd-version

Update OS

  freebsd-update fetch
  freebsd-update install

Ports

Ports are groups of 'make' files that allow software to be installed from source. They can be managed by 'portsnap'.

Packages

These packages are pre-compiled. They are similar to .deb or .rpm packages on Debian and RHEL respectively.

  # Package Info:
  pkg info

  # Install package:
  pkg install package_name

  # Update:
  pkg update

  # Upgrade:
  pkg upgrade

  # Uninstall package:
  pkg remove package_name

Slackware

Slackware Linux Commands

Use slackpkg to keep system updated.

  # Download slackpkg .tar.gz file with wget
  wget https://slackpkg.org/stable/slackpkg-2.60-noarch-1.tgz

  # Install slackpkg with 'installpkg'
  installpkg slackpkg-2.60-noarch-1.tgz

  # Uncomment and select a mirror:
  vi /etc/slackpkg/mirrors

  # Initialize slackpkg:
  slackpkg update

  # Install package
  slackpkg install package_name

  # Update to the latest slackpkg packages:
  slackpkg update
  slackpkg upgrade-all

Spring

  • After modifying the Spring pom.xml file, you may need to right-click and tell maven to reload the project for it to properly install all of the packages.

Ubuntu / Debian

Add or edit the lines below in this file /etc/network/interfaces.

  ...
  auto eth0
  iface eth0 inet static
  address 192.168.3.100
  netmask 255.255.255.0
  gateway 192.168.3.1
  broadcast 192.168.3.255
  dns-nameservers 192.168.3.1
  ...

Show Ubuntu Version

  lsb_release -a
  # or:
  cat /etc/*release
  # or:
  cat /etc/os-release

CentOS / RHEL

Change Hostname

  hostnamectl set-hostname my-new-hostname

Show Version

  cat /etc/*release

Add Static IP

Add modify the entries below within: /etc/sysconfig/network-scripts/ifcfg-eth0 (change IP addresses according to your network). The name for your network connection could differ from ifcfg-eth0.

  ...
  DEVICE="eth0"
  BOOTPROTO="static"
  IPADDR="192.168.3.100"
  NETMASK="255.255.255.0"
  GATEWAY="192.168.3.1"
  DNS1="192.168.3.1"
  DNS2="192.168.3.2"
  ONBOOT="yes"
  ...

ARCH

Pacman Commands

  # Sync and Update:
  pacman -Syu

  # Install a package:
  pacman -S package_name

  # Remove a package:
  pacman -R package_name

Show Version

  lsb_release -a

Linux

Init Systems

SystemD

Systemd is managed my 'systemctl'. To start sshd, we would run: systemctl start sshd.

Upstart

Upstart is managed by 'initctl'. To start sshd we would run: initctl start sshd. Upstart was invented as a replace for System V by Ubuntu.

System V (SysV)

To start sshd, we would run: '/etc/init.d/ssh start'. This was primarily used by older versions of Linux.

BSD Init

The BSD based init system is configured under /etc/rc.conf. To start sshd, we would run: '/etc/rc.d/sshd start'. BSD and Slackware use the BSD init system

Linux partition/format with Parted

  parted /dev/sdb # Open device with gparted:
  print # Print device info:
  print free # Show free space
  help mklabel # Print available label types:
  mklabel msdos # 'msdos' good option, select 'gpt' for uefi support
  help mkpart # Partitioning help:
  mkpart # Start partitioning:

 # You will usually select 'primary' for the partition type.

 # Select filesystem type, examples:
 # ext2, ext3, ext4, ntfs, exfat, fat32

 # Start/End need adjustment if not partitioning whole drive:
 # Start partition from '2048s'
 # End on '-1s'

  quit # Exit:

  # Format your partition with 'mkfs', examples:
  mkfs.ext2 /dev/sdb1
  mkfs.ext3 /dev/sdb1
  mkfs.ext4 /dev/sdb1
  mkfs.vfat /dev/sdb1
  mkfs.ntfs /dev/sdb1

  # Use '-L' to add a label:
  mkfs.ext4 -L mydrive /dev/sdb1

  eject /dev/sdb1 # Eject partition:

Show Directory Size

  du -sh directory_path

32 or 64 Bit OS:

  uname -m
  # or
  arch

Print Services Running on Port:

  lsof -i tcp:8000

SystemD

  # 'enable' will create a symbolic link so that the service starts on reboot
  # 'disable' will remove the symbolic link
  # 'is-active' will tell you if the service is running
  # 'is-enable' will tell you if it starts on boot
  systemctl [status, enable, disable, is-active, is-enabled start, restart, reload, stop] application.service

Scan a Folder for Viruses (ubuntu)

  sudo apt-get update
  sudo apt-get install clamav clamav-daemon

  # If you get an error here, it might be because freshclam is already running in the background:
  # This command will update the virus signatures:
  sudo freshclam

  # Scan a directory:
  clamscan -r —bell -i /path/to/directory

Change Username

If you want to switch user 'joe' to 'sally', below are the steps:

  usermod -l sally joe

  # Verify that the new user exists and the old one does not:
  id sally
  id joe

  # Swap out the new user's group:
  groupmod -n sally joe

  # Swap the home directory:
  usermod -d /home/sally -m sally

  # If the above command does not work, delete the old dir and re-create it:
  rm -rvf /home/joe
  mkhomedir_helper sally

  # If you search these two files, you should not see the 'joe' user/group:
  cat /etc/group | grep joe
  cat /etc/passwd | grep joe

Rsync

  rsync -avz --delete /original/folder/location /new/folder/location

Reload Bash Config

  source .bashrc

Check Drive for Errors

  # Health Summary:
  smartctl -H /dev/sdb
  # Time required to run HDD Test:
  smartctl -c /dev/sdb

  # Run Short Test:
  smartctl -t short /dev/sdb

  # Run Long Test:
  smartctl -t long /dev/sdb

  # Print Test Results Summary:
  smartctl -l selftest /dev/sdb

  # Print Details of Latest Test:
  smartctl -a /dev/sdb

Check Drive for Bad Blocks

  # Test for bad block:
  badblocks -vs /dev/sdb > badblocks_results.txt

  # Command with different options:
  badblocks -sw -t random /dev/sdb > badblocks_results.txt

  # If you get an error like: "Value too large for defined data type invalid end block ... must be 32-bit value"
  badblocks -sw -t random -b 4096 /dev/sdb > badblocks_results.txt

Correct Bad Blocks

  # ext(2/3/4) filesystem:
  e2fsck -l badblocks_results.txt /dev/sdb

  # other filesystems:
  fsck -l badblocks_results.txt /dev/sdb

Show Security Settings with ls

  ls -Z

Crontab

  *  *  *  *  *         command
  -  -  -  -  -
  |  |  |  |  |
  |  |  |  |  +---------------------- day of week (0 - 6) (0 - Sunday)
  |  |  |  +--------------------- month (1 - 12)
  |  |  +------------------- day of month (1 - 31)
  |  +------------- hour (0 - 23)
  +------------ minute (0 - 59)

Write ISO/IMG to Disk or USB

The command below could also be executed with 'bs=4M'.

  sudo fdisk -l
  sudo umount /dev/sdb
  sudo dd if=/path/to/iso/or/img of=/dev/sdb bs=1M status=progress && sync
  sudo eject /dev/sdb

Find Linux Version

Kernel:
  uname -mrs
Distribution:
  cat /etc/*-release

Prevent Command from Being Recorded in Terminal History

  <space> command

Logged In User History (last 10)

  last -10

Wipe HDD with 'dd' Command

  # With Zeros:
  dd if=/dev/zero of=/dev/sdb bs=1M status=progress && sync

  # With Random Data:
  dd if=/dev/urandom of=/dev/sdb bs=1M status=progress && sync

Terminal Calculator

  bc -l

System Uptime

  uptime

Clear Terminal

  CTRL + l

Extract a .tar File

  tar -xvf file.tar

Extract a .tar.gz File

  tar -xzvf file.tar.gz

Extract a .tar.bz2 File

  tar -xjvf file.tar.bz2

Finding a File

  find / -name [file name you are searching] 2> /dev/null

Bring Job Into the Foreground

  fg

Pause Job

  Ctrl + Z

Resume Paused Job in Background

  bg

Continue Execution after Shell Exit

  nohup ./script.sh &

List Background Jobs

  jobs

Start Program in Background

  ./script.sh &

Direct All Output to Log File

  ./script.sh 1> ~/tmp/log.txt 2> ~/tmp/log.txt &

Direct All Output to Null

  ./script.sh 1> /dev/null 2> /dev/null &

Run 256 Checksum

  sha256sum /the/path/to/file.iso

Mac

Run 256 Checksum

  shasum -a 256 /the/path/to/file.iso

Change Time Machine Backup Frequency

The interval is set in seconds.

  defaults write /System/Library/Launch Daemons/com.apple.backupd-auto StartInterval -int 1800

Find IP

  ifconfig |  grep -oE "\w* \b([0-9]{1,3}\.){3}[0-9]{1,3}\b"

Flush DNS

  killall -HUP mDNSResponder

Write ISO/IMG to Disk or USB

The command below could also be executed with 'bs=4m'.

  diskutil list
  umount /dev/disk2
  dd if=/path/to/iso/or/img/file of=/dev/disk2 bs=1m && sync
  diskutil eject /dev/disk2

Node

NPM Packages Installed Globally:

  npm list -g --depth 0

React

Components

  • Components should not be aware of state.

Containers

  • Containers are aware of state.
  • Do not do styling in Containers.
  • Integration test containers.

toContainHTML (jest)

Debugging data:

<pre>{JSON.stringify(resource)}</pre>

Commenting out JSX:

{
  /* <ReactComponent></ReactComponent> */
}

MySQL

Connect to Database

  mysql -u [username] -p [password] -h [hostname]

Netstat

Find Listening Port (Bash)

  netstat -nao | find "80"

Find Listening Port (Windows)

  netstat -nao | findstr "0.0.80"

MySQL

Connect to Database

  mysql -u [username] -p [password] -h [hostname]

PostgreSQL

Connect to Database
\c DATABASE_NAME
List Databases
\l
Tables in database:
\dt
Connect with admin user:
psql -U postgres
Connect with user to a specific database
psql -U username database_name
Show Users
\du
Create User, Database, Grant Privileges
CREATE USER my_user_name WITH PASSWORD 'MY_PASSWORD'; CREATE DATABASE my_user_db; GRANT ALL PRIVILEGES ON DATABASE my_user_db to my_user_name;
Describe Table
\dt+
Leave SQL Server
\q
Connect to Postgres
psql postgres
Create User
CREATE USER myuser WITH PASSWORD 'my password';
Create Role
CREATE ROLE myuser WITH LOGIN PASSWORD 'my password';
Alter Role
ALTER USER myuser WITH CREATEDB;

Kanban

Swim Lanes
Rows
WIP
Work In Progress
WIP Limit
The maximum amount of cards allowed in one column on the board
Blocker
Something that is preventing you from moving your card forward
Hidden Work
Something you are working on that is not visible on the Kanban Board

Python

Start Simple Server

  python -m SimpleHTTPServer

Start Simple Server with Python 3

  python -m http.server

Rails

Set to Production Mode Locally:

If you are using 'dotenv-rails' to add ENV data, you may need to move that outside of your development/test section in your Gemfile.

  bin/rails assets:precompile

  bin/rails s -b 0.0.0.0 -e production

Connect to Already Running Rails Instance:

  rails server -P /app/tmp/pids/server.pid

Update Gems:

Updating gems that are in your lock file, but not in your Gemfile can be updated with bundle update [gem name]. The gem can be upgraded to the next patch version with bundle update [gem name] --patch.

Use bundle update --help for more info.

Start server on a different port:

  rails s -e development -p 2000

Start server on a different port with another pid file:

Sometimes when you are running a server on a different port, you will get an error having to do with the pid file (I forgot exactly what it says). Running a command such as the below will allow you to write to a different pid file.

  rails s -e development -p 2000 -P tmp/pids/srv2.pid

Start rails listening on your local IP address

  rails s -b 0.0.0.0

Inheriting Directly from ActionController::Base

Inheriting directly from: "ActionController::Base" instead of: "ApplicationController" will circumvent any code in your application_controller.rb file. Essentially it is like "skip running anything in the application_controller.rb file". "ApplicationController" inherits from "ActionController::Base".

Output image path from console

  ActionController::Base. \
  helpers.asset_path('image.jpg')

  # Or:
  include ActionView::Helpers::AssetUrlHelper
  asset_path('image.jpg')

Open Rails Database Console

  rails dbconsole

Clear Test Log File

  rails log:clear LOGS=test

Rails Controller Methods Are Typically Ordered

  1. index
  2. show
  3. new
  4. edit
  5. create
  6. update
  7. destroy

Rollback in Steps

  rails db:rollback STEP=1

Show Migration Status

  rails db:migrate:status

Run Migrations on Test Database

  bin/rails db:migrate RAILS_ENV=test

Rails CRUD forms with no form plugin

github.com/joshayoung/rails-basic-forms

Start Local Server

  rails server (rails s)

Start Local Server on any IP

  rails s -b 0.0.0.0

Start Local Server on different port

The default port is 3000 if unspecified.

  rails s -b 0.0.0.0 -P tmp/pids/srv1.pid
  rails s -b 0.0.0.0 -p 3001 -P tmp/pids/srv2.pid
  rails s -b 0.0.0.0 -p 3002 -P tmp/pids/srv3.pid

Active Record Errors

  # Model validations:
  class Student
    validates :name, :grade, :act_score, presence: true
    ...
  end

new_student = Student.create(name: 'James', grade: '2nd.')

  # Show errors:
  new_student.errors

  # Show errors as sentences:
  new_student.errors.full_messages

Route Syntax

  verb "the_url" => "controller#action"
  get "tickets" => "tickets#index"
  get "tickets/:id" => "tickets#show"

Open SQLite from Rails

  rails dbconsole

Show Rail Project Info

  rails about

Open Rails Console

  rails console
  or:
  rails c

  # reload the console to pull in any code changes made:
  reload!

Rails Tasks

  rails -T (commands than can be run)
  rails -T db (database related commands that can be run)

Create Migration

Older versions of rails used the 'rake' command instead of 'rails' below.

  rails g migration [migration name] field:type field:type...

  rails db:migrate

  rails db:status

  rails db:rollback (rolls back the previous migration)

  rails db:migrate VERSION=XXX (rolls back to this migration)

Add More Columns

Using this convention, rails will know that you want to add the fields listed to the table defined by 'YYY' or 'yyy' below.

  rails g migration AddXXXToYYY ...
  rails g migration AddFieldsToTownships title:string moved_to:date

  rails g migration add_xxx_to_yyy
  rails g migration add_fields_to_townships

Show Rails Generators

  rails g

Create Scaffolding

  rails generate scaffold [name] attribute:type
  rails generate scaffold Product title:string price:decimal

Create Model (includes migration)

Model names should be singular.

String is the default type, so that can be left off if the type is a string.

Column Types

  rails generate model [model name] [field[:type][:index] field[:type][:index]] [options]

  # or:

  rails g model [model name] [field[:type][:index] field[:type][:index]] [options]

  # i.e.
  rails g model ticket title:string priority:string the_date:datetime

  # Run Migration:
  rails db:migrate

  # Migration Status:
  rails db:migrate:status

Example: A model named 'Student' would point to a table named 'students' by default.

Create Controller and View

Controller name is plural.

  rails generate controller [controller name]
  or:
  rails g controller [controller name]

Remove Controller and other files created above.

  rails destroy controller [controller name]

Basic Controller Methods

  class TicketsController < ApplicationController
  def index; end
  def create; end
  def show; end
  def update; end
  def destroy; end
  end

Views

When you do not point the controller action to a specific view it will try to render the view with the same name as the action.

def index; end would try to render the index.html.erb view.

Create resourceful routes

This will create:

  • Database migration for the 'students' table.
  • The Student model with the 'belongs_to' line pointing to 'course'.
  • A Student controller.
  • All of the resourceful routes for student.
  rails g resource [resource name] field:type field:type...

  rails g resource student first_name:string last_name:string course:references

Show Routes

Show routes from the browser app by going to this path: http://[url of app][:port]/rails/info/routes.

  rails routes
  # or:
  rake routes

Resourceful Routes in route.rb

  Rails.application.routes.draw
    root "students#index"
    get "students" => "students#index", as: "students"
    post "students" => "students#create"
    get "students/new" => "students#new", as: "new_student"
    get "students/:id/edit" => "students#edit", as: "edit_student"
    get "students/:id" => "students#show", as: "student"
    patch "students/:id" => "students#update"
    put "students/:id" => "students#update"
    delete "students/:id" => "students#destroy"
  end

  # This is actually the same thing as the above:

  Rails.application.routes.draw
    root "students#index"
    resources :students
  end

One-to-Many Nested Rotues in route.rb

  get '/lists/:list_id/notes' => 'notes#index', as: 'list_notes'
  post '/lists/:list_id/notes' => 'notes#create'
  get 'lists/:list_id/notes/new' => 'notes#new', as: 'new_list_note'
  get '/lists/:list_id/notes/:id/edit' => 'notes#edit', as: 'edit_list_note'
  get '/lists/:list_id/notes/:id' => 'notes#show', as: 'list_note'
  patch 'lists/:list_id/notes/:id' => 'notes#update'
  patch 'lists/:list_id/notes/:id' => 'notes#update'
  delete 'lists/:list_id/notes/:id' => 'notes#destroy'

List of Resourceful routes

NameVerbURLcontroller#actionTaskSQL**
studentsGET/studentsstudent#indexShow StudentsSELECT *
POST/studentsstudents#createCreate a new StudentCREATE
new_studentGET/students/newstudents#newShow new Student formDisplay a HTML form
edit_studentGET/students/:id/editstudents#editShow edit Student formSELECT where id =
studentGET/students/:idstudents#showShow a StudentSELECT where id =
PATCH/students/:idstudents#updateUpdate Student (partial)UPDATE tbl SET (name = 'Josh')
PUT/students/:idstudents#updateUpdate Student (complete)UPDATE tbl SET (name = 'Josh', day = 'Wed', state = 'AL' ...)
DELETE/students/:idstudents#destroyRemove a StudentDELETE

** There are exceptions to the SQL displayed here. These example serve as the most common implementations in my experience. Each of the 'name's listed in the table above is appended with either '_url' or '_path' in rails. In the rails app, use '_path' for your views and '_url' for controller redirects.

_url (full path to page)
_path (relative path to page)
  • i.e. students_path: /students
  • i.e. student_path(4): /students/4

Naming

By convention the name of the model is singular and the name of the table is plural.

Create New Table Entry

  township = Township.new
  township.city = 'London'
  township.country = 'England'
  township.save

  # Or:

  township = Township.new(city: 'London', country: 'England')
  township.save

  # Or:

  Township.create(city: 'London', country: 'England')

Update Table Value

  township = Township.find(2)
  township.city = 'London'
  township.country = 'England'
  township.save

  # or:

  township.update(city: 'London', country: 'England')

Delete Table Value

  township = Township.find_by(city: 'Jacksonville')
  township.destroy

One-to-Many Relationships

  # One (parent):
  class Student < ApplicationRecord
    has_many :movies
  end

  # Many (has a foreign key to reference parent):
  class Movie < ApplicationRecord
    belongs_to :student
  end
  # Setup the cascade to delete movies, then the student it removed:
  class Student < ApplicationRecord
    has_many :devices, dependent: :destroy
  end

Generate the relationship:

  rails g resource Device name:string student:references
One (parent):
students
idnameage
1Frank35
2Sally28
Many (child):
devices
idnamestudent_id
1iPhone2
2iPad2
3Laptop3

In the above example, 'student_id' is a foreign key pointing to the 'id' field in the 'students' table. The foreign key will always be the parent's table name in singular form (student) with an '_id' appended to the end. So in this case it is 'student_id' since the parent table is 'students'.

In the ruby console, student.devices would return all of the devices that student possesses. On the other hand, device.student would return the student who is the owner of the device selected.

Many-to-Many Relationships

  class Student < ApplicationRecord
    has_many :devices
  end

  class Device < ApplicationRecord
    belongs_to :student
    belongs_to :colors
  end

  class Color < ApplicationRecord
    has_many :devices
  end
students
idnameage
1Frank35
2Sally28
devices
idnamestudent_idcolor_id
1iPhone21
2iPad21
3Laptop12
colors
idcolor
1Green
2Blue
3Silver

Ruby

Messages

# `name` is the message sent to `animal`
  animal.name

Write to file from command line:

  f = File.new('log.txt', 'w')
  f << log_this_variables_value
  f.close

Output just a class' own methods

  klass = Klass.new

  puts klass.methods - methods

Loads IRB With Active Support

  !rails c

Struct

  # With Struct you can only define
  # the attributes at object creation
  Student = Struct.new(:name, :grade)
  george = Student.new('george', 95)

  # Outputs: 'george'
  puts george.name

  # Outputs: 95
  puts george.grade

OpenStruct

  require 'ostruct'
  george = OpenStruct.new(name: 'george', grade: 95)

  # Outputs: 'george'
  puts george.name

  # Outputs: 95
  puts george.grade

Open documentation for project's gems

  gem serve

Install to global gemset (when using rvm)

  rvm @global do gem install [gem name]

Empty Method Returns Nil

  def find_grade; end
  grade = find_grade

  # Outputs nil:
  puts grade

Naming

  # Class is a Noun:
  class Cards
    # Module is an Adjective:
    include Shuffleable
  end

Ranges

  # Inclusive:
  5..10
  # Exclusive:
  5...10

Find Methods

  cat.private_methods
  cat.public_methods
  cat.protected_methods
  cat.singleton_methods

  Cat.private_instance_methods
  Cat.protected_instance_methods
  Cat.public_instance_methods

Syntactic Sugar

At the end of the day, the operators we know like +, -, etc are actually methods in ruby. So these two will do the same thing:

  y = 5 + 6;
  y = 5.+(6)

Methods and Code Blocks

By default all methods will accept a code block. However, they will not yield to the block unless the method includes a yield keyword.

  # These are both valid ways to call a method:
  my_method
  my_method { puts "Test" }
  my_method() { puts "Test" }

Accept Multiple Arguments

  def lots_of(*a)
  end

  # Outpus: [1, 2, 3, 4]
  puts lots_of(1, 2, 3, 4)

Multiline Comment

=begin
  def a_function
  puts 'test'
  end
=end

Ruby Symbol vs Strings

Symbols have the same object ID whereas strings do not. Symbols are immutable and strings are mutable.

  # Open irb:
  >> :pathway.object_id
  => 9854917
  >>
  >> :pathway.object_id
  => 9854917
  >>
  >> "pathway".object_id
  => 97508076985508
  >>
  >> "pathway".object_id
  => 98508075985400
  >>
  >> :pathway == "pathway"
  => false

Ruby Class Properties

  class RubyStudent
    # readable only:
    attr_reader :name

    # writable only:
    attr_writer :name

    # readable and writable:
    attr_accessor :grade

    def initialize
      @name = 'Josh'
      @grade = 'a'
    end

    # Override the attr_accessor method in your class:
    def grade=(my_grade)
      @grade = my_grade.upcase
    end
    ...
  end

  rstudent = RubyStudent.new

  # Call the accessor method:
  puts rstudent.name

Static Methods

  class RubyStudent
    def self.my_method
      ...
    end
  end

  # Call static method:
  RubyStudent.my_method

Multiple Static Methods

  class RubyStudent
    class << self
      def my_method
        ...
      end

      def my_second_method
        ...
      end
    end
  end

  # Call static method:
  RubyStudent.my_method
  RubyStudent.my_second_method

Ruby Modules

Modules are a typically used to create reusable sections of code in the form of Mixins or they can be used to wrap classes thereby action as a Namespace.

Modules cannot be instantiated, so any methods have to be defined with self.

  module Learnable
    ...
    def self.calculate
      ...
    end
  end

  # Call the Module method:
  Learnable::calculate
  # or
  Learnable.calculate

Ruby Class Inheritance

Use inheritance when two class have a 'is-a' relationship. For instance: a MathStudent is a type of Student and a Fox is a type of Animal.

  class Student
    ...
    def print_grade
      puts 'A'
    end
  end

  class MathStudent < Student
    def print_grade
      puts 'A+'
    end
  end

  student = MathStudent.new

  # Prints 'A+':
  student.print_grade

Ruby Namespace

  module CollegeStudent
    class Student
      def self.outp
        puts 'output'
      end
      def out
        puts 'new output'
      end
    end
  end

  CollegeStudent::Student.outp
  student = CollegeStudent::Student.new
  student.out

Ruby Mixins

Ruby Mixins are just ruby modules that are included within a class.

  # If a module will be included in a class as a mixin, you do not have to define the method with self.
  # This way you can call the module method with the class instantiation.

  # File 'learnable.rb'
  module Learnable
    def calculate(num1, num2)
      num1 * num2
    end
  end

  # File: student.rb
  require_relative 'learnable'
  class Student
    include Learnable

    def add_up(n1, n2)
      calculate(n1, n2)
    end
  end

  student = Student.new
  puts student.calculate(2, 2)

When you define a mixin, if you know what class it will be included within, you can use class properties in the Module definition, like below:

  module Learnable
    def calculate(num1, num2)
      @first_number = 10
    end
  end

However, doing so could cause problems if you ever include the module within a class that does not define '@first_number'. Therefore it is best to use the class access within the module methods, like so:

  module Learnable
    def calculate(num1, num2)
      #Here we have to use 'self' otherwise the module will think it is defining a local variable.
      self.first_number = 10
    end
  end

Then when this is included in a class, it will work like this:

  require_relative 'learnable'
  class Student
    include Learnable

    attr_accessor :first_number

    def initialize
      calculate(2, 2)
    end
  end

  puts Student.new.first_number

Unless vs If

  # Prints 'false unless':
  unless false
    puts 'false unless'
  end

  # Prints 'false unless':
  puts 'false unless' unless false

  # Prints 'false if':
  if !false
    puts 'false if'
  end

  # Prints 'false if':
  puts 'false if' if !false

Memoization

  # If 'x' is false or nil return the value of 'y',
  # otherwise return the value of 'x':
  x ||= y

  # The first time through it will call the 'find_the_pizza' method.
  # For subsequent calls it will return '@pizza'.
  def pizza_special
    @pizza ||= PizzaSpecial.find_the_pizza('cheese')
  end

When You Must Use 'self'.

For assigning values with the accessor method from within a class:
  class Animal
    attr_accessor :tail

    def change_tail(new_tail)
      # To get this to work as expected, you would have
      # to change the line below to use 'self'
      tail = new_tail

      # Change to this:
      # self.tail = new_tail

      # If you do not use 'self' as shown above, ruby
      # thinks you are assigning to a local variable.

      # This works without 'self' because ruby knows that there is no local
      # variable titled 'tail' therefore it knows to return the value from the
      # accessor method:
      def send_tail
        tail
      end
    end
  end

  the_tail = Animal.new
  the_tail.tail = 'Brown'
  the_tail.change_tail('light brown')

  # This would output 'Brown'.
  puts the_tail.tail
For defining 'class methods' (a.k.a. Static Methods):
  class Student
    def self.new_grade(grade)
      @grade = grade
    end
  end

  Student.new_grade('A')

Convenient Methods

  class Test
  ...
  end

  # Prints: Test
  puts Test.inspect

  # Prints: Class
  puts Test.class

  # Prints: 89023478923
  puts test.object_id

Show Ancestors

  # In a file named 'my_module.rb':
  module MyMod
    ...
  end

  # In another class:
  require_relative 'my_module'
  class Test
    include MyMod
    ...
  end

  # Prints: [Test, MyMod, Object, Kernel, BasicObject]
  puts Test.ancestors

Function Return

Functions always return a value even if they are empty.

  def empty_function; end

  return_value = empty_function

  # Prints 'nil':
  puts return_value.inspect

Ruby Convert Types

  a_string = 'a string value'

  # Convert to Symbol:
  a_string.to_sym

  # Convert to String:
  123.to_s

  # Convert to Integer:
  "123".to_i

Look up Ruby Docs from command line

Online Documentation

  ri
  # or:
  ri -i (for interactive mode)

Interpolate code

  variable_value = 'test'
  puts "Print out #{variable_value}"

Start IRB Session

  irb

If/Else Statement

  if a_value == 1
  puts "Yes"
  elsif a_value == 2
  puts "No"
  else
  puts "Could not find."
  end

Switch Statement

  the_value = return_a_string()

  case the_value
  when "One"
    puts "It is one!"
  when "Two"
    puts "It is two!"
  else
    puts "Could not find result."
  end

Objects

Ruby objects are always passed by reference

Function

  def function_name(parameter)
    ...
  end

Add to Array

  the_array << "val"

  # Or:
  the_array.push("val")

Object Instantiation

  new_obj = Person.new

Iteration

  array.each do |elem| ... end

Custom Iteration

  # Example 1:
  def output
    yield
    yield
  end

  output { puts "This is output twice" }

  # Example 2:
  def output_num
    yield(100)
    yield(200)
  end

  output_num { |num| puts num }

Basic Blocks

  2.times { puts 'Josh' }

  2.times do
    puts 'Josh'
  end

  2.times { |i| puts "#{i} - Josh" }

  2.times do |i|
    puts "#{i} - Josh"
  end

Select Block

  # Returns just the numbers greater than '3':
  [1, 2, 3, 4, 5, 6, 7, 8, 9].select { |n| n > 3 }

Reject Block

  # Rejects the numbers greater than '3':
  [1, 2, 3, 4, 5, 6, 7, 8, 9].reject { |n| n > 3 }

Reduce Block

  # Gets the sum with the reduce method:
  [1, 2, 3, 4, 5, 6, 7, 8, 9].reduce { |total, n| total + n }
  # or:
  [1, 2, 3, 4, 5, 6, 7, 8, 9].reduce (:+)

Sort Lowest to Highest

  [11, 21, 73, 14, 95, 56, 97, 48, 19].sort

Sort Highest to Lowest

  [11, 21, 73, 14, 95, 56, 97, 48, 19].sort { |a, b| b <=> a }

Returns boolean if it finds the result

  # This should return false.
  [11, 21, 73, 14, 95, 56, 97, 48, 19].any? { |n| n > 100 }

Returns the first match

  # This should return 73.
  [11, 21, 73, 14, 95, 56, 97, 48, 19].detect { |n| n > 70 }

Map the values returned into a new array

  [11, 21, 73, 14, 95, 19].map { |n| n * 3 }

Hash (associative array / dictionary)

  {key => value}
  {:sport => "baseball"} (the key can be anything)

These are both the same:

  {:sport => "baseball", :time_limit => 60}

  # Or:
  {sport: "baseball", time_limit: 60}

Loop through a hash

  sports = {:sport => "baseball", :time_limit => 60}
  sports.each { |key, val| puts "#{key} - #{val}" }

SQLite

Execute a Single Query

  sqlite3 -line mydatabase.sqlite3 "select * from students"

Select Databse

  \c [database]

Connect to DB

  sqlite3 /path/to/database_file.db

Show databases

  .database

Show tables

  .tables

Tables Schema

  .schema table_name

Describe Table

  pragma table_info(table_name)

Select all

  select * from table_name

Exit SqLite Command Prompt:

  .quit

Security

Ping Sweep

  for i in `seq 1 255`; do ping -c 1 [IP ADDRESS].$i ; done

Software Engineering

Gherkin Success Criteria

Scenario: The Widget Should Play a Random Song
  • GIVEN: The widget is in the closed position.
  • AND: It has never been opened.
  • WHEN: You open it.
  • THEN: It plays a random song.
Resources:

Semantic versioning

# Major Version . Minor Version . Patch
1.4.9
  • The first number represents the major version. The second number represents the minor version. The third number represents the current patch level.
  • Typically if the first number changes that would represent a breaking change.
  • If the second number changes, that would represent a new feature.
  • If the third number changes, that would represent a bug fix.

Testing

Rspec Fail on First Error

  rspec --fail-fast

Rspec with Documentation

  rspec -f d

Test File Setup

We have a space between each part below.

  # Setup:
  user = create(:user)

  # Exercise:
  Student.addToClass(user)

  # Verify:
  expect(Student.users).to eq([user])

SSH

Remote Port Forwarding

Here 9100 is the remote port and 22 is the remote port.

  ssh -R 9100:127.0.0.1:22 username@192.168.6.7

Generate a SSH and transfer it to a server

  ssh-keygen -t ed25519 -C "comment"
  ssh-copy-id -i ~/.ssh/key_name.pub user@192.168.1.100

  Note: If you get permission errors after trying to connect with the key, make sure that you have this key setup in your `~/.ssh/config` file.

Sample config for ~/.ssh/config file:

Host 192.168.1.100
   IdentityFile ~/.ssh/key_name

Connect with a specific key

  ssh -i ~/.ssh/key_name user@192.168.1.100

Local Port Forward

In this case, 9100 would be our local port and 80 would be the remote.

  ssh -L 9100:www.remotesite.com:80 username@host

SVG

SVG viewBox

The viewBox has values of x, y, width, and height. The shapes within this box will be set in relation to the size of the viewBox. The viewBox location within the SVG tag can be offset with the first two numbers (x, y).

In the CodePen below below, you can see that the first and last example are consuming 100% of the width of the viewBox. When the screen is expanded or contracted, the elements within expand or contract accordingly, but always consume 100% of the size of the viewBox because the elements inside are sized to contain 100% of the viewBox width.

The middle example below internal shapes that total to less than the full width of the viewBox. The viewBox is also shifted from a starting point of 0,0 to demonstrate that the view box can be positioned anywhere within the contining SVG element.

To adjust the size of the SVG, you can set the outer containing SVG tag to be a certain percentage of the width of the browser window or even a fixed width. Within this the inner viewBox can be positioned within it.

See the Pen SVG viewBox by Josh Young (@joshayoung) on CodePen.

SVG Links

See the Pen SVG Symbol by Josh Young (@joshayoung) on CodePen.

SVG Elements

See the Pen SVG Stuff by Josh Young (@joshayoung) on CodePen.

Set SVG to Scale with Browser Width

By default an SVG element will take up the full width of the browser unless it has a defined width. To circumvent this, you can give it a definined with such as 300px or a percentage. Below is an example of a way to set the SVG element to be half of the browser width.

If the SVG tag is set to scale with the browser width, the SVG shapes within the internal viewBox will scale accordingly.

svg {
  height: auto;
  // This could be any percentage:
  width: 50%;
}

Rider

  • Alt + Insert
    • Generation Menu.
  • CMD/CTRL + n
    • Add Controller
  • CMD + OPTION + L
    • Format Code
  • CMD + D
    • Navigation to Source

RubyMine

Open Context Menu
Option(alt) + Enter
Search for Files
SHIFT + SHIFT
Search in Files
CMD + SHIFT + F
MVC Dialog
CTRL + CMD + UP-ARROW
Code Navigation
CMD/CTRL + b

IntelliJ

  • Context menu to add class components
    • CMD + N

SCP

Local to Remote

  scp file.txt username@host:/to/myremote/directory

Remote to Local

  scp username@host:file.txt /to/my/local/directory

Backup Local Folder to Remote

  scp -r local_folder/ user@host:/path/to/folder

Backup Folder Remote to Local

  scp -r user@host:/path/to/folder/* /to/my/local/directory/

Backup Folder Remote to Local, with Port

  scp -r -P 8000 user@host:/path/to/folder/* /to/my/local/directory/

Security

Nmap Ping Scan (detect hosts)

  nmap -sP 192.168.1.0/24

Bypass a Self-Signed SSL Warning in Chrome

Once you get the warning in the webpage, to continue to the site anyway, type: thisisunsafe.

Bash Ping Sweep

Usage: ./sweep.sh 192.168.1

  #!/bin/bash
  ip=$1
  for i in `seq 0 1 255`; do
    ping -c 3 -t 5 $ip.$i > /dev/null 2>&1 && echo $ip.$i is up;
  done

PHP

GET/POST Assignment

  $var = isset($_GET['var']) ? $_GET['var'] : '';

TMUX

Split Window Vertically:
Ctrl-b %
Open New Window
Ctrl-b + c
Previous Window
Ctrl-b + l
Navigate Between Windows
Ctrl-b + 0/1/2,etc
Split Window Horizontally:
Ctrl-b "
Navigate Between Windows:
Ctrl-b <ARROW KEYS>
Detach from tmux:
Ctrl-b + d
Re-attach to tmux:
tmux attach -t <SESSION> (i.e. tmux attach -t 0)
Show running tmux sessions:
tmux ls
Rename tmux Session:
Ctrl-b + $
Full Screen
Ctrl-b + z
Next Window
Ctrl-b + n
Previous Window
Ctrl-b + p
Open a Specific Session
Ctrl-b + <number>
Detach Current Session
Ctrl-b + d
Start Session with Name
tmux new -s [name]
Close a Session with Name
tmux kill-session -t [name]
Rename Session
tmux rename-session -t 0 [new name]

VIM

Remove all folds
zR
Toggle fold inside current indent
za
Find Character Before
t}
Find Character Before Backwards
T{
Change to Found Char Before
ct}
Find Character
f}
Find Character Backwards
F{
Change to Found Char
cf}
Re-run the last 'f' or 't' command
;
Re-run the last 'F' or 'T' command
,
End of Current Word
ea
Change Line
cc
Split Editor
:split(:sp) new_file_name
Vertical Split Editor
:vsplit(:vs) new_file_name
Switch Between Splits
Ctrl + w
Mark Current Line
m[a-z] (i.e. ma)
Go to Mark "h"
'h
Show all marks
:marks
Mark Across Files
Use an uppercase mark: m[A-Z]
Previous location (insert mode)
gi
Go to file under cursor
gf
Open shell from vi
:shell
Close shell
Ctrl + d
Open file browser
:E
Show Registers
:reg
Paste from # registers
"[0-9]p (i.e. 0p, "1p, etc.)
Yank to register
"[a-z]yy (then: "ap to paste)
Append to register
"[A-Z]yy (then: "Ap to paste)
Paste from Clipboard
"+p
Record Macro
q[a-z] (i.e. qm - records to m)
Open Multiple Files
vim *:bn - next file
Stop Macro Recording
q
Execute Macro
@[a-z] (i.e. @m or 20 @m to run 20 times
Increment Number
Ctrl + a
Search / Replace Globally
:%s/searchfor/replacewith/g
Search / Replace Current Line
:s/searchfor/replacewith/g
Search / Replace (confirmation)
:%s/searchfor/replacewith/gc
High, Middle, Low
H, M, L
Move up/down
Ctrl + U / Ctrl + D
Move to line 11
11 + G
Indent to surroundings
==
Delete around and within
daw / diw
Delete inner paragraph
dip
Indent a paragraph
>ip
Reverse paragraph indent
=ip
Change between html tags
cit
Delete html tag
dat
Open New Window
:new file_name.txt
Open Vertical Window
:vnew file_name.txt
Go to file
gf
Go Back to prev file
Ctrl + o
Open New Tab
:tabnew
Edit File in Tab
:tabedit file_name.txt
Move forward in tabs
gt
Move backward in tabs
gT
Open Visual Block mode
Ctrl + V
Move to beggining of line
0
Open NETRW file exporer
:e .
Open a file at a line number
vim /path/to/file.conf +120

VS Code

Output HTML Boilerplate
html:5 + ENTER
Open VS Code Settings
CMD/CTRL + ,
Change Values Incrementally
Select a variable thenCMD/CTRL + D to select next instanceEnter insert mode and change all of the selected values

Visual Studio

Windows

Switch to C Drive

  cd /d C:

Flush DNS

  ipconfig /flushdns

All Network Info

  ipconfig /all

Xamarin / MAUI

Push a New Content Page

  Navigation.PushAsync(new ContentPage());

Margin:

  • left/right, top/bottom
  • left, top, right, bottom

Margin with CSS:

  • top/bottom, left/right
  • top, left/right, bottom
  • top, right, bottom, left

YARN

Update all packages in packge.json to the lates version with:

  yarn upgrade

Upgrade to specific versions with:

  yarn upgrade package@version

Reference: yarn upgrade

Package Version (exclude dependencies)

  yarn list --depth 0 | grep [package name]

Show why a package was installed:

  yarn why

ZFS

ZFS Pool Status

  zpool status -v

  zpool history

  # List Datasets:
  zfs list

  # Display all information about all datasets:
  zfs get all

  # Mount filesystem:
  zfs mount /mount_location
Icons made by Freepik and Pixel perfect from www.flaticon.com. Also icon(s) from iconfinder.
"Nōn nōbīs, Domine, nōn nōbīs, sed nōminī tuō dā glōriam."