Thursday, September 5, 2013

How do you format javascript online?

http://jsbeautifier.org/

How do you transform XML into XHTML using XSLT?

1. Start with an  XML document (books.xml).
2. Create an XSL stylesheet (books.xsl).
3. Keep both files at a specific location. Otherwise update the value of "href" tag with the absolute path of "books.xsl" in "books.xml".
4. Click the "books.xml" file to open in browser by default.

books.xml
--------------------------------------
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="books.xsl"?>
<catalog>
   <book id="bk9781118013847">
      <title>Beginning Perl</title>
      <author>Curtis Ovid Poe</author>
      <genre>Computer Programming</genre>
      <publisher>Wiley / Wrox</publisher>
      <price>31.99</price>
      <publish_date>August 2012</publish_date>
      <isbn>978-1-4571-2094-7</isbn>
      <description>Perl's basics and best practices for Beginners</description>
   </book>
   <book id="bk9780596527242">
      <title>Mastering Perl</title>
      <author>Brian d Foy</author>
      <genre>Computer Programming</genre>
      <publisher>O'Reilly Media</publisher>
      <price>31.99</price>
      <publish_date>July 2007</publish_date>
      <isbn>978-0-596-52724-2</isbn>
      <description>Focuses on real-life problems of debugging, maintenance, configuration</description>
   </book>
   <book id="bk9780470556801">
      <title>Perl and Apache</title>
      <author>Adam McDaniel</author>
      <genre>Computer Programming</genre>
      <publisher>Wiley / Visual</publisher>
      <price>34.99</price>
      <publish_date>January 2011</publish_date>
      <isbn>978-1-4571-3092-2</isbn>
      <description>A visual blueprint for developing dynamic Web content</description>
   </book>
</catalog>

books.xsl
--------------------------------------
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html>
  <body>
  <h2>Book Details</h2>
  <table border="1" style="width:70%;">
    <tr bgcolor="#9acd32">
      <th>Id</th>
      <th>Title</th>
      <th>Author</th>     
      <th>Price ($)</th>
      <th>Publish Date</th>
      <th>Genre</th>
      <th>Description</th>
    </tr>
    <xsl:for-each select="catalog/book">
    <xsl:sort select="@id"/>
    <tr>
      <td><xsl:value-of select="@id"/></td>
      <td align="center"><xsl:value-of select="title"/></td>
      <td><xsl:value-of select="author"/></td>     
      <td align="right"><b><xsl:value-of select="price"/></b></td>
      <td><xsl:value-of select="publish_date"/></td>
      <td><xsl:value-of select="genre"/></td>
      <td align="justify"><xsl:value-of select="description"/></td>
    </tr>
    </xsl:for-each>
  </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

Monday, September 2, 2013

What is the use of %EXPORT_TAGS in Perl?

It is an associate array that specifies a way to access a list of symbols with tags.

Syntax:
%EXPORT_TAGS = (tag_name => [anonymous array/Array reference]);

For Example:
%EXPORT_TAGS = (
all => @EXPORT_OK
);

At the time of loading, use simply

use Module qw(:all); # instead of writing all the symbols

MyPerl.pm
---------------------------
package MyPerl;
require Exporter;

our @ISA = qw(Exporter);
our @EXPORT = qw(&Active);
our @EXPORT_OK = qw(&StrawBerry &IndigoStar);

our %EXPORT_TAGS = (
'Explicit' => \@EXPORT,
'Implicit' => \@EXPORT_OK,
'All' => [@EXPORT, @EXPORT_OK],
);

sub Active {
    print "Active Perl\n";
}

sub StrawBerry {
    print "StrawBerry Perl\n";
}

sub IndigoStar {
    print "IndigoStar Perl\n";
}

1;

test.pl
---------------------
#!/usr/local/bin/perl

use MyPerl qw(:Explicit :Implicit);
#or
#use MyPerl qw(:All);

Active();
IndigoStar();

Where do you get Perl binaries for MS Windows?

http://www.indigostar.com/
http://strawberryperl.com/
http://www.activestate.com/activeperl/downloads

What are the side-effects of Taint mode in Perl?

When the taint mode ("-T") is in effect, the "." directory is removed from @INC, and the environment variables "PERL5LIB" and "PERLLIB" are ignored by Perl since they are obscured.

You can still adjust @INC from outside the program by using the "-I" command line option. The "-I" switch is clearly visible and therefore permitted.

Another way to modify @INC without modifying the program, is to use the "lib" pragma at command line.

perl -Mlib=/my/module_dir script.pl

