Tag Archives: linkedin

Just finished “The Book” by Alan Watts. I like it.

I have just finished reading The Book.. On the Taboo Against Knowing Who You Are by Alan Watts.  I have thoroughly enjoyed reading this book!  It comes as close as I can imagine to a book that helps its reader truly understand the concept of existence, our world, and our “purpose in it”.

The Book (cover)

I must admit that I have had an affair with such ideas and philosophies for a very long time – and this perhaps makes the content and context of the book easier for me to grok than it would others – but it is worth the effort.  If there is anything worth doing in this world, I would image that understanding who you are, and understanding why you have the experiences and knowledge that you do, in contrast to the experiences and knowledge of others around you, to be of utmost significance and importance.

I have written a few articles under various pseudonyms over the years that explore the very concepts explained in this book, but have never really come across a published work that summarized these thoughts as clearly and succinctly as I would have liked, until now.

If you have any capacity or motivation to understand the world you live in, and you are able to free yourself (your mind) from the conditioning of your environment and your up-bringing, even for a moment, then I suggest you take the time read this book.

If you are not very familiar with Eastern or Western philosophy to begin with, then the ideas in this book may be difficult to grasp.  Nevertheless, once you’ve had a chance to explore the basics of such ideas in other writings, you would do well to circle ’round and come back to this marvelous treasure.

Playing With Prime Numbers

I’ve been toying around with functional programming, and recently came across a perlmonks thread discussing multiple ways to calculate prime numbers.  One of the things I noticed about many of the examples was that almost all of them used loops of some sort (for, when, etc).  So I decided to tackle the problem without using any loops.  Instead, I’ll just use recursive functions.

Firstly, here’s the perlmonks thread: Prime Number Finder

And here’s the solution I came up with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/env perl
 
use strict;
use warnings;
use 5.010;
 
$DB::deep = 500;
$DB::deep = $DB::deep; # Avoids silly 'used only once' warning
 
no warnings "recursion";
 
# Identify primes between ARG0 and ARG1
 
my ($x, $y, $re_int, $result);
my ($prime, $is_int);
 
$x = $ARGV[0];
$y = $ARGV[1];
 
$is_int = sub {
    my $re_int = qr(^-?\d+\z);
    my ($x) = @_;
    $x =~ $re_int
      ? 1
      : 0;
};
 
$prime = sub {
    my ( $x, $y ) = @_;
    if ( $y > 1 ) {
        given ($x) {
            when ( $is_int->( $x / $y ) ) {
                return 0;
            }
            default {
                return $prime->( $x, $y - 1 );
            }
        }
    }
    else { return 1; }
};
 
$result = sub {
    my ( $x, $y ) = @_;
    if ( $x <= $y ) {
        if ( $prime->($x, $x-1) ) {
            say $x;
        }
        $result->( ( $x + 1 ), $y );
    }
};
 
$result->($x, $y);

When running this code with larger numbers, I would eventually run into “deep recursion” warnings, which is why I’ve had to use no warnings "recursion"; and set $DB::deep to a specific value higher than 100 (which is the default). $DB::deep is a debugging variable used specifically to limit recursion depth, in order to prevent long-running or infinite recursive operations.

The method I’m using here to calculate prime numbers isn’t the most efficient, since I’m not doing anything to reduce the amount of numbers I have to test at each cycle. However, adding some extra intelligence to this, such as the filtering used by the Sieve of Eratosthenes (an “ancient Greek algorithm for finding all prime numbers up to a specified integer.”) should be doable.

I’ll be keeping an eye out for other solutions, since I’m sure there are many (especially in perl), but so far this one seems to be fairly fast and clean. I’m looking forward to what Math::BigInt can offer here as well, if anything.

Playing with Factorials, Haskell, and Perl

I’m currently making may way through a book called “Seven Languages in Seven Weeks” by Bruce A. Tate.  So far it’s been an interesting read, but I’m far from finished.

One of the things in the book that caught my eye was a recursive factorial function in Haskell, which seemed so simple, that I had to see what it would look like in perl.

