Monday, October 8, 2018

Regular Expression Note in Ruby

What does regular expression do
Given a string, and a pattern, find if the string contains the pattern as a sub-string.

Ruby's syntax
/cat/ => matches string "cat"
/t a b/ => matches "hit a ball"
#matching
/cat/ =~ "cat and dog"

Changing Strings
"my name is saif".sub(/saif/, "Joseph")

gsub replaces all the matches
gsub! affects original string

Regex options
i => case insensitive
o => subsititue once
m => multiple line
x => allow space

Special characters
. + \ ^  * $  ? | ( ) { } [ ]

Anchors
^ : start of a line. /^abc/ => matches "abc def ghe"
$ : end of a line
\A : matches begining of a string
\z : matches end of a string
\Z: matches end of a string unless ends with \n
\b : word boundary
\B: non-word boundary

character class
/[aeiou]/ => matches a vowel character
/[0-9]/ => matches any digit between 0 through 9
/[^0-9]/ => matches anything other than a digit

Ruby option provide
/(?d)\w+/ => a is default character set support
/(?u)\w+/ => matches full unicode characters
/(?a)\w+/  => matches ascii characterset

Posix character class
[[:digit:]] => matches a digit
[[:^digit:]]] => anything except a digit
/\p{Alnum}/ => match a alpha numberic unicode character
period outside [] represents any character
/c.s/ => matches cos

Repetition
r* => zero or more occurrences of r
r+ => one or more
r? => zero or one
r{m,n} =>at least m, at most n
r{m,} => at least m
r{,n} => at most n
r{m} => exactly m

greedy repetition reg_exp+
lazy repettion reg_exp+?
possesive repettion reg_exp++


Alternation
'|' has very low precedence
/d|e/ => matches d or e

grouping
/red (ball|angry) sky/
$1 accesses the first group from outside of the regular expression, \1 from inside the regular expression.

named groups
/(?<first>w+)\k<first>/

lookahead (?=reg_ex)  negated version (?!re_ex)
str = "red, white, and blue"
str.scan(/[a-z]+(?=,)/) # => ["red", "white"]

look behind (?<=reg_exp) negated version (?<!re)

Controlling back tracking
inhibit backtracking: (?>reg_exp)
/((?>X+))(?!O)/ => matches XXXY but not XXO
possesive repetition can be used as well
/(X++)(?!O)/

Back reference to named groups
declaration: (?<name>reg_exp)
reference: \g<name>, \g can be used recursively
re =
/
  \A
    (?<brace_expr>
      {
         (
            [^{}]
           |
            \g<brace_expr>
         )*
      }
    )
/x

conditional group
declaration (?<name>reg_exp)
usage (?<name>...)

alternative in conditions
(?(group_id) true_pattern | false_pattern)

/(?:(red)|blue) ball and (?(1)blue|red) bucket/x  # blue ball and red bucket matches

named sub-routine
sentence = %r{
  (?<subject> cat | dog ) {0}
  (?<verb> eats | drinks ) {0}
 The \g<subject> \g<verb>
}

Saturday, April 7, 2018

[Book Take Away] Farmer Boy

This book talks about an American Farmer Almanzo Wilder's childhood. I am very fond of the American way of life. I love the way the American people value freedom and above everything else. This book talks about many of American values. From this book I have learnt a quite a few things
a. Some people would put being free above everything else. That's why some people want to be a farmer. They won't like to be depended on other people. Even if that would cause them more works to do, they would have to depend on their weather and land and they might have to wake up a night to see if their cattle is freezing or not. Some people would not put their decisions to other people.
b. The way farmers break their colt and their oxen can be applied to day to day life. A farmer would be very careful about a young horse. They make sure that they are not startled when they are young. If you trouble a horse when it is young, it will be habituated for disobedient and will be a spoiled horse.
c. It is not good to put a huge amount of load to a Ox in the beginning. Because initially if they fails, they will always tend to give up.
d. We need to let choose people what they want to be in life or what they want to be. This is exactly what Almanzo Wilder's parents did.
e. We need to be frugal and not to waste money on things that we don't want. We cannot be lazy and waste time on unnecessary stuffs.
f. Like a good farmer we need to be prepared for future. 

Tuesday, April 3, 2018

[Philosophy] Walking Alone

I love to walk alone. This gives me a chance to reflect on a problem or think about something, on the least it lets my brain sometime to process some information. It becomes tempting sometimes to walk with someone else. I have found this, walking with someone else almost always makes me unhappy. Most of the time it is because I say mostly unnecessary things. It makes me sad later, I keep thinking why I have said those unnecessary things in the first place.

Next time when I am tempted to walk with someone, I need to remember these

0. I will almost be unhappier after the walk.
1. I will most likely say something that I will feel sorry inside me.
2. I would not get a chance for reflection.

I should walk alone whenever possible. When I am talking, I am not walking.

Sunday, March 18, 2018

[Algorithms][DP] Thinking in DP 3

10. Maximum Sum Increasing Sub-sequence:
Problem: Given an array of numbers, a, find the sub sequence that holds the following properties

  1. It is in increasing order
  2. The sum is the maximum
Example: For {1, 101, 2, 3, 100, 4, 5}, the output would be 106 (1 + 2 + 3 + 100).
Recurrence: f(i) = max( f(j) + a[j] ), where, 0<= j < i and a[i] > a[j] 
Base case: f(0) = a[0]
Runtime: Number of sub-problems = O(n) 
Time to solve a sub-problem = O(n)
Total runtime = O(n ^ 2).

11. Largest Chain
Problem: Given n pairs find the maximum chain. 2 pairs (a, b) and (c,d) can form a chain if b < c.
Example: Given an array of pairs arr,  {(5, 24), (39, 60), (15, 28), (27, 40), (50, 90) }, then the longest chain that can be formed is of length 3, and the chain is {(5, 24), (27, 40), (50, 90)}.
Recurrence: f(i) = max( f(j) ) + 1, where 0 <= j < i; arr[j][1] < arr[i][0]
Base case: f(0) = 1
Runtime: Number of sub-problems = O(n)
Time to solve a sub-problem = O(n)
Total runtime = O(n ^ 2)

