How to set a selected option using ajax in Laravel 5.6?

Hey friends, I am trying to show database column data in my edit form of a Laravel project. yesterday I failed to show data from database in a select list using ajax. so let’s see the below blade file and ajax also to get your solution.

edit.blade.php
<div class="form-group">
  <label for="Blood_Group">Blood Group</label>
	<select class="form-control" id="bgroup" name="bgroup">
	  <option value="" disabled selected>Select BG</option>
	  <option value="O+">O+</option>
	  <option value="O-">O-</option>
	  <option value="A+">A+</option>
	  <option value="A-">A-</option>
	  <option value="B+">B+</option>
	  <option value="B-">B-</option>
	  <option value="AB+">AB+</option>
	  <option value="AB+">AB-</option>
	</select>
</div>
profile.js
$.ajax({
	type: "GET",
	url: 'addprofile',
	data: null,
	success: function(response) {
          let data = response.data;
          $("#bgroup").append('<option value=' + data[0].bgroup+ '>' + data[0].bgroup+ 
           '</option>');

        }
});

Error : updated data from database is not showing in selected list when i am trying to update it again.

Solution :
$("#bgroup").val(data[0].bgroup).attr('selected','selected');

You can also use below code:

$('#bgroup option[value="' + data[0].bgroup+ '"]').prop('selected', true);

Above solution is working for me. so if you have more solution on select option then please feel free to comment and share your knowledge.

Resources :

  1. Click here
  2. Click here

Tagged : / / / /

Interview Questions and Answer for Perforce Version Control Tool

perforce-interview-questions-answers

Some of the perforce commands which is not commonly used but useful.
p4 annotate – Print file lines along with their revisions.
e.g p4 annotate file.c

How to ignore files/folder in perforce workspace/client?
Assuming you have a client named “CLIENT”, a directory named “foo” (located at your project root), and you wish to ignore all .dll files in that directory tree, you can add the following lines to your workspace view to accomplish this:

-//depot/foo/*.dll //CLIENT/foo/*.dll
-//depot/foo/…/*.dll //CLIENT/foo/…/*.dll

The first line removes them from the directory “foo” and the second line removes them from all sub directories. Now, when you ‘Reconcile Offline Work…’, all the .dll files will be moved into “Excluded Files” folders at the bottom of the folder diff display. They will be out of your way, but can still view and manipulate them if you really need to.

You can also do it another way, which will reduce your “Excluded Files” folder to just one, but you won’t be able to manipulate any of the files it contains because the path will be corrupt (but if you just want them out of your way, it doesn’t matter).

-//depot/foo.../*.dll //CLIENT/foo.../*.dll

Reference
How can I exclude a directory from a Perforce command?

P4IGNORE
Specify a file that contains a list of files to ignore when adding files to the depot and reconciling workspaces.
Reference

How to check last 10 submitted, pending, or shelved changelists that include any file under the project directory?
p4 changes -m 5 //depot/project/…

How to check last 10 submitted or pending, or shelved changelists that include any file under the project directory?
p4 changes -m 1 -s submitted | pending | shelved

Interview Questions Related to Perforce Admin

  1. How to take perforce backup
  2. How to restore perforce backup
  3. How to verify health of the perforce repos database
  4. What is the ise of p4 dbverify and p4 verify

What is the use of p4 admin commands.

The p4 admin command allows Perforce superusers to perform administrative tasks even when working from a different machine than the one running the shared Perforce service.
p4 [g-opts] admin checkpoint [ -z | -Z ] [ prefix ]
p4 [g-opts] admin journal [ -z ] [ prefix ]
p4 [g-opts] admin stop
p4 [g-opts] admin restart
p4 [g-opts] admin updatespecdepot [ -a | -s type ]
p4 [g-opts] admin resetpassword -a | -u user
Reference – Click here

How to remove files from perforce permanently?
p4 archive -p with caution. This is the one of only two commands in Perforce that actually removes file data. (The other command that removes file data is p4 obliterate.)

How to set properly in Perforce?
The Perforce service offers three ways of storing metadata: counters/keys, attributes, and properties.

If your application requires only the flat storage of simple key/value pairs, and attempts to implement no security model, use the p4 counters and p4 keys commands.

The p4 property command can be used by administrators to view and update property definitions stored in the Perforce service. The service does not use the property definitions; it provides this capability for other Perforce applications, such as P4V

If your application’s metadata is associated with particular files, use p4 attribute.

If your application’s metadata is not associated with files, and if you have a requirement to restrict its visibility to users, groups, and/or to control the precedence of multiple values using sequence numbers, use p4 property.

p4 property -n name -v value
p4 counter mycounter 123
p4 key mykey 12
p4 attribute -n name [ -v value ] files…

Perforce Integration with other Tools

  1. Gitfushion
  2. Swarm
  3. Replication
Tagged : / / / / / / / / / / / / / / /

Most asked Perl Interview Questions and Answers

perl-interview-questions-answers

What is Perl one-liner?

There are two ways a Perl script can be run:

a)from a command line, called one-liner, that means you type and execute immediately on the command line. You’ll need the -e option to start like “perl -e “print “Hello”;”. One-liner doesn’t mean one Perl statement. One-liner may contain many statements in one line.

b)from a script file, called Perl program.

Assuming both a local($var) and a my($var) exist, what’s the difference between ${var} and ${“var”}?

${var} is the lexical variable $var, and ${“var”} is the dynamic variable $var.

Note that because the second is a symbol table lookup, it is disallowed under `use strict “refs”‘. The words global, local, package, symbol table, and dynamic all refer to the kind of variables that local() affects, whereas the other sort, those governed by my(), are variously knows as private, lexical, or scoped variable.

Name all the prefix dereferencer in perl?

The symbol that starts all scalar variables is called a prefix dereferencer. The different types of dereferencer are.

(i) $-Scalar variables

(ii) %-Hash variables

(iii) @-arrays

(iv) &-subroutines

(v) Type globs-*myvar stands for @myvar, %myvar.

What exactly is grooving and shortening of the array?

You can change the number of elements in an array simply by changing the value of the last index of/in the array $#array. In fact, if you simply refer to a non existent element in an array perl extends the array as needed, creating new elements. It also includes new elements in its array.

What are the three ways to empty an array?

The three different ways to empty an array are as follows

  1. You can empty an array by setting its length to a negative number.
  2. Another way of empting an array is to assign the null list ().
  3. Try to clear an array by setting it to undef, but be aware when you set to undef.

How do you work with array slices

An array slice is a section of an array that acts like a list, and you indicate what elements to put into the slice by using multiple array indexes in square brackets. By specifying the range operator you can also specify a slice.

What is meant by splicing arrays explain in context of list and scalar.

Splicing an array means adding elements from a list to that array, possibly replacing elements now in the array. In list context, the splice function returns the elements removed from the array. In scalar context, the splice function returns the last element removed.

What are the different types of perl operators?

Please refer following URL..Perl Operators

What are the two different types of data perl handles?
Perl handles two types of data they are
(i) Scalar Variables and
(ii) Lists
Scalar variables hold a single data item whereas lists hold multiple data items.

What are scalar variables?
Scalar variables are what many programming languages refer to as simple variables. They hold a single data item, a number, a string, or a perl reference. Scalars are called scalars to differentiate them from constructs that can hold more than one item, like arrays.

Explain about lists?
A list is a construct that associates data elements together and you can specify a list by enclosing those elements in parenthesis and separating them with commas. They could themselves be arrays, hashes or even other lists. Lists do not have a specific list data type.

Name all the prefix dereferencer in perl?
The symbol that starts all scalar variables is called a prefix dereferencer. The different types of dereferencer are.
(i) $-Scalar variables
(ii) %-Hash variables
(iii) @-arrays
(iv) &-subroutines
(v) Type globs-*myvar stands for @myvar, %myvar.

Explain about an ivalue?
An ivalue is an item that can serve as the target of an assignment. The term I value originally meant a “left value”, which is to say a value that appears on the left. An ivalue usually represents a data space in memory and you can store data using the ivalues name. Any variable can serve as an ivalue.

How does a “grep” function perform?
Grep returns the number of lines the expression is true. Grep returns a sublist of a list for which a specific criterion is true. This function often involves pattern matching. It modifies the elements in the original list.

Explain about Typeglobs?
Type globs are another integral type in perl. A typeglob`s prefix derefrencer is *, which is also the wild card character because you can use typeglobs to create an alias for all types associated with a particular name. All kinds of manipulations are possible with typeglobs.

Is there any way to add two arrays together?

Of course you can add two arrays together by using push function. The push function adds a value or values to the end of an array. The push function pushes the values of list onto the end of the array. Length of an array can be increased by the length of list.

How to use the command shift?
Shift array function shifts off the first value of the array and returns it, thereby shortening the array by one element and moving everything from one place to the left. If you don’t specify an array to shift, shift uses @ ARGV, the array of command line arguments passed to the script or the array named @-.

Which has the highest precedence, List or Terms? Explain?
Terms have the highest precedence in perl. Terms include variables, quotes, expressions in parenthesis etc. List operators have the same level of precedence as terms. Specifically, these operators have very strong left word precedence.

What is a short circuit operator?
The C-Style operator, ll, performs a logical (or) operation and you can use it to tie logical clauses together, returning an overall value of true if either clause is true. This operator is called a short-circuit operator because if the left operand is true the right operand is not checked or evaluated.

What are the different forms of goto in perl? Explain?
The three forms of goto are as follows. They are
(i) Goto label
(ii) Goto name
(iii) Goto expr
The first form, goto LABEL, transfers execution to the statement labeled LABEL. The second form, goto EXPR, expects EXPR to evaluate to a label. The last form goto &name is used with subroutines. This goto statement is used only when there is a necessity as it can create havoc in a program.

What are the different types of eval statements?
There are two different types of eval statements they are eval EXPR and eval BLOCK. Eval EXPR executes an expression and eval BLOCK executes BLOCK. Eval Block executes an entire block, BLOCK. First one is used when you want your code passed in the expression and the second one is used to parse the code in the block.

Explain about returning values from subroutines (functions)?
The return value of the subroutine is the value of the last expression evaluated or you can explicitly use a return statement to exit the subroutine specifying the return value. That return value is evaluated in the appropriate content depending on the content of the subroutine call.

What is sed?
sed is stream editor, a Unix tool for working with streams of text data. See the awful truth about sed.

How do you substitute strings with sed?
Use ’s/old/new’ command, so sed ’s/hello/goodbye/’ would substitute the occurrence of the word hello to goodbye.

How do you inject text with sed?
& in the substitution string defines the pattern found in the search string. As an example, here’s us trying to find a word ‘hello’ and replacing it with ‘hello and how are you’:
echo ‘hello there’ | sed ’s/^hello/& and how are you/’

Can I find several patterns and refer to them in the replacement string?
Yes, use (pattern) and then refer to your patterns as \1, \2, \3 and so on.

If the string is ‘old old old’ and I run ’s/old/new’, I get ‘new old old’ as the result. I need ‘new new new‘.
You forgot the global modifier, which would replace every occurrence of the pattern with the substitution. ’s/old/new/g‘ will work.

But I want ‘old old new’ from the previous example. – Just use the numeric modifier saying you want the third occurrence to be replaced. ’s/old/new/3‘ will work.

I wrote a rather complex sed script. How do I save and run it?
Assuming that your file is named myscript1.sed, you can invoke sed -f myscript1.sed.

How do I delete trailing whitespaces from each line?
sed ’s/[ \t]*$//’ Here we’re replacing any occurrence of a space or a tab with nothing. Check sed one-liners for more examples.

How do you print just a few first lines of the file? – sed 1q will give you just the first line, sed 10q the first 10 lines.

How do you replace a pattern only if it’s found, so that it’s executed faster? – Nest the replacement statement: sed ‘/old/ s/old/new/g’ file.txt

How do you know the reference of a variable whether it is a reference,scaller, hash or array?
There is a ‘ref’ function that lets you know

What is the difference between ‘use’ and ‘require’ function?

Use: 1. the method is used only for modules (only to include .pm type file) 2. the included object are verified at the time of compilation. 3. No Need to give file extentsion. Require: 1. The method is used for both libraries ( package ) and modules 2. The include objects are varified at the run time. 3. Need to give file Extension.

What is the use of ‘chomp’ ? what is the difference between ‘chomp’ and ‘chop’?

Ans. ‘chop’ functiononly removes the last character completely ‘from the scaler, where as ‘chomp’ function only removes the last character if it is a newline. by default, chomp only removes what is currently defined as the $INPUT_RECORD_SEPARATOR. whenever you call ‘chomp ‘, it checks the value of a special variable ‘$/’. whatever the value of ‘$/’ is eliminated from the scaler. by default the value of ‘$/’ is ‘n’

Print this array @arr in reversed case-insensitive order

Ans> @solution = sort {lc $a comp lc$b } @arr.

What is ‘->’ in Perl?

Ans. it is a symbolic link to link one file name to a new name. so lets say we do it like file1-> file2, if we read file1, we end up reading file2.

how do you check the return code of system call?

System calls “traditionally” returns 9 when successful and 1 when it fails. system (cmd) or die “Error in command”;

#create directory if not there
if (! -s “$temp/engl_2/wf”){ System “mkdir -p $temp/engl_2/wf”; } if (! -s “$temp/backup_basedir”){ system “mkdir -p $temp/backup_basedir”; } ${pack_2} = -M “${temp}/engl_2/wf/${wf_package_name}.data”; ${new_pack}= -M “{pack}/package.data”; What is the use of -M and -s in the above script?

