Friday, October 29, 2010

Perl World clock

Heres another hacked up script that gives the time locally on the system(mine is NYT), the time in japan and the number of seconds fro NYT midnight..

Try running it(called datetime.pl) with these commands lines:
./datetime.pl 
./datetime.pl "7:00"
./datetime.pl "+ 1 day + 1 hours"
./datetime.pl "-10 seconds"

#!/usr/bin/env perl

use strict;
use Date::Manip;

sub string2date
{
    my ($str) = @_;
    return int(UnixDate($str, "%s")); 
}

sub date2string
{
    my ($time) = @_;
    return UnixDate("epoch $time", "%m/%d/%y %H:%M:%S"); 
}

sub date2timezone
{
    my ($time, $tz) = @_;

    return UnixDate(Date_ConvTZ(ParseDate("epoch $time"), '', $tz), '%m/%d/%y %H:%M:%S');
}

sub date2midnightSec
{
    my ($time) = @_;
    my @a = localtime($time); 
    return 3600*@a[2] + 60*@a[1] + @a[0];
}

my $intime = $ARGV[0];
$intime = 'now' unless defined $intime;

my $rawInTime  = string2date($intime);
print "NYT: " . date2string($rawInTime) . "\n";
print "JST: " .  date2timezone($rawInTime, "JST") . "\n";
print "Midnight Seconds: " .  date2midnightSec($rawInTime) . "\n";

hacky crontab replacement in perl

I love system admins. I have been one my self. All that power at the tips of my fingers, and a manager with a big club behind me, waiting to play wack a mole with my fingers if i mees up. Of course system admins can tell a coder that he doesn't have access to cron.... but guess what: cron was written by programmers soo.... hack yourself up a 30 min crontab system in perl and chuckle in your sleep.

Heres my hacked up mess for the day.

#!/usr/bin/env perl

use strict;
use Date::Manip;

#For the valid formats look at 
#http://search.cpan.org/~muir/Time-modules-2003.0211/lib/Time/ParseDate.pm

my $period = 10;
my @tasks = (
             { time => "09:00:00", label => "morning", cmd  => "echo 'good morning'"},
             { time => "01:34:00", label => "Hi", cmd  => "echo 'good morning'"},
             { step => "+ 1 minutes", label => "5 mins", cmd  => "echo '5 mins'"},
             { step => "+ 10 seconds", label => "10 seconsd", cmd  => "echo '5 mins'"}
             
             );

sub string2date
{
    my ($str) = @_;
    return int(UnixDate($str, "%s")); 
}

sub secsDiff
{
    my ($str) = @_;
    return string2date($str) - string2date("now");
}

sub update_firetime
{
    my ($task, $now) = @_;
    my $new = $now;
    if(defined $task->{time})
    {
        $new = string2date($task->{time});
        $new += secsDiff("+ 1 day") if $new < $now;
    }
    elsif(defined $task->{step})
    {
        $new  = $now;
        $new += secsDiff($task->{step}) while $new <= $now;
    }
    $task->{fire_time} = $new;

}

sub boot
{
    my $now = string2date("now");    
    update_firetime($_, $now)
        foreach (@tasks);
}

sub execute
{
    my ($task) = @_;

    my $pid = fork();
    if((defined $pid) && ($pid == 0)) 
    {
        if(defined $task->{xterm} && $task->{xterm} == 1)
        {
            #boot and leave an xt
            my $label   = $task->{label};
            my $cmd     = $task->{cmd};
            my $sys_cmd = "xterm -xrm 'XTerm*foreground: red3' -xrm 'XTerm*background: black' -title 'CRONTAB:$label' -e sh -c \"$cmd; ksh\" &";
            
            system($sys_cmd);
        }
        else
        {
            #just execute it..
            system($task->{cmd});
        }
        exit(0);
    }
}

sub cron_core
{
    while(1)
    {
        my $now = string2date("now");
        foreach my $task (@tasks)
        {
            if($now > $task->{fire_time})
            {
                print "fire! $task->{label}\n";
                execute($task);
                update_firetime($task, $now) 
            }
        }
        #cron loop an launch
        
        print("sleeping.....\n");
        sleep($period);
    }
}

print "Operating with an accuracy of +/-$period seconds\n";

boot();
cron_core();

Monday, October 25, 2010

Checking the version of a ksh

The system admins at my office are crazy they just replaced sh with ksh... evil little monsters... Here how to pull the ksh version

ksh
set -o vi

Now type esc and then Ctrl-V. The version of ksh will appear on the prompt. Something like "Version M-11/16/88f"

Yes its insane but so is ksh...

Friday, October 22, 2010

Profiling perl

