Thursday, November 2, 2017

Day 5 - Generics

Generics - Basically, Generics allows you to generalize what you put in the data structures. For example, let's take an example of a LinkedList of Integers. We define it as:

LinkedList intList = new LinkedList<>();

Similarly, we define list of Strings as:

LinkedList stringList = new LinkedList<>();

Suppose we create a method printArray() to print the above lists. We do it by creating two methods:

printArray(LinkedList

printArray(LinkedList

Generics allows to have a Generic datastructure in the following way:

private void printArray(E[] argArray){
  for(E element: argArray){
      System.out.println(element);
 }
}

E can be a Integer, String or any other Object. The limitation here is the element of type is E is limited to operations pertaining to Object such as wait(), notify(), hashCode() etc.

If we need to define a Type in a class to be used in the class, they can be defined as:

class Printer { // Define the Type along with class name.
D arr;
public void  printArray(T[] array) {
for(T element: array){
System.out.println(element);
}

}

}


 



Sunday, October 29, 2017

Day 4 - Bubble Sort

Bubble Sort - This is a simple sorting algorithm where elements of an array are swapped until sorting is achieved. It is a very inefficient algorithm. The basic theory behind bubble sorting is take an array of size n; iterate over the list; for each element at index i, if it greater than the element at next index (i+1), swap them. This causes the greater elements to go to the back of the array.

Implementation:
public class BubbleSort {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] a = new int[n];
        for(int a_i=0; a_i < n; a_i++){
            a[a_i] = in.nextInt();
        }
        int swap = 0;
        for(int i=0;i
        for(int j=i+1;j
        if(a[i]>a[j]){
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
        swap ++;
        }
        }
        }
        
        System.out.println("Array is sorted in "+swap+" swaps.");
        System.out.println("First element: "+a[0]);
        System.out.println("Last element: "+a[n-1]);

}

}
 Input: 
3
3 2 1

Output:
Array is sorted in 0 swaps.
First element: 1
Last element: 3

Friday, October 27, 2017

Day 2 - Queues & Stacks

Queues
Queues are data structures that follow the pattern of FIFO(first-in, first-out). It is similar to people standing in a queue. The first person gets serviced first.
The third person gets serviced after the first and second persons.
Similarly, in a queue, to get to the third element, first and second element need to be retrieved.

A simple implementation of a queue.
import java.util.LinkedList;

// Queue operate in FIFO. So, the first element added, gets out first.So, if we have to get the third element,
//we need to remove the first two elements to get to the third element
//Operations of a queue
// Check if queue is empty
// Get size of queue
// Enqueue - Add element to a queue
// Dequeue - Remove element from a queue. Usually the first element gets removed.
// Peek - Get the first element from a queue
public class Queue {
private LinkedList queue;
public Queue(){
queue = new LinkedList();
}

public boolean isEmpty(){
return queue.isEmpty();
}

public int size(){
return queue.size();
}

public void enqueue(int data){
queue.add(data);
}

public int dequeue(){
return (int)queue.remove(0);// When you remove the first element from a linked list, the second element becomes the head.
}

public int peek(){
return (int)queue.get(0);

}
public static void main(String[] args) {
Queue queue = new Queue();
queue.enqueue(5);
queue.enqueue(6);
queue.enqueue(7);
System.out.println("Size of queue:"+queue.size());
System.out.println("First element:"+queue.dequeue());
System.out.println("First element:"+queue.peek());
System.out.println("Second element:"+queue.dequeue());
System.out.println("Third element:"+queue.dequeue());
System.out.println("Is the queue emepty:"+queue.isEmpty());
               System.out.println("Size of queue after dequeuing:"+queue.size());
}

}
Output:
Size of queue:3
First element:5
First element:6
Second element:6
Third element:7
Is the queue emepty:true
Size of queue after dequeuing:0

Java does have a Queue Interface where the above operations as well as some other useful methods are available, which can be implemented using LinkedList. 

The only way to traverse a stack or a queue is to pop/dequeue - which means we remove all the elements in the queue to get to the desired element/index. So, unless we store the dequeued /popped elements in another variable, they will be lost.

Stacks

Stack is a data structure which behaves in the LIFO (last-in, first-out) fashion. 

