Friday, 29 January 2021

Custom single threaded java server

 package com.diffengine.csv;


import java.io.*;

import java.net.*;

import java.util.Date;


public class Server {


public static void main(String[] args) {

System.out.println("starting");

try (ServerSocket serverSocket = new ServerSocket(3333)) {

System.out.println("Server is listening on port " + 3333);

while (true) {

Socket socket = serverSocket.accept();

System.out.println("New client connected");

OutputStream output = socket.getOutputStream();

PrintWriter writer = new PrintWriter(output, true);

writer.println("HTTP/1.1 200 OK\r\n\r\n" +new Date().toString());

writer.close();

output.close();

socket.close();

}

} catch (IOException ex) {

System.out.println("Server exception: " + ex.getMessage());

ex.printStackTrace();

}

}

}


Friday, 22 March 2019

Tensor Flow from novice to expert - Part1

https://github.com/tensorflow/nmt

# -*- coding: utf-8 -*-
"""
Created on Tue Dec 26 21:21:01 2017

@author: krishgu
"""

import tensorflow as tf
node1 = tf.constant(3.0,tf.float32)
node2 = tf.constant(4.0)
# Printing it
print("Printing node1 node2 - %s" % node1,node2)

# Performing the operations in graph using session
sess=tf.Session()
print("Printing node1 node2 values - %s" % sess.run([node1,node2]))


#sample computation with constant value
a = tf.constant(5)
b = tf.constant(2)
c = tf.constant(3)

d=tf.multiply(a,b)
e=tf.add(c,b)

f=tf.subtract(d,e)

sess=tf.Session()
outs=sess.run(f)
sess.close()

print("outs = {}".format(outs))


#performing it with dynamic value
a= tf.placeholder(tf.float32)
b= tf.placeholder(tf.float32)

adder_node = a+b
sess= tf.Session()
print(sess.run(adder_node,{a:[1,2,3,4,5],b:[1,2,3,4,5]}))


#Perfroming it with variable values
w = tf.Variable([.3],tf.float32)
b = tf.Variable([-.3],tf.float32)
x = tf.placeholder(tf.float32)

linear_model=w*x+b;
init = tf.global_variables_initializer()
print(w)
print(b)
sess = tf.Session()
sess.run(init)
print(sess.run(w))
print(sess.run(b))
print(sess.run(linear_model,{x:[1,2,3,4]}))

linkedin

package com.linkedin.messaging;

User contacts and direct messaging are obtained through the features “r_network” and “w_messages,” respectively, both of which will be retired with this change. With this retirement, any direct sharing or contact related features that utilize LinkedIn contacts will no longer function after May 12th, 2015.


import java.util.Scanner;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.apis.LinkedInApi;
import com.github.scribejava.core.model.OAuth1AccessToken;
import com.github.scribejava.core.model.OAuth1RequestToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth10aService;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class LinkedInTest2 {
private static final String PROTECTED_RESOURCE_URL = "https://api.linkedin.com/v1/people/~";
private static String API_KEY = "81tqxy39b";

private static String API_SECRET = "bQg1l1hQzcKtL4";
private LinkedInTest2() {
}

public static void main(String... args) throws IOException, InterruptedException, ExecutionException {
final OAuth10aService service = new ServiceBuilder(API_KEY).apiSecret(API_SECRET).callback("https://www.google.co.in")
.build(LinkedInApi.instance());
final Scanner in = new Scanner(System.in);

System.out.println("=== LinkedIn's OAuth Workflow ===");
System.out.println();

// Obtain the Request Token
System.out.println("Fetching the Request Token...");
final OAuth1RequestToken requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println();

System.out.println("Now go and authorize ScribeJava here:");
System.out.println(service.getAuthorizationUrl(requestToken));
System.out.println("And paste the verifier here");
System.out.print(">>");
final String oauthVerifier = in.nextLine();
System.out.println();

// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
final OAuth1AccessToken accessToken = service.getAccessToken(requestToken, oauthVerifier);
System.out.println("Got the Access Token!");
System.out.println("(The raw response looks like this: " + accessToken.getRawResponse() + "')");
System.out.println();

// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
final OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
final Response response = service.execute(request);
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getBody());

System.out.println();
System.out.println("Thats it man! Go and build something awesome with ScribeJava! :)");
}
}

