Friday 1 May 2020

GO language Basics

This article covers the basics of GO language.
Go language is popular today due to simple to use, high performance because of its concurrency feature compared to other language like python. Go has garbage collector .

#1  Basic Program

// The program header should contain -> package main
// Also there will be import packages like in python.
// Every function or routine starts with "func" with open braces and closing braces
// fmt.Println -> is used to print the statements.

package main
import  "fmt"

func main(){
   fmt.Println("Hello World")
}

#2 How to define functions 

Tip:  use "func" keyword.
Function can return multiple values with named and unnamed

#prog:2

package main
import  "fmt"

//Declare function with zero or multiple arguments
func  display(){
        fmt.Println("I am in in Display function")
}
func recv(x int, y int){
        fmt.Println("The values of X and Y", x,y)
}

func recv(x int, y int){
        fmt.Println("The values of X and Y", x,y)
}
// Un named return function 
func return_multiple(x int, y int)(int, int){
        return x,y
}
func named_return(b,t string)(z,y string){
   z=b
   t=y
   return
}
func main(){
   fmt.Println("Hello World")
   // Call display function
   display()
   //recv function
   recv(2,3)
   // Function return value
   y:= add(2,4)
   fmt.Println("The Result of addition is", y)

   // Multiple values return by function by unamed
   a,b:= return_multiple(10,11)
   fmt.Println("The values are", a,b)
   
   fmt.println(named_return("mu","sekhar"))

}

O/p:
Hello World
I am in in Display function
The values of X and Y 2 3
The Result of addition is 6
The values are 10 11
mu sekhar

Tip :Short Hand Declaration : a int b int -> a,b int

#3 What are datatypes present in GO?

Boolean types : Consists of the two predefined constants: (a) true (b) false
Numeric types : a) integer types or b) floating point values throughout the program.
String types  : A string type represents the set of string values. 
             
Derived types:
   - Pointer types,   - Array types,     - Structure types,     - Union types 
   - Function types     - Slice types     - Interface types     - Map types     - Channel Types

Basic data Types
bool, string
int  int8  int16  int32  int64
uint uint8 uint16 uint32 uint64 uintptr

byte // alias for uint8
rune // alias for int32
     // represents a Unicode code point
float32 float64
complex64 complex128

#4 How to declare or define the variables in GO?

Syntax:   var < variable name> <data type>   e.g: var a int
            short hand --->   variable:= <value>  i:=2

Tip: By Default the variables are assigned to 0 for int, empty (" ") for strings and false for boolean

package main
import "fmt"

func main(){
  //Declaration 1
  var i int
  i=20
  fmt.Println(" The value of i", i)

  // Declaration 2 Short hand
  r:="muni"
  fmt.Println(" The value of r", r)

  var x  int
  var y, f bool
  fmt.Println(x, y,f)

  //intialise the variables
  var x1,y1,z string = "mu", "sekhar", "reddy"
  fmt.Println(x1,y1,z)

  // short Hand initialization
  i,j,k:=1,2,3
  var h,b,n int=10,11,13
  fmt.Println(i,j,k, h,b,n)

  // By Default the values of uninitialized to Zero values
  // f is 0 g false t ="" empty string
  var  m int
  var  g bool
  var  t string

  fmt.Println(m,g,t)

}
Output:
 The value of i 20
 The value of r muni
0 false false
mu sekhar reddy
1 2 3 10 11 13
0 false

#5 How to do Type conversions in GO?

Data-Type<Variable>   for e.g: i:=3   k=float64(i)  z=uint32(i)

Tip: var i int =10  j:=i  - > there is no need explicity mention the type for J.. It variable's type is determined from the value on the right hand side)

#6  How to define Const variables in GO?

Constant variables are declared using keyword "const". const <variable-name>= <value>
package main
import "fmt"

func main(){
   const i=2
   const k="muni"
   const j=8.7
   fmt.Println(i,k,j)
   i=9  // Cannot change constant value
}

Tip: Cons i:=2 // This way of constant cannot be declared. Not allowed

#7  LOOPS in GO

