In cases where we have multiple matches, each highlighted by a region of coordinates,
        we need to separate matches, and find mean of each to return as match position
489456
def match_positions(shape, list_of_coords):
    
    match_array = np.zeros(shape)
    try:
        # excpetion hit on this line if nothing in list_of_coords- i.e. no matches
        match_array[list_of_coords[:,0],list_of_coords[:,1]] = 1
        labelled = label(match_array)
        objects = find_objects(labelled[0])
        coords = [{'x':(slice_x.start, slice_x.stop),'y':(slice_y.start, slice_y.stop)} for (slice_y,slice_x) in objects]
        final_positions = [(int(np.mean(coords[i]['x'])),int(np.mean(coords[i]['y']))) for i in range(len(coords))]
        return final_positions
    except IndexError:
        print 'no matches found'
        # this error occurs if no matches are found
        return []
806048
def locate(self, pattern, big_endian=False):
        """"""
        space, self.space = tee(self.space)
        if pattern.startswith('0x'):
            target = unhexlify(
                pattern[2:].encode('utf-8')).decode('utf-8')
            if not big_endian:
                target = target[::-1]
        else:
            target = pattern
        for index, one in enumerate(window(space, self.position)):
            if ''.join(one) == target[:self.position]:
                return index
        raise KeyError('{target} Not Found In {sets}!'.format(
            target=pattern, sets=self.sets))
1069331
public boolean regionMatchesIgnoreCase(char []cb, int offset, int length)
  {
    int pos = getIndex();

    char ch = current();
    for (int i = 0; i < length; i++) {
      if (ch == DONE) {
        setIndex(pos);
        return false;
      }

      if (Character.toLowerCase(cb[i + offset]) != Character.toLowerCase(ch)) {
        setIndex(pos);
        return false;
      }

      ch = next();
    }

    return true;
  }
1239663
private void quickSelect(List<P> points, int splitAxis, int medianNum) {
		int numPoints = points.size();

		if( tmp.length < numPoints ) {
			tmp = new double[numPoints];
			indexes = new int[ numPoints ];
		}
		for( int i = 0; i < numPoints; i++ ) {
			tmp[i] = distance.valueAt(points.get(i),splitAxis);
		}

		QuickSelect.selectIndex(tmp, medianNum, numPoints, indexes);
	}
536395
def highlightNextMatch(self):
        
        # If this method was called on an empty input field (ie.
        # if the user hit <ctrl>+s again) then pick the default
        # selection.
        if self.qteText.toPlainText() == '':
            self.qteText.setText(self.defaultChoice)
            return

        # If the mathIdx variable is out of bounds (eg. the last possible
        # match is already selected) then wrap it around.
        if self.selMatchIdx < 0:
            self.selMatchIdx = 0
            return
        if self.selMatchIdx >= len(self.matchList):
            self.selMatchIdx = 0
            return

        # Shorthand.
        SCI = self.qteWidget

        # Undo the highlighting of the previously selected match.
        start, stop = self.matchList[self.selMatchIdx - 1]
        line, col = SCI.lineIndexFromPosition(start)
        SCI.SendScintilla(SCI.SCI_STARTSTYLING, start, 0xFF)
        SCI.SendScintilla(SCI.SCI_SETSTYLING, stop - start, 30)

        # Highlight the next match.
        start, stop = self.matchList[self.selMatchIdx]
        SCI.SendScintilla(SCI.SCI_STARTSTYLING, start, 0xFF)
        SCI.SendScintilla(SCI.SCI_SETSTYLING, stop - start, 31)

        # Place the cursor at the start of the currently selected match.
        line, col = SCI.lineIndexFromPosition(start)
        SCI.setCursorPosition(line, col)
        self.selMatchIdx += 1
