Search is not available for this dataset
identifier
stringlengths 1
155
| parameters
stringlengths 2
6.09k
| docstring
stringlengths 11
63.4k
| docstring_summary
stringlengths 0
63.4k
| function
stringlengths 29
99.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
Page.start_index | (self) |
Return the 1-based index of the first object on this page,
relative to total objects in the paginator.
|
Return the 1-based index of the first object on this page,
relative to total objects in the paginator.
| def start_index(self):
"""
Return the 1-based index of the first object on this page,
relative to total objects in the paginator.
"""
# Special case, return zero if no items.
if self.paginator.count == 0:
return 0
return (self.paginator.per_page * (self.number - 1)) + 1 | [
"def",
"start_index",
"(",
"self",
")",
":",
"# Special case, return zero if no items.",
"if",
"self",
".",
"paginator",
".",
"count",
"==",
"0",
":",
"return",
"0",
"return",
"(",
"self",
".",
"paginator",
".",
"per_page",
"*",
"(",
"self",
".",
"number",
"-",
"1",
")",
")",
"+",
"1"
] | [
205,
4
] | [
213,
64
] | python | en | ['en', 'error', 'th'] | False |
Page.end_index | (self) |
Return the 1-based index of the last object on this page,
relative to total objects found (hits).
|
Return the 1-based index of the last object on this page,
relative to total objects found (hits).
| def end_index(self):
"""
Return the 1-based index of the last object on this page,
relative to total objects found (hits).
"""
# Special case for the last page because there can be orphans.
if self.number == self.paginator.num_pages:
return self.paginator.count
return self.number * self.paginator.per_page | [
"def",
"end_index",
"(",
"self",
")",
":",
"# Special case for the last page because there can be orphans.",
"if",
"self",
".",
"number",
"==",
"self",
".",
"paginator",
".",
"num_pages",
":",
"return",
"self",
".",
"paginator",
".",
"count",
"return",
"self",
".",
"number",
"*",
"self",
".",
"paginator",
".",
"per_page"
] | [
215,
4
] | [
223,
52
] | python | en | ['en', 'error', 'th'] | False |
DataSource.__getitem__ | (self, index) | Allows use of the index [] operator to get a layer at the index. | Allows use of the index [] operator to get a layer at the index. | def __getitem__(self, index):
"Allows use of the index [] operator to get a layer at the index."
if isinstance(index, str):
try:
layer = capi.get_layer_by_name(self.ptr, force_bytes(index))
except GDALException:
raise IndexError('Invalid OGR layer name given: %s.' % index)
elif isinstance(index, int):
if 0 <= index < self.layer_count:
layer = capi.get_layer(self._ptr, index)
else:
raise IndexError('Index out of range when accessing layers in a datasource: %s.' % index)
else:
raise TypeError('Invalid index type: %s' % type(index))
return Layer(layer, self) | [
"def",
"__getitem__",
"(",
"self",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"str",
")",
":",
"try",
":",
"layer",
"=",
"capi",
".",
"get_layer_by_name",
"(",
"self",
".",
"ptr",
",",
"force_bytes",
"(",
"index",
")",
")",
"except",
"GDALException",
":",
"raise",
"IndexError",
"(",
"'Invalid OGR layer name given: %s.'",
"%",
"index",
")",
"elif",
"isinstance",
"(",
"index",
",",
"int",
")",
":",
"if",
"0",
"<=",
"index",
"<",
"self",
".",
"layer_count",
":",
"layer",
"=",
"capi",
".",
"get_layer",
"(",
"self",
".",
"_ptr",
",",
"index",
")",
"else",
":",
"raise",
"IndexError",
"(",
"'Index out of range when accessing layers in a datasource: %s.'",
"%",
"index",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'Invalid index type: %s'",
"%",
"type",
"(",
"index",
")",
")",
"return",
"Layer",
"(",
"layer",
",",
"self",
")"
] | [
87,
4
] | [
101,
33
] | python | en | ['en', 'en', 'en'] | True |
DataSource.__len__ | (self) | Return the number of layers within the data source. | Return the number of layers within the data source. | def __len__(self):
"Return the number of layers within the data source."
return self.layer_count | [
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"self",
".",
"layer_count"
] | [
103,
4
] | [
105,
31
] | python | en | ['en', 'en', 'en'] | True |
DataSource.__str__ | (self) | Return OGR GetName and Driver for the Data Source. | Return OGR GetName and Driver for the Data Source. | def __str__(self):
"Return OGR GetName and Driver for the Data Source."
return '%s (%s)' % (self.name, self.driver) | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"'%s (%s)'",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"driver",
")"
] | [
107,
4
] | [
109,
51
] | python | en | ['en', 'en', 'en'] | True |
DataSource.layer_count | (self) | Return the number of layers in the data source. | Return the number of layers in the data source. | def layer_count(self):
"Return the number of layers in the data source."
return capi.get_layer_count(self._ptr) | [
"def",
"layer_count",
"(",
"self",
")",
":",
"return",
"capi",
".",
"get_layer_count",
"(",
"self",
".",
"_ptr",
")"
] | [
112,
4
] | [
114,
46
] | python | en | ['en', 'en', 'en'] | True |
DataSource.name | (self) | Return the name of the data source. | Return the name of the data source. | def name(self):
"Return the name of the data source."
name = capi.get_ds_name(self._ptr)
return force_str(name, self.encoding, strings_only=True) | [
"def",
"name",
"(",
"self",
")",
":",
"name",
"=",
"capi",
".",
"get_ds_name",
"(",
"self",
".",
"_ptr",
")",
"return",
"force_str",
"(",
"name",
",",
"self",
".",
"encoding",
",",
"strings_only",
"=",
"True",
")"
] | [
117,
4
] | [
120,
64
] | python | en | ['en', 'en', 'en'] | True |
get_func_full_args | (func) |
Return a list of (argument name, default value) tuples. If the argument
does not have a default value, omit it in the tuple. Arguments such as
*args and **kwargs are also included.
|
Return a list of (argument name, default value) tuples. If the argument
does not have a default value, omit it in the tuple. Arguments such as
*args and **kwargs are also included.
| def get_func_full_args(func):
"""
Return a list of (argument name, default value) tuples. If the argument
does not have a default value, omit it in the tuple. Arguments such as
*args and **kwargs are also included.
"""
params = _get_callable_parameters(func)
args = []
for param in params:
name = param.name
# Ignore 'self'
if name == 'self':
continue
if param.kind == inspect.Parameter.VAR_POSITIONAL:
name = '*' + name
elif param.kind == inspect.Parameter.VAR_KEYWORD:
name = '**' + name
if param.default != inspect.Parameter.empty:
args.append((name, param.default))
else:
args.append((name,))
return args | [
"def",
"get_func_full_args",
"(",
"func",
")",
":",
"params",
"=",
"_get_callable_parameters",
"(",
"func",
")",
"args",
"=",
"[",
"]",
"for",
"param",
"in",
"params",
":",
"name",
"=",
"param",
".",
"name",
"# Ignore 'self'",
"if",
"name",
"==",
"'self'",
":",
"continue",
"if",
"param",
".",
"kind",
"==",
"inspect",
".",
"Parameter",
".",
"VAR_POSITIONAL",
":",
"name",
"=",
"'*'",
"+",
"name",
"elif",
"param",
".",
"kind",
"==",
"inspect",
".",
"Parameter",
".",
"VAR_KEYWORD",
":",
"name",
"=",
"'**'",
"+",
"name",
"if",
"param",
".",
"default",
"!=",
"inspect",
".",
"Parameter",
".",
"empty",
":",
"args",
".",
"append",
"(",
"(",
"name",
",",
"param",
".",
"default",
")",
")",
"else",
":",
"args",
".",
"append",
"(",
"(",
"name",
",",
")",
")",
"return",
"args"
] | [
26,
0
] | [
47,
15
] | python | en | ['en', 'error', 'th'] | False |
func_accepts_kwargs | (func) | Return True if function 'func' accepts keyword arguments **kwargs. | Return True if function 'func' accepts keyword arguments **kwargs. | def func_accepts_kwargs(func):
"""Return True if function 'func' accepts keyword arguments **kwargs."""
return any(
p for p in _get_callable_parameters(func)
if p.kind == p.VAR_KEYWORD
) | [
"def",
"func_accepts_kwargs",
"(",
"func",
")",
":",
"return",
"any",
"(",
"p",
"for",
"p",
"in",
"_get_callable_parameters",
"(",
"func",
")",
"if",
"p",
".",
"kind",
"==",
"p",
".",
"VAR_KEYWORD",
")"
] | [
50,
0
] | [
55,
5
] | python | en | ['en', 'en', 'en'] | True |
func_accepts_var_args | (func) |
Return True if function 'func' accepts positional arguments *args.
|
Return True if function 'func' accepts positional arguments *args.
| def func_accepts_var_args(func):
"""
Return True if function 'func' accepts positional arguments *args.
"""
return any(
p for p in _get_callable_parameters(func)
if p.kind == p.VAR_POSITIONAL
) | [
"def",
"func_accepts_var_args",
"(",
"func",
")",
":",
"return",
"any",
"(",
"p",
"for",
"p",
"in",
"_get_callable_parameters",
"(",
"func",
")",
"if",
"p",
".",
"kind",
"==",
"p",
".",
"VAR_POSITIONAL",
")"
] | [
58,
0
] | [
65,
5
] | python | en | ['en', 'error', 'th'] | False |
method_has_no_args | (meth) | Return True if a method only accepts 'self'. | Return True if a method only accepts 'self'. | def method_has_no_args(meth):
"""Return True if a method only accepts 'self'."""
count = len([
p for p in _get_callable_parameters(meth)
if p.kind == p.POSITIONAL_OR_KEYWORD
])
return count == 0 if inspect.ismethod(meth) else count == 1 | [
"def",
"method_has_no_args",
"(",
"meth",
")",
":",
"count",
"=",
"len",
"(",
"[",
"p",
"for",
"p",
"in",
"_get_callable_parameters",
"(",
"meth",
")",
"if",
"p",
".",
"kind",
"==",
"p",
".",
"POSITIONAL_OR_KEYWORD",
"]",
")",
"return",
"count",
"==",
"0",
"if",
"inspect",
".",
"ismethod",
"(",
"meth",
")",
"else",
"count",
"==",
"1"
] | [
68,
0
] | [
74,
63
] | python | en | ['en', 'en', 'en'] | True |
Extractor.fit | (self, documents, labels, weights=None) |
Fit :class`Extractor` features and model to a training dataset.
Args:
blocks (List[Block])
labels (``np.ndarray``)
weights (``np.ndarray``)
Returns:
:class`Extractor`
|
Fit :class`Extractor` features and model to a training dataset. | def fit(self, documents, labels, weights=None):
"""
Fit :class`Extractor` features and model to a training dataset.
Args:
blocks (List[Block])
labels (``np.ndarray``)
weights (``np.ndarray``)
Returns:
:class`Extractor`
"""
block_groups = np.array([self.blockifier.blockify(doc) for doc in documents])
mask = [self._has_enough_blocks(blocks) for blocks in block_groups]
block_groups = block_groups[mask]
labels = np.concatenate(np.array(labels)[mask])
# TODO: This only 'fit's one doc at a time. No feature fitting actually
# happens for now, but this might be important if the features change
features_mat = np.concatenate([self.features.fit_transform(blocks)
for blocks in block_groups])
if weights is None:
self.model.fit(features_mat, labels)
else:
weights = np.concatenate(np.array(weights)[mask])
self.model.fit(features_mat, labels, sample_weight=weights)
return self | [
"def",
"fit",
"(",
"self",
",",
"documents",
",",
"labels",
",",
"weights",
"=",
"None",
")",
":",
"block_groups",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"blockifier",
".",
"blockify",
"(",
"doc",
")",
"for",
"doc",
"in",
"documents",
"]",
")",
"mask",
"=",
"[",
"self",
".",
"_has_enough_blocks",
"(",
"blocks",
")",
"for",
"blocks",
"in",
"block_groups",
"]",
"block_groups",
"=",
"block_groups",
"[",
"mask",
"]",
"labels",
"=",
"np",
".",
"concatenate",
"(",
"np",
".",
"array",
"(",
"labels",
")",
"[",
"mask",
"]",
")",
"# TODO: This only 'fit's one doc at a time. No feature fitting actually",
"# happens for now, but this might be important if the features change",
"features_mat",
"=",
"np",
".",
"concatenate",
"(",
"[",
"self",
".",
"features",
".",
"fit_transform",
"(",
"blocks",
")",
"for",
"blocks",
"in",
"block_groups",
"]",
")",
"if",
"weights",
"is",
"None",
":",
"self",
".",
"model",
".",
"fit",
"(",
"features_mat",
",",
"labels",
")",
"else",
":",
"weights",
"=",
"np",
".",
"concatenate",
"(",
"np",
".",
"array",
"(",
"weights",
")",
"[",
"mask",
"]",
")",
"self",
".",
"model",
".",
"fit",
"(",
"features_mat",
",",
"labels",
",",
"sample_weight",
"=",
"weights",
")",
"return",
"self"
] | [
68,
4
] | [
94,
19
] | python | en | ['en', 'error', 'th'] | False |
Extractor.get_html_labels_weights | (self, data) |
Gather the html, labels, and weights of many files' data.
Primarily useful for training/testing an :class`Extractor`.
Args:
data: Output of :func:`dragnet.data_processing.prepare_all_data`.
Returns:
Tuple[List[Block], np.array(int), np.array(int)]: All blocks, all
labels, and all weights, respectively.
|
Gather the html, labels, and weights of many files' data.
Primarily useful for training/testing an :class`Extractor`. | def get_html_labels_weights(self, data):
"""
Gather the html, labels, and weights of many files' data.
Primarily useful for training/testing an :class`Extractor`.
Args:
data: Output of :func:`dragnet.data_processing.prepare_all_data`.
Returns:
Tuple[List[Block], np.array(int), np.array(int)]: All blocks, all
labels, and all weights, respectively.
"""
all_html = []
all_labels = []
all_weights = []
for html, content, comments in data:
all_html.append(html)
labels, weights = self._get_labels_and_weights(
content, comments)
all_labels.append(labels)
all_weights.append(weights)
return np.array(all_html), np.array(all_labels), np.array(all_weights) | [
"def",
"get_html_labels_weights",
"(",
"self",
",",
"data",
")",
":",
"all_html",
"=",
"[",
"]",
"all_labels",
"=",
"[",
"]",
"all_weights",
"=",
"[",
"]",
"for",
"html",
",",
"content",
",",
"comments",
"in",
"data",
":",
"all_html",
".",
"append",
"(",
"html",
")",
"labels",
",",
"weights",
"=",
"self",
".",
"_get_labels_and_weights",
"(",
"content",
",",
"comments",
")",
"all_labels",
".",
"append",
"(",
"labels",
")",
"all_weights",
".",
"append",
"(",
"weights",
")",
"return",
"np",
".",
"array",
"(",
"all_html",
")",
",",
"np",
".",
"array",
"(",
"all_labels",
")",
",",
"np",
".",
"array",
"(",
"all_weights",
")"
] | [
96,
4
] | [
117,
78
] | python | en | ['en', 'error', 'th'] | False |
Extractor._get_labels_and_weights | (self, content, comments) |
Args:
content (Tuple[np.array[int], np.array[int], List[str]])
comments (Tuple[np.array[int], np.array[int], List[str]])
Returns:
Tuple[np.array[int], np.array[int], List[str]]
|
Args:
content (Tuple[np.array[int], np.array[int], List[str]])
comments (Tuple[np.array[int], np.array[int], List[str]]) | def _get_labels_and_weights(self, content, comments):
"""
Args:
content (Tuple[np.array[int], np.array[int], List[str]])
comments (Tuple[np.array[int], np.array[int], List[str]])
Returns:
Tuple[np.array[int], np.array[int], List[str]]
"""
# extract content and comments
if 'content' in self.to_extract and 'comments' in self.to_extract:
labels = np.logical_or(content[0], comments[0]).astype(int)
weights = content[1],
# extract content only
elif 'content' in self.to_extract:
labels = content[0]
weights = content[1]
# extract comments only
else:
labels = comments[0]
weights = comments[1]
if self.max_block_weight is None:
weights = np.minimum(weights, self.max_block_weight)
return labels, weights | [
"def",
"_get_labels_and_weights",
"(",
"self",
",",
"content",
",",
"comments",
")",
":",
"# extract content and comments",
"if",
"'content'",
"in",
"self",
".",
"to_extract",
"and",
"'comments'",
"in",
"self",
".",
"to_extract",
":",
"labels",
"=",
"np",
".",
"logical_or",
"(",
"content",
"[",
"0",
"]",
",",
"comments",
"[",
"0",
"]",
")",
".",
"astype",
"(",
"int",
")",
"weights",
"=",
"content",
"[",
"1",
"]",
",",
"# extract content only",
"elif",
"'content'",
"in",
"self",
".",
"to_extract",
":",
"labels",
"=",
"content",
"[",
"0",
"]",
"weights",
"=",
"content",
"[",
"1",
"]",
"# extract comments only",
"else",
":",
"labels",
"=",
"comments",
"[",
"0",
"]",
"weights",
"=",
"comments",
"[",
"1",
"]",
"if",
"self",
".",
"max_block_weight",
"is",
"None",
":",
"weights",
"=",
"np",
".",
"minimum",
"(",
"weights",
",",
"self",
".",
"max_block_weight",
")",
"return",
"labels",
",",
"weights"
] | [
126,
4
] | [
150,
30
] | python | en | ['en', 'error', 'th'] | False |
Extractor.extract | (self, html, encoding=None, as_blocks=False) |
Extract the main content and/or comments from an HTML document and
return it as a string or as a sequence of block objects.
Args:
html (str): HTML document as a string.
encoding (str): Encoding of ``html``. If None (encoding unknown), the
original encoding will be guessed from the HTML itself.
as_blocks (bool): If False, return the main content as a combined
string; if True, return the content-holding blocks as a list of
block objects.
Returns:
str or List[Block]
|
Extract the main content and/or comments from an HTML document and
return it as a string or as a sequence of block objects. | def extract(self, html, encoding=None, as_blocks=False):
"""
Extract the main content and/or comments from an HTML document and
return it as a string or as a sequence of block objects.
Args:
html (str): HTML document as a string.
encoding (str): Encoding of ``html``. If None (encoding unknown), the
original encoding will be guessed from the HTML itself.
as_blocks (bool): If False, return the main content as a combined
string; if True, return the content-holding blocks as a list of
block objects.
Returns:
str or List[Block]
"""
preds, blocks = self.predict(html, encoding=encoding, return_blocks=True)
if as_blocks is False:
return str_cast(b'\n'.join(blocks[ind].text for ind in np.flatnonzero(preds)))
else:
return [blocks[ind] for ind in np.flatnonzero(preds)] | [
"def",
"extract",
"(",
"self",
",",
"html",
",",
"encoding",
"=",
"None",
",",
"as_blocks",
"=",
"False",
")",
":",
"preds",
",",
"blocks",
"=",
"self",
".",
"predict",
"(",
"html",
",",
"encoding",
"=",
"encoding",
",",
"return_blocks",
"=",
"True",
")",
"if",
"as_blocks",
"is",
"False",
":",
"return",
"str_cast",
"(",
"b'\\n'",
".",
"join",
"(",
"blocks",
"[",
"ind",
"]",
".",
"text",
"for",
"ind",
"in",
"np",
".",
"flatnonzero",
"(",
"preds",
")",
")",
")",
"else",
":",
"return",
"[",
"blocks",
"[",
"ind",
"]",
"for",
"ind",
"in",
"np",
".",
"flatnonzero",
"(",
"preds",
")",
"]"
] | [
152,
4
] | [
172,
65
] | python | en | ['en', 'error', 'th'] | False |
Extractor.predict | (self, documents, **kwargs) |
Predict class (content=1 or not-content=0) of the blocks in one or many
HTML document(s).
Args:
documents (str or List[str]): HTML document(s)
Returns:
``np.ndarray`` or List[``np.ndarray``]: array of binary predictions
for content (1) or not-content (0).
|
Predict class (content=1 or not-content=0) of the blocks in one or many
HTML document(s). | def predict(self, documents, **kwargs):
"""
Predict class (content=1 or not-content=0) of the blocks in one or many
HTML document(s).
Args:
documents (str or List[str]): HTML document(s)
Returns:
``np.ndarray`` or List[``np.ndarray``]: array of binary predictions
for content (1) or not-content (0).
"""
if isinstance(documents, (str, bytes, unicode_, np.unicode_)):
return self._predict_one(documents, **kwargs)
else:
return np.concatenate([self._predict_one(doc, **kwargs) for doc in documents]) | [
"def",
"predict",
"(",
"self",
",",
"documents",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"documents",
",",
"(",
"str",
",",
"bytes",
",",
"unicode_",
",",
"np",
".",
"unicode_",
")",
")",
":",
"return",
"self",
".",
"_predict_one",
"(",
"documents",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"np",
".",
"concatenate",
"(",
"[",
"self",
".",
"_predict_one",
"(",
"doc",
",",
"*",
"*",
"kwargs",
")",
"for",
"doc",
"in",
"documents",
"]",
")"
] | [
175,
4
] | [
190,
90
] | python | en | ['en', 'error', 'th'] | False |
Extractor._predict_one | (self, document, encoding=None, return_blocks=False) |
Predict class (content=1 or not-content=0) of each block in an HTML
document.
Args:
documents (str): HTML document
Returns:
``np.ndarray``: array of binary predictions for content (1) or
not-content (0).
|
Predict class (content=1 or not-content=0) of each block in an HTML
document. | def _predict_one(self, document, encoding=None, return_blocks=False):
"""
Predict class (content=1 or not-content=0) of each block in an HTML
document.
Args:
documents (str): HTML document
Returns:
``np.ndarray``: array of binary predictions for content (1) or
not-content (0).
"""
# blockify
blocks = self.blockifier.blockify(document, encoding=encoding)
# get features
try:
features = self.features.transform(blocks)
except ValueError: # Can't make features, predict no content
preds = np.zeros((len(blocks)))
# make predictions
else:
if self.prob_threshold is None:
preds = self.model.predict(features)
else:
self._positive_idx = (
self._positive_idx or list(self.model.classes_).index(1))
preds = self.model.predict_proba(features) > self.prob_threshold
preds = preds[:, self._positive_idx].astype(int)
if return_blocks:
return preds, blocks
else:
return preds | [
"def",
"_predict_one",
"(",
"self",
",",
"document",
",",
"encoding",
"=",
"None",
",",
"return_blocks",
"=",
"False",
")",
":",
"# blockify",
"blocks",
"=",
"self",
".",
"blockifier",
".",
"blockify",
"(",
"document",
",",
"encoding",
"=",
"encoding",
")",
"# get features",
"try",
":",
"features",
"=",
"self",
".",
"features",
".",
"transform",
"(",
"blocks",
")",
"except",
"ValueError",
":",
"# Can't make features, predict no content",
"preds",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"blocks",
")",
")",
")",
"# make predictions",
"else",
":",
"if",
"self",
".",
"prob_threshold",
"is",
"None",
":",
"preds",
"=",
"self",
".",
"model",
".",
"predict",
"(",
"features",
")",
"else",
":",
"self",
".",
"_positive_idx",
"=",
"(",
"self",
".",
"_positive_idx",
"or",
"list",
"(",
"self",
".",
"model",
".",
"classes_",
")",
".",
"index",
"(",
"1",
")",
")",
"preds",
"=",
"self",
".",
"model",
".",
"predict_proba",
"(",
"features",
")",
">",
"self",
".",
"prob_threshold",
"preds",
"=",
"preds",
"[",
":",
",",
"self",
".",
"_positive_idx",
"]",
".",
"astype",
"(",
"int",
")",
"if",
"return_blocks",
":",
"return",
"preds",
",",
"blocks",
"else",
":",
"return",
"preds"
] | [
193,
4
] | [
225,
24
] | python | en | ['en', 'error', 'th'] | False |
Cache.__init__ | (self, max_age) | Constructor.
Args:
max_age: Cache expiration in seconds.
| Constructor. | def __init__(self, max_age):
"""Constructor.
Args:
max_age: Cache expiration in seconds.
"""
self._max_age = max_age | [
"def",
"__init__",
"(",
"self",
",",
"max_age",
")",
":",
"self",
".",
"_max_age",
"=",
"max_age"
] | [
34,
2
] | [
40,
29
] | python | en | ['en', 'en', 'en'] | False |
sms_reply | () | Respond to incoming calls with a MMS message. | Respond to incoming calls with a MMS message. | def sms_reply():
"""Respond to incoming calls with a MMS message."""
# Start our TwiML response
resp = MessagingResponse()
# Add a text message
msg = resp.message("The Robots are coming! Head for the hills!")
# Add a picture message
msg.media(
"https://farm8.staticflickr.com/7090/6941316406_80b4d6d50e_z_d.jpg"
)
return str(resp) | [
"def",
"sms_reply",
"(",
")",
":",
"# Start our TwiML response",
"resp",
"=",
"MessagingResponse",
"(",
")",
"# Add a text message",
"msg",
"=",
"resp",
".",
"message",
"(",
"\"The Robots are coming! Head for the hills!\"",
")",
"# Add a picture message",
"msg",
".",
"media",
"(",
"\"https://farm8.staticflickr.com/7090/6941316406_80b4d6d50e_z_d.jpg\"",
")",
"return",
"str",
"(",
"resp",
")"
] | [
7,
0
] | [
20,
20
] | python | en | ['en', 'en', 'en'] | True |
config_file | (kind="local") | Get the filename of the distutils, local, global, or per-user config
`kind` must be one of "local", "global", or "user"
| Get the filename of the distutils, local, global, or per-user config | def config_file(kind="local"):
"""Get the filename of the distutils, local, global, or per-user config
`kind` must be one of "local", "global", or "user"
"""
if kind == 'local':
return 'setup.cfg'
if kind == 'global':
return os.path.join(
os.path.dirname(distutils.__file__), 'distutils.cfg'
)
if kind == 'user':
dot = os.name == 'posix' and '.' or ''
return os.path.expanduser(convert_path("~/%spydistutils.cfg" % dot))
raise ValueError(
"config_file() type must be 'local', 'global', or 'user'", kind
) | [
"def",
"config_file",
"(",
"kind",
"=",
"\"local\"",
")",
":",
"if",
"kind",
"==",
"'local'",
":",
"return",
"'setup.cfg'",
"if",
"kind",
"==",
"'global'",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"distutils",
".",
"__file__",
")",
",",
"'distutils.cfg'",
")",
"if",
"kind",
"==",
"'user'",
":",
"dot",
"=",
"os",
".",
"name",
"==",
"'posix'",
"and",
"'.'",
"or",
"''",
"return",
"os",
".",
"path",
".",
"expanduser",
"(",
"convert_path",
"(",
"\"~/%spydistutils.cfg\"",
"%",
"dot",
")",
")",
"raise",
"ValueError",
"(",
"\"config_file() type must be 'local', 'global', or 'user'\"",
",",
"kind",
")"
] | [
13,
0
] | [
29,
5
] | python | en | ['en', 'en', 'en'] | True |
edit_config | (filename, settings, dry_run=False) | Edit a configuration file to include `settings`
`settings` is a dictionary of dictionaries or ``None`` values, keyed by
command/section name. A ``None`` value means to delete the entire section,
while a dictionary lists settings to be changed or deleted in that section.
A setting of ``None`` means to delete that setting.
| Edit a configuration file to include `settings` | def edit_config(filename, settings, dry_run=False):
"""Edit a configuration file to include `settings`
`settings` is a dictionary of dictionaries or ``None`` values, keyed by
command/section name. A ``None`` value means to delete the entire section,
while a dictionary lists settings to be changed or deleted in that section.
A setting of ``None`` means to delete that setting.
"""
log.debug("Reading configuration from %s", filename)
opts = configparser.RawConfigParser()
opts.read([filename])
for section, options in settings.items():
if options is None:
log.info("Deleting section [%s] from %s", section, filename)
opts.remove_section(section)
else:
if not opts.has_section(section):
log.debug("Adding new section [%s] to %s", section, filename)
opts.add_section(section)
for option, value in options.items():
if value is None:
log.debug(
"Deleting %s.%s from %s",
section, option, filename
)
opts.remove_option(section, option)
if not opts.options(section):
log.info("Deleting empty [%s] section from %s",
section, filename)
opts.remove_section(section)
else:
log.debug(
"Setting %s.%s to %r in %s",
section, option, value, filename
)
opts.set(section, option, value)
log.info("Writing %s", filename)
if not dry_run:
with open(filename, 'w') as f:
opts.write(f) | [
"def",
"edit_config",
"(",
"filename",
",",
"settings",
",",
"dry_run",
"=",
"False",
")",
":",
"log",
".",
"debug",
"(",
"\"Reading configuration from %s\"",
",",
"filename",
")",
"opts",
"=",
"configparser",
".",
"RawConfigParser",
"(",
")",
"opts",
".",
"read",
"(",
"[",
"filename",
"]",
")",
"for",
"section",
",",
"options",
"in",
"settings",
".",
"items",
"(",
")",
":",
"if",
"options",
"is",
"None",
":",
"log",
".",
"info",
"(",
"\"Deleting section [%s] from %s\"",
",",
"section",
",",
"filename",
")",
"opts",
".",
"remove_section",
"(",
"section",
")",
"else",
":",
"if",
"not",
"opts",
".",
"has_section",
"(",
"section",
")",
":",
"log",
".",
"debug",
"(",
"\"Adding new section [%s] to %s\"",
",",
"section",
",",
"filename",
")",
"opts",
".",
"add_section",
"(",
"section",
")",
"for",
"option",
",",
"value",
"in",
"options",
".",
"items",
"(",
")",
":",
"if",
"value",
"is",
"None",
":",
"log",
".",
"debug",
"(",
"\"Deleting %s.%s from %s\"",
",",
"section",
",",
"option",
",",
"filename",
")",
"opts",
".",
"remove_option",
"(",
"section",
",",
"option",
")",
"if",
"not",
"opts",
".",
"options",
"(",
"section",
")",
":",
"log",
".",
"info",
"(",
"\"Deleting empty [%s] section from %s\"",
",",
"section",
",",
"filename",
")",
"opts",
".",
"remove_section",
"(",
"section",
")",
"else",
":",
"log",
".",
"debug",
"(",
"\"Setting %s.%s to %r in %s\"",
",",
"section",
",",
"option",
",",
"value",
",",
"filename",
")",
"opts",
".",
"set",
"(",
"section",
",",
"option",
",",
"value",
")",
"log",
".",
"info",
"(",
"\"Writing %s\"",
",",
"filename",
")",
"if",
"not",
"dry_run",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"opts",
".",
"write",
"(",
"f",
")"
] | [
32,
0
] | [
72,
25
] | python | en | ['en', 'en', 'en'] | True |
_xml_escape | (data) | Escape &, <, >, ", ', etc. in a string of data. | Escape &, <, >, ", ', etc. in a string of data. | def _xml_escape(data):
"""Escape &, <, >, ", ', etc. in a string of data."""
# ampersand must be replaced first
from_symbols = '&><"\''
to_symbols = ('&' + s + ';' for s in "amp gt lt quot apos".split())
for from_, to_ in zip(from_symbols, to_symbols):
data = data.replace(from_, to_)
return data | [
"def",
"_xml_escape",
"(",
"data",
")",
":",
"# ampersand must be replaced first",
"from_symbols",
"=",
"'&><\"\\''",
"to_symbols",
"=",
"(",
"'&'",
"+",
"s",
"+",
"';'",
"for",
"s",
"in",
"\"amp gt lt quot apos\"",
".",
"split",
"(",
")",
")",
"for",
"from_",
",",
"to_",
"in",
"zip",
"(",
"from_symbols",
",",
"to_symbols",
")",
":",
"data",
"=",
"data",
".",
"replace",
"(",
"from_",
",",
"to_",
")",
"return",
"data"
] | [
269,
0
] | [
277,
15
] | python | en | ['en', 'en', 'en'] | True |
col | (loc, strg) | Returns current column within a string, counting newlines as line separators.
The first column is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See
:class:`ParserElement.parseString` for more
information on parsing strings containing ``<TAB>`` s, and suggested
methods to maintain a consistent view of the parsed string, the parse
location, and line and column positions within the parsed string.
| Returns current column within a string, counting newlines as line separators.
The first column is number 1. | def col (loc, strg):
"""Returns current column within a string, counting newlines as line separators.
The first column is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See
:class:`ParserElement.parseString` for more
information on parsing strings containing ``<TAB>`` s, and suggested
methods to maintain a consistent view of the parsed string, the parse
location, and line and column positions within the parsed string.
"""
s = strg
return 1 if 0 < loc < len(s) and s[loc-1] == '\n' else loc - s.rfind("\n", 0, loc) | [
"def",
"col",
"(",
"loc",
",",
"strg",
")",
":",
"s",
"=",
"strg",
"return",
"1",
"if",
"0",
"<",
"loc",
"<",
"len",
"(",
"s",
")",
"and",
"s",
"[",
"loc",
"-",
"1",
"]",
"==",
"'\\n'",
"else",
"loc",
"-",
"s",
".",
"rfind",
"(",
"\"\\n\"",
",",
"0",
",",
"loc",
")"
] | [
1210,
0
] | [
1222,
86
] | python | en | ['en', 'en', 'en'] | True |
lineno | (loc, strg) | Returns current line number within a string, counting newlines as line separators.
The first line is number 1.
Note - the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See :class:`ParserElement.parseString`
for more information on parsing strings containing ``<TAB>`` s, and
suggested methods to maintain a consistent view of the parsed string, the
parse location, and line and column positions within the parsed string.
| Returns current line number within a string, counting newlines as line separators.
The first line is number 1. | def lineno(loc, strg):
"""Returns current line number within a string, counting newlines as line separators.
The first line is number 1.
Note - the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See :class:`ParserElement.parseString`
for more information on parsing strings containing ``<TAB>`` s, and
suggested methods to maintain a consistent view of the parsed string, the
parse location, and line and column positions within the parsed string.
"""
return strg.count("\n", 0, loc) + 1 | [
"def",
"lineno",
"(",
"loc",
",",
"strg",
")",
":",
"return",
"strg",
".",
"count",
"(",
"\"\\n\"",
",",
"0",
",",
"loc",
")",
"+",
"1"
] | [
1224,
0
] | [
1234,
39
] | python | en | ['en', 'en', 'en'] | True |
line | (loc, strg) | Returns the line of text containing loc within a string, counting newlines as line separators.
| Returns the line of text containing loc within a string, counting newlines as line separators.
| def line(loc, strg):
"""Returns the line of text containing loc within a string, counting newlines as line separators.
"""
lastCR = strg.rfind("\n", 0, loc)
nextCR = strg.find("\n", loc)
if nextCR >= 0:
return strg[lastCR + 1:nextCR]
else:
return strg[lastCR + 1:] | [
"def",
"line",
"(",
"loc",
",",
"strg",
")",
":",
"lastCR",
"=",
"strg",
".",
"rfind",
"(",
"\"\\n\"",
",",
"0",
",",
"loc",
")",
"nextCR",
"=",
"strg",
".",
"find",
"(",
"\"\\n\"",
",",
"loc",
")",
"if",
"nextCR",
">=",
"0",
":",
"return",
"strg",
"[",
"lastCR",
"+",
"1",
":",
"nextCR",
"]",
"else",
":",
"return",
"strg",
"[",
"lastCR",
"+",
"1",
":",
"]"
] | [
1236,
0
] | [
1244,
32
] | python | en | ['en', 'en', 'en'] | True |
nullDebugAction | (*args) | Do-nothing' debug action, to suppress debugging output during parsing. | Do-nothing' debug action, to suppress debugging output during parsing. | def nullDebugAction(*args):
"""'Do-nothing' debug action, to suppress debugging output during parsing."""
pass | [
"def",
"nullDebugAction",
"(",
"*",
"args",
")",
":",
"pass"
] | [
1255,
0
] | [
1257,
8
] | python | en | ['en', 'jv', 'en'] | True |
ParseBaseException._from_exception | (cls, pe) |
internal factory method to simplify creating one type of ParseException
from another - avoids having __init__ signature conflicts among subclasses
|
internal factory method to simplify creating one type of ParseException
from another - avoids having __init__ signature conflicts among subclasses
| def _from_exception(cls, pe):
"""
internal factory method to simplify creating one type of ParseException
from another - avoids having __init__ signature conflicts among subclasses
"""
return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement) | [
"def",
"_from_exception",
"(",
"cls",
",",
"pe",
")",
":",
"return",
"cls",
"(",
"pe",
".",
"pstr",
",",
"pe",
".",
"loc",
",",
"pe",
".",
"msg",
",",
"pe",
".",
"parserElement",
")"
] | [
315,
4
] | [
320,
61
] | python | en | ['en', 'error', 'th'] | False |
ParseBaseException.__getattr__ | (self, aname) | supported attributes by name are:
- lineno - returns the line number of the exception text
- col - returns the column number of the exception text
- line - returns the line containing the exception text
| supported attributes by name are:
- lineno - returns the line number of the exception text
- col - returns the column number of the exception text
- line - returns the line containing the exception text
| def __getattr__(self, aname):
"""supported attributes by name are:
- lineno - returns the line number of the exception text
- col - returns the column number of the exception text
- line - returns the line containing the exception text
"""
if aname == "lineno":
return lineno(self.loc, self.pstr)
elif aname in ("col", "column"):
return col(self.loc, self.pstr)
elif aname == "line":
return line(self.loc, self.pstr)
else:
raise AttributeError(aname) | [
"def",
"__getattr__",
"(",
"self",
",",
"aname",
")",
":",
"if",
"aname",
"==",
"\"lineno\"",
":",
"return",
"lineno",
"(",
"self",
".",
"loc",
",",
"self",
".",
"pstr",
")",
"elif",
"aname",
"in",
"(",
"\"col\"",
",",
"\"column\"",
")",
":",
"return",
"col",
"(",
"self",
".",
"loc",
",",
"self",
".",
"pstr",
")",
"elif",
"aname",
"==",
"\"line\"",
":",
"return",
"line",
"(",
"self",
".",
"loc",
",",
"self",
".",
"pstr",
")",
"else",
":",
"raise",
"AttributeError",
"(",
"aname",
")"
] | [
322,
4
] | [
335,
39
] | python | en | ['en', 'en', 'en'] | True |
ParseBaseException.markInputline | (self, markerString=">!<") | Extracts the exception line from the input string, and marks
the location of the exception with a special symbol.
| Extracts the exception line from the input string, and marks
the location of the exception with a special symbol.
| def markInputline(self, markerString=">!<"):
"""Extracts the exception line from the input string, and marks
the location of the exception with a special symbol.
"""
line_str = self.line
line_column = self.column - 1
if markerString:
line_str = "".join((line_str[:line_column],
markerString, line_str[line_column:]))
return line_str.strip() | [
"def",
"markInputline",
"(",
"self",
",",
"markerString",
"=",
"\">!<\"",
")",
":",
"line_str",
"=",
"self",
".",
"line",
"line_column",
"=",
"self",
".",
"column",
"-",
"1",
"if",
"markerString",
":",
"line_str",
"=",
"\"\"",
".",
"join",
"(",
"(",
"line_str",
"[",
":",
"line_column",
"]",
",",
"markerString",
",",
"line_str",
"[",
"line_column",
":",
"]",
")",
")",
"return",
"line_str",
".",
"strip",
"(",
")"
] | [
349,
4
] | [
358,
31
] | python | en | ['en', 'en', 'en'] | True |
ParseException.explain | (exc, depth=16) |
Method to take an exception and translate the Python internal traceback into a list
of the pyparsing expressions that caused the exception to be raised.
Parameters:
- exc - exception raised during parsing (need not be a ParseException, in support
of Python exceptions that might be raised in a parse action)
- depth (default=16) - number of levels back in the stack trace to list expression
and function names; if None, the full stack trace names will be listed; if 0, only
the failing input line, marker, and exception string will be shown
Returns a multi-line string listing the ParserElements and/or function names in the
exception's stack trace.
Note: the diagnostic output will include string representations of the expressions
that failed to parse. These representations will be more helpful if you use `setName` to
give identifiable names to your expressions. Otherwise they will use the default string
forms, which may be cryptic to read.
explain() is only supported under Python 3.
|
Method to take an exception and translate the Python internal traceback into a list
of the pyparsing expressions that caused the exception to be raised. | def explain(exc, depth=16):
"""
Method to take an exception and translate the Python internal traceback into a list
of the pyparsing expressions that caused the exception to be raised.
Parameters:
- exc - exception raised during parsing (need not be a ParseException, in support
of Python exceptions that might be raised in a parse action)
- depth (default=16) - number of levels back in the stack trace to list expression
and function names; if None, the full stack trace names will be listed; if 0, only
the failing input line, marker, and exception string will be shown
Returns a multi-line string listing the ParserElements and/or function names in the
exception's stack trace.
Note: the diagnostic output will include string representations of the expressions
that failed to parse. These representations will be more helpful if you use `setName` to
give identifiable names to your expressions. Otherwise they will use the default string
forms, which may be cryptic to read.
explain() is only supported under Python 3.
"""
import inspect
if depth is None:
depth = sys.getrecursionlimit()
ret = []
if isinstance(exc, ParseBaseException):
ret.append(exc.line)
ret.append(' ' * (exc.col - 1) + '^')
ret.append("{0}: {1}".format(type(exc).__name__, exc))
if depth > 0:
callers = inspect.getinnerframes(exc.__traceback__, context=depth)
seen = set()
for i, ff in enumerate(callers[-depth:]):
frm = ff[0]
f_self = frm.f_locals.get('self', None)
if isinstance(f_self, ParserElement):
if frm.f_code.co_name not in ('parseImpl', '_parseNoCache'):
continue
if f_self in seen:
continue
seen.add(f_self)
self_type = type(f_self)
ret.append("{0}.{1} - {2}".format(self_type.__module__,
self_type.__name__,
f_self))
elif f_self is not None:
self_type = type(f_self)
ret.append("{0}.{1}".format(self_type.__module__,
self_type.__name__))
else:
code = frm.f_code
if code.co_name in ('wrapper', '<module>'):
continue
ret.append("{0}".format(code.co_name))
depth -= 1
if not depth:
break
return '\n'.join(ret) | [
"def",
"explain",
"(",
"exc",
",",
"depth",
"=",
"16",
")",
":",
"import",
"inspect",
"if",
"depth",
"is",
"None",
":",
"depth",
"=",
"sys",
".",
"getrecursionlimit",
"(",
")",
"ret",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"exc",
",",
"ParseBaseException",
")",
":",
"ret",
".",
"append",
"(",
"exc",
".",
"line",
")",
"ret",
".",
"append",
"(",
"' '",
"*",
"(",
"exc",
".",
"col",
"-",
"1",
")",
"+",
"'^'",
")",
"ret",
".",
"append",
"(",
"\"{0}: {1}\"",
".",
"format",
"(",
"type",
"(",
"exc",
")",
".",
"__name__",
",",
"exc",
")",
")",
"if",
"depth",
">",
"0",
":",
"callers",
"=",
"inspect",
".",
"getinnerframes",
"(",
"exc",
".",
"__traceback__",
",",
"context",
"=",
"depth",
")",
"seen",
"=",
"set",
"(",
")",
"for",
"i",
",",
"ff",
"in",
"enumerate",
"(",
"callers",
"[",
"-",
"depth",
":",
"]",
")",
":",
"frm",
"=",
"ff",
"[",
"0",
"]",
"f_self",
"=",
"frm",
".",
"f_locals",
".",
"get",
"(",
"'self'",
",",
"None",
")",
"if",
"isinstance",
"(",
"f_self",
",",
"ParserElement",
")",
":",
"if",
"frm",
".",
"f_code",
".",
"co_name",
"not",
"in",
"(",
"'parseImpl'",
",",
"'_parseNoCache'",
")",
":",
"continue",
"if",
"f_self",
"in",
"seen",
":",
"continue",
"seen",
".",
"add",
"(",
"f_self",
")",
"self_type",
"=",
"type",
"(",
"f_self",
")",
"ret",
".",
"append",
"(",
"\"{0}.{1} - {2}\"",
".",
"format",
"(",
"self_type",
".",
"__module__",
",",
"self_type",
".",
"__name__",
",",
"f_self",
")",
")",
"elif",
"f_self",
"is",
"not",
"None",
":",
"self_type",
"=",
"type",
"(",
"f_self",
")",
"ret",
".",
"append",
"(",
"\"{0}.{1}\"",
".",
"format",
"(",
"self_type",
".",
"__module__",
",",
"self_type",
".",
"__name__",
")",
")",
"else",
":",
"code",
"=",
"frm",
".",
"f_code",
"if",
"code",
".",
"co_name",
"in",
"(",
"'wrapper'",
",",
"'<module>'",
")",
":",
"continue",
"ret",
".",
"append",
"(",
"\"{0}\"",
".",
"format",
"(",
"code",
".",
"co_name",
")",
")",
"depth",
"-=",
"1",
"if",
"not",
"depth",
":",
"break",
"return",
"'\\n'",
".",
"join",
"(",
"ret",
")"
] | [
386,
4
] | [
452,
29
] | python | en | ['en', 'error', 'th'] | False |
ParseResults.haskeys | (self) | Since keys() returns an iterator, this method is helpful in bypassing
code that looks for the existence of any defined results names. | Since keys() returns an iterator, this method is helpful in bypassing
code that looks for the existence of any defined results names. | def haskeys(self):
"""Since keys() returns an iterator, this method is helpful in bypassing
code that looks for the existence of any defined results names."""
return bool(self.__tokdict) | [
"def",
"haskeys",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"self",
".",
"__tokdict",
")"
] | [
695,
4
] | [
698,
35
] | python | en | ['en', 'en', 'en'] | True |
ParseResults.pop | (self, *args, **kwargs) |
Removes and returns item at specified index (default= ``last``).
Supports both ``list`` and ``dict`` semantics for ``pop()``. If
passed no argument or an integer argument, it will use ``list``
semantics and pop tokens from the list of parsed tokens. If passed
a non-integer argument (most likely a string), it will use ``dict``
semantics and pop the corresponding value from any defined results
names. A second default return value argument is supported, just as in
``dict.pop()``.
Example::
def remove_first(tokens):
tokens.pop(0)
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321']
label = Word(alphas)
patt = label("LABEL") + OneOrMore(Word(nums))
print(patt.parseString("AAB 123 321").dump())
# Use pop() in a parse action to remove named result (note that corresponding value is not
# removed from list form of results)
def remove_LABEL(tokens):
tokens.pop("LABEL")
return tokens
patt.addParseAction(remove_LABEL)
print(patt.parseString("AAB 123 321").dump())
prints::
['AAB', '123', '321']
- LABEL: AAB
['AAB', '123', '321']
|
Removes and returns item at specified index (default= ``last``).
Supports both ``list`` and ``dict`` semantics for ``pop()``. If
passed no argument or an integer argument, it will use ``list``
semantics and pop tokens from the list of parsed tokens. If passed
a non-integer argument (most likely a string), it will use ``dict``
semantics and pop the corresponding value from any defined results
names. A second default return value argument is supported, just as in
``dict.pop()``. | def pop(self, *args, **kwargs):
"""
Removes and returns item at specified index (default= ``last``).
Supports both ``list`` and ``dict`` semantics for ``pop()``. If
passed no argument or an integer argument, it will use ``list``
semantics and pop tokens from the list of parsed tokens. If passed
a non-integer argument (most likely a string), it will use ``dict``
semantics and pop the corresponding value from any defined results
names. A second default return value argument is supported, just as in
``dict.pop()``.
Example::
def remove_first(tokens):
tokens.pop(0)
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321']
label = Word(alphas)
patt = label("LABEL") + OneOrMore(Word(nums))
print(patt.parseString("AAB 123 321").dump())
# Use pop() in a parse action to remove named result (note that corresponding value is not
# removed from list form of results)
def remove_LABEL(tokens):
tokens.pop("LABEL")
return tokens
patt.addParseAction(remove_LABEL)
print(patt.parseString("AAB 123 321").dump())
prints::
['AAB', '123', '321']
- LABEL: AAB
['AAB', '123', '321']
"""
if not args:
args = [-1]
for k, v in kwargs.items():
if k == 'default':
args = (args[0], v)
else:
raise TypeError("pop() got an unexpected keyword argument '%s'" % k)
if (isinstance(args[0], int)
or len(args) == 1
or args[0] in self):
index = args[0]
ret = self[index]
del self[index]
return ret
else:
defaultvalue = args[1]
return defaultvalue | [
"def",
"pop",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"args",
":",
"args",
"=",
"[",
"-",
"1",
"]",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'default'",
":",
"args",
"=",
"(",
"args",
"[",
"0",
"]",
",",
"v",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"pop() got an unexpected keyword argument '%s'\"",
"%",
"k",
")",
"if",
"(",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"int",
")",
"or",
"len",
"(",
"args",
")",
"==",
"1",
"or",
"args",
"[",
"0",
"]",
"in",
"self",
")",
":",
"index",
"=",
"args",
"[",
"0",
"]",
"ret",
"=",
"self",
"[",
"index",
"]",
"del",
"self",
"[",
"index",
"]",
"return",
"ret",
"else",
":",
"defaultvalue",
"=",
"args",
"[",
"1",
"]",
"return",
"defaultvalue"
] | [
700,
4
] | [
753,
31
] | python | en | ['en', 'error', 'th'] | False |
ParseResults.get | (self, key, defaultValue=None) |
Returns named result matching the given key, or if there is no
such name, then returns the given ``defaultValue`` or ``None`` if no
``defaultValue`` is specified.
Similar to ``dict.get()``.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString("1999/12/31")
print(result.get("year")) # -> '1999'
print(result.get("hour", "not specified")) # -> 'not specified'
print(result.get("hour")) # -> None
|
Returns named result matching the given key, or if there is no
such name, then returns the given ``defaultValue`` or ``None`` if no
``defaultValue`` is specified. | def get(self, key, defaultValue=None):
"""
Returns named result matching the given key, or if there is no
such name, then returns the given ``defaultValue`` or ``None`` if no
``defaultValue`` is specified.
Similar to ``dict.get()``.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString("1999/12/31")
print(result.get("year")) # -> '1999'
print(result.get("hour", "not specified")) # -> 'not specified'
print(result.get("hour")) # -> None
"""
if key in self:
return self[key]
else:
return defaultValue | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"defaultValue",
"=",
"None",
")",
":",
"if",
"key",
"in",
"self",
":",
"return",
"self",
"[",
"key",
"]",
"else",
":",
"return",
"defaultValue"
] | [
755,
4
] | [
776,
31
] | python | en | ['en', 'error', 'th'] | False |
ParseResults.insert | (self, index, insStr) |
Inserts new element at location index in the list of parsed tokens.
Similar to ``list.insert()``.
Example::
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
# use a parse action to insert the parse location in the front of the parsed results
def insert_locn(locn, tokens):
tokens.insert(0, locn)
print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321']
|
Inserts new element at location index in the list of parsed tokens. | def insert(self, index, insStr):
"""
Inserts new element at location index in the list of parsed tokens.
Similar to ``list.insert()``.
Example::
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
# use a parse action to insert the parse location in the front of the parsed results
def insert_locn(locn, tokens):
tokens.insert(0, locn)
print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321']
"""
self.__toklist.insert(index, insStr)
# fixup indices in token dictionary
for name, occurrences in self.__tokdict.items():
for k, (value, position) in enumerate(occurrences):
occurrences[k] = _ParseResultsWithOffset(value, position + (position > index)) | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"insStr",
")",
":",
"self",
".",
"__toklist",
".",
"insert",
"(",
"index",
",",
"insStr",
")",
"# fixup indices in token dictionary",
"for",
"name",
",",
"occurrences",
"in",
"self",
".",
"__tokdict",
".",
"items",
"(",
")",
":",
"for",
"k",
",",
"(",
"value",
",",
"position",
")",
"in",
"enumerate",
"(",
"occurrences",
")",
":",
"occurrences",
"[",
"k",
"]",
"=",
"_ParseResultsWithOffset",
"(",
"value",
",",
"position",
"+",
"(",
"position",
">",
"index",
")",
")"
] | [
778,
4
] | [
797,
94
] | python | en | ['en', 'error', 'th'] | False |
ParseResults.append | (self, item) |
Add single element to end of ParseResults list of elements.
Example::
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
# use a parse action to compute the sum of the parsed integers, and add it to the end
def append_sum(tokens):
tokens.append(sum(map(int, tokens)))
print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444]
|
Add single element to end of ParseResults list of elements. | def append(self, item):
"""
Add single element to end of ParseResults list of elements.
Example::
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
# use a parse action to compute the sum of the parsed integers, and add it to the end
def append_sum(tokens):
tokens.append(sum(map(int, tokens)))
print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444]
"""
self.__toklist.append(item) | [
"def",
"append",
"(",
"self",
",",
"item",
")",
":",
"self",
".",
"__toklist",
".",
"append",
"(",
"item",
")"
] | [
799,
4
] | [
812,
35
] | python | en | ['en', 'error', 'th'] | False |
ParseResults.extend | (self, itemseq) |
Add sequence of elements to end of ParseResults list of elements.
Example::
patt = OneOrMore(Word(alphas))
# use a parse action to append the reverse of the matched strings, to make a palindrome
def make_palindrome(tokens):
tokens.extend(reversed([t[::-1] for t in tokens]))
return ''.join(tokens)
print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'
|
Add sequence of elements to end of ParseResults list of elements. | def extend(self, itemseq):
"""
Add sequence of elements to end of ParseResults list of elements.
Example::
patt = OneOrMore(Word(alphas))
# use a parse action to append the reverse of the matched strings, to make a palindrome
def make_palindrome(tokens):
tokens.extend(reversed([t[::-1] for t in tokens]))
return ''.join(tokens)
print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'
"""
if isinstance(itemseq, ParseResults):
self.__iadd__(itemseq)
else:
self.__toklist.extend(itemseq) | [
"def",
"extend",
"(",
"self",
",",
"itemseq",
")",
":",
"if",
"isinstance",
"(",
"itemseq",
",",
"ParseResults",
")",
":",
"self",
".",
"__iadd__",
"(",
"itemseq",
")",
"else",
":",
"self",
".",
"__toklist",
".",
"extend",
"(",
"itemseq",
")"
] | [
814,
4
] | [
831,
42
] | python | en | ['en', 'error', 'th'] | False |
ParseResults.clear | (self) |
Clear all elements and results names.
|
Clear all elements and results names.
| def clear(self):
"""
Clear all elements and results names.
"""
del self.__toklist[:]
self.__tokdict.clear() | [
"def",
"clear",
"(",
"self",
")",
":",
"del",
"self",
".",
"__toklist",
"[",
":",
"]",
"self",
".",
"__tokdict",
".",
"clear",
"(",
")"
] | [
833,
4
] | [
838,
30
] | python | en | ['en', 'error', 'th'] | False |
ParseResults.asList | (self) |
Returns the parse results as a nested list of matching tokens, all converted to strings.
Example::
patt = OneOrMore(Word(alphas))
result = patt.parseString("sldkj lsdkj sldkj")
# even though the result prints in string-like form, it is actually a pyparsing ParseResults
print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj']
# Use asList() to create an actual list
result_list = result.asList()
print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']
|
Returns the parse results as a nested list of matching tokens, all converted to strings. | def asList(self):
"""
Returns the parse results as a nested list of matching tokens, all converted to strings.
Example::
patt = OneOrMore(Word(alphas))
result = patt.parseString("sldkj lsdkj sldkj")
# even though the result prints in string-like form, it is actually a pyparsing ParseResults
print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj']
# Use asList() to create an actual list
result_list = result.asList()
print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']
"""
return [res.asList() if isinstance(res, ParseResults) else res for res in self.__toklist] | [
"def",
"asList",
"(",
"self",
")",
":",
"return",
"[",
"res",
".",
"asList",
"(",
")",
"if",
"isinstance",
"(",
"res",
",",
"ParseResults",
")",
"else",
"res",
"for",
"res",
"in",
"self",
".",
"__toklist",
"]"
] | [
892,
4
] | [
907,
97
] | python | en | ['en', 'error', 'th'] | False |
ParseResults.asDict | (self) |
Returns the named parse results as a nested dictionary.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString('12/31/1999')
print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})
result_dict = result.asDict()
print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}
# even though a ParseResults supports dict-like access, sometime you just need to have a dict
import json
print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable
print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"}
|
Returns the named parse results as a nested dictionary. | def asDict(self):
"""
Returns the named parse results as a nested dictionary.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString('12/31/1999')
print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})
result_dict = result.asDict()
print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}
# even though a ParseResults supports dict-like access, sometime you just need to have a dict
import json
print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable
print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"}
"""
if PY_3:
item_fn = self.items
else:
item_fn = self.iteritems
def toItem(obj):
if isinstance(obj, ParseResults):
if obj.haskeys():
return obj.asDict()
else:
return [toItem(v) for v in obj]
else:
return obj
return dict((k, toItem(v)) for k, v in item_fn()) | [
"def",
"asDict",
"(",
"self",
")",
":",
"if",
"PY_3",
":",
"item_fn",
"=",
"self",
".",
"items",
"else",
":",
"item_fn",
"=",
"self",
".",
"iteritems",
"def",
"toItem",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"ParseResults",
")",
":",
"if",
"obj",
".",
"haskeys",
"(",
")",
":",
"return",
"obj",
".",
"asDict",
"(",
")",
"else",
":",
"return",
"[",
"toItem",
"(",
"v",
")",
"for",
"v",
"in",
"obj",
"]",
"else",
":",
"return",
"obj",
"return",
"dict",
"(",
"(",
"k",
",",
"toItem",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"item_fn",
"(",
")",
")"
] | [
909,
4
] | [
943,
57
] | python | en | ['en', 'error', 'th'] | False |
ParseResults.copy | (self) |
Returns a new copy of a :class:`ParseResults` object.
|
Returns a new copy of a :class:`ParseResults` object.
| def copy(self):
"""
Returns a new copy of a :class:`ParseResults` object.
"""
ret = ParseResults(self.__toklist)
ret.__tokdict = dict(self.__tokdict.items())
ret.__parent = self.__parent
ret.__accumNames.update(self.__accumNames)
ret.__name = self.__name
return ret | [
"def",
"copy",
"(",
"self",
")",
":",
"ret",
"=",
"ParseResults",
"(",
"self",
".",
"__toklist",
")",
"ret",
".",
"__tokdict",
"=",
"dict",
"(",
"self",
".",
"__tokdict",
".",
"items",
"(",
")",
")",
"ret",
".",
"__parent",
"=",
"self",
".",
"__parent",
"ret",
".",
"__accumNames",
".",
"update",
"(",
"self",
".",
"__accumNames",
")",
"ret",
".",
"__name",
"=",
"self",
".",
"__name",
"return",
"ret"
] | [
945,
4
] | [
954,
18
] | python | en | ['en', 'error', 'th'] | False |
ParseResults.asXML | (self, doctag=None, namedItemsOnly=False, indent="", formatted=True) |
(Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.
|
(Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.
| def asXML(self, doctag=None, namedItemsOnly=False, indent="", formatted=True):
"""
(Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.
"""
nl = "\n"
out = []
namedItems = dict((v[1], k) for (k, vlist) in self.__tokdict.items()
for v in vlist)
nextLevelIndent = indent + " "
# collapse out indents if formatting is not desired
if not formatted:
indent = ""
nextLevelIndent = ""
nl = ""
selfTag = None
if doctag is not None:
selfTag = doctag
else:
if self.__name:
selfTag = self.__name
if not selfTag:
if namedItemsOnly:
return ""
else:
selfTag = "ITEM"
out += [nl, indent, "<", selfTag, ">"]
for i, res in enumerate(self.__toklist):
if isinstance(res, ParseResults):
if i in namedItems:
out += [res.asXML(namedItems[i],
namedItemsOnly and doctag is None,
nextLevelIndent,
formatted)]
else:
out += [res.asXML(None,
namedItemsOnly and doctag is None,
nextLevelIndent,
formatted)]
else:
# individual token, see if there is a name for it
resTag = None
if i in namedItems:
resTag = namedItems[i]
if not resTag:
if namedItemsOnly:
continue
else:
resTag = "ITEM"
xmlBodyText = _xml_escape(_ustr(res))
out += [nl, nextLevelIndent, "<", resTag, ">",
xmlBodyText,
"</", resTag, ">"]
out += [nl, indent, "</", selfTag, ">"]
return "".join(out) | [
"def",
"asXML",
"(",
"self",
",",
"doctag",
"=",
"None",
",",
"namedItemsOnly",
"=",
"False",
",",
"indent",
"=",
"\"\"",
",",
"formatted",
"=",
"True",
")",
":",
"nl",
"=",
"\"\\n\"",
"out",
"=",
"[",
"]",
"namedItems",
"=",
"dict",
"(",
"(",
"v",
"[",
"1",
"]",
",",
"k",
")",
"for",
"(",
"k",
",",
"vlist",
")",
"in",
"self",
".",
"__tokdict",
".",
"items",
"(",
")",
"for",
"v",
"in",
"vlist",
")",
"nextLevelIndent",
"=",
"indent",
"+",
"\" \"",
"# collapse out indents if formatting is not desired",
"if",
"not",
"formatted",
":",
"indent",
"=",
"\"\"",
"nextLevelIndent",
"=",
"\"\"",
"nl",
"=",
"\"\"",
"selfTag",
"=",
"None",
"if",
"doctag",
"is",
"not",
"None",
":",
"selfTag",
"=",
"doctag",
"else",
":",
"if",
"self",
".",
"__name",
":",
"selfTag",
"=",
"self",
".",
"__name",
"if",
"not",
"selfTag",
":",
"if",
"namedItemsOnly",
":",
"return",
"\"\"",
"else",
":",
"selfTag",
"=",
"\"ITEM\"",
"out",
"+=",
"[",
"nl",
",",
"indent",
",",
"\"<\"",
",",
"selfTag",
",",
"\">\"",
"]",
"for",
"i",
",",
"res",
"in",
"enumerate",
"(",
"self",
".",
"__toklist",
")",
":",
"if",
"isinstance",
"(",
"res",
",",
"ParseResults",
")",
":",
"if",
"i",
"in",
"namedItems",
":",
"out",
"+=",
"[",
"res",
".",
"asXML",
"(",
"namedItems",
"[",
"i",
"]",
",",
"namedItemsOnly",
"and",
"doctag",
"is",
"None",
",",
"nextLevelIndent",
",",
"formatted",
")",
"]",
"else",
":",
"out",
"+=",
"[",
"res",
".",
"asXML",
"(",
"None",
",",
"namedItemsOnly",
"and",
"doctag",
"is",
"None",
",",
"nextLevelIndent",
",",
"formatted",
")",
"]",
"else",
":",
"# individual token, see if there is a name for it",
"resTag",
"=",
"None",
"if",
"i",
"in",
"namedItems",
":",
"resTag",
"=",
"namedItems",
"[",
"i",
"]",
"if",
"not",
"resTag",
":",
"if",
"namedItemsOnly",
":",
"continue",
"else",
":",
"resTag",
"=",
"\"ITEM\"",
"xmlBodyText",
"=",
"_xml_escape",
"(",
"_ustr",
"(",
"res",
")",
")",
"out",
"+=",
"[",
"nl",
",",
"nextLevelIndent",
",",
"\"<\"",
",",
"resTag",
",",
"\">\"",
",",
"xmlBodyText",
",",
"\"</\"",
",",
"resTag",
",",
"\">\"",
"]",
"out",
"+=",
"[",
"nl",
",",
"indent",
",",
"\"</\"",
",",
"selfTag",
",",
"\">\"",
"]",
"return",
"\"\"",
".",
"join",
"(",
"out",
")"
] | [
956,
4
] | [
1015,
27
] | python | en | ['en', 'error', 'th'] | False |
ParseResults.getName | (self) | r"""
Returns the results name for this token expression. Useful when several
different expressions might match at a particular location.
Example::
integer = Word(nums)
ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d")
house_number_expr = Suppress('#') + Word(nums, alphanums)
user_data = (Group(house_number_expr)("house_number")
| Group(ssn_expr)("ssn")
| Group(integer)("age"))
user_info = OneOrMore(user_data)
result = user_info.parseString("22 111-22-3333 #221B")
for item in result:
print(item.getName(), ':', item[0])
prints::
age : 22
ssn : 111-22-3333
house_number : 221B
| r"""
Returns the results name for this token expression. Useful when several
different expressions might match at a particular location. | def getName(self):
r"""
Returns the results name for this token expression. Useful when several
different expressions might match at a particular location.
Example::
integer = Word(nums)
ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d")
house_number_expr = Suppress('#') + Word(nums, alphanums)
user_data = (Group(house_number_expr)("house_number")
| Group(ssn_expr)("ssn")
| Group(integer)("age"))
user_info = OneOrMore(user_data)
result = user_info.parseString("22 111-22-3333 #221B")
for item in result:
print(item.getName(), ':', item[0])
prints::
age : 22
ssn : 111-22-3333
house_number : 221B
"""
if self.__name:
return self.__name
elif self.__parent:
par = self.__parent()
if par:
return par.__lookup(self)
else:
return None
elif (len(self) == 1
and len(self.__tokdict) == 1
and next(iter(self.__tokdict.values()))[0][1] in (0, -1)):
return next(iter(self.__tokdict.keys()))
else:
return None | [
"def",
"getName",
"(",
"self",
")",
":",
"if",
"self",
".",
"__name",
":",
"return",
"self",
".",
"__name",
"elif",
"self",
".",
"__parent",
":",
"par",
"=",
"self",
".",
"__parent",
"(",
")",
"if",
"par",
":",
"return",
"par",
".",
"__lookup",
"(",
"self",
")",
"else",
":",
"return",
"None",
"elif",
"(",
"len",
"(",
"self",
")",
"==",
"1",
"and",
"len",
"(",
"self",
".",
"__tokdict",
")",
"==",
"1",
"and",
"next",
"(",
"iter",
"(",
"self",
".",
"__tokdict",
".",
"values",
"(",
")",
")",
")",
"[",
"0",
"]",
"[",
"1",
"]",
"in",
"(",
"0",
",",
"-",
"1",
")",
")",
":",
"return",
"next",
"(",
"iter",
"(",
"self",
".",
"__tokdict",
".",
"keys",
"(",
")",
")",
")",
"else",
":",
"return",
"None"
] | [
1024,
4
] | [
1062,
23
] | python | cy | ['en', 'cy', 'hi'] | False |
ParseResults.dump | (self, indent='', full=True, include_list=True, _depth=0) |
Diagnostic method for listing out the contents of
a :class:`ParseResults`. Accepts an optional ``indent`` argument so
that this string can be embedded in a nested display of other data.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString('12/31/1999')
print(result.dump())
prints::
['12', '/', '31', '/', '1999']
- day: 1999
- month: 31
- year: 12
|
Diagnostic method for listing out the contents of
a :class:`ParseResults`. Accepts an optional ``indent`` argument so
that this string can be embedded in a nested display of other data. | def dump(self, indent='', full=True, include_list=True, _depth=0):
"""
Diagnostic method for listing out the contents of
a :class:`ParseResults`. Accepts an optional ``indent`` argument so
that this string can be embedded in a nested display of other data.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString('12/31/1999')
print(result.dump())
prints::
['12', '/', '31', '/', '1999']
- day: 1999
- month: 31
- year: 12
"""
out = []
NL = '\n'
if include_list:
out.append(indent + _ustr(self.asList()))
else:
out.append('')
if full:
if self.haskeys():
items = sorted((str(k), v) for k, v in self.items())
for k, v in items:
if out:
out.append(NL)
out.append("%s%s- %s: " % (indent, (' ' * _depth), k))
if isinstance(v, ParseResults):
if v:
out.append(v.dump(indent=indent, full=full, include_list=include_list, _depth=_depth + 1))
else:
out.append(_ustr(v))
else:
out.append(repr(v))
elif any(isinstance(vv, ParseResults) for vv in self):
v = self
for i, vv in enumerate(v):
if isinstance(vv, ParseResults):
out.append("\n%s%s[%d]:\n%s%s%s" % (indent,
(' ' * (_depth)),
i,
indent,
(' ' * (_depth + 1)),
vv.dump(indent=indent,
full=full,
include_list=include_list,
_depth=_depth + 1)))
else:
out.append("\n%s%s[%d]:\n%s%s%s" % (indent,
(' ' * (_depth)),
i,
indent,
(' ' * (_depth + 1)),
_ustr(vv)))
return "".join(out) | [
"def",
"dump",
"(",
"self",
",",
"indent",
"=",
"''",
",",
"full",
"=",
"True",
",",
"include_list",
"=",
"True",
",",
"_depth",
"=",
"0",
")",
":",
"out",
"=",
"[",
"]",
"NL",
"=",
"'\\n'",
"if",
"include_list",
":",
"out",
".",
"append",
"(",
"indent",
"+",
"_ustr",
"(",
"self",
".",
"asList",
"(",
")",
")",
")",
"else",
":",
"out",
".",
"append",
"(",
"''",
")",
"if",
"full",
":",
"if",
"self",
".",
"haskeys",
"(",
")",
":",
"items",
"=",
"sorted",
"(",
"(",
"str",
"(",
"k",
")",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
")",
"for",
"k",
",",
"v",
"in",
"items",
":",
"if",
"out",
":",
"out",
".",
"append",
"(",
"NL",
")",
"out",
".",
"append",
"(",
"\"%s%s- %s: \"",
"%",
"(",
"indent",
",",
"(",
"' '",
"*",
"_depth",
")",
",",
"k",
")",
")",
"if",
"isinstance",
"(",
"v",
",",
"ParseResults",
")",
":",
"if",
"v",
":",
"out",
".",
"append",
"(",
"v",
".",
"dump",
"(",
"indent",
"=",
"indent",
",",
"full",
"=",
"full",
",",
"include_list",
"=",
"include_list",
",",
"_depth",
"=",
"_depth",
"+",
"1",
")",
")",
"else",
":",
"out",
".",
"append",
"(",
"_ustr",
"(",
"v",
")",
")",
"else",
":",
"out",
".",
"append",
"(",
"repr",
"(",
"v",
")",
")",
"elif",
"any",
"(",
"isinstance",
"(",
"vv",
",",
"ParseResults",
")",
"for",
"vv",
"in",
"self",
")",
":",
"v",
"=",
"self",
"for",
"i",
",",
"vv",
"in",
"enumerate",
"(",
"v",
")",
":",
"if",
"isinstance",
"(",
"vv",
",",
"ParseResults",
")",
":",
"out",
".",
"append",
"(",
"\"\\n%s%s[%d]:\\n%s%s%s\"",
"%",
"(",
"indent",
",",
"(",
"' '",
"*",
"(",
"_depth",
")",
")",
",",
"i",
",",
"indent",
",",
"(",
"' '",
"*",
"(",
"_depth",
"+",
"1",
")",
")",
",",
"vv",
".",
"dump",
"(",
"indent",
"=",
"indent",
",",
"full",
"=",
"full",
",",
"include_list",
"=",
"include_list",
",",
"_depth",
"=",
"_depth",
"+",
"1",
")",
")",
")",
"else",
":",
"out",
".",
"append",
"(",
"\"\\n%s%s[%d]:\\n%s%s%s\"",
"%",
"(",
"indent",
",",
"(",
"' '",
"*",
"(",
"_depth",
")",
")",
",",
"i",
",",
"indent",
",",
"(",
"' '",
"*",
"(",
"_depth",
"+",
"1",
")",
")",
",",
"_ustr",
"(",
"vv",
")",
")",
")",
"return",
"\"\"",
".",
"join",
"(",
"out",
")"
] | [
1064,
4
] | [
1127,
27
] | python | en | ['en', 'error', 'th'] | False |
ParseResults.pprint | (self, *args, **kwargs) |
Pretty-printer for parsed results as a list, using the
`pprint <https://docs.python.org/3/library/pprint.html>`_ module.
Accepts additional positional or keyword args as defined for
`pprint.pprint <https://docs.python.org/3/library/pprint.html#pprint.pprint>`_ .
Example::
ident = Word(alphas, alphanums)
num = Word(nums)
func = Forward()
term = ident | num | Group('(' + func + ')')
func <<= ident + Group(Optional(delimitedList(term)))
result = func.parseString("fna a,b,(fnb c,d,200),100")
result.pprint(width=40)
prints::
['fna',
['a',
'b',
['(', 'fnb', ['c', 'd', '200'], ')'],
'100']]
|
Pretty-printer for parsed results as a list, using the
`pprint <https://docs.python.org/3/library/pprint.html>`_ module.
Accepts additional positional or keyword args as defined for
`pprint.pprint <https://docs.python.org/3/library/pprint.html#pprint.pprint>`_ . | def pprint(self, *args, **kwargs):
"""
Pretty-printer for parsed results as a list, using the
`pprint <https://docs.python.org/3/library/pprint.html>`_ module.
Accepts additional positional or keyword args as defined for
`pprint.pprint <https://docs.python.org/3/library/pprint.html#pprint.pprint>`_ .
Example::
ident = Word(alphas, alphanums)
num = Word(nums)
func = Forward()
term = ident | num | Group('(' + func + ')')
func <<= ident + Group(Optional(delimitedList(term)))
result = func.parseString("fna a,b,(fnb c,d,200),100")
result.pprint(width=40)
prints::
['fna',
['a',
'b',
['(', 'fnb', ['c', 'd', '200'], ')'],
'100']]
"""
pprint.pprint(self.asList(), *args, **kwargs) | [
"def",
"pprint",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"pprint",
".",
"pprint",
"(",
"self",
".",
"asList",
"(",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
1129,
4
] | [
1154,
53
] | python | en | ['en', 'error', 'th'] | False |
ParseResults.from_dict | (cls, other, name=None) |
Helper classmethod to construct a ParseResults from a dict, preserving the
name-value relations as results names. If an optional 'name' argument is
given, a nested ParseResults will be returned
|
Helper classmethod to construct a ParseResults from a dict, preserving the
name-value relations as results names. If an optional 'name' argument is
given, a nested ParseResults will be returned
| def from_dict(cls, other, name=None):
"""
Helper classmethod to construct a ParseResults from a dict, preserving the
name-value relations as results names. If an optional 'name' argument is
given, a nested ParseResults will be returned
"""
def is_iterable(obj):
try:
iter(obj)
except Exception:
return False
else:
if PY_3:
return not isinstance(obj, (str, bytes))
else:
return not isinstance(obj, basestring)
ret = cls([])
for k, v in other.items():
if isinstance(v, Mapping):
ret += cls.from_dict(v, name=k)
else:
ret += cls([v], name=k, asList=is_iterable(v))
if name is not None:
ret = cls([ret], name=name)
return ret | [
"def",
"from_dict",
"(",
"cls",
",",
"other",
",",
"name",
"=",
"None",
")",
":",
"def",
"is_iterable",
"(",
"obj",
")",
":",
"try",
":",
"iter",
"(",
"obj",
")",
"except",
"Exception",
":",
"return",
"False",
"else",
":",
"if",
"PY_3",
":",
"return",
"not",
"isinstance",
"(",
"obj",
",",
"(",
"str",
",",
"bytes",
")",
")",
"else",
":",
"return",
"not",
"isinstance",
"(",
"obj",
",",
"basestring",
")",
"ret",
"=",
"cls",
"(",
"[",
"]",
")",
"for",
"k",
",",
"v",
"in",
"other",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"Mapping",
")",
":",
"ret",
"+=",
"cls",
".",
"from_dict",
"(",
"v",
",",
"name",
"=",
"k",
")",
"else",
":",
"ret",
"+=",
"cls",
"(",
"[",
"v",
"]",
",",
"name",
"=",
"k",
",",
"asList",
"=",
"is_iterable",
"(",
"v",
")",
")",
"if",
"name",
"is",
"not",
"None",
":",
"ret",
"=",
"cls",
"(",
"[",
"ret",
"]",
",",
"name",
"=",
"name",
")",
"return",
"ret"
] | [
1181,
4
] | [
1206,
18
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.setDefaultWhitespaceChars | (chars) | r"""
Overrides the default whitespace chars
Example::
# default whitespace chars are space, <TAB> and newline
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl']
# change to just treat newline as significant
ParserElement.setDefaultWhitespaceChars(" \t")
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def']
| r"""
Overrides the default whitespace chars | def setDefaultWhitespaceChars(chars):
r"""
Overrides the default whitespace chars
Example::
# default whitespace chars are space, <TAB> and newline
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl']
# change to just treat newline as significant
ParserElement.setDefaultWhitespaceChars(" \t")
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def']
"""
ParserElement.DEFAULT_WHITE_CHARS = chars | [
"def",
"setDefaultWhitespaceChars",
"(",
"chars",
")",
":",
"ParserElement",
".",
"DEFAULT_WHITE_CHARS",
"=",
"chars"
] | [
1356,
4
] | [
1369,
49
] | python | cy | ['en', 'cy', 'hi'] | False |
ParserElement.inlineLiteralsUsing | (cls) |
Set class to be used for inclusion of string literals into a parser.
Example::
# default literal class used is Literal
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31']
# change to Suppress
ParserElement.inlineLiteralsUsing(Suppress)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
date_str.parseString("1999/12/31") # -> ['1999', '12', '31']
|
Set class to be used for inclusion of string literals into a parser. | def inlineLiteralsUsing(cls):
"""
Set class to be used for inclusion of string literals into a parser.
Example::
# default literal class used is Literal
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31']
# change to Suppress
ParserElement.inlineLiteralsUsing(Suppress)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
date_str.parseString("1999/12/31") # -> ['1999', '12', '31']
"""
ParserElement._literalStringClass = cls | [
"def",
"inlineLiteralsUsing",
"(",
"cls",
")",
":",
"ParserElement",
".",
"_literalStringClass",
"=",
"cls"
] | [
1372,
4
] | [
1391,
47
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.copy | (self) |
Make a copy of this :class:`ParserElement`. Useful for defining
different parse actions for the same parsing pattern, using copies of
the original parse element.
Example::
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
integerK = integer.copy().addParseAction(lambda toks: toks[0] * 1024) + Suppress("K")
integerM = integer.copy().addParseAction(lambda toks: toks[0] * 1024 * 1024) + Suppress("M")
print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M"))
prints::
[5120, 100, 655360, 268435456]
Equivalent form of ``expr.copy()`` is just ``expr()``::
integerM = integer().addParseAction(lambda toks: toks[0] * 1024 * 1024) + Suppress("M")
|
Make a copy of this :class:`ParserElement`. Useful for defining
different parse actions for the same parsing pattern, using copies of
the original parse element. | def copy(self):
"""
Make a copy of this :class:`ParserElement`. Useful for defining
different parse actions for the same parsing pattern, using copies of
the original parse element.
Example::
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
integerK = integer.copy().addParseAction(lambda toks: toks[0] * 1024) + Suppress("K")
integerM = integer.copy().addParseAction(lambda toks: toks[0] * 1024 * 1024) + Suppress("M")
print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M"))
prints::
[5120, 100, 655360, 268435456]
Equivalent form of ``expr.copy()`` is just ``expr()``::
integerM = integer().addParseAction(lambda toks: toks[0] * 1024 * 1024) + Suppress("M")
"""
cpy = copy.copy(self)
cpy.parseAction = self.parseAction[:]
cpy.ignoreExprs = self.ignoreExprs[:]
if self.copyDefaultWhiteChars:
cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
return cpy | [
"def",
"copy",
"(",
"self",
")",
":",
"cpy",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"cpy",
".",
"parseAction",
"=",
"self",
".",
"parseAction",
"[",
":",
"]",
"cpy",
".",
"ignoreExprs",
"=",
"self",
".",
"ignoreExprs",
"[",
":",
"]",
"if",
"self",
".",
"copyDefaultWhiteChars",
":",
"cpy",
".",
"whiteChars",
"=",
"ParserElement",
".",
"DEFAULT_WHITE_CHARS",
"return",
"cpy"
] | [
1422,
4
] | [
1449,
18
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.setName | (self, name) |
Define name for this expression, makes debugging and exception messages clearer.
Example::
Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1)
Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1)
|
Define name for this expression, makes debugging and exception messages clearer. | def setName(self, name):
"""
Define name for this expression, makes debugging and exception messages clearer.
Example::
Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1)
Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1)
"""
self.name = name
self.errmsg = "Expected " + self.name
if __diag__.enable_debug_on_named_expressions:
self.setDebug()
return self | [
"def",
"setName",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"name",
"=",
"name",
"self",
".",
"errmsg",
"=",
"\"Expected \"",
"+",
"self",
".",
"name",
"if",
"__diag__",
".",
"enable_debug_on_named_expressions",
":",
"self",
".",
"setDebug",
"(",
")",
"return",
"self"
] | [
1451,
4
] | [
1464,
19
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.setResultsName | (self, name, listAllMatches=False) |
Define name for referencing matching tokens as a nested attribute
of the returned parse results.
NOTE: this returns a *copy* of the original :class:`ParserElement` object;
this is so that the client can define a basic element, such as an
integer, and reference it in multiple places with different names.
You can also set results names using the abbreviated syntax,
``expr("name")`` in place of ``expr.setResultsName("name")``
- see :class:`__call__`.
Example::
date_str = (integer.setResultsName("year") + '/'
+ integer.setResultsName("month") + '/'
+ integer.setResultsName("day"))
# equivalent form:
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
|
Define name for referencing matching tokens as a nested attribute
of the returned parse results.
NOTE: this returns a *copy* of the original :class:`ParserElement` object;
this is so that the client can define a basic element, such as an
integer, and reference it in multiple places with different names. | def setResultsName(self, name, listAllMatches=False):
"""
Define name for referencing matching tokens as a nested attribute
of the returned parse results.
NOTE: this returns a *copy* of the original :class:`ParserElement` object;
this is so that the client can define a basic element, such as an
integer, and reference it in multiple places with different names.
You can also set results names using the abbreviated syntax,
``expr("name")`` in place of ``expr.setResultsName("name")``
- see :class:`__call__`.
Example::
date_str = (integer.setResultsName("year") + '/'
+ integer.setResultsName("month") + '/'
+ integer.setResultsName("day"))
# equivalent form:
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
"""
return self._setResultsName(name, listAllMatches) | [
"def",
"setResultsName",
"(",
"self",
",",
"name",
",",
"listAllMatches",
"=",
"False",
")",
":",
"return",
"self",
".",
"_setResultsName",
"(",
"name",
",",
"listAllMatches",
")"
] | [
1466,
4
] | [
1487,
57
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.setBreak | (self, breakFlag=True) | Method to invoke the Python pdb debugger when this element is
about to be parsed. Set ``breakFlag`` to True to enable, False to
disable.
| Method to invoke the Python pdb debugger when this element is
about to be parsed. Set ``breakFlag`` to True to enable, False to
disable.
| def setBreak(self, breakFlag=True):
"""Method to invoke the Python pdb debugger when this element is
about to be parsed. Set ``breakFlag`` to True to enable, False to
disable.
"""
if breakFlag:
_parseMethod = self._parse
def breaker(instring, loc, doActions=True, callPreParse=True):
import pdb
# this call to pdb.set_trace() is intentional, not a checkin error
pdb.set_trace()
return _parseMethod(instring, loc, doActions, callPreParse)
breaker._originalParseMethod = _parseMethod
self._parse = breaker
else:
if hasattr(self._parse, "_originalParseMethod"):
self._parse = self._parse._originalParseMethod
return self | [
"def",
"setBreak",
"(",
"self",
",",
"breakFlag",
"=",
"True",
")",
":",
"if",
"breakFlag",
":",
"_parseMethod",
"=",
"self",
".",
"_parse",
"def",
"breaker",
"(",
"instring",
",",
"loc",
",",
"doActions",
"=",
"True",
",",
"callPreParse",
"=",
"True",
")",
":",
"import",
"pdb",
"# this call to pdb.set_trace() is intentional, not a checkin error",
"pdb",
".",
"set_trace",
"(",
")",
"return",
"_parseMethod",
"(",
"instring",
",",
"loc",
",",
"doActions",
",",
"callPreParse",
")",
"breaker",
".",
"_originalParseMethod",
"=",
"_parseMethod",
"self",
".",
"_parse",
"=",
"breaker",
"else",
":",
"if",
"hasattr",
"(",
"self",
".",
"_parse",
",",
"\"_originalParseMethod\"",
")",
":",
"self",
".",
"_parse",
"=",
"self",
".",
"_parse",
".",
"_originalParseMethod",
"return",
"self"
] | [
1498,
4
] | [
1515,
19
] | python | en | ['en', 'en', 'en'] | True |
ParserElement.setParseAction | (self, *fns, **kwargs) |
Define one or more actions to perform when successfully matching parse element definition.
Parse action fn is a callable method with 0-3 arguments, called as ``fn(s, loc, toks)`` ,
``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where:
- s = the original string being parsed (see note below)
- loc = the location of the matching substring
- toks = a list of the matched tokens, packaged as a :class:`ParseResults` object
If the functions in fns modify the tokens, they can return them as the return
value from fn, and the modified list of tokens will replace the original.
Otherwise, fn does not need to return any value.
If None is passed as the parse action, all previously added parse actions for this
expression are cleared.
Optional keyword arguments:
- callDuringTry = (default= ``False``) indicate if parse action should be run during lookaheads and alternate testing
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See :class:`parseString for more
information on parsing strings containing ``<TAB>`` s, and suggested
methods to maintain a consistent view of the parsed string, the parse
location, and line and column positions within the parsed string.
Example::
integer = Word(nums)
date_str = integer + '/' + integer + '/' + integer
date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31']
# use parse action to convert to ints at parse time
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
date_str = integer + '/' + integer + '/' + integer
# note that integer fields are now ints, not strings
date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31]
|
Define one or more actions to perform when successfully matching parse element definition.
Parse action fn is a callable method with 0-3 arguments, called as ``fn(s, loc, toks)`` ,
``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where: | def setParseAction(self, *fns, **kwargs):
"""
Define one or more actions to perform when successfully matching parse element definition.
Parse action fn is a callable method with 0-3 arguments, called as ``fn(s, loc, toks)`` ,
``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where:
- s = the original string being parsed (see note below)
- loc = the location of the matching substring
- toks = a list of the matched tokens, packaged as a :class:`ParseResults` object
If the functions in fns modify the tokens, they can return them as the return
value from fn, and the modified list of tokens will replace the original.
Otherwise, fn does not need to return any value.
If None is passed as the parse action, all previously added parse actions for this
expression are cleared.
Optional keyword arguments:
- callDuringTry = (default= ``False``) indicate if parse action should be run during lookaheads and alternate testing
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See :class:`parseString for more
information on parsing strings containing ``<TAB>`` s, and suggested
methods to maintain a consistent view of the parsed string, the parse
location, and line and column positions within the parsed string.
Example::
integer = Word(nums)
date_str = integer + '/' + integer + '/' + integer
date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31']
# use parse action to convert to ints at parse time
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
date_str = integer + '/' + integer + '/' + integer
# note that integer fields are now ints, not strings
date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31]
"""
if list(fns) == [None,]:
self.parseAction = []
else:
if not all(callable(fn) for fn in fns):
raise TypeError("parse actions must be callable")
self.parseAction = list(map(_trim_arity, list(fns)))
self.callDuringTry = kwargs.get("callDuringTry", False)
return self | [
"def",
"setParseAction",
"(",
"self",
",",
"*",
"fns",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"list",
"(",
"fns",
")",
"==",
"[",
"None",
",",
"]",
":",
"self",
".",
"parseAction",
"=",
"[",
"]",
"else",
":",
"if",
"not",
"all",
"(",
"callable",
"(",
"fn",
")",
"for",
"fn",
"in",
"fns",
")",
":",
"raise",
"TypeError",
"(",
"\"parse actions must be callable\"",
")",
"self",
".",
"parseAction",
"=",
"list",
"(",
"map",
"(",
"_trim_arity",
",",
"list",
"(",
"fns",
")",
")",
")",
"self",
".",
"callDuringTry",
"=",
"kwargs",
".",
"get",
"(",
"\"callDuringTry\"",
",",
"False",
")",
"return",
"self"
] | [
1517,
4
] | [
1564,
19
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.addParseAction | (self, *fns, **kwargs) |
Add one or more parse actions to expression's list of parse actions. See :class:`setParseAction`.
See examples in :class:`copy`.
|
Add one or more parse actions to expression's list of parse actions. See :class:`setParseAction`. | def addParseAction(self, *fns, **kwargs):
"""
Add one or more parse actions to expression's list of parse actions. See :class:`setParseAction`.
See examples in :class:`copy`.
"""
self.parseAction += list(map(_trim_arity, list(fns)))
self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False)
return self | [
"def",
"addParseAction",
"(",
"self",
",",
"*",
"fns",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"parseAction",
"+=",
"list",
"(",
"map",
"(",
"_trim_arity",
",",
"list",
"(",
"fns",
")",
")",
")",
"self",
".",
"callDuringTry",
"=",
"self",
".",
"callDuringTry",
"or",
"kwargs",
".",
"get",
"(",
"\"callDuringTry\"",
",",
"False",
")",
"return",
"self"
] | [
1566,
4
] | [
1574,
19
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.addCondition | (self, *fns, **kwargs) | Add a boolean predicate function to expression's list of parse actions. See
:class:`setParseAction` for function call signatures. Unlike ``setParseAction``,
functions passed to ``addCondition`` need to return boolean success/fail of the condition.
Optional keyword arguments:
- message = define a custom message to be used in the raised exception
- fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException
Example::
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
year_int = integer.copy()
year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later")
date_str = year_int + '/' + integer + '/' + integer
result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1)
| Add a boolean predicate function to expression's list of parse actions. See
:class:`setParseAction` for function call signatures. Unlike ``setParseAction``,
functions passed to ``addCondition`` need to return boolean success/fail of the condition. | def addCondition(self, *fns, **kwargs):
"""Add a boolean predicate function to expression's list of parse actions. See
:class:`setParseAction` for function call signatures. Unlike ``setParseAction``,
functions passed to ``addCondition`` need to return boolean success/fail of the condition.
Optional keyword arguments:
- message = define a custom message to be used in the raised exception
- fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException
Example::
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
year_int = integer.copy()
year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later")
date_str = year_int + '/' + integer + '/' + integer
result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1)
"""
for fn in fns:
self.parseAction.append(conditionAsParseAction(fn, message=kwargs.get('message'),
fatal=kwargs.get('fatal', False)))
self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False)
return self | [
"def",
"addCondition",
"(",
"self",
",",
"*",
"fns",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"fn",
"in",
"fns",
":",
"self",
".",
"parseAction",
".",
"append",
"(",
"conditionAsParseAction",
"(",
"fn",
",",
"message",
"=",
"kwargs",
".",
"get",
"(",
"'message'",
")",
",",
"fatal",
"=",
"kwargs",
".",
"get",
"(",
"'fatal'",
",",
"False",
")",
")",
")",
"self",
".",
"callDuringTry",
"=",
"self",
".",
"callDuringTry",
"or",
"kwargs",
".",
"get",
"(",
"\"callDuringTry\"",
",",
"False",
")",
"return",
"self"
] | [
1576,
4
] | [
1599,
19
] | python | en | ['en', 'en', 'en'] | True |
ParserElement.setFailAction | (self, fn) | Define action to perform if parsing fails at this expression.
Fail acton fn is a callable function that takes the arguments
``fn(s, loc, expr, err)`` where:
- s = string being parsed
- loc = location where expression match was attempted and failed
- expr = the parse expression that failed
- err = the exception thrown
The function returns no value. It may throw :class:`ParseFatalException`
if it is desired to stop parsing immediately. | Define action to perform if parsing fails at this expression.
Fail acton fn is a callable function that takes the arguments
``fn(s, loc, expr, err)`` where:
- s = string being parsed
- loc = location where expression match was attempted and failed
- expr = the parse expression that failed
- err = the exception thrown
The function returns no value. It may throw :class:`ParseFatalException`
if it is desired to stop parsing immediately. | def setFailAction(self, fn):
"""Define action to perform if parsing fails at this expression.
Fail acton fn is a callable function that takes the arguments
``fn(s, loc, expr, err)`` where:
- s = string being parsed
- loc = location where expression match was attempted and failed
- expr = the parse expression that failed
- err = the exception thrown
The function returns no value. It may throw :class:`ParseFatalException`
if it is desired to stop parsing immediately."""
self.failAction = fn
return self | [
"def",
"setFailAction",
"(",
"self",
",",
"fn",
")",
":",
"self",
".",
"failAction",
"=",
"fn",
"return",
"self"
] | [
1601,
4
] | [
1612,
19
] | python | en | ['en', 'en', 'en'] | True |
ParserElement.enablePackrat | (cache_size_limit=128) | Enables "packrat" parsing, which adds memoizing to the parsing logic.
Repeated parse attempts at the same string location (which happens
often in many complex grammars) can immediately return a cached value,
instead of re-executing parsing/validating code. Memoizing is done of
both valid results and parsing exceptions.
Parameters:
- cache_size_limit - (default= ``128``) - if an integer value is provided
will limit the size of the packrat cache; if None is passed, then
the cache size will be unbounded; if 0 is passed, the cache will
be effectively disabled.
This speedup may break existing programs that use parse actions that
have side-effects. For this reason, packrat parsing is disabled when
you first import pyparsing. To activate the packrat feature, your
program must call the class method :class:`ParserElement.enablePackrat`.
For best results, call ``enablePackrat()`` immediately after
importing pyparsing.
Example::
from pip._vendor import pyparsing
pyparsing.ParserElement.enablePackrat()
| Enables "packrat" parsing, which adds memoizing to the parsing logic.
Repeated parse attempts at the same string location (which happens
often in many complex grammars) can immediately return a cached value,
instead of re-executing parsing/validating code. Memoizing is done of
both valid results and parsing exceptions. | def enablePackrat(cache_size_limit=128):
"""Enables "packrat" parsing, which adds memoizing to the parsing logic.
Repeated parse attempts at the same string location (which happens
often in many complex grammars) can immediately return a cached value,
instead of re-executing parsing/validating code. Memoizing is done of
both valid results and parsing exceptions.
Parameters:
- cache_size_limit - (default= ``128``) - if an integer value is provided
will limit the size of the packrat cache; if None is passed, then
the cache size will be unbounded; if 0 is passed, the cache will
be effectively disabled.
This speedup may break existing programs that use parse actions that
have side-effects. For this reason, packrat parsing is disabled when
you first import pyparsing. To activate the packrat feature, your
program must call the class method :class:`ParserElement.enablePackrat`.
For best results, call ``enablePackrat()`` immediately after
importing pyparsing.
Example::
from pip._vendor import pyparsing
pyparsing.ParserElement.enablePackrat()
"""
if not ParserElement._packratEnabled:
ParserElement._packratEnabled = True
if cache_size_limit is None:
ParserElement.packrat_cache = ParserElement._UnboundedCache()
else:
ParserElement.packrat_cache = ParserElement._FifoCache(cache_size_limit)
ParserElement._parse = ParserElement._parseCache | [
"def",
"enablePackrat",
"(",
"cache_size_limit",
"=",
"128",
")",
":",
"if",
"not",
"ParserElement",
".",
"_packratEnabled",
":",
"ParserElement",
".",
"_packratEnabled",
"=",
"True",
"if",
"cache_size_limit",
"is",
"None",
":",
"ParserElement",
".",
"packrat_cache",
"=",
"ParserElement",
".",
"_UnboundedCache",
"(",
")",
"else",
":",
"ParserElement",
".",
"packrat_cache",
"=",
"ParserElement",
".",
"_FifoCache",
"(",
"cache_size_limit",
")",
"ParserElement",
".",
"_parse",
"=",
"ParserElement",
".",
"_parseCache"
] | [
1866,
4
] | [
1898,
60
] | python | en | ['en', 'en', 'en'] | True |
ParserElement.parseString | (self, instring, parseAll=False) |
Execute the parse expression with the given string.
This is the main interface to the client code, once the complete
expression has been built.
Returns the parsed data as a :class:`ParseResults` object, which may be
accessed as a list, or as a dict or object with attributes if the given parser
includes results names.
If you want the grammar to require that the entire input string be
successfully parsed, then set ``parseAll`` to True (equivalent to ending
the grammar with ``StringEnd()``).
Note: ``parseString`` implicitly calls ``expandtabs()`` on the input string,
in order to report proper column numbers in parse actions.
If the input string contains tabs and
the grammar uses parse actions that use the ``loc`` argument to index into the
string being parsed, you can ensure you have a consistent view of the input
string by:
- calling ``parseWithTabs`` on your grammar before calling ``parseString``
(see :class:`parseWithTabs`)
- define your parse action using the full ``(s, loc, toks)`` signature, and
reference the input string using the parse action's ``s`` argument
- explictly expand the tabs in your input string before calling
``parseString``
Example::
Word('a').parseString('aaaaabaaa') # -> ['aaaaa']
Word('a').parseString('aaaaabaaa', parseAll=True) # -> Exception: Expected end of text
|
Execute the parse expression with the given string.
This is the main interface to the client code, once the complete
expression has been built. | def parseString(self, instring, parseAll=False):
"""
Execute the parse expression with the given string.
This is the main interface to the client code, once the complete
expression has been built.
Returns the parsed data as a :class:`ParseResults` object, which may be
accessed as a list, or as a dict or object with attributes if the given parser
includes results names.
If you want the grammar to require that the entire input string be
successfully parsed, then set ``parseAll`` to True (equivalent to ending
the grammar with ``StringEnd()``).
Note: ``parseString`` implicitly calls ``expandtabs()`` on the input string,
in order to report proper column numbers in parse actions.
If the input string contains tabs and
the grammar uses parse actions that use the ``loc`` argument to index into the
string being parsed, you can ensure you have a consistent view of the input
string by:
- calling ``parseWithTabs`` on your grammar before calling ``parseString``
(see :class:`parseWithTabs`)
- define your parse action using the full ``(s, loc, toks)`` signature, and
reference the input string using the parse action's ``s`` argument
- explictly expand the tabs in your input string before calling
``parseString``
Example::
Word('a').parseString('aaaaabaaa') # -> ['aaaaa']
Word('a').parseString('aaaaabaaa', parseAll=True) # -> Exception: Expected end of text
"""
ParserElement.resetCache()
if not self.streamlined:
self.streamline()
# ~ self.saveAsList = True
for e in self.ignoreExprs:
e.streamline()
if not self.keepTabs:
instring = instring.expandtabs()
try:
loc, tokens = self._parse(instring, 0)
if parseAll:
loc = self.preParse(instring, loc)
se = Empty() + StringEnd()
se._parse(instring, loc)
except ParseBaseException as exc:
if ParserElement.verbose_stacktrace:
raise
else:
# catch and re-raise exception from here, clearing out pyparsing internal stack trace
if getattr(exc, '__traceback__', None) is not None:
exc.__traceback__ = self._trim_traceback(exc.__traceback__)
raise exc
else:
return tokens | [
"def",
"parseString",
"(",
"self",
",",
"instring",
",",
"parseAll",
"=",
"False",
")",
":",
"ParserElement",
".",
"resetCache",
"(",
")",
"if",
"not",
"self",
".",
"streamlined",
":",
"self",
".",
"streamline",
"(",
")",
"# ~ self.saveAsList = True",
"for",
"e",
"in",
"self",
".",
"ignoreExprs",
":",
"e",
".",
"streamline",
"(",
")",
"if",
"not",
"self",
".",
"keepTabs",
":",
"instring",
"=",
"instring",
".",
"expandtabs",
"(",
")",
"try",
":",
"loc",
",",
"tokens",
"=",
"self",
".",
"_parse",
"(",
"instring",
",",
"0",
")",
"if",
"parseAll",
":",
"loc",
"=",
"self",
".",
"preParse",
"(",
"instring",
",",
"loc",
")",
"se",
"=",
"Empty",
"(",
")",
"+",
"StringEnd",
"(",
")",
"se",
".",
"_parse",
"(",
"instring",
",",
"loc",
")",
"except",
"ParseBaseException",
"as",
"exc",
":",
"if",
"ParserElement",
".",
"verbose_stacktrace",
":",
"raise",
"else",
":",
"# catch and re-raise exception from here, clearing out pyparsing internal stack trace",
"if",
"getattr",
"(",
"exc",
",",
"'__traceback__'",
",",
"None",
")",
"is",
"not",
"None",
":",
"exc",
".",
"__traceback__",
"=",
"self",
".",
"_trim_traceback",
"(",
"exc",
".",
"__traceback__",
")",
"raise",
"exc",
"else",
":",
"return",
"tokens"
] | [
1900,
4
] | [
1956,
25
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.scanString | (self, instring, maxMatches=_MAX_INT, overlap=False) |
Scan the input string for expression matches. Each match will return the
matching tokens, start location, and end location. May be called with optional
``maxMatches`` argument, to clip scanning after 'n' matches are found. If
``overlap`` is specified, then overlapping matches will be reported.
Note that the start and end locations are reported relative to the string
being parsed. See :class:`parseString` for more information on parsing
strings with embedded tabs.
Example::
source = "sldjf123lsdjjkf345sldkjf879lkjsfd987"
print(source)
for tokens, start, end in Word(alphas).scanString(source):
print(' '*start + '^'*(end-start))
print(' '*start + tokens[0])
prints::
sldjf123lsdjjkf345sldkjf879lkjsfd987
^^^^^
sldjf
^^^^^^^
lsdjjkf
^^^^^^
sldkjf
^^^^^^
lkjsfd
|
Scan the input string for expression matches. Each match will return the
matching tokens, start location, and end location. May be called with optional
``maxMatches`` argument, to clip scanning after 'n' matches are found. If
``overlap`` is specified, then overlapping matches will be reported. | def scanString(self, instring, maxMatches=_MAX_INT, overlap=False):
"""
Scan the input string for expression matches. Each match will return the
matching tokens, start location, and end location. May be called with optional
``maxMatches`` argument, to clip scanning after 'n' matches are found. If
``overlap`` is specified, then overlapping matches will be reported.
Note that the start and end locations are reported relative to the string
being parsed. See :class:`parseString` for more information on parsing
strings with embedded tabs.
Example::
source = "sldjf123lsdjjkf345sldkjf879lkjsfd987"
print(source)
for tokens, start, end in Word(alphas).scanString(source):
print(' '*start + '^'*(end-start))
print(' '*start + tokens[0])
prints::
sldjf123lsdjjkf345sldkjf879lkjsfd987
^^^^^
sldjf
^^^^^^^
lsdjjkf
^^^^^^
sldkjf
^^^^^^
lkjsfd
"""
if not self.streamlined:
self.streamline()
for e in self.ignoreExprs:
e.streamline()
if not self.keepTabs:
instring = _ustr(instring).expandtabs()
instrlen = len(instring)
loc = 0
preparseFn = self.preParse
parseFn = self._parse
ParserElement.resetCache()
matches = 0
try:
while loc <= instrlen and matches < maxMatches:
try:
preloc = preparseFn(instring, loc)
nextLoc, tokens = parseFn(instring, preloc, callPreParse=False)
except ParseException:
loc = preloc + 1
else:
if nextLoc > loc:
matches += 1
yield tokens, preloc, nextLoc
if overlap:
nextloc = preparseFn(instring, loc)
if nextloc > loc:
loc = nextLoc
else:
loc += 1
else:
loc = nextLoc
else:
loc = preloc + 1
except ParseBaseException as exc:
if ParserElement.verbose_stacktrace:
raise
else:
# catch and re-raise exception from here, clearing out pyparsing internal stack trace
if getattr(exc, '__traceback__', None) is not None:
exc.__traceback__ = self._trim_traceback(exc.__traceback__)
raise exc | [
"def",
"scanString",
"(",
"self",
",",
"instring",
",",
"maxMatches",
"=",
"_MAX_INT",
",",
"overlap",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"streamlined",
":",
"self",
".",
"streamline",
"(",
")",
"for",
"e",
"in",
"self",
".",
"ignoreExprs",
":",
"e",
".",
"streamline",
"(",
")",
"if",
"not",
"self",
".",
"keepTabs",
":",
"instring",
"=",
"_ustr",
"(",
"instring",
")",
".",
"expandtabs",
"(",
")",
"instrlen",
"=",
"len",
"(",
"instring",
")",
"loc",
"=",
"0",
"preparseFn",
"=",
"self",
".",
"preParse",
"parseFn",
"=",
"self",
".",
"_parse",
"ParserElement",
".",
"resetCache",
"(",
")",
"matches",
"=",
"0",
"try",
":",
"while",
"loc",
"<=",
"instrlen",
"and",
"matches",
"<",
"maxMatches",
":",
"try",
":",
"preloc",
"=",
"preparseFn",
"(",
"instring",
",",
"loc",
")",
"nextLoc",
",",
"tokens",
"=",
"parseFn",
"(",
"instring",
",",
"preloc",
",",
"callPreParse",
"=",
"False",
")",
"except",
"ParseException",
":",
"loc",
"=",
"preloc",
"+",
"1",
"else",
":",
"if",
"nextLoc",
">",
"loc",
":",
"matches",
"+=",
"1",
"yield",
"tokens",
",",
"preloc",
",",
"nextLoc",
"if",
"overlap",
":",
"nextloc",
"=",
"preparseFn",
"(",
"instring",
",",
"loc",
")",
"if",
"nextloc",
">",
"loc",
":",
"loc",
"=",
"nextLoc",
"else",
":",
"loc",
"+=",
"1",
"else",
":",
"loc",
"=",
"nextLoc",
"else",
":",
"loc",
"=",
"preloc",
"+",
"1",
"except",
"ParseBaseException",
"as",
"exc",
":",
"if",
"ParserElement",
".",
"verbose_stacktrace",
":",
"raise",
"else",
":",
"# catch and re-raise exception from here, clearing out pyparsing internal stack trace",
"if",
"getattr",
"(",
"exc",
",",
"'__traceback__'",
",",
"None",
")",
"is",
"not",
"None",
":",
"exc",
".",
"__traceback__",
"=",
"self",
".",
"_trim_traceback",
"(",
"exc",
".",
"__traceback__",
")",
"raise",
"exc"
] | [
1958,
4
] | [
2030,
25
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.transformString | (self, instring) |
Extension to :class:`scanString`, to modify matching text with modified tokens that may
be returned from a parse action. To use ``transformString``, define a grammar and
attach a parse action to it that modifies the returned token list.
Invoking ``transformString()`` on a target string will then scan for matches,
and replace the matched text patterns according to the logic in the parse
action. ``transformString()`` returns the resulting transformed string.
Example::
wd = Word(alphas)
wd.setParseAction(lambda toks: toks[0].title())
print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york."))
prints::
Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
|
Extension to :class:`scanString`, to modify matching text with modified tokens that may
be returned from a parse action. To use ``transformString``, define a grammar and
attach a parse action to it that modifies the returned token list.
Invoking ``transformString()`` on a target string will then scan for matches,
and replace the matched text patterns according to the logic in the parse
action. ``transformString()`` returns the resulting transformed string. | def transformString(self, instring):
"""
Extension to :class:`scanString`, to modify matching text with modified tokens that may
be returned from a parse action. To use ``transformString``, define a grammar and
attach a parse action to it that modifies the returned token list.
Invoking ``transformString()`` on a target string will then scan for matches,
and replace the matched text patterns according to the logic in the parse
action. ``transformString()`` returns the resulting transformed string.
Example::
wd = Word(alphas)
wd.setParseAction(lambda toks: toks[0].title())
print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york."))
prints::
Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
"""
out = []
lastE = 0
# force preservation of <TAB>s, to minimize unwanted transformation of string, and to
# keep string locs straight between transformString and scanString
self.keepTabs = True
try:
for t, s, e in self.scanString(instring):
out.append(instring[lastE:s])
if t:
if isinstance(t, ParseResults):
out += t.asList()
elif isinstance(t, list):
out += t
else:
out.append(t)
lastE = e
out.append(instring[lastE:])
out = [o for o in out if o]
return "".join(map(_ustr, _flatten(out)))
except ParseBaseException as exc:
if ParserElement.verbose_stacktrace:
raise
else:
# catch and re-raise exception from here, clearing out pyparsing internal stack trace
if getattr(exc, '__traceback__', None) is not None:
exc.__traceback__ = self._trim_traceback(exc.__traceback__)
raise exc | [
"def",
"transformString",
"(",
"self",
",",
"instring",
")",
":",
"out",
"=",
"[",
"]",
"lastE",
"=",
"0",
"# force preservation of <TAB>s, to minimize unwanted transformation of string, and to",
"# keep string locs straight between transformString and scanString",
"self",
".",
"keepTabs",
"=",
"True",
"try",
":",
"for",
"t",
",",
"s",
",",
"e",
"in",
"self",
".",
"scanString",
"(",
"instring",
")",
":",
"out",
".",
"append",
"(",
"instring",
"[",
"lastE",
":",
"s",
"]",
")",
"if",
"t",
":",
"if",
"isinstance",
"(",
"t",
",",
"ParseResults",
")",
":",
"out",
"+=",
"t",
".",
"asList",
"(",
")",
"elif",
"isinstance",
"(",
"t",
",",
"list",
")",
":",
"out",
"+=",
"t",
"else",
":",
"out",
".",
"append",
"(",
"t",
")",
"lastE",
"=",
"e",
"out",
".",
"append",
"(",
"instring",
"[",
"lastE",
":",
"]",
")",
"out",
"=",
"[",
"o",
"for",
"o",
"in",
"out",
"if",
"o",
"]",
"return",
"\"\"",
".",
"join",
"(",
"map",
"(",
"_ustr",
",",
"_flatten",
"(",
"out",
")",
")",
")",
"except",
"ParseBaseException",
"as",
"exc",
":",
"if",
"ParserElement",
".",
"verbose_stacktrace",
":",
"raise",
"else",
":",
"# catch and re-raise exception from here, clearing out pyparsing internal stack trace",
"if",
"getattr",
"(",
"exc",
",",
"'__traceback__'",
",",
"None",
")",
"is",
"not",
"None",
":",
"exc",
".",
"__traceback__",
"=",
"self",
".",
"_trim_traceback",
"(",
"exc",
".",
"__traceback__",
")",
"raise",
"exc"
] | [
2032,
4
] | [
2078,
25
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.searchString | (self, instring, maxMatches=_MAX_INT) |
Another extension to :class:`scanString`, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
``maxMatches`` argument, to clip searching after 'n' matches are found.
Example::
# a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters
cap_word = Word(alphas.upper(), alphas.lower())
print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity"))
# the sum() builtin can be used to merge results into a single ParseResults object
print(sum(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity")))
prints::
[['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']]
['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity']
|
Another extension to :class:`scanString`, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
``maxMatches`` argument, to clip searching after 'n' matches are found. | def searchString(self, instring, maxMatches=_MAX_INT):
"""
Another extension to :class:`scanString`, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
``maxMatches`` argument, to clip searching after 'n' matches are found.
Example::
# a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters
cap_word = Word(alphas.upper(), alphas.lower())
print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity"))
# the sum() builtin can be used to merge results into a single ParseResults object
print(sum(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity")))
prints::
[['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']]
['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity']
"""
try:
return ParseResults([t for t, s, e in self.scanString(instring, maxMatches)])
except ParseBaseException as exc:
if ParserElement.verbose_stacktrace:
raise
else:
# catch and re-raise exception from here, clearing out pyparsing internal stack trace
if getattr(exc, '__traceback__', None) is not None:
exc.__traceback__ = self._trim_traceback(exc.__traceback__)
raise exc | [
"def",
"searchString",
"(",
"self",
",",
"instring",
",",
"maxMatches",
"=",
"_MAX_INT",
")",
":",
"try",
":",
"return",
"ParseResults",
"(",
"[",
"t",
"for",
"t",
",",
"s",
",",
"e",
"in",
"self",
".",
"scanString",
"(",
"instring",
",",
"maxMatches",
")",
"]",
")",
"except",
"ParseBaseException",
"as",
"exc",
":",
"if",
"ParserElement",
".",
"verbose_stacktrace",
":",
"raise",
"else",
":",
"# catch and re-raise exception from here, clearing out pyparsing internal stack trace",
"if",
"getattr",
"(",
"exc",
",",
"'__traceback__'",
",",
"None",
")",
"is",
"not",
"None",
":",
"exc",
".",
"__traceback__",
"=",
"self",
".",
"_trim_traceback",
"(",
"exc",
".",
"__traceback__",
")",
"raise",
"exc"
] | [
2080,
4
] | [
2110,
25
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.split | (self, instring, maxsplit=_MAX_INT, includeSeparators=False) |
Generator method to split a string using the given expression as a separator.
May be called with optional ``maxsplit`` argument, to limit the number of splits;
and the optional ``includeSeparators`` argument (default= ``False``), if the separating
matching text should be included in the split results.
Example::
punc = oneOf(list(".,;:/-!?"))
print(list(punc.split("This, this?, this sentence, is badly punctuated!")))
prints::
['This', ' this', '', ' this sentence', ' is badly punctuated', '']
|
Generator method to split a string using the given expression as a separator.
May be called with optional ``maxsplit`` argument, to limit the number of splits;
and the optional ``includeSeparators`` argument (default= ``False``), if the separating
matching text should be included in the split results. | def split(self, instring, maxsplit=_MAX_INT, includeSeparators=False):
"""
Generator method to split a string using the given expression as a separator.
May be called with optional ``maxsplit`` argument, to limit the number of splits;
and the optional ``includeSeparators`` argument (default= ``False``), if the separating
matching text should be included in the split results.
Example::
punc = oneOf(list(".,;:/-!?"))
print(list(punc.split("This, this?, this sentence, is badly punctuated!")))
prints::
['This', ' this', '', ' this sentence', ' is badly punctuated', '']
"""
splits = 0
last = 0
for t, s, e in self.scanString(instring, maxMatches=maxsplit):
yield instring[last:s]
if includeSeparators:
yield t[0]
last = e
yield instring[last:] | [
"def",
"split",
"(",
"self",
",",
"instring",
",",
"maxsplit",
"=",
"_MAX_INT",
",",
"includeSeparators",
"=",
"False",
")",
":",
"splits",
"=",
"0",
"last",
"=",
"0",
"for",
"t",
",",
"s",
",",
"e",
"in",
"self",
".",
"scanString",
"(",
"instring",
",",
"maxMatches",
"=",
"maxsplit",
")",
":",
"yield",
"instring",
"[",
"last",
":",
"s",
"]",
"if",
"includeSeparators",
":",
"yield",
"t",
"[",
"0",
"]",
"last",
"=",
"e",
"yield",
"instring",
"[",
"last",
":",
"]"
] | [
2112,
4
] | [
2135,
29
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__add__ | (self, other) |
Implementation of + operator - returns :class:`And`. Adding strings to a ParserElement
converts them to :class:`Literal`s by default.
Example::
greet = Word(alphas) + "," + Word(alphas) + "!"
hello = "Hello, World!"
print (hello, "->", greet.parseString(hello))
prints::
Hello, World! -> ['Hello', ',', 'World', '!']
``...`` may be used as a parse expression as a short form of :class:`SkipTo`.
Literal('start') + ... + Literal('end')
is equivalent to:
Literal('start') + SkipTo('end')("_skipped*") + Literal('end')
Note that the skipped text is returned with '_skipped' as a results name,
and to support having multiple skips in the same parser, the value returned is
a list of all skipped text.
|
Implementation of + operator - returns :class:`And`. Adding strings to a ParserElement
converts them to :class:`Literal`s by default. | def __add__(self, other):
"""
Implementation of + operator - returns :class:`And`. Adding strings to a ParserElement
converts them to :class:`Literal`s by default.
Example::
greet = Word(alphas) + "," + Word(alphas) + "!"
hello = "Hello, World!"
print (hello, "->", greet.parseString(hello))
prints::
Hello, World! -> ['Hello', ',', 'World', '!']
``...`` may be used as a parse expression as a short form of :class:`SkipTo`.
Literal('start') + ... + Literal('end')
is equivalent to:
Literal('start') + SkipTo('end')("_skipped*") + Literal('end')
Note that the skipped text is returned with '_skipped' as a results name,
and to support having multiple skips in the same parser, the value returned is
a list of all skipped text.
"""
if other is Ellipsis:
return _PendingSkip(self)
if isinstance(other, basestring):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return And([self, other]) | [
"def",
"__add__",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
"is",
"Ellipsis",
":",
"return",
"_PendingSkip",
"(",
"self",
")",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"And",
"(",
"[",
"self",
",",
"other",
"]",
")"
] | [
2137,
4
] | [
2173,
33
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__radd__ | (self, other) |
Implementation of + operator when left operand is not a :class:`ParserElement`
|
Implementation of + operator when left operand is not a :class:`ParserElement`
| def __radd__(self, other):
"""
Implementation of + operator when left operand is not a :class:`ParserElement`
"""
if other is Ellipsis:
return SkipTo(self)("_skipped*") + self
if isinstance(other, basestring):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other + self | [
"def",
"__radd__",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
"is",
"Ellipsis",
":",
"return",
"SkipTo",
"(",
"self",
")",
"(",
"\"_skipped*\"",
")",
"+",
"self",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"other",
"+",
"self"
] | [
2175,
4
] | [
2188,
27
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__sub__ | (self, other) |
Implementation of - operator, returns :class:`And` with error stop
|
Implementation of - operator, returns :class:`And` with error stop
| def __sub__(self, other):
"""
Implementation of - operator, returns :class:`And` with error stop
"""
if isinstance(other, basestring):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return self + And._ErrorStop() + other | [
"def",
"__sub__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"self",
"+",
"And",
".",
"_ErrorStop",
"(",
")",
"+",
"other"
] | [
2190,
4
] | [
2200,
46
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__rsub__ | (self, other) |
Implementation of - operator when left operand is not a :class:`ParserElement`
|
Implementation of - operator when left operand is not a :class:`ParserElement`
| def __rsub__(self, other):
"""
Implementation of - operator when left operand is not a :class:`ParserElement`
"""
if isinstance(other, basestring):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other - self | [
"def",
"__rsub__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"other",
"-",
"self"
] | [
2202,
4
] | [
2212,
27
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__mul__ | (self, other) |
Implementation of * operator, allows use of ``expr * 3`` in place of
``expr + expr + expr``. Expressions may also me multiplied by a 2-integer
tuple, similar to ``{min, max}`` multipliers in regular expressions. Tuples
may also include ``None`` as in:
- ``expr*(n, None)`` or ``expr*(n, )`` is equivalent
to ``expr*n + ZeroOrMore(expr)``
(read as "at least n instances of ``expr``")
- ``expr*(None, n)`` is equivalent to ``expr*(0, n)``
(read as "0 to n instances of ``expr``")
- ``expr*(None, None)`` is equivalent to ``ZeroOrMore(expr)``
- ``expr*(1, None)`` is equivalent to ``OneOrMore(expr)``
Note that ``expr*(None, n)`` does not raise an exception if
more than n exprs exist in the input stream; that is,
``expr*(None, n)`` does not enforce a maximum number of expr
occurrences. If this behavior is desired, then write
``expr*(None, n) + ~expr``
|
Implementation of * operator, allows use of ``expr * 3`` in place of
``expr + expr + expr``. Expressions may also me multiplied by a 2-integer
tuple, similar to ``{min, max}`` multipliers in regular expressions. Tuples
may also include ``None`` as in:
- ``expr*(n, None)`` or ``expr*(n, )`` is equivalent
to ``expr*n + ZeroOrMore(expr)``
(read as "at least n instances of ``expr``")
- ``expr*(None, n)`` is equivalent to ``expr*(0, n)``
(read as "0 to n instances of ``expr``")
- ``expr*(None, None)`` is equivalent to ``ZeroOrMore(expr)``
- ``expr*(1, None)`` is equivalent to ``OneOrMore(expr)`` | def __mul__(self, other):
"""
Implementation of * operator, allows use of ``expr * 3`` in place of
``expr + expr + expr``. Expressions may also me multiplied by a 2-integer
tuple, similar to ``{min, max}`` multipliers in regular expressions. Tuples
may also include ``None`` as in:
- ``expr*(n, None)`` or ``expr*(n, )`` is equivalent
to ``expr*n + ZeroOrMore(expr)``
(read as "at least n instances of ``expr``")
- ``expr*(None, n)`` is equivalent to ``expr*(0, n)``
(read as "0 to n instances of ``expr``")
- ``expr*(None, None)`` is equivalent to ``ZeroOrMore(expr)``
- ``expr*(1, None)`` is equivalent to ``OneOrMore(expr)``
Note that ``expr*(None, n)`` does not raise an exception if
more than n exprs exist in the input stream; that is,
``expr*(None, n)`` does not enforce a maximum number of expr
occurrences. If this behavior is desired, then write
``expr*(None, n) + ~expr``
"""
if other is Ellipsis:
other = (0, None)
elif isinstance(other, tuple) and other[:1] == (Ellipsis,):
other = ((0, ) + other[1:] + (None,))[:2]
if isinstance(other, int):
minElements, optElements = other, 0
elif isinstance(other, tuple):
other = tuple(o if o is not Ellipsis else None for o in other)
other = (other + (None, None))[:2]
if other[0] is None:
other = (0, other[1])
if isinstance(other[0], int) and other[1] is None:
if other[0] == 0:
return ZeroOrMore(self)
if other[0] == 1:
return OneOrMore(self)
else:
return self * other[0] + ZeroOrMore(self)
elif isinstance(other[0], int) and isinstance(other[1], int):
minElements, optElements = other
optElements -= minElements
else:
raise TypeError("cannot multiply 'ParserElement' and ('%s', '%s') objects", type(other[0]), type(other[1]))
else:
raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other))
if minElements < 0:
raise ValueError("cannot multiply ParserElement by negative value")
if optElements < 0:
raise ValueError("second tuple value must be greater or equal to first tuple value")
if minElements == optElements == 0:
raise ValueError("cannot multiply ParserElement by 0 or (0, 0)")
if optElements:
def makeOptionalList(n):
if n > 1:
return Optional(self + makeOptionalList(n - 1))
else:
return Optional(self)
if minElements:
if minElements == 1:
ret = self + makeOptionalList(optElements)
else:
ret = And([self] * minElements) + makeOptionalList(optElements)
else:
ret = makeOptionalList(optElements)
else:
if minElements == 1:
ret = self
else:
ret = And([self] * minElements)
return ret | [
"def",
"__mul__",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
"is",
"Ellipsis",
":",
"other",
"=",
"(",
"0",
",",
"None",
")",
"elif",
"isinstance",
"(",
"other",
",",
"tuple",
")",
"and",
"other",
"[",
":",
"1",
"]",
"==",
"(",
"Ellipsis",
",",
")",
":",
"other",
"=",
"(",
"(",
"0",
",",
")",
"+",
"other",
"[",
"1",
":",
"]",
"+",
"(",
"None",
",",
")",
")",
"[",
":",
"2",
"]",
"if",
"isinstance",
"(",
"other",
",",
"int",
")",
":",
"minElements",
",",
"optElements",
"=",
"other",
",",
"0",
"elif",
"isinstance",
"(",
"other",
",",
"tuple",
")",
":",
"other",
"=",
"tuple",
"(",
"o",
"if",
"o",
"is",
"not",
"Ellipsis",
"else",
"None",
"for",
"o",
"in",
"other",
")",
"other",
"=",
"(",
"other",
"+",
"(",
"None",
",",
"None",
")",
")",
"[",
":",
"2",
"]",
"if",
"other",
"[",
"0",
"]",
"is",
"None",
":",
"other",
"=",
"(",
"0",
",",
"other",
"[",
"1",
"]",
")",
"if",
"isinstance",
"(",
"other",
"[",
"0",
"]",
",",
"int",
")",
"and",
"other",
"[",
"1",
"]",
"is",
"None",
":",
"if",
"other",
"[",
"0",
"]",
"==",
"0",
":",
"return",
"ZeroOrMore",
"(",
"self",
")",
"if",
"other",
"[",
"0",
"]",
"==",
"1",
":",
"return",
"OneOrMore",
"(",
"self",
")",
"else",
":",
"return",
"self",
"*",
"other",
"[",
"0",
"]",
"+",
"ZeroOrMore",
"(",
"self",
")",
"elif",
"isinstance",
"(",
"other",
"[",
"0",
"]",
",",
"int",
")",
"and",
"isinstance",
"(",
"other",
"[",
"1",
"]",
",",
"int",
")",
":",
"minElements",
",",
"optElements",
"=",
"other",
"optElements",
"-=",
"minElements",
"else",
":",
"raise",
"TypeError",
"(",
"\"cannot multiply 'ParserElement' and ('%s', '%s') objects\"",
",",
"type",
"(",
"other",
"[",
"0",
"]",
")",
",",
"type",
"(",
"other",
"[",
"1",
"]",
")",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"cannot multiply 'ParserElement' and '%s' objects\"",
",",
"type",
"(",
"other",
")",
")",
"if",
"minElements",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"cannot multiply ParserElement by negative value\"",
")",
"if",
"optElements",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"second tuple value must be greater or equal to first tuple value\"",
")",
"if",
"minElements",
"==",
"optElements",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"cannot multiply ParserElement by 0 or (0, 0)\"",
")",
"if",
"optElements",
":",
"def",
"makeOptionalList",
"(",
"n",
")",
":",
"if",
"n",
">",
"1",
":",
"return",
"Optional",
"(",
"self",
"+",
"makeOptionalList",
"(",
"n",
"-",
"1",
")",
")",
"else",
":",
"return",
"Optional",
"(",
"self",
")",
"if",
"minElements",
":",
"if",
"minElements",
"==",
"1",
":",
"ret",
"=",
"self",
"+",
"makeOptionalList",
"(",
"optElements",
")",
"else",
":",
"ret",
"=",
"And",
"(",
"[",
"self",
"]",
"*",
"minElements",
")",
"+",
"makeOptionalList",
"(",
"optElements",
")",
"else",
":",
"ret",
"=",
"makeOptionalList",
"(",
"optElements",
")",
"else",
":",
"if",
"minElements",
"==",
"1",
":",
"ret",
"=",
"self",
"else",
":",
"ret",
"=",
"And",
"(",
"[",
"self",
"]",
"*",
"minElements",
")",
"return",
"ret"
] | [
2214,
4
] | [
2286,
18
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__or__ | (self, other) |
Implementation of | operator - returns :class:`MatchFirst`
|
Implementation of | operator - returns :class:`MatchFirst`
| def __or__(self, other):
"""
Implementation of | operator - returns :class:`MatchFirst`
"""
if other is Ellipsis:
return _PendingSkip(self, must_skip=True)
if isinstance(other, basestring):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return MatchFirst([self, other]) | [
"def",
"__or__",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
"is",
"Ellipsis",
":",
"return",
"_PendingSkip",
"(",
"self",
",",
"must_skip",
"=",
"True",
")",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"MatchFirst",
"(",
"[",
"self",
",",
"other",
"]",
")"
] | [
2291,
4
] | [
2304,
40
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__ror__ | (self, other) |
Implementation of | operator when left operand is not a :class:`ParserElement`
|
Implementation of | operator when left operand is not a :class:`ParserElement`
| def __ror__(self, other):
"""
Implementation of | operator when left operand is not a :class:`ParserElement`
"""
if isinstance(other, basestring):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other | self | [
"def",
"__ror__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"other",
"|",
"self"
] | [
2306,
4
] | [
2316,
27
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__xor__ | (self, other) |
Implementation of ^ operator - returns :class:`Or`
|
Implementation of ^ operator - returns :class:`Or`
| def __xor__(self, other):
"""
Implementation of ^ operator - returns :class:`Or`
"""
if isinstance(other, basestring):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return Or([self, other]) | [
"def",
"__xor__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"Or",
"(",
"[",
"self",
",",
"other",
"]",
")"
] | [
2318,
4
] | [
2328,
32
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__rxor__ | (self, other) |
Implementation of ^ operator when left operand is not a :class:`ParserElement`
|
Implementation of ^ operator when left operand is not a :class:`ParserElement`
| def __rxor__(self, other):
"""
Implementation of ^ operator when left operand is not a :class:`ParserElement`
"""
if isinstance(other, basestring):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other ^ self | [
"def",
"__rxor__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"other",
"^",
"self"
] | [
2330,
4
] | [
2340,
27
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__and__ | (self, other) |
Implementation of & operator - returns :class:`Each`
|
Implementation of & operator - returns :class:`Each`
| def __and__(self, other):
"""
Implementation of & operator - returns :class:`Each`
"""
if isinstance(other, basestring):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return Each([self, other]) | [
"def",
"__and__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"Each",
"(",
"[",
"self",
",",
"other",
"]",
")"
] | [
2342,
4
] | [
2352,
34
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__rand__ | (self, other) |
Implementation of & operator when left operand is not a :class:`ParserElement`
|
Implementation of & operator when left operand is not a :class:`ParserElement`
| def __rand__(self, other):
"""
Implementation of & operator when left operand is not a :class:`ParserElement`
"""
if isinstance(other, basestring):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other & self | [
"def",
"__rand__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"other",
"&",
"self"
] | [
2354,
4
] | [
2364,
27
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__invert__ | (self) |
Implementation of ~ operator - returns :class:`NotAny`
|
Implementation of ~ operator - returns :class:`NotAny`
| def __invert__(self):
"""
Implementation of ~ operator - returns :class:`NotAny`
"""
return NotAny(self) | [
"def",
"__invert__",
"(",
"self",
")",
":",
"return",
"NotAny",
"(",
"self",
")"
] | [
2366,
4
] | [
2370,
27
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__getitem__ | (self, key) |
use ``[]`` indexing notation as a short form for expression repetition:
- ``expr[n]`` is equivalent to ``expr*n``
- ``expr[m, n]`` is equivalent to ``expr*(m, n)``
- ``expr[n, ...]`` or ``expr[n,]`` is equivalent
to ``expr*n + ZeroOrMore(expr)``
(read as "at least n instances of ``expr``")
- ``expr[..., n]`` is equivalent to ``expr*(0, n)``
(read as "0 to n instances of ``expr``")
- ``expr[...]`` and ``expr[0, ...]`` are equivalent to ``ZeroOrMore(expr)``
- ``expr[1, ...]`` is equivalent to ``OneOrMore(expr)``
``None`` may be used in place of ``...``.
Note that ``expr[..., n]`` and ``expr[m, n]``do not raise an exception
if more than ``n`` ``expr``s exist in the input stream. If this behavior is
desired, then write ``expr[..., n] + ~expr``.
|
use ``[]`` indexing notation as a short form for expression repetition:
- ``expr[n]`` is equivalent to ``expr*n``
- ``expr[m, n]`` is equivalent to ``expr*(m, n)``
- ``expr[n, ...]`` or ``expr[n,]`` is equivalent
to ``expr*n + ZeroOrMore(expr)``
(read as "at least n instances of ``expr``")
- ``expr[..., n]`` is equivalent to ``expr*(0, n)``
(read as "0 to n instances of ``expr``")
- ``expr[...]`` and ``expr[0, ...]`` are equivalent to ``ZeroOrMore(expr)``
- ``expr[1, ...]`` is equivalent to ``OneOrMore(expr)``
``None`` may be used in place of ``...``. | def __getitem__(self, key):
"""
use ``[]`` indexing notation as a short form for expression repetition:
- ``expr[n]`` is equivalent to ``expr*n``
- ``expr[m, n]`` is equivalent to ``expr*(m, n)``
- ``expr[n, ...]`` or ``expr[n,]`` is equivalent
to ``expr*n + ZeroOrMore(expr)``
(read as "at least n instances of ``expr``")
- ``expr[..., n]`` is equivalent to ``expr*(0, n)``
(read as "0 to n instances of ``expr``")
- ``expr[...]`` and ``expr[0, ...]`` are equivalent to ``ZeroOrMore(expr)``
- ``expr[1, ...]`` is equivalent to ``OneOrMore(expr)``
``None`` may be used in place of ``...``.
Note that ``expr[..., n]`` and ``expr[m, n]``do not raise an exception
if more than ``n`` ``expr``s exist in the input stream. If this behavior is
desired, then write ``expr[..., n] + ~expr``.
"""
# convert single arg keys to tuples
try:
if isinstance(key, str):
key = (key,)
iter(key)
except TypeError:
key = (key, key)
if len(key) > 2:
warnings.warn("only 1 or 2 index arguments supported ({0}{1})".format(key[:5],
'... [{0}]'.format(len(key))
if len(key) > 5 else ''))
# clip to 2 elements
ret = self * tuple(key[:2])
return ret | [
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"# convert single arg keys to tuples",
"try",
":",
"if",
"isinstance",
"(",
"key",
",",
"str",
")",
":",
"key",
"=",
"(",
"key",
",",
")",
"iter",
"(",
"key",
")",
"except",
"TypeError",
":",
"key",
"=",
"(",
"key",
",",
"key",
")",
"if",
"len",
"(",
"key",
")",
">",
"2",
":",
"warnings",
".",
"warn",
"(",
"\"only 1 or 2 index arguments supported ({0}{1})\"",
".",
"format",
"(",
"key",
"[",
":",
"5",
"]",
",",
"'... [{0}]'",
".",
"format",
"(",
"len",
"(",
"key",
")",
")",
"if",
"len",
"(",
"key",
")",
">",
"5",
"else",
"''",
")",
")",
"# clip to 2 elements",
"ret",
"=",
"self",
"*",
"tuple",
"(",
"key",
"[",
":",
"2",
"]",
")",
"return",
"ret"
] | [
2377,
4
] | [
2411,
18
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__call__ | (self, name=None) |
Shortcut for :class:`setResultsName`, with ``listAllMatches=False``.
If ``name`` is given with a trailing ``'*'`` character, then ``listAllMatches`` will be
passed as ``True``.
If ``name` is omitted, same as calling :class:`copy`.
Example::
# these are equivalent
userdata = Word(alphas).setResultsName("name") + Word(nums + "-").setResultsName("socsecno")
userdata = Word(alphas)("name") + Word(nums + "-")("socsecno")
|
Shortcut for :class:`setResultsName`, with ``listAllMatches=False``. | def __call__(self, name=None):
"""
Shortcut for :class:`setResultsName`, with ``listAllMatches=False``.
If ``name`` is given with a trailing ``'*'`` character, then ``listAllMatches`` will be
passed as ``True``.
If ``name` is omitted, same as calling :class:`copy`.
Example::
# these are equivalent
userdata = Word(alphas).setResultsName("name") + Word(nums + "-").setResultsName("socsecno")
userdata = Word(alphas)("name") + Word(nums + "-")("socsecno")
"""
if name is not None:
return self._setResultsName(name)
else:
return self.copy() | [
"def",
"__call__",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_setResultsName",
"(",
"name",
")",
"else",
":",
"return",
"self",
".",
"copy",
"(",
")"
] | [
2413,
4
] | [
2431,
30
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.suppress | (self) |
Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from
cluttering up returned output.
|
Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from
cluttering up returned output.
| def suppress(self):
"""
Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from
cluttering up returned output.
"""
return Suppress(self) | [
"def",
"suppress",
"(",
"self",
")",
":",
"return",
"Suppress",
"(",
"self",
")"
] | [
2433,
4
] | [
2438,
29
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.leaveWhitespace | (self) |
Disables the skipping of whitespace before matching the characters in the
:class:`ParserElement`'s defined pattern. This is normally only used internally by
the pyparsing module, but may be needed in some whitespace-sensitive grammars.
|
Disables the skipping of whitespace before matching the characters in the
:class:`ParserElement`'s defined pattern. This is normally only used internally by
the pyparsing module, but may be needed in some whitespace-sensitive grammars.
| def leaveWhitespace(self):
"""
Disables the skipping of whitespace before matching the characters in the
:class:`ParserElement`'s defined pattern. This is normally only used internally by
the pyparsing module, but may be needed in some whitespace-sensitive grammars.
"""
self.skipWhitespace = False
return self | [
"def",
"leaveWhitespace",
"(",
"self",
")",
":",
"self",
".",
"skipWhitespace",
"=",
"False",
"return",
"self"
] | [
2440,
4
] | [
2447,
19
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.setWhitespaceChars | (self, chars) |
Overrides the default whitespace chars
|
Overrides the default whitespace chars
| def setWhitespaceChars(self, chars):
"""
Overrides the default whitespace chars
"""
self.skipWhitespace = True
self.whiteChars = chars
self.copyDefaultWhiteChars = False
return self | [
"def",
"setWhitespaceChars",
"(",
"self",
",",
"chars",
")",
":",
"self",
".",
"skipWhitespace",
"=",
"True",
"self",
".",
"whiteChars",
"=",
"chars",
"self",
".",
"copyDefaultWhiteChars",
"=",
"False",
"return",
"self"
] | [
2449,
4
] | [
2456,
19
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.parseWithTabs | (self) |
Overrides default behavior to expand ``<TAB>``s to spaces before parsing the input string.
Must be called before ``parseString`` when the input grammar contains elements that
match ``<TAB>`` characters.
|
Overrides default behavior to expand ``<TAB>``s to spaces before parsing the input string.
Must be called before ``parseString`` when the input grammar contains elements that
match ``<TAB>`` characters.
| def parseWithTabs(self):
"""
Overrides default behavior to expand ``<TAB>``s to spaces before parsing the input string.
Must be called before ``parseString`` when the input grammar contains elements that
match ``<TAB>`` characters.
"""
self.keepTabs = True
return self | [
"def",
"parseWithTabs",
"(",
"self",
")",
":",
"self",
".",
"keepTabs",
"=",
"True",
"return",
"self"
] | [
2458,
4
] | [
2465,
19
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.ignore | (self, other) |
Define expression to be ignored (e.g., comments) while doing pattern
matching; may be called repeatedly, to define multiple comment or other
ignorable patterns.
Example::
patt = OneOrMore(Word(alphas))
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj']
patt.ignore(cStyleComment)
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd']
|
Define expression to be ignored (e.g., comments) while doing pattern
matching; may be called repeatedly, to define multiple comment or other
ignorable patterns. | def ignore(self, other):
"""
Define expression to be ignored (e.g., comments) while doing pattern
matching; may be called repeatedly, to define multiple comment or other
ignorable patterns.
Example::
patt = OneOrMore(Word(alphas))
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj']
patt.ignore(cStyleComment)
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd']
"""
if isinstance(other, basestring):
other = Suppress(other)
if isinstance(other, Suppress):
if other not in self.ignoreExprs:
self.ignoreExprs.append(other)
else:
self.ignoreExprs.append(Suppress(other.copy()))
return self | [
"def",
"ignore",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"Suppress",
"(",
"other",
")",
"if",
"isinstance",
"(",
"other",
",",
"Suppress",
")",
":",
"if",
"other",
"not",
"in",
"self",
".",
"ignoreExprs",
":",
"self",
".",
"ignoreExprs",
".",
"append",
"(",
"other",
")",
"else",
":",
"self",
".",
"ignoreExprs",
".",
"append",
"(",
"Suppress",
"(",
"other",
".",
"copy",
"(",
")",
")",
")",
"return",
"self"
] | [
2467,
4
] | [
2489,
19
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.setDebugActions | (self, startAction, successAction, exceptionAction) |
Enable display of debugging messages while doing pattern matching.
|
Enable display of debugging messages while doing pattern matching.
| def setDebugActions(self, startAction, successAction, exceptionAction):
"""
Enable display of debugging messages while doing pattern matching.
"""
self.debugActions = (startAction or _defaultStartDebugAction,
successAction or _defaultSuccessDebugAction,
exceptionAction or _defaultExceptionDebugAction)
self.debug = True
return self | [
"def",
"setDebugActions",
"(",
"self",
",",
"startAction",
",",
"successAction",
",",
"exceptionAction",
")",
":",
"self",
".",
"debugActions",
"=",
"(",
"startAction",
"or",
"_defaultStartDebugAction",
",",
"successAction",
"or",
"_defaultSuccessDebugAction",
",",
"exceptionAction",
"or",
"_defaultExceptionDebugAction",
")",
"self",
".",
"debug",
"=",
"True",
"return",
"self"
] | [
2491,
4
] | [
2499,
19
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.setDebug | (self, flag=True) |
Enable display of debugging messages while doing pattern matching.
Set ``flag`` to True to enable, False to disable.
Example::
wd = Word(alphas).setName("alphaword")
integer = Word(nums).setName("numword")
term = wd | integer
# turn on debugging for wd
wd.setDebug()
OneOrMore(term).parseString("abc 123 xyz 890")
prints::
Match alphaword at loc 0(1,1)
Matched alphaword -> ['abc']
Match alphaword at loc 3(1,4)
Exception raised:Expected alphaword (at char 4), (line:1, col:5)
Match alphaword at loc 7(1,8)
Matched alphaword -> ['xyz']
Match alphaword at loc 11(1,12)
Exception raised:Expected alphaword (at char 12), (line:1, col:13)
Match alphaword at loc 15(1,16)
Exception raised:Expected alphaword (at char 15), (line:1, col:16)
The output shown is that produced by the default debug actions - custom debug actions can be
specified using :class:`setDebugActions`. Prior to attempting
to match the ``wd`` expression, the debugging message ``"Match <exprname> at loc <n>(<line>,<col>)"``
is shown. Then if the parse succeeds, a ``"Matched"`` message is shown, or an ``"Exception raised"``
message is shown. Also note the use of :class:`setName` to assign a human-readable name to the expression,
which makes debugging and exception messages easier to understand - for instance, the default
name created for the :class:`Word` expression without calling ``setName`` is ``"W:(ABCD...)"``.
|
Enable display of debugging messages while doing pattern matching.
Set ``flag`` to True to enable, False to disable. | def setDebug(self, flag=True):
"""
Enable display of debugging messages while doing pattern matching.
Set ``flag`` to True to enable, False to disable.
Example::
wd = Word(alphas).setName("alphaword")
integer = Word(nums).setName("numword")
term = wd | integer
# turn on debugging for wd
wd.setDebug()
OneOrMore(term).parseString("abc 123 xyz 890")
prints::
Match alphaword at loc 0(1,1)
Matched alphaword -> ['abc']
Match alphaword at loc 3(1,4)
Exception raised:Expected alphaword (at char 4), (line:1, col:5)
Match alphaword at loc 7(1,8)
Matched alphaword -> ['xyz']
Match alphaword at loc 11(1,12)
Exception raised:Expected alphaword (at char 12), (line:1, col:13)
Match alphaword at loc 15(1,16)
Exception raised:Expected alphaword (at char 15), (line:1, col:16)
The output shown is that produced by the default debug actions - custom debug actions can be
specified using :class:`setDebugActions`. Prior to attempting
to match the ``wd`` expression, the debugging message ``"Match <exprname> at loc <n>(<line>,<col>)"``
is shown. Then if the parse succeeds, a ``"Matched"`` message is shown, or an ``"Exception raised"``
message is shown. Also note the use of :class:`setName` to assign a human-readable name to the expression,
which makes debugging and exception messages easier to understand - for instance, the default
name created for the :class:`Word` expression without calling ``setName`` is ``"W:(ABCD...)"``.
"""
if flag:
self.setDebugActions(_defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction)
else:
self.debug = False
return self | [
"def",
"setDebug",
"(",
"self",
",",
"flag",
"=",
"True",
")",
":",
"if",
"flag",
":",
"self",
".",
"setDebugActions",
"(",
"_defaultStartDebugAction",
",",
"_defaultSuccessDebugAction",
",",
"_defaultExceptionDebugAction",
")",
"else",
":",
"self",
".",
"debug",
"=",
"False",
"return",
"self"
] | [
2501,
4
] | [
2542,
19
] | python | en | ['en', 'error', 'th'] | False |
_hash_dict | (d) | Return a stable sha224 of a dictionary. | Return a stable sha224 of a dictionary. | def _hash_dict(d):
# type: (Dict[str, str]) -> str
"""Return a stable sha224 of a dictionary."""
s = json.dumps(d, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
return hashlib.sha224(s.encode("ascii")).hexdigest() | [
"def",
"_hash_dict",
"(",
"d",
")",
":",
"# type: (Dict[str, str]) -> str",
"s",
"=",
"json",
".",
"dumps",
"(",
"d",
",",
"sort_keys",
"=",
"True",
",",
"separators",
"=",
"(",
"\",\"",
",",
"\":\"",
")",
",",
"ensure_ascii",
"=",
"True",
")",
"return",
"hashlib",
".",
"sha224",
"(",
"s",
".",
"encode",
"(",
"\"ascii\"",
")",
")",
".",
"hexdigest",
"(",
")"
] | [
22,
0
] | [
26,
56
] | python | en | ['en', 'en', 'en'] | True |
Cache._get_cache_path_parts | (self, link) | Get parts of part that must be os.path.joined with cache_dir
| Get parts of part that must be os.path.joined with cache_dir
| def _get_cache_path_parts(self, link):
# type: (Link) -> List[str]
"""Get parts of part that must be os.path.joined with cache_dir
"""
# We want to generate an url to use as our cache key, we don't want to
# just re-use the URL because it might have other items in the fragment
# and we don't care about those.
key_parts = {"url": link.url_without_fragment}
if link.hash_name is not None and link.hash is not None:
key_parts[link.hash_name] = link.hash
if link.subdirectory_fragment:
key_parts["subdirectory"] = link.subdirectory_fragment
# Include interpreter name, major and minor version in cache key
# to cope with ill-behaved sdists that build a different wheel
# depending on the python version their setup.py is being run on,
# and don't encode the difference in compatibility tags.
# https://github.com/pypa/pip/issues/7296
key_parts["interpreter_name"] = interpreter_name()
key_parts["interpreter_version"] = interpreter_version()
# Encode our key url with sha224, we'll use this because it has similar
# security properties to sha256, but with a shorter total output (and
# thus less secure). However the differences don't make a lot of
# difference for our use case here.
hashed = _hash_dict(key_parts)
# We want to nest the directories some to prevent having a ton of top
# level directories where we might run out of sub directories on some
# FS.
parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]
return parts | [
"def",
"_get_cache_path_parts",
"(",
"self",
",",
"link",
")",
":",
"# type: (Link) -> List[str]",
"# We want to generate an url to use as our cache key, we don't want to",
"# just re-use the URL because it might have other items in the fragment",
"# and we don't care about those.",
"key_parts",
"=",
"{",
"\"url\"",
":",
"link",
".",
"url_without_fragment",
"}",
"if",
"link",
".",
"hash_name",
"is",
"not",
"None",
"and",
"link",
".",
"hash",
"is",
"not",
"None",
":",
"key_parts",
"[",
"link",
".",
"hash_name",
"]",
"=",
"link",
".",
"hash",
"if",
"link",
".",
"subdirectory_fragment",
":",
"key_parts",
"[",
"\"subdirectory\"",
"]",
"=",
"link",
".",
"subdirectory_fragment",
"# Include interpreter name, major and minor version in cache key",
"# to cope with ill-behaved sdists that build a different wheel",
"# depending on the python version their setup.py is being run on,",
"# and don't encode the difference in compatibility tags.",
"# https://github.com/pypa/pip/issues/7296",
"key_parts",
"[",
"\"interpreter_name\"",
"]",
"=",
"interpreter_name",
"(",
")",
"key_parts",
"[",
"\"interpreter_version\"",
"]",
"=",
"interpreter_version",
"(",
")",
"# Encode our key url with sha224, we'll use this because it has similar",
"# security properties to sha256, but with a shorter total output (and",
"# thus less secure). However the differences don't make a lot of",
"# difference for our use case here.",
"hashed",
"=",
"_hash_dict",
"(",
"key_parts",
")",
"# We want to nest the directories some to prevent having a ton of top",
"# level directories where we might run out of sub directories on some",
"# FS.",
"parts",
"=",
"[",
"hashed",
"[",
":",
"2",
"]",
",",
"hashed",
"[",
"2",
":",
"4",
"]",
",",
"hashed",
"[",
"4",
":",
"6",
"]",
",",
"hashed",
"[",
"6",
":",
"]",
"]",
"return",
"parts"
] | [
51,
4
] | [
84,
20
] | python | en | ['en', 'en', 'en'] | True |
Cache.get_path_for_link | (self, link) | Return a directory to store cached items in for link.
| Return a directory to store cached items in for link.
| def get_path_for_link(self, link):
# type: (Link) -> str
"""Return a directory to store cached items in for link.
"""
raise NotImplementedError() | [
"def",
"get_path_for_link",
"(",
"self",
",",
"link",
")",
":",
"# type: (Link) -> str",
"raise",
"NotImplementedError",
"(",
")"
] | [
109,
4
] | [
113,
35
] | python | en | ['en', 'en', 'en'] | True |
Cache.get | (
self,
link, # type: Link
package_name, # type: Optional[str]
supported_tags, # type: List[Tag]
) | Returns a link to a cached item if it exists, otherwise returns the
passed link.
| Returns a link to a cached item if it exists, otherwise returns the
passed link.
| def get(
self,
link, # type: Link
package_name, # type: Optional[str]
supported_tags, # type: List[Tag]
):
# type: (...) -> Link
"""Returns a link to a cached item if it exists, otherwise returns the
passed link.
"""
raise NotImplementedError() | [
"def",
"get",
"(",
"self",
",",
"link",
",",
"# type: Link",
"package_name",
",",
"# type: Optional[str]",
"supported_tags",
",",
"# type: List[Tag]",
")",
":",
"# type: (...) -> Link",
"raise",
"NotImplementedError",
"(",
")"
] | [
115,
4
] | [
125,
35
] | python | en | ['en', 'en', 'en'] | True |
SimpleWheelCache.get_path_for_link | (self, link) | Return a directory to store cached wheels for link
Because there are M wheels for any one sdist, we provide a directory
to cache them in, and then consult that directory when looking up
cache hits.
We only insert things into the cache if they have plausible version
numbers, so that we don't contaminate the cache with things that were
not unique. E.g. ./package might have dozens of installs done for it
and build a version of 0.0...and if we built and cached a wheel, we'd
end up using the same wheel even if the source has been edited.
:param link: The link of the sdist for which this will cache wheels.
| Return a directory to store cached wheels for link | def get_path_for_link(self, link):
# type: (Link) -> str
"""Return a directory to store cached wheels for link
Because there are M wheels for any one sdist, we provide a directory
to cache them in, and then consult that directory when looking up
cache hits.
We only insert things into the cache if they have plausible version
numbers, so that we don't contaminate the cache with things that were
not unique. E.g. ./package might have dozens of installs done for it
and build a version of 0.0...and if we built and cached a wheel, we'd
end up using the same wheel even if the source has been edited.
:param link: The link of the sdist for which this will cache wheels.
"""
parts = self._get_cache_path_parts(link)
assert self.cache_dir
# Store wheels within the root cache_dir
return os.path.join(self.cache_dir, "wheels", *parts) | [
"def",
"get_path_for_link",
"(",
"self",
",",
"link",
")",
":",
"# type: (Link) -> str",
"parts",
"=",
"self",
".",
"_get_cache_path_parts",
"(",
"link",
")",
"assert",
"self",
".",
"cache_dir",
"# Store wheels within the root cache_dir",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cache_dir",
",",
"\"wheels\"",
",",
"*",
"parts",
")"
] | [
136,
4
] | [
155,
61
] | python | en | ['en', 'en', 'en'] | True |
WheelCache.get_cache_entry | (
self,
link, # type: Link
package_name, # type: Optional[str]
supported_tags, # type: List[Tag]
) | Returns a CacheEntry with a link to a cached item if it exists or
None. The cache entry indicates if the item was found in the persistent
or ephemeral cache.
| Returns a CacheEntry with a link to a cached item if it exists or
None. The cache entry indicates if the item was found in the persistent
or ephemeral cache.
| def get_cache_entry(
self,
link, # type: Link
package_name, # type: Optional[str]
supported_tags, # type: List[Tag]
):
# type: (...) -> Optional[CacheEntry]
"""Returns a CacheEntry with a link to a cached item if it exists or
None. The cache entry indicates if the item was found in the persistent
or ephemeral cache.
"""
retval = self._wheel_cache.get(
link=link,
package_name=package_name,
supported_tags=supported_tags,
)
if retval is not link:
return CacheEntry(retval, persistent=True)
retval = self._ephem_cache.get(
link=link,
package_name=package_name,
supported_tags=supported_tags,
)
if retval is not link:
return CacheEntry(retval, persistent=False)
return None | [
"def",
"get_cache_entry",
"(",
"self",
",",
"link",
",",
"# type: Link",
"package_name",
",",
"# type: Optional[str]",
"supported_tags",
",",
"# type: List[Tag]",
")",
":",
"# type: (...) -> Optional[CacheEntry]",
"retval",
"=",
"self",
".",
"_wheel_cache",
".",
"get",
"(",
"link",
"=",
"link",
",",
"package_name",
"=",
"package_name",
",",
"supported_tags",
"=",
"supported_tags",
",",
")",
"if",
"retval",
"is",
"not",
"link",
":",
"return",
"CacheEntry",
"(",
"retval",
",",
"persistent",
"=",
"True",
")",
"retval",
"=",
"self",
".",
"_ephem_cache",
".",
"get",
"(",
"link",
"=",
"link",
",",
"package_name",
"=",
"package_name",
",",
"supported_tags",
"=",
"supported_tags",
",",
")",
"if",
"retval",
"is",
"not",
"link",
":",
"return",
"CacheEntry",
"(",
"retval",
",",
"persistent",
"=",
"False",
")",
"return",
"None"
] | [
259,
4
] | [
286,
19
] | python | en | ['en', 'en', 'en'] | True |
_mkdir_if_not_exist | (path) |
mkdir if not exists, ignore the exception when multiprocess mkdir together
|
mkdir if not exists, ignore the exception when multiprocess mkdir together
| def _mkdir_if_not_exist(path):
"""
mkdir if not exists, ignore the exception when multiprocess mkdir together
"""
if not os.path.exists(path):
try:
os.makedirs(path)
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(path):
logger.warning(
'be happy if some process has already created {}'.format(
path))
else:
raise OSError('Failed to mkdir {}'.format(path)) | [
"def",
"_mkdir_if_not_exist",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"logger",
".",
"warning",
"(",
"'be happy if some process has already created {}'",
".",
"format",
"(",
"path",
")",
")",
"else",
":",
"raise",
"OSError",
"(",
"'Failed to mkdir {}'",
".",
"format",
"(",
"path",
")",
")"
] | [
31,
0
] | [
44,
64
] | python | en | ['en', 'error', 'th'] | False |
load_params | (exe, prog, path, ignore_params=None) |
Load model from the given path.
Args:
exe (fluid.Executor): The fluid.Executor object.
prog (fluid.Program): load weight to which Program object.
path (string): URL string or loca model path.
ignore_params (list): ignore variable to load when finetuning.
It can be specified by finetune_exclude_pretrained_params
and the usage can refer to the document
docs/advanced_tutorials/TRANSFER_LEARNING.md
|
Load model from the given path.
Args:
exe (fluid.Executor): The fluid.Executor object.
prog (fluid.Program): load weight to which Program object.
path (string): URL string or loca model path.
ignore_params (list): ignore variable to load when finetuning.
It can be specified by finetune_exclude_pretrained_params
and the usage can refer to the document
docs/advanced_tutorials/TRANSFER_LEARNING.md
| def load_params(exe, prog, path, ignore_params=None):
"""
Load model from the given path.
Args:
exe (fluid.Executor): The fluid.Executor object.
prog (fluid.Program): load weight to which Program object.
path (string): URL string or loca model path.
ignore_params (list): ignore variable to load when finetuning.
It can be specified by finetune_exclude_pretrained_params
and the usage can refer to the document
docs/advanced_tutorials/TRANSFER_LEARNING.md
"""
if not (os.path.isdir(path) or os.path.exists(path + '.pdparams')):
raise ValueError("Model pretrain path {} does not "
"exists.".format(path))
logger.info(
logger.coloring('Loading parameters from {}...'.format(path),
'HEADER'))
ignore_set = set()
state = _load_state(path)
# ignore the parameter which mismatch the shape
# between the model and pretrain weight.
all_var_shape = {}
for block in prog.blocks:
for param in block.all_parameters():
all_var_shape[param.name] = param.shape
ignore_set.update([
name for name, shape in all_var_shape.items()
if name in state and shape != state[name].shape
])
if ignore_params:
all_var_names = [var.name for var in prog.list_vars()]
ignore_list = filter(
lambda var: any([re.match(name, var) for name in ignore_params]),
all_var_names)
ignore_set.update(list(ignore_list))
if len(ignore_set) > 0:
for k in ignore_set:
if k in state:
logger.warning(
'variable {} is already excluded automatically'.format(k))
del state[k]
paddle.static.set_program_state(prog, state) | [
"def",
"load_params",
"(",
"exe",
",",
"prog",
",",
"path",
",",
"ignore_params",
"=",
"None",
")",
":",
"if",
"not",
"(",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
"or",
"os",
".",
"path",
".",
"exists",
"(",
"path",
"+",
"'.pdparams'",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Model pretrain path {} does not \"",
"\"exists.\"",
".",
"format",
"(",
"path",
")",
")",
"logger",
".",
"info",
"(",
"logger",
".",
"coloring",
"(",
"'Loading parameters from {}...'",
".",
"format",
"(",
"path",
")",
",",
"'HEADER'",
")",
")",
"ignore_set",
"=",
"set",
"(",
")",
"state",
"=",
"_load_state",
"(",
"path",
")",
"# ignore the parameter which mismatch the shape",
"# between the model and pretrain weight.",
"all_var_shape",
"=",
"{",
"}",
"for",
"block",
"in",
"prog",
".",
"blocks",
":",
"for",
"param",
"in",
"block",
".",
"all_parameters",
"(",
")",
":",
"all_var_shape",
"[",
"param",
".",
"name",
"]",
"=",
"param",
".",
"shape",
"ignore_set",
".",
"update",
"(",
"[",
"name",
"for",
"name",
",",
"shape",
"in",
"all_var_shape",
".",
"items",
"(",
")",
"if",
"name",
"in",
"state",
"and",
"shape",
"!=",
"state",
"[",
"name",
"]",
".",
"shape",
"]",
")",
"if",
"ignore_params",
":",
"all_var_names",
"=",
"[",
"var",
".",
"name",
"for",
"var",
"in",
"prog",
".",
"list_vars",
"(",
")",
"]",
"ignore_list",
"=",
"filter",
"(",
"lambda",
"var",
":",
"any",
"(",
"[",
"re",
".",
"match",
"(",
"name",
",",
"var",
")",
"for",
"name",
"in",
"ignore_params",
"]",
")",
",",
"all_var_names",
")",
"ignore_set",
".",
"update",
"(",
"list",
"(",
"ignore_list",
")",
")",
"if",
"len",
"(",
"ignore_set",
")",
">",
"0",
":",
"for",
"k",
"in",
"ignore_set",
":",
"if",
"k",
"in",
"state",
":",
"logger",
".",
"warning",
"(",
"'variable {} is already excluded automatically'",
".",
"format",
"(",
"k",
")",
")",
"del",
"state",
"[",
"k",
"]",
"paddle",
".",
"static",
".",
"set_program_state",
"(",
"prog",
",",
"state",
")"
] | [
60,
0
] | [
108,
48
] | python | en | ['en', 'error', 'th'] | False |
init_model | (config, program, exe) |
load model from checkpoint or pretrained_model
|
load model from checkpoint or pretrained_model
| def init_model(config, program, exe):
"""
load model from checkpoint or pretrained_model
"""
checkpoints = config.get('checkpoints')
if checkpoints:
paddle.static.load(program, checkpoints, exe)
logger.info(
logger.coloring("Finish initing model from {}".format(checkpoints),
"HEADER"))
return
pretrained_model = config.get('pretrained_model')
if pretrained_model:
if not isinstance(pretrained_model, list):
pretrained_model = [pretrained_model]
for pretrain in pretrained_model:
load_params(exe, program, pretrain)
logger.info(
logger.coloring("Finish initing model from {}".format(
pretrained_model), "HEADER")) | [
"def",
"init_model",
"(",
"config",
",",
"program",
",",
"exe",
")",
":",
"checkpoints",
"=",
"config",
".",
"get",
"(",
"'checkpoints'",
")",
"if",
"checkpoints",
":",
"paddle",
".",
"static",
".",
"load",
"(",
"program",
",",
"checkpoints",
",",
"exe",
")",
"logger",
".",
"info",
"(",
"logger",
".",
"coloring",
"(",
"\"Finish initing model from {}\"",
".",
"format",
"(",
"checkpoints",
")",
",",
"\"HEADER\"",
")",
")",
"return",
"pretrained_model",
"=",
"config",
".",
"get",
"(",
"'pretrained_model'",
")",
"if",
"pretrained_model",
":",
"if",
"not",
"isinstance",
"(",
"pretrained_model",
",",
"list",
")",
":",
"pretrained_model",
"=",
"[",
"pretrained_model",
"]",
"for",
"pretrain",
"in",
"pretrained_model",
":",
"load_params",
"(",
"exe",
",",
"program",
",",
"pretrain",
")",
"logger",
".",
"info",
"(",
"logger",
".",
"coloring",
"(",
"\"Finish initing model from {}\"",
".",
"format",
"(",
"pretrained_model",
")",
",",
"\"HEADER\"",
")",
")"
] | [
111,
0
] | [
131,
45
] | python | en | ['en', 'error', 'th'] | False |
save_model | (program, model_path, epoch_id, prefix='ppcls') |
save model to the target path
|
save model to the target path
| def save_model(program, model_path, epoch_id, prefix='ppcls'):
"""
save model to the target path
"""
model_path = os.path.join(model_path, str(epoch_id))
_mkdir_if_not_exist(model_path)
model_prefix = os.path.join(model_path, prefix)
paddle.static.save(program, model_prefix)
logger.info(
logger.coloring("Already save model in {}".format(model_path),
"HEADER")) | [
"def",
"save_model",
"(",
"program",
",",
"model_path",
",",
"epoch_id",
",",
"prefix",
"=",
"'ppcls'",
")",
":",
"model_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"model_path",
",",
"str",
"(",
"epoch_id",
")",
")",
"_mkdir_if_not_exist",
"(",
"model_path",
")",
"model_prefix",
"=",
"os",
".",
"path",
".",
"join",
"(",
"model_path",
",",
"prefix",
")",
"paddle",
".",
"static",
".",
"save",
"(",
"program",
",",
"model_prefix",
")",
"logger",
".",
"info",
"(",
"logger",
".",
"coloring",
"(",
"\"Already save model in {}\"",
".",
"format",
"(",
"model_path",
")",
",",
"\"HEADER\"",
")",
")"
] | [
134,
0
] | [
144,
34
] | python | en | ['en', 'error', 'th'] | False |
Requirement.project_name | (self) | The "project name" of a requirement.
This is different from ``name`` if this requirement contains extras,
in which case ``name`` would contain the ``[...]`` part, while this
refers to the name of the project.
| The "project name" of a requirement. | def project_name(self) -> NormalizedName:
"""The "project name" of a requirement.
This is different from ``name`` if this requirement contains extras,
in which case ``name`` would contain the ``[...]`` part, while this
refers to the name of the project.
"""
raise NotImplementedError("Subclass should override") | [
"def",
"project_name",
"(",
"self",
")",
"->",
"NormalizedName",
":",
"raise",
"NotImplementedError",
"(",
"\"Subclass should override\"",
")"
] | [
66,
4
] | [
73,
61
] | python | en | ['en', 'en', 'en'] | True |
Requirement.name | (self) | The name identifying this requirement in the resolver.
This is different from ``project_name`` if this requirement contains
extras, where ``project_name`` would not contain the ``[...]`` part.
| The name identifying this requirement in the resolver. | def name(self) -> str:
"""The name identifying this requirement in the resolver.
This is different from ``project_name`` if this requirement contains
extras, where ``project_name`` would not contain the ``[...]`` part.
"""
raise NotImplementedError("Subclass should override") | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"raise",
"NotImplementedError",
"(",
"\"Subclass should override\"",
")"
] | [
76,
4
] | [
82,
61
] | python | en | ['en', 'en', 'en'] | True |
Candidate.project_name | (self) | The "project name" of the candidate.
This is different from ``name`` if this candidate contains extras,
in which case ``name`` would contain the ``[...]`` part, while this
refers to the name of the project.
| The "project name" of the candidate. | def project_name(self) -> NormalizedName:
"""The "project name" of the candidate.
This is different from ``name`` if this candidate contains extras,
in which case ``name`` would contain the ``[...]`` part, while this
refers to the name of the project.
"""
raise NotImplementedError("Override in subclass") | [
"def",
"project_name",
"(",
"self",
")",
"->",
"NormalizedName",
":",
"raise",
"NotImplementedError",
"(",
"\"Override in subclass\"",
")"
] | [
102,
4
] | [
109,
57
] | python | en | ['en', 'en', 'en'] | True |
Candidate.name | (self) | The name identifying this candidate in the resolver.
This is different from ``project_name`` if this candidate contains
extras, where ``project_name`` would not contain the ``[...]`` part.
| The name identifying this candidate in the resolver. | def name(self) -> str:
"""The name identifying this candidate in the resolver.
This is different from ``project_name`` if this candidate contains
extras, where ``project_name`` would not contain the ``[...]`` part.
"""
raise NotImplementedError("Override in subclass") | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"raise",
"NotImplementedError",
"(",
"\"Override in subclass\"",
")"
] | [
112,
4
] | [
118,
57
] | python | en | ['en', 'en', 'en'] | True |
ListFilter.has_output | (self) |
Return True if some choices would be output for this filter.
|
Return True if some choices would be output for this filter.
| def has_output(self):
"""
Return True if some choices would be output for this filter.
"""
raise NotImplementedError('subclasses of ListFilter must provide a has_output() method') | [
"def",
"has_output",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of ListFilter must provide a has_output() method'",
")"
] | [
33,
4
] | [
37,
96
] | python | en | ['en', 'error', 'th'] | False |
ListFilter.choices | (self, changelist) |
Return choices ready to be output in the template.
`changelist` is the ChangeList to be displayed.
|
Return choices ready to be output in the template. | def choices(self, changelist):
"""
Return choices ready to be output in the template.
`changelist` is the ChangeList to be displayed.
"""
raise NotImplementedError('subclasses of ListFilter must provide a choices() method') | [
"def",
"choices",
"(",
"self",
",",
"changelist",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of ListFilter must provide a choices() method'",
")"
] | [
39,
4
] | [
45,
93
] | python | en | ['en', 'error', 'th'] | False |
ListFilter.queryset | (self, request, queryset) |
Return the filtered queryset.
|
Return the filtered queryset.
| def queryset(self, request, queryset):
"""
Return the filtered queryset.
"""
raise NotImplementedError('subclasses of ListFilter must provide a queryset() method') | [
"def",
"queryset",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of ListFilter must provide a queryset() method'",
")"
] | [
47,
4
] | [
51,
94
] | python | en | ['en', 'error', 'th'] | False |
ListFilter.expected_parameters | (self) |
Return the list of parameter names that are expected from the
request's query string and that will be used by this filter.
|
Return the list of parameter names that are expected from the
request's query string and that will be used by this filter.
| def expected_parameters(self):
"""
Return the list of parameter names that are expected from the
request's query string and that will be used by this filter.
"""
raise NotImplementedError('subclasses of ListFilter must provide an expected_parameters() method') | [
"def",
"expected_parameters",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of ListFilter must provide an expected_parameters() method'",
")"
] | [
53,
4
] | [
58,
106
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.