Thursday, November 24, 2011

Basic Priority queue in C

The source code of basic priority queue is given :
#include<stdio.h>
#include<malloc.h>

void insert();
void del();
void display();



struct node
    {

        int priority;
        int info;
        struct node *next;
    }*start, *q, *temp, *new;

typedef struct node *N;

int main()
{
    int ch;

    do
     {
            printf( "\n[1] INSERTION\t[2] DELETION\t[3] DISPLAY [4] EXIT\t:" );
            scanf( "%d", &ch );

            switch ( ch )
                {
                case 1:
                    insert();
                    break;
                case 2:
                    del();
                    break;
                case 3:
                    display();
                    break;
                case 4:
                    break;
                }
        }

    while ( ch < 4 );
}



void insert()
{

    int item, itprio;
    new = ( N* ) malloc( sizeof( N ) );

    printf( "ENTER THE ELT.TO BE INSERTED :\t" );
    scanf( "%d", &item );
    printf( "ENTER ITS PRIORITY :\t" );
    scanf( "%d", &itprio );
    new->info = item;
    new->priority = itprio;

    if ( start == NULL || itprio < start->priority )
    {
        new->next = start;
        start = new;
    }
    else
        {
            q = start;
            while ( q->next != NULL && q->next->priority <= itprio )
                q = q->next;

            new->next = q->next;
            q->next = new;
        }
}

void del()
{
    if ( start == NULL )
    {
         printf( "\nQUEUE UNDERFLOW\n" );
    }
    else
    {
    new = start;
    printf( "\nDELETED ITEM IS %d\n", new->info );
    start = start->next;
    free( start );

    }

}

void display()
{
    temp = start;
    if ( start == NULL )
        printf( "QUEUE IS EMPTY\n" );

    else
    {
        printf( "QUEUE IS:\n" );

        while ( temp != NULL )
        {
            printf( "\t%d[priority=%d]", temp->info, temp->priority );
            temp = temp->next;
        }
     }
}

Thursday, November 10, 2011

Hadoop Simple Indexer source code with Map reduce

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package lineindexer;

/**
 *
 * @author masteruser
 */
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.filecache.DistributedCache;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.FileSplit;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class Main extends Configured implements Tool{



  public static class LineIndexMapper extends MapReduceBase
      implements Mapper<LongWritable, Text, Text, Text> {

    private final static Text word = new Text();
    private final static Text location = new Text();

    public void map(LongWritable key, Text val,
        OutputCollector<Text, Text> output, Reporter reporter)
        throws IOException {

      FileSplit fileSplit = (FileSplit)reporter.getInputSplit();
      String fileName = fileSplit.getPath().getName();
      location.set(fileName);

      String line = val.toString();
      StringTokenizer itr = new StringTokenizer(line.toLowerCase());
      while (itr.hasMoreTokens()) {
        word.set(itr.nextToken());
        output.collect(word, location);
      }
    }
  }



  public static class LineIndexReducer extends MapReduceBase
      implements Reducer<Text, Text, Text, Text> {

    public void reduce(Text key, Iterator<Text> values,
        OutputCollector<Text, Text> output, Reporter reporter)
        throws IOException {

      boolean first = true;
      StringBuilder toReturn = new StringBuilder();
      while (values.hasNext()){
        if (!first)
          toReturn.append(", ");
        first=false;
        toReturn.append(values.next().toString());
      }

      output.collect(key, new Text(toReturn.toString()));
    }
  }


  /**
   * The actual main() method for our program; this is the
   * "driver" for the MapReduce job.
   */


  public int run(String[] args) throws Exception {
         JobConf conf = new JobConf(getConf(), Main.class);
         conf.setJobName("LineIndexer");

          conf.setOutputKeyClass(Text.class);
          conf.setOutputValueClass(Text.class);

          conf.setMapperClass(LineIndexMapper.class);
             conf.setReducerClass(LineIndexReducer.class);

          conf.setInputFormat(TextInputFormat.class);
             conf.setOutputFormat(TextOutputFormat.class);

     
         int i=args.length;
           
         

          FileInputFormat.setInputPaths(conf, new Path(args[i-2]));
          FileOutputFormat.setOutputPath(conf, new Path(args[i-1]));

          JobClient.runJob(conf);
          return 0;
       }


  public static void main(String[] args) throws Exception {
  

          int res = ToolRunner.run(new Configuration(), new Main(), args);
          System.exit(res);
    
  }
}

Tuesday, November 1, 2011

SCTP server client Code in C




Client.c
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/sctp.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

#define RECVBUFSIZE     4096
#define PPID            1234

int main()
{
       int SctpScocket, in, flags;
       socklen_t opt_len;
       char * szAddress;
       int iPort;
       char * szMsg;
       int iMsgSize;
       char a[1024];

    
       struct sockaddr_in servaddr = {0};
       struct sctp_status status = {0};
       struct sctp_sndrcvinfo sndrcvinfo = {0};
       struct sctp_event_subscribe events = {0};
       struct sctp_initmsg initmsg = {0};
       char * szRecvBuffer[RECVBUFSIZE + 1] = {0};
       socklen_t from_len = (socklen_t) sizeof(struct sockaddr_in);


       //get the arguments
       szAddress = "127.0.0.1";
       iPort = 5001;
      
       printf("Starting SCTP client connection to %s:%u\n", szAddress, iPort);

     
       SctpScocket = socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP);
       printf("socket created...\n");

       //set the association options
       initmsg.sinit_num_ostreams = 1;
       setsockopt( SctpScocket, IPPROTO_SCTP, SCTP_INITMSG, &initmsg,sizeof(initmsg));
       printf("setsockopt succeeded...\n");

       bzero( (void *)&servaddr, sizeof(servaddr) );
       servaddr.sin_family = AF_INET;
       servaddr.sin_port = htons(iPort);
       servaddr.sin_addr.s_addr = inet_addr( szAddress );

      
       connect( SctpScocket, (struct sockaddr *)&servaddr, sizeof(servaddr));
       printf("connect succeeded...\n");

       //check status
       opt_len = (socklen_t) sizeof(struct sctp_status);
       getsockopt(SctpScocket, IPPROTO_SCTP, SCTP_STATUS, &status, &opt_len);
      
       while(1)
       {
       printf("Sending Role  to server: ");
       gets(a);
       sctp_sendmsg(SctpScocket, (const void *)a, iMsgSize, NULL, 0,htonl(PPID), 0, 0 , 0, 0);

       //read response from test server
       in = sctp_recvmsg(SctpScocket, (void*)szRecvBuffer, RECVBUFSIZE,(struct sockaddr *)&servaddr, &from_len, &sndrcvinfo, &flags);
       if (in > 0 && in < RECVBUFSIZE - 1)
       {
               szRecvBuffer[in] = 0;
               printf("Received from server: %s\n",szRecvBuffer);
        }
      } 
       printf("exiting...\n");

       close(SctpScocket);
       return 0;
}




