Selected small useful codes

Some interesting codes developed by me as part of my projects. Please ask for details of codes as you may need class definitions.

(The below codes are to understand the solution for respective problems. Readers are advised to ignore class or function names and concern to formula or logic in use. Scroll down for other technologies code)

 in VC++:                                       
typedef struct{

double x;

double y;

int strokeNumber;

}CPointNormalized;
CArray<CPointNormalized, const CPointNormalized&> m_PPArray;
  • To find curliness of a trajectory
double CFeature::Curliness(int From, int To, CPointNormalized& LeftP,

CPointNormalized& RightP, CPointNormalized& BottomP, CPointNormalized& TopP)

{

CPreprocessing ObjPP;

CPointNormalized P1, P2;

double SL=0, Lx, Ly; ///S is sum of line segments in a stroke

int i;

for(i=From;i<To;i++)

{

P1=m_PPArray.GetAt(i);

P2=m_PPArray.GetAt(i+1);

SL+=ObjPP.Distance(P1, P2);

}

Lx=fabs(ObjPP.Distance(RightP, LeftP));

Ly=fabs(ObjPP.Distance(BottomP, TopP));

if(Ly>Lx) Lx=Ly;

return((SL/Lx)-2);

}
  • To find Linearity of a trajectory
double CFeature::Linearity(int From, int To, CPointNormalized& StartP,

CPointNormalized& EndP)

{

double L=0,m,c,x,y;

int i, N=(To-From)+1;

m=(EndP.y-StartP.y)/(EndP.x-StartP.x);

c=StartP.y-m*StartP.x;

for(i=From; i<=To; i++)

{

x=m_PPArray.GetAt(i).x; y=m_PPArray.GetAt(i).y;

L+=pow(PerpendicularDistance(m,c,x,y), 2);

}

return(L/N);

}
  • To check loop exists in trajectory, trajectory stored in an array or list
int CFeature::LoopExists(CPointNormalized& P, CPointNormalized& P1, CPointNormalized& P2,

CPointNormalized& P3, CPointNormalized& P4)

{

int t=0;

if(P1.x<=P2.x)

{

if(P1.y<=P2.y)

{

if(P.x>=P1.x && P.x<=P2.x && P.y>=P1.y && P.y<=P2.y)

t++;

}

else

{

if(P.x>=P1.x && P.x<=P2.x && P.y<=P1.y && P.y>=P2.y)

t++;

}

}

else

{

if(P1.y<=P2.y)

{

if(P.x<=P1.x && P.x>=P2.x && P.y>=P1.y && P.y<=P2.y)

t++;

}

else

{

if(P.x<=P1.x && P.x>=P2.x && P.y<=P1.y && P.y>=P2.y)

t++;

}

}

////////////////////////for next line P3, P4


if(P3.x<=P4.x)

{

if(P3.y<=P4.y)

{

if(P.x>=P3.x && P.x<=P4.x && P.y>=P3.y && P.y<=P4.y)

t++;

}

else

{

if(P.x>=P3.x && P.x<=P4.x && P.y<=P3.y && P.y>=P4.y)

t++;

}

}

else

{

if(P3.y<=P4.y)

{

if(P.x<=P3.x && P.x>=P4.x && P.y>=P3.y && P.y<=P4.y)

t++;

}

else

{

if(P.x<=P3.x && P.x>=P4.x && P.y<=P3.y && P.y>=P4.y)

t++;

}

}

return t;

}
int CFeature::LoopCheck(int i, int j, int choice)
{

double m1, m2, c1, c2; ///Slopes and Intercepts of lines

CPreprocessing ObjPP;

CPointNormalized P, P1, P2, P3, P4;

P1=m_PPArray.GetAt(i); P2=m_PPArray.GetAt(i+IC);

P3=m_PPArray.GetAt(j); P4=m_PPArray.GetAt(j+IC);

m1 = ObjPP.CalculateSlope(P1, P2); c1 = P1.y-m1*P1.x;

m2 = ObjPP.CalculateSlope(P3, P4); c2 = P3.y-m2*P3.x;

if(m1==m2) return 0;

if(m1==-9999)

{

P.x=P1.x; P.y=m2*P.x+c2;

}

else if(m2==-9999)

{

P.x=P2.x; P.y=m1*P.x+c1;

}

else

{

P.x=(c2-c1)/(m1-m2); P.y=(m1*c2-m2*c1)/(m1-m2);

}

P.strokeNumber=P1.strokeNumber;

if(LoopExists(P, P1, P2, P3, P4)>=2 && choice==1)

return 1;

if(LoopExists(P, P1, P2, P3, P4)>=2 && choice==2)

return 1;

return 0;

}
int CFeature::Loop(int From, int To)
{

int i, j, loop=1, lc=0, rlc=0; IC=1; //loop is for loop identity

for(i=From; i<To-3; i=i+IC)

{

j=i+2;

while(j<To)

{

lc=LoopCheck(i,j,loop);

if(lc==1 && (j-i)>1) //for strict visible loop and avoid overwriting

rlc = rlc*10+lc;

j=j+IC;

}

}

return rlc;

}
  • To check given trajectory behave as horizontal line or not
