Tuesday, 30 August 2016

Python Question & Answers SET-02

Ques 21 : consider the following function and tell What does the * in *args do?
def print_two(*args):
    arg1, arg2 = args
    print "arg1: %r, arg2: %r" % (arg1, arg2)

    That tells Python to take all the arguments to the function and then put them in args as a list. It's like argv that you've been using, but for functions. It's not normally used too often unless specifically needed.

Ques 22 : what does seek(0) ?
 seek() function is dealing in bytes, not lines. The code seek(0) moves the file to the 0 byte (first byte) in the file.

Ques 23 : How does readline() know where each line is?
Inside readline() is code that scans each byte of the file until it finds a \n character, then stops reading the file to return what it found so far. The file f is responsible for maintaining the current position in the file after each readline() call, so that it will keep reading each line.

Ques 24 : How can the words.pop function change the words variable?
That's a complicated question, but in this case words is a list, and because of that you can give it commands and it'll retain the results of those commands. This is similar to how files and many other things worked when you were working with them.
def print_first_word(words):
    """Prints the first word after popping it off."""
    word = words.pop(0)
    print word
def print_last_word(words):
    """Prints the last word after popping it off."""
    word = words.pop(-1)
    print word
def sort_words(words):
    """Sorts the words."""
    return sorted(words)

Ques 25 : Why does "test" and "test" return "test" or 1 and 1 return 1 instead of True?
Python and many languages like to return one of the operands to their boolean expressions rather than just True or False. This means that if you did False and 1 you get the first operand (False) but if you do True and 1 your get the second (1). Play with this a bit.

Ques 26 : Is there any difference between != and <>?
Python has deprecated <> in favor of !=, so use !=. Other than that there should be no difference.

Ques 27 : What does += mean?
The code x += 1 is the same as doing x = x + 1 but involves less typing. You can call this the "increment by" operator. The same goes for -= and many other expressions you'll learn later.'

Ques 28 : What happens if multiple elif blocks are True?
Python starts and the top runs the first block that is True, so it will run only the first one.

Ques 29 : How do I tell if a number is between a range of numbers?
You have two options: Use 0 < x < 10 or 1 <= x < 10, which is classic notation, or use x in range(1, 10).

Ques 30 : How do you make a 2-dimensional (2D) list?
That's a list in a list like this: [[1,2,3],[4,5,6]]

Ques 31 : Why does for i in range(1, 3): only loop two times instead of three times?'
The range() function only does numbers from the first to the last, not including the last. So it stops at two, not three in the above. This turns out to be the most common way to do this kind of loop.

Ques 32 : What's' the difference between a for-loop and a while-loop?
A for-loop can only iterate (loop) "over" collections of things. A while-loop can do any kind of iteration (looping) you want. However, while-loops are harder to get right and you normally can get many things done with for-loops.

