Monday, September 12, 2011

PERL Module: I don't have permission to install a module on the system!

If you don't have root permission you will not be able to install a module in the usual place on a shared user system. If you do not have root access you may get errors like:

$ make install
Warning: You do not have permissions to install into
/usr/local/lib/perl5/site_perl/5.005/i386-freebsd at
/usr/libdata/perl/5.00503/ExtUtils/Install.pm line 62.
mkdir /usr/local/lib/perl5/site_perl/5.005/CGI/Simple:
Permission denied at /usr/libdata/perl/5.00503/ExtUtils/Install.pm line 120
*** Error code 2
This is easy to get around. You just install it locally in your home directory. Make a directory called say /lib in your home directory like this:

# first navigate to your home directory
$ cd ~
# now make a directory called lib
# on UNIX
$ mkdir lib
# on Win32
C:\> md lib
Now you have a directory called ~/lib where the ~ represents the path to your home dir. ~ literally means your home dir but you knew that already. All you need to do is add a modifier to your perl Makefile.PL command

$ perl Makefile.PL PREFIX=~/lib LIB=~/lib
This tell MakeMaker to install the files in the lib directory in your home directory. You then just make/nmake as before. To use the module you just need to add ~/lib to @INC. See Simple Module Tutorial for full details of how. In a nutshell the top of your scripts will look like this:

#!/usr/bin/perl -w
use strict;
# add your ~/lib dir to @INC
use lib '/usr/home/your_home_dir/lib/';
# proceed as usual
use Some::Module;

Source: http://www.perlmonks.org/?node_id=128077

Thursday, September 01, 2011

Factory methods in Java

This story appeared on JavaWorld at
http://www.javaworld.com/javaworld/javaqa/2001-05/02-qa-0511-factory.html


Factory methods

How do you employ factory methods to your best advantage?

By Tony Sintes, JavaWorld.com, 05/11/01

While going through "Polymorphism in its purest form," I saw the unfamiliar term factory method. Could you please describe what a factory method is and explain how I can use it?

Factory method is just a fancy name for a method that instantiates objects. Like a factory, the job of the factory method is to create -- or manufacture -- objects.

Let's consider an example.

Every program needs a way to report errors. Consider the following interface:

Listing 1

public interface Trace {
// turn on and off debugging
public void setDebug( boolean debug );
// write out a debug message
public void debug( String message );
// write out an error message
public void error( String message );
}


Suppose that you've written two implementations. One implementation (Listing 2) writes the messages out to the command line, while another (Listing 3) writes them to a file.

Listing 2

public class FileTrace implements Trace {

private java.io.PrintWriter pw;
private boolean debug;
public FileTrace() throws java.io.IOException {
// a real FileTrace would need to obtain the filename somewhere
// for the example I'll hardcode it
pw = new java.io.PrintWriter( new java.io.FileWriter( "c:\trace.log" ) );
}
public void setDebug( boolean debug ) {
this.debug = debug;
}
public void debug( String message ) {
if( debug ) { // only print if debug is true
pw.println( "DEBUG: " + message );
pw.flush();
}
}
public void error( String message ) {
// always print out errors
pw.println( "ERROR: " + message );
pw.flush();
}
}


Listing 3

public class SystemTrace implements Trace {
private boolean debug;
public void setDebug( boolean debug ) {
this.debug = debug;
}
public void debug( String message ) {
if( debug ) { // only print if debug is true
System.out.println( "DEBUG: " + message );
}
}
public void error( String message ) {
// always print out errors
System.out.println( "ERROR: " + message );
}
}


To use either of these classes, you would need to do the following:

Listing 4

//... some code ...
SystemTrace log = new SystemTrace();
//... code ...
log.debug( "entering loog" );
// ... etc ...


Now if you want to change the Trace implementation that your program uses, you'll need to edit each class that instantiates a Trace implementation. Depending upon the number of classes that use Trace, it might take a lot of work for you to make the change. Plus, you want to avoid altering your classes as much as possible.

A factory method lets us be a lot smarter about how our classes obtain Trace implementation instances:

Listing 5