Note: There is no while Loop in Go. The for loop itself act like a while Loop.
Syntax:      for i:=0; i<num; i++ { .. }   
            ->   for { }  -> infinite loop
            ->   i:=0 for i<5; i++ { .... }


package main

import "fmt"



func main(){

  //Basic For Loop

  for i:=0; i<2; i++ {

          fmt.Println(i)

  }

  //initialization and  post increments are optional

  j:=0
  for ; j<2;  j++ {
     fmt.Println("Sekhar")
  }
  // There is no While Loop in GO language
  //While loop
  k:=0
  for k<2 {
     fmt.Println("I am Linux")
     k++
  }
}
Output:
0
1
Sekhar
Sekhar
I am Linux
I am Linux

#8  if-else statement in GO

Syntax:      if  <condition> { 

                   }

                  if  <condition> {

                 } else {

                       .....

                 }   

            
package main
import "fmt"

func main(){
   x:=7
   // x<8 we can have without braces as well.
   if (x<8) {
       fmt.Println(" I am in IF statement")
   } else {
       fmt.Println(" I am in Else Statement")
   }
   // Short Hand initialization
   if k:=99; (k<89) {
       fmt.Println(" K is True ")
   }else {
       fmt.Println(" K is False ")
   }
}

Output:
I am in IF statement

K is False

#9  Switch Statement in GO

There is no switch statement in python. But Go has switch feature.

package main
import "fmt"

func main(){
  ch:="test"
  switch ch {
      case "test":
         fmt.Println(" I am in test Function")
      case "not":
         fmt.Println("I am not case")
      default:
         fmt.Println("I am in default case")
  }
  // Mimic the if-else case
  i:=2
  switch{
     case i<3:
         fmt.Println(" I value is less than 3")
     case  i>3:
         fmt.Println(" I value is greater than 3")
    default:
         fmt.Println("Default Value")
  }
}

Output
------
I am in test Function
I value is less than 3


#9  DEFER Statement in GO

Defer statement -> It  will defer the execution of the statement until the function return.
Program 1 #
---------------
package main
import "fmt"

func main(){
    defer fmt.Println("I am First Function")
    fmt.Println(" I am after Defer Function")

}
Output:
I am after Defer Function
I am First Function

Program 2 #
--------------
package main
import "fmt"

func main(){
    for i:=0; i<2; i++ {
        defer fmt.Println(" The output is :", i)
    }
    fmt.Println(" I am after Defer Function")
}
Output:
I am after Defer Function
The output is : 1
The output is : 0


#10  Pointer in  GO

Pointer is variable which holds the memory address of another variable as in C.  This is used to change the value of variable with the pointer de-referencing operator *

Syntax:  var p *int
               var i int=4    p=&i -> Holds the address of the integer variable i

package main
import "fmt"

func main(){
        var p *int
        var i int
        i=400
        p=&i
        fmt.Println("The value of p and *p", p, *p)
        // Change the value of "i" as below
        *p=300
        fmt.Println("The value of i", i)
}

Output:
The value of p and *p 0xc0000a4010 400
The value of i 300

#11  Struct in  GO

Syntax:   type <struct-name> struct {
                      <variable-name> data-type
                      ......
               }
Defining values of the struct variable as  :  < variable> := <struct-name>
e.g:
type emp struct{
        emp_age  int
        emp_name string
        emp_sal  float64
   }
   x:= emp{1, "sekhar", 2.33}

The value of struct values shall be accessed using  dot(.) operator. (x.emp_age, x.emp_name, x.emp_sal)

Struct Pointer;
p := &x
p.emp_age = 2222  // It can be modified like this.

package main
import "fmt"

func main(){
   type emp struct{
        emp_age  int
        emp_name string
        emp_sal  float64
   }
   x:= emp{1, "sekhar", 2.33}
   fmt.Println(x)
   // Struct Fields can be accessed using '.'(dot)
   fmt.Println(x.emp_age, x.emp_name, x.emp_sal)

   // Struct Pointer
   // It inference the pointer as struct pointer
   p:= &x
   p.emp_age = 111
   fmt.Println(x.emp_age, x.emp_name, x.emp_sal)


   type dummy struct{
           xq ,yq string
   }
   // Various way of initialization values of struct
   d1 :=dummy{"muni","sekhar"}
   d2 :=dummy{xq: "muni"}
   d4 := dummy{}

   fmt.Println(d1)
   fmt.Println(d2)
   fmt.Println(d4)
}

