Friday, December 19, 2008

Login into to ssh server automatically with expect

#!/bin/expect -f
# Connect to the server, please change the username and remote server address
#   http://scriptdemo.blogspot.com

spawn ssh USERNAME@serveraddress
#send the password to the server, please change it for "send" line
expect "password:"
send "password\n"
interact

Tuesday, September 2, 2008

Using system command in different softwares

Matlab: ! COMMAND
Grads: ! COMMAND
Fortran: call system(COMMAND, status)
C: system("COMMAND")
VB: shell "COMMAND"
Ferret: sp system command
Python: import os or os.system('COMMAND')
PHP: system('command',$returnvalue) or exec('command',$output, $returnvalue)
R: system('command')
Continue.....

Monday, September 1, 2008

[Matlab] Reading Ascii data with matlab

function DataFromFile=ReadAsciiData(FileName,FMT,NumFmt)
% Function to read ascii data from a file with given format
% Usage:
%            DataFromFile=GetAsciiData(FileName,FMT,NumFmt)
%       e.g.,
%            Data=GetAsciiData('data.dat','%8f',4)
%            The data will be read in following command:
%                   Data=fscanf(fid,'%8f %8f %8f %8f',[4 inf]);
%            Same as: Data=ReadAsciiData('data.dat','%8f %8f %8f %8f')
%            http://scriptdemo.blogspot.com

fid=fopen(FileName,'r');
if (fid==-1)
   error(['Error in reading ',FileName,', Please check the file name.']);
else
   if ~exist('FMT');
      FMT='%f';
      if ~exist('NumFmt') NumFmt=1; end
      for N=1:NumFmt-1
           FMT=[FMT,' ','%f'];
      end
   else
      if ~exist('NumFmt')
         NumFmt=length(find(FMT=='%'));
      else
         for N=1:NumFmt-1
               FMT=[FMT,' ',FMT];
         end
      end
   end
   DataFromFile=fscanf(fid,FMT,[NumFmt,inf]); % [DataFromFile]=fscanf(fid,FMT);
   DataFromFile=DataFromFile';
   fclose(fid);
end

[Matlab] Saving 2D data in ASCII with matlab

function SaveDataAscii(data,filename,FileHead,Gformat)
% to save a 2d array into a ascii file as what you see in array editor
%     a format option is also provided
% Usage:
%     SaveDataAscii(data,filename,FileHead,Gformat)
% e.g.,
%       my2ddata=rand(3,5);
%       SaveDataAscii(my2ddata,'myrand2dtest.dat','it is a test','%7.4f');


isHeader=1;
if nargin==3
   Gformat='%10.4f';
elseif nargin==2
   isHeader=0;
   Gformat='%10.4f';
elseif nargin~=4
   help SaveDataAscii
   return
end
if (length(FileHead)==0)
   isHeader=0;
end

% open the file
fid=fopen(filename,'w');
if isHeader==1
   fprintf(fid,['%% ',FileHead]);
   fprintf(fid,'\n');
end

% write the datablock
for i=1:size(data,1)
    for j=1:size(data,2)
        fprintf(fid,Gformat,data(i,j));
    end;
    fprintf(fid,'\n');
end;
fclose(fid);

[Matlab] Plot rectangles with matlab

The script is not really useful. However, it shows how a matlab function works. More matlab functions will be added later.
function PlotRect(Xs,Ys,Xlen,Ylen,LineC,LineS,LineM)
% To draw rectangles with given position and properties
% Usage: PlotRect(Xs,Ys,Xlen,Ylen,LineC,LineS,LineM)
%  e.g.,
%        PlotRect(0.1,0.13,0.7,0.6,'k','-','.')
%        http://scriptdemo.blogspot.com

if exist('LineC','var')~=1
   LineC='k';
end
if exist('LineS','var')~=1
   LineS='-';
end
if exist('LineM','var')~=1
   LineM='none';
end
if ~ishold on; hold on; end

xx=[Xs Xs+Xlen Xs+Xlen Xs Xs];
yy=[Ys Ys Ys+Ylen Ys+Ylen Ys];
hp=plot(xx,yy); set(hp,'color',LineC,'linestyle',LineS,'Marker',LineM);

Monday, August 25, 2008

subplot for GrADS