int CFeature::HeadLine(int From, int loop)
{

bool Range=false;

double Linearity, Curliness, Slope, TestP; //linearity nad curliness

int i, SN; SN=m_PPArray.GetAt(From).strokeNumber;

TestP=(BP()+TP())/2;

for(i=0; i<=m_LowLevelFArray.GetUpperBound(); i++)

{

if(SN==m_LowLevelFArray.GetAt(i).SN)

{

Linearity=m_LowLevelFArray.GetAt(i).Linearity;

Curliness=m_LowLevelFArray.GetAt(i).Curliness;

Slope=m_LowLevelFArray.GetAt(i).Slope;

if(m_LowLevelFArray.GetAt(i).BottomP.y>=TestP)

Range=true;

break;

}

}

///check for curliness

if(Slope>=-1 && Slope<=1 && Range==true && Linearity<=2 && loop==0)

return 1;

else

return 0;

}
  • To check given trajectory behave as vertical straight line or not
int CFeature::StraightLine(int From, int loop, int hl)
{

CLowLevelF L; CPreprocessing ObjPP;

double Linearity, Curliness, Slope, Length; //linearity nad curliness

int i, SN; SN=m_PPArray.GetAt(From).strokeNumber;

for(i=0; i<=m_LowLevelFArray.GetUpperBound(); i++)

{

if(SN==m_LowLevelFArray.GetAt(i).SN)

{

L=m_LowLevelFArray.GetAt(i);

Linearity=L.Linearity;

Curliness=L.Curliness;

Slope=L.Slope;

Length=fabs(ObjPP.Distance(L.StartP, L.EndP));

break;

}

}

if((Slope>=2.74 || Slope<=-2.74) && Length>=30 && Linearity<=2 && loop==0 && hl==0)

return 1;

else

return 0;

}
  • To check given trajectory behave as a dot or 'bindu'
int CFeature::Dot(int From, int loop, int crossing, int hl, int sl)
{

CLowLevelF L; CPreprocessing ObjPP;

double Length, Height;

int i, SN; SN=m_PointArray.GetAt(From).strokeNumber;

for(i=0; i<=m_LowLevelFArray.GetUpperBound(); i++)

{

if(SN==m_LowLevelFArray.GetAt(i).SN)

{

L=m_LowLevelFArray.GetAt(i);

Length=fabs(ObjPP.Distance(L.StartP, L.EndP));

Height=fabs(ObjPP.Distance(L.BottomP, L.TopP));

break;

}

}

if(Length<=10 && Height<=10 && loop==0 && crossing==0 && hl==0 && sl==0)

return 1;

else

return 0;

}
  • To find third point for two consecutive points of trajectory (as equilateral triangle)
CPointNormalized CRecognitionDialog::FindThirdPoint(CPointNormalized pStart, CPointNormalized pMid, CPointNormalized pEnd)
{

double m, k, L, a, b, c;

CPointNormalized P1,P2;

if((pEnd.x-pStart.x)==0) m=9999;

else m=(pEnd.y-pStart.y)/(pEnd.x-pStart.x);

k=((pStart.x*pStart.x+pStart.y*pStart.y)-(pEnd.x*pEnd.x+pEnd.y*pEnd.y))/(2*(pEnd.x-pStart.x));

L=(pEnd.x-pStart.x)*(pEnd.x-pStart.x)+(pEnd.y-pStart.y)*(pEnd.y-pStart.y);

if(m==0)

{

P1.x=-k; P2.x=-k;

a=1; b=2*pEnd.y; c=pEnd.y*pEnd.y+k*k+pEnd.x*pEnd.x+2*pEnd.x*k-L;

P1.y=((-b)+sqrt(b*b-4*a*c))/(2*a); P2.y=((-b)-sqrt(b*b-4*a*c))/(2*a);

}

else

{

a=1+m*m; b=2*(m*pStart.y+k-pStart.x*m*m);

c=m*m*(pStart.x*pStart.x+pStart.y*pStart.y-L)+2*m*pStart.y*k+k*k;

P1.x=((-b)+sqrt(b*b-4*a*c))/(2*a); P2.x=((-b)-sqrt(b*b-4*a*c))/(2*a);

P1.y=-(P1.x+k)/m; P2.y=-(P2.x+k)/m;

}

if(Distance(P1,pMid)>=Distance(P2,pMid))

return P1;

else

return P2;

}
  • To find angle in degrees for two consecutive points of trajectory
