Adding some more java stuff

master
Michael Reber 3 years ago
parent b880c3ccde
commit 599b63599b
  1. 137
      java/CLChat Client.java
  2. 129
      java/CLChatServer.java
  3. 59
      java/Client Server Using RMI.java
  4. 36
      java/Creating a Non-Blocking Socket.java
  5. 49
      java/DateClient.java
  6. 61
      java/DateServer.java
  7. 66
      java/FTPLogin.java
  8. 69
      java/IPC Client Server Program.java
  9. 92
      java/Implement Apriori algorithm for association rule.java
  10. 187
      java/Implementation of Agglomerative Algorithm.java
  11. 138
      java/Implementation of clustering algorithm K-means.java
  12. 81
      java/Interprocess communication.java
  13. 54
      java/LoadBalancer.java
  14. 83
      java/Multi ClassLoader Demo.java
  15. 108
      java/Mutual Exclusion Algorithm.java
  16. 47
      java/MyThread.java
  17. 29
      java/Parallel Algorithms.java
  18. 23
      java/Ping a server.java
  19. 46
      java/Port Scanner.java
  20. 50
      java/SimpleApacheSoapClient.java
  21. 23
      java/SquareKaro.java
  22. 17
      java/SquareResult.java
  23. 44
      java/Squarer.java
  24. 154
      java/To implement Na‹ve Bayesian Classifier.java
  25. 167
      java/Using Proxy.java