function subplot(args)
*******************************************************
** Usage: run Subplot.gs mx my nw opt
** Creating an axes in the nw-th pane
** of a figure divided into an mx-by-my
** matrix of rectangular panes
** http://scriptdemo.blogspot.com
*******************************************************
mx=subwrd(args,1)
my=subwrd(args,2)
nw=subwrd(args,3)
opt=subwrd(args,4)
if (opt='')
opt=0
endif
* Portrait x=8.5, y=11 & LandScape x=11,y=8.5

if (opt=1)
say 'This function will create 'mx' by 'my' subplots with a layout of Portrait'
Xpage=8.5
Ypage=11.0
else
say 'This function will create 'mx' by 'my' subplots with a layout of Landscape'
Xpage=11.0
Ypage=8.5
endif

ML=0.25
MT=0.25
SX=(Xpage-2*ML)/mx
SY=(Ypage-2*MT)/my

nx=math_fmod(nw,mx)
ny=math_int(nw/mx)+1
if (nx=0)
nx=mx
ny=ny-1
endif

xmin=ML+(nx-1)*SX+0.02*SX
xmax=ML+(nx-1)*SX+0.98*SX
ymin=SY*my+MT-(ny-1)*SY-0.98*SY
ymax=SY*my+MT-(ny-1)*SY-0.02*SY
'set vpage 'xmin' 'xmax' 'ymin' 'ymax

Saturday, August 23, 2008

Download files automatically from ftp site

Download.bat
@echo off
@echo EmailAddress
echo Open FTPAdress>ftp.cfg
echo User USERNAME>>ftp.cfg
echo PASSWORD >>ftp.cfg
echo binary >>ftp.cfg
echo cd /datadir/ >>ftp.cfg
echo cd F08 >>ftp.cfg
echo cd MONTHLY >>ftp.cfg
set b=08
for /L %%a in (1989,1,1991) DO call subget %%a %b%
echo cd ..>>ftp.cfg
echo cd..>ftp.cfg
echo cd F11 >>ftp.cfg
echo cd MONTHLY >>ftp.cfg
set b=11
for /L %%a in (1991,1,1995) DO call subget %%a %b%
echo cd ..>>ftp.cfg
echo cd..>>ftp.cfg
echo cd F13 >>ftp.cfg
echo cd MONTHLY >>ftp.cfg
set b=13
for /L %%a in (1995,1,2006) DO call subget %%a %b%
echo cd ..>>ftp.cfg
echo cd..>>ftp.cfg
echo bye >>ftp.cfg
cls
ftp -n -s: "ftp.cfg" > Download_log.txt

subget.bat:
echo cd %1 >>ftp.cfg
echo get f%2-%1-tnn-00.tar>>ftp.cfg
echo get f%2-%1-tnn-05.tar>>ftp.cfg
echo get f%2-%1-tnn-10.tar>>ftp.cfg
echo get f%2-%1-tnn-15.tar>>ftp.cfg
echo cd ..>>ftp.cfg

