Wednesday, December 26, 2018

NBD (Network Block Device) kernel module - Build on RHEL 7

Prepare Directory Structure

mkdir -p ~/rpmbuild/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS}
echo '%_topdir %(echo $HOME)/rpmbuild' > ~/.rpmmacros

Download Kernel Source

cd ~/rpmbuild
wget http://vault.centos.org/7.4.1708/os/Source/SPackages/kernel-3.10.0-693.el7.src.rpm

Install Kernel Source

cd ~/rpmbuild/SOURCES
rpm -ivh kernel-3.10.0-693.el7.src.rpm

BUILD

cd ~/rpmbuild/SPECS
rpmbuild -bp --target=$(uname -m) kernel.spec
cd ~/rpmbuild/BUILD/kernel-3.10.0-693.el7/linux-3.10.0-693.el7.x86_64
make menuconfig   #Device Driver -> Block devices -> Set “M” On “Network block device support”
make prepare && make modules_prepare && make
make M=drivers/block -j8
modinfo drivers/block/nbd.ko

INSTALL

cd ~/rpmbuild/BUILD/kernel-3.10.0-693.el7/linux-3.10.0-693.el7.x86_64
cp drivers/block/nbd.ko /lib/modules/3.10.0-693.el7.x86_64/extra/ 
depmod -a && sudo modprobe nbd

Monday, June 18, 2012

Random Image Display

Many times we get bored without any reason.. if this is one of those moments then don't worry, coding will make the moment a little bit lighter;

We'll create a webpage that'll display a random image on each visit(refresh) to the page. PHP will be the language in which we'll create the webpage.

First of all, the RandomImage class,

class RandomImage {
    private $ImageDir;
    private $FileList;
   
    /* this is list of extension which will be allowed to display as an image */
    private $FilterList = array("jpg", "jpeg", "gif", "png");
   
    /* constructor */
    public function __construct($initDir) {
        $this->ImageDir = $initDir;
        $this->FileList = array();
    }
   
    /* function to filter out files based on extension */
    private function IsFileOkToShow($file){
        $isOk = false;
        /* check if file extension is not in the filter list */
        $matched = false;
        $fileExt = pathinfo($file, PATHINFO_EXTENSION);
        foreach ((array)$this->FilterList as $ext) {
            if(strcasecmp($fileExt, $ext) == 0) {
                $matched = true;
                break;
            }
        }
        if($matched) {
            $isOk = true;
        }
   
        return $isOk;
    }
   
    /* this function will scan through all the directories(in recursive manner)
     * and build the list of files in all directories.
     */
    private function buildImageList($dir) {
        if($handle = opendir($dir)) {
            while(false !== ($entry = readdir($handle))) {
                if($entry == '.' || $entry == '..') {
                    continue;
                }
                $fullPath = $dir.'/'.$entry;
                if(is_dir($fullPath)) {
                    $this->buildImageList($fullPath);
                } else {
                    if($this->IsFileOkToShow($fullPath)) {
                        array_push($this->FileList, $fullPath);
                    }
                }
            }
            closedir($handle);
        }
    }
   
    /* public function to return a random file */
    public function Get() {
        $this->buildImageList($this->ImageDir);
        srand((float)microtime()*1000000);
        $fileCount = count($this->FileList);
        if($fileCount > 0) {
            $randomIndex = rand(0, $fileCount -1);
            return $this->FileList[$randomIndex];
        } else {
            return "foo!";
        }
    }
}

This class is very simple and it has only one public function Get(). Calling the Get() function on an object of this class will scan through the directory and return a random file from it.

Upon receiving the filename, we'll pass this file to 'src' attribute of <img> tag, in order to display it.

<!--  html code to display the image -->
<html>
<head><title>Ignorance is bliss!</title></head>
<body>
<?php
    $image = new RandomImage("PATH_TO_IMAGE_FOLDER");
?>
    <img src="<?php echo $image->Get();?>">