411329
function(matches)
        {
            // Optimized by Jose Prado (http://joseprado.com)
            for (var i = 0; i < matches.length; i++)
            {
                if (matches[i] === null)
                    continue;

                var itemI = matches[i],
                    itemIEndPos = itemI.index + itemI.length
                    ;

                for (var j = i + 1; j < matches.length && matches[i] !== null; j++)
                {
                    var itemJ = matches[j];

                    if (itemJ === null)
                        continue;
                    else if (itemJ.index > itemIEndPos)
                        break;
                    else if (itemJ.index == itemI.index && itemJ.length > itemI.length)
                        matches[i] = null;
                    else if (itemJ.index >= itemI.index && itemJ.index < itemIEndPos)
                        matches[j] = null;
                }
            }

            return matches;
        }
545829
private void findLinesInRegion( List<LineSegment2D_F32> gridLines ) {

		List<Edgel> list = edgels.copyIntoList(null);

		int iterations = 0;

		// exit if not enough points or max iterations exceeded
		while( iterations++ < maxDetectLines) {
			if( !robustMatcher.process(list) )
				break;

			// remove the found edges from the main list
			List<Edgel> matchSet = robustMatcher.getMatchSet();

			// make sure the match set is large enough
			if( matchSet.size() < minInlierSize )
				break;

			for( Edgel e : matchSet ) {
				list.remove(e);
			}

			gridLines.add(convertToLineSegment(matchSet, robustMatcher.getModelParameters()));
		}
	}
161864
def search(geo_coords, mode=2, verbose=True):
    
    if not isinstance(geo_coords, tuple) and not isinstance(geo_coords, list):
        raise TypeError('Expecting a tuple or a tuple/list of tuples')
    elif not isinstance(geo_coords[0], tuple):
        geo_coords = [geo_coords]

    _rg = RGeocoder(mode=mode, verbose=verbose)
    return _rg.query(geo_coords)
12603
private static int firstNonMatchPosition(Slice utf8, int[] codePointsToMatch)
    {
        int length = utf8.length();

        int position = 0;
        while (position < length) {
            int codePoint = tryGetCodePointAt(utf8, position);
            if (codePoint < 0) {
                break;
            }
            if (!matches(codePoint, codePointsToMatch)) {
                break;
            }
            position += lengthOfCodePoint(codePoint);
        }
        return position;
    }
1161116
private void findMatches(Match match, int n) throws IOException {
    if (n > 0) {
      int largestMatchingEndPosition = match.endPosition();
      Set<Integer> list = ignoreItem.getFullEndPositionList(spans.docID(),
          match.endPosition());
      // try to find matches with existing queue
      if (!queueSpans.isEmpty()) {
        Match span;
        for (int i = 0; i < queueSpans.size(); i++) {
          span = queueSpans.get(i);
          if (match.endPosition() == span.startPosition()
              || (list != null && list.contains(span.startPosition()))) {
            findMatches(new Match(match.startPosition(), span.endPosition()),
                (n - 1));
            largestMatchingEndPosition = Math.max(largestMatchingEndPosition,
                span.endPosition());
          }
        }
      }
      // extend queue if necessary and possible
      while (!lastSpan && (largestMatchingEndPosition >= lastStartPosition)) {
        if (spans.nextStartPosition() == NO_MORE_POSITIONS) {
          lastSpan = true;
        } else {
          Match span = new Match(spans.startPosition(), spans.endPosition());
          queueSpans.add(span);
          lastStartPosition = spans.startPosition();
          // check if this provides new match
          if (match.endPosition() == span.startPosition()
              || (list != null && list.contains(span.startPosition()))) {
            findMatches(new Match(match.startPosition(), span.endPosition()),
                (n - 1));
            largestMatchingEndPosition = Math.max(largestMatchingEndPosition,
                span.endPosition());
          }
        }
      }
    } else {
      // only unique spans
      if (!queueMatches.contains(match)) {
        queueMatches.add(match);
      }
    }
  }