double CRecognitionDialog::Angle(CPointNormalized P1, CPointNormalized P2)
{

double radian, degree, k=(180/3.14);

if(P1.x==P2.x)

{

if(P1.y<=P2.y)

return 90;

else

return 270;

}

else

{

radian=atan((P2.y-P1.y)/(P2.x-P1.x));

degree=radian * k; degree = fabs(degree);

if(P2.x>P1.x && P1.y<=P2.y) return degree;

else if(P2.x>P1.x && P1.y>=P2.y) return (270+(90-degree));

else if(P2.x<P1.x && P1.y<=P2.y) return (90+(90-degree));

else if(P2.x<P1.x && P1.y>=P2.y) return (180+degree);

}

return degree;

}
  • To find files in a path
void CHWRAnujView::FindFiles(CString FilePath)
{

CFileFind WriterFile; CString FilePath2;

FilePath+=_T("\\*.*");

BOOL find = WriterFile.FindFile(FilePath);

while(find)

{

find = WriterFile.FindNextFileA();

if(WriterFile.IsDots()) continue;

else if(WriterFile.IsDirectory())

{

FilePath2 = WriterFile.GetFilePath();

FindFiles(FilePath2);

}

else

{

m_files++;

ReadFiles(WriterFile.GetFilePath()); //to further read a file

}

}

WriterFile.Close();

}
  • To make list numbers decimal points free (example 2.75 becomes 2)
void CPreprocessing::NonDecimalPoints()
{

int i, Size;

double fraction, t;

CPointNormalized P; //Defined at top

Size=m_PPArray.GetSize(); //m_PPArray list or array name

for(i=0; i<Size; i++)

{

P=m_PPArray.GetAt(i);

fraction=modf(P.x, &t);

if(fraction>0.5) P.x=P.x+1-fraction;

else P.x=P.x-fraction;

fraction=modf(P.y, &t);

if(fraction<-0.5) P.y=P.y-1-fraction;

else P.y=P.y-fraction;

m_PPArray.SetAt(i, P);

}

}
  • To find maximum and minimum values and their y-x ratio in Array or list
void CPreprocessing::CalculateMaxMinText()
{

int i, Size;

CPointNormalized TempPoint; //Defined at top

Size=m_PPArray.GetSize(); //m_PPArray list or array name

xMax=0; xMin=ConstantHighPlusValue; yMax=ConstantHighLowValue; yMin=0;

for(i=0; i<Size; i++)

{

TempPoint = m_PPArray.GetAt(i);

if(TempPoint.x > xMax)

xMax = TempPoint.x;

if(TempPoint.x < xMin)

xMin = TempPoint.x;

if(TempPoint.y > yMax)

yMax = TempPoint.y;

if(TempPoint.y < yMin)

yMin = TempPoint.y;

}

m_yxRatio=(double)fabs(yMin)/xMax;


}
  • To calculate perpendicular distance for y=mx+c from (x1,y1)
double CFeature::PerpendicularDistance(double m, double c, double x1, double y1)
{

return(fabs((m*x1-y1+c)/(sqrt(m*m+1))));

}
  • To filter repeat points in array or list
void CFeature::FilterRepeatPoints()
{

CPointNormalized Pi, Pj; //Defined at top

int i,j, Size; Size=m_PPArray.GetSize(); //m_PPArray list or array name

if(Size>0)

{

for(i=0;i<m_PPArray.GetUpperBound();i++)

{

for(j=i+1;j<=m_PPArray.GetUpperBound();j++)

{

Pi=m_PPArray.GetAt(i); Pj=m_PPArray.GetAt(j);

if(Pi.x==Pj.x && Pi.y==Pj.y)

m_PPArray.RemoveAt(j);

}

}

}

}
in Java/ J2ME fo symbian operating system
  • To write in a file in mobile based platform