output:
{1 sekhar 2.33}
1 sekhar 2.33
111 sekhar 2.33
{muni sekhar}
{muni }
{ }

#12  Arrays in  GO

Array stores elements of same data type.
Syntax:  [n] data-type  -> It stores the 'n' elements of data-type of T.
              e.g:   var a [7] int
                      Short Hand -> a := [7]{1,2,3,4,5,6,7}
package main
import "fmt"

func main(){
     var X[2] int
     X[0]=1
     X[1]=2
     fmt.Println(X[0], X[1])

     var Z= [3]int{1,2,3}
     fmt.Println(Z)

     Y:= [2] float64{2.00, 3.00}
     fmt.Println(Y)

     str:=[2] string {"muni","sekhar"}
     fmt.Println(str[0], str[1])
}
Output:
1 2
[1 2 3]
[2 3]
muni sekhar

#13  Slices in  GO

Array are fixed size, whereas slices can be dynamically sized, which generally stores the part of elements of the array.
Syntax:  [ ] data-type    -> It contains the elements of corresponding data -type

Slices doesn't store data, it contains the elements of underlying array. Modifying the slice data shall modify the elements of underlying array. i.e.Slices have reference  to array.

package main
import "fmt"

func main(){
   var arr1= [4]int{1,2,3,4}

   arr2 := [5]string{"mu","sek","red","tt","yy"}

   // A slice is formed by specifying two indices,
   // a low and high bound, separated by a colon:
   // a[low : high]

   s := arr2[1:4]
   var t1 []int= arr1[1:4]
   fmt.Println(s, t1)

   fmt.Println(s[0], s[1], s[2])

   // Modifying slice effect to the array.
   //slices have reference to array
   s[2] = "Modified"
   fmt.Println(arr2)
}

Output:
[sek red tt] [2 3 4]
sek red tt
[mu sek red Modified yy]

#13  Create Slices using "make" built-in function 

Syntax:-->  make ([] T, length, capacity)
                e.g:  v := make([] int, 3, 4) -> It creates slice of three elements with zero value and having capacity of 4.

// Slice can be created using "make" built-in function .
// "make" takes two arguments make( []data-type, length, capacity)
// length is used to index the items in the slice. ->len(v)
// capacity is used pre allocated space in the memory and it is optional. -> cap(v)
// Having capacity gives more performance rather than allocating newly using append operations.
//  v := make([] int, 3)  in this case both length and capacity is same as 3.

COPY in slice:     copy(slice1, slice2)
-------------------
APPEND in slice:    sli=append(sli, 2,3)  -> Append 2 and 3 to the existing slice sli.
--------------------
Length of slice ->    len(sli)    Capacity of slice ->  cap(sli)

package main
import "fmt"

func main(){
    // Slice can be created using "make" built-in function
    // make takes two arguments make( []data-type, length, capacity)
    // length is used to index the items in the slice
    // capacity is used pre allocated space in the memory and it is optional
    // Having capacity gives more performance rather than
    //allocating newly using append operations.

    sli := make([]int, 3,4)
    fmt.Println(sli, len(sli),cap(sli))

    // Append to the existing slice
    sli = append(sli, 10,11,12,13)

    fmt.Println(sli, len(sli),cap(sli))

    sli[0]=200
    sli[1]=300
    fmt.Println(sli, len(sli),cap(sli))

    i:= sli[2:]
    j:= sli[:4]
    fmt.Println(i,j)

    dup_sli := make([]int,  len(sli))
    copy(sli, dup_sli)
    fmt.Println(dup_sli)

    //Two dimensional array or Slice
    twoD := make([][]int, 3)
    for k:=0; k<len(twoD); k++{
         inner:= k+1
         twoD[k] = make([]int, inner)
         for  j:=0; j<inner; j++ {
             twoD[k][j]=k+j
         }
    }
    fmt.Println(twoD)
}
Output:
[0 0 0] 3 4
[0 0 0 10 11 12 13] 7 8
[200 300 0 10 11 12 13] 7 8
[0 10 11 12 13] [200 300 0 10]
[0 0 0 0 0 0 0]
[[0] [1 2] [2 3 4]]


