void MatchSiftFeatures( MatchArray& aryMatch, const CFeatureArray& set1, const CFeatureArray& set2 ) { aryMatch.resize( set1.size() ); int num = 0; // for each feature in set1 for( int i=0; i<(int)set1.size(); ++i ) { if( i%100 == 0 ) printf( "%d / %d\n", i, set1.size() ); // const CSiftFeature* ft1 = dynamic_cast< const CSiftFeature* >( set1[i] ); int j = FindMatch( ft1, set2 ); int k = FindMatch( set2[j], set1 ); bool bQualMatch = false; if( i==k ) bQualMatch = true; // TODO: Find the best match for ft1 in set2. // The quality of a match can be evaluated. We only // collect matches of good qualities. if( bQualMatch ) aryMatch[ num++ ] = make_pair( i, j ); } aryMatch.resize( num ); }
void InitVQ (VECTOR_OF_F_VECTORS *vfv,int numVectors, VECTOR_OF_F_VECTORS *clusterMeans, VECTOR_OF_F_VECTORS *clusterVars, int numClusters, int seed) { int index; int i, j; int random; float rmax; int *indexArray; int flag; srand(seed); fflush(stdout); indexArray = (int *) calloc (numClusters, sizeof(int)); for (i = 0; i < numClusters; i++) { flag = 1; while (flag) { random = rand(); rmax = RAND_MAX; index = (int) ((float) (random)/rmax*numVectors); index = index; flag = (int) FindIndex(indexArray, i-1, index); if (!flag) { flag = (int) FindMatch(vfv, numVectors, indexArray, i-1, index); // index = (index+5)%numVectors; //flag = (int) FindMatch(vfv, numVectors, indexArray, i-1, index); } } for (j = 0; j <vfv[0]->numElements; j++) { clusterMeans[i]->array[j] = vfv[index]->array[j]; clusterVars[i]->array[j] = 1.0; } indexArray[i] = index; } free(indexArray); }
bool Scraper::FindAllBMPs(const Mat mat, HBITMAP hBmp, const double threshold, const int maxMatch, vector<MATCHPOINTS> &matches) { // Convert HBITMAP to Mat unique_ptr<Gdiplus::Bitmap> pBitmap; pBitmap.reset(Gdiplus::Bitmap::FromHBITMAP(hBmp, NULL)); Mat img = CGdiPlus::CopyBmpToMat(pBitmap.get()); pBitmap.reset(); cvtColor( img, img, CV_BGRA2BGR ); // Get matches for this image and Mat Mat result( FindMatch(img, mat) ); // Parse through matches in result set int count = 0; while (count < maxMatch) { double minVal, maxVal; Point minLoc, maxLoc; minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc); // Fill haystack with pure green so we don't match this same location rectangle(img, maxLoc, cv::Point(maxLoc.x + mat.cols, maxLoc.y + mat.rows), CV_RGB(0,255,0), 2); // Fill results array with lo vals, so we don't match this same location floodFill(result, maxLoc, 0, 0, Scalar(0.1), Scalar(1.0)); if (maxVal >= threshold && maxVal > 0) { // Check if this point is within 5 pixels of an existing match to avoid dupes bool alreadyFound = false; for (int k=0; k<count; k++) { if (DistanceBetweenTwoPoints((double) maxLoc.x, (double) maxLoc.y, (double) matches.at(k).x, (double) matches.at(k).y) < 5.0) { alreadyFound = true; break; } } // Add matched location to the vector if (alreadyFound == false) { MATCHPOINTS match; match.val = maxVal; match.x = maxLoc.x; match.y = maxLoc.y; matches.push_back(match); count++; } } else { break; } } return true; }
/* * getBracketLoc - find a matching '(' for a ')' */ static vi_rc getBracketLoc( i_mark *pos ) { vi_rc rc; char tmp[3]; int len; // linenum lne; tmp[0] = '\\'; tmp[1] = ')'; tmp[2] = 0; // lne = CurrentPos.line; RegExpAttrSave( -1, NULL ); rc = GetFind( tmp, pos, &len, FINDFL_BACKWARDS | FINDFL_NOERROR | FINDFL_NOCHANGE ); RegExpAttrRestore(); if( pos->line != CurrentPos.line ) { return( ERR_FIND_NOT_FOUND ); } if( rc != ERR_NO_ERR ) { return( rc ); } /* * find the matching '(' */ CurrentPos = *pos; CGimmeLinePtr( CurrentPos.line, &CurrentFcb, &CurrentLine ); rc = FindMatch( pos ); return( rc ); } /* getBracketLoc */
void GoodPackerFrontEnd::TryBetterAhead() { Match tm; FindMatch(tm,AheadStart,Ahead); if(tm.Len>=Ahead && BackEnd->MatchLen(tm.Offs,Ahead)<BackEnd->MatchLen(BM.Offs,Ahead)) BM = tm; }
int main () { long Result = 0, CurrentLine = 0, CurrentOffset = 0; while (Result = FindMatch("this|is|a|test\nof|the|emergency|broadcast|system\nboom", "the", "|", 3, &CurrentLine, &CurrentOffset)) printf("%d", Result); }
bool Scraper::LocateSlots(const actionType aType, const slotType sType, HBITMAP hBmp, const double threshold, vector<MATCHPOINTS> &matches) { // Convert HBITMAP to Mat unique_ptr<Gdiplus::Bitmap> pBitmap; pBitmap.reset(Gdiplus::Bitmap::FromHBITMAP(hBmp, NULL)); Mat img = CGdiPlus::CopyBmpToMat(pBitmap.get()); pBitmap.reset(); cvtColor( img, img, CV_BGRA2BGR ); // Find right image group imageType iType = (aType==actionRaid && sType==slotTroop) ? raidTroopSlot : (aType==actionRaid && sType==slotSpell) ? raidSpellSlot : (aType==actionDonate && sType==slotTroop) ? donateTroopSlot : (aType==actionDonate && sType==slotSpell) ? donateSpellSlot : (aType==actionBarracks) ? barracksTroopSlot : (aType==actionCamp) ? armyCampTroop : (aType==actionReloadButton) ? reloadButton : (imageType) 0; int iTypeIndex = -1; for (int i = 0; i < (int) imageGroups.size(); i++) if (imageGroups[i].iType == iType) iTypeIndex = i; if (iTypeIndex == -1) return false; // Scan through each Mat in this image group for (int i=0; i<(int) imageGroups[iTypeIndex].mats.size(); i++) { Mat result( FindMatch(img, imageGroups[iTypeIndex].mats[i]) ); double minVal, maxVal; Point minLoc, maxLoc; minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc); MATCHPOINTS match; match.val = maxVal; if (maxVal >= threshold) { match.x = maxLoc.x; match.y = maxLoc.y; } else { match.x = -1; match.y = -1; } matches.push_back(match); } return true; }
void CorrespondenceTable::populate (edgeVector &lines, edgePlaneVector &planes) { // for each plane in <planes>, find the best scoring 3D line in <lines> int n = lines.size(); int m = planes.size(); edgePlaneVectorIter iter_edge = planes.begin(); for (;iter_edge!=planes.end();iter_edge++) { Correspondence best_correspondence; FindMatch (*iter_edge,lines,came,0,size(),best_correspondence); Insert(best_correspondence); } }
//----------------------------------------------------------------------------- // Receive a teleporting player //----------------------------------------------------------------------------- bool CObjectTeleporter::IsMatchingTeleporterReady( void ) { if ( m_hMatchingTeleporter.Get() == NULL ) { m_hMatchingTeleporter = FindMatch(); } if ( m_hMatchingTeleporter && m_hMatchingTeleporter->GetState() != TELEPORTER_STATE_BUILDING && !m_hMatchingTeleporter->IsDisabled() ) return true; return false; }
int main(void) { char *P="Shubhans"; char *T="Hello Shubhanshu Here.. are you Shubhanshu !!!"; int i; FindMatch(T,strlen(T),P,strlen(P)); for(i=0;i<appear;i++) printf("Occurence at %d \n\n",occur[i]); return 0; }
//----------------------------------------------------------------------------- // Receive a teleporting player //----------------------------------------------------------------------------- bool CObjectTeleporter::IsMatchingTeleporterReady( void ) { if ( m_hMatchingTeleporter.Get() == NULL ) { m_hMatchingTeleporter = FindMatch(); } CObjectTeleporter *pMatch = GetMatchingTeleporter(); if ( pMatch && pMatch->GetState() != TELEPORTER_STATE_BUILDING && !pMatch->IsDisabled() && !pMatch->IsUpgrading() && !pMatch->IsRedeploying() ) return true; return false; }
/* * findMatchingBrace find '{' for a '}' */ static vi_rc findMatchingBrace( i_mark *pos1 ) { vi_rc rc; i_mark pos2; rc = FindMatch( pos1 ); if( rc != ERR_NO_ERR ) { return( rc ); } SaveCurrentFilePos(); CurrentPos = *pos1; CGimmeLinePtr( CurrentPos.line, &CurrentFcb, &CurrentLine ); rc = getBracketLoc( &pos2 ); RestoreCurrentFilePos(); if( rc == ERR_NO_ERR ) { *pos1 = pos2; } return( ERR_NO_ERR ); } /* findMatchingBrace */
/* * IMCloseBracket - handle a ')' being entered in insert mode */ vi_rc IMCloseBracket( void ) { vi_rc rc; i_mark pos; startNewLineUndo(); insertChar( TRUE, FALSE ); if( EditFlags.ShowMatch ) { ReplaceCurrentLine(); rc = FindMatch( &pos ); if( rc == ERR_NO_ERR ) { tempMatch( &pos ); } GetCurrentLine(); } GoToColumn( CurrentPos.column + 1, WorkLine->len + 1 ); return( ERR_NO_ERR ); } /* IMCloseBracket */
/*Organize the whole process of object tracking*/ void TrackAssociation::ObjectTrackingAtKeyFrame(int frameNO, cv::Mat &image, bool external_detection) { std::vector<cv::Rect> evidence; std::vector<float> evidence_weight; //Predict using feature tracks motion descriptors UpdateModelsByPrediction(); if(external_detection) { PeopleDetection(frameNO, image, evidence, evidence_weight); //If external detection is available, perform Data Association by greedy method std::vector<AffinityVal> affinity_mat; CalculateAffinityScore(evidence,affinity_mat); std::vector<int> assign_match; std::vector<bool> evidence_used, model_used; FindMatch(affinity_mat,evidence,assign_match,evidence_used,model_used); //Tracking by particle filtering. If appearance model not available, normal method is applied std::list<ObjSubTrack*> new_track_list; // Some sub object track candidates may be declared as new obj tracks std::list<float> new_weight_list; //Update obj tracks with external detection (particle filtering) UpdateModel(objSeg,evidence,evidence_weight,assign_match,evidence_used,new_track_list,new_weight_list); //For evidence that neither matched or added, create new models for them CreateNewObjTracks(objSeg,evidence,evidence_weight,evidence_used,new_track_list,new_weight_list); //Clean sub track models CleanSubTrackVector(); //Init appearance models for all main sub tracks InitAppearanceModelForMainTracks(); }else { TrackWithoutExternalDetection(objSeg); } SuperviseTrainingForSubTracks(); DrawDetectionModels(image,frameNO); }
void TextFinder::scopeStringMatches(int identifier, const WebString& searchText, const WebFindOptions& options, bool reset) { if (reset) { // This is a brand new search, so we need to reset everything. // Scoping is just about to begin. m_scopingInProgress = true; // Need to keep the current identifier locally in order to finish the // request in case the frame is detached during the process. m_findRequestIdentifier = identifier; // Clear highlighting for this frame. LocalFrame* frame = m_ownerFrame.frame(); if (frame && frame->page() && frame->editor().markedTextMatchesAreHighlighted()) frame->page()->unmarkAllTextMatches(); // Clear the tickmarks and results cache. clearFindMatchesCache(); // Clear the counters from last operation. m_lastMatchCount = 0; m_nextInvalidateAfter = 0; m_resumeScopingFromRange = nullptr; // The view might be null on detached frames. if (frame && frame->page()) m_ownerFrame.viewImpl()->mainFrameImpl()->ensureTextFinder().m_framesScopingCount++; // Now, defer scoping until later to allow find operation to finish quickly. scopeStringMatchesSoon(identifier, searchText, options, false); // false means just reset, so don't do it again. return; } if (!shouldScopeMatches(searchText)) { // Note that we want to defer the final update when resetting even if shouldScopeMatches returns false. // This is done in order to prevent sending a final message based only on the results of the first frame // since m_framesScopingCount would be 0 as other frames have yet to reset. finishCurrentScopingEffort(identifier); return; } WebLocalFrameImpl* mainFrameImpl = m_ownerFrame.viewImpl()->mainFrameImpl(); Position searchStart = firstPositionInNode(m_ownerFrame.frame()->document()); Position searchEnd = lastPositionInNode(m_ownerFrame.frame()->document()); ASSERT(searchStart.document() == searchEnd.document()); if (m_resumeScopingFromRange) { // This is a continuation of a scoping operation that timed out and didn't // complete last time around, so we should start from where we left off. ASSERT(m_resumeScopingFromRange->collapsed()); searchStart = m_resumeScopingFromRange->startPosition().next(); if (searchStart.document() != searchEnd.document()) return; } // This timeout controls how long we scope before releasing control. This // value does not prevent us from running for longer than this, but it is // periodically checked to see if we have exceeded our allocated time. const double maxScopingDuration = 0.1; // seconds int matchCount = 0; bool timedOut = false; double startTime = currentTime(); do { // Find next occurrence of the search string. // FIXME: (http://crbug.com/6818) This WebKit operation may run for longer // than the timeout value, and is not interruptible as it is currently // written. We may need to rewrite it with interruptibility in mind, or // find an alternative. Position resultStart; Position resultEnd; findPlainText(searchStart, searchEnd, searchText, options.matchCase ? 0 : CaseInsensitive, resultStart, resultEnd); if (resultStart == resultEnd) { // Not found. break; } RefPtrWillBeRawPtr<Range> resultRange = Range::create(*resultStart.document(), resultStart, resultEnd); if (resultRange->collapsed()) { // resultRange will be collapsed if the matched text spans over multiple TreeScopes. // FIXME: Show such matches to users. searchStart = resultStart.next(); continue; } ++matchCount; // Catch a special case where Find found something but doesn't know what // the bounding box for it is. In this case we set the first match we find // as the active rect. IntRect resultBounds = resultRange->boundingBox(); IntRect activeSelectionRect; if (m_locatingActiveRect) { activeSelectionRect = m_activeMatch.get() ? m_activeMatch->boundingBox() : resultBounds; } // If the Find function found a match it will have stored where the // match was found in m_activeSelectionRect on the current frame. If we // find this rect during scoping it means we have found the active // tickmark. bool foundActiveMatch = false; if (m_locatingActiveRect && (activeSelectionRect == resultBounds)) { // We have found the active tickmark frame. mainFrameImpl->ensureTextFinder().m_currentActiveMatchFrame = &m_ownerFrame; foundActiveMatch = true; // We also know which tickmark is active now. m_activeMatchIndexInCurrentFrame = matchCount - 1; // To stop looking for the active tickmark, we set this flag. m_locatingActiveRect = false; // Notify browser of new location for the selected rectangle. reportFindInPageSelection( m_ownerFrame.frameView()->contentsToWindow(resultBounds), m_activeMatchIndexInCurrentFrame + 1, identifier); } addMarker(resultRange.get(), foundActiveMatch); m_findMatchesCache.append(FindMatch(resultRange.get(), m_lastMatchCount + matchCount)); // Set the new start for the search range to be the end of the previous // result range. There is no need to use a VisiblePosition here, // since findPlainText will use a TextIterator to go over the visible // text nodes. searchStart = resultStart.next(); m_resumeScopingFromRange = Range::create(*resultStart.document(), resultStart, resultStart); timedOut = (currentTime() - startTime) >= maxScopingDuration; } while (!timedOut); // Remember what we search for last time, so we can skip searching if more // letters are added to the search string (and last outcome was 0). m_lastSearchString = searchText; if (matchCount > 0) { m_ownerFrame.frame()->editor().setMarkedTextMatchesAreHighlighted(true); m_lastMatchCount += matchCount; // Let the mainframe know how much we found during this pass. mainFrameImpl->increaseMatchCount(matchCount, identifier); } if (timedOut) { // If we found anything during this pass, we should redraw. However, we // don't want to spam too much if the page is extremely long, so if we // reach a certain point we start throttling the redraw requests. if (matchCount > 0) invalidateIfNecessary(); // Scoping effort ran out of time, lets ask for another time-slice. scopeStringMatchesSoon( identifier, searchText, options, false); // don't reset. return; // Done for now, resume work later. } finishCurrentScopingEffort(identifier); }
bool Scraper::FindAllBMPs(const searchType type, HBITMAP hBmp, const double threshold, const int maxMatch, vector<MATCHPOINTS> &matches) { // Convert HBITMAP to Mat unique_ptr<Gdiplus::Bitmap> pBitmap; pBitmap.reset(Gdiplus::Bitmap::FromHBITMAP(hBmp, NULL)); Mat img = CGdiPlus::CopyBmpToMat(pBitmap.get()); pBitmap.reset(); cvtColor( img, img, CV_BGRA2BGR ); // Find right image group imageType iType = type==searchGoldStorage ? goldStorage : type==searchElixStorage ? elixStorage : type==searchDarkStorage ? darkStorage : type==searchLootCollector ? collector : type==searchLootBubble ? lootBubble : type==searchDonateButton ? donateButton : (imageType) 0; int iTypeIndex = -1; for (int i = 0; i < (int) imageGroups.size(); i++) if (imageGroups[i].iType == iType) iTypeIndex = i; if (iTypeIndex == -1) return false; // Scan through each Mat in this image group int count = 0; for (int i = 0; i < (int) imageGroups[iTypeIndex].mats.size(); i++) { // Get matches for this image Mat result( FindMatch(img, imageGroups[iTypeIndex].mats[i]) ); // Parse through matches in result set while (count < maxMatch) { double minVal, maxVal; Point minLoc, maxLoc; minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc); // Fill haystack with pure green so we don't match this same location rectangle(img, maxLoc, cv::Point(maxLoc.x + imageGroups[iTypeIndex].mats[i].cols, maxLoc.y + imageGroups[iTypeIndex].mats[i].rows), CV_RGB(0,255,0), 2); // Fill results array with lo vals, so we don't match this same location floodFill(result, maxLoc, 0, 0, Scalar(0.1), Scalar(1.0)); if (maxVal >= threshold && maxVal > 0) { // Check if this point is within 10 pixels of an existing match to avoid dupes bool alreadyFound = false; for (int k=0; k<count; k++) { if (DistanceBetweenTwoPoints((double) maxLoc.x, (double) maxLoc.y, (double) matches.at(k).x, (double) matches.at(k).y) < 10.0) { alreadyFound = true; break; } } // Add matched location to the vector if (alreadyFound == false) { MATCHPOINTS match; match.val = maxVal; match.x = maxLoc.x; match.y = maxLoc.y; matches.push_back(match); count++; } } else { break; } } if (count >= maxMatch) break; } return true; }
void ColorQuantize(uint8 const *Image, int Width, int Height, int flags, int ncolors, uint8 *out_pixels, uint8 *out_palette, int firstcolor) { int Error[MAX_QUANTIZE_IMAGE_WIDTH+1][3][2]; struct Sample *s=AllocSamples(Width*Height,N_DIMENSIONS); int x,y,c; for(y=0;y<Height;y++) for(x=0;x<Width;x++) { for(c=0;c<3;c++) NthSample(s,y*Width+x,N_DIMENSIONS)->Value[c]=PIXEL(x,y,c); // now, let's generate extra values to quantize on for(int i=0;i<N_EXTRAVALUES;i++) { int val1=0; for(c=0;c<3;c++) val1+=PIXEL(x,y,c)*ExtraValueXForms[i*3+c]; val1>>=8; NthSample(s,y*Width+x,N_DIMENSIONS)->Value[c]=(uint8) (MIN(255,MAX(0,val1))); } } struct QuantizedValue *q=Quantize(s,Width*Height,N_DIMENSIONS, ncolors,Weights,firstcolor); delete[] s; memset(out_palette,0x55,768); for(int p=0;p<256;p++) { struct QuantizedValue *v=FindQNode(q,p); if (v) for(int c=0;c<3;c++) out_palette[p*3+c]=v->Mean[c]; } memset(Error,0,sizeof(Error)); for(y=0;y<Height;y++) { int ErrorUse=y & 1; int ErrorUpdate=ErrorUse^1; for(x=0;x<Width;x++) { uint8 samp[3]; for(c=0;c<3;c++) { int tryc=PIXEL(x,y,c); if (! (flags & QUANTFLAGS_NODITHER)) { tryc+=Error[x][c][ErrorUse]; Error[x][c][ErrorUse]=0; } samp[c]=(uint8) MIN(255,MAX(0,tryc)); } struct QuantizedValue *f=FindMatch(samp,3,Weights,q); out_pixels[Width*y+x]=(uint8) (f->value); if (! (flags & QUANTFLAGS_NODITHER)) for(int i=0;i<3;i++) { int newerr=samp[i]-f->Mean[i]; int orthog_error=(newerr*3)/8; Error[x+1][i][ErrorUse]+=orthog_error; Error[x][i][ErrorUpdate]=orthog_error; Error[x+1][i][ErrorUpdate]=newerr-2*orthog_error; } } } if (q) FreeQuantization(q); }
void CRemoteFileDialog::FillFileList() { CAutoFlag af(m_bFilling, TRUE); if (m_pConnection) { m_pConnection->GetCurrentDirectory(m_sCurFolder); m_bRoot = (m_sCurFolder == _T("/")); if (m_bRoot) { m_sCurFolder = _T("(root)"); } UpdateData(FALSE); m_lcFiles.DeleteAllItems(); m_lcFiles.UpdateWindow(); m_lcFiles.SetRedraw(FALSE); m_mapItems.RemoveAll(); CFtpFileFind ff(m_pConnection); int nID = 0; BOOL bContinue = ff.FindFile(); while (bContinue) { bContinue = ff.FindNextFile(); if (!ff.IsDots()) { if (ff.IsDirectory()) { AddFileItem(ff.GetFileName(), RFDT_FOLDER, nID++, 0, NULL, m_silLarge.GetFolderImageIndex()); } else if (!FolderSelect()) // check extension matches filter { BOOL bMatch = m_sFilterExt.IsEmpty() || m_sFilterExt == _T(".*"); if (!bMatch) { TCHAR szExt[_MAX_EXT] = _T("*"); CString sFilename = ff.GetFileName(); _tsplitpath(sFilename, NULL, NULL, NULL, &szExt[1]); CStringArray aFilterExt; Misc::Split(m_sFilterExt, _T(';'), aFilterExt); bMatch = (Misc::Find(aFilterExt, szExt) != -1); } if (bMatch) { FILETIME tLastMod; ff.GetLastWriteTime(&tLastMod); AddFileItem(ff.GetFileName(), RFDT_FILE, nID++, (DWORD)ff.GetLength(), &tLastMod); } } } } ff.Close(); // resort m_lcFiles.SortItems(SortProc, (DWORD)&m_mapItems); m_lcFiles.SetRedraw(TRUE); // attempt to select a match int nSel = FindMatch(m_sFilenames); if (nSel != -1) { m_lcFiles.SetItemState(nSel, LVIS_SELECTED, LVIS_SELECTED); m_lcFiles.EnsureVisible(nSel, FALSE); } m_toolbar.GetToolBarCtrl().EnableButton(ID_UPONELEVEL, !m_bRoot && !(m_dwOptions & RFD_NONAVIGATE)); UpdateOKButton(); } }
void CRemoteFileDialog::UpdateFileResults() { m_aFiles.RemoveAll(); if (m_sFilenames.IsEmpty()) { return; } // we just parse m_sFilenames CString sFileNames(m_sFilenames); BOOL bMustExist = FileMustExist(); // for downloads int nStartQuote = sFileNames.Find(_T('\"')); if (nStartQuote == -1) { // single file sFileNames.TrimLeft(); sFileNames.TrimRight(); int nFindMatch = FindMatch(sFileNames); if (!bMustExist || nFindMatch != -1) { CString sFilePath(sFileNames); if (!m_bRoot) { sFilePath.Format(_T("%s/%s"), m_sCurFolder, sFileNames); } m_aFiles.Add(FILERESULT(sFilePath, GetItemSize(nFindMatch))); } } else // look for pairs of quotes { while (nStartQuote != -1) { int nEndQuote = sFileNames.Find('\"', nStartQuote + 1); if (nEndQuote != -1) { CString sFileName = sFileNames.Mid(nStartQuote + 1, nEndQuote - 1 - nStartQuote); sFileName.TrimLeft(); sFileName.TrimRight(); int nFindMatch = FindMatch(sFileName); if (!bMustExist || nFindMatch != -1) { CString sFilePath(sFileName); if (!m_bRoot) { sFilePath.Format(_T("%s/%s"), m_sCurFolder, sFileName); } m_aFiles.Add(FILERESULT(sFilePath, GetItemSize(nFindMatch))); } // next pair nStartQuote = sFileNames.Find(_T('\"'), nEndQuote + 1); } else { nStartQuote = -1; // we're done } } } }
void GoodPackerFrontEnd::DoPack(PackerCallback cb) { sU32 lookAhead,testAhead; Match tm; // tempmatch sBool betterMatch; sF32 sizec,sizet; sU8 tick; Head = new sU32[65536]; sSetMem(Head,0xff,sizeof(sU32)*65536); Link = new sU32[SourceSize]; FillPtr = 0; tick = 0; AheadStart = 0; Ahead = 0; while(SourcePtr<SourceSize-1) { if(!++tick && cb) cb(SourcePtr,SourceSize,BackEnd->GetCurrentSize()); lookAhead = SourceSize - SourcePtr; FindMatch(CM,SourcePtr,lookAhead); if(CM.Len>=2) { betterMatch = sFALSE; sizec = BackEnd->MatchLen(CM.Offs,CM.Len); // try to find a better match if(BackEnd->FindPrevOffset(CM.Offs)==-1 || Ahead && BackEnd->MatchLen(BM.Offs,Ahead)<BackEnd->LiteralLen(AheadStart,Ahead)) { for(testAhead=1;!betterMatch && CM.Len>testAhead && testAhead<3;testAhead++) { FindMatch(tm,SourcePtr+testAhead,lookAhead-testAhead); sizet = BackEnd->MatchLen(tm.Offs,tm.Len); if(sizet<1e+20f && CM.Len < tm.Len+(sizec-sizet)*BackEnd->InvAvgMatchLen || Ahead && tm.Len >= CM.Len && sizet<sizec) betterMatch = sTRUE; } if(testAhead==2 && !Ahead && tm.Len<CM.Len && BackEnd->LiteralLen(SourcePtr,1)+sizet>sizec) betterMatch = sFALSE; } if(!betterMatch) { if(Ahead) { TryBetterAhead(); FlushAhead(sizec - BackEnd->MatchLen(CM.Offs,CM.Len,BM.Offs)); } if(BackEnd->LiteralLen(SourcePtr,CM.Len)<BackEnd->MatchLen(CM.Offs,CM.Len)) BackEnd->EncodeLiteral(SourcePtr,CM.Len); else BackEnd->EncodeMatch(CM.Offs,CM.Len); SourcePtr += CM.Len; } else { if(!Ahead) { BM = CM; AheadStart = SourcePtr; } Ahead++; SourcePtr++; } } else { if(Ahead) Ahead++; else BackEnd->EncodeLiteral(SourcePtr,1); SourcePtr++; } if(Ahead && Ahead==BM.Len) { TryBetterAhead(); FlushAhead(); } } FlushAhead(); if(SourcePtr!=SourceSize) BackEnd->EncodeLiteral(SourcePtr,SourceSize-SourcePtr); delete[] Link; delete[] Head; }
void TextFinder::scopeStringMatches(int identifier, const WebString& searchText, const WebFindOptions& options, bool reset) { // TODO(dglazkov): The reset/continue cases need to be untangled into two // separate functions. This collation of logic is unnecessary and adds to // overall complexity of the code. if (reset) { // This is a brand new search, so we need to reset everything. // Scoping is just about to begin. m_scopingInProgress = true; // Need to keep the current identifier locally in order to finish the // request in case the frame is detached during the process. m_findRequestIdentifier = identifier; // Clear highlighting for this frame. unmarkAllTextMatches(); // Clear the tickmarks and results cache. clearFindMatchesCache(); // Clear the counters from last operation. m_lastMatchCount = 0; m_nextInvalidateAfter = 0; m_resumeScopingFromRange = nullptr; // The view might be null on detached frames. LocalFrame* frame = ownerFrame().frame(); if (frame && frame->page()) m_frameScoping = true; // Now, defer scoping until later to allow find operation to finish quickly. scopeStringMatchesSoon( identifier, searchText, options, false); // false means just reset, so don't do it again. return; } if (!shouldScopeMatches(searchText, options)) { finishCurrentScopingEffort(identifier); return; } PositionInFlatTree searchStart = PositionInFlatTree::firstPositionInNode(ownerFrame().frame()->document()); PositionInFlatTree searchEnd = PositionInFlatTree::lastPositionInNode(ownerFrame().frame()->document()); DCHECK_EQ(searchStart.document(), searchEnd.document()); if (m_resumeScopingFromRange) { // This is a continuation of a scoping operation that timed out and didn't // complete last time around, so we should start from where we left off. DCHECK(m_resumeScopingFromRange->collapsed()); searchStart = fromPositionInDOMTree<EditingInFlatTreeStrategy>( m_resumeScopingFromRange->endPosition()); if (searchStart.document() != searchEnd.document()) return; } // TODO(dglazkov): The use of updateStyleAndLayoutIgnorePendingStylesheets // needs to be audited. see http://crbug.com/590369 for more details. searchStart.document()->updateStyleAndLayoutIgnorePendingStylesheets(); // This timeout controls how long we scope before releasing control. This // value does not prevent us from running for longer than this, but it is // periodically checked to see if we have exceeded our allocated time. const double maxScopingDuration = 0.1; // seconds int matchCount = 0; bool timedOut = false; double startTime = currentTime(); do { // Find next occurrence of the search string. // FIXME: (http://crbug.com/6818) This WebKit operation may run for longer // than the timeout value, and is not interruptible as it is currently // written. We may need to rewrite it with interruptibility in mind, or // find an alternative. const EphemeralRangeInFlatTree result = findPlainText(EphemeralRangeInFlatTree(searchStart, searchEnd), searchText, options.matchCase ? 0 : CaseInsensitive); if (result.isCollapsed()) { // Not found. break; } Range* resultRange = Range::create( result.document(), toPositionInDOMTree(result.startPosition()), toPositionInDOMTree(result.endPosition())); if (resultRange->collapsed()) { // resultRange will be collapsed if the matched text spans over multiple // TreeScopes. FIXME: Show such matches to users. searchStart = result.endPosition(); continue; } ++matchCount; // Catch a special case where Find found something but doesn't know what // the bounding box for it is. In this case we set the first match we find // as the active rect. IntRect resultBounds = resultRange->boundingBox(); IntRect activeSelectionRect; if (m_locatingActiveRect) { activeSelectionRect = m_activeMatch.get() ? m_activeMatch->boundingBox() : resultBounds; } // If the Find function found a match it will have stored where the // match was found in m_activeSelectionRect on the current frame. If we // find this rect during scoping it means we have found the active // tickmark. bool foundActiveMatch = false; if (m_locatingActiveRect && (activeSelectionRect == resultBounds)) { // We have found the active tickmark frame. m_currentActiveMatchFrame = true; foundActiveMatch = true; // We also know which tickmark is active now. m_activeMatchIndex = matchCount - 1; // To stop looking for the active tickmark, we set this flag. m_locatingActiveRect = false; // Notify browser of new location for the selected rectangle. reportFindInPageSelection( ownerFrame().frameView()->contentsToRootFrame(resultBounds), m_activeMatchIndex + 1, identifier); } ownerFrame().frame()->document()->markers().addTextMatchMarker( EphemeralRange(resultRange), foundActiveMatch); m_findMatchesCache.append( FindMatch(resultRange, m_lastMatchCount + matchCount)); // Set the new start for the search range to be the end of the previous // result range. There is no need to use a VisiblePosition here, // since findPlainText will use a TextIterator to go over the visible // text nodes. searchStart = result.endPosition(); m_resumeScopingFromRange = Range::create( result.document(), toPositionInDOMTree(result.endPosition()), toPositionInDOMTree(result.endPosition())); timedOut = (currentTime() - startTime) >= maxScopingDuration; } while (!timedOut); // Remember what we search for last time, so we can skip searching if more // letters are added to the search string (and last outcome was 0). m_lastSearchString = searchText; if (matchCount > 0) { ownerFrame().frame()->editor().setMarkedTextMatchesAreHighlighted(true); m_lastMatchCount += matchCount; // Let the frame know how many matches we found during this pass. ownerFrame().increaseMatchCount(matchCount, identifier); } if (timedOut) { // If we found anything during this pass, we should redraw. However, we // don't want to spam too much if the page is extremely long, so if we // reach a certain point we start throttling the redraw requests. if (matchCount > 0) invalidateIfNecessary(); // Scoping effort ran out of time, lets ask for another time-slice. scopeStringMatchesSoon(identifier, searchText, options, false); // don't reset. return; // Done for now, resume work later. } finishCurrentScopingEffort(identifier); }
int main (int argc,char *argv []) { int argPos, argNum = argc, numGrpNames = 0, i = 0; char **groupnames, *rename = (char *) NULL, *tableName = (char *) NULL; bool ascii = false; FieldOptions *head = (FieldOptions *) NULL, *p = (FieldOptions *) NULL, *temp = (FieldOptions *) NULL; Groups **groups = (Groups **) NULL; FILE *outFile = (FILE *) NULL; DBObjData *inData, *outData; DBObjTable *inTable, *outTable; DBObjTableField *field; DBObjRecord *inRecord, *outRecord; DBObjectLIST<DBObjTableField> *fields; if(argc <= 2) { doHelp(false,argv[0]); return(DBSuccess); } outData = new DBObjData("Untitled", DBTypeTable); outTable = outData->Table(DBrNItems); head = new FieldOptions(BAD,"","", (FieldOptions *) NULL); groupnames = (char **) malloc(sizeof(char *)); for (argPos = 1;argPos < argNum;) { if (CMargTest(argv[argPos],"-f","--field")) { if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing operation and field after -f!"); return (CMfailed); } if(!strcmp(argv[argPos],"pct")) { if (argNum <= argPos + 2) { CMmsgPrint (CMmsgUsrError,"Missing field and/or percentage after -f pct!"); return (CMfailed); } p = FOHierarchy(argv[argPos],argv[argPos+1],rename,atoi(argv[argPos+2]),head); argNum = CMargShiftLeft(argPos,argv,argNum); argNum = CMargShiftLeft(argPos,argv,argNum); } else if(!strcmp(argv[argPos],"num")) { char *num = new char[4]; strcpy(num,"Num"); p = FOHierarchy(argv[argPos],num,rename,-1,head); } else { if (argNum < argPos + 1) { CMmsgPrint (CMmsgUsrError,"Missing operation or field after -f %s!",argv[argPos]); return (CMfailed); } p = FOHierarchy(argv[argPos],argv[argPos+1],rename,-1,head); argNum = CMargShiftLeft(argPos,argv,argNum); } p->setPrint(true); rename = (char *) NULL; if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-g","--group")) { if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing groupname!"); return (CMfailed); } if((groupnames = (char **) realloc(groupnames,(numGrpNames + 1) * sizeof(char *))) == (char **) NULL) { CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return(DBFault); } groupnames[numGrpNames] = argv[argPos]; numGrpNames++; if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-h","--help")) { argNum = CMargShiftLeft (argPos,argv,argNum); if(CMargTest(argv[argPos],"e","extend")) { doHelp(true,argv[0]); argNum = CMargShiftLeft (argPos,argv,argNum); } else doHelp(false,argv[0]); } if (CMargTest(argv[argPos],"-c","--ascii")) { ascii = true; if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-a","--table")) { if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing table name!"); return (CMfailed); } tableName = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-r","--rename")) { if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing field after -r!"); return (CMfailed); } rename = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-o","--output")) { if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing output filename!"); return (CMfailed); } if((outFile = fopen(argv[argPos],"w")) == (FILE *) NULL) { CMmsgPrint (CMmsgUsrError,"Cannot open file %s",argv[argPos]); return (CMfailed); } if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-t","--title")) { if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing title!"); return (CMfailed); } outData->Name(argv[argPos]); if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-s","--subject")) { if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing subject!"); return (CMfailed); } outData->Document(DBDocSubject,argv[argPos]); if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-d","--domain")) { if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing domain!"); return (CMfailed); } outData->Document(DBDocGeoDomain,argv[argPos]); if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-v","--version")) { if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing version!"); return (CMfailed); } outData->Document(DBDocVersion,argv[argPos]); if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if ((argv[argPos][0] == '-') && (strlen (argv[argPos]) > 1)) { CMmsgPrint (CMmsgUsrError, "Unknown option: %s!",argv[argPos]); return (CMfailed); } argPos++; } if(outFile == (FILE *) NULL) outFile = stdout; if(head->next == (FieldOptions *) NULL) return(DBSuccess); inData = new DBObjData(); if ((argNum > 1) && (strcmp(argv[1],"-") != 0)) inData->Read(argv[1]); else inData->Read(stdin); if (outData->Name() == (char *) NULL) outData->Name("Untitled"); if (outData->Document(DBDocSubject) == (char *) NULL) outData->Document(DBDocSubject,inData->Document(DBDocSubject)); if (outData->Document(DBDocGeoDomain) == (char *) NULL) outData->Document(DBDocGeoDomain,inData->Document(DBDocGeoDomain)); if (outData->Document(DBDocVersion) == (char *) NULL) outData->Document(DBDocVersion,inData->Document(DBDocVersion)); if(tableName == (char *) NULL) tableName = DBrNItems; if((inTable = inData->Table(tableName)) == (DBObjTable *) NULL) { CMmsgPrint (CMmsgUsrError,"Invalid table!"); delete inData; return (CMfailed); } if((groups = (Groups **) malloc(numGrpNames * sizeof(Groups *))) == (Groups **) NULL) { CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return(DBFault); } for(i = 0; i < numGrpNames; i++) { if((field = inTable->Field(groupnames[i])) == (DBObjTableField *) NULL) { CMmsgPrint (CMmsgUsrError, "Invalid group name: %s",groupnames[i]); return (CMfailed); } if(DBTableFieldIsCategory(field)) { groups[i] = new Groups(); groups[i]->srcFLD = field; groups[i]->dstFLD = new DBObjTableField(*field); outTable->AddField(groups[i]->dstFLD); // CMmsgPrint (CMmsgUsrError, "Added Group: %s",groups[i]->dstFLD->Name()); } else CMmsgPrint (CMmsgUsrError, "Group %s is not Category!",groupnames[i]); } delete groupnames; p = head->next; temp = head; while(p->next) { FieldOptions *duplicate = (FieldOptions *) NULL, *prev = p; if(!p->getPrint() && FLDExists(p,p->getOldName(),p->getFunc(),&duplicate)) { temp->next = p->next; delete p; p = temp->next; continue; } while(FLDExists(prev,prev->getOldName(),prev->getFunc(),&prev,&duplicate) && !duplicate->getPrint()) { prev->next = duplicate->next; delete duplicate; } temp = p; p = p->next; } // p = head->next; // while(p) { CMmsgPrint (CMmsgUsrError, "Added: o:%s n:%s p:",p->getOldName(),p->getNewName()); if(p->getPrint()) CMmsgPrint (CMmsgUsrError, "true"); else CMmsgPrint (CMmsgUsrError, "false"); p = p->next; } fields = inTable->Fields(); p = head->next; while(p) { field = fields->Item (p->getOldName()); if (p->getFunc() == MIN || p->getFunc() == MAX) p->field = new DBObjTableField(p->getNewName(),field->Type(),field->Format(),field->Length()); else if(p->getFunc() == NUM || p->getFunc() == NONNULL) p->field = new DBObjTableField(p->getNewName(), DBTableFieldInt, DBHiddenField, sizeof (DBInt)); else p->field = new DBObjTableField(p->getNewName(), DBTableFieldFloat, DBHiddenField, sizeof(DBFloat)); if(p->getFunc() != NUM && p->getFunc() != NONNULL) { // if ((field = inTable->Field(p->getOldName())) == (DBObjTableField *) NULL) if (field == (DBObjTableField *) NULL) { CMmsgPrint (CMmsgUsrError, "Invalid field name: %s",p->getOldName()); return(DBFault); } if (!DBTableFieldIsNumeric(field)) { CMmsgPrint (CMmsgUsrError, "Field is not Numeric: %s",p->getOldName()); return(DBFault); } } outTable->AddField(p->field); p = p->next; } // MAKE SURE TO TEST FOR SPEED BY DECLARING INTS OUTSIDE OF FOR LOOPS!!! for (int inRecID = 0;inRecID < inTable->ItemNum();++inRecID) { inRecord = inTable->Item(inRecID); if ((outRecord = FindMatch(inRecord, outTable,(const Groups**) groups, numGrpNames)) != (DBObjRecord *) NULL) { p = head->next; while(p) { field = fields->Item (p->getOldName()); switch(p->getFunc()) { default: break; case NUM: p->field->Int(outRecord,p->field->Int(outRecord) + 1); break; case NONNULL: if (p->isInt()) { if (field->Int(inRecord) != field->IntNoData()) p->field->Int(outRecord,p->field->Int(outRecord) + 1); } else { if (!CMmathEqualValues(field->Float(inRecord),field->FloatNoData())) p->field->Int(outRecord,p->field->Int(outRecord) + 1); } break; case MIN: if (p->isInt()) { if(field->Int(inRecord) != field->IntNoData()) { if (p->field->Int(outRecord) != p->field->IntNoData()) { if (field->Int(inRecord) < p->field->Int(outRecord)) p->field->Int(outRecord,field->Int(inRecord)); } else { p->field->Int(outRecord,field->Int(inRecord)); } } } else { if (!CMmathEqualValues(field->Float(inRecord),field->FloatNoData())) { if (!CMmathEqualValues(p->field->Float(inRecord),p->field->FloatNoData())) { if (field->Float(inRecord) < p->field->Float(outRecord)) p->field->Float(outRecord,field->Float(inRecord)); } else { p->field->Float(outRecord,field->Float(inRecord)); } } } break; case MAX: if (p->isInt()) { if(field->Int(inRecord) != field->IntNoData()) { if (p->field->Int(outRecord) != p->field->IntNoData()) { if (field->Int(inRecord) > p->field->Int(outRecord)) p->field->Int(outRecord,field->Int(inRecord)); } else { p->field->Int(outRecord,field->Int(inRecord)); } } } else { if (!CMmathEqualValues(field->Float(inRecord),field->FloatNoData())) { if (!CMmathEqualValues(p->field->Float(inRecord),p->field->FloatNoData())) { if (field->Float(inRecord) > p->field->Float(outRecord)) p->field->Float(outRecord,field->Float(inRecord)); } else { p->field->Float(outRecord,field->Float(inRecord)); } } } break; case SUM: if (p->isInt()) { if(field->Int(inRecord) != field->IntNoData()) p->field->Int(outRecord,p->field->Int(outRecord) + field->Int(inRecord)); } else { if (!CMmathEqualValues(field->Float(inRecord),field->FloatNoData())) p->field->Float(outRecord,p->field->Float(outRecord) + field->Float(inRecord)); } break; case DEV: case PCT: case MED: p->tailVal = p->tailVal->next = new Values(); p->tailVal->val = field->Float(inRecord); p->tailVal->next = 0; break; case MOD: Values *cur = p->getHead(); while(cur->next && !CMmathEqualValues(cur->val,field->Float(inRecord))) cur = cur->next; if(cur->next) cur->occur++; else { p->tailVal->val = field->Float(inRecord); p->tailVal->occur = 1; p->tailVal = p->tailVal->next = new Values(); } break; } p = p->next; } } else { outRecord = outTable->Add(); for(i = 0; i < numGrpNames; i++) { switch (groups[i]->srcFLD->Type()) { default: case DBTableFieldString: groups[i]->dstFLD->String(outRecord,groups[i]->srcFLD->String(inRecord)); break; case DBTableFieldInt: groups[i]->dstFLD->Int(outRecord,groups[i]->srcFLD->Int(inRecord)); break; } } p = head->next; while(p) { field = fields->Item (p->getOldName()); switch(p->getFunc()) { default: case BAD: break; case NUM: p->setInt(); p->field->Int(outRecord,1); break; case NONNULL: if (field->Type() == DBTableFieldInt) { p->setInt(); if (field->Int(inRecord) != field->IntNoData()) p->field->Int(outRecord,1); else p->field->Int(outRecord,0); } else { if (!CMmathEqualValues(field->Float(inRecord),field->FloatNoData())) p->field->Int(outRecord,1); else p->field->Int(outRecord,0); } break; case MIN: if (field->Type() == DBTableFieldInt) { p->setInt(); if (field->Int(inRecord) != field->IntNoData()) p->field->Int(outRecord,field->Int(inRecord)); } else { if(!CMmathEqualValues(field->Float(inRecord),field->FloatNoData())) p->field->Float(outRecord,field->Float(inRecord)); } break; case MAX: if (field->Type() == DBTableFieldInt) { p->setInt(); if (field->Int(inRecord) != field->IntNoData()) p->field->Int(outRecord,field->Int(inRecord)); } else { if(!CMmathEqualValues(field->Float(inRecord),field->FloatNoData())) p->field->Float(outRecord,field->Float(inRecord)); } break; case SUM: if (field->Type() == DBTableFieldInt) { p->setInt(); if (field->Int(inRecord) != field->IntNoData()) p->field->Int(outRecord,field->Int(inRecord)); else p->field->Int(outRecord,0); } else { if(!CMmathEqualValues(field->Float(inRecord),field->FloatNoData())) p->field->Float(outRecord,field->Float(inRecord)); else p->field->Float(outRecord,0.0); } break; case DEV: case PCT: case MED: p->tailVal = p->tailVal->next = new Values(); p->tailVal->val = field->Float(inRecord); p->tailVal->next = 0; break; case MOD: p->tailVal->val = field->Float(inRecord); p->tailVal->occur = 1; p->tailVal = p->tailVal->next = new Values(); break; } p = p->next; } } } for(int outRecID = 0; outRecID < outTable->ItemNum();++outRecID) { outRecord = outTable->Item(outRecID); p = head->next; FieldOptions *sum, *num; DBFloat mod; int occurrance; float i; bool mult; Values *cur; while(p) { field = fields->Item (p->getOldName()); switch(p->getFunc()) { case AVG: if((FLDExists(head,p->getOldName(),SUM,&sum)) && (FLDExists(head,p->getOldName(),NONNULL,&num))) p->field->Float(outRecord,sum->field->Float(outRecord) / (DBFloat) (num->field->Int(outRecord))); else CMmsgPrint (CMmsgUsrError, "Program Error! Could not find SUM or NONNULL in linked list! Please contact the GHAAS developers group!"); break; case NAVG: if((FLDExists(head,p->getOldName(),SUM,&sum)) && (FLDExists(head,"NUM",NUM,&num))) p->field->Float(outRecord,sum->field->Float(outRecord) / (DBFloat) (num->field->Int(outRecord))); else CMmsgPrint (CMmsgUsrError, "Program Error! Could not find SUM or NUM in linked list! Please contact the GHAAS developers group!"); break; case PCT: case MED: i = (float) (inTable->ItemNum() * p->getHead()->occur * 0.01) - 1; cur = p->getHead()->next; while(i > 0) { cur = cur->next; i--; } p->field->Float(outRecord,(cur->val + cur->next->val) / 2); break; case MOD: mod = 0.0; occurrance = 0; mult = false; cur = p->getHead(); while(cur) { if(cur->occur > occurrance) { mod = cur->val; occurrance = cur->occur; mult = false; } else if(cur->occur == occurrance) mult = true; cur = cur->next; } if(mult) CMmsgPrint (CMmsgUsrError, "** Warning, multiple answers for MOD, listing first found!"); p->field->Float(outRecord,mod); break; default: break; } p = p->next; } } p = head->next; while(p) { if(p->getFunc() == DEV) { FieldOptions *avg, *num; field = fields->Item (p->getOldName()); if((FLDExists(head,p->getOldName(),AVG,&avg)) && (FLDExists(head,"NUM",NUM,&num))) { for(int outRecID = 0; outRecID < outTable->ItemNum();++outRecID) { outRecord = outTable->Item(outRecID); DBFloat sum = 0.0; Values *cur = p->getHead()->next; while(cur) { // sum += (DBFloat) (pow((cur->val - avg->field->Float(outRecord)),2)); DBFloat add = (cur->val - avg->field->Float(outRecord)); sum += (DBFloat) (add * add); cur = cur->next; } sum = sqrt(sum /(DBFloat) num->field->Int(outRecord)); p->field->Float(outRecord,sum); } } else CMmsgPrint (CMmsgUsrError, "Program Error! Could not find AVG or NUM in linked list! Please contact the GHAAS developers group!"); } p = p->next; } // DELETE unnecessary fields which were for temp storage fields = outTable->Fields(); p = head->next; while(p) { if(!p->getPrint()) outTable->DeleteField(fields->Item(p->getNewName())); p = p->next; } p = head->next; while(p) { if ((strcmp(p->field->Format(),DBHiddenField) == 0) && p->getPrint()) { if(p->isInt()) { int maxval = 0; for(int outRecID = 0; outRecID < outTable->ItemNum();++outRecID) { int val = p->field->Int(outTable->Item(outRecID)); if (maxval < val) maxval = val; else if (maxval < -val) maxval = -val; } p->field->Format(DBMathIntAutoFormat(maxval)); } else { float maxval = 0.0; for(int outRecID = 0; outRecID < outTable->ItemNum();++outRecID) { float val = p->field->Float(outTable->Item(outRecID)); if (maxval < val) maxval = val; else if (maxval < -val) maxval = -val; } p->field->Format(DBMathFloatAutoFormat(maxval)); } } // CMmsgPrint (CMmsgUsrError, "Format(%s)%d,%d: '%s'",p->getFuncName(),p->isInt(),p->getPrint(),p->field->Format()); p = p->next; } DBObjectLIST<DBObjTableField> *list = new DBObjectLIST<DBObjTableField> ("Sorted Field List"); for(i = 0; i < numGrpNames; i++) list->Add(groups[i]->dstFLD); outTable->ListSort(list); if (ascii) DBExportASCIITable(outTable,outFile); else outData->Write(outFile); /* CLEANUP ************************************************/ if(outFile != stdout) fclose(outFile); for(i = 0; i < numGrpNames; i++) delete groups[i]->dstFLD; delete groups; p = head; while(p) { head = head->next; delete p; p = head; } return(DBSuccess); }
int main(void) { // Construct list pWord* hashList = (pWord*)malloc(260 * sizeof(pWord)); for (int i = 0; i < 260; ++i) { hashList[i] = NULL; } // Read and save words char allInput[40]; int i = 0; while (1) { fgets(allInput, sizeof(allInput), stdin); strtok(allInput, "\n"); if (strcmp(allInput, "\n") == 0) { break; } // Split words pWord wordGrp = SpiltWord(allInput); // Calculate Hash Number int wordHash = CalHash(wordGrp); // Store the section to the list if (hashList[wordHash] == NULL) { hashList[wordHash] = wordGrp; } else { // Go to the end of the list TraceList(hashList[wordHash])->nextWord = wordGrp; } i = 0; } char output[100000][10]; int pointer = 0; // Search while (1) { char queryWord[100]; i = 0; void* saver = fgets(queryWord, sizeof(queryWord), stdin); if (saver == NULL) { break; } strtok(queryWord, "\n"); strtok(queryWord, " "); int queryHash = WordHash(queryWord); pWord foundNode = FindMatch(hashList, queryHash, queryWord); if (foundNode) { strcpy(output[pointer++], foundNode->word); } else { strcpy(output[pointer++], "eh"); } } if (pointer != 0) { for (int i = 0; i < pointer; ++ i) { printf("%s\n", output[i]); } } return 0; }
bool Scraper::FindBestBMP(const searchType type, HBITMAP hBmp, const double threshold, MATCHPOINTS* match, char* matchedBMP) { // Convert HBITMAP to Mat unique_ptr<Gdiplus::Bitmap> pBitmap; pBitmap.reset(Gdiplus::Bitmap::FromHBITMAP(hBmp, NULL)); Mat img = CGdiPlus::CopyBmpToMat(pBitmap.get()); pBitmap.reset(); cvtColor( img, img, CV_BGRA2BGR ); // Find right image group imageType iType = type==searchTownHall ? townHall : type==searchLootCart ? lootCart : type==searchClashIcon ? clashIcon : type==searchPlayStoreOpenButton ? playStoreOpenButton : type==searchGoldStorage ? goldStorage : type==searchElixStorage ? elixStorage : type==searchDarkStorage ? darkStorage : (imageType) 0; int iTypeIndex = -1; for (int i = 0; i < (int) imageGroups.size(); i++) if (imageGroups[i].iType == iType) iTypeIndex = i; if (iTypeIndex == -1) return false; // Scan through each Mat in this image group double bestMaxVal = 0; Point bestMaxLoc(0, 0); string bestNeedlePath(""); for (int i = 0; i < (int) imageGroups[iTypeIndex].mats.size(); i++) { Mat result = FindMatch(img, imageGroups[iTypeIndex].mats[i]); // Localize the best match with minMaxLoc double minVal, maxVal; Point minLoc, maxLoc; minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc); bool beachSideOfSWLine = BeachSideOfSWLine((westPoint.x+maxLoc.x), (northPoint.y-10+maxLoc.y)); if (maxVal >= threshold && maxVal > bestMaxVal && (type!=searchTownHall || !beachSideOfSWLine)) { bestMaxVal = maxVal; bestMaxLoc = maxLoc; bestNeedlePath = imageGroups[iTypeIndex].imagePaths[i]; } } if (bestMaxVal > 0) { match->val = bestMaxVal; match->x = bestMaxLoc.x; match->y = bestMaxLoc.y; sprintf_s(matchedBMP, MAXSTRING, "%s", bestNeedlePath.c_str()); return true; } return false; }
/* * IMCloseBrace - handle '}' in insert mode */ vi_rc IMCloseBrace( void ) { int i, j; int ts; fcb *cfcb; line *cline; vi_rc rc; int newcol; i_mark pos; startNewLineUndo(); insertChar( TRUE, FALSE ); newcol = CurrentPos.column + 1; if( EditFlags.ShowMatch ) { ReplaceCurrentLine(); rc = FindMatch( &pos ); if( rc == ERR_NO_ERR ) { tempMatch( &pos ); } GetCurrentLine(); } if( EditFlags.CMode ) { i = 0; while( isspace( WorkLine->data[i] ) ) { i++; } if( WorkLine->data[i] == '}' ) { /* * added a {, so: * find matching } * find out indentation of that line * shift current line over to that indentation * set current indentation to that */ ReplaceCurrentLine(); rc = findMatchingBrace( &pos ); if( rc == ERR_NO_ERR ) { newcol = VirtualColumnOnCurrentLine( CurrentPos.column ); CGimmeLinePtr( pos.line, &cfcb, &cline ); i = FindStartOfALine( cline ); i = GetVirtualCursorPosition( cline->data, i ); j = i - VirtualColumnOnCurrentLine( CurrentPos.column ); ts = EditVars.ShiftWidth; if( j > 0 ) { EditVars.ShiftWidth = j; Shift( CurrentPos.line, CurrentPos.line, '>', FALSE ); } else if( j < 0 ) { EditVars.ShiftWidth = -j; Shift( CurrentPos.line, CurrentPos.line, '<', FALSE ); } EditVars.ShiftWidth = ts; newcol = 1 + RealColumnOnCurrentLine( j + newcol ); } GetCurrentLine(); } } GoToColumn( newcol, WorkLine->len + 1 ); return( ERR_NO_ERR ); } /* IMCloseBrace */
bool RecipientsHandler::ResolveRecipients(vector_wstring list, const AbstractRecipient::Location location, Recipients* pRecipients, bool& cancelSend) { if(cancelSend) { LOG_WS_INFO(L"User selected to cancel send."); return false; } if(list.empty()) { LOG_WS_INFO(L"No recipients to resolve."); return false; } const std::vector<const std::wstring> internalDomains = GetInternalDomainCollection(); AbstractRecipient::Type treatAmbiguousRecipientAs = TreatIndeterminateRecipientsAs(); bool resolveAmbiguousRecipients = (AbstractRecipient::NOT_CONFIGURED == treatAmbiguousRecipientAs); int index = 0; for(vector_wstring::iterator it = list.begin(); it != list.end(); ++it) { ++index; std::wstring displayName = Parser::Trim((*it)); if (displayName.empty()) continue; { std::wostringstream msg; msg << "Start resolving of the recipient [" << displayName.c_str() << "]" << std::ends; LOG_WS_INFO(msg.str().c_str()); } RecipientMatch recipientMatch; bool foundAmbiguousRecipient; bool recipientMatchFound = FindMatch(displayName, index, pRecipients->GetNoteHandle(), location, recipientMatch, resolveAmbiguousRecipients, foundAmbiguousRecipient, cancelSend); if(cancelSend) { LOG_WS_INFO(L"User selected to cancel send"); break; } // The user has enabled the option to not resolve ambiguous recipients and the name search found // more then one match. Force the recipient type to the value the user has set. if(foundAmbiguousRecipient && !resolveAmbiguousRecipients) { LOG_WS_INFO(L"Ambiguous recipient found but not resolved. Set type as defined for the [ResolveAmbiguousRecipients] option."); pRecipients->Add(new Recipient(pRecipients->GetNoteHandle(), index, location, L"", displayName, L"", L"", treatAmbiguousRecipientAs)); continue; } if(!recipientMatchFound) { AddRecipient_NoMatchFound(displayName, location, index, pRecipients); continue; } if(recipientMatch.IsGroup()) { AddRecipient_Group(displayName, location, index, recipientMatch, pRecipients, cancelSend); if(cancelSend) { LOG_WS_INFO(L"User selected to cancel send"); break; } continue; } //Mail-In DB is Internal if(recipientMatch.IsMailInDatabase()) { std::wostringstream msg; msg << "Internal: Match is Mail-In DB [" << displayName.c_str() << "]." << std::ends; LOG_WS_INFO(msg.str().c_str()); pRecipients->Add(new Recipient( pRecipients->GetNoteHandle(), index, location, recipientMatch.GetFullName(), displayName, recipientMatch.GetMailAddress(), recipientMatch.GetInternetAddress(), AbstractRecipient::INTERNAL)); continue; } // No Internal domains = External if(internalDomains.empty()) { std::wostringstream msg; msg << "External: No internal domain list [" << displayName.c_str() << "]." << std::ends; LOG_WS_INFO(msg.str().c_str()); pRecipients->Add(new Recipient( pRecipients->GetNoteHandle(), index, location, recipientMatch.GetFullName(), displayName, recipientMatch.GetMailAddress(), recipientMatch.GetInternetAddress(), AbstractRecipient::EXTERNAL)); continue; } if(!CompareRecipientDomainAgainstInternalDomains(recipientMatch.GetMailDomain(), internalDomains)) { std::wostringstream msg; msg << "External: Domain does not match value in internal domain list [" << displayName.c_str() << "]." << std::ends; LOG_WS_INFO(msg.str().c_str()); pRecipients->Add(new Recipient( pRecipients->GetNoteHandle(), index, location, recipientMatch.GetFullName(), displayName, recipientMatch.GetMailAddress(), recipientMatch.GetInternetAddress(), AbstractRecipient::EXTERNAL)); continue; } std::wostringstream msg; msg << "Internal: Domain match value in internal domain list[" << displayName.c_str() << "]." << std::ends; LOG_WS_INFO(msg.str().c_str()); pRecipients->Add(new Recipient( pRecipients->GetNoteHandle(), index, location, recipientMatch.GetFullName(), displayName, recipientMatch.GetMailAddress(), recipientMatch.GetInternetAddress(), AbstractRecipient::INTERNAL)); continue; } return true; }
/**************************************************************************** * Function : EncodeLZSSByFile * Description: This function will read an input file and write an output * file encoded according to the traditional LZSS algorithm. * This algorithm encodes strings as 16 bits (a 12 bit offset * + a 4 bit length). * Parameters : fpIn - pointer to the open binary file to encode * fpOut - pointer to the open binary file to write encoded * output * Effects : fpIn is encoded and written to fpOut. Neither file is * closed after exit. * Returned : EXIT_SUCCESS or EXIT_FAILURE ****************************************************************************/ int EncodeLZSSByFile(FILE *fpIn, FILE *fpOut) { bit_file_t *bfpOut; encoded_string_t matchData; unsigned int i, c; unsigned int len; /* length of string */ /* head of sliding window and lookahead */ unsigned int windowHead, uncodedHead; /* use stdin if no input file */ if (fpIn == NULL) { fpIn = stdin; } if (fpOut == NULL) { /* use stdout if no output file */ bfpOut = MakeBitFile(stdout, BF_WRITE); } else { /* convert output file to bitfile */ bfpOut = MakeBitFile(fpOut, BF_WRITE); } windowHead = 0; uncodedHead = 0; /* Window Size : 2^12 same as offset */ /************************************************************************ * Fill the sliding window buffer with some known vales. DecodeLZSS must * use the same values. If common characters are used, there's an * increased chance of matching to the earlier strings. ************************************************************************/ memset(slidingWindow, ' ', WINDOW_SIZE * sizeof(unsigned char)); /* MAX_CODED : 2 to 17 because we cant have 0 to 1 */ /************************************************************************ * Copy MAX_CODED bytes from the input file into the uncoded lookahead * buffer. ************************************************************************/ for (len = 0; len < MAX_CODED && (c = getc(fpIn)) != EOF; len++) { uncodedLookahead[len] = c; } if (len == 0) { return (EXIT_SUCCESS); /* inFile was empty */ } /* Look for matching string in sliding window */ InitializeSearchStructures(); matchData = FindMatch(windowHead, uncodedHead); /* now encoded the rest of the file until an EOF is read */ while (len > 0) { if (matchData.length > len) { /* garbage beyond last data happened to extend match length */ matchData.length = len; } if (matchData.length <= MAX_UNCODED) { /* not long enough match. write uncoded flag and character */ BitFilePutBit(UNCODED, bfpOut); BitFilePutChar(uncodedLookahead[uncodedHead], bfpOut); matchData.length = 1; /* set to 1 for 1 byte uncoded */ } else { unsigned int adjustedLen; /* adjust the length of the match so minimun encoded len is 0*/ adjustedLen = matchData.length - (MAX_UNCODED + 1); /* match length > MAX_UNCODED. Encode as offset and length. */ BitFilePutBit(ENCODED, bfpOut); BitFilePutBitsInt(bfpOut, &matchData.offset, OFFSET_BITS, sizeof(unsigned int)); BitFilePutBitsInt(bfpOut, &adjustedLen, LENGTH_BITS, sizeof(unsigned int)); } /******************************************************************** * Replace the matchData.length worth of bytes we've matched in the * sliding window with new bytes from the input file. ********************************************************************/ i = 0; while ((i < matchData.length) && ((c = getc(fpIn)) != EOF)) { /* add old byte into sliding window and new into lookahead */ ReplaceChar(windowHead, uncodedLookahead[uncodedHead]); uncodedLookahead[uncodedHead] = c; windowHead = Wrap((windowHead + 1), WINDOW_SIZE); uncodedHead = Wrap((uncodedHead + 1), MAX_CODED); i++; } /* handle case where we hit EOF before filling lookahead */ while (i < matchData.length) { ReplaceChar(windowHead, uncodedLookahead[uncodedHead]); /* nothing to add to lookahead here */ windowHead = Wrap((windowHead + 1), WINDOW_SIZE); uncodedHead = Wrap((uncodedHead + 1), MAX_CODED); len--; i++; } /* find match for the remaining characters */ matchData = FindMatch(windowHead, uncodedHead); } /* we've decoded everything, free bitfile structure */ BitFileToFILE(bfpOut); return (EXIT_SUCCESS); }
/* finds dictionary matches for characters in current sector */ void DictSearch(unsigned int dictpos, unsigned int bytestodo) { register unsigned int i, j; #if (GREEDY == 0) unsigned int matchlen1, matchpos1; /* non-greedy search loop (slow) */ i = dictpos; j = bytestodo; while (j) /* loop while there are still characters left to be compressed */ { FindMatch(i, THRESHOLD); if (matchlength > THRESHOLD) { matchlen1 = matchlength; matchpos1 = matchpos; for ( ; ; ) { FindMatch(i + 1, matchlen1); if (matchlength > matchlen1) { matchlen1 = matchlength; matchpos1 = matchpos; SendChar(dict[i++]); j--; } else { if (matchlen1 > j) { matchlen1 = j; if (matchlen1 <= THRESHOLD) { SendChar(dict[i++]); j--; break; } } SendMatch(matchlen1, (i - matchpos1) & (DICTSIZE - 1)); i += matchlen1; j -= matchlen1; break; } } } else { SendChar(dict[i++]); j--; } } #else /* greedy search loop (fast) */ i = dictpos; j = bytestodo; while (j) /* loop while there are still characters left to be compressed */ { FindMatch(i, THRESHOLD); if (matchlength > j) matchlength = j; /* clamp matchlength */ if (matchlength > THRESHOLD) /* valid match? */ { SendMatch(matchlength, (i - matchpos) & (DICTSIZE - 1)); i += matchlength; j -= matchlength; } else { SendChar(dict[i++]); j--; } } #endif }