<?php
?>
</body>
</html>

Thats all!
Download the attached source code and start clicking on refresh button!

Sunday, January 22, 2012

Re-build a Binary Tree from post-order and pre-order traverse

This is a well known problem, if we have two traversals of a binary tree, like post-order and pre-order etc.
we have to build a binary tree from these. Here is an example with post-order and pre-order case.


import java.util.Arrays;
import java.util.List;

public class ReConstructBTree {

/**
* @param args
*/
public static void main(String[] args) {

String[] pre = "I Q J H L E M V O T S B R G Y Z K C A & F P N U D W X".split("\\s");
String[] post = "H E M L J V Q S G Y R Z B T C P U D N F W & X A K O I".split("\\s");

List preList = Arrays.asList(pre);
List postList = Arrays.asList(post);

BTree tree = reBuildTree(preList, postList);

tree.inOrder(tree); //print in-order
System.out.println();
tree.postOrder(tree);//print post order to re-check
System.out.println();
tree.preOrder(tree);//print pre order to re-check
}

private static BTree reBuildTree(List preList, List postList) {
BTree tree = null;

if(preList.size() != 0 && postList.size() != 0) {
tree = new BTree();
String val = preList.get(0);
tree.val = val;

if(preList.size() > 1 && postList.size() > 1) {
int postOrderPos = postList.indexOf(preList.get(1));
int preOrderPos = preList.indexOf(postList.get(postList.size()-2));

//find the two sub set of the list from pre-order
List leftPreOrder = preList.subList(1, preOrderPos);
List rightPreOrder = preList.subList(preOrderPos, preList.size());

//find the two sub set of the list from post-order
List leftPostOrder = postList.subList(0, postOrderPos+1);
List rightPostOrder = postList.subList(postOrderPos+1, postList.size()-1);

tree.left = reBuildTree(leftPreOrder, leftPostOrder);
tree.right = reBuildTree(rightPreOrder, rightPostOrder);
}
}

return tree;
}

static class BTree {
String val;
BTree left;
BTree right;

void inOrder(BTree tree) {
if(tree.left != null)
inOrder(tree.left);
System.out.print(tree.val+" ");
if(tree.right != null)
inOrder(tree.right);
}

void preOrder(BTree tree) {
System.out.print(tree.val+" ");
if(tree.left != null)
preOrder(tree.left);
if(tree.right != null)
preOrder(tree.right);
}

void postOrder(BTree tree) {
if(tree.left != null)
postOrder(tree.left);
if(tree.right != null)
postOrder(tree.right);
System.out.print(tree.val+" ");
}

}
}

Sunday, March 6, 2011

WMP Hotkeys (a plug-in for Windows Media Player)

I like Windows Media Player and use it for all type of media playback but I am not very fond of key combination that WMP uses for Forward/Rewind etc. For that matter, I like VLC player's hotkeys, so I decided to bring some of the VLC player's, keyboard action to WMP.
The result is a WMP plug-in, that is hosted here.

Try it out and let me know what you guys think of it.

Note: I have tested this plug-in only with Windows Media Player 12(x86) on Windows 7(x64) system.

Monday, June 2, 2008

JAXP (Java API for XML Parsing)

The Java API for XML Processing (JAXP) makes it easy to process
XML data using applications written in the Java programming language. JAXP
leverages the parser standards SAX (Simple API for XML Parsing) and DOM
(Document Object Model) so that you can choose to parse your data as a stream
of events or to build a tree-structured representation of it. The latest versions of
JAXP also support the XSLT (XML Stylesheet Language Transformations) standard,
giving you control over the presentation of the data and enabling you to
convert the data to other XML documents or to other formats, such as HTML.
JAXP also provides namespace support, allowing you to work with schemas that
might otherwise have naming conflicts.

Designed to be flexible, JAXP allows you to use any XML-compliant parser
from within your application. It does this with what is called a pluggability layer, which allows you to plug in an implementation of the SAX or DOM APIs. The
pluggability layer also allows you to plug in an XSL processor, which lets you
transform your XML data in a variety of ways, including the way it is displayed.

