Snippets

Jason Cheong-Kee-You edited this page Sep 27, 2017 · 2 revisions

CSS

# Remove anchor outlines
a {outline: none;}

# Make element inline
.post h2 {display:inline;}

# Stop text from overlapping with right-aligned images
h1, h2, h3, hr {clear:both;}

Git

# Retroactively turn a set of commits into a branch
git branch fixes       # copies master to new branch
git reset --hard XXX   # resets master to XXX

# Delete local branches that have been deleted remotely
git remote prune origin

# Rebase branch
git co master
git pull
git co branch-name
git rebase master

# Merge changes from branch into master
git co master
git merge --ff-only branch-name

# Add file changes to index
git add .

# Selectively add changes
git add --patch somefile.txt

# List branches
git branch

# Rename local git branch
git branch -m [oldname] [newname]

# Create branch based on master
git branch scrap

# Branch from a previous commit
git branch branchname [sha1-of-commit]
git branch branchname HEAD~3

# Create branch based on current checkout
git checkout -b new_branch

# Delete branch
git branch -d scrap

# Rename branch
git branch -m old_branch new_branch

# Replace master branch with another branch
git branch -m master archive_master
git branch -m new_master master

# Create a branch from a specified commit point
git checkout [SHA]
git branch staging
git checkout staging

# Revert changes for a specifed file
git checkout myfile.txt

# Clone a project from github
git clone git@github.com:yourusername/yourapp.git

# Commit changes
git commit -m "commit message"

# Add files and commit with a single command
git commit -a -m "message"

# View diff and commit
git commit -v

# Amend last commit message
git commit --amend -m "New commit message"

# Configure git
git config --global user.name "Your Name"
git config --global user.email "your.email@gmail.com"
git config --global core.autocrlf false

# Show file changes
git diff

# View changes that have been added, but not committed
git diff --cached

# Pull changes from github
git fetch github
git merge github/master

# Create initial git repository
git init

# View git log
git log

# View git log for a specified file
git log myfile.txt

# Merge branch into master
git checkout master
git merge scrap

# Push changes to remote server
git push

# Delete remote branch
git push origin --delete [branchName]

# Push to remote repo
git push reponame master

# Push branch to remote repo
git push reponame branchname:master

# Force push of branch to heroku
git push --force heroku branchname:master

# Squash last 3 commits
git rebase -i HEAD~3

# Edit a commit
git rebase -i HEAD~3
  # Select 'e' for the commit to edit.
  # Run the following to undo the last commit:
  git reset --soft "HEAD^"

# Abort interactive rebase
git rebase --abort

# Add reference to remote repo
git remote add staging git@heroku.com:yourapp-staging.git

# Remove reference to remote repo
git remote rm heroku

# Unstage all files in index
git reset

# Unstage a single file in index
git reset [file]

# Revert all uncommitted changes
git reset --hard

# Revert back to a specific commit point (destroys all subsequent commits)
git reset --hard [commit]

# Undo last commit (keep changes in working directory)
git reset --soft "HEAD^"

# Revert an existing commit
git revert [commit]

# Revert an existing commit without committing
git revert -n [commit]

# Delete file and remove from source control
git rm somefile.rb

# Save current changes to stash
git stash

# Pop stash (restore and drop)
git stash pop

# Restore stash (without dropping it)
git stash apply

# Show files changed
git status

# Tag a project and push the tag to github
git tag -a v0.1.6
git push --tags

Heroku

# Pull database from heroku
dropdb joinful
production pg:pull HEROKU_POSTGRESQL_AMBER_URL joinful

# Push database to heroku
staging pg:reset HEROKU_POSTGRESQL_BLUE_URL
staging pg:push joinful HEROKU_POSTGRESQL_BLUE_URL

# Deploy steps
staging maintenance:on
git push staging master
staging run rake db:migrate
staging restart
staging maintenance:off

# Backup production and restore to staging
heroku addons:add pgbackups --app app-production
heroku addons:add pgbackups --app app-staging
heroku pgbackups:capture --app app-production
heroku pgbackups:restore DATABASE `heroku pgbackups:url --app app-production` --app app-staging

# Run heroku command for specified app
heroku config:add RACK_ENV=staging --app yourapp-staging

# Add exception logging
heroku addons:add exceptional

# View app's config vars
heroku config

# Exclude 'development' and 'test' gems
heroku config:add BUNDLE_WITHOUT=development:test

# Set RACK_ENV
heroku config:add RACK_ENV=staging

# Create a new Heroku app
heroku create

# View the most recent 100 lines of the production log file
heroku logs

# Realtime log streaming
heroku logs --tail

# Maintenance mode
heroku maintenance:on
heroku maintenance:off

