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/