Taking the example of people standing a queue, the last person who came in, gets serviced first. And the first person gets serviced last. (Sounds weird, isn't it?)

Java already has a built in feature class called stack.

Stack has the following features: 
Push: Push/Inset an element.
Pop: Pop/Remove element
Peek: Returns the first element.

Taking an example:

import java.util.Stack;

public class StackEx {

public static void main(String[] args) {
Stack strStack = new Stack();
strStack.push("Hi ");
strStack.push("There ");
               
 System.out.println("First element/Peek:"+strStack.peek());
System.out.print(strStack.pop());
System.out.println(strStack.pop()+"!");
}

}

Output: 
First element/Peek:There 
There Hi !

The first element pushed into the stack was 'Hi'. But the first element popped out was 'There'. 
Another point is if we do a peek() operation after all the pop operations, it will give an IndexOutOfBoundsException. . Because, just like queues, when all elements are popped, the stack becomes empty. 

Comparing it with Queue. 

public static void main(String[] args) {
Queue queue = new Queue();
queue.enqueue("Hi ");
queue.enqueue("There ");
System.out.print(queue.dequeue());
System.out.println(queue.dequeue()+"!");
}

Output:
Hi There !

The queue pops out in whatever way the elements are inserted into the queue. 

Thursday, October 26, 2017

Day 1 - Linked lists

Linked lists: Linked list is a list data structure where each element basically holds data as well as the reference to the next element.

Each element in a Linked List has two parts - Data (can be an Intger, String, Object) and a reference to the next element. Element of a linked list is also known as a node, perhaps for these reasons.

To define an element in a linked list. 

//Linked list have two things: data and reference to the next node.
// Here 'next' is a reference to the next node and 'data' is the value the node holds.
// 'data' is not limited to being an int. It could be a String, Object, float or any other datatype

public class Node {
Node next;
int data;

public Node(int newData){
data = newData;
}

public Node(Node newNode, int newData){
next = newNode;
data = newData;
}

public Node getNext() {
return next;
}

public void setNext(Node next) {
this.next = next;
}

public int getData() {
return data;
}

public void setData(int data) {
this.data = data;
}
}

To create a linked list data structure - 
import java.util.Scanner;

// Add nodes
// Remove nodes
// IsNodesavailable
// Get data related to a node
public class LinkedList {
static Node head; //First node
static int count; // count - tracks the number of nodes in the linked list

public LinkedList(){
head = null;
count = 0;
}

public LinkedList(Node newNode){
head = newNode ;
count ++;
}

// Add method - Create a new node with the data value as data 
public static Node add(int data){
Node temp = new Node(data);
if(count==0){
head = temp;
}
Node current = head;
while(current.getNext()!=null){
current = current.getNext();
}
if(count>0){
current.setNext(temp);
}
count++;
return head;

}
// Get the data at node 
public int get(int index){
if(index<=0){
return -1;
}
Node current = head;
for(int i=1;i
current = current.getNext();
}
return current.getData();
}

public int size(){
return count;
}

public boolean isEmpty(){
return head==null;
}
// Remove the last node from the list
public void remove(){
Node current = head;
while(current.getNext().getNext()!=null){
current = current.getNext();
}
current.setNext(null);
count--;
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Node head = null;
int N = sc.nextInt();

while (N-- > 0) {
int ele = sc.nextInt();
head = add(ele);
}
display(head);
sc.close();
}

public static void display(Node head) {
Node start = head;
while (start != null) {
System.out.print(start.getData() + " ");
start = start.getNext();
}
}
}

Input 
4 (number of elements in list)
2
3
4
1
Output:
2 3 4 1 

Linked lists over Arrays - In arrays, the elements are indexed. For example, in an array of [2,4,1,5], the element at arr[3] can be easily retrieved. However, in linked list, we need to traverse from the beginning of the linked list. 

So, retrieval of an element in a linked list takes linear time - O(n) 
whereas in an array takes constant time - O(1)

The advantage lies in the fact that insertions  and deletions in a linked list are much quicker. 
Insertion/Deletion at beginning of the linked list or prepend to the linked list - O(1) -- constant time 
Insertion/Deletion at end of the linked list or append to the linked list - O(n) -- linear (as we need to traverse from the beginning till end of the linked list)

Doubly linked list have references to both the nodes/ 

i.e. 
class Node {
   Node prev;
   Node next;
   int data;
}

So, in a doubly linked list, the last node's 'next' reference will null and the first node's 'prev' reference will be null. All other elements in between have 'prev' and 'next' reference. 

In a singly linked list, the last node's 'next' reference will be null.

A brief tutorial is presented in: 
https://www.youtube.com/watch?v=njTh_OwMljA

Courtesy: Hackerrank site

Blogathon - GAJ (Get A Job)

From today, I am going to do a blog-a-thon to track my preparation in getting a job. The topics covered, coding problems attempted, interviews taken up, interview questions attempted, books read, technology covered, etc/ I feel this is the only way to track if my day was really productive or utilized productively. For the almost two months, I have been doing some form of studies. Hope this blog-a-thon brings a structured form.


Tuesday, October 3, 2017

HIbernate Problems & Solutions.

Hibernate: “Field 'id' doesn't have a default value”  - This error came up when a simple insert was tried using HIbernate.

                session.getTransaction().begin();
User user = new User();
user.setBirthDate(new Date());
user.setCreatedBy("ABC");
user.setCreatedDate(new Timestamp(new Date().getTime()));
user.setEmailAdress("abc@gmail.com");
user.setFirstName("ABC");
user.setLastName("DEF");
user.setLastUpdatedBy("SBC");
user.setLastUpdatedDate(new Timestamp(new Date().getTime()));
session.save(user);
session.getTransaction().commit();


Dropped the table 'User' which was created explicitly user DDL scripts and tried to generate it through HIbernate.

Ran the program after dropping the 'User' table in database.
But,the table did not get created in database. 
 
An error came up. Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'User' doesn't exist.

Resolution: Added a line in hibernate.cfg.xml file 

create

This will create table in database using HIbernate as well insert the above row into the table.

The Generation strategy used in User entity class was 
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="USER_ID") 
 private Long userId;

