Polymorphism Explained

While studying object oriented programming, we learnt that ‘Polymorphism’ is one the fundamental feature of the object oriented programming. The simple definition of polymorphism means occurrence of something in different forms. Is it so? Then, water can exist as ice and vapors, so can we call it as polymorphism? Technically, yes. Now, in the programming world, why we need something to exists in different forms? Can we live without them?

In object oriented programming, the way to perceive the code blocks is different from when we talk about our favorite procedural programming. In OOP, the code block has to be class, which when instantiated, becomes an object, and it should have defined features, capable of performing defined actions, and defined sets of reactions too. This object should be more like a living thing.

The purpose of polymorphism is to implement a different style of programming in which objects of different types define a common interface of operation for users. So, if we talk about an odd example – your hands. There is a common interface of your hand, and it can be used to hold things, move things, etc. This type of style is called ‘message-passing’.

When programming in OOP, our objectivity is create the code blocks called ‘classes’, and ensure that these classes provides common interfaces to it’s users (which can be any other class – which will be written by the same programmer or some other programmer), so that they have easy life. This can be explained by:
The printf function can takes multiple parameters, any data types: this means that instead of having my printf functions (e.g. printf1, printf2, or printfstring, printfsint, etc), we just need to know that printf is the function using which we can print data (irrespective of the type). Don’t you think that this has eased the life of ours a bit?
So, while building our own code blocks (classes), we may have to look at this aspect, and see where we need to use the ‘message-passing’ style of coding. I will use the classic example here – write a code block that is capable of calculating the area of different shapes. Here the operation is to calculate the area, while shapes can be rectangle, circle or square.

