Friday, December 28, 2012

What is the substitute to '>/dev/null'?

|:’ is built-in pipe-based data sink and faster than ‘>/dev/null’. For instance,

echo "Hello World!" >/dev/null
can be rewritten as
echo "Hello World!" |:

How could you figure out the shell currently being run?

readlink -f /proc/$$/exe

Thursday, December 27, 2012

What are the ways to read contents of a file in Perl?

open (FH, "< io.txt") or die $!;
while(<FH>)
{
 print $_;
}
close(FH);

or

use Fcntl;

sysopen(FH, "io.txt", O_RDONLY) or die $!;
while(<FH>)
{
 print $_;
}
close(FH) || die "Couldn't close file properly.";

or

use IO::File;

my $FH = new IO::File("io.txt", "r") or die "could not open $filename : $!\n";
while ($line = $FH->getline())
{
   print $line;
}
$FH->close();

Friday, September 21, 2012

How do you run MS SQL Server queries from command prompt?

Use either osql ( Oregon SQL ) or sqlcmd  command line utility.

What is the difference between exec and fork?

fork creates a new process by replicating itself (file descriptors, etc) to a subshell and runs the forked process in that subshell via exec. The new process acts as an independent process in separte memory space with its own unique process ID. It creates a Parent-Child relationship wherin the child returns its PID to parent and the parent provides zero on successful fork.

exec, on the other hand, executes the given process by replacing the current process. exec doesn't return any value on success. It shares the same memory space for the new process.

Tuesday, September 18, 2012

How do you insert data into the table of a database in Oracle in Perl?

use DBI;

$oracle_server = 'localhost';
$oracle_user = '<UserName>';
$oracle_passwd = '<Password>';
$oracle_sid = 'ORCL';
$oracle_table = 'PerlDB';
$oracle_port = '1521';

$dbh = DBI->connect("dbi:Oracle:host=$oracle_server; port=$oracle_port; sid=$oracle_sid", $oracle_user, $oracle_passwd, { RaiseError => 1, AutoCommit => 0}) or die "$DBI::errstr\n";

my $sql = "INSERT INTO $oracle_table (EMP_NUM, EMP_NM, JOB, MNGR_ID, SAL) VALUES (?, ?, ?, ?, ?)";

my $rv = $dbh->do($sql, undef, 21295, 'RABINDRA', 'PROGRAMMER', 7839, 8000) or die "$DBI::errstr";
$dbh->disconnect();

Monday, September 17, 2012

How do you connect Perl and Oracle on Windows?

#!C:/Perl/bin/perl

use DBI;

$oracle_server = 'localhost';
$oracle_user = '<UserName>';
$oracle_passwd = '<Password>';
$oracle_sid = '<SID>';
$oracle_table = 'EMP';
$oracle_port = '1521';

# Get a database handle by connecting to the database
$dbh = DBI->connect("dbi:Oracle:host=$oracle_server; port=$oracle_port; sid=$oracle_sid", $oracle_user, $oracle_passwd, { RaiseError => 1, AutoCommit => 1}) or die "$DBI::errstr\n";

my $sql = "SELECT E.EMPNO AS EMPLOYEE_ID,
   E.ENAME AS EMPLOYEE_NM,
   M.ENAME AS MNGR_NM
   FROM   $oracle_table E
   LEFT OUTER JOIN $oracle_table M
            ON E.MGR = M.EMPNO
   ORDER  BY E.EMPNO";

my $sth = $dbh->prepare($sql) or die "$DBI::errstr";
$sth->execute() or die "$! $?\n";

my $COL_NM = join("\t", @{$sth->{NAME}});
print "$COL_NM\n";

while (my @row = $sth->fetchrow_array())
{
    print join("\t", @row), "\n";
}

$sth->finish();
$dbh->disconnect();

How can you get column names of a table in Oracle?

SELECT column_name
FROM USER_TAB_COLUMNS
WHERE table_name = '<TableName>';

How could you find out all the table names having a specific column name in Oracle?

SELECT TABLE_NAME
FROM ALL_TAB_COLUMNS
WHERE COLUMN_NAME = '<ColumnName>';

SELECT TABLE_NAME
FROM USER_TAB_COLUMNS
WHERE COLUMN_NAME = '<ColumnName>';

SELECT TABLE_NAME
FROM DBA_TAB_COLUMNS
WHERE COLUMN_NAME = '<ColumnName>';