# Open the deployed app in your browser
heroku open

# Drop database
heroku pg:reset SHARED_DATABASE

# Run rake commands
heroku rake db:migrate

# Rename app
heroku rename newname

# Restart app
heroku restart

Javascript

# Have html page reload on focus (good for spiking css)
<head>
  <script type="text/javascript">
    onload = function () {
      onfocus = function () {location.reload(true)}
    }
  </script>
</head>

# Trigger form submit on ui control event
$('#language').on('change', function() {
  $(this.form).submit();
});

# Suppress standard form submission
$('#z-search-form').on('submit', function(event) {
  event.preventDefault();
});

# Attach function call to form submission
$('#z-search-form').on('submit', doSearch);

# Set the contents of matching elements
$('.elements').html('content')

# Replace matching elements
$('.elements').replaceWith('content')

# Currently selected value in dropdown
$('#dropDownId').val()

# Currently selected text in dropdown
$('#dropDownId :selected').text()

# Test if something is hidden
$(element).is(":visible")

# Click on element
$('.some_element').click();

# Do something if element not found
if ($('.some_element').length == 0) {
  # Do something
}

# Click on link
var link = $(".some_link");
window.location.href = link[0].href;

# Get parent element
$(".some_element").parent();

# No-op anchors
href="javascript:void(0);"

# Shortcut for '$(document).ready(callback)'
$(function() {
  # code to execute when the DOM is ready
});

# Submit form when .js-link is clicked, where each .js-container contains
# a form and a .js-link
$('.js-link').click(function() {
  $(this).closest('.js-container').find('form').submit();
});

# Submit form
$(".form").submit();

# Determine if an element exists
if ($(selector).length)

# Run something after 2 second delay
$(this).setTimeout(function() {...}, 2000);

# Run code on checkbox change
$("input[type=checkbox]").change(function() {
  # code
});

# Run code on element click
$(selector).click(function() {
  # code
});

# Animate bootstrap dropdown using jquery
$('#something .dropdown-menu').fadeIn(function() {
  $(this).fadeOut();
});

Ruby

# Display callstack
puts caller

# Remove trailing and consecutive whitespace
' a  b  c '.squish == 'a b c'

# Debug Capybara
save_and_open_page

# Specify code that will not run when a file is required
if __FILE__ == $0
  puts "This will not be outputted."
end

# Render partial in a json call
render :json =>  { :html => render_to_string('agents/_partners.html.slim') }

# Render a partial inside a partial in a json call
render :template => 'posts/_post.html.erb'

# Get directory of current file
File.dirname(__FILE__)

# Get path of (possibly symlinked) file
THIS_FILE = File.symlink?(__FILE__) ? File.readlink(__FILE__) : __FILE__

# Get name of application
Rails.application.class.parent_name

# Redo last migration
rake db:migrate:redo

# Get list of files in directory
Dir.glob('/directory/*.html')

# Build directory, including parents
require 'fileutils'
FileUtils.mkdir_p directory

# Build hash from array
h = Hash[arr.map { |v| [v, f(v)] }]

# Build hash from array
arr = [:a, 1, :b, 2]
Hash[*arr]

# Build a duck type object without defining a class
OpenStruct.new(name: item.name, sell_in: sell_in, quality: quality)

# Automatically load files in a subdirectory relative to current source file
lib_dir = File.dirname(__FILE__)
full_pattern = File.join(lib_dir, 'updaters', '*.rb')
Dir.glob(full_pattern).each do |file|
  require file
end

# Automatically load stylesheets in a Rails directory
<%
  full_pattern = File.join(Rails.root, 'public', 'stylesheets', 'sass', '*.sass')
  files = Dir.glob(full_pattern).map do |file|
    file.split('/').last.split('.').first
  end
%>
<%= stylesheet_link_tag *files, :media => 'all' %>

# Convert a file name to a class name
require 'active_support/all'
file.split('/').last.split('.').first.classify

# Convert a string to a class
'SomeClass'.constantize

# Find date in range
(start_date..end_date).include?(date) # bad
(start_date..end_date).cover?(date) # good

# Log exceptions
logger.error e.message + "\n " + e.backtrace.join("\n ")

# Access view helpers from controller
ActionController::Base.helpers.number_to_currency

# Log exceptions in controller with exception_logger
log_exception(ex)

# Reference images from asset pipeline in email views
config.action_mailer.asset_host = 'http://localhost:3000'
config.action_mailer.default_url_options = { host: 'localhost:3000', only_path: false }

# URL encode
Rack::Utils.escape('http://example.com')
#=> "http%3A%2F%2Fexample.com"