Note that if a tainted string is added to @INC, the following problem will be reported:

"Insecure dependency in require while running with -T switch"

How can you restore original @INC in Perl?

When the lib module is first loaded, the current value of @INC is recorded in "@lib::ORIG_INC". To restore @INC to original value, you can use :

@INC = @lib::ORIG_INC;

How can you remove the directories from @INC in Perl?

It can be achieved via "no lib".
e.g.

no lib ".";  # removes cwd
no lib LIST; #removes directories defined in LIST

What is the difference between "-Mlib" and "-I" option in Perl?

Theses are the ways to modify @INC without modifying the program.

The benefit of using "-Mlib=/my/module_dir" over "-I /my/module_dir" is the former automatically removes any duplicate directories while the later does not.

Wednesday, August 28, 2013

What is mod_perl?

mod_perl is the fusion of Apache and Perl which enhances a new approach to create dynamic content by utilizing the feature of Apache web server through a persistent interpreter embedded into web server. It lets you avoid the overhead of starting an external interpreter and the penalty of Perl start-up time as well.

Tuesday, August 27, 2013

How do you select random rows in Oracle?

SELECT *
FROM
( SELECT *
 FROM <TableName>
ORDER BY dbms_random.value )
WHERE rownum <= 10;

How do you select random rows in DB2?

SELECT *
FROM <TableName>
ORDER BY rand()
FETCH FIRST 10 ROWS ONLY;

How do you select random rows in Sybase?

SELECT TOP 10 *
FROM <TableName>
ORDER BY NEWID();

How do you select random 10 rows in MySQL?

SELECT *
FROM <TableName>
ORDER BY RAND()
LIMIT 10;

How do you select random rows in MsSQL Server?

SELECT TOP 10 *
FROM <TableName>
ORDER BY NEWID();

How do you select 10 random rows in PostgreSQL?

SELECT *
FROM <TableName>
ORDER BY RANDOM()
LIMIT 10

How do you select top N records in PostgreSQL?

SELECT *
FROM <TableName>
LIMIT N;

Monday, August 19, 2013

How could you select only a row in Perl-DBI?

use strict;
use warnings;

use DBI;

my $dbh=DBI->connect("dbi:Pg:database=DATABASE_NAME;host=HOSTNAME;port=5678", 'USERNAME', 'PASSWORD')
or die "Can't connect: ", $DBI::errstr;
$dbh->{RaiseError} = 1;

my $sql = q( select *
from <TABLENAME>
where <CONDITION>);

my @row = $dbh->selectrow_array($sql);

print join (",", @row) . "\n";

$dbh->disconnect();

Wednesday, August 14, 2013

What is the best way to traverse through hashes in 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',
);

while (my ($Frequency, $Station) = each %FM) {
    print "$Frequency =  $Station\n";   
}

Thursday, August 8, 2013

What are the nitty-gritties for extensions of perl programs?

  1. Technically, the ".pl" extension must be used for Perl libraries, not for executable Perl programs.
  2. For executable, you should either specify ".plx" or no file extension at all if  OS allows it.
  3. Perl modules must use the ".pm" file extension.
It is good coding paradigm to use only alphanumeric characters and underscores in Perl script file-names, and to start those file-names with a letter (or underscore), similar to how you would start variable names.

What are the aliases for Regular Expressions?

Regular Expressions are also referred as "regexen" or "regexes" in the plural ("regex" singular). An alternate version of "regex" is "regexp".

What are the differences between "GET" and "POST"?

POST & GET are HTTP request methods to establish communications between clients and servers.

GET:
  • GET method exposes parameters being used in the address bar. This can be useful to bookmark the page.
  • The request gets cached by the browser which can be a potential threat while dealing with sensitive information like passwords.
  • GET method is not suitable for very large variable values (max URL length is 2048 chars).
  • It supports ASCII only.
  • GET requests should only be used to retrieve data.

POST:
  • POST method encapsulates information passed to the server.
  • The variables can be of almost any length (no limits on the amount of information to send).
  • It is impossible to bookmark the page.
  • It supports ASCII & Binary data as well.
  • POST requests should be used only to send data.

How can we map country, state & cities in a hash?