764896
function mergeMatches (matches1, matches2) {
  let next
  const length1 = matches1.length
  const length2 = matches2.length
  let lastEndIndex = -1
  const output = []

  const state = {
    a1: matches1,
    i1: 0,
    a2: matches2,
    i2: 0
  }

  while (state.i1 < length1 || state.i2 < length2) {
    next = pickNext(state)
    if (next.startIndex >= lastEndIndex) {
      output.push(next)
    }
    lastEndIndex = next.endIndex
  }

  return output
}
480126
def match(self, context, line):
		""""""
		
		return line.kind == 'code' and line.partitioned[0] in self._both
869167
def match_window(in_data, offset):
    '''
    '''
    window_start = max(offset - WINDOW_MASK, 0)

    for n in range(MAX_LEN, THRESHOLD-1, -1):
        window_end = min(offset + n, len(in_data))
        # we've not got enough data left for a meaningful result
        if window_end - offset < THRESHOLD:
            return None
        str_to_find = in_data[offset:window_end]
        idx = in_data.rfind(str_to_find, window_start, window_end-n)
        if idx != -1:
            code_offset = offset - idx # - 1
            code_len = len(str_to_find)
            return (code_offset, code_len)

    return None
556550
def findAll(self, pattern):
        
        find_time = time.time()
        r = self.clipRegionToScreen()
        if r is None:
            raise ValueError("Region outside all visible screens")
            return None
        seconds = self.autoWaitTimeout
        if not isinstance(pattern, Pattern):
            if not isinstance(pattern, basestring):
                raise TypeError("find expected a string [image path] or Pattern object")
            pattern = Pattern(pattern)
        needle = cv2.imread(pattern.path)
        if needle is None:
            raise ValueError("Unable to load image '{}'".format(pattern.path))
        needle_height, needle_width, needle_channels = needle.shape
        positions = []
        timeout = time.time() + seconds

        # Check TemplateMatcher for valid matches
        matches = []
        while time.time() < timeout and len(matches) == 0:
            matcher = TemplateMatcher(r.getBitmap())
            matches = matcher.findAllMatches(needle, pattern.similarity)
            time.sleep(1/self._defaultScanRate if self._defaultScanRate is not None else 1/Settings.WaitScanRate)

        if len(matches) == 0:
            Debug.info("Couldn't find '{}' with enough similarity.".format(pattern.path))
            return iter([])

        # Matches found! Turn them into Match objects
        lastMatches = []
        for match in matches:
            position, confidence = match
            x, y = position
            lastMatches.append(
                Match(
                    confidence,
                    pattern.offset,
                    ((x+self.x, y+self.y), (needle_width, needle_height))))
        self._lastMatches = iter(lastMatches)
        Debug.info("Found match(es) for pattern '{}' at similarity ({})".format(pattern.path, pattern.similarity))
        self._lastMatchTime = (time.time() - find_time) * 1000 # Capture find time in milliseconds
        return self._lastMatches
