Oct 21, 2017

Textual description of firstImageUrl

Factory and Decorator in AngularJS

Factory pattern is very ubiquitous design pattern which finds its uses in most of the design strategy. In this post we will use factory with Decorator and demonstrate - how decorator can be used along side of factory and provide extra functionality without disturbing cleanness of factory.

We will take user input and in return displays reversed output of that input string. Factory comes into picture to give an instance which contains getter and setter method. We define decorator for this Factory instance and reverse input string set via setter method.

Script for Factory and Decorator:


'use strict'

var app = angular.module('DecoratorApp', []);

app.controller("decoratorController", function($scope, reverseFactory) {
 $scope.reverseCall = function() {
  reverseFactory.setData($scope.inputVal);
  reverseFactory.reverse();
  $scope.outputVal = reverseFactory.getData();
 }
});

app.factory('reverseFactory', function() {
 var myPrivateData;
 return {
  getData : function() {
   return myPrivateData
  },
  setData : function(data) {
   return myPrivateData = data
  }
 }
})

/* Decoration created for factory reverseFactory */
app.config(function($provide) {
 $provide.decorator('reverseFactory', function($delegate) {
  $delegate.reverse = function() {
   $delegate.setData($delegate.getData().split('')
     .reverse().join(''))
  }
  return $delegate
 })
})

HTML for input and output  :
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Filter application</title>
</head>
<body ng-app="DecoratorApp" ng-controller="decoratorController" ng-cloak>
 <div class="mainBody">
  <div class="mainBodyMinHeight">
   <img ng-src="https://toddmotto.com/img/tags/angularjs.svg"
    height="100px">
   <p>
    <label>Input String: </label>
   </p>
   <div flex="100">
    <input type='text' ng-model="inputVal" ng-blur="reverseCall()" />
   </div>
   <hr />
   Reversed String:
   <div flex="100">
    <p>{{outputVal}}</p>
   </div>
  </div>
 </div>
 <script
  src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/
 1.4.3/angular.min.js"></script>
 <script src="scripts/decoratorApp.js"></script>
</body>
</html>

Output:-



Download complete source code.

Oct 20, 2017

Textual description of firstImageUrl

Custom filter in Angular : How to write a custom filter in AngularJS

Angular provides filtering capability which can be converting string from lower case to uppercase, converting time to Date or Sort(increasing or decreasing) an array based on some attributes. In this post we will see how to write custom filter - Filtering array elements based on some condition and show filtered elements in view.

Suppose we have an Employee model which contains name, salary, Address and phone. We have a grid showing all the fields in UI. We want to write a filter in Angular which shows employees with salary greater than input value in text field.

Data model:

{
    name : "Nikhil",
    address : "Hyderabad",
    Phone : "9988776655",
    salary : 3500,
    imgUrl : "img/1.ico"
}

We are writing filter below based on salary, if input is passed filter will use it else it will use default value as 4400 hardcoded inside filter function. This filter return a function which internally prepare a filtered array.

Filter Script: 

/*
 * custom filter returing a function,if salary is not passed default value 4400
 * is used.
 */
app.filter('salaryFilter', function() {
 return function(empAll, salaryRange) {
  var filteredEmp = [];
  debugger;
  if (!salaryRange) {
   salaryRange = 4400;
  }
  for (i = 0; i < empAll.length; i++) {
   var emp = empAll[i];
   if (emp.salary >= salaryRange)
    filteredEmp.push(emp);
  }
  return filteredEmp;
 }
})


HTML part ng-repeat with model and filter
:

<div
    ng-repeat-start="emp in employeeArray.myarr|salaryFilter:inputVal.salary"
    layout-align="left center" layout-padding>
    <div class="productImgAndText">
        <div class="orderDetailsText">
            <div>
                <img ng-src="{{emp.imgUrl}}" width="60px">
            </div>
            <div>
                <h5>{{emp.name}}</h5>
                <h5>Address and Phone</h5>
                <p>
                    <strong>{{emp.address}}</strong>
                </p>
                <p>
                    <strong>{{emp.phone}}</strong>
                </p>
                <h5>Salary</h5>
                <p ng-class="{blueText : $index == 1}">{{emp.salary}}</p>
            </div>

        </div>
    </div>
