Monday, July 24, 2017

Interpreter Vs Compiler

Interpreter Vs Compiler : Difference Between Interpreter and Compiler

We generally write a computer program using a high-level language. A high-level language is one which is understandable by us humans. It contains words and phrases from the English (or other) language. But a computer does not understand high-level language. It only understands program written in 0's and 1's in binary, called the machine code. A program written in high-level language is called a source code. We need to convert the source code into machine code and this is accomplished by compilers and interpreters. Hence, a compiler or an interpreter is a program that converts program written in high-level language into machine code understood by the computer.
The difference between an interpreter and a compiler is given below:
InterpreterCompiler
Translates program one statement at a time.Scans the entire program and translates it as a whole into machine code.
It takes less amount of time to analyze the source code but the overall execution time is slower.It takes large amount of time to analyze the source code but the overall execution time is comparatively faster.
No intermediate object code is generated, hence are memory efficient.Generates intermediate object code which further requires linking, hence requires more memory.
Continues translating the program until the first error is met, in which case it stops. Hence debugging is easy.It generates the error message only after scanning the whole program. Hence debugging is comparatively hard.
Programming language like Python, Ruby use interpreters.Programming language like C, C++ use compilers.
Difference between interpreter and compiler
From: https://www.programiz.com/article/difference-compiler-interpreter

Sunday, November 13, 2016

Anonymous Classes

Anonymous Classes

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
This section covers the following topics:

Declaring Anonymous Classes

While local classes are class declarations, anonymous classes are expressions, which means that you define the class in another expression. The following example, HelloWorldAnonymousClasses, uses anonymous classes in the initialization statements of the local variables frenchGreeting and spanishGreeting, but uses a local class for the initialization of the variable englishGreeting:
public class HelloWorldAnonymousClasses {
  
    interface HelloWorld {
        public void greet();
        public void greetSomeone(String someone);
    }
  
    public void sayHello() {
        
        class EnglishGreeting implements HelloWorld {
            String name = "world";
            public void greet() {
                greetSomeone("world");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Hello " + name);
            }
        }
      
        HelloWorld englishGreeting = new EnglishGreeting();
        
        HelloWorld frenchGreeting = new HelloWorld() {
            String name = "tout le monde";
            public void greet() {
                greetSomeone("tout le monde");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Salut " + name);
            }
        };
        
        HelloWorld spanishGreeting = new HelloWorld() {
            String name = "mundo";
            public void greet() {
                greetSomeone("mundo");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Hola, " + name);
            }
        };
        englishGreeting.greet();
        frenchGreeting.greetSomeone("Fred");
        spanishGreeting.greet();
    }

    public static void main(String... args) {
        HelloWorldAnonymousClasses myApp =
            new HelloWorldAnonymousClasses();
        myApp.sayHello();
    }            
}

Syntax of Anonymous Classes

As mentioned previously, an anonymous class is an expression. The syntax of an anonymous class expression is like the invocation of a constructor, except that there is a class definition contained in a block of code.
Consider the instantiation of the frenchGreeting object:
        HelloWorld frenchGreeting = new HelloWorld() {
            String name = "tout le monde";
            public void greet() {
                greetSomeone("tout le monde");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Salut " + name);
            }
        };
The anonymous class expression consists of the following:
  • The new operator
  • The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface HelloWorld.
  • Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
  • A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
Because an anonymous class definition is an expression, it must be part of a statement. In this example, the anonymous class expression is part of the statement that instantiates the frenchGreeting object. (This explains why there is a semicolon after the closing brace.)

Accessing Local Variables of the Enclosing Scope, and Declaring and Accessing Members of the Anonymous Class

Like local classes, anonymous classes can capture variables; they have the same access to local variables of the enclosing scope:
  • An anonymous class has access to the members of its enclosing class.
  • An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.
  • Like a nested class, a declaration of a type (such as a variable) in an anonymous class shadows any other declarations in the enclosing scope that have the same name. See Shadowing for more information.
Anonymous classes also have the same restrictions as local classes with respect to their members:
  • You cannot declare static initializers or member interfaces in an anonymous class.
  • An anonymous class can have static members provided that they are constant variables.
Note that you can declare the following in anonymous classes:
  • Fields
  • Extra methods (even if they do not implement any methods of the supertype)
  • Instance initializers
  • Local classes
However, you cannot declare constructors in an anonymous class.

Examples of Anonymous Classes