There are different type of parser available to parse the XML...
A. Event based parser (The SAX API)
B. Tree based parser (DOM)

The SAX API
The Simple API for XML (SAX) defines an API for an event-based
parser. Being event-based means that the parser reads an XML document from
beginning to end, and each time it recognizes a syntax construction, it notifies
the application that is running it. The SAX parser notifies the application by calling
methods from the ContentHandler interface. For example, when the parser
comes to a less than symbol (“<”), it calls the startElement method; when it
comes to character data, it calls the characters method; when it comes to the
less than symbol followed by a slash (“so on. To illustrate, let’s look at part of the example XML document from the
first section and walk through what the parser does for each line. (For simplicity,
calls to the method ignorableWhiteSpace are not included.)

Consider the following XML to parse.

<pricelist>
<coffee>
<name>Mocha Java </name>
<price>11.95</price>
</coffee>
<coffee>
<name>Sumatra</name>
<price>12.50</price>
</coffee>
</pricelist>

This would be parse as below.
<priceList> [parser calls startElement]
<coffee> [parser calls startElement]
<name>Mocha Java</name> [parser calls startElement,
characters, and endElement]
<price>11.95</price> [parser calls startElement,
characters, and endElement]
</coffee> [parser calls endElement]

The default implementations of the methods that the parser calls do nothing, so
you need to write a subclass implementing the appropriate methods to get the
functionality you want. For example, suppose you want to get the price per
pound for Mocha Java. You would write a class extending DefaultHandler (the
default implementation of ContentHandler) in which you write your own implementations
of the methods startElement and characters.

You first need to create a SAXParser object from a SAXParserFactory object. You
would call the method parse on it, passing it the price list and an instance of
your new handler class (with its new implementations of the methods startElement
and characters). In this example, the price list is a file, but the parse method can also take a variety of other input sources, including an InputStream object, a URL, and an InputSource object.

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse("priceList.xml", handler);

The result of calling the method parse depends, of course, on how the methods
in handler were implemented. The SAX parser will go through the file
priceList.xml line by line, calling the appropriate methods. In addition to the
methods already mentioned, the parser will call other methods such as startDocument, endDocument, ignorableWhiteSpace, and processingInstructions,
but these methods still have their default implementations and thus do nothing.

The following method definitions show one way to implement the methods
characters and startElement so that they find the price for Mocha Java and
print it out. Because of the way the SAX parser works, these two methods work
together to look for the name element, the characters “Mocha Java”, and the
price element immediately following Mocha Java. These methods use three
flags to keep track of which conditions have been met. Note that the SAX parser
will have to invoke both methods more than once before the conditions for printing
the price are met.

public void startElement(..., String elementName, ...){
if(elementName.equals("name")){
inName = true;
} else if(elementName.equals("price") && inMochaJava ){
inPrice = true;
inName = false;
}
}
public void characters(char [] buf, int offset, int len) {
String s = new String(buf, offset, len);
if (inName && s.equals("Mocha Java")) {
inMochaJava = true;
inName = false;
} else if (inPrice) {
System.out.println("The price of Mocha Java is: " + s);
inMochaJava = false;
inPrice = false;
}
}


Monday, May 5, 2008

Insertion Sort

Insertion sort is very simple sorting algorithm. It is an efficient algorithm to sort small number of elements.

Insertion sort works the way many people sort a hand of playing card.We then remove one card at a time from the table and insert it into the
correct position in the left hand. To find the correct position for a card, we compare
it with each of the cards already in the hand, from right to left, as illustrated in
Figure 2.1. At all times, the cards held in the left hand are sorted, and these cards
were originally the top cards of the pile on the table[1].

In insertion sort we start with the second element of array and insert this element at the correct position into the sorted subarray to the left of that element. We take next elements and insert this element at the correct position into the left sorted subarray. We continue in this manner until whole array is sorted(we reached at the end of array). We insert any element into left sorted array, at correct position by comparing the element by the elements of left sorted subarrray.

Now, i will show the procedure of Insertion Sort with the help of diagram and then i will make a C function to perform insertion sort on the array of integer.

Suppose we have an array of six elements A[ ] = { 5,2,4,6,1,3 }

 InsertionSort

This diagram shows the execution of insertion sort on a typical array. This diagram is self explanatory. On the first iteration second element 2 is compaired with first element 5, as 5 is the only element in the left sorted subarray(array with only one element is sorted in itself). Since 5 is greater than 2 hence 5 is shifted toward one place right and 2 is placed before 5(previous place occupied by element 5). Now after first iteration there are two elements on left sorted subarray. Now the 3rd element 4 is placed at the proper position into the left sorted subarray. The whole sorting algorithm continue in this fashion untill no element is left in right unordered array(see figure). When we shift more than one element during the execution , we shift the element toward right in the order of decreasing index value i.e. the element with the highest index value(in left sorted subarray) is shifted first then element with next lower index and so on. The order of shifting is shown in the figure with the help of thickness of arrow. The element with the thinest arrow is shifted first then next element with relativaly high thickness and so on.

Now I implement Insertion Sort in C language.


/* Insertion Sort Function
Created by: Abhinav Kushwaha*/

void InsertionSort(int *num, int length){
int i=0,j=0,key;
for(i=1;i<length;i++){
key=num[i]; //store the key value so that we can place it at proper position
j=i-1; //the upper bound of left sorted array will be i-1
while((j>=0)&&(key<num[j])){
num[j+1]=num[j]; //shift the elements of sorted left subarray toward one place right
j–;
}
num[j+1]=key; //after shifting the elements we place the key element at proper position
}
}


This function takes Array and its Length as parameter and perform insertion sort on that array. Since array is passed by reference the change in array in this function is also reflected in calling function.The outer for loop covers the right unordered subarray and inner while loop covers the left sorted subarray. key is variable that holds the element value which is currently under consideration(element in shaded box in the diagram). j variable span over left sorted subarray. In while loop we check where we have to insert the ‘key’ variable(the element under process).





while((j>=0)&&(key<num[j])){
num[j+1]=num[j];
j–;
}


The condition((j>=0) ) in while loop checks if the lower bound of array is reached or not. The condition((key<num[j])) in while loop ensure that comparision is made until procesing element(key) is less that the comparing element is left subarray.



The statement ( num[j+1]=num[j]; ) shifts the elements of left subarray to right, to make room for insertion of key element. After shifting of elements of left subarray thw while loop terminates , now statement ( num[j+1]=key; ) insert(store) the key element at the proper position.

Wednesday, February 27, 2008

Recursion

Recursion is just another subtle topic in any language paradigm. For some people recursion is breath taker and for some its just a handy tool for write a small code. At first Recursion seems complex to grasp, but after some practice we can master this technique very easily.

A simple definition of Recursion may be ” Recursion is a technique of defining the program in the terms of itself.”

Lets start with a simple example.

Any problem that can be subdivided in the term of itself can be solved with recursion. For example here is a recurrence formula for calculating the nth power of a ;


In this case for any value other than n = 0, we can calculate the nth power of a by multiplying the number by (n-1)th power of that number i.e an = a*an-1.

In recursion we always have to ensure a terminating condition. In absence of terminating condition the program will continue to call it self ever and ever again(forever).

In this case n=0 is terminating condition and we know its value (its 1).

Equipped with this knowledge, lets create a function for calculating nth power of a number. For simplicity assume that the number (a) is a Integer.

Here is power function in C .

int power(int base, int degree){
if(degree == 0){
return 1;
}else{
return (base*power(base, degree-1));
}
}

In this example for 2nd line test for terminating condition, otherwise 5th line calculate a*an-1 .