</div>
<hr ng-repeat-end />

Here inputVal.salary in filter is bind with input text from where we pass salary based on which filter computes and prepare filtered array.


Below is screenshot attached with input and filtered output.


Download complete source code.

Jul 26, 2017

Walmart Labs Interview Experience (6 Years experience in Java Development Stack)

Posting on behalf of my friend.

I applied in Walmart Labs through employee referral, next day got call from HR and asked me to brief about my work and how much I am interested in relocating Bangalore. He informed they will schedule interview (Telephonic) next week.Whole interview process took one week to complete - 2 Telephonic followed by 5 F2F discussion.

2 Telephonic Technical Discussion


1st Webex/Telephonic discussion (DS Questions)

  1. Find one triplet such that indexes are in increasing order so as values at index.
     http://www.geeksforgeeks.org/find-a-sorted-subsequence-of-size-3-in-linear-time/
    Follow up question to Optimize using one array since we have to find only one triplet not all. 
  2. Find all nodes at distance k from a target node.
    http://www.geeksforgeeks.org/print-nodes-distance-k-given-node-binary-tree/

2nd Webex/Telephonic discussion (DS and Design Questions)

  1. Design a stack such that it provides push(), pop() and min( ) is in O(1). Use only Stack not any other Data structure.http://www.geeksforgeeks.org/design-and-implement-special-stack-data-structure/
  2. Design a app for "Restaurant table booking" :
    - Database Design (Various tables involved) and how they are related (UML/ER Diagram)-
    - What are APIs need to be exposed at high level
    - Flow of application
    - More stress on booking efficiently and
    - Handling various scenarios like how to maintain empty & vacant seats for multi-storage  building of Hotels with tables. 
Received feedback by next day and was asked to come for F2F discussion.They provided flight tickets. It was one day event. Started early morning 6:00 AM from Hyderabad and came back Hyderabad by 11:30 PM. I had 5 F2F technical discussions at Walmart Labs office in Bangalore. 

5 F2F Technical Discussion

1st F2F discussion (Java/DS/Projects) :
  1. Project detailed discussion - In depth discussion of project I was working and my contribution.
    - Why this and that ?
    - Some other way to do ?
  2. Java Wrapper Class related question. What is importance of Wrapper class in Java ?
  3. Immutable class in Java and what is its significant in java ?
  4. Singleton class discussion and sample code.
    - Lazy and Early Initialization of Singleton
    - Double Checked locking sample code.
    - Holder pattern to create Singleton instance 
  5. Files with multiple lines -  two words passed as input. Find min distance between them
  6. Binary tree horizontal distance based question- print all nodes in sorted order of hd. i.e: Nodes at Horizontal distance: -3 -2 -1 0 1 2 3 (Used TreeHashmap instead of HashMap)
    http://www.geeksforgeeks.org/print-binary-tree-vertical-order-set-2/
2nd F2F discussion (DS/Resume scanning) 
  1. Write sample code to generate all permutation of a given string.
    - Idea was to do iteration of all recursion and 
    makes sure no mugged up.
    http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
  2. Find Longest palindrome in a string - Brute force solution to DP solution.
    http://www.geeksforgeeks.org/longest-palindrome-substring-set-1/
  3. Resume scanning understand where I have used which technologies
3rd F2F discussion (Java/DS) 
  1. Brief overview of  project I am working on and some questions related to it. I mentioned, I have written parser for SQL Server using javacc and it uses Tree DS for iteration of nodes. Next question from DS.  
  2. Find max sum at given level in given binary tree. (Level order traversal) 
  3. Find sum of all nodes at given Horizontal distance. Display in descending order(HD: 4 3 2 1 0 -1 -2 ...) 
  4. Regex implementation - match test or te*t or t?*t
    http://www.geeksforgeeks.org/wildcard-pattern-matching/
  5. Java memory model changes in Java 8 - metaspace concept. What's its benefit ?
    https://stackoverflow.com/questions/27131165/what-is-the-difference-between-permgen-and-metaspace
  6. What is Weak Reference - I was not good with answer for this question.
    https://docs.oracle.com/javase/7/docs/api/java/lang/ref/WeakReference.html
  7. What are other technology I have worked and where.
    - Spring AOP - Duck for me. Not worked with Spring 
  8. Design pattern I have used and where. Also what are DP I know. 
  9. Project which have done with good effort or some situation like this.
  10. Java provides some security mechanism to prevent attack via reflection- I could not answer properly. He was referring my blog, since I have written how to break singleton using Reflection. 