Anonymous classes are often used in graphical user interface (GUI) applications.
Consider the JavaFX example HelloWorld.java (from the section Hello World, JavaFX Style from Getting Started with JavaFX). This sample creates a frame that contains a Say 'Hello World' button. The anonymous class expression is highlighted:
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
 
public class HelloWorld extends Application {
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World!");
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
 
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });
        
        StackPane root = new StackPane();
        root.getChildren().add(btn);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }
}
In this example, the method invocation btn.setOnAction specifies what happens when you select the Say 'Hello World' button. This method requires an object of type EventHandler<ActionEvent>. The EventHandler<ActionEvent> interface contains only one method, handle. Instead of implementing this method with a new class, the example uses an anonymous class expression. Notice that this expression is the argument passed to the btn.setOnAction method.
Because the EventHandler<ActionEvent> interface contains only one method, you can use a lambda expression instead of an anonymous class expression. See the section Lambda Expressions for more information.
Anonymous classes are ideal for implementing an interface that contains two or more methods. The following JavaFX example is from the section Customization of UI Controls. The highlighted code creates a text field that only accepts numeric values. It redefines the default implementation of the TextField class with an anonymous class by overriding the replaceText and replaceSelection methods inherited from the TextInputControl class.
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class CustomTextFieldSample extends Application {
    
    final static Label label = new Label();
 
    @Override
    public void start(Stage stage) {
        Group root = new Group();
        Scene scene = new Scene(root, 300, 150);
        stage.setScene(scene);
        stage.setTitle("Text Field Sample");
 
        GridPane grid = new GridPane();
        grid.setPadding(new Insets(10, 10, 10, 10));
        grid.setVgap(5);
        grid.setHgap(5);
 
        scene.setRoot(grid);
        final Label dollar = new Label("$");
        GridPane.setConstraints(dollar, 0, 0);
        grid.getChildren().add(dollar);
        
        final TextField sum = new TextField() {
            @Override
            public void replaceText(int start, int end, String text) {
                if (!text.matches("[a-z, A-Z]")) {
                    super.replaceText(start, end, text);                     
                }
                label.setText("Enter a numeric value");
            }
 
            @Override
            public void replaceSelection(String text) {
                if (!text.matches("[a-z, A-Z]")) {
                    super.replaceSelection(text);
                }
            }
        };
 
        sum.setPromptText("Enter the total");
        sum.setPrefColumnCount(10);
        GridPane.setConstraints(sum, 1, 0);
        grid.getChildren().add(sum);
        
        Button submit = new Button("Submit");
        GridPane.setConstraints(submit, 2, 0);
        grid.getChildren().add(submit);
        
        submit.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {
                label.setText(null);
            }
        });
        
        GridPane.setConstraints(label, 0, 1);
        GridPane.setColumnSpan(label, 3);
        grid.getChildren().add(label);
        
        scene.setRoot(grid);
        stage.show();
    }
 
    public static void main(String[] args) {
        launch(args);
    }
}

Saturday, July 19, 2014

Construct Binary Tree from Inorder and Preorder/Postorder Traversal

For a binary tree inorder traversal and either a postorder or preorder traversal can uniquely identify the tree.
The inorder sequence will resolve the left-right problem, and the other sequence (pre or post) will tell us the roots of the various subtrees. For example, if inorder is CBA, and preorder is CAB, then we know that C is at the root, and both B and A are in the right subtree



Question1:

An array which is a Post order traversal of a Binary Tree. Write a function to check if the Binary Tree formed from the array is a Binary Search Tree.


Eg:
2
1 3

The array given as input would be 1 3 2.
Write a function to say if the tree formed is a Binary Search Tree.

Example 2: 4 is root. 0 is left child of 1 , 1 is left child of 2 and 2 is left child of 4. 5 is right child of 4 and 6 is right child of 5.
4
2 5
1 6
0

0 1 2 6 5 4 is the input array.

No need to reconstruct a BST and cannot either.
bool isPostTraversalOfBST(int arr[], int n)
{
 if(n < 2) return true;

 int i = 0;
 //try to find out the beginning of right subtree's traversal
 for(; arr[i] < arr[n-1]; ++i) ;
 //check if all arr[i,n-1) >= arr[n-1]
 for(int j = i + 1; j + 1 < n; ++j){
  if(arr[j] < arr[n-1]) return false;
 }
 //check if both two parts are post traversals of BSTs
 return isPostTraversalOfBST(arr, i) &&
     isPostTraversalOfBST(arr + i, n - i - 1);
}