After Run the first batch file, we got ftp.cfg as follows:
Open **.**.**.**
User Name
**@**
binary
cd *****
cd F08
cd MONTHLY
cd 1989
get f08-1989-tnn-00.tar
get f08-1989-tnn-05.tar
get f08-1989-tnn-10.tar
get f08-1989-tnn-15.tar
cd ..
cd 1990
get f08-1990-tnn-00.tar
get f08-1990-tnn-05.tar
get f08-1990-tnn-10.tar
get f08-1990-tnn-15.tar
cd ..
cd 1991
get f08-1991-tnn-00.tar
get f08-1991-tnn-05.tar
get f08-1991-tnn-10.tar
get f08-1991-tnn-15.tar
cd ..
cd ..
cd ..
cd F11
cd MONTHLY
cd 1991
get f11-1991-tnn-00.tar
get f11-1991-tnn-05.tar
get f11-1991-tnn-10.tar
get f11-1991-tnn-15.tar
cd ..
cd 1992
get f11-1992-tnn-00.tar
get f11-1992-tnn-05.tar
get f11-1992-tnn-10.tar
get f11-1992-tnn-15.tar
cd ..
cd 1993
get f11-1993-tnn-00.tar
get f11-1993-tnn-05.tar
get f11-1993-tnn-10.tar
get f11-1993-tnn-15.tar
cd ..
cd 1994
get f11-1994-tnn-00.tar
get f11-1994-tnn-05.tar
get f11-1994-tnn-10.tar
get f11-1994-tnn-15.tar
cd ..
cd 1995
get f11-1995-tnn-00.tar
get f11-1995-tnn-05.tar
get f11-1995-tnn-10.tar
get f11-1995-tnn-15.tar
cd ..
cd ..
cd ..
cd F13
cd MONTHLY
cd 1995
get f13-1995-tnn-00.tar
get f13-1995-tnn-05.tar
get f13-1995-tnn-10.tar
get f13-1995-tnn-15.tar
cd ..
cd 1996
get f13-1996-tnn-00.tar
get f13-1996-tnn-05.tar
get f13-1996-tnn-10.tar
get f13-1996-tnn-15.tar
cd ..
cd 1997
get f13-1997-tnn-00.tar
get f13-1997-tnn-05.tar
get f13-1997-tnn-10.tar
get f13-1997-tnn-15.tar
cd ..
cd 1998
get f13-1998-tnn-00.tar
get f13-1998-tnn-05.tar
get f13-1998-tnn-10.tar
get f13-1998-tnn-15.tar
cd ..
cd 1999
get f13-1999-tnn-00.tar
get f13-1999-tnn-05.tar
get f13-1999-tnn-10.tar
get f13-1999-tnn-15.tar
cd ..
cd 2000
get f13-2000-tnn-00.tar
get f13-2000-tnn-05.tar
get f13-2000-tnn-10.tar
get f13-2000-tnn-15.tar
cd ..
cd 2001
get f13-2001-tnn-00.tar
get f13-2001-tnn-05.tar
get f13-2001-tnn-10.tar
get f13-2001-tnn-15.tar
cd ..
cd 2002
get f13-2002-tnn-00.tar
get f13-2002-tnn-05.tar
get f13-2002-tnn-10.tar
get f13-2002-tnn-15.tar
cd ..
cd 2003
get f13-2003-tnn-00.tar
get f13-2003-tnn-05.tar
get f13-2003-tnn-10.tar
get f13-2003-tnn-15.tar
cd ..
cd 2004
get f13-2004-tnn-00.tar
get f13-2004-tnn-05.tar
get f13-2004-tnn-10.tar
get f13-2004-tnn-15.tar
cd ..
cd 2005
get f13-2005-tnn-00.tar
get f13-2005-tnn-05.tar
get f13-2005-tnn-10.tar
get f13-2005-tnn-15.tar
cd ..
cd 2006
get f13-2006-tnn-00.tar
get f13-2006-tnn-05.tar
get f13-2006-tnn-10.tar
get f13-2006-tnn-15.tar
cd ..
cd ..
cd ..
bye

Bash shell demo

#!/bin/bash
# function to convert the reference in alert letter from AGU to Endnote
# Usage A2S FileName
# http://scriptdemo.blogspot.com

sed '/^$/d' $1 > $1.temp
sed 's/^[ \t]*//' $1.temp > $1
sed 'n;n;n;n;n;d;' $1 > $1.temp
mv $1.temp $1

Nline=$( wc -l $1 | awk '{print $1}' )
Nfile=$( expr $[ $Nline + 1 ] / 5 )
# let "Nfile = $Nfile / 5" or Nfile=$[ $Nfile / 5 ]

Nfs=1
while [ ${Nfs} -le ${Nfile} ]
do
SCHfile=scholar${Nfs}.enw
if [ -e $SCHfile ]
then
echo "$SCHfile exist!"
echo "Going on anyway or not [y/n]"
read YesNo
case $YesNo in
y | Y ) # or [y,Y])
rm -f $SCHfile
;;
n | N)
echo 'Convert aborted!'
exit
;;
esac
fi
touch $SCHfile
echo '%0 Journal Article' > $SCHfile
Topic=$( sed -n "$( expr $Nfs \* 5 - 3 )p" $1)
echo "%T $Topic" >> $SCHfile

Ln=$( expr $Nfs \* 5 - 4 )
NumName=$( sed -n "${Ln}p" $1 | awk -F\; '{print NF }')
Ns=0
echo "NumName is $NumName"
while [ $Ns -lt $NumName ]
do
Ns=$( expr $Ns + 1 )
Name=$(sed -n "${Ln}p" $1 | awk -F\; '{print $NL}' NL=$Ns )
echo "%A $Name" >> $SCHfile
done

