Monday, December 31, 2007

How to Format a Hard Drive in Windows XP

  1. Permanently erase all files with a disk sanitizer such as WipeDrive.
  2. Insert the Windows installation CD into the CD drive. Make sure that there are no other disks in the computer, and restart.
  3. At the "Welcome to Setup" screen, press the Enter key to set up Windows.
  4. Press the C key to continue setup.
  5. Press the F8 key to agree to the license.
  6. Press the C key to create a partition.
  7. Enter the size of the partition, or just press the Enter key to use maximum size.
  8. Select the "New (Unformatted)" option, and press the Enter key.
  9. Select NTFS or FAT file system (select NTFS if you are unsure).
  10. Simply follow the prompts format the hard drive in Windows XP continue the Windows installation.

Perl language gets a revamp

According to the foundation, this is the first new version in five years, and it has an emphasis on rough-and-ready practicality over syntactical formality.

Perl 5.0 has some features designed to make programming a little easier, according to the Perl Foundation. Among them is a "say" command that could ease some text-output chores, a "switch" operator to send a program in various directions depending on different situations, and improvements to the all-important "regular expression" methods for handling text. The Perl interpreter, which runs Perl programs, is also faster and requires less memory, the foundation said.

Perl programmers have been working already on two other future versions, 5.12 and Perl 6, but neither has a launch date yet, according to foundation spokesman Andy Lester. "Perl 5 and Perl 6 will stay in dual development. Perl 5 has such a huge installed base, it won't be going away any time soon after Perl," he said.

Perl founder Larry Wall initially announced Perl 6 in 2000, and development is still under way. Perl 6 attempts, among other things, to clean up some of the problems caused by the informality of Perl 5.