@ -0,0 +1,137 @@
CLChat Client
import java.net.*;
import java.io.*;
public class CLChatClient {
static final int DEFAULT_PORT = 1728; // Port where server is
// listening, if no
// port is specified
// on the command line.
static final String HANDSHAKE = "CLChat"; // Handshake string.
// Each end of the connection sends this string
// to the other just after the connection is
// opened. This is done to confirm that the
// program on the other side of the connection
// is a CLChat program.
static final char MESSAGE = '0'; // This character is prepended
// to every message that is sent.
static final char CLOSE = '1'; // This character is sent to
// the connected program when
// the user quits.
public static void main(String[] args) {
String computer; // The computer where the server is running,
// as specified on the command line. It can
// be either an IP number or a domain name.
int port; // The port on which the server listens.
Socket connection; // For communication with the server.
TextReader incoming; // Stream for receiving data from server.
PrintWriter outgoing; // Stream for sending data to server.
String messageOut; // A message to be sent to the server.
String messageIn; // A message received from the server.
/* First, get the computer from the command line.
Get the port from the command line, if one is specified,
or use the default port if none is specified. */
if (args.length == 0) {
TextIO.putln("Usage: java SimpleClient <computer-name> [<port>]");
return;
}
computer = args[0];
if (args.length == 1)
port = DEFAULT_PORT;
else {
try {
port= Integer.parseInt(args[1]);
if (port <= 0 || port > 65535)
throw new NumberFormatException();
}
catch (NumberFormatException e) {
TextIO.putln("Illegal port number, " + args[1]);
return;
}
}
/* Open a connetion to the server. Create streams for
communication and exchange the handshake. */
try {
TextIO.putln("Connecting to " + computer + " on port " + port);
connection = new Socket(computer,port);
incoming = new TextReader(connection.getInputStream());
outgoing = new PrintWriter(connection.getOutputStream());
outgoing.println(HANDSHAKE);
outgoing.flush();
messageIn = incoming.getln();
if (! messageIn.equals(HANDSHAKE) ) {
throw new IOException("Connected program is not CLChat!");
}
TextIO.putln("Connected. Enter your first message.
");
}
catch (Exception e) {
TextIO.putln("An error occurred while opening connection.");
TextIO.putln(e.toString());
return;
}
/* Exchange messages with the other end of the connection
until one side or the other closes the connection.
This client program send the first message. After that,
messages alternate strictly back an forth. */
try {
while (true) {
TextIO.put("SEND: ");
messageOut = TextIO.getln();
if (messageOut.equalsIgnoreCase("quit")) {
// User wants to quit. Inform the other side
// of the connection, then close the connection.
outgoing.println(CLOSE);
outgoing.flush();
connection.close();
TextIO.putln("Connection closed.");
break;
}
outgoing.println(MESSAGE + messageOut);
outgoing.flush();
if (outgoing.checkError()) {
throw new IOException("Error ocurred while reading incoming message.");
}
TextIO.putln("WAITING...");
messageIn = incoming.getln();
if (messageIn.length() > 0) {
// The first character of the message is a command.
// If the command is CLOSE, then the connection
// is closed. Otherwise, remove the command
// character from the message and procede.
if (messageIn.charAt(0) == CLOSE) {
TextIO.putln("Connection closed at other end.");
connection.close();
break;
}
messageIn = messageIn.substring(1);
}
TextIO.putln("RECEIVED: " + messageIn);
}
}
catch (Exception e) {
TextIO.putln("Sorry, an error has occurred. Connection lost.");
TextIO.putln(e.toString());
System.exit(1);
}
} // end main()
} //end class CLChatClient

@ -0,0 +1,129 @@
CLChatServer
import java.net.*;
import java.io.*;
public class CLChatServer {
static final int DEFAULT_PORT = 1728; // Port to listen on,
// if none is specified
// on the command line.
static final String HANDSHAKE = "CLChat"; // Handshake string.
// Each end of the connection sends this string
// to the other just after the connection is
// opened. This is done to confirm that the
// program on the other side of the connection
// is a CLChat program.
static final char MESSAGE = '0'; // This character is prepended
// to every message that is sent.
static final char CLOSE = '1'; // This character is sent to
// the connected program when
// the user quits.
public static void main(String[] args) {
int port; // The port on which the server listens.
ServerSocket listener; // Listens for a connection request.
Socket connection; // For communication with the client.
TextReader incoming; // Stream for receiving data from client.
PrintWriter outgoing; // Stream for sending data to client.
String messageOut; // A message to be sent to the client.
String messageIn; // A message received from the client.
/* First, get the port number from the command line,
or use the default port if none is specified. */
if (args.length == 0)
port = DEFAULT_PORT;
else {
try {
port= Integer.parseInt(args[0]);
if (port < 0 || port > 65535)
throw new NumberFormatException();
}
catch (NumberFormatException e) {
TextIO.putln("Illegal port number, " + args[0]);
return;
}
}
/* Wait for a connection request. When it arrives, close
down the listener. Create streams for communication
and exchange the handshake. */
try {
listener = new ServerSocket(port);
TextIO.putln("Listening on port " + listener.getLocalPort());
connection = listener.accept();
listener.close();
incoming = new TextReader(connection.getInputStream());
outgoing = new PrintWriter(connection.getOutputStream());
outgoing.println(HANDSHAKE);
outgoing.flush();
messageIn = incoming.getln();
if (! messageIn.equals(HANDSHAKE) ) {
throw new IOException("Connected program is not CLChat!");
}
TextIO.putln("Connected. Waiting for the first message.
");
}
catch (Exception e) {
TextIO.putln("An error occurred while opening connection.");
TextIO.putln(e.toString());
return;
}
/* Exchange messages with the other end of the connection
until one side or the other closes the connection.
This server program waits for the first message from
the client. After that, messages alternate strictly
back an forth. */
try {
while (true) {
TextIO.putln("WAITING...");
messageIn = incoming.getln();
if (messageIn.length() > 0) {
// The first character of the message is a command.
// If the command is CLOSE, then the connection
// is closed. Otherwise, remove the command
// character from the message and procede.
if (messageIn.charAt(0) == CLOSE) {
TextIO.putln("Connection closed at other end.");
connection.close();
break;
}
messageIn = messageIn.substring(1);
}
TextIO.putln("RECEIVED: " + messageIn);
TextIO.put("SEND: ");
messageOut = TextIO.getln();
if (messageOut.equalsIgnoreCase("quit")) {
// User wants to quit. Inform the other side
// of the connection, then close the connection.
outgoing.println(CLOSE);
outgoing.flush(); // Make sure the data is sent!
connection.close();
TextIO.putln("Connection closed.");
break;
}
outgoing.println(MESSAGE + messageOut);
outgoing.flush(); // Make sure the data is sent!
if (outgoing.checkError()) {
throw new IOException("Error ocurred while reading incoming message.");
}
}
}
catch (Exception e) {
TextIO.putln("Sorry, an error has occurred. Connection lost.");
TextIO.putln(e.toString());
System.exit(1);
}
} // end main()
} //end class CLChatServer

@ -0,0 +1,59 @@
//AddInterface.java
import java.rmi.*;
public interface AddInterface extends Remote
{
public int sum(int n1, int n2) throws RemoteException
}
//Add.java
import java.rmi.*;
import java.rmi.server.*;
public class Add extends UnicastRemoteObject implements AddInterface
{
int num1, num2 ;
public Add() throws RemoteException
{
}
public int sum(int n1, int n2) throws RemoteException
{
num1=n1;
num2=n2;
return n1+n2;
}
}
//AddServer.java
import java.rmi.Naming;
public class AddServer
{
public static void main(String args[])
{
try
{
Naming.rebind("Add",new Add());
System.out.println("Server is connected and waiting for client");
}
catch(Exception e)
{
System.out.println("server could not connect:"+e);
}
}
}
//AddClient.java
import java.rmi.Naming;
public class AddClient
{
public static void main(String args[])
{
try
{
AddInterface ai=(AddInterface)Naming.lookup("//localhost/Add");
System.out.println("The sum of two nos. is :"+ai.sum(10,2));
}
catch(Exception e)
{
System.out.println("Client Exception:"+e);
}
}
}

@ -0,0 +1,36 @@
Creating a Non-Blocking Socket
public class test
{
public static void main(String args[])
{
// Create a non-blocking socket and check for connections
try {
// Create a non-blocking socket channel on port 8080
SocketChannel sChannel = createSocketChannel("www.xxx", 8080);
// Before the socket is usable, the connection must be completed
// by calling finishConnect(), which is non-blocking
while (!sChannel.finishConnect()) {
// Do something else
System.out.println("wonderful");
}
// Socket channel is now ready to use
}
catch (IOException e) {
}
}
// Creates a non-blocking socket channel for the specified host name and port.
// connect() is called on the new channel before it is returned.
public static SocketChannel createSocketChannel(String hostName, int port) throws IOException
{
// Create a non-blocking socket channel
SocketChannel sChannel = SocketChannel.open();
sChannel.configureBlocking(false);
// Send a connection request to the server; this method is non-blocking
sChannel.connect(new InetSocketAddress(hostName, port));
return sChannel;
}
}

@ -0,0 +1,49 @@
DateClient
import java.net.*;
import java.io.*;
public class DateClient {
static final int LISTENING_PORT = 32007;
public static void main(String[] args) {
String computer; // Name of the computer to connect to.
Socket connection; // A socket for communicating with
// that computer.
Reader incoming; // Stream for reading data from
// the connection.
/* Get computer name from command line. */
if (args.length > 0)
computer = args[0];
else {
// No computer name was given. Print a message and exit.
System.out.println("Usage: java DateClient <server>");
return;
}
/* Make the connection, then read and display a line of text. */
try {
connection = new Socket( computer, LISTENING_PORT );
incoming = new InputStreamReader( connection.getInputStream() );
while (true) {
int ch = incoming.read();
if (ch == -1 || ch == '
' || ch == '
')
break;
System.out.print( (char)ch );
}
System.out.println();
incoming.close();
}
catch (Exception e) {
TextIO.putln("Error: " + e);
}
} // end main()
} //end class DateClient

@ -0,0 +1,61 @@
DateServer
import java.net.*;
import java.io.*;
import java.util.Date;
public class DateServe {
static final int LISTENING_PORT = 32007;
public static void main(String[] args) {
ServerSocket listener; // Listens for incoming connections.
Socket connection; // For communication with the
// connecting program.
/* Accept and process connections forever, or until
some error occurs. (Note that errors that occur
while communicating with a connected program are
caught and handled in the sendDate() routine, so
they will not crash the server.)
*/
try {
listener = new ServerSocket(LISTENING_PORT);
TextIO.putln("Listening on port " + LISTENING_PORT);
while (true) {
connection = listener.accept();
sendDate(connection);
}
}
catch (Exception e) {
TextIO.putln("Sorry, the server has shut down.");
TextIO.putln("Error: " + e);
return;
}
} // end main()
static void sendDate(Socket client) {
// The parameter, client, is a socket that is
// already connected to another program. Get
// an output stream for the connection, send the
// current date, and close the connection.
try {
System.out.println("Connection from " +
client.getInetAddress().toString() );
Date now = new Date(); // The current data and time.
PrintWriter outgoing; // Stream for sending data.
outgoing = new PrintWriter( client.getOutputStream() );
outgoing.println( now.toString() );
outgoing.flush(); // Make sure the data is actually sent!
client.close();
}
catch (Exception e){
System.out.println("Error: " + e);
}
} // end sendDate()
} //end class DateServe

@ -0,0 +1,66 @@
FTPLogin
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.net.Socket;
public class FTPLogin
{
public static void main (String args[])
{
Socket socket = null;
BufferedReader in = null;
PrintWriter out = null;
String line = null;
if (args.length != 3)
{
System.out.println ("USAGE: IP USER PASS");
}
else
{
try
{
socket = new Socket (args[0], 21);
in = new BufferedReader (new InputStreamReader(socket.getInputStream()));
out = new PrintWriter (socket.getOutputStream());
out.print("user "+ args[1] + "
");
out.print("pass "+ args[2] + "
");
out.print ("pwd
");
out.print ("quit
");
out.flush();
while ( (line = in.readLine()) != null)
{
System.out.println(line);
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
out.close();
in.close();
socket.close();
}
catch (Exception fe)
{
System.out.println ("RESOURCE CLOSE EXCEPTION " +fe.getMessage());
}
}
} //end else
} //end main
} //end class

@ -0,0 +1,69 @@
// IPC CLient Program
import java.net.*;
import java.io.*;
public class IPCClient
{
public static void main(String args[])
{
try
{
Socket s=new Socket("localhost",3128);
DataOutputStream dos=new DataOutputStream(s.getOutputStream());
DataInputStream dis=new DataInputStream(s.getInputStream());
InputStreamReader isr=new InputStreamReader(System.in);
System.out.println("......Client PROCESS STARTED....");
System.out.println("Enter the value of 1 and 2 to pass the server process");
BufferedReader br=new BufferedReader(isr);
int a=Integer.parseInt(br.readLine());
System.out.println("\Number 1="+a);
dos.writeInt(+a);
int b=Integer.parseInt(br.readLine());
System.out.println("\Number 2="+b);
dos.writeInt(+b);
int result=dis.readInt();
System.out.println("Client Process has receieved result from server\n..");
s.close();
}
catch(Exception e)
{
System.out.println("Exception "+e);
}
}
}
//IPC Server
import java.net.*;
import java.io.*;
public class IPCServer
{
public static void main(String args[])
{
System.out.println("......INTERPROCESS COMMUNICATION....");
System.out.println("......SERVER PROCESS STARTED....");
System.out.println("......SERVER IS READY AND WAITING TO RECEIVE DATA FROM CLIENT FROM PORT...."+3128);
try
{
ServerSocket ss=new ServerSocket(3128);
Socket clientSocket=ss.accept();
System.out.println("Client is connected with IP Address"+clientSocket.getInetAddress()+"And Port no"+clientSocket.getPort());
DataOutputStream dos=new DataOutputStream(clientSocket.getOutputStream());
DataInputStream dis=new DataInputStream(clientSocket.getInputStream());
int a=dis.readInt();
System.out.println("Server recievd");
System.out.println("\Number 1="+a);
int b=dis.readInt();
System.out.println("\Number 2="+b);
int c=a+b;
dos.writeInt(c);
System.out.println("Server Process has executed..Requested process and sent result"+c+"To the Client\n");
clientSocket.close();
}
catch(Exception e)
{
System.out.println("Exception "+e);
}
}
}

@ -0,0 +1,92 @@
import java.io.*;
class apriori
{
public static void main(String []arg)throws IOException
{
int i,j,m=0;
int t1=0;
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of transaction :");
int n=Integer.parseInt(b.readLine());
System.out.println("items :1--Milk 2--Bread 3--Coffee 4--Juice 5--Cookies 6--Jam");
int item[][]=new int[n][6];
for(i=0; i<n; i++)
for(j=0; j<6; j++)
item[i][j]=0;
String[] itemlist= {"MILK","BREAD","COFFEE","JUICE","COOKIES","JAM"};
int nt[]=new int[6];
int q[]=new int[6];
for(i=0; i<n; i++)
{
System.out.println("Transaction "+(i+1)+" :");
for(j=0; j<6; j++)
{
//System.out.println(itemlist[j]);
System.out.println("Is Item "+itemlist[j]+" present in this transaction(1/0)? :");
item[i][j]=Integer.parseInt(b.readLine());
}
}
for(j=0; j<6; j++)
{
for(i=0; i<n; i++)
{
if(item[i][j]==1)
nt[j]=nt[j]+1;
}
System.out.println("Number of Item "+itemlist[j]+" :"+nt[j]);
}
for(j=0; j<6; j++)
{
if(((nt[j]/(float)n)*100)>=50)
q[j]=1;
else
q[j]=0;
if(q[j]==1)
{
t1++;
System.out.println("Item "+itemlist[j]+" is selected ");
}
}
for(j=0; j<6; j++)
{
for(i=0; i<n; i++)
{
if(q[j]==0)
{
item[i][j]=0;
}
}
}
int nt1[][]=new int[6][6];
for(j=0; j<6; j++)
{
for(m=j+1; m<6; m++)
{
for(i=0; i<n; i++)
{
if(item[i][j]==1 &&item[i][m]==1)
{
nt1[j][m]=nt1[j][m]+1;
}
}
if(nt1[j][m]!=0)
System.out.println("Number of Items of "+itemlist[j]+"& "+itemlist[m]+" :"+nt1[j][m]);
}
}
for(j=0; j<6; j++)
{
for(m=j+1; m<6; m++)
{
if(((nt1[j][m]/(float)n)*100)>=50)
q[j]=1;
else
q[j]=0;
if(q[j]==1)
{
System.out.println("Item "+itemlist[j]+"& "+itemlist[m]+" is selected ");
}
}
}
}
}

@ -0,0 +1,187 @@
package tutorial.clustering;
import de.lmu.ifi.dbs.elki.algorithm.AbstractDistanceBasedAlgorithm;
import de.lmu.ifi.dbs.elki.data.type.TypeInformation;
import de.lmu.ifi.dbs.elki.distance.distancefunction.DistanceFunction;
import de.lmu.ifi.dbs.elki.distance.distancevalue.NumberDistance;
import de.lmu.ifi.dbs.elki.logging.Logging;
import de.lmu.ifi.dbs.elki.result.Result;
public class NaiveAgglomerativeHierarchicalClustering<O, D extends NumberDistance<D, ?>>
extends AbstractDistanceBasedAlgorithm<O, D, Result>
{
protected NaiveAgglomerativeHierarchicalClustering(DistanceFunction<? super O, D> distanceFunction)
{
super(distanceFunction);
// TODO Auto-generated constructor stub
}
public TypeInformation[] getInputTypeRestriction()
{
// TODO Auto-generated method stub
return null;
}
protected Logging getLogger()
{
// TODO Auto-generated method stub
return null;
}
}
/**
* Static class logger.
*/
private static final Logging LOG = Logging.getLogger(NaiveAgglomerativeHierarchicalClustering.class);
protected Logging getLogger()
{
return LOG;
}
public TypeInformation[] getInputTypeRestriction()
{
return TypeUtil.array(
getDistanceFunction().getInputTypeRestriction()
);
}
// The run method
public Result run(Database db, Relation<O> relation)
{
return null;
}
DistanceQuery<O, D> dq = db.getDistanceQuery(relation, getDistanceFunction());
ArrayDBIDs ids = DBIDUtil.ensureArray(relation.getDBIDs());
final int size = ids.size();
LOG.verbose("Notice: SLINK is a much faster algorithm for single-linkage clustering!");
Computing the distance matrix
double[][] matrix = new double[size][size];
DBIDArrayIter ix = ids.iter(), iy = ids.iter();
for (int x = 0; ix.valid(); x++, ix.advance())
{
iy.seek(0);
for (int y = 0; y < x; y++, iy.advance())
{
final double dist = dq.distance(ix, iy).doubleValue();
matrix[x][y] = dist;
matrix[y][x] = dist;
}
}
Algorithm main loop
final int stop = size - numclusters;
FiniteProgress prog = LOG.isVerbose() ?
new FiniteProgress("Agglomerative clustering", stop, LOG)
: null;
for (int i = 0; i < stop; i++)
{
// TODO: find clusters to merge
// TODO: store the merge in auxillary data
// TODO: update distance matrix
if (prog != null)
{
prog.incrementProcessed(LOG);
}
}
if (prog != null)
{
prog.ensureCompleted(LOG);
}
double min = Double.POSITIVE_INFINITY;
int minx = -1, miny = -1;
for (int x = 0; x < size; x++)
{
if (height[x] < Double.POSITIVE_INFINITY)
{
continue;
}
for (int y = 0; y < x; y++)
{
if (height[y] < Double.POSITIVE_INFINITY)
{
continue;
}
if (matrix[x][y] < min)
{
min = matrix[x][y];
minx = x;
miny = y;
}
}
}
// Avoid allocating memory, by reusing existing iterators:
ix.seek(minx);
iy.seek(miny);
// Perform merge in data structure: x -> y
// Since y < x, prefer keeping y, dropping x.
height[minx] = min;
parent.set(minx, iy);
// Merge into cluster
ModifiableDBIDs cx = clusters.get(minx);
ModifiableDBIDs cy = clusters.get(miny);
if (cy == null)
{
cy = DBIDUtil.newHashSet();
cy.add(iy);
}
if (cx == null)
{
cy.add(ix);
}
else
{
cy.addDBIDs(cx);
clusters.remove(minx);
}
clusters.put(miny, cy);
// Update distance matrix for y:
for (int j = 0; j < size; j++)
{
matrix[j][miny] = Math.min(matrix[j][minx], matrix[j][miny]);
matrix[miny][j] = Math.min(matrix[minx][j], matrix[miny][j]);
}
Returning a Clustering
final Clustering<Model> dendrogram = new Clustering<>(
"Hierarchical-Clustering", "hierarchical-clustering");
for (int x = 0; x < size; x++)
{
if (height[x] < Double.POSITIVE_INFINITY)
{
continue;
}
DBIDs cids = clusters.get(x);
// For singleton objects, this may be null.
if (cids == null)
{
ix.seek(x);
cids = DBIDUtil.deref(ix);
}
Cluster<Model> cluster = new Cluster<>("Cluster", cids);
dendrogram.addToplevelCluster(cluster);
}
return dendrogram;
Updating the constructor
/**
* Threshold, how many clusters to extract.
*/
int numclusters;
public NaiveAgglomerativeHierarchicalClustering(
DistanceFunction<? super O, D> distanceFunction,
int numclusters)
{
super(distanceFunction);
this.numclusters = numclusters;
}
Adding a Parameterizer
public static class Parameterizer<O, D extends NumberDistance<D, ?>>
extends AbstractDistanceBasedAlgorithm.Parameterizer<O, D>
{
int numclusters = 0;
protected void makeOptions(Parameterization config)
{
super.makeOptions(config);
IntParameter numclustersP = new IntParameter(SLINK.Parameterizer.SLINK_MINCLUSTERS_ID);
numclustersP.addConstraint(new GreaterEqualConstraint(1));
if (config.grab(numclustersP))
{
numclusters = numclustersP.intValue();
}
}
protected NaiveAgglomerativeHierarchicalClustering<O, D> makeInstance()
{
return new NaiveAgglomerativeHierarchicalClustering<>(distanceFunction, numclusters);
}
}

@ -0,0 +1,138 @@
import java.util.*;
class k_means
{
static int count1,count2,count3;
static int d[];
static int k[][];
static int tempk[][];
static double m[];
static double diff[];
static int n,p;
static int cal_diff(int a) // This method will determine the cluster in which an element go at a particular step.
{
int temp1=0;
for(int i=0; i<p; ++i)
{
if(a>m[i])
diff[i]=a-m[i];
else
diff[i]=m[i]-a;
}
int val=0;
double temp=diff[0];
for(int i=0; i<p; ++i)
{
if(diff[i]<temp)
{
temp=diff[i];
val=i;
}
}//end of for loop
return val;
}
static void cal_mean() // This method will determine intermediate mean values
{
for(int i=0; i<p; ++i)
m[i]=0; // initializing means to 0
int cnt=0;
for(int i=0; i<p; ++i)
{
cnt=0;
for(int j=0; j<n-1; ++j)
{
if(k[i][j]!=-1)
{
m[i]+=k[i][j];
++cnt;
}
}
m[i]=m[i]/cnt;
}
}
static int check1() // This checks if previous k ie. tempk and current k are same.Used as terminating case.
{
for(int i=0; i<p; ++i)
for(int j=0; j<n; ++j)
if(tempk[i][j]!=k[i][j])
{
return 0;
}
return 1;
}
public static void main(String args[])
{
Scanner scr=new Scanner(System.in);
/* Accepting number of elements */
System.out.println("Enter the number of elements ");
n=scr.nextInt();
d=new int[n];
/* Accepting elements */
System.out.println("Enter "+n+" elements: ");
for(int i=0; i<n; ++i)
d[i]=scr.nextInt();
/* Accepting num of clusters */
System.out.println("Enter the number of clusters: ");
p=scr.nextInt();
/* Initialising arrays */
k=new int[p][n];
tempk=new int[p][n];
m=new double[p];
diff=new double[p];
/* Initializing m */
for(int i=0; i<p; ++i)
m[i]=d[i];
int temp=0;
int flag=0;
do
{
for(int i=0; i<p; ++i)
for(int j=0; j<n; ++j)
{
k[i][j]=-1;
}
for(int i=0; i<n; ++i) // for loop will cal cal_diff(int) for every element.
{
temp=cal_diff(d[i]);
if(temp==0)
k[temp][count1++]=d[i];
else if(temp==1)
k[temp][count2++]=d[i];
else if(temp==2)
k[temp][count3++]=d[i];
}
cal_mean(); // call to method which will calculate mean at this step.
flag=check1(); // check if terminating condition is satisfied.
if(flag!=1)
/*Take backup of k in tempk so that you can check for equivalence in next step*/
for(int i=0; i<p; ++i)
for(int j=0; j<n; ++j)
tempk[i][j]=k[i][j];
System.out.println("\n\nAt this step");
System.out.println("\nValue of clusters");
for(int i=0; i<p; ++i)
{
System.out.print("K"+(i+1)+"{ ");
for(int j=0; k[i][j]!=-1 && j<n-1; ++j)
System.out.print(k[i][j]+" ");
System.out.println("}");
}//end of for loop
System.out.println("\nValue of m ");
for(int i=0; i<p; ++i)
System.out.print("m"+(i+1)+"="+m[i]+" ");
count1=0;
count2=0;
count3=0;
}
while(flag==0);
System.out.println("\n\n\nThe Final Clusters By Kmeans are as follows: ");
for(int i=0; i<p; ++i)
{
System.out.print("K"+(i+1)+"{ ");
for(int j=0; k[i][j]!=-1 && j<n-1; ++j)
System.out.print(k[i][j]+" ");
System.out.println("}");
}
}
}

@ -0,0 +1,81 @@
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class Squarer
{
private BlockingQueue<Integer> in;
private BlockingQueue<SquareResult> out;
Squarer(BlockingQueue<Integer> request, BlockingQueue<SquareResult> replies)
{
this.in = request;
this.out = replies;
}
public void start()
{
new Thread(new Runnable()
{
public void run()
{
while(true)
{
try
{
int x = in.take();
int y = x*x;
Thread.sleep(2000);
System.out.println("OK, got it. Calculating..");
Thread.sleep(4000);
out.put(new SquareResult(x,y));
}
catch(InterruptedException e)
{
System.out.println("interrupted yo");
}
}
}
}).start();
}
}
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class SquareKaro
{
public static void main(String[] args)
{
BlockingQueue<Integer> number = new LinkedBlockingQueue<>();
BlockingQueue<SquareResult> result = new LinkedBlockingQueue<>();
Squarer mysquarer = new Squarer(number, result);
mysquarer.start();
try
{
System.out.println("Hey another process, give me square of => 54");
number.put(54);
System.out.println(result.take());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public class SquareResult
{
private int input;
private int output;
public SquareResult(int in, int out)
{
this.input = in;
this.output = out;
}
@Override public String toString()
{
return input +" ka square hai "+output;
}
}

@ -0,0 +1,54 @@
import java.util.Scanner;
class LoadBalancer
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of servers:");
int servers=sc.nextInt();
System.out.println();
System.out.print("Enter the number of processes:");
int Processes=sc.nextInt();
while(true)
{
printLoad(servers,Processes);
System.out.println("1.Add Servers 2.Remote Servers 3.Add Processes 4.Remove Processes 5.Exit :");
switch(sc.nextInt())
{
case 1:
System.out.print("How many more servers?:");
servers+=sc.nextInt();
break;
case 2:
System.out.print("How many servers to remove?:");
servers-=sc.nextInt();
break;
case 3:
System.out.print("How many more Processes?:");
Processes+=sc.nextInt();
break;
case 4:
System.out.print("How many Processes to remove?:");
Processes-=sc.nextInt();
break;
case 5:
return;
}
}
}
static void printLoad(int servers,int Processes)
{
int each=Processes/servers;
int extra=Processes%servers;
int total=0;
for(int i=0; i<servers; i++)
{
if(extra-->0)total=each+1;
else total=each;
System.out.println("Server "+(char)('A'+i)+" has "+total+" Processes");
}
}
}

@ -0,0 +1,83 @@
Multi ClassLoader Demo
import java.net.URLClassLoader;
import java.net.URL;
import java.io.File;
public class MultiCLDemo
{
public static void main(String[] args)
{
if (args.length<3)
{
System.out.println("Usage: java MultiCLDemo "+" ...");
System.out.println("Loads and runs toString() on class_name "+"found in each subDir.");
System.exit(0);
}
try
{
String className = args[0];
int count = args.length-1;
URL tmpURL;
Object[] objects = new Object[count];
URLClassLoader[] loaders = new URLClassLoader[count];
System.out.println("Loading "+count+" different classes "+"named: "+className);
for (int i=0; i {
tmpURL = new File(args[i+1]).toURL();
System.out.println("\nLoading from: "+tmpURL);
loaders[i] = new URLClassLoader(new URL[] { tmpURL });
objects[i] = loaders[i].loadClass(className).newInstance();
for (int k=0; k<=i; k++)
{
System.out.println("Got object: "+objects[k]);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
/*Some sample classes to load...
// c:\a/HelloWorld.java
public class HelloWorld
{
public String toString()
{
return "Hello";
}
}
// c:\b/HelloWorld.java
public class HelloWorld
{
public String toString()
{
return "World";
}
}
// c:\c/HelloWorld.java
public class HelloWorld
{
public String toString()
{
return "Hello World";
}
}
The code running...
java MultiCLDemo HelloWorld a b c
Loading 3 different classes named:
HelloWorldLoading from: file:/.../class_loader_demo/a/Got object:
HelloLoading from: file:/.../class_loader_demo/b/Got object:
HelloGot object: WorldLoading from: file:/.../class_loader_demo/c/Got object:
HelloGot object: WorldGot object: Hello World
regards, btcoburn*/

@ -0,0 +1,108 @@
// EchoServer.java
import java.io.*;
import java.net.*;
public class EchoServer implements Runnable
{
Socket socket=null;
static ServerSocket ss;
EchoServer(Socket newSocket)
{
this.socket=newSocket;
}
public static void main(String args[]) throws IOException
{
ss=new ServerSocket(7000);
System.out.println("Server Started");
while(true)
{
Socket s = ss.accept();
EchoServer es = new EchoServer(s);
Thread t = new Thread(es);
t.start();
}
}
public void run()
{
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true)
{
System.out.println(in.readLine());
}
}
catch(Exception e)
{}
}
}
// EchoClientOne.java
import java.io.*;
import java.net.*;
public class EchoClientOne
{
public static void main(String args[])throws IOException
{
Socket s=new Socket("localhost",7000);
PrintStream out = new PrintStream(s.getOutputStream());
ServerSocket ss = new ServerSocket(7001);
Socket s1 = ss.accept();
BufferedReader in1 = new BufferedReader(new InputStreamReader(s1.getInputStream()));
PrintStream out1 = new PrintStream(s1.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str="Token";
while(true)
{
if(str.equalsIgnoreCase("Token"))
{
System.out.println("Do you want to send some data");
System.out.println("Enter Yes or No");
str=br.readLine();
if(str.equalsIgnoreCase("Yes"))
{
System.out.println("Enter the data");
str=br.readLine();
out.println(str);
}
out1.println("Token");
}
System.out.println("Waiting for Token");
str=in1.readLine();
}
}
}
// EchoClientTwo.java
import java.io.*;
import java.net.*;
public class EchoClientTwo
{
public static void main(String args[])throws IOException
{
Socket s=new Socket("localhost",7000);
PrintStream out = new PrintStream(s.getOutputStream());
Socket s2=new Socket("localhost",7001);
BufferedReader in2 = new BufferedReader(new InputStreamReader(s2.getInputStream()));
PrintStream out2 = new PrintStream(s2.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
while(true)
{
System.out.println("Waiting for Token");
str=in2.readLine();
if(str.equalsIgnoreCase("Token"))
{
System.out.println("Do you want to send some data");
System.out.println("Enter Yes or No");
str=br.readLine();
if(str.equalsIgnoreCase("Yes"))
{
System.out.println("Enter the data");
str=br.readLine();
out.println(str);
}
out2.println("Token");
}
}
}
}

@ -0,0 +1,47 @@
import java.util.*;
class MyThread implements Runnable
{
private Thread t;
private String ThreadName;
MyThread(String name)
{
ThreadName = name;
}