Tuesday, September 5, 2017

WAS - Websphere Application Server - Something something..

Profiles - To create different types of WebSphere Application Server runtime environments, you must install the WebSphere Application Server 6 WebSphere Application Server V8.5 Administration and Configuration Guide for the Full Profile core product files and then create a set of configuration files called profiles.
Application server - The application server is the platform on which Java language-based applications run.
Node - A node is an administrative grouping of application servers for configuration and operational management within one operating system instance.
Deployment manager - The deployment manager is the central administration point of a cell that consists of multiple nodes and node groups in a distributed server
configuration.
Node agent - In distributed server configurations, each node has a node agent that works with the deployment manager to manage administration processes.
Cell - A cell is a group of nodes in a single administrative domain.
Administrative agent - An administrative agent is a component that provides enhanced management capabilities for multiple stand-alone application servers.
Job Manager - The job manager is a component that provides management capabilities for multiple stand-alone application servers, administrative agents, and deployment manager.

How to start websphere server

1: Start DeploymentManager
E:\IBM\WebSphere\AppServer\profiles\Dmgr02\bin>startManager.bat

2: Start Node
E:\IBM\WebSphere\AppServer\profiles\Node02Profile\bin\startNode.bat

3: Start BPM Server.[Optional - Only if required]
E:\IBM\WebSphere\AppServer\profiles\Node02Profile\bin>startServer.bat server1

(use admin/admin for any prompt)

4: Start AppServer.
E:\IBM\WebSphere\AppServer\profiles\AppSrv02\bin>startServer.bat server1

5: To Start queues [If queues need are available]
E:\IBM\WebSphere MQ\bin\strmqm
To End queue
E:\IBM\WebSphere MQ\bin>endmqm
To Open MQ Explorer
E:\IBM\WebSphere MQ\bin>strmqcfg

Wednesday, August 30, 2017

Debug mode in WAS


1) Go to http://localhost:9060/ibm/console
2) Servers --> Server Types --> Web Application Servers --> server1
3) Click on server1. Click on the 'Configuration' tab. Under Additional Services --> Click on  Debugging Service.
4) Ensure 'Enable service at server startup' ic clicked. The remote debug port would be port number as in 'JVM debug port'.

Saturday, August 26, 2017

DB2 Nitty Gritty Stuff

To change a column name of a table:

ALTER TABLE SCHEMANAME.TABLENAME RENAME COLUMN OLDCOLUMNNAME TO NEWCOLUMNNAME;

To take a DB backup:

db2stop force
db2start
db2 CONNECT TO DATABASENAME USER username USING password
db2 QUIESCE DATABASE IMMEDIATE FORCE CONNECTIONS
db2 CONNECT RESET
db2 BACKUP DATABASE DATABASENAME COMPRESS


Tip: SQL1035N  The operation failed because the specified database cannot be
connected to in the mode requested.  SQLSTATE=57019
If during database backup, if the above error comes up, check if any application server is accessing database or shut down any application server that can use database.


To restore a database backup:

db2> restore database DBNAME FROM D:\db_dump ON D:\ into DBNAME without prompting
D:\db_dump\DBNAME.0.DB2.DBPART000.20160610133049.001

DBNAME in bold is used in the above query

If the above command doesn't work.


1. Open Command as Administrator
2. Run the command runas /profile /user:machinename\dbadminuserid cmd
3. Enter the database password: dbadminpassword
4. Change to DB2 install location: [C:\Program Files\IBM\SQLLIB\BIN]
5. Run db2cwadmin.bat
6. Change directory to db_dump

7. Execute the above restore command.

Note: dbadminuserid must have been added in Windows user accounts [Control panel --> User Accounts]

To find database version:

db2> db2level

To verify if DB2 license is expired or not:

db2> db2licm.exe –l

To renew DB2 license, 
Open command prompt and change directory to the file location, where db2 license is stored. [db2ese_u.lic is the license file]

db2> db2licm -a db2ese_u.lic

To drop a database

db2> drop database DATABASENAME  

To list all the databases

 db2>list database directory

To drop a column from the table

db2> ALTER TABLE TABLENAME DROP COLUMNNAME

If after an alter script, the following error comes up
DB2 SQL Error: SQLCODE=-668, SQLSTATE=57016, SQLERRMC=7;xxx.xxx, DRIVER=3.69.24 [SQL State=57016, DB Errorcode=-668]
This error means access to the database is restricted.
Execute the following query to resolve the error:

db2> REORG TABLE TABLENAME

To create a new database

db2> create database NEWDATABASENAME

To disconnect from the current database

db2> disconnect DATABASENAME
To find the current database connected to the database.
db2> SELECT CURRENT SERVER FROM SYSIBM.SYSDUMMY1

Tuesday, July 11, 2017

When Eclipse doesn't startup...

On clicking on Eclipse.exe, if it doesn't startup, then delete the file "workbench.xmi" under \.metadata\.plugins\org.eclipse.e4.workbench.
Then, try to restart, Eclipse usually starts up.