Tuesday, November 20, 2012

[Bash] change current workspace by calling a script function

# to change current path using a customized script function
# instead of using alias. Need put this function in .bashrc
#    e.g.,
#            mycd ex1 ==> cd ~/scripttest/ex1
#            mycd ex2 ==> cd ~/scripttest/ex2
#            mycd eX2 ==> cd ~/scripttest/ex2
#   @ http://scriptdemo.blogspot.com 

function mycd (){
 if [ $# -ne 1 ]; then
    echo "Usage:"
    echo " mycd foldername"
 else
    targetF=`echo $1 | awk '{print tolower($1)}'`
    targetP=${HOME}/scripttest/${targetF}
    if [ -d ${targetP} ]; then
       eval "cd ${targetP}"
    else
       echo "${targetP} does not exist!"
    fi
    unset targetF
 fi
}

Monday, August 27, 2012

[Matlab] bar/tube plot along a 3d path

function hbarplot=barplot(x,y,z,varargin)
% plot a 3d surface/tube centered at (x,y,z)
% usage:
%           hbarplot=barplot(x,y,z,varargin)
%           varargin:
%                       'v' : the cdata values, same size as z
%                       'n' : N-isogon as the basic shape
%                       'r' : radius of the N-isogon
%    e.g.,
%          zz=0:0.5:10;
%          hh=barplot(cos(zz/10*pi),5,zz,'v',randn(1,numel(zz))+sin(zz/10*pi),'n',4,'r',sin(zz/10*pi)); view(3)
%          http://scriptdemo.blogspot.com

clc;
myN=3; myR=0.5; isV=0;
if nargin>3
   while(size(varargin,2)>0)
      switch lower(varargin{1})
      case {'v','cdata','colordata','facecolordata'}
          v=varargin{2};
          varargin(1:2)=[];
          isV=1;
      case {'n','nshape'}
          myN=varargin{2};
          varargin(1:2)=[];
      case {'r','radius'}
          myR=varargin{2};
          varargin(1:2)=[];
      otherwise
          error(['Not defined properties!',varargin{1}])
      end
   end
elseif nargin==0
   % demo case
   zz=0:0.5:10;
   hbarplot=barplot(cos(zz/10*pi),5,zz,'v',randn(1,numel(zz))+sin(zz/10*pi),'n',4,'r',sin(zz/10*pi));
   view(-150,30);
   return
elseif nargin<3
   help barplot
   return
end

[xx,yy,zz]=getMeshN(x,y,z,myR,myN);
if isV==0
   hbarplot=surface(xx',yy',zz');
else
   if numel(v)==numel(z)
      vv=repmat(reshape(v,[],1),1,size(xx,2));
   end
   hbarplot=surface(xx',yy',zz');
   set(hbarplot,'cdata',vv');
end
set(hbarplot,'tag','barplot','linestyle','none','facecolor','interp');
axis off equal
set(gcf,'color','w');

function [xx,yy,zz]=getMeshN(x0,y0,z,myR,N)
if nargin==3
   myR=0.5;
   N=3;
elseif nargin==4
   N=3;
elseif nargin~=5
   error('Usage: [xx,yy,zz]=getMeshN(x,y,z,myR,N)');
end
z=reshape(z,[],1);
numZ=numel(z);

myAng=linspace(0,2*pi,N+1);
xslab=cos(myAng); yslab=sin(myAng);
%N=numel(xslab)-1; % could be other shape as well.

if numel(x0)==1
   x0=repmat(x0,numZ,N+1);
elseif numel(x0)==numZ
   x0=repmat(reshape(x0,[],1),1,N+1);
end
if numel(y0)==1
   y0=repmat(y0,numZ,N+1);
elseif numel(y0)==numZ
   y0=repmat(reshape(y0,[],1),1,N+1);
end

if numel(myR)==1
   xx=repmat(xslab*myR,numZ,1)+x0;
   yy=repmat(yslab*myR,numZ,1)+y0;
else
   myR=repmat(reshape(myR,[],1),1,N+1);
   xx=repmat(xslab,numZ,1).*myR+x0;
   yy=repmat(yslab,numZ,1).*myR+y0;
end
zz=repmat(z,1,N+1);




Sunday, August 26, 2012

[Matlab] fill a specific-value region with a given color

function FillIt(lon,lat,Land,FillC,TagType,FillValue)
% To fill a specific-value region with a given color
% Usage:
%            FillIt(lon,lat,Land,FillC,TagType,FillValue)
%                   TagType: could be 'RU' or 'LD', 
%                                 to fill right-up square or left-down square
%                   FillValue: nan [default] or specific value to fill with color [FillC]
%            Note: lon, lat, Land must be the same size
%      e.g.,
%            FillIt(lon,lat,lsmask,[0.0 0.3 0.3],'RU')
%      http://scriptdemo.blogspot.com

if nargin==0
   %demo
   load topo topo;
   topo(topo>0)=nan;
   xx=1:360; yy=1:180;
   [xx,yy]=meshgrid(xx,yy);
   FillIt(xx,yy,topo,[0.4 0.3 0.4],'RU');
   set(gca,'tickdir','out','linewidth',2,'xminortick','on','yminortick','on','box','on','fontweight','bold');
   set(gcf,'color','w'); axis equal; axis tight;
   return
end

if nargin==3
   FillC=[0.3 0.3 0.3];
   TagType='RU';
   FillValue='nan';
elseif nargin==4
   TagType='RU';
   FillValue='nan';
elseif nargin==5
   FillValue='nan';
elseif nargin~=6
   help FillIt;
   return
end

if numel(lon)~=numel(lat)
   disp('lon and lat must be the same size')
   return
end
if numel(lon)~=numel(Land)
   disp('lon/lat and land must be the same size')
   return
end

[Ny,Nx]=size(Land);
if ischar(FillValue)
   if strcmpi(FillValue,'nan')
      [Indy,Indx]=find(isnan(Land));
   else
      disp(['invalid fill value: ',FillValue])
      return
   end
elseif isnumeric(FillValue)
      [Indy,Indx]=find(Land==FillValue);
else
      disp('invalid fill value')
      return
end

switch upper(TagType)
   case 'RU'
      % Right Up
      % 4----3
      % |      |
      % 1----2
      Indx(Indy==Ny)=[];Indy(Indy==Ny)=[];
      Indy(Indx==Nx)=[];Indx(Indx==Nx)=[];
      Fillx(1,:)=lon((Indx-1)*Ny+Indy);
      Fillx(2,:)=lon((Indx)*Ny+Indy);
      Fillx(3,:)=lon((Indx)*Ny+Indy+1);
      Fillx(4,:)=lon((Indx-1)*Ny+Indy+1);
      Fillx(5,:)=lon((Indx-1)*Ny+Indy);

      Filly(1,:)=lat((Indx-1)*Ny+Indy);
      Filly(2,:)=lat((Indx)*Ny+Indy);
      Filly(3,:)=lat((Indx)*Ny+Indy+1);
      Filly(4,:)=lat((Indx-1)*Ny+Indy+1);
      Filly(5,:)=lat((Indx-1)*Ny+Indy);
   case 'LD'
      % Left Down
      % 2----1
      % |     |
      % 3----4
      Indx(Indy==1)=[];Indy(Indy==1)=[];
      Indy(Indx==1)=[];Indx(Indx==1)=[];
      Fillx(1,:)=lon((Indx-1)*Ny+Indy);Filly(1,:)=lat((Indx-1)*Ny+Indy);
      Fillx(2,:)=lon((Indx-2)*Ny+Indy);Filly(2,:)=lat((Indx-2)*Ny+Indy);
      Fillx(3,:)=lon((Indx-2)*Ny+Indy-1);Filly(3,:)=lat((Indx-2)*Ny+Indy-1);
      Fillx(4,:)=lon((Indx-1)*Ny+Indy-1);Filly(4,:)=lat((Indx-1)*Ny+Indy-1);
      Fillx(5,:)=lon((Indx-1)*Ny+Indy);Filly(5,:)=lat((Indx-1)*Ny+Indy);
   otherwise
     disp('Not defined Fill Type')
     help FillIt
     return
end

if ~ishold; hold on; end
hf=patch(Fillx,Filly,FillC);
set(hf,'linestyle','none','tag','fillIt');

Friday, August 24, 2012

[Matlab] show 2d mesh grid

function ShowGridLine(lon,lat,NSkip,LineC,LineS,LineM)
% To show a 2d mesh-grid defined by given grid points
% similar to the function mesh?
% Example:
%          ShowGridLine(lon,lat,2,'k','-','.')
%          http://scriptdemo.blogspot.com
%

if (nargin>3)
    if exist('LineC','var')~=1 LineC='k'; end
    if exist('LineS','var')~=1 LineS='-'; end
    if exist('LineM','var')~=1 LineM='none'; end
elseif (nargin>=2)
    if exist('NSkip','var')==1
        if ischar(NSkip) LineC=NSkip; clear NSkip; end
    end
    if exist('NSkip','var')~=1 NSkip=5; end
    if exist('LineC','var')~=1 LineC='k'; end
    if exist('LineS','var')~=1 LineS='-'; end
    if exist('LineM','var')~=1 LineM='none'; end
elseif (nargin==0)
    close all;
    [xx,yy]=meshgrid(1:19,1:19);
    ShowGridLine(xx,yy,1,'k','-');
    plot(4,4,'o','markerfacecolor','k','markersize',4,'markeredgecolor','k');
    plot(16,16,'o','markerfacecolor','k','markersize',4,'markeredgecolor','k');
    plot(4,16,'o','markerfacecolor','k','markersize',4,'markeredgecolor','k');
    plot(16,4,'o','markerfacecolor','k','markersize',4,'markeredgecolor','k');
    set(gcf,'color','w');
    set(gca,'xtick',2:2:18,'ytick',2:2:18,'ydir','r','xaxislocation','top')
    axis equal; axis tight;
    xlabel('Go Board','fontweight','bold','fontsize',18,'color','red');
    return
else
    help ShowGridLine
    return
end

[N1,N2]=size(lat);
if ~ishold hold on; end
for NL=1:NSkip:N2
    hp=plot(lon(:,NL),lat(:,NL));
    set(hp,'color',LineC,'linestyle',LineS,'Marker',LineM)
end
for NL=1:NSkip:N1
    hp=plot(lon(NL,:),lat(NL,:));
    set(hp,'color',LineC,'linestyle',LineS,'Marker',LineM,'tag','gridLines')
end
Demo:

Thursday, July 5, 2012

[Bash] remove the temporary files generated by latex

#!/bin/bash
# to clean the "*.blg *.bbl *.aux *.spl" files
# usage:
#          cleanlatex option
#                          -l : just list those files
#                          -f : remove by force
#                      -dvi : dvi files as well
#                  -name : only those with a specifc filename
#    e.g.,
#          cleanlatex -l
#          cleanlatex -f -name pdftest -dvi
#          http://scriptdemo.blogspot.com   

[ $# -eq 0 ] && sed -n '3,11p' `which cleanlatex` && exit

isFLname=0
isForce=0
isList=0
isDvi=0
isDebug=0
fname='*'

while test -n "$1"
do
     case "$1" in
      -l|-L)
        isList=1
        shift
        ;;
      -f|-F|-force|-del|-remove)
        isForce=1
        shift
        ;;
      -dvi)
        isDvi=1
        shift
        ;;
      -name)
        fname=$2
        fname=${fname%.*}
        shift;
        shift;
        ;;
      -debug|-Debug)
        isDebug=1
        shift
        ;;
      *)
        echo "unkown option: $1"
        shift
        ;;
     esac