Server.c

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/sctp.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

#define RECVBUFSIZE             4096
#define PPID                    1234

int main() {
       int SctpScocket, n, flags;
       socklen_t from_len;

       struct sockaddr_in addr = {0};
       struct sctp_sndrcvinfo sinfo = {0};
       struct sctp_event_subscribe event = {0};
       char pRecvBuffer[RECVBUFSIZE + 1] = {0};

       char * szAddress;
       int iPort;
       char * szMsg;
       int iMsgSize;

       //get the arguments
       szAddress = "127.0.0.1";
       iPort = 5001;
       szMsg = "Hello Client";
       iMsgSize = strlen(szMsg);
       if (iMsgSize > 1024)
       {
               printf("Message is too big for this test\n");
               return 0;
       }

       //here we may fail if sctp is not supported
       SctpScocket = socket(AF_INET, SOCK_SEQPACKET, IPPROTO_SCTP);
       printf("socket created...\n");

       //make sure we receive MSG_NOTIFICATION
       setsockopt(SctpScocket, IPPROTO_SCTP, SCTP_EVENTS, &event,sizeof(struct sctp_event_subscribe));
       printf("setsockopt succeeded...\n");

       addr.sin_family = AF_INET;
       addr.sin_port = htons(iPort);
       addr.sin_addr.s_addr = inet_addr(szAddress);

       //bind to specific server address and port
       bind(SctpScocket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in));
       printf("bind succeeded...\n");

       //wait for connections
       listen(SctpScocket, 1);
       printf("listen succeeded...\n");

        int count = 0,i;
        char a[20][10],d[20][10];
        char send_data[1024];

        strcpy(a[0],"Abraham");
        strcpy(a[1],"Buck");
        strcpy(a[2],"Casper");
        strcpy(a[3],"Dammy");
        strcpy(d[0],"1");
        strcpy(d[1],"2");
        strcpy(d[2],"3");
        strcpy(d[3],"4");



       while(1)
       {
               //each time erase the stuff
               flags = 0;
               memset((void *)&addr, 0, sizeof(struct sockaddr_in));
               from_len = (socklen_t)sizeof(struct sockaddr_in);
               memset((void *)&sinfo, 0, sizeof(struct sctp_sndrcvinfo));

               n = sctp_recvmsg(SctpScocket, (void*)pRecvBuffer, RECVBUFSIZE,(struct sockaddr *)&addr, &from_len, &sinfo, &flags);
               if (-1 == n)
               {
                       printf("Error with sctp_recvmsg: -1... waiting\n");
                       printf("errno: %d\n", errno);
                       perror("Description: ");
                       sleep(1);
                       continue;
               }

               if (flags & MSG_NOTIFICATION)
               {
                       printf("Notification received!\n");
                       printf("From %s:%u\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
               }
               else
               {
                       printf("Received from %s:%u on stream %d, PPID %d.: %s\n",
                               inet_ntoa(addr.sin_addr),
                               ntohs(addr.sin_port),
                               sinfo.sinfo_stream,
                               ntohl(sinfo.sinfo_ppid),
                               pRecvBuffer
                       );

             int p = 0;
                     for(i=0;i<4;i++)
                     {
                        if(strcmp(pRecvBuffer,d[i]) == 0)
                        {
                             strcpy(send_data,a[i]);p=1;
                        }
                     }
                     if(p == 0)
                      strcpy(send_data,"No one on that role.");

               }

               //send message to client
               printf("Sending to client: %s\n", send_data);
               sctp_sendmsg(SctpScocket, (const void *)send_data, strlen(send_data), (struct sockaddr *)&addr, from_len, htonl(PPID), 0, 0 /*stream 0*/, 0, 0);

               //close server when exit is received
               if (0 == strcmp(pRecvBuffer, "exit"))
               {
                       break;
               }
       }//while

       printf("exiting...\n");

       close(SctpScocket);
       return (0);
}
 
To run this you have to have sctp library installed. then comand like >>$ gcc -g -lsctp filename

Thursday, October 20, 2011

Multithreading in C in Different CPU core

# define _GNU_SOURCE
# include <stdio.h>
# include <math.h>
# include <stdlib.h>
# include <pthread.h>
# include <stdlib.h>

pthread_mutex_t mux = PTHREAD_MUTEX_INITIALIZER;


struct p2p{
int st;
int en;
};

void *primeChk(void* val);

int main()
{
  pthread_t thread1,thread2,thread3,thread4;
  struct p2p valu1,valu2,valu3,valu4;
  int j,ret1,ret2,ret3,ret4;
  cpu_set_t cpuset;

// pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);


  valu1.st = 1;
  valu1.en = 5000;
  valu2.st = 5001;
  valu2.en = 10000;
  valu3.st = 10001;
  valu3.en = 15000;
  valu4.st = 15001;
  valu4.en = 20000;

   // initialization
   CPU_ZERO(&cpuset);


   CPU_SET(0,&cpuset);
   pthread_setaffinity_np(thread1, sizeof(cpu_set_t), &cpuset);
   ret1 = pthread_create(&thread1,NULL,&primeChk,(void*)&valu1);
   //CPU_ZERO(&cpuset); 

   CPU_SET(1,&cpuset);
   pthread_setaffinity_np(thread2, sizeof(cpu_set_t), &cpuset);
   ret2 = pthread_create(&thread2,NULL,&primeChk,(void*)&valu2);
  // CPU_ZERO(&cpuset);
/*      
    CPU_SET(2,&cpuset);
    pthread_setaffinity_np(thread3, sizeof(cpu_set_t), &cpuset);
    ret3 = pthread_create(&thread3,NULL,&primeChk,(void*)&valu3);
   
   CPU_SET(3,&cpuset);
   pthread_setaffinity_np(thread4, sizeof(cpu_set_t), &cpuset);
   ret4 = pthread_create(&thread4,NULL,&primeChk,(void*)&valu4);
  */

  pthread_join(thread1,NULL);
  pthread_join(thread2,NULL);
 // pthread_join(thread3,NULL);
 // pthread_join(thread4,NULL);

  return 0;
}


void *primeChk(void *val)
{
  struct p2p *valu = (struct p2p *)val;
  int str,end,i,k,j,l,m;

 // pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
  str = valu->st;
  end = valu->en;
  if(str == 1)
  printf("%d",++str);

  pthread_mutex_lock(&mux);
  for(i=str;i<=end;i++)
  {
     k = sqrt(i);l = 0;
     for(j=2;j<=k+1;j++)
     if(i % j == 0)
     {
        l = 1;break;
     }
     if(l == 0)printf(" %d",i);
  }
  pthread_mutex_unlock(&mux);

  //pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
 // printf("\nSet returned by pthread_getaffinity_np() contained:\n");
 // for (j = 0; j < CPU_SETSIZE; j++)
   //    if (CPU_ISSET(j, &cpuset))
    //   printf("    CPU %d\n", j);


}

