Java Optional Best Practices


Linux File Manager Nemo Tips and Tricks


Spell and Grammar Check for Markdown


Best Practices to Handle Exceptions in Java


Autoboxing and Unboxing Tips and Traps in Java


Add Google Custom Search to WebSite


Git Tips Tricks for Developers


Untitled

Install Bash git completion

  • brew install git bash-completion

Caching GitHub password in Git

  • git config --global credential.helper 'cache --timeout 72000'
  • Remove cached password (to reenter new password when it’s changed)
    • git credential-osxkeychain erase

Temporarily ignoring files

  • git update-index --assume-unchanged file-path
  • git update-index --no-assume-unchanged file-path

Remove file from the repository but keep it locally

  • git rm --cached -r somedir/somefile then add them to .gitignore

Reset current HEAD to the specified state

undo last commit
  • git reset --soft HEAD~1
  • Undo commits permanently: git reset --hard HEAD~3
    • The last three commits (HEAD, HEAD^, and HEAD~2) were bad and you do not want to ever see them again.
  • Undo a merge or pull inside a dirty working tree: git reset –merge ORIG_HEAD
  • return to any previous revision
    • git reset --soft commit_hash
  • Reset committed changes to local changes
    • git reset HEAD~

undo git pull

  • git reset --hard

Reset local branch to be same as remote branch

  • git fetch --all && git reset --hard upstream/master
  • If need delete everything(just like re-clone): git clean -x -d -f

~ vs ^

  • Both ~ and ^ on their own refer to the parent of the commit.
  • ~2 means up two levels in the hierarchy, via the first parent if a commit has more than one parent
  • ^2 means the second parent where a commit has more than one parent (i.e. because it’s a merge)
  • HEAD~2^3 means HEAD’s grandparent commit’s third parent commit.

rebase

Edit your X most recent commits interactively (squash, fixup, reword, drop)
  • git rebase -i HEAD~X
Modify a specific commit
Split a commit in two with Git
Delete a commit
  • If it is the last commit this is very straight forward. git reset HEAD

Branch

  • Delete local branch: git branch -d <local_branchname>
  • Delete remote branch: git push origin --delete <remote_branchname> or git push origin :<remote_branchname>
  • Rename local branch name: git branch -m <new-branch-name>
Checkout remote brach

git log

  • git log –oneline [–pretty=oneline]
Show commit id only
  • git log -1 –pretty=format:“%H”

View change in a specific commit

  • git show

Undo anything

Wipes your unstaged changes
  • git checkout
undo rm -rf * - git stash - if no local update

undo git commit –amend

  • git reset –soft HEAD@{1}
Checkout remote file after merge conflict
  • git checkout HEAD the_file

shallow clone

  • git clone --depth 1 https://path/to/repo/foo.git -b bar
  • –no–single–branch instead -b bar, to download first commit form ALL branches.
  • –no-checkout(-n): No checkout of HEAD is performed after the clone is complete.

ls-remote

git ls-remote --tags remote_git_url

Tags

  • git tag

git clean

  • -n: –dry-run
  • git clean -x -d -f

git commit

  • Add change to your last commit, instead of making a new commit
    • git commit --amend
Commit messages
  • <type>(<scope>): <subject>
  • type: feat(new feature), fix, docs, style(format code, no code change), refactor, test(add test cases), chore

git remote

  • List all remotes: git remote
  • Add another remote: git remote add upstream the_url
  • git remote show
  • git remote show upstream

git stash

  • -u|–include-untracked
  • List all stashes: git stash list
  • git stash
  • Also stack untracked files: git stash -u
  • Apply the stash: git stash apply <stash@{n}>
  • Apply last stash and remove the stash: git stash pop
  • git stash clear
  • git checkout <stash@{n}> -- <filePath>

git diff

  • Ignore the white space: git diff -w
  • Show local staged change(added but not committed): git diff --cached
  • Show committed but not pushed change: git diff origin/master..master

emoji

Misc

How to Copy Text From Copy-Protected Web Pages


How to Copy Text From Copy-Protected Web Pages

Awesome Tips about Chrome Series


The Problem

Sometimes we want to copy some text/code from a website, but find out that it disables copy text or even completely disables right click, right context menu. It’s annoying, but we can fix it easily.

Using Proxy Sites

Specific Chrome Extensions

We can use the following Specific Chrome extensions to make us able to copy text.

Reader View Chrome Extensions