4th F2F discussion (Design / Problem solving) 
  1. Project discussion and my contribution to it.
  2. Design a inventory system.
    - High level system design considering scalability and performance.
    - Discussion of distributed cache and how it's used.
    - Significance of Load balancer and its usages.
    - Database design,
    - How to achieve database abstraction (Today Relational DB, tomorrow may be NOSQL). 
  3. How to handle large volume traffic request ? 
  4. Some questions related to thread dump and profiling. 
  5. A problem to solve - one XML is given with order nodes. Display sorted nodes based on id followed by order name.- I gave brute force solution.
    Restriction imposed : Not to use collection API for sort and No comprator. 
5th F2F discussion (Design / Distributed systems round/Abstract Questions) 
  1. Project where you have worked makes you feel proud and follow up question regarding effort and code lines.
  2. Design a multi-threaded system which handles failure request, failure requests are updated in database.
    - My solution was to find hashcode of time-stamp of record and distribute failed record to multiple threads, a thread pool is maintained for specified number of thread.
  3. Next question what about if multiple servers are in picture - how to send request to handle by multiple server thread pool .
    -I suggested to use a load balancer and does pull request - read record from db and send to multiple server so not same record sent to two server.
  4. What is Implicit and explicit locking. How manual works for threads? Interfaces and  Class used for implementing explicit locking. 
  5. Design of distributed locking.
    - I suggested file based locking mechanism, jvm to jvm communication.
    - He asked what about db based locking. Could not explain properly. 
  6. How to design a system such that - one type(kind/somePK) of data is always updated in sequence no dirty update.
    - I suggested map-reduce approach.
    - Time-stamp based approach.
Ahhhhh !!! Finally, Time to leave. Exhausted !!

May 29, 2017

How to exploit Singleton class with Reflection API and Its prevention

Singleton design pattern is intended to create only one instance of given class in context of given class loader (class loader which loads this given class). i.e: One instance per class loader. This post will discuss how to exploit a Singleton class with Reflection API and create multiple instance of that class followed by how do we resolve it.

Below is a singleton class with instance created while class is loaded in JVM by a class loader.
class SingletonBreakable {

 private static final SingletonBreakable INSTANCE = new SingletonBreakable();

 private SingletonBreakable() {
  // No object creation allowed from outside world
 }

 public static SingletonBreakable getInstance() {
  return INSTANCE;
 }

 public Object clone() throws CloneNotSupportedException {
  throw new CloneNotSupportedException(
    "Cannot clone instance of this class");
 }

 public void display() {
  System.out.println("Hello from SingletonBreakable");
 }
}

In order to prevent multiple object creation, above class provides private constructor and it looks logical. But Java provides reflection API with we can create Multiple instance of this class and it breaks Singleton goal of creating only one instance of given class.

Lets use reflection API and try to create multiple object. Below sample class makes private constructor accessible using Reflection API and create another object from outside (other than provided by Singleton class SingletonBreakable)
package javacore;

import java.lang.reflect.Constructor;

public class SingletonBreakableClinet {

 /**
  * @param args
  */
 public static void main(String[] args) {
  /*
   * 1.Execute display method using default object provided by
   * SingletonBreakable and display hashCode too.
   */
  SingletonBreakable sb1 = SingletonBreakable.getInstance();
  System.out.println("Hashcode of original object is  " + sb1.hashCode());
  sb1.display();

  /*
   * 2. Use reflection to create duplicateObject and display its hashCode.
   */
  SingletonBreakable sb2 = createObjetUsingRefletion();
  System.out.println("Hashcode of Duplicate Object is  " + sb2.hashCode());
  sb2.display();
 }