my %geo = (
INDIA => {
OR => [ qw ( Bhubaneswar Cuttack Rourkela Brahmapur Sambalpur Balasore Puri Bhadrak Baripada ) ],
AP => [ qw ( Adilabad Adoni Amravati Anantapur Cuddapah Eluru Guntur Hyderabad Karimnagar Khammam Kothagudem Kurnool Lepakshi NagarjunaSagar Nagarjunakonda Nalgonda Nellore Nizamabad Puttaparthi Srikakulam Tirupati Vijayawada Visakhapatnam Warangal ) ],
MH => [ qw (Mumbai Pune Aurangabad Nashik Kolhapur Nagpur Amaravati Ahmadnagar Thane Chandrapur Solapur) ],
GJ => [ qw ( Ahmedabad Ankleshwar Atul Anand Ambaji Bharuch Baroda Bilimora Bhavnagar Dwarka gandhinagar Jamnagar Junagadh Kutch Mehsana Morbi Patan Nadiad Navsari Porbandar Palanpur Rajkot Surat Valsad Vasad Vapi) ],
},
);

foreach my $country (keys %geo)
{
  print " Country : " . "$country \n";
  foreach my $state (keys %{$geo{$country}})
  {
    print " State : " . "$state\n City : ";
    foreach $city ( @{$geo{$country}->{$state}} )
    {
      print $city . "\t" ;
    }
    print "\n";
  }
}

What is the difference between "implode" and "explode" in PHP?

"explode" splits a string into fragments specified by delimiter whereas "implode" conglomerates words separated by delimiter to form a string.

<html>
<head>
<title>Difference between explode and implode.</title>
</head>
<body>
<?php
$mNumber = "+91-988-620-2991";
$fragments = explode("-", $mNumber);
echo "Country Code : $fragments[0]";

echo '<br>';

$string = array("My", "name", "is", "Rabindra.");
$fullString = implode(" ", $string);
echo $fullString;
?>
</body>
</html>

Tuesday, August 6, 2013

Where does PHP store global variables?

PHP stores all global variables in an array called $GLOBALS[index].

<?php
$x=5;
$y=10;

$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y']; //Same as "$y = $x + $y;"

echo $y;
?>

Tuesday, July 30, 2013

How do you access elements of hash containing an array and a hash?

my %employee = ( 
CSV_NAME => 'EMPLOYEE',
columns => [    
[EMP_ID => 'ID'],  
[EMP_NAME => 'ENAME'],   
],);

print $employee{CSV_NAME};
print "\n";
print map $_->[0], @{$employee{columns}};
print "\n";
print map $_->[1], @{$employee{columns}};

Friday, July 26, 2013

How do you send emails with attachment in UNIX?

uuencode <FileName> <FileName> | mailx -s "Subject" <eMailId> [-c CC_Address] [-b BCC_Address]

mutt -s "<Subject>" -a <Attachment_FileName> <eMailId> [-c CC_Address] < [/dev/null | MailBodyFileName]

How do you keep watching on a directory in UNIX?

watch -n 60 -d ls -lrt

Monday, July 22, 2013

How could you make variables exportable in ".pm" file?

use Exporter qw (import);

our @EXPORT_OK = ();

sub  _exportable(@)
{
     push @EXPORT_OK, @_;
}

our $dir_bin="/home/usr/bin";
_exportable '$dir_bin';

Thursday, July 18, 2013

Where can you format your xml and test the XPath online?

How do you permanently set colors for VI/VIM editor?

1. Go to your HOME directory using the following command
cd ~
or
cd $HOME
2. Create a file ".vimrc" (if not present in HOME directory) by typing
vi .vimrc
3. Thereafter make the following entries in insert mode
set nu
syntax on
highlight normal cterfg=white ctermbg=black
4. Save and exit

To temporarily override the attributes within vi, you may use
:set bg = [dark | light]
:set background = [dark | light]
:synatx [on | off]
:colorscheme [nature | desert | torte | pablo | evening]

Wednesday, July 17, 2013

How do you obtain last word of string in perl?

my $string = "www.regen.com/issn/vol/isssue/art";
$string =~ m/([^\/]+)$/;
print $1;

How do you access last element in split() in perl?

my $uri = "readytips.blogspot.in";
my $domain = ( split /\./, $uri )[-1];
print $domain;

How do you replace strings in URLs in perl?

use URI::Split qw(uri_split uri_join);

$lhost='readytips.blogspot.in';

my $uri='http://www.blogspot.in/2013/07/how-do-you-extract-string-between-two.html';
my ($protocol, $host, $path, $query, $fragment) = uri_split($uri);
my $uri = uri_join($protocol, $lhost, $path, $query, $fragment);

print $uri;

How do you extract string between two key words in perl?

my $title = "<locator>readytips.blogspot.in</locator>";
$title =~m/<locator>([\s\S]+?)<\/locator>/;
print $1;
$title =~m/<locator>(.*?)<\/locator>/;
print $1;
$title =~m/<locator>(.*+)<\/locator>/;
print $1;
$title =~ /<locator>\s+(.*)\s+<\/locator>/;
print $1;