So I wrote up the following perl snippets to calculate factorials.  There are, of course, multiple ways to do it as I’ll describe below.  There are also (likely) many other ways which I haven’t thought of, so if you have an interesting solution, please share.

One of the things that really caught my attention was how simplistic the syntax was for writing somthing so complex.  Recursion is a fairly simple idea once you’ve seen it in action – a function that executes itself.  However, the implementation of recursion in a given programming language can be somewhat difficult to comprehend, especially for new programmers or those without programming experience.

Although I haven’t dived into Haskell quite yet, it seems to make implementing a factorial function so simple, that I kind of stumbled when trying to understand it, thinking I was missing something.. but it was all there in front of me!

Firstly, let’s clarify what a factorial is (from wikipedia):

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example,

5 ! = 5 \times 4 \times 3 \times 2 \times 1 = 120 \

 

So the factorial of 5 is 120.  Or 5! = 120.   Lets look at the Haskell example from the book.

let fact x = if x == 0 then 1 else fact (x - 1) * x

The above line is saying “if x is 0, then the factorial is 1 – otherwise, call myself with (x – 1), multiplied by x”

Lets look at this in ghci (the Haskell console):

[jbl@watchtower tmp]$ ghci
GHCi, version 7.0.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Loading package ffi-1.0 ... linking ... done.
Prelude> let fact x = if x == 0 then 1 else fact (x - 1) * x
Prelude> fact 5
120
Prelude>

After seeing how easy it was to implement the recursive factorial function in Haskell, here are my attempts in perl.

Firstly, using a loop:

#!/usr/bin/env perl
 
use strict;
use warnings;
use feature "say";
 
my $nni = $ARGV[0] ? $ARGV[0] : 5;
 
for my $i ( 1..($nni - 1) )
{
    $nni = $nni * $i;
    say $nni;
}

This first example doesn’t implement a function, and is really just bad (but still working) code. It requires that your base number be global and alterable, in this case $nni.

Now, lets try it with an actual function:

#!/usr/bin/env perl
 
use strict;
use warnings;
use feature "say";
 
my $nni = $ARGV[0] ? $ARGV[0] : 5;
 
sub fact 
{ 
    my ($nni) = @_;
    return !$nni ? 1 : fact( $nni - 1 ) * $nni;
}
 
say fact($nni);

This second method works similarly to the Haskell implementation. It implements a function that calls itself, without any looping required.

However, it’s still not as concise as the Haskell version, so lets try again:

#!/usr/bin/env perl
 
use strict;
use warnings;
use feature "say";
 
my $nni = $ARGV[0] ? $ARGV[0] : 5;
my $fact;
$fact = sub { my ($nni) = @_; !$nni ? 1 : $fact->( $nni - 1 ) * $nni };
say $fact->($nni);

Aha, now we’re getting somewhere. In this third example, the fact() function is anonymous, and we’re assigning it to $fact via reference. This allows us to use $fact like an object with a single method that does the factorial calculation.

Although this is pretty much as concise as I was able to get it while taking readability into account, here’s a final example that goes a step further:

#!/usr/bin/env perl
 
use strict;
use warnings;
use feature "say";
 
my ($nni, $fact);
$nni = $ARGV[0] ? $ARGV[0] : 5;
$fact = sub { !$_[0] ? 1 : $fact->( $_[0] - 1 ) * $_[0] };
say $fact->($nni);

This last example uses perl’s pre-defined variable @_ which automatically holds a list of function arguments by default. I usually avoid doing this, since it hurts readability, especially for those who don’t live and breathe perl on a daily basis.

To my surprise, it would seem that Haskell has Perl beat (at least in this example) as far as readability + conciseness is concerned.

I haven’t spent much time playing golf here to reduce the number of lines or characters beyond the last example, but if anyone does come up with a tighter solution, please let me know!


Edit (20111005T22:43:50): Here’s a version I found that uses the Math::BigInt module

#!/usr/bin/env perl
 
use strict;
use warnings;
use feature "say";
use Math::BigInt lib=>'GMP';
 
my $b = Math::BigInt->new($ARGV[0]);
say $b->bfac();

