Tuesday, December 20, 2016

Corners of a square matrix remain corners no matter how many times you invert them

This is a hint That can be used in many programming contests which I noticed during solving the Flipping the matrix problem in Hackerrank.com and thought that it is something that I should write down somewhere. :)
Here is the problem description from Hackerrank.
Sean invented a game involving a  matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times, and the goal of the game is to maximize the sum of the elements in the  submatrix located in the upper-left corner of the  matrix (i.e., its upper-left quadrant).
Given the initial configurations for  matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal. For each matrix, print the maximized sum on a new line.
Input Format
The first line contains an integer, , denoting the number of queries. The subsequent lines describe each of the  queries in the following format:
  1. The first line of each query contains an integer, .
  2. Each line  the  subsequent lines contains  space-separated integers describing the respective values of row  in the matrix.
So first I tried varios thing to reverse the rows and columns in various ways. But later realizd that there should be a simple hint that solve this poblem and there was a one. That is
Corners of a square matrix remain corners no matter how many times you invert them
Using that hint to find the max,

In a 4X4 matrix


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16














Sunday, December 11, 2016

3 different ways to loop through every char in a string in c++

When programming sometimes we need to loop through a string and deal with every character in that string. In c++ there are several ways to do that. In this post lets see 3 different ways to loop through a string.
  1. Using a range-based for loop (This feature is available from c++ 11)


  2. Using ierators


  3. Using normal for loop



If you have a null terminated character array this method also can be used.

Those are the 4 different ways that can be used to loop through strings. If you have suggestions or new methods pleas leave a comment below.

Wednesday, December 7, 2016

Find running time of an algorithm in C++

Some times we need to find how long would an algorithm take to complete a task. This is needed very much when we comparing two or more algorithms. So I looked for that in several forums and most of them have suggested to use clock() function which comes with ctime header. That didn't work properly because It gives the time from the start of the program (which I will explain latter part of the post) and not suitable for measuring intervals in nanosecond level.

So here is the solution for that. We can use functions in class high_resolution_clock. Here IsPrime is the function that I want to find the running time of.
As you can see in line 30, we can cast the time difference int any unit we want (ns,ms). That gives us a great advantage of finding very small time intervals. But if we use clock() function instead we wan't be able to achieve that much of accuracy.

