Trang 1 trên tổng số 2 12 Cuối cùngCuối cùng
Từ 1 tới 10 trên tổng số 11 kết quả

Đề tài: Mã nguồn C | chương trình tìm kiếm dữ liệu

  1. #1
    Ngày gia nhập
    04 2008
    Nơi ở
    Đồng Nai
    Bài viết
    6

    Angry Mã nguồn C | chương trình tìm kiếm dữ liệu

    đây là mã nguồn em tìm được,nó nói về việc tìm kiếm thông tin nhưng em ko bit nó đã đủ để làm 1 công cụ tìm kiếm đơn giản chưa?nếu thiếu xin chỉ giúp thêm.
    C++ Code:
    1. #include <iostream.h>
    2. #include <conio.h>
    3. #include <string.h>
    4. # define MAX 100
    5. void main()
    6.  
    7.  
    8.     {
    9.     char sen[MAX]; //for sentance input
    10.     char srch[MAX]; //for search word input
    11.     int occ=0,cnt=0;
    12.     int plc[100];
    13.     clrscr();
    14.     cout<<("Please Type a Sentance of Your Choice\n");
    15.     cin.getline(sen,'.');
    16.     cout<<("\n Enter a Word To Search\n");
    17.     cin.getline(srch,'.');
    18.     int ln=strlen(srch);
    19.     for(int i=0;i<strlen(sen);i++)
    20.     if(srch[0]==sen[i] && srch[ln-1]==sen[i+ln-1])//if searching word first and last digit matches
    21.  
    22.  
    23.         {
    24.         for( int m=1 ; m<ln; m++)
    25.  
    26.  
    27.             {
    28.             if(srch[m]==sen[i+m])//check the inner letters
    29.  
    30.  
    31.                     {
    32.                      plc[cnt]=i; //set place equals to i
    33.                      cnt++;
    34.                      if(m==ln-1) //if all secussful till the endof lenght then incremt occ+
    35.                      occ++;
    36.                     }
    37.                     else
    38.  
    39.  
    40.                         {
    41.                         occ=0; // else set occ to zero and count to zero
    42.                         cnt=0;
    43.                         break ; //break loop
    44.                 }
    45.             }
    46.         }
    47.         cout <<"the occurance of word u entered is "<<occ<<" times in the given string"<<endl;
    48.         for(int k=0 ;k<occ ;k++)
    49.  
    50.  
    51.             {
    52.             cout<<"the matching string found at "<<plc[k]<<endl;
    53.         }
    54.         getch();
    55.     }

  2. #2
    Ngày gia nhập
    02 2009
    Bài viết
    21

    Trích dẫn Nguyên bản được gửi bởi ruacon Xem bài viết
    đây là mã nguồn em tìm được,nó nói về việc tìm kiếm thông tin nhưng em ko bit nó đã đủ để làm 1 công cụ tìm kiếm đơn giản chưa?nếu thiếu xin chỉ giúp thêm.
    C++ Code:
    1. #include <iostream.h>
    2. #include <conio.h>
    3. #include <string.h>
    4. # define MAX 100
    5. void main()
    6.  
    7.  
    8.     {
    9.     char sen[MAX]; //for sentance input
    10.     char srch[MAX]; //for search word input
    11.     int occ=0,cnt=0;
    12.     int plc[100];
    13.     clrscr();
    14.     cout<<("Please Type a Sentance of Your Choice\n");
    15.     cin.getline(sen,'.');
    16.     cout<<("\n Enter a Word To Search\n");
    17.     cin.getline(srch,'.');
    18.     int ln=strlen(srch);
    19.     for(int i=0;i<strlen(sen);i++)
    20.     if(srch[0]==sen[i] && srch[ln-1]==sen[i+ln-1])//if searching word first and last digit matches
    21.  
    22.  
    23.         {
    24.         for( int m=1 ; m<ln; m++)
    25.  
    26.  
    27.             {
    28.             if(srch[m]==sen[i+m])//check the inner letters
    29.  
    30.  
    31.                     {
    32.                      plc[cnt]=i; //set place equals to i
    33.                      cnt++;
    34.                      if(m==ln-1) //if all secussful till the endof lenght then incremt occ+
    35.                      occ++;
    36.                     }
    37.                     else
    38.  
    39.  
    40.                         {
    41.                         occ=0; // else set occ to zero and count to zero
    42.                         cnt=0;
    43.                         break ; //break loop
    44.                 }
    45.             }
    46.         }
    47.         cout <<"the occurance of word u entered is "<<occ<<" times in the given string"<<endl;
    48.         for(int k=0 ;k<occ ;k++)
    49.  
    50.  
    51.             {
    52.             cout<<"the matching string found at "<<plc[k]<<endl;
    53.         }
    54.         getch();
    55.     }
    bạn ơi đoạn code này tìm cho bạn số lần xuất hiên của 1 từ trong 1 dãy thôi ,còn ứng dụng nhiều hơn phụ thuộc vào bạn. Mình đang tìm code làm cái này hay quá ,bạn tìm thấy nó ở trang nào cho mình link được không thk

    Chú ý : bạn nên đưa code vào thẻ code cho dễ nhìn

  3. #3
    Ngày gia nhập
    04 2008
    Nơi ở
    Đồng Nai
    Bài viết
    6

    em ko nhớ là em đang tìm trang nào nữa nhưng anh co thể vào google code search để tìm nó.Nhưng anh có thể giải thích rõ hơn ko và anh biết làm gì để thực hiện dc công cụ tìm kiếm đơn giản.Xin cảm ơn!!!!!!!!!

  4. #4
    Ngày gia nhập
    02 2009
    Bài viết
    21

    VD bạn có chuỗi "alo csosfg dfgh jer hd 22g htrjvbmmm"
    -bạn tìm từ "22" nó sẽ báo xuất hiện 1 lần
    -bạn tìm từ "mm" nó sẽ báo xuất hiện 2 lần<<đây là chỗ chưa hoàn chỉnh của chương trình mình có đoạn code đơn giản hơn sau cũng có chức năng tìm số lần xuất hiện nhưng không tìm được vị trí

    C++ Code:
    1.  void solanxh()    //nhap vao 1 tu va dem so lan xuat hien
    2.  {
    3.  char tu[50];int k,d=0;
    4.  cout<<" \n Chuong Trinh Nhap 1 Ky Tu Roi Dem So Lan Xuat Hien Ky Tu Do Trong Xau";
    5.  cout<<" Moi Nhap Ky Tu Can Kiem Tra : ";
    6.  gets(tu);
    7.  for (i=0;i<strlen(xau);i++)    //duyet xau chinh.
    8.   {
    9.     for (int j=0,k=0;j<strlen(tu);j++)    //duyet tu vua nhap
    10.     if ( xau[(i+j)]==tu[j]) k++;
    11.     if(k==strlen(tu)) {d++;i+=strlen(tu);}
    12.   }
    13.     cout<<" Tu '"<<tu<<"' Vua Nhap Xuat Hien : "<<d<<" Lan trong xau. ";
    14.  }

  5. #5
    Ngày gia nhập
    02 2009
    Bài viết
    21

    đoạn sau thì hoàn chỉnh hơn này đếm khá chính xác , nhưng không thông báo được vị trí
    C++ Code:
    1. void SoLanXuatHienTu(char *s)
    2. {
    3.     char tu[10];
    4.     int x=0,dem=0;
    5.     printf("\n\nBan nhap tu can kiem tra : ");
    6.     gets(tu);
    7.     for(int i=0;i<strlen(s)-strlen(tu);i++)
    8.         {
    9.         for(int j=0,x=0;tu[j]!='\0';j++) if (s[i+j]==tu[j]) x++;
    10.         if (x==strlen(tu))  {dem++;i+=strlen(tu);}
    11.         }
    12.     printf("\nTu '");
    13.     for(int h=0;tu[h]!='\0';h++)
    14.         printf("%c",tu[h]);
    15.     printf("' xuat hien %d lan. ",dem);
    16. }

  6. #6
    Ngày gia nhập
    04 2008
    Nơi ở
    Đồng Nai
    Bài viết
    6

    Mặc định Mã nguồn C | chương trình tìm kiếm dữ liệu

    em có cái này mới anh xem thử.
    Code:
    #include <qmultilineedit.h>
    #include <qprogressdialog.h>
    #include <qinputdialog.h>
    #include <klocale.h>
    #include <kdebug.h>
    #include <kmessagebox.h>
    #include <kfiledialog.h>
    #include <kurlrequester.h>
    #include <kstddirs.h>
    #include "kapp.h"
    #include "KDBSearchEngine.h"
    #include "dbscan.h"
    #include "errno.h"
    #include "stdio.h"
    #include "stdlib.h"
    #include <sys/time.h>
    #include "preferenceswidget.h"
    #include "dbse_factory.h"
    #include <qprogressbar.h>
    #include <qpushbutton.h>
    #include <klineedit.h>
    #include <kconfig.h>
    #include <qdir.h>
    #include <qradiobutton.h>
    #include <qcheckbox.h>
    #include <qspinbox.h>
    #include <qslider.h>
    #include <qarray.h>
    #include "database.h"
    #include "catalogsettings.h"
    #define BIGNUMBER 400000000
    KDBSearchEngine::KDBSearchEngine(QObject *parent,const char*name)
     : SearchEngine(parent,name)
    {
    edited="unknown";
    dm=0;   //Database Manager
    pw=0;   //Preference widget
    lang="";
    dbOpened=false;
    dbname="";
    lasterror=i18n("No error");
    connect(this,SIGNAL(hasError(QString)),SLOT(setLastError(QString)));
      IAmReady=true;  //  I don't know if it is a good idea, no DB loaded!!!
      scanInProgress=false;
      searching=false;
      stopNow=false;
      norm=false;   // Normalize white space = FALSE
      comm=true;    // Remove Comments = TRUE
    }
    KDBSearchEngine::~KDBSearchEngine()
    {
    }
    bool KDBSearchEngine::loadDatabase(QString database,bool noask=false)
    {
       bool ret=true;
       bool asked=false;
       if(noask)  asked=true;
       if(dm!=0)
       {
           delete dm;
           dm=0;
       }
       QDir dir(database);
       if(!dir.exists())
       {
           if(asked || KMessageBox::questionYesNo(0,i18n(
                "Database directory does not exist:\n%1\n"
                "Do you want to create it now?").arg(database))
                   ==KMessageBox::Yes)
           {
               asked=true;
               QStringList dirList;
               while(!dir.exists() && !dir.dirName().isEmpty())
               {
                  dirList.prepend(dir.dirName());
                  dir.setPath(dir.path()+"/..");
               }
               for(QStringList::Iterator it = dirList.begin(); it!=dirList.end()
                       ; ++it)
               {
                  if(!dir.mkdir(*it))
                  {
                      KMessageBox::sorry(0,
                           i18n("It was not possible to create directory %1")
                           .arg(dir.path()+"/"+(*it)) );
                      ret=false;
                      break;
                  }
                  dir.cd(*it);
               }
           }
           else
           {
               ret=false;
           }
       }
      if(ret)
      {
          dm= new DataBaseManager(database,lang,this,"Database manager");
          if(!dm->isOk())
          {
            if(asked || KMessageBox::questionYesNo(0
                ,i18n("Database files not found.\nDo you want to create them now?"))
                ==KMessageBox::Yes)
            {
               //fprintf(stderr,"SI\n");
               ret=dm->createDataBase(database,lang);
            }
            else
              ret=false;
          }
          else ret=true;
      }
    //Wrong errore hangdling
      if(ret)
       totalRecord=dm->count();
      else totalRecord=0;
      return ret;
    }
    void KDBSearchEngine::setNormalizeSpace(bool normalize)
    {
      norm=normalize;
    }
    void KDBSearchEngine::setRemoveInternalComment(bool internalcomment)
    {
      comm=internalcomment;
    }
    void KDBSearchEngine::setCaseSensitive(bool sensitive)
    {
      sens=sensitive;
    }
    void KDBSearchEngine::setRemoveCharString(QString chartoremove)
    {
      remchar=chartoremove;
    }
    bool KDBSearchEngine::isSearching() const
    {
      return searching;
    }
    int KDBSearchEngine::addSearchString(QString searchString, int rule)
    {
      if(searching||scanInProgress) return -1;
      SearchEntry e;
      e.string=QString(searchString);
      e.rules=rule;
      searchStringList.append(e);
      return searchStringList.count();
    }
    bool KDBSearchEngine::startSearch(QString str)
    {
    
     if(autoUpdate)
       {
        updateSettings();
       }
     int l1=0,l2=0;
     if(defSub1) l1=defLimit1;
     if(defSub2) l2=defLimit2;
    return startSingleSearch(str,l1,l2);
    }
    bool KDBSearchEngine::startSearchInTranslation(QString s)
    {
     if(autoUpdate)
       {
        updateSettings();
       }
     int l1=0,l2=0;
     if(defSub1) l1=defLimit1;
     if(defSub2) l2=defLimit2;
     return startSingleSearch(s,l1,l2,true);
    }
    bool KDBSearchEngine::openDb(bool noask=false)
    {
      if(!dbOpened)
        {
          dbOpened=loadDatabase(dbname,noask);  //Try first to open it now
         if(!dbOpened) // Still not opened!!
             {
                 hasError(i18n("Cannot open the database"));
                 return false;
              }
        }
    return true;
    }
    bool KDBSearchEngine::messagesForPackage(const QString& package
                             , QValueList<Message>& resultList, QString& error)
    {
    
      int count = 0;
      stopNow=false; // Remove dirty.
      Message m;
      if(searching )
      {
       error=i18n("Another search has already been started");
       return false;
      }
      if(scanInProgress)
      {
       error=i18n("Cannot search now: a po file scan is in progress");
       return false;
      }
      if(!openDb()) {
       error=i18n("Cannot open the database");
       return false;
      }
       if(totalRecord<=0)
         {
         error=i18n("Database empty");
         return false;
         }
       int step=(totalRecord/30)+1;
       int ntra,nref;
       int req=dm->searchCatalogInfo(package);
       if(req==-1) {
        error=i18n("No entry for this package in the database.");
        return false;
       }
       DataBaseItem item;
       int i,h;
       kdDebug(0) << "looking for catalog " << req <<endl;
       progressStarts(i18n("Searching for %1 in database").arg(package));
       for(item = dm->firstItem();!item.isNull();item=dm->nextItem())
       {
          count++;
          if(count%step==0){
               emit progress(100*count/totalRecord);
               kapp->processEvents();
             }
          if(stopNow) {
            stopNow=false;
            searching=false;
            emit finished();
            return true;    // No error, stopped!
          }
          ntra=item.numTra;
          for(i=0;i<ntra;i++) {
           nref=item.translations[i].numRef;
              for(h=0;h<nref;h++){
                if(item.translations[i].infoRef[h]==req) {
                    m.msgid=item.key;
                    m.msgstr=item.translations[i].translation;
                    resultList.append(m);
                  }
              }
          }
    
       }
       return true;
    }
    void KDBSearchEngine::repeat()
    {
      int count = 0;
      stopNow=false; // Remove dirty.
      if(searching )
      {
        return;
      }
      if(scanInProgress)
      {
       return;
      }
      if(!openDb()) {
       return;
      }
       if(totalRecord<=0)
         {
         return;
         }
       int step=(totalRecord/30)+1;
       int ntra,nref;
       DataBaseItem item;
       int i,h,tot;
       int req=dm->searchCatalogInfo("kdelibs.po");
       if(req==-1) kdDebug(0) << "No kdelibs.po found!" << endl;
       QProgressDialog *pd=new QProgressDialog(i18n("Looking for repetitions"),i18n("Stop"),100);
       connect(this,SIGNAL(progress(int)),pd,SLOT(setProgress(int)));
       connect(this,SIGNAL(finished()),pd,SLOT(close()));
       connect(pd,SIGNAL(cancelled()),this,SLOT(stopSearch()));
       QString txt="// %1 repetitions, %2 translation(s)\ni18n(\"%3\");\n";
       QString id;
       int min;
       bool ok = false;
       min=QInputDialog::getInteger(i18n("Minimum repetition"),i18n("Insert the minimum number of repetitions for a string"),
                                    2,1,999999,1,&ok);
       if(!ok)
           return;
         pd->show();
       progressStarts(i18n("Searching repeated string"));
       static QMultiLineEdit *mle=new QMultiLineEdit();
       mle->clear();
       bool inlibs;
       for(item = dm->firstItem();!item.isNull();item=dm->nextItem())
       {
          count++;
          if(count%step==0){
               emit progress(100*count/totalRecord);
               kapp->processEvents();
             }
          if(stopNow) {
            stopNow=false;
            searching=false;
            emit finished();
            return; // No error, stopped!
          }
          tot=0;
          inlibs=false;
          ntra=item.numTra;
          for(i=0;i<ntra;i++) {
           nref=item.translations[i].numRef;
              for(h=0;h<nref;h++)
                if(item.translations[i].infoRef[h]==req) inlibs=true;
                tot+=nref;
              }
          if (tot>=min && !inlibs)
            {
                id=item.key;
                id=id.replace(QRegExp("\\n"),"\"\n\"");
                mle->append(txt.arg(tot).arg(ntra).arg(id));
            }
          }
         emit progress(100);
            emit finished();
        mle->resize(400,400);
        mle->show();
        delete pd;
       return;
    }
    bool KDBSearchEngine::startSearchNow(int searchmode)
    {
      if(searchmode==-1) searchmode=mode;
      int count = 0;
      stopNow=false; // Remove dirty.
      clearResults();
      if(searching )
      {
       hasError(i18n("Another search has already been started"));
       return false;
      }
      if(scanInProgress)
      {
       hasError(i18n("Cannot search now: a po file scan is in progress"));
       return false;
      }
      if(!openDb())
       return false;
       if(totalRecord<=0)
         {
         hasError(i18n("Database empty"));
         return false;
         }
      searching=true;
      emit started();
      bool allkey=(searchmode==MD_ALL_GOOD_KEYS);
      bool equal,contains,contained,regexp,intra;
      intra=searchmode & MD_IN_TRANSLATION;
      QString msgIdFound;
      QString msgId;
      QString msgStr;
      //QString msgIdRequested;
      SearchResult *aresult;
      TranslationInfo *adescription;
      SearchList searchList;
      int i,len,files,h;
      len=remchar.length();
      int n,m;//,word;
      QString  *id;
      QString mainRequest=searchStringList[0].string;
      SearchList::Iterator it,it1;
      QString *idMod;
      bool foundSomething=false;
      searchList=searchStringList;   //Create a copy and modify it
      if(!allkey)
      {
      for ( it=searchList.begin(); it != searchList.end(); ++it )
        {
          idMod=&((*it).string);
            int pos;
            for(i=0;i<len;i++)
             while((pos=idMod->find(remchar.at(i)))!=-1)
            idMod->remove(pos,1);
            if(comm)
             idMod->replace(QRegExp("\\_\\:.*\\\\n"),"");  //Read it from catalog !!! (NOT ONLY HERE)
          if(norm) idMod->simplifyWhiteSpace();
          if(!sens) *idMod=idMod->upper();
        }
       }
      timeval now;
      gettimeofday(&now,NULL);
      //fprintf(stderr,"\n%ld.%ld\n",now.tv_sec,now.tv_usec);
      double tim=1.0*now.tv_usec/1000000.0+now.tv_sec;
      int pos;
       DataBaseItem item;
      //Now we can browse the whole db or the "good keys"
     QValueList<KeyAndScore> goodkeys;
      int totalprogress;
      bool gk=(searchmode==MD_GOOD_KEYS)||allkey;
      int k=0;
      if(gk) {
         goodkeys=searchWords(mainRequest,thre,threorig,listmax);//FIX IT, mainReq?
            }
       totalprogress=gk?goodkeys.count():totalRecord;
       int step=(totalprogress/30)+1;
       for(item = gk?(dm->getItem(goodkeys[0])):(dm->firstItem());
            !item.isNull();
           item = gk?(dm->getItem(goodkeys[++k])):(dm->nextItem()))
       {
    //   Emit progress, process event and check stop now
          if(count%step==0){
               emit progress(100*count/totalprogress);
               kapp->processEvents();
             }
          if(stopNow) {
            stopNow=false;
            searching=false;
            emit finished();
            return true;    // No error, stopped!
          }
        //  fprintf(stderr,"%s\n",(const char *)item.key.utf8());
          msgIdFound=item.key;  //Check if this is OK with UTF8
    //     searchmode && MD_IN_TRANSLATION)
          count++;
           msgId=msgIdFound;
         if(!allkey)
         {
            //Remove character in list of character to be ignored
            for(i=0;i<len;i++)
             while((pos=msgId.find(remchar.at(i)))!=-1)
            msgId.remove(pos,1);
            //Remove context information from id found
            if(comm)
             msgId.replace(QRegExp("\\_\\:.*\\\\n"),"");
          if(norm) msgId.simplifyWhiteSpace();
          if(!sens) msgId=msgId.upper();
          }
          it=searchList.begin();
          idMod=&((*it).string);
          bool foundExact=false;
          for ( it1=searchStringList.begin(); it1 != searchStringList.end(); it1++ )
            {
              id=&((*it1).string);
              int nn=0;
              do {
                if(intra) {
                   msgId=item.translations[nn].translation;
                   if(!allkey) {
                       //Remove character in list of character to be ignored
                        for(i=0;i<len;i++)
                        while((pos=msgId.find(remchar.at(i)))!=-1)
                            msgId.remove(pos,1);
                       //Remove context information from id found
                       if(comm)
                           msgId.replace(QRegExp("\\_\\:.*\\\\n"),"");
                       if(norm) msgId.simplifyWhiteSpace();
                       if(!sens) msgId=msgId.upper();
                  }
                }
                int rules=(*it).rules;
                if (rules & Equal) equal=(*idMod==msgId); else equal=false;
                if (rules & Contains) contains=idMod->contains(msgId); 
               else contains=false;
                if (rules & Contained) contained=msgId.contains(*idMod); else contained=false;
                if  (!foundExact && (rules & RegExp ))
                    {
                      QRegExp reg(*idMod);
                      regexp=(reg.match(msgId)!=-1);
                    } else regexp=false;
              nn++;
              } while(intra && nn<item.numTra);
              if(equal||contains||contained||regexp||allkey)
                {
    //           kdDebug(0) << QString("Found") << endl;
                  if(equal) foundExact=true;
                 m=item.numTra;  //Translations found.
                  for(n=0;n<m;n++)
                    {
                      foundSomething=true;
                      msgStr=item.translations[n].translation;
                      files=item.translations[n].numRef;
                      aresult=new SearchResult();
                      results.setAutoDelete(true);
                     if(!gk)
                      aresult->score=score(mainRequest,msgIdFound);
                     else
                      aresult->score=goodkeys[k].score;
                    if(intra)
                      aresult->score=score(mainRequest,item.translations[n].translation);
                      SearchResult *s=0;
                      for(s=results.first();s!=0;s=results.next())
                       {
                        if(s->score > aresult->score)
                        {
                         results.insert(results.at(),aresult);
                         break;
                        }
                       }
                      if(s==0) //no break or empty list
                         results.append(aresult);
    /*                if(*id==msgIdFound)  //Put it first of the list
                      results.prepend(aresult);
                        else
                      results.append(aresult);
    */
                      aresult->requested=*id;
                      aresult->found=msgIdFound;
                      aresult->translation=msgStr;
                      aresult->descriptions.setAutoDelete(true);
                      for(h=0;h<files;h++)
                        {
                          aresult->descriptions.append(adescription=new TranslationInfo());
                          int rr=item.translations[n].infoRef[h];
                          InfoItem info=dm->getCatalogInfo(rr);
                          adescription->location=info.catalogName;
                          adescription->translator=info.lastTranslator;
                          adescription->filePath=info.lastFullPath;
                        }
                      emit numberOfResultsChanged(results.count());
              emit resultFound(aresult);
    //                if(*id==msgIdFound)  //Put it first of the list so th order change
                        emit  resultsReordered();
                    }
                }
              //        idMod=searchList.next();
              it++;
              idMod=&((*it).string);
            }
        }
      gettimeofday(&now,NULL);
      //fprintf(stderr,"%ld.%ld\n",now.tv_sec,now.tv_usec);
      //fprintf(stderr,"Finish, %d (of %d) records in %f seconds!!\n",count,totalRecord, 1.0*now.tv_usec/1000000.0+now.tv_sec-tim);
      emit progress(100);
      emit finished();
      searching=false;
      return true;          //foundSomething;
    }
    bool KDBSearchEngine::startSingleSearch(QString searchString,
                                         unsigned int pattern1Limit=0,unsigned int pattern2Limit=0,
                                         bool inTranslation=false)
    {
       unsigned int nw=0;
      int in=0,len=0;
      clearList();
      addSearchString(searchString,defRule);
      QRegExp  reg("[a-zA-Z0-9_%"/*+remchar*/+regaddchar+"]+");
      while((in=reg.match(searchString,in+len,&len))!=-1) {nw++;}
      in=0;
      len=0;
     // fprintf(stderr,"asas %d\n",nw);
      if(mode==MD_ALL_GOOD_KEYS && !inTranslation)
            return startSearchNow();
      if((nw<pattern1Limit) && (nw >1))
        for(unsigned int k=0;k<nw;k++)
          {
            in=reg.match(searchString,in+len,&len);
            QString regToAdd = searchString;
            regToAdd.replace(in,len,"[a-zA-Z0-9_%"+regaddchar+"]*");
            regToAdd.append("$");
            regToAdd.prepend("^");
    //      fprintf(stderr,"%s",(const char *)regToAdd.local8Bit());
            addSearchString(regToAdd,RegExp);
          }
    
    if(inTranslation)
      return startSearchNow(MD_IN_TRANSLATION);
     else
      return startSearchNow();
      return false;
    }
    //bool KDBSearchEngine::startListSearch(QList<QString> searchStrList)
    //{
      //  searchStringList=searchStrList;
    //  return startSearchNow();
    //}
    void KDBSearchEngine::setLanguageCode(QString ll)
    {
    if(ll==lang) return;
    lang=ll;
     if(dbOpened)  //if opened open it again with new code, what about close before open ?
       dbOpened=loadDatabase(dbname);
    }
    void KDBSearchEngine::setLanguage(QString languageCode, QString languageName)
    {
    setLanguageCode(languageCode);
    }
    void KDBSearchEngine::stopSearch()
    {
      stopNow=true;
    }
    void KDBSearchEngine::clearList()
    {
     searchStringList.clear();
    }
    bool  KDBSearchEngine::isReady() const
            {return IAmReady;}
    void  KDBSearchEngine::saveSettings(KConfigBase *config)
    {
    // updateSettings();  //maybe with autoupdate
     KConfigGroupSaver cgs(config,"KDBSearchEngine");
     config->writeEntry("Filename",dbname);
     config->writeEntry("Language",lang);
     config->writeEntry("CaseSensitive",sens);
     config->writeEntry("Normalize",norm);
     config->writeEntry("RemoveContext",comm);
     config->writeEntry("Rules",defRule);
     config->writeEntry("Limit1",defLimit1);
     config->writeEntry("Limit2",defLimit2);
     config->writeEntry("Substitution1",defSub1);
     config->writeEntry("Substitution2",defSub2);
     config->writeEntry("RegExp",regaddchar);
     config->writeEntry("RemoveCharacter", remchar);
    config->writeEntry("Threshold1",thre);
    config->writeEntry("Threshold2",threorig);
    config->writeEntry("ListMax",listmax);
    config->writeEntry("Mode",mode);
    config->writeEntry("CommonThrs",commonthre);
    config->writeEntry("ReturnNothing",retnot);
    config->writeEntry("AutoAuthor",autoauthor);
    config->writeEntry("AutoUp",autoup);
    }
    void  KDBSearchEngine::readSettings(KConfigBase *config)
    {
     QString newName;
     KConfigGroupSaver cgs(config,"KDBSearchEngine");
     QString defaultLang;
     QString oldLang=lang;
     defaultLang = Defaults::Identity::languageCode();
     lang=config->readEntry("Language",defaultLang);
     QString defaultDir;
     KStandardDirs * dirs = KGlobal::dirs();
     if(dirs)
     {
         defaultDir = dirs->saveLocation("data");
         if(defaultDir.right(1)!="/")
             defaultDir+="/";
         defaultDir += "kbabeldict/dbsearchengine";
     }
     newName=config->readEntry("Filename",defaultDir);
     if(newName!=dbname || oldLang!=lang)
       {
        dbname=newName;
        if(dbOpened)  //Reload only if it is opened
        dbOpened=loadDatabase(dbname);
       }
     sens=config->readBoolEntry("CaseSensitive",false);
     norm=config->readBoolEntry("Normalize",true);
     comm=config->readBoolEntry("RemoveContext",true);
     defRule=config->readNumEntry("Rules",1);
     defLimit1=config->readNumEntry("Limit1",20);
     defLimit2=config->readNumEntry("Limit2",8);
      thre=config->readNumEntry("Threshold1",50);
      threorig=config->readNumEntry("Threshold2",50);
      listmax=config->readNumEntry("ListMax",500);
      mode=config->readNumEntry("Mode",MD_GOOD_KEYS);
     defSub1=config->readBoolEntry("Substitution1",true);
     defSub2=config->readBoolEntry("Substitution2",false);
     regaddchar=config->readEntry("RegExp");
     remchar=config->readEntry("RemoveCharacter","&.:");
     commonthre=config->readNumEntry("CommonThrs",300);
     retnot=config->readBoolEntry("ReturnNothing",false);
     autoauthor=config->readEntry("AutoAuthor");
     autoup=config->readBoolEntry("AutoUp",true);
     setSettings();
    }
    PrefWidget * KDBSearchEngine::preferencesWidget(QWidget *parent)
    {
     pw =  new PreferencesWidget(parent);
     kdDebug(0) << "new pref" << endl;
     setSettings();
     connect(pw,SIGNAL(restoreNow()),this,SLOT(setSettings()));
     connect(pw,SIGNAL(applyNow()),this,SLOT(updateSettings()));
     connect(pw,SIGNAL(destroyed()),this,SLOT(prefDestr()));
     connect(pw->dbpw->scanPB_2,SIGNAL(clicked()),this,SLOT(scan()));
     connect(pw->dbpw->scanrecPB,SIGNAL(clicked()),this,SLOT(scanRecur()));
     connect(pw->dbpw->scanFilePB,SIGNAL(clicked()),this,SLOT(scanFile()));
     connect(pw->dbpw->repeatPB,SIGNAL(clicked()),this,SLOT(repeat()));
    return pw;
    }
    void KDBSearchEngine::scanRecur()
    {
    if (scanInProgress) return;
    updateSettings();
    if(!openDb())
            return;
    scanInProgress=true;
    PoScanner *sca=new PoScanner(dm,this,"Po Scanner");
    QString cvsdir;
    cvsdir=KFileDialog::getExistingDirectory("",0,i18n("Select a directory you want to scan recursively"));
    if(cvsdir.isEmpty()) {scanInProgress=false; return;}
    if(pw) {
    connect(sca,SIGNAL(patternProgress(int)),pw->dbpw->totalPB,SLOT(setProgress(int)) );
    connect(sca,SIGNAL(fileLoading(int)),pw->dbpw->loadingPB,SLOT(setProgress(int)));
    connect(sca,SIGNAL(fileProgress(int)),pw->dbpw->processPB,SLOT(setProgress(int)));
    }
    connect(sca,SIGNAL(patternProgress(int)),SIGNAL(progress(int)) ); //Kbabel progress bar
    connect(sca,SIGNAL(added(int)),pw,SLOT(setEntries(int)));
    connect(sca,SIGNAL(filename(QString)),pw,SLOT(setName(QString)));
    progressStarts(i18n("Scanning directory %1").arg(cvsdir));
    connect(sca,SIGNAL(patternFinished()),SIGNAL(progressEnds()) );
    sca->scanPattern(cvsdir,"*.po",true);
    disconnect(this,SIGNAL(progress(int)) );
    //disconnect(SIGNAL(patternStarted()),this,SIGNAL(started()) );
    disconnect(this,SIGNAL(progressEnds()) );
    if(pw) {
    disconnect(pw->dbpw->totalPB,SLOT(setProgress(int)) );
    disconnect(pw->dbpw->loadingPB,SLOT(setProgress(int)));
    disconnect(pw->dbpw->processPB,SLOT(setProgress(int)));
    }
    totalRecord=dm->count();
    scanInProgress=false;
    dm->sync();
    delete sca;
    }
    void KDBSearchEngine::scan()
    {
    if (scanInProgress) return;
    updateSettings();
    if(!openDb())
            return;
    scanInProgress=true;
    PoScanner *sca=new PoScanner(dm,this,"Po Scanner");
    QString cvsdir;
    cvsdir=KFileDialog::getExistingDirectory("",0,i18n("Select a directory you want to scan"));
    if(cvsdir.isEmpty()) {scanInProgress=false; return;}
    if(pw){
    connect(sca,SIGNAL(patternProgress(int)),pw->dbpw->totalPB,SLOT(setProgress(int)) );
    connect(sca,SIGNAL(fileLoading(int)),pw->dbpw->loadingPB,SLOT(setProgress(int)));
    connect(sca,SIGNAL(fileProgress(int)),pw->dbpw->processPB,SLOT(setProgress(int)));
    }
    connect(sca,SIGNAL(patternProgress(int)),SIGNAL(progress(int)) );
    progressStarts(i18n("Scanning directory %1").arg(cvsdir));
    connect(sca,SIGNAL(patternFinished()),SIGNAL(progressEnds()) );
    connect(sca,SIGNAL(added(int)),pw,SLOT(setEntries(int)));
    connect(sca,SIGNAL(filename(QString)),pw,SLOT(setName(QString)));
    sca->scanPattern(cvsdir,"*.po",false);
    disconnect(this,SIGNAL(progress(int)) );
    //disconnect(SIGNAL(patternStarted()),this,SIGNAL(started()) );
    disconnect(this,SIGNAL(progressEnds()) );
    if(pw){
    disconnect(pw->dbpw->totalPB,SLOT(setProgress(int)) );
    disconnect(pw->dbpw->loadingPB,SLOT(setProgress(int)));
    disconnect(pw->dbpw->processPB,SLOT(setProgress(int)));
    }
    totalRecord=dm->count();
    scanInProgress=false;
    dm->sync();
    delete sca;
    }
    void KDBSearchEngine::scanFile()
    {
    if (scanInProgress) return;
    updateSettings();
    if(!openDb())
            return;
    scanInProgress=true;
    PoScanner *sca=new PoScanner(dm,this,"Po Scanner");
    QString cvsdir;
    pw->dbpw->totalPB->setProgress(0);
    cvsdir=KFileDialog::getOpenFileName("","*.po",0
            ,i18n("Select a po file to scan"));
    if(cvsdir.isEmpty()) {scanInProgress=false; return;}
    if(pw){
    connect(sca,SIGNAL(fileLoading(int)),pw->dbpw->loadingPB,SLOT(setProgress(int)));
    connect(sca,SIGNAL(fileProgress(int)),pw->dbpw->processPB,SLOT(setProgress(int)));
    }
    connect(sca,SIGNAL(fileProgress(int)),SIGNAL(progress(int)) );
    progressStarts(i18n("Scanning file %1").arg(directory(cvsdir,0)));
    connect(sca,SIGNAL(fileFinished()),SIGNAL(progressEnds()) );
    connect(sca,SIGNAL(added(int)),pw,SLOT(setEntries(int)));
    connect(sca,SIGNAL(filename(QString)),pw,SLOT(setName(QString)));
    sca->scanFile(cvsdir);
    sca->disconnect(SIGNAL(fileProgress(int)),this,SIGNAL(progress(int)) );
    //disconnect(SIGNAL(patternStarted()),this,SIGNAL(started()) );
    sca->disconnect(SIGNAL(fileFinished()),this,SIGNAL(progressEnds()) );
    if(pw)
    {
    disconnect(pw->dbpw->loadingPB,SLOT(setProgress(int)));
    disconnect(pw->dbpw->processPB,SLOT(setProgress(int)));
    }
    totalRecord=dm->count();
    scanInProgress=false;
    dm->sync();
    delete sca;
    }
    const KAboutData *KDBSearchEngine::about() const
    {
            return DbSeFactory::instance()->aboutData();
    }
    QString  KDBSearchEngine::name() const
    {
    return i18n("Translation database");
    }
    QString  KDBSearchEngine::id() const
    {
    return QString("KDBSearchEngine");
    }
    QString  KDBSearchEngine::lastError()
    {
    return lasterror;
    }
    void  KDBSearchEngine::prefDestr()
    {
    pw=0;
    }
    void  KDBSearchEngine::setSettings()
    {
    if(pw==0) return;
     pw->dbpw->dirInput->setURL(dbname);
     pw->dbpw->caseSensitiveCB->setChecked(sens);
     pw->dbpw->normalizeCB->setChecked(norm);
     pw->dbpw->removeContextCB->setChecked(comm);
     pw->dbpw->oneWordSubCB->setChecked(defSub1);
     pw->dbpw->twoWordSubCB->setChecked(defSub2);
     if(defRule==8) pw->dbpw->RegExpRB->setChecked(true);
      else
      {
       pw->dbpw->normalTextRB->setChecked(true);
      pw->dbpw->equalCB->setChecked( defRule & Equal );
       pw->dbpw->containsCB->setChecked( defRule & Contains );
       pw->dbpw->containedCB->setChecked( defRule & Contained );
      }
     pw->dbpw->oneWordSubSB->setValue(defLimit1);
     pw->dbpw->twoWordSubSB->setValue(defLimit2);
     pw->dbpw->maxSB->setValue(listmax);
     pw->dbpw->thresholdSL->setValue(thre);
     pw->dbpw->thresholdOrigSL->setValue(threorig);
      pw->dbpw->allRB->setChecked( mode==MD_ALL_DB);
      pw->dbpw->slistRB->setChecked( mode==MD_GOOD_KEYS);
      pw->dbpw->rlistRB->setChecked( mode==MD_ALL_GOOD_KEYS  );
      pw->dbpw->nothingCB->setChecked(retnot);
      pw->dbpw->freqSB->setValue(commonthre);
     pw->dbpw->regExpLE->setText(regaddchar);
     pw->dbpw->ignoreLE->setText(remchar);
      pw->dbpw->authorLE->setText(autoauthor);
      pw->dbpw->autoAddCB_2->setChecked(autoup);
    }
    void  KDBSearchEngine::updateSettings()
    {
    if(pw==0) return;
     QString newName=pw->dbpw->dirInput->url();
     if(newName!=dbname)
       {
        kdDebug(0) << "Database changed" << endl;
        dbname=newName;
        if(dbOpened)
        dbOpened=loadDatabase(dbname);
       }
     sens=pw->dbpw->caseSensitiveCB->isChecked();
     norm=pw->dbpw->normalizeCB->isChecked();
     comm=pw->dbpw->removeContextCB->isChecked();
     int tmpRule=0;
     if(pw->dbpw->RegExpRB->isChecked())
      tmpRule=RegExp;
      else
      {
       if(pw->dbpw->equalCB->isChecked()) tmpRule+=Equal;
       if(pw->dbpw->containsCB->isChecked()) tmpRule+=Contains;
       if(pw->dbpw->containedCB->isChecked()) tmpRule+=Contained;
      }
     defRule=tmpRule;
     defLimit1=pw->dbpw->oneWordSubSB->text().toInt();
     defLimit2=pw->dbpw->twoWordSubSB->text().toInt();
     defSub1=pw->dbpw->oneWordSubCB->isChecked();
     defSub2=pw->dbpw->twoWordSubCB->isChecked();
     listmax=pw->dbpw->maxSB->value();
     thre=pw->dbpw->thresholdSL->value();
     threorig=pw->dbpw->thresholdOrigSL->value();
    if(pw->dbpw->allRB->isChecked()) mode=MD_ALL_DB;
     if(pw->dbpw->slistRB->isChecked()) mode=MD_GOOD_KEYS;
    if(pw->dbpw->rlistRB->isChecked()) mode=MD_ALL_GOOD_KEYS;
     regaddchar=pw->dbpw->regExpLE->text();
     remchar=pw->dbpw->ignoreLE->text();
     retnot=pw->dbpw->nothingCB->isChecked();
     commonthre=pw->dbpw->freqSB->value();
     autoauthor=pw->dbpw->authorLE->text();
     autoup=pw->dbpw->autoAddCB_2->isChecked();
    }
    void  KDBSearchEngine::setLastError(QString er)
    {
    lasterror=er;
    }
    QString KDBSearchEngine::translate(const QString text)
    {
    if(!openDb())
          return QString::null;
    /*
    if(!dbOpened)
        {
        dbOpened=loadDatabase(dbname);  //Try first to open it now
        if(!dbOpened) // Still not opened!!
            {
             //emit anerror
             hasError(i18n("Database not opened"));
             return QString::null;
           }
         }
    */
    DataBaseItem dbit=dm->getItem(text);
    if(dbit.isNull()) return QString::null;
    if(dbit.numTra==1) return dbit.translations[0].translation;
    uint32 n=dbit.numTra;
    uint32 max=0,nmax=0;
    for(uint32 i=0;i<n;i++)
     if(dbit.translations[i].numRef>max)
        {
                nmax=i;
                max= dbit.translations[i].numRef;
        }
    return dbit.translations[nmax].translation;
    }
    QValueList<KeyAndScore> KDBSearchEngine::searchWords(QString phrase,int threshold,
                                                     int thresholdorig,uint32 max)
    {
    QValueList<QString> wordlist;
    
        if(!openDb())
        {
          QValueList<KeyAndScore> a;
          return a;
        }
    progressStarts(i18n("Searching words"));
    QValueList<QString>::Iterator wlit;
    wordlist=dm->wordsIn(phrase);
    int nw=wordlist.count();
    //QArray<WordItem> wi(nw);
    QArray<uint32> numofloc(nw),currentloc(nw);
    QArray<int> score(nw);
    QArray<uint32 *> loc(nw),locorig(nw);
    QValueList<uint32> resloc;
    QValueList<int> resfound;
    QValueList<KeyAndScore> keylist;
    //wi.resize(wordlist.count());
    int totalprogress=0;
    int totrec=dm->count();
    uint32 cthre=totrec*commonthre/10000;
    int i=0,common=0;
    for(wlit=wordlist.begin();wlit!=wordlist.end();++wlit)
     {
      WordItem wi=dm->getWordLocations(*wlit);
      if(!wi.notFound())
      {
      if(wi.count<cthre)
           score[i]=1;
          else
          { score[i]=0; common++; }
    
               locorig[i]=loc[i]=wi.locations;
               totalprogress+=numofloc[i]=wi.count;
               currentloc[i]=0;
    //         score[i]=wi.score;
               //wi[i]=WordItem(wi[i]);
               //wi[i].locations.detach();
              i++;
    //     }
     //   else
       //  common++;
      }
     }
    bool cs=(common==nw);  //All words are common;
    if (totalprogress==0) totalprogress=1;
    int step=totalprogress/30+1;
    int count=0;
    int thrs=(wordlist.count()*threshold)/100;
    if(thrs<1) thrs=1;  // whole database ???
    int tot=i;
    //nt32 jmin=0;
    int found;
    uint32 min; //Big ?
    bool empty=false;
    while(!empty)
    {
     empty=true;
    found=retnot?common:0;
    if(thrs<=found) thrs=found+1;  // whole database ???
     min=BIGNUMBER;
     for(int j=0;j<tot;j++)
      if(cs || score[j]) {
         if(numofloc[j]>currentloc[j])   // Check if there's still something to do.
          empty=false;
             if(loc[j][0]<min)                  //Found the minimum head
                   min=loc[j][0];
       }
    if(min!=BIGNUMBER)
     {
     for(int j=0;j<tot;j++)
        if(cs || score[j]) {
          if(loc[j][0]==min)            //Count the heads, move forward
            {
            found++;
            count++;
            //check stopnow  here
            if(count%step==0)
            {
               emit progress(100*count/totalprogress);
                kapp->processEvents();
              }
    
            currentloc[j]++;
             if(numofloc[j]==currentloc[j]) //End reached
                loc[j][0]=BIGNUMBER;        //so set head to a big number
               else   //Go on..
               {
                 loc[j]++;
               }
            }
        }   //end of for
    bool inserted=false;
    if(found>=thrs)
      {
      //Words count in key.
      int nword=0;
      int in=0,len=0;
      QString keyst=dm->getKey(min);
      QRegExp  reg("[a-zA-Z0-9_%"/*+remchar*/+regaddchar+"]+");
      while((in=reg.match(keyst,in+len,&len))!=-1) {nword++;}
      if(found>=nword*thresholdorig/100)  //
       {
            if(resfound.count()<=max || (*resfound.end() < found))
            if((*resfound.end())>= found)
            {
                    inserted=true;
                    resloc.append(min);
                     resfound.append(found);
            }
            else
            for(uint32 j=0;j<resloc.count();j++)
            {
                    if(resfound[j]<found || (resfound[j]==found && 0) )  //Orig word
                    {
                     resloc.insert(resloc.at(j),min);
                     resfound.insert(resfound.at(j),found);
                     inserted=true;
                     break;
                    }
             }
                    if(!inserted)
                    {
                            resloc.append(min);
                            resfound.append(found);
                    }
          }
      }
     }
    }
    int nres=(resloc.count()<max)?resloc.count():max;
    for(int j=0;j<nres;j++)
     {
      QString strkey=dm->getKey(resloc[j]);
      int stdscore=KDBSearchEngine::score(phrase,strkey);
      int sc=0;
      if(stdscore<99)
        {
        int in=0,len=0,nword=0;
        int remove=retnot?common:0;
         QRegExp  reg("[a-zA-Z0-9_%"/*+remchar*/+regaddchar+"]+");
         while((in=reg.match(strkey,in+len,&len))!=-1) {nword++;}
    //    kdDebug(0) << nword << "NWORD  " << resfound[j] << "FOUND  "
    //    << resfound[j]-remove << "REAL  " << remove << "to be remove   " << endl;
        if(nword<1) nword=1;
        sc=  70-resfound[j]*70/nw+abs(nword-(resfound[j]-remove))*30/nword+2;
        sc=100-sc;
    //    kdDebug(0) <<" Score : " << sc << endl;
        }else
        sc=stdscore;
      KeyAndScore key(strkey,sc);
    //  kdDebug(0) << (QString) key << " [" << key.score << "]" << endl;
      keylist.append(key);
     }
    //kdDebug(0) << "Here!" << endl;
    for(int j=0;j<tot;j++)
     {
             free(locorig[j]);
     }
    progressStarts(i18n("Process output"));
    return keylist;
    }
    void KDBSearchEngine::stringChanged( QString orig, QString translated
                                          , QString description)
    {
    //author is KBABEL ????
    //#warning uncomment and FIXME
            //done
    if(autoup)
    {
    /* if(!dbOpened)
     {
      dm= new DataBaseManager(dbname,lang,this,"Database manager");
      if(dm->isOk())
       dbOpened=true;
      else
      {
       dbOpened=false;
       delete dm;
       dm=0;
      }
     }*/
    
    if(openDb(true))  //true= no ask
     {
    
            dm->putNewTranslation(orig,translated,dm->catalogRef(directory(edited,0),autoauthor,edited));
     //kdDebug(0) << "Changed " << orig << " " << translated << endl;
          dm->sync();
     }
    }
    }
    void KDBSearchEngine::setEditedFile(QString file)
    {
    
            edited=file;//kdDebug(0) << edited << endl;
    }
    
    KeyAndScore::KeyAndScore(const QString &a,int sc)
    : QString(a)
    {
    score=sc;
    }
    KeyAndScore::KeyAndScore()
    : QString()
    {
    score=0;
    }
    
    #include "KDBSearchEngine.moc"

  7. #7
    Ngày gia nhập
    02 2009
    Bài viết
    21

    Trích dẫn Nguyên bản được gửi bởi ruacon Xem bài viết
    em có cái này mới anh xem thử.
    C++ Code:
    1. #include <qmultilineedit.h>
    2. #include <qprogressdialog.h>
    3. #include <qinputdialog.h>
    4. #include <klocale.h>
    5. #include <kdebug.h>
    6. #include <kmessagebox.h>
    7. #include <kfiledialog.h>
    8. #include <kurlrequester.h>
    9. #include <kstddirs.h>
    10. #include "kapp.h"
    11. #include "KDBSearchEngine.h"
    12. #include "dbscan.h"
    13. #include "errno.h"
    14. #include "stdio.h"
    15. #include "stdlib.h"
    16. #include <sys/time.h>
    17. #include "preferenceswidget.h"
    18. #include "dbse_factory.h"
    19. #include <qprogressbar.h>
    20. #include <qpushbutton.h>
    21. #include <klineedit.h>
    22. #include <kconfig.h>
    23. #include <qdir.h>
    24. #include <qradiobutton.h>
    25. #include <qcheckbox.h>
    26. #include <qspinbox.h>
    27. #include <qslider.h>
    28. #include <qarray.h>
    29. #include "database.h"
    30. #include "catalogsettings.h"
    31. #define BIGNUMBER 400000000
    32. KDBSearchEngine::KDBSearchEngine(QObject *parent,const char*name)
    33.  : SearchEngine(parent,name)
    34. {
    35. edited="unknown";
    36. dm=0;   //Database Manager
    37. pw=0;   //Preference widget
    38. lang="";
    39. dbOpened=false;
    40. dbname="";
    41. lasterror=i18n("No error");
    42. connect(this,SIGNAL(hasError(QString)),SLOT(setLastError(QString)));
    43.   IAmReady=true;  //  I don't know if it is a good idea, no DB loaded!!!
    44.   scanInProgress=false;
    45.   searching=false;
    46.   stopNow=false;
    47.   norm=false;   // Normalize white space = FALSE
    48.   comm=true;    // Remove Comments = TRUE
    49. }
    50. KDBSearchEngine::~KDBSearchEngine()
    51. {
    52. }
    53. bool KDBSearchEngine::loadDatabase(QString database,bool noask=false)
    54. {
    55.    bool ret=true;
    56.    bool asked=false;
    57.    if(noask)  asked=true;
    58.    if(dm!=0)
    59.    {
    60.        delete dm;
    61.        dm=0;
    62.    }
    63.    QDir dir(database);
    64.    if(!dir.exists())
    65.    {
    66.        if(asked || KMessageBox::questionYesNo(0,i18n(
    67.             "Database directory does not exist:\n%1\n"
    68.             "Do you want to create it now?").arg(database))
    69.                ==KMessageBox::Yes)
    70.        {
    71.            asked=true;
    72.            QStringList dirList;
    73.            while(!dir.exists() && !dir.dirName().isEmpty())
    74.            {
    75.               dirList.prepend(dir.dirName());
    76.               dir.setPath(dir.path()+"/..");
    77.            }
    78.            for(QStringList::Iterator it = dirList.begin(); it!=dirList.end()
    79.                    ; ++it)
    80.            {
    81.               if(!dir.mkdir(*it))
    82.               {
    83.                   KMessageBox::sorry(0,
    84.                        i18n("It was not possible to create directory %1")
    85.                        .arg(dir.path()+"/"+(*it)) );
    86.                   ret=false;
    87.                   break;
    88.               }
    89.               dir.cd(*it);
    90.            }
    91.        }
    92.        else
    93.        {
    94.            ret=false;
    95.        }
    96.    }
    97.   if(ret)
    98.   {
    99.       dm= new DataBaseManager(database,lang,this,"Database manager");
    100.       if(!dm->isOk())
    101.       {
    102.         if(asked || KMessageBox::questionYesNo(0
    103.             ,i18n("Database files not found.\nDo you want to create them now?"))
    104.             ==KMessageBox::Yes)
    105.         {
    106.            //fprintf(stderr,"SI\n");
    107.            ret=dm->createDataBase(database,lang);
    108.         }
    109.         else
    110.           ret=false;
    111.       }
    112.       else ret=true;
    113.   }
    114. //Wrong errore hangdling
    115.   if(ret)
    116.    totalRecord=dm->count();
    117.   else totalRecord=0;
    118.   return ret;
    119. }
    120. void KDBSearchEngine::setNormalizeSpace(bool normalize)
    121. {
    122.   norm=normalize;
    123. }
    124. void KDBSearchEngine::setRemoveInternalComment(bool internalcomment)
    125. {
    126.   comm=internalcomment;
    127. }
    128. void KDBSearchEngine::setCaseSensitive(bool sensitive)
    129. {
    130.   sens=sensitive;
    131. }
    132. void KDBSearchEngine::setRemoveCharString(QString chartoremove)
    133. {
    134.   remchar=chartoremove;
    135. }
    136. bool KDBSearchEngine::isSearching() const
    137. {
    138.   return searching;
    139. }
    140. int KDBSearchEngine::addSearchString(QString searchString, int rule)
    141. {
    142.   if(searching||scanInProgress) return -1;
    143.   SearchEntry e;
    144.   e.string=QString(searchString);
    145.   e.rules=rule;
    146.   searchStringList.append(e);
    147.   return searchStringList.count();
    148. }
    149. bool KDBSearchEngine::startSearch(QString str)
    150. {
    151.  
    152.  if(autoUpdate)
    153.    {
    154.     updateSettings();
    155.    }
    156.  int l1=0,l2=0;
    157.  if(defSub1) l1=defLimit1;
    158.  if(defSub2) l2=defLimit2;
    159. return startSingleSearch(str,l1,l2);
    160. }
    161. bool KDBSearchEngine::startSearchInTranslation(QString s)
    162. {
    163.  if(autoUpdate)
    164.    {
    165.     updateSettings();
    166.    }
    167.  int l1=0,l2=0;
    168.  if(defSub1) l1=defLimit1;
    169.  if(defSub2) l2=defLimit2;
    170.  return startSingleSearch(s,l1,l2,true);
    171. }
    172. bool KDBSearchEngine::openDb(bool noask=false)
    173. {
    174.   if(!dbOpened)
    175.     {
    176.       dbOpened=loadDatabase(dbname,noask);  //Try first to open it now
    177.      if(!dbOpened) // Still not opened!!
    178.          {
    179.              hasError(i18n("Cannot open the database"));
    180.              return false;
    181.           }
    182.     }
    183. return true;
    184. }
    185. bool KDBSearchEngine::messagesForPackage(const QString& package
    186.                          , QValueList<Message>& resultList, QString& error)
    187. {
    188.  
    189.   int count = 0;
    190.   stopNow=false; // Remove dirty.
    191.   Message m;
    192.   if(searching )
    193.   {
    194.    error=i18n("Another search has already been started");
    195.    return false;
    196.   }
    197.   if(scanInProgress)
    198.   {
    199.    error=i18n("Cannot search now: a po file scan is in progress");
    200.    return false;
    201.   }
    202.   if(!openDb()) {
    203.    error=i18n("Cannot open the database");
    204.    return false;
    205.   }
    206.    if(totalRecord<=0)
    207.      {
    208.      error=i18n("Database empty");
    209.      return false;
    210.      }
    211.    int step=(totalRecord/30)+1;
    212.    int ntra,nref;
    213.    int req=dm->searchCatalogInfo(package);
    214.    if(req==-1) {
    215.     error=i18n("No entry for this package in the database.");
    216.     return false;
    217.    }
    218.    DataBaseItem item;
    219.    int i,h;
    220.    kdDebug(0) << "looking for catalog " << req <<endl;
    221.    progressStarts(i18n("Searching for %1 in database").arg(package));
    222.    for(item = dm->firstItem();!item.isNull();item=dm->nextItem())
    223.    {
    224.       count++;
    225.       if(count%step==0){
    226.            emit progress(100*count/totalRecord);
    227.            kapp->processEvents();
    228.          }
    229.       if(stopNow) {
    230.         stopNow=false;
    231.         searching=false;
    232.         emit finished();
    233.         return true;    // No error, stopped!
    234.       }
    235.       ntra=item.numTra;
    236.       for(i=0;i<ntra;i++) {
    237.        nref=item.translations[i].numRef;
    238.           for(h=0;h<nref;h++){
    239.             if(item.translations[i].infoRef[h]==req) {
    240.                 m.msgid=item.key;
    241.                 m.msgstr=item.translations[i].translation;
    242.                 resultList.append(m);
    243.               }
    244.           }
    245.       }
    246.  
    247.    }
    248.    return true;
    249. }
    250. void KDBSearchEngine::repeat()
    251. {
    252.   int count = 0;
    253.   stopNow=false; // Remove dirty.
    254.   if(searching )
    255.   {
    256.     return;
    257.   }
    258.   if(scanInProgress)
    259.   {
    260.    return;
    261.   }
    262.   if(!openDb()) {
    263.    return;
    264.   }
    265.    if(totalRecord<=0)
    266.      {
    267.      return;
    268.      }
    269.    int step=(totalRecord/30)+1;
    270.    int ntra,nref;
    271.    DataBaseItem item;
    272.    int i,h,tot;
    273.    int req=dm->searchCatalogInfo("kdelibs.po");
    274.    if(req==-1) kdDebug(0) << "No kdelibs.po found!" << endl;
    275.    QProgressDialog *pd=new QProgressDialog(i18n("Looking for repetitions"),i18n("Stop"),100);
    276.    connect(this,SIGNAL(progress(int)),pd,SLOT(setProgress(int)));
    277.    connect(this,SIGNAL(finished()),pd,SLOT(close()));
    278.    connect(pd,SIGNAL(cancelled()),this,SLOT(stopSearch()));
    279.    QString txt="// %1 repetitions, %2 translation(s)\ni18n(\"%3\");\n";
    280.    QString id;
    281.    int min;
    282.    bool ok = false;
    283.    min=QInputDialog::getInteger(i18n("Minimum repetition"),i18n("Insert the minimum number of repetitions for a string"),
    284.                                 2,1,999999,1,&ok);
    285.    if(!ok)
    286.        return;
    287.      pd->show();
    288.    progressStarts(i18n("Searching repeated string"));
    289.    static QMultiLineEdit *mle=new QMultiLineEdit();
    290.    mle->clear();
    291.    bool inlibs;
    292.    for(item = dm->firstItem();!item.isNull();item=dm->nextItem())
    293.    {
    294.       count++;
    295.       if(count%step==0){
    296.            emit progress(100*count/totalRecord);
    297.            kapp->processEvents();
    298.          }
    299.       if(stopNow) {
    300.         stopNow=false;
    301.         searching=false;
    302.         emit finished();
    303.         return; // No error, stopped!
    304.       }
    305.       tot=0;
    306.       inlibs=false;
    307.       ntra=item.numTra;
    308.       for(i=0;i<ntra;i++) {
    309.        nref=item.translations[i].numRef;
    310.           for(h=0;h<nref;h++)
    311.             if(item.translations[i].infoRef[h]==req) inlibs=true;
    312.             tot+=nref;
    313.           }
    314.       if (tot>=min && !inlibs)
    315.         {
    316.             id=item.key;
    317.             id=id.replace(QRegExp("\\n"),"\"\n\"");
    318.             mle->append(txt.arg(tot).arg(ntra).arg(id));
    319.         }
    320.       }
    321.      emit progress(100);
    322.         emit finished();
    323.     mle->resize(400,400);
    324.     mle->show();
    325.     delete pd;
    326.    return;
    327. }
    328. bool KDBSearchEngine::startSearchNow(int searchmode)
    329. {
    330.   if(searchmode==-1) searchmode=mode;
    331.   int count = 0;
    332.   stopNow=false; // Remove dirty.
    333.   clearResults();
    334.   if(searching )
    335.   {
    336.    hasError(i18n("Another search has already been started"));
    337.    return false;
    338.   }
    339.   if(scanInProgress)
    340.   {
    341.    hasError(i18n("Cannot search now: a po file scan is in progress"));
    342.    return false;
    343.   }
    344.   if(!openDb())
    345.    return false;
    346.    if(totalRecord<=0)
    347.      {
    348.      hasError(i18n("Database empty"));
    349.      return false;
    350.      }
    351.   searching=true;
    352.   emit started();
    353.   bool allkey=(searchmode==MD_ALL_GOOD_KEYS);
    354.   bool equal,contains,contained,regexp,intra;
    355.   intra=searchmode & MD_IN_TRANSLATION;
    356.   QString msgIdFound;
    357.   QString msgId;
    358.   QString msgStr;
    359.   //QString msgIdRequested;
    360.   SearchResult *aresult;
    361.   TranslationInfo *adescription;
    362.   SearchList searchList;
    363.   int i,len,files,h;
    364.   len=remchar.length();
    365.   int n,m;//,word;
    366.   QString  *id;
    367.   QString mainRequest=searchStringList[0].string;
    368.   SearchList::Iterator it,it1;
    369.   QString *idMod;
    370.   bool foundSomething=false;
    371.   searchList=searchStringList;   //Create a copy and modify it
    372.   if(!allkey)
    373.   {
    374.   for ( it=searchList.begin(); it != searchList.end(); ++it )
    375.     {
    376.       idMod=&((*it).string);
    377.         int pos;
    378.         for(i=0;i<len;i++)
    379.          while((pos=idMod->find(remchar.at(i)))!=-1)
    380.         idMod->remove(pos,1);
    381.         if(comm)
    382.          idMod->replace(QRegExp("\\_\\:.*\\\\n"),"");  //Read it from catalog !!! (NOT ONLY HERE)
    383.       if(norm) idMod->simplifyWhiteSpace();
    384.       if(!sens) *idMod=idMod->upper();
    385.     }
    386.    }
    387.   timeval now;
    388.   gettimeofday(&now,NULL);
    389.   //fprintf(stderr,"\n%ld.%ld\n",now.tv_sec,now.tv_usec);
    390.   double tim=1.0*now.tv_usec/1000000.0+now.tv_sec;
    391.   int pos;
    392.    DataBaseItem item;
    393.   //Now we can browse the whole db or the "good keys"
    394.  QValueList<KeyAndScore> goodkeys;
    395.   int totalprogress;
    396.   bool gk=(searchmode==MD_GOOD_KEYS)||allkey;
    397.   int k=0;
    398.   if(gk) {
    399.      goodkeys=searchWords(mainRequest,thre,threorig,listmax);//FIX IT, mainReq?
    400.         }
    401.    totalprogress=gk?goodkeys.count():totalRecord;
    402.    int step=(totalprogress/30)+1;
    403.    for(item = gk?(dm->getItem(goodkeys[0])):(dm->firstItem());
    404.         !item.isNull();
    405.        item = gk?(dm->getItem(goodkeys[++k])):(dm->nextItem()))
    406.    {
    407. //   Emit progress, process event and check stop now
    408.       if(count%step==0){
    409.            emit progress(100*count/totalprogress);
    410.            kapp->processEvents();
    411.          }
    412.       if(stopNow) {
    413.         stopNow=false;
    414.         searching=false;
    415.         emit finished();
    416.         return true;    // No error, stopped!
    417.       }
    418.     //  fprintf(stderr,"%s\n",(const char *)item.key.utf8());
    419.       msgIdFound=item.key;  //Check if this is OK with UTF8
    420. //     searchmode && MD_IN_TRANSLATION)
    421.       count++;
    422.        msgId=msgIdFound;
    423.      if(!allkey)
    424.      {
    425.         //Remove character in list of character to be ignored
    426.         for(i=0;i<len;i++)
    427.          while((pos=msgId.find(remchar.at(i)))!=-1)
    428.         msgId.remove(pos,1);
    429.         //Remove context information from id found
    430.         if(comm)
    431.          msgId.replace(QRegExp("\\_\\:.*\\\\n"),"");
    432.       if(norm) msgId.simplifyWhiteSpace();
    433.       if(!sens) msgId=msgId.upper();
    434.       }
    435.       it=searchList.begin();
    436.       idMod=&((*it).string);
    437.       bool foundExact=false;
    438.       for ( it1=searchStringList.begin(); it1 != searchStringList.end(); it1++ )
    439.         {
    440.           id=&((*it1).string);
    441.           int nn=0;
    442.           do {
    443.             if(intra) {
    444.                msgId=item.translations[nn].translation;
    445.                if(!allkey) {
    446.                    //Remove character in list of character to be ignored
    447.                     for(i=0;i<len;i++)
    448.                     while((pos=msgId.find(remchar.at(i)))!=-1)
    449.                         msgId.remove(pos,1);
    450.                    //Remove context information from id found
    451.                    if(comm)
    452.                        msgId.replace(QRegExp("\\_\\:.*\\\\n"),"");
    453.                    if(norm) msgId.simplifyWhiteSpace();
    454.                    if(!sens) msgId=msgId.upper();
    455.               }
    456.             }
    457.             int rules=(*it).rules;
    458.             if (rules & Equal) equal=(*idMod==msgId); else equal=false;
    459.             if (rules & Contains) contains=idMod->contains(msgId);
    460.            else contains=false;
    461.             if (rules & Contained) contained=msgId.contains(*idMod); else contained=false;
    462.             if  (!foundExact && (rules & RegExp ))
    463.                 {
    464.                   QRegExp reg(*idMod);
    465.                   regexp=(reg.match(msgId)!=-1);
    466.                 } else regexp=false;
    467.           nn++;
    468.           } while(intra && nn<item.numTra);
    469.           if(equal||contains||contained||regexp||allkey)
    470.             {
    471. //           kdDebug(0) << QString("Found") << endl;
    472.               if(equal) foundExact=true;
    473.              m=item.numTra;  //Translations found.
    474.               for(n=0;n<m;n++)
    475.                 {
    476.                   foundSomething=true;
    477.                   msgStr=item.translations[n].translation;
    478.                   files=item.translations[n].numRef;
    479.                   aresult=new SearchResult();
    480.                   results.setAutoDelete(true);
    481.                  if(!gk)
    482.                   aresult->score=score(mainRequest,msgIdFound);
    483.                  else
    484.                   aresult->score=goodkeys[k].score;
    485.                 if(intra)
    486.                   aresult->score=score(mainRequest,item.translations[n].translation);
    487.                   SearchResult *s=0;
    488.                   for(s=results.first();s!=0;s=results.next())
    489.                    {
    490.                     if(s->score > aresult->score)
    491.                     {
    492.                      results.insert(results.at(),aresult);
    493.                      break;
    494.                     }
    495.                    }
    496.                   if(s==0) //no break or empty list
    497.                      results.append(aresult);
    498. /*                if(*id==msgIdFound)  //Put it first of the list
    499.                   results.prepend(aresult);
    500.                     else
    501.                   results.append(aresult);
    502. */
    503.                   aresult->requested=*id;
    504.                   aresult->found=msgIdFound;
    505.                   aresult->translation=msgStr;
    506.                   aresult->descriptions.setAutoDelete(true);
    507.                   for(h=0;h<files;h++)
    508.                     {
    509.                       aresult->descriptions.append(adescription=new TranslationInfo());
    510.                       int rr=item.translations[n].infoRef[h];
    511.                       InfoItem info=dm->getCatalogInfo(rr);
    512.                       adescription->location=info.catalogName;
    513.                       adescription->translator=info.lastTranslator;
    514.                       adescription->filePath=info.lastFullPath;
    515.                     }
    516.                   emit numberOfResultsChanged(results.count());
    517.           emit resultFound(aresult);
    518. //                if(*id==msgIdFound)  //Put it first of the list so th order change
    519.                     emit  resultsReordered();
    520.                 }
    521.             }
    522.           //        idMod=searchList.next();
    523.           it++;
    524.           idMod=&((*it).string);
    525.         }
    526.     }
    527.   gettimeofday(&now,NULL);
    528.   //fprintf(stderr,"%ld.%ld\n",now.tv_sec,now.tv_usec);
    529.   //fprintf(stderr,"Finish, %d (of %d) records in %f seconds!!\n",count,totalRecord, 1.0*now.tv_usec/1000000.0+now.tv_sec-tim);
    530.   emit progress(100);
    531.   emit finished();
    532.   searching=false;
    533.   return true;          //foundSomething;
    534. }
    535. bool KDBSearchEngine::startSingleSearch(QString searchString,
    536.                                      unsigned int pattern1Limit=0,unsigned int pattern2Limit=0,
    537.                                      bool inTranslation=false)
    538. {
    539.    unsigned int nw=0;
    540.   int in=0,len=0;
    541.   clearList();
    542.   addSearchString(searchString,defRule);
    543.   QRegExp  reg("[a-zA-Z0-9_%"/*+remchar*/+regaddchar+"]+");
    544.   while((in=reg.match(searchString,in+len,&len))!=-1) {nw++;}
    545.   in=0;
    546.   len=0;
    547.  // fprintf(stderr,"asas %d\n",nw);
    548.   if(mode==MD_ALL_GOOD_KEYS && !inTranslation)
    549.         return startSearchNow();
    550.   if((nw<pattern1Limit) && (nw >1))
    551.     for(unsigned int k=0;k<nw;k++)
    552.       {
    553.         in=reg.match(searchString,in+len,&len);
    554.         QString regToAdd = searchString;
    555.         regToAdd.replace(in,len,"[a-zA-Z0-9_%"+regaddchar+"]*");
    556.         regToAdd.append("$");
    557.         regToAdd.prepend("^");
    558. //      fprintf(stderr,"%s",(const char *)regToAdd.local8Bit());
    559.         addSearchString(regToAdd,RegExp);
    560.       }
    561.  
    562. if(inTranslation)
    563.   return startSearchNow(MD_IN_TRANSLATION);
    564.  else
    565.   return startSearchNow();
    566.   return false;
    567. }
    568. //bool KDBSearchEngine::startListSearch(QList<QString> searchStrList)
    569. //{
    570.   //  searchStringList=searchStrList;
    571. //  return startSearchNow();
    572. //}
    573. void KDBSearchEngine::setLanguageCode(QString ll)
    574. {
    575. if(ll==lang) return;
    576. lang=ll;
    577.  if(dbOpened)  //if opened open it again with new code, what about close before open ?
    578.    dbOpened=loadDatabase(dbname);
    579. }
    580. void KDBSearchEngine::setLanguage(QString languageCode, QString languageName)
    581. {
    582. setLanguageCode(languageCode);
    583. }
    584. void KDBSearchEngine::stopSearch()
    585. {
    586.   stopNow=true;
    587. }
    588. void KDBSearchEngine::clearList()
    589. {
    590.  searchStringList.clear();
    591. }
    592. bool  KDBSearchEngine::isReady() const
    593.         {return IAmReady;}
    594. void  KDBSearchEngine::saveSettings(KConfigBase *config)
    595. {
    596. // updateSettings();  //maybe with autoupdate
    597.  KConfigGroupSaver cgs(config,"KDBSearchEngine");
    598.  config->writeEntry("Filename",dbname);
    599.  config->writeEntry("Language",lang);
    600.  config->writeEntry("CaseSensitive",sens);
    601.  config->writeEntry("Normalize",norm);
    602.  config->writeEntry("RemoveContext",comm);
    603.  config->writeEntry("Rules",defRule);
    604.  config->writeEntry("Limit1",defLimit1);
    605.  config->writeEntry("Limit2",defLimit2);
    606.  config->writeEntry("Substitution1",defSub1);
    607.  config->writeEntry("Substitution2",defSub2);
    608.  config->writeEntry("RegExp",regaddchar);
    609.  config->writeEntry("RemoveCharacter", remchar);
    610. config->writeEntry("Threshold1",thre);
    611. config->writeEntry("Threshold2",threorig);
    612. config->writeEntry("ListMax",listmax);
    613. config->writeEntry("Mode",mode);
    614. config->writeEntry("CommonThrs",commonthre);
    615. config->writeEntry("ReturnNothing",retnot);
    616. config->writeEntry("AutoAuthor",autoauthor);
    617. config->writeEntry("AutoUp",autoup);
    618. }
    619. void  KDBSearchEngine::readSettings(KConfigBase *config)
    620. {
    621.  QString newName;
    622.  KConfigGroupSaver cgs(config,"KDBSearchEngine");
    623.  QString defaultLang;
    624.  QString oldLang=lang;
    625.  defaultLang = Defaults::Identity::languageCode();
    626.  lang=config->readEntry("Language",defaultLang);
    627.  QString defaultDir;
    628.  KStandardDirs * dirs = KGlobal::dirs();
    629.  if(dirs)
    630.  {
    631.      defaultDir = dirs->saveLocation("data");
    632.      if(defaultDir.right(1)!="/")
    633.          defaultDir+="/";
    634.      defaultDir += "kbabeldict/dbsearchengine";
    635.  }
    636.  newName=config->readEntry("Filename",defaultDir);
    637.  if(newName!=dbname || oldLang!=lang)
    638.    {
    639.     dbname=newName;
    640.     if(dbOpened)  //Reload only if it is opened
    641.     dbOpened=loadDatabase(dbname);
    642.    }
    643.  sens=config->readBoolEntry("CaseSensitive",false);
    644.  norm=config->readBoolEntry("Normalize",true);
    645.  comm=config->readBoolEntry("RemoveContext",true);
    646.  defRule=config->readNumEntry("Rules",1);
    647.  defLimit1=config->readNumEntry("Limit1",20);
    648.  defLimit2=config->readNumEntry("Limit2",8);
    649.   thre=config->readNumEntry("Threshold1",50);
    650.   threorig=config->readNumEntry("Threshold2",50);
    651.   listmax=config->readNumEntry("ListMax",500);
    652.   mode=config->readNumEntry("Mode",MD_GOOD_KEYS);
    653.  defSub1=config->readBoolEntry("Substitution1",true);
    654.  defSub2=config->readBoolEntry("Substitution2",false);
    655.  regaddchar=config->readEntry("RegExp");
    656.  remchar=config->readEntry("RemoveCharacter","&.:");
    657.  commonthre=config->readNumEntry("CommonThrs",300);
    658.  retnot=config->readBoolEntry("ReturnNothing",false);
    659.  autoauthor=config->readEntry("AutoAuthor");
    660.  autoup=config->readBoolEntry("AutoUp",true);
    661.  setSettings();
    662. }
    663. PrefWidget * KDBSearchEngine::preferencesWidget(QWidget *parent)
    664. {
    665.  pw =  new PreferencesWidget(parent);
    666.  kdDebug(0) << "new pref" << endl;
    667.  setSettings();
    668.  connect(pw,SIGNAL(restoreNow()),this,SLOT(setSettings()));
    669.  connect(pw,SIGNAL(applyNow()),this,SLOT(updateSettings()));
    670.  connect(pw,SIGNAL(destroyed()),this,SLOT(prefDestr()));
    671.  connect(pw->dbpw->scanPB_2,SIGNAL(clicked()),this,SLOT(scan()));
    672.  connect(pw->dbpw->scanrecPB,SIGNAL(clicked()),this,SLOT(scanRecur()));
    673.  connect(pw->dbpw->scanFilePB,SIGNAL(clicked()),this,SLOT(scanFile()));
    674.  connect(pw->dbpw->repeatPB,SIGNAL(clicked()),this,SLOT(repeat()));
    675. return pw;
    676. }
    677. void KDBSearchEngine::scanRecur()
    678. {
    679. if (scanInProgress) return;
    680. updateSettings();
    681. if(!openDb())
    682.         return;
    683. scanInProgress=true;
    684. PoScanner *sca=new PoScanner(dm,this,"Po Scanner");
    685. QString cvsdir;
    686. cvsdir=KFileDialog::getExistingDirectory("",0,i18n("Select a directory you want to scan recursively"));
    687. if(cvsdir.isEmpty()) {scanInProgress=false; return;}
    688. if(pw) {
    689. connect(sca,SIGNAL(patternProgress(int)),pw->dbpw->totalPB,SLOT(setProgress(int)) );
    690. connect(sca,SIGNAL(fileLoading(int)),pw->dbpw->loadingPB,SLOT(setProgress(int)));
    691. connect(sca,SIGNAL(fileProgress(int)),pw->dbpw->processPB,SLOT(setProgress(int)));
    692. }
    693. connect(sca,SIGNAL(patternProgress(int)),SIGNAL(progress(int)) ); //Kbabel progress bar
    694. connect(sca,SIGNAL(added(int)),pw,SLOT(setEntries(int)));
    695. connect(sca,SIGNAL(filename(QString)),pw,SLOT(setName(QString)));
    696. progressStarts(i18n("Scanning directory %1").arg(cvsdir));
    697. connect(sca,SIGNAL(patternFinished()),SIGNAL(progressEnds()) );
    698. sca->scanPattern(cvsdir,"*.po",true);
    699. disconnect(this,SIGNAL(progress(int)) );
    700. //disconnect(SIGNAL(patternStarted()),this,SIGNAL(started()) );
    701. disconnect(this,SIGNAL(progressEnds()) );
    702. if(pw) {
    703. disconnect(pw->dbpw->totalPB,SLOT(setProgress(int)) );
    704. disconnect(pw->dbpw->loadingPB,SLOT(setProgress(int)));
    705. disconnect(pw->dbpw->processPB,SLOT(setProgress(int)));
    706. }
    707. totalRecord=dm->count();
    708. scanInProgress=false;
    709. dm->sync();
    710. delete sca;
    711. }
    712. void KDBSearchEngine::scan()
    713. {
    714. if (scanInProgress) return;
    715. updateSettings();
    716. if(!openDb())
    717.         return;
    718. scanInProgress=true;
    719. PoScanner *sca=new PoScanner(dm,this,"Po Scanner");
    720. QString cvsdir;
    721. cvsdir=KFileDialog::getExistingDirectory("",0,i18n("Select a directory you want to scan"));
    722. if(cvsdir.isEmpty()) {scanInProgress=false; return;}
    723. if(pw){
    724. connect(sca,SIGNAL(patternProgress(int)),pw->dbpw->totalPB,SLOT(setProgress(int)) );
    725. connect(sca,SIGNAL(fileLoading(int)),pw->dbpw->loadingPB,SLOT(setProgress(int)));
    726. connect(sca,SIGNAL(fileProgress(int)),pw->dbpw->processPB,SLOT(setProgress(int)));
    727. }
    728. connect(sca,SIGNAL(patternProgress(int)),SIGNAL(progress(int)) );
    729. progressStarts(i18n("Scanning directory %1").arg(cvsdir));
    730. connect(sca,SIGNAL(patternFinished()),SIGNAL(progressEnds()) );
    731. connect(sca,SIGNAL(added(int)),pw,SLOT(setEntries(int)));
    732. connect(sca,SIGNAL(filename(QString)),pw,SLOT(setName(QString)));
    733. sca->scanPattern(cvsdir,"*.po",false);
    734. disconnect(this,SIGNAL(progress(int)) );
    735. //disconnect(SIGNAL(patternStarted()),this,SIGNAL(started()) );
    736. disconnect(this,SIGNAL(progressEnds()) );
    737. if(pw){
    738. disconnect(pw->dbpw->totalPB,SLOT(setProgress(int)) );
    739. disconnect(pw->dbpw->loadingPB,SLOT(setProgress(int)));
    740. disconnect(pw->dbpw->processPB,SLOT(setProgress(int)));
    741. }
    742. totalRecord=dm->count();
    743. scanInProgress=false;
    744. dm->sync();
    745. delete sca;
    746. }
    747. void KDBSearchEngine::scanFile()
    748. {
    749. if (scanInProgress) return;
    750. updateSettings();
    751. if(!openDb())
    752.         return;
    753. scanInProgress=true;
    754. PoScanner *sca=new PoScanner(dm,this,"Po Scanner");
    755. QString cvsdir;
    756. pw->dbpw->totalPB->setProgress(0);
    757. cvsdir=KFileDialog::getOpenFileName("","*.po",0
    758.         ,i18n("Select a po file to scan"));
    759. if(cvsdir.isEmpty()) {scanInProgress=false; return;}
    760. if(pw){
    761. connect(sca,SIGNAL(fileLoading(int)),pw->dbpw->loadingPB,SLOT(setProgress(int)));
    762. connect(sca,SIGNAL(fileProgress(int)),pw->dbpw->processPB,SLOT(setProgress(int)));
    763. }
    764. connect(sca,SIGNAL(fileProgress(int)),SIGNAL(progress(int)) );
    765. progressStarts(i18n("Scanning file %1").arg(directory(cvsdir,0)));
    766. connect(sca,SIGNAL(fileFinished()),SIGNAL(progressEnds()) );
    767. connect(sca,SIGNAL(added(int)),pw,SLOT(setEntries(int)));
    768. connect(sca,SIGNAL(filename(QString)),pw,SLOT(setName(QString)));
    769. sca->scanFile(cvsdir);
    770. sca->disconnect(SIGNAL(fileProgress(int)),this,SIGNAL(progress(int)) );
    771. //disconnect(SIGNAL(patternStarted()),this,SIGNAL(started()) );
    772. sca->disconnect(SIGNAL(fileFinished()),this,SIGNAL(progressEnds()) );
    773. if(pw)
    774. {
    775. disconnect(pw->dbpw->loadingPB,SLOT(setProgress(int)));
    776. disconnect(pw->dbpw->processPB,SLOT(setProgress(int)));
    777. }
    778. totalRecord=dm->count();
    779. scanInProgress=false;
    780. dm->sync();
    781. delete sca;
    782. }
    783. const KAboutData *KDBSearchEngine::about() const
    784. {
    785.         return DbSeFactory::instance()->aboutData();
    786. }
    787. QString  KDBSearchEngine::name() const
    788. {
    789. return i18n("Translation database");
    790. }
    791. QString  KDBSearchEngine::id() const
    792. {
    793. return QString("KDBSearchEngine");
    794. }
    795. QString  KDBSearchEngine::lastError()
    796. {
    797. return lasterror;
    798. }
    799. void  KDBSearchEngine::prefDestr()
    800. {
    801. pw=0;
    802. }
    803. void  KDBSearchEngine::setSettings()
    804. {
    805. if(pw==0) return;
    806.  pw->dbpw->dirInput->setURL(dbname);
    807.  pw->dbpw->caseSensitiveCB->setChecked(sens);
    808.  pw->dbpw->normalizeCB->setChecked(norm);
    809.  pw->dbpw->removeContextCB->setChecked(comm);
    810.  pw->dbpw->oneWordSubCB->setChecked(defSub1);
    811.  pw->dbpw->twoWordSubCB->setChecked(defSub2);
    812.  if(defRule==8) pw->dbpw->RegExpRB->setChecked(true);
    813.   else
    814.   {
    815.    pw->dbpw->normalTextRB->setChecked(true);
    816.   pw->dbpw->equalCB->setChecked( defRule & Equal );
    817.    pw->dbpw->containsCB->setChecked( defRule & Contains );
    818.    pw->dbpw->containedCB->setChecked( defRule & Contained );
    819.   }
    820.  pw->dbpw->oneWordSubSB->setValue(defLimit1);
    821.  pw->dbpw->twoWordSubSB->setValue(defLimit2);
    822.  pw->dbpw->maxSB->setValue(listmax);
    823.  pw->dbpw->thresholdSL->setValue(thre);
    824.  pw->dbpw->thresholdOrigSL->setValue(threorig);
    825.   pw->dbpw->allRB->setChecked( mode==MD_ALL_DB);
    826.   pw->dbpw->slistRB->setChecked( mode==MD_GOOD_KEYS);
    827.   pw->dbpw->rlistRB->setChecked( mode==MD_ALL_GOOD_KEYS  );
    828.   pw->dbpw->nothingCB->setChecked(retnot);
    829.   pw->dbpw->freqSB->setValue(commonthre);
    830.  pw->dbpw->regExpLE->setText(regaddchar);
    831.  pw->dbpw->ignoreLE->setText(remchar);
    832.   pw->dbpw->authorLE->setText(autoauthor);
    833.   pw->dbpw->autoAddCB_2->setChecked(autoup);
    834. }
    835. void  KDBSearchEngine::updateSettings()
    836. {
    837. if(pw==0) return;
    838.  QString newName=pw->dbpw->dirInput->url();
    839.  if(newName!=dbname)
    840.    {
    841.     kdDebug(0) << "Database changed" << endl;
    842.     dbname=newName;
    843.     if(dbOpened)
    844.     dbOpened=loadDatabase(dbname);
    845.    }
    846.  sens=pw->dbpw->caseSensitiveCB->isChecked();
    847.  norm=pw->dbpw->normalizeCB->isChecked();
    848.  comm=pw->dbpw->removeContextCB->isChecked();
    849.  int tmpRule=0;
    850.  if(pw->dbpw->RegExpRB->isChecked())
    851.   tmpRule=RegExp;
    852.   else
    853.   {
    854.    if(pw->dbpw->equalCB->isChecked()) tmpRule+=Equal;
    855.    if(pw->dbpw->containsCB->isChecked()) tmpRule+=Contains;
    856.    if(pw->dbpw->containedCB->isChecked()) tmpRule+=Contained;
    857.   }
    858.  defRule=tmpRule;
    859.  defLimit1=pw->dbpw->oneWordSubSB->text().toInt();
    860.  defLimit2=pw->dbpw->twoWordSubSB->text().toInt();
    861.  defSub1=pw->dbpw->oneWordSubCB->isChecked();
    862.  defSub2=pw->dbpw->twoWordSubCB->isChecked();
    863.  listmax=pw->dbpw->maxSB->value();
    864.  thre=pw->dbpw->thresholdSL->value();
    865.  threorig=pw->dbpw->thresholdOrigSL->value();
    866. if(pw->dbpw->allRB->isChecked()) mode=MD_ALL_DB;
    867.  if(pw->dbpw->slistRB->isChecked()) mode=MD_GOOD_KEYS;
    868. if(pw->dbpw->rlistRB->isChecked()) mode=MD_ALL_GOOD_KEYS;
    869.  regaddchar=pw->dbpw->regExpLE->text();
    870.  remchar=pw->dbpw->ignoreLE->text();
    871.  retnot=pw->dbpw->nothingCB->isChecked();
    872.  commonthre=pw->dbpw->freqSB->value();
    873.  autoauthor=pw->dbpw->authorLE->text();
    874.  autoup=pw->dbpw->autoAddCB_2->isChecked();
    875. }
    876. void  KDBSearchEngine::setLastError(QString er)
    877. {
    878. lasterror=er;
    879. }
    880. QString KDBSearchEngine::translate(const QString text)
    881. {
    882. if(!openDb())
    883.       return QString::null;
    884. /*
    885. if(!dbOpened)
    886.     {
    887.     dbOpened=loadDatabase(dbname);  //Try first to open it now
    888.     if(!dbOpened) // Still not opened!!
    889.         {
    890.          //emit anerror
    891.          hasError(i18n("Database not opened"));
    892.          return QString::null;
    893.        }
    894.      }
    895. */
    896. DataBaseItem dbit=dm->getItem(text);
    897. if(dbit.isNull()) return QString::null;
    898. if(dbit.numTra==1) return dbit.translations[0].translation;
    899. uint32 n=dbit.numTra;
    900. uint32 max=0,nmax=0;
    901. for(uint32 i=0;i<n;i++)
    902.  if(dbit.translations[i].numRef>max)
    903.     {
    904.             nmax=i;
    905.             max= dbit.translations[i].numRef;
    906.     }
    907. return dbit.translations[nmax].translation;
    908. }
    909. QValueList<KeyAndScore> KDBSearchEngine::searchWords(QString phrase,int threshold,
    910.                                                  int thresholdorig,uint32 max)
    911. {
    912. QValueList<QString> wordlist;
    913.  
    914.     if(!openDb())
    915.     {
    916.       QValueList<KeyAndScore> a;
    917.       return a;
    918.     }
    919. progressStarts(i18n("Searching words"));
    920. QValueList<QString>::Iterator wlit;
    921. wordlist=dm->wordsIn(phrase);
    922. int nw=wordlist.count();
    923. //QArray<WordItem> wi(nw);
    924. QArray<uint32> numofloc(nw),currentloc(nw);
    925. QArray<int> score(nw);
    926. QArray<uint32 *> loc(nw),locorig(nw);
    927. QValueList<uint32> resloc;
    928. QValueList<int> resfound;
    929. QValueList<KeyAndScore> keylist;
    930. //wi.resize(wordlist.count());
    931. int totalprogress=0;
    932. int totrec=dm->count();
    933. uint32 cthre=totrec*commonthre/10000;
    934. int i=0,common=0;
    935. for(wlit=wordlist.begin();wlit!=wordlist.end();++wlit)
    936.  {
    937.   WordItem wi=dm->getWordLocations(*wlit);
    938.   if(!wi.notFound())
    939.   {
    940.   if(wi.count<cthre)
    941.        score[i]=1;
    942.       else
    943.       { score[i]=0; common++; }
    944.  
    945.            locorig[i]=loc[i]=wi.locations;
    946.            totalprogress+=numofloc[i]=wi.count;
    947.            currentloc[i]=0;
    948. //         score[i]=wi.score;
    949.            //wi[i]=WordItem(wi[i]);
    950.            //wi[i].locations.detach();
    951.           i++;
    952. //     }
    953.  //   else
    954.    //  common++;
    955.   }
    956.  }
    957. bool cs=(common==nw);  //All words are common;
    958. if (totalprogress==0) totalprogress=1;
    959. int step=totalprogress/30+1;
    960. int count=0;
    961. int thrs=(wordlist.count()*threshold)/100;
    962. if(thrs<1) thrs=1;  // whole database ???
    963. int tot=i;
    964. //nt32 jmin=0;
    965. int found;
    966. uint32 min; //Big ?
    967. bool empty=false;
    968. while(!empty)
    969. {
    970.  empty=true;
    971. found=retnot?common:0;
    972. if(thrs<=found) thrs=found+1;  // whole database ???
    973.  min=BIGNUMBER;
    974.  for(int j=0;j<tot;j++)
    975.   if(cs || score[j]) {
    976.      if(numofloc[j]>currentloc[j])   // Check if there's still something to do.
    977.       empty=false;
    978.          if(loc[j][0]<min)                  //Found the minimum head
    979.                min=loc[j][0];
    980.    }
    981. if(min!=BIGNUMBER)
    982.  {
    983.  for(int j=0;j<tot;j++)
    984.     if(cs || score[j]) {
    985.       if(loc[j][0]==min)            //Count the heads, move forward
    986.         {
    987.         found++;
    988.         count++;
    989.         //check stopnow  here
    990.         if(count%step==0)
    991.         {
    992.            emit progress(100*count/totalprogress);
    993.             kapp->processEvents();
    994.           }
    995.  
    996.         currentloc[j]++;
    997.          if(numofloc[j]==currentloc[j]) //End reached
    998.             loc[j][0]=BIGNUMBER;        //so set head to a big number
    999.            else   //Go on..
    1000.            {
    1001.              loc[j]++;
    1002.            }
    1003.         }
    1004.     }   //end of for
    1005. bool inserted=false;
    1006. if(found>=thrs)
    1007.   {
    1008.   //Words count in key.
    1009.   int nword=0;
    1010.   int in=0,len=0;
    1011.   QString keyst=dm->getKey(min);
    1012.   QRegExp  reg("[a-zA-Z0-9_%"/*+remchar*/+regaddchar+"]+");
    1013.   while((in=reg.match(keyst,in+len,&len))!=-1) {nword++;}
    1014.   if(found>=nword*thresholdorig/100)  //
    1015.    {
    1016.         if(resfound.count()<=max || (*resfound.end() < found))
    1017.         if((*resfound.end())>= found)
    1018.         {
    1019.                 inserted=true;
    1020.                 resloc.append(min);
    1021.                  resfound.append(found);
    1022.         }
    1023.         else
    1024.         for(uint32 j=0;j<resloc.count();j++)
    1025.         {
    1026.                 if(resfound[j]<found || (resfound[j]==found && 0) )  //Orig word
    1027.                 {
    1028.                  resloc.insert(resloc.at(j),min);
    1029.                  resfound.insert(resfound.at(j),found);
    1030.                  inserted=true;
    1031.                  break;
    1032.                 }
    1033.          }
    1034.                 if(!inserted)
    1035.                 {
    1036.                         resloc.append(min);
    1037.                         resfound.append(found);
    1038.                 }
    1039.       }
    1040.   }
    1041.  }
    1042. }
    1043. int nres=(resloc.count()<max)?resloc.count():max;
    1044. for(int j=0;j<nres;j++)
    1045.  {
    1046.   QString strkey=dm->getKey(resloc[j]);
    1047.   int stdscore=KDBSearchEngine::score(phrase,strkey);
    1048.   int sc=0;
    1049.   if(stdscore<99)
    1050.     {
    1051.     int in=0,len=0,nword=0;
    1052.     int remove=retnot?common:0;
    1053.      QRegExp  reg("[a-zA-Z0-9_%"/*+remchar*/+regaddchar+"]+");
    1054.      while((in=reg.match(strkey,in+len,&len))!=-1) {nword++;}
    1055. //    kdDebug(0) << nword << "NWORD  " << resfound[j] << "FOUND  "
    1056. //    << resfound[j]-remove << "REAL  " << remove << "to be remove   " << endl;
    1057.     if(nword<1) nword=1;
    1058.     sc=  70-resfound[j]*70/nw+abs(nword-(resfound[j]-remove))*30/nword+2;
    1059.     sc=100-sc;
    1060. //    kdDebug(0) <<" Score : " << sc << endl;
    1061.     }else
    1062.     sc=stdscore;
    1063.   KeyAndScore key(strkey,sc);
    1064. //  kdDebug(0) << (QString) key << " [" << key.score << "]" << endl;
    1065.   keylist.append(key);
    1066.  }
    1067. //kdDebug(0) << "Here!" << endl;
    1068. for(int j=0;j<tot;j++)
    1069.  {
    1070.          free(locorig[j]);
    1071.  }
    1072. progressStarts(i18n("Process output"));
    1073. return keylist;
    1074. }
    1075. void KDBSearchEngine::stringChanged( QString orig, QString translated
    1076.                                       , QString description)
    1077. {
    1078. //author is KBABEL ????
    1079. //#warning uncomment and FIXME
    1080.         //done
    1081. if(autoup)
    1082. {
    1083. /* if(!dbOpened)
    1084.  {
    1085.   dm= new DataBaseManager(dbname,lang,this,"Database manager");
    1086.   if(dm->isOk())
    1087.    dbOpened=true;
    1088.   else
    1089.   {
    1090.    dbOpened=false;
    1091.    delete dm;
    1092.    dm=0;
    1093.   }
    1094.  }*/
    1095.  
    1096. if(openDb(true))  //true= no ask
    1097.  {
    1098.  
    1099.         dm->putNewTranslation(orig,translated,dm->catalogRef(directory(edited,0),autoauthor,edited));
    1100.  //kdDebug(0) << "Changed " << orig << " " << translated << endl;
    1101.       dm->sync();
    1102.  }
    1103. }
    1104. }
    1105. void KDBSearchEngine::setEditedFile(QString file)
    1106. {
    1107.  
    1108.         edited=file;//kdDebug(0) << edited << endl;
    1109. }
    1110.  
    1111. KeyAndScore::KeyAndScore(const QString &a,int sc)
    1112. : QString(a)
    1113. {
    1114. score=sc;
    1115. }
    1116. KeyAndScore::KeyAndScore()
    1117. : QString()
    1118. {
    1119. score=0;
    1120. }
    1121.  
    1122. #include "KDBSearchEngine.moc"

    bạn nên nói rõ thêm tác dụng của đoạn code mọi người mới dễ xem , và bạn nên ghi thêm nguồn để mọi người có gì tham khảo thêm , mình vẫn đang xem nhưng nói trước mình cũng đang học nha , có gì cùng trao đổi

    bạn nên để [CODE=c++] để dễ nhìn
    Đã được chỉnh sửa lần cuối bởi Devost24 : 07-04-2009 lúc 10:26 PM.

  8. #8
    Ngày gia nhập
    04 2008
    Nơi ở
    Đồng Nai
    Bài viết
    6

    chức năng của nó là dò tìm tài liệu xml nhưng mình ko chắc nữa do mình ko có công cụ để thử nó.

  9. #9
    Ngày gia nhập
    04 2008
    Nơi ở
    Đồng Nai
    Bài viết
    6

    bạn nào cho biết các hàm thư viện đó sao turbo c++ ko hiểu vậy

  10. #10
    Ngày gia nhập
    03 2008
    Bài viết
    12

    Đơn giản là Turbo C không có. Bạn cài VS 6.0 hoặc mới hơn đi mới có. Còn cái code dài ngoằn kia. Coi chóng mặt quá. Up lên Project đi bạn. Sặc sặc, mắt tui 10/10, kinh nghiệm lập trình 5 năm, các môn kĩ thuật lập trình 10.0 mà còn không đỡ nỗi.

    Nếu được thì chuyển đổi nó qua kiến trúc 3 tầng đi. Em cám ơn nhiều.