This version is likely much faster, since the Math::BigInt package is intended to be used in situations where large integers are being handled.

Here’s the post I found with examples written in other languages as well: Factorial Challenge: Python, Perl, Ruby, and C

Understanding the Concepts of Classes, Objects, and Data-types in Computer Programming

book-car

Every once in a while I get into discussions with various people about computer programming concepts such as objects, classes, data-types, methods, and functions.

Sometimes these discussions result in questions about the definition of these terms from those who have some programming experience, and sometimes these questions come from those who have no background in computer science or familiarity with programming terminology whatsoever.

I usually attempt to answer these questions using various metaphors and concepts that I feel the individual or group may be able to relate to.

It is quite possible that even my own understanding of these concepts may be incorrect or incomplete in some way. For the sake of reference and consistency, I am writing this brief article to explore these concepts in the hope that it will provide clarity into their meaning and purpose.

 

So, what is a data-type?

Some languages, like C, have a strict set of data-types. Other languages, like C++, and Java offer the developer the ability to create their own data-types that have the same privilages as the data-types that are built into the language itself.

A data-type is a strict set of rules that govern how a variable can be used.

A variable with a specific data-type can be thought of in the same way as material things in the real world. Things have attributes that make them what they are. For example, a book has pages made of paper that can be read. A car is generally understood to be an automobile that has four wheels and can be used for transport. You cannot drive a book to the grocery store, in the same sense that you cannot turn the pages of a car.

A data-type is a specific set of rules for how a variable can be used.

 

Data-types in computer programming may include examples such as:
_____________________ 
Object Type
==== ========
Int = number, no decimal places
Float = large number with decimal places
Char = a plain-text character
_____________________  

 

More familiar, real-world examples may include:
_____________________
Object Type
==== ========
Bucket = Strong, can hold water, has handle
Balloon = Fragile, can hold a variable amount of air, elastic, portable
Wheel = Round, metal, rubber, rolls
_____________________ 

 

In languages like C++, there are core data-types such as the ones found in C. However, C++ also offers developers the ability to create their own data-types.  Providing developers the ability to create their own data-types makes the language much more flexible. We more commonly refer to a user-defined data-type by the more popular term, class.

In C++, a class is a user-defined data-type [1]. That’s all it is. It provides the developer the ability to create a variable (or object) with specific attributes and restrictions, in the same way that doing “int dollars = 5;” creates an object called “dollars” who’s attribute is to have a value which is strictly an integer. In the real world, a five-dollar bill cannot be eaten (technically), and it cannot be driven like a car to a grocery store (even though that’s where it will likely end up).

An object is a variable that has been defined with a specific data-type. A variable is an object when it is used as an intance of a class, or when it contains more than just data. An object in computer programming is like an object in the real world such as a car, or a book. There are specific rules that govern how an object can be used which are inferred by the very nature of the object itself.

The nature of computer programming means that developers have the ability to redefine objects, for example making the object “book” something that can be driven. In the real world however, we know that you can call a car a book, but it’s still a car. The core understanding of what a car is has been ingrained within us. Although “car” is simply a three letter word (a symbol, or label), there are too many people and things in the world that depend on the word “car” having a specific definition. Therefore objects in the real world cannot be as easily redefined as their counter-parts in computer programming (however, it is still possible [2]).


So what is a method?

In computer programming, we have things called “functions”. A function is an enclosed set of instructions which are executed in order to generate (or “return”) a specific result or set of results. You can think of a function as a mini program. Computer programs are often created by piecing together multiple functions in interesting and creative ways.

Functions have many names, and can also be referred to as subroutines, blocks and methods. A method is a function which is specifically part of a class, or a user-defined data-type, which makes a method an attribute of an object – something that the object is capable of doing.  Just like in the real world, methods can be manipulated and redefined for an object, but not for that object’s base class.  A book can be used to prop-up a coffee table, but that does not mean that books are by definition meant to be used in this way.


Enlightenment achieved!