JSPDF with Angular (Acro forms are not included)

JSPDF :- If you want to print a pdf from web page

1. Run below commands to get the code base.
npm install jspdf --save

typings install dt~jspdf --global --save

npm install @types/jspdf --save

2. Create html and wire to Angular component :- Invoke printAdapter from there

3. Create a class in typescript : - Copy paste below code

const jsPDF = require('jspdf'); // or import * as jsPDF from 'jspdf' or import jsPDF from 'jspdf'
printValues(img) {
const doc = new jsPDF();
doc.addImage(img, 'PNG', 2, 5, 60, 30);
doc.text(70, 20, 'Web');
doc.setTextColor(255, 0, 0);
doc.text(140, 20, 'Confidential');
const reportTitle = 'This is a confidential report';
const splitTitle = doc.splitTextToSize(reportTitle, 180);
doc.text(2, 44, splitTitle);
doc.setTextColor(0, 0, 0);
doc.setLineWidth(0.5);
doc.text(60, 64, 'list section').setFillColor(0, 0, 0);
doc.text(2, 69, 'name :');
doc.text(50, 69, 'India');
doc.line(50, 69.5, 68, 69.5);
doc.text(2, 79, 'Code :');
doc.text(50, 79, 'INH');

doc.setDrawColor(0);
doc.setFillColor(211, 211, 211);
doc.rect(1, 99, 200, 10, 'F');


doc.setFontSize(12);
doc.setFontType('bold');
doc.text('ComboBox:', 10, 105);

doc.rect(20, 120, 5, 5); // empty square
doc.line(20, 120, 18, 118);
doc.text(20, 120, '✓');

doc.rect(40, 120, 10, 10, 'F'); // filled square

doc.setDrawColor(255, 0, 0);
doc.rect(60, 120, 10, 10); // empty red square

doc.setDrawColor(255, 0, 0);
doc.rect(80, 120, 10, 10, 'FD'); // filled square with red borders

doc.setDrawColor(0);
doc.setFillColor(255, 0, 0);
doc.rect(100, 120, 10, 10, 'F'); // filled red square

doc.setDrawColor(0);
doc.setFillColor(255, 0, 0);
doc.rect(120, 120, 5, 5, 'FD'); // filled red square with black borders

doc.setDrawColor(0);
doc.setFillColor(255, 255, 255);
doc.roundedRect(140, 120, 5, 5, 3, 3, 'FD'); // Black square with rounded corners

doc.save('FirstSample.pdf');
}

printAdapter() {
this.getImageFromUrl('http://localhost:4200/assets/images/logo.png'); // Path to image
}

getImageFromUrl(url) {
const current = this;
const img = new Image();
img.onload = function () {
current.printValues(img);
};
img.src = url;
}

Wednesday, 18 April 2018

FTL looping over map

FTL interating over a map :-

List<String> cityList1 = new ArrayList<String>();
cityList.add("Washington DC");

List<String> cityList2 = new ArrayList<String>();
cityList2.add("Berlin");
cityList2.add("Paris");
cityList2.add("Rome");

Map<String,List<String>> map = new HashMap<String,List<String>>();
map.put("US",cityList1);
map.put("UK",cityList2);

approach 1 :-
<#list map?keys as key>
    //looping map valuesfor the key we can set it to UI component
    <#list map[key] as city>
       <b> ${city} </b>
     </#list>
</#list>

approach 2 :-
<#list map?keys as key>
    //looping map valuesfor the key we can set it to UI component
    <#list map.values[key] as city>
       <b> ${city} </b>
     </#list>
