Thursday, July 14, 2011

Algorithms sample source codes

Timer - a class that uses microtime() to provide easy calculation of elapsed times


class c_Timer {
var $t_start = 0;
var $t_stop = 0;
var $t_elapsed = 0;


function start() { $this->t_start = microtime(); }

function stop() { $this->t_stop = microtime(); }

function elapsed() {
if ($this->t_elapsed) {
return $this->t_elapsed;
} else {
$start_u = substr($this->t_start,0,10);
$start_s = substr($this->t_start,11,10);
$stop_u = substr($this->t_stop,0,10);
$stop_s = substr($this->t_stop,11,10);
$start_total = doubleval($start_u) + $start_s;
$stop_total = doubleval($stop_u) + $stop_s;

$this->t_elapsed = $stop_total - $start_total;

return $this->t_elapsed;
}
}
};

/* Here's an example usage:

$timer = new c_Timer;

$timer->start();
echo "
";
$timer->stop();

echo $timer->elapsed();

*/
?>

timeago-style-php-timestamps

function get_timeago( $ptime )
{
$etime = time() - $ptime;

if( $etime < 1 )
{
return 'less than 1 second ago';
}

$a = array( 12 * 30 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);

foreach( $a as $secs => $str )
{
$d = $etime / $secs;

if( $d >= 1 )
{
$r = round( $d );
return 'about ' . $r . ' ' . $str . ( $r > 1 ? 's' : '' ) . ' ago';
}
}
}
?>

Saturday, July 9, 2011

Access the enclosing class from an inner class

public class Temp {
public static void main(String a[]) {
new Temp().doit();
}

public void doit() {
new InnerClass().sayHello();
}

public void enclosingClassMethod() {
System.out.println("Hello world!");
}

class InnerClass {
public void sayHello() {
Temp.this.enclosingClassMethod();
}
}
}

Avoid NullPointerException

public class Temp {
private static final String ONE = "one";

public static void main(String args[]) {
String temp = null;

//WRONG APPROACH
//System.out.println(temp.equals(ONE));

//RIGHT APPROACH AND AVOIDS NULL POINTER EXCEPTION
System.out.println(ONE.equals(temp));
}
}

Print the limits of Java primitive types

public class Temp {
public static void main(String args[]) {
System.out.println("Min byte value = " + Byte.MIN_VALUE);
System.out.println("Max byte value = " + Byte.MAX_VALUE);
System.out.println("Min short value = " + Short.MIN_VALUE);
System.out.println("Max short value = " + Short.MAX_VALUE);
System.out.println("Min int value = " + Integer.MIN_VALUE);
System.out.println("Max int value = " + Integer.MAX_VALUE);
System.out.println("Min float value = " + Float.MIN_VALUE);
System.out.println("Max float value = " + Float.MAX_VALUE);
System.out.println("Min double value = " + Double.MIN_VALUE);
System.out.println("Max double value = " + Double.MAX_VALUE);
}
}

Reverse the characters of a given string

public class Temp {

public static void main(String[] args) {

String a = "Hello Java Galaxy";
System.out.println("
Original string: " + a);

StringBuffer b = new StringBuffer(a).reverse();
System.out.println("Reverse character string: " + b);

System.out.println("
");

}

}

Get hashtable keys from value

class keyhash
{
ResultSet rs;
Hashtable hash;
Vector v;
static int i;
Enumeration e;

public static void main(String[] args)
{
keyhash gs = new keyhash();
System.out.println("Hello World!");
gs.getresultset();
}

public void getresultset()
{
Hashtable hash = new Hashtable();
Vector v = new Vector();
boolean connected = dbConnect();
// Establish database connection here

if(connected == true)
{
try{
PreparedStatement getArticles = db.con.prepareStatement
("select * from xx where id = ?"
// sample query

)


String artid;
getArticles.setInt(1, 4);
//This passes integer 4 as a parameter in
//the sql query


rs = getArticles.executeQuery();

while (rs.next() == true)

{
key = rs.getString(1);

value = rs.getString(2);

hash.put(key,value);
//Hashtable populated

}

fillvector(hash,v);
getkeys(v);
rs.close();
}
catch(Exception ex){

ex.printStackTrace();
}
}

}
public void fillvector(Hashtable hash,Vector v)
{
int j=0;
boolean success;
Enumeration e = hash.keys();
while(e.hasMoreElements())
{
String key = (String)(e.nextElement());
String value = (String)hash.get(key);


if(value.matches("*****"))
//Put the value here to retrieve the
// corresponding keys
{
v.addElement(key);
//Add the corresponding keys to the vector
}
}

}
public void getkeys(Vector v)
{
Enumeration ev= v.elements();
while (ev.hasMoreElements())
{
System.out.println(ev.nextElement());
// Print the keys related to a single value
}

}

}

List of users in the network core java

import java.io.*;

public class NetworkUsers
{
public static void main(java.lang.String[] args)
{
StringBuffer strBuffer= new StringBuffer();
String line= null;
try
{
Process process= Runtime.getRuntime().exec("cmd");
BufferedReader b=
new BufferedReader(new InputStreamReader(process.getInputStream()));
PrintWriter to= new PrintWriter(process.getOutputStream());
to.println("net view");
to.println("exit");
to.close();

try
{
// we need the process to end, else we~ll get an
// illegal Thread State Exception
line= b.readLine();
while (line != null)
{
strBuffer.append(line+"
");
line= b.readLine();
}
process.waitFor();
}
catch (InterruptedException inte)
{
System.out.println("InterruptedException Caught");
}

if (process.exitValue() == 0)
{
System.out.println(strBuffer.toString());
}

process.destroy();

}
catch (IOException ioe)
{
System.out.println(
"IO Exception Occured While Messing aruond with Processes! -> " + ioe);
}



}
}

javascript Replace a token by another in a string

function replace(s, t, u) {
/*
** Replace a token in a string
** s string to be processed
** t token to be found and removed
** u token to be inserted
** returns new String
*/
i = s.indexOf(t);
r = "";
if (i == -1) return s;
r += s.substring(0,i) + u;
if ( i + t.length < s.length)
r += replace(s.substring(i + t.length, s.length), t, u);
return r;
}

Get the printStackTrace message into a String. in java

import java.io.PrintWriter;
import java.io.StringWriter;

public class Temp {
public static void main(String args[]) {
try {
int x = 10 / 0;
} catch (Exception e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
String trace = writer.toString();
System.out.println(trace);
}
}

}

Viewing txt files on command prompt in Java

import java.io.*;

public class File1
{
public static void main (String[] args)
{
String file_name;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter file name eg: (d:\\test.txt) ");
try
{
file_name = br.readLine(); // getting file name from user
InputStream fileIn = new FileInputStream(file_name);
File ff = new File(file_name);
long lon_size = ff.length(); //getiing the length of the file
int buff_size = (int)lon_size;
System.out.println("Size of File " + lon_size);
byte buff[] = new byte[buff_size];
int i = fileIn.read(buff);
String s = new String(buff);
System.out.println(s);
}

catch(FileNotFoundException e)
{
System.out.println("File not found.");
}

catch(IOException e)
{
e.printStackTrace();
}

} //main
}//class

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More