24 May 2012

Creating a custom Dojo Widget with Dojo 1.7


Dojo widgets can be placed under dojo root directory.
Sample directory strcuture for creating a sample widget is like

dojo
  - dijit
  - dojo
  - dojox
  - mywidget
      - TestWidget.js
      - widget.tmpl



Sample widget code ( TestWidget.js)

require (
// Define the dependancies
    [
        "dojo/_base/declare", "dojo/parser", "dojo/ready",
        "dijit/_WidgetBase",  "dijit/_TemplatedMixin",
        "dijit/_WidgetsInTemplateMixin",
        "dijit/layout/BorderContainer",
        "dijit/layout/AccordionContainer",
        "dijit/layout/TabContainer",
        "dijit/layout/ContentPane"
    ],
   
    // Pass them as argument to declare function

    function(declare, parser, ready, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin){
   
        // Actual Widget body goes here
        declare("mywiget.TestWidget", [_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin ], {

            // gives the path for template to use
            templatePath: "js/dojo/mywidget/widget.tmpl",
   
           // If want to use template String instead
           // templateString: "<div>MyWidget<div>;

            widgetsInTemplate : true,

            postCreate : function (args, farg)
            {
                //this.inherited('postCreate', arguments);
            },

            }
        });

        ready(function(){
            // Call the parser manually so it runs after our
           //  widget is defined, and page has finished loading
            parser.parse();
        });
    }
);



Sample widget template code (widget.tmpl)

<div id="${id}" style='height:100%; width:100%'>
    <div data-dojo-type="dijit.layout.BorderContainer" data-dojo-props="liveSplitters:false, design:'sidebar'" style='height:100%; width:100%'>
        <div data-dojo-type="dijit.layout.AccordionContainer" data-dojo-props="region:'leading', splitter:true, minSize:20" style="width: 300px;">
            <div data-dojo-type="dijit.layout.ContentPane" data-dojo-props="title:'Tab1', style:'padding:10px;display:none;'">
                    Tab 1 Content
            </div>
        </div>
        <div data-dojo-type="dijit.layout.TabContainer" data-dojo-props="region:'center', tabStrip:true">
            <div data-dojo-type="dijit.layout.ContentPane" data-dojo-props="title:'Tab1', style:'padding:10px;display:none;'">
                Tab 1 content
            </div>
        </div>
    </div>
</div>




Using Widget in html page:

<html>
<head>
    <title> My widget : test</title>

    <link rel="stylesheet" type="text/css" href="js/dojo/dojo/resources/dojo.css"/>
    <link rel="stylesheet" href="js/dojo/dijit/themes/tundra/tundra.css"></link>

    <script src="js/dojo/dojo/dojo.js" data-dojo-config="async: true, parseOnLoad: false" ></script>

    <script type='text/css'>
    </script>

    <script type='text/javascript'>
        require(["dijit/registry", "dojo/parser", "mywidget/TestWidget",
                "dojo/domReady!"], function(registry, parser) {
                    // Explicitly parse the page
                    //parser.parse();

        });
    </script>
   
</head>
    <body class='tundra'>
        <span data-dojo-type="mywidget.TestWidget"></span>
    </body>
</html>


21 May 2012

Cyrus IMAP: setting user quota


Setting Cyrus IMAP user quota


1. Using Cyrus::IMAP::Admin



#!/usr/bin/perl -w

use Data::Dumper;
use Cyrus::IMAP::Admin;   

# Create admin client object
my $client = Cyrus::IMAP::Admin->new('localhost');
if (!$client) {
    print "\n Error: $!";
    exit 1;
}
$client->setflags(Cyrus::IMAP::CONN_NONSYNCLITERAL);

# Connect to IMAP server
my %h = ("Mechanism" => "login",
        "User" => "cyrus",
        "Password" => "password");
$client->authenticate(%h) || die "error $@ \n";

my $username = 'user.' . $ARGV[0];
my $quota = $ARGV[1];


# Set cyrus IMAP quota for user
if (defined $quota && $quota ne "") {
    print "\n Setting Quota";
    if (! $client->setquota("$username", "STORAGE", "$quota")) {
        print "\n Unable to set quota : error: $@";
    };
} else {

    # To remove quota use following call
    print "\nRemoving quota";
    if (! $client->setquota("$username")) {
        print "\n Unable to set quota : error: $@";
    };
}

