Wednesday, September 21, 2011

Holiday Calendar

This is a Java application which can indicate the Sri Lankan holidays (other followers please don't mind). If you hover the mouse over the marked date, it'll indicate the holiday in detail as well.


 


You can use this application instead of windows calender gadget.
To download this application click here.


To run this app in startup,

  • Extract the My Calendar.rar
  • Create a desktop shortcut for HolidayCalendar.jar
  • Copy that shortcut and paste it in StartMenu/Programs/StartUp (can find in start menu) folder
I appreciate your valuable comments...


Tuesday, September 13, 2011

Some Useful Functions Related to Geo Coordinates

//GIVE THE DISTANCE BETWEEN TWO LAT, LNG COORDINATES IN METERS
public double distanceInMeters(double lat1, double lng1, double lat2,double lng2) {
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2 - lat1);
double dLng = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2)* Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double dist = earthRadius * c;
int meterConversion = 1609;
return dist * meterConversion;
}


//GIVE THE NEAREST LAT, LNG COORDINATE WHICH IS IN A ROAD, FOR THE GIVEN LAT, LNG
private double[] nearToRoad(double[] latLng1) {
double[] latLng = new double[] { latLng1[0], latLng1[1] };
try {
URL url = new URL(
"http://maps.googleapis.com/maps/api/directions/xml?origin="+ latLng1[0] + "," + latLng1[1] + "&destination=" + latLng1[0] + "," + latLng1[1] + "&sensor=false");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("<lat>")) {
latLng[0] = Double.parseDouble(line.substring(line.indexOf('>') + 1, line.indexOf('/') - 1));
line = reader.readLine();
latLng[1] = Double.parseDouble(line.substring(line.indexOf('>') + 1, line.indexOf('/') - 1));
break;
}
}
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return latLng;
}