12. Longest Common Substring
Problem: Given 2 strings, find the longest substring.
Example: Given, ϵABCDE, ϵXBCDG, then longest common substring = BCD. All string starts with empty, ϵ.
Recurrence: 
                   {   if s1[i] == s2[j] then f(i-1, j-1) + 1
     f(i, j) =  {           
                   {   max( f(i-1, j), f(i, j-1) )
Base case: f(i, j) = 0
Runtime: Number of sub-problems = O(n ^ 2) as we have 2 indices i, j.
Time to solve a subproblem = O(1)
Total runtime = O(n ^ 2)

13. Catalan number
Problem: (n+1) th Catalan number, C_(n+1) = sum ( C_i * C_(n-i) )
Recurrence: See above
base case, C_0 = 1
Runtime: Number of sub-problems = O(n)
Time to solve a sub-problem = O(n)
Total runtime = O(n ^ 2)

14. Count Number of Ways to Reach a Given Score
Problem: The array pts gives the achievable point from any state of a game. Given a point n, find the number of ways those points can be reached.
Recurrence: f(i) = sum(f(i - pts[k])) for all 0 <= k < lenght (pts)
Runtime: Number of sub-problems = O(n)
Time to solve a problem = O(k)
Total Runtime = O(n * k)

Monday, March 5, 2018

[Story] Only the necessary things!

Oliver is a new driver. He has been trying to understand the basics of driving. Initially it seemed like a lot of rules, road signs and laws to deal with. When you are driving, you need to constantly look in front, look to the front at the left and right side of the road, using mirrors constantly check left and right of the car's back, using rear-view mirror check the back of the car. And every driving experience seemed to be a new experience. To him, all these aspects of driving seemed discrete and hard to relate.

Eventually he realized driving is mostly about doing the things that you absolutely need to do. For instance, driving faster than the speed limit is not necessary, if you want to change a lane and it is not safe to do so at the time then it is not necessary to change lane that moment of time, just take your time, keep going on, when it is safe, change lane. Also, it is not necessary to slam the break suddenly most of the time if you are paying attention.

Driving is about being conscious of the surrounding and do what is necessary. You need to know what is in front of you, what is far ahead, what is on your side and back.

You do not take action abruptly. You do not suddenly change lane or hit the break. If you want to change lane, you need to convey your intentions before hand by putting on turn signals so that other people on the road know what you are going to do. All other drivers will help you if you communicate properly and do not rush.

The intersections and lane changes are interesting parts. When you are on a intersection, this is the place where a road for two drivers overlaps. You need to be alert and let any car on the intersection go first. You need to clear the intersection as soon as you can safely. When you are changing lanes, you are attempting to get into other driver's drive way. Let them know your intention through signals, check blindspots to make absolutely sure that no car is in the place where you are trying to be. You need to speed up little bit while changing lane so that you do not interrupt the other driver's space.

At any given time, there are many people on the road with different state of mind. Some might be on rush, some might be new drivers like Oliver, some might be drunk or some might be having a medical condition. So it is very likely that something unexpected might happen. Some driver can cut in front him without proper signaling. Some pedestrian might be crossing the road dangerously, some driver can ignore the red signal or some driver can honk at him. It is good to accept the unexpected and act accordingly. Should something unexpected happens, he should not let go his cool, instead he should take it easy and accept these unexpectedness, take necessary steps and keep moving on without thinking about the past.


A few things driving teaches us

  1. Know the rules of the road. We need to know what means what and should be aware of known incidents.
  2. Safety first.
  3. Know where you want to go and what you want to do.
  4. Be mindful. Know what is in front, on sides and on back. 
  5. Do not do anything if you absolutely have to do. For instance, you missed an Exit? Do not try to adjust your route right away and back up from there to exit. Instead keep moving on, take the next exit.
  6. Do not take an action abruptly. Have a plan. Let others know what you are trying to do.
  7. When sharing space with others, be extra careful (like when you are on an intersection or changing lanes).  
  8. Expect the unexpected. Someone will always do something unexpected or stupid. Don't let stupid actions of others take your peace of mind. Take proper actions, keep moving on.
And surprisingly, the above are the basic teaching of Buddha!

Tuesday, February 20, 2018

[MATHEMATICS] Mendelbrot and Julia set

Background
When we define functions recursively, such as
f(t) = f(t-1) * f(t-1) + c
A few cases might arise, as we keep increasing number of iterations, t.
Converge: Eventually, f(t) might converge to a zero or non-zero number.
Diverge: f(t) might keep getting bigger and bigger.
Periodic: f(t) might oscillate among 2 or more values.
Chaos: f(t) might produce random values.

There are cases where a function behave might differently with the choice of base case and other constants in this case f(0) and c. For,
Example: f(t) = r * f(t - 1) * (1 - f(t - 1))
f(0) = 0.2, r = 1, f(t) converges to zero.
f(0) = 0.2, r = 2, f(t) converges to 0.52
f(0) = 0.2, r = 3, f(t) is a attenuating-oscillating function
f(0) = 0.2, r = 4 f(t) is a chaotic function

For a function, for a specific set of points in a closed boundary used as the choice for f(0) or c, the f(t) might converge or diverge fast or slowly.

Mendelbrot and Julia set
For Mendelbrot set, the function is defined as the following
f(t) = f(t-1) * f(t-1) + c
f(0) = 0 and c is chosen from numbers from complex number domain from the following rectangular boundary,
bottom-left = -2.25 -1.5i
top-right = 0.75 + 1.5i

Algorithm to generate the plot
We count number of iterations, t, for which magnitude(f(t)) reaches to 4. If f(t) converges, we say it took MAX_ITERATIONS to converge. We put computed iteration counts in a 2D array. Plotting the 2D array in 2D plane gives a visualization of the Mendelbrot set. Yellow regions depicts those points that converges so for them iterations count = MAX_ITERATIONS. Darker points say that they diverge very quickly.

f(0) = 0, c ranged from (-0.22 -0.7i to 0.75 -0.21i)


For Julia set, we fix c, and vary f(0) from a complex number boundary.

                              c = -0.35 + 0.65i and f(0) ranged from -2 to +2 in complex plane

c = -0.77 + 0.13i and f(0) ranged from -1 to +1 in complex plane

Reference:

Sunday, February 18, 2018

[Algorithms][DP] Dynamic Programming Explained - 1

Dynamic programming systematically checks all possibility of a given problem.

To solve using dynamic programming, we need to come up with a way to recursively solve a problem. The recursion should be of format of DAG, a bigger sub problem should be depended on a smaller subproblem. Dynamic problem will not work if a smaller sub-problem depends on a bigger sub-problem.

Dynamic programming problem is a favorite choice of interviewers, at it tests understanding of recursion of an interviewee.

Steps to apply dynamic programming for a given problem
0. Check if the problem can be solved using recursion. Think if you have n items, can you solve the problem if you already know solution for n-1 th item. Consider each sub problem an optimal solution. If you know an optimal solution to all reachable lower state, how can you reach higher state with that knowledge.
1. If 0 holds, write the problem in terms of smaller problem. Observe how many variables you need. The number of variables determines the dimension of the array you will need to store solution.
2. Guesses is the number of steps your algorithm needs to combine small solutions to big solution.
3. From variables, determine how many sub problems will be there. Remember, recursive function calling is cheap O(1) time if dynamic programming is used. Guesses * number of sub problems will give the order of the algorithm.

Example:
problem: find fibonacci number

Using recursion:
fibonacci(i) = fibonacci(i-1) + fibonacci(i-2)

number variables is 1 (only i). Which means Number of sub problems = n;
Guesses = O(1) [fibonacci(i-1) + fibonacci(i-2) can be evaluated in O(1) time. Recursion is cheap for dp]

O(algorithm) = O(subproblem_count * guesses_at_each_subproblem) = O(n)

Another Example:
Rod cutting problem. An i lengthed rod can be cut in 2 spots. We need to find the maximum profit we can make out of it.

profit(i) = max(profit(j) + profit(i-j)) for all 0 < j < i-1

here # of variables = 1 => # subproblems = n
#guesses = O(n) [need to generate all points from 1 to i-1 for length i]

O(n * n) = O(n ^ 2)

Yet Another Example:
Knapsack problem
profit(i, capacity) = max(
                                         profit(i-1, capacity), //don't take i th element
                                         profit(i-1, capacity-w[i]) + val[i] //take ith element
                             )
we see 2 variables here. #subproblems = item_count * bag_capacity
#guesses = O(1)

O(algorithm) = O(item_count * bag_capacity)

this is a pseudo polynomial runtime. if bag_capacity is increases, we will need bigger array to store the intermediate results.

[AlgorithmS][DP] Thinking in DP -1

5. Longest Increasing sub sequence:
Problem: Given a sequence, find the longest increasing sub sequence. LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60, 80}.
Recurrence: Given an Input array, I. Build an auxiliary array of same size as I, A such that.
A(i) = max(A(j)) + 1, if an entry is found in I, such that i > j and j >= 0 and I(i) > I(j)
else A(i) = 1
Base case: A(0) = 0
Runtime:
Number of sub-problems = O(n).
Time to solve a sub-problem = O(n), as to build A(i) we need to traverse A(0) through A(i-1).
Total runtime = O(n ^ 2).

6. Given available coin values, {a, b, c} what is the minimum number of coins required to give change for n Cents.
Recurrence: f(n) = min(f(n-a) + f(n-b) + f(n-c)) + 1
base case:
f(0) = 0
f(a) = 1
f(b) = 1
f(c) = 1
f(-coinval) = + infinity
Runtime: Number of sub-problems = O(n), time to solve a sub-problem = O(m), here is m is the size of coin types.
Total runtime = O(m * n)

7. Edit distance
Problem: Given two strings a and b, find minimum number of elementary character operations (insert, delete, replace) to convert a to b.
Example:
f(UTEP, KTEP) = 1 (replace U by K)
f(RATS, BAT) = 2 (replace R by B, delete S)
Recurrence:
f(i, j) = f(i - 1, j - 1) if a[i] == b[j] 
f(i, j) = min(f(i, j - 1), f(i - 1, j), f(i - 1, j - 1)) + 1 if a[i] != b[j]
base case:
f(0, 0) = 0
f(i, 0) = i
f(0, j) = j
Explanation: f(i, j) is the edit distance of string a[0...i] and b[0...j]. Let, a = FIAS, b = FITA.
Here, we want to compute f(3, 3). Here, a[3] != b[3] so we need to insert, delete or replace.
In string a, if we choose to,
insert   A then we need to convert          FIASA -> FITA   >> f(i, j - 1)
delete   S then we need to convert          FIA -> FITA        >> f(i - 1, j)
replace S by A then we need to convert FIAA -> FITA     >> f(i -1, j - 1)
Runtime: Number of subproblems = O(n ^ 2), we are constructing a 2D array.
Time to solve a sub problem = O(1)
Total order = O(n ^ 2)
Naive order: f(i, j) ~ 3f(i-1, j-1) = O(3 ^ n)
                                                                                                    
8. Cutting Rod
Problem: A rod with n length is given. Value of all rod length 1..n is given. Find the maximum profit can be obtained by cutting the rod in optimal way.
Recurrence:
f(n) = max( max(f(n-i) + f(i)) for n > i  > 0, val[n])
base case:
f(0) = 0
Explanation: n = 4. We need to know which one gives the most profit, the max of val[4], f(1) + f(3), f(2) + f(2).
Runtime:
Number of sub-problems = O(n).
Time to solve a sub-problem = O(n), as we need to traverse all the values f(0) to f(n-1).
Total runtime = O(n ^ 2)

9. Subset Sum
Problem: Given a set of numbers, S and a number n, find if any subset of S sums up to n.
Recurrence:
f(i, n) = f(i - 1, n) | f(i - 1, n - S[i])
base case:
f(0, n) = false where n > 0
f(i, 0) = true where i >= 0
Explanation: f(i, n) represents if a subset from S[0...i] sums to n.
f(i - 1, n) is if a subset of S[0...i-1] sums to n.
f(i - 1, n - S[i]) is if a subset of S[0...i-1] sums to n - S[i] if so then including S[i] would sum to n.
Runtime:
Number of sub-problems = O(|S| * n)
Time to solve one sub-problem = O(1)
Total runtime = O(|S| * n)
The order depends on the value n holds, this scenario is known as Pseudo-Polynomial.


Saturday, February 17, 2018

[Algorithms][DP] Thinking in DP - 0

We will discuss a few problems and how to solve them using binary programming in this post.

0. n th fibonacci number:
Recurrence relation:
f(n) = f(n-1) + f(n-2)

Base case:
f(0) = 0
f(1) = 1

Complexity:
Number of sub problems = n,
Time to solve one sub problem = 0(1)
Total order = O(n)

Naive complexity: O(2 ^ n), as each recursive call will do full computation instead of using previous computed value.

1. n choose k (binomial coefficient)
Recurrence relationship:
f(n, k) = f(n-1, k-1) + f(n-1, k)
Explanation: 
From ABCD how many combination you can form taking only 3 of them?
Total combinations: ABD, ACD, BCD, ABC.

Ignore D first, compute how many 2 element item can be formed from ABC
AB, AC, BC. We can just add D at last position and we will get
ABD, ACD, BCD, this gives f(n-1, k-1).
Now, lets see how many 3 length String we can form from ABC (still ignoring D). Just 1, ABC.
this gives, f(n-1, k) 

Base case:
f(n, 0) = 1
f(n, n) = 1

Complexity:
From the equations, we will need to fill up a 2D array. Intuitively, it tells the order would be O(n ^ 2).
Number of subproblems: O(n ^ 2) [for each value of i of n, we will have to iterate all the values from 0 to i]
Time to solve one sub-problem: O(1)
Runtime = O(n^2)
Naive Complexity: O(2 ^ n)

2. Longest Common Sub-sequence:
Problem: Find the longest common sub-sequence of two strings.
Recurrence:
f(i, j) = if (a[i] == b[j])
                f(i - 1, j - 1) + 1
             else
                max(f(i, j - 1), f(i - 1, j))

Explanation: a = ABABDCD, b = AXBYCZ are two strings. Note that, the longest common sub-sequence is ABC. f(i, j) means find the length of the longest common sub-sequence in a[0..i] and b[0..j].

Base case: f(n, 0) = f(0, n) = 0
Complexity: O(n ^ 2). Same reasoning as above.
Naive Complexity: O(2 ^ n) if all the f is computed separately.
Backtracking can be applied here as well.
Generate all possible subsets of characters in string a. (2 ^ n)
Generate all possible subsets of characters in string b. (2 ^ n)
Find the sub-string of maximum length of the 2 subsets.

3. Maximum sum contiguous sub array
Problem: Given a 1-D array, find the contiguous sub array with the maximum sum.
Recurrence: At first compute all the sum of starting from i ending at j.
f(i, j) = f(i, j - 1) + f(j, j)
find the cell with the maximum value in it.

Complexity: O(n ^ 2)

4. Maximum size square sub array with all 1s:
Problem: Given a 2D array A holding 0 or 1 in cells, find the maximum sub 2D array that is square and that has all element 1.
Recurrence: Construct an auxiliary 2D array S such that
S(i, j) = min(S(i - 1, j), S(i, j - 1), S(i - 1, j - 1)) + 1 if A(i, j) = 1
S(i, j) = 0 if A(i, j)  = 0
Base case, S(0, j) = A(0, j), S(i, 0) = A(i, 0)
S(i, j) essentially holds the size of the maximum square sub array all holding 1 whose bottom right corner is A(i, j).

After constructing, S, find the S(i, j) with maximum value.

Complexity: O(n ^ 2) as we are constructing a 2D array.

Wednesday, February 14, 2018

[Algorithms][DP] Dynamic Programming Explaiend

Dynamic Programming (DP) is a technique of solving a problem that depends on a smaller instance of a smaller problem

When DP can be applied:
0. If the best solution of the larger problem can be computed from the best solution of the smaller problem(s). This property is called optimal substructure property.  If you can formulate a recursive equation such as f(n) = f(n-1) + f(n-2), you can solve the bigger problem f(n) with the result from smaller problems, which means the problem shows optimal substructure property. To know if the optimal substructure property exists or not ask the following -
"Can I solve the problem recursively?"

1. DP can be applied on the problems that shows overlapping sub problems. For instance, fibonacci(n) = fibonacci(n-1) + fibonacci(n-2). Lets see the tree structure of this problem,
                                                  f(n)
                                                 /    \
                                           f(n-1)   f(n-2)
                                            /     \         /   \
                                     f(n-2)    f(n-3) .......................

From the tree above, we can see that f(n-2) appears twice. To find if there is overlapping sub-problem property or not ask the following question-
"Am I solving the same problem more than once?"


In short, to check if DP can be applied on a given problem or not, see at first if it can be solved recursively, then see in the recursion tree if any sub-problem is occurring more than once.

Steps on formulating a problem using DP
Lets consider the problem of finding the shortest path in a graph.
0. Find variables that express the problem. To find shortest path, we need a vertex to start from (u) and a vertex we want to reach (v). For this problem u and v are the minimum number of variables to express the problem at hand. DP(u, v) would be state of the problem we want to compute.
1. Find relationship of the main problem with sub-problem states.
DP(u, v) = min(DP(u, k) + DP(k, v)) for all k
3. Build table to memorize sub problem's solutions.

Determining Order of a DP problem
0. Find the total number of sub-problems (s). For the shortest path problem, u would take all possible vertices. So, s = |V|
1. Determine how much work is done to compute a problem (w). Order of a recursive call to a sub-problem would be constant, as for DP it will be only a table look up, so for the shortest path problem,  DP(u, k) + DP(k, v) takes constant time.  We need to iterate through all k reachable from u, so w = degree(u).
3. Runt time, O(DP(u, v)) = s * w = O(|V| + |E|)

Reference:
0. MIT OCW
1. GeeksforGeeks
2. Dr. Fuentes' lecture
3.

Monday, February 5, 2018

Github Troubleshooting

# git push fails with the following

Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Steps
0. copy your public key to github.com
cat ~/.ssh/id_rsa.pub  >> copy the content

1. go to github.com > settings > ssh and gpg keys > new ssh key > paste your public key there > save

Try git push again. 

My Favorite Movies

Preference
Movies are retreat for me from my life. Usually, I like to watch a movie based on true story. These movies help me to see other perspectives of life. Danish girl, Boys don't cry, Speak, The Wrestler, Cinderella Man are name of a few movies. I am a big fan of western civilization, my movie preference reflects this. I sometimes love to see movies that has a simple story line, sometimes I like to see movies with an interesting plot. I have noticed that at a given point of time my preference of watching a movie changes based on what I want at that time. For instance, I might end up watching an inspirational movie when I am feeling bit down.

12 Angry Men ++

3 Idiots ++


A Beautiful Mind ++


American Beauty +++
The story evolves around an American family with a sexually unsatisfied father, professionally unsuccessful mother and a teen daughter with the thought she needs a breast implant. The story includes the daughter's pretty friend on whom the father has a crush, a neighborhood with a house with gay partners, a retired army person with teen aged son on drugs, and a guy who is the business idol of the mother.
Reason of liking: The movie narrates stories of untold desires and thoughts of human mind. Those desires might sound improper, yet those are beautiful in the sense that they are unique and strong among us, we cannot deny their existence.

Andaj Apna Apna 
Hilarious journey of two good looking guy's to marry a rich man's daughter.

Back to the Future ++

Boyhood +++
A boy grows up with typical incidents in a typical family of developed country.
Reason of liking: The movie gave me an idea of how a family of privileged race works in a developed country. How dads are, how moms are, how kids are brought up.

Brave heart +++
A Scot man fights the mighty British empire to take avenge his wife's death.

Cars +++

Cast Away +
A FedEx plane crashes in midst of the sea, only one person survives and find himself in a lonely island.

Catch Me if You Can ++
A good looking young man gets himself into fake currency business.

Children of Heaven +++

Cinderella Man +++
A formerly famous wrestler struggles to survive with a family depending on him and with a injury on his wrist during the great depression period of USA prior to the Second World War.

Coco ++
A music loving little kid goes to land of the dead and find surprising history of his ancestors.

Dark Knight +++
Batman fights the most brilliant psycho opponent, Joker, in order to sustain people's belief in goodness.

Dead Poets Society +++

Definitely, May be ++
A single dad tells stories of the women he dated to his little daughter. The father changes names of the women and the daughter has to find out who is her mom and which lady the father still loves.

Flipped ++
In a neighborhood a little girl has a crush on little boy. Growing upto teen-age the boy keeps ignoring the girl. Things starts getting interested when at some point the girl starts ignoring the boy.

Fight Club +++++
A regular office worker meets a rebellious person with an interesting philosophy that changes his way of life.

Finding Neverland +++
The story behind how the author of  "Peter Pan" collected the ingredients of the story from his family and surroundings.

Forrest Gump ++
An autistic person narrates story of his simple life.

Freedom Writers +++ (True Story)
During Early 90s, there was an extreme racial tension in California. One race would attack, beat, murder people from other race. Schools are full of teens who hate people from other race and education is not their primary concern when they are always in fear of death. One of those schools comes a new young female teacher, Erin. She quickly finds out her students have a difficult past. She attempts to teach them in different way. She goes through a lot of opposition, troubles and hatred from students and from fellow teachers. She does not loose hope on her students.
Reason of liking: After I watched the movie, I instantly fell in love with Erin's spirit. I like that she said, when we are young that is the time for us to go for our dreams. She is a strong woman, she is not a feminist. She treated men and women the same. This is type of women I would definitely love to stand by and walk with on the way of life.

Gladiator ++
A roman general falls into victim of a conspiracy and eventually sold as a gladiator.

Good Will Hunting
A teen janitor of MIT turns out to be a mathematical genius. He had a difficult childhood, now he is confused and insecured, he does not know what to do with his life. A MIT professor wants him to contribute in the field of mathematics while a counselor from a Community College thinks the boy should decide what the boy wants to do by himself without any external rush or push.
Reason of liking: I kind of felt the movie tells the story what would have happened if Ramanujan, the great mathematician, was born in modern day USA.

Hirok Rajar Deshe +++
A group of two singers and a teacher tries to fight against tyranny.

In to the Wild ++++ (true story)
An american recent college graduate finds that this society is full of falseness, fake smiles and unnecessary works. He decides to leave home for good and live in a place where no people lives. He sets out his journey and meets many people on his way.
Reason of liking: This movie reflects my dream and agrees with my philosophy. I felt deeply connected with the boy.

Indiana Jones series +
A history professor becomes treasure-hunter due to circumstances.

Inside Out ++

Interstellar ++
Human beings tries to survive as the earth starts becoming inhabitable.

It's a wonderful life +++
A man wants to commit suicide. Eventually, his friends and good deeds helps him get out of the situation.

Kingdom of Heaven ++
A crusader fights back Saladin's seize to rescue people in Jerusalem.

Krishna Kanter Will +++
A young rich honest man's fate slowly gets altered by actions of people in surrounding and his impulsive acts.

Kungfu Panda ++
A big fat panda wants to be a master of kung fu. Eventually, he has to fight against the greatest masters.

Lawless ++

Les Miserable +++

Life is Beautiful +++
A jew father in a Italian concentration camp tries to cheer up his little boy with his imagination.

Little Manhattan ++
A 10 year old boy falls in love with a 11 year old girl and expresses his emotions and feelings in soliloquy.

Little Miss Sunshine +++
A family has an eventful journey to California that would change perception of the family members.

Maha Nagar +
Life of a middle class family during 1960 in Kalkata.

Malena +

Matrix +++
A man wakes and finds he has been inside a simulation all his life.

Match Point +++
A poor tennis trainer gets married to a rich man's daughter. Things starts changing when he gets attracted by a poor but extremely beautiful actress.

Meet the Robinsons +++
A geeky-orphan boy attempts to build a time machine to find his mother.

Mongol +++
Life of the legendary warrior, Genghis Khan.

Mr. India(1987) +

National Treasure 
A treasure hunter's journey to the treasure of the knight-templer through clues hidden by the founding fathers of America.

Nayak(1966) +++
A famous actor reveals his secret to good looking reporter during a train journey.

Nayak(2001) 
A courageous tv anchor gets chance to be the head of India for one day.

Nightcrawler ++
An ambitious man gets involved in collecting breaking news for tv channels.

Now You See Me ++
During a show in US, a group of magicians robs a bank in Paris.

Pirates of the Caribbean
Fantasy journey of pirates during British period.

Prisoners ++
A father tries to find his lost 6 year old daughter.

Rang De Basanti +++

Ratatouille ++

Real Steel 
A single dad agrees to take care of his son for money.

Remember the Titans +
An African-American football couch comes in city of USA where there is a racial tension.

Rudy ++
A short and weak guy wants to be an American football player.

Taare Zameen Par +++

The Danish Girl

The Devil's Advocate +++

The Godfather +++

The Patriot +++
An American father of a big family eventually gets involved with the liberation war against Britain.

The Reader +

The Sixth Sense +
A doctor tries to help a kid who can see ghosts.

The Wolf of Wall Street

Titanic +++

Seven Samurai ++

Shawshank Redemption +++
A young bright banker gets life sentence for the false charge of murdering his wife.

Shutter Island ++
A US detective comes to visit a dangerous asylum and finds there is a conspiracy going on.

Speak +
A teen-aged girl suddenly starts behaving abnormally after her summer camp.

Stand and Deliver +++

Terminal ++
A foreigner gets stucked in a US airport and has to stay there for legal causes.

Theory of Everything +++
Life of Stephen Hawking.

The Butterfly Effect +++
A young man tries to prevent unfortunate events of life of his loved ones by frequently going to past.

The Curious Case of Benjamin Button ++
Benjamin Button is born as an old, he gets younger as time passes by.

The Hunt ++
A kindergarten school teacher gets accused for sexual harassment on little kindergarten girl. His and his family's life becomes very difficult with the hatred of surrounding people.

The Man from the Earth +++
A history middle-aged professor claims he is thousands of years of age in his farewell party.

The Prestige +
Two gifted magicians become rivals willing to harm each other after unwanted events.

The Professional ++
A hitman's life changes once he saves life of a little girl.

The Pursuit of Happyness +++

The Secret Life of Walter Mitty

The Wrestler +++

To Kill a Mockingbird

Toy Story +++
Life of a group toys that belong to a young boy.

Up ++

Wall-e ++




Watch List:
Full Metal Jacket
Amelie
Singing in the Rain
Some like it hot
Bicycle theives
The boy in stripped pajama
Graveyard of the fire flies
3:10 to yuma

Sunday, February 4, 2018

[Compiler] Inside My Implementation of the Jack Compiler

A compiler would take a program written in a high level language and translate the instruction to the instruction for a Virtual Machine(VM).

#Modules
A compiler has the following modules
0. Tokenizer
1. Parser
2. Symbol table generator
3. VM code generator

# Implementation Detail
0. Tokenizer
A language defines its basic building blocks (tokens). These basic building blocks contains comment structure, keywords, symbols, identifier logic,  literals(integer, string etc). A parser would take a program and generate stream of tokens as defined by a given language.

The tokenizer gives the following apis
i. hasMoreTokens()
ii. advance()
iii. getCurrentToken()

Algorithm:
i. Load given program in to memory
ii. Remove all the comments
iii. Add a space where 2 tokens are joined (eg. convert 5; to 5 <Space> ;)
iv. Look for a character
             if (character != ")
                curIndex = i
                j = index of next space
                subString = extract(i, j)
                using regular expression, check if the subString is a proper token, if so store in a list raise                     an exception otherwise
            if (character == ")
                look for next " and extract the substring and store in the token list


1. Parser
Uses a tokenizer and checks if the token sequence is in harmony with the grammar of the language.

Implementation:
Lets consider rule for class
class   >>>
    'class' identifer '{'
              classVarDec*
              subroutineDec*
     '}'

A set of function related to each grammar construct and bunch of helper function helped me writing the parser module.
Example:
For the rule above, I wrote the following method in the parser

void CompileClass(){
  keyword(CLASS);
  identifier();
  symbol('{');
  classVarDec_zero_more();
  subroutineDec_zero_more();
  symbol('}');  
}
Here compileClass is the method related to the grammar rule and classVarDec_zero_more() is a helper function.
the method symbol(char) was implemented as follows

void symbol(s)
  curTok = tokenizer.getCurrentToken();
  if(curTok.type != SYMBOL)
    raise exception
   
  if(curTok.val != s)
    raise exception
 
  tokenizer.advance()
end

2. Symbol Table
A symbol table is used to translate a variable declared in a high level language to a (segment, offset) pair of a virtual machine. Symbol table is divided in two spaces, one for variables declared in class level another one for subroutine level

API
i. define(varName, kind(static, field etc), type(String, CustomClass etc))
  called when a variable declaratrion is encountered
ii. startMethodLevelSymbolTable()
  called when a method declaration is encountered
iii. getInfo(varName)
  used to resolve a variable name encountered

An instance of symbol table needs to be added on the parser. As the parser process any variable declaration, an entry needs to be created in the symbol table.

3. VM Code generator
A VM Code generator needs to be augmented within the parser. As the parser parses through a given source code, a VM Code Generator would gather context and when appropriate will generate proper VM Code. This module keeps an eye on the following cases
i. Function declartion handling
A VM only cares about subroutines. A compiler needs to translate and write all the subroutines in a output file. To resolve name collision, when a subroutine subRot is encountered in class MyClass, the VM code generator would give the subroutine the name "MyClass.subRot". Here is how it deals with different subroutine types.

#Static
Observes how many local variables declared in the static method (lets call it n) and then generate the following code
function  MyClass.subRot n

#Construtor
Observes how many local variables are declared(localCount) from parser and how many fields the MyClass has(fieldCount) from symbol table. Then generates the following code-

function MyClass.new localCount
  call Memory.Alloc(fieldCount)
  pop pointer 0 //pointer 0 is used for current object also known as this
 
#Method
A method implicitly expects the object to act on as its first argument. It observes how many local variables are declared(localCount) from parser then generates the following code-

function MyClass.subRot localCount+1
  push arg 0
  pop pointer 0 //sets this pointer
 
The above code essentially sets this pointer to the object on which the method is called.

# Variable declaration
Create an entry in appropraite space of the symbol table with proper context.

# Expressions
An expression is evaluated and is value is pushed to stack.
## for an int value, generate -> push value.
## True -> generate -> push -1 //notice -1 means 11111... in memory
## False, null -> push 0
## "ab" generate the following
  call Memory.alloc 3 //3 characters in the string
  call String.appendChar 97 //ascii value of 'a'
  call String.appendChar 98
## variable, a variable is resolved using the symbol table. For example, lets say a variable var was declared in a method and it was the 2nd variable. So this variable exists in local segemnt's 2nd index. it will be resolved as following
  push local 2
A variable declared in a class, or declared as staic or declared as an argument would resolved with a proper segment and a proper offset.
 
## binary operator, an expression with the form (exp1 op exp1) is translated in the following way
  evaluate exp1 //exp1's value would be on top of the stack
  evaluate exp2
  op //apply the operator on the top two values of the stack
 
## unary operator, op exp
  evalute exp
  op
 
## for a method call myMethod(1, 2) of class MyClass, the following code will be generated
  push pointer 0 //push this object's reference to stack
  push constant 1
  push constant 2
  call MyClass.myMethod 3 //3 is the number of arguments the caller has passed to the function
 
## To translate a call of myObj.myMethod(1,2) using the symbol table, Code generator module finds its type lets say MyClass. Then it generates the following-
  push myObj //pseudo code, myObj needs to be resolved using symbol table as described earlier.
  push 1
  push 2
  call MyClass.myMethod 3
 
## To translate a static method MyClass.myStatic(1,2) the Code generator does not have to push any objects reference as the first argument. Other than that, it produces VM code as following the logic earlier.

## Access array index, myObj[exp] is translated as follows
  evaluate exp
  push segment offset //myObj variable's segment offset
  add
  pop pointer 1 //set that pointer (pointer 1), with the address of myObj[exp]
  push that 0 // push the value of myObj[exp] to stack

# Statements
## return : Every subroutine is expected to produce a result and push it to the stack.
return; is translated as
  push constant 0
  return
 
return exp; is translated as -
  evaluate exp //the value of exp will be on top of the stack
  return
 
## method call. A method call statement, do myMethodCall(1,2); would be translated as follows
  generate code for myMethodCall(1,2) discussed in the Expression section
  pop temp 0 // discard the value generated by the function as it will not be used
 
## assignment
  ### let var = exp; using symbol table first finds segment, offset of the var. Then the following code gets generated
    evaluate exp
    pop segment offset
   
  ### let var[exp1] = exp2
    evaluate exp2
    evaluate exp1
    push segment offset
    add
    pop pointer 1
    pop that 0
   
## If else
  if(cond) { stmts1 } else { stmts2 } is translated as follows
 
  if-goto IF-TRUE
  goto IF-FALSE
  label IF-TRUE
 
  generate code for stmts1
 
  goto IF-END
  label IF-FALSE
 
  generate code for stmts2
 
  label IF-END

## while
  while(cond) { stmts } is translated as follows
 
  label WHILE-BEGIN
  evaluate cond
  not
  if-goto WHILE-END
 
  generate code for stmts
 
  goto WHILE-BEGIN
  label END

Conclusion:
To build a compiler from the scratch, start with the tokenizer module. Build parser module with the the help of tokenizer. Write symbol table module and integrate it to the Parser. Write VM Code generator module, then augment it to the Parser module; also add proper context capturing code in the Parser module.

Reference:
0. My compiler implementation
1. Elements of computing: Building a modern computer from the first principle
2. A modern compiler generation in Java
3. Stanford Compiler course by Dr. Alex Aiken
4. GATE lecture on Compilers by RavindraBabu

Monday, January 22, 2018

[Big Data] Hadoop Core

Hadoop in Layman's term
Lets say you have file that contains name of all the people who lives in your apartment complex. You want to see how many people has same name as yours. You write a program that reads the file and outputs how many people has same name as yours. Now, lets say you want to know how many people in your city has same name as yours. The data is too big to fit in a single computer. So you get some 20 computers and connect them which forms a cluster. You install Hadoop on the cluster. Now, you start writing name of the people of your city in a file in Hadoop File System (HDFS) which in turn starts breaking your data into small chunks and writes into your 20 computers. You keep appending the file until you have written all the names of your city. Now, you submit the program that you previously have written for a single computer to find the count of name match on Hadoop. Hadoop takes your program, and asks your 20 computers to run the program parallelly. Hadoop then asks your 20 computers to aggregate and provide you the result.

Some terms:
node: a small computer capable of storing data and do processing on the data
cluster: combination of lots of node

Hadoop provides 2 functionalities.
0. Distributed fault tolerant data storage (hdfs)
1. Batch processing on stored data (map-reduce)

# HDFS
hdfs is a Unix like distributed file system. It splits large files into small blocks and stores them in different nodes. hdfs stores each block by default 3 times in 3 separate nodes to provide safety of the data in case of a node failure.

## Services
0. many data nodes: these service is run on those nodes that stores data. send heart beat and block information to master node. clients connects to data nodes to read/write data.
1. master name node: stores meta data about which data block is stored in which data node. guides client to write/read data to/from appropriate data node
2. check point node: creates check point for the name node. this is not a hot back up for master name node.

## How hdfs works
Write
0. client connect to name node and asks which data nodes to write data to
1. name node gives data node address to client
2. client connects to data nodes and writes data to data nodes
3. data nodes takes action to replicate data to other data nodes guided by name node

Read
0. client connects to name node and asks which data nodes to read from
1. name node gives data node addresses
2. client connects to data nodes and read data
3. in case of a datanode failure, client reads the data block from another data node guided by name node


# MapReduce
Clients want to process data stored in hdfs. A client submits a "Job" to MapReduce that MapReduce runs across diffrent nodes in the cluster.

## Services
0. Job tracker: master service to monitor jobs. A job is ran as many tasks in several nodes distributedly. retries failed task attempts. Schedules incoming jobs from different clients.
1. Task tracker: runs on the same physical machine as the data node. several tasks executed in a distributed system accomplishes the Job that a client submits. A task has one or more attempts. Sends heartbeat and task status to job tracker. It runs on its own JVM on a datanode.

## How Mapreduce works
0. Clients submits job to job tracker
1. Job tracker assigns tasks to task trackers that are close to the data blocks.
2. Task trackers executes tasks. and writes the result to hdfs with replication
3. if a task tracker fails, job tracker assigns the task to another task tracker


# YARN
Abstract framework for distributed processing. MapReduce is a concrete YARN application. It divides duty of the Job Tracker into Application master, Resource manager. Task tracker acts as a node manager, which have "Containers" on which a map or reduce task can be executed. Number of containers on a node is configurable.


## Map Reduce
Data processing a is done in 2 phases.
0. Map phase: apply map function on input key value pairs to generate intermediate key value pairs. group intermediate key value pairs by intermediate keys. each group will contain one key and one or more values.
Components used during map phase:
a. InputFormat: Reads file line by line.
b. RecordReader: Reads input key, value pair from a line using InputFormat.
c. Mapper: Contains map function to apply on input key, value pairs and produces intermediate key, value pairs.
d. Combiner: Performs a local reduction on intermediate key, value pair.
e. Partitioner: Decides which intermediate key, value should go to which partition.

1. Reduce phase: apply reduce function on grouped intermediate key value pairs.
Components of reduce phase
a. Shuffle: Decides on which partition this reducer should operate on.
b. Sort: Sorts data on a single partition by key.
c. Reducer: given an intermediate key and a set of values, performs reduce operation and produces output key value pair.
d. RecordWriter: used to store one key, value pair.
f. OutputFormat: creates the record writer and writes content of the RecordWriter.

Component used by both phase:
WritableInterface: specifies how to read/write data to/from a file. Integer data is written as IntWritable, read as IntWritable.

Misc Notes
0. A map-reduce job can contain only one mapper job and only one reducer job. So a job such as word counter can be created. To create MR jobs pipeline, framework such as Crunch can be used.
1. You can append data on a hdfs file. There is no way to modify existing content of a file stored in HDFS.
1. Hadoop Streaming: Executing shell, python etc. script as jobs. Example:
hadoop jar hadoop-streaming.jar -input input -output outputdir
-mapper org.apache.hadoop.mapreduce.Mapper -reduce /bin/wc



Reference:
0. hadoop just the basics - slides
1. hadoop just the basics - youtube video






Thursday, January 18, 2018

[Book Take Away] The Zen Programmer

Buddha
Siddhartha Gautama, A prince from Nepal born 500 years before christ. At age of 26, he learns about death, distress and disease. He left his house to find the remedy of this basic problems. In his journey, he understood four noble truth that expresses reality of pain. He found eightfold path that would minimize pain of a human-being. He is known as the first "Buddha" which means awakened.

# Buddhism
Teachings of the first Buddha. In Buddhism there is no God.

## Four noble truth
0. There exists dissatisfaction.
1. Root cause of dissatisfaction is desire, hatred and wrong thoughts.
2. If the root causes are gone, pain will seize.
3. Eight-fold path helps eliminate root cause.

## Eight-fold path to nirvana
Eight-fold paths are not commandments. These can be considered more as "Best Practices".

0. Right view: Understand four noble truth. See things without prejudice. There is no correct or wrong view. Right view can be considered as absence of any view.
1. Right intention: Right intention means acting without any desire. Right intention is absence of any intention.
2. Right speech: Right speech is no speech or amount of speech that is absolutely necessary.
3. Right action: Right action is no action or action that have minimum possible impact.
4. Right livelihood: Right livelihood is no livelihood or a livelihood with minimum possible impact to surroundings.
5. Right effort: An effort where mind(thought) is constantly monitored.
6. Right mindfulness: Leading life with full attention on body and mind.
7. Right concentration: Keeping balance between chaos and tranquility of mind.

## Zen Buddhism
A sect of Buddhism. Not thinking about anything is Zen. Once this mind-clearing technique is mastered, everything such as walking, standing, sitting or eating becomes Zen practice.

Some Zen terms:
### Hell: Situation a person creates for oneself and surroundings through wrong thoughts and action.
### Ghost: The thoughts that keep desiring good looking sexual partner or comfortable belongings.
Zen does not give a person something. Zen does not make one happy. Zen does not tell a person do something good. Zen is about clearing unnecessary stuffs, keeping mind and dwelling empty. Zen acknowledge there is by default pain and dissatisfaction. Zen teaches to minimize pain.

Why Zen programming?
A programmers day is a combination of the following
0. overtime
1. ambitious requirements
2. wrong team
3. high expectation
4. not dealing with life
5. motivation by threat
6. changing requirement
7. greed
8. comparison with others
9. burn out
so on and so forth. Dealing with so many chaos is not easy. A programmer will need a way to deal with all these stresses. Zen can help her with these problems.

The nature of mind
# Chaos and rational thinking: Chaotic thoughts increases dissatisfaction. Rational thinking sees everything as the same and decreases desire. Chaos in mind needs to kept under control by minimizing chaos making actions and thoughts. Chaotic thinking is sometimes good for creativity yet it needs to be under check.

# Associative thinking: A process of mind's drifting with a hint. Example: you think about apple, next your mind thinks automatically about mac book and Steve jobs.

Zen Practices
Ki:  (Breath and vitality) Breathing mindfully.

Kizen: Keeping chaos and rational thinking in balance and being mindful about associative thinking.

Task breakdown: A larger task needs to be broken on smaller chunks.

Reflection: Every once on a while focus on what you are thinking and what you are doing.

Focus time: Set aside a time slot for uninterrupted work.

Email check: Set aside a less productive hours for non-pressing email.

Chair relaxation: Every once in a while, while sitting on the chair, focus on breathing.

Walking relaxation: Walking while being fully aware of the surrounding.

Sleep: If you are tired take a nap. Go to your car if necessary.

Work without holiday: If you work mindfully, following the above practice, everyday you'll feel you are in holiday.

Drink Tea: Be mindful about every step of making a cup of tea. Observe every sip. There should not be any other thoughts other than you and your cup of tea.

Clean: Keep your desk clean. There will be less things to get distracted with.

Defeat mind monkey: Do not roam around websites. Clear desk mindfully. Mindful work helps defeat mind monkey.

Take break: Take a real holiday. Stay away from computers. In work you focus more on mind. Focus more on body when in holiday.

Todo list: Make a weekly list of tasks. It is important how many tasks you accomplished rather than how much time you put (Saif disagrees with this).

Two minute rule: If you are in middle of something and another task comes from another source. If the task is non-pressing and can be done in 2 minutes, switch from original task, otherwise write the task down in your todo list and keep doing the original task.

Pomodoro principle: Break your task in 25 minutes slots(1 Pomodoro). Take 5 minutes break after each Pomodoro. After 5 consecutive Pomodoros, take 30 minutes break.

Chain: Take a calendar. Put a X mark on the calendar as you have done the work you want to do regularly. Try to make a chain of Xs. Try your best not to break the chain..

Personalized Kanban: Use your wall and sticky notes to make your own personalized Kanban. In one section, put works you want to do. In another section put the works that are in progress. Don't clutter in progress with too many tasks. (More than four are too many).

Don't become an extremist: Keep a healthy balance of work and rest.

Frequently made complains:
0. Others don't treat me well: There will always be someone who treats nice, there will be someone who does not treat others so nice. Accept it.

1. I deserve it: What we think we deserve (such as costly phones) endup in earth's cheapest dumping ground(poor countries of Africa). Beware of what you think you deserve.

2. I had bad childhood: Many people probably had worse childhood than you had, yet they were able to go through it and did what they wanted to do in life. So bad childhood should not be a complain once you are aware of it. Stop leaving in past, act properly now.

3. I know it better: We don't know what will bring good or bad for us. Most of the time everything ends up being the same anyway.

Things to remember:
0. It's your life: No matter what happens to you, it is still your life. Don't forget that every day is a good day.

1. No ego: Some attributes that we think represents us, such as good look, attractive figure, knowledge, money etc are actually pretty volatile. Attaching these things to self might cause more pain when these things go away.

2. Ego makes you do things: You keep doing those things that you think the world thinks of you.

3. Ego-less programming: You are not your work. Your work can be made better with the help of others feedback. Take reviews to your work constructively.

4. Shut up: Only speak up if you absolutely have to. Don't waste your collegue's time with unnecessary chit-chat.

Zen is hard work
Zen is done with body and mind. Do your daily chores with your body and mind.

Career: Sometimes your career path might take you to the path which might not be the best for you. Feel free to say no to such promotions.

Taking care of body is important: You will regret when you are old if you don't take care of your body today.

Learn: Everything changes. Don't stop the room for improvement and learning.

Beware of environment: Know what is in your surroundings and know how to connect the gaps through learning.

Theory needs practice: What you learn, you need to practice them.

Don't become job title addict.

Calm down: In order to see things clearly, you need to calm down.

Keep the beginner mindset: Always look at things through a beginner's eye. Don't have an experts mindset. Being an Expert means a lot of ego. Beware that you can be wrong have the beginner's mindset.

Work being aware: Know what is needed, what help is available, have some preplanning of work.

Karma:
  Good karma that does something good.
  Bad karma is something that does something bad.
  Karma always backfires, a good or bad karma might end up causing troubles and pains. So, strive on no karma.

Code karma: Good code karma is coding with praise in mind. Bad karma is coding without care. Strive to avoid both good and bad code karma. Code with being aware, do only the much that needs to be done.

Buddha Programmer
A person who maintains calm mood and clear sight is a Buddha programmer. She sees good things in her colleagues and speaks up about bad things. She does not look for followers or worshipers. She does not have desire for greatness. She practices for the sake of practice, works for the sake of work, nothing else.

On being a student
0. Listen, learn what your teacher wants to teach you.
1. Keep respect, do your research, come up with short concise and easy to understand question for your teacher.
2. Don't go after your teachers job.
3. If your teacher has some fault, talk with her first.
4. You must give loyalty, honesty and commitment as you are receiving valuable knowledge from your teacher.

On being a teacher
0. Give advice sparingly, only if asked for.
1. Remember people learn on their own, give them time to figure things out by themselves. Only help/answer if a question is asked.
2. If a student becomes less engaged or unwilling to learn from you, simply stop being her teacher, be a colleague.

Best student-teacher relationship is when a teacher becomes a student and student become a teacher.

Hungry ghost
The people who work for recognition, gets angry if something desired is not met.

# Ignorance
There will be hungry ghosts and it is necessary to ignore them.

# Confrontation
If there are only a few hungry ghosts in your team and you have at least the same authority as they have and there is no other option, confront. Know that things will worsen and chaos would increase.

# Manipulation
Identify hungry ghosts who are after you. Find what they want. Do your work and give them recognition.

Incompetence
It's hard to find a truly incompetent person. It's likely that the person is not in right position.

Zennify your project

# As a team leader: Take care of your team. Before someone gets to your teammate, they should get through you.

# Path of ruin: If leaders work with anger,they send anger to his associates. Which goes down the hierarchy. Eventually these falls to the family members at the bottom.

# It's never that bad: People work out of fear, forgetting being mindful of actual outcome of losing job. It's never that bad. A few months will be tough. This is a part of life, no one can expect sunshine and rainbow all the time. For sunshine, night is necessary; for rainbow rain necessary.

# Laugh when desperate: Stop taking yourself seriously. You are just a guy, working on some company. Take things easily. Mindfully try to understand the situation. Think of an action. Do as much as you can. Know failure occurs often, accept it and learn from it. Don't get desperate when failure occurs.

Ten rules of Zen programmer
0. Focus: Do one task with mindfulness at a time. When you are sleeping only sleep. When you are eating only eat. When you are thinking only think.
1. Keep mind clear: Need to clear mind of every temptation such as social network, emails, news and songs.
2. Keep beginner's mind: See things through a beginner's mind.
3. No ego: Remember you are not important. Do not get proud because you can do something well. Everyone is good at something. Do not attach an idea, a piece of code or appearance to "mine".
4. There is no career goal: Be aware of present moment. Mindfully learn, act, work, speak. Do not wait to go to a higher post. Do things with right intention and mindfulness now.
5. Shut up: Do not speak up if you do not have to. Do not waste others time.
6. Mindfulness, care and awareness: Listen to sign of your body. Take rest and breaks. Take care of your body. Remember, no work is beneath you. When some one gives you a task, do it with as much focus as possible. Block all thought of hatred towards the task.
7. There is no boss: If your authority is asking for tasks that is or might hurt your body(unhealthy overtimes), say no.
8. Do something else: Do a thing that is not related to computers.
9. There is nothing special: Remember there is nothing special, you are not special and you are not important. You are not special just because you can craft good code. No one cares who built the pyramid. Everything you posses today, you have to loose everything eventually. Everything will change, decay and go away. Remember this.

What now
Know that
  - Only you can help yourself.
  - Your feeling and thought shapes your reality.
  - You need time for silence and concentration.
  - Take ten minutes of silence and solitude everyday morning. Breathe the morning air.

Reference:
https://www.zenprogrammer.org/