Thursday, July 31, 2014


Styles within HTML tags:
<p style="font-family: Arial; font-size: 20px; color: blue">A truly spectacular paragraph!</p>

<ol style="background-color: yellow;">
<li style="text-align:left">The Hawthorn Football Club</li>

<strong> -- bold
<em> -- to italicize

<table style="border-collapse:collapse;">
<th colspan="2">test</th>
<td style="padding:5px;border-left:1px solid black;">1</td>
<td style="padding:5px;border-left:1px solid black;">2</td>

Following div will create a 50px X 50px rectangular block of red color:
<div style="width:50px; height:50px; background-color:red"></div>

A very long <span style="color:red;">text</span>!

<link type="text/css" rel="stylesheet" href="stylesheet.css"/>

/* A comment */
body {
    background-color: #C6E2FF;

p {
    color: green;

td {
    height: 50px;
    border: 1px dashed blue;

table {
    border:1px solid black;

a {
    color: #cc0000;
    text-decoration: none;

img {
   display: block;
    height: 100px;
    width: 300px;
    border: 1px solid #4682b4;
    margin: auto; -- puts the image in the center

div {
    height: 50px;
    border-radius: 5px; -- gives a rounded corner
    margin: auto; -- puts the entire block in the center (equal margin on all sides)
    text-align: center; -- center the text within the div block
Cascading selection:
To select p nested within 2 divs:
        <p>I like tacos!</p>

div div p {
    /*CSS stuff!*/

The font-size unit em is a relative measure: one em is equal to the default font size on whatever screen the user is using.
<p style="font-size: 0.5em">Half an em!</p>

Universal Selector: applies to all HTML elements on the page
* {
    border: 1px dashed #3A5FCD;

Classes and IDs based selection:
ID: good for identifying single selector/element on a page.
#summary {
font-size: 20px;
color: #000000;
<p id="summary">summary</p>

Class: good for identify a class/group of elements on a page.
.list_item {
font-family: Vivaldi, cursive;
<p class="list_item">

Psuedo class selectors: - way of accessing state of HTML elements like mouse hover on element <a>:
a:link {
    text-decoration: none;

a:hover {

a:visited {

First child selector: applies to first child <p> element only
p:first-child {
    font-family: cursive;
p:nth-child(2) { -- 2nd child p selected

p:nth-child(3) { -- 3rd child p selected
    color: #CC0000;

Draw circle with div:
div {
display: inline-block;
margin-left: 5px;
border:2px solid black;

Each element gets its own box. The outermost box of each element go all the way across the page.
display property -
• Block - element becomes a block box and takes up the whole width of page (no other element can sit with it on same line) -- this is default behavior in the absence of display property.
• Inline-block: element becomes a block box (no overlapping elements), but allows other elements on same line.
• Inline: allows overlapping and other elements on same line and does not honour dimension settings (height and width etc)
• None: hides the element

div {
height: 50px;
width: 100px;
border: 2px solid black;
border-radius: 5px;
Following universal selector makes all boxes shown in the image above visible.
* {
border: 1px dashed blue;

Margins, border and padding: - Refer box model diagram above.
• Margin - outermost box - space around element.
• Border - edge of element
• Padding - space between content and border.
• Content - content within the element like text within <p>.

Margin: auto - sets equal margin on all sides (top, left, bottom and right)
div {
height: 50px;
width: 100px;
border: 2px solid black;
border-radius: 5px;
background-color: #308014;
margin-top: 20px;
margin-right: 50px;
margin-bottom: 10px;
margin-left: 5px;
Same goes with padding (padding-top, etc).

We can even set margin and padding on one line as:
padding: [top] [right] [bottom] [left];

Border takes - line size in px, solid/dotted/dashed/none, color.

Float property: no overlapping elements, used to place elements.
div {
height: 300px;
width: 100px;
border: 2px solid black;
border-radius: 5px;
background-color: #308014;
float: right;

p {
font-family: Verdana, sans-serif;
font-size: 20px;
width: 280px;
/*Add your CSS here!*/
float: right;

In the above snippet, both <p> and <div> contents will be floated to right however first element in the document will occupy the rightmost position followed by the next element in the doc floated to the right on the same line of page.

 If you tell it to clear: both, it will get out of the way of elements floating on the left and right!

#header { <!DOCTYPE html>
        height: 50px; <html>
        background-color: #F38630;        <head>
        margin-bottom: 10px;                <link type="text/css" rel="stylesheet" href="stylesheet.css"/>
}                <title>Result</title>
.left {        <body>
        height: 300px;                <div id="header"></div>
        width: 150px;                <div class="left"></div>
        background-color: #A7DBD8;                <div class="right"></div>
        float: left;                <div id="footer"></div>
        margin-bottom: 10px;        </body>
} </html>

.right {
        height: 300px;
        width: 450px;
        background-color: #E0E4CC;
        float: right;
        margin-bottom: 10px;

#footer {
        height: 50px;
        background-color: #69D2E7;

1. Default is "static" position - so element is position relative to entire page.
Position: static
2. Absolute - position relative to its parent element that does not have position: static. In absence of such a parent the element will position relative to <html> element.
3. Relative - position relative to where it would have landed if it had default static positioning.
4. Fixed - anchors element to the browser window. Element won't change its position even if you scroll up or down. So this element seems to be glued to the screen and when one scrolls its always visible.

z-index property:
You can think of the z-index as a measure of importance: the higher an element's z-index, the higher it will be "stacked" on the page. Giving your header a z-index of 1 while not giving any of the other elements a z-index ensures that your header will sit "on top of" your other elements and won't get stuck behind them.

#header {
    height: 50px;
    width: 100%;
    background-color: violet;

Saturday, July 26, 2014

Python 2 by example

Python 2.7 syntax examples:
Code samples at : 

1.       Math:
2**3 = 8 , where, ** is exponent operator
+, -, *, / = math operators
% = modulo operator
# - single line comment

“”” my multi line
comment “””
3.       Print:
print(“%.2f”, total) -> will print total rounded to 2 decimal places.
4.       Escape char:
'There\'s a snake in my boot!'
Not required when using double quotes for string.
5.       String:
fifth_letter = "MONTY"[4]
print fifth_letter => prints Y
parrot = "Norwegian Blue"
print len(parrot)
print parrot.lower()
print parrot.upper()
pi = 3.14
print str(pi) => str() converts non-strings to string
Methods that use dot notation only work with strings.
On the other hand, len() andstr() can work on other data types.
print "Spam " + "and " + "eggs"
print "The value of pi is around " + str(3.14)
string_1 = "Camelot"
string_2 = "place"

print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)
ð  Let's not go to Camelot. 'Tis a silly place.
String slicing:
s = "Charlie"

print s[0]
# will print "C"

print s[1:4]
# will print "har"
Getting i/p and printing o/p:
name = raw_input("What is your name?")
quest = raw_input("What is your quest?")
color = raw_input("What is your favorite color?")

print "Ah, so your name is %s, your quest is %s, " \
"and your favorite color is %s." % (name, quest, color)
6.       Datetime library:
from datetime import datetime
print => 2014-07-25 17:42:13.304805
print now.month => 7
print => 25
print now.year => 2014
print '%s/%s/%s' % (now.month,, now.year) => 7/25/2014
print '%s:%s:%s' % (now.hour, now.minute, now.second) =>17:48:28

7.       Comparison:
==, !=, <, >, <=, >=
8.       Logical: and, or, not
9.       Conditional: if, elif, else
def clinic():
    print ("You\'ve just entered the clinic!")
    print ("Do you take the door on the left or the right?")
    answer = input("Type left or right and hit 'Enter'.").lower()
    if answer == "left" or answer == "l":
        print ("This is the Verbal Abuse Room, you heap of parrot droppings!")
    elif answer == "right" or answer == "r":
        print ("Of course this is the Argument Room, I've told you that already!")
        print ("You didn't pick left or right! Try again.")

10.   Functions:
See above example –
def [function_name(param1, param2)]:
                x = 2
                return x
11.   Import:
a.       Generic import: Import a module by name. Ex:
import math

print math.sqrt(25)
b.      Function import:
from [module] import [function]

from math import sqrt
print sqrt(25)
c.       Universal import:
from [module] import *

from math import *
print sqrt(25)
d.      Check everything a module has:
Import math
Print dir(math)
12.   Built-in functions: max, min, abs, type
Max(1,2,3) => 3
Min(1,2,3) => 1
Abs(-10) => 10
Print type(1) => or type(num) == int
13.   List:
zoo_animals = ["pangolin", "cassowary", "cat", "dog"]
print "The first animal at the zoo is the " + zoo_animals[0]
print len(zooanimals)
print zooanimals[0:2] => 1st and 2nd elements in the list
pets = zooanimals[2:4] or zooanimals[2:] => cat and dog => slicing the list.
Cat_index = zooanimals.index(“cat”)
Zoonimals.insert(cat_index, “cobra”) => ["pangolin", "cassowary", “cobra”, "cat", "dog"]
Zooanimals.sort() => sort the list.
zooanimals.remove(“cat”) => remove element from list
                pets[] => empty list
                print “----“.join(zooanimals) => pangolin ---- cassowary ---- cobra ---- cat ----- dog
                List Comprehension syntax:      

                my_list = range(51)
evens_to_50 = [i for i in range(51) if i % 2 == 0]

List Slicing:
List slicing allows us to access elements of a list in a concise manner. The syntax looks like this:


                my_list = range(1, 11) # List of numbers 1 - 10

# print all odds from start to finish so no need to specify the start and end only need stride.
print my_list[::2]
# reverse a list
backwards = my_list[::-1]

to_21 = range(1,22)
odds = to_21[::2]
middle_third = to_21[7:14:1]
14.   For loop:
my_list = [1,9,3,8,5,7]
for number in my_list:
    print 2*number
    print “Well done”
The else block only executes if the for loop executes normally (ie there is no break causing the loop to terminate mid-way).
for loop with range():
n = [3, 5, 7]
def print_list(x):
    for i in range(0, len(x)):
        print x[i]

for I in range(20) => 0 to 20
for I in range(1, 10) => 1 to 9
Need index with for each loop – use enumerate() built-in function:
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
    print index+1, item
Iterate over 2 or more lists at once:
Zip() will create pairs of elements when passed two lists, and will stop at the end of the shorter list.
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_a, list_b):
    # Add your code here!
    print max(a,b)
Populate a list:
evens_to_50 = [i for i in range(51) if i % 2 == 0]
print evens_to_50

15.   Dictionary:
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}
menu = {}
menu[‘Samosa’] = 1.60
del residents[‘Puffin’] => remove item from dictionary
menu[‘Samosa’] = 1.50

for key in residents
                print residents[key]

print residents.items() => returns dictionary as list of key/value pairs.
Print residents.keys() => list of all keys
Print residents.values() => list of all values
16.   While loop:
while count < 10:
                count += 1
                print “Game over!”
17.   Print:
The , character after our printstatement means that our next printstatement keeps printing on the same line.
d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}

for key in d:
    # Your code here!
    print key, " ", d[key]
18.   Lambda: Anonymous function:
Python’s support for functional programming => meaning you are allowed to pass functions around just as if they were variables or values.

lambda x: x % 3 == 0

is same as:

def by_three(x):
    return x % 3 == 0

Usage: filter uses lamba expression below to print only those elements of the list that satisfy that return true for the lambda expression (or satisfy the condition divisible by 3).

my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list) => [0, 3, 6, 9, 12, 15]
19.   Bitwise:

print 5 >> 4  # Right Shift => 0
print 5 << 1  # Left Shift => 10
print 8 & 5   # Bitwise AND => 0
print 9 | 4   # Bitwise OR => 13
print 12 ^ 42 # Bitwise XOR => 38
print ~88     # Bitwise NOT => -89 (equivalent to adding 1 to the number and putting a – sign).

XOR => in-equality is true (0b1100 ^ 0b101010 => 0b100110)

In Python, you can write numbers in binary format by starting the number with 0b.

print 0b1 + 0b11 => 4

bin() – to binary (as string)
hex() – to hex
oct() – to octal

print bin(5) => 0b101
print hex(5) => 0x5
print oct(5) => 05

int(str, radix)  - any string (includes, binary/hex/octal with appropriate radix (2,16,8)) to int

int("110", 2) => 6
print int("0b100",2) => 4
print int(bin(5),2) => 5

20.   Classes:
An empty class:
class Animal(object):

pass – special python keyword for placeholder – in areas of code where python expects an expression.

class Triangle(object):
    number_of_sides = 3
    def __init__(self, angle1, angle2, angle3):
        self.angle1 = angle1
        self.angle2 = angle2
        self.angle3 = angle3

    def check_angles(self):
        if self.angle1 + self.angle2 + self.angle3 == 180:
            return True
            return False

my_triangle = Triangle(90, 30, 60)
print my_triangle.number_of_sides
print my_triangle.check_angles()

class Equilateral(Triangle):
    angle = 60
    def __init__(self):
        self.angle1 = self.angle
        self.angle2 = self.angle
        self.angle3 = self.angle

class MyTriangle(Equilateral):
    def __init__(self, beauty): = beauty
        self.angle1 = 70

my_triangle = MyTriangle(True)
print my_triangle.angle1 # angle1/2/3 not inherited from base class Triangle
print my_triangle.number_of_sides # member inherited from Triangle
print my_triangle.angle # member inherited from Equilateral

1.       object is base class from which all classes inherit (same as Java).
2.       Constructors are - __init__(self…)
3.       Self needs to be the first param for all member methods and constructors.
4.       Derived class constructor needs to initialize all base members that don’t have a default value.
5.       Derived class inherits all base class members that have default values (defined outside of base class’s constructor).

21.   File I/O:
my_list = [i**2 for i in range(1,11)]
# Generates a list of squares of the numbers 1 - 10

f = open("output.txt", "w")

for item in my_list:
    f.write(str(item) + "\n")



with open("text.txt", "w") as my_file:

with … as syntax is like try-with-resources in Java and it auto closes the file.

Monday, July 21, 2014

Book Review: Pro Git

Very nicely explained and author has a sound understanding of the fundamentals of the Git version control system is evident from his writing. I did not need to buy the dead tree version of the book since the ebook for my kindle was available for free. It delves into the basic topics first so that if you have read the first 4 chapters, then that knowledge will be sufficient to get you to start using git on a day 2 day basis. The remaining chapters can be browsed over and read on an as needed basis. Since the book is available in several formats it is very easy to access it at work on a PC and at home on my kindle. Scott Chacon has done an excellent job explaining Git concepts very clearly and the illustrations in the book are also very well done and aid in the understanding of the text and the subject matter. Highly recommended.

Sunday, July 20, 2014

Concise Git Reference for everyday use

This is compilation of all Git commands referring to "Pro Git" book by Scott Chacon.
  • Git config files:
    • /etc/gitconfig - config applicable to all users.
    • /.gitconfig - specific to a user.
    • ~/.git/config - config per git repo.
    • Typical configs:
      • git config --global "Watsh Rajneesh"
      • git config --global ""
      • git config --global color.ui true
      • git config --global push.default simple
      • git config alias.last=log -1 HEAD
    • git config -l => shows the current config.
  • git [command]  --help
    • e.g. git commit --help
  • Create a new git repo from existing directory:
    • git init
    • git add *
    • git commit -m 'my comment'
  • Cloning an existing repo:
    • git clone
      • will create a local .git directory which will hold the entire repo with all the history known at the time of cloning.
      • will create a tracking branch "master" which will track the "master" branch on remote (or origin/master - see below point)
      • will save the as remote named "origin"
  • Git lifecycle states:
    • Untracked -> staged -> committed (tracked)
  • git status => shows:
    • Changes to be committed - staged files
    • Changed but not updated - modified files
  • git diff - to see diff between modified and staged version
    • git diff --cached - to see diff between staged and last committed version
  • git commit -a -m 'message' => skips staging and directly commits all modified files.
  • Remove files:
    • git rm [file]
    • git rm --cached => keeps the modified file but removes the staged versions of the file.
  • Rename a file:
    • git mv [file_from] [file_to]
  • Git log:
    • git log --pretty=format:"%h <%cr> [%cn] %s" --graph --name-only --since=2.weeks --author=Watsh
    • gitk - GUI to visualize history
  • Change last commit:
    • git commit --amend
  • Unstage a staged file:
    • git reset HEAD [file]
  • Unmodify a modified file:
    • git checkout -- [file]
  • Remotes:
    • git remote -v
    • git remote add watsh_repo
    • Inspecting remote:
      • git remote show watsh_repo
    • Removing and renaming remote:
      • git remote rename watsh_repo watsh_repo2
      • git remote rm watsh_repo2
  • Fetching from remote:
    • git fetch [remote]
      • git fetch watsh_repo
    • The command goes out to that remote project and pulls down all the data from that remote project that you don’t have yet. After you do this, you should have references to all the branches from that remote, which you can merge in or inspect at any time.
    • If you fetched a new branch created and pushed by your colleague and you need to start working on the same branch, you first get the branch reference in your local git repo (the .git directory) by doing a git fetch and then create a new branch referring to that reference ([remote]/[remotebranch]). The new branch thus created will be a tracking branch (hence git pull/push will automatically resolve to the right remote branch from the local tracking branch context).
      • git fetch watsh_repo
      • git checkout -b bug456 watsh_repo/bug456
  • Pushing to remote:
    • git push
      • git push watsh_repo master
      • It pushes your "master" branch changes to watsh_repo's "master" branch.
    • git push [remote] [localbranch]:[remotebranch]
      • git push watsh_repo master:release1.2.3_branch
      • Pushes local master to release1.2.3_branch remote branch on watsh_repo.
  • Tagging:
    • git tag -l 'v1.2.3.*'
    • git tag -a v1.4 -m 'my version 1.4' => creates annotated tags
    • git show  [tagname]
    • git push [remote] [tagname] => by default tags are not pushed with git push so we need to do this explicitly.
      • git push watsh_repo2 v1.4
      • git push watsh_repo2 --tags => push all tags
  • Auto completion for git:
    • wget 
    • . ~/.git-completion.bash
    • cp ~/.git-completion.bash /etc/bash_completion.d => will enable git auto completion on bash launch for all users.
  • Branching & Merging:
    • git branch bug123
    • git checkout bug123
      • Fix the bug123 by making changes
      • git commit -a -m 'added fix for bug123'
    • git checkout -b 'hotfix'
      • Make hotfixes
      • git commit -a -m 'hotfixes done'
    • git checkout master
      • git merge hostfix
      • git branch -d hotfix => since we are done with hotfix branch, so delete it.
      • git merge bug123
      • git branch -d bug123
    • See which branches are already merged into:
      • git branch --merged
    • See all branches that contain work you have not merged in:
      • git branch --no-merged
    • Checking out a local branch from a remote branch automatically creates what is called a tracking branch. Tracking branches are local branches that have a direct relationship to a remote branch. If you’re on a tracking branch and type git push, Git automatically knows which server and branch to push to. Same is true for git pull.
    •  git checkout -b [branch] [remotename]/[branch]
      • git checkout -b sf origin/serverfix
      • Now, your local branch sf will automatically push to and pull from origin/serverfix 
    • Delete remote branch:
      • git push [remotename]  :[remotebranch]
      • Giving no local branch name before ':' above has the effect of deleting the remote branch.
  • Use cases:
    • Begin working on a new feature/bug:
      • git checkout -b myfeature_branch origin_feature_branch
      • git pull 
      • // do your works on myfeature_branch
      • git push --set-upstream origin myfeature_branch
      • git push origin myfeature_branch 
        • Make your myfeature_branch available on the remote git server so others can checkout it for reviewing or working with you (say multiple ppl working on the myfeature feature).
      • // once work is reviewed and ready to be merged to origin_feature_branch
      • git checkout origin_feature_branch
      • git pull
      • git merge --squash myfeature_branch 
        • Merge with --squash option which will commit all changes from myfeature_branch (across several commits on myfeature_branch) into a single commit on the origin_feature_branch. This ensures a cleaner history, ease of reverting the changes collectively that were brought in from myfeature_branch.
        • Note down this SHA-1 - we can use this for cherry picking this change to release branch next.
      • git push origin origin_feature_branch 
      • Delete the myfeature_branch from remote and local:
        • git branch -d myfeature_branch
        • git push origin :myfeature_branch
    • Cherry pick a change by its SHA-1 id:
      • git checkout release_branch
      • git cherry-pick [SHA-1 of the squashed commit from myfeature_branch]
      • git push origin release_branch
  • Git credentials:
You can store your credentials using the following command. This was very helpful to not having to re-enter credentials everytime i did a git push for instance.
$ git config credential.helper store
$ git push
Also I suggest you to read
$git help credentials
The above is generally the basic working knowledge of Git which one needs on a day-to-day basis. Of course there are more advanced use cases related to stashing away your changes (pushing to a stack and popping them out), rebasing (which is more or less like merge command). I intend to cover those in later updates to this post. So long...

Sunday, July 06, 2014

MyGit repo - Some of my code samples

rwatsh/MyGit -

I have pushed some sample code which i had written recently covering various areas of Java programming (maven, OSGI, JUnit, Annotations, REST, JSF, Design patterns, algorithms, data structures, Java EE etc.).

sjsucohort6 -

My MSSE projects (i will be making them public as and when i am done with the exams).

Reset the AdminServer Password in WebLogic 11g and 12c

ORACLE-BASE - Reset the AdminServer Password in WebLogic 11g and 12c

Reset the AdminServer Password in WebLogic 11g and 12c

If you forget the AdminServer password for your WebLogic 11g domain, you can reset it from the command line using the following process.
  • Set up the following environment variables. They are not necessary for the process itself, but will help you navigate. In this case my domain is called "ClassicDomain". Remember to change the value to match your domain.

    export MW_HOME=/u01/app/oracle/middleware
    export DOMAIN_HOME=$MW_HOME/user_projects/domains/ClassicDomain
  • Shut down the WebLogic domain.

    $ $DOMAIN_HOME/bin/
  • Rename the data folder.

    $ mv $DOMAIN_HOME/servers/AdminServer/data $DOMAIN_HOME/servers/AdminServer/data-old
  • Set the environment variables.

    $ . $DOMAIN_HOME/bin/
  • Reset the password using the following command. Remember to substitute the appropriate username and password.

    $ cd $DOMAIN_HOME/security
    $ java <username> <password> .
  • Update the "$DOMAIN_HOME/servers/AdminServer/security/" file with the new username and password. The file format is shown below.

  • Start the WebLogic domain.

    $ $DOMAIN_HOME/bin/

Wednesday, July 02, 2014

Book Review: The Complete Tales of Winnie The Pooh by A.A.Milne

The Complete Tales and Poems of Winnie-the-PoohThe Complete Tales and Poems of Winnie-the-Pooh by A.A. Milne
My rating: 5 of 5 stars

Read it to my about-to-be 7 years old son, who generally likes science fiction chapter books to be read to him, but for a change, one day picked up this book and to my surprise we read chapter after chapter for a few days in succession during bed time. He was particularly delighted by the humor in the book and it was a great fun reading him this classic by A.A.Milne. Christopher Robin in the stories is author's son and author is narrating the stories as if he is reading it to his son and then at times he will come out of the hundred acre woods to the real world and respond to his son's questions. Most children who have watched disney's rendition of Pooh's world already will be familiar with the characters in the stories - from Pooh, to piglet, to owl, eeyore, rabbit, kanga, roo and tigger. The book and its prose may be more suited to a child 5yrs and above as then they will be able to appreciate the humor and the literature of the book. One humorous incident in one of the stories happens between Pooh and Owl when Owl is trying to tell him about an "issue" and Pooh thinks Owl is sneezing when he is saying "issue". The way author presents this in the story is very humorous and both me and my son went rolling with laughter. A must read collection of short stories.

View all my reviews

15 sorting algorithms visualized in 5 minutes, with awesome arcade sounds

15 sorting algorithms visualized in 5 minutes, with awesome arcade sounds from r/programming