Ans. -s means is filename a non-empty file -M how long since filename modified?

How to substitute a particular string in a file containing million of record?

Ans. perl -p -ibak -e ‘s/search_str/replace_str/g’ filename

I have a variable named $objref which is defined in main package. I want to make it as a Object of class XYZ. how could I do it?

Ans. use XYZ my $objref =XYZ -> new() OR, bless $objref, ‘XYZ’;

what is meant by a ‘pack’ in perl?

Pack Converts a list into a binary representation. Takes an array or list of values and packs it into a binary structure, returning the string containing the structure It takes a LIST of values and converts it into a string. The string contaings a con-catenation of the converted values. Typically, each converted values looks like its machine-level repesentation. for example, on 32-bit machines a converted integer may be representated by a sequence of 4 bytes.

how to implement stack in Perl?

through push() and shift() function. push adds the element at the last of array and shift() removes from the beginning of an array.

What is Grep used for in Perl?

Grep is used with regular expression to check if a parituclar value exist in an array. it returns 0 it the value does not exists, 1 otherwise.

How to code in Perl to implement the tail function in unix?

And. You have to maintain a structure to store the line number and the size of the file at that time eg. 1-10bytes, 2-18bytes.. you have a counter to increase the number of lines to find out the number of lines in the file. once you are through the file, you will know the size of the file at any nth line, use ‘sysseek’ to move the file pointer back to that position (last 10) and thens tart reading till the end.

15. How do you navigate thorugh an XML documents?

Ans. You can use the XML::DOM navigation methods to navigate thorugh an XML::DOM node tree and use the getnodevalue to recover the data. DOM Parser is used when it is neede to do node operation. Instead we may use SAX parser if you require simple processing of the xml structure.

Why do you use Perl?

* Perl is a powerful free interpreter.
* Perl is portable, flexible and easy to learn.

How do I set environment variables in Perl programs?

You can just do something like this:
$ENV{‘PATH’} = ‘…’;
As you may remember, “%ENV” is a special hash in Perl that contains the value of all your environment variables.
Because %ENV is a hash, you can set environment variables just as you’d set the value of any Perl hash variable. Here’s how you can set your PATH variable to make sure the following four directories are in your path::

$ENV{‘PATH’} = ‘/bin:/usr/bin:/usr/local/bin:/home/yourname/bin’;

Which of these is a difference between C++ and Perl?
Perl can have objects whose data cannot be accessed outside its class, but C++ cannot.

Perl can use closures with unreachable private data as objects, and C++ doesn’t support closures. Furthermore, C++ does support pointer arithmetic via `int *ip = (int*)&object’, allowing you do look all over the object. Perl doesn’t have pointer arithmetic. It also doesn’t allow `#define private public’ to change access rights to foreign objects. On the other hand, once you start poking around in /dev/mem, no one is safe.

How to open and read data files with Perl

Data files are opened in Perl using the open() function. When you open a data file, all you have to do is specify (a) a file handle and (b) the name of the file you want to read from.
As an example, suppose you need to read some data from a file named “checkbook.txt”. Here’s a simple open statement that opens the checkbook file for read access: open (CHECKBOOK, “checkbook.txt”); In this example, the name “CHECKBOOK” is the file handle that you’ll use later when reading from the checkbook.txt data file. Any time you want to read data from the checkbook file, just use the file handle named “CHECKBOOK”.
Now that we’ve opened the checkbook file, we’d like to be able to read what’s in it. Here’s how to read one line of data from the checkbook file:
$record = < CHECKBOOK > ;
After this statement is executed, the variable $record contains the contents of the first line of the checkbook file. The “<>” symbol is called the line reading operator.
To print every record of information from the checkbook file

open (CHECKBOOK, “checkbook.txt”) || die “couldn’t open the file!”;
while ($record = < CHECKBOOK >) {
print $record;
}
close(CHECKBOOK);

How do I do fill_in_the_blank for each file in a directory?
Answer:Here’s code that just prints a listing of every file in the current directory:
#!/usr/bin/perl -w
opendir(DIR, “.”);
@files = readdir(DIR);
closedir(DIR);
foreach $file (@files) {
print “$file\n”;
}

How do I generate a list of all .html files in a directory?

Answer:
Here’s a snippet of code that just prints a listing of every file in the current directory that ends with the extension .html:
#!/usr/bin/perl -w
opendir(DIR, “.”);
@files = grep(/\.html$/,readdir(DIR));
closedir(DIR);
foreach $file (@files) {
print “$file\n”;
}

What happens when you return a reference to a private variable?

Perl keeps track of your variables, whether dynamic or otherwise, and doesn’t free things before you’re done using them.

How to turn on Perl warnings? Why is that important?

Perl is very forgiving of strange and sometimes wrong code, which can mean hours spent searching for bugs and weird results. Turning on warnings helps uncover common mistakes and strange places and save a lot of debugging time in the long run. There are various ways ofturning on Perl warnings:

* For Perl one-liner, use -w option on the command line.
* On Unix or Windows, use the -w option in the shebang line (The first # line in the script). Note: Windows Perl interpreter may not require it.
* For other systems, choose compiler warnings, or check compiler documentation.

What are scalar data and scalar variables?

Perl has a flexible concept of data types. Scalar means a single thing, like a number or string. So the Java concept of int, float, double and string equals to Perl\’s scalar in concept and the numbers and strings are exchangeable. Scalar variable is a Perl variable that is used to store scalar data. It uses a dollar sign $ and followed by one or more alphanumeric characters or underscores. It is case sensitive.

Why should I use the -w argument with my Perl programs?

Many Perl developers use the -w option of the interpreter, especially during the development stages of an application. This warning option turns on many warning messages that can help you understand and debug your applications.
To use this option on Unix systems, just include it on the first line of the program, like this:
#!/usr/bin/perl -w
If you develop Perl apps on a DOS/Windows computer, and you’re creating a program named myApp.pl, you can turn on the warning messages when you run your program like this:
perl -w myApp.pl

I want users send data by formmail but when they send nothing or call it from web site they will see error. codes in PHP like this: if (isset($HTTP_POST_VARS)){ ………. } else{ echo (“error lalalalal”) } How it will look in perl?

In php it will be like
if (isset($HTTP_POST_VARS)){
….
}
In perl, tried this.
if ($ENV{‘REQUEST_METHOD’} eq ‘POST’){
…..
}

What is the output of the following Perl program?
1 $p1 = “prog1.java”;
2 $p1 =~ s/(.*)\.java/$1.cpp/;
3 print “$p1\n”;

Answer:What is the output of the following Perl program?
1 $p1 = “prog1.java”;
2 $p1 =~ s/(.*)\.java/$1.cpp/;
3 print “$p1\n”;

prog1.cpp

Why are not Perls patterns regular expressions?

Because Perl patterns have backreferences.
A regular expression by definition must be able to determine the next state in the finite automaton without requiring any extra memory to keep around previous state. A pattern /([ab]+)c\1/ requires the state machine to remember old states, and thus disqualifies such patterns as being regular expressions in the classic sense of the term.

What does Perl do if you try to exploit the execve(2) race involving setuid scripts?

Sends mail to root and exits.
It has been said that all programs advance to the point of being able to automatically read mail. While not quite at that point (well, without having a module loaded), Perl does at least automatically send it.

How do I do < fill-in-the-blank > for each element in a hash?

Here’s a simple technique to process each element in a hash:

#!/usr/bin/perl -w

%days = (
‘Sun’ =>’Sunday’,
‘Mon’ => ‘Monday’,
‘Tue’ => ‘Tuesday’,
‘Wed’ => ‘Wednesday’,
‘Thu’ => ‘Thursday’,
‘Fri’ => ‘Friday’,
‘Sat’ => ‘Saturday’ );

foreach $key (sort keys %days) {
print “The long name for $key is $days{$key}.\n”;
}

How do I sort a hash by the hash key?

Suppose we have a class of five students.
Their names are kim, al, rocky, chrisy, and jane.

Here’s a test program that prints the contents
of the grades hash, sorted by student name:

#!/usr/bin/perl -w

%grades = (
kim => 96,
al => 63,
rocky => 87,
chrisy => 96,
jane => 79,
);

print “\n\tGRADES SORTED BY STUDENT NAME:\n”;
foreach $key (sort (keys(%grades))) {
print “\t\t$key \t\t$grades{$key}\n”;
}

The output of this program looks like this:

GRADES SORTED BY STUDENT NAME:
al 63
chrisy 96
jane 79
kim 96
rocky 87

}

How do you print out the next line from a filehandle with all its bytes reversed?

print scalar reverse scalar <FH>
Surprisingly enough, you have to put both the reverse and the <FH> into scalar context separately for this to work.

How do I send e-mail from a Perl/CGI program on a Unix system?

Sending e-mail from a Perl/CGI program on a Unix computer system is usually pretty simple. Most Perl programs directly invoke the Unix sendmail program. We’ll go through a quick example here.
Assuming that you’ve already have e-mail information you need, such as the send-to address and subject, you can use these next steps to generate and send the e-mail message:
# the rest of your program is up here …
open(MAIL, “|/usr/lib/sendmail -t”);
print MAIL “To: $sendToAddress\n”;
print MAIL “From: $myEmailAddress\n”;
print MAIL “Subject: $subject\n”;
print MAIL “This is the message body.\n”;
print MAIL “Put your message here in the body.\n”;
close (MAIL);

How to read from a pipeline with Perl
Example 1:

To run the date command from a Perl program, and read the output
of the command, all you need are a few lines of code like this:

open(DATE, “date|”);
$theDate = <DATE>;
close(DATE);

The open() function runs the external date command, then opens
a file handle DATE to the output of the date command.

Next, the output of the date command is read into
the variable $theDate through the file handle DATE.

Example 2:

The following code runs the “ps -f” command, and reads the output:

open(PS_F, “ps -f|”);
while (<PS_F>) {
($uid,$pid,$ppid,$restOfLine) = split;
# do whatever I want with the variables here …
}
close(PS_F);

Why is it hard to call this function: sub y { “because” }

Because y is a kind of quoting operator.
The y/// operator is the sed-savvy synonym for tr///. That means y(3) would be like tr(), which would be looking for a second string, as in tr/a-z/A-Z/, tr(a-z)(A-Z), or tr[a-z][A-Z].

What does $result = f() .. g() really return?

False so long as f() returns false, after which it returns true until g() returns true, and then starts the cycle again.
This is scalar not list context, so we have the bistable flip-flop range operator famous in parsing of mail messages, as in `$in_body = /^$/ .. eof()’. Except for the first time f() returns true, g() is entirely ignored, and f() will be ignored while g() later when g() is evaluated. Double dot is the inclusive range operator, f() and g() will both be evaluated on the same record. If you don’t want that to happen, the exclusive range operator, triple dots, can be used instead. For extra credit, describe this:
$bingo = ( a() .. b() ) … ( c() .. d() );

Why does Perl not have overloaded functions?

Because you can inspect the argument count, return context, and object types all by yourself.
In Perl, the number of arguments is trivially available to a function via the scalar sense of @_, the return context via wantarray(), and the types of the arguments via ref() if they’re references and simple pattern matching like /^\d+$/ otherwise. In languages like C++ where you can’t do this, you simply must resort to overloading of functions.

What does read() return at end of file?

0
A defined (but false) 0 value is the proper indication of the end of file for read() and sysread().

What does new $cur->{LINK} do? (Assume the current package has no new() function of its own.)

$cur->new()->{LINK}
The indirect object syntax only has a single token lookahead. That means if new() is a method, it only grabs the very next token, not the entire following expression.
This is why `new $obj[23] arg’ does’t work, as well as why `print $fh[23] “stuff\n”‘ does’t work. Mixing notations between the OO and IO notations is perilous. If you always use arrow syntax for method calls, and nothing else, you’ll not be surprised.

How do I sort a hash by the hash value?

Here’s a program that prints the contents
of the grades hash, sorted numerically by the hash value:

#!/usr/bin/perl -w

# Help sort a hash by the hash ‘value’, not the ‘key’.
to highest).
sub hashValueAscendingNum {
$grades{$a} <=> $grades{$b};
}

# Help sort a hash by the hash ‘value’, not the ‘key’.
# Values are returned in descending numeric order
# (highest to lowest).
sub hashValueDescendingNum {
$grades{$b} <=> $grades{$a};
}

%grades = (
student1 => 90,
student2 => 75,
student3 => 96,
student4 => 55,
student5 => 76,
);

print “\n\tGRADES IN ASCENDING NUMERIC ORDER:\n”;
foreach $key (sort hashValueAscendingNum (keys(%grades))) {
print “\t\t$grades{$key} \t\t $key\n”;
}

print “\n\tGRADES IN DESCENDING NUMERIC ORDER:\n”;
foreach $key (sort hashValueDescendingNum (keys(%grades))) {
print “\t\t$grades{$key} \t\t $key\n”;
}

How to read file into hash array ?

open(IN, “<name_file”)
or die “Couldn’t open file for processing: $!”;
while (<IN>) {
chomp;
$hash_table{$_} = 0;
}
close IN;

print “$_ = $hash_table{$_}\n” foreach keys %hash_table;

How do you find the length of an array?

$@array

What value is returned by a lone return; statement?

The undefined value in scalar context, and the empty list value () in list context.
This way functions that wish to return failure can just use a simple return without worrying about the context in which they were called.

What is the difference between /^Foo/s and /^Foo/?

The second would match Foo other than at the start of the record if $* were set.
The deprecated $* flag does double duty, filling the roles of both /s and /m. By using /s, you suppress any settings of that spooky variable, and force your carets and dollars to match only at the ends of the string and not at ends of line as well — just as they would if $* weren’t set at all.

Does Perl have reference type?

Yes. Perl can make a scalar or hash type reference by using backslash operator.
For example
$str = “here we go”; # a scalar variable
$strref = \$str; # a reference to a scalar

@array = (1..10); # an array
$arrayref = \@array; # a reference to an array
Note that the reference itself is a scalar.

How to dereference a reference?

There are a number of ways to dereference a reference.
Using two dollar signs to dereference a scalar.
$original = $$strref;
Using @ sign to dereference an array.
@list = @$arrayref;
Similar for hashes.

What does length(%HASH) produce if you have thirty-seven random keys in a newly created hash?

5
length() is a built-in prototyped as sub length($), and a scalar prototype silently changes aggregates into radically different forms. The scalar sense of a hash is false (0) if it’s empty, otherwise it’s a string representing the fullness of the buckets, like “18/32” or “39/64”. The length of that string is likely to be 5. Likewise, `length(@a)’ would be 2 if there were 37 elements in @a.

