Thursday, July 1, 2021

Python - Exception handling

There are many built in exceptions which are raised in python when something goes wrong. Exceptions in python can be handled using a try statement. The code that handles the exception is written in the except clause.

try:

    #code

except Exception as e:

    print(e)

when the exception is handled the code flow continues without program interruption.

try:

    #code

except ZeroDivisionError:

    #code

except TypeError:

    #code

except:

    #code

Raising Exceptions:

We can raise custom exceptions using the raise keuword.

try with else clause:

sometimes we want to run a piece of code when try was successful.

try:

    #code

except:

    #code

else:

    #code

try with finally:

python offers a finally clause which ensures execution of a piece of code irrespective of the exception.

try:

    #code

except:

    #code

finally:

#code

if __name__ = '__main__':

__name__ evaluates to the name of the module in python from where the program is run. if the module is being run directly from the cmd line the __name__ is set to string "__main__".

thus this behaviour is used to check if the module is run directly or imported to another file.

Global keyword:

global keyword is used to modify the variable outside of the current scope.

enumerate function:

It adds counter to an iterable and returns it.

for i,item in enumerate(list1):

    print(i,item)

list comprehensions:

It is an elegant way to create lists based on existing lists.

list1=[1,7,12,11,22]

list2=[i for item in list1 if item >8]


Practice:

Write a program to open 3 files 1.txt,2.txt and 3.txt.if any one of the files do not present then a message without exiting the program must be printed prompting the same.