1113271
function matchSegment(ax, ay, bx, by, cx, cy, dx, dy, r, result) {
    var len = result.length;

    var ap = closePoint(ax, ay, cx, cy, dx, dy, r);
    var bp = closePoint(bx, by, cx, cy, dx, dy, r);

    //     a----b
    // c---ap---bp---d
    if (ap !== null && bp !== null) return true; // fully covered

    var cp = closePoint(cx, cy, ax, ay, bx, by, r);
    var dp = closePoint(dx, dy, ax, ay, bx, by, r);

    if (cp !== null && cp === dp) return false; // degenerate case, no overlap

    var cpx, cpy, dpx, dpy;
    if (cp !== null) {
        cpx = interp(ax, bx, cp);
        cpy = interp(ay, by, cp);
    }
    if (dp !== null) {
        dpx = interp(ax, bx, dp);
        dpy = interp(ay, by, dp);
    }

    if (cp !== null && dp !== null) {

        if (cpx === dpx && cpy === dpy) return false; // degenerate case

        // a---cp---dp---b
        //     c----d
        if (cp < dp) {
            if (!equals(ax, ay, cpx, cpy)) addSegment(result, ax, ay, cpx, cpy);
            if (!equals(dpx, dpy, bx, by)) addSegment(result, dpx, dpy, bx, by);

        // a---dp---cp---b
        //     d----c
        } else {
            if (!equals(ax, ay, dpx, dpy)) addSegment(result, ax, ay, dpx, dpy);
            if (!equals(cpx, cpy, bx, by)) addSegment(result, cpx, cpy, bx, by);
        }

    } else if (cp !== null) {
        //     a----cp---b
        // d---ap---c
        if (ap !== null && !equals(ax, ay, cpx, cpy)) addSegment(result, cpx, cpy, bx, by);

        // a---cp---b
        //     c----bp---d
        else if (bp !== null && !equals(cpx, cpy, bx, by)) addSegment(result, ax, ay, cpx, cpy);

    } else if (dp !== null) {
        // a---dp---b
        //     d----bp---c
        if (bp !== null && !equals(dpx, dpy, bx, by)) addSegment(result, ax, ay, dpx, dpy);

        //     a----dp---b
        // c---ap---d
        else if (ap !== null && !equals(ax, ay, dpx, dpy)) addSegment(result, dpx, dpy, bx, by);
    }

    return result.length !== len; // segment processed
}
644341
def find_geo_coords(s):
    """"""
    coords = []
    LOG.debug("Matching in text size %s", len(s))
    for c in INFO_BOX_LAT_LON.findall(s):
        try:
            coord = (float(c[1]), float(c[2]))  #, c[0])
            coords.append(coord)
            LOG.debug("Found info box lat/lon: %s", coord)
        except Exception as ex:
            LOG.warn("Bad parse of info box %s: %s", c, ex)
    for c in COORDS_GEN.findall(s):
        # Special cases
        if skip_coords(c):
            LOG.debug("Ignorning coords %s", c)
            continue
        m = COORDS_GROUPS.search(c)
        if not m:
            LOG.warn("Unrecognized coord format: %s", c)
            continue
        try:
            # Remove empty optional groups and remove pipes from matches
            g = [(s[0:-1] if s[-1] == '|' else s) for s in list(m.groups()) if s is not None and len(s)]
            #LOG.info("Found groups: %s", g)
            if len(g) == 1: # Single lat|lon
                lat, lon = g[0].split('|')
                coord = (float(lat), float(lon))  #, c)
                coords.append(coord)
                LOG.debug("Found lat|lon: %s", coord)
            elif g[3] == 'E' or g[3] == 'W':
                lat = depipe(g[0]) * (1 if g[1].upper() == 'N' else -1)
                lon = depipe(g[2]) * (1 if g[3].upper() == 'E' else -1)
                coord = (lat, lon)  #, c)
                coords.append(coord)
                LOG.debug("Found lat|NS|lon|EW: %s", coord)
            else:
                LOG.warn("Unrecognized coord format: %s (parsed %s)", c, g)
        except Exception as ex:
            LOG.warn("Bad parse of %s: %s", c, ex)
    l = []
    for c in set(coords):  # Dedupe; the reality is non-trivial though...we want to keep only the most precise
        if c[0] > 90 or c[0] < -90 or c[1] > 180 or c[1] < -180 or (c[0] == 0 and c[1] == 0):
            LOG.warn("Invalid lat or lon: %s", c)
        else:
            l.append({"type": "Point", "coordinates": (c[1], c[0])})  # GeoJSON, lon goes first
    return l
385210
def _find_row_label_positions(self, match_value_or_fct, levels=None):
        """"""
        allmatches = find_locations(self.df.index, match_value_or_fct, levels)
        if allmatches and self.inc_index:  # tramslate back
            allmatches = [m + self.nhdrs for m in allmatches]
        return allmatches