# Get the user quota
my %userQuota = $client->listquota("$username");
print "\n Qutota for user : $username: " . Dumper(@{$userQuota{STORAGE}}[1]);

exit(0);



2. Using IMAP::Admin


#! /usr/bin/perl -w

require IMAP::Admin;
use Data::Dumper;

my $user = $ARGV[0];

if (! defined $user || $user eq "") {
    print STDERR "please provide username ";
    exit 1;
}

# Connect to IMAP server
my $imap = IMAP::Admin->new('Server' => 'localhost',
                           'Login' => 'cyrus',
                           'Password' => 'password',
                           'Port' => 143, # (143 is default),
                           'Separator' => ".", # default is a period
                        );

if (! $imap) {
    print STDERR "ERROR: while connecting to imap server: $@";
    exit 1;
}


# Setting cyrus IMAP quota for user
my $err = $imap->set_quota("user.$user", 10000);
if ($err ) {
    print "\n STDERR: Unable to set quota: $err";
    exit 1;
};

# Get the quota for the user
my @quota = $imap->get_quota("user.$user");
print "\n Quota for user : $user ". Dumper(@quota);

exit 0;


06 March 2012

Uploading file using Dojo and CGI AJAX

Sample Html file: (upload.html)

<html>
    <title>Upload file </title>
    <link href="/css/sitestyles.css" rel="stylesheet" type="text/css"/>
    <link rel="stylesheet" type="text/css" href="/js/dojo/dojo/resources/dojo.css"/>
    <link rel="stylesheet" type="text/css" href="/js/dojo/dijit/themes/tundra/tundra.css"/>
    <script type="text/javascript" src="/js/dojo/dojo/dojo.js" djConfig="parseOnLoad: true"></script>

    <script type="text/javascript">
    dojo.require("dijit.form.Form");
    dojo.require("dijit.form.Button");
    dojo.require("dojox.form.FileUploader");
    dojo.require("dijit.form.Button");
    dojo.require("dojo.parser");

    //using this early for the forceNoFlash test:
    dojo.require("dojox.embed.Flash");

    // Function to upload the file to server
    function doUpload () {
        var f0 = dijit.byId('btn0');
        console.log("doUpload")
        dojo.byId("fileToUpload").innerHTML = "uploading...";

        // If we want to send other fields along with the file
        // use submit method other use simple f0.upload() method
            f0.submit(dijit.byId('logoForm').domNode);
    }

    dojo.addOnLoad(function() {
        var f0 = dijit.byId('btn0');
       
        // Show file selected in div
        // data contains list of files selected
        dojo.connect(f0, "onChange", function(data){
        console.log("DATA:", data);
        var n = dojo.byId('fileToUpload');
        n.innerHTML = "";
        dojo.forEach(data, function(d){
            n.innerHTML += d.name
        });
        });

        // When file upload is in progress
        // Showing status inprogress
        dojo.connect(f0, "onProgress", function(data){
        console.warn("onProgress", data);
        var n = dojo.byId('fileToUpload');
        n.innerHTML = 'Uploading file';
        });

        //
        // Show the uploaded image
        // on successful upload of image
        //
        dojo.connect(f0, "onComplete", function(data){
        console.log("Uploaded file");
        var uf = dojo.byId('fileToUpload');
        var d = data[0];
        if ( d.status == "0" ) {
            uf.innerHTML = "<img src='" + data[0]['file'] + "'/>";
        } else {
            uf.innerHTML = d.message;
        }
        console.log(data);
        });
    });
    </script>

<body class='tundra'>
<center>

    <!-- Will show the status of file upload -->
    <table border='1' width='30%'>
    <tr>
    <td align='center'>
    <div id="uploadedFile"></div>
    <br>

    <!-- Other data to send to server along with file -->
    <form id='logoForm' dojoType='dijit.form.Form' accept="image/gif,image/jpeg">
        <div class='disabled'>
        <input name='action' value='upload' type='input'>
        </div>
    </form>
    <br>
    <!-- Show uploaded file -->
    <div id="fileToUpload"></div>
    <br>
    <!-- File uploader dijit -->
    <div id="btn0"
        dojoType="dojox.form.FileUploader"
        force="html"
        uploadOnChange=false isdebug=true htmlFieldName=orglogo
        uploadUrl="/sampleapp/upload-file" >
        Browse
    </div>
    <br>
    <div dojoType='dijit.form.Button' label='Upload' onClick='doUpload()'></div>
    <br>
    <br>
    </td>
    </tr>
    </table>