Wednesday, October 19, 2011

UDP server client in c

Server

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

int main()
{
        int sock;
        int addr_len, bytes_read;
        char recv_data[1024],send_data[1024];
        struct sockaddr_in server_addr , client_addr;


        if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
            perror("Socket");
            exit(1);
        }

        server_addr.sin_family = AF_INET;
        server_addr.sin_port = htons(5000);
        server_addr.sin_addr.s_addr = INADDR_ANY;
        bzero(&(server_addr.sin_zero),8);


        if (bind(sock,(struct sockaddr *)&server_addr,
            sizeof(struct sockaddr)) == -1)
        {
            perror("Bind");
            exit(1);
        }

        addr_len = sizeof(struct sockaddr);

        printf("\nUDPServer Waiting for client on port 5000");
        fflush(stdout);

        int count = 0,i;
        char a[20][10],d[20][10];
        strcpy(a[0],"A");
        strcpy(a[1],"B");
        strcpy(a[2],"C");
        strcpy(a[3],"D");
        strcpy(d[0],"123");
        strcpy(d[1],"124");
        strcpy(d[2],"100");
        strcpy(d[3],"99");

        while (1)
        {

          bytes_read = recvfrom(sock,recv_data,1024,0,
                            (struct sockaddr *)&client_addr, &addr_len);


          recv_data[bytes_read] = '\0';

          printf("\n(%s , %d) said : ",inet_ntoa(client_addr.sin_addr),
                                       ntohs(client_addr.sin_port));
          printf("%s", recv_data);
          printf("SEND : ");
         // gets(send_data);

             int p = 0;
                 for(i=0;i<4;i++)
                 {
                        if(strcmp(recv_data,d[i]) == 0)
                        {
                             strcpy(send_data,a[i]);p=1;
                        }
                 }
                 if(p == 0)
                 strcpy(send_data,"No one on that role.");

          sendto(sock,send_data,strlen(send_data),0,(struct sockaddr *)&client_addr,sizeof(struct sockaddr));

          fflush(stdout);

        }
        return 0;
}
CLIENT
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

int main()
{
int sock,bytes_recv,sin_size;
struct sockaddr_in server_addr;
struct hostent *host;
char send_data[1024],recv_data[1024];

host= (struct hostent *) gethostbyname((char *)"127.0.0.1");


if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("socket");
exit(1);
}

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr = *((struct in_addr *)host->h_addr);
bzero(&(server_addr.sin_zero),8);
sin_size = sizeof(struct sockaddr);

   while (1)
   {

    printf("Type Something (q or Q to quit):");
    gets(send_data);

    if ((strcmp(send_data , "q") == 0) || strcmp(send_data , "Q") == 0)
       break;

    else
       sendto(sock, send_data, strlen(send_data), 0,
              (struct sockaddr *)&server_addr, sizeof(struct sockaddr));

         bytes_recv = recvfrom(sock,recv_data,1024,0,(struct sockaddr *)&server_addr,&sin_size);
          recv_data[bytes_recv]= '\0';
     printf("Received :%s\n",recv_data);
   }

}


Sunday, October 16, 2011

TCP server client in C

Client Code
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>


int main()

{

        int sock, bytes_recieved;
        char send_data[1024],recv_data[1024];
        struct hostent *host;
        struct sockaddr_in server_addr;

        host = gethostbyname("127.0.0.1");

        sock = socket(AF_INET, SOCK_STREAM,0);

        server_addr.sin_family = AF_INET;
        server_addr.sin_port = htons(5000);
        server_addr.sin_addr = *((struct in_addr *)host->h_addr);
        bzero(&(server_addr.sin_zero),8);

        connect(sock, (struct sockaddr *)&server_addr,sizeof(struct sockaddr));

        while(1)
        {

          bytes_recieved=recv(sock,recv_data,1024,0);
          recv_data[bytes_recieved] = '\0';

           printf("\nRecieved data = %s " , recv_data);
           printf("\nSend Data :");

           gets(send_data);

           send(sock,send_data,strlen(send_data), 0);

        }
return 0;
} 
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>


int main()
{
        int sock, connected, bytes_recieved , true = 1;
        char send_data [1024] , recv_data[1024];

        struct sockaddr_in server_addr,client_addr;
        int sin_size;

        sock = socket(AF_INET, SOCK_STREAM, 0);
       // setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int));

        server_addr.sin_family = AF_INET;
        server_addr.sin_port = htons(5000);
        server_addr.sin_addr.s_addr = INADDR_ANY;
        bzero(&(server_addr.sin_zero),8);
        printf("%d\n",sock);
        bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr));

        listen(sock, 5);
        printf("\nTCPServer Waiting for client on port 5000");
        fflush(stdout);
        int count = 0,i;
        char a[20][10],d[20][10];
        strcpy(a[0],"A");
        strcpy(a[1],"B");
        strcpy(a[2],"C");
        strcpy(a[3],"D");
        strcpy(d[0],"123");
        strcpy(d[1],"124");
        strcpy(d[2],"100");
        strcpy(d[3],"99");

        while(1)
        {

            sin_size = sizeof(struct sockaddr_in);

            connected = accept(sock, (struct sockaddr *)&client_addr,&sin_size);

            printf("\n I got a connection from (%s , %d)",
                   inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));

            while (1)
            {
                ++count;
                 printf("\n SEND : ");
                 //gets(send_data);

                 if(count == 1)
                 strcpy(send_data,"Welcome to TCPServer");
                 send(connected, send_data,strlen(send_data), 0);

                 bytes_recieved = recv(connected,recv_data,1024,0);

                 recv_data[bytes_recieved] = '\0';

                 printf("\n RECIEVED DATA = %s " , recv_data);
                 int p = 0;
                 for(i=0;i<4;i++)
                 {
                        if(strcmp(recv_data,d[i]) == 0)
                        {
                             strcpy(send_data,a[i]);p=1;
                        }
                 }
                 if(p == 0)
                 strcpy(send_data,"No one on that role.");
                 fflush(stdout);
            }
        }

      close(sock);
      return 0;
}

Monday, September 12, 2011

Video Conferencing Source code in JAVA

My video conferencing project was completed as 300 project for 3rd year.It is not totally completed. There is some bug in here.To solve these bugs and to help other students this project is open.It is first try to make a project open source in this way so it can be modified.Any kind of question against this project will be answered. As this project was created in 3rd year 1st semester and now i nearly completed my BSc. so there will be little description about this.I will try to describe every class and function later when i get the chance.