public class TraceFactory {
public static Trace getTrace() {
return new SystemTrace();
}
}


getTrace() is a factory method. Now, whenever you want to obtain a reference to a Trace, you can simply call TraceFactory.getTrace():

Listing 6

//... some code ...
Trace log = new TraceFactory.getTrace();
//... code ...
log.debug( "entering loog" );
// ... etc ...


Using a factory method to obtain an instance can save you a lot of work later. In the code above, TraceFactory returns SystemTrace instances. Imagine again that your requirements change and that you need to write your messages out to a file. However, if you use a factory method to obtain your instance, you need to make only one change in one class in order to meet the new requirements. You do not need to make changes in every class that uses Trace. Instead you can simply redefine getTrace():

Listing 7

public class TraceFactory {
public static Trace getTrace() {
try {
return new FileTrace();
} catch ( java.io.IOException ex ) {
Trace t = new SystemTrace();
t.error( "could not instantiate FileTrace: " + ex.getMessage() );
return t;
}
}
}


Further, factory methods prove useful when you're not sure what concrete implementation of a class to instantiate. Instead, you can leave those details to the factory method.

In the above examples your program didn't know whether to create FileTrace or SystemTrace instances. Instead, you can program your objects to simply use Trace and leave the instantiation of the concrete implementation to a factory method.

About the author

Tony Sintes is a principal consultant at BroadVision. A Sun-certified Java 1.1 programmer and Java 2 developer, he has worked with Java since 1997.

Wednesday, July 20, 2011

Implementing Callback in Java

interface InterestingEvent {
 // This is just a regular method so it can return something or
    // take arguments if you like.
    public void interestingEvent ();

}


class CallMe implements InterestingEvent {
    public CallMe ()
    {
     // en = new EventNotifier (this);
    } 
    // Define the actual handler for the event.
    public void interestingEvent ()
    {
     System.out.println("Wow!  Something really interesting must have occurred!");
    // Do something...
    } 
    //...

}


class EventNotifier {
    private InterestingEvent ie;
    private boolean somethingHappened; 
    public EventNotifier (InterestingEvent event)
    {
    // Save the event object for later use.
    ie = event; 
    // Nothing to report yet.
    somethingHappened = false;
    } 
    //...  
    public void doWork ()
    {
    somethingHappened = true; 
    // Check the predicate, which is set elsewhere.
    if (somethingHappened)
        {
        // Signal the even by invoking the interface's method.
        ie.interestingEvent ();
        }
    //...
    } 
    // ...


}

public class TestCallback {
    
    public static void main(String[] args) {
     CallMe me = new CallMe();
  EventNotifier event = new EventNotifier(me);
  event.doWork();
    }
}


Source: href="http://www.javaworld.com/javaworld/javatips/jw-javatip10.html

Sunday, July 17, 2011

Array of Pointers

A pointer can only point to a single object such as char and int; whereas an array of pointers can point to several objects. For example,


    // void printName(char *p[])
void printName(char **p)  
{
printf("Name1: %s\n", p[0]);
printf("Name2: %s\n", p[1]);
}




int main(int argc, char *argv[])
{
char name1[] = "Name 1";
char name2[] = "Name 2";
char *p[2];


p[0] = name1;
p[1] = name2;


printName(p);


}

Monday, May 02, 2011

Simple File Input

Simple File Input

C++ programs can read and write files in many ways. For the sake of simplicity and uniformity, files are read and written using the same stream method already introduced for keyboard input. For this page, we first need a test data file with known contents. Please compile and run the following program:

#include 
#include 

using namespace std;

int main()
{
 ofstream ofs("data.txt");
 for(int i =1;i <= 10;i++) {
  ofs << "This is line " << i << endl;
 }
 return 0;
}
    
If you want to see what this program's output is, simply examine the contents of the file "data.txt" that this program creates when run. Not visible in the output file are some "control characters." A "control character" is a character that, instead of printing a symbol, causes an action to take place, like moving down to the next line on the display. A regular character is simply printed. A control character causes an action. Here are some common control characters, their symbols, and what they do:
Linefeed '\n' Causes the printing position to move to a new line
Tab '\t' Causes the printing position to advance to a fixed column
Bell '\a' Causes a bell to ring (most platforms)
These special symbols can be used alone or in quoted strings to format the display:

 cout << "This is a test line\n\n";
    