</#list>

approach 3 :-
<#list map?keys as key>
    //looping map valuesfor the key we can set it to UI component
    <#list map?values[key] as city>
       <b> ${city} </b>
     </#list>
</#list>

approach 4 :-
<#list map.entrySet() as entry>
    //looping map valuesfor the key we can set it to UI component
    <#list entry.key as city>
       <b> ${city} </b>
     </#list>
</#list>

approach 5 :-
<#list map.entrySet() as entry>
     <#assign keyValue="${entry.key}">
    //looping map valuesfor the key we can set it to UI component
    <#list keyValue as city>
       <b> ${city} </b>
     </#list>
</#list>

approach 6 :-
<#list map?keys as key>
    <#assign keyValue="map[key]">
    //looping map valuesfor the key we can set it to UI component
    <#list keyValue as city>
       <b> ${city} </b>
     </#list>
</#list>

Tuesday, 13 February 2018

HTML parser

package org.tiaa.indiatraining.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;

import java.net.URLConnection;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ScanEngine {
private static final Logger LOGGER = Logger.getLogger(ScanEngine.class.getName());
List<String> tags = Arrays.asList("<title>,</title>", "<body>,</body>");
private static final String HTML_A_TAG_PATTERN = "(?i)<a([^>]+)>(.+?)</a>";
private static final String HTML_IMG_TAG_PATTERN ="(?i)<img\\s+(.*?)/?>";

public static URLConnection connect(String connectionString) {
URL url;
URLConnection conn = null;
try {
url = new URL(connectionString);
conn = url.openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return conn;
}

public static BufferedReader getStream(URLConnection con) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
return in;
}

public static StringBuilder parse(BufferedReader in){
       StringBuilder sb = new StringBuilder();
String inputLine;
try {
while ((inputLine = in.readLine()) != null)
sb.append(inputLine);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
       return sb;
}

public static void invokeScanEngine(String url) {
try {
URLConnection con = connect(url);
LOGGER.log(Level.INFO,"Hostname :-"+ getHost(con));
LOGGER.log(Level.INFO,"IpAddress :-"+ getIpAddress(con));
BufferedReader in  = getStream(con);
if(in!=null){
StringBuilder sb = parse(in);
LOGGER.log(Level.INFO,"Submitted On :-"+getTime());
LOGGER.log(Level.INFO,"Title :-"+extractTag(sb,"<title>","</title>").trim());
LOGGER.log(Level.INFO,"Body :-"+extractTag(sb,"<body","</body>").trim());
LOGGER.log(Level.INFO,"Count of links :-"+countTag(sb,HTML_A_TAG_PATTERN));
LOGGER.log(Level.INFO,"Count of images :-"+countTag(sb,HTML_IMG_TAG_PATTERN));
}
} catch (IOException e) {
e.printStackTrace();
}
}

private static String getIpAddress(URLConnection con) throws UnknownHostException {
InetAddress address = InetAddress.getByName(getHost(con));
String ip = address.getHostAddress();
return ip;
}

private static String getHost(URLConnection con) {
return con.getURL().getHost();
}

public static String extractTag(StringBuilder sb ,String startElement,String endElement){
int start = sb.indexOf(startElement);
int end = sb.indexOf(endElement);
String title = sb.substring(start+startElement.length(),end);
return title;
}

public static void main(String args[]){
invokeScanEngine("http://intranet.ops.tiaa-cref.org/");
//System.out.println("krishna".substring(0,"krishna".length()-1));
}

public static String getTime(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH.mm.ss");
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
String date = sdf.format(timestamp);
return date;
}

public static int countTag(StringBuilder sb ,String expression){
Pattern patternTag = Pattern.compile(expression);
Matcher matcherTag = patternTag.matcher(sb);
        int count = 0;
while (matcherTag.find()) {
count = count +1;
}
return count;
}
}

Thursday, 6 July 2017

Angular $broadcast ,$On and $emit for novice

Intercommunication and eventing :- $brodcast and $emit falls under intercommunication between controllers. There are other ways also like having data in parent and root controller and one other way is getting data from service. $on is unitized for event registering on scopes. Broadcast is like jms broadcasting it will send a copy to everyone. Emit will send it only to its parents  its something like inheritance in java. Please have a look at below program and output to understand it clearly.

Example :- 
<!doctype html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <script >
"use strict";
var allScopes = {};
      var angModule = angular.module("app",[]);
function globalController(ctrlName){
  return function($scope){
  console.log("entering controller");
          //Registering event on individual scope
     $scope.$on("customMessage",function(e,opt){
     console.log("Controller :-"+ ctrlName + " recievedMessage "+opt.message);
 })
allScopes[ctrlName]=$scope;
  };  
}
angModule.controller("tcmController",globalController("tcmController"))
.controller("projectController",globalController("projectController"))
.controller("defectsController",globalController("defectsController"))
.controller("jiraController",globalController("jiraController"))
.controller("rtcController",globalController("rtcController"))
.run(function($timeout,$rootScope){
 console.log("entering run");
          //Registering event on global scope
  $rootScope.$on("customMessage",function(e,opt){
     console.log("root Controller recievedMessage "+opt.message);
 });
  allScopes["root"]= $rootScope;  
  $timeout(function(){
   console.log("entering timeout");
//broadcast will communicate to everyone in the scope
     $rootScope.$broadcast("customMessage",{
    message : 'broadcasting from root'
 });

 //emit will communicate to everyone in the inheritance heiracrhy scope
     allScopes["projectController"].$broadcast("customMessage",{
    message : 'broadcasting from root'
 });

 //To see the result run them individually by commenting them out
  },1000);
});
</script>
 
  </head>
  <body>
 <div  ng-app="app">
    <div  ng-controller="tcmController">
       <div  ng-controller="projectController">
       </div>
  <div  ng-controller="defectsController">  
       </div>
   </div>
       <div  ng-controller="jiraController">  
       </div>
  <div  ng-controller="rtcController">  
      </div>
</div>
  </body>
</html>

Output for $emit :- 
Controller :-projectController recievedMessage broadcasting from root
Controller :-tcmController recievedMessage broadcasting from root
 root Controller recievedMessage broadcasting from root


Output for $broadcast:-
root Controller recievedMessage broadcasting from root
Controller :-tcmController recievedMessage broadcasting from root
Controller :-projectController recievedMessage broadcasting from root
Controller :-defectsController recievedMessage broadcasting from root
Controller :-jiraController recievedMessage broadcasting from root
Controller :-rtcController recievedMessage broadcasting from root

Wednesday, 5 July 2017

Angular $watch explanation for novice person

Angular $watch :- To get clear understanding on $watch below i have implemented the example using $watch and without using it. In one liner definitions we can watch on variables based on changes to it we can correspondingly change the variables dependent on it in angular scope. Something like observer pattern but exactly not like that

Example :-  In this example we will have a text box and a label beside to display computed fund based on initial fund release.
<!doctype html>
<html ng-app="app">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <script >
         var angModule = angular.module("app",[]);
angModule.controller("checkWatchProperty",function($scope){
      $scope.funding = {startingEstimate:0}
                          //without watch    
 $scope.computeNeeded = function(){        
   $scope.funding.needed = $scope.funding.startingEstimate*10;
  }
   //with watch  
   $scope.$watch('funding.startingEstimate', function(){        
   $scope.funding.needed = $scope.funding.startingEstimate*10;
  });
});
</script>
 
  </head>
  <body ng-controller="checkWatchProperty">
  <!--With out watch -->
   Starting : <input ng-model="funding.startingEstimate" ng-change="computeNeeded()">
    <!--With  watch we no need to attach the ng-change as previous statement. Angular takes care of invoking callback function-->
   Starting : <input ng-model="funding.startingEstimate" >
   Recommendation : {{funding.needed}}
  </body>
</html>

Friday, 26 May 2017

Game of Thrones - I

Dothraki are planning an attack to usurp King Robert's throne. King Robert learns of this conspiracy from Raven and plans to lock the single door through which the enemy can enter his kingdom.
But, to lock the door he needs a key that is an anagram of a certain palindrome string.
The king has a string composed of lowercase English letters. Help him figure out whether any anagram of the string can be a palindrome or not.
Input Format 
A single line which contains the input string.
Constraints 
 length of string  
Each character of the string is a lowercase English letter.
Output Format 
A single line which contains YES or NO in uppercase.
Sample Input : 01
aaabbbb
Sample Output : 01
YES
Explanation 
A palindrome permutation of the given string is bbaaabb
Sample Input : 02
cdefghmnopqrstuvw
Sample Output : 02
NO
Explanation 
You can verify that the given string has no palindrome permutation. 
Sample Input : 03
cdcdcdcdeeeef
Sample Output : 03
YES
CODE:-  main logic is if length is even then count the individual characters in ths string. Each characters duplicate count should be even, Then it ti palendrome. If the string length is odd then there should be only one character whose duplicate count is a odd number.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner myScan = new Scanner(System.in);
        String inputString = myScan.nextLine(); 
        HashMap<Character,Integer> hashMap = new HashMap<Character,Integer>();
        String ans = "NO";
       for(int i=0;i<inputString.length();i++){
           if(hashMap.containsKey(inputString.charAt(i))){
               hashMap.put(inputString.charAt(i),hashMap.get(inputString.charAt(i))+1);
           }else{
               hashMap.put(inputString.charAt(i),1);
           }
       }
        int oddCount=0;
           Set<Character> set= hashMap.keySet();
           Iterator iter = set.iterator();
           while(iter.hasNext()){
               if(hashMap.get(iter.next())%2!=0){
                   oddCount+=1;
               }
           }
        if(inputString.length()%2==0 && oddCount==0){
                ans = "YES";
        }else if(inputString.length()%2!=0 && oddCount==1){
            ans = "YES";
        }
        System.out.println(ans);
        myScan.close();
    }
}