</center>
</body>
</html>


HTML tag


div id btn0 is File upload dijit with following properties :
force="html" if "html" html file uploader is used to upload file.
To use flash uploader set to "flash"

uploadOnChange=false If true selected file will be uploaded as soon as selected.

htmlFieldName=orglogo Name of html field under which the file-content to send

uploadUrl="/sampleapp/upload-file" Upload URL


Java script function:

dojo.connect(f0, "onChange", function(data){
});


Function used to display the selected file. This function will be called when file
browser dialoug is opened and we select a file. data will look like
[{ name="icon-server.png", size=0}]

dojo.connect(f0, "onProgress", function(data){
})

Function will be called when file uploading is in progress data will contain the
list of files. data will look like
[{bytesLoaded=1, bytesTotal=1, name="icon-server.png", percent=100, size=0, type=""}]

dojo.connect(f0, "onComplete", function(data){
})

Function will be called with server finishes the file process. It doesn't mean
successful file upload. You need send correct message and need to check from
data. data will look like
[{ status=0, file="/var/tmp/icon-server.png"}]

Server should send response in following format only and the should set header
Content-type: text/html.

Response format for success
<textarea>{"status":0,"file":"/var/tmp/a.xcf","message":null}</textarea>

Response format for error
<textarea>{"status":1,"file":"/var/tmp/a.xcf","message":"Invalid file format"}</textarea>

Response should be written in "textarea" tag

To send other form fields along with file use
var formdomNode = dijit.byId("logoForm").domNode;
dijit.byId("btn0").submit(formdomNode)


If you don't want any other field to send along file use
dijit.byId("btn0").upload() method


Sample server side code using Perl CGI
upload-file cgi


#!/usr/bin/perl -w

use strict;

use CGI;
my $result = {status => 1};

my $cgi = new CGI;
my $action = $cgi->param('action');

print "Content-type: text/html \n\n";

if ($action eq "upload") {

    #
    # Set MAX max upload limit
    #
    $CGI::POST_MAX = 1024 * 5000;


    my $msg;
    my $status = 0;
    my $INTERNAL_ERR = "Internal error";

    # What is field having file contain
    my $fieldname = 'orglogo0';
    my $filename = $cgi->param($fieldname);
    if (! $filename) {
    $msg = "File size exceded";
    }

    # Get file upload handle
    my $upload_filehandle = $cgi->upload($fieldname);
    my $uploadfilepath = "/var/tmp/$filename";

    # Write the file to disk
    if (open(UPLOADFILE, ">$uploadfilepath")) {
    if (! binmode UPLOADFILE)  {
        $msg = $INTERNAL_ERR;
    } else {
        while (<$upload_filehandle>) { 
        print UPLOADFILE;
        } 
        unless (close UPLOADFILE) {
        $msg = $INTERNAL_ERR;
        }
    }
    } else {
    $msg = $INTERNAL_ERR;
    }

    if ($msg) {
    $status = 1;
    }

    # Send status to client
    my $out = {
        file => $uploadfilepath,
        status => $status, 
        message => $msg
        };

    #
    # To handle cross platform problem dojo need the response in following format.
    # Reference: http://dojotoolkit.org/reference-guide/dojox/form/FileUploader.html
    #
    print "<textarea>". JSON::to_json ($out)."</textarea>";
    exit 0;

}

$result->{message} = "command not found";
print "<textarea>" . JSON::to_json($result) . "</textarea>"; 



12 December 2011

Apache Solr - Master / Slave configuration

Master Slave Configuration (Replication) :


Java based replication is implemented as RequestHandler. Using single solrconfig.xml for master and slave.

changes in solrconfig.xml

<requestHandler name="/replication" class="solr.ReplicationHandler" >
    <lst name="master">

        <str name="enable">${enable.master:false}</str>
        <str name="replicateAfter">commit</str>
        <str name="replicateAfter">startup</str>
        <str name="confFiles">schema.xml,stopwords.txt,elevate.xml</str>
        <str name="commitReserveDuration">00:00:20</str>
        <str name="backupAfter">optimize</str>
     </lst>
     <lst name="slave">
        <str name="enable">${enable.slave:false}</str>
        <str name="masterUrl">http://192.168.1.120:8983/solr/replication</str>
        <str name="pollInterval">00:00:60</str>
        <str name="compression">internal</str>
        <str name="httpConnTimeout">5000</str>
        <str name="httpReadTimeout">10000</str> 
        <str name="httpBasicAuthUser">username</str>
        <str name="httpBasicAuthPassword">password</str>
     </lst>
