Browsing AuthorCelso

Base64 Encoding and Decoding

At one time, I needed to encode and decode strings in Base64 but I was on a very old Perl version that does not include the MIME::Base64 core module, nor am I able to install the said module. So, here’s the source for encoding and decoding Base64 ripped from the MIME::Base64 module:

sub EncodeBase64
{
    my $s = shift ;
    my $r = '';
    while( $s =~ /(.{1,45})/gs ){
        chop( $r .= substr(pack("u",$1),1) );
    }
    my $pad=(3-length($s)%3)%3;
    $r =~ tr|` -_|AA-Za-z0-9+/|; 
    $r=~s/.{$pad}$/"="x$pad/e if $pad; 
    $r=~s/(.{1,72})/$1n/g; 
    $r; 
} 
 
sub DecodeBase64 
{ 
    my $d = shift; 
    $d =~ tr!A-Za-z0-9+/!!cd; 
    $d =~ s/=+$//; 
    $d =~ tr!A-Za-z0-9+/! -_!; 
    my $r = ''; 
    while( $d =~ /(.{1,60})/gs ){ 
        my $len = chr(32 + length($1)*3/4); 
        $r .= unpack("u", $len . $1 ); 
    } 
    $r; 
}

Read string from stdin using fgets

#include <stdio.h>
#include <string.h>

int main(void)
{
  char str[80];
  int i;

  printf("Enter a string: ");
  fgets(str, 10, stdin);

  /* remove newline, if present */
  i = strlen(str)-1;
  if( str[ i ] == 'n')
      str[i] = '';

  printf("This is your string: %s", str);

  return 0;
}

How to determine DST time changes

Here’s how to determine the dates when the Daylight Savings Time changes for a given year (I keep forgetting how to do this.):

zdump -v /etc/localtime|grep 2008 /etc/localtime Sun Mar 9 06:59:59 2008 UTC = Sun Mar 9 01:59:59 2008 EST isdst=0 gmtoff=-18000 /etc/localtime Sun Mar 9 07:00:00 2008 UTC = Sun Mar 9 03:00:00 2008 EDT isdst=1 gmtoff=-14400 /etc/localtime Sun Nov 2 05:59:59 2008 UTC = Sun Nov 2 01:59:59 2008 EDT isdst=1 gmtoff=-14400 /etc/localtime Sun Nov 2 06:00:00 2008 UTC = Sun Nov 2 01:00:00 2008 EST isdst=0 gmtoff=-18000

 

Obviously, change 2008 to whatever year you want.

Uninstall Perl Module

Here’s how to cleanly uninstall any Perl module:

#!/usr/local/bin/perl

use ExtUtils::Packlist;
use ExtUtils::Installed;

$ARGV[0] or die "Usage: $0 Module::Namen";

my $mod = $ARGV[0];

my $inst = ExtUtils::Installed->new();

foreach my $item (sort($inst->files($mod))) {
         print "removing $itemn";
         unlink $item;
}

my $packfile = $inst->packlist($mod)->packlist_file();
print "removing $packfilen";
unlink $packfile;

Find Out the Top 10 CPU Hogs

I found this command useful in finding out which top 10 processes are hogging my CPU resources. Note that this command is specific to the Red Hat flavor of Linux. See the man page for ps for the correct output format to use for your specific platform:

ps -eo pcpu,pid,user,args | sort -k1 -r | head -11

Substitue pcpu above with pmem to see the memory hogs instead.