 public static SingletonBreakable createObjetUsingRefletion() {
  SingletonBreakable sb = null;
  try {
   Constructor<SingletonBreakable> constructor = SingletonBreakable.class
     .getDeclaredConstructor(new Class[0]);
   constructor.setAccessible(true);
   sb = constructor.newInstance();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return sb;
 }
}

Sample Output:-

Hashcode of original object is 576315909
Hello from SingletonBreakable
Hashcode of Duplicate Object is  990234593
Hello from SingletonBreakable

Hashcode of both object is different, it indicates we are able to create multiple object using reflection. It breaks Singleton contract and claim to create Just one instance of this class with respect of one class loader.

How to prevent reflection to create multiple instance of Singleton ? 

Instead of creating a empty private constructor, we need to throw exception from it, if instance is already created (which will be always created as class is loaded). So modified class is:

class SingletonThrowException {

 private static final SingletonThrowException INSTANCE = 
   new SingletonThrowException();

 private SingletonThrowException() {
  if (INSTANCE != null) {
   throw new IllegalStateException("Already instantiated");
  }
 }

 public static SingletonThrowException getInstance() {
  return INSTANCE;
 }

 public Object clone() throws CloneNotSupportedException {
  throw new CloneNotSupportedException(
    "Cannot clone instance of this class");
 }

 public void display() {
  System.out.println("Hello from SingletonThrowException "); }
}

 We have added a check in above constructor, if we will try to create instance of this class, exception will be thrown and object creation will not be successful. Now we try to create duplicate object and validate the modification.


package javacore;

import java.lang.reflect.Constructor;

public class SingletonUnbreakableClinet {
 public static void main(String[] args) {
  /*
   * 1.Execute display method using default object provided by
   * SingletonBreakable and display hashCode too.
   */
  SingletonThrowException sb1 = SingletonThrowException.getInstance();
  System.out.println("Hashcode of original object is  " + sb1.hashCode());
  sb1.display();

  /*
   * 2. Use reflection to create duplicateObject and display its hashCode.
   */
  SingletonThrowException sb2 = createObjetUsingRefletion();
  if (sb2 != null)
   System.out.println("Hashcode of Duplicate Object is  "
     + sb2.hashCode());
  else
   System.out.println("Object creation failed !!");
 }