Friday, July 12, 2013

How do you find the key of a value in hash in 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',
             );

my ($key) = grep{ $FM{$_} eq '92.7' } keys %FM;
print $key;

Wednesday, July 3, 2013

How could you populate keys and values of a config file into hash of hashes?

$ini="config.ini";
my %conf = ();

open (INI, "$ini") || die "Can't open $ini: $!\n";
while (<INI>)
{
  chomp;
  if (/^\s*\[(\w+)\].*/)
  {
        $header = $1;
  }
  elsif (/^\W*(\w+)=?(\w+)\W*(#.*)?$/)
  {
    #put them into hash
    $conf{$header}{$1} = $2; 
  }
}
close (INI);

print $conf{'QA'}->{'ip'} . "\n";
---------------------------------------------------------
config.ini:

[DEV]
url=http://readytips.blogspot.in/dev/
ip=127.0.0.0
[QA]
url=http://readytips.blogspot.in/qa/
ip=127.0.0.1
[PROD]
url=http://readytips.blogspot.in/live/
ip=127.0.0.2

Tuesday, July 2, 2013

How do you access individual keys and values of a hash of array

%attributes = (
    'OS_List' =>  [ 'Linux', 'Windows', 'MAC' ],
    'Script_List' => [ 'Perl', 'Python', 'Ruby' ],
);

print join (",", @{$attributes{'OS_List'}}) . "\n";

print @{$attributes{'OS_List'}}[1] . "\n"; #Output : Windows

Saturday, June 29, 2013

How could you parse config file with "key=value" format with a header in Perl?

my %params = ();
my $INIFILE='config.ini';

open (INI, $INIFILE) || die "could not open $INIFILE - $!";

while (<INI>)
{
chomp($_);
if($_=~/^#/ || $_=~/^;/ || $_=~/^\/\//)
{
#ignore these lines coz they are comments!
}
elsif($_=~/^$/)
{
#ignore these lines coz they are blank!
#die "Blank line detected at $.\n";
}
elsif ($_ =~ /^\[(.+)\]/) #extract string enclosed in '[]'
{
$header = $1;
}
else
{
my ( $key, $value ) = split( /=/, $_ );
$params{$header}{$key} = $value;
}
}

foreach $header(keys %params)
{
  print "$header: ";
  foreach $subheader (sort keys %{$params{$header}})
  {
    print "$subheader = $params{$header}{$subheader} ";
  }
  print "\n";
}

#To access individual key, value
print $params{'DEV'}{'url'};
-----------------------------------------------------------------
config.ini:

[DEV]
server=rocket
port=8080
url=http://dev.single-ticket.com/

[QA]
server=princeton
port=8081
url=http://beta.single-ticket.com/

[PROD]
server=saboo
port=8082
url=http://www.single-ticket.com/

How could you parse config file with "key=value" format in Perl?

my %params = ();
my $INI_FILE='config.ini';

open (INI, $INI_FILE) || die "could not open $INI_FILE - $!";

while (<INI>)
{
     chomp($_);
     if($_=~/^#/ || $_=~/^;/ || $_=~/^\/\//)
     {
          #ignore these lines coz they are comments!
     }
     elsif($_=~/^$/)
     {
          #ignore these lines coz they are blank!
     }
     else
     {
          my ( $key, $value ) = split( /=/, $_ );
          $params{ $key } = $value;
     }
}

foreach (sort keys %params)
{
     print "$_ = $params{$_}\n";
}

#Get value for individual key
print $params{url};
----------------------------------------------
config.ini:

dev_server=singleton
dev_port=8081
dev_url=http://dev.single-ticket.com/

server=mingleton
port=8080
url=http://www.single-ticket.com/

Friday, June 28, 2013

How could you remove wide characters in Perl?

$content =~ s/[^\x00-\x7f]//g;

How could you transpose a matrix in Perl?

my @arr = (['a','b','c'],
                    ['h','i','j'],
                    ['x','y','z']);

for (  $i=0; $i<=$#arr; $i++ )
{
        print join(",", (map $_->[$i], @arr));
        print "\n";
}

Tuesday, May 14, 2013

How do you find all the tables with specific column names in MySQL?

SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ( 'ColumnA', 'ColumnB' )
AND TABLE_SCHEMA = 'DatabaseName';

Wednesday, April 24, 2013

How could you maintain passwordless connection for SSH, SCP, SFTP, RSYNC commands?


Step 01:
On the client/local machine run the following commands:

mkdir -p $HOME/.ssh (if .shh does not exist.)
chmod 0700 $HOME/.ssh
ssh-keygen -t dsa -f $HOME/.ssh/id_dsa -P ''

This should result in two files, $HOME/.ssh/id_dsa (private key) and $HOME/.ssh/id_dsa.pub (public
        key).

Step 02:
Copy $HOME/.ssh/id_dsa.pub to the server.

Step 03:
On the server run the following commands:

cat id_dsa.pub >> $HOME/.ssh/authorized_keys2
chmod 0600 $HOME/.ssh/authorized_keys2

Or maybe depending on the version of OpenSSH the following commands may also be required:

cat id_dsa.pub >> $HOME/.ssh/authorized_keys
chmod 0600 $HOME/.ssh/authorized_keys

Step 04 (Optional):
An alternative is to create a link from authorized_keys2 to authorized_keys:
cd $HOME/.ssh && ln -s authorized_keys2 authorized_keys

Step 05:
On the client test the results by ssh'ing to the server:

ssh -i $HOME/.ssh/id_dsa server
Add the following $HOME/.ssh/config on the client(Optional).

Host server IdentityFile ~/.ssh/id_dsa
This allows ssh access to the server without having to specify the path to the id_dsa file as an argument to ssh each time.

How could you synchronize files between local to remote machine?


"rsync" allows you to synchronize files/directories between the local and remote system.

rsync -avz /<local_path_to_file> <remote_user>@<remote_host>:/<remote_path_to_file>

Monday, April 22, 2013

Thursday, April 18, 2013

How do you ensure the listener for a service on Oracle Network is up?

Use "tnsping" utility available in the "HOME/bin" directory of ORACLE to test if a remote listener is up (checks if the socket is reachable). This utility only ensures the availability of a listener; but not about the databases behind the listener.

Thursday, April 11, 2013

How could you convert an .XLSX format to .CSV format in Perl?

use Spreadsheet::XLSX;

my $excel = Spreadsheet::XLSX->new("Emp.xlsx");
my $sheet = ${$excel->{Worksheet}}[0];

my ($row_min, $row_max) =  $sheet->row_range();
my ($col_min, $col_max) = $sheet->col_range();

open (FH,">", "Emp.csv") or die "$!";
for my $row ($row_min..$row_max)
{
  print FH join (",", map {$sheet->get_cell($row,$_)->value()} ($col_min..$col_max));
  print FH "\n";
}
close (FH);

Thursday, April 4, 2013

How could you login into MySQL database?

mysql -h <DBHOSTNAME-u <DBUSER> -p <PASSWORD>

How could you select the first N rows in MySQL?

# Retrieve first 5 rows, equivalent to: limit 0,5
SELECT * FROM <TableName> Limit 5;

# Retrieve rows 6-10
SELECT * FROM <TableName> Limit 5,10;

What's the difference between "import" and "from...import *" in Python?

"import <ModuleName>" loads a Python module into its own namespace and restricts direct access to the members of the module. The references can be accessed by prefixing the module name followed by a dot.

import sys
sys.exit()

On the contrary, "from <ModuleName> import *" loads a module into the current namespace and allows to access those references without a prefix.

from sys import *
exit()

What is the difference between 'load' and 'require' in Ruby?

'require' looks for the library in all the defined search paths and also appends '.rb' or '.so' to the file name. It ensures that the library is included only once.

'load' needs the full name of the library and it gets loaded each time you call.

Friday, March 29, 2013

How could you split a field or a column in AWK?

echo "DD-MM-YYYY" | awk '{split($0, TM, "-"); print "Date = "TM[1] "\tMonth = "TM[2] "\tYear = "TM[3]}'

What is the difference between NR and FNR in AWK?

NR - The ordinal number of the current record from the start of input.
FNR - The ordinal number of the current record in the current file.

So NR counts the lines from the very beginning continuously until the end. FNR restarts the counting at the beginning of each input file.

Saturday, March 16, 2013

How could you dereference an anonymous subroutine?

$ref_to_welcome = sub
{
     print "Welcome, @_!";
};

&$ref_to_welcome("Rabindra");
$ref_to_welcome->("Rabindra");

Thursday, March 14, 2013

What is the difference between UNION and UNION ALL?

UNION eliminates duplicate records whereas UNION ALL retains duplicates.

How could you import or export bulk data in SQL Server?

Import/Load data:
bcp itinerary.dbo.tariff in "C:\mobile\itinerary.txt" -N -S <ServerName/IP> -U <userid> -P <password> -T

Export/Extract Data:
bcp itinerary.dbo.tariff out "C:\fruit\inventory.txt" -c -S <ServerName/IP> -U <userid> -P <password> -T -h "TABLOCKX"

What is the maximum number of columns in a row in SQL Server?

1024 columns.

How many columns per SELECT statement are possible in SQL Server?

4096

What are the types of temp tables in Ms SQL Server?

1. Local Temp Table
Table prefixed with a single hash (#) denotes a local temporary table available to the current connection for the user. It disappears when the user disconnects.

CREATE TABLE #tempLocal ( Uid int, Fname varchar(50), Lname varchar(50) )

2. Global Temp Table
Table prefixed with double hash (##) denotes a global temporary table available to all users via all connections. They are deleted only when all connections are closed.

CREATE TABLE ##tempGlobal ( Uid int, Fname varchar(50), Lname varchar(50) )

What is the maximum no. of SPROC nesting in Ms SQL Server?

The maximum level of SPROC nesting is 32.

Which TCP/IP port does Ms SQL Server run on?

Ms SQL Server runs on port 1433.

How could you select top N records in Ms SQL Server?

SELECT TOP N * FROM <TableName>

Or

SELECT TOP N PERCENT <Column_01>, <Column_02>
FROM <TableName>
WHERE <Condition>

Or

( For SQL Server 7.0 or earlier )
SET ROWCOUNT N
SELECT <Column_01>, <Column_02>, <Column_03>
FROM <TableName>
ORDER BY <Column_Name> DESC

What is the difference between ROWNUM and ROWID in Oracle?

ROWID is the unique physical address of every row of a table maintained by database automatically. ROWNUM is the sequential number allocated to each row in the result set object during query execution.

ROWID is permanent whereas ROWNUM is temporary. ROWID is 16-bit hexadecimal whereas ROWNUM is numeric.

How could you embed external image for background in Perl-CGI?

print $cgi->start_html ( -background=>"http://localhost/images/bg.jpg" );

How could you embed external CSS file in Perl-CGI?

print $cgi->start_html ( -style => {'src' => 'http://localhost/styles/bg.css'} );

Full form of some Banks.


ICICI   => Industrial Credit and Investment Corporation of India
HSBC  => Hongkong and Shanghai Banking Corporation
HDFC  => Housing Development Finance Corporation
IDBI     => Industrial Development Bank of India
DENA  => Development Enterprenure National Association
BNP     => Banque Nationale de Paris
UTI      => Unit Trust of India
UCO    => United Commercial Bank
YES     => Youth Enterprise Scheme
EXIM  => Export Import Bank Of India
SIDBI  => Small Industries Development Bank of India
NABARD => National Bank for Agriculture and Rural Development

Tuesday, March 12, 2013

How could you set default value for a variable in UNIX?

Set default values for variables using ":-".

VARIABLE=${1:-DEFAULT_VALUE}

sets VARIABLE with the value of 1st Arg to DEFAULT_VALUE, if 1st arg is not entered.

How could you perform bulk upload & download in DB2?

Utilities available for bulk upload & downoad are:
  1. Export
  2. Import
  3. Load

How could you determine size of file in UNIX?

stat -c %s <FileName>  # Size in bytes

How could you estimate the elapsed time for execution of a script in Perl?

#!/usr/bin/perl
use Time::HiRes;

my $start = Time::HiRes::gettimeofday();
## -- Your Code -- ##
my $end = Time::HiRes::gettimeofday();

printf("$0 took %.4f seconds!\n", $end - $start);

Monday, March 11, 2013

How could you force all users off the specified instance or database in DB2?

Use 'QUIESCE' command which doesn't allow all users ( except SYSADM, SYSMAINT, DBADM, or SYSCTRL ) to connect to the database until the 'UNQUIESCE' command is given.

For example:

-- Forces off all users with connections to an instance
quiesce instance <Instance_Name> immediate force connections

-- Forces off all users with connections to the database
quiesce database <Database_Name> immediate force connections

How could you connect Oracle and Python?


#!/usr/bin/python

import os
import cx_Oracle

SQL_STMT="SELECT * FROM TABLE_NAME"

# set Oracle Environment variables in case it has not been
os.putenv('ORACLE_HOME', '/oracle/product/10.2.0/db_1')
os.putenv('LD_LIBRARY_PATH', '/oracle/product/10.2.0/db_1/lib')

connection = cx_Oracle.connect('userid/password@127.0.0.1:1521/SID')

cursor = connection.cursor()
cursor.execute(SQL_STMT)
for row in cursor:
    print row

cursor.close()
connection.close()

How could you swap values of variables in Python?


#!/usr/bin/python
   
a = 5
b = 6

print "Before Swapping : a =", a , "b =", b
a, b = b, a
print "After Swapping : a =", a , "b =", b

Friday, March 8, 2013

How could you check the existence of a function (say new) within a package (say CGI) in Perl?

use CGI;

$cgi=CGI->new;

if (exists &CGI::new)
{
    print "Exists\n";
}

Or

if ( defined( &CGI::new ) )
{
print "Defined\n";
}

Or

if ( CGI->can('new') )
{
print "Exists\n";
}

Or

if ( $cgi->can('new') )
{
print "Defined\n";
}

How could you list out all the variables defined in a package in Perl?

use CGI;

no strict 'refs';

foreach ( keys %CGI:: )
{
print "$_\n";
}

How could you list all the methods defined in the package (say CGI) in Perl?

use CGI;

no strict 'refs';
print join ', ', grep { defined &{ "CGI::$_" } } keys %{ CGI:: };

When is “use lib” implemented in Perl?

use lib’ is used in two cases:
  • When you have a fixed, but not standard company-wide environment in which you put modules in a common standard location.
  • When you are developing an application and you'd like to make sure the script always picks up the modules relative to their own location.

Thursday, March 7, 2013

Wednesday, March 6, 2013

Tuesday, March 5, 2013

How could you execute command stored in a string or variable in Shell Scripting?

#!/bin/bash

CMD="ls -lrt"
eval $CMD

How could you run commands/scripts when you log out session in UNIX?

Run commands/scripts when you log out by appending required lines to the ".logout" file in your HOME directory.

sh shell : ~/.sh_logout
bash shell : ~/.bash_logout
ksh shell : ~/.ksh_logout
tcsh / csh : ~/.logout

Next add the below line to your ".profile" file :
trap '. $HOME/.sh_logout; exit' 0

Saturday, March 2, 2013

How could you generate a sequence of numbers in Shell Scripting?

#!/bin/bash

for (( count=1; count <= 3 ; count++ ))
do
 echo "Value of count = $count."
done

# Or

#!/bin/bash

for count in $(seq 4 7)
do
 echo "Value of count = $count."
done

# Or

#!/bin/bash

for count in {7..10}; do
 echo "Value of count = $count."
done

Wednesday, February 27, 2013

Explain the meaning of "Segmentation Violation".

At the time of compiling the program, a segmentation violation usually indicates an attempt to access memory which doesn't even exist.

What is the advantage of 'do-while' loop as compared to 'while' loop?

A while loop checks the condition first before executing the content whereas do-while loop executes the content of the loop before checking the condition and makes obligatory to enter the loop at least once.

What is the size of register for storage class?

register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the size of a processor's general-purpose registers (GPRs) and the default size is usually one word or 2 byte or 16 bits.

What are Bit-fields?

The variables defined with a fixed width are called bit fields. A well-known usage of bit-fields is to represent a set of bits, and/or series of bits. They are space-saving structure members. They allow integer members to be stored into memory spaces smaller than the compiler would ordinarily allow. The default integer type for a bit field is unsigned.

The declaration of a bit-field inside a structure has the form:

struct
{
  type [member_name] : width ;
};

What is a self-referential structure?

A structure containing a reference to itself as a member is known as Self-Referential Structure.

struct linked_list_node
{
int data;
struct linked_list_node *next;  // self reference
};

What do you mean by associativity and precedence?

Precedence denotes the order or priority of evaluation whereas associativity implies the direction of evaluation.

What are dangling, wild, void, and null pointers?


A pointer pointing to a memory location which is deleted or freed is known as Dangling Pointer.

A pointer which has not necessarily initialized prior to its usage is a Wild Pointer.

A pointer pointing to nothing or that does not refer to a valid memory location is a NULL Pointer.

The pointer not having any type associated with it and can hold the address of any type is known as Void Pointer (aka Generic Pointer).

Are functions declared or defined in header files?

Traditionally the standard functions are declared in header files and defined in the library routines only.

What is the difference between '#include' and '#include "File"'?


It is compiler dependent. Generallly '#include "File"' prioritizes headers to be checked in the current working directory over system headers. And if there is not a suitable match, it moves on to check the system paths. "#include <File>" always looks out for system headers.

How could you find the size of a variable with out using sizeof operator?


#include <stdio.h>

#define SIZEOF(var)  ((size_t)(&(var)+1) - (size_t)(&(var)))

main( )
{
int x;
printf ("The size of x is %d\n", SIZEOF(x) );
}

Monday, February 25, 2013

How could you multiply 2 Integers using bit-wise operators?


#include<stdio.h>

main()
{
int a, b, num1, num2, result=0;  
printf("\nEnter the numbers to be multiplied :");
scanf("%d%d",&num1,&num2);
a=num1;
b=num2;
while(num2 != 0)            
{
if (num2 & 01)              
               {
        result+=num1;  
               }
num1<<=1;                
                num2>>=1;                
}
printf("\nMultiplication of %d*%d=%d", a, b, result);
}

What is the difference between '#define' and 'typedef'?


(a) typedef keep the property of attributes whereas #define doesn’t. For example

typedef char *type_t;
#define char *type_d

type_t s1,s2;
type_d s3,s4;

In the above declarations, s1,s2 and s3 are all declared as char* but s4 is declared as a char, which is probably not the intention.

(b) #define keeps string attributes whereas typedef doesn’t.

#define int INT;
typedef int MYINT

unsigned MYINT a;
unsigned INT a; /* Illegal */

For the typedef scenario, it doesn't change to unsigned 'int a' but in #define case it works!!!.

Wednesday, January 23, 2013

How could you comment out block of code in Ruby?

Multiple lines of text or code can be marked as comments using the Ruby "=begin" and "=end"  markers. These are known as the comment block markers.

=begin
This is a comment line.
It shows that the next line of code is
marked as a comment.
=end

How could you comment out block of code in Python?

Use triple-quoted strings.

#!/usr/bin/python
   
'''
print "This is a \
multiline \
comment.";
'''

Monday, January 21, 2013

What are the various ways you can run UNIX commands in Ruby?

Backticks (``) - Backticks (aka backquotes) runs the command in a sub-shell and returns the standard output from that command.

#!/usr/local/bin/ruby -w
today = `date`
puts today

System (Kernel.system) - This command runs in a subshell and returns true if the command ran successfully and false otherwise.

system "ls -1"

Exec (Kernel.exec) - It runs the given command by replacing the current process with the one created by the external command.

exec "ls -1"

spawn (available in Ruby v1.9. aka Kernel.spawn also available as Process.spawn) - It doesn‘t wait for end of the command but returns the pid of the sub-process. Therefore, you'll have to use Process.wait or Process.detach on the resulting pid.

pid = kernel.spawn ("ls -lA", {:chdir => "/home/ravi"})
Process.wait pid

%x operator - The operator makes it easy and readable to use quotes in a command.

#!/usr/bin/env ruby
list=%x[ls -1]
puts list

IO.popen - It is another way to run a command in a sub-process. It helps you control the connection to IO object between standard input and standard output in that the sub-process.

Open3.popen3 - The Ruby standard library includes the class Open3. It is easy to use and returns stdin, stdout and stderr.

Open4.popen4 - It is a Ruby Gem put together by Ara Howard. It operates similarly to open3 except that we can get the exit status from the program. It also returns a process id for the subshell and we can get the exit status from that waiting on that process.

How could you run UNIX commands in Python?

#!/usr/bin/python
import os
os.system("ls -l")

or

import os
buffer=os.popen("ls -l")
for i in buffer.readlines():
     print "Result:",i,

or

from subprocess import call
call(["ls", "-l"])

What are the modules available in Perl to run external commands or 3rd party programs?

On UNIX:
  •     IPC::Open2
  •     IPC::Open3
  •     IPC::Run
On Windows:
  •     Win32::Process::Create

Friday, January 18, 2013

How could you add or remove elements in a Hash in 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);

# Add one more element to the hash
$FM{'FM Berhampur'} = 100.6;

# Remove one element from the hash
delete ( $FM{'FM Gold'} );

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

How could you find out size of a Hash in 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);

print "size of Hash: ",scalar keys %FM,"\n";
# or
print "size of Hash:  " . keys ( %FM ) . ".\n";

How could you check the existance of a key in a Hash in 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);

if (exists ( $FM { "Fever" } ) )
{
    print "Frequency of FM Fever is $FM{Fever}MHz.\n";
}

Thursday, January 10, 2013

What does bless() do?

The process of turning a reference into an object is called 'blessing' and the bless() function
just turns the reference into an object of the required class.

Thursday, January 3, 2013

What is the difference between pipe and xargs?

xargs converts the input into command line arguments and is useful when the parameter list is too long for the shell. It splits the parameter list and iterates over the smaller list.

The pipe takes the standard output of the first command and copies it to the standard input. Roughly, pipe is an option to concatenate two/more commands.