Thursday, 11 May 2017

Custom hashmap implementation to clear basics of hashmap and hashtable for any software engineer

HashMap/HashTable :- This question arises in most of the interviews. General hashcode and quals contract even fresher will also explain. The main point is why the hash map is faster? why hashmap best time complexity is O(1) without collision?.What is collision what happens when the collision occurs?. what is the internal data structure used in Hash map? and many more questions. Below example will clear all your doubts which has customized hashmap with minimal functionality mimicking actual hashmap/hashtable.

Implementation :- 

package com.shift.tcm.util;

/* Operations performed in custom map */
interface ExtendableMap {
public abstract void put(Object key, Object value);

public abstract Object get(Object key);
}

/* MapEntry is the actual data structure used inside array to store the data*/
class MapEntry<K, V> {
final K key;
V value;
/*
* Incase of duplicates we need to maintain it as a linked list when hash
* code collides
*/
MapEntry<K, V> next;
final int hash;

MapEntry(int h, K k, V v, MapEntry<K, V> n) {
value = v;
next = n;
key = k;
hash = h;
}

public final K getKey() {
return key;
}

public final V getValue() {
return value;
}

// whether two entry objects are equal based on their hashcode and equals
// method
public final boolean equals(Object o) {
if (!(o instanceof MapEntry))
return false;
MapEntry e = (MapEntry) o;
Object k1 = getKey();
Object k2 = e.getKey();
if (k1 == k2 || (k1 != null && k1.equals(k2))) {
Object v1 = getValue();
Object v2 = e.getValue();
if (v1 == v2 || (v1 != null && v1.equals(v2)))
return true;
}
return false;
}

public final int hashCode() {
return key.hashCode();
}

public final String toString() {
return getKey() + "=" + getValue();
}
}