Ln=$( expr $Ln + 2 )
Jname=$( sed -n "${Ln}p" $1 | awk -F, '{print $1}')
Vnum=$( sed -n "${Ln}p" $1 | awk -F, '{print $2}' | awk '{print $2}')
Nnum=$( sed -n "${Ln}p" $1 | awk -F, '{print $3}' | awk '{print $2}')
Pnum=$( sed -n "${Ln}p" $1 | awk -F, '{print $4}')
Nyear=$( sed -n "$[ $Ln + 2 ]p" $1 | awk '{print $3}')
Uname=$( sed -n "$[ $Ln + 1 ]p" $1 )
echo "%J $Jname" >> $SCHfile
echo "%V $Vnum" >> $SCHfile
echo "%N $Nnum" >> $SCHfile
echo "%P $Pnum" >> $SCHfile
echo "%D $Nyear" >> $SCHfile
echo "%U $Uname" >> $SCHfile

Nfs=$( expr $Nfs + 1 )
done

Grapher

'If you copy or distribute this script without any change except the copyright
'information, please let me know. If you are interested and find a lot of fun or
'bugs in it, please contact with me. It's my pleasure to make friends with
'everyone.
'Copyright: http://scriptdemo.blogspot.com
Sub Main
'Open the application and get it visible
Dim GrapherApp As Object
On Error Resume Next 'Turn off error reporting.
Set SurferApp = GetObject(,"Grapher.Application")
If Err.Number<>0 Then
Set GrapherApp = CreateObject("Grapher.Application")
End If
On Error GoTo 0 'Turn on error reporting.
GrapherApp.Visible = True

' set up the canvas
Dim Docs As Object
Set Docs = GrapherApp.Documents
Dim Plot As Object
Set Plot = Docs.Add(grfPlotDoc)
Plot.PageSetup.pageSize=grfA4 'grfA4Small for small A4
Plot.NewWindow.PageUnits = grfCentimeters
Dim Shapes As Object
Set Shapes = Plot.Shapes

' Control of the x-limit and y-limit of the axes, change it if needed,
' here all are the same for the figures in one page
xxMax=0.8
xxMin=0
yyMax=60
yyMin=0
' %%%%%%% DO NOT USE RELATIVE PATH HERE %%%%%%
DataPath="D:\Program Files\Golden Software\Grapher5\Scripter\"

FigXlen=8 ' cm
FigYlen=4.5 ' cm

' Open files and draw lines
For Nfig=1 To 10 Step 1

'#############################################
' Change it if needed, Assumption:
' Data file is "data01.txt, data02.txt ... data10.txt"
' Add text here is "101, 102, .... 110"
'#############################################

fn = Str$(Nfig+100)
Filename = DataPath + "data" + Right(fn,2) +".txt"
AddText=fn

Set Graph1 = Shapes.AddLinePlotGraph(FileName,2,1)
Nhalf=Int((Nfig+1)/2)
With Graph1
.top=29.7-1-(Nhalf-1)*FigYlen*1.15
.height=FigYlen
.Left=FigXlen*( (Nfig+1) Mod 2 )* 1.2
.width=FigYlen
End With

Set LinePlot1 =Graph1.Plots.Item(1)
Set LinePlot1.line.foreColor=grfColorRed
Set Axesplot1 =Graph1.Axes
Set xAX1=Axesplot1(1)
Set yAx1=Axesplot1(2)

'Set the limit of x-axis
Set xAx1.AutoMax = False
Set xAx1.AutoMin = False
Set xAx1.Max=xxMax
Set xAX1.Min=xxMin

' set the mod of y-axis
Set yAX1.Descending=True

Set Graph2 = Shapes.AddLinePlotGraph(FileName,3,1)
With Graph2
.top = 29.7-1-(Nhalf-1)*FigYlen*1.15
.height=FigYlen
.Left =1+ FigXlen*( (Nfig+1) Mod 2 )* 1.2
.width=FigYlen
End With

Set LinePlot2 =Graph2.Plots.Item(1)
Set LinePlot2.line.foreColor=grfColorBlue
Set Axesplot2 =Graph2.Axes