If we don’t want to install the above specific Chrome extensions, then we can use the more general reader view chrome extension which can also make us able to copy text.

Read here for more must-have google chrome extensions

Reader View

  • This opens the page in chrome-extension:// and we have to wait until (at least) the main content of the page is loaded.
  • The greatest thing is it reduces the memory usage a LOT for pages that load a lot of flashes, ads.
    • e.g. reduces this page from around 450+ mb to 87mb.
  • This also works well together with The Great Suspender: the page in reader view will not be suspended as it runs in extension mode.
  • Assign shortcut Ctrl+Shift+R to Toggle the Reader View
  • Print and save the reader mode version, show or hide image.
  • Able to change the speed of text-to-speech
  • The Cron is it doesn’t work with other extensions, e.g., Chrome Vimium
    • as It opens the page in chrome-extension.
Tips

Just Read

  • Able to change theme(dark or light), width, font size and save the config.
  • Assign Ctrl+Shift+L to Open the Just Read format for the current page
  • Assign Ctrl+Shift+K to Enable user text selection mode using Just Read, then choose which part you want to select then enter (it will automatically try best to choose), it will show the section in read mode.
  • When it doesn’t work(e.g. in quip), use View this selection in Just Read.
  • Works with Chrome Vimium

Clearly

  • Assign shortcut Ctrl+Shift+C to Toggle Clearly
  • Make not easy to copy text easier to copy
  • Support outline, different themes, fullscreen, text-to-voice
  • Cron: Can’t change the width
  • Distill Page from Chrome
  • the result is not that good, and hard to run the command.

Mercury Reader

  • can’t change width

Summary

  • Use Reader View when the page(website) is slow: load lots of ads, flash, uses a lot of memory and you will take time(2+ mins) to read it.
  • Use Just Read in other case.
  • Use Clearly to check the outline.

Prefer Collections over Arrays


How to Make Money with the Amazon Associates Program


How to Make Money with the Amazon Associates Program

Amazon Affiliate Program provides different kinds of ads.

Native Shopping Ads

  • amzn_assoc_placement should be unique.
  • amzn_assoc_search_bar: false/true to whetehr show the search bar.

Custom Ads

Custom Ads allows us to curate specific products from Amazon that you would like to recommend and place the ad unit into your webpage. All we need is find a list ASINs of products and add them into amzn_assoc_asins.

<script type="text/javascript">
amzn_assoc_placement = "adunit0";
amzn_assoc_search_bar = "false";
amzn_assoc_tracking_id = "the_tracking_id";
amzn_assoc_ad_mode = "manual";
amzn_assoc_ad_type = "smart";
amzn_assoc_marketplace = "amazon";
amzn_assoc_region = "US";
amzn_assoc_title = "Best books for algorithms interview";
amzn_assoc_linkid = "the_amzn_assoc_linkid";
amzn_assoc_asins = "0984782850,1517671272,1617292230,032157351X,1537713949,0262033844,111941847X,819324527X";
</script>
<script src="//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US"></script>

<div id="amzn-assoc-ad-19c89cc6-6f8f-485d-a31a-7bc49e98e831"></div><script async src="//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US&adInstanceId=19c89cc6-6f8f-485d-a31a-7bc49e98e831"></script>

Recommendation Ads

  • Displays products related to your page content and visitors
  • We can choose “Emphasize Categories”.

Search Ads

  • Display search results from Amazon.com by specifying a search phrase and selecting a relevant category to your page content in a responsive ad unit that works across screen sizes.

  • We can specify a list of search phrases and sort them by priority, random pick one search phrase and stick to it in the X(10) days.

<script type="text/javascript">
  function createCookie(name, value, days) {
    if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      var expires = "; expires=" + date.toGMTString();
    } else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
  }

  function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(";");
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == " ") c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
  }

  function deleteCookie(name, path, domain) {
    if (readCookie(name)) createCookie(name, "", -1, path, domain);
  }

  function pickOne(weightedPosts) {
    var totalWeight = 0;
    for (let post of weightedPosts) {
      totalWeight += post.weight;
    }
    var randomWeight = Math.random() * totalWeight;
    var currWeight = 0;
    for (let post of weightedPosts) {
      currWeight += post.weight;
      if (currWeight > randomWeight) {
        return post;
      }
    }
  }
</script>

<script type="text/javascript">
var pos = readCookie("amazonItemPos")
var products = Array("iphone",  "iPad Pro", "iPad Mini", "apple watch series 4", "MacBook Pro", "MacBook Air", "google pixel 3", "chromebook", "Amazon Echo");