#######################################################
FEATURE 
#######################################################

1.Multi Chat(Used Threadpole)
2.P2P Chat
3.P2P Audio Chat
4.P2P Video Chat
5.Complete Automated
6.H.263 compression Video 
7.raw audio


PREREQUISITE: 
1. JUST INSTALL jmf-2.1.1 e
2.SQL

LINK OF THE SOURCE CODE

Monday, September 5, 2011

Desktop Inside Document Searcher


While I was working with lucene I tried to analyze it for the purpose of creating a demo search engine . From That I got the plan to make a search tool for pc which will search in .txt , .cpp,.pdf,.ppt,.doc as search engine do. Like If I have written sieve or kmp in any file my tool will find it ,rank it and give the location .After finding location just paste it in the explorer and it will give you the particular file.

Work Flow :

1.Indexed the particular drive.
2.Then search option enable
3. Give the input string for search
4.Output will be given rank wise in an area.
5. Copy the link and paste it to the explorer.
6.Cheachk is this you need.


There are three classes
1.RS.java (Main Class)
2.Indexer.java
3.Searcher.java

You must have to add the api of lucene here.


Rs.java

/**
 * @
 *
 *
 * @author sharma
 * @version 1.00 2010/7/16
 */

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.MalformedURLException;

import java.net.URLConnection;

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.SwingConstants;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Transparency;
import javax.swing.event.*;
import java.sql.*;
import java.util.*;
import java.net.URL;
import javax.imageio.ImageIO;
import java.lang.*;

import java.io.*;
import javax.swing.BoxLayout;

public class Rs extends JFrame {
    
    String name="";
    String str[] = new String[1000];
    int k,chk;
    StringBuilder builder;

    JLabel Send_lebel = new JLabel();
    JTextField send_bit = new JTextField();
    
    JLabel Rec_lebel = new JLabel();
    JTextArea rec_bit = new JTextArea();
    JTextField err = new JTextField();
    
    JButton gen = new JButton();
    JButton sen = new JButton();
    JButton cal = new JButton();
    JScrollPane scrollPane = new JScrollPane();
    int a[] = new int[100];
    int b[] = new int[100];
    WindowListener l;

    public Rs(){
        
        
        setTitle("INDEXER AND SEARCHER DEMO");
        setSize(600,453);
        setLocation(220,100);

        l = new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                setEnabled(true);
            }
        };
         setUndecorated(true);
        getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
        setVisible(true);
        jbinit();
        
    }
    
    
       void jbinit(){
             this.setResizable(false);
             this.getContentPane().setLayout(null);
             
             Send_lebel.setText("ADDRESS / TEXT");
             Send_lebel.setBounds(new Rectangle(18, 18, 150, 42));
             send_bit.setFont(new java.awt.Font("Dialog", 1, 12));
             send_bit.setText("");
             send_bit.setBounds(new Rectangle(18, 48, 156, 21));
             
             Rec_lebel.setText("LINKS:");
             Rec_lebel.setBounds(new Rectangle(330, 18, 132, 21));
             rec_bit.setFont(new java.awt.Font("Dialog", 1, 12));
             rec_bit.setText("");
             rec_bit.setBounds(new Rectangle(212,48,336,341));
             scrollPane.setBounds(new Rectangle(212, 48, 336, 341));
             
             gen.setBounds(new Rectangle(18, 100, 88, 24));
             gen.setFont(new java.awt.Font("Dialog", 1, 12));
             gen.setBorder(BorderFactory.createRaisedBevelBorder());
             gen.setMnemonic('I');
             gen.setText("INDEXING");     
             gen.addActionListener(new gen_actionAdapter(this));
            
             sen.setBounds(new Rectangle(118, 100, 88, 24));
             sen.setFont(new java.awt.Font("Dialog", 1, 12));
             sen.setBorder(BorderFactory.createRaisedBevelBorder());
             sen.setMnemonic('S');
             sen.setText("SEARCH");     
             sen.addActionListener(new sen_actionAdapter(this));
            
                     
                        
             
             this.getContentPane().add(Send_lebel, null);
             this.getContentPane().add(Rec_lebel, null);
             this.getContentPane().add(scrollPane,null);
             scrollPane.getViewport().add(rec_bit,null);
             this.getContentPane().add(send_bit, null);  
             this.getContentPane().add(gen,null);
             this.getContentPane().add(sen,null);      
               

               

    }

    public static void main(String[] args) {
       Rs jmain = new Rs();

       jmain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
    
   
// all button action
void gen_actionPerformed(ActionEvent e)
{

 String pre ="";
 String rc="";
          name = send_bit.getText().toLowerCase();
       
              
            try {
            
    
             
             rc = name;
             Indexer ind = new Indexer("D:",rc);
             pre += ind.pep;
                 
             rec_bit.setText(pre);
            }
            
            catch (Exception ex) {
          
            
        }
            
            
}

void sen_actionPerformed(ActionEvent e)
{
            String sp ="",nam;
            nam = send_bit.getText().toLowerCase();
            try {
                  Searcher sc =  new Searcher("D:",nam);
                  sp += sc.prs;
                  rec_bit.setText(sp);
                } 
                catch (Exception ep) 
                    {
                        System.out.print("failed writing"); 
                    } 
}



}



// all button class

class gen_actionAdapter implements java.awt.event.ActionListener {
Rs adaptee;

    gen_actionAdapter(Rs adaptee) {
    this.adaptee = adaptee;
  }
  public void actionPerformed(ActionEvent e) {
    adaptee.gen_actionPerformed(e);
  }
}


class sen_actionAdapter implements java.awt.event.ActionListener {
Rs adaptee;

    sen_actionAdapter(Rs adaptee) {
    this.adaptee = adaptee;
  }
  public void actionPerformed(ActionEvent e) {
    adaptee.sen_actionPerformed(e);
  }
}





Indexer.java




/**
 * @(#)Indexer.java
 *Lucene 2.9
 *
 * @author Sharma 
 * @version 1.00 2011/1/30
 * 
 *comand prompt
 *DwnlData\New Folder (2)\Thesis\Lucene - Opensource search Engine\lucene-1.9-final\src\java
 *java Indexer.java D: C:lucene
 */

import org.apache.lucene.analysis.standard.*;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import java.io.FileReader;

import java.io.IOException;



import java.util.*;
import java.io.*;
import java.lang.*;