Map impelmentation starts here :- 
public class CustomHashMap implements ExtendableMap {
// Using array will provide random access which returns value in constant
// time
Object[] table;
int length;

// Setting up default size 16
public CustomHashMap() {
this.table = new Object[16];
this.length = 16;
}

// User setting custom size
public CustomHashMap(int size) {
this.table = new Object[size];
this.length = size;
}

@Override
public void put(Object key, Object value) {
int hashKey = calculateHash(key.hashCode());
if (hashKey > -1 && hashKey < length) {
MapEntry entry = new MapEntry(key.hashCode(), key, value, null);
if (table[hashKey] == null) {
table[hashKey] = entry;
} else {
// If there are duplicates we need to form an linkedlist of type
// MapEntry
handleDuplicatesOrUpdateExisting(entry, hashKey);
}
}
}

@Override
public Object get(Object key) {
// Determine hashvalue
int hashKey = calculateHash(key.hashCode());
// Now lookup is very fast because array is an index based hash no need
// to loop through the array
if (hashKey > -1 && hashKey < length) {
MapEntry entry = (MapEntry) table[hashKey];
if (entry.next != null) {
return exactMatchInList(entry, key);
}
return entry.getValue();
}
return null;
}

/*
* If hashcodes are matching then we have to loop through linked list and
* find the exact value

*/
private Object exactMatchInList(MapEntry entry, Object key) {
while (entry!= null) {
if (entry.hashCode() == key.hashCode() && entry.getKey().equals(key)) {
return entry;
} else {
entry = entry.next;
}
}
return null;
}

/*
* If hashcodes are matching then we have to form a linked list and store
* the value

*/
private void handleDuplicatesOrUpdateExisting(MapEntry entry, int hashKey) {
MapEntry prevEntry = (MapEntry) table[hashKey];
if (prevEntry.equals(entry)) {
table[hashKey] = entry;
} else {
prevEntry.next = entry;
table[hashKey] = prevEntry;
}
}

/*
* Base hash function responsible for converting hash key to actual hash
* value Generally many people gets confuse between hashkey and actual hash
* value which is computed to make hashmap respond in constant time to make it work
         * in constant time always
*/
private int calculateHash(int key) {
return key % length;
}

}