First, we will touch on something called – Overloading. This is quite simple, very much like the ‘printf’ example quoted above. In function overloading, two or more functions will have same name, but operate on different types of data. If we consider the operation of calculating the area of shapes – for rectangle, we need length and breadth, for circle, we need only radius, and for square, we need only length. For the example sake, we are going to use different data types – for radius, we will accept a float as datatype, while for square, we will accept integer as datatype. Thus, we can overload the functions by:
Having different number of arguments
Having different datatype for arguments.
Let’s look at the code now (implemented in C#).

//Define single class for calculating areas of different shapes
class Area
{
//Define variables
float area;

//Declare different forms of Functions -
public void cal_area(int length ,int breadth)
{
area=length*breadth;
Console.WriteLine(“Area of Rectangle:”,area);
}

public void cal_area(int length)
{
area=length*length;
Console.WriteLine(“Area of Square:”,area);
}

public void cal_area(float radius)
{
area=3.14*radius*radius;
Console.WriteLine(“Area of Circle:”,area);
}
}

Let’s now use this class (implement) – code given below. Now how the compiler would know which function to call? Given the parameters of a particular shape, the choice is made on the basis of number or type of arguments.
Area a;
a.cal_area(5); //calls the cal_area(int) function
a.cal_area(5,6); //calls the cal_area(int, int) function
a.cal_area(3.5); //calls the cal_area(float) function

In the above example, the decision of which function to be executed is made by the compiler at compile time, this type of overloading is also called ‘compile-type’ polymorphism.

Now, let’s touch on another aspect called – Overriding. This is related to another fundamental feature of OOP – inheritance. So, what if an inherited class wants to do differently from it’s parent class for function? Can inherited class do that? Yes, in this case the inherited class (of the sub class) has to override the function.

Let’s look at the same example of calculating area in ‘overriding’ way (implemented in C++).

//parent class with variable to store area, and a virtual function to calculate area
class Shape
{
public double area;
public virtual void cal_area(){}
}

//Inherited from shape, with it’s own implementation of area.
class Circle:Shape
{
public float radius;
public void cal_area()
{
area=3.14*radius*radius;
}
}

//Inherited from shape, with it’s own implementation of area.
class Square: Shape
{
public int side;
public void cal_area()
{
area=side*side;
}
}

//Inherited from shape, with it’s own implementation of area.
class Rectangle: Shape
{
public int length;
public int breadth;
public void cal_area()
{
area=length*breadth;
}
}
In the above code, we have 4 classes, 1 parent, and 3 sub classes. All the sub classes, has it’s own way of calculating area (different cal_area function). Here, we have overridden the cal_area in all the sub classes. So, this is called function overriding. Now, let’s have a look at it’s implementation.

Shape *s1;
Circle c;
c.radius = 10.5;
Square s;
s.side = 5;
Rectangle r;
r.length = 8;
r.breadth = 4;

s1=&c;
s->cal_area();
s1=&s;
s->cal_area();
s1=&r;
s->cal_area();

In this example, the base class pointer contains address of derived class, the decision of calling different versions of virtual function is taken at the time of execution of code – runtime, hence the term runtime polymorphism.

The primary usage of polymorphism in industry (object-oriented programming theory) is the ability of objects belonging to different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior. The programmer (and the program) does not have to know the exact type of the object in advance, and so the exact behavior can be determined at compilation time or at runtime (this is also called late binding or dynamic binding).

Printing In Unix

  1. lpr filename — print. Use the -P option to specify the printer name if you want to use a printer other than your default printer. For example, if you want to print double-sided, use ‘lpr -Pvalkyr-d’, or if you’re at CSLI, you may want to use ‘lpr -Pcord115-d’. See ‘help printers’ for more information about printers and their locations.
  2. lpq — check out the printer queue, e.g. to get the number needed for removal, or to see how many other files will be printed before yours will come out.
  3. lprm jobnumber — remove something from the printer queue. You can find the job number by using lpq. Theoretically you also have to specify a printer name, but this isn’t necessary as long as you use your default printer in the department.
  4. genscript — converts plain text files into postscript for printing, and gives you some options for formatting. Consider making an alias like alias ecop ‘genscript -2 -r \!* | lpr -h -Pvalkyr’ to print two pages on one piece of paper.
  5. dvips filename — print .dvi files (i.e. files produced by LaTeX). You can use dviselect to print only selected pages.

File Compression In Unix

1. zip filename — compresses files, so that they take up much less space. Usually text files compress to about half their original size, but it depends very much on the size of the file and the nature of the contents. There are other tools for this purpose too (e.g compress), but gzip usually gives the highest compression rate. Gzip produces files with the ending ‘.gz’ appended to the original filename.

2. gunzip filename — uncompresses files compressed by gzip.

3. gzcat filename — lets you look at a gzipped file without actually having to gunzip it (same as gunzip -c). You can even print it directly, using

gzcatfilename | lpr

 

Running Wamp and IIS togther

A Simple way of doing that is changing the localhost port for wamp server.
Easy steps for doing that are as following :

To change the port address of Apache in Wamp server :

1.       Go to   \wamp\bin\apache\apache2.2.8\conf

2.       Open  “httpd.conf” in notepad

3.       Find “Listen 80” and Change it to your desired port

(for example : Listen 8081)

4.       Save it and close it .

To show the starting page of Wamp Server with new changed port address :

1.       Go to \wamp

2.       Open “wampmanager.tpl” in notepad

3.       Find “http://localhost”  and replace with your given port address

(for example :

) 4.       Save and close it .

Export Data to Excel

Here is the way to Export some data to Excel. Code written in VB.net using some help of VBA script . Here are the steps for doing that:-

Sub ExportToExcelDetail(ByVal R_ID As String)

        Dim strSQLQuery As String = String.Empty
        Dim dtTable As DataTable = New DataTable

        Dim xlApp As Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkSheet As Excel.Worksheet
        Dim misValue As Object = System.Reflection.Missing.Value
        Dim strRowCount As String = ""
        Dim strXValues As String = ""
        Dim strValues As String = ""
        Dim strPath As String
        Dim iSheetCount As Integer = 1
        Dim linkArray As String()
        Dim ds As DataSet
        Try

            xlApp = New Excel.ApplicationClass
            xlWorkBook = xlApp.Workbooks.Add(Server.MapPath("~\Temp\Blank.xlsx"))
            xlWorkSheet = xlWorkBook.Sheets("Sheet1")

            'DELETING TWO EXTRA SHEETS CREATED DEFAULT
            ''BEGIN
            Dim wsD As Excel.Worksheet
            wsD = xlWorkBook.Sheets("Sheet2")
            wsD.Delete()
            wsD = xlWorkBook.Sheets("Sheet3")
            wsD.Delete()
            ''END
            ds = GetData(R_ID)

            dtTable = ds.Tables(0)
            ExcelDataForamtCustom(xlWorkSheet, dtTable, 3, 4)

''Exporting File to Screen

            xlWorkSheet.Name = "Default OCS Report"
            Dim strReport As String

            strReport = "OCS - OS- Report(" + Format(Date.Now, "yyyyMMdd-HHmmss").ToString + ").xlsx"
            strPath = Server.MapPath("Temp\") & strReport.ToString
            excelpath = strPath
            excelfilename = strReport
            Dim filename As String = strReport.ToString
            Dim file As System.IO.FileInfo = New System.IO.FileInfo(strPath)

            If file.Exists Then
                file.Delete()
            End If

            xlWorkSheet.SaveAs(strPath)
            xlWorkBook.Close()
            file = Nothing

            file = New System.IO.FileInfo(excelpath)
            If file.Exists Then
                Response.ContentType = "application/octet-stream"
                Response.AppendHeader("content-disposition", "attachment; filename=" + filename)
                '  Response.Flush()
                Response.TransmitFile(file.FullName)
                Response.End()
            End If

        Catch ex As Exception

        Finally
            '' ReleaseObject(xlApp)
            '' ReleaseObject(xlWorkBook)
            '' ReleaseObject(xlWorkSheet)
        End Try

2) Then Add bellow function for getting data. function is calling a procedure and returning dataset. you can do it in your way:

Private Function GetData(ByVal Report_Type As String) As System.Data.DataSet
        Dim strSql As [String]
        Dim DBConnection As SqlConnection
        Dim cmd As SqlCommand
        Dim adapter As New SqlDataAdapter
        Dim dsExport = New DataSet()
        Dim strGroup As String
        Dim strQueue As String
        Try
            DBConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("OCS").ConnectionString)
            DBConnection.Open()
            cmd = New SqlCommand
            cmd.Connection = DBConnection
            cmd.CommandType = CommandType.Text

            strSql = "EXEC [dbo].[PROC_OCS_R0010]   @R_ID  = '" & Report_Type & "', @R_GroupName = '" & hdSelGroup.Value & "'"
            'strSql = "EEXEC PROC_GHR_MIS0010 @P_USERID = 1,	@P_FROMDATE = '2011/05/05' ,@P_TODATE = '2011/06/01',	@P_REPOT_TYPE = 'ISSUE COMPLIANCES'"
            cmd.CommandText = strSql
            adapter.SelectCommand = cmd

            adapter.Fill(dsExport, Report_Type)
            adapter.Dispose()
            Return dsExport
        Catch ex As Exception
            Throw New Exception(ex.Message.ToString)
        Finally
            adapter.Dispose()
            cmd.Dispose()
            If DBConnection.State <> ConnectionState.Closed Then
                DBConnection.Close()
            End If
        End Try
    End Function