I’m not really sure where I was going with all of this, but the above should be sufficiently lucid.   I was motivated to write this after recently referencing Bjarne Stroustrup’s “The C++ Programming Language”.  If you’ve ever asked yourself the question “what is an object?” or “what is a class?”, then the above descriptions should serve as a useful reference.

[1] “The C++ Programming Language – Special Edition”, page 224.

[2] For example, the definition of “phone” has been redefined several times in recent history, from the concept of a dial-based phone, to cell phones, to modern smart-phones.

 

S5 Presentation Software, XMind, Freemind, and mm2s5

I’m tired and a bit wired, but I figured I’d put a few words together just to purge my messy mind. So today I’d like to talk about presentation software (a la powerpoint); mind-mapping software, and how to get from one to the other in an interesting way.

I’ve been a mind-mapping fanatic for many years, as far back as 2004 if I recall correctly. Back then (and even up to today) I’ve used and loved the free and open-source mind-mapping software called Freemind [http://freemind.sourceforge.net/wiki/index.php/Main_Page]. It’s a great little piece of java software which provides a great UI for doing brainstorming and outlining using mind-maps.

These days, I use a mix of Freemind and XMind to do my day-to-day brainstorming and planning. XMind is like Freemind (in fact, I’m sure it borrowed many ideas from that project), but has a nicer UI, and many more options in terms of layout, tagging, markers, etc. I find that I jump between the two often, until my brainstorming takes on a life of it’s own, then I will stick to one or the other for the remainder of the map creation.

I recently had to put together a presentation for the Toronto Perl Mongers group to discuss, well Perl.. and VMware. And of course I whipped out Freemind and XMind to start the brainstorming process. XMind has a nice feature that allows you to export your mind-maps to an MS Power Point or OpenOffice Impress type format, which is great and what I needed. Problem is though that this feature is not free, it comes as part of XMind’s online subscription services for their “professional” version of the product. Even though the price is fairly reasonable, and I’m sure at some point may just bite the bullet and subscribe, I wasn’t ready to do that just yet. So I was on the hunt for some way to convert my mind-map into some kind of presentation.

To their credit, one thing that XMind does do properly is allow you to export your XMind maps to Freemind’s .mm format. This is great, because Freemind itself has multiple freely accessible export formats, including exports to OpenOffice.org and PDF. However, I wasn’t satisfied, I was looking for something that would do the job more completely.

Eventually I came across a neat little HTML/Javascript based presentation tool called S5, which stood for “Simple Standards-Based Slide Show System”. This tool was exactly what I was looking for! It’s small, clean, no-fluff implementation meant that I could whip up a professional looking presentation without the need to load up any bulky software aside from Firefox. Problem remained though, that my data was still in XMind (and Freemind) formats. I was considering writing a tool that would convert Freemind XML files into S5 HTML documents, which would have been fairly easy since both formats are fairly open and clear, however that would have taken a good deal of time, and time is one that that I never seem to have enough of these days.

So I went hunting on the plains of Google to see if anyone was experiencing the same problem I was, and if they did anything about it. And what do you know! I found a project on Google Code that does exactly that! The project is called (reasonably enough) mm2s5, and does a wonderful job at converting my Freemind mind-maps into S5 Presentation format!

Anyone who’s interested in finding a nice way to brainstorm and turn their ideas into presentations should seriously consider trying these tools out, they’re fantastic, and they’re free!

Work on CPAN-API and Perl Modules Indexing

Since the last TPM meeting in October, some of the TPM members have been working diligently to improve the CPAN search experience by re-architecting CPAN search from the bottom up. I’ve joined the design team in the hopes of providing the Perl community a much more improved CPAN experience.

As most Perl developers are aware, search.cpan.org is great for finding useful libraries and modules, but horrible at providing any significant information which relates modules to each-other, or providing useful meta-information or statistics which can be used to make better decisions on which modules to use, let alone deploy in a production environment.

If you are interested in taking part in the CPAN-API community project, please contact me, or visit the CPAN-API project site on GitHub.

CPAN-API: https://github.com/CPAN-API/cpan-api/wiki/
Toronto Perl Mongers: http://to.pm.org/

Jolicloud is of the Awesome

So if you haven’t heard of Jolicloud http://www.jolicloud.com/, then you need to download and install it now. It’s an Ubuntu based OS (a self-proclaimed “Cloud OS”) specifically designed for Netbooks, and it rocks. I have Jolicloud installed on my Samsung N110 Netbook, and I use it for everything from e-mail to games (snes9x) to work (Perl/Vim/Screen). Now what makes Jolicloud super-awesome is that it treats web applications no differently from desktop applications. Each application gets it’s own icon on the “Home screen”. It’s also socially aware – it can connect to facebook and allow you to search for applications and/or people who’ve used those applications, so that you can ask them questions and get guidance on the tools you’re trying to use.

The interface is very slick – big icons and a clean method of navigation to the lesser used functions of a standard Gnome/Ubuntu desktop. The most-awesomest part is that once you load up a terminal, you have full access to the command-line and all Ubuntu apt repositories.

Jolicloud isn’t just for netbooks! I’ve also installed it on my Acer Veriton (similar to the Acer Revo), and am using it as a media center OS. Jolicloud also comes in an “express” edition, which allows you to install it under windows, where it will come up as a secondary OS option under the windows boot-loader.

If you have a netbook, nettop, or any light-weight PC, then install Jolicloud. Highly recommended.

Diving in with Arch Linux

The Problem

The time had come for me to “invest” in getting some new equipment. The only workstation that I had up until recently was a company laptop which I had toted back and forth between VMware and my home office. I keep my personal documents on removable storage, but that doesn’t really help when you don’t have a workstation at home, so lugging the laptop around with me was a must.

Don’t get me wrong, I have systems, but their mostly systems running as file servers or VM servers doing various little things automagically, and they’re not sitting in or around my actual desk at home. Also, my printers/scanner at home relied on my laptop to be of any use. It was time to fix all of these unecessary grievences.

The Dilemma

For the past couple of weeks I had been thinking hard about what kind of system I should buy – should it be a powerful / modern desktop system with lots of RAM and screaming CPU/Video? Or would it be a powerful laptop/notebook which would serve as a desktop replacement? Should I go for the i3, i5, or i7 processor? ATI or Nvidia? What kind of budget was I looking at?

All of these questions plagued me for quite some time (okay, not that long.. I admit I’m a bit of an impulse buyer). I’ve spent long enough thinking about this that I realized a lot about myself. For one, I’m not a gamer. I was once one of those people who would have been ecstatic about getting next-gen hardware to play the lastest power-hungry games. Not any more.. and not for quite some time. The last time I seriously played a PC game was about 3 years ago. When I say “seriously”, I mean played it regulary, at least once a week. The last game I played was a game that I was really into; it was X2 of the X-Series space combat simulators.

Since then, I’ve touched a game or two, on and off, but the has fascination is no longer there. i’m more interested in hacking around with open source programs and becoming a better developer.

The Solution

Since I wasn’t going to focus on gaming and media for my new system purchase, this opened the door for a lot of possibilities that I haven’t considered, and some unexpected disappointments. First off, since I wasn’t going to plop $1,000.00 on a single system, I could, theoretically buy two lower-powered systems. And that’s exactly what I did. Instead of going with a full-fledged desktop or power-house laptop, I ended up buying an Acer Aspire Revo net-top unit as my primary workstation, and a Samsung N110 Netbook as my portable. This Revo is awesome! It has 2GB of RAM (upgradable to 4), an Nvidia ION chipset, and an Intel Atom processor (dual-core). I didn’t need much more than this for my purposes, this was perfect. The Samsung N110 was also a nice little beauty. It was a Atom processor with integrated graphics, but was light, pretty, and had a 6-cell battery, which meant that it would last about 8 hours during heavy use. I quickly installed JoliCloud Express on the Netbook, and have been very happy with it ever since.

The Disappointment (In myself)

The disappointment that I experienced was not in the purchase or the hardware, but it was in the fact that I hesitated for a long time to wipe away the Revo’s bundled OS to install Linux. The OS that the Revo came with was Windows 7 Home edition (the Samsung netbook had Windows XP). I haven’t used windows as my primary OS in years, and have always been proud to say so. For the last four years or so, I’ve been using Ubuntu (severely customized), and before that I was using Debian. When I initially started up the Revo, I was impressed by the windows 7 user interface, the nice colors, the clean lines, and the fact that it picked up all my hardware. It was pretty simple, and I have to admit somewhat luring. I’m definately not the little hacker I was 10 years ago. I don’t have time to spend hours hacking away into the wee morning just on my OS configuration. At least that’s what I keep telling myself :) But then it dawned on me – that’s how I got where I am today, by embracing curiousity, and defying conformity. That’s where life becomes interesting and liberating, and that’s where I feel at home. All these thoughts of nostalgia hit me shortly after I hard-reset the Revo, and windows 7 came up saying “system wasn’t shut down correctly – use safe mode” or something to that effect. There was no way for me to tell it to disregard the unclean boot-up, it persisted to ask me to go into safe mode, with no specific explanation. That’s when I wish I had a grub prompt or command line handy.