</requestHandler>


Tag description:

Master

enable
If a server needs to be turned into a master from a slave or if you wish to use the same solrconfig.xml for both master and slave. When the master is started, pass in -Denable.master=true and in the slave pass in -Denable.slave=true

replicateAfter
Replicate on give value. Valid values are "commit", "startup", "optimize". You can give multiple values. If only the startup option is given, replication will not be triggered on subsequent commits/optimizes after it is done for the first time at the start.

confFiles
Configuration files names mentioned will be replicated. The files that are to be replicated have to be mentioned explicitly in using the 'confFiles' parameter. Only files in the 'conf' dir of the solr instance are replicated. The files are replicated only along with a fresh index.

commitReserveDuration
If your commits are very frequent and network is particularly slow, you can tweak an extra attribute <str name="commitReserveDuration">00:00:20</str>. Default is 10 secs.

backup
Create a backup after action specified in backupAfter. Valid values are 'optimize', 'commit', 'startup'. It is possible to have multiple entries of this config string. Note that this is just for backup, replication does not require this.

Slave

enable
Same as of master. pass in -Denable.slave=true to run the solr in slave mode.

masterUrl
Master apache solr server url.

pollInterval
Interval in which the slave should poll master .Format is HH:mm:ss . If this is absent slave does not poll automatically. But a fetchindex can be triggered from the admin or the http API

compression
The possible values are internal|external if the value is 'external' make sure that your master Solr has the settings to honour the accept-encoding header. If it is 'internal' everything will be taken care of automatically. Use this only if you bandwidth is low

httpConnTimeout/httpReadTimeout
The following values are used when the slave connects to the master to download the index files. Default values implicitly set as 5000ms and 10000ms respectively. The user DOES NOT need to specify these unless the bandwidth is extremely low or if there is an extremely high latency.

httpBasicAuthUser/httpBasicAuthPassword
If HTTP Basic authentication is enabled on the master we need to specify these parameters other not.

Just copy the above xml fragment to solrconfig.xml

Starting apache solr in master mode.
$ java -jar -Dmaster.enable=true start.jar

Starting apache solr in slave mode
$ java -jar -Dslave.enable=true start.jar

For More information please refer :
http://wiki.apache.org/solr/SolrReplication

Apache Solr - committing changes


Auto-Commit
Solr configuration has the following option available for commit (solrconfig.xml)

<autoCommit>
    <maxDocs>10000</maxDocs>
    <maxTime>1000</maxTime>
</autoCommit>

maxDocs - Maximum number of documents to add since the last commit before automatically triggering a new commit.
maxTime - Maximum amount of time that is allowed to pass since a document was added before automaticly triggering a new commit.


commitWithin
commitWithin = "(milliseconds)" if the "commitWithin" attribute is present, the document will be added within that time.
e.g

<add>
  <doc commitWithin="1000">
    <field name="employeeId">05991</field>
    <field name="office" boost="2.0">Bridgewater</field>
  </doc>
</add>


Committing manually
We can issuse a commit using simple commit=true in update querystring or using curl.

As Query String
$curl 'http://localhost:8983/solr/update?commit=true'

As XML request
$curl 'http://localhost:8983/solr/update' --data-binary  '<commit/>' -H 'Content-type:text/xml; charset=utf-8'


Commit Policy
A commit operation makes index changes visible to new search requests.
A hard commit also calls fsync on the index files to ensure they have been flushed to stable storage and no data loss will result from a power failure.

A soft commit is much faster since it only makes index changes visible and does not fsync index files or write a new index descriptor. If the JVM crashes or there is a loss of power, changes that occurred after the last hard commit will be lost. Search collections that have near-real-time requirements (that want index changes to be quickly visible to searches) will want to soft commit often but hard commit less frequently.

Optional attributes for commit

waitFlush = "true" | "false" — default is true — block until index changes are flushed to disk
softCommit = "true" | "false" — default is false — perform a soft commit - this will refresh the 'view' of the index in a more performant manner, but without "on-disk" guarantees.
expungeDeletes = "true" | "false" — default is false — merge segments with deletes away.

e.g.
As Query String:
$curl 'http://localhost:8983/solr/update?commit=true&waitFlush=true&expungeDeletes=true