 public static SingletonThrowException createObjetUsingRefletion() {
  SingletonThrowException sb = null;
  try {
   Constructor<SingletonThrowException> constructor = 
     SingletonThrowException.class
     .getDeclaredConstructor(new Class[0]);
   constructor.setAccessible(true);
   sb = constructor.newInstance();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return sb;
 }
}

Sample Output:-

Hashcode of original object is  1486987673
Hello from SingletonThrowException

java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at javacore.SingletonUnbreakableClinet.createObjetUsingRefletion(SingletonUnbreakableClinet.java:32)
at javacore.SingletonUnbreakableClinet.main(SingletonUnbreakableClinet.java:18)
Caused by: java.lang.IllegalStateException: Already instantiated
at javacore.SingletonThrowException.<init>(SingletonThrow.java:56)
... 6 more
Object creation failed !!

Here only one instance of object is created and  when reflection API tries to create an instance it fails. so in this way we can prevent Object creation using reflection API. 

Summary :- "Always throws Exception from private constructor in the case of Singleton class."

May 27, 2017

Interview Experience at Teradata Hyderabad - Senior software engineer

Posting on behalf of my friend

Round-1:
This round was all about thread followed by some puzzle and java concept!!
Q1. It started with couple of basic questions about threads.

Q2. Sample code how do we achieve threading in java - Implementing Runnable/Extending thread.
As a follow-up start two thread and how to make main thread wait till these two threads done with its task execution - Concept of join.
What are other ways we can do it - With Countdown latch.

Q3. What is cyclic barrier and what's its uses.

Q4. Write sample code for simulating Producer-consumer problem.
Quick question related to wait()/notify()

Q5. Attributed involved in - system.out.println().
 As a followup question, In java how to redirect console output to file ?

Q6. What are design patterns I am aware of - list down all what I know and uses with example, what I have used.

Q7. Display spiral matrix of order nxn.

Q8. Puzzle: Bridge and torch problem

Round-2: It was all about Data structures and Internals of Java collections
Q1. Find distinct element in an array with repeated elements.

Q2. Find two elements in array with sum k. (Naive  and O(n) solution)

Q3. Find two elements in BST with sum k.

Q4. Discussion about HashMap and its implementaion. How we can modify this implementation of adding entry in case of collision - using BST instead of List. How does it affect complexity and all.

Round-3: Design patterns - this time not what I know. A problem was given and solve using Design patterns I know.
Q1. Design a client/server communication with following details.
Server does send and receive functionality.
Client can be of multiple types,in future multiple clients can be added in system

Q2. How to check whether one instance of java program/application is already running. if already running, do not allow to run same application again. Reference1 and Reference2

Round-4: Honest resume writing check.
Q1. What projects I have done. How much work I did ?
Q2. What was goal of doing that project ?
Q3. Summarise your carrier path what are you good at ?
Q4. Some basic question about micro-services. (It was not in my resume, popped up in discussion)
Q5. Here it comes the most difficult question I was waiting for - why I am looking for change ?

Round-5 : HR round, needless to say. it was typical HR round starting from class 10th and all.
I could not answer - any weakness which you want to improve ?
What is your current and expectation - this I answer loudly with word negotiable.
All done. We will communicate you after internal discussion.

May 22, 2017

Write an algorithm that collapses a list of Iterators into a single Iterator - Java Program

Write an algorithm that collapses a list of Iterators into a single Iterator. 

package javacore;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class CollapseIterators {
 /**
  * @param args
  *            Write an algorithm that collapses a list of Iterators into a
  *            single Iterator.
  */
 public static void main(String[] args) {
  final Iterator<Integer> a = Arrays.asList(1, 2, 3, 4, 5).iterator();
  final Iterator<Integer> b = Arrays.asList(6).iterator();
  final Iterator<Integer> c = new ArrayList<Integer>().iterator();
  final Iterator<Integer> d = new ArrayList<Integer>().iterator();
  final Iterator<Integer> e = Arrays.asList(7, 8, 9).iterator();

  final Iterator<Integer> singleIterator = singleIterator(Arrays.asList(
    a, b, c, d, e));
  if (null != singleIterator && singleIterator.hasNext()) {
   System.out.println("Single Iterator obtained!!");
   while (singleIterator.hasNext()) {
    System.out.println(singleIterator.next().toString());
   }
  } else {
   System.out.println("Single Iterator did not obtained");
  }
 }

 public static <T> Iterator<T> singleIterator(
   final List<Iterator<T>> iteratorList) {
  ListIterator<T> it = new ListIterator<>(iteratorList);
  return it;

 }
}

class ListIterator<T> implements Iterator<T> {
 // Field
 private final Iterator<Iterator<T>> listIterator;
 private Iterator<T> currentIterator;

 // Constructor: make list iterator into Iterator<iterator>>
 public ListIterator(List<Iterator<T>> iterators) {
  this.listIterator = iterators.iterator();
  this.currentIterator = listIterator.next();
 }

 @Override
 public boolean hasNext() {
  // CurrentIterator has no next
  if (!currentIterator.hasNext()) {
   // set up next iterator as currentIterator
   if (!listIterator.hasNext())
    return false;
   currentIterator = listIterator.next();
   // NOTE: recurse to check if next still has no next
   hasNext();
  }

  return true;

 }

 public T next() {
  hasNext();
  return currentIterator.next();
 }

