Find the best similarity within known trigrams.
354601
def similarity(self, other: Trigram) -> float:
        
        return max((self._match(x, other) for x in self.trigrams), default=0)
261487
public function similarity(&$A, &$B)
    {
        $alpha = $this->alpha;
        $beta = $this->beta;

        $a = array_fill_keys($A,1);
        $b = array_fill_keys($B,1);

        $min = min(count(array_diff_key($a,$b)),count(array_diff_key($b, $a)));
        $max = max(count(array_diff_key($a,$b)),count(array_diff_key($b, $a)));

        $intersect = count(array_intersect_key($a,$b));

        return $intersect/($intersect + ($beta * ($alpha * $min + $max*(1-$alpha)) ));
    }
512699
def similarity_by_infocontent(sense1: "wn.Synset", sense2: "wn.Synset", option: str) -> float:
    

    if sense1.pos != sense2.pos: # infocontent sim can't do diff POS.
        return 0

    if option in ['res', 'resnik']:
        if sense1.pos not in wnic_bnc_resnik_add1.ic:
            return 0
        return wn.res_similarity(sense1, sense2, wnic_bnc_resnik_add1)
    #return min(wn.res_similarity(sense1, sense2, wnic.ic(ic)) \
    #             for ic in info_contents)

    elif option in ['jcn', "jiang-conrath"]:
        if sense1.pos not in wnic_bnc_add1.ic:
            return 0
        return wn.jcn_similarity(sense1, sense2, wnic_bnc_add1)

    elif option in ['lin']:
        if sense1.pos not in wnic_bnc_add1.ic:
            return 0
        return wn.lin_similarity(sense1, sense2, wnic_bnc_add1)
1095327
def matches_input(self, optimized_str):
        """"""

        if all([keyword in optimized_str for keyword in self['keywords']]):
            logger.debug('Matched template %s', self['template_name'])
            return True
1117817
def _match(self, local: Tuple[Trigram, ...], other: Trigram) -> float:
        

        pos = local[0] % other
        neg = max((x % other for x in local[1:]), default=0)

        if neg > pos:
            return 0.0

        return pos
1294966
def _get_comparison_strings(self, s):
        """"""
        str_len = len(s)
        comparison_idxs = make_unique_ngrams(s, self.idx_size)
        min_len = len(s) - self.plus_minus

        if min_len < 0:
            min_len = 0

        if self._els_idxed is None:
            raise UnintitializedError('Database not created')

        all_sets = set()
        for idx in comparison_idxs:
            found_idx = self._els_idxed.get(idx, None)
            if found_idx is None:
                continue
            for i in range(min_len, str_len + self.plus_minus):
                found_len = found_idx.get(i, None)
                if found_len is not None:
                    all_sets = all_sets.union(found_len)
        return all_sets
15440
def __similarity(s1, s2, ngrams_fn, n=3):
    
    ngrams1, ngrams2 = set(ngrams_fn(s1, n=n)), set(ngrams_fn(s2, n=n))
    matches = ngrams1.intersection(ngrams2)
    return 2 * len(matches) / (len(ngrams1) + len(ngrams2))
1239652
def find_near_matches_substitutions(subsequence, sequence, max_substitutions):
    
    _check_arguments(subsequence, sequence, max_substitutions)

    if max_substitutions == 0:
        return [
            Match(start_index, start_index + len(subsequence), 0)
            for start_index in search_exact(subsequence, sequence)
        ]

    elif len(subsequence) // (max_substitutions + 1) >= 3:
        return find_near_matches_substitutions_ngrams(
            subsequence, sequence, max_substitutions,
        )

    else:
        return find_near_matches_substitutions_lp(
            subsequence, sequence, max_substitutions,
        )
526959
def tril(P, k=0):
    """"""
    A = P.A.copy()
    for key in P.keys:
        A[key] = numpy.tril(P.A[key])
    return Poly(A, dim=P.dim, shape=P.shape)