Here is a code example of using clock() function (which I don't recommend in this scenario)


clock() function will give the total number of clock ticks until the execution of function from the start of the program (If we want to convert it into seconds, have to divide by CLOCKS_PER_SEC).
But this gives a good result only if we are doing a considerable calculation between the time interval. other wise we will get a zero as result.

Sunday, November 13, 2016

Enabling C++11 in Eclipse Kepler/Luna CDT

When you are coding in C++ using eclipse IDE (installing CDT plugin)and if you use newer features of C++11 sometimes you might get errors when compiling. Reason for that might be you haven't enabled C++11 in Eclipse CDT. Lets see how to enable C++11 in Eclipse CDT. These steps are given assuming you are using GCC compiler. But steps are more similar to the other compilers as well.

Step 1 : Set up your compiler

  • Right click your project and click Properties
  • Under C/C++ Build click Settings
  • Under GCC C++ Compiler, click Miscellaneous
  • In the Other Flags box, append "-std=c++11" to the list of tokens
  • Click Apply and OK

Wednesday, November 9, 2016

Comment a code block in gvim


When we are coding we have to comment out some blocks of code and uncomment those time to time. It is easy with IDE like eclipse, netbeens, Visual Studio. I recently moved to vim and here is how to comment and uncomment in gvim. (lets assume character "#" is used for line commenting)

Method 1 

Command mode of vim used for this.
Use this command to comment lines from 10 to 15 with "#"
:10,15s/^/#
Use this command to uncomment lines commented before.
:10,15s/^#/

Method 2

VISUAL BLOCK mode is used for this.
  1. First, move the cursor to the first char of the first line in block code you want to comment. Then press Ctrl + v to enter VISUAL BLOCK mode
  2. Then move cursor with arrow keys to the end of code block that want to comment.
  3.  Then press Shift + i and cursor will come to the begining of code block
  4. The type the commenting character. In this case "#".
  5. Final press Esc and it will comment out the block you marked
To uncomment,

do the same things but instead of type Shift + i, you just type x to remove all # after highlight them in VISUAL BLOCK mode.

Monday, November 7, 2016

Select and replace strings in gvim


Here are some ways to replace strings in gvim.

For replacing a string across a file

:%s/<search_string>/<replace_string>/g

To replace in current line

:s/<search_string>/>replace_string>/

To select and replace words from selective lines in vim(In this example want to replace in line 6 to 10 and 14 to 18).

:6,10s/<search_string>/<replace_string>/g | 14,18&&
The :&& command repeats the last substitution with the same flags. You can supply the additional range(s) to it (and concatenate as many as you like):

If you have many ranges you can use loops as well.

:for range in split('6,10 14,18')| exe range 's/<search_string>/<replace_string>/g' | endfor
This four options can be used in almost any time that we want select and replace in gvim

Sunday, October 30, 2016

Templates in C++ simply explained.

Here are three videos that simply explain concepts of function templates, class templates and template Specialization.

1.  Function templates



2.  Class templates



3.  Template Specialization

Friday, October 28, 2016

Compilation process of a C++ program.

When we write a C++ program we use g++ -Wall -o sample sample.cpp command (file name is sample.cpp) to compile the program then we run the executable output from that process.

In this this post lets see how this compilation process happen before output an executable.

This compilation process has four main stages.
  1. Preprocessing

    In this stage preprocessor copies the contents of the included header files into the source code file, generates macro code, and replaces symbolic constants defined using #define with their values.
    Normally the standard header files to be included are in "/usr/include" directory in Ubuntu. [GCC looks in several different places for headers]
    We can stop the compilation process after preprocessing using
    g++ -E sample.cpp
    Output we get after this stage might be very long because all the header files are also included.
  2. So directing the output to a txt file would be better.
    g++ -E sample.cpp > AfterPrePros.txt

Tuesday, October 25, 2016

Some Linux Command that I found useful



Here are some linux command I found useful in my day to day work.
This is not a full list of LINUX commands. recently started working with LINUX. So this is a set of simple commands I found useful.


  • whatis

    It provides very brief descriptions of command line programs and other topics related to Linux and other Unix-like operating systems.whatis searches a set of database files containing short descriptions of system commands for keywords and displays the result
    whatis head
    whatis head tail
    
  • source

    source is a bash shell built-in command that executes the content of the file passed as argument, in the current shell. It has a synonym in '.' (period).
    source .cshrc
    
  • ls -la ~/ | more

    Find hidden files on a directory
  • Move files from one place to another

    mv /home/jack/testfile /home/jack/testfile2
    mv testfile testfile2
    mv /home/jack/testfile /home/jack/Documents/
  • Monday, October 24, 2016

    Copy constructors in C++ simple explained

    Here are three videos that explains concept of copy constructor in C++ nicely. Best I found so far.

    1. Copy constructor



    Tuesday, September 6, 2016

    Why C++ would not print the memory address of a char.

    If I said that "C++ is not able to print pointer value of a char", would you believe it?? I also confused at first, but found the reason.

    char ch ='a';
    int num=0;
    string str = "abc";
    
    cout << &ch << endl;
    cout << &num << endl;
    cout << &str << endl;
    
    
    If you compile and run this code it will print character "a" instead of address of ch variable.

    Why is this happening..?

    Later found that it only happens with  << operator.

    When you are taking the address of b, you get char *. operator<< interprets that as a C string, and tries to print a character sequence instead of its address because there is a special overload in operator<<.

    Tuesday, June 21, 2016

    Adding a PPA through a proxy server

    PPA stands for Personal Package Archive and it is a special software repository for uploading source packages to be built and published as an APT repository by Launchpad.
    Simply PPAs are for non standard software or updates. We can find latest software or updates that doesn't normally provided by Ubuntu software center. So people add these PPAs to system in order to use latest softwares. Some times there might be risks of adding PPA.

    On the command line you can add a PPA using apt-add-repository,
    e.g.: sudo apt-add-repository ppa:strukturag/libde265 

    If you are connected to Internet through a proxy server above command will give an error.
    e.g.:
    Cannot add PPA: 'ppa:strukturag/libde265'. 
    Please check that the PPA name or format is correct.

    Thursday, June 9, 2016

    Serializing objects in java

    Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link. The byte stream can then be deserialized - converted into a replica of the original object.

    There are few important things that need to be known.

    • In Java, the serialization mechanism is built into the platform, but you need to implement the Serializable interface to make an object serializable.
    • You can also prevent some data in your object from being serialized by marking the attribute as transient.
    • It is important to notice that what gets serialized is the "value" of the object, or the contents, and not the class definition. Thus methods are not serialized.
    Here is an example of a Java class that can be that can be instantiate as a serializable object.

    
    import java.io.*;
    
    
    public class Student implements Serializable {
     public String name;
     public String address;
     public transient int regNumber;
     public int classNumber;
     
     public Student(String name,String add,int regNo,int clsNo){
      this.name=name;
      this.address=add;
      this.regNumber=regNo;
      this.classNumber=clsNo;
     }
     

    Sunday, June 5, 2016

    What is Activiti and Installing Activiti plugin to eclipse

    What is Activiti?? Activiti is a light-weight workflow and Business Process Management (BPM) Platform targeted at business people, developers and system admins.

    It helps to build and structure the solutions on business processes.

    A business process is defined as a set of activities and tasks that, once completed, will accomplish an organizational goal. Here are some examples for business processes of an organization.
    • A billing process 
    •  A risk management process 
    •  An invoicing process 
    •  An product assembly process 
    •  A quality assurance process
    Lets see how to install Activiti plugin on eclipse
    1. click Help -> Install New Software... in eclipse IDE
    2. Click on  Add button to add a new repository
    3. Give Activiti BPMN 2.0 designer as the Name and http://activiti.org/designer/update/ as the Location.

    Saturday, June 4, 2016

    What are In-Memory Databases and why we need them????

    An in-memory database (IMDB) is a database management system that primarily relies on main memory for computer data storage. It is also known as main memory database system (MMDB) or memory resident database.
    Traditional database systems are designed to store data on persistent media. But working with a data in memory is much faster than working with persistent medias.
    When working with a traditional database system there are disk I/O processes, caching processes. and the following diagram will describe the process of accessing and modifying data with a traditional database.


    Why use Hibernate and what is JPA ???

    Hibernate is an object-relational mapping framework for the Java language. It provides a framework for mapping an object-oriented domain model to a relational database.
    There are some key points about Hibernate

    • It is an ORM (Object Relational Mapping) framework.
    • It implements JPA (Java Persistence API).
      JPA is a set of standards that have been described for implement any persistence in software.


    Monday, May 30, 2016

    Java Threading - Usage of synchronized key word

    Go through the following simple code snippet. It increment the value of variable using two threads.
    
    public class App {
     private int number = 0;
     
     public static void main(String args[]){
       App app = new App();
       app.increment();
     } 
     public void increment(){
      Thread t1 = new Thread(new Runnable(){
       @Override
       public void run() {
        for(int i=0;i<10000;i++){
         number=number+1;
        }
       }   
      });  
      Thread t2 = new Thread(new Runnable(){
       @Override
       public void run() {
        for(int i=0;i<10000;i++){
         number=number+1;
        }
       }   
      });  
      t1.start();
      t2.start();
    

    Monday, May 16, 2016

    What is continuous integration (CI)

    Continuous integration is one of software engineering best practices. this post summarize the my attempt of finding what continuous integration is and it's uses.

    First of all lets see what is continuous integration is in a simple sentence.

    it is simply a mechanism that rebuilds your project whenever a check in is made into some revision control system.

    This can be extended though to include running tests, all the way through to generating a CD image, mounting it within VMs, installing the product and running full tests on it.

    This explanation was taken from a stackoverflow post.

    It describe the advantages of continuous integration as well in the same post and it says,

    Continuous integration has the simple advantage of highlighting when code changes break the system as early as possible. Not only does it detect breaks in the code, it highlights who caused the break. This psychological effect is very effective in encouraging good testing prior to check in!

    Lets see important facts about continuous integration in points.
    • Continuous Integration is a software development practice where members of a team integrate their work frequently(usually each person integrates at least daily)
    • It lead to multiple integration s per day. So each integration is verified by an automated build (including test) to detect integration errors as quickly as possible.
    • Many teams find that this approach leads to significantly reduced integration problems and allows a team to develop cohesive software more rapidly
    Those points are obtained from a nice article about continuous integration written by Martin Fowler.

    CI originated from within the extreme programming paradigm but the principles can be applied to any iterative programming model, such as agile programming. Traditional development approaches, such as the waterfall model can benefit from using CI methods for the construction stage.

    Sunday, May 15, 2016

    Java Threading - Usage of volatile key word.

    Threading is important when considering the obligation of work in a program, handle more than one event at a time. But if it is not used in proper way it can lead to some problems as well.

    Data being cached is a problem that can encounter in some scenarios. Lets take a look at one.

    Consider the following java class
    
    class Processor extends Thread{
     private boolean running =true;
     public void run(){
      while(running){
       System.out.println("hello ");
       try{
        Thread.sleep(100);
       }catch(InterruptedException e){
        e.printStackTrace();
       }
      }
     }
     public void shutDown(){
      running = false;
     }
    }

    Difference between compiled and interpreted programming languages

    When considering about implementation of different programming languages they have used different approaches to achieve their goals. Compiled and interpreted are two different implementations which are used by people who developed programming languages.

    I wanted to know what are these interpreted and compiled programming languages, what are the differences, advantages and disadvantages of those approaches. In this post I'm presenting simple and clear answers, I found in my small research of interpreted and compiled programming languages.

    [This content is from a answer to a stackoverflow question about programming languages.]

    • In a compiled implementation, the original program is translated into native machine instructions, which are executed directly by the hardware.

    Saturday, April 16, 2016

    Java Threading - Three ways to create java threads

    In programming, threading is a way of distributing our work. We can delegate a huge load of work in to several threads (i.e several processes). A thread will run as a separate operating system process which can run concurrently with other threads.

    There are three ways of creating threads in java

    1. Extend the thread class

    Thread class has a run method and need override method with the code to run in a its own thread.
    To execute code in a separate thread,
    • Instantiate an object of class which is extended by Thread class (Runner)
    • Invoke the start() method of Thread class.
      • start() method will go to Thread class and look for the run method and invoke that in a separate thread.

    2. Implement Runnable interface

    • Implement Runnable interface in a class
    • Pass object of that class to a constructor of Thread class.
    • Invoke the start() method 
    
    
    
    

    3. Instantiate a Thread object with a Runnable instance

    Java Socket Programming - Simple Server And Client

    In Java socket programming(Network programming) we basically study about how to implement programs that communicate over a network. When we use java to implement those kind of applications java.net package will be used because it contains collection of classes and interfaces that provide low level communication details. It provides support for TCP and UDP which are two major network protocols.


    Process between client and a server


    • First client program creates a socket and try to connect to a socket in a server. That server socket should be already created and ready for client requests. 
    • After a connection is made server and client communicate by writing and reading from the socket.

    Wednesday, February 24, 2016

    Sorting Algorithms - Part I

    Selection Sorting

    Algorithm

    for i = 1:n,
        k = i
        for j = i+1:n, if a[j] < a[k], k = j
        → invariant: a[k] smallest of a[i..n]
        swap a[i,k]
        → invariant: a[1..i] in final position
    end
    
    

    Implementation in Java

    public static void selectionSorting(int[] arr){  
      for(int i=0;i<arr.length;i++){
       int k =i;
       for(int j=i+1;j<arr.length;j++){
        if(arr[j]<arr[k]){
         k=j;
        }
       }
       int temp=arr[k];
       arr[k]=arr[i];
       arr[i]=temp;
      }  
     }
    
    

    Properties

    • O(1) extra space
    • O(n2) comparisons
    • O(n) swaps

    Usage

    This algorithms has O(n2) comparisons property so run time is always quadratic. So selection sort is not an algorithm that we don't want to use.
    Interesting property is it minimizes the number of swaps. There for it can be used in sorting where swapping costs  high.

    Saturday, February 13, 2016

    What is a Java Bean (JB)

    There are lot of confusions among people new to Java programming what is a Java Bean. What does that really mean. Is it a different type of class in Java as Enum . I also had all those questions at the beginning. So here i'm writing about what i learn on the way of finding what java bean is.
    • What is a Java Bean
    Simple answer for that is Java Bean is also a normal java class. But all java classes are not java beans.
    To be a Java Bean classes should have following,
    1. All properties of the class should be private. Getters and setters can be used to get and set the elements.
    2. Class should has a public but no-argument constructor.
    3. Java Serializable interface should be implemented.
    So if those things have in a java class we can call it as a Java Bean. So it is a standard 
    People use Word java bean to recognize java classes which are built in a predefined way.

    • Could you give me an example
    Here is an example java bean
    
    public class Employee implements java.io.Serializable{  
    
    private int id;  
    private String name; 
    private String address;
    private int age;
      
    public Employee(){}  
      
    public void setId(int id){this.id=id;}  
      
    public int getId(){return id;}  
      
    public void setName(String name){this.name=name;}  
      
    public String getName(){return name;}  
    
    public void setAge(int age){this.age=age;}
    
    public int getAge(){return age;}
      
    }  
    

    Look whether this has all the features mentioned above. YES. so this is a java bean

    Note: Remember,  we talked about normal java beans. there is whole different thing named EJB (enterprise java bean). names are similar. but don't be mixed with plain java beans and Enterprise java beans.

    Thursday, January 28, 2016

    Adding resource file for localization in Asp.net

    Localization is the process of customization to make our application behave as per the current culture and locale. So in that case what we do is we keep key value pairs in a type of file called resource files (.resx files)

    Lets see how to store key value pairs in a resource file and how to use them in a Razor view.(Assume our project name is "MyApplication" for examples)


    1. Create a directory in your project for resource files (Ex: directory named "Localization")
    2. To create a resource file in that directory,
      right click on that directory => click Add => click New Item => Select general tab under Visual C# => Select Resource File => click Add (Give a name to that file as you want ex:MyResource)
    3. Then your resource file will be displayed in a table format in Visual Studio Insert your Name , Value pairs. 
    4. Set "Custom Tool Namespace" value as path to your resource file (ex:MyApplication.Localization)
    Now you have created a resource file successfully. Then you just have to use them in Razor views.
    for that,
    Add this code at the top of your views.

    @using Resources = MyApplication.Localization

    Here MyApplication is project name and Localization is directory of resource file.

    Then when ever you want to use a value in Razor view use this,

    @Resources.MyResource.Name

    Here "MyResource" is name of your resource file and "Name" name of your key value pair. 

    Saturday, January 23, 2016

    Direct user to a web page using a bat file


    code is simple.
    
    @echo off
    title Go to site
    start http://jascripts.blogspot.com/
    

    Save this batch script with a name you want and after executing it you will be taken to the URL specified in your script in your default browser.

    Note: If it gives errors
    use start iexplore.exe http://jascripts.blogspot.com/

    First steps to write batch files in windows



    I'm sure that nearly every windows user have seen files with extension .bat . What are the they, What do they do, How can we make them.

    They are actually one type of files that exist in windows operating system and those files can be used to get some work done by OS.

    Lets see how we can create those files with simple example.
    
    @echo off
    title My First Batch File
    echo Hello!
    pause
    


    • Don't worry about the first line @echo off (If you want check out more details from here)
    • title My First Batch File this line gives a title to our batch file
    • echo Hello! line print the word "hello!"
    • pause this will pause the program for user inputs
    Now save this file with any name you want with .bat extension and double click on the created batch file to execute what you programmed.

    Note:Make sure when you save set Save as type to "All types".


    Friday, January 22, 2016

    Split string by another string in C#

    Normally developers use String.Split method to split a string by a character. An Overloaded version of same method can be used to split a string by string in C#.

    
    string data = "THExxQUICKxxBROWNxxFOX"; 
    return data.Split(new string[] { "xx" }, StringSplitOptions.None);

    • A string array should be passed as first parameter. 
    • In second parameter we can specify whether the substrings include empty array elements. etc
    In this example string "xx" is passed but multiple string values can be passed as we want

    string value = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate."; 
    string[] separators = {",", ".", "!", "?", ";", ":", " "}; 
    string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries); 
     foreach (var word in words) 
      Console.WriteLine(word);

    more details can be found here.

    Thursday, January 21, 2016

    Best method to extract text from PDF in asp.net C#


    There are many ways to extract text from PDF.
    • Microsoft IFilter interface and Adobe IFilter implementation
    • iTextSharp
    • PDFBox
    Among those solutions using PDFBox is the best according to my experiences because,
    • Using Adobe IFilter implementation need to have lot of other things set up in running machine like,
      • Windows 2000 or later
      • Adobe Acrobat or Reader 7.0.5+
      • IFilter COM wrapper class
    • iTextSharp is opensource but can't be used in commercial products.
    So the best solution is using PDFBox. It doesn't need other things installed on your machine.

    PDFBox is a java PDF library and there is a .net version of PDFBox (It can be downloaded from here


    Here is an example how to use PDFBox

    
    using org.apache.pdfbox.pdmodel;
    using org.apache.pdfbox.util;
    
    // ...
    
    private static string ExtractTextFromPdf(string path)
    {
      PDDocument doc = null;
      try {
        doc = PDDocument.load(path)
        PDFTextStripper stripper = new PDFTextStripper();
        return stripper.getText(doc);
      }
      finally {
        if (doc != null) {
          doc.close();
        }
      }
    }  
    

    NOTE:
    1. Following dll files of PDFBox library should be added to bin file of your project
      • commons-logging.dll
      • fontbox-1.8.9.dll
      • IKVM.OpenJDK.Text.dll
      • IKVM.OpenJDK.Util.dll
      • IKVM.Runtime.dll
    2. Reference for following dll s should be added
      • IKVM.OpenJDK.Core.dll
      • IKVM.OpenJDK.SwingAWT.dll
      • pdfbox-1.8.9.dll

    Deleting Files in ASP.NET C#

    Simplest way to delete files in asp.net C#
    
    if ((System.IO.File.Exists(fileName)))
                    {
                        System.IO.File.Delete(fileName);
    }
    
    

    This is a simple code snippet in asp.net that can be used to delete files from any directory.
    In here variable "fileName" is the specific path to the file.

    Ex: If want to delete a file called "hello.pdf" in "upload" folder which is in my C drive, file name should be full path to that file "C:\upload\hello.pdf"


    Monday, January 11, 2016

    What is Windows Power Shell & how it differs from CMD

    Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework.
    If it sounds complicated you can think it as same as the CMD prompt but with more advance tools.
    PowerShell is a much more powerful command-line shell and scripting language than the Command Prompt is. It gives Windows system administrators a useful command-line environment.

    There are some fabulous things that can be done using Power Shell
    • perform your favorite CMD tasks
    • Kill processes in power shell instead of using task manager
    • Export NTFS file permossions
    • Play with power sell 2.0
    • Background a time consuming task
    • Report all of the USB devices installed
    ( Read more about these tasks)

    There are few main differences between cmd prompt and power shell
    • Power sell uses a different set of commands called cmdlets.Many system administration tasks are exposed via Power Shell cmdlets
    • PowerShell makes use of pipes, just as Linux and other Unix-like systems do. 
    • You can create complex scripts for managing Windows systems much more easily than you could with the Command Prompt.
    So here is why people use Power Sell over cmd prompt
    • Cmd prompt is limited, can’t access many Windows system administration features.
    • It is is more difficult to compose complex scripts with 
    PowerShell is a new environment for Windows system administrators that allows them to use a more modern command-line environment to manage Windows.

    Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

    Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...