 // public boolean remove()
 public void remove() {
  hasNext();
  currentIterator.remove();
 }
}

Sample Output:-
 
Single Iterator obtained!!
1
2
3
4
5
6
7
8
9

Problem reference: "Java Programming Interviews Exposed"

Related Question:
How can we achieve this behaviour using Google Guava collections framework ?

May 2, 2017

Textual description of firstImageUrl

Linear classifier using least square approach in Pyhton

Sample Data:-  Use following data set 1 and data set-2 for classifier using least square approach
Data Set -1
Data Set -2

Problem statement 
:- Sample program to find the linear classifier using least square approach.

import sys
import matplotlib.pyplot as plt
import pylab as pl
import numpy as np

def getMultiplePoints(x,y,weight,boundX1,boundX2):
 x1 =[x,0]
 x2 =[0,y]
 pointsX = []
 pointsY = []
 pointsX.insert(1,y)
 pointsX.insert(2,0)
 pointsY.insert(1,0)
 pointsY.insert(2,x)
 #for boundX1
 pointsX.insert(0,boundX1)
 temp = -(weight[0]*boundX1 + weight[2])/weight[1]
 pointsY.insert(0,temp)
 #for boundX2
 pointsX.insert(3,boundX2)
 temp = -((weight[0]*boundX2) + weight[2])/weight[1]
 pointsY.insert(3,temp) 
 return (pointsX,pointsY)

#plot points 
def getCoordinatesList(dataset,weightPlot):
 XList1 =[]
 YList1 =[]
 XList2 =[]
 YList2 =[] 
 count = 0
 boundX = -4
 boundY =  4
 #compute classifier co-ordinates
 x1 = - (weightPlot[2]/weightPlot[1])
 y1 = 0
 x2 = 0
 y2 = - (weightPlot[2]/weightPlot[0])
 itr = len(dataset)/2
 # compute some random point with slope as W and bias b 
 plotTup = getMultiplePoints(x1,y2,weightPlot,boundX,boundY)
 for row in dataset:
  if(count< itr):
   XList1.append(row[0])
   YList1.append(row[1])
  else:
   XList2.append(row[0])
   YList2.append(row[1])
  count = count+1
 return (XList1, YList1,XList2, YList2,plotTup)

def plotDataPointsAndClassifier(plotData,weightPlotLS):
 boundX = -4
 boundY =  4
 colorLS = 'black'
 (XList1, YList1,XList2, YList2,plotTupLS) =
  getCoordinatesList(plotData,weightPlotLS)
 #Draw points with red and Blue color 
 plt.plot(XList1, YList1, 'ro',XList2, YList2, 'bo')
 plt.axis([boundX, boundY, boundX, boundY])
 plt.plot(plotTupLS[0],plotTupLS[1],color = colorLS,label='Least Square')
 plt.legend(loc='best') 
 plt.show()
 
def compute(row, weights):
 bias = weights[2]
 output = bias
 for i in range(len(row)-1):
  output += weights[i] * row[i]
 if row[2] == 1 and output > 0:
  return True
 elif row[2] == -1 and output <= 0: 
  return True
 else:
  return False 

#compute b to such data data point are segrated 
def getB(dataset,weights):
 flag = True
 epoch = 1
 while(True):
  flag = False ; epoch = epoch + 1
  for row in dataset:
   prediction = compute(row, weights)
   if not prediction:
    weights[2] = row[2] -(weights[0]*row[0]+weights[1]*row[1])
    flag = True
  if epoch == 10 or flag == False : 
   break
 return weights
 
# To find classifier Minimum Squared Error Procedures - using Pseudoinverse
def LeastSquareClassifier(inputData):
 #Compute b based on input size. B is 1x<size> matrix with 1
 size = len(inputData)
 b = [1 for x in range(size)]
 #find b's transpose - > 8x1 matrix 
 bt = np.matrix(b).getT()
 #Prepare input matrix from dataset 
 m = np.matrix(inputData)
 #find tranpose of input matrix
 t = m.getT()
 #Multiply transpose of input matrix and matrix -  (Y^tY)
 mul = t*m
 #find inverse of outcome of above operation - (Y^tY)^-1 
 inv = mul.getI()
 # Find pseudo inverse- Multiply inversed matrix with 
 #transpose of input matrix - (Y^tY)^-1Y^t
 secondMul = inv * t
 #find solution matrix - Multiply pseudo matrix with b
 f = secondMul * bt
 #compute weight for ploting classifier 
 weightPlot = []
 weightPlot.insert(0,f.item(1))
 weightPlot.insert(1,f.item(2))
 weightPlot.insert(2,f.item(0))
 return weightPlot

def ClassifierOnTable1():
 #Find least square classifier weight 
 inputData = [[1,3,3], [1,3,0],[1,2,1] ,[1,0,2] ,
   [-1,1 ,-1],[-1,0, 0],[-1,1,1],[-1,-1 ,0]]
 plotData =  [[3,3,1], [3,0,1],[2,1,1] ,[0,2,1] ,[-1 ,1,-1],
   [0, 0,-1],[-1,-1,-1],[1,0,-1]]
 # find classifier for given dataset and Plot it. 
 weightPlotLS = LeastSquareClassifier(inputData)
 #plot data points and classifier 
 plotDataPointsAndClassifier(plotData,weightPlotLS)
 
def ClassifierOnTable2():
 inputData = [[1,3,3], [1,3,0],[1,2,1] ,[1,0,1.5] ,
   [-1,1 ,-1],[-1,0, 0],[-1,1,1],[-1,-1 ,0]]
 plotData  = [[3,3,1], [3,0,1],[2,1,1] ,[0,1.5,1] ,[-1 ,1,-1],
   [0, 0,-1],[-1,-1,-1],[1,0,-1]]
 # find classifier for given dataset and Plot it. 
 weightPlotLS = LeastSquareClassifier(inputData)
 #plot data points and classifier 
 plotDataPointsAndClassifier(plotData,weightPlotLS)

# map the inputs to the function blocks
options = {
  1 : ClassifierOnTable1,
  2 : ClassifierOnTable2,
 }
#start
if __name__ == '__main__':
 Dataset1C1 = [ [3,3], [3,0],[2,1] ,[0,1.5]]
 Dataset1C2 = [[-1 ,1],[0, 0],[-1,-1],[1 ,0]]
 print "1. LeastSquareClassifier on Data points in Table 1 \n \
  2. LeastSquareClassifier) on Data points in Table 2 \n"
 print "Enter your choice:\t"
 num = int(raw_input())
 options[num]()

Sample Output 
:-
[zytham@s158519-vm perceptron]$ python LSP.py
1. LeastSquareClassifier on Data points in Table 1
2. LeastSquareClassifier) on Data points in Table 2

Enter your choice:
1


[zytham@s158519-vm perceptron]$ python LSP.py 
1. LeastSquareClassifier on Data points in Table 1 
 2. LeastSquareClassifier) on Data points in Table 2 