1096678
void findHistogramPeaks() {
		// reset data structures
		peaks.reset();
		angles.reset();
		peakAngle = 0;

		// identify peaks and find the highest peak
		double largest = 0;
		int largestIndex = -1;
		double before = histogramMag[ histogramMag.length-2 ];
		double current = histogramMag[ histogramMag.length-1 ];
		for(int i = 0; i < histogramMag.length; i++ ) {
			double after = histogramMag[ i ];

			if( current > before && current > after ) {
				int currentIndex = CircularIndex.addOffset(i,-1,histogramMag.length);
				peaks.push(currentIndex);
				if( current > largest ) {
					largest = current;
					largestIndex = currentIndex;
				}
			}
			before = current;
			current = after;
		}

		if( largestIndex < 0 )
			return;

		// see if any of the other peaks are within 80% of the max peak
		double threshold = largest*0.8;
		for( int i = 0; i < peaks.size; i++ ) {
			int index = peaks.data[i];
			current = histogramMag[index];
			if( current >= threshold) {
				double angle = computeAngle(index);

				angles.push( angle );

				if( index == largestIndex )
					peakAngle = angle;
			}
		}
	}
209902
def get_closest(word, possibilities, cutoff=0.6, fallback_to_first=True):
    """"""
    possibilities = list(possibilities)
    try:
        return difflib_get_close_matches(word, possibilities, 1, cutoff)[0]
    except IndexError:
        if fallback_to_first:
            return possibilities[0]
42389
def cosine_similarity(sent1: str, sent2: str) -> float:
    

    WORD = re.compile(r'\w+')
    def get_cosine(vec1, vec2):
        intersection = set(vec1.keys()) & set(vec2.keys())
        numerator = sum([vec1[x] * vec2[x] for x in intersection])

        sum1 = sum([vec1[x]**2 for x in vec1.keys()])
        sum2 = sum([vec2[x]**2 for x in vec2.keys()])
        denominator = math.sqrt(sum1) * math.sqrt(sum2)

        if not denominator:
            return 0.0
        else:
            return float(numerator) / denominator

    def text_to_vector(text):
        words = WORD.findall(text)
        return Counter(words)

    vector1 = text_to_vector(sent1)
    vector2 = text_to_vector(sent2)
    cosine = get_cosine(vector1, vector2)

    return cosine
499558
def findByBiSearch(self, strSeq) :
		""""""
		arr = self.encode(strSeq)
		return self._dichFind(arr[0], self, 0, lst = None)
5918
def findSynonyms(self, word, num):
        
        if not isinstance(word, basestring):
            word = _convert_to_vector(word)
        words, similarity = self.call("findSynonyms", word, num)
        return zip(words, similarity)
1128731
function _bestMagicWordsMatch(wishesMagicWords, givenMagicWord) {
  const bestMatch = {
    matchType: _matchRankMap.noMatch,
    magicWordIndex: -1,
  }
  _each(wishesMagicWords, (wishesMagicWord, index) => {
    const matchRank = _stringsMatch(wishesMagicWord, givenMagicWord)
    if (matchRank > bestMatch.matchType) {
      bestMatch.matchType = matchRank
      bestMatch.magicWordIndex = index
    }
    return bestMatch.matchType !== _matchRankMap.equals
  })
  return bestMatch
}
299129
def word_matches(s1, s2, n=3):
    
    return __matches(s1, s2, word_ngrams, n=n)
321926
function reorderFinderPatterns(pattern1, pattern2, pattern3) {
        // Find distances between pattern centers
        const oneTwoDistance = distance(pattern1, pattern2);
        const twoThreeDistance = distance(pattern2, pattern3);
        const oneThreeDistance = distance(pattern1, pattern3);
        let bottomLeft;
        let topLeft;
        let topRight;
        // Assume one closest to other two is B; A and C will just be guesses at first
        if (twoThreeDistance >= oneTwoDistance && twoThreeDistance >= oneThreeDistance) {
            [bottomLeft, topLeft, topRight] = [pattern2, pattern1, pattern3];
        }
        else if (oneThreeDistance >= twoThreeDistance && oneThreeDistance >= oneTwoDistance) {
            [bottomLeft, topLeft, topRight] = [pattern1, pattern2, pattern3];
        }
        else {
            [bottomLeft, topLeft, topRight] = [pattern1, pattern3, pattern2];
        }
        // Use cross product to figure out whether bottomLeft (A) and topRight (C) are correct or flipped in relation to topLeft (B)
        // This asks whether BC x BA has a positive z component, which is the arrangement we want. If it's negative, then
        // we've got it flipped around and should swap topRight and bottomLeft.
        if (((topRight.x - topLeft.x) * (bottomLeft.y - topLeft.y)) - ((topRight.y - topLeft.y) * (bottomLeft.x - topLeft.x)) < 0) {
            [bottomLeft, topRight] = [topRight, bottomLeft];
        }
        return { bottomLeft, topLeft, topRight };
    }