If EXPR is an arbitrary expression, what is the difference between $Foo::{EXPR} and *{“Foo::”.EXPR}?

The second is disallowed under `use strict “refs”‘.
Dereferencing a string with *{“STR”} is disallowed under the refs stricture, although *{STR} would not be. This is similar in spirit to the way ${“STR”} is always the symbol table variable, while ${STR} may be the lexical variable. If it’s not a bareword, you’re playing with the symbol table in a particular dynamic fashion.

How do I do < fill-in-the-blank > for each element in an array?

#!/usr/bin/perl -w
@homeRunHitters = (‘McGwire’, ‘Sosa’, ‘Maris’, ‘Ruth’);
foreach (@homeRunHitters) {
print “$_ hit a lot of home runs in one year\n”;
}

How do I replace every <TAB> character in a file with a comma?

perl -pi.bak -e ‘s/\t/,/g’ myfile.txt

What is the easiest way to download the contents of a URL with Perl?
Answer:
Once you have the libwww-perl library, LWP.pm installed, the code is this:
#!/usr/bin/perl
use LWP::Simple;
$url = get ‘http://www.websitename.com/’;

How to concatenate strings with Perl?
Method #1 – using Perl’s dot operator:
$name = ‘checkbook’;
$filename = “/tmp/” . $name . “.tmp”;

Method #2 – using Perl’s join function
$name = “checkbook”;
$filename = join “”, “/tmp/”, $name, “.tmp”;

Method #3 – usual way of concatenating strings
$filename = “/tmp/${name}.tmp”;

How do I read command-line arguments with Perl?

With Perl, command-line arguments are stored in the array named @ARGV.
$ARGV[0] contains the first argument, $ARGV[1] contains the second argument, etc.
$#ARGV is the subscript of the last element of the @ARGV array, so the number of arguments on the command line is $#ARGV + 1.
Here’s a simple program:
#!/usr/bin/perl
$numArgs = $#ARGV + 1;
print “thanks, you gave me $numArgs command-line arguments.\n”;
foreach $argnum (0 .. $#ARGV) {
print “$ARGV[$argnum]\n”;
}

When would local $_ in a function ruin your day?

When your caller was in the middle for a while(m//g) loop
The /g state on a global variable is not protected by running local on it. That’ll teach you to stop using locals. Too bad $_ can’t be the target of a my() — yet.

What happens to objects lost in “unreachable” memory, such as the object returned by Ob->new() in `{ my $ap; $ap = [ Ob->new(), \$ap ]; }’ ?

Their destructors are called when that interpreter thread shuts down.
When the interpreter exits, it first does an exhaustive search looking for anything that it allocated. This allows Perl to be used in embedded and multithreaded applications safely, and furthermore guarantees correctness of object code.

Assume that $ref refers to a scalar, an array, a hash or to some nested data structure. Explain the following statements:
Answer:
$$ref; # returns a scalar
$$ref[0]; # returns the first element of that array
$ref- > [0]; # returns the first element of that array
@$ref; # returns the contents of that array, or number of elements, in scalar context
$&$ref; # returns the last index in that array
$ref- > [0][5]; # returns the sixth element in the first row
@{$ref- > {key}} # returns the contents of the array that is the value of the key “key”

How do you match one letter in the current locale?

Answer:
/[^\W_\d]/
We don’t have full POSIX regexps, so you can’t get at the isalpha() <ctype.h> macro save indirectly. You ask for one byte which is neither a non-alphanumunder, nor an under, nor a numeric. That leaves just the alphas, which is what you want.

How do I print the entire contents of an array with Perl?
Answer:
To answer this question, we first need a sample array. Let’s assume that you have an array that contains the name of baseball teams, like this:
@teams = (‘cubs’, ‘reds’, ‘yankees’, ‘dodgers’);
If you just want to print the array with the array members separated by blank spaces, you can just print the array like this:
@teams = (‘cubs’, ‘reds’, ‘yankees’, ‘dodgers’);
print “@teams\n”;
But that’s not usually the case. More often, you want each element printed on a separate line. To achieve this, you can use this code:
@teams = (‘cubs’, ‘reds’, ‘yankees’, ‘dodgers’);
foreach (@teams) {
print “$_\n”;
}

How many ways can we express string in Perl?
Many. For example ‘this is a string’ can be expressed in:
“this is a string”
qq/this is a string like double-quoted string/
qq^this is a string like double-quoted string^
q/this is a string/
q&this is a string&
q(this is a string)

How do you give functions private variables that retain their values between calls?

Create a scope surrounding that sub that contains lexicals.
Only lexical variables are truly private, and they will persist even when their block exits if something still cares about them. Thus:
{ my $i = 0; sub next_i { $i++ } sub last_i { –$i } }
creates two functions that share a private variable. The $i variable will not be deallocated when its block goes away because next_i and last_i need to be able to access it.

What is the Use of Symbolic Reference in PERL?

How to find type of variable?

What is Grep used for in Perl?

grep ( EXPR, LIST) extract any elements from LIST for which EXPR is TRUE.
Return Value

In scalar context – Number of times the expression returned true

In list context – List of elements that matched the expression

Example

Try out following example:

#!/usr/bin/perl

@list = (1,”Test”, 0, “foo”, 20 );

@has_digit = grep ( /\d/, @list );

print “@has_digit\n”;

It produces following result

1 0 20

What is eval in perl?

Evaluates EXPR at execution time as if EXPR were a separate Perl script. This allows you to use a separate, perhaps user-supplied, piece of Perl script within your program. An eval EXPR statement is evaluated separately each time the function is called.

The second form evaluates BLOCK when the rest of the script is parsed (before execution).

How to substitute a particular string in a file containing millions of records?

$_ = s/ string1 / string2 /g

How we can navigate the XML documents?

What is the difference between die and exit in perl?

Die is exmplained below;

exit Evaluates EXPR, exits the Perl interpreter, and returns the value as the exit value.Always runs all END{} blocks defined in the script (and imported packages) before exiting. If EXPR is omitted, then the interpreter exits with a value of 0. Should not be used to exit from a subroutine; either use eval and die or use return.

Following are the usage…

$ans = <STDIN>;
exit 0 if $ans =~ /^[Xx]/

What is hash in perl?

A hash represents a set of key/value pairs. Actaully hash are type of arrays with the exception that hash index could be a number or string. They are prefixed by % sign as follows:

my %fruit_color = (“apple”, “red”, “banana”, “yellow”);

what is meant ‘die’ in a perl program?

Raise an exception or bail out.

Following are the usage…

die “Can’t cd to spool: $!\n” unless chdir ‘/usr/spool/news’;
or
chdir ‘/usr/spool/news’ or die “Can’t cd to spool: $!\n”
or
open( FILEH, “>/tmp/test” ) || die( “Can’t open file test $!\n” );

what’s is the use of ‘require’ and what does this mean?

Load in external functions from a library at runtime

what does this mean ‘$^O’? tell briefly plse..

Contains the name of the operating system that the current Perl binary was compiled for.

what does this mean : ‘$_’ ?

$_ is a default special varible in perl which store the inputs for further pattern searching.

what are regular expressions?

A regular expression, also referred to as regex or regexp, provides a concise and flexible means for matching strings of text, such as particular characters, words, or patterns of characters. A regular expression is written in a formal language that can be interpreted by a regular expression processor, a program that either serves as a parser generator or examines text and identifies parts that match the provided specification.

Difference between for and foreach?

Using for you can initialize variable, condition check and increment the variables like ‘C’ or like some other languages.
foreach is a function having in perl using you can iterates over the list and you cannot initialize or condition check or increment like ‘for’ in a single line.
We can use both for or foreach for any scenario but Perl author suggest that you can use for where you are counting a number of iteration like conventional for loops. foreach for list based operation where you are access the list from array.

Difference between exec and system in perl?

http://www.scmgalaxy.com/forum/perl-script/t-521.html#522

What is use strict. Explain with example.
strict – Perl pragma to restrict unsafe constructs.

Example:
use strict;
use strict “vars”;
use strict “refs”;
use strict “subs”;
use strict;
no strict “vars”;

use strict “subs”;
The use function allows you to use modules located in the standard liberary. When the strict pragma takes subs as an argument, it will catch any barewords found in the program while it is being internally compiled. If a bareword is found, the program will be aborted with an error message.

use strict “vars”
This generates a compile-time error if you access a variable that was neither explicitly declared (using any of my, our, state, or use vars ) nor fully qualified.

use strict “refs”
This generates a runtime error if you use symbolic references.

More –
http://perldoc.perl.org/strict.html
http://szabgab.com/barewords-in-perl.html

What is CPAN?
CPAN is the Comprehensive Perl Archive Network, a large collection of Perl software and documentation. You can begin exploring from either http://www.cpan.org/ or any of the mirrors listed at http://www.cpan.org/SITES.html.

CPAN is also the name of a Perl module, CPAN.pm, which is used to download and install Perl software from the CPAN archive.you may find the documentation for it by using perldoc CPAN via the command line
More: –
http://www.cpan.org/misc/cpan-faq.html#What_is_CPAN

How to install modules using CPAN or PPM (Perl Package Manager)
Install cpanm to make installing other modules easier
> cpan App::cpanminus (Mac OS X, Win32, X Windows/Linux)

Now install any module you can find in http://www.cpan.org/modules/index.html
cpanm Module::Name
such as to insall local::lib
> cpanm local::lib

ActiveState maintains repositories of precompiled CPAN packages that can be installed with either the PPM command-line client, or the PPM GUI application. To install the DBD-mysql database driver all you have to do is run the ppm install command:
> ppm install DBD-mysql

Alternatively you can run ppm without any parameters to invoke the GUI, search for DBD-mysql, select the DBD-mysql package, and perform the installation:
> ppm

How do you open a file for writing?

open(FH, "> $path") or die $!;

Difference between printf and sprintf in perl ? || print vs sprintf || Difference between print vs sprintf

The printf and sprintf is built-in function. One difference is printf prints it’s output and sprintf returns it’;s value.
Prints the value of LIST interpreted via the format specified by FORMAT to the current output filehandle, or to the one specified by FILEHANDLE.

Syntax
printf FILEHANDLE FORMAT, LIST
printf FORMAT, LIST

Return Value
0 on failure
1 on success

Effectively equivalent to print FILEHANDLE sprintf(FORMAT, LIST)

Try out following example:
#!/usr/bin/perl -w
printf “%d\n”, 3.1415126;
printf “The cost is \$%6.2f\n”,499;
printf “Perl’s version is v%vd\n”,%^V;
printf “%04d\n”, 20;

It will produce following results: Try more options yourself.
3
The cost is $499.00
Perl’s version is v
0020

On the other hand, The sprintf function uses FORMAT to return a formatted string based on the values in LIST. Essentially identical to printf, but the formatted string is returned instead of being printed.

Syntax
sprintf FORMAT, LIST

Return Value
SCALAR, a formatted text string.

Example
Try out following example:
#!/usr/bin/perl -w
$text = sprintf(“%0d \n”, 9);
print “Formated string $text\n”;

It will produce following result:
Formated string 9

What arguments do you frequently use for the Perl interpreter and what do they mean?
-w to show warning
-d to debug
-c to compile only not run
-e Which executes

You can check to see if your script has compiled successfully by using the –c switch. This used to check for syntax errors.
perl –c scriptname.pl

To Run on command line:executes the program given as an argument
perl –e ‘print “hello world\n”;’ unix/linux

With Warning Pragma
Perl –w <scriptname>

To start perl debugger on the file name specified as an argument
Perl –d <scriptname>

What do the symbols $ @ and % mean when prefixing a variable?
$  – To Define Scalar Variable
@ – To Define an Array
% – To define a hash

What elements of the Perl language could you use to structure your code to allow for maximum re-use and maximum readability?
It could be Subroutine, Module, Class, Package or objects. Questions should be more clear.

Why do you program in Perl?
Practice Report and Extraction Language
Interpreted Language optimized for scanning arbitrary test files, extracting information from them, and printing based on that information.
Very Powerful String handling features
Available for all platforms