public class Indexer {
    public  String prp="";
    public String pep="";
  /*public static void main(String[] args) throws Exception {
    if (args.length != 2) {
      throw new Exception("Usage: java " + Indexer.class.getName()
        + " <index dir> <data dir>");
    }
    File indexDir = new File(args[0]);   
    File dataDir = new File(args[1]);   
    long start = new Date().getTime();
    int numIndexed = index(indexDir, dataDir);
    long end = new Date().getTime();
    System.out.println("Indexing " + numIndexed + " files took "
      + (end - start) + " milliseconds");
  }
  */
  Indexer(String rs,String rp)
  {
      System.out.println(rs+" "+rp);
  
    File indexDir = new File(rs);   
    File dataDir = new File(rp);   
    long start = new Date().getTime();
    try{
        int numIndexed = index(indexDir, dataDir);
        long end = new Date().getTime();
        //System.out.println("Indexing " + numIndexed + " files took "
       // + (end - start) + " milliseconds");
        pep += "Indexing " + numIndexed + " files took "+ (end - start) + " milliseconds"+"\n";
        
    }
    catch(Exception e)
    {
        System.out.print(" "+e);
    }

  }
  
  // open an index and start file directory traversal
  public int index(File indexDir, File dataDir)
    throws IOException 
        {
            if (!dataDir.exists() || !dataDir.isDirectory()) 
            {
                throw new IOException(dataDir+ " does not exist or is not a directory");
               }
        IndexWriter writer = new IndexWriter(indexDir,new StandardAnalyzer(), true);
        writer.setUseCompoundFile(false);
        indexDirectory(writer, dataDir);
        int numIndexed = writer.docCount();
        writer.optimize();
        writer.close();    
        return numIndexed;
      }
      
    private void indexDirectory(IndexWriter writer, File dir)
    throws IOException {
    File[] files = dir.listFiles();
    for (int i = 0; i < files.length; i++) {
      File f = files[i];
      if (f.isDirectory()) {
        indexDirectory(writer, f);   
      } else if (f.getName().endsWith(".txt")|| f.getName().endsWith(".pdf")||f.getName().endsWith(".doc") ||f.getName().endsWith(".docx")) {   
        indexFile(writer, f);
      }
    }
  }
  
    // method to actually index a file using Lucene
  private void indexFile(IndexWriter writer, File f)
    throws IOException {
    if (f.isHidden() || !f.exists() || !f.canRead()) {
      return;
    }
   // System.out.println("Indexing " + f.getCanonicalPath());
    
     pep += "Indexing " + f.getCanonicalPath()+"\n";
     
     //rp.rec_bit.setText(pep);
    Document doc = new Document();
    doc.add(Field.Text("contents", new FileReader(f)));   
    doc.add(Field.Keyword("filename", f.getCanonicalPath()));
    writer.addDocument(doc);                  
  }
}





Searcher.java



/**
 * @(#)Searcher.java
 *
 *
 * @author Sharma
 * @version 1.00 2011/2/1
 */


import org.apache.lucene.analysis.standard.*;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.*;
import org.apache.lucene.store.RAMDirectory;
import java.io.FileReader;

import java.io.IOException;



import java.util.*;
import java.io.*;
import java.lang.*;
public class Searcher 
{
    String prs = "";

  /*public static void main(String[] args) throws Exception {
    if (args.length != 2) 
    {
        throw new Exception("Usage: java " + Searcher.class.getName()
        + " <index dir> <query>");
    }
    
    File indexDir = new File(args[0]);   
    String q = args[1];   
    if (!indexDir.exists() || !indexDir.isDirectory()) 
    {
      throw new Exception(indexDir +" does not exist or is not a directory.");
    }
    search(indexDir, q);
  }*/
  
    public  Searcher(String f, String q)
    throws Exception {
           
            File indexDir = new File(f);
            Directory fsDir = FSDirectory.getDirectory(indexDir, false);
            IndexSearcher is = new IndexSearcher(fsDir);   
            Query query = QueryParser.parse(q, "contents",new StandardAnalyzer());
    long start = new Date().getTime();
    Hits hits = is.search(query);    
    long end = new Date().getTime();
    System.err.println("Found " + hits.length() +" document(s) (in " + (end - start) +" milliseconds) that matched query '" + q + "':");
    prs += "Found " + hits.length() +" document(s) (in " + (end - start) +" milliseconds) that matched query '" + q + "':\n";
    for (int i = 0; i < hits.length(); i++) {
      Document doc = hits.doc(i); 
      prs += doc.get("filename");
      prs += "\n";                 
      System.out.println(doc.get("filename"));   
    }
  }
}



Saturday, August 20, 2011

Web Crawler or Site grabber code in java with Page downloader

/**
 * @Web Crawler *
 *
 * @author sharma
 * @version 1.00 2010/7/16
 */

import java.io.BufferedInputStream;

import java.io.IOException;

import java.net.MalformedURLException;

import java.util.*;

import java.net.URLConnection;



import java.awt.BorderLayout;

import java.awt.Color;

import javax.swing.JFrame;

import javax.swing.JTabbedPane;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JButton;

import javax.swing.SwingConstants;

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.awt.Transparency;

import javax.swing.event.*;

import java.sql.*;

import java.util.*;

import java.net.URL;

import javax.imageio.ImageIO;

import java.lang.*;



import java.io.*;

import javax.swing.BoxLayout;



public class assign_3 extends JFrame {

   

    String name="";

    String str[] = new String[1000];

    int k;

    StringBuilder builder;



    JLabel Send_lebel = new JLabel();

    JTextField send_bit = new JTextField();

   

    JLabel Rec_lebel = new JLabel();

    JTextArea rec_bit = new JTextArea();

    JTextField err = new JTextField();

   

    JButton gen = new JButton();

    JButton sen = new JButton();

    JButton cal = new JButton();

   

    int a[] = new int[100];

    int b[] = new int[100];

    WindowListener l;



    public assign_3(){

       

       

        setTitle("ASSIGNMENT #3");

        setSize(600,453);

        setLocation(220,100);



        l = new WindowAdapter() {

            public void windowClosing(WindowEvent e) {

                setEnabled(true);

            }

        };

         setUndecorated(true);

        getRootPane().setWindowDecorationStyle(JRootPane.FRAME);

        setVisible(true);

        jbinit();

       

    }

   

   