The main problem with perl scripts is that they get hacked too much and this generally results in them either breaking or ending up doing useless things... DProf is the older perl profiling lib, and can easily be booted from the command line via a direct call to perl with the debug option. Basically it requires no mod of your existing script(assuming the script is the standard #!/usr/bin/env perl type).

perl -d:DProf <script_file>
dprofpp

It produces a file called "tmon.out" that is processed with "dprofpp" into a human readable form. After that point its up to you to find and kill the pointless junk.

Kindergarden science - Biology

My young daughter has reached 4 years old and I have decided its time to get her started with some basic science. Everyone knows about the classic carrot-top in a dish experiment. So here is the recipe for it;

Stage0) Adult basics.
  • Young kids learn alot by mimicry
    • How you act and react will directly teach them. More than what you say about it
    • They will learn good scientific procedure if you show them it rather than tell them it
  • Young kids have an very short attention span about 15mins max.
    • Experiments need to have simple easy to understand objectives
    • You must prep the materials before hand or the child might wander off or lose interest before its ready.
    • Experiments need to be piece wise if they are long, take a break if its too long and rekindle your kids interest
    • Experiments need to have a fascinating or intriguing result.
    • Sometimes things go wrong or you get stuck it is best to get the kid of on a side project while you sort it out or risk them becoming confused and frustrated as you do.
  • You dont want kids handling dangerous stuff, but you want the child to learn enough practical caution
    • For example using scissors is ok, but using them badly or in a way not intended will teach your kid to do the same.
    • With chemistry experiments think food science, if it cant be eaten or goes boom then its most likely not suitable for a young kid.

Stage 1) Create some interest (And adult prep)
Take a carrot, and cut of the top(about 1 cm thick) and take it to your kid. Ask her what it is what she thinks about it. Ask her where it came from and how it grew up to be a carrot. Explain to her the that the carrot is still alive even now and we can make it grew again. Ask her if she believes it. Ask her if she wants to see it happen.

Stage 2) Prep the experiment(done by your kid)
Gather the materials, A plastic container, cup of water, the carrot top, and a piece of paper(the less the bleach and artificial coloring the better)

Stage 3) Experiment(done by the child)
Place the paper in the container, add the carrot on top, poor on the water(about 1/3 of the carrot should be underwater) and place near a sunny window. Go play elsewhere

Stage 4) Measure and discuss(done by the child)
Come back every day with a log book, ruler and pencil. Ask her about what has changed and measure how long the new green sprouts and roots are. Write it down in the log book. Then after a week create a graph and play connect the dots with her.

Stage 5) End the Experiment(done by the child)
After a while this will start to get monotonous and the fascination will end, it is best not to kill your kids enthusiasm by over doing it. My daughter choose to end this experiment by feeding the new carrot sprouts to a rabbit.

To sum it up you have exposed your child to;
  • Basic experimental procedure
  • Measurement and logging of results
  • Basic charting
  • Basic biology; What are Roots, What are Leaves, What are Stems
  • Basic biology; Planets grow slowly and fresh veggies are alive
http://www.dummies.com/how-to/content/plant-biology-roots-shoots-stems-and-leaves.html

Thursday, October 21, 2010

Stream wrappers for cerr and cout

Its always convient to have a quick wrapper class at your finger tips to turn on or off all output from you system in one foul swoop. Here is a class that adds a layer of indirection to output and allows you to go into a "testing" mode where all output is suppressed

//compile with g++

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

class Streams 
{
public:
static Streams& instance()
    {
        static Streams* self = NULL;
        if(self == NULL)
        {
            self = new Streams();
        }
        return *self;
    }

    static inline std::ostream& out() { return *(instance().out_); }
    static inline std::ostream& err() { return *(instance().err_); }

    void setNormal()
    {
        out_ = &std::cout;
        err_ = &std::cerr;
    }

    void setRedirected()
    {
        if(test)
        {
            delete test;
        }
        test = new std::ostringstream();
        out_ =  test;
        err_ =  test;
    }

private:
    Streams() { test = NULL; setNormal(); }
    ~Streams() { if(test) delete test; }

    std::ostream* test;
    std::ostream* out_;
    std::ostream* err_;
};

int main()
{
    Streams::out() << "bah bah bah" << endl;
    Streams::err() << "err erh ber" << endl;

    Streams::instance().setRedirected();

    Streams::out() << "bah bah bah" << endl;
    Streams::err() << "err erh ber" << endl;
}

Wednesday, October 20, 2010

Object Anti-patterns

Object design patterns are great but there are many pit falls from over engineering a system or creating designs that become menaces, They have become know as the Anti-patterns.

Im currently trying to explain why a class that lists its objective as "This can either be seconds-from midnight. Or a time_t with a date." is a very bad idea.

I dont understand why people dont get it. Its basically a "Staralised schema" IE one object trying to be both things at the same time... and violates the "Single Responsibility principle"

UPDATE:
I have tried exploring the issues that occur with the implementation of an operator+ for this dual purpose class with them but they seem tied to the idea that what is in disk MUST be represented as is in memory.