Closely related to Perl but separate is Parrot, an attempt to create a virtual machine that can execute programs written not just in Perl 6 but also in Ruby, Lua, Javascript, Python and PHP. (Virtual machine software provides an insulating layer that shields programs from the particulars of the computer and operating system they're running on.) Programmers released Parrot version 0.5.1 on 18 December.

Perl Offers Incremental Update; Version 6.0 Still Awaited

The first new version in five years of Perl, the popular Web scripting language, is now available, according to spokesmen from the Perl Foundation. The release is available for a free download as open source code from Perl.org or the Perl archive network.

Release 5.10 contains additions and enhancements to the language rather than the total revamp represented by a new version, Perl 6.0, announced by Perl's original author, Larry Wall, in 2000.

Perl -- like Tcl, Python, JavaScript, and PHP -- is a "dynamic" language that is interpreted, or run through an interpreter for each use of the program, instead of compiled once in advance. For that reason, changes to a phrase or line of Perl get picked up immediately in the next use of a Perl program in a runtime environment. Perl is often used to tie together dissimilar elements of a Web site, such as pieces of Java and Visual Basic code and other site resources.

But Perl has developed spontaneously, adding features and function before an overall design was in place. Wall, on the Perl.org Web site, said, "Perl 5 was my rewrite of Perl. I want version 6 to be the community's rewrite of Perl."

On the same site, the internals of the version 5 interpreter are described as "so tangled that they hinder maintenance, thwart some new feature efforts, and scare off potential internals hackers. The language as of version 5 has some mis-features that are a hassle to ongoing maintenance of the interpreter and of programs written in Perl."

Release 5.10 of Perl is meant to incorporate some additions to the language in lieu of the emergence of version 6.0. The interpreter has been sped up and given a smaller footprint in memory. "State variables" allow variables in a program to persist between calls to subroutines, so they don't have to be named again at a later point in the program.

A "say" command has been added to govern text output tasks. A "switch" operator sends a program's logic in various directions, depending on the conditions encountered. Changes have been made to how text is handled by the "regular expression" approach, according to information posted on the Perl.org Web site.

Release 5.10 was produced by Rafael Garcia-Suarez, a French software engineer who lives in Paris and is employed by Booking.com. He is a longtime contributor to Perl.

Version 6.0 seeks to establish a neutral mode of operation for the interpreter, allowing it to deal with different scripting languages. Interpreters often run pre-compiled code or byte code that has been moved beyond source code into a language that is more readily interpreted to the hardware. The version 6.0 interpreter may be able to run the byte code of other scripting languages, such as Python or Ruby, as well as Perl.

Fully compiled code, such as C or C++, runs faster but interpreted code is constantly picking up small changes to a program and incorporating them into its operation at runtime. Web site developers often resort to scripting languages for that purpose and for their ability to adapt to different languages and data types.

Thursday, December 20, 2007

submit forms to a new window, with window.open() features

you can just set up your form tag like this:

target=_blank
action=whatever.asp>

However, some would like to submit their forms to a new window that they have a little more control over.

This is not really an ASP issue, as the solution could be used in any web-based technology (including plain HTML). However, here is a way to submit a form to a new window, and have control over parameters like width, height, toolbar, etc.:

//
// method=post
// action=whatever.asp
//target=myNewWin>
/
//
/
// // value=' Submit '
// onClick='sendme();'>
//


CREATE VIEW in postgresql

Name
CREATE VIEW -- define a new view

Synopsis

CREATE [ OR REPLACE ] [ TEMP | TEMPORARY ] VIEW name [ ( column_name [, ...] ) ]
AS query

Description

CREATE VIEW defines a view of a query. The view is not physically materialized. Instead, the query is run every time the view is referenced in a query.

CREATE OR REPLACE VIEW is similar, but if a view of the same name already exists, it is replaced. You can only replace a view with a new query that generates the identical set of columns (i.e., same column names and data types).

If a schema name is given (for example, CREATE VIEW myschema.myview ...) then the view is created in the specified schema. Otherwise it is created in the current schema. Temporary views exist in a special schema, so a schema name cannot be given when creating a temporary view. The name of the view must be distinct from the name of any other view, table, sequence, or index in the same schema.
Parameters

TEMPORARY or TEMP

If specified, the view is created as a temporary view. Temporary views are automatically dropped at the end of the current session. Existing permanent relations with the same name are not visible to the current session while the temporary view exists, unless they are referenced with schema-qualified names.

If any of the tables referenced by the view are temporary, the view is created as a temporary view (whether TEMPORARY is specified or not).
name

The name (optionally schema-qualified) of a view to be created.
column_name

An optional list of names to be used for columns of the view. If not given, the column names are deduced from the query.
query

A SELECT or VALUES command which will provide the columns and rows of the view.

Notes

Currently, views are read only: the system will not allow an insert, update, or delete on a view. You can get the effect of an updatable view by creating rules that rewrite inserts, etc. on the view into appropriate actions on other tables. For more information see CREATE RULE.

Use the DROP VIEW statement to drop views.

Be careful that the names and types of the view's columns will be assigned the way you want. For example:

CREATE VIEW vista AS SELECT 'Hello World';

is bad form in two ways: the column name defaults to ?column?, and the column data type defaults to unknown. If you want a string literal in a view's result, use something like:

CREATE VIEW vista AS SELECT text 'Hello World' AS hello;

Access to tables referenced in the view is determined by permissions of the view owner. However, functions called in the view are treated the same as if they had been called directly from the query using the view. Therefore the user of a view must have permissions to call all functions used by the view.
Examples

Create a view consisting of all comedy films:

CREATE VIEW comedies AS
SELECT *
FROM films
WHERE kind = 'Comedy';

Compatibility

The SQL standard specifies some additional capabilities for the CREATE VIEW statement:

CREATE VIEW name [ ( column_name [, ...] ) ]
AS query
[ WITH [ CASCADED | LOCAL ] CHECK OPTION ]

The optional clauses for the full SQL command are:

CHECK OPTION

This option has to do with updatable views. All INSERT and UPDATE commands on the view will be checked to ensure data satisfy the view-defining condition (that is, the new data would be visible through the view). If they do not, the update will be rejected.
LOCAL

Check for integrity on this view.
CASCADED

Check for integrity on this view and on any dependent view. CASCADED is assumed if neither CASCADED nor LOCAL is specified.

CREATE OR REPLACE VIEW is a PostgreSQL language extension. So is the concept of a temporary view.

Why use stored procedures?

Stored procedures offer several distinct advantages over embedding queries in your Graphical User Interface (GUI). Your first thought may be: "Why tolerate the added development overhead?" After seeing the advantages, you may change your mind.

Advantage 1: Stored procedures are modular. This is a good thing from a maintenance standpoint. When query trouble arises in your application, you would likely agree that it is much easier to troubleshoot a stored procedure than an embedded query buried within many lines of GUI code.

Advantage 2: Stored procedures are tunable. By having procedures that handle the database work for your interface, you eliminate the need to modify the GUI source code to improve a query's performance. Changes can be made to the stored procedures--in terms of join methods, differing tables, etc.--that are transparent to the front-end interface.

Advantage 3: Stored procedures abstract or separate server-side functions from the client-side. It is much easier to code a GUI application to call a procedure than to build a query through the GUI code.

Advantage 4: Stored procedures are usually written by database developers/administrators. Persons holding these roles are usually more experienced in writing efficient queries and SQL statements. This frees the GUI application developers to utilize their skills on the functional and graphical presentation pieces of the application. If you have your people performing the tasks to which they are best suited, then you will ultimately produce a better overall application.

In short, queries are best handled via stored procedures. While the initial development overhead is greater, you will more than make up for the investment down the line.

Friday, December 7, 2007

PHP Vs Perl

1. The Language

If you are coming from a C, C++, Perl, Java or JavaScript background, learning PHP would probably be a piece of cake. In fact, you probably can get started writing your scripts almost immediately.

It uses typeless variables the way Perl does, prefixed with a "$" sign and holding any data type you wish. For example, $whatever can be a variable that you can use to contain strings, numbers, whatever. If $whatever contained a number, you can increment its value using

$whatever++ ;

or

$whatever += 1 ;

or

$whatever = $whatever + 1 ;

Doesn't it remind you of Perl, C, C++, Java, JavaScript? See what I mean?

2. Built-in Facilities

Unlike Perl, which is a general purpose scripting language that you can use for a wide variety of purposes (and not just generating web pages), PHP was designed from the ground up to be used for scripting web pages. As a result, it has lots of facilities built into that you may have to write yourself or use some pre-written module if you were using Perl.

For example, do you want to send email to yourself from a form on the web page? In Perl, one common way to do this is to use code like the following:

open ( MAIL,"|/usr/sbin/sendmail -t");
print MAIL "To: myself\@mydomain.com\n" ;
print MAIL "From: visitor\@hisdomain.com\n" ;
print MAIL "Subject: Comments from Web Form\n\n" ;
print MAIL $mainmessage ;
close ( MAIL ) ;

In PHP, the same thing would be coded as follows:

mail ( "myself@mydomain.com", "Comments from Web Form",
$mainmessage, "From: visitor@hisdomain.com" );

Nifty, huh? The same goes for other facilities like sending or retrieving a document via HTTP or FTP, etc. Since PHP was specially designed for a website, the facilities that web designers typically want in a scripting language are built into it.

Another convenience is its handling of form input. Take for example a form with a field like:

The data submitted for that field is made available to your script in the array variable $_REQUEST['dateofbirth']. You can assign its contents to any variable you like, or use it directly. There's no need to parse form inputs or the like. All fields in the form are automatically converted to variables that you can access.

Accessing databases is just as easy. There are built-in facilities in PHP to access MySQL, MSQL, Dbase, Oracle, InterBase, and so on (the list is very long). Need to MIME encode your message? There's a function to do it for you too.

There're many more features. I obviously can't run through the entire list - it would take a whole book to be exhaustive. This is just to whet your appetite.

3. Generating web pages

By default anything you type in your PHP document is given verbatim to the web browser. So a simple PHP script might look like the following:


My First PHP Script

My First PHP Script



Welcome, Internet user from IP address
. Hope you like my first
PHP page.


Notice that it looks exactly like a web page, except for the bit, which encloses the PHP script. In this case, all we want is for the script to output the visitor's IP address to the page, hence we use the "echo" function. The web server's environment variable REMOTE_ADDR is automatically made available to the PHP script via an array variable $_SERVER['REMOTE_ADDR']. In fact, all server environment variables are available to the PHP script in the $_SERVER array variable. So, for example, the name of your visitor's browser is available in $_SERVER['HTTP_USER_AGENT'].

There are many ways to embed your PHP script into your page, or to design your page itself. But you've probably already got the general idea. As I said, PHP was designed for web pages, so the idea of output to the server is built into its design. It makes writing such scripts a very pleasant task.

How to convert date to unixtime in perl (or vice versa)

  • time return number of seconds since 0 in your computer (1 jan 1970) on unix
  • localtime converts unixtime to normal dates
    To convert a specific date to its corresponding unixtime, you use Time::Local, the function looks like this:
      $time = timelocal($sec,$min,$hours,$mday,$mon,$year);
    so to convert 3rd of Sept 2000 to unixtime, (note that jan=0,feb=1,...):
      use Time::Local;
    $time = timelocal(0,0,0,'3','08','2000');
  • Site Replication and Mirroring

    Often you will want to mirror a page or set of pages from another server, for example, to distribute the load amongst several replicate servers, or to keep a set of reference pages handy. The LWP library makes this easy.


    Mirroring Single Pages

     % ./MirrorOne.pl
    cats.html: Not Modified
    dogs.html: OK
    gillie_fish.html: Not Modified

    ----------------------Script I.3.1 mirrorOne.pl--------------------

     #!/usr/local/bin/perl
    # mirrorOne.pl

     use LWP::Simple;
    use HTTP::Status;

     use constant DIRECTORY => '/local/web/price_lists';
    %DOCUMENTS = (
    'dogs.html' => 'http://www.pets.com/dogs/price_list.html',
    'cats.html' => 'http://www.pets.com/cats/price_list.html',
    'gillie_fish.html' => 'http://aquaria.com/prices.html'
    );
    chdir DIRECTORY;
    foreach (sort keys %DOCUMENTS) {
    my $status = mirror($DOCUMENTS{$_},$_);
    warn "$_: ",status_message($status),"\n";
    }

    -------------------------------------------------------------------


    Mirroring a Document Tree

    With a little more work, you can recursively mirror an entire set of linked pages. Script I.3.2 mirrors the requested document and all subdocuments, using the LWP HTML::LinkExtor module to extract all the HTML links.

    ----------------------Script I.3.2 mirrorTree.pl--------------------

     #!/usr/local/bin/perl

    # File: mirrorTree.pl

    use LWP::UserAgent;
    use HTML::LinkExtor;
    use URI::URL;
    use File::Path;
    use File::Basename;
    %DONE = ();

    my $URL = shift;

    $UA = new LWP::UserAgent;
    $PARSER = HTML::LinkExtor->new();
    $TOP = $UA->request(HTTP::Request->new(HEAD => $URL));
    $BASE = $TOP->base;

    mirror(URI::URL->new($TOP->request->url));

    sub mirror {
    my $url = shift;

    # get rid of query string "?" and fragments "#"
    my $path = $url->path;
    my $fixed_url = URI::URL->new ($url->scheme . '://' . $url->netloc . $path);

    # make the URL relative
    my $rel = $fixed_url->rel($BASE);
    $rel .= 'index.html' if $rel=~m!/$! || length($rel) == 0;

    # skip it if we've already done it
    return if $DONE{$rel}++;

    # create the directory if it doesn't exist already
    my $dir = dirname($rel);
    mkpath([$dir]) unless -d $dir;

    # mirror the document
    my $doc = $UA->mirror($fixed_url,$rel);
    print STDERR "$rel: ",$doc->message,"\n";
    return if $doc->is_error;

    # Follow HTML documents
    return unless $rel=~/\.html?$/i;
    my $base = $doc->base;

    # pull out the links and call us recursively
    my @links = $PARSER->parse_file("$rel")->links;
    my @hrefs = map { url($_->[2],$base)->abs } @links;

    foreach (@hrefs) {
    next unless is_child($BASE,$_);
    mirror($_);
    }

    }

    sub is_child {
    my ($base,$url) = @_;
    my $rel = $url->rel($base);
    return ($rel ne $url) && ($rel !~ m!^[/.]!);
    }

    Checking for Bad Links

    A slight modification of this last script allows you to check an entire document hierarchy (your own or someone else's) for bad links. The script shown in I.3.3 traverses a document, and checks each of the http:, ftp: and gopher: links to see if there's a response at the other end. Links that point to sub-documents are fetched and traversed as before, so you can check your whole site in this way.

      % find_bad_links http://prego/apache-1.2/
    checking http://prego/apache-1.2/...
    checking http://prego/apache-1.2/manual/...
    checking http://prego/apache-1.2/manual/misc/footer.html...
    checking http://prego/apache-1.2/manual/misc/header.html...
    checking http://prego/apache-1.2/manual/misc/nopgp.html...
    checking http://www.yahoo.com/Science/Mathematics/Security_and_Encryption/...
    checking http://www.eff.org/pub/EFF/Policy/Crypto/...
    checking http://www.quadralay.com/www/Crypt/Crypt.html...
    checking http://www.law.indiana.edu/law/iclu.html...
    checking http://bong.com/~brian...
    checking http://prego/apache-1.2/manual/cgi_path.html...
    checking http://www.ics.uci.edu/pub/ietf/http/...
    .
    .
    .
    BAD LINKS:
    manual/misc/known_bugs.html : http://www.apache.org/dist/patches/apply_to_1.2b6/
    manual/misc/fin_wait_2.html : http://www.freebsd.org/
    manual/misc/fin_wait_2.html : http://www.ncr.com/
    manual/misc/compat_notes.html : http://www.eit.com/
    manual/misc/howto.html : http://www.zyzzyva.com/robots/alert/
    manual/misc/perf.html : http://www.software.hp.com/internet/perf/tuning.html
    manual/misc/perf.html : http://www.qosina.com/~awm/apache/linux-tcp.html
    manual/misc/perf.html : http://www.sun.com/sun-on-net/Sun.Internet.Solutions/performance/
    manual/misc/perf.html : http://www.sun.com/solaris/products/siss/
    manual/misc/nopgp.html : http://www.yahoo.com/Science/Mathematics/Security_and_Encryption/

    152 documents checked
    11 bad links

    ----------------------Script I.3.2 mirrorTree.pl--------------------

     #!/usr/local/bin/perl

     # File: find_bad_links.pl

    use LWP::UserAgent;
    use HTML::LinkExtor;
    use URI::URL;

     %CAN_HANDLE = ('http'=>1,
    'gopher'=>1,
    # 'ftp'=>1, # timeout problems?
    );
    %OUTCOME = ();
    $CHECKED = $BAD = 0;
    @BAD = ();

     my $URL = shift;

     $UA     = new LWP::UserAgent;
    $PARSER = HTML::LinkExtor->new();
    $TOP = $UA->request(HTTP::Request->new(HEAD => $URL));
    $BASE = $TOP->base;

     check_links(URI::URL->new($TOP->request->url));
    if (@BAD) {
    print "\nBAD LINKS:\n";
    print join("\n",@BAD),"\n\n";
    }
    print "$CHECKED documents checked\n",scalar(@BAD)," bad links\n";

     sub check_links {
    my $url = shift;
    my $fixed_url = $url;
    $fixed_url =~ s/\#.+$//;

        return 1 unless $CAN_HANDLE{$url->scheme};

        # check cached outcomes
    return $OUTCOME{$fixed_url} if exists $OUTCOME{$fixed_url};

        print STDERR "checking $fixed_url...\n";
    $CHECKED++;

        my $rel = $url->rel($BASE) || 'index.html';
    my $child = is_child($BASE,$url);
    $UA->timeout(5);
    my $doc = $d = $UA->request(HTTP::Request->new(($child ? 'GET' : 'HEAD' )=>$url));
    $OUTCOME{$fixed_url} = $doc->is_success;

        return $OUTCOME{$fixed_url}
    unless $child && $doc->header('Content-type') eq 'text/html';

        # Follow HTML documents
    my $base = $doc->base;

    # pull out the links and call us recursively
    my @links = $PARSER->parse($doc->content)->links;
    my @hrefs = map { url($_->[2],$base)->abs } @links;

        foreach (@hrefs) {
    next if check_links($_);
    push (@BAD,"$rel : $_");
    }
    1;
    }

     sub is_child {
    my ($base,$url) = @_;
    my $rel = $url->rel($base);
    return ($rel ne $url) && ($rel !~ m!^[/.]!);
    }

    Ten Neat Tricks With Perl

    Here are ten one liners in perl, illustrating the kinds of task one would use a script for under linux. All the scripts take some kind of argument after the final ' quote that signals the end of the program.

    1. perl -p -i -e 's/this/that/g' filename

    Search and replace the string 'this' with the string 'that' in the file filename. You can also say * or *.html or any valid wildcard expression instead of filename. The s/// command uses regular expressions. If you want to alter the 'this' and 'that', it's best to avoid .*?[]{}$^ and other odd characters which act as metacharacters in regular expressions. Or better still look at the perlre documentation page. You can do this by saying perldoc perlre. Perl has extensive online documentation, try perldoc perltoc for a list.

    2. perl -e 'for (@ARGV) { rename $_, lc($_) unless -e lc($_); }' *

    Rename all the files in the current directory to lower case. The $_ is a sort of 'default' variable which is widely used in Perl.

    3. perl -e 'for (@ARGV) { rename $_,$_.'l' unless -e lc($_); }' *

    Add an 'l' on the end of every filename in the current directory. That is: .htm => .html. The 'unless -e' statement means 'unless the filename exists'.

    4. perl -MLWP::Simple -e 'mirror("http://www.perl.com/" , "perl.html")'

    Copy a file across the Web if it is newer than the local copy. You will need to install the "libnet" and "libwww" bundles to make this work. The LWP package comes with a great documentation page'lwpcook' which has lots of examples of other ways to transfer data across the WWW with Perl.

    5. perl -p -i -e 's/'

    Convert Unix files to DOS files. Unix files have a different end of line character sequence from DOS.

    6. perl -e 'if (!fork) {sleep $ARGV[0]*60; print "aaa" ; exit;} exit;' 1

    Wait for the number of minutes specified and then beep. Note the use of the fork() to run in the background. Use the linux commnd 'ps' if you want to watch the command running.

    7.perl -e 'use Socket; $name =gethostbyaddr(inet_aton($ARGV[0] ),AF_INET); print $name;' 207.153.253.38

    Convert the given domain name or dotted IP number to a hostname. It will convert whatever you throw at it to a sensible and consistent hostname.

    8. perl -MTime::Local -e '$y2k=timelocal(0,0,0,1,0,2000); $until=$y2k-time; print "seconds $until to y2k ";'

    This finds the number of seconds until the year 2000 is upon us.

    9. perl -e '$n=utime ((stat($ARGV[0]))[8,9], @ARGV) ;print $n' aaa t*

    Make all files beginning with the letter t have the same time stamp as the file 'aaa'

    10. perl -l -e 'open(F,"/usr/dict/english"); $w=join("",sort split(//,$ARGV[0])); print grep {chop;join("",sort split(//,$_)) eq $w} ;' life

    Tuesday, December 4, 2007

    Creating a HTML back button.

    Creating a HTML back button.

    Issue:

    Creating a HTML back button.

    Reason:

    You may find it more helpful to provide a back button for your users to allow them to go back where they originally came from. This will also make it easier to program your HTML pages.

    Solution:

    Copy and paste the below source code.

    In the above code the -1 tells the browser to go back one page.

    What is SQL*Plus and where does it come from?

    SQL*Plus is a command line SQL and PL/SQL language interface and reporting tool that ships with the Oracle Database Client and Server. It can be used interactively or driven from scripts. SQL*Plus is frequently used by DBAs and Developers to interact with the Oracle database.

    If you are familiar with other databases, sqlplus is equivalent to "sql" in Ingres, "isql" in Sybase and SQLServer, "db2" in IBM DB2, "psql" in PostgresQL, and "mysql" in MySQL.

    SQL*Plus's predecessor was called UFI (User Friendly Interface). UFI was included in the first Oracle releases up to Oracle v4. The UFI interface was extremely primitive and, in today's terms, anything but user friendly. If a statement was entered incorrectly, UFI issued an error and rolled back the entire transaction (ugggh).

    How does one use the SQL*Plus utility?

    Start using SQL*Plus by executing the "sqlplus" command-line utility. Valid options are:
     userid/password@db -- Connection details
    /nolog -- Do not login to Oracle. You will need to do it yourself.
    -s or -silent -- start sqlplus in silent mode. Not recommended for beginners!
    @myscript -- Start executing script called "myscript.sql"
    Look at this example session:
     sqlplus /nolog
    SQL> connect scott/tiger
    SQL> select * from tab;
    SQL> disconnect
    SQL> exit
    Please note that one must prepare the environment before starting sqlplus. Linux/ Unix example:
      $ . oraenv
    ORACLE_SID = [orcl] ? orcl
    $ sqlplus scott/tiger
    Windows Example:
      Click on "Start" -> "Run" and enter "cmd"
    C:> set ORACLE_SID=orcl
    C:> sqlplus scott/tiger
    or
    C:> sqlplus scott/tiger@orcl

    What is AFIEDT.BUF?

    AFIEDT.BUF is the SQL*Plus default edit save file. When you issue the command "ed" or "edit" without arguments, the last SQL or PL/SQL command will be saved to a file called AFIEDT.BUF and opened in the default editor.

    In the prehistoric days when SQL*Plus was called UFI (User Friendly Interface) this file was named "ufiedt.buf", short for UFI editing buffer. When new features were added to UFI, it was the initially named Advanced UFI and the filename was changed to "aufiedt.buf" and then to "afiedt.buf". They presumably needed to keep the name short for compatibility with some of the odd operating systems that Oracle supported in those days. The name "Advanced UFI" was never used officially, as the name was changed to SQL*Plus before this version was released.

    You can overwrite the default edit save file's name like this:

     SET EDITFILE "afiedt.buf"

    What are the basic SQL*Plus commands?

    The following SQL*Plus commands are available:

    ACCEPT Get input from the user
    DEFINE Declare a variable (short: DEF)
    DESCRIBE Lists the attributes of tables and other objects (short: DESC)
    EDIT Places you in an editor so you can edit a SQL command (short: ED)
    EXIT or QUIT Disconnect from the database and terminate SQL*Plus
    GET Retrieves a SQL file and places it into the SQL buffer
    HOST Issue an operating system command (short: !)
    LIST Displays the last command executed/ command in the SQL buffer (short: L)
    PROMPT Display a text string on the screen. Eg prompt Hello World!!!
    RUN List and Run the command stored in the SQL buffer (short: /)
    SAVE Saves command in the SQL buffer to a file. Eg "save x" will create a script file called x.sql
    SET Modify the SQL*Plus environment eg. SET PAGESIZE 23
    SHOW Show environment settings (short: SHO). Eg SHOW ALL, SHO PAGESIZE etc.
    SPOOL Send output to a file. Eg "spool x" will save STDOUT to a file called x.lst
    START Run a SQL script file (short: @)

    Popups in Javascript

    Sometimes it's useful to add a popup to your pages. When the user clicks on a link, a new window opens and displays a page.

    There are two ways to do this. You can add a TARGET="_blank" to the -tag, but this simply opens a new browser window that completely obscures the old one.

    This may be what you want, but at other times a small window on top of the large browser window is much better. This small window is popularly known as a popup.

    First the basic syntax of how to create a popup, then an explanation of the script, including a table of the most common arguments you can give to a popup and the problem of focusing.
    Then a new way of adding popup behaviour to a link. This site uses the new system because it's much cleaner than the old one.
    Finally some notes about writing content directly into the popup. This gives several problems, most importantly the confusion over exactly what the URL of the popup is.

    This page only treats the opening of popups. For communication between the opening window and the popup, see the Cross-window scripting page.

    Creating a popup

    To create a popup you'll need the following script:


    Then, you link to it by:

    Link to popup

    Open popup.

    See below for a far cleaner way of adding popup behaviour to a link.

    Explanation

    First, you open the new window. The page to be opened is passed on by the argument url. Note that, if you want to open a page on another server, Explorer will frequently give errors. This is a feature, not a bug, so there's little you can do about it.

    You have to give a name to the window (in this case, name). However, this name is completely useless.

    In addition, you have to load the window into a JavaScript variable. The reasons for this are complex and have mostly to do with preventing errors in various browsers, especially when you want more links to lead to the same popup.

    function popitup(url) {
    newwindow=window.open(url,'name','height=200,width=150');

    Arguments

    So first we define the url to be loaded in the popup and then the useless name.

    As third argument, you can assign all kinds of variables. Most common are height and width, which define the height and width of the new window.

    'height=200,width=150'

    As soon as you define anything, all yes | no arguments that you have not defined are set to no.
    Warning: Spaces or hard returns are not allowed within the quote-marks.

    Open popup, and set the arguments through the checkboxes below.

    dependent
    directories
    fullscreen
    location
    menubar
    resizable
    scrollbars
    status
    toolbar
    top=200
    left=400
    width=200
    height=200
    screenX=200
    screenY=100

    Selecting and deleting duplicate rows postgresql

    create table test ( a text, b text );
    -- unique values
    insert into test values ( 'x', 'y');
    insert into test values ( 'x', 'x');
    insert into test values ( 'y', 'y' );
    insert into test values ( 'y', 'x' );
    -- duplicate values
    insert into test values ( 'x', 'y');
    insert into test values ( 'x', 'x');
    insert into test values ( 'y', 'y' );
    insert into test values ( 'y', 'x' );
    -- one more double duplicate
    insert into test values ( 'x', 'y');
    --
    select oid, a, b from test;
    --
    -- select duplicate rows
    --
    select o.oid, o.a, o.b from test o
    where exists ( select 'x'
    from test i
    where i.a = o.a
    and i.b = o.b
    and i.oid < o.oid
    );
    --
    -- delete duplicate rows
    --
    -- Note: PostgreSQL dosn't support aliases on
    -- the table mentioned in the from clause
    -- of a delete.
    --

    delete from test
    where exists ( select 'x'
    from test i
    where i.a = test.a
    and i.b = test.b
    and i.oid < test.oid
    );
    --
    -- Let's see if it worked.
    --

    select oid, a, b from test;

    --
    -- Delete duplicates with respect to a only, ignoring
    -- the value in b. Note, the first deletion leaves the
    -- first oid with the unique values and removes subsequent
    -- ones, in this delete we reverse the direction of the <
    -- to save the last oid, and remove the previous ones.
    --

    delete from test
    where exists ( select 'x'
    from test i
    where i.a = test.a
    and i.oid > test.oid
    );

    --
    -- Let's see if it worked.
    --

    select oid, a, b from test;

    Moving, renaming, and copying files in UNIX


    cp file1 file2 copy a file
    mv file1 newname move or rename a file
    mv file1 ~/AAA/ move file1 into sub-directory AAA in your home directory.
    rm file1 [file2 ...] remove or delete a file
    rm -r dir1 [dir2...] recursivly remove a directory and its contents BE CAREFUL!
    mkdir dir1 [dir2...] create directories
    mkdir -p dirpath create the directory dirpath, including all implied directories in the path.
    rmdir dir1 [dir2...] remove an empty directory

    Changing file permissions and attributes in UNIX

    chmod 755 file       Changes the permissions of file to be rwx for the owner, and rx for
    the group and the world. (7 = rwx = 111 binary. 5 = r-x = 101 binary)
    chgrp user file Makes file belong to the group user.
    chown cliff file Makes cliff the owner of file.
    chown -R cliff dir Makes cliff the owner of dir and everything in its directory tree.

    You must be the owner of the file/directory or be root before you can do any of these things.

    Listing directory contents in UNIX

    ls    list a directory
    ls -l list a directory in long ( detailed ) format

    for example:
    $ ls -l
    drwxr-xr-x 4 cliff user 1024 Jun 18 09:40 WAITRON_EARNINGS
    -rw-r--r-- 1 cliff user 767392 Jun 6 14:28 scanlib.tar.gz
    ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
    | | | | | | | | | | |
    | | | | | owner group size date time name
    | | | | number of links to file or directory contents
    | | | permissions for world
    | | permissions for members of group
    | permissions for owner of file: r = read, w = write, x = execute -=no permission
    type of file: - = normal file, d=directory, l = symbolic link, and others...

    ls -a List the current directory including hidden files. Hidden files start
    with "."
    ls -ld * List all the file and directory names in the current directory using
    long format. Without the "d" option, ls would list the contents
    of any sub-directory of the current. With the "d" option, ls
    just lists them like regular files.

    Basics of the vi editor

    Opening a file
    vi filename

    Creating text
    Edit modes: These keys enter editing modes and type in the text
    of your document.

    i Insert before current cursor position
    I Insert at beginning of current line
    a Insert (append) after current cursor position
    A Append to end of line
    r Replace 1 character
    R Replace mode
    Terminate insertion or overwrite mode

    Deletion of text

    x Delete single character
    dd Delete current line and put in buffer
    ndd Delete n lines (n is a number) and put them in buffer
    J Attaches the next line to the end of the current line (deletes carriage return).

    Oops

    u Undo last command

    cut and paste
    yy Yank current line into buffer
    nyy Yank n lines into buffer
    p Put the contents of the buffer after the current line
    P Put the contents of the buffer before the current line

    cursor positioning
    ^d Page down
    ^u Page up
    :n Position cursor at line n
    :$ Position cursor at end of file
    ^g Display current line number
    h,j,k,l Left,Down,Up, and Right respectivly. Your arrow keys should also work if
    if your keyboard mappings are anywhere near sane.

    string substitution

    :n1,n2:s/string1/string2/[g] Substitute string2 for string1 on lines
    n1 to n2. If g is included (meaning global),
    all instances of string1 on each line
    are substituted. If g is not included,
    only the first instance per matching line is
    substituted.

    ^ matches start of line
    . matches any single character
    $ matches end of line

    These and other "special characters" (like the forward slash) can be "escaped" with \
    i.e to match the string "/usr/STRIM100/SOFT" say "\/usr\/STRIM100\/SOFT"

    Examples:

    :1,$:s/dog/cat/g Substitute 'cat' for 'dog', every instance
    for the entire file - lines 1 to $ (end of file)

    :23,25:/frog/bird/ Substitute 'bird' for 'frog' on lines
    23 through 25. Only the first instance
    on each line is substituted.


    Saving and quitting and other "ex" commands

    These commands are all prefixed by pressing colon (:) and then entered in the lower
    left corner of the window. They are called "ex" commands because they are commands
    of the ex text editor - the precursor line editor to the screen editor
    vi. You cannot enter an "ex" command when you are in an edit mode (typing text onto the screen)
    Press to exit from an editing mode.

    :w Write the current file.
    :w new.file Write the file to the name 'new.file'.
    :w! existing.file Overwrite an existing file with the file currently being edited.
    :wq Write the file and quit.
    :q Quit.
    :q! Quit with no changes.

    :e filename Open the file 'filename' for editing.

    :set number Turns on line numbering
    :set nonumber Turns off line numbering

    Monday, November 19, 2007

    Configuring sendmail Options

    sendmail has a number of options that allow you to customize the way it performs certain tasks. There are a large number of these, so we've listed only a few of the more commonly used ones in the upcoming list.

    To configure any of these options, you may either define them in the m4 configuration file, which is the preferable method, or you may insert them directly into the sendmail.cf file. For example, if we wished to have sendmail fork a new job for each mail message to be delivered, we might add the following line to our m4 configuration file:

    define(‘confSEPARATE_PROC’,‘true’)

    The corresponding sendmail.cf entry created is:

    O ForkEachJob=true

    The following list describes common sendmail m4 options (and sendmail.cf equivalents):

    confMIN_FREE_BLOCKS (MinFreeBlocks)

    There are occasions when a problem might prevent the immediate delivery of mail messages, causing messages to be queued in the mail spool. If your mail host processes large volumes of mail, it is possible for the mail spool to grow to such a size that it fills the filesystem supporting the spool. To prevent this, sendmail provides this option to specify the minimum number of free disk blocks that must exist before a mail message will be accepted. This allows you to ensure that sendmail never causes your spool filesystem to be filled (Default: 100).

    confME_TOO (MeToo)

    When a mail target such as an email alias is expanded, it is sometimes possible for the sender to appear in the recipient list. This option determines whether the originators of an email message will receive a copy if they appear in the expanded recipient list. Valid values are “true” and “false” (Default: false).

    confMAX_DAEMON_CHILDREN (MaxDaemonChildren)

    Whenever sendmail receives an SMTP connection from a remote host, it spawns a new copy of itself to deal with the incoming mail message. This way, it is possible for sendmail to be processing multiple incoming mail messages simulatanenously. While this is useful, each new copy of sendmail consumes memory in the host computer. If an unusually large number of incoming connections are received, by chance, because of a problem or a malicious attack, it is possible for sendmail daemons to consume all system memory. This option provides you with a means of limiting the maximum number of daemon children that will be spawned. When this number is reached, new connections are rejected until some of the existing children have terminated (Default: undefined).

    confSEPARATE_PROC (ForkEachJob)

    When processing the mail queue and sending mail messages, sendmail processes one mail message at a time. When this option is enabled, sendmail will fork a new copy of itself for each message to be delivered. This is particularly useful when there are some mail messages that are stuck in the queue because of a problem with the target host (Default: false).

    confSMTP_LOGIN_MSG (SmtpGreetingMessage)

    Whenever a connection is made to sendmail, a greeting message is sent. By default, this message contains the hostname, name of the mail transfer agent, the sendmail version number, the local version number, and the current date. RFC821 specifies that the first word of the greeting should be the fully qualified domain name of the host, but the rest of the greeting can be configured however you please. You can specify sendmail macros here and they will be expanded when used. The only people who will see this message are suffering system administrators diagnosing mail delivery problems or strongly curious people interested in discovering how your machine is configured. You can relieve some of the tedium of their task by customizing the welcome message with some witticisms; be nice. The word “EMSTP” will be inserted between the first and second words by sendmail, as this is the signal to remote hosts that we support the ESMTP protocol (Default: $j Sendmail $v/$Z; $b).

    Be Smart and Prevent Virus Infections through USB Drives

    One of the most common support requests we receive from our customers is for clearing their computers of viruses. Most of the infections that we see are by viruses that spread by capitalizing on the ignorance of the users. A few smart steps, if taken by the users, could easily prevent infection from some of the more common viruses that float around in the cyber-universe.

    USB drives(also called Thumb Drives and Flash Drives) have long replaced floppies and cds as the preferred medium to transfer files from one computer to another. Lot of virus infections happen when using USB drives infected with viruses. One common way in which they spread is by exploiting the 'autorun' feature in Microsoft Windows XP. When a USB drive is connected to an infected computer the virus copies itself on to the USB drive and creates an autorun.inf file in the drive pointing to the copy of the virus on the USB drive. When the drive is then plugged on to a clean system with Windows XP the autorun gets triggered and the virus gets executed and the system gets infected.

    You can very easily prevent this from happening by setting the "Take no Action" as the default action on inserting a USB drive. If you have the guts you could also disable autorun for all removable media by setting the key 'NoDriveTypeAutorun' at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\ CurrentVersion\policies\Explorer with the value 255. You can read more about disabling autorun at Annoyances.org

    Even after disabling autorun you could trigger the virus execution if you double click on the "Removable Media" drive from "My Computer" as autorun would be the default action when autorun.inf is present in the media. The safest way to browse the contents in a USB drive is to right click on the drive icon and then using the "Explore" option.

    Another common set of viruses use an innocuous setting in the Explorer to trick the user into executing the virus and infecting the system with the virus. The default settings in Windows XP sets the options "Hide extensions for known file types" and "Do not show Hidden Files and Folders". When a USB drive is connected to a PC infected with the virus, the virus hides all the folders in the USB drive, copies itself as many times to the drive as there were folders in the drive and renames the copies to the names of the original folders.

    A feature of the virus is that the file icon for the virus is exactly identical to the default folder icon in windows. So if you view the contents of the USB drive with the above options set, you will see icons of as many 'folders' as you would have expected. However each of these folder icons represents a file and not a folder and this file would be the virus file. The first of the above options ensures that you will not see the ".exe" part in the name and the second of the options ensures that you will not see the original folders that are now hidden. Additionally some of the strains of these viruses does the same processes in the subfolders in the drive too.

    When an unsuspecting user connects this infected Thumb Drive to his system and opens the drive he would see the folder icon he was looking for and once double clicked he would inadvertently infect his system with the virus.

    You can unset the above options by going to My Computer >> Tools >> Folder options >> View >> Advanced settings and then selecting the appropriate radio buttons. Once that is done you will be able to identify infected Thumb Drives and prevent infection very easily. Also if you are using the explore option while opening the Thumb Drive you will very easily see that, though the folder icons are listed as icons in the explorer, they will not come up as folders in the folder bar.

    So Important things to remember are

    • Never autorun from a Thumb Drive
    • Always use the explore option when opening Thumb Drives
    • Unset the option "Hide extensions for known file types"
    • Set the option "Show Hidden files and folders"
    • Keep your antivirus software updated and running all the time

    Finally, as a closing word, we urge you to take a look at the virus free world of Linux. Instead of trying to plug all loopholes in Windows and living under a constant threat of ever-evolving viruses, you could take a break and relax under the safe canopy of a secure Linux installation.

    Tuesday, November 13, 2007

    The Beauty of Math

    The Beauty of Mathematics with lesson for life.

    1 x 8 + 1 = 9
    12 x 8 + 2 = 98
    123 x 8 + 3 = 987
    1234 x 8 + 4 = 9876
    12345 x 8 + 5 = 98765
    123456 x 8 + 6 = 987654
    1234567 x 8 + 7 = 9876543
    12345678 x 8 + 8 = 98765432
    123456789 x 8 + 9 = 987654321

    1 x 9 + 2 = 11
    12 x 9 + 3 = 111
    123 x 9 + 4 = 1111
    1234 x 9 + 5 = 11111
    12345 x 9 + 6 = 111111
    123456 x 9 + 7 = 1111111
    1234567 x 9 + 8 = 11111111
    12345678 x 9 + 9 = 111111111
    123456789 x 9 +10= 1111111111

    9 x 9 + 7 = 88
    98 x 9 + 6 = 888
    987 x 9 + 5 = 8888
    9876 x 9 + 4 = 88888
    98765 x 9 + 3 = 888888
    987654 x 9 + 2 = 8888888
    9876543 x 9 + 1 = 88888888
    98765432 x 9 + 0 = 888888888

    Brilliant, isn't it?

    And look at this symmetry:

    1 x 1 = 1
    11 x 11 = 121
    111 x 111 = 12321
    1111 x 1111 = 1234321
    11111 x 11111 = 123454321
    111111 x 111111 = 12345654321
    1111111 x 1111111 = 1234567654321
    11111111 x 11111111 = 123456787654321
    111111111 x 111111111=12345678987654321

    Now, take a look at this...

    101%

    >From a strictly mathematical
    viewpoint:

    What Equals 100%? What does it mean to
    give MORE than 100%?
    Ever wonder about those people who say
    they are giving more than 100%?

    We have all been in situations where
    someone wants you to GIVE OVER 100%.

    How about ACHIEVING 101%?
    What equals 100% in life?
    Here's a little mathematical formula
    that might help answer these questions:
    If:
    A B C D E F G H I J K L M N O P Q R S T
    U V W X Y Z
    Is represented as:
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
    17 18 19 20 21 22 23 24 25 26
    If:
    H-A-R-D-W-O-R- K
    8+1+18+4+23+15+18+11 = 98%
    And:
    K-N-O-W-L-E-D-G-E
    11+14+15+23+12+5+4+7+5 = 96%
    But:
    A-T-T-I-T-U-D-E
    1+20+20+9+20+21+4+5 = 100%
    THEN, look how far the love of God will
    take you:
    L-O-V-E -O-F-G-O-D
    12+15+22+5+15+6+7+15+4 = 101%


    Therefore, one can conclude with
    mathematical certainty that:
    While Hard Work and Knowledge will get
    you close, and Attitude will get you
    there, it's the Love of God that will
    put you over the top!

    Character Types in postgresql

    NameDescription
    character varying(n), varchar(n)variable-length with limit
    character(n), char(n)fixed-length, blank padded
    textvariable unlimited length

    shows the general-purpose character types available in PostgreSQL.

    SQL defines two primary character types: character varying(n) and character(n), where n is a positive integer. Both of these types can store strings up to n characters in length. An attempt to store a longer string into a column of these types will result in an error, unless the excess characters are all spaces, in which case the string will be truncated to the maximum length. (This somewhat bizarre exception is required by the SQL standard.) If the string to be stored is shorter than the declared length, values of type character will be space-padded; values of type character varying will simply store the shorter string.

    If one explicitly casts a value to character varying(n) or character(n), then an over-length value will be truncated to n characters without raising an error. (This too is required by the SQL standard.)

    Note: Prior to PostgreSQL 7.2, strings that were too long were always truncated without raising an error, in either explicit or implicit casting contexts.

    The notations varchar(n) and char(n) are aliases for character varying(n) and character(n), respectively. character without length specifier is equivalent to character(1); if character varying is used without length specifier, the type accepts strings of any size. The latter is a PostgreSQL extension.

    In addition, PostgreSQL provides the text type, which stores strings of any length. Although the type text is not in the SQL standard, several other SQL database management systems have it as well.

    The storage requirement for data of these types is 4 bytes plus the actual string, and in case of character plus the padding. Long strings are compressed by the system automatically, so the physical requirement on disk may be less. Long values are also stored in background tables so they do not interfere with rapid access to the shorter column values. In any case, the longest possible character string that can be stored is about 1 GB. (The maximum value that will be allowed for n in the data type declaration is less than that. It wouldn't be very useful to change this because with multibyte character encodings the number of characters and bytes can be quite different anyway. If you desire to store long strings with no specific upper limit, use text or character varying without a length specifier, rather than making up an arbitrary length limit.)

    Tip: There are no performance differences between these three types, apart from the increased storage size when using the blank-padded type.

    Refer to Section 4.1.2.1 for information about the syntax of string literals, and to Chapter 9 for information about available operators and functions.

    Example 8-1. Using the character types

    CREATE TABLE test1 (a character(4));
    INSERT INTO test1 VALUES ('ok');
    SELECT a, char_length(a) FROM test1; -- (1)
    a | char_length
    ------+-------------
    ok | 4


    CREATE TABLE test2 (b varchar(5));
    INSERT INTO test2 VALUES ('ok');
    INSERT INTO test2 VALUES ('good ');
    INSERT INTO test2 VALUES ('too long');
    ERROR: value too long for type character varying(5)
    INSERT INTO test2 VALUES ('too long'::varchar(5)); -- explicit truncation
    SELECT b, char_length(b) FROM test2;
    b | char_length
    -------+-------------
    ok | 2
    good | 5
    too l | 5
    (1)
    The char_length function is discussed in Section 9.4.

    There are two other fixed-length character types in PostgreSQL, shown in Table 8-5. The name type exists only for storage of identifiers in the internal system catalogs and is not intended for use by the general user. Its length is currently defined as 64 bytes (63 usable characters plus terminator) but should be referenced using the constant NAMEDATALEN. The length is set at compile time (and is therefore adjustable for special uses); the default maximum length may change in a future release. The type "char" (note the quotes) is different from char(1) in that it only uses one byte of storage. It is internally used in the system catalogs as a poor-man's enumeration type.

    Table 8-5. Special Character Types

    NameStorage SizeDescription
    "char"1 bytesingle-character internal type
    name64 bytesinternal type for object names

    Installing sendmail

    The sendmail mail transport agent is included in prepackaged form in most Linux distributions. Installation in this case is relatively simple. Despite this fact, there are some good reasons to install sendmail from source, especially if you are security conscious. The sendmail program is very complex and has earned a reputation over the years for containing bugs that allow security breaches. One of the best known examples is the RTM Internet worm that exploited a buffer overflow problem in early versions of sendmail. We touched on this briefly in Chapter 9. Most security exploits involving buffer overflows rely on all copies of sendmail on different machines being identical, as the exploits rely on data being stored in specific locations. This, of course, is precisely what happens with sendmail installed from Linux distributions. Compiling sendmail from source yourself can help reduce this risk. Modern versions of sendmail are less vulnerable because they have come under exceedingly close scrutiny as security has become a more widespread concern throughout the Internet community.

    The sendmail source code is available via anonymous FTP from ftp.sendmail.org.

    Compilation is very simple bceause the sendmail source package directly supports Linux. The steps involved in compiling sendmail are:

    # cd /usr/local/src
    # tar xvfz sendmail.8.9.3.tar.gz
    # cd src
    # ./Build
    You need root permissions to complete the installation of the resulting binary files using:
    # cd obj.Linux.2.0.36.i586
    # make install
    You have now installed the sendmail binary into the /usr/sbin directory. Several symbolic links to the sendmail binary will be installed into the /usr/bin/ directory. We'll talk about those links when we discuss common tasks in running sendmail.

    sendmail

    It's been said that you aren't a real Unix system administrator until you've edited a sendmail.cf file. It's also been said that you're crazy if you've attempted to do so twice.

    sendmail is an incredibly powerful mail program. It's also incredibly difficult to learn and understand. Any program whose definitive reference (sendmail, by Bryan Costales and Eric Allman, published by O'Reilly) is 1,050 pages long scares most people off. Information on the sendmail reference is contained in the bibliography at the end of this book.

    Fortunately, new versions of sendmail are different. You no longer need to directly edit the cryptic sendmail.cf file; the new version provides a configuration utility that will create the sendmail.cf file for you based on much simpler macro files. You do not need to understand the complex syntax of the sendmail.cf file; the macro files don't require you to. Instead, you need only list items, such as the name of features you wish to include in your configuration, and specify some of the parameters that determine how that feature operates. A traditional Unix utility called m4 then takes your macro configuration data and mixes it with the data it reads from template files containing the actual sendmail.cf syntax, to produce your sendmail.cf file.

    In this chapter we introduce sendmail and describe how to install, configure and test it, using the Virtual Brewery as an example. If the information presented here helps make the task of configuring sendmail less daunting for you, we hope you'll gain the confidence to tackle more complex configurations on your own.

    Thursday, October 11, 2007

    Procedure to add a user to PostgreSQL database

    To create a normal user and an associated database you need to type the following commands. The easiest way to use is to create a Linux / UNUX IDENT authentication i.e. add user tom to UNIX or Linux system first.

    Step # 1: Add a Linux/UNIX user called tom

    Type the following commands to create a UNIX/Linux user called tom:
    # adduser tom
    # passwd tom

    Step # 2: Becoming a superuser

    You need to login as database super user under postgresql server. Again the simplest way to connect as the postgres user is to change to the postgres unix user on the database server using su command as follows:
    # su - postgres

    Step #3: Now connect to database server

    Type the following command
    $ psql template1
    OR
    $ psql -d template1 -U postgres
    Output:

    Welcome to psql 7.4.16, the PostgreSQL interactive terminal.

    Type: \copyright for distribution terms
    \h for help with SQL commands
    \? for help on internal slash commands
    \g or terminate with semicolon to execute query
    \q to quit

    template1=#

    Step #4: Add a user called tom

    Type the following command to create a user called tom with a password called myPassword (you need to type command highlighted with red color):
    template1=# CREATE USER tom WITH PASSWORD ‘myPassword’;

    Step #5: Add a database called jerry

    Type the following command (you need to type command highlighted with red color):
    template1=# CREATE DATABASE jerry;
    Now grant all privileges on database
    template1=# GRANT ALL PRIVILEGES ON DATABASE jerry to tom;
    Type \q to quit:
    template1=# \q

    Step #6: Test tom user login

    In order to login as tom you need to type following commands. Login as tom or use su command:
    $ su - tom
    $ psql -d jerry -U tom

    Output:

    Welcome to psql 7.4.16, the PostgreSQL interactive terminal.

    Type: \copyright for distribution terms
    \h for help with SQL commands
    \? for help on internal slash commands
    \g or terminate with semicolon to execute query
    \q to quit

    jerry=>

    Tuesday, October 9, 2007

    Common error messages

    10.1 ‘The server's host key is not cached in the registry’

    This error message occurs when PuTTY connects to a new SSH server. Every server identifies itself by means of a host key; once PuTTY knows the host key for a server, it will be able to detect if a malicious attacker redirects your connection to another machine.

    If you see this message, it means that PuTTY has not seen this host key before, and has no way of knowing whether it is correct or not. You should attempt to verify the host key by other means, such as asking the machine's administrator.

    If you see this message and you know that your installation of PuTTY has connected to the same server before, it may have been recently upgraded to SSH protocol version 2. SSH protocols 1 and 2 use separate host keys, so when you first use SSH 2 with a server you have only used SSH 1 with before, you will see this message again. You should verify the correctness of the key as before.

    See section 2.2 for more information on host keys.

    10.2 ‘WARNING - POTENTIAL SECURITY BREACH!’

    This message, followed by ‘The server's host key does not match the one PuTTY has cached in the registry’, means that PuTTY has connected to the SSH server before, knows what its host key should be, but has found a different one.

    This may mean that a malicious attacker has replaced your server with a different one, or has redirected your network connection to their own machine. On the other hand, it may simply mean that the administrator of your server has accidentally changed the key while upgrading the SSH software; this shouldn't happen but it is unfortunately possible.

    You should contact your server's administrator and see whether they expect the host key to have changed. If so, verify the new host key in the same way as you would if it was new.

    See section 2.2 for more information on host keys.

    10.3 ‘Out of space for port forwardings’

    PuTTY has a fixed-size buffer which it uses to store the details of all port forwardings you have set up in an SSH session. If you specify too many port forwardings on the PuTTY or Plink command line and this buffer becomes full, you will see this error message.

    We need to fix this (fixed-size buffers are almost always a mistake) but we haven't got round to it. If you actually have trouble with this, let us know and we'll move it up our priority list.

    10.4 ‘The first cipher supported by the server is ... below the configured warning threshold’

    This occurs when the SSH server does not offer any ciphers which you have configured PuTTY to consider strong enough.

    See section 4.17.5 for more information on this message.

    10.5 ‘Server sent disconnect message type 2 (SSH_DISCONNECT_PROTOCOL_ERROR): "Too many authentication failures for root"’

    This message is produced by an OpenSSH (or Sun SSH) server if it receives more failed authentication attempts than it is willing to tolerate. This can easily happen if you are using Pageant and have a large number of keys loaded into it. This can be worked around on the server by disabling public-key authentication or (for Sun SSH only) by increasing MaxAuthTries in sshd_config. Neither of these is a really satisfactory solution, and we hope to provide a better one in a future version of PuTTY.

    10.6 ‘Out of memory’

    This occurs when PuTTY tries to allocate more memory than the system can give it. This may happen for genuine reasons: if the computer really has run out of memory, or if you have configured an extremely large number of lines of scrollback in your terminal. PuTTY is not able to recover from running out of memory; it will terminate immediately after giving this error.

    However, this error can also occur when memory is not running out at all, because PuTTY receives data in the wrong format. In SSH 2 and also in SFTP, the server sends the length of each message before the message itself; so PuTTY will receive the length, try to allocate space for the message, and then receive the rest of the message. If the length PuTTY receives is garbage, it will try to allocate a ridiculous amount of memory, and will terminate with an ‘Out of memory’ error.

    This can happen in SSH 2, if PuTTY and the server have not enabled encryption in the same way (see question A.7.5 in the FAQ). Some versions of OpenSSH have a known problem with this: see question A.7.16.

    This can also happen in PSCP or PSFTP, if your login scripts on the server generate output: the client program will be expecting an SFTP message starting with a length, and if it receives some text from your login scripts instead it will try to interpret them as a message length. See question A.7.6 for details of this.

    10.7 ‘Internal error’, ‘Internal fault’, ‘Assertion failed’

    Any error beginning with the word ‘Internal’ should never occur. If it does, there is a bug in PuTTY by definition; please see appendix B and report it to us.

    Similarly, any error message starting with ‘Assertion failed’ is a bug in PuTTY. Please report it to us, and include the exact text from the error message box.

    10.8 ‘Unable to use this private key file’, ‘Couldn't load private key’, ‘Key is of wrong type’

    Various forms of this error are printed in the PuTTY window, or written to the PuTTY Event Log (see section 3.1.3.1) when trying public-key authentication, or given by Pageant when trying to load a private key.

    If you see one of these messages, it often indicates that you've tried to load a key of an inappropriate type into PuTTY, Plink, PSCP, PSFTP, or Pageant.

    You may have specified a key that's inappropriate for the connection you're making. The SSH-1 and SSH-2 protocols require different private key formats, and a SSH-1 key can't be used for a SSH-2 connection (or vice versa).

    Alternatively, you may have tried to load an SSH-2 key in a ‘foreign’ format (OpenSSH or ssh.com) directly into one of the PuTTY tools, in which case you need to import it into PuTTY's native format (*.PPK) using PuTTYgen - see section 8.2.12.

    10.9 ‘Server refused our public key’ or ‘Key refused’

    Various forms of this error are printed in the PuTTY window, or written to the PuTTY Event Log (see section 3.1.3.1) when trying public-key authentication.

    If you see one of these messages, it means that PuTTY has sent a public key to the server and offered to authenticate with it, and the server has refused to accept authentication. This usually means that the server is not configured to accept this key to authenticate this user.

    This is almost certainly not a problem with PuTTY. If you see this type of message, the first thing you should do is check your server configuration carefully. Also, read the PuTTY Event Log; the server may have sent diagnostic messages explaining exactly what problem it had with your setup.

    10.10 ‘Access denied’, ‘Authentication refused’

    Various forms of this error are printed in the PuTTY window, or written to the PuTTY Event Log (see section 3.1.3.1) during authentication.

    If you see one of these messages, it means that the server has refused all the forms of authentication PuTTY has tried and it has no further ideas.

    It may be worth checking the Event Log for diagnostic messages from the server giving more detail.

    This error can be caused by buggy SSH-1 servers that fail to cope with the various strategies we use for camouflaging passwords in transit. Upgrade your server, or use the workarounds described in section 4.20.1 and possibly section 4.20.2.

    10.11 ‘Incorrect CRC received on packet’ or ‘Incorrect MAC received on packet’

    This error occurs when PuTTY decrypts an SSH packet and its checksum is not correct. This probably means something has gone wrong in the encryption or decryption process. It's difficult to tell from this error message whether the problem is in the client or in the server.

    A known server problem which can cause this error is described in question A.7.16 in the FAQ.

    10.12 ‘Incoming packet was garbled on decryption’

    This error occurs when PuTTY decrypts an SSH packet and the decrypted data makes no sense. This probably means something has gone wrong in the encryption or decryption process. It's difficult to tell from this error message whether the problem is in the client or in the server.

    If you get this error, one thing you could try would be to fiddle with the setting of ‘Miscomputes SSH2 encryption keys’ on the Bugs panel (see section 4.20.5).

    Another known server problem which can cause this error is described in question A.7.16 in the FAQ.

    10.13 ‘PuTTY X11 proxy: various errors

    This family of errors are reported when PuTTY is doing X forwarding. They are sent back to the X application running on the SSH server, which will usually report the error to the user.

    When PuTTY enables X forwarding (see section 3.4) it creates a virtual X display running on the SSH server. This display requires authentication to connect to it (this is how PuTTY prevents other users on your server machine from connecting through the PuTTY proxy to your real X display). PuTTY also sends the server the details it needs to enable clients to connect, and the server should put this mechanism in place automatically, so your X applications should just work.

    A common reason why people see one of these messages is because they used SSH to log in as one user (let's say ‘fred’), and then used the Unix su command to become another user (typically ‘root’). The original user, ‘fred’, has access to the X authentication data provided by the SSH server, and can run X applications which are forwarded over the SSH connection. However, the second user (‘root’) does not automatically have the authentication data passed on to it, so attempting to run an X application as that user often fails with this error.

    If this happens, it is not a problem with PuTTY. You need to arrange for your X authentication data to be passed from the user you logged in as to the user you used su to become. How you do this depends on your particular system; in fact many modern versions of su do it automatically.

    10.14 ‘Network error: Software caused connection abort’

    This error occurs when the Windows network code decides that your network connection is dead. For example, it will happen if you pull the network cable out of the back of an Ethernet-connected computer, or if Windows has any other similar reason to believe the entire network has become unreachable.

    We are not aware of any reason why this error might occur that would represent a bug in PuTTY. The problem is between you, your Windows system, your network and the remote system.

    10.15 ‘Network error: Connection reset by peer’

    This error occurs when the machines at each end of a network connection lose track of the state of the connection between them. For example, you might see it if your SSH server crashes, and manages to reboot fully before you next attempt to send data to it.

    However, the most common reason to see this message is if you are connecting through a firewall or a NAT router which has timed the connection out. See question A.7.10 in the FAQ for more details. You may be able to improve the situation by using keepalives; see section 4.13.4 for details on this.

    10.16 ‘Network error: Connection refused’

    This error means that the network connection PuTTY tried to make to your server was rejected by the server. Usually this happens because the server does not provide the service which PuTTY is trying to access.

    Check that you are connecting with the correct protocol (SSH, Telnet or Rlogin), and check that the port number is correct. If that fails, consult the administrator of your server.

    10.17 ‘Network error: Connection timed out’

    This error means that the network connection PuTTY tried to make to your server received no response at all from the server. Usually this happens because the server machine is completely isolated from the network, or because it is turned off.

    Check that you have correctly entered the host name or IP address of your server machine. If that fails, consult the administrator of your server.

    Monday, October 8, 2007

    How do I use sprintf() function in a perl script under Linux or UNIX?

    perl printf() function is use to format and print data on screen.

    You need to use sprintf to print or store formatted data/string to a variable or to a string.

    Also note that Perl does its own sprintf formatting–it emulates the C function sprintf, but it doesn’t use it (except for floating-point numbers, and even then only the standard modifiers are allowed). As a result, any non-standard extensions in your local sprintf are not available from Perl.

    perl printf() example

    Following statement will round number to 2 digits after decimal point (type at shell prompt):
    $ perl -e '$num=53535.35353535;printf ("Result = %.2f\n",$num);'

    perl sprintf() example

    Type following at shell prompt:

    $ perl -e '$num=53535.35353535;$result=sprintf("Result = %.2f\n",$num);print "$result"'

    If you need to store output to a string / variable called $result you need to use sprintf(). Here is a small script to make you idea more clear:

    #!/usr/bin/perl
    $num=585858.64645;
    $result = sprintf("%.2f", $num);
    $now=sprintf("Today is ".`date`);
    print "$result\n";
    print "$now\n";

    How to use unrar

    unrar command supports various options below are common options that you need to use everyday.

    Task: To open rar (unpack) file in current directory type command:

    $ unrar e file.rar

    Please note that replace file.rar filename with your actual filename.

    Task: List (l) file inside rar archive:

    $ unrar l file.rar

    Task: To extract (x) files with full path type command:

    $ unrar x file.rar

    (D) To test (t) integrity of archive, file type command:
    $ unrar t file.rar

    Install unrar command

    Under Debian Linux, you need to type apt-get as follows to install unrar program:
    # apt-get install unrar

    If you are using Fedora core Linux then use yum command as follows (see discussion below):
    # yum install unrar

    If you are using FreeBSD, use:
    # pkg_add -v -r unrar

    If any of above, methods is not working for you, download binary package from official rarlab site:
    $ cd /tmp
    $ wget http://www.rarlab.com/rar/rarlinux-3.6.0.tar.gz

    Untar file
    $ tar -zxvf rarlinux-3.6.0.tar.gz

    Both unrar and rar commands are located in rar sub-directory. Just go to rar directory:
    $ cd rar
    $ ./unrar

    Now copy rar and unrar to /bin directory:
    # cp rar unrar /bin

    Sunday, October 7, 2007

    puzzles

    Apples delivery

    The distance between the towns A and B is 1000 miles. There is 3000 apples in A, and the apples have to be delivered to B. The available car can take 1000 apples at most. The car driver has developed an addiction to apples: when he has apples aboard he eats 1 apple with each mile made. Figure out the strategy that yields the largest amount of apples to be delivered to B.

    Generalize the strategy for an arbitrary amount of apples.

    Zen problem

    A Buddhist monk got an errand from his teacher: to meditate for exactly 45 minutes. He has no watch; instead he is given two inscent sticks, and he is told that each of those sticks would completely burn in 1 hour. The sticks are not identical, and they burn with variant yet unknown rates (they are hand-made). So he has these two inscent and some matches: can he arrange for exactly 45 minutes of meditation?

    Tuesday, October 2, 2007

    Recovering Permanently Deleted Mails :

    Procedure

    1: Go to Run & type regedit.

    2: Go to hkey_local_machine\software\microsoft\exchange\client\options.

    3: right click on the right hand side & choose new dword value & name the key to DumpsterAlwaysOn It is case sensitive.

    4: Then right click & select ‘modify’ & make the value 1 to turn the recover deleted items menu choice on for all the folders or enter 0 to turn it off.

    5: Then go to Outlook, & choose”Recover deleted items” option from the tools menu to get back your permanently deleted” mails.

    Note: this procedure can recover mails which were deleted by pressing shift+del in the past 4 days.

    SEARCH ENGINES

    THE MYTH

    It is a myth among web designers that with the right meta tags you can make it to the top on all search engines.
    The truth is close to being the opposite.

    With the wrong meta tags you can make it to the bottom,
    but meta tags alone do not take you to the top anywhere.



    THE ABUSE

    Two meta tags have special relevance for search engines: Description and Keywords.

    When search engines first started to look for these meta tags, the intention was that web designers could emphasize what the pages were about. For example, a scientific page about the surface of the moon might not have the word "moon" on it, although the page definately related to the topic "moon".

    Creative minds didn't take long to find out that this could be an excellent tool for improving search rankings. Many webmasters included keywords and descriptions that held no relevance to their page.

    THE STRIKE BACK

    After some time, the meta tags did not serve the purpose they were intended for. Most were being used for spamming. Therefore, some search engines, such as Excite, stopped looking at them entirely.

    Other search engines, such as Infoseek, directed the spammers weapons back at them. They simply ranked sites lower if the meta tags included words that were not present in the content of the page.

    THE CONCLUSION

    • Use meta tags with care.

    • Do not include words that are not present on your pages.

    • Do not repeat words.

    • Use the meta tags the way they were intended, because the search engines are well aware that meta tags are an excellent filter for spam sites.


    Let's proceed to the details about the tags.




    DESCRIPTION

    name="DESCRIPTION" content="AN HTML Tutorial">


    Most search engines will display the description when they list results from a search.
    If you do not include this tag, then the engine will simply list the first words on the page - which is not always very meaningful.




    KEYWORDS

    name="KEYWORDS" content="html, webdesign, javascript">


    This meta tag was intended to be used for keywords with special relevance for the page.
    But because of misuse, many engines skip them. Others use them as an indicator of whether a page is spam or not.
    The few that use them to indicate what the page is really about, do not value them as much as they used to.




    OTHER TAGS

    Many HTML editors create a meta tag telling which program was used for the page.

    name="GENERATOR" content="Frontpage 3.0">






    Another common tag tells who created the page:

    name="AUTHOR" content="Bill Gates">





    Finally there are some meta tags that are only relevant to certain search engines.

    Individual search engines will recognize different tags telling it when to come back and re-index the site etc.

    Look at the help sections for particular search engines to see which meta tags are supported.