Set xAX2=Axesplot2(1)
Set yAX2=Axesplot2(2)
Set xAX2.AutoMax = False
Set xAx2.Max=xxMax
Set xAX2.Min=xxMin
Set Axesplot2(2).Descending=True
Set xAx1.length=Figxlen 'xxleng
Set xAx2.length=Figxlen 'xxleng
Set yAx1.length=Figylen 'yyleng
Set yAx2.length=FigYlen

yypos=yAx2.yPos
yxpos=yAx2.xPos
yyleng=yAx2.length
xxpos=xAx2.xPos
xypos=xAx2.yPos
xxleng=xAx2.length
Set xAx1.length=xxleng
Set xAx2.length=xxleng
Set yAx1.length=yyleng
Set yAx1.yPos=yypos
Set yAx1.xPos=yxpos
Set xAx1.xPos=xxpos
Set xAx1.yPos=xypos

' Add x-label and y-label
If Nfig<=8 Then Set xAX1.TickLabels.MajorOn = False Set xAX2.TickLabels.MajorOn=False Else Set xAX1.title.text="Attenuation Coefficient ( /m )" End If If Nfig Mod 2 <>0 Then
Set yAx1.title.text="Depth ( m )"
Else
Set yAx1.TickLabels.MajorOn = False
Set yAx2.TickLabels.MajorOn = False
End If

Set yAxAdd=Graph1.AddAxis(grfYAxis)
Set yAxAdd.xPos= yxpos + xxleng
Set yAxAdd.yPos= yypos
Set yAxAdd.length=yyleng
Set yAxAdd.Descending=True
Set yAxAdd.AutoMax=False
Set yAxAdd.Max=yyMax
Set yAxAdd.TickLabels.MajorOn = False

Set xAxAdd=Graph1.AddAxis(grfXAxis)
Set xAxAdd.xPos=xxpos
Set xAxAdd.yPos= yypos + yyleng
Set xAxAdd.length=xxleng
Set xAxAdd.Descending=True
Set xAxAdd.AutoMax=False
Set xAxAdd.Max=xxMax
Set xAxAdd.Min=xxMin
Set xAxAdd.TickLabels.MajorOn = False

'add text
Set text_data = Shapes.AddText(yxpos+xxleng*0.8,xypos+yyleng*0.2,AddText)
Next Nfig
''quit the application
'GrapherApp.Quit()
End Sub

Surfer

' Copyright: http://scriptdemo.blogspot.com
'曾经几次试图看 Surfer 脚本的写法,总是没有动力地夭折了。终于逮住个机会完整地看了一个。再实践操作了几遍,也算入了门了。
'第一步启动Surfer
Sub main
Dim SurferApp As Object
Dim Doc As Object
Dim Plotwindow As Object
Dim ContourMapFrame As Object
Dim ContourMap As Object
Set SurferApp = CreateObject("Surfer.Application")
SurferApp.Visible=True
'第二步数据导入处理:
path="D:\Program Files\Golden Software\Surfer8\test"
Infile1= path + "1.dat"
OutFile1= path + "1.grd"
retValue = SurferApp.GridData(DataFile:=InFile1, xCol:=1, yCol:=2, zCol:=zlist, _
                         Algorithm:=srfKriging, ShowReport:=False, OutGrid:=OutFile1)
'第三步打开绘图窗口:
Set Doc = SurferApp.Documents.Add(srfDocPlot)
Set Plotwindow=Doc.Windows(1)
Plotwindow.AutoRedraw = False
Set ContourMapFrame =Doc.Shapes.AddContourMap(OutFile1)
Set ContourMap = ContourMapFrame.Overlays(1)
'修改部分属性:
ContourMap.FillContours = True
ContourMap.ShowColorScale = False
ContourMap.SmoothContours = srfConSmoothMed
ContourMap.BlankFill.Pattern = "Water"
ContourMap.BlankFill.ForeColor = srfColorOrange
ContourMap.BlankFill.BackColor = srfColorWhite
'等等
'第四步:输出图象,退出Surfer
OutFig= path + "aa.gif"
 Doc.Export(filename:=outfig,Options:="Width=800, Height=600")
 Plotwindow.Close
 SurferApp.Quit
End Sub
其它属性以及功能可以参考help文件进行添加修改,可以做的事情还是很多的,语法基本上与vb一样。

ShowCalendar