Enter your choice: 
2

Textual description of firstImageUrl

Perceptron Learning - Implement online perceptron algorithm in python

The perceptron is a linear classifier, therefore it will never get to the state with all the input vectors classified correctly if the training set D is not linearly separable, i.e. if the positive examples can not be separated from the negative examples by a hyperplane. (Source: Wikipedia)

Sample Data:  C1, C2 and C3 represents three different class of data. It is guaranteed that these data set are linearly separable.
Linearly separable data sample (Three classes C1, C2 and C3)
Problem statement:- Write a program to generate
1.linear classifier for class C1 and C2
2. linear classifier for class C2 and C3

Sample code: - 
import sys
import matplotlib.pyplot as plt
import numpy as np

# Make a prediction with weights
def compute(row, weights):
 bias = weights[2]
 output = bias
 #output = (w1 * X1) + (w2 * X2) + bias
 for i in range(len(row)-1):
  output += weights[i] * row[i]
  ##print "output is",output
 return 1 if output > 0 else 0

#extrapolate classifer line with same slope as computed by final weights 
def getMultiplePoints(x,y,weight,boundX1,boundX2):
 x1 =[x,0]
 x2 =[0,y]
 pointsX = []
 pointsY = []
 pointsX.insert(1,y)
 pointsX.insert(2,0)
 pointsY.insert(1,0)
 pointsY.insert(2,x)
 #for boundX1
 pointsX.insert(0,boundX1)
 temp = -(weight[0]*boundX1 + weight[2])/weight[1]
 pointsY.insert(0,temp)
 #for boundX2
 pointsX.insert(3,boundX2)
 temp = -((weight[0]*boundX2) + weight[2])/weight[1]
 pointsY.insert(3,temp) 
 return (pointsX,pointsY)

#plot points 
def plotCoordinates(dataset,weightPlot):
 XList1 =[]
 YList1 =[]
 XList2 =[]
 YList2 =[] 
 count = 0
 boundX = -8
 boundY = 10
 x1 = - (weightPlot[2]/weightPlot[1])
 y1 = 0
 x2 = 0
 y2 = - (weightPlot[2]/weightPlot[0])
 #print x1 , y2
 # compute some random point with slope as W and bias b 
 plotTup = getMultiplePoints(x1,y2,weightPlot,boundX,boundY)
 for row in dataset:
  if(count<=9):
   XList1.append(row[0])
   YList1.append(row[1])
  else:
   XList2.append(row[0])
   YList2.append(row[1])
  count = count+1
 #Draw points with red and Blue color 
 plt.plot(XList1, YList1, 'ro',XList2, YList2, 'bo')
 plt.axis([boundX, boundY, boundX, boundY])
 plt.plot(plotTup[0],plotTup[1])
 plt.show()


