Saturday, July 5, 2014

When Grep FAILS, Find works

Couple of times over the linux and mac platform I found the grep failing miserably when trying to search for  a word in a present directory like

grep -ri "context" .  {search for all files having context word appear anywhere in the file. i for ignore case, r is recursively}

find came to the rescue. find is also recommended because of the speed and ability to deal with files having spaces in their names

Couple of commands the worked real well for me on Mac and Linux platforms :

find ~/workspace/directoryspace/fileswithsimplenames/ -type f -exec grep -ri "Context" {} +


In case you want find to deal with spaces and other metacharacters, use the print()

find ~/workspace/directoryspace/fileswithawefulnames/ -type f -print0 | xargs -0 grep -l "foo"





Friday, June 27, 2014

Code Slot machine in Java


Its been a busy week so far. I went out with a few few friends for some fun this weekend. Found a slot machine and thought of doing it in Java.
So here I present to you a simple Slot Machine in Java 8.
package Casino;

import java.lang.Override;
import java.lang.String;
import java.util.*;
import java.lang.Math;

public class SlotMachine {
    public static Scanner input;


    public static final String BAR = "BAR";
    public static final String CHERRIES = "CHERRIES";
    public static final String SPACE = "SPACE";
    public static final String SEVEN = "7";


    // main method
    public static void main(String[] args) {
        input = new Scanner(System.in);

        // getting user bet
        int bettingAmount;

        do {

            bettingAmount = getBet();

            // validating input bet
            if (bettingAmount < 0 || bettingAmount > 100)
                continue;
            if (bettingAmount == 0)
                break;


            // player pulls the slot machine
            TripleString tripleString = pull();


            // get multiplier from the slot pull
            int multiplier = getPayMultiplier(tripleString);


            // getting winnings (or nothing)
            int winnings = bettingAmount * multiplier;


            // showing winnings (or nothing)
            display(tripleString, winnings);
        } while (bettingAmount != 0);
        input.close();
    }

    // get bet method
    public static int getBet() {
        int inputBet;
        String instructions = "How much would you like to bet (1 - 100) or 0 to quit?";
        System.out.println(instructions);
        inputBet = input.nextInt();

        return inputBet;
    }


    public static String randString() {
        double randomValue;
        randomValue = Math.random() * 100;
        int randomIntValue;
        randomIntValue = (int) randomValue;


        // all even numbers between 1 and 100 will return bar (50%)
        if (randomIntValue % 2 == 0)
            return Bar;


        // all odd numbers between 1 and 50 will return cherries (25%)
        if (randomIntValue >= 1 && randomIntValue < 50)
            return Cherries;


        // all odd numbers between 51 and 75 will return space (12.5%)
        if (randomIntValue >= 51 && randomIntValue < 74)
            return Space;


        // all odd numbers between 76 and 100 will return 7 (12.5%)
        if (randomIntValue >= 75 && randomIntValue < 100)
            return Seven;
        return "";
    }


    // pull method
    public static TripleString pull() {

        // creating object from default constructor
        TripleString thePull = new TripleString();

        // using mutators to change string values
        thePull.setString1(randString());
        thePull.setString2(randString());
        thePull.setString3(randString());

        // returning triple string
        return thePull;
    }


    // returning amount won (0, 5, 15, 30, 50 or 100).
    public static int getPayMultiplier(TripleString thePull) {
        if (thePull.getString1() == Cherries)
            if (thePull.getString2() == Cherries)
                if (thePull.getString3() == Cherries)
                    return 30;
                else
                    return 15;
            else
                return 5;
        if (thePull.getString1() == Bar && thePull.getString2() == Bar
                && thePull.getString3() == Bar)
            return 50;
        if (thePull.getString1() == Seven && thePull.getString2() ==
                Seven && thePull.getString3() == Seven)
            return 100;

        return 0;
    }


    // displaying if user won or lost
    public static void display(TripleString thePull, int winnings) {
        System.out.println("Whirrrr.......and your pull is");
        System.out.println(thePull);
        if (winnings > 0)
            System.out.println("Congratulations, you win: " + winnings);
        else
            System.out.println("Sorry, you lose. Better luck next time.");
    }

}

class TripleString {

    public static final String BAR = "BAR";
    public static final String CHERRIES = "CHERRIES";
    public static final String SPACE = "SPACE";
    public static final String SEVEN = "7";

    // member data
    private String string1 = "", string2 = "", string3 = "";

    // static constant
    public static final int MAX_LEN = 20;

    // private helper method
    private boolean validString(String str) {
        if (str != null && str.length() <= MAX_LEN)
            return true;
        else
            return false;
    }

    // accessor method for string 1
    public String getString1() {
        return string1;
    }


    // accessor method for string 2
    public String getString2() {
        return string2;
    }


    // accessor method for string 3
    public String getString3() {
        return string3;
    }