3) Add bellow function to add custom formatting to the sheets:

Public Function ExcelDataForamtCustom(ByRef xlWSOS As Excel.Worksheet, ByVal dtOSList As DataTable, Optional ByVal itopRow As Integer = 1, Optional ByVal itopCol As Integer = 1) As String()
        Dim iOsROWCount As Integer = dtOSList.Rows.Count
        Dim iOsCOLCount As Integer = dtOSList.Columns.Count
        Dim OSListArray(iOsROWCount, iOsCOLCount) As String
        Dim intR As Integer
        Dim intRow As Integer
        Dim intColumn As Integer
        Dim xlRange As Excel.Range
        Dim intBorderWeight As Integer = Excel.XlBorderWeight.xlMedium
        Dim strLinkArray(iOsROWCount) As String

        xlWSOS.Cells.Interior.PatternColorIndex = 10

        'For displaying the column name in the the excel file.
        For intColumn = 0 To iOsCOLCount - 1
            xlWSOS.Cells(itopRow, intColumn + itopCol).Value = dtOSList.Columns(intColumn).ColumnName.ToString
        Next

        'For displaying the column value row-by-row in the the excel file.
        For intRow = 0 To iOsROWCount - 1
            For intColumnValue = 0 To iOsCOLCount - 1
                ' xlWorkSheet.Cells(intRow + 3, intColumnValue + 2).Value = dtTable.Rows(intRow).ItemArray(intColumnValue).ToString
                OSListArray(intRow, intColumnValue) = dtOSList.Rows(intRow).ItemArray(intColumnValue).ToString
            Next
            strLinkArray(intRow) = OSListArray(intRow, 0)
        Next

        xlRange = xlWSOS.Range(ExcelColName(itopCol) & itopRow + 1, ExcelColName(iOsCOLCount + itopCol - 1) & iOsROWCount + itopRow)
        xlRange.Value = OSListArray
        xlRange.Interior.Color = RGB(230, 160, 160)

        'Format the HEADER ROW
        xlRange = xlWSOS.Range(ExcelColName(itopCol) & itopRow, ExcelColName(iOsCOLCount + itopCol - 1) & itopRow)
        With xlRange
            .Borders(Excel.XlBordersIndex.xlEdgeTop).Weight = intBorderWeight
            .Borders(Excel.XlBordersIndex.xlEdgeBottom).Weight = intBorderWeight
            .Borders(Excel.XlBordersIndex.xlEdgeLeft).Weight = intBorderWeight
            .Borders(Excel.XlBordersIndex.xlEdgeRight).Weight = intBorderWeight
            .Interior.Color = RGB(211, 1, 1)
            .Font.Size = 12
            .Font.Bold = True
            .Font.Color = RGB(255, 255, 255)
            .HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
            .VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
        End With

        'Building Data Row & Columnss
        For intR = itopRow + 1 To intRow + itopRow
            If intR Mod 2 = 0 Then
                xlRange = xlWSOS.Range(ExcelColName(itopCol) & intR, ExcelColName(iOsCOLCount + itopCol - 1) & intR)
                xlRange.Interior.Color = RGB(250, 235, 235)
            End If
        Next
        'AutoFit all Data Columns
        For intR = itopCol To intColumn + itopCol + 1
            xlWSOS.Columns(ExcelColName(intR) & ":" & ExcelColName(intR)).AutoFit()
        Next

        'Format the Data Columns
        xlRange = xlWSOS.Range(ExcelColName(itopCol) & itopRow, ExcelColName(iOsCOLCount + itopCol - 1) & iOsROWCount + itopRow)
        With xlRange
            .Borders(Excel.XlBordersIndex.xlEdgeTop).Weight = intBorderWeight
            .Borders(Excel.XlBordersIndex.xlEdgeBottom).Weight = intBorderWeight
            .Borders(Excel.XlBordersIndex.xlEdgeLeft).Weight = intBorderWeight
            .Borders(Excel.XlBordersIndex.xlEdgeRight).Weight = intBorderWeight
            With .Borders(Excel.XlBordersIndex.xlInsideHorizontal)
                .LineStyle = Excel.XlLineStyle.xlContinuous
                .Weight = Excel.XlBorderWeight.xlHairline
            End With
            With .Borders(Excel.XlBordersIndex.xlInsideVertical)
                .LineStyle = Excel.XlLineStyle.xlContinuous
                .Weight = Excel.XlBorderWeight.xlHairline
            End With
            .HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
            .VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
        End With
        Return strLinkArray
    End Function

Basic Unix Commands:

If you are new to UNIX, then these basic commands will help you a lot

1. ls — lists your files

2. ls -l — lists your files in ‘long format’, which contains lots of useful information, e.g. the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified.

3. ls -a — lists all files, including the ones whose filenames begin in a dot, which you do not always want to see.

4. more filename — shows the first part of a file, just as much as will fit on one screen. Just hit the space bar to see more or q to quit.

5. emacs filename — is an editor that lets you create and edit a file.

6mv filename1 filename2 — moves a file (i.e. gives it a different name, or moves it into a different directory.

7. cp filename1 filename2 — copies a file

8. rm filename — removes a file. It is wise to use the option rm -i, which will ask you for confirmation before actually deleting anything. You can make this your default by making an alias in your .cshrc file.

9. diff filename1 filename2 — compares files, and shows where they differ.

10. wc filename — tells you how many lines, words, and characters there are in a file.

11. chmod options filename — lets you change the read, write, and execute permissions on your files. The default is that only you can look at them and change them, but you may sometimes want to change these permissions. For example, chmod o+r filename will make the file readable for everyone, and chmod o-r filename will make it unreadable for others again. Note that for someone to be able to actually look at the file the directories it is in need to be at least executable.