Diving in with Arch Linux

After coming to my senses, I realized that I definately didn’t want to go back to using Ubuntu for my primary workstation. For a while I’ve been feeling like Ubuntu has lost much of it’s luster, especially for someone like me who loves simplicity and minimalism over fancy GUIs and extra features. I wanted a distribution that tried to stay at the cutting edge with it’s packages, but didn’t screw with the basics of linux so much that you’re forced to use GUIs to configure your OS. Debian didn’t fit the bill here – it’s great for servers – rock solid, but it’s not that great if you want a cutting edge workstation without having to compile things from source.

After a little bit of reading and browsing distrowatch.com, I came across Arch Linux (which I’ve known of only in passing before), and decided that this was the OS for me. The Arch Linux community is small enough that I could make some significant contributions without much effort. The distribution itself is awesome, very clean, and very minimal. And most importantly, all of the system configurations are done by editing text files!

The Arch Way

Installing Arch was relatively straight-forward (IMO). It wasn’t as easy as installing, say, Linux Mint, but it also wasn’t as hard as installing Debian 3.0 either. The installation dialogs were ncurses based, but they were descriptive, linear, and logical. When it came time to supply arguments for the initial configuration of the packages I selected, they were all text files (very well documented) which I could edit with vim! I think at that point I knew that was about to embrace a distribution that was very special indeed. This distro was going back to basics, and not flooding it’s users with fancy splash screens and progress meters, it was doing the needful, and it was doing it well.