def readFile(fileName):
    try:    
        with open(fileName,'r'as f:
            print(f.read())
    except:
        print(f"the file {fileName} does not exist")


readFile("1.txt")
readFile("2.txt")
readFile("3.txt")       


WAP to print 3rd,5th and 7th element from a list using enumerate function.

myList=[1,2,3,4,5,6,7,8,8,9,10]

for i,item in enumerate(myList):
    if i==2 or i==4 or i==6:
        print(f"the {i+1} element is {item}")


Write a list comprehension to print a list which contains the multiplication table of a user entered number.


numint(input("Please enter a number: "))

table = [num*i for i in range(1,11) ]
print(table)

WAP to display a/b  where a and b are integers. if b=0, display infinite by handling the ZeroDivisionError.

aint(input("Please enter 1st number: "))
bint(input("Please enter 2nd number: "))

try:
    print(a/b)
except ZeroDivisionError:
    print("Infinite")
except Exception as e:
    print(e)
finally:
    print("Thanks!")



Wednesday, June 30, 2021

Python - Inheritance & more on OOPs

 Inheritance is a way of creating a new class from an existing class.

Syntax:

class Emoloyee: #Base Class

#Code

class Programmer(Employee): #Derived or child class

#Code

We can use the methods and attributes of Employee in Programmer object. Also, we can overwrite or add new attributes and methods in the Programmer class.


Type of Inheritance:

  • Single inheritance
  • Multiple inheritance
  • Multilevel inheritance

Single Inheritance

Single inheritance occurs when child class inherits only a single parent class.

Base -> Derived


Multiple Inheritance:

Multiple inheritance occurs when the child class inherits from more than one parent class.

Multilevel Inheritance

When a child class becomes a parent for another child class.


Super() method

Super method is used to access the methods of a super class in the derived class.

super().__init__()  #Calls constructor of the base class


Class methods

A class method is a method which is bound to the class and not the object of the class.

@classmethod decorator is used to create a class method.

Syntax to create a class method:

@classmethod

def (cls, p1, p2):

#code

@property decorators

Consider the following class

class Employee:

@property 

def name(self):

return self.ename

if e = Employee() is an object of class employee, we can print (e.name) top print the ename/call name() function.


@.getters and @.setters

The method name with @property decorator is called getter method.

We can define a function + @name.setter decorator like below:

@name.setter

def name(self, value):

self.ename = value

Operator overloading in Python

Operators in python can be overloaded using dunder methods.

These methods are called when a given operator is used on the objects.

Operators in python can be overloaded using the following methods:

p1 + p2 -> p1.__add__(p2)

p1 – p2 -> p1.__sub__(p2)

p1 * p2 -> p1.__mul__(p2)

p1 / p2 -> p1.__truediv__(p2)

p1 // p2 -> p1.__floordiv__(p2)

Other dunder/magic methods in Python

__str__() -> used  to set what gets displayed upon calling str(obj)

__len__() -> used to set what gets displayed upon calling .__len__() or len(obj)

 

Practice:

Create a class C-2d vector and use it to create another class representing a 3-d vector.

class C2dVec:
    def __init__(selfij):
        self.icap = i
        self.jcap = j

    def __str__(self):
        return f"{self.icap}i + {self.jcap}j"

class C3dVec(C2dVec):
    def __init__(selfijk):
        super().__init__(ij)
        self.kcap = k
    
    def __str__(self):
        return f"{self.icap}i + {self.jcap}j + {self.kcap}k"
    
    
v2d = C2dVec(13)
v3d = C3dVec(197)
print(v2d)
print(v3d)

Create a class pets from a class Animals and further create class Dog from Pets. Add a method bark to class Dog.

class Animals:
    color = "White"

class Pets(Animals):
    @staticmethod
    def sleep():
        print("Pets are sleeping")


class Dog(Pets):
    
    @staticmethod
    def bark():
        print("Dog is barking Bow Bow")

d = Dog()
print(d.color)
d.sleep()
d.bark()

Create a class Employee and add salary and increment properties to it.

Write a method SalaryAfterIncrement method with a @property decorator with a setter which changes the value of increment based on the salary.

class Employee:
    salary2000
    increments=1.5

    @property
    def salaryAfterIncrements(self):
        return self.salary * self.increments

    @salaryAfterIncrements.setter
    def salaryAfterIncrements(selfsal):
        self.incrementssal / self.salary

e = Employee()
print(e.salaryAfterIncrements)
print(e.increments)
e.salaryAfterIncrements=5000
print(e.salaryAfterIncrements)
print(e.increments)

Write a class complex to represent complex numbers, along with overloaded operators + and * which adds and multiplies them.

class Complex:
    def __init__(selfij):
        self.i =i
        self.j=j
    
    def __add__(self,obj2):
        return Complex(self.i + obj2.i, self.j + obj2.j)
    def __str__(self):
        return f"{self.i} + {self.j}i"
c1=Complex(2,3)
c2=Complex(3,4)
print(c1 + c2)



Thursday, June 24, 2021

OIC - pgp tool to encrypt or decrypt the file

Object: Pgp tool is used to encrypt or decrypt any file. Suppose your integration is handling or sending  any encrypted file to endpoint and there is any issue occured in the file data, so we may need to check the file contents, using the pgp key we can easily decrypt the file with this pgp tool and debug the issue.

Download links:

Go to below link or search in google with pgp key

https://pgptool.github.io/

Download the installer package or zip package as per your convenient.

One more thing, to run this tool we need to install java jdk 1.8.0 version.

Go this below link or search in google.

https://java.com/en/download/


After installation

open the pgp tool and go to keyring tab and use import pgp key to import the pgp key and then click encrypt or decrypt.



Monday, June 21, 2021

OIC JS - return today's date in yyyymmdd format

 Js codes:

function returnMultiPeriodDate(){

var today = new Date();

var dd = today.getDate();

var mm = today.getMonth() + 1;

var yyyy = today.getFullYear();

if (dd <10){

dd = '0' + dd;

}

if (mm < 10) {

mm = '0' + mm;

}

today = yyyy + '0' + mm;

return today;

}


Note:

today = yyyy + mm + dd; 

OIC JS - return last day

Object: Return last day of the month in this format yyyy-mm-dd

Js codes:

function returnLastDay(){

var date = new Date(), y = date.getFullYear(), m = date.getMonth();

var lastDate = new Date(y, m + 1, 0);

var day = lastDate.getDate();

var month = lastDate.getMonth() + 1;

var year = lastDate.getFullYear();

if ( parseInt(month) < 10 ) {

var newMonth = "0" + month;

}

else { 

var newMonth = month;

}

if ( parseInt(day) < 10 ) {

var newDay = "0" + day;

}

else { 

var newDay = day;

}

var lastday = year + "-" + newMonth + "-" + newDay;

return lastday;

}


Note

getMonth() method returns the months from 0 to 11. January is the 0 and February is 1 and so on...

firstDay = new Date(y, m, 1)

lastDay = new Date(y, m+1, 0)




Tuesday, June 8, 2021

OIC - NVL in javascript

NVL lets us to replace null (returned as blank) with a string in the results of a query. For example, 

NVL(value1, value2)

If value1 is null then it will be replaced with value2.


Javascript:

function nvl(value,nullValue){

var output = "";

if (value == null || value == "")

{

output = nullValue;

}else {

output = value;

}

return output;

}

Monday, June 7, 2021

OIC - send Notification - email, log file and create incident

Usecase: Here, we will create a reusable component "Notification service" and we will perform following functions:

  • Send Email
  • Create Incident
  • LogFile
Rest Request Json:
{
"sendEmailFlag": "Y",
"emailFrom": "",
"emailSubject": "",
"emailBody": "",
"attachmentFlag": "",
"attachmentBase64Reference": "",
"createIncidentFlag" : "",
"incidentCallerId" : "",
"incidentBusinessService" : "",
"incidentCategory" : "",
"incidentSubcategory: "",
"incidentContactType": "",
"incidentShortDescription" : "",
"incidentDescription" : "",
"createLogFileFlag" : "",
"directoryAdaptet" : "",
"logDescription" : "",
"logFileName" : ""
}

Response rest Json:

{
"emailSent" : "",
"incidentCreated" : "",
"incidentId" : "",
"logCreated" : "",
"ExceptionCode" : "",
"ExceptionReason" : "",
"ExceptionDetails" : ""
}

To send email:

  • Create a app driven integration and take body scope
  • Within the body, take a switch block and check if sendEmailFlag = "Y" then 
  • Take a stage action and write a file for the attachment.
  • Take a notification action and provide all details like emailFrom, emailSubject, create a EMAIL_BODY param and assign with emailBody and use in the body section with {EMAIL_BODY}.
  • In the attachment section, add the write file reference. Or use decodebase64ToReference() to convert the feeded attachment base64 to reference.
  • Update the emailsent response as "Y"

To Log file:

Here i will log the zip file in the S3 bucket using rest call.
  1. First create a rest S3 connection using
    1. rest api base url like https://hostname, 
    2. security as aws Signature version 4 and
    3.  access key, secret key, aws region like US West(Oregon) Region (us-west-2) and service name Amazon S3.
  2. In the integration, check if createLogFlag = "Y" then , write the log file using stage action. Provide file name, output directory,provide a csv file etc and in the map, assign log description.
  3. Zip the file. Provide logFileZipName and directory to zip and output directory.
  4. Configure the S3 rest connection and provide 
    1. relative url as /{pathAndFileName}, 
    2. verb put ,  
    3. provide request payload as Binary and media type of the request body as application/zip.
    4. In the map, assign pathandFilename to template param and zip reference to stream reference.
    5. Update that log created = Y

To create Incident:

  1. As service now is a rest service so first create a rest incident service connection using base API base URI, basic authentication and provide user and password.
  2. Use that connection  and configure in the integration and
    1.  provide relative uri "/api/now/table/incident" in this case, 
    2. verb as post
    3. Provide request and response JSON sample payload
    4.  then map the request payload.


Featured Post

11g to 12c OSB projects migration points

1. Export 11g OSB code and import in 12c Jdeveloper. Steps to import OSB project in Jdeveloper:   File⇾Import⇾Service Bus Resources⇾ Se...