Speed of Development
You can  enter the  program in a text file and just run it. It is an interpretive language; no compiler is neede
It is Powerful
The Regular expression of Perl are extremely powerful
Uses sophisticated pattern matching techniques to scan large amounts of data quickly.

Portability
Perl is a standard language and is available on all platforms.
Free version are available on the internet

Editing Perl programs
No sophisticated editing tool is needed
Any simple text editor like Notepad or vi will do

Flexibility
Perl Does not limit the size of your data
If Memory is available, perl can handle the whole file as a single string.
Allow one to write simple programs to perform complex task

What’s your favorite module and why?
use DBI;
use Getopt::Long;
use Time::Local;
use List::Compare;
use Log::Log4perl;
use CGI;
use HTML::Template;
use Data::Dumper;
use LWP;
use File::Find;

What is a hash?

A hash can be initialized with a list, where elements of the list are key and value pairs:

my %food_color = ( “Apple” => “red”, “Banana” => “yellow”, “Lemon” => “yellow”);

%age = ( “Nat”, 24, “Jules”, 25, “Josh”, 17 );
is equivalent to
$age{“Nat”} = 24; $age{“Jules”} = 25; $age{“Josh”} = 17;

$hash{“other”}

Only use the % when referring to the hash as a whole such as %boss
Hashes is that their elements are stored in an internal order convenient for efficient retrieval. it will come out in an unpredictable disorder.
When Referring to the value associated with a particular key, that’s a single scalar value, so is $ is called for.
When referring to one element of an array, you also use a $.
You can store only scalar value in a hash. References, however, are scalars. This solves the problem of storing multiple values for one key by making $hash{$key} a reference to an array containing values of $key.

What purpose does each of the following serve: -w?
Perl –w <scriptname>
Or
#! /usr/bin/perl –w
Or
use warnings; perl version 5.6 and later

The –w switch prints warnings about ambiguous identifiers, such as variables that have been used only once, improper conversion of stings and numbers etc

What is the difference between ‘use’ and ‘require’ function?
Use:
1. the method is used only for modules (only to include .pm type file)
2. the included object are verified at the time of compilation.
3. No Need to give file extentsion.
Require:
1. The method is used for both libraries ( package ) and modules
2. The include objects are varified at the run time.
3. Need to give file Extension.

Explain the difference between my and local.
Both of them are used to declare local variables.
The variables declared with “my” can live only within the block it was defined and cannot get its visibility inherited functions called within that block, but one defined with “local” can live within the block and have its visibility in the functions called within that block.

In the example below, $::a refers to $a in the ‘global’ namespace.

‘local’ temporarily changes the value of the variable, but only within the scope it exists in.

$a = 3.14159;
{
local $a = 3;
print “In block, \$a = $a\n”;
print “In block, \$::a = $::a\n”;
}

print “Outside block, \$a = $a\n”;
print “Outside block, \$::a = $::a\n”;

# This outputs In block,

# This outputs

In block, $a = 3
In block, $::a = 3
Outside block, $a = 3.14159
Outside block, $::a = 3.14159

‘my’ has no effect on the global $a, even inside the block.

$a = 3.14159;
{
my $a = 3;
print “In block, \$a = $a\n”;
print “In block, \$::a = $::a\n”;
}
print “Outside block, \$a = $a\n”;
print “Outside block, \$::a = $::a\n”;

# This outputs
In block, $a = 3
In block, $::a = 3.14159
Outside block, $a = 3.14159
Outside block, $::a = 3.14159

What is the difference between for & foreach?
What is the difference between exec & system?
What is the difference between map & grep?
What is the difference between sysread & read?
What is the difference between chop & chomp?
What is the difference between qq,qw & qx?
What is the difference between rand & srand?
What is the difference between exists and defined?
What is the difference between use and require?
What is the difference between eval & study?

Tagged : / / / / / / / / / / / / / / /

Selected AnthillPro Interview Questions

anthillpro-interview-questions

Selected AnthillPro Interview Questions

  • Building Procedures in AnthillPro
  • Deploying Procedures with AnthillPro
  • Using AnthillPro for Audit
  • Process of Integrating with Defect & Feature Tracking
  • Process of Integrating with Static Code Analysis
Tagged : / / / / / / / / / / / / / / / /

Top Selected Bamboo Interview Questions

bamboo-interview-questions

Top Selected Bamboo Interview Questions

Bamboo Questions:

  1. Tell me more about continuous integration ? How did you configured?
  2. Plugins used in Bamboo?
  3. Tell me more about Bamboo Schedule Options?
  4. How did you configured Bamboo with Subversion?

 

Tagged : / / / / / / / / / / / / / / / /

Apache Interview Questions – Apache Job Interview Kit

apche-interview-questions-answers

Apache Interview Questions – Apache Job Interview Kit

On a fresh install, why does Apache have three config files – srm.conf, access.conf and httpd.conf? – The first two are remnants from the NCSA times, and generally you should be ok if you delete the first two, and stick with httpd.conf.

What’s the command to stop Apache? – kill the specific process that httpd is running under, or killall httpd. If you have apachectl installed, use apachectl stop.

What does apachectl graceful do? – It sends a SIGUSR1 for a restart, and starts the apache server if it’s not running.
How do you check for the httpd.conf consistency and any errors in it? – apachectl configtest

When I do ps -aux, why do I have one copy of httpd running as root and the rest as nouser? – You need to be a root to attach yourself to any Unix port below 1024, and we need 80.

But I thought that running apache as a root is a security risk? – That one root process opens port 80, but never listens to it, so no user will actually enter the site with root rights. If you kill the root process, you will see the other kids disappear as well.

Why do I get the message “… no listening sockets available, shutting down”? – In Apache 2 you need to have a listen directive. Just put Listen 80 in httpd.conf.

How do you set up a virtual host in Apache?
<VirtualHost www.techinterviews.com>
ServerAdmin admin@techinterviews.com
DocumentRoot /home/apache/share/htdocs/hostedsites
ServerName www.techinterviews.com
ErrorLog /home/apache/logs/error/hostedsites/error_log
TransferLog /home/apache/logs/access/hostedsites/access_log
</VirtualHost>

What is ServerType directive? – It defines whether Apache should spawn itself as a child process (standalone) or keep everything in a single process (inetd). Keeping it inetd conserves resources. This is deprecated, however.

What is mod_vhost_alias? – It allows hosting multiple sites on the same server via simpler configurations.

What does htpasswd do? – It creates a new user in a specified group, and asks to specify a password for that user.
If you specify both deny from all and allow from all, what will be the default action of Apache? – In case of ambiguity deny always takes precedence over allow.

 

Tagged : / / / / / / / / / / / / / / / /

Apache and HTTP Interview Questions and Answers – Interview Guide

apache-and-http-interview-question-answers

Apache and HTTP Interview Questions and Answers – Interview Guide

List of Apache and HTTP Interview Questions: –

<!– /* Font Definitions */ @font-face {font-family:”Cambria Math”; panose-1:2 4 5 3 5 4 6 3 2 4; mso-font-charset:1; mso-generic-font-family:roman; mso-font-format:other; mso-font-pitch:variable; mso-font-signature:0 0 0 0 0 0;} @font-face {font-family:Calibri; panose-1:2 15 5 2 2 2 4 3 2 4; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:-1610611985 1073750139 0 0 159 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-unhide:no; mso-style-qformat:yes; mso-style-parent:””; margin-top:0in; margin-right:0in; margin-bottom:10.0pt; margin-left:0in; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:”Calibri”,”sans-serif”; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:Calibri; mso-fareast-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:”Times New Roman”; mso-bidi-theme-font:minor-bidi;} .MsoChpDefault {mso-style-type:export-only; mso-default-props:yes; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:Calibri; mso-fareast-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:”Times New Roman”; mso-bidi-theme-font:minor-bidi;} .MsoPapDefault {mso-style-type:export-only; margin-bottom:10.0pt; line-height:115%;} @page Section1 {size:8.5in 11.0in; margin:1.0in 1.0in 1.0in 1.0in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} /* List Definitions */ @list l0 {mso-list-id:1388797391; mso-list-template-ids:-480605428;} ol {margin-bottom:0in;} ul {margin-bottom:0in;} –>

  1. On a fresh install, why does Apache have three config files – srm.conf, access.conf and httpd.conf? – The first two are remnants from the NCSA times, and generally you should be ok if you delete the first two, and stick with httpd.conf.
  2. What’s the command to stop Apache? – kill the specific process that httpd is running under, or killall httpd. If you have apachectl installed, use apachectl stop.
  3. What does apachectl graceful do? – It sends a SIGUSR1 for a restart, and starts the apache server if it’s not running.
  4. How do you check for the httpd.conf consistency and any errors in it? – apachectl configtest
  5. When I do ps -aux, why do I have one copy of httpd running as root and the rest as nouser? – You need to be a root to attach yourself to any Unix port below 1024, and we need 80.
  6. But I thought that running apache as a root is a security risk? – That one root process opens port 80, but never listens to it, so no user will actually enter the site with root rights. If you kill the root process, you will see the other kids disappear as well.
  7. Why do I get the message “… no listening sockets available, shutting down”? – In Apache 2 you need to have a listen directive. Just put Listen 80 in httpd.conf.
  8. How do you set up a virtual host in Apache?
    <VirtualHost www.techinterviews.com>
    ServerAdmin admin@techinterviews.com
    DocumentRoot /home/apache/share/htdocs/hostedsites
    ServerName www.techinterviews.com
    ErrorLog /home/apache/logs/error/hostedsites/error_log
    TransferLog /home/apache/logs/access/hostedsites/access_log
    </VirtualHost>
  9. What is ServerType directive? – It defines whether Apache should spawn itself as a child process (standalone) or keep everything in a single process (inetd). Keeping it inetd conserves resources. This is deprecated, however.
  10. What is mod_vhost_alias? – It allows hosting multiple sites on the same server via simpler configurations.
  11. What does htpasswd do? – It creates a new user in a specified group, and asks to specify a password for that user.
  12. If you specify both deny from all and allow from all, what will be the default action of Apache? – In case of ambiguity deny always takes precedence over allow.
Tagged : / / / / / / / / / / / / / / / / / / /

General SCM Interview Questions – SCM Job Interview Kit

scm-interview-questions

 

General SCM Interview Questions – SCM Job Interview Kit

  • What do you think about configuration management?
  • What do you understand about Change Management?
  • branching methodologies and what currently theya re using it. Show with some example with pros and cons
  • Concept of Merging and Why do we need?
  • What do you think about build Management?
  • What are the key benefit of build Automation and what are the key inputs to automate the build process in the project?
  • Discuss about tools and technology which help to automate the entire build cycle.
  • What is Continuous Build Integration and How this is useful for the project?
  • What is daily build & nightly builds and what are the process need to set up to Automate & monitor consistently.
  • Explain in details for writing build sciprt for any project
  • What do you think about release Management?
  • Talk about Release Management on several platforms?
  • What do you understand about Packaging and Deployment?
  • How to Automate Remote Deployment of Builds on Development & Test Servers?
  • What is workflow management. exmplain this in details.
  • What do you understand about Code Coverage? Describe repective tools & utilities.
  • Describe the Integrate Packaging scripts & Test Automation scripts with build & Monitor build verification test status and tools.
  • How to co-ordinate with development team to increase their productiavity.
  • What do you understand about multisite project
  • How SCM team perform integration and co-ordination between Dev and QA
  • Explain Troubleshooting in Build Server and Process
  • Explain Troubleshooting in Configuration Server and Process
  • Explain Troubleshooting inMost popular java Comipler issues in build server
  • Explain Troubleshooting inMost popular C++ compiler issues in build server
  • software packaging tools if they will be packaging or writing the installations for the releases.
  • Backup your code daily with respect to SVN.
  • Overview of Batch Scripts and top 25 commands
  • Discuss about Web Servers and Application servers
  • What do you think about distributed and multi-site environment
  • Can you name some software development methodologies and describe them?
  • Agile attempts to minimize risk by developing software in short iterations.
  • Extreme Programming employs simplicity, frequent communication, constant customer feedback and decision empowerment.
  • Iterative development is a cyclical methodology that incorporates refactorying into the process.
  • Waterfall software development is a phased methodology. When one phase is complete, it moves onto the next phase.
  • What is an API?
  • What is a web service?
  • What the difference between a global and a local variable?
  • What are Bug /Issue Tatcking tools available and descibe them
  • How does Subversion handle binary files?
  • What is ADO?
  • What is polymorphism?
  • Plz Let me the Difference Between Bea Weblogic IBM Websphere

Perforce:

  • What are basic skills required for Perforce administration including Command Line info.
  • How we can develop Build summary reports for Mgmt team and what are the key inputs for report.
  • Explain the best practice for Setup process & maintain the Archive of software releases (internal & external) & license management of Third Party Libraries
  • Identify the Cdeployment tools for major/minor/patch releases in different environment.
  • Explain Red Hat Linux and some of daily used features.
  • Explain Perforce & Multisite
  • Concept of labeling, branching and merging
  • labeling, branching and merging in perforce

Talk about Release Process

Can you describe some source code control best practice?
# Use a reliable and dedicated server to house your code.
# Backup your code daily.
# Test your backup and restore processes.
# Choose a source control tool that fits your organization’s requirements.
# Perform all tool specific administrative tasks.
# Keep your code repositories as clean as possible.
# Secure access to your code.

Can you describe software build best practices?
# Fully automated build process
# Build repeatability
# Build reproducibility
# Build process adherence