I still have a lot more to learn about Arch, as I’ve only scratched the surface so far. I’ve been able to set up sound (with alsa) and video using the latest Nvidia drivers. I’ve configured Xmonad as my window manager, and have gotten a handle of how to query and install packages with “pacman”, the Arch package installer. The only real problem that I’ve run into is setting up CUPS for my printers. After some research, it seems that the version of CUPS (1.4.3-2) available in the Arch packages is the latest version available from the CUPS source repository, and that I may have to downgrade (to 1.3.9) it in order to get my printers working.

Overall, I like what I see so far with Arch. I expect to post more on my experiences with it as I learn.

Syncronizing Xymon’s ‘bb-hosts’ Configurations

I’ve been using Xymon (formerly known as “Hobbit”) for a long time.  In most situations, I have Xymon running in a redundant configuration, with two or more instances of Xymon working together to monitor a network.

Even though Xymon works very well, a single change to the primary server’s configuration file (the “bb-hosts” file) means that you have to make the same change to all other ‘bb-hosts’ files in all other Xymon instances.

There are some creative ways to eliminate the drudgery of updating all these files any time a change to the primary file is necessary.  One method, for example would be to have the master file exported via NFS to all the other Xymon server instances, and each of those instances would sym-link to that primary ‘bb-hosts’ file from their local mount of that NFS export.

I don’t like the NFS export idea, because if the primary server has a problem, and the NFS export is no longer available, all instances of Xymon would break – badly.