- USER_TAB_COLS for tables owned by the current user and ALL_TAB_COLS or DBA_TAB_COLS for tables owned by all users.

How can you get the First/Top N rows in Oracle?

select *
from <TableName>
where rownum <= n;

Saturday, September 15, 2012

How do you run shell commands transparently within Perl?

#!/usr/bin/perl
use Shell;

my $sh = Shell->new;
print $sh->ls(-l);

or

#!/usr/bin/perl

use Shell qw(ls who);
@fileList = ls ("-l");
@userList = who ("-m");
print @fileList;
print @userList;

How can you receive the output of an external command using open( ) in Perl?

#!C:/Perl/bin/perl -w
use strict;
open (PS, "dir/b |") || die "$!\n";
while ( <PS> )
{
   print "$_\n";
}
close (PS) or die $!;

Thursday, September 13, 2012

Write a batch file to kill frozen programs.

@echo off
taskkill /f /fistatus eq not responding
exit

- Copy the above 3 lines to Notepad and save the file as "killall.bat".
- On click, it kills all the programs that do not respond.

How do you remove duplicate lines in a file in UNIX without changing order of contents?

awk '!x[$0]++' <FileName> > <New FileName>

How do you create a pseudo drive or map a local folder to a pseudo drive in MS Windows?

Suppose, we want a folder (e.g. AutoDrive) to act as a pseudo drive. Now assume "Z:" to be used as Drive Letter, do either of the followings:

Click Start, choose Run and type:
SUBST Z: C:\AutoDrive
then click OK.
or
type "SUBST Z: C:\AutoDrive" at the command prompt without quotes.

Again, to remove the substituted "Z:" drive, follow either of the ways mentioned below:

click Start, choose Run and type:
SUBST Z: /d
or
type "SUBST Z: /d" at the command prompt without quotes.

Wednesday, September 5, 2012

How can you get basename of a Perl script on any OS using regular expression?

$me = $0;

if ( $^O eq 'MSWin32' )
{
         $me=~s{.*\\}{};
         print "Usage :  $me <file>!\n"
}
else
{
         $me=~s{.*/}{};
         print "Usage :  $me <file>!\n"
}

Or

my $command = $0;
$command =~ s#^.*/##;

Or

( my $me = $0 ) =~ s{.*(\\|/)}{};

Tuesday, September 4, 2012

How do you run the last command without the last argument?

use "!:-"

For example, if the following is the last command

sort -k2 <FileName>

then

!:- <New FileName>

is the same as

sort -k2 <New FileName>

How do you insert the result of a command into VI?

!!<COMMAND>

- will insert the result of the command into vi at the current position of the cursor.

How do you execute a command and kill itself after some duration?

timeout 5s <COMMAND>

-> Starts COMMAND, and kills itself after 5 seconds

How can you sort the values of a Hash alphabeticlly?

#!/usr/bin/perl
   
%FM = ( '91.1 '=> 'Radio City',
              '92.7' => 'Big FM',
              '93.5' => 'Red FM',
              '94.3' => 'Radio One',
              '98.3' => 'Radio Mirchi',
              '104.0' => 'Fever',
              '104.8' => 'Oye FM',
              '107.1' => 'FM Rainbow',
              '100.7' => 'FM Gold');

foreach $station (sort { $FM{$a} cmp $FM{$b} } keys %FM)
{
    print "$station is $FM{$station}.\n";
}

How can you sort the values of a Hash numerically?

#!/usr/bin/perl
   
%FM = ( 'Radio City' => '91.1',
              'Big FM' => '92.7',
              'Red FM' => '93.5',
              'Radio One' => '94.3',
              'Radio Mirchi' => '98.3',
              'Fever' => '104.0',
              'Oye FM' => '104.8',
              'FM Rainbow' => '107.1',
              'FM Gold' => '100.7');

foreach $station (sort { $FM {$a} <=> $FM {$b}} keys %FM )
{
        print "$station is $FM{$station} MHz.\n";
}

How can you sort the keys of a Hash alphabetically?

#!/usr/bin/perl
   
%FM = ( 'Radio City' => 91.1,
              'Big FM' => 92.7,
              'Red FM' => 93.5,
              'Radio One' => 94.3,
              'Radio Mirchi' => 98.3,
              'Fever' => 104.0,
              'Oye FM' => 104.8,
              'FM Rainbow' => 107.1,
              'FM Gold' => 100.7);