CM tools Comparison

  • Difference Between CVS and SVN
  • Difference Between perforce and SVN
  • Difference Between perforce and Clearcasee
  • Difference Between VSS and TFSC
  • Difference Between perforce and MKS

 

 

Tagged : / / / / / / / / / / / / / / / /

Interview Questions Sets : Shell Script Descriptive

shell-script-descriptive-interview-questions-sets

Interview Questions Sets : Shell Script Descriptive Questions Sets

What is shell scripting?
Shell scripting is used to program command line of an operating system. Shell Scripting is also used to program the shell which is the base for any operating system. Shell scripts often refer to programming UNIX. Shell scripting is mostly used to program operating systems of windows, UNIX, Apple, etc. Also this script is used by companies to develop their own operating system with their own features.

Advantages of Shell scripting?
There are many advantages of shell scripting some of them are, one can develop their own operating system with relevant features best suited to their organization than to rely on costly operating systems. Software applications can be designed according to their platform.

What are the disadvantages of shell scripting?
There are many disadvantages of shell scripting they are

  • Design flaws can destroy the entire process and could prove a costly error.
  • Typing errors during the creation can delete the entire data as well as partition data.
  • Initially process is slow but can be improved.
  • *Portbility between different operating system is a prime concern as it is very difficult to port scripts etc.


Explain about the slow execution speed of shells?
Major disadvantage of using shell scripting is slow execution of the scripts. This is because for every command a new process needs to be started. This slow down can be resolved by using pipeline and filter commands. A complex script takes much longer time than a normal script.

Give some situations where typing error can destroy a program?
There are many situations where typing errors can prove to be a real costly effort. For example a single extra space can convert the functionality of the program from deleting the sub directories to files deletion. cp, cn, cd all resemble the same but their actual functioning is different. Misdirected > can delete your data.
Coding Related Shell Scripting Interview Questions …

Explain about return code?
Return code is a common feature in shell programming. These return codes indicate whether a particular program or application has succeeded or failed during its process. && can be used in return code to indicate which application needs to be executed first.

What are the different variables present in Linux shell?
Variables can be defined by the programmer or developer they specify the location of a particular variable in the memory. There are two types of shells they are System variables and user defined variables. System variables are defined by the system and user defined variables are to be defined by the user (small letters).

Explain about GUI scripting?
Graphical user interface provided the much needed thrust for controlling a computer and its applications. This form of language simplified repetitive actions. Support for different applications mostly depends upon the operating system. These interact with menus, buttons, etc.

Shell Scripting Command Interview Questions …

Explain about echo command?
Echo command is used to display the value of a variable. There are many different options give different outputs such as usage \c suppress a trailing line, \r returns a carriage line, -e enables interpretation, \r returns the carriage.

Explain about Stdin, Stdout and Stderr?
These are known as standard input, output and error. These are categorized as 0, 1 and 2. Each of these functions has a particular role and should accordingly functions for efficient output. Any mismatch among these three could result in a major failure of the shell.

Explain about sourcing commands?
Sourcing commands help you to execute the scripts within the scripts. For example sh command makes your program to run as a separate shell. .command makes your program to run within the shell. This is an important command for beginners and for special purposes.

Explain about debugging?
Shell can make your debugging process easier because it has lots of commands to perform the function. For example sh –ncommand helps you to perform debugging. It helps you to read the shell but not to execute it during the course. Similarly sh –x command helps you by displaying the arguments and functions as they are executed.

Explain about Login shell?
Login shell is very useful as it creates an environment which is very useful to create the default parameters. It consists of two files they are profile files and shell rc files. These files initialize the login and non login files. Environment variables are created by Login shell.

Explain about non-login shell files?
The non login shell files are initialized at the start and they are made to run to set up variables. Parameters and path can be set etc are some important functions. These files can be changed and also your own environment can be set. These functions are present in the root. It runs the profile each time you start the process.

Explain about shebang?
Shebang is nothing but a # sign followed by an exclamation. This is visible at the top of the script and it is immediately followed by an exclamation. To avoid repetitive work each time developers use shebang. After assigning the shebang work we pass info to the interpreter.

Explain about the Exit command?
Every program whether on UNIX or Linux should end at a certain point of time and successful completion of a program is denoted by the output 0. If the program gives an output other than 0 it defines that there has been some problem with the execution or termination of the problem. Whenever you are calling other function, exit command gets displayed.

Explore about Environment variables?
Environment variables are set at the login time and every shell that starts from this shell gets a copy of the variable. When we export the variable it changes from an shell variable to an environment variable and these variables are initiated at the start of the shell.

How can you tell what shell you are running on a UNIX system?
Answer :
You can do the Echo $RANDOM. It will return a undefined variable if you are from the C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit random numbers if you are from the Korn shell.

You could also do a ps -l and look for the shell with the highest PID.

What are conditions on which deadlock can occur while swapping the processes?

All processes in the main memory are asleep. All ‘ready-to-run’ processes are swapped out.
There is no space in the swap device for the new incoming process that are swapped out of the main memory. There is no space in the main memory for the new incoming process.

How do you change File Access Permissions?

Answer :

Every file has following attributes:
owner’s user ID ( 16 bit integer )
owner’s group ID ( 16 bit integer )
File access mode word

‘r w x -r w x- r w x’
(user permission-group permission-others permission)

r-read, w-write, x-execute

To change the access mode, we use chmod(filename,mode).
Example:
To change mode of myfile to ‘rw-rw-r–’ (ie. read, write permission for user – read,write permission for group – only read permission for others) we give the args as:
chmod(myfile,0664) .

Each operation is represented by discrete values
‘r’ is 4
‘w’ is 2
‘x’ is 1

Therefore, for ‘rw’ the value is 6(4+2).

Example 2:
To change mode of myfile to ‘rwxr–r–’ we give the args as:
chmod(myfile,0744).

List the system calls used for process management.
Answer :

System calls Description
fork() To create a new process
exec() To execute a new program in a process
wait() To wait until a created process completes its execution
exit() To exit from a process execution
getpid() To get a process identifier of the current process
getppid() To get parent process identifier
nice() To bias the existing priority of a process
brk() To increase/decrease the data segment size of a process

What is the difference between Swapping and Paging?
Answer:

Swapping:
Whole process is moved from the swap device to the main memory for execution. Process size must be less than or equal to the available main memory. It is easier to implementation and overhead to the system. Swapping systems does not handle the memory more flexibly as compared to the paging systems.

Paging:
Only the required memory pages are moved to main memory from the swap device for execution. Process size does not matter. Gives the concept of the virtual memory.

It provides greater flexibility in mapping the virtual address space into the physical memory of the machine. Allows more number of processes to fit in the main memory simultaneously. Allows the greater process size than the available physical memory. Demand paging systems handle the memory more flexibly.

What is the difference between cmp and diff commands?
Answer :

cmp – Compares two files byte by byte and displays the first mismatch
diff – tells the changes to be made to make the files identical

What is meant by the nice value?
Answer :

Nice value is the value that controls {increments or decrements} the priority of the process. This value that is returned by the nice () system call. The equation for using nice value is:
Priority = (“recent CPU usage”/constant) + (base- priority) + (nice value)
Only the administrator can supply the nice value. The nice () system call works for the running process only. Nice value of one process cannot affect the nice value of the other process.

What is a daemon?
Answer :
A daemon is a process that detaches itself from the terminal and runs, disconnected, in the background, waiting for requests and responding to them. It can also be defined as the background process that does not belong to a terminal session. Many system functions are commonly performed by daemons, including the sendmail daemon, which handles mail, and the NNTP daemon, which handles USENET news. Many other daemons may exist. Some of the most common daemons are:
init: Takes over the basic running of the system when the kernel has finished the boot process.
inetd: Responsible for starting network services that do not have their own stand-alone daemons. For example, inetd usually takes care of incoming rlogin, telnet, and ftp connections.
cron: Responsible for running repetitive tasks on a regular schedule.

What are the process states in UNIX?

Answer :
As a process executes it changes state according to its circumstances. Unix processes have the following states:
Running : The process is either running or it is ready to run .
Waiting : The process is waiting for an event or for a resource.
Stopped : The process has been stopped, usually by receiving a signal.
Zombie : The process is dead but have not been removed from the process table.

How are devices represented in UNIX?
All devices are represented by files called special files that are located in/dev directory. Thus, device files and other files are named and accessed in the same way. A ‘regular file’ is just an ordinary data file in the disk. A ‘block special file’ represents a device with characteristics similar to a disk (data transfer in terms of blocks). A ‘character special file’ represents a device with characteristics similar to a keyboard (data transfer is by stream of bits in sequential order).

What is ‘inode’?
All UNIX files have its description stored in a structure called ‘inode’. The inode contains info about the file-size, its location, time of last access, time of last modification, permission and so on. Directories are also represented as files and have an associated inode. In addition to descriptions about the file, the inode contains pointers to the data blocks of the file. If the file is large, inode has indirect pointer to a block of pointers to additional data blocks (this further aggregates for larger files). A block is typically 8k.
Inode consists of the following fields:
• File owner identifier
• File type
• File access permissions
• File access times
• Number of links
• File size
• Location of the file data

Brief about the directory representation in UNIX
A Unix directory is a file containing a correspondence between filenames and inodes. A directory is a special file that the kernel maintains. Only kernel modifies directories, but processes can read directories. The contents of a directory are a list of filename and inode number pairs. When new directories are created, kernel makes two entries named ‘.’ (refers to the directory itself) and ‘..’ (refers to parent directory).
System call for creating directory is mkdir (pathname, mode).

What are the Unix system calls for I/O?
• open(pathname,flag,mode) – open file
• creat(pathname,mode) – create file
• close(filedes) – close an open file
• read(filedes,buffer,bytes) – read data from an open file
• write(filedes,buffer,bytes) – write data to an open file
• lseek(filedes,offset,from) – position an open file
• dup(filedes) – duplicate an existing file descriptor
• dup2(oldfd,newfd) – duplicate to a desired file descriptor
• fcntl(filedes,cmd,arg) – change properties of an open file
• ioctl(filedes,request,arg) – change the behaviour of an open file
The difference between fcntl anf ioctl is that the former is intended for any open file, while the latter is for device-specific operations.

How do you change File Access Permissions?
Every file has following attributes:
• owner’s user ID ( 16 bit integer )
• owner’s group ID ( 16 bit integer )
• File access mode word
‘r w x -r w x- r w x’
(user permission-group permission-others permission)
r-read, w-write, x-execute
To change the access mode, we use chmod(filename,mode).
Example 1:
To change mode of myfile to ‘rw-rw-r–‘ (ie. read, write permission for user – read,write permission for group – only read permission for others) we give the args as:
chmod(myfile,0664) .
Each operation is represented by discrete values
‘r’ is 4
‘w’ is 2
‘x’ is 1
Therefore, for ‘rw’ the value is 6(4+2).
Example 2:
To change mode of myfile to ‘rwxr–r–‘ we give the args as:
chmod(myfile,0744).

What are links and symbolic links in UNIX file system?
A link is a second name (not a file) for a file. Links can be used to assign more than one name to a file, but cannot be used to assign a directory more than one name or link filenames on different computers.
Symbolic link ‘is’ a file that only contains the name of another file.Operation on the symbolic link is directed to the file pointed by the it.Both the limitations of links are eliminated in symbolic links.
Commands for linking files are:
Link ln filename1 filename2
Symbolic link ln -s filename1 filename2

What is a FIFO?
FIFO are otherwise called as ‘named pipes’. FIFO (first-in-first-out) is a special file which is said to be data transient. Once data is read from named pipe, it cannot be read again. Also, data can be read only in the order written. It is used in interprocess communication where a process writes to one end of the pipe (producer) and the other reads from the other end (consumer).

How do you create special files like named pipes and device files?
The system call mknod creates special files in the following sequence.
kernel assigns new inode,
sets the file type to indicate that the file is a pipe, directory or special file,
If it is a device file, it makes the other entries like major, minor device numbers.
For example:
If the device is a disk, major device number refers to the disk controller and minor device number is the disk.

Discuss the mount and unmount system calls
The privileged mount system call is used to attach a file system to a directory of another file system; the unmount system call detaches a file system. When you mount another file system on to your directory, you are essentially splicing one directory tree onto a branch in another directory tree. The first argument to mount call is the mount point, that is , a directory in the current file naming system. The second argument is the file system to mount to that point. When you insert a cdrom to your unix system’s drive, the file system in the cdrom automatically mounts to /dev/cdrom in your system.

How does the inode map to data block of a file?
Inode has 13 block addresses. The first 10 are direct block addresses of the first 10 data blocks in the file. The 11th address points to a one-level index block. The 12th address points to a two-level (double in-direction) index block. The 13th address points to a three-level(triple in-direction)index block. This provides a very large maximum file size with efficient access to large files, but also small files are accessed directly in one disk read.

What is a shell?
A shell is an interactive user interface to an operating system services that allows an user to enter commands as character strings or through a graphical user interface. The shell converts them to system calls to the OS or forks off a process to execute the command. System call results and other information from the OS are presented to the user through an interactive interface. Commonly used shells are sh,csh,ks etc.

Brief about the initial process sequence while the system boots up.
While booting, special process called the ‘swapper’ or ‘scheduler’ is created with Process-ID 0. The swapper manages memory allocation for processes and influences CPU allocation. The swapper inturn creates 3 children:
• the process dispatcher,
• vhand and
• dbflush
with IDs 1,2 and 3 respectively.
This is done by executing the file /etc/init. Process dispatcher gives birth to the shell. Unix keeps track of all the processes in an internal data structure called the Process Table (listing command is ps -el).