What is Cloud Computing? And its Basics

In this below post, i would like to capture about cloud computing concepts.


What is Cloud Computing?

      Cloud Computing is the delivery of computing services  such as servers, storage, networking, software, analytics etc.. and more over the internet ("The cloud"). The companies offering these computing services are called cloud providers.  These companies charge for the cloud computing services based on the usage.  Like how you billed for electricity or water

What are benefits of Cloud computing?

 > Reduce the costs of buying hardware or software

> By using the cloud computing, these services can be provisioned in minutes. Obviously, speediness in setting up the services.

>  We can scale the services on the fly based on the need. For example, if it requires more storage or network bandwidth or high computing power can be achieved on the fly by using these services.

>  High Reliability, availability of servers (Back up and disaster recover mechanism)

>  It removes unnecessary tasks which ultimately saves more time. So that teams can concentrate on important business goals( High productivity).

> Cloud Vendors uses the latest technologies  to achieve the high performance.
 
What are types of cloud services?

Basically there are three types of services:

  • Software as a service
  • Platform as a service
  • Infrastructure as a service

IaaS [ Infrastructure as a service]:
It is renting IT infrastructure such as servers, networks, storage, Virtual machines and operating systems. User pays based on the usage.

E.g: It is like leasing a car.

IaaS examples include Amazon Web Services (ASW), Microsoft Azure and Google Compute Engine.

These services are managed by the biggest companies in the world effectively maintaining huge data centers in various corners of the globe in order to offer very inexpensive infrastructure with large potential for scalability.

Other examples of IaaS include Bluelock, Rackspace, CSC, GoGrid, Linode, DigitalOcean.

PaaS [ Platform as a service]:
Developers shall code, unit test and deploy in the provided platform or environments. It is top of IaaS. Developers quickly create web app or mobile applications, with out worrying about the setting up and manage the underlying servers, storage,network, databases needed for development.

 PaaS (Platform as a Service), as the name suggests, provides you computing platforms which typically includes operating system, programming language execution environment, 
database, web server etc. Examples: Heroku, EngineYard, App42 PaaS and OpenShift, Google App Engine” system


SaaS [ Software as a service]:
It is the top of  PaaS. The application software's are available to users over the internet on demand basis. They don't  have to worry about any infrastructure or platform.  All they can access the software via web browsers. 

 A Simple Example is SaaS is an online email service, like Gmail. If you use Gmail, you are not hosting your own email server.  Google is hosting it, and you are simply accessing it through your browser-as-client.  There are so many applications like this which are available for business purposes.

Examples : Google Apps, Salesforce.com, and Microsoft Office 365,  or Gmail, Dropbox, Salesforce, or Netflix.




Basic difference between IaaS, PaaS & SaaS
FeaturesIaasPaaSSaaS
What you getYou get the infrastructure & pay accordingly .Freedom to use or install any OS, software or compositionHere you get what you demand. Software, hardware, OS, web environment.  You get the platform to use & pay accordingly Here you don’t have to worry about anything. A pre-installed, pre-configured package as per your requirement is given and you only need to pay accordingly.
ImportanceThe basic layer of ComputingTop of IaaSIt is like a Complete package of services
Technical DifficultiesTechnical knowledge requiredYou get the Basic setup but still the knowledge of subject is required.No need to worry about technicalities. The SaaS provider company handles everything.
Deals withVirtual Machines, Storage (Hard Disks), Servers, Network, Load Balancers etcRuntimes (like java runtimes), Databases (like mySql, Oracle), Web Servers (tomcat etc)Applications like email (Gmail, Yahoo mail etc), Social Networking sites (Facebook etc)
Popularity GraphPopular among highly skilled developers, researchers who require custom configuration as per their requirement or field of research.Most popular among developers as they can focus on the development of their apps or scripts. They don’t have to worry about traffic load or server management etc.Most popular among normal consumers or companies which reply on softwares such as email, file sharing, social networking as they don’t have to worry about the technicalities.