done

[ ${isList} -eq 1 ] && isForce=0
flist="${fname}.spl ${fname}.aux ${fname}.bbl ${fname}.blg ${fname}.log"
[ ${isDvi} -eq 1 ] && flist="${flist} ${fname}.dvi"
if [ ${isForce} -eq 0 ]; then
   if [ ${isDebug} -eq 1 ]; then
      echo "ls ${flist}"
   else
      eval "ls ${flist} 2>/dev/null"
   fi
   exit
else
   if [ ${isDebug} -eq 1 ]; then
      echo "rm -f ${flist}"
   else
      eval "rm -f ${flist} 2>/dev/null"
   fi
fi

[Bash] mail2me: send email with attachments from terminal

This is mutt version. A "mail" version is here.
#!/bin/bash
# send files to an email account as the attachment(s)
# usage:
#           mail2me email -s 'YourSubject'  YourAttachments
#           http://scriptdemo.blogspot.com

function isEmail()
{
   cEmail=`echo $1 | grep "^[a-zA-Z]\+\([._][a-zA-Z0-9]\+\)*@\([a-zA-Z0-9]\+\.\)\+[a-zA-Z]\{2,3\}$"`
   if [ ${#cEmail} -gt 0 ]; then
      echo "true"
   else
      echo "false"
   fi
}
function isServerOn()
{
  myS=$1
  myp=`ping -c 2 ${myS} 2>&1 | grep "% packet" | awk '{print $6*100}'`
  if [ ${#myp} -eq 0 ]; then
     echo "-1" #server: ${myS} is not valid
  elif [ ${myp} -eq 100 ]; then
     echo "0" #server: ${myS} is off
  else
     echo "1" #server: ${myS} is $(( 100 - ${myp}))% response
  fi
}

if [ $# -le 1 ]; then
   echo "usage: mail2me email -s Subject file1 [file2] ..."
   exit
fi

#check email
targetEmail=$1
isValidEmail=`isEmail ${targetEmail}`
[ ${isValidEmail} == "false" ] && echo "${targetEmail} is not a valid email address!!!" && exit

#check smtp server
smtpS=`echo ${targetEmail} | awk -F\@ '{print $2}'`
smtpS="smtp.${smtpS}"
isOnline=`isServerOn ${smtpS}`
if [ ${isOnline} == "-1" ]; then
     echo "SMTP server: ${smtpS} is invalid. STOP" && exit
elif [ ${isOnline} == "0" ]; then
     echo "SMTP server: ${smtpS} is offline. STOP" && exit
fi

#send email
numF=0
nf=2
isDebug=0
shift #shift the email
while [ $# -ge 1 ]
do
    case $1 in
       -s|-S)
         mysubj=$2
         shift; shift;
         ;;
       -d|-D)
         isDebug=1
         shift
         ;;
       *)
         if [ -f ${tmpfn} ]; then
            myfile[${numF}]=$1
            numF=`expr ${numF} + 1`
         else
            echo "$1 is not found!"
         fi
         shift
         ;;
     esac
done

if [ ${numF} -eq 1 ]; then
   [ ${#mysubj} -eq 0 ] && mysubj="[script] ${myfile[0]}"
elif [ ${numF} -gt 1 ]; then
   [ ${#mysubj} -eq 0 ] && mysubj="[script] backup ${myfile[0]} etc."
else
   echo "no file is found!!!" && exit
fi

if [ ${isDebug} -eq 1 ]; then
   echo "echo \"The attachment is ${myfile[*]} sent by `whoami` from `hostname`\" | mutt -s '${mysubj}' -a ${myfile[*]} -- ${targetEmail}"
else
   echo "The attachment is ${myfile[*]} sent by `whoami` from `hostname` " | mutt -s "${mysubj}" -a ${myfile[*]} -- ${targetEmail}
fi

Thursday, June 21, 2012

[Bash] png2pdf: convert png files into a single pdf file

Download link
#!/bin/bash
# to convert png files into a single pdf file using pdflatex
# usage:
#           png2pdf.sh png-file[s] -o png2pdf.pdf -nC nCol -nR nRow
# e.g.,
#          Given 12 png files (one for each month) with a name like "ssh_??.png",
#          to create a 3-pages pdf file with 2 by 2 on each page,
#          and a caption like "Fiugre* Sea Surface Height \\ ??; ?? \\ ??; ??"
#          where \\ means line break and ?? is the month-tag in original png filename.
#          you can run,
#            png2pdf.sh -o ssh_monthly.pdf -nC 2 -nR 2 ssh_??.png -title 'Sea Surface Height' -ns 5 -ne 6
#                               [ here -ns: start-index of characters for the caption; -ne: end-index]
#          or
#           png2pdf.sh -o ssh_monthly.pdf -nC 2 -nR 2 ssh_??.png -title 'Sea Surface Height' -sep '_' 2
#                               [-sep: field seperator, 2 is the No. of field used for the caption]
#
#         http://scriptdemo.blogspot.com

fixCaption()
{
    echo $* | sed -e 's@_@--@g'
}

nfile=0
isPDFname=0
isnCol=0
isnRow=0
isDel=0
isCaption=0
isSep=0
isDebug=0


[ $# -eq 0 ] && sed -n '3,17p' `which png2pdf.sh` && exit

while test -n "$1"
do
  case "$1" in
    -nC|-nc|-nCol|-ncol|-Ncol)
       nCol=$2
       isnCol=1
       shift
       shift
       ;;
    -nR|-nr|-nRow|-Nrow|-nrow)
       nRow=$2
       isnRow=1
       shift
       shift
       ;;
    -title|-Title|-Caption|-caption|-c)
       myCaption=$2
       isCaption=1
       shift
       shift
       ;;
    -sep|-Sep|-seperator)
       mysep=$2
       mynf=$3
       isSep=1
       isCaption=1
       shift;
       shift;
       ;;
    -ns|-NS|-CS|-cs)
       cstart=$2
       isCaption=1
       shift
       shift
       ;;
    -ne|-NE|-CE|-ce)
       cend=$2
       isCaption=1
       shift
       shift
       ;;
    -d|-delete|-del|-D)
       isDel=1;
       shift
       ;;
    -debug|-Debug)
       isDebug=1
       shift
       ;;
    -o|-O)
       pdfname=$2
       isPDFname=1
       shift
       shift
       ;;
     *)
       sufstr=`echo $1 | awk -F. '{print $2}'`
       if [ ${#sufstr} -eq 0 ]; then
          tmpfile="$1".png
          if [ -f ${tmpfile} ]; then
             imgfile[$nfile]=${tmpfile}
             nfile=`expr $nfile + 1`
          fi
       elif [ -f $1 ]; then
          if [ -f $1 ]; then
             imgfile[$nfile]=$1
             nfile=`expr $nfile + 1`
          fi
       fi
       shift
       ;;
  esac
done
if [ ${isnRow} -eq 0 ] && [ ${isnCol} -eq 0 ]; then
   nCol=1
   nRow=1
   nPage=${nfile}
elif [ ${isnCol} -eq 1 ] && [ ${isnRow} -eq 0 ]; then
   nRow=`echo "${nfile}/${nCol}" | bc -l | awk '{ if ($1 == int($1)) {printf "%d\n", $1} else { if ($1>0) {printf "%d\n",int($1)+1 } else {printf "%d\n",int($1)} } }'`
   nPage=1
elif [ ${isnRow} -eq 1 ] & [ ${isnCol} -eq 0 ]; then
   nCol=`echo "${nfile}/${nRow}" | bc -l | awk '{ if ($1 == int($1)) {printf "%d\n", $1} else { if ($1>0) {printf "%d\n",int($1)+1 } else {printf "%d\n",int($1)} } }'`
   nPage=1
else
   nPage=`echo "${nfile}/${nRow}/${nCol}" | bc -l | awk '{ if ($1 == int($1)) {printf "%d\n", $1} else { if ($1>0) {printf "%d\n",int($1)+1 } else {printf "%d\n",int($1)} } }'`
fi
if [ ${isCaption} -eq 1 ]; then
   if [ ${#cend} -ne 0 ] & [ ${#cstart} -eq 0 ]; then
      cstart=1
   fi
fi
colstr=`printf "%*s\n" ${nCol} " " | sed -e 's/\ /c/g'`
nwidth=$(printf "%.2f\n" `echo "1/${nCol}" | bc -l`)

[ ${nwidth} == "1.00" ] && nwidth=""
[ ${isDebug} -eq 1 ] && echo -e "nCol=${nCol}\nnRow=${nRow}\nnWid=${nwidth}\nnPage=${nPage}"

# header of tex file
[ ${isPDFname} -eq 0 ] && pdfname="png2pdf.pdf"
texfile=${pdfname%.*}.tex
[ -e ${texfile} ] && mv ${texfile} old_${texfile}
touch ${texfile}

echo '\documentclass[letterpaper,12pt]{article}' >> ${texfile}
echo '\usepackage{graphicx}' >> ${texfile}
[ ${isCaption} -eq 1 ] && echo '\usepackage{caption}' >> ${texfile}
echo '\begin{document}' >> ${texfile}

for (( np=0; np<${nPage}; np++ ))
do
    echo '\thispagestyle{empty}' >> ${texfile}
    echo '\begin{figure}' >> ${texfile}
    echo '\centering' >> ${texfile}
    echo "\begin{tabular}{${colstr}}" >> ${texfile}

    ns=`expr ${np} \* ${nCol} \* ${nRow}`
    if [ ${isCaption} -eq 1 ] && [ ${#myCaption} -ne 0 ]; then
       if [ ${#cstart} -ne 0 ] || [ ${#cend} -ne 0 ]; then
          tmpCaption="${myCaption} \protect \\\\"
       else
          tmpCaption="${myCaption}"
       fi
    else
       tmpCaption=""
    fi
    for (( nL=0; nL<${nRow}; nL++ ))
    do
       nss=`expr ${ns} + ${nCol} \* ${nL}`
       for (( nC=0; nC<${nCol}; nC++ ))
       do
           nfig=`expr ${nss} + ${nC}`
           if [ ${nfig} -lt ${nfile} ]; then
              imgname=${imgfile[$nfig]}
              if [ ${nC} -eq `expr ${nCol} - 1` ]; then
                 if [ ${nL} -eq `expr ${nRow} - 1` ]; then
                    tmpstr=""
                 else
                    tmpstr=" \\\\"
                 fi
              else
                 tmpstr=" &"
              fi

              if [ ${nL} -eq `expr ${nRow} - 1` ] && [ ${nC} -eq `expr ${nCol} - 1` ]; then
                 tmpstr=""
              fi
              [ ${nfig} -eq `expr ${nfile} - 1` ] && tmpstr=""
              if [ ${isCaption} -eq 1 ]; then
                 if [ ${isSep} -eq 0 ]; then
                    if [ ${#cend} -eq 0 ]; then
                       subfn=`echo ${imgname} | cut -c${cstart}-`
                    else
                       subfn=`echo ${imgname} | cut -c${cstart}-${cend}`
                    fi
                 else
                    subfn=`echo ${imgname} | cut -d${mysep} -f${mynf}`
                    #echo "${imgname} "sep="${mysep} nf=${mynf} ==> ${subfn}"
                 fi
                 if [ ${#subfn} -ne 0 ]; then
                    [ "${tmpstr}" == "" ] && tmpCaption="${tmpCaption}${subfn}"
                    [ "${tmpstr}" == " \\\\" ] && tmpCaption="${tmpCaption}${subfn} \protect \\\\ "
                    [ "${tmpstr}" == " &" ] && tmpCaption="${tmpCaption}${subfn}; "
                 fi
              fi
              echo "\includegraphics[width=${nwidth}\linewidth]{${imgname}} ${tmpstr}" >> ${texfile}
           fi
       done
    done
    echo "\end{tabular}" >> ${texfile}
    if [ ${isCaption} -eq 1 ]; then
       tmpCaption=`fixCaption ${tmpCaption}`
       echo "\caption{${tmpCaption}}" >> ${texfile}
    fi
    echo "\end{figure}" >> ${texfile}
    [ ${np} -lt `expr ${nPage} - 1` ] && echo "\clearpage" >> ${texfile}
done

echo "\end{document}" >> ${texfile}
[ ! -f ${texfile} ] && echo "failed to create tex file ==> exit" && exit

#compile the tex file
logfile=${pdfname%.*}.log
auxfile=${pdfname%.*}.aux
if [ ${isDebug} -eq 1 ]; then
   pdflatex ${texfile}
else
   pdflatex -interaction=batchmode ${texfile} 1>/dev/null
fi
[ -f ${logfile} ] && rm -f ${logfile}
[ -f ${auxfile} ] && rm -f ${auxfile}
[ ${isDel} -eq 1 ] && rm -f ${texfile}

ShowCalendar