Saturday, February 22, 2020

Journey to the Success


Are you an Undergraduate?

Looking to be the best among others? 

My life journey will be a boost to your career.

I started to write this blog way back in 2016 during my 1st year.  This was started with 2 friends. But ultimately, both of them left blogging and I continued to blog.

The main purpose of this blog was to provide past paper answers to question papers of SLIIT. I had that aim mainly because we found it difficult to find answers to questions in past papers. So I thought to write answers and publish them here, so juniors and batch mates would benefit from it.

But after a few years of time, I stopped posting answers due to the criticism that came to me from a few people in SLIIT. I felt like why should I waste time and help those types of buggers to pass the exams 😀

If you are just starting at SLIIT or where ever, try to help the people. You'll be criticized, hated and even be an enemy to a few people.

Ok! that's enough about the boring old stories. Let's get into the point.

Before coming to SLIIT, I had completed the BCS. It gave me a real boost in the studies at SLIIT.

You won't believe after A/L's I wanted to do Engineering 😂. But when I went through the Engineering course amount at SLIIT, it was really expensive for me to bear. So I decided to do a computing degree which was manageable. What a turnaround in my life.

Once I join SLIIT, the course amount was Rs.115, 000. If you don't know, SLIIT is providing scholarships for the best people in the batch. Either half schol(GPA>3.7) or Full schol(GPA>3.9).

Half schol worth half of the semester fee and Full schol worth full semester fee.

I'm happy to say for the entire 4 years at SLIIT, I paid less than 2 lakhs. Most of the semesters were free for me :)

Thereby my parents didn't need to spend a single penny on my degree at the beginning.

During the 1st year at SLIIT, I came across a platform called Fiverr. It was a freelancing platform and didn't know much about it.

I just created an account and put some GIGS and waited for something to happen. But nothing interesting happened. 😜

Later that year, I got a message from a person from the USA asking if I can help to do his assignment in Java. As I was thorough in Java, I took the order worth $30 as I remember.

That was my very first order in Fiverr. I still remember that moment. I was really happy and I even showed that to my Mom as well. She had no clue what so ever 😰

With time, I was able to develop my profile and earn a good amount of money. For everything, I spend my own money and my parents didn't have to spend a single penny.

Now I'm working on Fiverr, Adsense, E-bay, and many other platforms and earning a good amount of money as my passive income!

My advice for everyone is that try to create your own side business and earn. Don't wait until the degree to be over and get a job to do your work!

That's enough boosting about myself I guess 😆

Getting back to the SLIIT journey, for every exam I didn't went to study hard. There is no need if you're doing an IT degree. If you know the essence, it is very easy.

For the 1st 2 years at SLIIT, I did old past papers as well. Mainly due to the aim of posting them on the blog and some questions were repeated from the old past papers.

Apart from 1st 2 years, I rarely attended the lectures. But I say, please attend lectures.  😰

I still remember the very 1st lecture I attended. It was done by Ms. Namalie Walgampaya. Her C++ lecture took me to a different world. From that moment, I got the motivation that I wanted to be the best and finally, I'm.

It's not easy to be the best performer in the Software Engineering Batch with many talented people around you!

Try harder, nothing is impossible!

To answer the question, did I continuously do well?

No! I had some ups and downs. It was the 3rd year 2nd semester as I remember. I was doing my internship. That period was really stressful and I did manage to get only a GPA of 3.5 for that semester. It was the foremost the lowest I ever had taken.

I will show you my results later at this post but keep in mind everyone has downs. The real strength is that you come over them.


Finally, I managed to get a CGPA of 3.9 and WGPA of 3.88 and become the Best Performer of Software Engineering batch passing 120+ students.






Finally, what I have to say is do your final year Research project well. It really counts for your final GPA.

This could be the final post that will be posted on this blog. There were so many appreciations that came for this blog. I'm really happy about that. In the end, the amount of time put on this was not gone in vain. If you need any help or have any inquiry you can contact me at LinkedIn or Facebook.

I hope you all have an amazing future ahead. Good Bye!🙆









Saturday, June 1, 2019

Count the Number of Bits Set to One using Java



In this article, we’ll be counting the number of bits set to one using Java. To make it clearer, let’s take number 6 as an example. Number 6 is written as 1102 in binary. From our example, we’ll get the output as 2, as there are 2 ones in the binary of the converted number. In this process, we use 2 concepts related to the binary numbers.   
  • Binary Comparison
  • Binary Shifting

What is Binary Comparison?

In our example, we are using and operation (&) for the binary comparison. It also called as bitwise and operation. Let’s take a look at the below example to understand how this binary comparison works with the & operator.

For Eg: Let’s take n as 4 and evaluate the (n&1) operation.

Logic Gate of AND operation
n = 00000000  00000100

A
B
Result
0
0
0
0
1
0
1
0
0
1
1
1

1 = 00000000  00000001 AND
------------------------------
0 = 00000000  00000000
==================


From the bitwise-and, result of (n&1); where n=4 is 0. This is frequently used to extract the Least Significant Bit (LSB) from a given number.

What is Binary Shifting?

Binary shifting refers to as shifting of all the bits in the operand used to a particular direction assigned by the user. There are 2 types of shifting.
  • ·         Arithmetic Left shifting(<<)
  • ·         Arithmetic Right shifting(>>)

In our example, arithmetic Right shifting is used to shift all the bits to the right side. To understand how arithmetic right shifting works, take a look at the below example.

When n = 12                                            Binary Representation = 1100