As XML
$curl 'http://localhost:8983/solr/update' --data-binary  '<commit waitFlush="true" expungeDeletes="true"/>' -H 'Content-type:text/xml; charset=utf-8'

30 November 2011

Apache solr some optimization and trouble shooting


Checking for corrupt Indexes
Make a backup of the existing index before running the CheckIndex tool. First create a sample folder then copy the lucence-core-x.jar and index file to this folder. Suppose the directory structure is

../check-corrupt-index
|-- lucene-core-3.5.0.jar
`-- test-index
|-- _1.fdt
|-- _1.fdx
|-- _1.fnm
|-- _1.frq
|-- _1.nrm
|-- _1.prx
|-- _1.tii
|-- _1.tis
....
|-- _z.tis
|-- segments.gen
`-- segments_12

Just checking the indexes are corrupt or not use following command

$ java -ea:org.apache.lucene... org.apache.lucene.index.CheckIndex /opt/apache-solr-3.5.0/example/solr/data/check-corrupt-index/test-index/

Here /opt/apache-solr-3.5.0/.. is path to the indexes to check. The output will be like

Opening index @ /opt/apache-solr-3.5.0/example/solr/data/check-corrupt-index/test-index/

Segments file=segments_12 numSegments=10 version=3.5 format=FORMAT_3_1 [Lucene 3.1+]
1 of 10: name=_c docCount=2938
compound=false
hasProx=true
numFiles=8
size (MB)=38.219
diagnostics = {mergeFactor=10, os.version=2.6.18-194.el5, os=Linux, lucene.version=3.5.0 1204988 - simon - 2011-11-22 14:46:51, source=merge,
os.arch=i386, mergeMaxNumSegments=-1, java.version=1.6.0_11, java.vendor=Sun Microsystems Inc.}
no deletions
test: open reader.........OK
test: fields..............OK [11 fields]
test: field norms.........OK [5 fields]
test: terms, freq, prox...OK [171871 terms; 1354874 terms/docs pairs; 6045083 tokens]
test: stored fields.......OK [35110 total field count; avg 11.95 fields per doc]
test: term vectors........OK [0 total vector count; avg 0 term/freq vector fields per doc]

....

10 of 10: name=_13 docCount=22
compound=false
hasProx=true
numFiles=8
size (MB)=2.192
diagnostics = {os.version=2.6.18-194.el5, os=Linux, lucene.version=3.5.0 1204988 - simon - 2011-11-22 14:46:51, source=flush,
os.arch=i386, java.version=1.6.0_11, java.vendor=Sun Microsystems Inc.}
no deletions
test: open reader.........OK
test: fields..............OK [11 fields]
test: field norms.........OK [5 fields]
test: terms, freq, prox...OK [6290 terms; 9779 terms/docs pairs; 35206 tokens]
test: stored fields.......OK [248 total field count; avg 11.273 fields per doc]
test: term vectors........OK [0 total vector count; avg 0 term/freq vector fields per doc]

No problems were detected with this index.


The last line shows the status. If there is not problem it will say "No problems were detected with this index" Otherwise it will show error message like "org.apache.lucene.index.CorruptIndexException: did not read all bytes" or similar other
message to fix this problem use following command

$ java -ea:org.apache.lucene... org.apache.lucene.index.CheckIndex /opt/apache-solr-3.5.0/example/solr/data/check-corrupt-index/test-index -fix


For more information check:
http://solr.pl/en/2011/01/17/checkindex-for-the-rescue

Reduce the number of files the index is made of
In order to make the index more compound and merge all the segment files into one file, we need to run the optimize command. To do that, we run the optimize command in the following way:

curl 'http://localhost:8983/solr/update' --data-binary '<optimize/>" -H 'Content-type:text/xml; charset=utf-8'


It is good to have an optimize command running in a set period of time; for example, once a day. But remember to run it only on the master server and during the time when the master server is not used as much as during the peak indexing time. The optimize command uses the I/O operations heavily, and this can and will affect the performance of the server you send the optimize command to. Also, remember to send the optimize command to every core you have deployed on your Solr server.
You should always measure the performance of Solr servers on optimized and non-optimized indexes to ensure that the optimization is really needed.

Dealing with with a locked indexes
If there is no indexing process running and lock is beacause of error. then go to the directory containing the index files. One of the files in the /usr/share/solr/data/index/ directory is he one we are searching for. That file is:
lucene-fe3fc928a4bbfeb55082e49b32a70c10-write.lock
Remove that file and restart Jetty.