Instead, I’ve opted for automatically synchronizing the ‘bb-hosts’ file across all Xymon instances via the use of apache, cron, a sym-link, and a simple bash script.

Here’s  how it works:

  • On the primary Xymon instance, sym-link ‘/home/xymon/server/etc/bb-hosts’ to ‘/var/www/bb-hosts’.
  • On the other instances of Xymon, run a bash script which grabs the primary server’s ‘bb-hosts’ via HTTP, which does some simple comparisons, and over-writes the local Xymon ‘bb-hosts’ if changes are detected.
  • Automat this script with cron.

Perhaps the trickiest part of doing this is the actual script used to grab, compare, and over-write the ‘bb-hosts’ file for the other instances of Xymon.  The script I’ve written below grabs the primary ‘bb-hosts’ file, and does a simple MD5 comparison with md5sum, and if it detects a change in the ‘bb-hosts’ file, it will send an e-mail to notify me that this change has occurred, along with details on what has changed.

Here’s the script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/bin/bash
 
REMOTE_BB_HOSTS="/tmp/bb-hosts"
LOCAL_BB_HOSTS="/home/xymon/server/etc/bb-hosts"
BB_HOSTS_DIFFS="/tmp/bb-hosts-diffs"
 
wget http://somewebhost.domain.com/bb-hosts -qO "$REMOTE_BB_HOSTS"
 
LOCAL_MD5=`md5sum $LOCAL_BB_HOSTS  | cut -d " " -f 1`
REMOTE_MD5=`md5sum  $REMOTE_BB_HOSTS  | cut -d " " -f 1`
 
#echo "$LOCAL_MD5"
#echo "$REMOTE_MD5"
 
if [ "$LOCAL_MD5" != "$REMOTE_MD5" ]; then
        echo "Generated by $0" > $BB_HOSTS_DIFFS;
        diff $LOCAL_BB_HOSTS $REMOTE_BB_HOSTS >> $BB_HOSTS_DIFFS;
        cp $REMOTE_BB_HOSTS $LOCAL_BB_HOSTS;
        mail -s "Xymon: monitor-02 bb-hosts updated" alertme@email.com < $BB_HOSTS_DIFFS;
fi

If you need a way to keep your Xymon ‘bb-hosts’ files in sync, something along the lines of the above script just may be what you’re looking for. If you’re currently accomplishing the same thing in an interesting way, please post a comment and let me know!

Using DZEN with Xmonad to view Currently Active Network Shares

Currently Xmonad is my window manager of choice, because it’s clean, functional, and removes all the unnecessary crap that most modern desktops usually come with by default.

Although Xmonad is very cool, there are still some things that it’s lacking as far as functionality. Much of this is made up for by the use of Xmobar, Trayer, and other Xmonad compatible plugins and applications. I recently came across another one of these applications, and found it to be an exciting find. The tool is called Dzen.

Dzen is a desktop messaging tool which allows you to easily write some useful scripts, and have the output of those scripts become part of your desktop interface. Many examples of how this works are available on the Dzen webite, but some examples are as follows:

  • CPU Monitoring graphs
  • dmesg log monitoring
  • Notification of system events which are commonly found in syslog
  • E-mail or twitter alerts shown on your desktop as they come in
  • Custom calendar alerts
  • and much more..

Now this idea is not new – I remember there being a project called “OSD” (on-screen display) which essentially allows you to do the same thing. However, I think OSD was meant as more of an single message notification system, rather than the way that Dzen works, with master and slave windows, and the ability to implement menus, etc.

In any case, I decided to give Dzen a try, and am happy with the tool that I’ve been able to whip up. For the longest while, I wanted the ability for my xmonad environment to tell me, at a quick glance, what network mounts and removable devices I currently have mounted. I’m sure that this kind of information is easily available on many bloated desktops, including GNOME and KDE, but I was looking for something simple, small and configurable. Didn’t find it, so I ended up writing my own – with the help of Dzen.

Here are a couple of screenshots of how it looks:

Dzen “Active Mounts” widget (mouse out):
dzen-1

 

Dzen “Active Mounts” widget (mouse over):
dzen-2

 