//GIVE THE ADDRESS OF THE LAT, LNG COORDINATE (REVERSE GEOCODING)
public String findLocationAddress(double lat, double lng) {
String name = "unnamed";
try {
URL url = new URL(
"https://maps.googleapis.com/maps/api/geocode/xml?latlng="+ lat + "," + lng + "&sensor=false");
BufferedReader reader = new BufferedReader(new InputStreamReader(
url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("<formatted_address>")) {
name = line.substring(line.indexOf('>') + 1,line.indexOf('/') - 1);
break;
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return name;
}

Approximate String Matching


Here I used Levenshtein Distance method to calculate the amount of similarity between two strings. The method LevenshteinDistance(String source, String target) will return the cost to convert the source string to target string, by considering insertion, deletion and substitution of a character, each of them costs 1.

In the Tester class you can use an appropriate threshold to get the approximate matching strings.

public class StringUtils {

    public static int LevenshteinDistance(String source, String target) {
        // d[i,j] will hold the Levenshtein distance between
        // the 1st i characters of s & the 1st j characters of t;
        // note that d has (m+1) x (n+1) values

        int m = source.length(), n = target.length();
        int[][] d = new int[m][n];
        char[] s = source.toLowerCase().toCharArray();
        char[] t = target.toLowerCase().toCharArray();

        for (int i = 0; i < m; i++) {
            d[i][0] = i; // any 1st string to an empty 2nd string
        }
        for (int j = 0; j < n; j++) {
            d[0][j] = j; // any 2nd string to an empty 1st string
        }

        for (int j = 1; j < n; j++) {
            for (int i = 1; i < m; i++) {
                if (s[i] == t[j]) {
                    d[i][j] = d[i - 1][j - 1]; // no operation
                } else {
    //minimum of DELETION, INSERTION, SUBSTITUTION (each costs 1)
    d[i][j] = Math.min(d[i - 1][j] + 1, Math.min(d[i][j - 1] + 1, d[i - 1][j - 1] + 1));
                }
            }
        }
        return d[m - 1][n - 1];
    }
}

public class Tester {

    public static void main(String[] args) {
        List<String> suggestionList = new ArrayList<String>();
        List<String> sourceList = new ArrayList<String>();
sourceList.add("abc");
sourceList.add("abcefg");
sourceList.add("abcfgh");
sourceList.add("abcdhfgi");
sourceList.add("abcd ghi");
sourceList.add("abcdefgh");
        for (String s : sourceList) {
            int editCost = StringUtils.LevenshteinDistance(s,"abcdefgh");
            if (editCost <= 3) {
                suggestionList.add(editCost + s);
            }
        }
//Sort, best match first
        Collections.sort(suggestionList);
        int count = 0;
        for (String s : suggestionList) {
            System.out.println(s);
        }
    }
}

Guess the output...

Monday, June 6, 2011

AutoCompleteTextView Demo

This demonstrates the AutoCompleteTextView feature in Android. Here the 'main.xml' layout resource is used and it has an AutoCompleteTextView and a TextView. Here the 'COUNTRIES' array is populated in the code but, you can populate it from a Content Provider. This program will show the available suggestions from the 'COUNTRIES' array when you start typing in the text field.

Activity Class

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;

public class HelloAutoComplete extends Activity {
    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        AutoCompleteTextView autoTextView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES);
        autoTextView.setAdapter(adapter);
        autoTextView.setThreshold(1);    //threshold to show auto complete
       
        TextView out=(TextView)findViewById(R.id.textView1);
        out.setText(textView.getText());
    }
    static final String[] COUNTRIES = new String[] {    //search domain array
          "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
          "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
          "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Zimbabwe"
        };
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="tutorial.autocomplete"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".HelloAutoComplete"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-sdk android:minSdkVersion="8" />

</manifest>

main.xml   

//The main layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:padding="5dp" android:orientation="vertical">
    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="Country" />
    <AutoCompleteTextView android:id="@+id/autocomplete_country"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_marginLeft="5dp" />
    <TextView android:text="TextView" android:id="@+id/textView1"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
</LinearLayout>

list_item.xml

//Auto complete layout
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp"
    android:textColor="#000">
</TextView>

Monday, February 28, 2011

Path Finding in Prolog

Prolog is a First Order Logic (FOL) interpreter which can be used to solve logic based problems. Logic based solutions are widely needed in Intelligent System Design. 
Using FOL we can create the Knowledge Base (KB) for the problem whish has objects, predicates & functions. After the construction of the KB, by the use of an Resolution algorithm we can logically take decision from the KB.
Prolog uses Backward Chaining resolution algorithm.

Here you can see a program which finds the path between two nodes in a given graph, under the given constraints.

Eg-1: Find the path between the given two nodes?

The graph is defined by the edges as edge(start, end).
After compiling, type the query in the prompt, which will give the results shown.

-------------------------------------------------
%Edge List (Knowledge Base)
edge(1,2).
edge(1,4).
edge(2,4).
edge(3,6).
edge(3,7).
edge(4,3).
edge(4,5).
edge(5,6).
edge(5,7).
edge(6,5).
edge(7,5).
edge(8,6).
edge(8,7).

%Program
path(X,Y,[X,Y]):- edge(X,Y).
path(X,Y,[X|Xs]):- edge(X,W), path(W,Y,Xs).
-------------------------------------------------

%Query
path(1, 7, P).

%Results
Z = [1, 2, 4, 3, 6, 5, 7];
Z = [1, 2, 4, 3, 6, 5, 6, 5, 7];
.........................

Eg-1: Find the path between the given two nodes, where nodes appear in ascending order?

Knowledge Base is the same.

-------------------------------------------------
%Program
path(X,Y,[X,Y]):- edge(X,Y),X<Y.
path(X,Y,[X|Xs]):-edge(X,W), X<W, path(W,Y,Xs).
-------------------------------------------------

%Query
path(1, 7, P).

%Results
Z = [1, 2, 4, 5, 7];
Z = [1, 4, 5, 7]

Eg-3: Find the path between the given two nodes with the given length?

The graph is defined by the edges as edge(start, end, cost).

-----------------------------------------------------------------
%Edge List (Knowledge Base)
edge(1, 2, 3).
edge(1, 4, 5).
edge(2, 4, 2).
edge(3, 6, 6).
edge(3, 7, 5).
edge(4, 3, 7).
edge(4, 5, 4).
edge(5, 6, 8).
edge(5, 7, 1).
edge(6, 5, 2).
edge(7, 5, 2).
edge(8, 6, 3).
edge(8, 7, 4).

%Program
path(X,Y,C,[X,Y]):- edge(X,Y,C).
path(X,Y,C,[X|Xs]):- edge(X,W,C1), plus(C1,C2,C),C2>0, path(W,Y,C2,Xs).
-----------------------------------------------------------------

%Query
path(1, 7, 17, P).

%Results
Z = [1, 2, 4, 3, 7];
Z = [1, 4, 3, 7]

Sunday, January 23, 2011

Progress Bar Demo

import java.awt.*;
import javax.swing.*;
Interface Design
class Progress extends JFrame{
PbThread t1;
JProgressBar pb;
JLabel l;

Progress() {
super("Progress Bar");
setLayout(null);
setResizable(false);
setSize(300,100);

pb=new JProgressBar();
add(pb);
pb.setBounds(10,12,270,25);
l=new JLabel();
l.setText("");
add(l);
l.setBounds(120,40,97,25);

Dimension ss=Toolkit.getDefaultToolkit().getScreenSize();
Dimension ws=getSize();
this.setBounds((ss.width-ws.width)/2,(ss.height-ws.height)/2,ws.width,ws.height);

t1=new PbThread(pb,l);
t1.start();
}
public static void main(String args[]){
Progress p=new Progress();
p.setVisible(true);
}
}

Thread to show Progress
class PbThread extends Thread{
JProgressBar pb1;
JLabel l1=new JLabel();

PbThread(JProgressBar pb,JLabel l) {
this.pb1=pb;
this.l1=l;
}
public void run(){
pb1.setMaximum(100);
pb1.setMinimum(0);
for(int x=0;x<=100;x++) {
pb1.setValue(x);
l1.setText(x+"%");
try {
sleep(100);
}
catch(InterruptedException e) {
JOptionPane.showMessageDialog(null,e,"Error",JOptionPane.ERROR_MESSAGE);
}
if(x==100)
System.exit(0);
}
}
}

Thursday, January 13, 2011

Strangest Buildings in the World

Mind House (Barcelona, Spain)

Cathedral of Brasilia (Brazil)

La Pedrera (Barcelona, Spain)

Atomium (Brussels, Belgium)

Kansas City Library (Missouri, USA)

Rotating Tower, Dubai, UAE

Habitat 67 (Montreal, Canada)

Nautilus House (Mexico City, Mexico)

The National Library (Minsk, Belarus)

National Theatre (Beijing, China)

House Attack (Viena, Austria)

Bibliotheca Alexandrina (Egypt)

Cubic Houses (Kubus woningen) (Rotterdam, Netherlands)

Eden project (United Kingdom)

Montreal Biosphere (Canada)

Wonderworks (Pigeon Forge, TN, USA)

The Basket Building (Ohio, USA)

Kunsthaus (Graz, Austria)

Saturday, January 1, 2011

Speech Recognition Using Correlation

Correlation represents the similarities between the two signals. Here I use Correlation to recognize the uttered word (Expecially in the same voice).
First of all have to record the uttered word, sample it and save in a wav file and use this function to check whether it has already in the database.
Fs is the sampling frequency.

function speechRecog_corr(filename)

voice=wavread(filename); % READ THE FILE
x=voice;
x=x';
x=x(1,:); % GET THE FIRST RAW
x=x';

y1=wavread('test1.wav');
y1=y1';
y1=y1(1,:);
y1=y1';
z1=xcov(x,y1); % FIND THE COVARIANCE
m1=max(z1);

y2=wavread('test2.wav');
y2=y2';
y2=y2(1,:);
y2=y2';
z2=xcov(x,y2);
m2=max(z2);

y3=wavread('test3.wav');
y3=y3';
y3=y3(1,:);
y3=y3';
z3=xcov(x,y3);
m3=max(z3);

y4=wavread('test4.wav');
y4=y4';
y4=y4(1,:);
y4=y4';
z4=xcov(x,y4);
m4=max(z4);

y5=wavread('test5.wav');
y5=y5';
y5=y5(1,:);
y5=y5';
z5=xcov(x,y5);
m5=max(z5);

m6=5; % SET THE REFERENCE
a=[m1 m2 m3 m4 m5 m6];
m=max(a); % GET THE MAXIMUM CORRELATION

if m<=m1
    soundsc(wavread('test1.wav'),Fs) % PLAY THE FILE
        elseif m<=m2
    soundsc(wavread('test2.wav'),Fs)
        elseif m<=m3
    soundsc(wavread('test3.wav'),Fs)
        elseif m<=m4
    soundsc(wavread('test4.wav'),Fs)
        elseif m<=m5
    soundsc(wavread('test5.wav'),Fs)
        else % IF NOT ALREADY KNOWN WORD
soundsc(wavread('denied.wav'),Fs) 
end