Merge Factor
The lower the mergeFactor setting, the longer the indexing time will be, and will thus improve the search speed. On the other hand, the higher the mergeFactor setting, the less time indexing will take, but search time may degrade as there will be more segments, and thus more files that create the index.

MergeFactor Tradeoffs
High value merge factor (e.g., 25):
    * Pro: Generally improves indexing speed
    * Con: Less frequent merges, resulting in a collection with more index files which may slow searching

Low value merge factor (e.g., 2):
    * Pro: Smaller number of index files, which speeds up searching.
    * Con: More segment merges slow down indexing.

31 August 2011

Bash script: Common tasks

Wrting a shell script some comman tasks

1. Getting running script name
Suppose script name is script.sh

#!/bin/bash
ME="$(basename $0)"
echo "My name: $ME"
ME=${ME%.*}
echo "My name without extension: $ME"


Output will be:
My name: script.sh
My name without extension: script


ME="$(basename $0)" Will return the scipt name
ME=${ME%.*} Will remove the last extension from the script

2. Getting PID of the running script
#!/bin/bash
echo "My PID: $$"

$$ gives the PID of the running shell script.

3. Getting command like options using getopts
#!/bin/bash
ME="$(basename $0)"
VERSION=1.0
usage()
{
echo "usage:$ME [options]"
echo "-h, --help print the help for this program"
}

args=`getopt -o hv -l help,version -- $@`;
errcode=$?;

# Check if any argument value is missing
if [ $errcode -ne 0 ]; then
usage;
exit 1;
fi;
set -- $args
argsarr=($args)

# Get the value of the arguments
for i; do
argval=$2
shift
case "$i" in
-h|'--help') usage; exit 0;;
-v|'--version') echo $VERSION; exit 0;;
--) ;;
esac
done


"getopts" provides the facility to take named arguments. Arguments -o will specify which small arguments will be allowed and -l provides the long listing arguments.

We can run above script as-
$ ./script.sh -h or $./script --help
will print the help

4. Getting disk space for a particular partition
#!/bin/bash
partition="/var"
availdisk="$(df -kP ${partition}| awk '{ print $4 }' | tail -1)"
echo "Available disk space: $availdisk"


5. Getting System architecture
#!/bin/bash
arch="$(uname -a)"
echo "System architecture : $arch"


6. Getting system load average
#!/bin/bash
loadavg="$(uptime | awk -F "load average:" '{ print $2 }' | cut -d, -f1)"
echo "Load average for last 1 Minute: $loadavg"
loadavg="$(uptime | awk -F "load average:" '{ print $2 }' | cut -d, -f2)"
echo "Load average for last 5 Minute: $loadavg"
loadavg="$(uptime | awk -F "load average:" '{ print $2 }' | cut -d, -f3)"
echo "Load average for last 10 Minute: $loadavg"


7. Getting current time in specific format
#!/bin/bash
ts="$(date +%F-%H.%M.%S.0000)"
echo $ts


8. Returning values other than integer from shell function
Shell allow only intger to be used in return statement of the function. To return value other than integer from function use echo command.

#! /bin/bash
concat()
{
echo "$1" "$2"
# return "$1" "$2" # not allowed
}
str="$(concat 'Hi' 'There')"
echo "$str"


9. Comparing two floating number
Only integer number can be compaired using lt gt. To comapre the floating
point number we can bc.

#! /bin/bash
compareNumber()
{
compare_result=`echo "$1 > $2" | bc 2>/dev/null`
if [ $compare_result ]; then
return 1
fi
return 0
}
if ! compare_result 10.1 20.5; then
echo "First one is less than second"
else
echo "First one is grater than second"
fi


10. Stripping out filename from full path
#!/bin/bash

getFileName()
{
local fullpath="$1"
local filename="${fullpath##*/}" # Strip longest match of */ from start
echo $filename
}
filename="$(getFileName $1)"

echo "File name from path : $filename"


11. Stripping directory path from full path
#!/bin/bash

getDirPath()
{
local fullpath="$1"
local filename="${fullpath##*/}" # Strip longest match of */ from start
local dir="${fullpath:0:${#fullpath} - ${#filename}}"
echo "$dir"
}

path="$(getDirPath $1)"
echo "Direcotry path: $path"