_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q258200
sim_manhattan
validation
def sim_manhattan(src, tar, qval=2, alphabet=None): """Return the normalized Manhattan similarity of two strings. This is a wrapper for :py:meth:`Manhattan.sim`. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison qval : int The length of each q-gram; 0 for non-q-gram version alphabet : collection or int The values or size of the alphabet Returns ------- float The normalized Manhattan similarity Examples -------- >>> sim_manhattan('cat', 'hat') 0.5 >>> round(sim_manhattan('Niall', 'Neil'), 12) 0.363636363636 >>> round(sim_manhattan('Colin', 'Cuilen'), 12) 0.307692307692 >>> sim_manhattan('ATCG', 'TAGC') 0.0 """ return Manhattan().sim(src, tar, qval, alphabet)
python
{ "resource": "" }
q258201
dist_jaro_winkler
validation
def dist_jaro_winkler( src, tar, qval=1, mode='winkler', long_strings=False, boost_threshold=0.7, scaling_factor=0.1, ): """Return the Jaro or Jaro-Winkler distance between two strings. This is a wrapper for :py:meth:`JaroWinkler.dist`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison qval : int The length of each q-gram (defaults to 1: character-wise matching) mode : str Indicates which variant of this distance metric to compute: - ``winkler`` -- computes the Jaro-Winkler distance (default) which increases the score for matches near the start of the word - ``jaro`` -- computes the Jaro distance long_strings : bool Set to True to "Increase the probability of a match when the number of matched characters is large. This option allows for a little more tolerance when the strings are large. It is not an appropriate test when comparing fixedlength fields such as phone and social security numbers." (Used in 'winkler' mode only.) boost_threshold : float A value between 0 and 1, below which the Winkler boost is not applied (defaults to 0.7). (Used in 'winkler' mode only.) scaling_factor : float A value between 0 and 0.25, indicating by how much to boost scores for matching prefixes (defaults to 0.1). (Used in 'winkler' mode only.) Returns ------- float Jaro or Jaro-Winkler distance Examples -------- >>> round(dist_jaro_winkler('cat', 'hat'), 12) 0.222222222222 >>> round(dist_jaro_winkler('Niall', 'Neil'), 12) 0.195 >>> round(dist_jaro_winkler('aluminum', 'Catalan'), 12) 0.39880952381 >>> round(dist_jaro_winkler('ATCG', 'TAGC'), 12) 0.166666666667 >>> round(dist_jaro_winkler('cat', 'hat', mode='jaro'), 12) 0.222222222222 >>> round(dist_jaro_winkler('Niall', 'Neil', mode='jaro'), 12) 0.216666666667 >>> round(dist_jaro_winkler('aluminum', 'Catalan', mode='jaro'), 12) 0.39880952381 >>> round(dist_jaro_winkler('ATCG', 'TAGC', mode='jaro'), 12) 0.166666666667 """ return JaroWinkler().dist( src, tar, qval, mode, long_strings, boost_threshold, scaling_factor )
python
{ "resource": "" }
q258202
sim_hamming
validation
def sim_hamming(src, tar, diff_lens=True): """Return the normalized Hamming similarity of two strings. This is a wrapper for :py:meth:`Hamming.sim`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison diff_lens : bool If True (default), this returns the Hamming distance for those characters that have a matching character in both strings plus the difference in the strings' lengths. This is equivalent to extending the shorter string with obligatorily non-matching characters. If False, an exception is raised in the case of strings of unequal lengths. Returns ------- float The normalized Hamming similarity Examples -------- >>> round(sim_hamming('cat', 'hat'), 12) 0.666666666667 >>> sim_hamming('Niall', 'Neil') 0.4 >>> sim_hamming('aluminum', 'Catalan') 0.0 >>> sim_hamming('ATCG', 'TAGC') 0.0 """ return Hamming().sim(src, tar, diff_lens)
python
{ "resource": "" }
q258203
SkeletonKey.fingerprint
validation
def fingerprint(self, word): """Return the skeleton key. Parameters ---------- word : str The word to transform into its skeleton key Returns ------- str The skeleton key Examples -------- >>> sk = SkeletonKey() >>> sk.fingerprint('The quick brown fox jumped over the lazy dog.') 'THQCKBRWNFXJMPDVLZYGEUIOA' >>> sk.fingerprint('Christopher') 'CHRSTPIOE' >>> sk.fingerprint('Niall') 'NLIA' """ word = unicode_normalize('NFKD', text_type(word.upper())) word = ''.join(c for c in word if c in self._letters) start = word[0:1] consonant_part = '' vowel_part = '' # add consonants & vowels to to separate strings # (omitting the first char & duplicates) for char in word[1:]: if char != start: if char in self._vowels: if char not in vowel_part: vowel_part += char elif char not in consonant_part: consonant_part += char # return the first char followed by consonants followed by vowels return start + consonant_part + vowel_part
python
{ "resource": "" }
q258204
mean_pairwise_similarity
validation
def mean_pairwise_similarity( collection, metric=sim, mean_func=hmean, symmetric=False ): """Calculate the mean pairwise similarity of a collection of strings. Takes the mean of the pairwise similarity between each member of a collection, optionally in both directions (for asymmetric similarity metrics. Parameters ---------- collection : list A collection of terms or a string that can be split metric : function A similarity metric function mean_func : function A mean function that takes a list of values and returns a float symmetric : bool Set to True if all pairwise similarities should be calculated in both directions Returns ------- float The mean pairwise similarity of a collection of strings Raises ------ ValueError mean_func must be a function ValueError metric must be a function ValueError collection is neither a string nor iterable type ValueError collection has fewer than two members Examples -------- >>> round(mean_pairwise_similarity(['Christopher', 'Kristof', ... 'Christobal']), 12) 0.519801980198 >>> round(mean_pairwise_similarity(['Niall', 'Neal', 'Neil']), 12) 0.545454545455 """ if not callable(mean_func): raise ValueError('mean_func must be a function') if not callable(metric): raise ValueError('metric must be a function') if hasattr(collection, 'split'): collection = collection.split() if not hasattr(collection, '__iter__'): raise ValueError('collection is neither a string nor iterable type') elif len(collection) < 2: raise ValueError('collection has fewer than two members') collection = list(collection) pairwise_values = [] for i in range(len(collection)): for j in range(i + 1, len(collection)): pairwise_values.append(metric(collection[i], collection[j])) if symmetric: pairwise_values.append(metric(collection[j], collection[i])) return mean_func(pairwise_values)
python
{ "resource": "" }
q258205
pairwise_similarity_statistics
validation
def pairwise_similarity_statistics( src_collection, tar_collection, metric=sim, mean_func=amean, symmetric=False, ): """Calculate the pairwise similarity statistics a collection of strings. Calculate pairwise similarities among members of two collections, returning the maximum, minimum, mean (according to a supplied function, arithmetic mean, by default), and (population) standard deviation of those similarities. Parameters ---------- src_collection : list A collection of terms or a string that can be split tar_collection : list A collection of terms or a string that can be split metric : function A similarity metric function mean_func : function A mean function that takes a list of values and returns a float symmetric : bool Set to True if all pairwise similarities should be calculated in both directions Returns ------- tuple The max, min, mean, and standard deviation of similarities Raises ------ ValueError mean_func must be a function ValueError metric must be a function ValueError src_collection is neither a string nor iterable ValueError tar_collection is neither a string nor iterable Example ------- >>> tuple(round(_, 12) for _ in pairwise_similarity_statistics( ... ['Christopher', 'Kristof', 'Christobal'], ['Niall', 'Neal', 'Neil'])) (0.2, 0.0, 0.118614718615, 0.075070477184) """ if not callable(mean_func): raise ValueError('mean_func must be a function') if not callable(metric): raise ValueError('metric must be a function') if hasattr(src_collection, 'split'): src_collection = src_collection.split() if not hasattr(src_collection, '__iter__'): raise ValueError('src_collection is neither a string nor iterable') if hasattr(tar_collection, 'split'): tar_collection = tar_collection.split() if not hasattr(tar_collection, '__iter__'): raise ValueError('tar_collection is neither a string nor iterable') src_collection = list(src_collection) tar_collection = list(tar_collection) pairwise_values = [] for src in src_collection: for tar in tar_collection: pairwise_values.append(metric(src, tar)) if symmetric: pairwise_values.append(metric(tar, src)) return ( max(pairwise_values), min(pairwise_values), mean_func(pairwise_values), std(pairwise_values, mean_func, 0), )
python
{ "resource": "" }
q258206
_Snowball._sb_r1
validation
def _sb_r1(self, term, r1_prefixes=None): """Return the R1 region, as defined in the Porter2 specification. Parameters ---------- term : str The term to examine r1_prefixes : set Prefixes to consider Returns ------- int Length of the R1 region """ vowel_found = False if hasattr(r1_prefixes, '__iter__'): for prefix in r1_prefixes: if term[: len(prefix)] == prefix: return len(prefix) for i in range(len(term)): if not vowel_found and term[i] in self._vowels: vowel_found = True elif vowel_found and term[i] not in self._vowels: return i + 1 return len(term)
python
{ "resource": "" }
q258207
_Snowball._sb_r2
validation
def _sb_r2(self, term, r1_prefixes=None): """Return the R2 region, as defined in the Porter2 specification. Parameters ---------- term : str The term to examine r1_prefixes : set Prefixes to consider Returns ------- int Length of the R1 region """ r1_start = self._sb_r1(term, r1_prefixes) return r1_start + self._sb_r1(term[r1_start:])
python
{ "resource": "" }
q258208
_Snowball._sb_ends_in_short_syllable
validation
def _sb_ends_in_short_syllable(self, term): """Return True iff term ends in a short syllable. (...according to the Porter2 specification.) NB: This is akin to the CVC test from the Porter stemmer. The description is unfortunately poor/ambiguous. Parameters ---------- term : str The term to examine Returns ------- bool True iff term ends in a short syllable """ if not term: return False if len(term) == 2: if term[-2] in self._vowels and term[-1] not in self._vowels: return True elif len(term) >= 3: if ( term[-3] not in self._vowels and term[-2] in self._vowels and term[-1] in self._codanonvowels ): return True return False
python
{ "resource": "" }
q258209
_Snowball._sb_short_word
validation
def _sb_short_word(self, term, r1_prefixes=None): """Return True iff term is a short word. (...according to the Porter2 specification.) Parameters ---------- term : str The term to examine r1_prefixes : set Prefixes to consider Returns ------- bool True iff term is a short word """ if self._sb_r1(term, r1_prefixes) == len( term ) and self._sb_ends_in_short_syllable(term): return True return False
python
{ "resource": "" }
q258210
_Snowball._sb_has_vowel
validation
def _sb_has_vowel(self, term): """Return Porter helper function _sb_has_vowel value. Parameters ---------- term : str The term to examine Returns ------- bool True iff a vowel exists in the term (as defined in the Porter stemmer definition) """ for letter in term: if letter in self._vowels: return True return False
python
{ "resource": "" }
q258211
Eudex.encode
validation
def encode(self, word, max_length=8): """Return the eudex phonetic hash of a word. Parameters ---------- word : str The word to transform max_length : int The length in bits of the code returned (default 8) Returns ------- int The eudex hash Examples -------- >>> pe = Eudex() >>> pe.encode('Colin') 432345564238053650 >>> pe.encode('Christopher') 433648490138894409 >>> pe.encode('Niall') 648518346341351840 >>> pe.encode('Smith') 720575940412906756 >>> pe.encode('Schmidt') 720589151732307997 """ # Lowercase input & filter unknown characters word = ''.join( char for char in word.lower() if char in self._initial_phones ) if not word: word = '÷' # Perform initial eudex coding of each character values = [self._initial_phones[word[0]]] values += [self._trailing_phones[char] for char in word[1:]] # Right-shift by one to determine if second instance should be skipped shifted_values = [_ >> 1 for _ in values] condensed_values = [values[0]] for n in range(1, len(shifted_values)): if shifted_values[n] != shifted_values[n - 1]: condensed_values.append(values[n]) # Add padding after first character & trim beyond max_length values = ( [condensed_values[0]] + [0] * max(0, max_length - len(condensed_values)) + condensed_values[1:max_length] ) # Combine individual character values into eudex hash hash_value = 0 for val in values: hash_value = (hash_value << 8) | val return hash_value
python
{ "resource": "" }
q258212
_TokenDistance._get_qgrams
validation
def _get_qgrams(self, src, tar, qval=0, skip=0): """Return the Q-Grams in src & tar. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison qval : int The length of each q-gram; 0 for non-q-gram version skip : int The number of characters to skip (only works when src and tar are strings) Returns ------- tuple of Counters Q-Grams Examples -------- >>> pe = _TokenDistance() >>> pe._get_qgrams('AT', 'TT', qval=2) (QGrams({'$A': 1, 'AT': 1, 'T#': 1}), QGrams({'$T': 1, 'TT': 1, 'T#': 1})) """ if isinstance(src, Counter) and isinstance(tar, Counter): return src, tar if qval > 0: return QGrams(src, qval, '$#', skip), QGrams(tar, qval, '$#', skip) return Counter(src.strip().split()), Counter(tar.strip().split())
python
{ "resource": "" }
q258213
NCDlzma.dist
validation
def dist(self, src, tar): """Return the NCD between two strings using LZMA compression. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison Returns ------- float Compression distance Raises ------ ValueError Install the PylibLZMA module in order to use LZMA Examples -------- >>> cmp = NCDlzma() >>> cmp.dist('cat', 'hat') 0.08695652173913043 >>> cmp.dist('Niall', 'Neil') 0.16 >>> cmp.dist('aluminum', 'Catalan') 0.16 >>> cmp.dist('ATCG', 'TAGC') 0.08695652173913043 """ if src == tar: return 0.0 src = src.encode('utf-8') tar = tar.encode('utf-8') if lzma is not None: src_comp = lzma.compress(src)[14:] tar_comp = lzma.compress(tar)[14:] concat_comp = lzma.compress(src + tar)[14:] concat_comp2 = lzma.compress(tar + src)[14:] else: # pragma: no cover raise ValueError( 'Install the PylibLZMA module in order to use LZMA' ) return ( min(len(concat_comp), len(concat_comp2)) - min(len(src_comp), len(tar_comp)) ) / max(len(src_comp), len(tar_comp))
python
{ "resource": "" }
q258214
sim_levenshtein
validation
def sim_levenshtein(src, tar, mode='lev', cost=(1, 1, 1, 1)): """Return the Levenshtein similarity of two strings. This is a wrapper of :py:meth:`Levenshtein.sim`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison mode : str Specifies a mode for computing the Levenshtein distance: - ``lev`` (default) computes the ordinary Levenshtein distance, in which edits may include inserts, deletes, and substitutions - ``osa`` computes the Optimal String Alignment distance, in which edits may include inserts, deletes, substitutions, and transpositions but substrings may only be edited once cost : tuple A 4-tuple representing the cost of the four possible edits: inserts, deletes, substitutions, and transpositions, respectively (by default: (1, 1, 1, 1)) Returns ------- float The Levenshtein similarity between src & tar Examples -------- >>> round(sim_levenshtein('cat', 'hat'), 12) 0.666666666667 >>> round(sim_levenshtein('Niall', 'Neil'), 12) 0.4 >>> sim_levenshtein('aluminum', 'Catalan') 0.125 >>> sim_levenshtein('ATCG', 'TAGC') 0.25 """ return Levenshtein().sim(src, tar, mode, cost)
python
{ "resource": "" }
q258215
OmissionKey.fingerprint
validation
def fingerprint(self, word): """Return the omission key. Parameters ---------- word : str The word to transform into its omission key Returns ------- str The omission key Examples -------- >>> ok = OmissionKey() >>> ok.fingerprint('The quick brown fox jumped over the lazy dog.') 'JKQXZVWYBFMGPDHCLNTREUIOA' >>> ok.fingerprint('Christopher') 'PHCTSRIOE' >>> ok.fingerprint('Niall') 'LNIA' """ word = unicode_normalize('NFKD', text_type(word.upper())) word = ''.join(c for c in word if c in self._letters) key = '' # add consonants in order supplied by _consonants (no duplicates) for char in self._consonants: if char in word: key += char # add vowels in order they appeared in the word (no duplicates) for char in word: if char not in self._consonants and char not in key: key += char return key
python
{ "resource": "" }
q258216
sim_minkowski
validation
def sim_minkowski(src, tar, qval=2, pval=1, alphabet=None): """Return normalized Minkowski similarity of two strings. This is a wrapper for :py:meth:`Minkowski.sim`. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison qval : int The length of each q-gram; 0 for non-q-gram version pval : int or float The :math:`p`-value of the :math:`L^p`-space alphabet : collection or int The values or size of the alphabet Returns ------- float The normalized Minkowski similarity Examples -------- >>> sim_minkowski('cat', 'hat') 0.5 >>> round(sim_minkowski('Niall', 'Neil'), 12) 0.363636363636 >>> round(sim_minkowski('Colin', 'Cuilen'), 12) 0.307692307692 >>> sim_minkowski('ATCG', 'TAGC') 0.0 """ return Minkowski().sim(src, tar, qval, pval, alphabet)
python
{ "resource": "" }
q258217
Cosine.sim
validation
def sim(self, src, tar, qval=2): r"""Return the cosine similarity of two strings. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison qval : int The length of each q-gram; 0 for non-q-gram version Returns ------- float Cosine similarity Examples -------- >>> cmp = Cosine() >>> cmp.sim('cat', 'hat') 0.5 >>> cmp.sim('Niall', 'Neil') 0.3651483716701107 >>> cmp.sim('aluminum', 'Catalan') 0.11785113019775793 >>> cmp.sim('ATCG', 'TAGC') 0.0 """ if src == tar: return 1.0 if not src or not tar: return 0.0 q_src, q_tar = self._get_qgrams(src, tar, qval) q_src_mag = sum(q_src.values()) q_tar_mag = sum(q_tar.values()) q_intersection_mag = sum((q_src & q_tar).values()) return q_intersection_mag / sqrt(q_src_mag * q_tar_mag)
python
{ "resource": "" }
q258218
dist_monge_elkan
validation
def dist_monge_elkan(src, tar, sim_func=sim_levenshtein, symmetric=False): """Return the Monge-Elkan distance between two strings. This is a wrapper for :py:meth:`MongeElkan.dist`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison sim_func : function The internal similarity metric to employ symmetric : bool Return a symmetric similarity measure Returns ------- float Monge-Elkan distance Examples -------- >>> dist_monge_elkan('cat', 'hat') 0.25 >>> round(dist_monge_elkan('Niall', 'Neil'), 12) 0.333333333333 >>> round(dist_monge_elkan('aluminum', 'Catalan'), 12) 0.611111111111 >>> dist_monge_elkan('ATCG', 'TAGC') 0.5 """ return MongeElkan().dist(src, tar, sim_func, symmetric)
python
{ "resource": "" }
q258219
Phonem.encode
validation
def encode(self, word): """Return the Phonem code for a word. Parameters ---------- word : str The word to transform Returns ------- str The Phonem value Examples -------- >>> pe = Phonem() >>> pe.encode('Christopher') 'CRYSDOVR' >>> pe.encode('Niall') 'NYAL' >>> pe.encode('Smith') 'SMYD' >>> pe.encode('Schmidt') 'CMYD' """ word = unicode_normalize('NFC', text_type(word.upper())) for i, j in self._substitutions: word = word.replace(i, j) word = word.translate(self._trans) return ''.join( c for c in self._delete_consecutive_repeats(word) if c in self._uc_set )
python
{ "resource": "" }
q258220
CLEFSwedish.stem
validation
def stem(self, word): """Return CLEF Swedish stem. Parameters ---------- word : str The word to stem Returns ------- str Word stem Examples -------- >>> clef_swedish('undervisa') 'undervis' >>> clef_swedish('suspension') 'suspensio' >>> clef_swedish('visshet') 'viss' """ wlen = len(word) - 2 if wlen > 2 and word[-1] == 's': word = word[:-1] wlen -= 1 _endings = { 5: {'elser', 'heten'}, 4: {'arne', 'erna', 'ande', 'else', 'aste', 'orna', 'aren'}, 3: {'are', 'ast', 'het'}, 2: {'ar', 'er', 'or', 'en', 'at', 'te', 'et'}, 1: {'a', 'e', 'n', 't'}, } for end_len in range(5, 0, -1): if wlen > end_len and word[-end_len:] in _endings[end_len]: return word[:-end_len] return word
python
{ "resource": "" }
q258221
SnowballDutch._undouble
validation
def _undouble(self, word): """Undouble endings -kk, -dd, and -tt. Parameters ---------- word : str The word to stem Returns ------- str The word with doubled endings undoubled """ if ( len(word) > 1 and word[-1] == word[-2] and word[-1] in {'d', 'k', 't'} ): return word[:-1] return word
python
{ "resource": "" }
q258222
String.fingerprint
validation
def fingerprint(self, phrase, joiner=' '): """Return string fingerprint. Parameters ---------- phrase : str The string from which to calculate the fingerprint joiner : str The string that will be placed between each word Returns ------- str The fingerprint of the phrase Example ------- >>> sf = String() >>> sf.fingerprint('The quick brown fox jumped over the lazy dog.') 'brown dog fox jumped lazy over quick the' """ phrase = unicode_normalize('NFKD', text_type(phrase.strip().lower())) phrase = ''.join([c for c in phrase if c.isalnum() or c.isspace()]) phrase = joiner.join(sorted(list(set(phrase.split())))) return phrase
python
{ "resource": "" }
q258223
ipa_to_features
validation
def ipa_to_features(ipa): """Convert IPA to features. This translates an IPA string of one or more phones to a list of ints representing the features of the string. Parameters ---------- ipa : str The IPA representation of a phone or series of phones Returns ------- list of ints A representation of the features of the input string Examples -------- >>> ipa_to_features('mut') [2709662981243185770, 1825831513894594986, 2783230754502126250] >>> ipa_to_features('fon') [2781702983095331242, 1825831531074464170, 2711173160463936106] >>> ipa_to_features('telz') [2783230754502126250, 1826957430176000426, 2693158761954453926, 2783230754501863834] """ features = [] pos = 0 ipa = normalize('NFD', text_type(ipa.lower())) maxsymlen = max(len(_) for _ in _PHONETIC_FEATURES) while pos < len(ipa): found_match = False for i in range(maxsymlen, 0, -1): if ( pos + i - 1 <= len(ipa) and ipa[pos : pos + i] in _PHONETIC_FEATURES ): features.append(_PHONETIC_FEATURES[ipa[pos : pos + i]]) pos += i found_match = True if not found_match: features.append(-1) pos += 1 return features
python
{ "resource": "" }
q258224
get_feature
validation
def get_feature(vector, feature): """Get a feature vector. This returns a list of ints, equal in length to the vector input, representing presence/absence/neutrality with respect to a particular phonetic feature. Parameters ---------- vector : list A tuple or list of ints representing the phonetic features of a phone or series of phones (such as is returned by the ipa_to_features function) feature : str A feature name from the set: - ``consonantal`` - ``sonorant`` - ``syllabic`` - ``labial`` - ``round`` - ``coronal`` - ``anterior`` - ``distributed`` - ``dorsal`` - ``high`` - ``low`` - ``back`` - ``tense`` - ``pharyngeal`` - ``ATR`` - ``voice`` - ``spread_glottis`` - ``constricted_glottis`` - ``continuant`` - ``strident`` - ``lateral`` - ``delayed_release`` - ``nasal`` Returns ------- list of ints A list indicating presence/absence/neutrality with respect to the feature Raises ------ AttributeError feature must be one of ... Examples -------- >>> tails = ipa_to_features('telz') >>> get_feature(tails, 'consonantal') [1, -1, 1, 1] >>> get_feature(tails, 'sonorant') [-1, 1, 1, -1] >>> get_feature(tails, 'nasal') [-1, -1, -1, -1] >>> get_feature(tails, 'coronal') [1, -1, 1, 1] """ # :param bool binary: if False, -1, 0, & 1 represent -, 0, & + # if True, only binary oppositions are allowed: # 0 & 1 represent - & + and 0s are mapped to - if feature not in _FEATURE_MASK: raise AttributeError( "feature must be one of: '" + "', '".join( ( 'consonantal', 'sonorant', 'syllabic', 'labial', 'round', 'coronal', 'anterior', 'distributed', 'dorsal', 'high', 'low', 'back', 'tense', 'pharyngeal', 'ATR', 'voice', 'spread_glottis', 'constricted_glottis', 'continuant', 'strident', 'lateral', 'delayed_release', 'nasal', ) ) + "'" ) # each feature mask contains two bits, one each for - and + mask = _FEATURE_MASK[feature] # the lower bit represents + pos_mask = mask >> 1 retvec = [] for char in vector: if char < 0: retvec.append(float('NaN')) else: masked = char & mask if masked == 0: retvec.append(0) # 0 elif masked == mask: retvec.append(2) # +/- elif masked & pos_mask: retvec.append(1) # + else: retvec.append(-1) # - return retvec
python
{ "resource": "" }
q258225
cmp_features
validation
def cmp_features(feat1, feat2): """Compare features. This returns a number in the range [0, 1] representing a comparison of two feature bundles. If one of the bundles is negative, -1 is returned (for unknown values) If the bundles are identical, 1 is returned. If they are inverses of one another, 0 is returned. Otherwise, a float representing their similarity is returned. Parameters ---------- feat1 : int A feature bundle feat2 : int A feature bundle Returns ------- float A comparison of the feature bundles Examples -------- >>> cmp_features(ipa_to_features('l')[0], ipa_to_features('l')[0]) 1.0 >>> cmp_features(ipa_to_features('l')[0], ipa_to_features('n')[0]) 0.8709677419354839 >>> cmp_features(ipa_to_features('l')[0], ipa_to_features('z')[0]) 0.8709677419354839 >>> cmp_features(ipa_to_features('l')[0], ipa_to_features('i')[0]) 0.564516129032258 """ if feat1 < 0 or feat2 < 0: return -1.0 if feat1 == feat2: return 1.0 magnitude = len(_FEATURE_MASK) featxor = feat1 ^ feat2 diffbits = 0 # print(featxor) while featxor: if featxor & 0b1: diffbits += 1 featxor >>= 1 # print(diffbits) return 1 - (diffbits / (2 * magnitude))
python
{ "resource": "" }
q258226
Length.sim
validation
def sim(self, src, tar): """Return the length similarity of two strings. Length similarity is the ratio of the length of the shorter string to the longer. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison Returns ------- float Length similarity Examples -------- >>> cmp = Length() >>> cmp.sim('cat', 'hat') 1.0 >>> cmp.sim('Niall', 'Neil') 0.8 >>> cmp.sim('aluminum', 'Catalan') 0.875 >>> cmp.sim('ATCG', 'TAGC') 1.0 """ if src == tar: return 1.0 if not src or not tar: return 0.0 return ( len(src) / len(tar) if len(src) < len(tar) else len(tar) / len(src) )
python
{ "resource": "" }
q258227
hmean
validation
def hmean(nums): r"""Return harmonic mean. The harmonic mean is defined as: :math:`\frac{|nums|}{\sum\limits_{i}\frac{1}{nums_i}}` Following the behavior of Wolfram|Alpha: - If one of the values in nums is 0, return 0. - If more than one value in nums is 0, return NaN. Cf. https://en.wikipedia.org/wiki/Harmonic_mean Parameters ---------- nums : list A series of numbers Returns ------- float The harmonic mean of nums Raises ------ AttributeError hmean requires at least one value Examples -------- >>> hmean([1, 2, 3, 4]) 1.9200000000000004 >>> hmean([1, 2]) 1.3333333333333333 >>> hmean([0, 5, 1000]) 0 """ if len(nums) < 1: raise AttributeError('hmean requires at least one value') elif len(nums) == 1: return nums[0] else: for i in range(1, len(nums)): if nums[0] != nums[i]: break else: return nums[0] if 0 in nums: if nums.count(0) > 1: return float('nan') return 0 return len(nums) / sum(1 / i for i in nums)
python
{ "resource": "" }
q258228
lmean
validation
def lmean(nums): r"""Return logarithmic mean. The logarithmic mean of an arbitrarily long series is defined by http://www.survo.fi/papers/logmean.pdf as: :math:`L(x_1, x_2, ..., x_n) = (n-1)! \sum\limits_{i=1}^n \frac{x_i} {\prod\limits_{\substack{j = 1\\j \ne i}}^n ln \frac{x_i}{x_j}}` Cf. https://en.wikipedia.org/wiki/Logarithmic_mean Parameters ---------- nums : list A series of numbers Returns ------- float The logarithmic mean of nums Raises ------ AttributeError No two values in the nums list may be equal Examples -------- >>> lmean([1, 2, 3, 4]) 2.2724242417489258 >>> lmean([1, 2]) 1.4426950408889634 """ if len(nums) != len(set(nums)): raise AttributeError('No two values in the nums list may be equal') rolling_sum = 0 for i in range(len(nums)): rolling_prod = 1 for j in range(len(nums)): if i != j: rolling_prod *= math.log(nums[i] / nums[j]) rolling_sum += nums[i] / rolling_prod return math.factorial(len(nums) - 1) * rolling_sum
python
{ "resource": "" }
q258229
seiffert_mean
validation
def seiffert_mean(nums): r"""Return Seiffert's mean. Seiffert's mean of two numbers x and y is: :math:`\frac{x - y}{4 \cdot arctan \sqrt{\frac{x}{y}} - \pi}` It is defined in :cite:`Seiffert:1993`. Parameters ---------- nums : list A series of numbers Returns ------- float Sieffert's mean of nums Raises ------ AttributeError seiffert_mean supports no more than two values Examples -------- >>> seiffert_mean([1, 2]) 1.4712939827611637 >>> seiffert_mean([1, 0]) 0.3183098861837907 >>> seiffert_mean([2, 4]) 2.9425879655223275 >>> seiffert_mean([2, 1000]) 336.84053300118825 """ if len(nums) == 1: return nums[0] if len(nums) > 2: raise AttributeError('seiffert_mean supports no more than two values') if nums[0] + nums[1] == 0 or nums[0] - nums[1] == 0: return float('NaN') return (nums[0] - nums[1]) / ( 2 * math.asin((nums[0] - nums[1]) / (nums[0] + nums[1])) )
python
{ "resource": "" }
q258230
lehmer_mean
validation
def lehmer_mean(nums, exp=2): r"""Return Lehmer mean. The Lehmer mean is: :math:`\frac{\sum\limits_i{x_i^p}}{\sum\limits_i{x_i^(p-1)}}` Cf. https://en.wikipedia.org/wiki/Lehmer_mean Parameters ---------- nums : list A series of numbers exp : numeric The exponent of the Lehmer mean Returns ------- float The Lehmer mean of nums for the given exponent Examples -------- >>> lehmer_mean([1, 2, 3, 4]) 3.0 >>> lehmer_mean([1, 2]) 1.6666666666666667 >>> lehmer_mean([0, 5, 1000]) 995.0497512437811 """ return sum(x ** exp for x in nums) / sum(x ** (exp - 1) for x in nums)
python
{ "resource": "" }
q258231
heronian_mean
validation
def heronian_mean(nums): r"""Return Heronian mean. The Heronian mean is: :math:`\frac{\sum\limits_{i, j}\sqrt{{x_i \cdot x_j}}} {|nums| \cdot \frac{|nums| + 1}{2}}` for :math:`j \ge i` Cf. https://en.wikipedia.org/wiki/Heronian_mean Parameters ---------- nums : list A series of numbers Returns ------- float The Heronian mean of nums Examples -------- >>> heronian_mean([1, 2, 3, 4]) 2.3888282852609093 >>> heronian_mean([1, 2]) 1.4714045207910316 >>> heronian_mean([0, 5, 1000]) 179.28511301977582 """ mag = len(nums) rolling_sum = 0 for i in range(mag): for j in range(i, mag): if nums[i] == nums[j]: rolling_sum += nums[i] else: rolling_sum += (nums[i] * nums[j]) ** 0.5 return rolling_sum * 2 / (mag * (mag + 1))
python
{ "resource": "" }
q258232
agmean
validation
def agmean(nums): """Return arithmetic-geometric mean. Iterates between arithmetic & geometric means until they converge to a single value (rounded to 12 digits). Cf. https://en.wikipedia.org/wiki/Arithmetic-geometric_mean Parameters ---------- nums : list A series of numbers Returns ------- float The arithmetic-geometric mean of nums Examples -------- >>> agmean([1, 2, 3, 4]) 2.3545004777751077 >>> agmean([1, 2]) 1.4567910310469068 >>> agmean([0, 5, 1000]) 2.9753977059954195e-13 """ m_a = amean(nums) m_g = gmean(nums) if math.isnan(m_a) or math.isnan(m_g): return float('nan') while round(m_a, 12) != round(m_g, 12): m_a, m_g = (m_a + m_g) / 2, (m_a * m_g) ** (1 / 2) return m_a
python
{ "resource": "" }
q258233
ghmean
validation
def ghmean(nums): """Return geometric-harmonic mean. Iterates between geometric & harmonic means until they converge to a single value (rounded to 12 digits). Cf. https://en.wikipedia.org/wiki/Geometric-harmonic_mean Parameters ---------- nums : list A series of numbers Returns ------- float The geometric-harmonic mean of nums Examples -------- >>> ghmean([1, 2, 3, 4]) 2.058868154613003 >>> ghmean([1, 2]) 1.3728805006183502 >>> ghmean([0, 5, 1000]) 0.0 >>> ghmean([0, 0]) 0.0 >>> ghmean([0, 0, 5]) nan """ m_g = gmean(nums) m_h = hmean(nums) if math.isnan(m_g) or math.isnan(m_h): return float('nan') while round(m_h, 12) != round(m_g, 12): m_g, m_h = (m_g * m_h) ** (1 / 2), (2 * m_g * m_h) / (m_g + m_h) return m_g
python
{ "resource": "" }
q258234
aghmean
validation
def aghmean(nums): """Return arithmetic-geometric-harmonic mean. Iterates over arithmetic, geometric, & harmonic means until they converge to a single value (rounded to 12 digits), following the method described in :cite:`Raissouli:2009`. Parameters ---------- nums : list A series of numbers Returns ------- float The arithmetic-geometric-harmonic mean of nums Examples -------- >>> aghmean([1, 2, 3, 4]) 2.198327159900212 >>> aghmean([1, 2]) 1.4142135623731884 >>> aghmean([0, 5, 1000]) 335.0 """ m_a = amean(nums) m_g = gmean(nums) m_h = hmean(nums) if math.isnan(m_a) or math.isnan(m_g) or math.isnan(m_h): return float('nan') while round(m_a, 12) != round(m_g, 12) and round(m_g, 12) != round( m_h, 12 ): m_a, m_g, m_h = ( (m_a + m_g + m_h) / 3, (m_a * m_g * m_h) ** (1 / 3), 3 / (1 / m_a + 1 / m_g + 1 / m_h), ) return m_a
python
{ "resource": "" }
q258235
median
validation
def median(nums): """Return median. With numbers sorted by value, the median is the middle value (if there is an odd number of values) or the arithmetic mean of the two middle values (if there is an even number of values). Cf. https://en.wikipedia.org/wiki/Median Parameters ---------- nums : list A series of numbers Returns ------- int or float The median of nums Examples -------- >>> median([1, 2, 3]) 2 >>> median([1, 2, 3, 4]) 2.5 >>> median([1, 2, 2, 4]) 2 """ nums = sorted(nums) mag = len(nums) if mag % 2: mag = int((mag - 1) / 2) return nums[mag] mag = int(mag / 2) med = (nums[mag - 1] + nums[mag]) / 2 return med if not med.is_integer() else int(med)
python
{ "resource": "" }
q258236
var
validation
def var(nums, mean_func=amean, ddof=0): r"""Calculate the variance. The variance (:math:`\sigma^2`) of a series of numbers (:math:`x_i`) with mean :math:`\mu` and population :math:`N` is: :math:`\sigma^2 = \frac{1}{N}\sum_{i=1}^{N}(x_i-\mu)^2`. Cf. https://en.wikipedia.org/wiki/Variance Parameters ---------- nums : list A series of numbers mean_func : function A mean function (amean by default) ddof : int The degrees of freedom (0 by default) Returns ------- float The variance of the values in the series Examples -------- >>> var([1, 1, 1, 1]) 0.0 >>> var([1, 2, 3, 4]) 1.25 >>> round(var([1, 2, 3, 4], ddof=1), 12) 1.666666666667 """ x_bar = mean_func(nums) return sum((x - x_bar) ** 2 for x in nums) / (len(nums) - ddof)
python
{ "resource": "" }
q258237
Schinke.stem
validation
def stem(self, word): """Return the stem of a word according to the Schinke stemmer. Parameters ---------- word : str The word to stem Returns ------- str Word stem Examples -------- >>> stmr = Schinke() >>> stmr.stem('atque') {'n': 'atque', 'v': 'atque'} >>> stmr.stem('census') {'n': 'cens', 'v': 'censu'} >>> stmr.stem('virum') {'n': 'uir', 'v': 'uiru'} >>> stmr.stem('populusque') {'n': 'popul', 'v': 'populu'} >>> stmr.stem('senatus') {'n': 'senat', 'v': 'senatu'} """ word = normalize('NFKD', text_type(word.lower())) word = ''.join( c for c in word if c in { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', } ) # Rule 2 word = word.replace('j', 'i').replace('v', 'u') # Rule 3 if word[-3:] == 'que': # This diverges from the paper by also returning 'que' itself # unstemmed if word[:-3] in self._keep_que or word == 'que': return {'n': word, 'v': word} else: word = word[:-3] # Base case will mean returning the words as is noun = word verb = word # Rule 4 for endlen in range(4, 0, -1): if word[-endlen:] in self._n_endings[endlen]: if len(word) - 2 >= endlen: noun = word[:-endlen] else: noun = word break for endlen in range(6, 0, -1): if word[-endlen:] in self._v_endings_strip[endlen]: if len(word) - 2 >= endlen: verb = word[:-endlen] else: verb = word break if word[-endlen:] in self._v_endings_alter[endlen]: if word[-endlen:] in { 'iuntur', 'erunt', 'untur', 'iunt', 'unt', }: new_word = word[:-endlen] + 'i' addlen = 1 elif word[-endlen:] in {'beris', 'bor', 'bo'}: new_word = word[:-endlen] + 'bi' addlen = 2 else: new_word = word[:-endlen] + 'eri' addlen = 3 # Technically this diverges from the paper by considering the # length of the stem without the new suffix if len(new_word) >= 2 + addlen: verb = new_word else: verb = word break return {'n': noun, 'v': verb}
python
{ "resource": "" }
q258238
sim_editex
validation
def sim_editex(src, tar, cost=(0, 1, 2), local=False): """Return the normalized Editex similarity of two strings. This is a wrapper for :py:meth:`Editex.sim`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison cost : tuple A 3-tuple representing the cost of the four possible edits: match, same-group, and mismatch respectively (by default: (0, 1, 2)) local : bool If True, the local variant of Editex is used Returns ------- int Normalized Editex similarity Examples -------- >>> round(sim_editex('cat', 'hat'), 12) 0.666666666667 >>> round(sim_editex('Niall', 'Neil'), 12) 0.8 >>> sim_editex('aluminum', 'Catalan') 0.25 >>> sim_editex('ATCG', 'TAGC') 0.25 """ return Editex().sim(src, tar, cost, local)
python
{ "resource": "" }
q258239
NCDarith.dist
validation
def dist(self, src, tar, probs=None): """Return the NCD between two strings using arithmetic coding. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison probs : dict A dictionary trained with :py:meth:`Arithmetic.train` Returns ------- float Compression distance Examples -------- >>> cmp = NCDarith() >>> cmp.dist('cat', 'hat') 0.5454545454545454 >>> cmp.dist('Niall', 'Neil') 0.6875 >>> cmp.dist('aluminum', 'Catalan') 0.8275862068965517 >>> cmp.dist('ATCG', 'TAGC') 0.6923076923076923 """ if src == tar: return 0.0 if probs is None: # lacking a reasonable dictionary, train on the strings themselves self._coder.train(src + tar) else: self._coder.set_probs(probs) src_comp = self._coder.encode(src)[1] tar_comp = self._coder.encode(tar)[1] concat_comp = self._coder.encode(src + tar)[1] concat_comp2 = self._coder.encode(tar + src)[1] return ( min(concat_comp, concat_comp2) - min(src_comp, tar_comp) ) / max(src_comp, tar_comp)
python
{ "resource": "" }
q258240
readfile
validation
def readfile(fn): """Read fn and return the contents. Parameters ---------- fn : str A filename Returns ------- str The content of the file """ with open(path.join(HERE, fn), 'r', encoding='utf-8') as f: return f.read()
python
{ "resource": "" }
q258241
FONEM.encode
validation
def encode(self, word): """Return the FONEM code of a word. Parameters ---------- word : str The word to transform Returns ------- str The FONEM code Examples -------- >>> pe = FONEM() >>> pe.encode('Marchand') 'MARCHEN' >>> pe.encode('Beaulieu') 'BOLIEU' >>> pe.encode('Beaumont') 'BOMON' >>> pe.encode('Legrand') 'LEGREN' >>> pe.encode('Pelletier') 'PELETIER' """ # normalize, upper-case, and filter non-French letters word = unicode_normalize('NFKD', text_type(word.upper())) word = word.translate({198: 'AE', 338: 'OE'}) word = ''.join(c for c in word if c in self._uc_set) for rule in self._rule_order: regex, repl = self._rule_table[rule] if isinstance(regex, text_type): word = word.replace(regex, repl) else: word = regex.sub(repl, word) return word
python
{ "resource": "" }
q258242
Synoname._synoname_strip_punct
validation
def _synoname_strip_punct(self, word): """Return a word with punctuation stripped out. Parameters ---------- word : str A word to strip punctuation from Returns ------- str The word stripped of punctuation Examples -------- >>> pe = Synoname() >>> pe._synoname_strip_punct('AB;CD EF-GH$IJ') 'ABCD EFGHIJ' """ stripped = '' for char in word: if char not in set(',-./:;"&\'()!{|}?$%*+<=>[\\]^_`~'): stripped += char return stripped.strip()
python
{ "resource": "" }
q258243
Synoname.dist
validation
def dist( self, src, tar, word_approx_min=0.3, char_approx_min=0.73, tests=2 ** 12 - 1, ): """Return the normalized Synoname distance between two words. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison word_approx_min : float The minimum word approximation value to signal a 'word_approx' match char_approx_min : float The minimum character approximation value to signal a 'char_approx' match tests : int or Iterable Either an integer indicating tests to perform or a list of test names to perform (defaults to performing all tests) Returns ------- float Normalized Synoname distance """ return ( synoname(src, tar, word_approx_min, char_approx_min, tests, False) / 14 )
python
{ "resource": "" }
q258244
Jaccard.sim
validation
def sim(self, src, tar, qval=2): r"""Return the Jaccard similarity of two strings. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison qval : int The length of each q-gram; 0 for non-q-gram version Returns ------- float Jaccard similarity Examples -------- >>> cmp = Jaccard() >>> cmp.sim('cat', 'hat') 0.3333333333333333 >>> cmp.sim('Niall', 'Neil') 0.2222222222222222 >>> cmp.sim('aluminum', 'Catalan') 0.0625 >>> cmp.sim('ATCG', 'TAGC') 0.0 """ return super(self.__class__, self).sim(src, tar, qval, 1, 1)
python
{ "resource": "" }
q258245
Jaccard.tanimoto_coeff
validation
def tanimoto_coeff(self, src, tar, qval=2): """Return the Tanimoto distance between two strings. Tanimoto distance :cite:`Tanimoto:1958` is :math:`-log_{2} sim_{Tanimoto}(X, Y)`. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison qval : int The length of each q-gram; 0 for non-q-gram version Returns ------- float Tanimoto distance Examples -------- >>> cmp = Jaccard() >>> cmp.tanimoto_coeff('cat', 'hat') -1.5849625007211563 >>> cmp.tanimoto_coeff('Niall', 'Neil') -2.1699250014423126 >>> cmp.tanimoto_coeff('aluminum', 'Catalan') -4.0 >>> cmp.tanimoto_coeff('ATCG', 'TAGC') -inf """ coeff = self.sim(src, tar, qval) if coeff != 0: return log(coeff, 2) return float('-inf')
python
{ "resource": "" }
q258246
sim_sift4
validation
def sim_sift4(src, tar, max_offset=5, max_distance=0): """Return the normalized "common" Sift4 similarity of two terms. This is a wrapper for :py:meth:`Sift4.sim`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison max_offset : int The number of characters to search for matching letters max_distance : int The distance at which to stop and exit Returns ------- float The normalized Sift4 similarity Examples -------- >>> round(sim_sift4('cat', 'hat'), 12) 0.666666666667 >>> sim_sift4('Niall', 'Neil') 0.6 >>> sim_sift4('Colin', 'Cuilen') 0.5 >>> sim_sift4('ATCG', 'TAGC') 0.5 """ return Sift4().sim(src, tar, max_offset, max_distance)
python
{ "resource": "" }
q258247
NCDbz2.dist
validation
def dist(self, src, tar): """Return the NCD between two strings using bzip2 compression. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison Returns ------- float Compression distance Examples -------- >>> cmp = NCDbz2() >>> cmp.dist('cat', 'hat') 0.06666666666666667 >>> cmp.dist('Niall', 'Neil') 0.03125 >>> cmp.dist('aluminum', 'Catalan') 0.17647058823529413 >>> cmp.dist('ATCG', 'TAGC') 0.03125 """ if src == tar: return 0.0 src = src.encode('utf-8') tar = tar.encode('utf-8') src_comp = bz2.compress(src, self._level)[10:] tar_comp = bz2.compress(tar, self._level)[10:] concat_comp = bz2.compress(src + tar, self._level)[10:] concat_comp2 = bz2.compress(tar + src, self._level)[10:] return ( min(len(concat_comp), len(concat_comp2)) - min(len(src_comp), len(tar_comp)) ) / max(len(src_comp), len(tar_comp))
python
{ "resource": "" }
q258248
MetaSoundex.encode
validation
def encode(self, word, lang='en'): """Return the MetaSoundex code for a word. Parameters ---------- word : str The word to transform lang : str Either ``en`` for English or ``es`` for Spanish Returns ------- str The MetaSoundex code Examples -------- >>> pe = MetaSoundex() >>> pe.encode('Smith') '4500' >>> pe.encode('Waters') '7362' >>> pe.encode('James') '1520' >>> pe.encode('Schmidt') '4530' >>> pe.encode('Ashcroft') '0261' >>> pe.encode('Perez', lang='es') '094' >>> pe.encode('Martinez', lang='es') '69364' >>> pe.encode('Gutierrez', lang='es') '83994' >>> pe.encode('Santiago', lang='es') '4638' >>> pe.encode('Nicolás', lang='es') '6754' """ if lang == 'es': return self._phonetic_spanish.encode( self._spanish_metaphone.encode(word) ) word = self._soundex.encode(self._metaphone.encode(word)) word = word[0].translate(self._trans) + word[1:] return word
python
{ "resource": "" }
q258249
SStemmer.stem
validation
def stem(self, word): """Return the S-stemmed form of a word. Parameters ---------- word : str The word to stem Returns ------- str Word stem Examples -------- >>> stmr = SStemmer() >>> stmr.stem('summaries') 'summary' >>> stmr.stem('summary') 'summary' >>> stmr.stem('towers') 'tower' >>> stmr.stem('reading') 'reading' >>> stmr.stem('census') 'census' """ lowered = word.lower() if lowered[-3:] == 'ies' and lowered[-4:-3] not in {'e', 'a'}: return word[:-3] + ('Y' if word[-1:].isupper() else 'y') if lowered[-2:] == 'es' and lowered[-3:-2] not in {'a', 'e', 'o'}: return word[:-1] if lowered[-1:] == 's' and lowered[-2:-1] not in {'u', 's'}: return word[:-1] return word
python
{ "resource": "" }
q258250
RatcliffObershelp.sim
validation
def sim(self, src, tar): """Return the Ratcliff-Obershelp similarity of two strings. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison Returns ------- float Ratcliff-Obershelp similarity Examples -------- >>> cmp = RatcliffObershelp() >>> round(cmp.sim('cat', 'hat'), 12) 0.666666666667 >>> round(cmp.sim('Niall', 'Neil'), 12) 0.666666666667 >>> round(cmp.sim('aluminum', 'Catalan'), 12) 0.4 >>> cmp.sim('ATCG', 'TAGC') 0.5 """ def _lcsstr_stl(src, tar): """Return start positions & length for Ratcliff-Obershelp. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison Returns ------- tuple The start position in the source string, start position in the target string, and length of the longest common substring of strings src and tar. """ lengths = np_zeros((len(src) + 1, len(tar) + 1), dtype=np_int) longest, src_longest, tar_longest = 0, 0, 0 for i in range(1, len(src) + 1): for j in range(1, len(tar) + 1): if src[i - 1] == tar[j - 1]: lengths[i, j] = lengths[i - 1, j - 1] + 1 if lengths[i, j] > longest: longest = lengths[i, j] src_longest = i tar_longest = j else: lengths[i, j] = 0 return src_longest - longest, tar_longest - longest, longest def _sstr_matches(src, tar): """Return the sum of substring match lengths. This follows the Ratcliff-Obershelp algorithm :cite:`Ratcliff:1988`: 1. Find the length of the longest common substring in src & tar. 2. Recurse on the strings to the left & right of each this substring in src & tar. 3. Base case is a 0 length common substring, in which case, return 0. 4. Return the sum. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison Returns ------- int Sum of substring match lengths """ src_start, tar_start, length = _lcsstr_stl(src, tar) if length == 0: return 0 return ( _sstr_matches(src[:src_start], tar[:tar_start]) + length + _sstr_matches( src[src_start + length :], tar[tar_start + length :] ) ) if src == tar: return 1.0 elif not src or not tar: return 0.0 return 2 * _sstr_matches(src, tar) / (len(src) + len(tar))
python
{ "resource": "" }
q258251
MRA.dist_abs
validation
def dist_abs(self, src, tar): """Return the MRA comparison rating of two strings. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison Returns ------- int MRA comparison rating Examples -------- >>> cmp = MRA() >>> cmp.dist_abs('cat', 'hat') 5 >>> cmp.dist_abs('Niall', 'Neil') 6 >>> cmp.dist_abs('aluminum', 'Catalan') 0 >>> cmp.dist_abs('ATCG', 'TAGC') 5 """ if src == tar: return 6 if src == '' or tar == '': return 0 src = list(mra(src)) tar = list(mra(tar)) if abs(len(src) - len(tar)) > 2: return 0 length_sum = len(src) + len(tar) if length_sum < 5: min_rating = 5 elif length_sum < 8: min_rating = 4 elif length_sum < 12: min_rating = 3 else: min_rating = 2 for _ in range(2): new_src = [] new_tar = [] minlen = min(len(src), len(tar)) for i in range(minlen): if src[i] != tar[i]: new_src.append(src[i]) new_tar.append(tar[i]) src = new_src + src[minlen:] tar = new_tar + tar[minlen:] src.reverse() tar.reverse() similarity = 6 - max(len(src), len(tar)) if similarity >= min_rating: return similarity return 0
python
{ "resource": "" }
q258252
ParmarKumbharana.encode
validation
def encode(self, word): """Return the Parmar-Kumbharana encoding of a word. Parameters ---------- word : str The word to transform Returns ------- str The Parmar-Kumbharana encoding Examples -------- >>> pe = ParmarKumbharana() >>> pe.encode('Gough') 'GF' >>> pe.encode('pneuma') 'NM' >>> pe.encode('knight') 'NT' >>> pe.encode('trice') 'TRS' >>> pe.encode('judge') 'JJ' """ word = word.upper() # Rule 3 word = self._delete_consecutive_repeats(word) # Rule 4 # Rule 5 i = 0 while i < len(word): for match_len in range(4, 1, -1): if word[i : i + match_len] in self._rules[match_len]: repl = self._rules[match_len][word[i : i + match_len]] word = word[:i] + repl + word[i + match_len :] i += len(repl) break else: i += 1 word = word[:1] + word[1:].translate(self._del_trans) # Rule 6 return word
python
{ "resource": "" }
q258253
eudex_hamming
validation
def eudex_hamming( src, tar, weights='exponential', max_length=8, normalized=False ): """Calculate the Hamming distance between the Eudex hashes of two terms. This is a wrapper for :py:meth:`Eudex.eudex_hamming`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison weights : str, iterable, or generator function The weights or weights generator function max_length : int The number of characters to encode as a eudex hash normalized : bool Normalizes to [0, 1] if True Returns ------- int The Eudex Hamming distance Examples -------- >>> eudex_hamming('cat', 'hat') 128 >>> eudex_hamming('Niall', 'Neil') 2 >>> eudex_hamming('Colin', 'Cuilen') 10 >>> eudex_hamming('ATCG', 'TAGC') 403 >>> eudex_hamming('cat', 'hat', weights='fibonacci') 34 >>> eudex_hamming('Niall', 'Neil', weights='fibonacci') 2 >>> eudex_hamming('Colin', 'Cuilen', weights='fibonacci') 7 >>> eudex_hamming('ATCG', 'TAGC', weights='fibonacci') 117 >>> eudex_hamming('cat', 'hat', weights=None) 1 >>> eudex_hamming('Niall', 'Neil', weights=None) 1 >>> eudex_hamming('Colin', 'Cuilen', weights=None) 2 >>> eudex_hamming('ATCG', 'TAGC', weights=None) 9 >>> # Using the OEIS A000142: >>> eudex_hamming('cat', 'hat', [1, 1, 2, 6, 24, 120, 720, 5040]) 1 >>> eudex_hamming('Niall', 'Neil', [1, 1, 2, 6, 24, 120, 720, 5040]) 720 >>> eudex_hamming('Colin', 'Cuilen', [1, 1, 2, 6, 24, 120, 720, 5040]) 744 >>> eudex_hamming('ATCG', 'TAGC', [1, 1, 2, 6, 24, 120, 720, 5040]) 6243 """ return Eudex().dist_abs(src, tar, weights, max_length, normalized)
python
{ "resource": "" }
q258254
dist_eudex
validation
def dist_eudex(src, tar, weights='exponential', max_length=8): """Return normalized Hamming distance between Eudex hashes of two terms. This is a wrapper for :py:meth:`Eudex.dist`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison weights : str, iterable, or generator function The weights or weights generator function max_length : int The number of characters to encode as a eudex hash Returns ------- int The normalized Eudex Hamming distance Examples -------- >>> round(dist_eudex('cat', 'hat'), 12) 0.062745098039 >>> round(dist_eudex('Niall', 'Neil'), 12) 0.000980392157 >>> round(dist_eudex('Colin', 'Cuilen'), 12) 0.004901960784 >>> round(dist_eudex('ATCG', 'TAGC'), 12) 0.197549019608 """ return Eudex().dist(src, tar, weights, max_length)
python
{ "resource": "" }
q258255
sim_eudex
validation
def sim_eudex(src, tar, weights='exponential', max_length=8): """Return normalized Hamming similarity between Eudex hashes of two terms. This is a wrapper for :py:meth:`Eudex.sim`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison weights : str, iterable, or generator function The weights or weights generator function max_length : int The number of characters to encode as a eudex hash Returns ------- int The normalized Eudex Hamming similarity Examples -------- >>> round(sim_eudex('cat', 'hat'), 12) 0.937254901961 >>> round(sim_eudex('Niall', 'Neil'), 12) 0.999019607843 >>> round(sim_eudex('Colin', 'Cuilen'), 12) 0.995098039216 >>> round(sim_eudex('ATCG', 'TAGC'), 12) 0.802450980392 """ return Eudex().sim(src, tar, weights, max_length)
python
{ "resource": "" }
q258256
Eudex.gen_fibonacci
validation
def gen_fibonacci(): """Yield the next Fibonacci number. Based on https://www.python-course.eu/generators.php Starts at Fibonacci number 3 (the second 1) Yields ------ int The next Fibonacci number """ num_a, num_b = 1, 2 while True: yield num_a num_a, num_b = num_b, num_a + num_b
python
{ "resource": "" }
q258257
Eudex.dist_abs
validation
def dist_abs( self, src, tar, weights='exponential', max_length=8, normalized=False ): """Calculate the distance between the Eudex hashes of two terms. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison weights : str, iterable, or generator function The weights or weights generator function - If set to ``None``, a simple Hamming distance is calculated. - If set to ``exponential``, weight decays by powers of 2, as proposed in the eudex specification: https://github.com/ticki/eudex. - If set to ``fibonacci``, weight decays through the Fibonacci series, as in the eudex reference implementation. - If set to a callable function, this assumes it creates a generator and the generator is used to populate a series of weights. - If set to an iterable, the iterable's values should be integers and will be used as the weights. max_length : int The number of characters to encode as a eudex hash normalized : bool Normalizes to [0, 1] if True Returns ------- int The Eudex Hamming distance Examples -------- >>> cmp = Eudex() >>> cmp.dist_abs('cat', 'hat') 128 >>> cmp.dist_abs('Niall', 'Neil') 2 >>> cmp.dist_abs('Colin', 'Cuilen') 10 >>> cmp.dist_abs('ATCG', 'TAGC') 403 >>> cmp.dist_abs('cat', 'hat', weights='fibonacci') 34 >>> cmp.dist_abs('Niall', 'Neil', weights='fibonacci') 2 >>> cmp.dist_abs('Colin', 'Cuilen', weights='fibonacci') 7 >>> cmp.dist_abs('ATCG', 'TAGC', weights='fibonacci') 117 >>> cmp.dist_abs('cat', 'hat', weights=None) 1 >>> cmp.dist_abs('Niall', 'Neil', weights=None) 1 >>> cmp.dist_abs('Colin', 'Cuilen', weights=None) 2 >>> cmp.dist_abs('ATCG', 'TAGC', weights=None) 9 >>> # Using the OEIS A000142: >>> cmp.dist_abs('cat', 'hat', [1, 1, 2, 6, 24, 120, 720, 5040]) 1 >>> cmp.dist_abs('Niall', 'Neil', [1, 1, 2, 6, 24, 120, 720, 5040]) 720 >>> cmp.dist_abs('Colin', 'Cuilen', ... [1, 1, 2, 6, 24, 120, 720, 5040]) 744 >>> cmp.dist_abs('ATCG', 'TAGC', [1, 1, 2, 6, 24, 120, 720, 5040]) 6243 """ # Calculate the eudex hashes and XOR them xored = eudex(src, max_length=max_length) ^ eudex( tar, max_length=max_length ) # Simple hamming distance (all bits are equal) if not weights: binary = bin(xored) distance = binary.count('1') if normalized: return distance / (len(binary) - 2) return distance # If weights is a function, it should create a generator, # which we now use to populate a list if callable(weights): weights = weights() elif weights == 'exponential': weights = Eudex.gen_exponential() elif weights == 'fibonacci': weights = Eudex.gen_fibonacci() if isinstance(weights, GeneratorType): weights = [next(weights) for _ in range(max_length)][::-1] # Sum the weighted hamming distance distance = 0 max_distance = 0 while (xored or normalized) and weights: max_distance += 8 * weights[-1] distance += bin(xored & 0xFF).count('1') * weights.pop() xored >>= 8 if normalized: distance /= max_distance return distance
python
{ "resource": "" }
q258258
Eudex.dist
validation
def dist(self, src, tar, weights='exponential', max_length=8): """Return normalized distance between the Eudex hashes of two terms. This is Eudex distance normalized to [0, 1]. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison weights : str, iterable, or generator function The weights or weights generator function max_length : int The number of characters to encode as a eudex hash Returns ------- int The normalized Eudex Hamming distance Examples -------- >>> cmp = Eudex() >>> round(cmp.dist('cat', 'hat'), 12) 0.062745098039 >>> round(cmp.dist('Niall', 'Neil'), 12) 0.000980392157 >>> round(cmp.dist('Colin', 'Cuilen'), 12) 0.004901960784 >>> round(cmp.dist('ATCG', 'TAGC'), 12) 0.197549019608 """ return self.dist_abs(src, tar, weights, max_length, True)
python
{ "resource": "" }
q258259
euclidean
validation
def euclidean(src, tar, qval=2, normalized=False, alphabet=None): """Return the Euclidean distance between two strings. This is a wrapper for :py:meth:`Euclidean.dist_abs`. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison qval : int The length of each q-gram; 0 for non-q-gram version normalized : bool Normalizes to [0, 1] if True alphabet : collection or int The values or size of the alphabet Returns ------- float: The Euclidean distance Examples -------- >>> euclidean('cat', 'hat') 2.0 >>> round(euclidean('Niall', 'Neil'), 12) 2.645751311065 >>> euclidean('Colin', 'Cuilen') 3.0 >>> round(euclidean('ATCG', 'TAGC'), 12) 3.162277660168 """ return Euclidean().dist_abs(src, tar, qval, normalized, alphabet)
python
{ "resource": "" }
q258260
dist_euclidean
validation
def dist_euclidean(src, tar, qval=2, alphabet=None): """Return the normalized Euclidean distance between two strings. This is a wrapper for :py:meth:`Euclidean.dist`. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison qval : int The length of each q-gram; 0 for non-q-gram version alphabet : collection or int The values or size of the alphabet Returns ------- float The normalized Euclidean distance Examples -------- >>> round(dist_euclidean('cat', 'hat'), 12) 0.57735026919 >>> round(dist_euclidean('Niall', 'Neil'), 12) 0.683130051064 >>> round(dist_euclidean('Colin', 'Cuilen'), 12) 0.727606875109 >>> dist_euclidean('ATCG', 'TAGC') 1.0 """ return Euclidean().dist(src, tar, qval, alphabet)
python
{ "resource": "" }
q258261
sim_euclidean
validation
def sim_euclidean(src, tar, qval=2, alphabet=None): """Return the normalized Euclidean similarity of two strings. This is a wrapper for :py:meth:`Euclidean.sim`. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison qval : int The length of each q-gram; 0 for non-q-gram version alphabet : collection or int The values or size of the alphabet Returns ------- float The normalized Euclidean similarity Examples -------- >>> round(sim_euclidean('cat', 'hat'), 12) 0.42264973081 >>> round(sim_euclidean('Niall', 'Neil'), 12) 0.316869948936 >>> round(sim_euclidean('Colin', 'Cuilen'), 12) 0.272393124891 >>> sim_euclidean('ATCG', 'TAGC') 0.0 """ return Euclidean().sim(src, tar, qval, alphabet)
python
{ "resource": "" }
q258262
Lovins._cond_k
validation
def _cond_k(self, word, suffix_len): """Return Lovins' condition K. Parameters ---------- word : str Word to check suffix_len : int Suffix length Returns ------- bool True if condition is met """ return (len(word) - suffix_len >= 3) and ( word[-suffix_len - 1] in {'i', 'l'} or (word[-suffix_len - 3] == 'u' and word[-suffix_len - 1] == 'e') )
python
{ "resource": "" }
q258263
Lovins._cond_n
validation
def _cond_n(self, word, suffix_len): """Return Lovins' condition N. Parameters ---------- word : str Word to check suffix_len : int Suffix length Returns ------- bool True if condition is met """ if len(word) - suffix_len >= 3: if word[-suffix_len - 3] == 's': if len(word) - suffix_len >= 4: return True else: return True return False
python
{ "resource": "" }
q258264
Lovins._cond_s
validation
def _cond_s(self, word, suffix_len): """Return Lovins' condition S. Parameters ---------- word : str Word to check suffix_len : int Suffix length Returns ------- bool True if condition is met """ return word[-suffix_len - 2 : -suffix_len] == 'dr' or ( word[-suffix_len - 1] == 't' and word[-suffix_len - 2 : -suffix_len] != 'tt' )
python
{ "resource": "" }
q258265
Lovins._cond_x
validation
def _cond_x(self, word, suffix_len): """Return Lovins' condition X. Parameters ---------- word : str Word to check suffix_len : int Suffix length Returns ------- bool True if condition is met """ return word[-suffix_len - 1] in {'i', 'l'} or ( word[-suffix_len - 3 : -suffix_len] == 'u' and word[-suffix_len - 1] == 'e' )
python
{ "resource": "" }
q258266
Lovins._cond_bb
validation
def _cond_bb(self, word, suffix_len): """Return Lovins' condition BB. Parameters ---------- word : str Word to check suffix_len : int Suffix length Returns ------- bool True if condition is met """ return ( len(word) - suffix_len >= 3 and word[-suffix_len - 3 : -suffix_len] != 'met' and word[-suffix_len - 4 : -suffix_len] != 'ryst' )
python
{ "resource": "" }
q258267
Lovins.stem
validation
def stem(self, word): """Return Lovins stem. Parameters ---------- word : str The word to stem Returns ------- str Word stem Examples -------- >>> stmr = Lovins() >>> stmr.stem('reading') 'read' >>> stmr.stem('suspension') 'suspens' >>> stmr.stem('elusiveness') 'elus' """ # lowercase, normalize, and compose word = normalize('NFC', text_type(word.lower())) for suffix_len in range(11, 0, -1): ending = word[-suffix_len:] if ( ending in self._suffix and len(word) - suffix_len >= 2 and ( self._suffix[ending] is None or self._suffix[ending](word, suffix_len) ) ): word = word[:-suffix_len] break if word[-2:] in { 'bb', 'dd', 'gg', 'll', 'mm', 'nn', 'pp', 'rr', 'ss', 'tt', }: word = word[:-1] for ending, replacement in self._recode: if word.endswith(ending): if callable(replacement): word = replacement(word) else: word = word[: -len(ending)] + replacement return word
python
{ "resource": "" }
q258268
NCDzlib.dist
validation
def dist(self, src, tar): """Return the NCD between two strings using zlib compression. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison Returns ------- float Compression distance Examples -------- >>> cmp = NCDzlib() >>> cmp.dist('cat', 'hat') 0.3333333333333333 >>> cmp.dist('Niall', 'Neil') 0.45454545454545453 >>> cmp.dist('aluminum', 'Catalan') 0.5714285714285714 >>> cmp.dist('ATCG', 'TAGC') 0.4 """ if src == tar: return 0.0 src = src.encode('utf-8') tar = tar.encode('utf-8') self._compressor.compress(src) src_comp = self._compressor.flush(zlib.Z_FULL_FLUSH) self._compressor.compress(tar) tar_comp = self._compressor.flush(zlib.Z_FULL_FLUSH) self._compressor.compress(src + tar) concat_comp = self._compressor.flush(zlib.Z_FULL_FLUSH) self._compressor.compress(tar + src) concat_comp2 = self._compressor.flush(zlib.Z_FULL_FLUSH) return ( min(len(concat_comp), len(concat_comp2)) - min(len(src_comp), len(tar_comp)) ) / max(len(src_comp), len(tar_comp))
python
{ "resource": "" }
q258269
pylint_color
validation
def pylint_color(score): """Return Pylint badge color. Parameters ---------- score : float A Pylint score Returns ------- str Badge color """ # These are the score cutoffs for each color above. # I.e. score==10 -> brightgreen, down to 7.5 > score >= 5 -> orange score_cutoffs = (10, 9.5, 8.5, 7.5, 5) for i in range(len(score_cutoffs)): if score >= score_cutoffs[i]: return BADGE_COLORS[i] # and score < 5 -> red return BADGE_COLORS[-1]
python
{ "resource": "" }
q258270
pydocstyle_color
validation
def pydocstyle_color(score): """Return pydocstyle badge color. Parameters ---------- score : float A pydocstyle score Returns ------- str Badge color """ # These are the score cutoffs for each color above. # I.e. score==0 -> brightgreen, down to 100 < score <= 200 -> orange score_cutoffs = (0, 10, 25, 50, 100) for i in range(len(score_cutoffs)): if score <= score_cutoffs[i]: return BADGE_COLORS[i] # and score > 200 -> red return BADGE_COLORS[-1]
python
{ "resource": "" }
q258271
flake8_color
validation
def flake8_color(score): """Return flake8 badge color. Parameters ---------- score : float A flake8 score Returns ------- str Badge color """ # These are the score cutoffs for each color above. # I.e. score==0 -> brightgreen, down to 100 < score <= 200 -> orange score_cutoffs = (0, 20, 50, 100, 200) for i in range(len(score_cutoffs)): if score <= score_cutoffs[i]: return BADGE_COLORS[i] # and score > 200 -> red return BADGE_COLORS[-1]
python
{ "resource": "" }
q258272
Bag.dist_abs
validation
def dist_abs(self, src, tar): """Return the bag distance between two strings. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison Returns ------- int Bag distance Examples -------- >>> cmp = Bag() >>> cmp.dist_abs('cat', 'hat') 1 >>> cmp.dist_abs('Niall', 'Neil') 2 >>> cmp.dist_abs('aluminum', 'Catalan') 5 >>> cmp.dist_abs('ATCG', 'TAGC') 0 >>> cmp.dist_abs('abcdefg', 'hijklm') 7 >>> cmp.dist_abs('abcdefg', 'hijklmno') 8 """ if tar == src: return 0 elif not src: return len(tar) elif not tar: return len(src) src_bag = Counter(src) tar_bag = Counter(tar) return max( sum((src_bag - tar_bag).values()), sum((tar_bag - src_bag).values()), )
python
{ "resource": "" }
q258273
Bag.dist
validation
def dist(self, src, tar): """Return the normalized bag distance between two strings. Bag distance is normalized by dividing by :math:`max( |src|, |tar| )`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison Returns ------- float Normalized bag distance Examples -------- >>> cmp = Bag() >>> cmp.dist('cat', 'hat') 0.3333333333333333 >>> cmp.dist('Niall', 'Neil') 0.4 >>> cmp.dist('aluminum', 'Catalan') 0.625 >>> cmp.dist('ATCG', 'TAGC') 0.0 """ if tar == src: return 0.0 if not src or not tar: return 1.0 max_length = max(len(src), len(tar)) return self.dist_abs(src, tar) / max_length
python
{ "resource": "" }
q258274
CLEFGermanPlus.stem
validation
def stem(self, word): """Return 'CLEF German stemmer plus' stem. Parameters ---------- word : str The word to stem Returns ------- str Word stem Examples -------- >>> stmr = CLEFGermanPlus() >>> clef_german_plus('lesen') 'les' >>> clef_german_plus('graues') 'grau' >>> clef_german_plus('buchstabieren') 'buchstabi' """ # lowercase, normalize, and compose word = normalize('NFC', text_type(word.lower())) # remove umlauts word = word.translate(self._accents) # Step 1 wlen = len(word) - 1 if wlen > 4 and word[-3:] == 'ern': word = word[:-3] elif wlen > 3 and word[-2:] in {'em', 'en', 'er', 'es'}: word = word[:-2] elif wlen > 2 and ( word[-1] == 'e' or (word[-1] == 's' and word[-2] in self._st_ending) ): word = word[:-1] # Step 2 wlen = len(word) - 1 if wlen > 4 and word[-3:] == 'est': word = word[:-3] elif wlen > 3 and ( word[-2:] in {'er', 'en'} or (word[-2:] == 'st' and word[-3] in self._st_ending) ): word = word[:-2] return word
python
{ "resource": "" }
q258275
dist_mlipns
validation
def dist_mlipns(src, tar, threshold=0.25, max_mismatches=2): """Return the MLIPNS distance between two strings. This is a wrapper for :py:meth:`MLIPNS.dist`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison threshold : float A number [0, 1] indicating the maximum similarity score, below which the strings are considered 'similar' (0.25 by default) max_mismatches : int A number indicating the allowable number of mismatches to remove before declaring two strings not similar (2 by default) Returns ------- float MLIPNS distance Examples -------- >>> dist_mlipns('cat', 'hat') 0.0 >>> dist_mlipns('Niall', 'Neil') 1.0 >>> dist_mlipns('aluminum', 'Catalan') 1.0 >>> dist_mlipns('ATCG', 'TAGC') 1.0 """ return MLIPNS().dist(src, tar, threshold, max_mismatches)
python
{ "resource": "" }
q258276
sim
validation
def sim(src, tar, method=sim_levenshtein): """Return a similarity of two strings. This is a generalized function for calling other similarity functions. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison method : function Specifies the similarity metric (:py:func:`sim_levenshtein` by default) Returns ------- float Similarity according to the specified function Raises ------ AttributeError Unknown distance function Examples -------- >>> round(sim('cat', 'hat'), 12) 0.666666666667 >>> round(sim('Niall', 'Neil'), 12) 0.4 >>> sim('aluminum', 'Catalan') 0.125 >>> sim('ATCG', 'TAGC') 0.25 """ if callable(method): return method(src, tar) else: raise AttributeError('Unknown similarity function: ' + str(method))
python
{ "resource": "" }
q258277
dist
validation
def dist(src, tar, method=sim_levenshtein): """Return a distance between two strings. This is a generalized function for calling other distance functions. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison method : function Specifies the similarity metric (:py:func:`sim_levenshtein` by default) -- Note that this takes a similarity metric function, not a distance metric function. Returns ------- float Distance according to the specified function Raises ------ AttributeError Unknown distance function Examples -------- >>> round(dist('cat', 'hat'), 12) 0.333333333333 >>> round(dist('Niall', 'Neil'), 12) 0.6 >>> dist('aluminum', 'Catalan') 0.875 >>> dist('ATCG', 'TAGC') 0.75 """ if callable(method): return 1 - method(src, tar) else: raise AttributeError('Unknown distance function: ' + str(method))
python
{ "resource": "" }
q258278
Porter._m_degree
validation
def _m_degree(self, term): """Return Porter helper function _m_degree value. m-degree is equal to the number of V to C transitions Parameters ---------- term : str The word for which to calculate the m-degree Returns ------- int The m-degree as defined in the Porter stemmer definition """ mdeg = 0 last_was_vowel = False for letter in term: if letter in self._vowels: last_was_vowel = True else: if last_was_vowel: mdeg += 1 last_was_vowel = False return mdeg
python
{ "resource": "" }
q258279
Porter._has_vowel
validation
def _has_vowel(self, term): """Return Porter helper function _has_vowel value. Parameters ---------- term : str The word to scan for vowels Returns ------- bool True iff a vowel exists in the term (as defined in the Porter stemmer definition) """ for letter in term: if letter in self._vowels: return True return False
python
{ "resource": "" }
q258280
Porter._ends_in_doubled_cons
validation
def _ends_in_doubled_cons(self, term): """Return Porter helper function _ends_in_doubled_cons value. Parameters ---------- term : str The word to check for a final doubled consonant Returns ------- bool True iff the stem ends in a doubled consonant (as defined in the Porter stemmer definition) """ return ( len(term) > 1 and term[-1] not in self._vowels and term[-2] == term[-1] )
python
{ "resource": "" }
q258281
Porter._ends_in_cvc
validation
def _ends_in_cvc(self, term): """Return Porter helper function _ends_in_cvc value. Parameters ---------- term : str The word to scan for cvc Returns ------- bool True iff the stem ends in cvc (as defined in the Porter stemmer definition) """ return len(term) > 2 and ( term[-1] not in self._vowels and term[-2] in self._vowels and term[-3] not in self._vowels and term[-1] not in tuple('wxY') )
python
{ "resource": "" }
q258282
filter_symlog
validation
def filter_symlog(y, base=10.0): """Symmetrical logarithmic scale. Optional arguments: *base*: The base of the logarithm. """ log_base = np.log(base) sign = np.sign(y) logs = np.log(np.abs(y) / log_base) return sign * logs
python
{ "resource": "" }
q258283
usage_function
validation
def usage_function(parser): """Show usage and available curve functions.""" parser.print_usage() print('') print('available functions:') for function in sorted(FUNCTION): doc = FUNCTION[function].__doc__.strip().splitlines()[0] print(' %-12s %s' % (function + ':', doc)) return 0
python
{ "resource": "" }
q258284
usage_palette
validation
def usage_palette(parser): """Show usage and available palettes.""" parser.print_usage() print('') print('available palettes:') for palette in sorted(PALETTE): print(' %-12s' % (palette,)) return 0
python
{ "resource": "" }
q258285
Terminal.size
validation
def size(self): """Get the current terminal size.""" for fd in range(3): cr = self._ioctl_GWINSZ(fd) if cr: break if not cr: try: fd = os.open(os.ctermid(), os.O_RDONLY) cr = self._ioctl_GWINSZ(fd) os.close(fd) except Exception: pass if not cr: env = os.environ cr = (env.get('LINES', 25), env.get('COLUMNS', 80)) return int(cr[1]), int(cr[0])
python
{ "resource": "" }
q258286
Terminal.color
validation
def color(self, index): """Get the escape sequence for indexed color ``index``. The ``index`` is a color index in the 256 color space. The color space consists of: * 0x00-0x0f: default EGA colors * 0x10-0xe7: 6x6x6 RGB cubes * 0xe8-0xff: gray scale ramp """ if self.colors == 16: if index >= 8: return self.csi('bold') + self.csi('setaf', index - 8) else: return self.csi('sgr0') + self.csi('setaf', index) else: return self.csi('setaf', index)
python
{ "resource": "" }
q258287
Terminal.csi
validation
def csi(self, capname, *args): """Return the escape sequence for the selected Control Sequence.""" value = curses.tigetstr(capname) if value is None: return b'' else: return curses.tparm(value, *args)
python
{ "resource": "" }
q258288
Terminal.csi_wrap
validation
def csi_wrap(self, value, capname, *args): """Return a value wrapped in the selected CSI and does a reset.""" if isinstance(value, str): value = value.encode('utf-8') return b''.join([ self.csi(capname, *args), value, self.csi('sgr0'), ])
python
{ "resource": "" }
q258289
Graph.consume
validation
def consume(self, istream, ostream, batch=False): """Read points from istream and output to ostream.""" datapoints = [] # List of 2-tuples if batch: sleep = max(0.01, self.option.sleep) fd = istream.fileno() while True: try: if select.select([fd], [], [], sleep): try: line = istream.readline() if line == '': break datapoints.append(self.consume_line(line)) except ValueError: continue if self.option.sort_by_column: datapoints = sorted(datapoints, key=itemgetter(self.option.sort_by_column - 1)) if len(datapoints) > 1: datapoints = datapoints[-self.maximum_points:] self.update([dp[0] for dp in datapoints], [dp[1] for dp in datapoints]) self.render(ostream) time.sleep(sleep) except KeyboardInterrupt: break else: for line in istream: try: datapoints.append(self.consume_line(line)) except ValueError: pass if self.option.sort_by_column: datapoints = sorted(datapoints, key=itemgetter(self.option.sort_by_column - 1)) self.update([dp[0] for dp in datapoints], [dp[1] for dp in datapoints]) self.render(ostream)
python
{ "resource": "" }
q258290
Graph.consume_line
validation
def consume_line(self, line): """Consume data from a line.""" data = RE_VALUE_KEY.split(line.strip(), 1) if len(data) == 1: return float(data[0]), None else: return float(data[0]), data[1].strip()
python
{ "resource": "" }
q258291
Graph.update
validation
def update(self, points, values=None): """Add a set of data points.""" self.values = values or [None] * len(points) if np is None: if self.option.function: warnings.warn('numpy not available, function ignored') self.points = points self.minimum = min(self.points) self.maximum = max(self.points) self.current = self.points[-1] else: self.points = self.apply_function(points) self.minimum = np.min(self.points) self.maximum = np.max(self.points) self.current = self.points[-1] if self.maximum == self.minimum: self.extents = 1 else: self.extents = (self.maximum - self.minimum) self.extents = (self.maximum - self.minimum)
python
{ "resource": "" }
q258292
Graph.color_ramp
validation
def color_ramp(self, size): """Generate a color ramp for the current screen height.""" color = PALETTE.get(self.option.palette, {}) color = color.get(self.term.colors, None) color_ramp = [] if color is not None: ratio = len(color) / float(size) for i in range(int(size)): color_ramp.append(self.term.color(color[int(ratio * i)])) return color_ramp
python
{ "resource": "" }
q258293
Graph.human
validation
def human(self, size, base=1000, units=' kMGTZ'): """Convert the input ``size`` to human readable, short form.""" sign = '+' if size >= 0 else '-' size = abs(size) if size < 1000: return '%s%d' % (sign, size) for i, suffix in enumerate(units): unit = 1000 ** (i + 1) if size < unit: return ('%s%.01f%s' % ( sign, size / float(unit) * base, suffix, )).strip() raise OverflowError
python
{ "resource": "" }
q258294
Graph.apply_function
validation
def apply_function(self, points): """Run the filter function on the provided points.""" if not self.option.function: return points if np is None: raise ImportError('numpy is not available') if ':' in self.option.function: function, arguments = self.option.function.split(':', 1) arguments = arguments.split(',') else: function = self.option.function arguments = [] # Resolve arguments arguments = list(map(self._function_argument, arguments)) # Resolve function filter_function = FUNCTION.get(function) if filter_function is None: raise TypeError('Invalid function "%s"' % (function,)) else: # We wrap in ``list()`` to consume generators and iterators, as # ``np.array`` doesn't do this for us. return filter_function(np.array(list(points)), *arguments)
python
{ "resource": "" }
q258295
Graph.line
validation
def line(self, p1, p2, resolution=1): """Resolve the points to make a line between two points.""" xdiff = max(p1.x, p2.x) - min(p1.x, p2.x) ydiff = max(p1.y, p2.y) - min(p1.y, p2.y) xdir = [-1, 1][int(p1.x <= p2.x)] ydir = [-1, 1][int(p1.y <= p2.y)] r = int(round(max(xdiff, ydiff))) if r == 0: return for i in range((r + 1) * resolution): x = p1.x y = p1.y if xdiff: x += (float(i) * xdiff) / r * xdir / resolution if ydiff: y += (float(i) * ydiff) / r * ydir / resolution yield Point((x, y))
python
{ "resource": "" }
q258296
Graph.set_text
validation
def set_text(self, point, text): """Set a text value in the screen canvas.""" if not self.option.legend: return if not isinstance(point, Point): point = Point(point) for offset, char in enumerate(str(text)): self.screen.canvas[point.y][point.x + offset] = char
python
{ "resource": "" }
q258297
AxisGraph.render
validation
def render(self, stream): """Render graph to stream.""" encoding = self.option.encoding or self.term.encoding or "utf8" if self.option.color: ramp = self.color_ramp(self.size.y)[::-1] else: ramp = None if self.cycle >= 1 and self.lines: stream.write(self.term.csi('cuu', self.lines)) zero = int(self.null / 4) # Zero crossing lines = 0 for y in range(self.screen.size.y): if y == zero and self.size.y > 1: stream.write(self.term.csi('smul')) if ramp: stream.write(ramp[y]) for x in range(self.screen.size.x): point = Point((x, y)) if point in self.screen: value = self.screen[point] if isinstance(value, int): stream.write(chr(self.base + value).encode(encoding)) else: stream.write(self.term.csi('sgr0')) stream.write(self.term.csi_wrap( value.encode(encoding), 'bold' )) if y == zero and self.size.y > 1: stream.write(self.term.csi('smul')) if ramp: stream.write(ramp[y]) else: stream.write(b' ') if y == zero and self.size.y > 1: stream.write(self.term.csi('rmul')) if ramp: stream.write(self.term.csi('sgr0')) stream.write(b'\n') lines += 1 stream.flush() self.cycle = self.cycle + 1 self.lines = lines
python
{ "resource": "" }
q258298
AxisGraph._normalised_numpy
validation
def _normalised_numpy(self): """Normalised data points using numpy.""" dx = (self.screen.width / float(len(self.points))) oy = (self.screen.height) points = np.array(self.points) - self.minimum points = points * 4.0 / self.extents * self.size.y for x, y in enumerate(points): yield Point(( dx * x, min(oy, oy - y), ))
python
{ "resource": "" }
q258299
AxisGraph._normalised_python
validation
def _normalised_python(self): """Normalised data points using pure Python.""" dx = (self.screen.width / float(len(self.points))) oy = (self.screen.height) for x, point in enumerate(self.points): y = (point - self.minimum) * 4.0 / self.extents * self.size.y yield Point(( dx * x, min(oy, oy - y), ))
python
{ "resource": "" }