This example will print a line followed by two linefeeds, which assures one blank line appears before the next line is printed. Q: If I can add "\n" to the text of my printed lines, why use the special operator "endl" as in the example above?
The operator "endl" does two things. It (1) causes a newline to be printed, and it (2) causes the output to appear immediately.
In C++, input and output streams are "buffered." This means characters are read and written in groups, for the sake of efficiency. When keyboard input is being accepted, an entire line is read at once, which is why the user must press "Enter" to move along. When program data is being written, it is normally emitted in chunks. To force output to be emitted at a particular time, either use "endl" as in the above example, or do this:

 cout << "This will appear right away." << flush;
    
The operator "flush" causes immediate output, which means these two lines are equivalent:

 cout << endl;
 cout << "\n" << flush;
    
Now let's read our data file in an obvious way — line by line. The following program contains the single most common student error in file reading. See if you can spot what the error is, what mistake it creates, and why. To reduce any chance for confusion, the error is in red :

#include 
#include 
#include 

using namespace std;

// this program contains an error

int main()
{
 ifstream ifs("data.txt");
 string line;
 // error in stream test
 while(!ifs.eof()) {
  getline(ifs,line);  cout << "[ " << line << " ]" << endl;
 }
 return 0;
}
    
When you run this program, you will see a blank line is printed after the last valid data line. This is caused by the program error. The error is attempting to test the stream for "end-of-file" without also trying to read it:

 while(!ifs.eof()) {
    
Remember: a C++ stream can have any origin — a file, a network connection, a keyboard, or any other source. Therefore the stream cannot detect that the data has ended until a read attempt fails. Because of this, a program that tests for end-of-file without reading, then reads without testing, always fails. A successful program always tests and reads at once. Here is a corrected version of the program:

#include 
#include 
#include 

using namespace std;

int main()
{
 ifstream ifs("data.txt");
 string line;
 while(getline(ifs,line)) {
  cout << "[ " << line << " ]" << endl;
 }
 return 0;
}
    
In the next example, we will use the stream extraction operator ">>" to read our file. Compile and run this program (it also has an error ):

#include 
#include 
#include 

using namespace std;

int main()
{
 ifstream ifs("data.txt");
 string word1, word2, word3;
 int num;
 while(ifs >> word1 >> word2 >> word3 >> num) {
  cout << "[ "
  << word1
  << word2
  << word3
  << num
  << " ]"
  << endl;
 }
 return 0;
}

    
Why does the error cause the output to look all squeezed together? To answer this question, we need to look at how the stream extraction operator ">>" works. The extraction operator is actually a very sophisticated tool. It knows what kind of variable is receiving the data, and it conducts itself accordingly. It works like this:
  • Phase 1 (search):
    • Read characters.
    • If a character is "whitespace" (control characters or spaces), discard it.
    • If a non-whitespace character appears that is not appropriate to the target variable, stop, indicate an error, "break" the stream.
    • If a character is appropriate to the target variable --
      • For integer variables, any of "+-0123456789".
      • For float/double variables, any of "+-.0123456789e" in a prescribed order.
      • For string variables, any non-whitespace characters.
      — begin phase 2.
  • Phase 2 (read):
    • Read and accept characters that are appropriate to the target variable.
    • If a character appears that is not appropriate to the target variable, either whitespace or some other character, don't discard it, stop reading, no error.
If you can commit this sequence of events to memory, it will greatly aid your stream programming. Using the extraction operator is called "formatted reading." It is called "formatted" because the input is expected to have a particular format — groups of characters meant to be received by particular variable types, separated by whitespace. This kind of reading is ideal for text files that contain different kinds of data, data that is separated by whitespace. Here is another common student error — mixing the extraction operator and getline() in the same program, without appropriate safeguards. Compile and run this program:

#include 
#include 
#include 

using namespace std;

int main()
{
 ifstream ifs("data.txt");
 string word1, word2, word3, line;
 int num;
 // read a line using the extraction operator
 if(ifs >> word1 >> word2 >> word3 >> num) {
  cout << "[ "
  << word1 << ' '
  << word2 << ' '
  << word3 << ' '
  << num << " ]"
  << endl;
 }
 // read a line using getline
 if(getline(ifs,line)) {
  cout << "[" << line << "]" << endl;
 } return 0;
}
    
Why does this program fail — why can't it read the file's second line? Think:
  1. In Phase 2, the extraction operator reads characters until it encounters whitespace, then it stops without discarding any of the whitespace.
  2. getline() only reads until it encounters a linefeed.
Unfortunately for our test program, the whitespace character that is left behind by the extraction operator is a linefeed. getline() reads this single linefeed and stops without reading the line that follows it. The solution is to remove the linefeed that was left behind by the extraction operator. Here is the corrected program:

#include 
#include 
#include 

using namespace std;

int main()
{
 ifstream ifs("data.txt");
 string word1, word2, word3, line;
 int num;
 // read a line using the extraction operator
 if(ifs >> word1 >> word2 >> word3 >> num) {
  cout << "[ "
  << word1 << ' '
  << word2 << ' '
  << word3 << ' '
  << num << " ]"
  << endl;
 } // discard whitespace
 ifs.ignore(10000,'\n');
 // read a line using getline
 if(getline(ifs,line)) {
  cout << "[ " << line << " ]" << endl;
 } return 0;
}

    
Source: http://www.arachnoid.com/cpptutor/student2.html
    

Thursday, March 17, 2011

Perl: BEGIN and END


Perl ScriptOutput
BEGIN {
    print "Birth of a process...\n";
}

print "Life of a process...\n";
die "Murder of a process...\n";

END {
    print "Death of a process...\n";
}
Birth of a process...
Life of a process...
Murder of a process...
Death of a process...
bash-2.03$ 
bash-2.03$ 
 
Perl ScriptOutput
BEGIN {
    print "Birth still runs !\n";
}

This won't compile;

END {
    print "Death still runs !\n";
}

Birth still runs !
Can't locate object method "This" via package "won::t"
(perhaps you forgot to load "won::t"?) at 1.pl line 5.
Death still runs !

 
Perl ScriptOutput
die "Bye";

END   { print "End 1\n"    }
BEGIN { print "Begin 1\n"; }
END   { print "End 2\n"    }
BEGIN { print "Begin 2\n"; }

Begin 1
Begin 2
Bye at 1.pl line 1.
End 2
End 1

BEGIN

Run some code as soon as it has all been read in by the parser and before the rest compiles.

END

Run some code as late as possible. When the interpreter is ready to shut down.

Monday, March 14, 2011

How to implement callback functions in Java?


The callback function is excutable code that is called through a function pointer. You pass a callback function pointer as an argument to other code, or register callback function pointer in somewhere. When something happens, the callback function is invoked.
C/C++ allow function pointers as arguments to other functions but there are no pointers in Java. In Java, only objects and primitive data types can be passed to methods of a class. Java's support of interfaces provides a mechanism by which we can get the equivalent of callbacks. You should declare an interface which declares the function you want to pass.
The collections.sort(List list, Comparator c) is an example of implementing callback function in Java. The c is an instance of a class which implements compare(e1, e2)method in the Comparator interface. It sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator.
Use inner classes to define an anonymous callback class, instantiate an anonymous callback delegate object, and pass it as a parameter all in one line. One of the common usage for inner classes is to implement interfaces in event handling.
class SomePanel extends JPanel {

    private JButton    myGreetingButton = new JButton("Hello");
    private JTextField myGreetingField  = new JTextField(20);

    private ActionListener doGreeting = new ActionListener {
            public void actionPerformed(ActionEvent e) {
               myGreetingField.setText("Hello");
            }
 };

    public SomePanel() {
        myGreetingButton.addActionListener(doGreeting);
        // . . . Layout the panel.
    }

}
Source: http://www.xyzws.com/javafaq/how-to-implement-callback-functions-in-java/157