foreach $station (sort keys %FM)
{
    print "$station is $FM{$station} MHz.\n";
}

How can you sort the keys of a Hash numerically?

#!/usr/bin/perl

%FM = ( '91.1' => 'Radio City',
              '92.7' => 'Big FM',
              '93.5' => 'Red FM',
              '94.3' => 'Radio One',
              '98.3' => 'Radio Mirchi',
              '104.0' => 'Fever',
              '104.8' => 'Oye FM',
              '107.1' => 'FM Rainbow',
              '100.7' => 'FM Gold');

for $key ( sort {$a<=>$b} keys %FM )
{
        print "$key->$FM{$key}\n";
}

or

foreach ( sort { $a <=> $b } keys(%FM) )
{
    print "$_ = $FM{$_}\n";
}

How can you get the keys of a Hash in Perl?

#!/usr/bin/perl

%FM = ( 'Radio City' => 91.1,
              'Big FM' => 92.7,
              'Red FM' => 93.5,
              'Radio One' => 94.3,
              'Radio Mirchi' => 98.3,
              'FM Gold' =>100.7,
              'Fever' => 104.0,
              'Oye FM' => 104.8,
              'FM Rainbow' => 107.1);

#get keys only
foreach my $key (sort keys %FM)
{
        print "$key\n";
}

Write shell script to convert 10 to binary.

#!/bin/sh

binary=({0..1}{0..1}{0..1}{0..1})
echo ${binary[10]}

How could you delete all empty lines from a file within VI?

:g/^$/d
or
:g!/\S/d

Monday, September 3, 2012

How do you get the duplicate/repeated lines in a file in UNIX?

uniq -d <FileName> # print only those lines which are repeated

uniq -c <FileName> # adds the number of occurrences of each line

uniq -u <FileName> # print only those lines which are not at all repeated

What is the substitute to backticks?

"$( )" is the substitute to backticks (``) with an advantage of nesting commands without escapes and better readability. The only bottleneckness $( ) suffers from is lack of portability.

For Example,

VAR=`date +%D`
echo "The date is: $VAR"

or

echo "The date is: `date +%D`"

The above lines can be replaced with the following one :

echo "The date is: $(date +%D)"

How could you close shell keeping all subprocess running?

disown -a && exit

How do you empty or flush all contents of a file without removing it in UNIX?

Prefix the file with ">" and "space" at command line.

> <FileName>

How do you run a command without saving in the history in UNIX?

Prefixing one or more spaces to the command won't be saved in history.
<space> command

How do you wrap text file / line / words to fit in specified width in UNIX?

fold -sw {COUNT} {input.txt} > {output.txt}

Where,
-s: break at spaces.
-w: {COUNT} use COUNT as WIDTH columns instead of default 80.

For instance, following command will wrap input.txt at 70 width columns:

fold -sw 70 input.txt > output.txt

How do you sort a file on a particular column in UNIX?

sort -k2 <FileName>

will be sorted on column 2.

How do you preserve Ownership and Timestamp while copying files in UNIX?

cp -p <source> <destination>

Wednesday, August 29, 2012

How could you convert a flat file to XML in Perl?

#!/usr/bin/perl