Types of cloud deployments: public, private, hybrid

There are three different ways to deploy cloud computing resources: public cloud, private cloud and hybrid cloud.

Public cloud

Public clouds are owned and operated by a third-party cloud service provider, which deliver their computing resources like servers and storage over the Internet. Microsoft Azure  and AWS are examples of public cloud. With a public cloud, all hardware, software and other 
supporting infrastructure is owned and managed by the cloud provider. You access these services and manage your account using a web browser.

Private cloud

A private cloud refers to cloud computing resources used exclusively by a single business or organisation. 
A private cloud can be physically located on the company’s on-site data center. 
Some companies also pay third-party service providers to host their private cloud. A private cloud is one in which the services and infrastructure are maintained on a private network.

Hybrid cloud

Hybrid clouds combine public and private clouds, bound together by technology that allows data and applications to be shared between them. 
By allowing data and applications to move between private and public clouds, hybrid cloud gives businesses greater flexibility and more deployment options.     

[Source : https://azure.microsoft.com/en-in/overview/what-is-cloud-computing/]




Monday 14 August 2017

How to install GIT in Ubuntu server? How to add/clone the local repository to/from the GitHub?

In this post, i would like to present you some interesting things of GIT.

GIT - is a version control system and which is been used in many projects in the recent days.

Step 1:  Install GIT in Ubuntu

sudo apt-get install git
Installation Log:

How to add the local repository to the GitHub?

Step 2: Configure the GitHub 

Once the git is successfully installed in the Linux machine. Then it is required to configure the GitHub by using the user name and email Id as shown below.

git config --global user.name  "provide_your_user_name"
git config --global user.email "provide_your_email_id"

Step 3: Create a Local Repository (or directory) 

Create a local directory in your system and later this repository can be pushed in to the GIT HUB website.
git init your_preferred_directory_name

If the command is successful, it will show message as Initialized empty Git repository in  /root/Localproject/.git/

Step 4: Change directory to locally created
cd Localproject
Step 5: Create your files for Local repository 

Create two sample files in the local repository.
>  File 1:  Readme   -> Write description about your project.  
               e.g: "Set up the GIT test repository"
>  File 2:  testfile.py -> Any source code file.

#!/usr/bin/python

def test():
  print "Hello world"

test()

Step 6: Add files to the Local repository 

After creating the sample files, then add these files to the local repository index.
git add <your_files>
Here git add will place the files in the buffer like space, later it will be added to the git repository.

Step 7: Commit the changes to Local repository 

Once the files are added and finalized, then commit or uploaded the  files to the local repository 
git commit -m "your commit message" 

Check the log of the file using the below command.

git log "your_file_name" 
root@muni:~/Localproject# git log testfile.py
commit 0db1bb0ea2a595ec46a23f7956786de04c075ea4
Author: amsekhar <ams@gmail.com>
Date:   Fri Aug 11 14:42:18 2017 -0500

    first commit the files

Step 8: Create user Account in  GitHub website and Create Repository 

1. Login to https://github.com/ 
2. Create your user Account using "SIGN UP" option in the website.
3. Create repository on GitHub as shown below. Note that the name of the GitHub repository (Localproject) should be same as the local repository name (Localproject).  

Click on right hand side of create repository 

Step 9: Connect to the GitHub Repository

Once the repository is created, then push the changes of local repository to the GitHub website.

git remote add origin https://github.com/your_user_name/your_project_name.git
e.g:  git remote add origin https://github.com/amsekhar/Localproject.git
Step 10: Push the local files to the remote GitHub Repositry

Push the local files present in local server to the remote GitHub repository

git push origin master
It will prompt you to enter the credentials of GitHub account.  Username : xxxx and  Password:xxxx



How to clone the repository from the GitHub to local server?
To get an copy of an existing Git repository from GitHub or from any GIT server use the "git clone" command.

  • We shall receives a full copy of all data that the GitHub or server has. 
  • Every version of every file for the history of the project is pulled down by default when you run git clone.
Steps: Clone the GitHub Repository using "git clone command"
  •  Login in to the GitHub website with your credentials
  •  Navigate to the main page of repository.
  •  Under your repository name, click Clone or download.   Copy the link to clipboard.
  •  Use one of the below commands 
git clone <https://github.com/your_git_user_name/your_project_name.git>  
git clone <https://github.com/user_name/project_name.git>  <your_desired_name>
e.g: git clone https://github.com/rishi417/testproject.git
e.g: git clone https://github.com/rishi417/testproject.git  Mytestproject



How to create new Branch in GitHub?
1. Login to https://github.com/ 
2. Create your user Account using "SIGN UP" option in the website.
3. Create branch on GitHub as shown below.


How to checkout the feature Branch from Remote/GitHub?

Step 1: Clone the GitHub Repository using "git clone command"
  •  Login in to the GitHub website with your credentials
  •  Navigate to the main page of repository.
  •  Under your repository name, click Clone or download.   Copy the link to clipboard.
  •  Use one of the below commands

git clone <https://github.com/your_git_user_name/your_project_name.git>  
e.g: git clone https://github.com/rishi417/testproject.git
Step 2: Change directory to the Local Repository (Here, testproject)

cd testproject
Step 3: Then checkout the respective branch from GitHub 

git checkout -b <Local_repository_branch_name> origin/<gitHub-Branch-name>
e.g: git checkout -b my_local_branch origin/new_feature_branch_001
verify using: git status
How to add a new file to GitHub branch from the local repository?

Step 1: Be in the local Repository
             create new file and add using git add, git commit -m "new file added"

cd testproject; vim new_file.py; git add new_file.py;  git commit -m "new file added"
Step 2: Push the new file in to the GitHub Feature Branch

git push origin <local_branch_name> : <remote_branch_name>
e.g: git push origin my_local_branch : new_feature_branch_001

Step 3: Verify in the GitHub repository for the new file.

How to remove file from local branch and also from the feature Branch located in GitHub?

Step 1: Be in the local Repository
             Remove using git rm <file_name>

git rm "file_name"        e.g: git rm new_file_rishi.py
Step 2: Commit the changes
             
git commit -m "new file removed"        
Step 3: Push the changes in to the GitHub Feature Branch

git push origin <local_branch_name> : <remote_branch_name>
e.g: git push origin my_local_branch : new_feature_branch_001

Step 3: Verify in the GitHub repository for removed file.

How to merge the feature branch changes in to master branch?

You can do either using "git fetch"  and  "git merge" commands (or).
Git fetch - Download objects and refs from another repository

Use "git pull command" . "git pull" => "git fetch" + "git merge"

Step1: First checkout the Master branch.
git checkout master
Step 2: Merge the changes in to master branch using git pull command.
git pull origin <feature_branch_name>
git pull origin new_feature_branch_001
Step 3: Verify in the GitHub Master branch for the changes.


How to switch between the branches?
git checkout <branch_name>
e.g: git checkout master   >-- git checkout new_feature_branch_001
How to check which branch your repository is pointing?
git branch  or git status
How to update the local repository with the changes from GitHub repository?


Step1: First check which branch your local repository is working on.
            The below command will show the branch you are working on.
git branch
Step 2: Update the local repository using git pull command.
git pull origin <branch_name>
e.g: git pull origin master

How to find out who has commit the file?
git log <file_name>
 There is another interesting command "git blame" which gives information about each line of a file (or)
e.g: git blame <file_name>
 Annotates each line in the given file with information from the revision which last modified the line.
useful to blame your colleague that you haven't the wrong fix.. :) .. 





Useful commands of GIT 
  • git checkout
  • git status
  • git pull
  • git fetch
  • git rebase
  • git blame
  • git diff
  • git stash
  • git clone
  • git push
  • git rm

Git GUI Tools
In Linux , one can manage the GIT commands from the command line.
If you don't feel comfortable with command line, then there are several graphical user interface (GUI) tools are available.

  •  GitKraken
  •  Git-cola
  •  SmartGit
  •  Giggle
  •  Gitg
  •  Git GUI
  •  Qgit

Please check out this link for more info.
      https://www.tecmint.com/best-gui-git-clients-git-repository-viewers-for-linux/