#Update weight and bias 
def updateWeight(weights,x,l_rate,error):
 #update bias
 weights[2] = weights[2] + x[2] + l_rate * error
 #update weight part w1, w2
 for i in range(len(x)-1):
  weights[i] = weights[i] + l_rate * error * x[i]
 return weights

#Find linear classifier, predit outcome for each point and if error compute weight  
def findPerceptronClassifier(dataset,weights):
 flag = True
 epoch = 0
 retList = []
 l_rate = 0.2
 count = 0
 #lastWeight = []
 while(flag):
  #flag = False
  epoch = epoch + 1  
  #print("\nepoch = epoch + 1 is %d\n",epoch)
  count = 0
  for row in dataset:
   
   predicted_val = compute(row, weights)
   error = row[-1] - predicted_val
     
   #update weights
   if error != 0:
    weights = updateWeight(weights,row,l_rate,error)
    count = count + 1
   lastWeight = weights
  if error == 0 and count == 0:   
    flag = False
  else:
   flag = True
 retList.append(epoch)
 #print "Weight is ",weights
 #print "last Weight is ",lastWeight
 
 retList.append(weights) 
 return retList
 
# Input dataset for classifier 
datasetC1C2 =[[0.1,1.1,0], [6.8 ,7.1,0], [-3.5 ,-4.1,0], [2.0 ,2.7,0] , [4.1 ,2.8,0] ,
   [3.1 ,5.0,0], [-0.8 ,-1.3,0],[0.9 ,1.2,0], [5.0 ,6.4,0], [3.9, 4.0,0],
   [7.1 ,4.2,1], [-1.4, -4.3,1],[4.5 ,0.0,1 ], [6.3 ,1.6,1 ],[4.2 ,1.9,1 ], 
   [1.4 ,-3.2,1], [2.4 ,-4.0,1 ],[2.5 ,-6.1,1 ],[8.4 ,3.7,1], [4.1 ,-2.2,1]]


datasetC2C3 = [[-3.0 , -2.9,0], [0.5,  8.7,0], [2.9 , 2.1,0], [-0.1,  5.2,0], 
 [-4.0 , 2.2,0], [-1.3,  3.7,0], 
 [-3.4,  6.2,0], [-4.1,  3.4,0], [-5.1,  1.6,0], [1.9 , 5.1,0],[7.1 ,4.2,1], 
 [-1.4, -4.3,1],[4.5 ,0.0,1 ], [6.3 ,1.6,1 ],[4.2 ,1.9,1 ],    
 [1.4 ,-3.2,1], [2.4 ,-4.0,1 ],[2.5 ,-6.1,1 ],[8.4 ,3.7,1], [4.1 ,-2.2,1]]

#initialize inital weight and bias
initial_weights = [0,0,0]
#Iteration count 
epoch = 0
outList = []
def C1C2Classifier():
 #Iteration count for convergence - Dataset C1 and C2  
 outList = findPerceptronClassifier(datasetC1C2,initial_weights)
 epoch = outList[0]
 weightPlot = outList[1]
 ##print "Weight plot is ",weightPlot
 plotCoordinates(datasetC1C2,weightPlot)
 
def C2C3Classifier():
     #Iteration count for convergence - Dataset C2 and C3  
 outList = findPerceptronClassifier(datasetC2C3,initial_weights)
 epoch = outList[0]
 weightPlot = outList[1]
 ##print "Weight plot is ",weightPlot
 plotCoordinates(datasetC2C3,weightPlot)

# map the inputs to the function blocks
options = {
  1 : C1C2Classifier,
         2 : C2C3Classifier,
 }

#start
if __name__ == '__main__':
 print "1. Run C1C2 classifier \n2. Run C2C3 classifier\n"
 print "Enter your choice:\t"
 num = int(raw_input())
 options[num]()

Sample output:-
[zytham@s158519-vm perceptron]$ python Perceptron.py
1. Run C1C2 classifier
2. Run C2C3 classifier

Enter your choice: 1



[zytham@s158519-vm perceptron]$ python Perceptron.py
1. Run C1C2 classifier
2. Run C2C3 classifier

Enter your choice:
2