Các đề tài tương tự

  1. [Kiếm Thế] Kiếm Thế Ngạo Thiên Kiếm Chạy Thử Nghiệm vào 10h ngày 15/09
    Gửi bởi c0jskull trong diễn đàn Giới thiệu website, sản phẩm của bạn
    Trả lời: 5
    Bài viết cuối: 29-09-2013, 10:45 AM
  2. Tài liệu tối ưu hóa mã nguồn, tinh chỉnh mã nguồn (code Tuning)?
    Gửi bởi sunshine trong diễn đàn Nhập môn lập trình C/C++
    Trả lời: 1
    Bài viết cuối: 19-04-2013, 09:13 AM
  3. Tài liệu và mã nguồn spyware có thể kiếm ở đâu ?
    Gửi bởi public trong diễn đàn Lập trình Virus & Anti-Virus
    Trả lời: 1
    Bài viết cuối: 13-01-2013, 09:10 AM
  4. Cây nhị phân tìm kiếm trong C [Mã nguồn trên Turbo C/ Borland C++]
    Gửi bởi PoPoPoPo trong diễn đàn Thủ thuật, Tutorials CTDL & Giải thuật
    Trả lời: 4
    Bài viết cuối: 29-03-2012, 10:54 PM
  5. Mã nguồn C | Tổng hợp một số mã nguồn hay đã được up lên.
    Gửi bởi iamvtn trong diễn đàn Thủ thuật, Tutorials và Mã nguồn C/C++/C++0x
    Trả lời: 0
    Bài viết cuối: 15-06-2007, 12:36 AM

Quyền hạn của bạn

  • Bạn không thể gửi đề tài mới
  • Bạn không thể gửi bài trả lời
  • Bạn không thể gửi các đính kèm
  • Bạn không thể chỉnh sửa bài viết của bạn