if ($#ARGV < 0)
{
 print "Usage : $0 <FlatFile Name>\n";
 exit;
}

my $in_txt=shift @ARGV;
my $out_xml=$in_txt;
$out_xml=~s/\.txt/\.xml/g;

open(INFO,"<$in_txt");
open(XML,">$out_xml");

print XML "<\?xml version=\"1.0\" encoding=\"UTF-16\"\?>\n";
print XML "<employee>\n";
while(<INFO>)
{
 if (/\A(.*?),(\d*+),(.*?),(\d*+),(\d*-\d*-\d+)/is)
 {
  print XML "<Employee_Detail>\n\t<Name>$1<\/Name>\n\t<Id>$2<\/Id>\n\t<State>$3<\/State>\n\t<Extension>$4<\/Extension>\n\t<Mobile>$5<\/Mobile>\n<\/Employee_Detail>\n";
 }
}
print XML "<\/employee>";
print "\"$in_txt\" got successfully converted to \"$out_xml\"";

employee.txt - The Flat File
------------------------------------------------------------------
Rabindra Nayak,23371,New Jercy,2370,212-555-6868
Mark Perino,23750,New York,2459,212-555-7979
Adam Gill,18654,DC,3897,212-555-5757
Tim Anderson,23456,Virginia,6543,212-555-3030
Mike Gotham,22500,Phoenix,7856,212-555-8989

Tuesday, August 28, 2012

Write a shell script to print itself.

#!/bin/sh

cat $0

How do you kill a process tree in UNIX?

Sometimes processes tend to re-spawn after being killed even if the parent process is killed.
The command below will kill all of the process (e.g. httpd process) :

ps -ef | grep httpd | awk '{print $2}' | xargs kill -9

How do you create temporary tables in Oracle?

Oracle database allows us to create Temporary tables of two types:

1- Transaction Specific Temporary Table
2- Session Specific Temporary Table

A transaction specific temporary table holds data when a transaction begins with execution of first SQL statement and ends either by commit or rollback. The following command creates a transaction specific temporary table.

CREATE global TEMPORARY TABLE temp_table
  (
     emp_id   NUMBER,
     emp_name VARCHAR2(50)
  )
ON COMMIT DELETE ROWS;


Note :- If "ON COMMIT" clause is omitted, by default oracle creates a transaction specific temporary table.

A session specific temporary table holds data until session lasts. When a commit is performed on session specific temporary table, data is preserved in table. But the data is not visible to others session. The data is lost when session ends.

Session specific temporary table can be created using “PRESERVE ROWS” in ON COMMIT clause.

CREATE global TEMPORARY TABLE temp_table
  (
     emp_id   NUMBER,
     emp_name VARCHAR2(50)
  )
ON COMMIT preserve ROWS;


The definition of temporary table is visible to all the sessions. Unlike permanent table, segment for temporary table is allocated when first INSERT statement is executed on temporary table. Indexes can also be created on temporary tables. The scope and life time of these indexes is similar to temporary tables.

Monday, August 27, 2012

How do you create temp tables in Sybase?

You can create Sybase temp tables in 2 ways :

1. CREATE TABLE #TableName
2. CREATE TABLE tempdb..TableName

Temp table being created with "#" are accessible by the current session or procedure and the table gets  automatically dropped when the session/procedure ends or is dropped manually.

Table being created using "tempdb..TableName" resides in tempdb database and remains as long as not dropped in manually. It is shareable among all sessions.

** If a table is created in any database other than tempdb, it won't be a temp table.

How could you determine the directory a shell script is in?

#!/usr/bin/sh -f

_DIR=`dirname "$(readlink -f $0)"`
echo ${_DIR}

Write a self-terminating shell script which doesn't hang up indefinately.

#!/usr/bin/sh

( sleep 5 ; echo Warning $0 hanging - aborted ; kill -9 $$ ) &
TIMEOUT_PID=$!

Your_Line1 ...
Your_Line2 ...
Your_Line3 ...
Your_Line4 ...
Your_Line5 ... 

# kill supervision sub-process
kill -9 $TIMEOUT_PID

How do you get 2nd, 3rd column of 2nd, 3rd row of CSV file?


head -3  <FileName> | tail -2 | cut -d "," -f 2-3
or
cat <FileName> | sed -n '2,3p' | cut -d "," -f 2-3
or
cat <FileName> | awk 'NR==2,NR==3' | cut -d "," -f 2-3

How could you read a file line by line in UNIX?

#!/usr/bin/sh

for line in $(cat <FileName>)
do
    echo "$line"
done

or

#!/bin/sh

file="<FileName>"

while read line
do
    echo $line
done < $file

Wednesday, August 22, 2012

How could you retrieve the manager's name of an employee within the EMPLOYEE table?

SELECT E.EMP_ID   AS EMPLOYEE_ID,
       E.EMP_NAME AS EMPLOYEE_NM,
       M.EMP_NAME AS MNGR_NM
FROM   EMP_MNGR E
       LEFT OUTER JOIN EMP_MNGR M
                    ON E.MNGR_ID = M.EMP_ID
ORDER  BY E.EMP_ID;


And the EMPLOYEE table goes as below :
EMP_ID    EMP_NAME    MNGR_ID
1001    Roger Scott   
2500    Mike Larsen    1001
2538    Marry Gartner  2500
2567    David Rice     2538
2570    Ben Tenesion   2567
2590    Joseph Robert  2570
3000    Adam McNally   1001

Tuesday, August 21, 2012

How can you execute the shell script currently editing within the VI editor?

You can execute the script from within the vi editor by using
:!%
where '%' refers to the file that you are currently editing.

How do you locate the source of a command/executable in UNIX?

Try - which or whereis or whence

For Example:
which perl
or
whereis perl
or
whence $0 (Korn Shell)

How could you debug specific lines in shell script intelligently?

We can implement an intelligent DEBUG-function to debug a script at specified line by putting the following function at the beginning of the script:

_DEBUG="on"
function DEBUG()
{
 [ "$_DEBUG" == "on" ] &&  $@
}

When done with debugging  or before moving your script to production, set "_DEBUG" to 'off'.
 _DEBUG="off"  # set to anything but not to 'on'

For Example:

#!/bin/bash

_DEBUG="on"
function DEBUG()
{
[ "$_DEBUG" == "on" ] && $@
}

DEBUG echo 'Hi!'

How do you convert all cvs files to text or change the extension of all files?

#!/bin/sh

for FILE in *.cvs
do
 #Strip off extension
 FNAME=`echo $FILE | awk -F . '{ print $1 }'`
 mv $FILE ${FNAME}.txt
done

How do you get last command-line parameter passed to shell script?

#!/bin/sh

echo "${!#}"

How do you rename all the files in a directory at terminal?

for FILE in *; do mv $FILE $FILE.bkp; done
or
ls *.* | xargs -i mv \{\} \{\}.bkp

Monday, August 13, 2012

How do you get/print last field of every input line in UNIX?

sed -e 's/^.* //' <File Name>
or
awk '{ print $NF }' <File Name>

How do you implement auto-login FTP process in Perl via a proxy (.netrc)?

#!/usr/bin/perl -w

use Net::FTP;
use Net::Netrc;
use Logger::Simple;

# Declare and Define values for variables
my $logfile="/home/logs/$0.log";
my $log=Logger::Simple->new(LOG=>$logfile);

# Get the login info from the .netrc file located in HOME directory
my $RemoteHost=Net::Netrc->lookup('<Server Name>');
my $User=$NT->login;
my $Pass=$NT->password;

# Craete the FTP object
my $ftp=new Net::FTP($RemoteHost, Debug => 1);

# Log into Server and list files
if(! $ftp->login($User,$Pass) )
{
  $log->write("Unable to connect to $RemoteHost!");
  die $ftp->message;
}
else
{
  $log->write("Successfully Connected to $RemoteHost");
  $ftp->ascii();
  $ftp->cwd("/HOME/nayakr/project/perl");
  @list=$ftp->ls('-lart');
  $ftp->close();
}
foreach (@list)
{
        print $_;
}

Wednesday, August 8, 2012

How could you display the last line of a file in UNIX?

tail -1 <File Name>
or
sed '$!d' <File Name>
or
awk 'END{print $0}' <File Name>

What is the difference between 'MV' and 'CP' command?

mv :
- used to rename a file or move a file from one location to other.
- doesn't change timestamp.
- works like Cut+Paste.

cp :
- used to copy a file or create a duplicate of a file
- modifies the timestamp.
- works like Copy+Paste.

How could you read/display the nth line of a file?

head -n <File Name> | tail -1
or
sed 'nq;d' <File Name>
or
awk 'NR==<Line No.> { print $0; exit }' <File Name>

How do you set variable accessible form sub shells?

This can be achieved by using "export" command. It marks the variable for automatic export to the environment of subsequently executed commands i.e. makes the local shell variable global or environmental. For example :

export PATH=$PATH:/usr/local/bin

will make PATH variable global.

To see the list of all exported variables and functions, type :

export -p

Tuesday, August 7, 2012

How do you pass output of a command as a parameter to Perl script?

"xargs" allows you to use the output of one command as the argument to another command. For instance :

<Command Name> | xargs perl myscript.pl

How do you find tables with particular column by name in Sybase?

SELECT Object_name(id)
FROM syscolumns
WHERE name = '<Coulmn Name>'


or

SELECT sysobjects.name
FROM sysobjects, syscolumns
WHERE sysobjects.id = syscolumns.id

AND syscolumns.name = '<Column Name>'

How could you beautify SQL script online?

How could you find out all the table names having a specific column name in SQL?

SELECT COLUMN_NAME, TABLE_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%<Column Name>%'

or

SELECT SO.NAME, SC.NAME
FROM SYSOBJECTS SO INNER JOIN SYSCOLUMNS SC
ON SO.ID = SC.ID
WHERE SC.NAME = '<Column Name>'

What is the difference between "IN" and "BETWEEN"?

"BETWEEN" requires a range of values whereas "IN" demands a list of values to operate on.

How could you test your code online?

You can take advantage of the following Online Compilers :

http://ideone.com/
http://codepad.org/
http://compileonline.com/

How could you delete duplicate rows?

DELETE FROM <Table Name>
WHERE rowid not in ( SELECT MIN (rowid)
FROM <Table Name>
GROUP BY column1, column2, column3, ... );

Monday, August 6, 2012

Friday, August 3, 2012

What is the difference between array and hash (associative array) in Perl?

An array is a list of ordered items where as a hash is a set of key-value pairs of unordered items.
To be precise, hash is for mapping and arrays for ordering. Numerically indexed array is more efficient than that of the hash lookup.Hash is slower than array.

If you have things in a line or ordered or in a sequence, use an array. For instance:
- A list of files to read
- A list of people in a queue

If you have a bag of unordered things to look up, use a hash. For example:
- An index of last names, looked up by first name
- An index showing the size of files, looked up by name

What is difference CTLIB and DBLIB?

 An important difference between CTlib and DBlib lies in how the SYBASE environment variable
is handled. DBlib only checks for the SYBASE variable when it requires access to the interfaces file. This allows for definition of the SYBASE variable in the script. CTlib requires the SYBASE variable to be defined BEFORE initialization. If the variable is not defined then CTlib will not initialize properly and the script won't run.

Wednesday, August 1, 2012

What is the difference between "Sybase::BCP" and "Sybase::BLK"?

"Sybase::BCP" is based on "Sybase::CTlib" whereas "Sybase::BLK" on "Sybase::DBlib" though both serves as a simplified front end for Sybase's Bulk Copy library.

What is the maximum number of Index per table in MS SQL Server?

For SQL Server 2005:
 1 Clustered Index + 249 Nonclustered Index = 250 Index
For SQL Server 2008:
 1 Clustered Index + 999 Nonclustered Index = 1000 Index

What is the generic or full syntax of SELECT statement?

SELECT select_list
[ INTO new_table ]
FROM table_source
[ WHERE search_condition ]
[ GROUP BY group_by_expression ]
[ HAVING search_condition ]
[ ORDER BY order_expression [ ASC | DESC ] ]

What is the difference between Clustered and Non-Clustered Index?

Clustered Index
 - describes the order wherein the records are physically stored
 - only one per table
 - faster to read as data is physically stored in index order
 - to enhance insert & update, clustered indexes should be set on a field that is normally incremental i.e. Id or Timestamp

Non Clustered Index
 - defines a logical order that does not match the physical order on disk
 - can be used many times per table
 - quicker for insert and update operations than a clustered index

Can we have a Virtual Constructor?

A constructor assigns value to variables at compile time and the virtual table is created on the fly.
So it is impossible to a have a virtual constructor since the time a constructor is invoked the vtable won't be available in memory;

When does a Copy Constructor get invoked?

The following cases give rise to call a copy constructor:
 1. When an object is returned by value
 2. When an object is passed (to a function) by value as an argument
 3. When an object is thrown
 4 .When an object is caught
 5 .When an object is placed in a brace-enclosed initializer list

How do you debug specific block of code in shell scripting?

You can mention the block of code within "set -x" and "set +x" command. For example :

#!/usr/bin/sh

echo "Welcome"
set -x
echo "Rabindra!"
echo "Nayak"
set +x
echo " to the world!"

What and why are the operators that can't be overloaded?

We can't overload the 'sizeof', ':?', '::', '.' and '.*' operators in C++ since they take name as their argument whereas all other operators take value as argument.

Tuesday, July 31, 2012

How do you flip bits on and off?

Use xor to flip between 1 and 0.  
x = x ^ 1;   // or x ^= 1;
This will change x alternately between 0 and 1.

How do you divide a number by 2 without division?

Just right shift the number by 1.
main()
{
    int x=6;
    printf("%d\n", y>>1); /* Divide by 2 */
    printf("%d\n", y>>2); /* Divide by 4 */
}

Output:
3
1

How do you multiply a number by 2 without multiplication?

Just shift left the number by 1.
main()
{
    int x=6;
    printf("%d\n", x<<1); /* Multiply by 2 */
    printf("%d\n", x<<2); /* Multiply by 4 */
}

Output:
12
24

Monday, July 23, 2012

What is the difference between a Reference and a Pointer?


1. References cannot be null, whereas pointers can;
2. References must be initialized as soon as they are created. On the contrary, it is not mandatory for pointers.
3. A pointer must be manually freed whereas a reference gets automatically dereferenced.
4. You can create the array of Pointer; but you can't create the Array of reference.
5. A pointer can point to many different objects during its lifetime; but a reference can only object during its lifetime.
6. You can declare a constant pointer; but you can't declare a constant reference though it is inherently constant.


What is the difference between '$#' and '$*'?

'$#' variable represents the count of command line parameters whereas '$*' holds the value of command line parameters.

Friday, July 20, 2012

How does compiler differentiate virtual and pure virtual function?

The compiler stores a NULL pointer to the pure virtual function in the V-Table and thus identifies it.

What is the difference between copy constructor and assignment?


A copy constructor is used to initialize a newly declared variable from an existing variable. This makes a deep copy like assignment, but the basic difference are as follows :
  1. There is no need to test to see if it is being initialized from itself.
  2. There is no need to clean up (eg, delete) an existing value (there is none).
  3. A reference to itself is not returned.

Monday, July 16, 2012

What are the modules included in SybPerl?

Sybperl (Sybase extensions to Perl) includes the following four modules:

1. Sybase::DBlib
2. Sybase::CTlib
3. Sybase::BCP
4. Sybase::Sybperl

Sunday, July 15, 2012

How do you check SQL error codes easily in DB2?

You can run the following query :

VALUES SQLERRM(<Error Code>)

For Example, if the error code is "-171" then the query should be :

VALUES SQLERRM(-171)

which shows SQL0171N and its equivalent error description - "THE DATA TYPE, LENGTH, OR VALUE OF ARGUMENT  IS INVALID".

How do you generate and format report in Perl?

#!C:/Perl/bin/perl
format STDOUT_TOP =
-----------------------------------------------------------------------
@||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"MERA BAZZAR - TERA BAZZAR"
-----------------------------------------------------------------------
@<<<<< @<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<< @<<<<<<<< @<<<<<<<< @>>>>>>> @>>>> @#
CODE,DATE,DESCRIPTION,PRICE,QUANTITY,AMOUNT,Page,$%
-----------------------------------------------------------------------
.
format STDOUT =
@<<<<< @>>>>>>>>> @<<<<<<<<<<<<<<<<<<< @####.## $ @######### @####.## $
$CODE,$DATE,$DESCRIPTION,$PRICE,$QUANTITY,$AMOUNT
.
format STDOUT_TOTAL =
-----------------------------------------------------------------------
            TOTAL = @###.## $
$TOTAL
.
open(INP, "item.dat") || die "Can't read file - $!\n";
while (<INP>)
{
 ($CODE,$DATE,$DESCRIPTION,$PRICE,$QUANTITY) = split(/\t/);
 $AMOUNT=$PRICE * $QUANTITY;
        write;
 $TOTAL += $AMOUNT;
}
close(INP);
$~ = "STDOUT_TOTAL";
write;
# Footer
$^L = '-' x 71 . "\n Copyright, 2012, MERA BAZZAR - TERA BAZZAR \n" . '-' x 71 . "\n";
print ("$^L");

The ITEM.DAT file should contail the following data of columns separated by a TAB :

SOA01        01-01-2012        LUX                   01.35        03
SOA02        03-01-2012        LYRIL                01.15        06
SOA03        02-02-2012        DOVE                01.20        09
SOA04        04-02-2012        HAMMAM        01.10        03
SOA05        12-02-2012        NIRMA              01.36        06
SOA06        03-03-2012        RIN                     01.50        09
SOA07        10-03-2012        SURF                  01.85        03
SOA08        04-04-2012        DETOL               01.90        06

Friday, July 13, 2012

SQL0803N: One or more values in the INSERT statement, UPDATE statement, or foreign key update caused by a DELETE statement are not valid because the primary key, unique constraint or unique index identified by "1" constrains table "STMT_REVISION".

Run the following query to trace the error:


SELECT INDNAME, INDSCHEMA
FROM SYSCAT.INDEXES
WHERE IID = <Index Id>
AND TABSCHEMA = '<Schema Name>'
AND TABNAME = '<Table Name>';


For Example:

SELECT INDNAME, INDSCHEMA
FROM SYSCAT.INDEXES
WHERE IID = 1
AND TABSCHEMA = 'FIG_ADS'
AND TABNAME = 'STMT_REVISION';