I have also explain that when the class is viewed in isolate it loses the format information related to the time. This is because the Time classes main use is as an aggregate data-member and the aggregator classes type gives an implicit indication of what the Aggregatees time format is... I have even shown them code that proves the point and exposes many of the problems. To all this effort they have responded with "well maybe you should write/use a whole new time class for that"..

The main reason why I am fighting this so hard boils down the fact that these guys control QA in the system, and unless I can change there minds the problem will remain and other coders will continue to created hacks that avoid issues. These hacks then have a knock on effect(violation of Encapsulation principle) and become maintenance nightmares later...

Refer:
http://www.worldlingo.com/ma/enwiki/en/Anti-pattern

http://en.wikipedia.org/wiki/Single_responsibility_principle

Friday, October 15, 2010

bitsets

The STLs Bitsets are a great way to get flexible and expandable masking and flag logic without using using uints. They print nicely, mask correctly and are very readable compared to inline masking logic.

//complie with g++
#include <iostream>
#include <bitset>

using namespace std;

int main()
{
    const int count=50;
    bitset<count> bits;
    uint32_t      mask;

    bits = 0;
    mask = 0;

    cout << "All off" << endl;
    cout << bits << endl;
    cout << hex << mask << endl;

    //setting
    for(int i=0; i<count; i+=3)
    {
        bits[i] = true;        
        mask |= 1<<i;
    }

    cout << "Every 3rd on" << endl;
    cout << bits << endl;
    cout << hex << mask << endl;

    //masking test
    cout << "Self invert with ^" << endl;
    cout << (bits ^ bits) << endl;
    cout << hex << (mask ^ mask) << endl;

    cout << "Self mask with &" << endl;
    cout << (bits & bits) << endl;
    cout << hex << (mask & mask) << endl;

    //turn on all
    bits = 0; bits.flip();
    mask = -1;

    cout << "All on" << endl;
    cout << bits << endl;
    cout << hex << mask << endl;

    bits = -1; bits.flip();

    cout << "when bits are: " << bits << endl;
    cout << "check any on:  " << (bits != 0) << endl;
    cout << "check any off: " << (~bits != 0) << endl;

    bits = 0;

    cout << "when bits are: " << bits << endl;
    cout << "check any on:  " << (bits != 0) << endl;
    cout << "check any off: " << (~bits != 0) << endl;

    bits.flip();

    cout << "when bits are: " << bits << endl;
    cout << "check any on:  " << (bits != 0) << endl;
    cout << "check any off: " << (~bits != 0) << endl;

    return 0;
}

This outputs the following
All off
00000000000000000000000000000000000000000000000000
0
Every 3rd on
01001001001001001001001001001001001001001001001001
4925b6db
Self invert with ^
00000000000000000000000000000000000000000000000000
0
Self mask with &
01001001001001001001001001001001001001001001001001
4925b6db
All on
11111111111111111111111111111111111111111111111111
ffffffff
when bits are: 11111111111111111100000000000000000000000000000000
check any on:  1
check any off: 1
when bits are: 00000000000000000000000000000000000000000000000000
check any on:  0
check any off: 1
when bits are: 11111111111111111111111111111111111111111111111111
check any on:  1
check any off: 0

Thursday, October 14, 2010

Sum compiler typenotall error

The piece of crud excuse for a compiler has the most meaningless errors ever. "typenotall" means that something BEFORE your type/class (ie the prior line) is missing/wrong like a ";"

Thursday, October 7, 2010

Google Goggles

Well it looks like google has released an image search this stuff is seriously non-trival so anything is better than nothing!

http://www.google.com/mobile/goggles/#text

Get it for the iphone at:
http://itunes.apple.com/us/app/google-mobile-app/id284815942?mt=8

Wednesday, October 6, 2010

A hacky way to get your class streaming out

Needing a quick way to seem to contents of a classes.. dump it into cout with a overloaded operator<< and an existing print function of some kind with very little fuss..

//complie with g++
#include <iostream>
#include <sstream>

using namespace std;

class A  {
public:
    A(): str1("Hi"), str2("There") {}
 
    string print()
    {
 ostringstream out;
 out << " str1: " << str1 << endl;
 out << " str2: " << str2 << endl;
 return out.str();
    }

private:
    string str1;
    string str2;
};

ostream& operator<<(ostream& out, A& val)
{
    out << val.print();
    return out;
}

int main()
{
    A test;
    cout << test << endl;
    return 0;
}

Monday, October 4, 2010

supressing purecov messages for untested functions

Add the "purecov: begin inspected" blocks around the untestable/difficult to test code.

/* purecov: begin inspected */
void Timer::tickTock()
{
}
/* purecov: end inspected */

Determine the arch type of the executable

file <exe_name>

Sunday, October 3, 2010

Sudo trick to get a root like shell

Here is the command to get a su like shell from sudo

sudo -i

Friday, October 1, 2010

Ksh completion

Here is kshs way of getting file completion. (just another useless fact)

Keystoke Action
ESC ESC tab complete
ESC = list possible completions
ESC * expand all possible completions into command line