       void jbinit(){

             this.setResizable(false);

             this.getContentPane().setLayout(null);

            

             Send_lebel.setText("ADDRESS:");

             Send_lebel.setBounds(new Rectangle(8, 18, 150, 42));

             send_bit.setFont(new java.awt.Font("Dialog", 1, 12));

             send_bit.setText("");

             send_bit.setBounds(new Rectangle(18, 48, 156, 21));

            

             Rec_lebel.setText("LINKS:");

             Rec_lebel.setBounds(new Rectangle(350, 48, 132, 21));

             rec_bit.setFont(new java.awt.Font("Dialog", 1, 12));

             rec_bit.setText("");

             rec_bit.setBounds(new Rectangle(345,88,226,311));

            

             gen.setBounds(new Rectangle(48, 100, 88, 24));

             gen.setFont(new java.awt.Font("Dialog", 1, 12));

             gen.setBorder(BorderFactory.createRaisedBevelBorder());

             gen.setMnemonic('G');

             gen.setText("GO!");    

             gen.addActionListener(new gen_actionAdapter(this));

           

             sen.setBounds(new Rectangle(208, 100, 88, 24));

             sen.setFont(new java.awt.Font("Dialog", 1, 12));

             sen.setBorder(BorderFactory.createRaisedBevelBorder());

             sen.setMnemonic('S');

             sen.setText("DOWNLOAD");    

             sen.addActionListener(new sen_actionAdapter(this));

           

                    

                       

            

             this.getContentPane().add(Send_lebel, null);

             this.getContentPane().add(Rec_lebel, null);

             this.getContentPane().add(rec_bit, null);

             this.getContentPane().add(send_bit, null); 

             this.getContentPane().add(gen,null);

             this.getContentPane().add(sen,null);     

              



              



    }



    public static void main(String[] args) {

       assign_3 jmain = new assign_3();



       jmain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);



    }

   

  

// all button action

void gen_actionPerformed(ActionEvent e)

{



 int head,tail,num;

 boolean flag=true; 

 head = tail = num= 0;

 Vector<String> vc = new Vector<String>();

 Map m1 = new HashMap();



 String pre ="";

          name = send_bit.getText().toLowerCase();

          vc.addElement(name);

              System.out.println(name); 

                  m1.put(name,true);

                  ++tail;

              while(flag)

              {

                  if(head == tail){break;}

                  name = (String)vc.elementAt(head);

                 

                  System.out.println(name);

                  ++head;

            try {

           

       

            URL url = new URL("http://"+name);

            URLConnection urlc = url.openConnection();

            String st ="";

            BufferedInputStream buffer = new BufferedInputStream(urlc.getInputStream());

           

            builder = new StringBuilder();

            int byteRead;

            while ((byteRead = buffer.read()) != -1)

            {

                

                 builder.append((char) byteRead);

                 st += (char)byteRead;

            }

            buffer.close();

            System.out.println("URL VALID");

                  try {

                      ++num;

                BufferedWriter out = new BufferedWriter(new FileWriter("D:\\html\\"+num+".html"));

                out.write(builder.toString()); 

                out.close(); 

                } 

                catch (IOException ep) 

                    {

                        System.out.print("failed writing"+ep); 

                    } 

          

           // finding URL in given Page

            int r = 0;

            int i,j,l,s;

           

            for(i=0;i<1000;i++)

                str[i] = "";

               

             k = 0;   

             for(i=0;i<st.length();i++)

             {

               r = l = 0;

               for(j=i;j<st.length();j++)

               {

                  if(st.charAt(j) == 'w' && r == 0)  

                      ++l;

             

                 

                  if(l == 3)

                  {

                    str[k]+="www."; 

                      for(s=j+2;;s++)

                      {

                        if(st.charAt(s) == ' ' || st.charAt(s) == '<' || st.charAt(s) == '"')break;   

                        str[k] +=  st.charAt(s);

                       

                      }

                     

                      k++;

                      break;

                  }

                  else if(st.charAt(j) != 'w'){ r= 1;break;}

                }       

             }

            

            

             for(i=0;i<k;i++)

             {

                if(m1.containsValue(str[i]) != true)

                {

                

                    pre += str[i];

                    vc.addElement(str[i]);

                    m1.put(str[i],true);

                    ++tail;

                     pre += "\n";

                     rec_bit.setText(str[i]+"\n");

                }

             }   

            // rec_bit.setText(pre);

            }

            catch (MalformedURLException ex) {

             pre += "Sorry ! URL ERROR";

             rec_bit.setText(pre);

           

             }

            catch (IOException ex) {

            pre += "Sorry ! There Is no Site Like that";

            rec_bit.setText(pre);   

           

        }

              }

           

           

}



void sen_actionPerformed(ActionEvent e)

{

            try {

                BufferedWriter out = new BufferedWriter(new FileWriter(name+".html"));

                out.write(builder.toString()); 

                out.close(); 

                } 

                catch (IOException ep) 

                    {

                        System.out.print("failed writing"); 

                    } 

}







}







// all button class



class gen_actionAdapter implements java.awt.event.ActionListener {

assign_3 adaptee;



    gen_actionAdapter(assign_3 adaptee) {

    this.adaptee = adaptee;

  }

  public void actionPerformed(ActionEvent e) {

    adaptee.gen_actionPerformed(e);

  }

}





class sen_actionAdapter implements java.awt.event.ActionListener {

assign_3 adaptee;



    sen_actionAdapter(assign_3 adaptee) {

    this.adaptee = adaptee;

  }

  public void actionPerformed(ActionEvent e) {

    adaptee.sen_actionPerformed(e);

  }

}




Friday, July 29, 2011

Mediun Cut Image Compression source code in java



The median cut algorithm is a popular algorithm for color quantization, but can be applied to virtually any point clustering problem. In outline, it works as follows:

* Let B be a set of boxes containing points, initially containing only a single box containing all points.
* While the number of boxes in B is less than desired number of clusters...
o Find the largest side length of any side of any box.
o Cut that box into two boxes along its largest side in such a way that half the contained points fall into each new box.
o Shrink the two new boxes so that they are just large enough to contain their points.



If anyone need any help how to do without my code just post comment I will try to give proper direction to do it.





CoDe