public void WriteFile() throws IOException
{
        String path;
        byte[] bytePL = currentList.getBytes();
        javax.microedition.io.Connection con = null;
        java.io.OutputStream os = null;
        if(forMb) path =  "file:///e:/fileName.txt"; //if using mobile
        else  path = "file:///root1/att/fileName.txt"; //if using emulators
        try {
            con = javax.microedition.io.Connector.open(path, javax.microedition.io.Connector.READ_WRITE);
            javax.microedition.io.file.FileConnection fcon =
                    (javax.microedition.io.file.FileConnection) con;
            if (!fcon.exists())
                fcon.create();
            os = fcon.openOutputStream(fcon.fileSize());
            os.write(bytePL);
            os.flush();
            } catch (Exception e) {
            System.out.println("file not created by author");
            } finally {
            try {
                if (os != null)
                    os.close();
                if (con != null)
                    con.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            }
       }
  • To read from a file in mobile based platform
     public void getLines(){
        InputStream inputStreamText =null;
        inputStreamText = this.getClass().getResourceAsStream("fileName.txt");
        StringBuffer buf = new StringBuffer();
        int i ;
        while ((i = inputStreamText.read()) != -1)
        {
        char ch = (char)i;
        if (ch == '\n')
        {
            lines.addElement(buf.toString());
            buf.delete(0,buf.length());
        }
        else
            buf.append(ch);
        }
        inputStreamText.close();
    }
  • To get array from string, where data is trajectory of X-Y position and x and y positions start with 'X' and 'Y', trajectory end with ';' and new pen up in trajectory start with 'S'.
    void GetArrayFromString(String Line, int choice)
    {
            int i=0, l, indx=0; double AngleLine; String ps;
            Point P1, P2; TemplatePoint ObjT; 

P1=new Point(); P2=new Point(); ObjT = new TemplatePoint();

            i=2;
            l=Line.length(); 
            while(i<l)
            {
                    if(Line.charAt(i)==' ' || Line.charAt(i)=='-' || Line.charAt(i)=='S') break;
                    if(Line.charAt(i)==';') break;
                    if(Line.charAt(i)=='X') 
                    {
                            i++; ps="";
                            while(Line.charAt(i)!='Y')
                            {
                                    ps+=Line.charAt(i); i++; 
                            }
                            P2.x = Double.parseDouble(ps);
                    }
                    if(Line.charAt(i)=='Y') 
                    {
                            i++; ps="";
                            while(Line.charAt(i)!='X')
                            {
                                    if(Line.charAt(i)=='S') { i++; break;}
                                    if(Line.charAt(i)==';') break;
                                    ps+=Line.charAt(i); i++; 
                            }
                            P2.y = Double.parseDouble(ps); 
                            ObjT.P=P2; 
                            if(indx==0) { P1=P2; ObjT.angle=0; } 
                            else ObjT.angle=Angle(P1, P2);
                            if(choice==1)
                                    m_TestArray.add(ObjT);
                            else
                                    m_TrainArray.add(ObjT);
                            P1=P2;
                    }

// i++;

            }
    }
in VBA (macros to work with ms-excel)
  • To merge files
Sub MergeFileFunction()
Dim s1 As Worksheet
Dim s2 As Worksheet
Dim s1_currRow, s2_currRow As Integer
Set s1 = ActiveWorkbook.Sheets("sheet1")
Set s2 = ActiveWorkbook.Sheets("sheet2")
For s2_currRow = 1 To sheet1_row_length
    For s1_currRow = 1 To sheet2_row_length
        If s2.Cells(s2_currRow, 1) = s1.Cells(s1_currRow, 5) Then
            If IsEmpty(s1_currRow, 1) Then
                s1.Cells(s1_currRow, 1) = s2.Cells(s2_currRow, 2)
                s1.Cells(s1_currRow, 2) = s2.Cells(s2_currRow, 3)
                s1.Cells(s1_currRow, 3) = s2.Cells(s2_currRow, 4)
                s1.Cells(s1_currRow, 4) = s2.Cells(s2_currRow, 5)
            End If
        End If
    Next s1_currRow
Next s2_currRow
End Sub
  • To delete empty rows
Sub DeleteRowFunction()
Dim currRow As Long
For currRow = 1 To num_rows
    If IsEmpty(Cells(currRow, 1)) Then
        Rows(currRow).EntireRow.Delete
    End If
Next currRow
End Sub
  • To put data in empty cells
Sub InsertDataInCellFunction()
Dim currRow As Long
Dim txt As String
txt = "txt_to_insert"
For currRow = 1 To
num_rows
If IsEmpty(Cells(currRow, n_col)) Then
Cells(currRow, n_col) = txt
End If
Next currRow
End Sub