Let’s apply right shifting to the 12 => 1100>>1 which shifts one bit to right at a time.
1st Iteration – Last 0 is removed (110)
2nd Iteration – Next 0 is removed (11)

public static void main(String args[]){
      System.out.print("Please enter the number: ");
      //take the input from the user
      Scanner input = new Scanner(System.in);
      int number = input.nextInt();
             
      System.out.print("Total number of 1s
                            : "+countBitsSetToOne(number));
      //close the scanner instance
      input.close();
}
       
public static int countBitsSetToOne(int number) {
      int count = 0;
      while (number > 0){
        //binary comparison
        count = count + (number & 1);
        //binary shifting
        number = number >> 1;
      }
      return count;
}


In here, we have created a static method which takes one integer parameter. First, it checks whether the number is equal to zero or not. If the number is equal to zero, it will return the default value of the count variable; which is zero. When the number is greater than zero, it will increase the count while doing the bitwise-and operation. As I said earlier, bitwise-and returns the LSB of the number passed in. Finally, binary shifting is done to shift all the bits to right one by one until the whole iteration ends. When the number becomes zero, while loop terminates and returns the count.             

Basic Authentication in Web API



Authentication is the process of identifying the users based on their username and password. This restricts unauthorized people getting access to data or applications. There are 3 common ways of ensuring authentication. The basic method is to validate the username and password. Next method is to use smart cards and the final method is to use biometric details of the user.
From this post, we are going to talk about username and password authentication using a web API. In here we are using AuthorizationFilterAttribute class which is readily available from the System.Web.Http.Filters package to implement the authentication.

Why we use Authorization Filter class?

Authorization filters are the easiest way of handling the requests from the user and identifies whether the user has access to the application. Otherwise, UnauthorizedAccess exception will be thrown from the class. For the authorization, we will create our own class inheriting the features of the AuthorizationFilterAttribute class and overrides the OnAuthorization method by passing an action parameter. It is the method used to provide the request and response to the data we are passing.
namespace Authentication
class AuthenticationClass : AuthorizationFilterAttribute 
{ 
       public override void OnAuthorization(HttpActionContext httpActionContext) 
       { 
           base.OnAuthorization(httpActionContext); 
       } 
}

The main purpose of using an HTTPAction object is to check whether the header, we are passing is null or not. For any invalid header, OnAuthorization returns unauthorized access which is the 401 error code. Thereby no unauthorized third party can access the information. Hence, it is important to check the header before proceeding to the next section of the code. Now let’s override the OnAuthorization method with our customizations.


public override void OnAuthorization(HttpActionContext httpActionContext)  {      
           if (httpActionContext.Request.Headers.Authorization != null)  { 
                     // code
            }
            else { 
              httpActionContext.unauthorizedResponse =
           httpActionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); 
            }
}

For more information regarding the OnAuthorization() method, check the below link: https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.authorizeattribute.onauthorization?view=aspnet-mvc-5.2

Next, we have to get the user credentials and check it against the values from the database. For this example, I’ll be using 2 dummy values to illustrate the concept. Hence, this method will return true as a result of authorized login and return false for any unauthorized credentials.
public static bool isAuthorized(string username, string password)  {
           if( username == "admin" && password == "admin123"){
                return true;
            }
           else{
               return false;
           } 
}

So far we have overridden the OnAuthorization() method and created a new method to check the validity of the credentials. Now it’s time to implement the OnAuthorization() method combining all the components we created thus far. First, we need to create a token to store the headers of the request. For that, we use the headers property available in the HttpActionContext.
var accessToken = httpActionContext.Request.Headers.Authorization.Parameter;

As a security measure, AuthorizationFilterAttribute class encodes our credentials into the base64 encoding scheme. To get the original values we need to decode those back using UTF8 encoding scheme. For this conversion, we need to use the default method available in the System.Text library called FromBase64String.
var decodedaccessToken = System.Text.Encoding.UTF8.GetString( 
                                 Convert.FromBase64String (accessToken)); 

After the decoding, we will obtain the username and password separated by a colon. To separate out them into 2 parts, we need to use the split function available for the strings.
 var credentials = decodedaccessToken.Split(':'); 
string user = credentials[0]; // assigning values to each variable
string passwrd = credentials[1];


To proceed further, we need to check the validity of the credentials. For that, we need to pass the variables “user” and “password” to the method that we created to check the authorization. On the return of “true” function will proceeds and for “false”, unauthorized access code is returned.
  if (isAuthorized (user, passwrd)){
        Thread.CurrentPrincipal =
                           new GenericPrincipal(new GenericIdentity(user), null); 
  } 
  else 
  { 
      httpActionContext. unauthorizedResponse =
                                             httpActionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); 
  } 

If the isAuthorized() returns true, new instance of GenericPrincipal() is created and current state of user is assigned to it. Generic Principal takes two parameters, user identity and an array of roles names that the particular user belongs to. In here we will set that array to null and user identity as the username of the user. By now we have created the complete code to authorize the user.
For more information about the Generic Principle, take a look at the below link:

Now it’s the time to create a small API, to call the function we created. For that we need to create a controller class from the namespace we used earlier “Authentification” and this class will inherits features from the ApiController class.
namespace Authentication.Controllers 
{ 
    public class BasicController : ApiController 
    { 
         // GET api/value/id
         public string GetID(int id)
         {
            return id.ToString();
         }
    } 
} 


Finally, if you are using HTTP client like Postman to check this, it is important to set the Type as “Basic Auth”.