    // mutator method for string 1
    public boolean setString1(String string1) {
        if (validString(string1)) {
            this.string1 = string1;
            return true;
        } else
            return false;
    }


    // mutator method for string 2
    public boolean setString2(String string2) {
        if (validString(string2)) {
            this.string2 = string2;
            return true;
        } else
            return false;
    }


    // mutator method for string 3
    public boolean setString3(String string3) {
        if (validString(string3)) {
            this.string3 = string3;
            return true;
        } else
            return false;
    }

    @Override
    public String toString() {
 
        return "  " + ((string1.contains(Space)) ? "(" + string1 + ")" : string1) + "  " + ((string2.contains(Space)) ? "(" + string2 + ")" : string2) + 
"  " + ((string3.contains(Space)) ? "(" + string3 + ")" : string3);
    }
}


Thursday, June 26, 2014

Java 8 : Frequently Asked Questions for Interviews - 7 Serial Killer !!!

Often Serialization and Deserialization is considered the most frequently asked questions in Java. In Java8, Serialization & Deserialization are treated no differently. The only difference you will notice is the gravity of complex questions asked in the interview Process. Specially if you are interviewing for a company that deals with massive amounts of data transfer over the wire AND OFCourse, uses java.
Have a look at the following Serialization/ Deserialization code that is supposed to be working but freaked out because of the set being invariant. In case you can not figure out what is the problem, stay tuned for the correct solution.

package com.java8.examples;

import java.io.*;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by sonis on 6/21/14.
 */
public class SerialKiller {
    public static void main(String[] args) throws Exception{
        SerialObjectsClassType obj1 = new SerialObjectsClassType(111);
        obj1.checkIfSerialSetInvariant();

        /**
         * lets make a serialized copy of the invariants
         */
        try {
            SerialObjectsClassType serialCopy_of_Obj1 = (SerialObjectsClassType) makeSerialCopy(obj1);
            serialCopy_of_Obj1.checkIfSerialSetInvariant();
        } catch (Exception e) {
            e.printStackTrace();
        }

        obj1.checkIfSerialSetInvariant();
    }

    // Making a generic function that copies its arguments via Serialization
    public static Object makeSerialCopy(Object obj) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        new ObjectOutputStream(byteArrayOutputStream).writeObject(obj);

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        return new ObjectInputStream(byteArrayInputStream).readObject();
    }
}

/*
A class for keeping sets of Seralized objects
 */
class SerialSet implements Serializable {
    final Set serialized_Object_Sets = new HashSet();
}

final class SerialObjectsClassType extends SerialSet {
    private int id;

    public SerialObjectsClassType(int id) {
        this.id = id;
        serialized_Object_Sets.add(this);
    }

    @Override
    public boolean equals(Object obj) {
        return (obj instanceof SerialObjectsClassType) && (id == ((SerialObjectsClassType) obj).id);
    }

    @Override
    public int hashCode() {
        return id;
    }

    public void checkIfSerialSetInvariant() throws Exception{

        if (!serialized_Object_Sets.contains(this))
            throw new AssertionError("Serial set is not invariant. Recheck Serialization. SERIAL KILLER !!!");
            
    }
}
The system fails with the following error:
java.lang.Exception: Serial set is not invariant. Recheck Serialization. SERIAL KILLER !!!
 at com.java8.examples.SerialObjectsClassType.checkIfSerialSetInvariant(SerialKiller.java:77)
 at com.java8.examples.SerialKiller.main(SerialKiller.java:25)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:483)
 at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)



Friday, June 20, 2014

Shortcuts for MVIM


Cursor movement

  • h - move left
  • j - move down
  • k - move up
  • l - move right
  • w - jump by start of words (punctuation considered words)
  • W - jump by words (spaces separate words)
  • e - jump to end of words (punctuation considered words)
  • E - jump to end of words (no punctuation)
  • b - jump backward by words (punctuation considered words)
  • B - jump backward by words (no punctuation)
  • 0 - (zero) start of line
  • ^ - first non-blank character of line
  • $ - end of line
  • G - Go To command (prefix with number - 5G goes to line 5)
Note: Prefix a cursor movement command with a number to repeat it. For example, 4j moves down 4 lines.

Insert Mode - Inserting/Appending text

  • i - start insert mode at cursor
  • I - insert at the beginning of the line
  • a - append after the cursor
  • A - append at the end of the line
  • o - open (append) blank line below current line (no need to press return)
  • O - open blank line above current line
  • ea - append at end of word
  • Esc - exit insert mode

Editing

  • r - replace a single character (does not use insert mode)
  • J - join line below to the current one
  • cc - change (replace) an entire line
  • cw - change (replace) to the end of word
  • c$ - change (replace) to the end of line
  • s - delete character at cursor and subsitute text
  • S - delete line at cursor and substitute text (same as cc)
  • xp - transpose two letters (delete and paste, technically)
  • u - undo
  • . - repeat last command