What are various IDs associated with a process?
Unix identifies each process with a unique integer called ProcessID. The process that executes the request for creation of a process is called the ‘parent process’ whose PID is ‘Parent Process ID’. Every process is associated with a particular user called the ‘owner’ who has privileges over the process. The identification for the user is ‘UserID’. Owner is the user who executes the process. Process also has ‘Effective User ID’ which determines the access privileges for accessing resources like files.
getpid() -process id
getppid() -parent process id
getuid() -user id
geteuid() -effective user id

Explain fork() system call.
The `fork()’ used to create a new process from an existing process. The new process is called the child process, and the existing process is called the parent. We can tell which is which by checking the return value from `fork()’. The parent gets the child’s pid returned to him, but the child gets 0 returned to him.

Predict the output of the following program code
main()
{
fork();
printf(“Hello World!”);
}
Answer:
Hello World!Hello World!
Explanation:
The fork creates a child that is a duplicate of the parent process. The child begins from the fork().All the statements after the call to fork() will be executed twice.(once by the parent process and other by child). The statement before fork() is executed only by the parent process.

Predict the output of the following program code
main()
{
fork(); fork(); fork();
printf(“Hello World!”);
}
Answer:
“Hello World” will be printed 8 times.
Explanation:
2^n times where n is the number of calls to fork()

List the system calls used for process management:
System calls Description
fork() To create a new process
exec() To execute a new program in a process
wait() To wait until a created process completes its execution
exit() To exit from a process execution
getpid() To get a process identifier of the current process
getppid() To get parent process identifier
nice() To bias the existing priority of a process
brk() To increase/decrease the data segment size of a process

How can you get/set an environment variable from a program?
Getting the value of an environment variable is done by using `getenv()’.
Setting the value of an environment variable is done by using `putenv()’.

How can a parent and child process communicate?
A parent and child can communicate through any of the normal inter-process communication schemes (pipes, sockets, message queues, shared memory), but also have some special ways to communicate that take advantage of their relationship as a parent and child. One of the most obvious is that the parent can get the exit status of the child.

What is a zombie?
When a program forks and the child finishes before the parent, the kernel still keeps some of its information about the child in case the parent might need it – for example, the parent may need to check the child’s exit status. To be able to get this information, the parent calls `wait()’; In the interval between the child terminating and the parent calling `wait()’, the child is said to be a `zombie’ (If you do `ps’, the child will have a `Z’ in its status field to indicate this.)

What are the process states in Unix?
As a process executes it changes state according to its circumstances. Unix processes have the following states:
Running : The process is either running or it is ready to run .
Waiting : The process is waiting for an event or for a resource.
Stopped : The process has been stopped, usually by receiving a signal.
Zombie : The process is dead but have not been removed from the process table.

What Happens when you execute a program?
When you execute a program on your UNIX system, the system creates a special environment for that program. This environment contains everything needed for the system to run the program as if no other program were running on the system. Each process has process context, which is everything that is unique about the state of the program you are currently running. Every time you execute a program the UNIX system does a fork, which performs a series of operations to create a process context and then execute your program in that context. The steps include the following:
• Allocate a slot in the process table, a list of currently running programs kept by UNIX.
• Assign a unique process identifier (PID) to the process.
• iCopy the context of the parent, the process that requested the spawning of the new process.
• Return the new PID to the parent process. This enables the parent process to examine or control the process directly.
After the fork is complete, UNIX runs your program.

What Happens when you execute a command?
When you enter ‘ls’ command to look at the contents of your current working directory, UNIX does a series of things to create an environment for ls and the run it:

The shell has UNIX perform a fork. This creates a new process that the shell will use to run the ls program.
The shell has UNIX perform an exec of the ls program. This replaces the shell program and data with the program and data for ls and then starts running that new program.

The ls program is loaded into the new process context, replacing the text and data of the shell. The ls program performs its task, listing the contents of the current directory.

What is a Daemon?
A daemon is a process that detaches itself from the terminal and runs, disconnected, in the background, waiting for requests and responding to them. It can also be defined as the background process that does not belong to a terminal session. Many system functions are commonly performed by daemons, including the sendmail daemon, which handles mail, and the NNTP daemon, which handles USENET news. Many other daemons may exist. Some of the most common daemons are:
• init: Takes over the basic running of the system when the kernel has finished the boot process.
• inetd: Responsible for starting network services that do not have their own stand-alone daemons. For example, inetd usually takes care of incoming rlogin, telnet, and ftp connections.
• cron: Responsible for running repetitive tasks on a regular schedule.

What is ‘ps’ command for?
The ps command prints the process status for some or all of the running processes. The information given are the process identification number (PID),the amount of time that the process has taken to execute so far etc.

How would you kill a process?
The kill command takes the PID as one argument; this identifies which process to terminate. The PID of a process can be got using ‘ps’ command.

What is an advantage of executing a process in background?
The most common reason to put a process in the background is to allow you to do something else interactively without waiting for the process to complete. At the end of the command you add the special background symbol, &. This symbol tells your shell to execute the given command in the background.
Example: cp *.* ../backup& (cp is for copy)

How do you execute one program from within another?
The system calls used for low-level process creation are execlp() and execvp(). The execlp call overlays the existing program with the new one , runs that and exits. The original program gets back control only when an error occurs.
execlp(path,file_name,arguments..); //last argument must be NULL
A variant of execlp called execvp is used when the number of arguments is not known in advance.
execvp(path,argument_array); //argument array should be terminated by NULL

What is IPC? What are the various schemes available?
The term IPC (Inter-Process Communication) describes various ways by which different process running on some operating system communicate between each other. Various schemes available are as follows:
Pipes:
One-way communication scheme through which different process can communicate. The problem is that the two processes should have a common ancestor (parent-child relationship). However this problem was fixed with the introduction of named-pipes (FIFO).

Message Queues :
Message queues can be used between related and unrelated processes running on a machine.

Shared Memory:
This is the fastest of all IPC schemes. The memory to be shared is mapped into the address space of the processes (that are sharing). The speed achieved is attributed to the fact that there is no kernel involvement. But this scheme needs synchronization.

State and explain about features of UNIX?
UNIX operating system originally was developed in 1969. This is an open source operating system developed by AT&T. It is widely used in work stations and servers. It is designed to be multi tasking, multi user and portable. UNIX has many several components packed together.

Explain about sh?
Sh is the command line interpreter and it is the primary user interface. This forms the programmable command line interpreter. After windows appeared it still retained the programmable characteristics.

Explain about system and user utilities?
There are two utilities they are system and user utilities. System utilities contain administrative tools such as mkfs, fsck, etc. Where as user utilities contain features such as passwd, kill, etc. It basically contains environment values.

Explain about document formatting?
UNIX systems were primarily used for typesetting systems and document formatting. Modern UNIX systems used packages such as Tex and Ghostscript. It uses some of the programs such as nroff, tbl, troff, refer, eqn and pic. Document formatting is very used because it forms the base of UNIX.

Explain about communication features in UNIX?
Early UNIX systems used inter user communication programs mail and write commands. They never contained a fully embedded inter user communication features. Systems with BSD included TCP/IP protocols.

Explain about chmod options filename?
This command allows you to change, write, read and execute permissions on your file. Changes can be done to the file system but at times you need to change permissions for the file systems. At times files should be executable for viewing the files.

Explain about gzip filename?
Gzip filename is used to compress the files so that those files take up less space. The size of the file actually gets reduced to half their size but they might also depend upon about the file size and nature of the file systems. Files using gzip file name end with .gz.

Explain about refer?
Refer was written in Bell Laboratories and it is implemented as a troff preprocessor. This program is used managing bibliographic references and it is used to cite them in troff documents. It is offered in most of the UNIX packages. It refers with text and reference file.

Explain about lpr filename?
This command is used to print a file. If you want to change the default print you can change the printer by using the P option. For double sided print you can use lpr-Pvalkyr-d. This is very useful command in UNIX present in many packages.

Explain about lprm job number?
This command is used to remove documents from the printer queue. The job number or the queue number can be found by using lpq. Printer name should be specified but this is not necessary if you want to use your default printer.

Brief about the command ff?
This command finds files present anywhere on the system. This command is used to find document location where you forgot the directory in which you kept the file but you do remember about the name. This command is not restricted in finding files it displays files and documents relevant to the name.

Brief about finger username?
This command is used to give information about the user; it gives out a profile about the user. This command is very useful for administrators as it gives the log information, email, current log information, etc. finger also displays information such as phone number and name when they use a file called .plan.

Explain about the command elm?
This command lets you to send email message from your system. This command is not the only one which sends email there are lots of other messenger systems which can facilitate the process of sending a mail. This command behaves differently on different machines.

Brief about the command kill PID?
This command ends the process to which it was assigned (ID). This command cannot be used in multi systems in the network. ID can be obtained by the command ps. This command ignores completely the state at which the process is it kills the process.

Explain about the command lynx?
This command helps you to browse web from an ordinary terminal. Text can be seen but not the pictures. URL can be assigned as an argument to the G command. Help section can be obtained by pressing H and Q makes the program to quit.

Brief about the command nn?
This command allows you to read the news. First you can read about the local news and then the remote news. “nnl” command makes or allows you to read local news and nnr command is used to read remote news. Manual and help information is available with many popular packages.

Brief about ftp hostname?
This command lets you download information, documents, etc from a remote ftp. First it is important to configure an FTP for the process to begin. Some of the important commands relevant to the usage of FTP are as follows get, put, mget, mput, etc. If you are planning to transfer files other than ASCII defined it is imperative to use binary mode.

Explain about the case statement.
The case statement compares word to the patterns from top to bottom, and performs the commands associated with the first, and only the first, pattern that matches. The patterns are written using the shells pattern matching rules, slightly generalized.

Explain the basic forms of each loop?
There are three loops; for, while and until. For loop is by far the most commonly used form of loop. Basically like other programs it executes a given set of commands and instructions. While and until forms of loop use the exit status from a command based system. They control the execution of the commands in the body of the loop.

Describe about awk and sed?
The awk program processes this to report the changes in an easier to understand format. Sed output is always behind its input by one line; there is always a line of input that has been processed but not printed, and this would introduce an unwanted delay.
Explain about signal argument?
The sequence of commands is a single argument, so it must almost always be quoted. The signal numbers are small integers that identify the signal. For example, 2 is the signal generated by pressing the DEL key, and 1 is generated by hanging up the phone. Unless a program has taken explicit action to deal with signals, the signal will terminate it.

Explain about exec?
The exec is just for efficiency, the command would run just as well without it. Exec is a shell built-in that replaces the process running this shell by the named program, thereby saving one process- the shell that would normally wait for the program to complete. Exec could be used at the end of the enhanced cal program when it invokes /usr/bin/cal.

Explain about trap command
The trap command sequence must explicitly invoke exit, or the shell program will continue to execute after the interrupt. The command sequence will be read twice: once when the trap is set and once when it is invoked. Trap is used sometimes interactively, most often to prevent a program from being killed by the hangup signal.

Explain about sort command?
The sort command has an option –o to overwrite a file:
$ sort file1 -0 file2
Is equivalent to
$ sort file1 > file2
If file 1 and file 2 are the same file, redirection with > will truncate the input file before it is sorted. The –o option works correctly because the input is sorted and saved in a temporary file before the output file is created. Many other commands could also use a –o option.

Explain about the command overwrite?
Overwrite is committed to changing the original file. If the program providing input to overwrite gets an error, its output will be empty and overwrite will dutifully and reliably destroy the argument file. Overwrite could ask for conformation before replacing the file, but making overwrite interactive would negate its efficiency. Overwrite could check that its input is empty.

Explain about kill command?
The kill command only terminates processes specified by process-id when a specific background process needs to be killed, you must usually run ps to find the process-id and then re type it as an argument to kill. Killing process is dangerous and care must be taken to kill the right processes.

Explain about the shell variable IFS?
The shell variable IFS (internal field separator) is a string of characters that separate words in argument lists such as back quotes and for statements. Normally IFS contains a blank, a tab, and a new line, but we can change it to anything useful, such as just a newline.

Explain about the rules used in overwrite to preserve the arguments to the users command?
Some of the rules are
• $* and $@ expand into the arguments and are rescanned; blanks in arguments will result in multiple arguments.
• “$*” is a single word composed of all the arguments to the shell file joined together with spaces.
• “$@” is identical to the arguments received by the shell file: blanks in arguments are ignored and the result is a list of words identical to the original arguments.

Explain about @@@ lines?
@@@ Lines are counted (but not printed), and as long as the count is not greater than the desired version, the editing commands are passed through. Two ed commands are added after those from the history file: $d deletes the single @@@ line that sed left on the current version.

Explain about vis?
Vis that copied its standard input to its standard output, except that it makes all non printing characters visible by printing them as \nnn, where nnn is the octal value of the character. Vis is invaluable for detecting strange or unwanted characters that may have crept into files.

Is the function call to exit at the end of vis necessary?
The call to exit at the end of vis is not necessary to make the program work properly, but it ensures that any caller of the program will see a normal exit status from the program when it completes. An alternate way to return status is to leave main with return 0; the return value from main is the program`s exit status.

Explain about fgets?

Fgets (buf, size, fp) fetches the next line of input from fp, up to and including a newline, into buf, and adds a terminating \0; at most size-1 characters are copied. A Null value is returned at the end of the file.