Monday, June 23, 2014

Linux Commands

# Create a new tar archive.
# the folder dirname/ is compressed into archive_name.tar
tar cvf archive_name.tar dirname/
# Extract from an existing tar archive
tar xvf archive_name.tar
# View an existing tar archive
tar tvf archive_name.tar


# Search for a given string in a file (case in-sensitive search).
grep -i "the" demo_file
# Print the matched line, along with the 3 lines after it.
grep -A 3 -i "example" demo_text
# Search for a given string in all files recursively
grep -r "ramesh" *
# Match regular expression in files
grep "lines.*empty" demo_file
# Match the string as a whole word
grep -iw "is" demo_file
# When you want to count that how many lines matches the given pattern/
string, then use the option -c
grep -c "go" demo_text
# To show the line number of file with the line matched
grep -n "go" demo_text


# Find the passwd file under root and two levels down.
#(i.e root — level 1, and two sub-directories — level 2 and 3 )
find / -maxdepth 3 -name passwd
# Find files using file-name ( case in-sensitve find)
find -iname "MyCProgram.c"
# Execute commands on files found by the find command
# it is to calculate the file's signature which is a hashcode
find -iname "MyCProgram.c" -exec md5sum {} ;
# Find all empty files in home directory
find ~ -empty
# Shows the files or directories whose name are not MyCProgram.c
find -maxdepth 1 -not -iname "MyCProgram.c"
# Find files which has read permission only to group
find . -perm 040 -type f -exec ls -l {} ;
# The following command will display the top 5 largest file in the current
directory and its subdirectory.
find . -type f -exec ls -s {} ; | sort -n -r | head -5
# Top 5 smallest: Technique is same as finding the bigger files, but the
only difference the sort is ascending order.
find . -type f -exec ls -s {} ; | sort -n  | head -5
# Find files bigger than the given size
find ~ -size +100M
# Find files smaller than the given size
find ~ -size -100M


# When you substitute a path name which has ‘/’, you can use @ as a
delimiter instead of ‘/’.
# In the sed example below, in the last line of the input file, /opt/omni/
lbin was changed to /opt/tools/bin
sed 's@/opt/omni/lbin@/opt/tools/bin@g' path.txt
# sed & Usage: Substitute /usr/bin/ to /usr/bin/local
sed 's@/usr/bin@&/local@g' path.txt
# sed & Usage: Match the whole line
sed 's@^.*$@<<<&>>>@g' path.txt
# Grouping using ()
# Get only the first path in each line, the number "1" is for the first
matched group
sed 's/(/[^:]*).*/1/g' path.txt
# In the above command $ specifies substitution to happen only for the last
line.
# Output shows that the order of the path values in the last line has been
reversed.
sed '$s@([^:]*):([^:]*):([^:]*)@3:2:1@g' path.txt
# Get the list of usernames in /etc/passwd file
# This sed example displays only the first field from the /etc/passwd file.
sed 's/([^:]*).*/1/' /etc/passwd
# Parenthesize first character of each word
echo "Welcome To The Geek Stuff" | sed 's/(b[A-Z])/(1)/g'
# Convert DOS format to UNIX format
sed 's/$/r/' input.txt > output.txt
# Commify the simple number
sed 's/(^|[^0-9.])([0-9]+)([0-9]{3})/12,3/g' numbers


# Remove duplicate lines using awk
awk '!($0 in array) { array[$0]; print }' temp
# Print all lines from /etc/passwd that has the same uid and gid
awk -F ':' '$3==$4' passwd.txt
# Print only specific field from a file
awk '{print $2,$5;}' employee.txt
# Awk reads and parses each line from input based on whitespace character by
default and set the variables $1,$2
# Awk FS variable is used to set the field separator for each record
# Awk FS can be set to any single character or regular expression
# 1 Using -F command line option: awk -F 'FS' 'commands' inputfilename as
following
awk -F':' '{print $3,$4;}' /etc/passwd
# 2 Awk FS can be set like normal variable: awk 'BEGIN{FS="FS";}' as
following
BEGIN{
FS=":";
print "NametUserIDtGroupIDtHomeDirectory";
}
{
    print $1"t"$3"t"$4"t"$6;
}
END {
    print NR,"Records Processed";
}
# And the execution of the awk script
awk -f etc_passwd.awk /etc/passwd
# Output field separator: field 3 and 4 are connected with "="
awk -F':' 'BEGIN{OFS="=";} {print $3,$4;}' /etc/passwd
# Awk RS Example: Record Separator variable and its execution
BEGIN {
    RS="nn";
    FS="n";

}
{
    print $1,$2;
}
awk -f student.awk  student.txt
# Awk ORS Example: Output Record Separator Variable
awk 'BEGIN{ORS="=";} {print;}' student-marks
# Awk NR Example: Number of Records Variable
awk '{print "Processing Record - ",NR;}END {print NR, "Students Records are
processed";}' student-marks
# Awk NF Example: Number of Fields in a record
awk '{print NR,"->",NF}' student-marks
# Awk FILENAME Example: Name of the current input file
awk '{print FILENAME}' student-marks
# Awk FNR Example: Number of Records relative to the current input file
awk '{print FILENAME, FNR;}' student-marks bookdetails
#  diff command examples :Ignore white space while comparing.
diff -w name_list.txt name_list_new.txt