Marking text (visual mode)

  • v - start visual mode, mark lines, then do command (such as y-yank)
  • V - start Linewise visual mode
  • o - move to other end of marked area
  • Ctrl+v - start visual block mode
  • O - move to Other corner of block
  • aw - mark a word
  • ab - a () block (with braces)
  • aB - a {} block (with brackets)
  • ib - inner () block
  • iB - inner {} block
  • Esc - exit visual mode

Visual commands

  • > - shift right
  • < - shift left
  • y - yank (copy) marked text
  • d - delete marked text
  • ~ - switch case

Cut and Paste

  • yy - yank (copy) a line
  • 2yy - yank 2 lines
  • yw - yank word
  • y$ - yank to end of line
  • p - put (paste) the clipboard after cursor
  • P - put (paste) before cursor
  • dd - delete (cut) a line
  • dw - delete (cut) the current word
  • x - delete (cut) current character

Exiting

  • :w - write (save) the file, but don't exit
  • :wq - write (save) and quit
  • :q - quit (fails if anything has changed)
  • :q! - quit and throw away changes

Search/Replace

  • /pattern - search for pattern
  • ?pattern - search backward for pattern
  • n - repeat search in same direction
  • N - repeat search in opposite direction
  • :%s/old/new/g - replace all old with new throughout file
  • :%s/old/new/gc - replace all old with new throughout file with confirmations

Working with multiple files

  • :e filename - Edit a file in a new buffer
  • :bnext (or :bn) - go to next buffer
  • :bprev (of :bp) - go to previous buffer
  • :bd - delete a buffer (close a file)
  • :sp filename - Open a file in a new buffer and split window
  • ctrl+ws - Split windows
  • ctrl+ww - switch between windows
  • ctrl+wq - Quit a window
  • ctrl+wv - Split windows vertically

Monday, June 16, 2014

IPTABLE rules to ACCEPT all TRAFFIC

IPTABLE rules to ACCEPT all TRAFFIC

Run the following. It'll insert the rule at the top of your iptables and will allow all traffic unless subsequently handled by another rule.

iptables -I INPUT -j ACCEPT

You can also flush your entire iptables setup with the following:

iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT

If you flush it, you might want to run something like:

iptables -A INPUT -i lo -j ACCEPT -m comment --comment "Allow all loopback traffic"
iptables -A INPUT ! -i lo -d 127.0.0.0/8 -j REJECT -m comment --comment "Drop all traffic to 127 that doesn't use lo"
iptables -A OUTPUT -j ACCEPT -m comment --comment "Accept all outgoing"
iptables -A INPUT -j ACCEPT -m comment --comment "Accept all incoming"
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -m comment --comment "Allow all incoming on established connections"
iptables -A INPUT -j REJECT -m comment --comment "Reject all incoming"
iptables -A FORWARD -j REJECT -m comment --comment "Reject all forwarded"

If you want to be a bit safer with your traffic, don't use the accept all incoming rule, or remove it with "iptables -D INPUT -j ACCEPT -m comment --comment "Accept all incoming"", and add more specific rules like:

iptables -I INPUT -p tcp --dport 80 -j ACCEPT -m comment --comment "Allow HTTP"
iptables -I INPUT -p tcp --dport 443 -j ACCEPT -m comment --comment "Allow HTTPS"
iptables -I INPUT -p tcp -m state --state NEW --dport 22 -j ACCEPT -m comment --comment "Allow SSH"
iptables -I INPUT -p tcp --dport 8071:8079 -j ACCEPT -m comment --comment "Allow torrents"

NOTE: They need to be above the 2 reject rules at the bottom, so use I to insert them at the top. Or if you're anal like me, use "iptables -nL --line-numbers" to get the line numbers, then use "iptables -I INPUT ..." to insert a rule at a specific line number.

Finally, save your work with:


iptables-save > /etc/network/iptables.rules #Or wherever your iptables.rules file is

Saturday, June 14, 2014

Java 8 : Frequently Asked Questions for Interviews - 6

How can a Lambda Expression be converted to Functional Interface? Example.
When a Lambda expression is executed 
  • an object of some class that implements the functional interface is created behind the scenes.
  • when the abstract method on this object is invoked, the body of lambda expression is executed.
PTR: The management of these classes and objects are totally dependent on implementation but its still very efficient than using traditional inner classes.
  • This conversion to interfaces is what makes Lambda Expressions so compelling as the syntax is short and simple, easier to read.