Explain about efopen page?
The routine efopen encapsulates a vey common operation: try to open a file; if it`s not possible, print an error message and exit. To encourage error messages that identify the offending program, efopen refers to an external string program containing the name of the program, which is set in main.

Explain about yacc parser generator?
Yacc is a parser generator that is a program for converting a grammatical specification of a language like the one above into a parser that will parse statements in the language.

What is $*?
Will display all the commandline arguments that are passed to the script

Different types of shells?
Bourne Shell (bash)
Korn Shell (ksh)
C Shell (csh)

What  is difference between a wild-card and regular expression?

Tagged : / / / / / / / / / / / / / / / / / / / /

Maven Interview Questions and Answers – Maven Job Interview Kit

maven-interview-questions-answers

Maven Interview Questions and Answers

Contributed by Rajesh Kumar with the help of Google Search and www.scmGalaxy.com
Is there a way to use the current date in the POM?
Take a look at the buildnumber plugin. It can be used to generate a build date each time I do a build, as follows:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>maven-buildnumber-plugin</artifactId>
<version>0.9.4</version>
<configuration>
<format>{0,date,yyyy-MM-dd HH:mm:ss}</format>
<items>
<item>timestamp</item>
</items>
<doCheck>false</doCheck>
<doUpdate>false</doUpdate>
</configuration>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>create</goal>
</goals>
</execution>
</executions>
</plugin>

pom.xml or settings.xml? What is the best practice configuration usage for these files?
The best practice guideline between settings.xml and pom.xml is that configurations in settings.xml must be specific to the current user and that pom.xml configurations are specific to the project.
For example, <repositories> in pom.xml would tell all users of the project to use the <repositories> specified in the pom.xml. However, some users may prefer to use a mirror instead, so they’ll put <mirrors> in their settings.xml so they can choose a faster repository server.
so there you go:
settings.xml -> user scope
pom.xml -> project scope

How do I indicate array types in a MOJO configuration?

<tags>
    <tag>value1</tag>
    <tag>value2</tag>
  </tags>

How should I point a path for maven 2 to use a certain version of JDK when I have different versions of JDK installed on my PC and my JAVA_HOME already set?
If you don’t want to change your system JAVA_HOME, set it in maven script instead.
How do I setup the classpath of my antrun plugin to use the classpath from maven?
The maven classpaths are available as ant references when running your ant script. The ant reference names and some examples can be found here: maven-antrun-plugin
Is it possible to use HashMap as configurable parameter in a plugin? How do I configure that in pom.xml?
Yes. Its possible to use a HashMap field as a parameter in your plugin. To use it, your pom configuration should look like this:

<myMap>
      <yourkey>yourvalue</yourkey>
      .....
   </myMap>

How do I filter which classes should be put inside the packaged jar?
All compiled classes are always put into the packaged jar. However, you can configure the compiler plugin to exclude compiling some of the java sources using the compiler parameter excludes as follows:

<project>
   ...
   <build>
     ...
     <plugins>
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-compiler-plugin</artifactId>
         <configuration>
           <excludes>
             <exclude>**/NotNeeded*.java</exclude>
           </excludes>
         </configuration>
       </plugin>
     </plugins>
     ...
   </build>
  </project>

How can I change the default location of the generated jar when I command “mvn package”?
By default, the location of the generated jar is in ${project.build.directory} or in your target directory.
We can change this by configuring the outputDirectory of maven-jar-plugin.

<plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-jar-plugin</artifactId>
              <configuration>
                  <outputDirectory>${project.build.directory}/<!-- directory --></outputDirectory>
              </configuration>
          </plugin>

How does maven 2 implement reproducibility?

  • Add the exact versions of plugins into your pluginDepenencies (make use of the release plugin)
  • Make use of ibiblio for your libraries. This should always be the case for jars. (The group is working on stabilising metadata and techniques for locking it down even if it changes. An internal repository mirror that doesn’t fetch updates (only new) is recommended for true reproducibility.)

Why there are no dependency properties in Maven 2?
They were removed because they aren’t reliable in a transitive environment. It implies that the dependency knows something about the
environment of the dependee, which is back to front. In most cases, granted, the value for war bundle will be the same for a particular
dependency – but that relies on the dependency specifying it.
In the end, we give control to the actual POM doing the building, trying to use sensible defaults that minimise what needs to be
specified, and allowing the use of artifact filters in the configuration of plugins.

What does aggregator mean in mojo?
When a Mojo has a @aggregator expression, it means that It can only build the parent project of your multi-module-project, the one who has the packaging of pom. It can also give you values for the expression ${reactorProjects} where reactorProjects are the MavenProject references to the parent pom modules.
Where is the plugin-registry.xml?
From the settings.xml, you may enable it by setting <usePluginRegistry/> to true
and the file will be in ~/.m2/plugin-registry.xml
How do I create a command line parameter (i.e., -Dname=value ) in my mojo?
In your mojo, put “expression=${<exp>}” in your parameter field

/**
   * @parameter expression="${expression.name}"
   */
  private String exp;

You may now able to pass parameter values to the command line.
“mvn -Dexpression.name=value install”
How do I convert my <reports> from Maven 1 to Maven 2?
In m1, we declare reports in the pom like this:

<project>
    ...
    <reports>
      <report>maven-checkstyle-plugin</report>
      <report>maven-pmd-plugin</report>
    </reports>
  </project>

In m2, the <reports> tag is replaced with <reporting>

<project>
    ...
    <reporting>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-checkstyle-plugin</artifactId>
          <configuration>
             <!-- put your config here -->
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-pmd-plugin</artifactId>
          <configuration>
             <!-- put your config here -->
          </configuration>
        </plugin>
      </plugins>
    <reporting>
  </project>

What does the “You cannot have two plugin executions with the same (or missing) elements” message mean?
It means that you have executed a plugin multiple times with the same <id>. Provide each <execution> with a unique <id> then it would be ok.
How do I add my generated sources to the compile path of Maven, when using modello?
Modello generate the sources in the generate-sources phase and automatically adds the source directory for compilation in maven. So you don’t have to copy the generated sources. You have to declare the modello-plugin in the build of your plugin for source generation (in that way the sources are generated each time).
What is Maven’s order of inheritance?

  1. parent pom
  2. project pom
  3. settings
  4. CLI parameters

where the last overrides the previous.
How do I execute the assembly plugin with different configurations?
Add this to your pom,

<build>
    ...
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <executions>
          <execution>
      <id>1</id>
            <phase>install</phase>
        <goals>
             <goal>assembly</goal>
       </goals>
          <configuration>
               <descriptor>src/main/descriptors/bin.xml</descriptor>
               <finalName>${project.build.finalName}-bin</finalName>
       </configuration>
          </execution>

<execution>
<id>2</id>
<phase>install</phase>
<goals>
<goal>assembly</goal>
</goals>
<configuration>
<descriptor>src/main/descriptors/src.xml</descriptor>
<finalName>${project.build.finalName}-src</finalName>
</configuration>
</execution>
</executions>
</plugin>
</plugins>

</build>

and run mvn install, this will execute the assembly plugin twice with different config.
How do I configure the equivalent of maven.war.src of war plugin in Maven 2.0?

<build>
    ...
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <configuration>
           <warSourceDirectory><!-- put the path of the directory --></warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
    ...
  </build>

How do I add main class in a generated jar’s manifest?
Configure the maven-jar-plugin and add your main class.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
      <archive>
        <manifest>
     <mainClass>com.mycompany.app.App</mainClass>
        </manifest>
      </archive>
    </configuration>
  </plugin>

What does the FATAL ERROR with the message “Class org.apache.commons.logging.impl.Jdk14Logger does not implement Log” when using the maven-checkstyle-plugin mean?
Checkstyle uses commons-logging, which has classloader problems when initialized within a Maven plugin’s container. This results in the above message – if you run with ‘-e’, you’ll see something like the following:

Caused by: org.apache.commons.logging.LogConfigurationException: org.apache.commons.logging.LogConfigurationException: Class org.apache.commons.logging.impl.Jdk14Logger does not implement Log

buried deep in the stacktrace.
The only workaround we currently have for this problem is to include another commons-logging Log implementation in the plugin itself. So, you can solve the problem by adding the following to your plugin declaration in your POM:

<project>
    ...
    <build>
      ...
      <plugins>
        ...
        <plugin>
          <artifactId>maven-checkstyle-plugin</artifactId>
          <dependencies>
            <dependency>
              <groupId>log4j</groupId>
              <artifactId>log4j</artifactId>
              <version>1.2.12</version>
            </dependency>
          </dependencies>
        </plugin>
      </plugins>
    </build>
    ...
    <reporting>
      ...
      <plugins>
        <!-- your checkstyle report is registered here, according to Maven documentation -->
      </plugins>
    </reporting>
  </project>

While this may seem a counter-intuitive way of configuring a report, it’s important to remember that Maven plugins can have a mix of reports and normal mojos. When a POM has to configure extra dependencies for a plugin, it should do so in the normal plugins section.
We will probably try to fix this problem before the next release of the checkstyle plugin.
UPDATE: This problem has been fixed in the SVN trunk version of the checkstyle plugin, which should be released very soon.
Plugins and Lifecycle, Sites & Reporting, Errors
How do I determine the stale resources in a Mojo to avoid reprocessing them?
This can be done using the following piece of code:

// Imports needed
  import org.codehaus.plexus.compiler.util.scan.InclusionScanException;
  import org.codehaus.plexus.compiler.util.scan.StaleSourceScanner;
  import org.codehaus.plexus.compiler.util.scan.mapping.SuffixMapping;

// At some point of your code
StaleSourceScanner scanner = new StaleSourceScanner( 0, Collections.singleton( “**/*.xml” ), Collections.EMPTY_SET );
scanner.addSourceMapping( new SuffixMapping( “.xml”, “.html” ) );
Set<File> staleFiles = (Set<File>) scanner.getIncludedSources( this.sourceDirectory, this.targetDirectory );

The second parameter to the StaleSourceScanner is the set of includes, while the third parameter is the set of excludes. You must add a source mapping to the scanner (second line). In this case we’re telling the scanner what is the extension of the result file (.html) for each source file extension (.xml). Finally we get the stale files as a Set<File> calling the getIncludedSources method, passing as parameters the source and target directories (of type File). The Maven API doesn’t support generics, but you may cast it that way if you’re using them.
In order to use this API you must include the following dependency in your pom:

<dependencies>
    <dependency>
      <groupId>org.codehaus.plexus</groupId>
      <artifactId>plexus-compiler-api</artifactId>
      <version>1.5.1</version>
    </dependency>
  </dependencies>

Is there a property file for plug-in configuration in Maven 2.0?
No. Maven 2.x no longer supports plug-in configuration via properties files. Instead, in Maven 2.0 you can configure plug-ins directly from command line using the -D arguement, or from the plug-in’s POM using the <configuration> element.
How do I determine which POM contains missing transitive dependency?
run “mvn -X”
How do I integrate static (x) html into my Maven site?
You can integrate your static pages in this several steps,

  • Put your static pages in the resources directory, ${basedir}/src/site/resources.
  • Create your site.xml and put it in ${basedir}/src/site. An example below:
<project name="Maven War Plugin">
    <bannerLeft>
      <name>Maven War Plugin</name>
      <src>http://maven.apache.org/images/apache-maven-project.png</src>
      <href>http://maven.apache.org/</href>
    </bannerLeft>
    <bannerRight>
      <src>http://maven.apache.org/images/maven-small.gif</src>
    </bannerRight>
    <body>
      <links>
        <item name="Maven 2" xhref="http://maven.apache.org/maven2/"/>
      </links>

<menu name=”Overview”>
<item name=”Introduction” xhref=”introduction.html”/>
<item name=”How to Use” xhref=”howto.html”/>
</menu>
${reports}
</body>
</project>

Link the static pages by modifying the <menu> section, create items and map it with the filename of the static pages.

<menu name="Overview">
    <item name="Introduction" xhref="introduction.html"/>
    <item name="How to Use" xhref="howto.html"/>
    <item name="<put-name-here>" xhref="<filename-of-the-static-page>"/>
  </menu>

How do I run an ant task twice, against two different phases?
You can specify multiple execution elements under the executions tag, giving each a different id and binding them at different phases.

<plugin>
         <artifactId>maven-antrun-plugin</artifactId>
         <executions>
           <execution>
              * <id>one</id>*
             <phase>generate-sources</phase>
             <configuration>
               <tasks>
                 <echo message="generate-sources!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"/>
               </tasks>
             </configuration>
             <goals>
               <goal>run</goal>
             </goals>
           </execution>

<execution>
*<id>two</id>*
<phase>package</phase>
<configuration>
<tasks>
* <echo message=”package!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!”/>*

</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>

Can a profile inherit the configuration of a “sibling” profile?
No. Profiles merge when their ID’s match – so you can inherit them from a parent POM (but you can’t inherit profiles from the same POM).
Inheritence and Interpolation, Plugins and Lifecycle, POM
How do I invoke the “maven dist” function from Maven 1.0, in Maven 2.0?
mvn assembly:assembly
See the Assembly Plugin documentation for more details.
General, Plugins and Lifecycle
How do I specify which output folders the Eclipse plugin puts into the .classpath file?

<build>
  ...
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-eclipse-plugin</artifactId>
          <configuration>
            <outputDirectory>target-eclipse</outputDirectory>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  ...
  </build>

What is a Mojo?
A mojo is a Maven plain Old Java Object. Each mojo is an executable goal in Maven, and a plugin is a distribution of one or more related mojos.
How to produce execution debug output or error messages?
You could call Maven with -X parameter or -e parameter. For more information, run:

mvn --help

Maven compiles my test classes but doesn’t run them?
Tests are run by the surefire plugin. The surefire plugin can be configured to run certain test classes and you may have unintentionally done so by specifying a value to ${test}. Check your settings.xml and pom.xml for a property named “test” which would like this:

  ...
    <properties>
      <property>
        <name>test</name>
        <value>some-value</value>
      </property>
   </properties>
    ...

Or

  ...
    <properties>
      <test>some-value</test>
   </properties>
    ...

How do I include tools.jar in my dependencies?
The following code includes tools.jar on Sun JDKs (it is already included in the runtime for Mac OS X and some free JDKs).

...
    <profiles>
      <profile>
        <id>default-tools.jar</id>
        <activation>
          <property>
            <name>java.vendor</name>
            <value>Sun Microsystems Inc.</value>
         </property>
       </activation>
        <dependencies>
          <dependency>
            <groupId>com.sun</groupId>
            <artifactId>tools</artifactId>
            <version>1.4.2</version>
            <scope>system</scope>
            <systemPath>${java.home}/../lib/tools.jar</systemPath>
         </dependency>
       </dependencies>
     </profile>
   </profiles>
    ...

I have a jar that I want to put into my local repository. How can I copy it in?
If you understand the layout of the maven repository, you can copy the jar directly into where it is meant to go. Maven will find this file next time it is run.
If you are not confident about the layout of the maven repository, then you can adapt the following command to load in your jar file, all on one line.

mvn install:install-file
    -Dfile=<path-to-file>
    -DgroupId=<group-id>
    -DartifactId=<artifact-id>
    -Dversion=<version>
    -Dpackaging=<packaging>
    -DgeneratePom=true

Where: <path-to-file>  the path to the file to load
<group-id>      the group that the file should be registered under
<artifact-id>   the artifact name for the file
<version>       the version of the file
<packaging>     the packaging of the file e.g. jar

This should load in the file into the maven repository, renaming it as needed.
How do I set up Maven so it will compile with a target and source JVM of my choice?
You must configure the source and target parameters in your pom. For example, to set the source and target JVM to 1.5, you should have in your pom :

...
    <build>
    ...
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.0.2</version>
          <configuration>
            <source>1.5</source>
            <target>1.5</target>
         </configuration>
       </plugin>
     </plugins>
    ...
   </build>
    ...

How can I use Ant tasks in Maven 2?

There are currently 2 alternatives:

Maven 2.0 Eclipse Plug-in

Plugins are great in simplifying the life of programmers; it actually reduces the repetitive tasks involved in the programming. In this article our experts will show you the steps required to download and install the Maven Plugin with your eclipse IDE.
Why Maven with Eclipse
Eclipse is an industry leader in IDE market, it is used very extensively in developing projects all around the world. Similarly, Maven is a high-level, intelligent project management, build and deployment tool provided by Apache’s software foundation group. Maven deals with application development lifecycle management.

Maven–Eclipse Integration makes the development, testing, packaging and deployment process easy and fast. Maven Integration for Eclipse provides a tight integration for Maven into the IDE and avails the following features:
· It helps to launch Maven builds from within Eclipse
· It avails the dependency management for Eclipse build path based on Maven’s pom.xml
· It resolves Maven dependencies from the Eclipse workspace withoutinstalling to local Maven repository
· It avails an automatic downloading of the required dependencies from the remote Maven repositories
· It provides wizards for creating new Maven projects, pom.xml or to enable Maven support on plain Java project
· It helps to search quickly for dependencies in Maven remote repositories
· It quickly fixes in the Java editor for looking up required dependencies/jars by the class or package name.
What do you Need?
1. Get the Eclipse Development Environment :
In this tutorial we are using the eclipse-SDK-3.3-win32, which can be downloaded fromhttp://www.eclipse.org/downloads/
2. Get Maven-eclipse-plugin-plugin :
It is available at http://mevenide.codehaus.org/maven-eclipse-plugin-plugin/

Download and Install Eclipse
First download and install the eclipse plugin on your development machine then proceed with the installation process of the eclipse-maven plugin.

A Maven 2.0 Repository: An Introduction

Maven repository Types:

  • Public remote external repository: This public external repository exists at ibiblio.org and maven synchronizes with this repository.
  • Private remote internal repository: We set up this repository and make changes in the maven’s pom.xml or settings.xml file to use this repository.
  • Local repository: This repository is maintained by the developer and stays on the developer’s machine. It is synchronous to the maven repository defined in the settings.xml file that exists in the .m2 directory at its standard location i.e. C:\Documents and Settings\Administrator. If no private internal repository is setup and not listed in the pom.xml or in the setting.xml then the local repository exists on the developer’s machine is synchronized with the public maven repository at ibiblio.org.

Advantages of having an internal private repository :

  • Reduces conflicts among likelihood versions.
  • To build first time it requires less manual intervention.
  • Rather than having several separate independent libraries it provides a single central reference repository for all the dependent software libraries.
  • It quickly builds the project while using an internal repository as maven artifacts are retrieved from the intranet server rather than retrieving from the server on internet.

Use cases for maven repository:

  • It creates two sub-repository inside the internal repository.
  • Downloads ibiblio-cache from ibiblio for artifacts and make it available publically. This synchronizes with external repository from ibiblio.
  • internal-maven-repository: used for internal artifacts of an organization. It contains unique artifacts for the organization and is not synchronized with any repository.
  • Alternatively, another sub-repository that is not at ibiblio can be created for artifacts. This does not synchronize with any external repository.
  • Browse the remote repository by using a web browser.
  • Search the artifacts in the repository.
  • Download code from version control and make changes in settings.xml to point to the internal repository and build without any manual intervention.
  • Install new version of the artifacts.
  • Import artifacts into the repository in bulk.
  • Export artifacts from the repository in bulk.
  • Setup the task to backup the repository automatically.

Criteria for choosing a maven repository implementation: In ideal condition a maven repository implementation should be:

  • Free and open source
  • Provide admin tools
  • Easy to setup and use
  • Provide backup facility
  • Able to create, edit and delete sub repositories.
  • Anonymous read only access and also access control facility.
  • Deployable in any standard web server such as Tomcat or Apache.
  • Issue tracker, forums and other independent source of information.
  • Active community developers make the product enhanced and bugs fixed.
  • Bulk import/export facility to move groups of artifacts into the repository and out of the repository.
  • Provide a repository browser: should be a web browser instead of the desktop application.

Shifting from Apache Ant to Maven

Maven is entirely a different creature from Ant. Ant is simply a toolbox whereas Maven is about the application of patterns in order to achieve an infrastructure which displays the characteristics of visibility, reusability, maintainability, and comprehensibility. It is wrong to consider Maven as a build tool and just a replacement for Ant.
Ant Vs Maven
There is nothing that Maven does that Ant cannot do. Ant gives the ultimate power and flexibility in build and deployment to the developer. But Maven adds a layer of abstraction above Ant (and uses Jelly). Maven can be used to build any Java application. Today JEE build and deployment has become much standardized. Every enterprise has some variations, but in general it is all the same: deploying EARs, WARs, and EJB-JARs. Maven captures this intelligence and lets you achieve the build and deployment in about 5-6 lines of Maven script compared to dozens of lines in an Ant build script.
Ant lets you do any variations you want, but requires a lot of scripting. Maven on the other hand mandates certain directories and file names, but it provides plugins to make life easier. The restriction imposed by Maven is that only one artifact is generated per project (A project in Maven terminology is a folder with a project.xml file in it). A Maven project can have sub projects. Each sub project can build its own artifact. The topmost project can aggregate the artifacts into a larger one. This is synonymous to jars and wars put together to form an EAR. Maven also provides inheritance in projects.
Maven : Stealing the show
Maven simplifies build enormously by imposing certain fixed file names and acceptable restrictions like one artifact per project. Artifacts are treated as files on your computer by the build script. Maven hides the fact that everything is a file and forces you to think and script to create a deployable artifact such as an EAR. Artifact has a dependency on a particular version of a third party library residing in a shared remote (or local) enterprise repository, and then publish your library into the repository as well for others to use. Hence there are no more classpath issues. No more mismatch in libraries. It also gives the power to embed even the Ant scripts within Maven scripts if absolutely essential.

Maven 2.0: Features

Maven is a high-level, intelligent project management, build and deployment tool provided by Apache’s software foundation group. Maven deals with application development lifecycle management. Maven was originally developed to manage and to minimize the complexities of building the Jakarta Turbine project. But its powerful capabilities have made it a core entity of the Apache Software Foundation projects. Actually, for a long time there was a need to standardized project development lifecycle management system and Maven has emerged as a perfect option that meets the needs. Maven has become the de- facto build system in many open source initiatives and it is rapidly being adopted by many software development organizations.
Maven was borne of the very practical desire to make several projects at Apache work in a consistence manner. So that developers could freely move between these projects, knowing clearly how they all worked by understanding how one of them worked.

If a developer spent time understanding how one project built it was intended that they would not have to go through this process again when they moved on to the next project. The same idea extends to testing, generating documentation, generating metrics and reports, testing and deploying. All projects share enough of the same characteristics, an understanding of which Maven tries to harness in its general approach to project management.
On a very high level all projects need to be built, tested, packaged, documented and deployed. There occurs infinite variation in each of the above mentioned steps, but these variation still occur within the confines of a well defined path and it is this path that Maven attempts to present to everyone in a clear way. The easiest way to make a path clear is to provide people with a set of patterns that can be shared by anyone involved in a project.

The key benefit of this approach is that developers can follow one consistent build lifecycle management process without having to reinvent such processes again. Ultimately this makes developers more productive, agile, disciplined, and focused on the work at hand rather than spending time and effort doing grunt work understanding, developing, and configuring yet another non-standard build system.
Maven: Features

  1. Portable: Maven is portable in nature because it includes:
    • Building configuration using maven are portable to another machine, developer and architecture without any effort
    • Non trivial: Maven is non trivial because all file references need to be relative, environment must be completely controlled and independent from any specific file system.
  2. Technology: Maven is a simple core concept that is activated through IoC container (Plexus). Everything is done in maven through plugins and every plugin works in isolation (ClassLoader). Plugings are downloaded from a plugin-repository on demand.

Maven’s Objectives:
The primary goal of maven is to allow the developers to comprehend the complete state of a project in the shortest time by using easy build process, uniform building system, quality project management information (such as change Log, cross-reference, mailing lists, dependencies, unit test reports, test coverage reports and many more), guidelines for best practices and transparent migration to new features. To achieve to this goal Maven attempts to deal with several areas like:

  • It makes the build process easy
  • Provides a uniform building system
  • Provides quality related project information
  • Provides guidelines related to development to meet the best goal.
  • Allows transparent migration to new features.

Introduction to Maven 2.0

Maven2 is an Open Source build tool that made the revolution in the area of building projects. Like the build systems as “make” and “ant” it is not a language to combine the build components but it is a build lifecycle framework. A development team does not require much time to automate the project’s build infrastructure since maven uses a standard directory layout and a default build lifecycle. Different development teams, under a common roof can set-up the way to work as standards in a very short time. This results in the automated build infrastructure in more stable state. On the other hand, since most of the setups are simple and reusable immediately in all the projects using maven therefore many important reports, checks, build and test animation are added to all the projects. Which was not possible without maven because of the heavy cost of every project setup.

Maven 2.0 was first released on 19 October 2005 and it is not backward compatible with the plugins and the projects of maven1. In December 2005, a lot of plugins were added to maven but not all plugins that exists for maven1 are ported yet. Maven 2 is expected to stabilize quickly with most of the Open Source technologies. People are introduced to use maven as the core build system for Java development in one project and a multi-project environment. After a little knowledge about the maven, developers are able to setup a new project with maven and also become aware of the default maven project structure. Developers are easily enabled to configure maven and its plugins for a project. Developers enable common settings for maven and its plugins over multiple projects, how to generate, distribute and deploy products and reports with maven so that they can use repositories to set up a company repository. Developers can also know about the most important plugins about how to install, configure and use them, just to look for other plugins to evaluate them so that they can be integrated in their work environment.

Maven is the standard way to build projects and it also provides various other characters like clearing the definition of the project, ways to share jars across projects. It also provides the easy way to publish project information (OOS).
Originally maven was designed to simplify the building processes in the Jakarta Turbine project. Several projects were there containing their own slightly different Ant build files and JARs were checked into CVS. An apache group’s tool that can build the projects, publish project information, defines what the project consists of and that can share JARs across several projects. The result of all these requirement was the maven tool that builds and manages the java-based-project.

Why maven is a great build tool? how does it differ from other Build tools?
Tell me more about Profiles and Nodes in Maven?
Tell me more about local repositories?
How did you configured local repositories in different environment (Development, Testing , Production etc)?
What is Transcend Dependencies in maven 2?
Did you write plugins in maven? if so what are they?
Why a matrix report is required during a new release?  How does this benefit QA Team?
What are pre-scripts and post-scripts in maven? Illustrate with an example?
What are the checklists for artifacts ? and what are the checklists for source code artifact?
Tell me the experience about Static Analysis Code?

Reference:
http://www.javabeat.net

Tagged : / / / / / / / / / / / / / / / / /