I wrote the scripts fairly quickly, so I’m sure they could be written better, but I think they will provide those of you who are interested, a good example of how to implement a regularly updated notification widget with Dzen.

The scripts are written to check for changes in the mount list, and only update Dzen when a change is detected. It is written in two components:

1) A perl script which captures the mount information in the exact format that I want, and
2) a bash script which handles loading Dzen

Here’s the source code (perl script):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/perl
 
# Written by J. Bobby Lopez <jbl@jbldata.com> - 27 Jan 2010
# Script to -be loaded- by the 'dzen-mounts.bash' script
# This script can also be run by itself, if you want to dump a
# custom plain-text table of your network shares or removable
# devices.
#
# This script is meant to be utilized the Dzen notification system
# Information on Dzen can be found at http://dzen.geekmode.org/
 
use strict;
use warnings;
 
use Data::Dumper;
use Text::Table;
 
my @types = qw( cifs ntfs davfs sshfs smbfs vfat );
 
sub getmounts
{
    my @valid_mounts; # to hold mounts we want
    my @all_mounts = split (/\n/, `mount`);
    foreach my $mount (@all_mounts)
    {
        foreach my $type (@types)
        {
            if ( $mount =~ m/$type/ )
            {
                push (@valid_mounts, $mount);
            }
        }
    }
    return @valid_mounts;
}
 
sub getsizes
{
    my @mounts = getmounts();
    my @list;
    foreach my $mount (@mounts)
    {
        my @cols = split (/\ /, $mount);
        my @df_out = split (/\n/, `df -h $cols[2]`);
        $df_out[1] .= $df_out[2] if defined($df_out[2]);
        $df_out[1] =~ s/[[:space:]]+/\ /;
	    my @df_cols = split (/[[:space:]]+/, $df_out[1]);
        push (@list, ([@df_cols]));
    }
    return @list;
}
 
my $tb = Text::Table->new(
	"Filesystem", "Size", "Used", "Avail", "Use%", "Mounted on"
);
$tb->load(getsizes());
print "Active Mounts\n";
print $tb;

And the bash script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/bin/bash
 
# Script to load Dzen with output from 'dzen-mounts.pl' script
# Written by J. Bobby Lopez <jbl@jbldata.com> - 27 Jan 2010
#
# This script utilizes the Dzen notification system
# Information on Dzen can be found at http://dzen.geekmode.org/
 
function mountlines
{
        LINES=`perl dzen-mounts.pl|wc -l`;
        echo "$LINES"
}
 
function freshmounts
{
        OUTPUT=`perl dzen-mounts.pl`;
        echo "$OUTPUT"
}
 
function rundzen
{
        OUTPUT=`freshmounts`;
        MOUNTLINES=`mountlines`;
        echo "$OUTPUT" | dzen2 -p -l "$MOUNTLINES" -u -x 500 -y 0 -w 600 -h 12 -tw 120 -ta l &
        PID=`pgrep -f "dzen2 -p -l $MOUNTLINES -u -x 500 -y 0 -w 600 -h 12 -tw 120 -ta l"`;
        echo "$PID"
}
 
function killdzen
{
        PID="$1"
        if [ ! "$PID" ]; then
            MOUNTLINES=`mountlines`;
            PID=`pgrep -f "dzen2 -p -l $MOUNTLINES -u -x 500 -y 0 -w 600 -h 12 -tw 120 -ta l"`;
        fi
 
        if [ "$PID" ]; then
            #echo "Killing $PID..";  # DEBUG STATEMENT
            kill "$PID";
        fi;
}
 
function checkchanges
{
    while true; do
        NEW=`freshmounts`;
        #echo "$NEW - new";  # DEBUG STATEMENT
        if [ "$OLD" != "$NEW" ]; then
            killdzen "$PID";
            rundzen;
            #echo "$PID started";  # DEBUG STATEMENT
            OLD="$NEW";
            #echo "$OLD - old updated"  # DEBUG STATEMENT
        fi
        sleep 1;
    done
}
 
checkchanges

You can also download the scripts in a tgz archive here. Enjoy!