Example:
Array.sort(cars, (Car firstCar, Car secondCar) ->
        firstCar.getColor().compareTo(secondCar.getColor() 
    );

Can you Assign a lambda expression to a variable ( ofcourse of type Object) ?
No, Since Object is not a Functional Interface. It does not have any abstract method.

Can we declare function types such as (String, String) -> int, as used in other programming languages that support function literals?
No, CONVERSION TO FUNCTIONAL INTERFACE is the ONLY THING that one can do with Lambda Expressions in Java.

  • There are no function types added to Java language in Java 8.
  • There are only Lambda expressions that can be converted to functional interfaces.
  • This is natural for Java programmers as they know that certain interfaces e.g.. Comparator has a specific purpose. Its not just a method with given params and return type. So when you want to use Lamdba Expressions , its important to keep the purpose in perspective and have a specific functional interface for it.
For example: java.util.function has various generic functional interfaces. One such interface is BiFunction(T, U, R), describes functions with parameter types T and U and a return type R. We can use it as
BiFunction comp = (int first, int second) -> Integer.compare(first.length(), second.length())
However, that does not help with sorting, as Arrays.sort does not want a BiFunction. It wants a Comparator.

Are there any annotations introduced to help identify Functional Interfaces?
Yes, the annotation @FunctionalInterfaces can be used to tag any functional interface. It has two advantages 

  • The compiler will check the annotated entity to see if it has a single abstract interface or not.
  • The Javadoc page will include an statement that the annotated entity is a functional interfaces
However, the use of @FunctionalInterface is totally optional. Any interface having a single abstract method can be used a functional interface.

Does Checked exceptions matter in lambda Expressions? If yes, when and when not?
Yes, Checked exceptions matter when a lambda is converted to an instance of a functional interface. In case the body of lambda expression throws a checked exception, that exception needs to be declared in the abstract method of functional interface.
For example, Callable interface has an abstract call method that throws "Exception". However, the Run method in Runnable interface throws no exception of any sort.
Declaration :

public interface Callable<V> has abstract method V call throws Exception
Callable sleepDuringCall = () -> { 
    System.out.println("Calling"); 
    Thread.sleep(10000);} 
Thread.sleep (declared as public static void sleep(long miliseconds) throws InterruptedException) can throw checked exception.

Whereas,
public interface Runnable has abstract method void run()
Runnable sleepWhileRunning = () -> { 
    System.out.println("Sleeping during run"); 
    Thread.sleep(10); }
// will error out as Thread.sleep throws a checked exception.
However, you can catch the checked exception inside of the lambda body to keep the assignment legal.
Runnable sleepWhileRunning = () -> { 
    System.out.println("Sleeping during run"); 
    try{ 
        Thread.sleep(10); 
    }catch( InterrrupedException e){
        e.printStackTrace();
    }
}

Java 8 : Frequently Asked Questions for Interviews - 5


What are Functional Interfaces

A functional interface is an interface with a single abstract method. That abstract method is used as the type of a lambda expression.
public interface ActionListner extends EventListener {
      public void actionPerformed( ActionEvent event);
}
In the above example ActionListener has only one method actionPerformed and we use it to represent the action that takes one argument and returns no result. => It is a functional Interfaces.
  • It doesn't matter what the single method ( e.g. actionPerformed ) is called. 
  • The method will match up to lambda expression as long as it has compatible method signature
  • One can see the type of the parameter in the functional interface => improves readability and understanding in code.
  • Functional interfaces can use generics also.
  • Some important functional interfaces in Java :
Interface NameArgumentsReturnsExample
Predicate<T>sasdadasTdfasdfasdfafsadfsbooleanasfsdfsdadfsdHas this book been published yet?aasdfsdfasdfasdfasdfasdfasdfasfsdfsfsdfsdadfsd
Consumer<T>TvoidPrinting out a value. Getting an action/task done.
Function<T,R>TRGet a property/instance var from an object. Eg: get the author from book object
Supplier<T>NoneTAny Factory Method. Get Constant Values defined in certain context.
UnaryOperator<T>TTLogical not (!)
BinaryOperator<T> (T,T)(T,T)TMultiplying two numbers (*)

  • There are many interfaces in Java that encapsulates blocks of code such as "Runnable" or "Comparator"
  • Lambdas are backwards compatible with these interfaces.

When to supply Lambda Expression?

  • When an object of an interfaces with a single method is expected. Eg. ActionListerner is the functional interfaces in  the following example: The Left Hand Side Code changes to written in Lambda expression in the right hand side.
  • button.addActionListener( new ActionListener() {

        public void actionPerformed(ActionEvent event){
            System.out.println("Click on Button");
            }
    })
    button.addActionListerner( event ->
                 System.out.println("Click on Button"); )
  • The boiler plate code is minimized, readability enhanced and meaningfulness accomplished.

Why a functional interface must have a single abstract method. Aren’t all methods in an interface abstract?

  • In Java 8, interfaces can declare nonabstract methods.
  • Some interfaces in the Java API redeclare Objectmethods (such as toString or clone) to attach javadoc comments. But these declarations do not make the methods abstract.
    • Check out the Comparator API for an example.

Java 8 : Frequently Asked Questions for Interviews - 4



  1. What  is the Syntax of Lamdba Expression ? Give examples of each.
  2. Can we use annotations and final modifiers for parameters in Lambda expressions?
  3. Since Java is statically typed language, it is necessary to specify the type for parameters in lambda expressions?
  4. In what cases and when can we avoid specifying type for parameters in Lambdas?
  5. How do you specify type of returned variables in Lambdas?


Syntax of Lambda expressions in Java8 is very similar to writing methods without any return types :

  • parameter -> expression
  • (parameters) -> {expressions}
  • () -> expression
  • () -> {expressions}
  • (type parameter, type parameter ....) -> expression
  • (type parameter, type parameter ....) -> { expressions }
  • Never specify the result type of a lambda expression. It is always inferred from the context.
SyntaxMeaningExample
parameter -> expression sasdasdadsadadadadadasSimplest Lambda expression, the code fits into one expression.
A single parameter with inferred type of passed to the lambda expression. The type of parameter is implied in the context.
asdasfasdfassdsdfsfsdfsdfsdfsddfsdfasdfasdfafsadfsd
ActionListener acl = event ->
       System.out.println("Single expression Lamdba");asdasfasdfassdsdfsfsdfsdfsdfsdadfsd
(parameters) -> {expressions}Multiple parameters with multiple expressions are often coded inside "( )" and " { } " respectively.The type of parameters is implied in the context.BinaryOperator<Long> add = (x , y) ->
        { z = x + y;
              return z; }
Comparator<String> comp = (first, second) ->
         Integer.compare( first.length(),
                                      second.length() )
() -> expressionLambda that requires no parameters , one still provides an empty parenthesisRunnable myRun = () ->
          System.out.println("Running a
                runnable's RUN !!")
() -> {expressions}Lambda has no parameters but performs a bunch of tasks/multiple expressions() -> { for ( int i = 0; i <10 ; i++ ) {
          new Thread(myRun).start();
}}
(type parameter, type parameter ....) -> expressionWhen the type of parameters are not implied in the context, we need to supply the type with the parameter. 
(type parameter, type parameter ....) -> 
{ expressions }
Same meaning as above, but with more number of expressions.
No return type for lambdaThe result type of lambda expression is always inferred from the context (first, second) ->
            Integer.compare(first.length(),
                      second.length())
The above example is used in context where the result type is int.
(annotations type parameter) -> expressionJust like method parameters, you can add annotations to lambda parameters(@NonNull String name) -> ....
(final type parameter) -> expressionSimilarly, one can add final modifier to typed parameter in Lambda expressions(final String name) -> ....



Friday, June 13, 2014

Java 8 : Frequently Asked Questions for Interview - 3

What is Lambda Expression?
Lamdba expressions are just a block of code that can be passed around, which can be executed later, once or multiple times. A detailed answer here

Follow-up Question - Where have you seen similar code blocks in Java all along, before Java 8?

There are several examples where you write code in Java at some point, and it is executed at a later time. However, since Java is Object Oriented language, its not easy to pass or give somebody a block of code without having to construct an object belonging to a class that has the method with the desired behavior ( the method is the only behavior we want to execute ).
  1. run Method of a Runnable : while working with separate threads, we put the work in run method of a Runnable. Which we either execute by constructing an instance of the class that implements Runnable or simply submit the instance to a thread pool to start it in queue.
  2. class Task implements Runnable {
        public void run() {
            for(int i = 0; i < 10 ; i++) doTask(); 
        }
    }
    
    Task task = new Task();
    new Thread(w).start();
    
  3. sorting with custom comparator :while primitive sorts can work without any custom comparator code, sometimes the need arises to sort values based on different criteria. For instance  sorting an array of car objects, based on first their color, or their ratings or based on their prices. One can construct separate comparators and pass it to Array.sort method to defer the sorting at runtime. Note: the current code works with Java7 which has static method Integer.compare implemented in core java library.
  4. class ColorComparator implements Comparator<Car> {
        public int compare(Car firstCar, Car secondCar) {
            return firstCar.getColor().compareTo(secondCar.getColor()); 
        }
    }
    class RatingComparator implements Comparator<Car> {
        public int compare(Car firstCar, Car secondCar) {
            return Float.compare(firstCar.getRatings(),secondCar.getRatings());
        }
    }
    
    class PriceComparator implements Comparator<Car> {
        public int compare(Car firstCar, Car secondCar) {
            return Integer.compare(firstCar.getPrice(),secondCar.getPrice());
        }
    }
    
    
    Car cars = new Car[] { new Car("blue", 5.2f, 12000), new Car("green", 5.1f, 200000), new Car("grey", 6.2f, 1000), new Car("blue", 5.25f, 12090)}
    Arrays.sort(cars, newColorComparator());
    Color Cars
    Car [ blue, 5.2 12000 ]
    Car [ blue, 5.25 12090 ]
    Car [ green, 5.1 200000 ]
    Car [ grey, 6.2 1000 ]
    
    Arrays.sort(cars, new RatingComparator());
    Ratings Cars
    Car [ green, 5.1 200000 ]
    Car [ blue, 5.2 12000 ]
    Car [ blue, 5.25 12090 ]
    Car [ grey, 6.2 1000 ]
    
    Arrays.sort(cars, new PriceComparator());
    Price Cars
    Car [ grey, 6.2 1000 ]
    Car [ blue, 5.2 12000 ]
    Car [ blue, 5.25 12090 ]
    Car [ green, 5.1 200000 ]
    
    
  5. button callback : Button callback is another example of deferred execution. A callback action added to a class implementing the listener interface is a good example of that sort. For button, we can construct an instance of the class implementing the listener interface and then register it to the button class. In fact, the strategy is used often for creating GUI component callback actions the most listeners use "anonymous instance of the anonymous class".
  6. button.setOnAction(new EventHandler<actionEvent>() {
        public void handle(ActionEvent event) {
            System.out.Println("Event registered with User's click!!!")
        }
    }
    
    
    The callback is executed only on the click of the button, which eventually calls the code inside the handle method.
NOTE : It is possible to work with blocks of code in directly in other languages, However, in those languages it is vary easy to spawn a thread or to register a button click handler. In java, one could accomplish similar goals by writing similar API, but such API would be very unpleasant to use.

Wednesday, June 11, 2014

Java 8 : Frequently Asked Questions for Interview - 2

What is Lamdba Expression

Lambda Expressions are at the heart of Java SE 8. A “Lambda Expression” is a block of code that you can pass around so it can be executed later, once or multiple times.

Lambda Expressions are Closures or anonymous methods that provide developers with a simple and compact means for representing behavior as data.
  • The use or lambda expression improves readability, performance and reusability
  • The use of lambda expressions is all about abstracting complexity away into libraries
  • The use of lambda expressions improves developer productivity  
For example:  If one wants to model a workflow such as ` do A before you start, do B for each file in the file group, do C upon error and do D after you finish`, than one needs to break the phases of the workflow & the client code has to be directly involved in each phase.
=> Java (before java8) lacks in tools which can express the behavior from A to D. It also affects the APIs design.

Things to Remember in Lambda Expressions :

  • A lambda expression is a block of code with parameters.
BinaryOperator add = (long x, long y) -> {
    x+y
}
  • Use a lambda expression whenever you want a block of code executed at a later point in time.
Runnable myRunnable = () -> { 
    System.out.Println("Executing the Run method inside the Runnable!!!");
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    System.out.println("Running at a deferred time > "+df.format(date));
}
  • Lambda expressions can be converted to functional interfaces.
  • Lambda expressions can access effectively final or final variables from the enclosing scope.
public void enclosingMethod() {

    final String IamFinalVariable = "This is an immutable final variable";
    Button button = new Button("click me");
    button.addActionListener( event -> System.out.println(IamFinalVariable);

    String IamEffectivelyFinalVariable = "This is effectively final variable. Its value should not change in this scope.";
    IamEffectivelyFinalVariable = "Do not try to change me. Otherwise compiler will error out";

    JRadioButton finalRadioButton = new JRadioButton("Final Var Selected");
    finalRadioButton.setActionCommand(IamFinalVariable);
    JRadioButton effectiveFinalRadioButton = new JRadioButton("Effective Final Var Selected");
    effectiveFinalRadioButton.setActionCommand(IamEffectivelyFinalVariable);

    ButtonGroup group = new ButtonGroup();
    group.add(finalRadioButton);
    group.add(effectiveFinalRadioButton);

    ActionListener selectOrDeselect = event -> {
        System.out.println("You are talking to >"+ event.getActionCommand(    ));
   }
}
  • Method and constructor references refer to methods or constructors without invoking them.
  • You can now add default and static methods to interfaces that provide concrete implementations.
  • You must resolve any conflicts between default methods from multiple interfaces






Tuesday, June 10, 2014

Java 8 : Frequently Asked Questions for Interview - 1

What was lacking in Java before JAVA 8? Why are Lambda expressions introduced?

Now-a-days there is rising demand and requirement for 
1. Highly COMPLICATED applications
2. Programs that are executed on machines with MULTI-CORE CPU

Java (before Java8) has various cavets that makes it hard to write programs that could satisfy modern computing requirements because :

1. Programs using locks are error-prone and time-consuming
2. There is limits on level-of-abstraction that library writers can use
  • eg. lack of efficient parallel operations over large collections of data
3. There is lack of tools for expressing behavior easily without having to be involved in client code
4. Anonymous inner classes are hard-to-read & too verbose.
  • Callbacks and event handlers makes the process of reading code difficult.

What is Functional Programming?

  • Abstracting over behavior.
  • It is different from Object Oriented Programming in the sense that OOPs is mostly abstraction over data. 
  • Long before OOPs was introduced, there were several functional programming languages such as Lisp and Scheme. However, their benefits were not much appreciated outside academic circles. 
  • Functional programming is important because it is well suited for concurrent and event-driven (or “reactive”) programming

Whats new/Different for a Java programmer in Java 8 ?

  1. Learn to write and read lambda-enabled code
  2. Learn new syntax and a new idioms ( better than writing hugely complex thread-safe code )
  3. Write performance critical code
  4. Write easier-to-read code (code expressing business logic clearly rather than how its achieving it)
  5. Be able to blend both OOPS and functional programming together
  6. Even if you are not interested in concurrency, Java 8 provides a powerful upgrade. For example: Collection libraries can be given powerful APIs if the language has a convenient syntax for function expressions.
  7. ENJOY!
    • Code is easier to maintain, more reliable and less error-prone

Friday, June 6, 2014

Setting up SSH public/private keys


Setting up SSH public/private keys

SSH (Secure Shell) can be set up with public/private key pairs so that you don't have to type the password each time. Because SSH is the transport for other services such as SCP (secure copy), SFTP (secure file transfer), and other services (CVS, etc), this can be very convenient and save you a lot of typing.

SSH Version 2

On the local machine, type the BOLD part. The non-bold part is what you might see as output or prompt.
  • Step 1:
    % ssh-keygen -t dsa
    Generating public/private dsa key pair.
    Enter file in which to save the key (~/.ssh/id_dsa):
    (just type return)
    Enter passphrase (empty for no passphrase):
    (just type return)
    Enter same passphrase again:
    (just type return)
    Your identification has been saved in ~/.ssh/id_dsa
    Your public key has been saved in ~/.ssh/id_dsa.pub
    The key fingerprint is:
    Some really long string
    %
  • Step 2:
    Then, paste the content of the local ~/.ssh/id_dsa.pub file into the file ~/.ssh/authorized_keys on the remote host.
  • RSA instead of DSA
    • If you want something strong, you could try
      % ssh-keygen -t rsa -b 4096
    • Instead of the names id_dsa and id_dsa.pub, it will be id_rsa and id_rsa.pub , etc.
    • The rest of the steps are identical.
That's it!
FAQ:
  • Q: I follow the exact steps, but ssh still ask me for my password!
  • A: Check your remote .ssh directory. It should have only your own read/write/access permission (octal 700)
    % chmod 700 ~/.ssh

SSH Version 1

  • Step 1:
    % cd ~/.ssh
    % ssh-keygen -t rsa1
    Generating public/private rsa1 key pair.
    Enter file in which to save the key (~/.ssh/identity):
    (just type return)
    Enter passphrase (empty for no passphrase):
    (just type return) Enter same passphrase again: (just type return)
    Your identification has been saved in ~/.ssh/identity
    Your public key has been saved in ~/.ssh/identity.pub
    The key fingerprint is:
    Some really long string
    %
  • Step 2:
    Then, paste content of the local ~/.ssh/identity.pub file into the file ~/.ssh/authorized_keys on the remote host.             

Tuesday, June 3, 2014

Configure Git to only ask password WHILE pushing to remote repository

Configure Git to only ask password WHILE pushing to remote repository


You could tell git to store your credentials using the following command:


git config --global credential.helper store

git config --global credential.helper cache

Using this method, you only need to enter your username and password once and git will never ask for it again.

You can also go for caching instead which will store your password after having typed it once in a session for some period of time.
You can set the timeout yourself if your not happy with the default:


git config --global credential.helper 'cache --timeout=600'

Once again this is not always ideal.

What you should really be using is the ssh protocol to push and pull your data. This should work with proxies without any issues so you should definitely give it a go.

You can set it up by setting your remote url as follows:


git remote set-url origin git@github.com:<username>/<project>.git

git remote add origin https://{your_username}:{your_password}@github.com/{your_username}/repo.git

ex:- git push origin master


If you are using another hosting service like bitbucket, just replace "github.com" with your providers domain.
Once you do that, you will need to set up a public and private key pair for communication between github and your computer. 

There is a very good tutorial on how to set it up here. If you are using Linux or MacOSX you simply need to follow the steps when running the command ssh-keygen.
After that, you can get an ssh agent to store your password for you which is typically more secure. Ssh agents usually ask you to input your password just once after turning on your computer - but after that it should do everything automatically for you.
The ssh agent you use will depend on your operating system but it shouldn't be hard to set up.

Git submodules Cavets add, update, init & remove


Need for submodule

  • It often happens that while working on one project, you need to use another project from within it. 
    • A library that a third party developed or 
    • A library you’re developing separately and using in multiple parent projects
  • One needs to treat the two projects as separate yet still be able to use one from within the other.

What Git has to offer

  • Submodules allow you to keep a Git repository as a subdirectory of another Git repository. 
  • This lets you clone another repository into your project and keep your commits separate.
  • Submodules maintain their own identity; 
  • The submodule support just stores the submodule repository location and commit ID, so other developers who clone the superproject can easily clone all the submodules at the same revision.

Creating a github submodule

1. The steps are the same as creating a repository: cd into project1 repository ( lets assume its under test organization.

$ git init
$ echo "Initial commit" > Readme.txt
$ git add Readme.txt

$ git commit -m "Initial commit, public module $mod"
$ git clone --bare . ~/subtut/public/$mod.git
    
In case you have already committed to a remote repository use 
  • $ git remote set-url https://github.com/test/project1.git
  • $ git push origin master
OR
Add a new remote repository with github location
$ git remote add origin https://github.com/test/project1.git

$ git config branch.master.remote origin
$ git config branch.master.merge refs/heads/master
$ git push -u origin master


2. If in case the submodules were part of a parent repository as subfolders, you need to git rm those folders in order to add the submodules as git's submodules

$ git rm sudmodule or git rm subfolder


3. Now add the git submodule into parent as

$ git clone https://github.com/test/parent.git
$ cd parent
$ git pull origin master
$ ls
$ mkdir library/project1 && cd library/project1
$ git submodule add https://github.com/test/project1.git

The "git submodule add" command does a couple of things:
  • It clones the submodule under the current directory and by default checks out the master branch.
  • It adds the submodule's clone path to the ".gitmodules" file and adds this file to the index, ready to be committed.
  • It adds the submodule's current commit ID to the index, ready to be committed.
4. Checkout .gitmodules file to check if the repository is added to the index and if the current commit ID of the submodule is added to the index.

$ cat .gitmodules 
[submodule "game/guess_number"]
 path = library/project1
 url = https://github.com/test/project1.git

$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
# new file:   .gitmodules
# new file:   library/project1

5. Commit the parent project and publish it:


$ cd ~/parent
$ git commit -m "Add submodules project1"
Created commit fc7c350: Add submodules a, b, c, d.
 5 files changed, 16 insertions(+), 0 deletions(-)
 create mode 100644 .gitmodules
 create mode 160000 a
 create mode 160000 b
 create mode 160000 c
 create mode 160000 d
$ git push
$ git submodule init


Things To Remember

1. In case you are pulling parent into current repository, you will need to perform 2 simple steps to get the submodules updates and filled

First run "git submodule init" to add the submodule repository URLs to .git/config:
$ git submodule init
$ git config -l
...
submodule.a.url=/home/moses/subtut/public/a.git
Now use "git submodule update" to clone the repositories and check out the commits specified in the superproject.
$ git submodule update


2. One major difference between "submodule update" and "submodule add" is that "update" checks out a specific commit, rather than the tip of a branch. It's like checking out a tag: the head is detached, so you're not working on a branch.
$ git branch
* (no branch)
  master

3. If you want to make a change within a submodule, you should first check out a branch, make your changes, publish the change within the submodule, and then update the Parent project to reference the new commit:
$ git branch
* (no branch)
  master
$ git checkout master
$ echo "adding a line again" >> README.txt
$ git commit -a -m "Updated the submodule from within the ParentProject."
$ git push
$ cd ..
$ git add README.txt        # There is a gotcha here.  Read about it below.
$ git commit -m "Updated submodule project1."
$ git show
...
diff --git a/README.txt b/README.txt
index d266b98..261dfac 160000
--- a/README
+++ b/README
@@ -1 +1 @@
-Subproject commit d266b9873ad50488163457f025db7cdd9683d88b
+Subproject commit 261dfac35cb99d380eb966e102c1197139f7fa24
$ git submodule summary HEAD^
* a d266b98...261dfac (1):
  > Updated the submodule from within the ParentProject.

$ git push

4. To remove a submodule you need to:
  1. Delete the relevant line from the .gitmodules file.
  2. Delete the relevant section from .git/config.
  3. Run git rm --cached path_to_submodule (no trailing slash).
  4. Commit the superproject.
  5. Delete the now untracked submodule files.


references : http://git-scm.com/book/en/Git-Tools-Submodules

Monday, June 2, 2014

Install an APK file in the Android emulator



Windows:
  1. Execute the emulator (SDK Manager.exe->Tools->Manage AVDs...->New then Start)
  2. Start the console (Windows XP), Run -> type cmd, and move to the platform-tools folder of SDK directory.
  3. Paste the APK file in the 'android-sdk\tools' or 'platform-tools' folder.
  4. Then type the following command.
    adb install [.apk path]
    Example:
    adb install C:\Users\Name\MyProject\build\Jorgesys.apk
Linux:
In Linux the adb file is found in platform-tools directory under the SDK root directory

MAC:
PATH=$PATH:"adb location"  
Example : PATH=$PATH:/users/jorgesys/eclipse/android-sdk-mac_64/tools
Then run adb.
go to sdk folder, then go to tools.

copy your apk file inside the tool directory
./emulator -avd myEmulator

to run the emulator on your machine 

>>>> adb install fileName.apk (Windows)

OR
>>>>./adb install fileName.apk (Linux or Mac)