End usage of the custom hashmap :-

package com.shift.tcm.util;

/*
 * Test case for unit testing customhashmap
 * 
 * */
public class HashMapTest {

public static void main(String[] args) {
// Initialize the custom hashmap with default size 16
CustomHashMap customHashMap = new CustomHashMap();

//Put data to map
Employee employee= new Employee(2,"krishna");
customHashMap.put(employee, "Manager");
Employee employee1= new Employee(1,"satish");
customHashMap.put(employee1, "Assistent Manager");
                Employee employee4= new Employee(4,"employee");
customHashMap.put(employee4, "Engineer");

//Putting duplicate key data
Employee employee2= new Employee(2,"krishna1");
customHashMap.put(employee2, "Director");
Employee employee3= new Employee(1,"satish1");
customHashMap.put(employee3, "Sr Director");

//Retrieve Data from map;
Employee retrieveEmployee1= new Employee(1,"satish1");
        System.out.println(customHashMap.get(retrieveEmployee1));
Employee retrieveEmployee2= new Employee(2,"krishna");
System.out.println(customHashMap.get(retrieveEmployee2));
                Employee employee5= new Employee(4,"employee");
System.out.println(customHashMap.get(employee5));
}

}

class Employee {
int id;
String name;

public Employee(int id,String name) {
this.id = id;
this.name=name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

/* If hashcode is equals it is not necessary that both the objects are same. 
* In case of duplicate values in hashmap its equals methods is verified to check whether the objects are same are not
*/
@Override
public int hashCode() {
return id;
}

/* If both the objects equals method returns same then its hashcode method should also return same value */
@Override
public boolean equals(Object o) {
if(o instanceof Employee){
Employee employee = (Employee)o;
if(employee.getName()== getName()){
return true;
}else {
return false;
}
}else{
return false;
}
}

public String toString(){
return "Employee ID :- "+id;

}
}

Sunday, 30 April 2017

Sorting array list based on name using collections.sort

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class TestClass2 {

public static void main(String[] args) {
// TODO Auto-generated method stub
        ArrayList<Person> list = new ArrayList<Person>();
        list.add(new Person("B"));
        list.add(new Person("A"));
        list.add(new Person("D"));
        list.add(new Person("C"));
        Collections.sort(list,new Comparator<Person>(){
@Override
public int compare(Person arg0, Person arg1) {
return arg0.name.compareToIgnoreCase(arg1.name);
}
       
        });
        for(Person person:list){
        System.out.println(person.name);
        }
}

}

class Person {
String name;
Person(String name){
this.name=name;
}
}

Parsing hash tags twitter trends

Twitter Trends
Twitter shows trends in order to make its users aware of the trending news. These trends are nothing but trending hashtags that the users are tweeting about. For example: If thousands of users are talking about United States by adding a hashtag #US in their tweet, then US will be a trending hashtag. Couple of example tweets with hashtag #US could be:

Donald Trump becomes the 45th #US President
Roger Federer wins #US Open for 5th time
Given a list of
N
N tweets, your task is to find top the five trending hashtags. Each tweet, let's call it
S
S, will contain at least one one word with hashtag. There will be maximum of three hashtags in any tweet. All hashtags in a single tweet will be unique.

Input:
First line of the input will contain   N
N denoting the number of tweets.
Next
N
N lines, each will contain a string S
S.

Output:
Print the top five trending hashtags. In case of tie between any two hashtags, print them in lexicographical order in a new line.

Note:

Any tweet is composed of lowercase and uppercase English letters, digits and spaces.
Any hashtag begins with # and the subsequent characters will only contain lowercase and uppercase English letters and digits.



Sample Input
10
Donald Trump becomes the 45th #US President
Potentially habitable exoplanet #ProximaB discovered
#RogerFederer wins #US Open for 5th time
#GravitationalWaves detection successful
Traces of liquid water discovered on #Mars
Life Could Survive on Exoplanet #ProximaB
Go go #RogerFederer
Ten ways #ProximaB is different from Earth
ISRO becomes 4th space agency to reach #Mars
#RogerFederer beats #Nadal



Sample Output
#ProximaB
#RogerFederer
#Mars
#US
#GravitationalWaves
Explanation
In the given sample test case, the count of occurrences of all the hashtags are:

#US: 2
#Mars: 2
#RogerFederer: 3
#ProximaB: 3
#Nadal: 1
#GravitationalWaves: 1

Sort them by count and in case of tie in count we sort them in lexicographical order of hashtag. It means that Since #RogerFederer and #ProximaB has equal count, we compare the strings and since #ProximaB is lexicographically smaller than #RogerFederer, #ProximaB will have precedence over #RogerFederer.

Final sorted order is:

#ProximaB: 3
#RogerFederer: 3
#Mars: 2
#US: 2
#GravitationalWaves: 1
#Nadal: 1

Top 5 hashtags from the above list is the correct output.


Code :- 

package com.deutsche.Domain;


//imports for BufferedReader
import java.io.BufferedReader;
import java.io.InputStreamReader;

//import for Scanner and other utility classes
import java.util.*;
import java.util.Map.Entry;

class TestClass {
  public static void main(String args[] ) throws Exception {
      //BufferedReader
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      HashMap<String,Integer> hashMap = new HashMap<String,Integer>();
      String line = br.readLine();
      for(int i=0;i<Integer.parseInt(line);i++){
          String line1= br.readLine();
          while(true){
          int index = line1.indexOf('#');
          if(index<0){
              break;
          }
          line1=line1.substring(index,line1.length());
          int spaceIndex = line1.indexOf(' ');
          if(spaceIndex<0){
         spaceIndex=line1.length();
          }
          String tag = line1.substring(0,spaceIndex);
          if(hashMap.containsKey(tag)){
               hashMap.put(tag,hashMap.get(tag)+1);
          }else{
         hashMap.put(tag,1);
          }
          if(spaceIndex==line1.length()){
         break;
          }
          line1 = line1.substring(spaceIndex+1,line1.length());
          }
      }
      Set<Entry<String, Integer>> set = hashMap.entrySet();
      List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
      Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()
      {
          public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 )
          {
         if(o2.getValue() == o1.getValue()){
         return (o1.getKey()).compareToIgnoreCase (o2.getKey());
         }else{
                return (o2.getValue()).compareTo( o1.getValue());
         }
          }
      } );
      int count =0;
       for(Map.Entry<String, Integer> entry:list){
           if(count>5){
               break;
           }
          System.out.println(entry.getKey()+": "+entry.getValue());
          count=count+1;
      }
     
  }
}