*****************************************************************************


    /**
     * @(#)box.java
     *
     *
     * @author sharma
     * @version 1.00 2011/7/8
     */


    public class Box {
    
        public double R = 0;
        public double G = 0;
        public double B = 0;
    
        public Box()
        {
         R = 0;
         G = 0;
         B = 0;
        }
    
        public Box(double[] rgb) {
            R = rgb[0];
            G = rgb[1];
            B = rgb[2];
        }
    
    
    }


    


    /**
     * @(#)rBox.java
     *
     *
     * @author
     * @version 1.00 2002/1/2
     */


    public class rBox {
        public double R = 0;
        public double G = 0;
        public double B = 0;
        public double mR = 0;
        public double mG = 0;
        public double mB = 0;
        public rBox() {
         R = 0;
         G = 0;
         B = 0;
        }
    
        public rBox(double rr,double rg,double rb,double mr,double mg,double mb)
        {
            R = rr;
            G = rg;
            B = rb;
            mR = mr;
            mG = mg;
            mB = mb;
        
        }
    
    
    }

   
   /**
     * @(#)Func.java
     *
     *
     * @author sharma
     * @version 1.00 2011/7/8
     */
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import java.util.ArrayList;
    import java.awt.image.Raster;
    import java.awt.image.WritableRaster;

    public class Func {
          public static boolean[][][] rgbflag = new boolean[350][350][350];
      
          public static BufferedImage imagetaker(String Img) {
            BufferedImage img = null;
            try {
                img = ImageIO.read(new File(Img));
            } catch (IOException ex) {

            }
            return img;
        }
    
       public static ArrayList imageSplit(BufferedImage image) {
            ArrayList inRGB = new ArrayList();

            Raster r = image.getData();
            double[] dem = new double[4];

            for (int i = 0; i < image.getWidth(); i++) {
                for (int j = 0; j < image.getHeight(); j++) {
                    r.getPixel(i, j, dem);


                    int R = (int) dem[0];
                    int G = (int) dem[1];
                    int B = (int) dem[2];

                   // if (!rgbflag[R][G][B]) {
                        inRGB.add(new Box(dem));
                 //   }

                    rgbflag[R][G][B] = true;
                }
            }
            return inRGB;
        }
    
        public static int longdim(ArrayList inRGB) {

            int r_mn = 10000, r_mx = 0;
            int g_mn = 10000, g_mx = 0;
            int b_mn = 10000, b_mx = 0;


            for (int i = 0; i < inRGB.size(); i++) {
                r_mn = Math.min((int) inRGB.get(i).R, r_mn);
                r_mx = Math.max((int) inRGB.get(i).R, r_mx);

                g_mn = Math.min((int) inRGB.get(i).G, g_mn);
                g_mx = Math.max((int) inRGB.get(i).G, g_mx);

                b_mn = Math.min((int) inRGB.get(i).B, b_mn);
                b_mx = Math.max((int) inRGB.get(i).B, b_mx);
            }



            int def_R = r_mx - r_mn;
            int def_G = g_mx - g_mn;
            int def_B = b_mx - b_mn;

            if((def_R > def_G) && (def_R > def_B))
                return 1;
            else if((def_G > def_R) && (def_G > def_B))
                return 2;
            else
                return 3;


        }
    
        public static Box medValue(ArrayList inRGB, int LOD) {
        
            Box med = new Box(new double[]{0,0,0});

            if (inRGB.size() == 1) {
                med = inRGB.get(0);
            }
            else {
                double avg = 0;
                double totalValue = 0;
                double Ravg = 0;
                double Gavg = 0;
                double Bavg = 0;

                for (int i = 0; i < inRGB.size(); i++) {
                    Ravg = Ravg+inRGB.get(i).R;
                    Gavg = Gavg+inRGB.get(i).G;
                    Bavg = Bavg+inRGB.get(i).B;
                  
                    if (LOD == 1) {
                        totalValue = totalValue + inRGB.get(i).R;
                    }
                    else if (LOD == 2) {
                        totalValue = totalValue + inRGB.get(i).G;
                    }
                    else if (LOD == 3) {
                        totalValue = totalValue + inRGB.get(i).B;
                    }
                }
            
                //System.out.println(Ravg+" *"+Gavg+" *"+Bavg);
                avg = totalValue / inRGB.size();
                Ravg = Ravg / inRGB.size();
                Gavg = Gavg / inRGB.size();
                Bavg = Bavg / inRGB.size();
              //  System.out.println(Ravg+" |"+Gavg+" |"+Bavg);
                double minDistance = 1000000.0;
                double tempDis = 0;

                for (int i = 0; i < inRGB.size(); i++) {

                    if (LOD == 1) {
                        tempDis = Math.abs(avg - inRGB.get(i).R);
                    }
                    else if (LOD == 2) {
                        tempDis = Math.abs(avg - inRGB.get(i).G);
                    }
                    else if (LOD == 3) {
                        tempDis = Math.abs(avg - inRGB.get(i).B);
                    }

                    if (minDistance > tempDis) {
                        minDistance = tempDis;
                        med.R = inRGB.get(i).R;
                        med.G = inRGB.get(i).G;
                        med.B = inRGB.get(i).B;
                    }
                }
                med.R = Ravg;
                med.G = Gavg;
                med.B = Bavg;
            
            }

            return med;
        }
    
        public static void view(ArrayList pix)
        {
        
            int sz = pix.size();
            System.out.println("total :"+sz);
            for(int i=0;i LOT = new ArrayList();
        ArrayList Pseg = new ArrayList();
        int px,py;
    
        public Median(String ImageLoc,int lim) {
            BufferedImage InImage = Func.imagetaker(ImageLoc);
            ArrayList inRGB = Func.imageSplit(InImage);
            man(inRGB,lim);
            //genLOT(inRGB, Func.longdim(inRGB), lim);
           // Func.view(LOT);
           outImage(InImage);
        }
    
    
        public void man(ArrayList inRGB,int lim)
        {
        
            int[] siz = new int[1010];
            int[] st = new int[1010];
            ArrayList Seg = new ArrayList();
        
            siz[0] = 0;
            siz[1] = inRGB.size();
            st[1] = 0;
            int sz = 1,pos=0,len;
            len = inRGB.size();
            for(int i=0;i mx)
                    {
                        mx = siz[j];
                        pos = j;
                    }
                }
            
                // select segment to divide
                Seg.clear();
                int p=st[pos];
                for(int j=p;j=pos+1;j--)
                {
                    siz[j+1] = siz[j];
                    st[j+1] = st[j];
                //    System.out.print("i :"+siz[j+1]);
                }
                ++sz;
                siz[pos+1] = py;
                siz[pos] = px;
                st[pos+1] = st[pos]+siz[pos];
                px =0;py=0;
             /*  System.out.println("max :"+mx);
                for(int j=1;j<=sz;j++)
                {
                    System.out.print("st: "+st[j]+" "+siz[j]+" ");
                }
                System.out.println();*/
            }
        
            for(int i=1;i<=sz;i++)
            {
                System.out.println("i :"+i+" "+siz[i]);
            }
   
    
        int tot=0;
        for(int i=1;i<=sz;i++)
        {
            Seg.clear();
            tot += siz[i];
            for(int j=st[i];j inRGB) {
  
            ArrayList Seg1 = new ArrayList();
            ArrayList Seg2 = new ArrayList();
            Box mbox;
            int LOD = Func.longdim(inRGB);
            mbox = Func.medValue(inRGB, LOD);
        
            int p=0,q=0;
        
            for (int i = 0; i < inRGB.size(); i++) {
                double realRGB = 0;
                double medRGB = 0;
                if (LOD == 1) {
                    realRGB = inRGB.get(i).R;
                    medRGB = mbox.R;
                }
                 else if (LOD == 2) {
                    realRGB = inRGB.get(i).G;
                    medRGB = mbox.G;
                }
                else if (LOD == 3) {
                    realRGB = inRGB.get(i).B;
                    medRGB = mbox.B;
                }

                if (realRGB <= medRGB) {
                    Seg1.add(inRGB.get(i));
                    ++p;
                }
                else if (realRGB > medRGB) {
                    Seg2.add(inRGB.get(i));
                    ++q;
                }
            }
        
            Pseg.clear();
            for(int i=0;i< LOT.size(); i++) {
  
                if (RGB.R == LOT.get(i).R && RGB.G == LOT.get(i).G && RGB.B == LOT.get(i).B ) {
                    nearRGB.R = LOT.get(i).mR;
                    nearRGB.G = LOT.get(i).mG;
                    nearRGB.B = LOT.get(i).mB;
                    break;
                }
            }
    
            return nearRGB;
        } 
      
      void outImage(BufferedImage image) {
            BufferedImage imageOut = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
            WritableRaster raster = imageOut.getRaster();

            Raster r = image.getData();

            double[] rgb = new double[4];

            for (int i = 0; i < image.getWidth(); i++) {
                for (int j = 0; j < image.getHeight(); j++) {
                    r.getPixel(i, j, rgb);
             
                   Box rgbNew = nearRGB(new Box(rgb));
               
                   double sample[] = {rgbNew.R, rgbNew.G, rgbNew.B};
                   raster.setPixel(i, j, sample);
              
                }
            }
        
           ImageWriter writer = null;
            Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
            if (iter.hasNext()) {
                writer = iter.next();
            }
            File f = new File("D:\\output.jpg");
            ImageOutputStream imageOutputStream;
            try {
                imageOutputStream = ImageIO.createImageOutputStream(f);
                writer.setOutput(imageOutputStream);
            } catch (IOException ex) {
                ex.printStackTrace();
   
            }

            try {
                writer.write(new IIOImage(imageOut, null, null));

            } catch (IOException ex) {
                ex.printStackTrace();
          
            }
        
         //   drawImage(imageOut, "jpg", "D:\\output.jpg");
        }
    
        public static void drawImage(BufferedImage img, String format, String fileLoc) {
        try {
            ImageIO.write(img, format, new File(fileLoc));
        } catch (IOException ex) {
        }
    }

    
    
    }

    
 /**
     * @(#)sr_med.java
     *
     * sr_med application
     *
     * @author sharma
     * @version 1.00 2011/7/8
     */
  
     import java.awt.*;
     import java.awt.event.*;
     import java.awt.image.*;
     import javax.swing.*;
  
    public class sr_med extends Frame{
    
         Image im,tmp;
         int iw,ih;
         int[] pixels;
         boolean flag=false;
         int ans=0;
         TextField tx,limi;
         String st;
     
         public sr_med(){
             super("MedianImage");
             Panel pdown;
             Button load,run,save,quit;
          
          
             addWindowListener(new WindowAdapter(){
                 public void windowClosing(WindowEvent e){
                     System.exit(0);
                 }
             });
            
             pdown = new Panel();
             pdown.setBackground(Color.lightGray);
            
             load=new Button("Load");
             run = new Button("Run"); 
             quit=new Button("Quit");
             tx = new TextField(30);
             limi = new TextField(10);
             this.add(pdown,BorderLayout.SOUTH);
         
             pdown.add(tx);
             pdown.add(load);
             pdown.add(limi);
             pdown.add(run);
      
            pdown.add(quit);
            
             load.addActionListener(new ActionListener(){
                 public void actionPerformed(ActionEvent e){
                     jLoad_ActionPerformed(e);
                 }
             });
            
             run.addActionListener(new ActionListener(){
                 public void actionPerformed(ActionEvent e){
                     jRun_ActionPerformed(e);
                 }
             });
            
             quit.addActionListener(new ActionListener(){
                 public void actionPerformed(ActionEvent e){
                     jQuit_ActionPerformed(e);
                 }
             });
   
         }
        
         public void jLoad_ActionPerformed(ActionEvent e){
         
             st = tx.getText();
             MediaTracker tracker = new MediaTracker(this);
             im=Toolkit.getDefaultToolkit().getImage(st);
             tracker.addImage(im,0);
             System.out.println(st);
        
             try{
             tracker.waitForID(0);
             }catch(InterruptedException e2){ e2.printStackTrace();}
            
        
             iw=im.getWidth(this);
             ih=im.getHeight(this);
             pixels=new int[iw*ih];
            
             try{
             PixelGrabber pg=new PixelGrabber(im,0,0,iw,ih,pixels,0,iw);
             pg.grabPixels();
             }catch (InterruptedException e3) {
                 e3.printStackTrace();
             }
        
        
             ImageProducer ip=new MemoryImageSource(iw,ih,pixels,0,iw);
             tmp=createImage(ip);
             flag=true;
             repaint();
         }
        
         public  void jRun_ActionPerformed(ActionEvent e){
         
              String sp = limi.getText();
              int n = Integer.parseInt(sp);
              System.out.println(n);
              new Median(st,n);
           
              MediaTracker tracker = new MediaTracker(this);
             im=Toolkit.getDefaultToolkit().getImage("D:\\output.jpg");
             tracker.addImage(im,0);
            // System.out.println(st);
        
             try{
             tracker.waitForID(0);
             }catch(InterruptedException e2){ e2.printStackTrace();}
    
             try{
             PixelGrabber pg=new PixelGrabber(im,0,0,iw,ih,pixels,0,iw);
             pg.grabPixels();
             }catch (InterruptedException e3) {
                 e3.printStackTrace();
             }
                   
             ImageProducer ip=new MemoryImageSource(iw,ih,pixels,0,iw);
             tmp=createImage(ip);
             flag=true;
             ans = 0;
             repaint();
        
         }
   
        
         public void jQuit_ActionPerformed(ActionEvent e){
      
             JOptionPane op =new JOptionPane();
             int exit=op.showConfirmDialog(this,"Are you sure? ?","Warning!",JOptionPane.YES_NO_OPTION);
            
             if(exit==JOptionPane.YES_OPTION)
             {
                 System.exit(0);
                
             }else{ }
         }
    
    
         public void paint(Graphics g){
                   if(flag){
                 g.drawImage(tmp,10+ans,20+ans,this);
             }else { }
   
         }
        
   
         public static void main(String[] args) {
             sr_med mi = new sr_med();
             mi.setLocation(50,50);
             mi.setSize(600,600);
             mi.show();
         }
    }
  
  

Try to modify the genLO
T class .(Hint use sort instead of my divission by average value)


Picture of Output

How to Generate and use the ssh key on Gerrit, github.io, gitlab, and bitbucket.

 Details can be found here -