Ques 33 : What does exit(0) do?
On many operating systems a program can abort with exit(0), and the number passed in will indicate an error or not. If you do exit(1) then it will be an error, but exit(0) will be a good exit. The reason its backward from normal boolean logic (with 0==False is that you can use different numbers to indicate different error results. You can do exit(100) for a different error result than exit(2) or exit(1).

Ques 34 : What does stuff[3:5] do?
That extracts a "slice" from the stuff list that is from element 3 to element 4, meaning it does not include element 5. It's similar to how range(3,5) would work.

Ques 35 : What is the difference between a list and a dictionary?'
A list is for an ordered list of items. A dictionary (or dict) is for matching some items (called "keys") to other items (called "values").

Ques 36 : What would I use a dictionary for?
When you have to take one value and "look up" another value. In fact you could call dictionaries "look up tables."

Ques 37 : What would I use a list for?
Use a list for any sequence of things that need to be in order, and you only need to look them up by a numeric index.

Ques 38 : What if I need a dictionary, but I need it to be in order?
Take a look at the collections.OrderedDict data structure in Python. Search for it online to find the documentation.

Python Question & Answers SET-01

Ques 1 : What does #!/usr/bin/python mean?
You've probably already seen one of the following lines:
#!/bin/sh
#!/usr/bin/python
#!/usr/bin/python3
#!/usr/bin/env python
#!/usr/bin/perl
#!/usr/bin/php
#!/usr/bin/ruby

This is a shebang. It's a directive for your command line interpreter how it should execute a script.
For example, you have a file with this content:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
print(sys.version_info)
Now you can execute it via python3 yourFile.py. But alternatively, you can make it executable and simply type ./yourFile.py

By the way, you should use #!/usr/bin/env python for some reasons.

Ques 2 : Why is '#!/usr/bin/env python' supposedly more correct than just '#!/usr/bin/python'?
When do you

#!/usr/local/bin/python
You are specifying the location to the python executable in your machine, that rest of the script needs to be interpreted with.
You are pointing to python is located at /usr/local/bin/python

Consider the possiblities that in a different machine, python may be installed at /usr/bin/python or /bin/python in those cases, the above #! will fail.
For those cases, we get to call the env executable with argument which will determine the arguments path by searching in the $PATH and use it correctly.

Thus,
#/usr/bin/env python
Will figure out the correct location of python ( /usr/bin/python or /bin/python from $PATH) and make that as the interpreter for rest of the script.
- ( env is almost always located in /usr/bin/ so one need not worry what is env is not present at /usr/bin)

Ques 3 : How do I get my country's language characters into my file?
Just add at top of you file # -*- coding: utf-8 -*-

Ques 4 : If # is for comments, then how come # -*- coding: utf-8 -*- works?
Python still ignores that as code, but it's used as a kind of "hack" or workaround for problems with setting and detecting the format of a file. You also find a similar kind of comment for editor settings.

Ques 5 : How do I comment out multiple lines?
Put a # in front of each one.
 or use tripple quote as following:
 '''
    This is the multiple line
    comments
'''


Ques 6 : How to get results in decimal points using '/'?
use either following expression:
10/3.0 or 10.0/3 or 10.0/3.0

Ques 7 : What is the difference between %r and %s ?
Use the %r for debugging, since it displays the "raw" data of the variable, but the others are used for displaying to users.

Ques 8 : what will do the folowing code ?
print "." * 10
it will print "." 10 times.

Ques 9 : what will be output of following script?
#!/usr/bin/python

print "mukesh"
print "kumar"
############
print "mukesh",
print "kumar"

Ques 10 : I tried putting Chinese (or some other non-ASCII characters) into these strings, but %r prints out weird symbols.
Use %s to print that instead and it'll work.

Ques 11 : Why do the \n newlines not work when I use %r?
That's how %r formatting works; it prints it the way you wrote it (or close to it). It's the "raw" format for debugging.

Ques 12 : What's the difference between input() and raw_input()?
The input() function will try to convert things you enter as if they were Python code, but it has security problems so you should avoid it.

Ques 13 : When my strings print out there's a u in front of them, as in u'35'.
That's how Python tells you that the string is Unicode. Use a %s format instead and you'll see it printed like normal.

Ques 14 : pydoc command ?
In Terminal where you normally run python to run your scripts, type pydoc raw_input. Read what it says. If you're on Windows try python -m pydoc raw_input instead.
exp: pydoc sys

Ques 15 : output of the command print "How old are you?" , raw_input()
>>> print "How old are you?" , raw_input()
How old are you? 12
12
>>>

Ques 16 : Are the command line arguments strings?
Yes, they come in as strings, even if you typed numbers on the command line. Use int() to convert them just like with int(raw_input()).

Ques 17 : What does mean the following file reading and writing related commmands.
close -- Closes the file. Like File->Save.. in your editor.
read -- Reads the contents of the file. You can assign the result to a variable.
readline -- Reads just one line of a text file.
truncate -- Empties the file. Watch out if you care about the file.
write('stuff') -- Writes "stuff" to the file.

Ques 18 : What does 'w' mean?
It's really just a string with a character in it for the kind of mode for the file. If you use 'w' then you're saying "open this file in 'write' mode," thus the 'w' character. There's also 'r' for "read," 'a' for append, and modifiers on these.'

Ques 19 : What modifiers to the file modes can I use?
The most important one to know for now is the + modifier, so you can do 'w+', 'r+', and 'a+'. This will open the file in both read and write mode, and depending on the character use position the file in different ways.

Ques 20 : Does just doing open(filename) open it in 'r' (read) mode?
Yes, that's the default for the open() function.

Friday, 24 June 2016

Apache Server Interview Questions & Answers

Q. What is the Apache server ? 
  •  Apache Web Server is one of the most secure, powerful and popular open source HTTP Server which is written in portable C. It can be used to host anything from personal web sites to corporate domains.
  • It mostly serves static content by itself, but there are many add-on modules (some of which come with Apache itself) that let it modify the content and also serve dynamic content written in Perl, PHP, Python, Ruby, or other languages.       
Q. How to check the version of Apache server ?
    First, use the rpm command to check whether Apache installed or not. If it’s installed, then use
    httpd -v command to check its version.
    # rpm -qa | grep httpd

    httpd-devel-2.2.15-29.el6.centos.i686
    httpd-2.2.15-29.el6.centos.i686
    httpd-tools-2.2.15-29.el6.centos.i686

    # httpd -v

    Server version: Apache/2.2.15 (Unix)
    Server built:   Aug 13 2013 17:27:11

    In ubuntu linux try following command.
    mukesh@ubuntu:~$ apache2 -v
    Server version: Apache/2.2.22 (Ubuntu)
  
Q.  On which version of apache you have worked ?
    httpd-2.2.3

Q. What is location of log files in Apache server ?
    /var/log/httpd/access_log
    /var/log/httpd/error_log
  
    In Ubuntu:
    /var/log/apache2/other_vhosts_access.log
    /var/log/apache2/error.log
    /var/log/apache2/access.log
  
Q. Apache runs as which user? and location of main config file?
   Apache runs with the user "nobody" and httpd daemon. Apache main configuration file:
   /etc/httpd/conf/httpd.conf (CentOS/RHEL/Fedora)
   /etc/apache2.conf  or /etc/apache2/apache2.conf (Ubuntu/Debian)
 
Q. On which port Apache listens http and https both?
   By default Apache runs on http port 80 and https port 443 (for SSL certificate). You can also use
   netstat command to check ports.
    [root@mukesh ~]# netstat -antp | grep http

    tcp        0      0 :::80                       :::*                        LISTEN      1076/httpd        
    tcp        0      0 :::443                      :::*                        LISTEN      1076/httpd
  
Q. Where you can find all configuration directories of Apache Web Server?
   /etc/httpd/conf/ (CentOS/RHEL/Fedora)
   /etc/apache2/     (Ubuntu/Debian)
 
Q. You see a error "connection reset by peer" in error log. What could be the reason for this?
   If the end user terminates the connection when the server response was being formed or was being
   transferred, we see "connection reset by peer" in the error log.

Q. What is virtual hosting?
     Virtual hosting is a method for hosting multiple domain names on a server using a single IP
     address. Virtual hosting allows one server to share its resources, such as memory and processor
     cycles, in order to use its resources more efficiently.

   Sample VirtualHost:
    <VirtualHost *:80>
       ServerAdmin webmaster@dummy-host.example.com
       DocumentRoot /www/docs/dummy-host.example.com
       ServerName dummy-host.example.com
       ErrorLog logs/dummy-host.example.com-error_log
       CustomLog logs/dummy-host.example.com-access_log common
    </VirtualHost>

    Where :
    ServerAdmin  : Its usually the email address of the website owner, where the error or notification
                               can be sent.
    DocumentRoot : location where the web files are located in the server(Necessary).
    ServerName   : Its the domain name which you want to access from your web
                               browser(Necessary).
    ErrorLog     : Its the location of the log file where all the domain related logs are being recorded.


Q. What are the types of virtual hosts ?
    There are two types of virtual host name-based and IP-based.

    Name-based virtual host means that multiple names are running on each IP address.
    IP-based virtual host means that a different IP address exists for each website served. Most
    configurations are named-based because it only requires one IP address.
  
Q. If you have only one IP address, but you want to host two web sites on your server.
     What will you do?
     In this case I will use Name Based Virtual hosting.
  
    ServerName 10.111.203.25
    NameVirtualHost *:80
    <VirtualHost *:80>
        ServerName web1.test.com
        DocumentRoot /var/www/html/web1
    </VirtualHost>

    <VirtualHost *:80>
        ServerName web2.test2.com
        DocumentRoot /var/www/html/web2
    </VirtualHost>

  
Q. You need to install Apache web server on Ubuntu server. How can you download and install the
     Apache2 package?
     sudo apt-get install Apache2
         OR
     sudo aptitude install Apache2
     aptitude is known to sort out program dependencies in a better way.


Q. What are Iptables?
     Iptables are user space application programs that allow a system administrator to configure the
     tables provided by the Linux kernel firewall.

Q. Which privilege is required to operate iptables?
     Iptables require root user privilege for execution, otherwise they fail to function.

Q. What type of ports are 80 and 443?
     The port 80 is a regular port while port 443 is a secure port.

Q. How to restart Apache web server ?
    /etc/init.d/httpd  restart  (CentOS/RHEL/Fedora)
    service httpd restart        (CentOS/RHEL/Fedora)
  
    sudo /etc/init.d/apache2 restart (Ubuntu/Debian)

Q. What is the difference between a restart and a graceful restart of a web server?
    During a normal restart, the server is stopped and then started, causing some requests to be lost.
    A graceful restart allows Apache children to continue to serve their current requests until they can
    be replaced with children running the new configuration.
  
Q. What is DocumentRoot ?
     It is a location of web files which are accessible by clients. The default DocumentRoot of Apache
     is /var/www/html or /var/www. This can be changed to anything, by setting up "DocumentRoot"
     in a virtual host of configuration file of domain.
  
Q. How to change default Apache Port and How Listen Directive works in Apache?
    There is a directive "Listen" in httpd.conf file which allows us to change the default Apache port.
    With the help of Listen directive we can make Apache listen on different port as well as different
    interfaces.

   To change the Apache default port, please open your Apache main configuration file httpd.conf or
   apache2.conf or ports.conf(ubuntu/Debian) file with VI editor.
    [root@mukesh ~]# vi /etc/httpd/conf/httpd.conf
    [root@mukesh ~]# vi /etc/apache2/apache2.conf
    [root@mukesh ~]# vi /etc/apache2/ports.conf
  
    Search for the word "Listen", comment the original line and write your own directive below that
     line as following.
    # Listen 80
        OR
    Listen 8080
    Listen 172.16.16.1:8080
    Save the file and restart the web server.
    [root@mukesh ~]# service httpd restart
    [root@mukesh ~]# service apache2 restart
  
Q. Can we have two Apache Web servers on a single machine?
     Yes, we can run two different Apache servers at one time on a Linux machine, but the condition
     for that is they should listen on different ports and we can change the ports with Listen directive
     of  Apache.
 
Q. What is the difference between <Location> and <Directory>?
    <Location> is used to set element related to the URL / address bar of the web server.
    <Directory> refers that the location of file system object on the server

Q. If you have added "loglevel Debug" in httpd.conf file, than what will happen?
   It will give you more information in the error log in order to debug a problem.
   With the help of Loglevel Debug option, we can get/log more information in the error logs which
    helps us to debug a problem.
  
======================Some More Questions ==============================

Q. What type of IP is required for Apache Web Server to host our website?
    a DSL connection with a static IP then we can use the Apache web server to host our website.

Q. While installing Apache HTTP server, do we need SSL and PHP support?
   Yes, SSL and PHP support is required to install Apache HTTP server.

Q. Is there any size limit for URL rewriting and aliasing in Apache web server?
   Apache has no fixed limit on the numbers of Aliases and Redirects which may be declared in the
   config files.

Q. Create a new user file and add a user with username "test" and password "test".
    htpasswd -c /usr/local/etc/httpd/users test
    User will be prompted to provide the password. The -c argument tells htpasswd to create new file
    for users.
    To add more users, -c argument can be omitted.

Q. What do you mean by a valid ServerName directive?
    The DNS system is used to associate IP addresses with domain names. The value of ServerName is
     returned when the server generates a URL. If you are using a certain domain name, you must
     make sure that it is included in your DNS system and will be available to clients visiting your site.

Q. What is the use of mod_perl module?
    mod_perl scripting module to allow better Perl script performance and easy integration with the
    Web server.

Q. Can you record the MAC (hardware) address of clients that access your server.
    No

Q. Can you record all the cookies sent to your server by clients in Web Server logs?
    Yes, add following lines in httpd.conf file.
    CustomLog logs/cookies_in.log "%{UNIQUE_ID}e %{Cookie}i" CustomLog
    logs/cookies2_in.log "%{UNIQUE_ID}e %{Cookie2}i"

Q. Can we do automatically roll over the Apache logs at specific times without having to shut down
     and restart the server?
    Yes
    Use CustomLog and the rotatelogs programs
    Add following line in httpd.conf file. CustomLog "| /path/to/rotatelogs/path/to/logs/access_log.%Y-%m-%d 86400" combined

Q. What we can do to find out how people are reaching your site?
     Add the following effector to your activity log format. %{Referer}

Q. Can I serve content out of a directory other than the DocumentRootdirectory?
    Yes, by using "Alias" we can do this.

Q. If you have to more than one URL map to the same directory but you don't have multiple Alias
     directives. What you will do?
    In this case I will use “AliasMatch” directives.
    The AliasMatch directive allows you to use regular expressions to match arbitrary patterns in
     URLs and map anything matching the pattern to the desired URL.

Q. I want to stop people using my site by Proxy server. Is it possible?
    <Directory proxy:http://www.test.com/myfiles>
        Order Allow,Deny
        Deny from all
        Satisfy All
    </Directory>

Q. What is mod_evasive module?
    mod_evasive is a third-party module that performs one simple task, and performs it very well. It detects when your site is receiving a Denial of Service (DoS) attack, and it prevents that attack from doing as much damage. mod_evasive detects when a single client is making multiple requests in a short period of time, and denies further requests from that client. The period for which the ban is in place can be very short, because it just gets renewed the next time a request is detected from that same host.

Q. How to enable PHP scripts on your server?
   If you have mod_php installed, use AddHandler to map .php and .phtml files to the PHP handler.
   AddHandler application/x-httpd-php .phtml .php

Q. Which tool you have used for Apache benchmarking?
    ab (Apache bench)
    ab -n 1000 -c 10 http://www.test.com/test.html

Q. Can we cache files which are viewed frequently?
    Yes we can do it by using mod_file_cache module.
    CacheFile /www/htdocs/index.html

Q. Can Apache be secured with TCP wrappers?
    No, It can’t be secured with the TCP wrappers since it doesn’t support libwrap.a library of Linux.

Q. Can we host files in different folder and what is Alias directive?
   Yes, this can be achieved by Alias directive in the main Apache configuration file. Alias directive
    maps resources in File system, it takes a URL path and substitute it with a file or directory path on
    the system with is set up to redirect.
   To use Alias directive, Its the part of mod_alias module of Apache. The default syntax of Alias
    directive is:

    Alias /images /var/data/images/
  
    Here in above example, /images url prefix to the /var/data/images prefix that mean clients will query for "http://www.test.com/images/sample-image.png" and Apache will pick up the "sample-image.png" file from /var/data/images/sample-image.png on the server. It’s also known as URL Mapping.

Q. What do you understand by "DirectoryIndex"?
   DirectoryIndex is the name of first file which Apache looks for when a request comes from a domain. For Example: www.test.com is requested by the client, so Apache will go the document root of that website and looks for the index file (first file to display). The default setting of DirectoryIndex is .html index.html index.php, if you have different names of your first file, you need to make the changes in httpd.conf or apache2.conf for DirectoryIndex value to display that to your client browser.


Q. How to disable Directory listing when an index file is missing?
   If, the main index file is missing in the website root directory, then the Apache will lists all the contents like files and folder of the website on the browser instead of Main website pages. To stop Apache directory listing, you can set the following rule in the main configuration file globally or in .htaccess file for a particular website.
    <Directory /var/www/html>
       Options -Indexes
    </Directory>

Q. What do you understand by MPM in Apache?
   MPM stands for Multi Processing Modules, actually Apache follows some mechanism to accept and complete web server requests.

Q. What is the difference between Worker and Prefork MPM?
   Both MPMs, Worker and prefork has their own mechanism to work with Apache. It totally depends on you that in which mode you want to start your Apache.
   Basic difference between Worker and MPM is in their process of spawning the child process. In the Prefork MPM, a master httpd process is started and this master process starts manages all other child processes to serve client requests. Whereas, In the worker MPM one httpd process is active, and it uses different threads to serve client requests.
   Prefork MPM uses multiple child processes with one thread each, where worker MPM uses multiple child processes with many threads each.Connection handling in the Prefork MPM, each process handles one connection at a time, whereas in the Worker mpm each thread handles one connection at a time.Memory footprints Prefork MPM Large memory footprints, where Worker has smaller memory footprints.

Q. What is the use of LimitRequestBody and how to put limit on your uploads?
   LimitRequestBody directive is used to put a limit on the upload size.
   For example: I want to put limits of 100000 Bytes in the folder /var/www/html/mks/uploads. So, you need to add following directive in Apache
    configuration file.
    <Directory "/var/www/html/mks/uploads">
        LimitRequestBody 100000
    </Directory>

Q. What is mod_perl and mod_php?
    mod_perl is an Apache module which is compiled with Apache for easy integration and to
    increase the performance of Perl scripts.
    mod_php is used for easy integration of PHP scripts by the web server, it embeds the PHP interpreter inside the Apache process. Its forces Apache child process to use more memory and works with Apache only but still very popular.

Q. What is the use of mod_ssl and how SSL works with Apache?
   Mod_ssl package is an Apache module, which allows Apache to establish its connection and transfer all the data in a secure encrypted environment. With the help of SSL certificates, all the Login details and other important secret details get transferred in an encrypted manner over the Internet, which prevents our data from Eavesdropping and IP spoofing.

Shell Script To Read a Text File Line by Line

Here i am going to show you two methods of reading a text file with shell script. For our entire exercise consider a demo.txt file which having the following contents .

mukesh@ubuntu:~/Desktop$ cat demo.txt
this is line one
Hello everyone\\ how are you.
this is\ line third with back slash.
This is sample last line.


Method 01: cat file then read line

#! /bin/bash

# Script name : readFile.sh
# Description : Script will read demo.txt which is in current directory.

cat demo.txt | while read LINE
do
        echo $LINE
done


Output:
this is line one
Hello everyone\ how are you.
this is line third with back slash.
This is sample last line.



Method2: Redirecting file into while loop and then read line.

#! /bin/bash

# Script name : readFile.sh
# Description : Script will read demo.txt which is in current directory.

while read LINE
do
    #do what you want to $LINE
    echo $LINE
done < demo.txt

Output:
this is line one
Hello everyone\ how are you.
this is line third with back slash.
This is sample last line.


Note:
If you observe above both the program you will notice in the output back slash "\" is in not printing.
This is happening because program treating "\" as a special character. To avoid this problem use -r while reading line as in the following script.

#!/bin/bash
# Script name : readFile.sh
# Description : Script reading the demo.txt file line by line and treating backslash as a normal character.


if [ $# -ne 1 ]
then
    echo "Usage : $0 filename "
    echo "Give the file name as command line argument."
    echo "Ex.: $0 demo.txt"
    exit 1
fi

filename="$1"

while read -r LINE
do
    echo "$LINE"
done < "$filename"


Output:
this is line one
Hello everyone\\ how are you.
this is\ line third with back slash.
This is sample last line.


where :
-r  Do not treat a backslash character in any special way.
    Consider each backslash to be part of the input line.
   
Related Posts Plugin for WordPress, Blogger...