Thursday, 6 April 2017

Find factorial for number which are larger than 64 bit in java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        BigInteger big = new BigInteger(String.valueOf(in.nextInt()));
        System.out.println(factorial(big));
    }
   
    static BigInteger factorial(BigInteger n){
        if(n == BigInteger.ONE || n== BigInteger.ZERO)
            return BigInteger.ONE;
        else
            return n.multiply(factorial(n.subtract(BigInteger.ONE)));
    }
}

Tuesday, 14 March 2017

Arraylist contains search for non primitive and custom objects

Searching custom objects in arraylist :- Typical developer quickly codes foreach to check whether the object is matching. Instead of that if your search is always based on constant factor like name or phone number you can override the hashcode and equals method as given below.


public class MainThread {
    private static Object ob1 = new Object();

    public static void main(String[] args) {
        Employee e1 = new Employee("krishna1", 1);
        Employee e2 = new Employee("krishna2", 12);
        Employee e3 = new Employee("krishna3", 13);
        Employee e4 = new Employee("krishna4", 14);
        Employee e5 = new Employee("krishna5", 15);
        Employee e6 = new Employee("krishna6", 16);
        Employee e7 = new Employee("krishna7", 17);
        Employee e8 = new Employee("krishna8", 18);
        Employee e9 = new Employee("krishna9", 19);
        Employee e10 = new Employee("krishna10", 20);
        Employee e11 = new Employee("krishna11", 21);
        Employee e12 = new Employee("krishna12", 22);
        ArrayList<Employee> arrayLis = new ArrayList<Employee>();
        arrayLis.add(e1);
        arrayLis.add(e2);
        arrayLis.add(e3);
        arrayLis.add(e4);
        arrayLis.add(e5);
        arrayLis.add(e6);
        arrayLis.add(e7);
        arrayLis.add(e8);
        arrayLis.add(e9);
        arrayLis.add(e10);
        arrayLis.add(e11);
        arrayLis.add(e12);
        System.out.println(arrayLis.contains(new Employee("krishna2", 12)));

    }
}

class Employee {
    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(int phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    int phoneNumber;

    Employee(String name, int phoneNumber) {
        this.name = name;
        this.phoneNumber = phoneNumber;
    }

    //Logic to determine when will the objects will be same
    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Employee) {
            Employee employee = (Employee) obj;
            if (this.name.equals(employee.getName())) {
                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }
    }

 //Logic to determine when will the objects will be same
    @Override
    public int hashCode(){
        return this.name.hashCode();
    }

}

Custom single threaded java server

 package com.diffengine.csv; import java.io.*; import java.net.*; import java.util.Date; public class Server { public static void main(Str...