# sort command examples Sort a file in ascending order
sort names.txt
# Sort a file in descending order
sort -r names.txt
# Sort passwd file by 3rd field. Filed separator is : (-t)  by a key (-k)
sort -t: -k 3n /etc/passwd | more


# To view oracle related environment variables
export | grep ORACLE
# To export an environment variable:
export ORACLE_HOME=/u01/app/oracle/product/10.2.0


# To create a *.gz compressed file:
gzip test.txt
# To uncompress a *.gz file:
gzip -d test.txt.gz
# To extract a *.zip compressed file:
unzip test.zip


# To view current running processes
ps -ef | more
# To view current running processes in a tree structure. H option stands for
process hierarchy.
ps -efH | more
# for kill
ps -ef | grep vim
kill -9 7243


# To displays only the processes that belong to a particular user use -u
option.
# The following will show only the top processes that belongs to oracle user.
top -u oracle


# Miscellaneous
# Displays the file system disk space usage. By default df -k displays
output in bytes
df -k
# Get confirmation before removing the file.
rm -i filename.txt
# Following example recursively removes all files and directories under the
example directory
rm -r example
# Copy file1 to file2 preserving the mode, ownership and timestamp.
cp -p file1 file2
# Rename file1 to file2. if file2 exists prompt for confirmation before
overwritting it.
mv -i file1 file2
# Give full access to user and group (i.e read, write and execute ) on a
specific file
chmod ug+rwx file.txt
# Revoke all access for the group (i.e read, write and execute ) on a
specific file.
chmod g-rwx file.txt
# Apply the file permissions recursively to all the files in the sub-
directories. o is for others
chmod -R ugo+rwx file.txt
# One more way to change
chmod 777 file.txt
# create a directory
mkdir ~/temp
# Use ifconfig command to view or configure a network interface on the Linux
system
ifconfig -a
# Print N number of lines from the file named filename.txt
tail -n N filename.txt
# To install apache using yum
yum install httpd
# To upgrade apache using yum
yum update httpd
# To uninstall/remove apache using yum.
yum remove httpd
# Can do the samethings using rpm
# The quick and effective method to download software, music, video from
internet is using wget command.
wget http://prdownloads.sourceforge.net/sourceforge/nagios/nagios-3.2.1.tar.gz

Monday, June 2, 2014

Inspiration


"When you do the common things in life in an uncommon way, you will command the attention of the world." – George Washington Carver

Tuesday, May 20, 2014

C#: Difference between int.Parse() and Convert.ToInt32


If you've got a string, and you expect it to always be an integer (say, if some web service is handing you an integer in string format), you'd use Int32.Parse().

If you're collecting input from a user, you'd generally use Int32.TryParse(), since it allows you more fine-grained control over the situation when the user enters in invalid input.

Convert.ToInt32() takes an object as its argument, and I believe it invokes Int32.TryParse() when it finds that the object taken as the argument is a string.

Convert.ToInt32 also does not throw ArgumentNullException when it's argument is null the way Int32.Parse() does. That also means that Convert.ToInt32() is probably a wee bit slower than Int32.Parse(), though in practice, unless you're doing a very large numbers of iterations in a loop, you'll never notice it.

Monday, May 12, 2014

C++ New virtual function controls: override, final, default, and delete

Reference http://www.learncpp.com/cpp-tutorial/b-6-new-virtual-function-controls-override-final-default-and-delete/