# Use factory_girl in console
require 'factory_girl'
require './spec/support/factories'
100.times { FactoryGirl.create(:coupgon) }

# Redirect to another page from javascript request
format.js { render :js => "window.location.href = '#{some_path}'" }

# Update files for new version of rails
rake rails:update

# Sum array
[1, 3].reduce(:+)

# Install test-specific gems
sudo rake RAILS_ENV=test gems:install

# Assert text is rendered in the html for a Cucumber feature step
response.body.should =~ /#{text}/

# Create a new Rails application
railsapp base scrap

# Add anchor to link
<%= link_to 'Comments', post_path(post, :anchor => 'disqus_thread') %>

# Configure app based on rails environment
if RAILS_ENV == 'development'
  # do something dev-specific
end

# Set focus on first field with jQuery
$("input:text:first:visible").focus();

# Trim leading zeros
s.sub! /\A0+/, ''

# Use hash parameter
set_file :open_now => true, :filename => 'jeff.txt', :lines_to_read => 50
def set_file(options)
  if options[:open_now]
    # open the file
  end
  # etc.
end

# Determine whether a variable is defined
if defined? variable_name

# Set default value
your_variable ||= "Default"

# Catch all exceptions
rescue Exception => e

# Class constants
class ConstClass
  C1=101
end
ConstClass::C1

# Use Array.new() to create an array with a block
Array.new(57) {|i| "slejfund.#{i.to_s}@mailinator.com" }.join(',')

# Access raw value from database before ruby converts to a ruby object
l = Lesson.find(:first)
l.start_date
l.start_date_before_type_cast

# View database schema
script/dbconsole
.help
.schema posts
.quit

# Irreversible migration
raise ActiveRecord::IrreversibleMigration

# Get day of week index for date
date.wday

# Write day of week for date
date.strftime("%A")

# Test object for nil
a.nil?

# sort_by
h.sort_by{|p| [p['fname'], p['lname']]}

# Format dates and times
strftime

Miscellaneous

# View hidden files in Finder
[Command + Shift + .]

# Backup and restore Postgres database
pg_dump --verbose -F c -b -h hostname -p port -U username -f "backup.dump" database_name
pg_restore --verbose --clean --no-acl --no-owner -h hostname -p port -U username -d database_name "backup.dump"

# Uninstall all gems
for gem (`gem list | cut -d" " -f1`); do gem uninstall $gem -aIx; done

# Install gems into project directory
bundle install --path=.bundle

# Stop/Start Postgres
sudo port unload postgresql92-server
sudo port load postgresql92-server

# Get ip address
ipconfig getifaddr en1

# Visual diff
opendiff [file1] [file2]

# Rename Terminal tab
[Command + Shift + I]

# Create thumbnail of an image
convert -thumbnail x100 source.jpg thumbnail.jpg

# Clear Terminal
[Command + K]

# Toggle between windows for current app
[Command + `]

# Bring back last closed tab in Chrome
[Command + Shift + T]

# Run series of commands, short ciruit on failure
ls foo && ls bar

# Find and kill process
ps -all | grep [name]
kill [pid] # Tell process to cleanup and terminate
kill -9 [pid] # Only if plain kill fails, since process will terminate without cleanup
killall [name]
killall -9 [name]
pkill rsync*
pkill -9 rsync*

# Install nodeunit with npm
sudo npm install nodeunit -g

# Record current directory and change location to specified directory
pushd [directory]

# Change location to last recorded directory and remove directory from record
popd

# Determine type of file
file -I [filename]

# Delete git entries from a ZIP file
zip -d [filename] "*.git*"

# Extract ZIP file, converting line endings for text files
unzip -a [filename]

# Find files in tree
find . -type f -name [filename]
find . -name "*.js"
find . | grep .js

# Find filenames quickly
locate [filename]

# Show shutdown dialog on Mac OS X
Control-Eject

# Move focus to the menu bar on Mac OS X
Control-F2

# Restore Dell machine to factory settings
Hold down Control+F11 at the Dell splash screen during boot up

# Flush DNS cache on Mac OS X
dscacheutil -flushcache

# Deterine Ubuntu version
lsb_release -r

# Open shell with root
sudo -s

# Synchronize time on Ubuntu
sudo apt-get install ntp

# Zip current directory to scrap.zip
zip -r scrap .

# Toggle between the two most recent current working directories
cd -

# Grep directory recursively
grep -r [string] [directory]

# Enable [Backspace]
stty erase [Ctrl-v][Backspace]

# Enable [Ctrl-c]
stty intr [Ctrl-v][Ctrl-c]

# Gzip Tar Files
tar cvzf [filename] # create
tar tvzf [filename] # list table of contents
tar xvzf [filename] # extract
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.