repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
ml31415/numpy-groupies
numpy_groupies/utils.py
get_func
def get_func(func, aliasing, implementations): """ Return the key of a found implementation or the func itself """ try: func_str = aliasing[func] except KeyError: if callable(func): return func else: if func_str in implementations: return func_str ...
python
def get_func(func, aliasing, implementations): """ Return the key of a found implementation or the func itself """ try: func_str = aliasing[func] except KeyError: if callable(func): return func else: if func_str in implementations: return func_str ...
[ "def", "get_func", "(", "func", ",", "aliasing", ",", "implementations", ")", ":", "try", ":", "func_str", "=", "aliasing", "[", "func", "]", "except", "KeyError", ":", "if", "callable", "(", "func", ")", ":", "return", "func", "else", ":", "if", "func...
Return the key of a found implementation or the func itself
[ "Return", "the", "key", "of", "a", "found", "implementation", "or", "the", "func", "itself" ]
train
https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/utils.py#L118-L134
ml31415/numpy-groupies
numpy_groupies/utils_numpy.py
minimum_dtype
def minimum_dtype(x, dtype=np.bool_): """returns the "most basic" dtype which represents `x` properly, which provides at least the same value range as the specified dtype.""" def check_type(x, dtype): try: converted = dtype.type(x) except (ValueError, OverflowError): ...
python
def minimum_dtype(x, dtype=np.bool_): """returns the "most basic" dtype which represents `x` properly, which provides at least the same value range as the specified dtype.""" def check_type(x, dtype): try: converted = dtype.type(x) except (ValueError, OverflowError): ...
[ "def", "minimum_dtype", "(", "x", ",", "dtype", "=", "np", ".", "bool_", ")", ":", "def", "check_type", "(", "x", ",", "dtype", ")", ":", "try", ":", "converted", "=", "dtype", ".", "type", "(", "x", ")", "except", "(", "ValueError", ",", "Overflow...
returns the "most basic" dtype which represents `x` properly, which provides at least the same value range as the specified dtype.
[ "returns", "the", "most", "basic", "dtype", "which", "represents", "x", "properly", "which", "provides", "at", "least", "the", "same", "value", "range", "as", "the", "specified", "dtype", "." ]
train
https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/utils_numpy.py#L60-L90
ml31415/numpy-groupies
numpy_groupies/utils_numpy.py
input_validation
def input_validation(group_idx, a, size=None, order='C', axis=None, ravel_group_idx=True, check_bounds=True): """ Do some fairly extensive checking of group_idx and a, trying to give the user as much help as possible with what is wrong. Also, convert ndim-indexing to 1d indexing. ""...
python
def input_validation(group_idx, a, size=None, order='C', axis=None, ravel_group_idx=True, check_bounds=True): """ Do some fairly extensive checking of group_idx and a, trying to give the user as much help as possible with what is wrong. Also, convert ndim-indexing to 1d indexing. ""...
[ "def", "input_validation", "(", "group_idx", ",", "a", ",", "size", "=", "None", ",", "order", "=", "'C'", ",", "axis", "=", "None", ",", "ravel_group_idx", "=", "True", ",", "check_bounds", "=", "True", ")", ":", "if", "not", "isinstance", "(", "a", ...
Do some fairly extensive checking of group_idx and a, trying to give the user as much help as possible with what is wrong. Also, convert ndim-indexing to 1d indexing.
[ "Do", "some", "fairly", "extensive", "checking", "of", "group_idx", "and", "a", "trying", "to", "give", "the", "user", "as", "much", "help", "as", "possible", "with", "what", "is", "wrong", ".", "Also", "convert", "ndim", "-", "indexing", "to", "1d", "in...
train
https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/utils_numpy.py#L189-L280
ml31415/numpy-groupies
numpy_groupies/utils_numpy.py
multi_arange
def multi_arange(n): """By example: # 0 1 2 3 4 5 6 7 8 n = [0, 0, 3, 0, 0, 2, 0, 2, 1] res = [0, 1, 2, 0, 1, 0, 1, 0] That is it is equivalent to something like this : hstack((arange(n_i) for n_i in n)) This version seems quite a bit faster, at...
python
def multi_arange(n): """By example: # 0 1 2 3 4 5 6 7 8 n = [0, 0, 3, 0, 0, 2, 0, 2, 1] res = [0, 1, 2, 0, 1, 0, 1, 0] That is it is equivalent to something like this : hstack((arange(n_i) for n_i in n)) This version seems quite a bit faster, at...
[ "def", "multi_arange", "(", "n", ")", ":", "if", "n", ".", "ndim", "!=", "1", ":", "raise", "ValueError", "(", "\"n is supposed to be 1d array.\"", ")", "n_mask", "=", "n", ".", "astype", "(", "bool", ")", "n_cumsum", "=", "np", ".", "cumsum", "(", "n"...
By example: # 0 1 2 3 4 5 6 7 8 n = [0, 0, 3, 0, 0, 2, 0, 2, 1] res = [0, 1, 2, 0, 1, 0, 1, 0] That is it is equivalent to something like this : hstack((arange(n_i) for n_i in n)) This version seems quite a bit faster, at least for some possible...
[ "By", "example", ":", "#", "0", "1", "2", "3", "4", "5", "6", "7", "8", "n", "=", "[", "0", "0", "3", "0", "0", "2", "0", "2", "1", "]", "res", "=", "[", "0", "1", "2", "0", "1", "0", "1", "0", "]" ]
train
https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/utils_numpy.py#L309-L332
ml31415/numpy-groupies
numpy_groupies/utils_numpy.py
label_contiguous_1d
def label_contiguous_1d(X): """ WARNING: API for this function is not liable to change!!! By example: X = [F T T F F T F F F T T T] result = [0 1 1 0 0 2 0 0 0 3 3 3] Or: X = [0 3 3 0 0 5 5 5 1 1 0 2] result = [0 1 1 0 0 2 2 2 3 3 0 4] T...
python
def label_contiguous_1d(X): """ WARNING: API for this function is not liable to change!!! By example: X = [F T T F F T F F F T T T] result = [0 1 1 0 0 2 0 0 0 3 3 3] Or: X = [0 3 3 0 0 5 5 5 1 1 0 2] result = [0 1 1 0 0 2 2 2 3 3 0 4] T...
[ "def", "label_contiguous_1d", "(", "X", ")", ":", "if", "X", ".", "ndim", "!=", "1", ":", "raise", "ValueError", "(", "\"this is for 1d masks only.\"", ")", "is_start", "=", "np", ".", "empty", "(", "len", "(", "X", ")", ",", "dtype", "=", "bool", ")",...
WARNING: API for this function is not liable to change!!! By example: X = [F T T F F T F F F T T T] result = [0 1 1 0 0 2 0 0 0 3 3 3] Or: X = [0 3 3 0 0 5 5 5 1 1 0 2] result = [0 1 1 0 0 2 2 2 3 3 0 4] The ``0`` or ``False`` elements of ``X`` a...
[ "WARNING", ":", "API", "for", "this", "function", "is", "not", "liable", "to", "change!!!", "By", "example", ":" ]
train
https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/utils_numpy.py#L335-L372
ml31415/numpy-groupies
numpy_groupies/utils_numpy.py
relabel_groups_unique
def relabel_groups_unique(group_idx): """ See also ``relabel_groups_masked``. keep_group: [0 3 3 3 0 2 5 2 0 1 1 0 3 5 5] ret: [0 3 3 3 0 2 4 2 0 1 1 0 3 4 4] Description of above: unique groups in input was ``1,2,3,5``, i.e. ``4`` was missing, so group 5 was relabled to be ``...
python
def relabel_groups_unique(group_idx): """ See also ``relabel_groups_masked``. keep_group: [0 3 3 3 0 2 5 2 0 1 1 0 3 5 5] ret: [0 3 3 3 0 2 4 2 0 1 1 0 3 4 4] Description of above: unique groups in input was ``1,2,3,5``, i.e. ``4`` was missing, so group 5 was relabled to be ``...
[ "def", "relabel_groups_unique", "(", "group_idx", ")", ":", "keep_group", "=", "np", ".", "zeros", "(", "np", ".", "max", "(", "group_idx", ")", "+", "1", ",", "dtype", "=", "bool", ")", "keep_group", "[", "0", "]", "=", "True", "keep_group", "[", "g...
See also ``relabel_groups_masked``. keep_group: [0 3 3 3 0 2 5 2 0 1 1 0 3 5 5] ret: [0 3 3 3 0 2 4 2 0 1 1 0 3 4 4] Description of above: unique groups in input was ``1,2,3,5``, i.e. ``4`` was missing, so group 5 was relabled to be ``4``. Relabeling maintains order, just "compres...
[ "See", "also", "relabel_groups_masked", ".", "keep_group", ":", "[", "0", "3", "3", "3", "0", "2", "5", "2", "0", "1", "1", "0", "3", "5", "5", "]", "ret", ":", "[", "0", "3", "3", "3", "0", "2", "4", "2", "0", "1", "1", "0", "3", "4", ...
train
https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/utils_numpy.py#L375-L391
ml31415/numpy-groupies
numpy_groupies/utils_numpy.py
relabel_groups_masked
def relabel_groups_masked(group_idx, keep_group): """ group_idx: [0 3 3 3 0 2 5 2 0 1 1 0 3 5 5] 0 1 2 3 4 5 keep_group: [0 1 0 1 1 1] ret: [0 2 2 2 0 0 4 0 0 1 1 0 2 4 4] Description of above in words: remove group 2, and relabel group 3,4, and 5 to be 2, 3 ...
python
def relabel_groups_masked(group_idx, keep_group): """ group_idx: [0 3 3 3 0 2 5 2 0 1 1 0 3 5 5] 0 1 2 3 4 5 keep_group: [0 1 0 1 1 1] ret: [0 2 2 2 0 0 4 0 0 1 1 0 2 4 4] Description of above in words: remove group 2, and relabel group 3,4, and 5 to be 2, 3 ...
[ "def", "relabel_groups_masked", "(", "group_idx", ",", "keep_group", ")", ":", "keep_group", "=", "keep_group", ".", "astype", "(", "bool", ",", "copy", "=", "not", "keep_group", "[", "0", "]", ")", "if", "not", "keep_group", "[", "0", "]", ":", "# ensur...
group_idx: [0 3 3 3 0 2 5 2 0 1 1 0 3 5 5] 0 1 2 3 4 5 keep_group: [0 1 0 1 1 1] ret: [0 2 2 2 0 0 4 0 0 1 1 0 2 4 4] Description of above in words: remove group 2, and relabel group 3,4, and 5 to be 2, 3 and 4 respecitvely, in order to fill the gap. Note that group...
[ "group_idx", ":", "[", "0", "3", "3", "3", "0", "2", "5", "2", "0", "1", "1", "0", "3", "5", "5", "]", "0", "1", "2", "3", "4", "5", "keep_group", ":", "[", "0", "1", "0", "1", "1", "1", "]", "ret", ":", "[", "0", "2", "2", "2", "0"...
train
https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/utils_numpy.py#L394-L423
ml31415/numpy-groupies
numpy_groupies/aggregate_numpy.py
_array
def _array(group_idx, a, size, fill_value, dtype=None): """groups a into separate arrays, keeping the order intact.""" if fill_value is not None and not (np.isscalar(fill_value) or len(fill_value) == 0): raise ValueError("fill_value must be None, a scalar or an emp...
python
def _array(group_idx, a, size, fill_value, dtype=None): """groups a into separate arrays, keeping the order intact.""" if fill_value is not None and not (np.isscalar(fill_value) or len(fill_value) == 0): raise ValueError("fill_value must be None, a scalar or an emp...
[ "def", "_array", "(", "group_idx", ",", "a", ",", "size", ",", "fill_value", ",", "dtype", "=", "None", ")", ":", "if", "fill_value", "is", "not", "None", "and", "not", "(", "np", ".", "isscalar", "(", "fill_value", ")", "or", "len", "(", "fill_value...
groups a into separate arrays, keeping the order intact.
[ "groups", "a", "into", "separate", "arrays", "keeping", "the", "order", "intact", "." ]
train
https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_numpy.py#L188-L200
ml31415/numpy-groupies
numpy_groupies/aggregate_numpy.py
_generic_callable
def _generic_callable(group_idx, a, size, fill_value, dtype=None, func=lambda g: g, **kwargs): """groups a by inds, and then applies foo to each group in turn, placing the results in an array.""" groups = _array(group_idx, a, size, ()) ret = np.full(size, fill_value, dtype=dtype or...
python
def _generic_callable(group_idx, a, size, fill_value, dtype=None, func=lambda g: g, **kwargs): """groups a by inds, and then applies foo to each group in turn, placing the results in an array.""" groups = _array(group_idx, a, size, ()) ret = np.full(size, fill_value, dtype=dtype or...
[ "def", "_generic_callable", "(", "group_idx", ",", "a", ",", "size", ",", "fill_value", ",", "dtype", "=", "None", ",", "func", "=", "lambda", "g", ":", "g", ",", "*", "*", "kwargs", ")", ":", "groups", "=", "_array", "(", "group_idx", ",", "a", ",...
groups a by inds, and then applies foo to each group in turn, placing the results in an array.
[ "groups", "a", "by", "inds", "and", "then", "applies", "foo", "to", "each", "group", "in", "turn", "placing", "the", "results", "in", "an", "array", "." ]
train
https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_numpy.py#L203-L213
ml31415/numpy-groupies
numpy_groupies/aggregate_numpy.py
_cumsum
def _cumsum(group_idx, a, size, fill_value=None, dtype=None): """ N to N aggregate operation of cumsum. Perform cumulative sum for each group. group_idx = np.array([4, 3, 3, 4, 4, 1, 1, 1, 7, 8, 7, 4, 3, 3, 1, 1]) a = np.array([3, 4, 1, 3, 9, 9, 6, 7, 7, 0, 8, 2, 1, 8, 9, 8]) _cumsum(group_idx, a, ...
python
def _cumsum(group_idx, a, size, fill_value=None, dtype=None): """ N to N aggregate operation of cumsum. Perform cumulative sum for each group. group_idx = np.array([4, 3, 3, 4, 4, 1, 1, 1, 7, 8, 7, 4, 3, 3, 1, 1]) a = np.array([3, 4, 1, 3, 9, 9, 6, 7, 7, 0, 8, 2, 1, 8, 9, 8]) _cumsum(group_idx, a, ...
[ "def", "_cumsum", "(", "group_idx", ",", "a", ",", "size", ",", "fill_value", "=", "None", ",", "dtype", "=", "None", ")", ":", "sortidx", "=", "np", ".", "argsort", "(", "group_idx", ",", "kind", "=", "'mergesort'", ")", "invsortidx", "=", "np", "."...
N to N aggregate operation of cumsum. Perform cumulative sum for each group. group_idx = np.array([4, 3, 3, 4, 4, 1, 1, 1, 7, 8, 7, 4, 3, 3, 1, 1]) a = np.array([3, 4, 1, 3, 9, 9, 6, 7, 7, 0, 8, 2, 1, 8, 9, 8]) _cumsum(group_idx, a, np.max(group_idx) + 1) >>> array([ 3, 4, 5, 6, 15, 9, 15, 22, 7, ...
[ "N", "to", "N", "aggregate", "operation", "of", "cumsum", ".", "Perform", "cumulative", "sum", "for", "each", "group", "." ]
train
https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_numpy.py#L216-L235
ml31415/numpy-groupies
numpy_groupies/aggregate_numpy.py
_fill_untouched
def _fill_untouched(idx, ret, fill_value): """any elements of ret not indexed by idx are set to fill_value.""" untouched = np.ones_like(ret, dtype=bool) untouched[idx] = False ret[untouched] = fill_value
python
def _fill_untouched(idx, ret, fill_value): """any elements of ret not indexed by idx are set to fill_value.""" untouched = np.ones_like(ret, dtype=bool) untouched[idx] = False ret[untouched] = fill_value
[ "def", "_fill_untouched", "(", "idx", ",", "ret", ",", "fill_value", ")", ":", "untouched", "=", "np", ".", "ones_like", "(", "ret", ",", "dtype", "=", "bool", ")", "untouched", "[", "idx", "]", "=", "False", "ret", "[", "untouched", "]", "=", "fill_...
any elements of ret not indexed by idx are set to fill_value.
[ "any", "elements", "of", "ret", "not", "indexed", "by", "idx", "are", "set", "to", "fill_value", "." ]
train
https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_numpy.py#L296-L300
ml31415/numpy-groupies
numpy_groupies/benchmarks/generic.py
aggregate_grouploop
def aggregate_grouploop(*args, **kwargs): """wraps func in lambda which prevents aggregate_numpy from recognising and optimising it. Instead it groups and loops.""" extrafuncs = {'allnan': allnan, 'anynan': anynan, 'first': itemgetter(0), 'last': itemgetter(-1), 'nanfirst...
python
def aggregate_grouploop(*args, **kwargs): """wraps func in lambda which prevents aggregate_numpy from recognising and optimising it. Instead it groups and loops.""" extrafuncs = {'allnan': allnan, 'anynan': anynan, 'first': itemgetter(0), 'last': itemgetter(-1), 'nanfirst...
[ "def", "aggregate_grouploop", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "extrafuncs", "=", "{", "'allnan'", ":", "allnan", ",", "'anynan'", ":", "anynan", ",", "'first'", ":", "itemgetter", "(", "0", ")", ",", "'last'", ":", "itemgetter", "(...
wraps func in lambda which prevents aggregate_numpy from recognising and optimising it. Instead it groups and loops.
[ "wraps", "func", "in", "lambda", "which", "prevents", "aggregate_numpy", "from", "recognising", "and", "optimising", "it", ".", "Instead", "it", "groups", "and", "loops", "." ]
train
https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/benchmarks/generic.py#L13-L23
ml31415/numpy-groupies
numpy_groupies/aggregate_numpy_ufunc.py
_prod
def _prod(group_idx, a, size, fill_value, dtype=None): """Same as aggregate_numpy.py""" dtype = minimum_dtype_scalar(fill_value, dtype, a) ret = np.full(size, fill_value, dtype=dtype) if fill_value != 1: ret[group_idx] = 1 # product should start from 1 np.multiply.at(ret, group_idx, a) ...
python
def _prod(group_idx, a, size, fill_value, dtype=None): """Same as aggregate_numpy.py""" dtype = minimum_dtype_scalar(fill_value, dtype, a) ret = np.full(size, fill_value, dtype=dtype) if fill_value != 1: ret[group_idx] = 1 # product should start from 1 np.multiply.at(ret, group_idx, a) ...
[ "def", "_prod", "(", "group_idx", ",", "a", ",", "size", ",", "fill_value", ",", "dtype", "=", "None", ")", ":", "dtype", "=", "minimum_dtype_scalar", "(", "fill_value", ",", "dtype", ",", "a", ")", "ret", "=", "np", ".", "full", "(", "size", ",", ...
Same as aggregate_numpy.py
[ "Same", "as", "aggregate_numpy", ".", "py" ]
train
https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_numpy_ufunc.py#L50-L57
ml31415/numpy-groupies
numpy_groupies/aggregate_weave.py
c_func
def c_func(funcname, reverse=False, nans=False, scalar=False): """ Fill c_funcs with constructed code from the templates """ varnames = ['group_idx', 'a', 'ret', 'counter'] codebase = c_base_reverse if reverse else c_base iteration = c_iter_scalar[funcname] if scalar else c_iter[funcname] if scalar:...
python
def c_func(funcname, reverse=False, nans=False, scalar=False): """ Fill c_funcs with constructed code from the templates """ varnames = ['group_idx', 'a', 'ret', 'counter'] codebase = c_base_reverse if reverse else c_base iteration = c_iter_scalar[funcname] if scalar else c_iter[funcname] if scalar:...
[ "def", "c_func", "(", "funcname", ",", "reverse", "=", "False", ",", "nans", "=", "False", ",", "scalar", "=", "False", ")", ":", "varnames", "=", "[", "'group_idx'", ",", "'a'", ",", "'ret'", ",", "'counter'", "]", "codebase", "=", "c_base_reverse", "...
Fill c_funcs with constructed code from the templates
[ "Fill", "c_funcs", "with", "constructed", "code", "from", "the", "templates" ]
train
https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_weave.py#L154-L163
ml31415/numpy-groupies
numpy_groupies/aggregate_weave.py
step_indices
def step_indices(group_idx): """ Get the edges of areas within group_idx, which are filled with the same value """ ilen = step_count(group_idx) + 1 indices = np.empty(ilen, int) indices[0] = 0 indices[-1] = group_idx.size inline(c_step_indices, ['group_idx', 'indices'], define_macro...
python
def step_indices(group_idx): """ Get the edges of areas within group_idx, which are filled with the same value """ ilen = step_count(group_idx) + 1 indices = np.empty(ilen, int) indices[0] = 0 indices[-1] = group_idx.size inline(c_step_indices, ['group_idx', 'indices'], define_macro...
[ "def", "step_indices", "(", "group_idx", ")", ":", "ilen", "=", "step_count", "(", "group_idx", ")", "+", "1", "indices", "=", "np", ".", "empty", "(", "ilen", ",", "int", ")", "indices", "[", "0", "]", "=", "0", "indices", "[", "-", "1", "]", "=...
Get the edges of areas within group_idx, which are filled with the same value
[ "Get", "the", "edges", "of", "areas", "within", "group_idx", "which", "are", "filled", "with", "the", "same", "value" ]
train
https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_weave.py#L212-L221
takuti/flurs
flurs/utils/projection.py
RandomProjection.__create_proj_mat
def __create_proj_mat(self, size): """Create a random projection matrix [1] D. Achlioptas. Database-friendly random projections: Johnson-Lindenstrauss with binary coins. [2] P. Li, et al. Very sparse random projections. http://scikit-learn.org/stable/modules/random_projection.html#spar...
python
def __create_proj_mat(self, size): """Create a random projection matrix [1] D. Achlioptas. Database-friendly random projections: Johnson-Lindenstrauss with binary coins. [2] P. Li, et al. Very sparse random projections. http://scikit-learn.org/stable/modules/random_projection.html#spar...
[ "def", "__create_proj_mat", "(", "self", ",", "size", ")", ":", "# [1]", "# return np.random.choice([-np.sqrt(3), 0, np.sqrt(3)], size=size, p=[1 / 6, 2 / 3, 1 / 6])", "# [2]", "s", "=", "1", "/", "self", ".", "density", "return", "np", ".", "random", ".", "choice", "...
Create a random projection matrix [1] D. Achlioptas. Database-friendly random projections: Johnson-Lindenstrauss with binary coins. [2] P. Li, et al. Very sparse random projections. http://scikit-learn.org/stable/modules/random_projection.html#sparse-random-projection
[ "Create", "a", "random", "projection", "matrix" ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/projection.py#L72-L88
takuti/flurs
flurs/datasets/movielens.py
load_movies
def load_movies(data_home, size): """Load movie genres as a context. Returns: dict of movie vectors: item_id -> numpy array (n_genre,) """ all_genres = ['Action', 'Adventure', 'Animation', "Children's", 'Comedy', ...
python
def load_movies(data_home, size): """Load movie genres as a context. Returns: dict of movie vectors: item_id -> numpy array (n_genre,) """ all_genres = ['Action', 'Adventure', 'Animation', "Children's", 'Comedy', ...
[ "def", "load_movies", "(", "data_home", ",", "size", ")", ":", "all_genres", "=", "[", "'Action'", ",", "'Adventure'", ",", "'Animation'", ",", "\"Children's\"", ",", "'Comedy'", ",", "'Crime'", ",", "'Documentary'", ",", "'Drama'", ",", "'Fantasy'", ",", "'...
Load movie genres as a context. Returns: dict of movie vectors: item_id -> numpy array (n_genre,)
[ "Load", "movie", "genres", "as", "a", "context", ".", "Returns", ":", "dict", "of", "movie", "vectors", ":", "item_id", "-", ">", "numpy", "array", "(", "n_genre", ")" ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/datasets/movielens.py#L12-L62
takuti/flurs
flurs/datasets/movielens.py
load_users
def load_users(data_home, size): """Load user demographics as contexts.User ID -> {sex (M/F), age (7 groupd), occupation(0-20; 21)} Returns: dict of user vectors: user_id -> numpy array (1+1+21,); (sex_flg + age_group + n_occupation, ) """ ages = [1, 18, 25, 35, 45, 50, 56, 999] users = {} ...
python
def load_users(data_home, size): """Load user demographics as contexts.User ID -> {sex (M/F), age (7 groupd), occupation(0-20; 21)} Returns: dict of user vectors: user_id -> numpy array (1+1+21,); (sex_flg + age_group + n_occupation, ) """ ages = [1, 18, 25, 35, 45, 50, 56, 999] users = {} ...
[ "def", "load_users", "(", "data_home", ",", "size", ")", ":", "ages", "=", "[", "1", ",", "18", ",", "25", ",", "35", ",", "45", ",", "50", ",", "56", ",", "999", "]", "users", "=", "{", "}", "if", "size", "==", "'100k'", ":", "all_occupations"...
Load user demographics as contexts.User ID -> {sex (M/F), age (7 groupd), occupation(0-20; 21)} Returns: dict of user vectors: user_id -> numpy array (1+1+21,); (sex_flg + age_group + n_occupation, )
[ "Load", "user", "demographics", "as", "contexts", ".", "User", "ID", "-", ">", "{", "sex", "(", "M", "/", "F", ")", "age", "(", "7", "groupd", ")", "occupation", "(", "0", "-", "20", ";", "21", ")", "}", "Returns", ":", "dict", "of", "user", "v...
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/datasets/movielens.py#L65-L124
takuti/flurs
flurs/datasets/movielens.py
load_ratings
def load_ratings(data_home, size): """Load all samples in the dataset. """ if size == '100k': with open(os.path.join(data_home, 'u.data'), encoding='ISO-8859-1') as f: lines = list(map(lambda l: list(map(int, l.rstrip().split('\t'))), f.readlines())) elif size == '1m': with ...
python
def load_ratings(data_home, size): """Load all samples in the dataset. """ if size == '100k': with open(os.path.join(data_home, 'u.data'), encoding='ISO-8859-1') as f: lines = list(map(lambda l: list(map(int, l.rstrip().split('\t'))), f.readlines())) elif size == '1m': with ...
[ "def", "load_ratings", "(", "data_home", ",", "size", ")", ":", "if", "size", "==", "'100k'", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "data_home", ",", "'u.data'", ")", ",", "encoding", "=", "'ISO-8859-1'", ")", "as", "f", ":",...
Load all samples in the dataset.
[ "Load", "all", "samples", "in", "the", "dataset", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/datasets/movielens.py#L127-L148
takuti/flurs
flurs/datasets/movielens.py
delta
def delta(d1, d2, opt='d'): """Compute difference between given 2 dates in month/day. """ delta = 0 if opt == 'm': while True: mdays = monthrange(d1.year, d1.month)[1] d1 += timedelta(days=mdays) if d1 <= d2: delta += 1 else: ...
python
def delta(d1, d2, opt='d'): """Compute difference between given 2 dates in month/day. """ delta = 0 if opt == 'm': while True: mdays = monthrange(d1.year, d1.month)[1] d1 += timedelta(days=mdays) if d1 <= d2: delta += 1 else: ...
[ "def", "delta", "(", "d1", ",", "d2", ",", "opt", "=", "'d'", ")", ":", "delta", "=", "0", "if", "opt", "==", "'m'", ":", "while", "True", ":", "mdays", "=", "monthrange", "(", "d1", ".", "year", ",", "d1", ".", "month", ")", "[", "1", "]", ...
Compute difference between given 2 dates in month/day.
[ "Compute", "difference", "between", "given", "2", "dates", "in", "month", "/", "day", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/datasets/movielens.py#L151-L167
takuti/flurs
flurs/utils/feature_hash.py
n_feature_hash
def n_feature_hash(feature, dims, seeds): """N-hot-encoded feature hashing. Args: feature (str): Target feature represented as string. dims (list of int): Number of dimensions for each hash value. seeds (list of float): Seed of each hash function (mmh3). Returns: numpy 1d a...
python
def n_feature_hash(feature, dims, seeds): """N-hot-encoded feature hashing. Args: feature (str): Target feature represented as string. dims (list of int): Number of dimensions for each hash value. seeds (list of float): Seed of each hash function (mmh3). Returns: numpy 1d a...
[ "def", "n_feature_hash", "(", "feature", ",", "dims", ",", "seeds", ")", ":", "vec", "=", "np", ".", "zeros", "(", "sum", "(", "dims", ")", ")", "offset", "=", "0", "for", "seed", ",", "dim", "in", "zip", "(", "seeds", ",", "dims", ")", ":", "v...
N-hot-encoded feature hashing. Args: feature (str): Target feature represented as string. dims (list of int): Number of dimensions for each hash value. seeds (list of float): Seed of each hash function (mmh3). Returns: numpy 1d array: n-hot-encoded feature vector for `s`.
[ "N", "-", "hot", "-", "encoded", "feature", "hashing", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/feature_hash.py#L5-L24
takuti/flurs
flurs/utils/feature_hash.py
feature_hash
def feature_hash(feature, dim, seed=123): """Feature hashing. Args: feature (str): Target feature represented as string. dim (int): Number of dimensions for a hash value. seed (float): Seed of a MurmurHash3 hash function. Returns: numpy 1d array: one-hot-encoded feature vec...
python
def feature_hash(feature, dim, seed=123): """Feature hashing. Args: feature (str): Target feature represented as string. dim (int): Number of dimensions for a hash value. seed (float): Seed of a MurmurHash3 hash function. Returns: numpy 1d array: one-hot-encoded feature vec...
[ "def", "feature_hash", "(", "feature", ",", "dim", ",", "seed", "=", "123", ")", ":", "vec", "=", "np", ".", "zeros", "(", "dim", ")", "i", "=", "mmh3", ".", "hash", "(", "feature", ",", "seed", ")", "%", "dim", "vec", "[", "i", "]", "=", "1"...
Feature hashing. Args: feature (str): Target feature represented as string. dim (int): Number of dimensions for a hash value. seed (float): Seed of a MurmurHash3 hash function. Returns: numpy 1d array: one-hot-encoded feature vector for `s`.
[ "Feature", "hashing", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/feature_hash.py#L27-L42
takuti/flurs
flurs/utils/metric.py
count_true_positive
def count_true_positive(truth, recommend): """Count number of true positives from given sets of samples. Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. Returns: int: Number of true positives. """ tp = 0 ...
python
def count_true_positive(truth, recommend): """Count number of true positives from given sets of samples. Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. Returns: int: Number of true positives. """ tp = 0 ...
[ "def", "count_true_positive", "(", "truth", ",", "recommend", ")", ":", "tp", "=", "0", "for", "r", "in", "recommend", ":", "if", "r", "in", "truth", ":", "tp", "+=", "1", "return", "tp" ]
Count number of true positives from given sets of samples. Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. Returns: int: Number of true positives.
[ "Count", "number", "of", "true", "positives", "from", "given", "sets", "of", "samples", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/metric.py#L4-L19
takuti/flurs
flurs/utils/metric.py
recall
def recall(truth, recommend, k=None): """Recall@k. Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. k (int): Top-k items in `recommend` will be recommended. Returns: float: Recall@k. """ if len(trut...
python
def recall(truth, recommend, k=None): """Recall@k. Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. k (int): Top-k items in `recommend` will be recommended. Returns: float: Recall@k. """ if len(trut...
[ "def", "recall", "(", "truth", ",", "recommend", ",", "k", "=", "None", ")", ":", "if", "len", "(", "truth", ")", "==", "0", ":", "if", "len", "(", "recommend", ")", "==", "0", ":", "return", "1.", "return", "0.", "if", "k", "is", "None", ":", ...
Recall@k. Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. k (int): Top-k items in `recommend` will be recommended. Returns: float: Recall@k.
[ "Recall@k", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/metric.py#L22-L41
takuti/flurs
flurs/utils/metric.py
precision
def precision(truth, recommend, k=None): """Precision@k. Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. k (int): Top-k items in `recommend` will be recommended. Returns: float: Precision@k. """ if...
python
def precision(truth, recommend, k=None): """Precision@k. Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. k (int): Top-k items in `recommend` will be recommended. Returns: float: Precision@k. """ if...
[ "def", "precision", "(", "truth", ",", "recommend", ",", "k", "=", "None", ")", ":", "if", "len", "(", "recommend", ")", "==", "0", ":", "if", "len", "(", "truth", ")", "==", "0", ":", "return", "1.", "return", "0.", "if", "k", "is", "None", ":...
Precision@k. Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. k (int): Top-k items in `recommend` will be recommended. Returns: float: Precision@k.
[ "Precision@k", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/metric.py#L44-L63
takuti/flurs
flurs/utils/metric.py
average_precision
def average_precision(truth, recommend): """Average Precision (AP). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. Returns: float: AP. """ if len(truth) == 0: if len(recommend) == 0: r...
python
def average_precision(truth, recommend): """Average Precision (AP). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. Returns: float: AP. """ if len(truth) == 0: if len(recommend) == 0: r...
[ "def", "average_precision", "(", "truth", ",", "recommend", ")", ":", "if", "len", "(", "truth", ")", "==", "0", ":", "if", "len", "(", "recommend", ")", "==", "0", ":", "return", "1.", "return", "0.", "tp", "=", "accum", "=", "0.", "for", "n", "...
Average Precision (AP). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. Returns: float: AP.
[ "Average", "Precision", "(", "AP", ")", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/metric.py#L66-L87
takuti/flurs
flurs/utils/metric.py
auc
def auc(truth, recommend): """Area under the ROC curve (AUC). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. Returns: float: AUC. """ tp = correct = 0. for r in recommend: if r in truth: ...
python
def auc(truth, recommend): """Area under the ROC curve (AUC). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. Returns: float: AUC. """ tp = correct = 0. for r in recommend: if r in truth: ...
[ "def", "auc", "(", "truth", ",", "recommend", ")", ":", "tp", "=", "correct", "=", "0.", "for", "r", "in", "recommend", ":", "if", "r", "in", "truth", ":", "# keep track number of true positives placed before", "tp", "+=", "1.", "else", ":", "correct", "+=...
Area under the ROC curve (AUC). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. Returns: float: AUC.
[ "Area", "under", "the", "ROC", "curve", "(", "AUC", ")", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/metric.py#L90-L115
takuti/flurs
flurs/utils/metric.py
reciprocal_rank
def reciprocal_rank(truth, recommend): """Reciprocal Rank (RR). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. Returns: float: RR. """ for n in range(recommend.size): if recommend[n] in truth: ...
python
def reciprocal_rank(truth, recommend): """Reciprocal Rank (RR). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. Returns: float: RR. """ for n in range(recommend.size): if recommend[n] in truth: ...
[ "def", "reciprocal_rank", "(", "truth", ",", "recommend", ")", ":", "for", "n", "in", "range", "(", "recommend", ".", "size", ")", ":", "if", "recommend", "[", "n", "]", "in", "truth", ":", "return", "1.", "/", "(", "n", "+", "1", ")", "return", ...
Reciprocal Rank (RR). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. Returns: float: RR.
[ "Reciprocal", "Rank", "(", "RR", ")", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/metric.py#L118-L132
takuti/flurs
flurs/utils/metric.py
mpr
def mpr(truth, recommend): """Mean Percentile Rank (MPR). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. Returns: float: MPR. """ if len(recommend) == 0 and len(truth) == 0: return 0. # best ...
python
def mpr(truth, recommend): """Mean Percentile Rank (MPR). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. Returns: float: MPR. """ if len(recommend) == 0 and len(truth) == 0: return 0. # best ...
[ "def", "mpr", "(", "truth", ",", "recommend", ")", ":", "if", "len", "(", "recommend", ")", "==", "0", "and", "len", "(", "truth", ")", "==", "0", ":", "return", "0.", "# best", "elif", "len", "(", "truth", ")", "==", "0", "or", "len", "(", "tr...
Mean Percentile Rank (MPR). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. Returns: float: MPR.
[ "Mean", "Percentile", "Rank", "(", "MPR", ")", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/metric.py#L135-L156
takuti/flurs
flurs/utils/metric.py
ndcg
def ndcg(truth, recommend, k=None): """Normalized Discounted Cumulative Grain (NDCG). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. k (int): Top-k items in `recommend` will be recommended. Returns: float:...
python
def ndcg(truth, recommend, k=None): """Normalized Discounted Cumulative Grain (NDCG). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. k (int): Top-k items in `recommend` will be recommended. Returns: float:...
[ "def", "ndcg", "(", "truth", ",", "recommend", ",", "k", "=", "None", ")", ":", "if", "k", "is", "None", ":", "k", "=", "len", "(", "recommend", ")", "def", "idcg", "(", "n_possible_truth", ")", ":", "res", "=", "0.", "for", "n", "in", "range", ...
Normalized Discounted Cumulative Grain (NDCG). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. k (int): Top-k items in `recommend` will be recommended. Returns: float: NDCG.
[ "Normalized", "Discounted", "Cumulative", "Grain", "(", "NDCG", ")", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/metric.py#L159-L189
takuti/flurs
flurs/base.py
RecommenderMixin.initialize
def initialize(self, *args): """Initialize a recommender by resetting stored users and items. """ # number of observed users self.n_user = 0 # store user data self.users = {} # number of observed items self.n_item = 0 # store item data s...
python
def initialize(self, *args): """Initialize a recommender by resetting stored users and items. """ # number of observed users self.n_user = 0 # store user data self.users = {} # number of observed items self.n_item = 0 # store item data s...
[ "def", "initialize", "(", "self", ",", "*", "args", ")", ":", "# number of observed users", "self", ".", "n_user", "=", "0", "# store user data", "self", ".", "users", "=", "{", "}", "# number of observed items", "self", ".", "n_item", "=", "0", "# store item ...
Initialize a recommender by resetting stored users and items.
[ "Initialize", "a", "recommender", "by", "resetting", "stored", "users", "and", "items", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/base.py#L11-L24
takuti/flurs
flurs/base.py
RecommenderMixin.register_user
def register_user(self, user): """For new users, append their information into the dictionaries. Args: user (User): User. """ self.users[user.index] = {'known_items': set()} self.n_user += 1
python
def register_user(self, user): """For new users, append their information into the dictionaries. Args: user (User): User. """ self.users[user.index] = {'known_items': set()} self.n_user += 1
[ "def", "register_user", "(", "self", ",", "user", ")", ":", "self", ".", "users", "[", "user", ".", "index", "]", "=", "{", "'known_items'", ":", "set", "(", ")", "}", "self", ".", "n_user", "+=", "1" ]
For new users, append their information into the dictionaries. Args: user (User): User.
[ "For", "new", "users", "append", "their", "information", "into", "the", "dictionaries", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/base.py#L45-L53
takuti/flurs
flurs/base.py
RecommenderMixin.scores2recos
def scores2recos(self, scores, candidates, rev=False): """Get recommendation list for a user u_index based on scores. Args: scores (numpy array; (n_target_items,)): Scores for the target items. Smaller score indicates a promising item. candidates (numpy array; (#...
python
def scores2recos(self, scores, candidates, rev=False): """Get recommendation list for a user u_index based on scores. Args: scores (numpy array; (n_target_items,)): Scores for the target items. Smaller score indicates a promising item. candidates (numpy array; (#...
[ "def", "scores2recos", "(", "self", ",", "scores", ",", "candidates", ",", "rev", "=", "False", ")", ":", "sorted_indices", "=", "np", ".", "argsort", "(", "scores", ")", "if", "rev", ":", "sorted_indices", "=", "sorted_indices", "[", ":", ":", "-", "1...
Get recommendation list for a user u_index based on scores. Args: scores (numpy array; (n_target_items,)): Scores for the target items. Smaller score indicates a promising item. candidates (numpy array; (# target items, )): Target items' indices. Only these items are con...
[ "Get", "recommendation", "list", "for", "a", "user", "u_index", "based", "on", "scores", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/base.py#L115-L133
takuti/flurs
flurs/evaluator.py
Evaluator.fit
def fit(self, train_events, test_events, n_epoch=1): """Train a model using the first 30% positive events to avoid cold-start. Evaluation of this batch training is done by using the next 20% positive events. After the batch SGD training, the models are incrementally updated by using the 20% tes...
python
def fit(self, train_events, test_events, n_epoch=1): """Train a model using the first 30% positive events to avoid cold-start. Evaluation of this batch training is done by using the next 20% positive events. After the batch SGD training, the models are incrementally updated by using the 20% tes...
[ "def", "fit", "(", "self", ",", "train_events", ",", "test_events", ",", "n_epoch", "=", "1", ")", ":", "# make initial status for batch training", "for", "e", "in", "train_events", ":", "self", ".", "__validate", "(", "e", ")", "self", ".", "rec", ".", "u...
Train a model using the first 30% positive events to avoid cold-start. Evaluation of this batch training is done by using the next 20% positive events. After the batch SGD training, the models are incrementally updated by using the 20% test events. Args: train_events (list of Event...
[ "Train", "a", "model", "using", "the", "first", "30%", "positive", "events", "to", "avoid", "cold", "-", "start", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/evaluator.py#L35-L64
takuti/flurs
flurs/evaluator.py
Evaluator.evaluate
def evaluate(self, test_events): """Iterate recommend/update procedure and compute incremental recall. Args: test_events (list of Event): Positive test events. Returns: list of tuples: (rank, recommend time, update time) """ for i, e in enumerate(test_e...
python
def evaluate(self, test_events): """Iterate recommend/update procedure and compute incremental recall. Args: test_events (list of Event): Positive test events. Returns: list of tuples: (rank, recommend time, update time) """ for i, e in enumerate(test_e...
[ "def", "evaluate", "(", "self", ",", "test_events", ")", ":", "for", "i", ",", "e", "in", "enumerate", "(", "test_events", ")", ":", "self", ".", "__validate", "(", "e", ")", "# target items (all or unobserved depending on a detaset)", "unobserved", "=", "set", ...
Iterate recommend/update procedure and compute incremental recall. Args: test_events (list of Event): Positive test events. Returns: list of tuples: (rank, recommend time, update time)
[ "Iterate", "recommend", "/", "update", "procedure", "and", "compute", "incremental", "recall", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/evaluator.py#L66-L106
takuti/flurs
flurs/evaluator.py
Evaluator.__batch_update
def __batch_update(self, train_events, test_events, n_epoch): """Batch update called by the fitting method. Args: train_events (list of Event): Positive training events. test_events (list of Event): Test events. n_epoch (int): Number of epochs for the batch training....
python
def __batch_update(self, train_events, test_events, n_epoch): """Batch update called by the fitting method. Args: train_events (list of Event): Positive training events. test_events (list of Event): Test events. n_epoch (int): Number of epochs for the batch training....
[ "def", "__batch_update", "(", "self", ",", "train_events", ",", "test_events", ",", "n_epoch", ")", ":", "for", "epoch", "in", "range", "(", "n_epoch", ")", ":", "# SGD requires us to shuffle events in each iteration", "# * if n_epoch == 1", "# => shuffle is not require...
Batch update called by the fitting method. Args: train_events (list of Event): Positive training events. test_events (list of Event): Test events. n_epoch (int): Number of epochs for the batch training.
[ "Batch", "update", "called", "by", "the", "fitting", "method", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/evaluator.py#L126-L149
takuti/flurs
flurs/evaluator.py
Evaluator.__batch_evaluate
def __batch_evaluate(self, test_events): """Evaluate the current model by using the given test events. Args: test_events (list of Event): Current model is evaluated by these events. Returns: float: Mean Percentile Rank for the test set. """ percentiles ...
python
def __batch_evaluate(self, test_events): """Evaluate the current model by using the given test events. Args: test_events (list of Event): Current model is evaluated by these events. Returns: float: Mean Percentile Rank for the test set. """ percentiles ...
[ "def", "__batch_evaluate", "(", "self", ",", "test_events", ")", ":", "percentiles", "=", "np", ".", "zeros", "(", "len", "(", "test_events", ")", ")", "all_items", "=", "set", "(", "self", ".", "item_buffer", ")", "for", "i", ",", "e", "in", "enumerat...
Evaluate the current model by using the given test events. Args: test_events (list of Event): Current model is evaluated by these events. Returns: float: Mean Percentile Rank for the test set.
[ "Evaluate", "the", "current", "model", "by", "using", "the", "given", "test", "events", "." ]
train
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/evaluator.py#L151-L180
linkedin/asciietch
asciietch/graph.py
Grapher._scale_x_values
def _scale_x_values(self, values, max_width): '''Scale X values to new width''' if type(values) == dict: values = self._scale_x_values_timestamps(values=values, max_width=max_width) adjusted_values = list(values) if len(adjusted_values) > max_width: def get_pos...
python
def _scale_x_values(self, values, max_width): '''Scale X values to new width''' if type(values) == dict: values = self._scale_x_values_timestamps(values=values, max_width=max_width) adjusted_values = list(values) if len(adjusted_values) > max_width: def get_pos...
[ "def", "_scale_x_values", "(", "self", ",", "values", ",", "max_width", ")", ":", "if", "type", "(", "values", ")", "==", "dict", ":", "values", "=", "self", ".", "_scale_x_values_timestamps", "(", "values", "=", "values", ",", "max_width", "=", "max_width...
Scale X values to new width
[ "Scale", "X", "values", "to", "new", "width" ]
train
https://github.com/linkedin/asciietch/blob/33499e9b1c5226c04078d08a210ef657c630291c/asciietch/graph.py#L11-L25
linkedin/asciietch
asciietch/graph.py
Grapher._scale_x_values_timestamps
def _scale_x_values_timestamps(self, values, max_width): '''Scale X values to new width based on timestamps''' first_timestamp = float(values[0][0]) last_timestamp = float(values[-1][0]) step_size = (last_timestamp - first_timestamp) / max_width values_by_column = [[] for i in r...
python
def _scale_x_values_timestamps(self, values, max_width): '''Scale X values to new width based on timestamps''' first_timestamp = float(values[0][0]) last_timestamp = float(values[-1][0]) step_size = (last_timestamp - first_timestamp) / max_width values_by_column = [[] for i in r...
[ "def", "_scale_x_values_timestamps", "(", "self", ",", "values", ",", "max_width", ")", ":", "first_timestamp", "=", "float", "(", "values", "[", "0", "]", "[", "0", "]", ")", "last_timestamp", "=", "float", "(", "values", "[", "-", "1", "]", "[", "0",...
Scale X values to new width based on timestamps
[ "Scale", "X", "values", "to", "new", "width", "based", "on", "timestamps" ]
train
https://github.com/linkedin/asciietch/blob/33499e9b1c5226c04078d08a210ef657c630291c/asciietch/graph.py#L27-L44
linkedin/asciietch
asciietch/graph.py
Grapher._scale_y_values
def _scale_y_values(self, values, new_min, new_max, scale_old_from_zero=True): ''' Take values and transmute them into a new range ''' # Scale Y values - Create a scaled list of values to use for the visual graph scaled_values = [] y_min_value = min(values) if sca...
python
def _scale_y_values(self, values, new_min, new_max, scale_old_from_zero=True): ''' Take values and transmute them into a new range ''' # Scale Y values - Create a scaled list of values to use for the visual graph scaled_values = [] y_min_value = min(values) if sca...
[ "def", "_scale_y_values", "(", "self", ",", "values", ",", "new_min", ",", "new_max", ",", "scale_old_from_zero", "=", "True", ")", ":", "# Scale Y values - Create a scaled list of values to use for the visual graph", "scaled_values", "=", "[", "]", "y_min_value", "=", ...
Take values and transmute them into a new range
[ "Take", "values", "and", "transmute", "them", "into", "a", "new", "range" ]
train
https://github.com/linkedin/asciietch/blob/33499e9b1c5226c04078d08a210ef657c630291c/asciietch/graph.py#L46-L62
linkedin/asciietch
asciietch/graph.py
Grapher._get_ascii_field
def _get_ascii_field(self, values): '''Create a representation of an ascii graph using two lists in this format: field[x][y] = "char"''' empty_space = ' ' # This formats as field[x][y] field = [[empty_space for y in range(max(values) + 1)] for x in range(len(values))] # Draw g...
python
def _get_ascii_field(self, values): '''Create a representation of an ascii graph using two lists in this format: field[x][y] = "char"''' empty_space = ' ' # This formats as field[x][y] field = [[empty_space for y in range(max(values) + 1)] for x in range(len(values))] # Draw g...
[ "def", "_get_ascii_field", "(", "self", ",", "values", ")", ":", "empty_space", "=", "' '", "# This formats as field[x][y]", "field", "=", "[", "[", "empty_space", "for", "y", "in", "range", "(", "max", "(", "values", ")", "+", "1", ")", "]", "for", "x",...
Create a representation of an ascii graph using two lists in this format: field[x][y] = "char"
[ "Create", "a", "representation", "of", "an", "ascii", "graph", "using", "two", "lists", "in", "this", "format", ":", "field", "[", "x", "]", "[", "y", "]", "=", "char" ]
train
https://github.com/linkedin/asciietch/blob/33499e9b1c5226c04078d08a210ef657c630291c/asciietch/graph.py#L68-L95
linkedin/asciietch
asciietch/graph.py
Grapher._assign_ascii_character
def _assign_ascii_character(self, y_prev, y, y_next): # noqa for complexity '''Assign the character to be placed into the graph''' char = '?' if y_next > y and y_prev > y: char = '-' elif y_next < y and y_prev < y: char = '-' e...
python
def _assign_ascii_character(self, y_prev, y, y_next): # noqa for complexity '''Assign the character to be placed into the graph''' char = '?' if y_next > y and y_prev > y: char = '-' elif y_next < y and y_prev < y: char = '-' e...
[ "def", "_assign_ascii_character", "(", "self", ",", "y_prev", ",", "y", ",", "y_next", ")", ":", "# noqa for complexity", "char", "=", "'?'", "if", "y_next", ">", "y", "and", "y_prev", ">", "y", ":", "char", "=", "'-'", "elif", "y_next", "<", "y", "and...
Assign the character to be placed into the graph
[ "Assign", "the", "character", "to", "be", "placed", "into", "the", "graph" ]
train
https://github.com/linkedin/asciietch/blob/33499e9b1c5226c04078d08a210ef657c630291c/asciietch/graph.py#L97-L120
linkedin/asciietch
asciietch/graph.py
Grapher._draw_ascii_graph
def _draw_ascii_graph(self, field): '''Draw graph from field double nested list, format field[x][y] = char''' row_strings = [] for y in range(len(field[0])): row = '' for x in range(len(field)): row += field[x][y] row_strings.insert(0, row) ...
python
def _draw_ascii_graph(self, field): '''Draw graph from field double nested list, format field[x][y] = char''' row_strings = [] for y in range(len(field[0])): row = '' for x in range(len(field)): row += field[x][y] row_strings.insert(0, row) ...
[ "def", "_draw_ascii_graph", "(", "self", ",", "field", ")", ":", "row_strings", "=", "[", "]", "for", "y", "in", "range", "(", "len", "(", "field", "[", "0", "]", ")", ")", ":", "row", "=", "''", "for", "x", "in", "range", "(", "len", "(", "fie...
Draw graph from field double nested list, format field[x][y] = char
[ "Draw", "graph", "from", "field", "double", "nested", "list", "format", "field", "[", "x", "]", "[", "y", "]", "=", "char" ]
train
https://github.com/linkedin/asciietch/blob/33499e9b1c5226c04078d08a210ef657c630291c/asciietch/graph.py#L122-L131
linkedin/asciietch
asciietch/graph.py
Grapher.asciigraph
def asciigraph(self, values=None, max_height=None, max_width=None, label=False): ''' Accepts a list of y values and returns an ascii graph Optionally values can also be a dictionary with a key of timestamp, and a value of value. InGraphs returns data in this format for example. ''' ...
python
def asciigraph(self, values=None, max_height=None, max_width=None, label=False): ''' Accepts a list of y values and returns an ascii graph Optionally values can also be a dictionary with a key of timestamp, and a value of value. InGraphs returns data in this format for example. ''' ...
[ "def", "asciigraph", "(", "self", ",", "values", "=", "None", ",", "max_height", "=", "None", ",", "max_width", "=", "None", ",", "label", "=", "False", ")", ":", "result", "=", "''", "border_fill_char", "=", "'*'", "start_ctime", "=", "None", "end_ctime...
Accepts a list of y values and returns an ascii graph Optionally values can also be a dictionary with a key of timestamp, and a value of value. InGraphs returns data in this format for example.
[ "Accepts", "a", "list", "of", "y", "values", "and", "returns", "an", "ascii", "graph", "Optionally", "values", "can", "also", "be", "a", "dictionary", "with", "a", "key", "of", "timestamp", "and", "a", "value", "of", "value", ".", "InGraphs", "returns", ...
train
https://github.com/linkedin/asciietch/blob/33499e9b1c5226c04078d08a210ef657c630291c/asciietch/graph.py#L133-L192
HPAC/matchpy
matchpy/functions.py
substitute
def substitute(expression: Union[Expression, Pattern], substitution: Substitution) -> Replacement: """Replaces variables in the given *expression* using the given *substitution*. >>> print(substitute(f(x_), {'x': a})) f(a) If nothing was substituted, the original expression is returned: >>> expre...
python
def substitute(expression: Union[Expression, Pattern], substitution: Substitution) -> Replacement: """Replaces variables in the given *expression* using the given *substitution*. >>> print(substitute(f(x_), {'x': a})) f(a) If nothing was substituted, the original expression is returned: >>> expre...
[ "def", "substitute", "(", "expression", ":", "Union", "[", "Expression", ",", "Pattern", "]", ",", "substitution", ":", "Substitution", ")", "->", "Replacement", ":", "if", "isinstance", "(", "expression", ",", "Pattern", ")", ":", "expression", "=", "expres...
Replaces variables in the given *expression* using the given *substitution*. >>> print(substitute(f(x_), {'x': a})) f(a) If nothing was substituted, the original expression is returned: >>> expression = f(x_) >>> result = substitute(expression, {'y': a}) >>> print(result) f(x_) >>> ex...
[ "Replaces", "variables", "in", "the", "given", "*", "expression", "*", "using", "the", "given", "*", "substitution", "*", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/functions.py#L30-L71
HPAC/matchpy
matchpy/functions.py
replace
def replace(expression: Expression, position: Sequence[int], replacement: Replacement) -> Replacement: r"""Replaces the subexpression of `expression` at the given `position` with the given `replacement`. The original `expression` itself is not modified, but a modified copy is returned. If the replacement i...
python
def replace(expression: Expression, position: Sequence[int], replacement: Replacement) -> Replacement: r"""Replaces the subexpression of `expression` at the given `position` with the given `replacement`. The original `expression` itself is not modified, but a modified copy is returned. If the replacement i...
[ "def", "replace", "(", "expression", ":", "Expression", ",", "position", ":", "Sequence", "[", "int", "]", ",", "replacement", ":", "Replacement", ")", "->", "Replacement", ":", "if", "len", "(", "position", ")", "==", "0", ":", "return", "replacement", ...
r"""Replaces the subexpression of `expression` at the given `position` with the given `replacement`. The original `expression` itself is not modified, but a modified copy is returned. If the replacement is a list of expressions, it will be expanded into the list of operands of the respective operation: >>...
[ "r", "Replaces", "the", "subexpression", "of", "expression", "at", "the", "given", "position", "with", "the", "given", "replacement", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/functions.py#L96-L135
HPAC/matchpy
matchpy/functions.py
replace_many
def replace_many(expression: Expression, replacements: Sequence[Tuple[Sequence[int], Replacement]]) -> Replacement: r"""Replaces the subexpressions of *expression* at the given positions with the given replacements. The original *expression* itself is not modified, but a modified copy is returned. If the repla...
python
def replace_many(expression: Expression, replacements: Sequence[Tuple[Sequence[int], Replacement]]) -> Replacement: r"""Replaces the subexpressions of *expression* at the given positions with the given replacements. The original *expression* itself is not modified, but a modified copy is returned. If the repla...
[ "def", "replace_many", "(", "expression", ":", "Expression", ",", "replacements", ":", "Sequence", "[", "Tuple", "[", "Sequence", "[", "int", "]", ",", "Replacement", "]", "]", ")", "->", "Replacement", ":", "if", "len", "(", "replacements", ")", "==", "...
r"""Replaces the subexpressions of *expression* at the given positions with the given replacements. The original *expression* itself is not modified, but a modified copy is returned. If the replacement is a sequence of expressions, it will be expanded into the list of operands of the respective operation. ...
[ "r", "Replaces", "the", "subexpressions", "of", "*", "expression", "*", "at", "the", "given", "positions", "with", "the", "given", "replacements", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/functions.py#L138-L208
HPAC/matchpy
matchpy/functions.py
replace_all
def replace_all(expression: Expression, rules: Iterable[ReplacementRule], max_count: int=math.inf) \ -> Union[Expression, Sequence[Expression]]: """Replace all occurrences of the patterns according to the replacement rules. A replacement rule consists of a *pattern*, that is matched against any subexpr...
python
def replace_all(expression: Expression, rules: Iterable[ReplacementRule], max_count: int=math.inf) \ -> Union[Expression, Sequence[Expression]]: """Replace all occurrences of the patterns according to the replacement rules. A replacement rule consists of a *pattern*, that is matched against any subexpr...
[ "def", "replace_all", "(", "expression", ":", "Expression", ",", "rules", ":", "Iterable", "[", "ReplacementRule", "]", ",", "max_count", ":", "int", "=", "math", ".", "inf", ")", "->", "Union", "[", "Expression", ",", "Sequence", "[", "Expression", "]", ...
Replace all occurrences of the patterns according to the replacement rules. A replacement rule consists of a *pattern*, that is matched against any subexpression of the expression. If a match is found, the *replacement* callback of the rule is called with the variables from the match substitution. Whatever...
[ "Replace", "all", "occurrences", "of", "the", "patterns", "according", "to", "the", "replacement", "rules", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/functions.py#L214-L261
HPAC/matchpy
matchpy/functions.py
replace_all_post_order
def replace_all_post_order(expression: Expression, rules: Iterable[ReplacementRule]) \ -> Union[Expression, Sequence[Expression]]: """Replace all occurrences of the patterns according to the replacement rules. A replacement rule consists of a *pattern*, that is matched against any subexpression of ...
python
def replace_all_post_order(expression: Expression, rules: Iterable[ReplacementRule]) \ -> Union[Expression, Sequence[Expression]]: """Replace all occurrences of the patterns according to the replacement rules. A replacement rule consists of a *pattern*, that is matched against any subexpression of ...
[ "def", "replace_all_post_order", "(", "expression", ":", "Expression", ",", "rules", ":", "Iterable", "[", "ReplacementRule", "]", ")", "->", "Union", "[", "Expression", ",", "Sequence", "[", "Expression", "]", "]", ":", "return", "_replace_all_post_order", "(",...
Replace all occurrences of the patterns according to the replacement rules. A replacement rule consists of a *pattern*, that is matched against any subexpression of the expression. If a match is found, the *replacement* callback of the rule is called with the variables from the match substitution. Whatever...
[ "Replace", "all", "occurrences", "of", "the", "patterns", "according", "to", "the", "replacement", "rules", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/functions.py#L264-L291
HPAC/matchpy
matchpy/functions.py
is_match
def is_match(subject: Expression, pattern: Expression) -> bool: """ Check whether the given *subject* matches given *pattern*. Args: subject: The subject. pattern: The pattern. Returns: True iff the subject matches the pattern. """ return any(Tru...
python
def is_match(subject: Expression, pattern: Expression) -> bool: """ Check whether the given *subject* matches given *pattern*. Args: subject: The subject. pattern: The pattern. Returns: True iff the subject matches the pattern. """ return any(Tru...
[ "def", "is_match", "(", "subject", ":", "Expression", ",", "pattern", ":", "Expression", ")", "->", "bool", ":", "return", "any", "(", "True", "for", "_", "in", "match", "(", "subject", ",", "pattern", ")", ")" ]
Check whether the given *subject* matches given *pattern*. Args: subject: The subject. pattern: The pattern. Returns: True iff the subject matches the pattern.
[ "Check", "whether", "the", "given", "*", "subject", "*", "matches", "given", "*", "pattern", "*", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/functions.py#L315-L328
HPAC/matchpy
matchpy/matching/bipartite.py
BipartiteGraph.as_graph
def as_graph(self) -> Graph: # pragma: no cover """Returns a :class:`graphviz.Graph` representation of this bipartite graph.""" if Graph is None: raise ImportError('The graphviz package is required to draw the graph.') graph = Graph() nodes_left = {} # type: Dict[TLeft, str...
python
def as_graph(self) -> Graph: # pragma: no cover """Returns a :class:`graphviz.Graph` representation of this bipartite graph.""" if Graph is None: raise ImportError('The graphviz package is required to draw the graph.') graph = Graph() nodes_left = {} # type: Dict[TLeft, str...
[ "def", "as_graph", "(", "self", ")", "->", "Graph", ":", "# pragma: no cover", "if", "Graph", "is", "None", ":", "raise", "ImportError", "(", "'The graphviz package is required to draw the graph.'", ")", "graph", "=", "Graph", "(", ")", "nodes_left", "=", "{", "...
Returns a :class:`graphviz.Graph` representation of this bipartite graph.
[ "Returns", "a", ":", "class", ":", "graphviz", ".", "Graph", "representation", "of", "this", "bipartite", "graph", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/bipartite.py#L121-L142
HPAC/matchpy
matchpy/matching/bipartite.py
BipartiteGraph.find_matching
def find_matching(self) -> Dict[TLeft, TRight]: """Finds a matching in the bipartite graph. This is done using the Hopcroft-Karp algorithm with an implementation from the `hopcroftkarp` package. Returns: A dictionary where each edge of the matching is represented by a key-v...
python
def find_matching(self) -> Dict[TLeft, TRight]: """Finds a matching in the bipartite graph. This is done using the Hopcroft-Karp algorithm with an implementation from the `hopcroftkarp` package. Returns: A dictionary where each edge of the matching is represented by a key-v...
[ "def", "find_matching", "(", "self", ")", "->", "Dict", "[", "TLeft", ",", "TRight", "]", ":", "# The directed graph is represented as a dictionary of edges", "# The key is the tail of all edges which are represented by the value", "# The value is a set of heads for the all edges origi...
Finds a matching in the bipartite graph. This is done using the Hopcroft-Karp algorithm with an implementation from the `hopcroftkarp` package. Returns: A dictionary where each edge of the matching is represented by a key-value pair with the key being from the left part...
[ "Finds", "a", "matching", "in", "the", "bipartite", "graph", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/bipartite.py#L144-L174
HPAC/matchpy
matchpy/matching/bipartite.py
BipartiteGraph.without_nodes
def without_nodes(self, edge: Edge) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]': """Returns a copy of this bipartite graph with the given edge and its adjacent nodes removed.""" return BipartiteGraph(((n1, n2), v) for (n1, n2), v in self._edges.items() if n1 != edge[0] and n2 != edge[1])
python
def without_nodes(self, edge: Edge) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]': """Returns a copy of this bipartite graph with the given edge and its adjacent nodes removed.""" return BipartiteGraph(((n1, n2), v) for (n1, n2), v in self._edges.items() if n1 != edge[0] and n2 != edge[1])
[ "def", "without_nodes", "(", "self", ",", "edge", ":", "Edge", ")", "->", "'BipartiteGraph[TLeft, TRight, TEdgeValue]'", ":", "return", "BipartiteGraph", "(", "(", "(", "n1", ",", "n2", ")", ",", "v", ")", "for", "(", "n1", ",", "n2", ")", ",", "v", "i...
Returns a copy of this bipartite graph with the given edge and its adjacent nodes removed.
[ "Returns", "a", "copy", "of", "this", "bipartite", "graph", "with", "the", "given", "edge", "and", "its", "adjacent", "nodes", "removed", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/bipartite.py#L176-L178
HPAC/matchpy
matchpy/matching/bipartite.py
BipartiteGraph.without_edge
def without_edge(self, edge: Edge) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]': """Returns a copy of this bipartite graph with the given edge removed.""" return BipartiteGraph((e2, v) for e2, v in self._edges.items() if edge != e2)
python
def without_edge(self, edge: Edge) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]': """Returns a copy of this bipartite graph with the given edge removed.""" return BipartiteGraph((e2, v) for e2, v in self._edges.items() if edge != e2)
[ "def", "without_edge", "(", "self", ",", "edge", ":", "Edge", ")", "->", "'BipartiteGraph[TLeft, TRight, TEdgeValue]'", ":", "return", "BipartiteGraph", "(", "(", "e2", ",", "v", ")", "for", "e2", ",", "v", "in", "self", ".", "_edges", ".", "items", "(", ...
Returns a copy of this bipartite graph with the given edge removed.
[ "Returns", "a", "copy", "of", "this", "bipartite", "graph", "with", "the", "given", "edge", "removed", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/bipartite.py#L180-L182
HPAC/matchpy
matchpy/matching/bipartite.py
BipartiteGraph.limited_to
def limited_to(self, left: Set[TLeft], right: Set[TRight]) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]': """Returns the induced subgraph where only the nodes from the given sets are included.""" return BipartiteGraph(((n1, n2), v) for (n1, n2), v in self._edges.items() if n1 in left and n2 in right)
python
def limited_to(self, left: Set[TLeft], right: Set[TRight]) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]': """Returns the induced subgraph where only the nodes from the given sets are included.""" return BipartiteGraph(((n1, n2), v) for (n1, n2), v in self._edges.items() if n1 in left and n2 in right)
[ "def", "limited_to", "(", "self", ",", "left", ":", "Set", "[", "TLeft", "]", ",", "right", ":", "Set", "[", "TRight", "]", ")", "->", "'BipartiteGraph[TLeft, TRight, TEdgeValue]'", ":", "return", "BipartiteGraph", "(", "(", "(", "n1", ",", "n2", ")", ",...
Returns the induced subgraph where only the nodes from the given sets are included.
[ "Returns", "the", "induced", "subgraph", "where", "only", "the", "nodes", "from", "the", "given", "sets", "are", "included", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/bipartite.py#L184-L186
HPAC/matchpy
matchpy/matching/bipartite.py
_DirectedMatchGraph.as_graph
def as_graph(self) -> Digraph: # pragma: no cover """Returns a :class:`graphviz.Digraph` representation of this directed match graph.""" if Digraph is None: raise ImportError('The graphviz package is required to draw the graph.') graph = Digraph() subgraphs = [Digraph(graph...
python
def as_graph(self) -> Digraph: # pragma: no cover """Returns a :class:`graphviz.Digraph` representation of this directed match graph.""" if Digraph is None: raise ImportError('The graphviz package is required to draw the graph.') graph = Digraph() subgraphs = [Digraph(graph...
[ "def", "as_graph", "(", "self", ")", "->", "Digraph", ":", "# pragma: no cover", "if", "Digraph", "is", "None", ":", "raise", "ImportError", "(", "'The graphviz package is required to draw the graph.'", ")", "graph", "=", "Digraph", "(", ")", "subgraphs", "=", "["...
Returns a :class:`graphviz.Digraph` representation of this directed match graph.
[ "Returns", "a", ":", "class", ":", "graphviz", ".", "Digraph", "representation", "of", "this", "directed", "match", "graph", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/bipartite.py#L203-L230
HPAC/matchpy
matchpy/expressions/functions.py
is_constant
def is_constant(expression): """Check if the given expression is constant, i.e. it does not contain Wildcards.""" if isinstance(expression, Wildcard): return False if isinstance(expression, Expression): return expression.is_constant if isinstance(expression, Operation): return al...
python
def is_constant(expression): """Check if the given expression is constant, i.e. it does not contain Wildcards.""" if isinstance(expression, Wildcard): return False if isinstance(expression, Expression): return expression.is_constant if isinstance(expression, Operation): return al...
[ "def", "is_constant", "(", "expression", ")", ":", "if", "isinstance", "(", "expression", ",", "Wildcard", ")", ":", "return", "False", "if", "isinstance", "(", "expression", ",", "Expression", ")", ":", "return", "expression", ".", "is_constant", "if", "isi...
Check if the given expression is constant, i.e. it does not contain Wildcards.
[ "Check", "if", "the", "given", "expression", "is", "constant", "i", ".", "e", ".", "it", "does", "not", "contain", "Wildcards", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/functions.py#L15-L23
HPAC/matchpy
matchpy/expressions/functions.py
is_syntactic
def is_syntactic(expression): """ Check if the given expression is syntactic, i.e. it does not contain sequence wildcards or associative/commutative operations. """ if isinstance(expression, Wildcard): return expression.fixed_size if isinstance(expression, Expression): return exp...
python
def is_syntactic(expression): """ Check if the given expression is syntactic, i.e. it does not contain sequence wildcards or associative/commutative operations. """ if isinstance(expression, Wildcard): return expression.fixed_size if isinstance(expression, Expression): return exp...
[ "def", "is_syntactic", "(", "expression", ")", ":", "if", "isinstance", "(", "expression", ",", "Wildcard", ")", ":", "return", "expression", ".", "fixed_size", "if", "isinstance", "(", "expression", ",", "Expression", ")", ":", "return", "expression", ".", ...
Check if the given expression is syntactic, i.e. it does not contain sequence wildcards or associative/commutative operations.
[ "Check", "if", "the", "given", "expression", "is", "syntactic", "i", ".", "e", ".", "it", "does", "not", "contain", "sequence", "wildcards", "or", "associative", "/", "commutative", "operations", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/functions.py#L26-L39
HPAC/matchpy
matchpy/expressions/functions.py
get_head
def get_head(expression): """Returns the given expression's head.""" if isinstance(expression, Wildcard): if isinstance(expression, SymbolWildcard): return expression.symbol_type return None return type(expression)
python
def get_head(expression): """Returns the given expression's head.""" if isinstance(expression, Wildcard): if isinstance(expression, SymbolWildcard): return expression.symbol_type return None return type(expression)
[ "def", "get_head", "(", "expression", ")", ":", "if", "isinstance", "(", "expression", ",", "Wildcard", ")", ":", "if", "isinstance", "(", "expression", ",", "SymbolWildcard", ")", ":", "return", "expression", ".", "symbol_type", "return", "None", "return", ...
Returns the given expression's head.
[ "Returns", "the", "given", "expression", "s", "head", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/functions.py#L42-L48
HPAC/matchpy
matchpy/expressions/functions.py
match_head
def match_head(subject, pattern): """Checks if the head of subject matches the pattern's head.""" if isinstance(pattern, Pattern): pattern = pattern.expression pattern_head = get_head(pattern) if pattern_head is None: return True if issubclass(pattern_head, OneIdentityOperation): ...
python
def match_head(subject, pattern): """Checks if the head of subject matches the pattern's head.""" if isinstance(pattern, Pattern): pattern = pattern.expression pattern_head = get_head(pattern) if pattern_head is None: return True if issubclass(pattern_head, OneIdentityOperation): ...
[ "def", "match_head", "(", "subject", ",", "pattern", ")", ":", "if", "isinstance", "(", "pattern", ",", "Pattern", ")", ":", "pattern", "=", "pattern", ".", "expression", "pattern_head", "=", "get_head", "(", "pattern", ")", "if", "pattern_head", "is", "No...
Checks if the head of subject matches the pattern's head.
[ "Checks", "if", "the", "head", "of", "subject", "matches", "the", "pattern", "s", "head", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/functions.py#L51-L62
HPAC/matchpy
matchpy/expressions/functions.py
preorder_iter
def preorder_iter(expression): """Iterate over the expression in preorder.""" yield expression if isinstance(expression, Operation): for operand in op_iter(expression): yield from preorder_iter(operand)
python
def preorder_iter(expression): """Iterate over the expression in preorder.""" yield expression if isinstance(expression, Operation): for operand in op_iter(expression): yield from preorder_iter(operand)
[ "def", "preorder_iter", "(", "expression", ")", ":", "yield", "expression", "if", "isinstance", "(", "expression", ",", "Operation", ")", ":", "for", "operand", "in", "op_iter", "(", "expression", ")", ":", "yield", "from", "preorder_iter", "(", "operand", "...
Iterate over the expression in preorder.
[ "Iterate", "over", "the", "expression", "in", "preorder", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/functions.py#L65-L70
HPAC/matchpy
matchpy/expressions/functions.py
preorder_iter_with_position
def preorder_iter_with_position(expression): """Iterate over the expression in preorder. Also yields the position of each subexpression. """ yield expression, () if isinstance(expression, Operation): for i, operand in enumerate(op_iter(expression)): for child, pos in preorder_it...
python
def preorder_iter_with_position(expression): """Iterate over the expression in preorder. Also yields the position of each subexpression. """ yield expression, () if isinstance(expression, Operation): for i, operand in enumerate(op_iter(expression)): for child, pos in preorder_it...
[ "def", "preorder_iter_with_position", "(", "expression", ")", ":", "yield", "expression", ",", "(", ")", "if", "isinstance", "(", "expression", ",", "Operation", ")", ":", "for", "i", ",", "operand", "in", "enumerate", "(", "op_iter", "(", "expression", ")",...
Iterate over the expression in preorder. Also yields the position of each subexpression.
[ "Iterate", "over", "the", "expression", "in", "preorder", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/functions.py#L73-L82
HPAC/matchpy
matchpy/expressions/functions.py
is_anonymous
def is_anonymous(expression): """Returns True iff the expression does not contain any variables.""" if hasattr(expression, 'variable_name') and expression.variable_name: return False if isinstance(expression, Operation): return all(is_anonymous(o) for o in op_iter(expression)) return Tru...
python
def is_anonymous(expression): """Returns True iff the expression does not contain any variables.""" if hasattr(expression, 'variable_name') and expression.variable_name: return False if isinstance(expression, Operation): return all(is_anonymous(o) for o in op_iter(expression)) return Tru...
[ "def", "is_anonymous", "(", "expression", ")", ":", "if", "hasattr", "(", "expression", ",", "'variable_name'", ")", "and", "expression", ".", "variable_name", ":", "return", "False", "if", "isinstance", "(", "expression", ",", "Operation", ")", ":", "return",...
Returns True iff the expression does not contain any variables.
[ "Returns", "True", "iff", "the", "expression", "does", "not", "contain", "any", "variables", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/functions.py#L85-L91
HPAC/matchpy
matchpy/expressions/functions.py
contains_variables_from_set
def contains_variables_from_set(expression, variables): """Returns True iff the expression contains any of the variables from the given set.""" if hasattr(expression, 'variable_name') and expression.variable_name in variables: return True if isinstance(expression, Operation): return any(cont...
python
def contains_variables_from_set(expression, variables): """Returns True iff the expression contains any of the variables from the given set.""" if hasattr(expression, 'variable_name') and expression.variable_name in variables: return True if isinstance(expression, Operation): return any(cont...
[ "def", "contains_variables_from_set", "(", "expression", ",", "variables", ")", ":", "if", "hasattr", "(", "expression", ",", "'variable_name'", ")", "and", "expression", ".", "variable_name", "in", "variables", ":", "return", "True", "if", "isinstance", "(", "e...
Returns True iff the expression contains any of the variables from the given set.
[ "Returns", "True", "iff", "the", "expression", "contains", "any", "of", "the", "variables", "from", "the", "given", "set", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/functions.py#L94-L100
HPAC/matchpy
matchpy/expressions/functions.py
get_variables
def get_variables(expression, variables=None): """Returns the set of variable names in the given expression.""" if variables is None: variables = set() if hasattr(expression, 'variable_name') and expression.variable_name is not None: variables.add(expression.variable_name) if isinstance(...
python
def get_variables(expression, variables=None): """Returns the set of variable names in the given expression.""" if variables is None: variables = set() if hasattr(expression, 'variable_name') and expression.variable_name is not None: variables.add(expression.variable_name) if isinstance(...
[ "def", "get_variables", "(", "expression", ",", "variables", "=", "None", ")", ":", "if", "variables", "is", "None", ":", "variables", "=", "set", "(", ")", "if", "hasattr", "(", "expression", ",", "'variable_name'", ")", "and", "expression", ".", "variabl...
Returns the set of variable names in the given expression.
[ "Returns", "the", "set", "of", "variable", "names", "in", "the", "given", "expression", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/functions.py#L103-L112
HPAC/matchpy
matchpy/expressions/functions.py
rename_variables
def rename_variables(expression: Expression, renaming: Dict[str, str]) -> Expression: """Rename the variables in the expression according to the given dictionary. Args: expression: The expression in which the variables are renamed. renaming: The renaming dictionary. Maps...
python
def rename_variables(expression: Expression, renaming: Dict[str, str]) -> Expression: """Rename the variables in the expression according to the given dictionary. Args: expression: The expression in which the variables are renamed. renaming: The renaming dictionary. Maps...
[ "def", "rename_variables", "(", "expression", ":", "Expression", ",", "renaming", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "Expression", ":", "if", "isinstance", "(", "expression", ",", "Operation", ")", ":", "if", "hasattr", "(", "expression",...
Rename the variables in the expression according to the given dictionary. Args: expression: The expression in which the variables are renamed. renaming: The renaming dictionary. Maps old variable names to new ones. Variable names not occuring in the dictionary ar...
[ "Rename", "the", "variables", "in", "the", "expression", "according", "to", "the", "given", "dictionary", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/functions.py#L115-L139
HPAC/matchpy
matchpy/utils.py
fixed_integer_vector_iter
def fixed_integer_vector_iter(max_vector: Tuple[int, ...], vector_sum: int) -> Iterator[Tuple[int, ...]]: """ Return an iterator over the integer vectors which - are componentwise less than or equal to *max_vector*, and - are non-negative, and where - the sum of their components is exactly *vector_...
python
def fixed_integer_vector_iter(max_vector: Tuple[int, ...], vector_sum: int) -> Iterator[Tuple[int, ...]]: """ Return an iterator over the integer vectors which - are componentwise less than or equal to *max_vector*, and - are non-negative, and where - the sum of their components is exactly *vector_...
[ "def", "fixed_integer_vector_iter", "(", "max_vector", ":", "Tuple", "[", "int", ",", "...", "]", ",", "vector_sum", ":", "int", ")", "->", "Iterator", "[", "Tuple", "[", "int", ",", "...", "]", "]", ":", "if", "vector_sum", "<", "0", ":", "raise", "...
Return an iterator over the integer vectors which - are componentwise less than or equal to *max_vector*, and - are non-negative, and where - the sum of their components is exactly *vector_sum*. The iterator yields the vectors in lexicographical order. Examples: List all vectors that are...
[ "Return", "an", "iterator", "over", "the", "integer", "vectors", "which" ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/utils.py#L30-L75
HPAC/matchpy
matchpy/utils.py
weak_composition_iter
def weak_composition_iter(n: int, num_parts: int) -> Iterator[Tuple[int, ...]]: """Yield all weak compositions of integer *n* into *num_parts* parts. Each composition is yielded as a tuple. The generated partitions are order-dependant and not unique when ignoring the order of the components. The partitions...
python
def weak_composition_iter(n: int, num_parts: int) -> Iterator[Tuple[int, ...]]: """Yield all weak compositions of integer *n* into *num_parts* parts. Each composition is yielded as a tuple. The generated partitions are order-dependant and not unique when ignoring the order of the components. The partitions...
[ "def", "weak_composition_iter", "(", "n", ":", "int", ",", "num_parts", ":", "int", ")", "->", "Iterator", "[", "Tuple", "[", "int", ",", "...", "]", "]", ":", "if", "n", "<", "0", ":", "raise", "ValueError", "(", "\"Total must not be negative\"", ")", ...
Yield all weak compositions of integer *n* into *num_parts* parts. Each composition is yielded as a tuple. The generated partitions are order-dependant and not unique when ignoring the order of the components. The partitions are yielded in lexicographical order. Example: >>> compositions = list(w...
[ "Yield", "all", "weak", "compositions", "of", "integer", "*", "n", "*", "into", "*", "num_parts", "*", "parts", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/utils.py#L78-L124
HPAC/matchpy
matchpy/utils.py
commutative_sequence_variable_partition_iter
def commutative_sequence_variable_partition_iter(values: Multiset, variables: List[VariableWithCount] ) -> Iterator[Dict[str, Multiset]]: """Yield all possible variable substitutions for given values and variables. .. note:: The results are not yielded i...
python
def commutative_sequence_variable_partition_iter(values: Multiset, variables: List[VariableWithCount] ) -> Iterator[Dict[str, Multiset]]: """Yield all possible variable substitutions for given values and variables. .. note:: The results are not yielded i...
[ "def", "commutative_sequence_variable_partition_iter", "(", "values", ":", "Multiset", ",", "variables", ":", "List", "[", "VariableWithCount", "]", ")", "->", "Iterator", "[", "Dict", "[", "str", ",", "Multiset", "]", "]", ":", "if", "len", "(", "variables", ...
Yield all possible variable substitutions for given values and variables. .. note:: The results are not yielded in any particular order because the algorithm uses dictionaries. Dictionaries until Python 3.6 do not keep track of the insertion order. Example: For a subject like ``fc(a,...
[ "Yield", "all", "possible", "variable", "substitutions", "for", "given", "values", "and", "variables", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/utils.py#L173-L232
HPAC/matchpy
matchpy/utils.py
get_short_lambda_source
def get_short_lambda_source(lambda_func: LambdaType) -> Optional[str]: """Return the source of a (short) lambda function. If it's impossible to obtain, return ``None``. The source is returned without the ``lambda`` and signature parts: >>> get_short_lambda_source(lambda x, y: x < y) 'x < y' T...
python
def get_short_lambda_source(lambda_func: LambdaType) -> Optional[str]: """Return the source of a (short) lambda function. If it's impossible to obtain, return ``None``. The source is returned without the ``lambda`` and signature parts: >>> get_short_lambda_source(lambda x, y: x < y) 'x < y' T...
[ "def", "get_short_lambda_source", "(", "lambda_func", ":", "LambdaType", ")", "->", "Optional", "[", "str", "]", ":", "try", ":", "all_source_lines", ",", "lnum", "=", "inspect", ".", "findsource", "(", "lambda_func", ")", "source_lines", ",", "_", "=", "ins...
Return the source of a (short) lambda function. If it's impossible to obtain, return ``None``. The source is returned without the ``lambda`` and signature parts: >>> get_short_lambda_source(lambda x, y: x < y) 'x < y' This should work well for most lambda definitions, however for multi-line or hi...
[ "Return", "the", "source", "of", "a", "(", "short", ")", "lambda", "function", ".", "If", "it", "s", "impossible", "to", "obtain", "return", "None", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/utils.py#L270-L321
HPAC/matchpy
matchpy/utils.py
extended_euclid
def extended_euclid(a: int, b: int) -> Tuple[int, int, int]: """Extended Euclidean algorithm that computes the Bézout coefficients as well as :math:`gcd(a, b)` Returns ``x, y, d`` where *x* and *y* are a solution to :math:`ax + by = d` and :math:`d = gcd(a, b)`. *x* and *y* are a minimal pair of Bézout's c...
python
def extended_euclid(a: int, b: int) -> Tuple[int, int, int]: """Extended Euclidean algorithm that computes the Bézout coefficients as well as :math:`gcd(a, b)` Returns ``x, y, d`` where *x* and *y* are a solution to :math:`ax + by = d` and :math:`d = gcd(a, b)`. *x* and *y* are a minimal pair of Bézout's c...
[ "def", "extended_euclid", "(", "a", ":", "int", ",", "b", ":", "int", ")", "->", "Tuple", "[", "int", ",", "int", ",", "int", "]", ":", "if", "b", "==", "0", ":", "return", "(", "1", ",", "0", ",", "a", ")", "x0", ",", "y0", ",", "d", "="...
Extended Euclidean algorithm that computes the Bézout coefficients as well as :math:`gcd(a, b)` Returns ``x, y, d`` where *x* and *y* are a solution to :math:`ax + by = d` and :math:`d = gcd(a, b)`. *x* and *y* are a minimal pair of Bézout's coefficients. See `Extended Euclidean algorithm <https://en.wiki...
[ "Extended", "Euclidean", "algorithm", "that", "computes", "the", "Bézout", "coefficients", "as", "well", "as", ":", "math", ":", "gcd", "(", "a", "b", ")" ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/utils.py#L323-L364
HPAC/matchpy
matchpy/utils.py
base_solution_linear
def base_solution_linear(a: int, b: int, c: int) -> Iterator[Tuple[int, int]]: r"""Yield solutions for a basic linear Diophantine equation of the form :math:`ax + by = c`. First, the equation is normalized by dividing :math:`a, b, c` by their gcd. Then, the extended Euclidean algorithm (:func:`extended_euc...
python
def base_solution_linear(a: int, b: int, c: int) -> Iterator[Tuple[int, int]]: r"""Yield solutions for a basic linear Diophantine equation of the form :math:`ax + by = c`. First, the equation is normalized by dividing :math:`a, b, c` by their gcd. Then, the extended Euclidean algorithm (:func:`extended_euc...
[ "def", "base_solution_linear", "(", "a", ":", "int", ",", "b", ":", "int", ",", "c", ":", "int", ")", "->", "Iterator", "[", "Tuple", "[", "int", ",", "int", "]", "]", ":", "if", "a", "<=", "0", "or", "b", "<=", "0", ":", "raise", "ValueError",...
r"""Yield solutions for a basic linear Diophantine equation of the form :math:`ax + by = c`. First, the equation is normalized by dividing :math:`a, b, c` by their gcd. Then, the extended Euclidean algorithm (:func:`extended_euclid`) is used to find a base solution :math:`(x_0, y_0)`. All non-negative sol...
[ "r", "Yield", "solutions", "for", "a", "basic", "linear", "Diophantine", "equation", "of", "the", "form", ":", "math", ":", "ax", "+", "by", "=", "c", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/utils.py#L367-L428
HPAC/matchpy
matchpy/utils.py
solve_linear_diop
def solve_linear_diop(total: int, *coeffs: int) -> Iterator[Tuple[int, ...]]: r"""Yield non-negative integer solutions of a linear Diophantine equation of the format :math:`c_1 x_1 + \dots + c_n x_n = total`. If there are at most two coefficients, :func:`base_solution_linear()` is used to find the solution...
python
def solve_linear_diop(total: int, *coeffs: int) -> Iterator[Tuple[int, ...]]: r"""Yield non-negative integer solutions of a linear Diophantine equation of the format :math:`c_1 x_1 + \dots + c_n x_n = total`. If there are at most two coefficients, :func:`base_solution_linear()` is used to find the solution...
[ "def", "solve_linear_diop", "(", "total", ":", "int", ",", "*", "coeffs", ":", "int", ")", "->", "Iterator", "[", "Tuple", "[", "int", ",", "...", "]", "]", ":", "if", "len", "(", "coeffs", ")", "==", "0", ":", "if", "total", "==", "0", ":", "y...
r"""Yield non-negative integer solutions of a linear Diophantine equation of the format :math:`c_1 x_1 + \dots + c_n x_n = total`. If there are at most two coefficients, :func:`base_solution_linear()` is used to find the solutions. Otherwise, the solutions are found recursively, by reducing the number of v...
[ "r", "Yield", "non", "-", "negative", "integer", "solutions", "of", "a", "linear", "Diophantine", "equation", "of", "the", "format", ":", "math", ":", "c_1", "x_1", "+", "\\", "dots", "+", "c_n", "x_n", "=", "total", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/utils.py#L431-L474
HPAC/matchpy
matchpy/utils.py
generator_chain
def generator_chain(initial_data: T, *factories: Callable[[T], Iterator[T]]) -> Iterator[T]: """Chain multiple generators together by passing results from one to the next. This helper function allows to create a chain of generator where each generator is constructed by a factory that gets the data yielded ...
python
def generator_chain(initial_data: T, *factories: Callable[[T], Iterator[T]]) -> Iterator[T]: """Chain multiple generators together by passing results from one to the next. This helper function allows to create a chain of generator where each generator is constructed by a factory that gets the data yielded ...
[ "def", "generator_chain", "(", "initial_data", ":", "T", ",", "*", "factories", ":", "Callable", "[", "[", "T", "]", ",", "Iterator", "[", "T", "]", "]", ")", "->", "Iterator", "[", "T", "]", ":", "generator_count", "=", "len", "(", "factories", ")",...
Chain multiple generators together by passing results from one to the next. This helper function allows to create a chain of generator where each generator is constructed by a factory that gets the data yielded by the previous generator. So each generator can generate new data dependant on the data yielded...
[ "Chain", "multiple", "generators", "together", "by", "passing", "results", "from", "one", "to", "the", "next", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/utils.py#L477-L532
HPAC/matchpy
matchpy/expressions/substitution.py
Substitution.try_add_variable
def try_add_variable(self, variable_name: str, replacement: VariableReplacement) -> None: """Try to add the variable with its replacement to the substitution. This considers an existing replacement and will only succeed if the new replacement can be merged with the old replacement. Merging can ...
python
def try_add_variable(self, variable_name: str, replacement: VariableReplacement) -> None: """Try to add the variable with its replacement to the substitution. This considers an existing replacement and will only succeed if the new replacement can be merged with the old replacement. Merging can ...
[ "def", "try_add_variable", "(", "self", ",", "variable_name", ":", "str", ",", "replacement", ":", "VariableReplacement", ")", "->", "None", ":", "if", "variable_name", "not", "in", "self", ":", "self", "[", "variable_name", "]", "=", "replacement", ".", "co...
Try to add the variable with its replacement to the substitution. This considers an existing replacement and will only succeed if the new replacement can be merged with the old replacement. Merging can occur if either the two replacements are equivalent. Replacements can also be merged if the o...
[ "Try", "to", "add", "the", "variable", "with", "its", "replacement", "to", "the", "substitution", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/substitution.py#L32-L77
HPAC/matchpy
matchpy/expressions/substitution.py
Substitution.union_with_variable
def union_with_variable(self, variable: str, replacement: VariableReplacement) -> 'Substitution': """Try to create a new substitution with the given variable added. See :meth:`try_add_variable` for a version of this method that modifies the substitution in place. Args: vari...
python
def union_with_variable(self, variable: str, replacement: VariableReplacement) -> 'Substitution': """Try to create a new substitution with the given variable added. See :meth:`try_add_variable` for a version of this method that modifies the substitution in place. Args: vari...
[ "def", "union_with_variable", "(", "self", ",", "variable", ":", "str", ",", "replacement", ":", "VariableReplacement", ")", "->", "'Substitution'", ":", "new_subst", "=", "Substitution", "(", "self", ")", "new_subst", ".", "try_add_variable", "(", "variable", "...
Try to create a new substitution with the given variable added. See :meth:`try_add_variable` for a version of this method that modifies the substitution in place. Args: variable_name: The name of the variable to add. replacement: The subs...
[ "Try", "to", "create", "a", "new", "substitution", "with", "the", "given", "variable", "added", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/substitution.py#L79-L101
HPAC/matchpy
matchpy/expressions/substitution.py
Substitution.extract_substitution
def extract_substitution(self, subject: 'expressions.Expression', pattern: 'expressions.Expression') -> bool: """Extract the variable substitution for the given pattern and subject. This assumes that subject and pattern already match when being considered as linear. Also, they both must be :ter...
python
def extract_substitution(self, subject: 'expressions.Expression', pattern: 'expressions.Expression') -> bool: """Extract the variable substitution for the given pattern and subject. This assumes that subject and pattern already match when being considered as linear. Also, they both must be :ter...
[ "def", "extract_substitution", "(", "self", ",", "subject", ":", "'expressions.Expression'", ",", "pattern", ":", "'expressions.Expression'", ")", "->", "bool", ":", "if", "getattr", "(", "pattern", ",", "'variable_name'", ",", "False", ")", ":", "try", ":", "...
Extract the variable substitution for the given pattern and subject. This assumes that subject and pattern already match when being considered as linear. Also, they both must be :term:`syntactic`, as sequence variables cannot be handled here. All that this method does is checking whether all th...
[ "Extract", "the", "variable", "substitution", "for", "the", "given", "pattern", "and", "subject", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/substitution.py#L103-L164
HPAC/matchpy
matchpy/expressions/substitution.py
Substitution.union
def union(self, *others: 'Substitution') -> 'Substitution': """Try to merge the substitutions. If a variable occurs in multiple substitutions, try to merge the replacements. See :meth:`union_with_variable` to see how replacements are merged. Does not modify any of the original substitu...
python
def union(self, *others: 'Substitution') -> 'Substitution': """Try to merge the substitutions. If a variable occurs in multiple substitutions, try to merge the replacements. See :meth:`union_with_variable` to see how replacements are merged. Does not modify any of the original substitu...
[ "def", "union", "(", "self", ",", "*", "others", ":", "'Substitution'", ")", "->", "'Substitution'", ":", "new_subst", "=", "Substitution", "(", "self", ")", "for", "other", "in", "others", ":", "for", "variable_name", ",", "replacement", "in", "other", "....
Try to merge the substitutions. If a variable occurs in multiple substitutions, try to merge the replacements. See :meth:`union_with_variable` to see how replacements are merged. Does not modify any of the original substitutions. Example: >>> subst1 = Substitution({'x': Multi...
[ "Try", "to", "merge", "the", "substitutions", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/substitution.py#L166-L197
HPAC/matchpy
matchpy/expressions/substitution.py
Substitution.rename
def rename(self, renaming: Dict[str, str]) -> 'Substitution': """Return a copy of the substitution with renamed variables. Example: Rename the variable *x* to *y*: >>> subst = Substitution({'x': a}) >>> subst.rename({'x': 'y'}) {'y': Symbol('a')} ...
python
def rename(self, renaming: Dict[str, str]) -> 'Substitution': """Return a copy of the substitution with renamed variables. Example: Rename the variable *x* to *y*: >>> subst = Substitution({'x': a}) >>> subst.rename({'x': 'y'}) {'y': Symbol('a')} ...
[ "def", "rename", "(", "self", ",", "renaming", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "'Substitution'", ":", "return", "Substitution", "(", "(", "renaming", ".", "get", "(", "name", ",", "name", ")", ",", "value", ")", "for", "name", ...
Return a copy of the substitution with renamed variables. Example: Rename the variable *x* to *y*: >>> subst = Substitution({'x': a}) >>> subst.rename({'x': 'y'}) {'y': Symbol('a')} Args: renaming: A dictionary mapping old v...
[ "Return", "a", "copy", "of", "the", "substitution", "with", "renamed", "variables", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/substitution.py#L199-L218
HPAC/matchpy
matchpy/matching/syntactic.py
is_operation
def is_operation(term: Any) -> bool: """Return True iff the given term is a subclass of :class:`.Operation`.""" return isinstance(term, type) and issubclass(term, Operation)
python
def is_operation(term: Any) -> bool: """Return True iff the given term is a subclass of :class:`.Operation`.""" return isinstance(term, type) and issubclass(term, Operation)
[ "def", "is_operation", "(", "term", ":", "Any", ")", "->", "bool", ":", "return", "isinstance", "(", "term", ",", "type", ")", "and", "issubclass", "(", "term", ",", "Operation", ")" ]
Return True iff the given term is a subclass of :class:`.Operation`.
[ "Return", "True", "iff", "the", "given", "term", "is", "a", "subclass", "of", ":", "class", ":", ".", "Operation", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L40-L42
HPAC/matchpy
matchpy/matching/syntactic.py
is_symbol_wildcard
def is_symbol_wildcard(term: Any) -> bool: """Return True iff the given term is a subclass of :class:`.Symbol`.""" return isinstance(term, type) and issubclass(term, Symbol)
python
def is_symbol_wildcard(term: Any) -> bool: """Return True iff the given term is a subclass of :class:`.Symbol`.""" return isinstance(term, type) and issubclass(term, Symbol)
[ "def", "is_symbol_wildcard", "(", "term", ":", "Any", ")", "->", "bool", ":", "return", "isinstance", "(", "term", ",", "type", ")", "and", "issubclass", "(", "term", ",", "Symbol", ")" ]
Return True iff the given term is a subclass of :class:`.Symbol`.
[ "Return", "True", "iff", "the", "given", "term", "is", "a", "subclass", "of", ":", "class", ":", ".", "Symbol", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L45-L47
HPAC/matchpy
matchpy/matching/syntactic.py
_get_symbol_wildcard_label
def _get_symbol_wildcard_label(state: '_State', symbol: Symbol) -> Type[Symbol]: """Return the transition target for the given symbol type from the the given state or None if it does not exist.""" return next((t for t in state.keys() if is_symbol_wildcard(t) and isinstance(symbol, t)), None)
python
def _get_symbol_wildcard_label(state: '_State', symbol: Symbol) -> Type[Symbol]: """Return the transition target for the given symbol type from the the given state or None if it does not exist.""" return next((t for t in state.keys() if is_symbol_wildcard(t) and isinstance(symbol, t)), None)
[ "def", "_get_symbol_wildcard_label", "(", "state", ":", "'_State'", ",", "symbol", ":", "Symbol", ")", "->", "Type", "[", "Symbol", "]", ":", "return", "next", "(", "(", "t", "for", "t", "in", "state", ".", "keys", "(", ")", "if", "is_symbol_wildcard", ...
Return the transition target for the given symbol type from the the given state or None if it does not exist.
[ "Return", "the", "transition", "target", "for", "the", "given", "symbol", "type", "from", "the", "the", "given", "state", "or", "None", "if", "it", "does", "not", "exist", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L50-L52
HPAC/matchpy
matchpy/matching/syntactic.py
_term_str
def _term_str(term: TermAtom) -> str: # pragma: no cover """Return a string representation of a term atom.""" if is_operation(term): return term.name + '(' elif is_symbol_wildcard(term): return '*{!s}'.format(term.__name__) elif isinstance(term, Wildcard): return '*{!s}{!s}'.for...
python
def _term_str(term: TermAtom) -> str: # pragma: no cover """Return a string representation of a term atom.""" if is_operation(term): return term.name + '(' elif is_symbol_wildcard(term): return '*{!s}'.format(term.__name__) elif isinstance(term, Wildcard): return '*{!s}{!s}'.for...
[ "def", "_term_str", "(", "term", ":", "TermAtom", ")", "->", "str", ":", "# pragma: no cover", "if", "is_operation", "(", "term", ")", ":", "return", "term", ".", "name", "+", "'('", "elif", "is_symbol_wildcard", "(", "term", ")", ":", "return", "'*{!s}'",...
Return a string representation of a term atom.
[ "Return", "a", "string", "representation", "of", "a", "term", "atom", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L200-L211
HPAC/matchpy
matchpy/matching/syntactic.py
FlatTerm.is_syntactic
def is_syntactic(self): """True, iff the flatterm is :term:`syntactic`.""" for term in self._terms: if isinstance(term, Wildcard) and not term.fixed_size: return False if is_operation(term) and issubclass(term, (AssociativeOperation, CommutativeOperation)): ...
python
def is_syntactic(self): """True, iff the flatterm is :term:`syntactic`.""" for term in self._terms: if isinstance(term, Wildcard) and not term.fixed_size: return False if is_operation(term) and issubclass(term, (AssociativeOperation, CommutativeOperation)): ...
[ "def", "is_syntactic", "(", "self", ")", ":", "for", "term", "in", "self", ".", "_terms", ":", "if", "isinstance", "(", "term", ",", "Wildcard", ")", "and", "not", "term", ".", "fixed_size", ":", "return", "False", "if", "is_operation", "(", "term", ")...
True, iff the flatterm is :term:`syntactic`.
[ "True", "iff", "the", "flatterm", "is", ":", "term", ":", "syntactic", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L131-L138
HPAC/matchpy
matchpy/matching/syntactic.py
FlatTerm.merged
def merged(cls, *flatterms: 'FlatTerm') -> 'FlatTerm': """Concatenate the given flatterms to a single flatterm. Args: *flatterms: The flatterms which are concatenated. Returns: The concatenated flatterms. """ return cls(cls._combined_wild...
python
def merged(cls, *flatterms: 'FlatTerm') -> 'FlatTerm': """Concatenate the given flatterms to a single flatterm. Args: *flatterms: The flatterms which are concatenated. Returns: The concatenated flatterms. """ return cls(cls._combined_wild...
[ "def", "merged", "(", "cls", ",", "*", "flatterms", ":", "'FlatTerm'", ")", "->", "'FlatTerm'", ":", "return", "cls", "(", "cls", ".", "_combined_wildcards_iter", "(", "sum", "(", "flatterms", ",", "cls", ".", "empty", "(", ")", ")", ")", ")" ]
Concatenate the given flatterms to a single flatterm. Args: *flatterms: The flatterms which are concatenated. Returns: The concatenated flatterms.
[ "Concatenate", "the", "given", "flatterms", "to", "a", "single", "flatterm", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L146-L156
HPAC/matchpy
matchpy/matching/syntactic.py
FlatTerm._flatterm_iter
def _flatterm_iter(cls, expression: Expression) -> Iterator[TermAtom]: """Generator that yields the atoms of the expressions in prefix notation with operation end markers.""" if isinstance(expression, Operation): yield type(expression) for operand in op_iter(expression): ...
python
def _flatterm_iter(cls, expression: Expression) -> Iterator[TermAtom]: """Generator that yields the atoms of the expressions in prefix notation with operation end markers.""" if isinstance(expression, Operation): yield type(expression) for operand in op_iter(expression): ...
[ "def", "_flatterm_iter", "(", "cls", ",", "expression", ":", "Expression", ")", "->", "Iterator", "[", "TermAtom", "]", ":", "if", "isinstance", "(", "expression", ",", "Operation", ")", ":", "yield", "type", "(", "expression", ")", "for", "operand", "in",...
Generator that yields the atoms of the expressions in prefix notation with operation end markers.
[ "Generator", "that", "yields", "the", "atoms", "of", "the", "expressions", "in", "prefix", "notation", "with", "operation", "end", "markers", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L159-L171
HPAC/matchpy
matchpy/matching/syntactic.py
FlatTerm._combined_wildcards_iter
def _combined_wildcards_iter(flatterm: Iterator[TermAtom]) -> Iterator[TermAtom]: """Combine consecutive wildcards in a flatterm into a single one.""" last_wildcard = None # type: Optional[Wildcard] for term in flatterm: if isinstance(term, Wildcard) and not isinstance(term, SymbolW...
python
def _combined_wildcards_iter(flatterm: Iterator[TermAtom]) -> Iterator[TermAtom]: """Combine consecutive wildcards in a flatterm into a single one.""" last_wildcard = None # type: Optional[Wildcard] for term in flatterm: if isinstance(term, Wildcard) and not isinstance(term, SymbolW...
[ "def", "_combined_wildcards_iter", "(", "flatterm", ":", "Iterator", "[", "TermAtom", "]", ")", "->", "Iterator", "[", "TermAtom", "]", ":", "last_wildcard", "=", "None", "# type: Optional[Wildcard]", "for", "term", "in", "flatterm", ":", "if", "isinstance", "("...
Combine consecutive wildcards in a flatterm into a single one.
[ "Combine", "consecutive", "wildcards", "in", "a", "flatterm", "into", "a", "single", "one", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L174-L191
HPAC/matchpy
matchpy/matching/syntactic.py
_StateQueueItem.labels
def labels(self) -> Set[TransitionLabel]: """Return the set of transition labels to examine for this queue state. This is the union of the transition label sets for both states. However, if one of the states is fixed, it is excluded from this union and a wildcard transition is included ...
python
def labels(self) -> Set[TransitionLabel]: """Return the set of transition labels to examine for this queue state. This is the union of the transition label sets for both states. However, if one of the states is fixed, it is excluded from this union and a wildcard transition is included ...
[ "def", "labels", "(", "self", ")", "->", "Set", "[", "TransitionLabel", "]", ":", "labels", "=", "set", "(", ")", "# type: Set[TransitionLabel]", "if", "self", ".", "state1", "is", "not", "None", "and", "self", ".", "fixed", "!=", "1", ":", "labels", "...
Return the set of transition labels to examine for this queue state. This is the union of the transition label sets for both states. However, if one of the states is fixed, it is excluded from this union and a wildcard transition is included instead. Also, when already in a failed state (one of...
[ "Return", "the", "set", "of", "transition", "labels", "to", "examine", "for", "this", "queue", "state", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L280-L299
HPAC/matchpy
matchpy/matching/syntactic.py
DiscriminationNet.add
def add(self, pattern: Union[Pattern, FlatTerm], final_label: T=None) -> int: """Add a pattern to the discrimination net. Args: pattern: The pattern which is added to the DiscriminationNet. If an expression is given, it will be converted to a `FlatTerm` for i...
python
def add(self, pattern: Union[Pattern, FlatTerm], final_label: T=None) -> int: """Add a pattern to the discrimination net. Args: pattern: The pattern which is added to the DiscriminationNet. If an expression is given, it will be converted to a `FlatTerm` for i...
[ "def", "add", "(", "self", ",", "pattern", ":", "Union", "[", "Pattern", ",", "FlatTerm", "]", ",", "final_label", ":", "T", "=", "None", ")", "->", "int", ":", "index", "=", "len", "(", "self", ".", "_patterns", ")", "self", ".", "_patterns", ".",...
Add a pattern to the discrimination net. Args: pattern: The pattern which is added to the DiscriminationNet. If an expression is given, it will be converted to a `FlatTerm` for internal processing. You can also pass a `FlatTerm` directly. final_label: ...
[ "Add", "a", "pattern", "to", "the", "discrimination", "net", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L329-L356
HPAC/matchpy
matchpy/matching/syntactic.py
DiscriminationNet._generate_net
def _generate_net(cls, flatterm: FlatTerm, final_label: T) -> _State[T]: """Generates a DFA matching the given pattern.""" # Capture the last sequence wildcard for every level of operation nesting on a stack # Used to add backtracking edges in case the "match" fails later last_wildcards ...
python
def _generate_net(cls, flatterm: FlatTerm, final_label: T) -> _State[T]: """Generates a DFA matching the given pattern.""" # Capture the last sequence wildcard for every level of operation nesting on a stack # Used to add backtracking edges in case the "match" fails later last_wildcards ...
[ "def", "_generate_net", "(", "cls", ",", "flatterm", ":", "FlatTerm", ",", "final_label", ":", "T", ")", "->", "_State", "[", "T", "]", ":", "# Capture the last sequence wildcard for every level of operation nesting on a stack", "# Used to add backtracking edges in case the \...
Generates a DFA matching the given pattern.
[ "Generates", "a", "DFA", "matching", "the", "given", "pattern", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L385-L461
HPAC/matchpy
matchpy/matching/syntactic.py
DiscriminationNet.match
def match(self, subject: Union[Expression, FlatTerm]) -> Iterator[Tuple[T, Substitution]]: """Match the given subject against all patterns in the net. Args: subject: The subject that is matched. Must be constant. Yields: A tuple :code:`(final label, subs...
python
def match(self, subject: Union[Expression, FlatTerm]) -> Iterator[Tuple[T, Substitution]]: """Match the given subject against all patterns in the net. Args: subject: The subject that is matched. Must be constant. Yields: A tuple :code:`(final label, subs...
[ "def", "match", "(", "self", ",", "subject", ":", "Union", "[", "Expression", ",", "FlatTerm", "]", ")", "->", "Iterator", "[", "Tuple", "[", "T", ",", "Substitution", "]", "]", ":", "for", "index", "in", "self", ".", "_match", "(", "subject", ")", ...
Match the given subject against all patterns in the net. Args: subject: The subject that is matched. Must be constant. Yields: A tuple :code:`(final label, substitution)`, where the first component is the final label associated with the pattern as gi...
[ "Match", "the", "given", "subject", "against", "all", "patterns", "in", "the", "net", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L645-L664
HPAC/matchpy
matchpy/matching/syntactic.py
DiscriminationNet.is_match
def is_match(self, subject: Union[Expression, FlatTerm]) -> bool: """Check if the given subject matches any pattern in the net. Args: subject: The subject that is matched. Must be constant. Returns: True, if any pattern matches the subject. """ ...
python
def is_match(self, subject: Union[Expression, FlatTerm]) -> bool: """Check if the given subject matches any pattern in the net. Args: subject: The subject that is matched. Must be constant. Returns: True, if any pattern matches the subject. """ ...
[ "def", "is_match", "(", "self", ",", "subject", ":", "Union", "[", "Expression", ",", "FlatTerm", "]", ")", "->", "bool", ":", "try", ":", "next", "(", "self", ".", "match", "(", "subject", ")", ")", "except", "StopIteration", ":", "return", "False", ...
Check if the given subject matches any pattern in the net. Args: subject: The subject that is matched. Must be constant. Returns: True, if any pattern matches the subject.
[ "Check", "if", "the", "given", "subject", "matches", "any", "pattern", "in", "the", "net", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L666-L680
HPAC/matchpy
matchpy/matching/syntactic.py
DiscriminationNet.as_graph
def as_graph(self) -> Digraph: # pragma: no cover """Renders the discrimination net as graphviz digraph.""" if Digraph is None: raise ImportError('The graphviz package is required to draw the graph.') dot = Digraph() nodes = set() queue = [self._root] while ...
python
def as_graph(self) -> Digraph: # pragma: no cover """Renders the discrimination net as graphviz digraph.""" if Digraph is None: raise ImportError('The graphviz package is required to draw the graph.') dot = Digraph() nodes = set() queue = [self._root] while ...
[ "def", "as_graph", "(", "self", ")", "->", "Digraph", ":", "# pragma: no cover", "if", "Digraph", "is", "None", ":", "raise", "ImportError", "(", "'The graphviz package is required to draw the graph.'", ")", "dot", "=", "Digraph", "(", ")", "nodes", "=", "set", ...
Renders the discrimination net as graphviz digraph.
[ "Renders", "the", "discrimination", "net", "as", "graphviz", "digraph", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L682-L715
HPAC/matchpy
matchpy/matching/syntactic.py
SequenceMatcher.add
def add(self, pattern: Pattern) -> int: """Add a pattern that will be recognized by the matcher. Args: pattern: The pattern to add. Returns: An internal index for the pattern. Raises: ValueError: If the pattern does n...
python
def add(self, pattern: Pattern) -> int: """Add a pattern that will be recognized by the matcher. Args: pattern: The pattern to add. Returns: An internal index for the pattern. Raises: ValueError: If the pattern does n...
[ "def", "add", "(", "self", ",", "pattern", ":", "Pattern", ")", "->", "int", ":", "inner", "=", "pattern", ".", "expression", "if", "self", ".", "operation", "is", "None", ":", "if", "not", "isinstance", "(", "inner", ",", "Operation", ")", "or", "is...
Add a pattern that will be recognized by the matcher. Args: pattern: The pattern to add. Returns: An internal index for the pattern. Raises: ValueError: If the pattern does not have the correct form. TypeError: ...
[ "Add", "a", "pattern", "that", "will", "be", "recognized", "by", "the", "matcher", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L750-L790
HPAC/matchpy
matchpy/matching/syntactic.py
SequenceMatcher.can_match
def can_match(cls, pattern: Pattern) -> bool: """Check if a pattern can be matched with a sequence matcher. Args: pattern: The pattern to check. Returns: True, iff the pattern can be matched with a sequence matcher. """ if not isinstance(...
python
def can_match(cls, pattern: Pattern) -> bool: """Check if a pattern can be matched with a sequence matcher. Args: pattern: The pattern to check. Returns: True, iff the pattern can be matched with a sequence matcher. """ if not isinstance(...
[ "def", "can_match", "(", "cls", ",", "pattern", ":", "Pattern", ")", "->", "bool", ":", "if", "not", "isinstance", "(", "pattern", ".", "expression", ",", "Operation", ")", "or", "isinstance", "(", "pattern", ".", "expression", ",", "CommutativeOperation", ...
Check if a pattern can be matched with a sequence matcher. Args: pattern: The pattern to check. Returns: True, iff the pattern can be matched with a sequence matcher.
[ "Check", "if", "a", "pattern", "can", "be", "matched", "with", "a", "sequence", "matcher", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L800-L824
HPAC/matchpy
matchpy/matching/syntactic.py
SequenceMatcher.match
def match(self, subject: Expression) -> Iterator[Tuple[Pattern, Substitution]]: """Match the given subject against all patterns in the sequence matcher. Args: subject: The subject that is matched. Must be constant. Yields: A tuple :code:`(pattern, substi...
python
def match(self, subject: Expression) -> Iterator[Tuple[Pattern, Substitution]]: """Match the given subject against all patterns in the sequence matcher. Args: subject: The subject that is matched. Must be constant. Yields: A tuple :code:`(pattern, substi...
[ "def", "match", "(", "self", ",", "subject", ":", "Expression", ")", "->", "Iterator", "[", "Tuple", "[", "Pattern", ",", "Substitution", "]", "]", ":", "if", "not", "isinstance", "(", "subject", ",", "self", ".", "operation", ")", ":", "return", "subj...
Match the given subject against all patterns in the sequence matcher. Args: subject: The subject that is matched. Must be constant. Yields: A tuple :code:`(pattern, substitution)` for every matching pattern.
[ "Match", "the", "given", "subject", "against", "all", "patterns", "in", "the", "sequence", "matcher", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L826-L868
HPAC/matchpy
matchpy/matching/one_to_one.py
match
def match(subject: Expression, pattern: Pattern) -> Iterator[Substitution]: r"""Tries to match the given *pattern* to the given *subject*. Yields each match in form of a substitution. Parameters: subject: An subject to match. pattern: The pattern to match. Yiel...
python
def match(subject: Expression, pattern: Pattern) -> Iterator[Substitution]: r"""Tries to match the given *pattern* to the given *subject*. Yields each match in form of a substitution. Parameters: subject: An subject to match. pattern: The pattern to match. Yiel...
[ "def", "match", "(", "subject", ":", "Expression", ",", "pattern", ":", "Pattern", ")", "->", "Iterator", "[", "Substitution", "]", ":", "if", "not", "is_constant", "(", "subject", ")", ":", "raise", "ValueError", "(", "\"The subject for matching must be constan...
r"""Tries to match the given *pattern* to the given *subject*. Yields each match in form of a substitution. Parameters: subject: An subject to match. pattern: The pattern to match. Yields: All possible match substitutions. Raises: ValueError: ...
[ "r", "Tries", "to", "match", "the", "given", "*", "pattern", "*", "to", "the", "given", "*", "subject", "*", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/one_to_one.py#L23-L50
HPAC/matchpy
matchpy/matching/one_to_one.py
match_anywhere
def match_anywhere(subject: Expression, pattern: Pattern) -> Iterator[Tuple[Substitution, Tuple[int, ...]]]: """Tries to match the given *pattern* to the any subexpression of the given *subject*. Yields each match in form of a substitution and a position tuple. The position is a tuple of indices, e.g. the ...
python
def match_anywhere(subject: Expression, pattern: Pattern) -> Iterator[Tuple[Substitution, Tuple[int, ...]]]: """Tries to match the given *pattern* to the any subexpression of the given *subject*. Yields each match in form of a substitution and a position tuple. The position is a tuple of indices, e.g. the ...
[ "def", "match_anywhere", "(", "subject", ":", "Expression", ",", "pattern", ":", "Pattern", ")", "->", "Iterator", "[", "Tuple", "[", "Substitution", ",", "Tuple", "[", "int", ",", "...", "]", "]", "]", ":", "if", "not", "is_constant", "(", "subject", ...
Tries to match the given *pattern* to the any subexpression of the given *subject*. Yields each match in form of a substitution and a position tuple. The position is a tuple of indices, e.g. the empty tuple refers to the *subject* itself, :code:`(0, )` refers to the first child (operand) of the subject, :c...
[ "Tries", "to", "match", "the", "given", "*", "pattern", "*", "to", "the", "any", "subexpression", "of", "the", "given", "*", "subject", "*", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/one_to_one.py#L53-L79
HPAC/matchpy
matchpy/matching/one_to_one.py
_build_full_partition
def _build_full_partition( optional_parts, sequence_var_partition: Sequence[int], subjects: Sequence[Expression], operation: Operation ) -> List[Sequence[Expression]]: """Distribute subject operands among pattern operands. Given a partitoning for the variable part of the operands (i.e. a list of how ma...
python
def _build_full_partition( optional_parts, sequence_var_partition: Sequence[int], subjects: Sequence[Expression], operation: Operation ) -> List[Sequence[Expression]]: """Distribute subject operands among pattern operands. Given a partitoning for the variable part of the operands (i.e. a list of how ma...
[ "def", "_build_full_partition", "(", "optional_parts", ",", "sequence_var_partition", ":", "Sequence", "[", "int", "]", ",", "subjects", ":", "Sequence", "[", "Expression", "]", ",", "operation", ":", "Operation", ")", "->", "List", "[", "Sequence", "[", "Expr...
Distribute subject operands among pattern operands. Given a partitoning for the variable part of the operands (i.e. a list of how many extra operands each sequence variable gets assigned).
[ "Distribute", "subject", "operands", "among", "pattern", "operands", "." ]
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/one_to_one.py#L179-L216
HPAC/matchpy
matchpy/matching/many_to_one.py
_MatchIter.grouped
def grouped(self): """ Yield the matches grouped by their final state in the automaton, i.e. structurally identical patterns only differing in constraints will be yielded together. Each group is yielded as a list of tuples consisting of a pattern and a match substitution. Yields...
python
def grouped(self): """ Yield the matches grouped by their final state in the automaton, i.e. structurally identical patterns only differing in constraints will be yielded together. Each group is yielded as a list of tuples consisting of a pattern and a match substitution. Yields...
[ "def", "grouped", "(", "self", ")", ":", "for", "_", "in", "self", ".", "_match", "(", "self", ".", "matcher", ".", "root", ")", ":", "yield", "list", "(", "self", ".", "_internal_iter", "(", ")", ")" ]
Yield the matches grouped by their final state in the automaton, i.e. structurally identical patterns only differing in constraints will be yielded together. Each group is yielded as a list of tuples consisting of a pattern and a match substitution. Yields: The grouped matches.
[ "Yield", "the", "matches", "grouped", "by", "their", "final", "state", "in", "the", "automaton", "i", ".", "e", ".", "structurally", "identical", "patterns", "only", "differing", "in", "constraints", "will", "be", "yielded", "together", ".", "Each", "group", ...
train
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/many_to_one.py#L102-L112