override
When working with derived classes, it’s fairly easy to inadvertently create a new virtual function in the derived class when you actually meant to override a function in the base class. This happens when you fail to properly match the function prototype in the derived class with the one in the base class. For example:
1
2
3
4
5
6
7
8
9
10
11
class Base
{
    virtual void A(float=0.0);
    virtual void B() const;
};
class Derived: public Base
{
    virtual void A(int=0); // specifies parameter as int instead of float, treated as new function
    virtual void B(); // specifies function as non-const, treated as new function
};
When this happens, it’s can be easy to make a function call to A() or B() and expect to get the derived version but end up getting the base version instead.
This phenomena can also easily occur when you add a new parameter to a function in Base but forget to update the version in Derived. When that happens, the function that was an override in Derived is no longer an override, and your code mysteriously stops working. These kinds of problems can be hard to find because the change that triggers them is so innocuous looking.
C++11 introduces a new identifier called override that allows you to explicitly mark functions you intend to be overrides. If the function is not an override, the compiler will complain about it. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Base
{
    virtual void A(float=0.0);
    virtual void B() const;
    virtual void C();
    void D();
};
class Derived: public Base
{
    virtual void A(int=0) override; // compile error because Derived::A(int) does not override Base::A(float)
    virtual void B() override; // compile error because Derived::B() does not override Base::B() const
    virtual void C() override; // ok!  Derived::C() overrides Base::C()
    void D() override; // compile error because Derived::D() does not override Base::D()
};
Although use of the override identifier is not required, it is highly recommended, as it will help prevent inadvertent errors.
(If you’re wondering why this was implemented as an identifier rather than a keyword, I presume this was done so that the name “override” can be used as a normal variable name in other contexts. If it had been defined as a keyword, it would be reserved in all contexts, which might break existing applications)
final
There are occasionally times when you don’t want to allow someone to override a virtual function, or even create a derived class. C++11 adds the identifier final to provide this functionality.
The following example shows the use of the final identifier to make a function non-overrideable:
1
2
3
4
5
6
7
8
9
class Base
{
    virtual void A() final; // final identifier marks this function as non-overrideable
};
class Derived: public Base
{
    virtual void A(); // trying to override final function Base::A() will cause a compiler error
};
The final identifier can also be used on classes to make them non-inheritable:
1
2
3
4
5
6
7
class Base final // final identifier marks this class as non-inheritable
{
};
class Derived: public Base // trying to override final class Base will cause a compiler error
{
};
There are some legitimate reasons to make functions or classes final. For example, the most common use of final is to ensure that an immutable class stays immutable. An immutable class is a specially-designed class whose state cannot be modified after it is created. Without the final identifier, a derived class could add functions that could cause the class to become mutable. If the base class is made final, it cannot be subclasses, and this is avoided.
However, generally speaking, unless you have a really good reason, use of final should generally be avoided. And if you do use the final keyword, document why, as it will likely not be obvious to whomever inherits your code.
default
By default, C++ will provide a default constructor, copy constructor, copy assignment operator (operator=) and a destructor. If you provide alternate versions of any of these functions for your class, C++ will not provide a default version. However, in C++11, you can now specify that you would like the compiler to provide a default one anyway. This is done by prototyping the function and using the default specifier:
1
2
3
4
5
class Foo
{
    Foo(int x); // Custom constructor
    Foo() = default; // The compiler will now provide a default constructor for class Foo as well
};
The default specifier can only be used with functions that have a default.
delete
More useful than the default specifier is the delete specifier, which can be used to disallow a function from being defined or called. One of the best uses of the delete specifier is to make a class uncopyable:
1
2
3
4
5
class Foo
{
    Foo& operator=(const Foo&) = delete; // disallow use of assignment operator
    Foo(const Foo&) = delete; // disallow copy construction
};
The delete specifier can also be used to make sure member functions with particular parameters aren’t called. For example:
1
2
3
4
5
class Foo
{
    void Foo(long long); // Can create Foo() with a long long
    void Foo(long) = delete; // But can't create it with anything smaller
};
In the above example, if you try to call Foo with a char, short, int, or long, those will all get implicitly converted to a long, which will then match Foo(long). Since Foo(long) has been deleted, the compiler will error.
If you want your class to only be called with very specific data types, you can turn off implicit conversions altogether by using a templated function to match everything that isn’t defined explicitly:
1
2
3
4
5
class Foo
{
    void Foo(long long); // Can create Foo() with a long long
    template<typename T> void Foo(T) = delete; // But can't create it with anything else
};