var items = new Set();
var totalCount = products.length;
for (var i = 0; i < products.length; i++) {
  items.add(
    {
      product: products[i],
      weight: totalCount - i,
      pos: i
    }
  );
}
// var item = items[Math.floor(Math.random() * items.length)];
if (pos == null || pos <0 || pos > products.length) {
  // pos = Math.floor(Math.random() * items.length);
  pos = pickOne(items).pos
  createCookie("amazonItemPos", pos, 10);  
}

var item = products[pos];
amzn_assoc_placement = "adunit3";
amzn_assoc_search_bar = "true";
amzn_assoc_tracking_id = "the_tracking_id";
amzn_assoc_search_bar_position = "bottom";
amzn_assoc_ad_mode = "search";
amzn_assoc_ad_type = "smart";
amzn_assoc_marketplace = "amazon";
amzn_assoc_region = "US";
amzn_assoc_title = "";
amzn_assoc_default_search_phrase = item;
amzn_assoc_default_category = "All";
amzn_assoc_linkid = "the_amzn_assoc_linkid";
</script>
<script src="//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US"></script>

Tips

Mockito Best Practices


User Scripts to Change Html5 Video Player Speed


The Goal

I Would like to change the speed of HTML5 video player at pan.baidu.com, so I can spend less time on the video and finish it sooner.

The Implementation

I found some user script at greasyfork for Chrome with tampermonkey extension

Based on these 2 script, I made the following simple user script that can change video speed to 1.5, 1.75, 2.0.

Other Ideas

  • Able to resume playback of a video at the point in time it was left.

How to be More Productive - Detail


Make it easier to find

  • Put frequently used apps (like Google Keep) in first screen, etc
  • Add bookmark with short and easy to remember name in Chrome to make it easier to find
  • Delete history in Chrome to make search/autocompletion in Address bar work better
  • Minimize(or kill) windows that are not going to be used recently

How to Save Context

  • Compile error
  • TODO tag
  • Put the web page into a new window
    • When we find something online that we should read or search later, we can shift+w to put this page into a new window so we can go back to it later.
    • We can also use The Great Suspender to suspend the new tab or window so these pages don’t consume a lot of RAM.
  • Git diff
  • Undo then redo in editor
    • Use Case: After search, or move pointer, we would like to go back to last edit position.
Pin
  • Use Atom pinned-tabs to pin files that you are constantly working on recently
  • “PINNED-TABS: CLOSE UNPINNED” if needed.

Preserve Last Session

  • Set Chrome, iTerm2, Atom to restore last session.
  • In Atom, select Preserve Last Search for Command Palette and Fuzzy Finder

2X player

What to do at Spare Time (<5)

  • Clear things in Gmail(delete emails or draft), Google Keep

What else we can do

  • During development, the depended service is down, before they fix it, we can still clean the code or create the PR.

Example

  • Need a pr to test branch in another remote to make some experiment -> directly push to the test branch
  • Run multiple long-time(>2+ seconds) commands together: delete.sh && build.sh && deploy.sh
  • During development/test, don’t make change in the build output,
    • When we apply the change back to source, we may forget what change we have made, or waste some time to figure it out.

java.time Best Practices


Generics in Java


How to be More Productive


What Problems to Solve

  • is it worth?
  • to what extent?
  • Should we fix it now? or put it into backlog and solve it later?
    • Our brain will work on the problem in background, after we work on more same problem/domain, it may be much easier to solve it.
  • what you try to achieve or learn

Priority

  • work on the most important thing
    • put trivial things into backlog

Proactive

Track + Notification

  • Use Timer for wakeup
  • Use Calendar to track event, deadline
  • Use Keep to track ideas/todo

Less Distraction

Turn off unnecessary notification

  • Gmail
    • Gmail App only notifies email from primary category
    • Figure our why it’s marked as important and remove its filter or move it out from Primary category

Schedule

Health

  • sleep and wake up at the same time

Sleep & Rest

Music

  • to wake up
  • get excited

Wake up

  • My wife is a teacher, so she wakes up very early at 6:00 am
  • It’s best for me to adjust accordingly: wake up early.

Track TODO

Developer TODO

  • TODO
  • leave a compile error

Motivation

  • Have a thing to do/wake up tomorrow

Get Things Done

  • the problem/pain-point, find a way to fix it
  • Write things down

Guide to Google Guice


Java subList Tips and Traps


Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)