repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
dr-leo/pandaSDMX | pandasdmx/reader/sdmxjson.py | Reader.write_source | def write_source(self, filename):
'''
Save source to file by calling `write` on the root element.
'''
with open(filename, 'w') as fp:
return json.dump(self.message._elem, fp, indent=4, sort_keys=True) | python | def write_source(self, filename):
'''
Save source to file by calling `write` on the root element.
'''
with open(filename, 'w') as fp:
return json.dump(self.message._elem, fp, indent=4, sort_keys=True) | [
"def",
"write_source",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"fp",
":",
"return",
"json",
".",
"dump",
"(",
"self",
".",
"message",
".",
"_elem",
",",
"fp",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
")"
]
| Save source to file by calling `write` on the root element. | [
"Save",
"source",
"to",
"file",
"by",
"calling",
"write",
"on",
"the",
"root",
"element",
"."
]
| 71dd81ebb0d5169e5adcb8b52d516573d193f2d6 | https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/reader/sdmxjson.py#L86-L91 | train |
dr-leo/pandaSDMX | pandasdmx/reader/sdmxml.py | Reader.write_source | def write_source(self, filename):
'''
Save XML source to file by calling `write` on the root element.
'''
return self.message._elem.getroottree().write(filename, encoding='utf8') | python | def write_source(self, filename):
'''
Save XML source to file by calling `write` on the root element.
'''
return self.message._elem.getroottree().write(filename, encoding='utf8') | [
"def",
"write_source",
"(",
"self",
",",
"filename",
")",
":",
"return",
"self",
".",
"message",
".",
"_elem",
".",
"getroottree",
"(",
")",
".",
"write",
"(",
"filename",
",",
"encoding",
"=",
"'utf8'",
")"
]
| Save XML source to file by calling `write` on the root element. | [
"Save",
"XML",
"source",
"to",
"file",
"by",
"calling",
"write",
"on",
"the",
"root",
"element",
"."
]
| 71dd81ebb0d5169e5adcb8b52d516573d193f2d6 | https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/reader/sdmxml.py#L52-L56 | train |
dr-leo/pandaSDMX | pandasdmx/model.py | Series.group_attrib | def group_attrib(self):
'''
return a namedtuple containing all attributes attached
to groups of which the given series is a member
for each group of which the series is a member
'''
group_attributes = [g.attrib for g in self.dataset.groups if self in g]
if group_attributes:
return concat_namedtuples(*group_attributes) | python | def group_attrib(self):
'''
return a namedtuple containing all attributes attached
to groups of which the given series is a member
for each group of which the series is a member
'''
group_attributes = [g.attrib for g in self.dataset.groups if self in g]
if group_attributes:
return concat_namedtuples(*group_attributes) | [
"def",
"group_attrib",
"(",
"self",
")",
":",
"group_attributes",
"=",
"[",
"g",
".",
"attrib",
"for",
"g",
"in",
"self",
".",
"dataset",
".",
"groups",
"if",
"self",
"in",
"g",
"]",
"if",
"group_attributes",
":",
"return",
"concat_namedtuples",
"(",
"*",
"group_attributes",
")"
]
| return a namedtuple containing all attributes attached
to groups of which the given series is a member
for each group of which the series is a member | [
"return",
"a",
"namedtuple",
"containing",
"all",
"attributes",
"attached",
"to",
"groups",
"of",
"which",
"the",
"given",
"series",
"is",
"a",
"member",
"for",
"each",
"group",
"of",
"which",
"the",
"series",
"is",
"a",
"member"
]
| 71dd81ebb0d5169e5adcb8b52d516573d193f2d6 | https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/model.py#L632-L640 | train |
dr-leo/pandaSDMX | pandasdmx/reader/__init__.py | BaseReader.read_instance | def read_instance(self, cls, sdmxobj, offset=None, first_only=True):
'''
If cls in _paths and matches,
return an instance of cls with the first XML element,
or, if first_only is False, a list of cls instances
for all elements found,
If no matches were found, return None.
'''
if offset:
try:
base = self._paths[offset](sdmxobj._elem)[0]
except IndexError:
return None
else:
base = sdmxobj._elem
result = self._paths[cls](base)
if result:
if first_only:
return cls(self, result[0])
else:
return [cls(self, i) for i in result] | python | def read_instance(self, cls, sdmxobj, offset=None, first_only=True):
'''
If cls in _paths and matches,
return an instance of cls with the first XML element,
or, if first_only is False, a list of cls instances
for all elements found,
If no matches were found, return None.
'''
if offset:
try:
base = self._paths[offset](sdmxobj._elem)[0]
except IndexError:
return None
else:
base = sdmxobj._elem
result = self._paths[cls](base)
if result:
if first_only:
return cls(self, result[0])
else:
return [cls(self, i) for i in result] | [
"def",
"read_instance",
"(",
"self",
",",
"cls",
",",
"sdmxobj",
",",
"offset",
"=",
"None",
",",
"first_only",
"=",
"True",
")",
":",
"if",
"offset",
":",
"try",
":",
"base",
"=",
"self",
".",
"_paths",
"[",
"offset",
"]",
"(",
"sdmxobj",
".",
"_elem",
")",
"[",
"0",
"]",
"except",
"IndexError",
":",
"return",
"None",
"else",
":",
"base",
"=",
"sdmxobj",
".",
"_elem",
"result",
"=",
"self",
".",
"_paths",
"[",
"cls",
"]",
"(",
"base",
")",
"if",
"result",
":",
"if",
"first_only",
":",
"return",
"cls",
"(",
"self",
",",
"result",
"[",
"0",
"]",
")",
"else",
":",
"return",
"[",
"cls",
"(",
"self",
",",
"i",
")",
"for",
"i",
"in",
"result",
"]"
]
| If cls in _paths and matches,
return an instance of cls with the first XML element,
or, if first_only is False, a list of cls instances
for all elements found,
If no matches were found, return None. | [
"If",
"cls",
"in",
"_paths",
"and",
"matches",
"return",
"an",
"instance",
"of",
"cls",
"with",
"the",
"first",
"XML",
"element",
"or",
"if",
"first_only",
"is",
"False",
"a",
"list",
"of",
"cls",
"instances",
"for",
"all",
"elements",
"found",
"If",
"no",
"matches",
"were",
"found",
"return",
"None",
"."
]
| 71dd81ebb0d5169e5adcb8b52d516573d193f2d6 | https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/reader/__init__.py#L54-L74 | train |
dr-leo/pandaSDMX | pandasdmx/api.py | Request.load_agency_profile | def load_agency_profile(cls, source):
'''
Classmethod loading metadata on a data provider. ``source`` must
be a json-formated string or file-like object describing one or more data providers
(URL of the SDMX web API, resource types etc.
The dict ``Request._agencies`` is updated with the metadata from the
source.
Returns None
'''
if not isinstance(source, str_type):
# so it must be a text file
source = source.read()
new_agencies = json.loads(source)
cls._agencies.update(new_agencies) | python | def load_agency_profile(cls, source):
'''
Classmethod loading metadata on a data provider. ``source`` must
be a json-formated string or file-like object describing one or more data providers
(URL of the SDMX web API, resource types etc.
The dict ``Request._agencies`` is updated with the metadata from the
source.
Returns None
'''
if not isinstance(source, str_type):
# so it must be a text file
source = source.read()
new_agencies = json.loads(source)
cls._agencies.update(new_agencies) | [
"def",
"load_agency_profile",
"(",
"cls",
",",
"source",
")",
":",
"if",
"not",
"isinstance",
"(",
"source",
",",
"str_type",
")",
":",
"# so it must be a text file",
"source",
"=",
"source",
".",
"read",
"(",
")",
"new_agencies",
"=",
"json",
".",
"loads",
"(",
"source",
")",
"cls",
".",
"_agencies",
".",
"update",
"(",
"new_agencies",
")"
]
| Classmethod loading metadata on a data provider. ``source`` must
be a json-formated string or file-like object describing one or more data providers
(URL of the SDMX web API, resource types etc.
The dict ``Request._agencies`` is updated with the metadata from the
source.
Returns None | [
"Classmethod",
"loading",
"metadata",
"on",
"a",
"data",
"provider",
".",
"source",
"must",
"be",
"a",
"json",
"-",
"formated",
"string",
"or",
"file",
"-",
"like",
"object",
"describing",
"one",
"or",
"more",
"data",
"providers",
"(",
"URL",
"of",
"the",
"SDMX",
"web",
"API",
"resource",
"types",
"etc",
".",
"The",
"dict",
"Request",
".",
"_agencies",
"is",
"updated",
"with",
"the",
"metadata",
"from",
"the",
"source",
"."
]
| 71dd81ebb0d5169e5adcb8b52d516573d193f2d6 | https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/api.py#L63-L77 | train |
dr-leo/pandaSDMX | pandasdmx/api.py | Request.series_keys | def series_keys(self, flow_id, cache=True):
'''
Get an empty dataset with all possible series keys.
Return a pandas DataFrame. Each
column represents a dimension, each row
a series key of datasets of
the given dataflow.
'''
# Check if requested series keys are already cached
cache_id = 'series_keys_' + flow_id
if cache_id in self.cache:
return self.cache[cache_id]
else:
# download an empty dataset with all available series keys
resp = self.data(flow_id, params={'detail': 'serieskeysonly'})
l = list(s.key for s in resp.data.series)
df = PD.DataFrame(l, columns=l[0]._fields, dtype='category')
if cache:
self.cache[cache_id] = df
return df | python | def series_keys(self, flow_id, cache=True):
'''
Get an empty dataset with all possible series keys.
Return a pandas DataFrame. Each
column represents a dimension, each row
a series key of datasets of
the given dataflow.
'''
# Check if requested series keys are already cached
cache_id = 'series_keys_' + flow_id
if cache_id in self.cache:
return self.cache[cache_id]
else:
# download an empty dataset with all available series keys
resp = self.data(flow_id, params={'detail': 'serieskeysonly'})
l = list(s.key for s in resp.data.series)
df = PD.DataFrame(l, columns=l[0]._fields, dtype='category')
if cache:
self.cache[cache_id] = df
return df | [
"def",
"series_keys",
"(",
"self",
",",
"flow_id",
",",
"cache",
"=",
"True",
")",
":",
"# Check if requested series keys are already cached",
"cache_id",
"=",
"'series_keys_'",
"+",
"flow_id",
"if",
"cache_id",
"in",
"self",
".",
"cache",
":",
"return",
"self",
".",
"cache",
"[",
"cache_id",
"]",
"else",
":",
"# download an empty dataset with all available series keys",
"resp",
"=",
"self",
".",
"data",
"(",
"flow_id",
",",
"params",
"=",
"{",
"'detail'",
":",
"'serieskeysonly'",
"}",
")",
"l",
"=",
"list",
"(",
"s",
".",
"key",
"for",
"s",
"in",
"resp",
".",
"data",
".",
"series",
")",
"df",
"=",
"PD",
".",
"DataFrame",
"(",
"l",
",",
"columns",
"=",
"l",
"[",
"0",
"]",
".",
"_fields",
",",
"dtype",
"=",
"'category'",
")",
"if",
"cache",
":",
"self",
".",
"cache",
"[",
"cache_id",
"]",
"=",
"df",
"return",
"df"
]
| Get an empty dataset with all possible series keys.
Return a pandas DataFrame. Each
column represents a dimension, each row
a series key of datasets of
the given dataflow. | [
"Get",
"an",
"empty",
"dataset",
"with",
"all",
"possible",
"series",
"keys",
"."
]
| 71dd81ebb0d5169e5adcb8b52d516573d193f2d6 | https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/api.py#L150-L170 | train |
dr-leo/pandaSDMX | pandasdmx/api.py | Request.preview_data | def preview_data(self, flow_id, key=None, count=True, total=True):
'''
Get keys or number of series for a prospective dataset query allowing for
keys with multiple values per dimension.
It downloads the complete list of series keys for a dataflow rather than using constraints and DSD. This feature is,
however, not supported by all data providers.
ECB and UNSD are known to work.
Args:
flow_id(str): dataflow id
key(dict): optional key mapping dimension names to values or lists of values.
Must have been validated before. It is not checked if key values
are actually valid dimension names and values. Default: {}
count(bool): if True (default), return the number of series
of the dataset designated by flow_id and key. If False,
the actual keys are returned as a pandas DataFrame or dict of dataframes, depending on
the value of 'total'.
total(bool): if True (default), return the aggregate number
of series or a single dataframe (depending on the value of 'count'). If False,
return a dict mapping keys to dataframes of series keys.
E.g., if key={'COUNTRY':'IT+CA+AU'}, the dict will
have 3 items describing the series keys for each country
respectively. If 'count' is True, dict values will be int rather than
PD.DataFrame.
'''
all_keys = self.series_keys(flow_id)
# Handle the special case that no key is provided
if not key:
if count:
return all_keys.shape[0]
else:
return all_keys
# So there is a key specifying at least one dimension value.
# Wrap single values in 1-elem list for uniform treatment
key_l = {k: [v] if isinstance(v, str_type) else v
for k, v in key.items()}
# order dim_names that are present in the key
dim_names = [k for k in all_keys if k in key]
# Drop columns that are not in the key
key_df = all_keys.loc[:, dim_names]
if total:
# DataFrame with matching series keys
bool_series = reduce(
and_, (key_df.isin(key_l)[col] for col in dim_names))
if count:
return bool_series.value_counts()[True]
else:
return all_keys[bool_series]
else:
# Dict of value combinations as dict keys
key_product = product(*(key_l[k] for k in dim_names))
# Replace key tuples by namedtuples
PartialKey = namedtuple_factory('PartialKey', dim_names)
matches = {PartialKey(k): reduce(and_, (key_df.isin({k1: [v1]
for k1, v1 in zip(dim_names, k)})[col]
for col in dim_names))
for k in key_product}
if not count:
# dict mapping each key to DataFrame with selected key-set
return {k: all_keys[v] for k, v in matches.items()}
else:
# Number of series per key
return {k: v.value_counts()[True] for k, v in matches.items()} | python | def preview_data(self, flow_id, key=None, count=True, total=True):
'''
Get keys or number of series for a prospective dataset query allowing for
keys with multiple values per dimension.
It downloads the complete list of series keys for a dataflow rather than using constraints and DSD. This feature is,
however, not supported by all data providers.
ECB and UNSD are known to work.
Args:
flow_id(str): dataflow id
key(dict): optional key mapping dimension names to values or lists of values.
Must have been validated before. It is not checked if key values
are actually valid dimension names and values. Default: {}
count(bool): if True (default), return the number of series
of the dataset designated by flow_id and key. If False,
the actual keys are returned as a pandas DataFrame or dict of dataframes, depending on
the value of 'total'.
total(bool): if True (default), return the aggregate number
of series or a single dataframe (depending on the value of 'count'). If False,
return a dict mapping keys to dataframes of series keys.
E.g., if key={'COUNTRY':'IT+CA+AU'}, the dict will
have 3 items describing the series keys for each country
respectively. If 'count' is True, dict values will be int rather than
PD.DataFrame.
'''
all_keys = self.series_keys(flow_id)
# Handle the special case that no key is provided
if not key:
if count:
return all_keys.shape[0]
else:
return all_keys
# So there is a key specifying at least one dimension value.
# Wrap single values in 1-elem list for uniform treatment
key_l = {k: [v] if isinstance(v, str_type) else v
for k, v in key.items()}
# order dim_names that are present in the key
dim_names = [k for k in all_keys if k in key]
# Drop columns that are not in the key
key_df = all_keys.loc[:, dim_names]
if total:
# DataFrame with matching series keys
bool_series = reduce(
and_, (key_df.isin(key_l)[col] for col in dim_names))
if count:
return bool_series.value_counts()[True]
else:
return all_keys[bool_series]
else:
# Dict of value combinations as dict keys
key_product = product(*(key_l[k] for k in dim_names))
# Replace key tuples by namedtuples
PartialKey = namedtuple_factory('PartialKey', dim_names)
matches = {PartialKey(k): reduce(and_, (key_df.isin({k1: [v1]
for k1, v1 in zip(dim_names, k)})[col]
for col in dim_names))
for k in key_product}
if not count:
# dict mapping each key to DataFrame with selected key-set
return {k: all_keys[v] for k, v in matches.items()}
else:
# Number of series per key
return {k: v.value_counts()[True] for k, v in matches.items()} | [
"def",
"preview_data",
"(",
"self",
",",
"flow_id",
",",
"key",
"=",
"None",
",",
"count",
"=",
"True",
",",
"total",
"=",
"True",
")",
":",
"all_keys",
"=",
"self",
".",
"series_keys",
"(",
"flow_id",
")",
"# Handle the special case that no key is provided",
"if",
"not",
"key",
":",
"if",
"count",
":",
"return",
"all_keys",
".",
"shape",
"[",
"0",
"]",
"else",
":",
"return",
"all_keys",
"# So there is a key specifying at least one dimension value.",
"# Wrap single values in 1-elem list for uniform treatment",
"key_l",
"=",
"{",
"k",
":",
"[",
"v",
"]",
"if",
"isinstance",
"(",
"v",
",",
"str_type",
")",
"else",
"v",
"for",
"k",
",",
"v",
"in",
"key",
".",
"items",
"(",
")",
"}",
"# order dim_names that are present in the key",
"dim_names",
"=",
"[",
"k",
"for",
"k",
"in",
"all_keys",
"if",
"k",
"in",
"key",
"]",
"# Drop columns that are not in the key",
"key_df",
"=",
"all_keys",
".",
"loc",
"[",
":",
",",
"dim_names",
"]",
"if",
"total",
":",
"# DataFrame with matching series keys",
"bool_series",
"=",
"reduce",
"(",
"and_",
",",
"(",
"key_df",
".",
"isin",
"(",
"key_l",
")",
"[",
"col",
"]",
"for",
"col",
"in",
"dim_names",
")",
")",
"if",
"count",
":",
"return",
"bool_series",
".",
"value_counts",
"(",
")",
"[",
"True",
"]",
"else",
":",
"return",
"all_keys",
"[",
"bool_series",
"]",
"else",
":",
"# Dict of value combinations as dict keys",
"key_product",
"=",
"product",
"(",
"*",
"(",
"key_l",
"[",
"k",
"]",
"for",
"k",
"in",
"dim_names",
")",
")",
"# Replace key tuples by namedtuples",
"PartialKey",
"=",
"namedtuple_factory",
"(",
"'PartialKey'",
",",
"dim_names",
")",
"matches",
"=",
"{",
"PartialKey",
"(",
"k",
")",
":",
"reduce",
"(",
"and_",
",",
"(",
"key_df",
".",
"isin",
"(",
"{",
"k1",
":",
"[",
"v1",
"]",
"for",
"k1",
",",
"v1",
"in",
"zip",
"(",
"dim_names",
",",
"k",
")",
"}",
")",
"[",
"col",
"]",
"for",
"col",
"in",
"dim_names",
")",
")",
"for",
"k",
"in",
"key_product",
"}",
"if",
"not",
"count",
":",
"# dict mapping each key to DataFrame with selected key-set",
"return",
"{",
"k",
":",
"all_keys",
"[",
"v",
"]",
"for",
"k",
",",
"v",
"in",
"matches",
".",
"items",
"(",
")",
"}",
"else",
":",
"# Number of series per key",
"return",
"{",
"k",
":",
"v",
".",
"value_counts",
"(",
")",
"[",
"True",
"]",
"for",
"k",
",",
"v",
"in",
"matches",
".",
"items",
"(",
")",
"}"
]
| Get keys or number of series for a prospective dataset query allowing for
keys with multiple values per dimension.
It downloads the complete list of series keys for a dataflow rather than using constraints and DSD. This feature is,
however, not supported by all data providers.
ECB and UNSD are known to work.
Args:
flow_id(str): dataflow id
key(dict): optional key mapping dimension names to values or lists of values.
Must have been validated before. It is not checked if key values
are actually valid dimension names and values. Default: {}
count(bool): if True (default), return the number of series
of the dataset designated by flow_id and key. If False,
the actual keys are returned as a pandas DataFrame or dict of dataframes, depending on
the value of 'total'.
total(bool): if True (default), return the aggregate number
of series or a single dataframe (depending on the value of 'count'). If False,
return a dict mapping keys to dataframes of series keys.
E.g., if key={'COUNTRY':'IT+CA+AU'}, the dict will
have 3 items describing the series keys for each country
respectively. If 'count' is True, dict values will be int rather than
PD.DataFrame. | [
"Get",
"keys",
"or",
"number",
"of",
"series",
"for",
"a",
"prospective",
"dataset",
"query",
"allowing",
"for",
"keys",
"with",
"multiple",
"values",
"per",
"dimension",
".",
"It",
"downloads",
"the",
"complete",
"list",
"of",
"series",
"keys",
"for",
"a",
"dataflow",
"rather",
"than",
"using",
"constraints",
"and",
"DSD",
".",
"This",
"feature",
"is",
"however",
"not",
"supported",
"by",
"all",
"data",
"providers",
".",
"ECB",
"and",
"UNSD",
"are",
"known",
"to",
"work",
"."
]
| 71dd81ebb0d5169e5adcb8b52d516573d193f2d6 | https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/api.py#L495-L564 | train |
dr-leo/pandaSDMX | pandasdmx/api.py | Response.write | def write(self, source=None, **kwargs):
'''Wrappe r to call the writer's write method if present.
Args:
source(pandasdmx.model.Message, iterable): stuff to be written.
If a :class:`pandasdmx.model.Message` is given, the writer
itself must determine what to write unless specified in the
keyword arguments. If an iterable is given,
the writer should write each item. Keyword arguments may
specify what to do with the output depending on the writer's API. Defaults to self.msg.
Returns:
type: anything the writer returns.
'''
if not source:
source = self.msg
return self._writer.write(source=source, **kwargs) | python | def write(self, source=None, **kwargs):
'''Wrappe r to call the writer's write method if present.
Args:
source(pandasdmx.model.Message, iterable): stuff to be written.
If a :class:`pandasdmx.model.Message` is given, the writer
itself must determine what to write unless specified in the
keyword arguments. If an iterable is given,
the writer should write each item. Keyword arguments may
specify what to do with the output depending on the writer's API. Defaults to self.msg.
Returns:
type: anything the writer returns.
'''
if not source:
source = self.msg
return self._writer.write(source=source, **kwargs) | [
"def",
"write",
"(",
"self",
",",
"source",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"source",
":",
"source",
"=",
"self",
".",
"msg",
"return",
"self",
".",
"_writer",
".",
"write",
"(",
"source",
"=",
"source",
",",
"*",
"*",
"kwargs",
")"
]
| Wrappe r to call the writer's write method if present.
Args:
source(pandasdmx.model.Message, iterable): stuff to be written.
If a :class:`pandasdmx.model.Message` is given, the writer
itself must determine what to write unless specified in the
keyword arguments. If an iterable is given,
the writer should write each item. Keyword arguments may
specify what to do with the output depending on the writer's API. Defaults to self.msg.
Returns:
type: anything the writer returns. | [
"Wrappe",
"r",
"to",
"call",
"the",
"writer",
"s",
"write",
"method",
"if",
"present",
"."
]
| 71dd81ebb0d5169e5adcb8b52d516573d193f2d6 | https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/api.py#L618-L635 | train |
dropbox/pyannotate | pyannotate_tools/annotations/parse.py | parse_json | def parse_json(path):
# type: (str) -> List[FunctionInfo]
"""Deserialize a JSON file containing runtime collected types.
The input JSON is expected to to have a list of RawEntry items.
"""
with open(path) as f:
data = json.load(f) # type: List[RawEntry]
result = []
def assert_type(value, typ):
# type: (object, type) -> None
assert isinstance(value, typ), '%s: Unexpected type %r' % (path, type(value).__name__)
def assert_dict_item(dictionary, key, typ):
# type: (Mapping[Any, Any], str, type) -> None
assert key in dictionary, '%s: Missing dictionary key %r' % (path, key)
value = dictionary[key]
assert isinstance(value, typ), '%s: Unexpected type %r for key %r' % (
path, type(value).__name__, key)
assert_type(data, list)
for item in data:
assert_type(item, dict)
assert_dict_item(item, 'path', Text)
assert_dict_item(item, 'line', int)
assert_dict_item(item, 'func_name', Text)
assert_dict_item(item, 'type_comments', list)
for comment in item['type_comments']:
assert_type(comment, Text)
assert_type(item['samples'], int)
info = FunctionInfo(encode(item['path']),
item['line'],
encode(item['func_name']),
[encode(comment) for comment in item['type_comments']],
item['samples'])
result.append(info)
return result | python | def parse_json(path):
# type: (str) -> List[FunctionInfo]
"""Deserialize a JSON file containing runtime collected types.
The input JSON is expected to to have a list of RawEntry items.
"""
with open(path) as f:
data = json.load(f) # type: List[RawEntry]
result = []
def assert_type(value, typ):
# type: (object, type) -> None
assert isinstance(value, typ), '%s: Unexpected type %r' % (path, type(value).__name__)
def assert_dict_item(dictionary, key, typ):
# type: (Mapping[Any, Any], str, type) -> None
assert key in dictionary, '%s: Missing dictionary key %r' % (path, key)
value = dictionary[key]
assert isinstance(value, typ), '%s: Unexpected type %r for key %r' % (
path, type(value).__name__, key)
assert_type(data, list)
for item in data:
assert_type(item, dict)
assert_dict_item(item, 'path', Text)
assert_dict_item(item, 'line', int)
assert_dict_item(item, 'func_name', Text)
assert_dict_item(item, 'type_comments', list)
for comment in item['type_comments']:
assert_type(comment, Text)
assert_type(item['samples'], int)
info = FunctionInfo(encode(item['path']),
item['line'],
encode(item['func_name']),
[encode(comment) for comment in item['type_comments']],
item['samples'])
result.append(info)
return result | [
"def",
"parse_json",
"(",
"path",
")",
":",
"# type: (str) -> List[FunctionInfo]",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"data",
"=",
"json",
".",
"load",
"(",
"f",
")",
"# type: List[RawEntry]",
"result",
"=",
"[",
"]",
"def",
"assert_type",
"(",
"value",
",",
"typ",
")",
":",
"# type: (object, type) -> None",
"assert",
"isinstance",
"(",
"value",
",",
"typ",
")",
",",
"'%s: Unexpected type %r'",
"%",
"(",
"path",
",",
"type",
"(",
"value",
")",
".",
"__name__",
")",
"def",
"assert_dict_item",
"(",
"dictionary",
",",
"key",
",",
"typ",
")",
":",
"# type: (Mapping[Any, Any], str, type) -> None",
"assert",
"key",
"in",
"dictionary",
",",
"'%s: Missing dictionary key %r'",
"%",
"(",
"path",
",",
"key",
")",
"value",
"=",
"dictionary",
"[",
"key",
"]",
"assert",
"isinstance",
"(",
"value",
",",
"typ",
")",
",",
"'%s: Unexpected type %r for key %r'",
"%",
"(",
"path",
",",
"type",
"(",
"value",
")",
".",
"__name__",
",",
"key",
")",
"assert_type",
"(",
"data",
",",
"list",
")",
"for",
"item",
"in",
"data",
":",
"assert_type",
"(",
"item",
",",
"dict",
")",
"assert_dict_item",
"(",
"item",
",",
"'path'",
",",
"Text",
")",
"assert_dict_item",
"(",
"item",
",",
"'line'",
",",
"int",
")",
"assert_dict_item",
"(",
"item",
",",
"'func_name'",
",",
"Text",
")",
"assert_dict_item",
"(",
"item",
",",
"'type_comments'",
",",
"list",
")",
"for",
"comment",
"in",
"item",
"[",
"'type_comments'",
"]",
":",
"assert_type",
"(",
"comment",
",",
"Text",
")",
"assert_type",
"(",
"item",
"[",
"'samples'",
"]",
",",
"int",
")",
"info",
"=",
"FunctionInfo",
"(",
"encode",
"(",
"item",
"[",
"'path'",
"]",
")",
",",
"item",
"[",
"'line'",
"]",
",",
"encode",
"(",
"item",
"[",
"'func_name'",
"]",
")",
",",
"[",
"encode",
"(",
"comment",
")",
"for",
"comment",
"in",
"item",
"[",
"'type_comments'",
"]",
"]",
",",
"item",
"[",
"'samples'",
"]",
")",
"result",
".",
"append",
"(",
"info",
")",
"return",
"result"
]
| Deserialize a JSON file containing runtime collected types.
The input JSON is expected to to have a list of RawEntry items. | [
"Deserialize",
"a",
"JSON",
"file",
"containing",
"runtime",
"collected",
"types",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/parse.py#L96-L133 | train |
dropbox/pyannotate | pyannotate_tools/annotations/parse.py | tokenize | def tokenize(s):
# type: (str) -> List[Token]
"""Translate a type comment into a list of tokens."""
original = s
tokens = [] # type: List[Token]
while True:
if not s:
tokens.append(End())
return tokens
elif s[0] == ' ':
s = s[1:]
elif s[0] in '()[],*':
tokens.append(Separator(s[0]))
s = s[1:]
elif s[:2] == '->':
tokens.append(Separator('->'))
s = s[2:]
else:
m = re.match(r'[-\w]+(\s*(\.|:)\s*[-/\w]*)*', s)
if not m:
raise ParseError(original)
fullname = m.group(0)
fullname = fullname.replace(' ', '')
if fullname in TYPE_FIXUPS:
fullname = TYPE_FIXUPS[fullname]
# pytz creates classes with the name of the timezone being used:
# https://github.com/stub42/pytz/blob/f55399cddbef67c56db1b83e0939ecc1e276cf42/src/pytz/tzfile.py#L120-L123
# This causes pyannotates to crash as it's invalid to have a class
# name with a `/` in it (e.g. "pytz.tzfile.America/Los_Angeles")
if fullname.startswith('pytz.tzfile.'):
fullname = 'datetime.tzinfo'
if '-' in fullname or '/' in fullname:
# Not a valid Python name; there are many places that
# generate these, so we just substitute Any rather
# than crashing.
fullname = 'Any'
tokens.append(DottedName(fullname))
s = s[len(m.group(0)):] | python | def tokenize(s):
# type: (str) -> List[Token]
"""Translate a type comment into a list of tokens."""
original = s
tokens = [] # type: List[Token]
while True:
if not s:
tokens.append(End())
return tokens
elif s[0] == ' ':
s = s[1:]
elif s[0] in '()[],*':
tokens.append(Separator(s[0]))
s = s[1:]
elif s[:2] == '->':
tokens.append(Separator('->'))
s = s[2:]
else:
m = re.match(r'[-\w]+(\s*(\.|:)\s*[-/\w]*)*', s)
if not m:
raise ParseError(original)
fullname = m.group(0)
fullname = fullname.replace(' ', '')
if fullname in TYPE_FIXUPS:
fullname = TYPE_FIXUPS[fullname]
# pytz creates classes with the name of the timezone being used:
# https://github.com/stub42/pytz/blob/f55399cddbef67c56db1b83e0939ecc1e276cf42/src/pytz/tzfile.py#L120-L123
# This causes pyannotates to crash as it's invalid to have a class
# name with a `/` in it (e.g. "pytz.tzfile.America/Los_Angeles")
if fullname.startswith('pytz.tzfile.'):
fullname = 'datetime.tzinfo'
if '-' in fullname or '/' in fullname:
# Not a valid Python name; there are many places that
# generate these, so we just substitute Any rather
# than crashing.
fullname = 'Any'
tokens.append(DottedName(fullname))
s = s[len(m.group(0)):] | [
"def",
"tokenize",
"(",
"s",
")",
":",
"# type: (str) -> List[Token]",
"original",
"=",
"s",
"tokens",
"=",
"[",
"]",
"# type: List[Token]",
"while",
"True",
":",
"if",
"not",
"s",
":",
"tokens",
".",
"append",
"(",
"End",
"(",
")",
")",
"return",
"tokens",
"elif",
"s",
"[",
"0",
"]",
"==",
"' '",
":",
"s",
"=",
"s",
"[",
"1",
":",
"]",
"elif",
"s",
"[",
"0",
"]",
"in",
"'()[],*'",
":",
"tokens",
".",
"append",
"(",
"Separator",
"(",
"s",
"[",
"0",
"]",
")",
")",
"s",
"=",
"s",
"[",
"1",
":",
"]",
"elif",
"s",
"[",
":",
"2",
"]",
"==",
"'->'",
":",
"tokens",
".",
"append",
"(",
"Separator",
"(",
"'->'",
")",
")",
"s",
"=",
"s",
"[",
"2",
":",
"]",
"else",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r'[-\\w]+(\\s*(\\.|:)\\s*[-/\\w]*)*'",
",",
"s",
")",
"if",
"not",
"m",
":",
"raise",
"ParseError",
"(",
"original",
")",
"fullname",
"=",
"m",
".",
"group",
"(",
"0",
")",
"fullname",
"=",
"fullname",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"if",
"fullname",
"in",
"TYPE_FIXUPS",
":",
"fullname",
"=",
"TYPE_FIXUPS",
"[",
"fullname",
"]",
"# pytz creates classes with the name of the timezone being used:",
"# https://github.com/stub42/pytz/blob/f55399cddbef67c56db1b83e0939ecc1e276cf42/src/pytz/tzfile.py#L120-L123",
"# This causes pyannotates to crash as it's invalid to have a class",
"# name with a `/` in it (e.g. \"pytz.tzfile.America/Los_Angeles\")",
"if",
"fullname",
".",
"startswith",
"(",
"'pytz.tzfile.'",
")",
":",
"fullname",
"=",
"'datetime.tzinfo'",
"if",
"'-'",
"in",
"fullname",
"or",
"'/'",
"in",
"fullname",
":",
"# Not a valid Python name; there are many places that",
"# generate these, so we just substitute Any rather",
"# than crashing.",
"fullname",
"=",
"'Any'",
"tokens",
".",
"append",
"(",
"DottedName",
"(",
"fullname",
")",
")",
"s",
"=",
"s",
"[",
"len",
"(",
"m",
".",
"group",
"(",
"0",
")",
")",
":",
"]"
]
| Translate a type comment into a list of tokens. | [
"Translate",
"a",
"type",
"comment",
"into",
"a",
"list",
"of",
"tokens",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/parse.py#L173-L210 | train |
dropbox/pyannotate | pyannotate_tools/annotations/main.py | generate_annotations_json_string | def generate_annotations_json_string(source_path, only_simple=False):
# type: (str, bool) -> List[FunctionData]
"""Produce annotation data JSON file from a JSON file with runtime-collected types.
Data formats:
* The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items.
* The output JSON is a list of FunctionData items.
"""
items = parse_json(source_path)
results = []
for item in items:
signature = unify_type_comments(item.type_comments)
if is_signature_simple(signature) or not only_simple:
data = {
'path': item.path,
'line': item.line,
'func_name': item.func_name,
'signature': signature,
'samples': item.samples
} # type: FunctionData
results.append(data)
return results | python | def generate_annotations_json_string(source_path, only_simple=False):
# type: (str, bool) -> List[FunctionData]
"""Produce annotation data JSON file from a JSON file with runtime-collected types.
Data formats:
* The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items.
* The output JSON is a list of FunctionData items.
"""
items = parse_json(source_path)
results = []
for item in items:
signature = unify_type_comments(item.type_comments)
if is_signature_simple(signature) or not only_simple:
data = {
'path': item.path,
'line': item.line,
'func_name': item.func_name,
'signature': signature,
'samples': item.samples
} # type: FunctionData
results.append(data)
return results | [
"def",
"generate_annotations_json_string",
"(",
"source_path",
",",
"only_simple",
"=",
"False",
")",
":",
"# type: (str, bool) -> List[FunctionData]",
"items",
"=",
"parse_json",
"(",
"source_path",
")",
"results",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"signature",
"=",
"unify_type_comments",
"(",
"item",
".",
"type_comments",
")",
"if",
"is_signature_simple",
"(",
"signature",
")",
"or",
"not",
"only_simple",
":",
"data",
"=",
"{",
"'path'",
":",
"item",
".",
"path",
",",
"'line'",
":",
"item",
".",
"line",
",",
"'func_name'",
":",
"item",
".",
"func_name",
",",
"'signature'",
":",
"signature",
",",
"'samples'",
":",
"item",
".",
"samples",
"}",
"# type: FunctionData",
"results",
".",
"append",
"(",
"data",
")",
"return",
"results"
]
| Produce annotation data JSON file from a JSON file with runtime-collected types.
Data formats:
* The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items.
* The output JSON is a list of FunctionData items. | [
"Produce",
"annotation",
"data",
"JSON",
"file",
"from",
"a",
"JSON",
"file",
"with",
"runtime",
"-",
"collected",
"types",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/main.py#L48-L70 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | _my_hash | def _my_hash(arg_list):
# type: (List[Any]) -> int
"""Simple helper hash function"""
res = 0
for arg in arg_list:
res = res * 31 + hash(arg)
return res | python | def _my_hash(arg_list):
# type: (List[Any]) -> int
"""Simple helper hash function"""
res = 0
for arg in arg_list:
res = res * 31 + hash(arg)
return res | [
"def",
"_my_hash",
"(",
"arg_list",
")",
":",
"# type: (List[Any]) -> int",
"res",
"=",
"0",
"for",
"arg",
"in",
"arg_list",
":",
"res",
"=",
"res",
"*",
"31",
"+",
"hash",
"(",
"arg",
")",
"return",
"res"
]
| Simple helper hash function | [
"Simple",
"helper",
"hash",
"function"
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L69-L75 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | name_from_type | def name_from_type(type_):
# type: (InternalType) -> str
"""
Helper function to get PEP-484 compatible string representation of our internal types.
"""
if isinstance(type_, (DictType, ListType, TupleType, SetType, IteratorType)):
return repr(type_)
else:
if type_.__name__ != 'NoneType':
module = type_.__module__
if module in BUILTIN_MODULES or module == '<unknown>':
# Omit module prefix for known built-ins, for convenience. This
# makes unit tests for this module simpler.
# Also ignore '<uknown>' modules so pyannotate can parse these types
return type_.__name__
else:
name = getattr(type_, '__qualname__', None) or type_.__name__
delim = '.' if '.' not in name else ':'
return '%s%s%s' % (module, delim, name)
else:
return 'None' | python | def name_from_type(type_):
# type: (InternalType) -> str
"""
Helper function to get PEP-484 compatible string representation of our internal types.
"""
if isinstance(type_, (DictType, ListType, TupleType, SetType, IteratorType)):
return repr(type_)
else:
if type_.__name__ != 'NoneType':
module = type_.__module__
if module in BUILTIN_MODULES or module == '<unknown>':
# Omit module prefix for known built-ins, for convenience. This
# makes unit tests for this module simpler.
# Also ignore '<uknown>' modules so pyannotate can parse these types
return type_.__name__
else:
name = getattr(type_, '__qualname__', None) or type_.__name__
delim = '.' if '.' not in name else ':'
return '%s%s%s' % (module, delim, name)
else:
return 'None' | [
"def",
"name_from_type",
"(",
"type_",
")",
":",
"# type: (InternalType) -> str",
"if",
"isinstance",
"(",
"type_",
",",
"(",
"DictType",
",",
"ListType",
",",
"TupleType",
",",
"SetType",
",",
"IteratorType",
")",
")",
":",
"return",
"repr",
"(",
"type_",
")",
"else",
":",
"if",
"type_",
".",
"__name__",
"!=",
"'NoneType'",
":",
"module",
"=",
"type_",
".",
"__module__",
"if",
"module",
"in",
"BUILTIN_MODULES",
"or",
"module",
"==",
"'<unknown>'",
":",
"# Omit module prefix for known built-ins, for convenience. This",
"# makes unit tests for this module simpler.",
"# Also ignore '<uknown>' modules so pyannotate can parse these types",
"return",
"type_",
".",
"__name__",
"else",
":",
"name",
"=",
"getattr",
"(",
"type_",
",",
"'__qualname__'",
",",
"None",
")",
"or",
"type_",
".",
"__name__",
"delim",
"=",
"'.'",
"if",
"'.'",
"not",
"in",
"name",
"else",
"':'",
"return",
"'%s%s%s'",
"%",
"(",
"module",
",",
"delim",
",",
"name",
")",
"else",
":",
"return",
"'None'"
]
| Helper function to get PEP-484 compatible string representation of our internal types. | [
"Helper",
"function",
"to",
"get",
"PEP",
"-",
"484",
"compatible",
"string",
"representation",
"of",
"our",
"internal",
"types",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L417-L437 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | resolve_type | def resolve_type(arg):
# type: (object) -> InternalType
"""
Resolve object to one of our internal collection types or generic built-in type.
Args:
arg: object to resolve
"""
arg_type = type(arg)
if arg_type == list:
assert isinstance(arg, list) # this line helps mypy figure out types
sample = arg[:min(4, len(arg))]
tentative_type = TentativeType()
for sample_item in sample:
tentative_type.add(resolve_type(sample_item))
return ListType(tentative_type)
elif arg_type == set:
assert isinstance(arg, set) # this line helps mypy figure out types
sample = []
iterator = iter(arg)
for i in range(0, min(4, len(arg))):
sample.append(next(iterator))
tentative_type = TentativeType()
for sample_item in sample:
tentative_type.add(resolve_type(sample_item))
return SetType(tentative_type)
elif arg_type == FakeIterator:
assert isinstance(arg, FakeIterator) # this line helps mypy figure out types
sample = []
iterator = iter(arg)
for i in range(0, min(4, len(arg))):
sample.append(next(iterator))
tentative_type = TentativeType()
for sample_item in sample:
tentative_type.add(resolve_type(sample_item))
return IteratorType(tentative_type)
elif arg_type == tuple:
assert isinstance(arg, tuple) # this line helps mypy figure out types
sample = list(arg[:min(10, len(arg))])
return TupleType([resolve_type(sample_item) for sample_item in sample])
elif arg_type == dict:
assert isinstance(arg, dict) # this line helps mypy figure out types
key_tt = TentativeType()
val_tt = TentativeType()
for i, (k, v) in enumerate(iteritems(arg)):
if i > 4:
break
key_tt.add(resolve_type(k))
val_tt.add(resolve_type(v))
return DictType(key_tt, val_tt)
else:
return type(arg) | python | def resolve_type(arg):
# type: (object) -> InternalType
"""
Resolve object to one of our internal collection types or generic built-in type.
Args:
arg: object to resolve
"""
arg_type = type(arg)
if arg_type == list:
assert isinstance(arg, list) # this line helps mypy figure out types
sample = arg[:min(4, len(arg))]
tentative_type = TentativeType()
for sample_item in sample:
tentative_type.add(resolve_type(sample_item))
return ListType(tentative_type)
elif arg_type == set:
assert isinstance(arg, set) # this line helps mypy figure out types
sample = []
iterator = iter(arg)
for i in range(0, min(4, len(arg))):
sample.append(next(iterator))
tentative_type = TentativeType()
for sample_item in sample:
tentative_type.add(resolve_type(sample_item))
return SetType(tentative_type)
elif arg_type == FakeIterator:
assert isinstance(arg, FakeIterator) # this line helps mypy figure out types
sample = []
iterator = iter(arg)
for i in range(0, min(4, len(arg))):
sample.append(next(iterator))
tentative_type = TentativeType()
for sample_item in sample:
tentative_type.add(resolve_type(sample_item))
return IteratorType(tentative_type)
elif arg_type == tuple:
assert isinstance(arg, tuple) # this line helps mypy figure out types
sample = list(arg[:min(10, len(arg))])
return TupleType([resolve_type(sample_item) for sample_item in sample])
elif arg_type == dict:
assert isinstance(arg, dict) # this line helps mypy figure out types
key_tt = TentativeType()
val_tt = TentativeType()
for i, (k, v) in enumerate(iteritems(arg)):
if i > 4:
break
key_tt.add(resolve_type(k))
val_tt.add(resolve_type(v))
return DictType(key_tt, val_tt)
else:
return type(arg) | [
"def",
"resolve_type",
"(",
"arg",
")",
":",
"# type: (object) -> InternalType",
"arg_type",
"=",
"type",
"(",
"arg",
")",
"if",
"arg_type",
"==",
"list",
":",
"assert",
"isinstance",
"(",
"arg",
",",
"list",
")",
"# this line helps mypy figure out types",
"sample",
"=",
"arg",
"[",
":",
"min",
"(",
"4",
",",
"len",
"(",
"arg",
")",
")",
"]",
"tentative_type",
"=",
"TentativeType",
"(",
")",
"for",
"sample_item",
"in",
"sample",
":",
"tentative_type",
".",
"add",
"(",
"resolve_type",
"(",
"sample_item",
")",
")",
"return",
"ListType",
"(",
"tentative_type",
")",
"elif",
"arg_type",
"==",
"set",
":",
"assert",
"isinstance",
"(",
"arg",
",",
"set",
")",
"# this line helps mypy figure out types",
"sample",
"=",
"[",
"]",
"iterator",
"=",
"iter",
"(",
"arg",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"min",
"(",
"4",
",",
"len",
"(",
"arg",
")",
")",
")",
":",
"sample",
".",
"append",
"(",
"next",
"(",
"iterator",
")",
")",
"tentative_type",
"=",
"TentativeType",
"(",
")",
"for",
"sample_item",
"in",
"sample",
":",
"tentative_type",
".",
"add",
"(",
"resolve_type",
"(",
"sample_item",
")",
")",
"return",
"SetType",
"(",
"tentative_type",
")",
"elif",
"arg_type",
"==",
"FakeIterator",
":",
"assert",
"isinstance",
"(",
"arg",
",",
"FakeIterator",
")",
"# this line helps mypy figure out types",
"sample",
"=",
"[",
"]",
"iterator",
"=",
"iter",
"(",
"arg",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"min",
"(",
"4",
",",
"len",
"(",
"arg",
")",
")",
")",
":",
"sample",
".",
"append",
"(",
"next",
"(",
"iterator",
")",
")",
"tentative_type",
"=",
"TentativeType",
"(",
")",
"for",
"sample_item",
"in",
"sample",
":",
"tentative_type",
".",
"add",
"(",
"resolve_type",
"(",
"sample_item",
")",
")",
"return",
"IteratorType",
"(",
"tentative_type",
")",
"elif",
"arg_type",
"==",
"tuple",
":",
"assert",
"isinstance",
"(",
"arg",
",",
"tuple",
")",
"# this line helps mypy figure out types",
"sample",
"=",
"list",
"(",
"arg",
"[",
":",
"min",
"(",
"10",
",",
"len",
"(",
"arg",
")",
")",
"]",
")",
"return",
"TupleType",
"(",
"[",
"resolve_type",
"(",
"sample_item",
")",
"for",
"sample_item",
"in",
"sample",
"]",
")",
"elif",
"arg_type",
"==",
"dict",
":",
"assert",
"isinstance",
"(",
"arg",
",",
"dict",
")",
"# this line helps mypy figure out types",
"key_tt",
"=",
"TentativeType",
"(",
")",
"val_tt",
"=",
"TentativeType",
"(",
")",
"for",
"i",
",",
"(",
"k",
",",
"v",
")",
"in",
"enumerate",
"(",
"iteritems",
"(",
"arg",
")",
")",
":",
"if",
"i",
">",
"4",
":",
"break",
"key_tt",
".",
"add",
"(",
"resolve_type",
"(",
"k",
")",
")",
"val_tt",
".",
"add",
"(",
"resolve_type",
"(",
"v",
")",
")",
"return",
"DictType",
"(",
"key_tt",
",",
"val_tt",
")",
"else",
":",
"return",
"type",
"(",
"arg",
")"
]
| Resolve object to one of our internal collection types or generic built-in type.
Args:
arg: object to resolve | [
"Resolve",
"object",
"to",
"one",
"of",
"our",
"internal",
"collection",
"types",
"or",
"generic",
"built",
"-",
"in",
"type",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L498-L549 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | prep_args | def prep_args(arg_info):
# type: (ArgInfo) -> ResolvedTypes
"""
Resolve types from ArgInfo
"""
# pull out any varargs declarations
filtered_args = [a for a in arg_info.args if getattr(arg_info, 'varargs', None) != a]
# we don't care about self/cls first params (perhaps we can test if it's an instance/class method another way?)
if filtered_args and (filtered_args[0] in ('self', 'cls')):
filtered_args = filtered_args[1:]
pos_args = [] # type: List[InternalType]
if filtered_args:
for arg in filtered_args:
if isinstance(arg, str) and arg in arg_info.locals:
# here we know that return type will be of type "type"
resolved_type = resolve_type(arg_info.locals[arg])
pos_args.append(resolved_type)
else:
pos_args.append(type(UnknownType()))
varargs = None # type: Optional[List[InternalType]]
if arg_info.varargs:
varargs_tuple = arg_info.locals[arg_info.varargs]
# It's unclear what all the possible values for 'varargs_tuple' are,
# so perform a defensive type check since we don't want to crash here.
if isinstance(varargs_tuple, tuple):
varargs = [resolve_type(arg) for arg in varargs_tuple[:4]]
return ResolvedTypes(pos_args=pos_args, varargs=varargs) | python | def prep_args(arg_info):
# type: (ArgInfo) -> ResolvedTypes
"""
Resolve types from ArgInfo
"""
# pull out any varargs declarations
filtered_args = [a for a in arg_info.args if getattr(arg_info, 'varargs', None) != a]
# we don't care about self/cls first params (perhaps we can test if it's an instance/class method another way?)
if filtered_args and (filtered_args[0] in ('self', 'cls')):
filtered_args = filtered_args[1:]
pos_args = [] # type: List[InternalType]
if filtered_args:
for arg in filtered_args:
if isinstance(arg, str) and arg in arg_info.locals:
# here we know that return type will be of type "type"
resolved_type = resolve_type(arg_info.locals[arg])
pos_args.append(resolved_type)
else:
pos_args.append(type(UnknownType()))
varargs = None # type: Optional[List[InternalType]]
if arg_info.varargs:
varargs_tuple = arg_info.locals[arg_info.varargs]
# It's unclear what all the possible values for 'varargs_tuple' are,
# so perform a defensive type check since we don't want to crash here.
if isinstance(varargs_tuple, tuple):
varargs = [resolve_type(arg) for arg in varargs_tuple[:4]]
return ResolvedTypes(pos_args=pos_args, varargs=varargs) | [
"def",
"prep_args",
"(",
"arg_info",
")",
":",
"# type: (ArgInfo) -> ResolvedTypes",
"# pull out any varargs declarations",
"filtered_args",
"=",
"[",
"a",
"for",
"a",
"in",
"arg_info",
".",
"args",
"if",
"getattr",
"(",
"arg_info",
",",
"'varargs'",
",",
"None",
")",
"!=",
"a",
"]",
"# we don't care about self/cls first params (perhaps we can test if it's an instance/class method another way?)",
"if",
"filtered_args",
"and",
"(",
"filtered_args",
"[",
"0",
"]",
"in",
"(",
"'self'",
",",
"'cls'",
")",
")",
":",
"filtered_args",
"=",
"filtered_args",
"[",
"1",
":",
"]",
"pos_args",
"=",
"[",
"]",
"# type: List[InternalType]",
"if",
"filtered_args",
":",
"for",
"arg",
"in",
"filtered_args",
":",
"if",
"isinstance",
"(",
"arg",
",",
"str",
")",
"and",
"arg",
"in",
"arg_info",
".",
"locals",
":",
"# here we know that return type will be of type \"type\"",
"resolved_type",
"=",
"resolve_type",
"(",
"arg_info",
".",
"locals",
"[",
"arg",
"]",
")",
"pos_args",
".",
"append",
"(",
"resolved_type",
")",
"else",
":",
"pos_args",
".",
"append",
"(",
"type",
"(",
"UnknownType",
"(",
")",
")",
")",
"varargs",
"=",
"None",
"# type: Optional[List[InternalType]]",
"if",
"arg_info",
".",
"varargs",
":",
"varargs_tuple",
"=",
"arg_info",
".",
"locals",
"[",
"arg_info",
".",
"varargs",
"]",
"# It's unclear what all the possible values for 'varargs_tuple' are,",
"# so perform a defensive type check since we don't want to crash here.",
"if",
"isinstance",
"(",
"varargs_tuple",
",",
"tuple",
")",
":",
"varargs",
"=",
"[",
"resolve_type",
"(",
"arg",
")",
"for",
"arg",
"in",
"varargs_tuple",
"[",
":",
"4",
"]",
"]",
"return",
"ResolvedTypes",
"(",
"pos_args",
"=",
"pos_args",
",",
"varargs",
"=",
"varargs",
")"
]
| Resolve types from ArgInfo | [
"Resolve",
"types",
"from",
"ArgInfo"
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L552-L583 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | _flush_signature | def _flush_signature(key, return_type):
# type: (FunctionKey, InternalType) -> None
"""Store signature for a function.
Assume that argument types have been stored previously to
'collected_args'. As the 'return_type' argument provides the return
type, we now have a complete signature.
As a side effect, removes the argument types for the function from
'collected_args'.
"""
signatures = collected_signatures.setdefault(key, set())
args_info = collected_args.pop(key)
if len(signatures) < MAX_ITEMS_PER_FUNCTION:
signatures.add((args_info, return_type))
num_samples[key] = num_samples.get(key, 0) + 1 | python | def _flush_signature(key, return_type):
# type: (FunctionKey, InternalType) -> None
"""Store signature for a function.
Assume that argument types have been stored previously to
'collected_args'. As the 'return_type' argument provides the return
type, we now have a complete signature.
As a side effect, removes the argument types for the function from
'collected_args'.
"""
signatures = collected_signatures.setdefault(key, set())
args_info = collected_args.pop(key)
if len(signatures) < MAX_ITEMS_PER_FUNCTION:
signatures.add((args_info, return_type))
num_samples[key] = num_samples.get(key, 0) + 1 | [
"def",
"_flush_signature",
"(",
"key",
",",
"return_type",
")",
":",
"# type: (FunctionKey, InternalType) -> None",
"signatures",
"=",
"collected_signatures",
".",
"setdefault",
"(",
"key",
",",
"set",
"(",
")",
")",
"args_info",
"=",
"collected_args",
".",
"pop",
"(",
"key",
")",
"if",
"len",
"(",
"signatures",
")",
"<",
"MAX_ITEMS_PER_FUNCTION",
":",
"signatures",
".",
"add",
"(",
"(",
"args_info",
",",
"return_type",
")",
")",
"num_samples",
"[",
"key",
"]",
"=",
"num_samples",
".",
"get",
"(",
"key",
",",
"0",
")",
"+",
"1"
]
| Store signature for a function.
Assume that argument types have been stored previously to
'collected_args'. As the 'return_type' argument provides the return
type, we now have a complete signature.
As a side effect, removes the argument types for the function from
'collected_args'. | [
"Store",
"signature",
"for",
"a",
"function",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L656-L671 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | type_consumer | def type_consumer():
# type: () -> None
"""
Infinite loop of the type consumer thread.
It gets types to process from the task query.
"""
# we are not interested in profiling type_consumer itself
# but we start it before any other thread
while True:
item = _task_queue.get()
if isinstance(item, KeyAndTypes):
if item.key in collected_args:
# Previous call didn't get a corresponding return, perhaps because we
# stopped collecting types in the middle of a call or because of
# a recursive function.
_flush_signature(item.key, UnknownType)
collected_args[item.key] = ArgTypes(item.types)
else:
assert isinstance(item, KeyAndReturn)
if item.key in collected_args:
_flush_signature(item.key, item.return_type)
_task_queue.task_done() | python | def type_consumer():
# type: () -> None
"""
Infinite loop of the type consumer thread.
It gets types to process from the task query.
"""
# we are not interested in profiling type_consumer itself
# but we start it before any other thread
while True:
item = _task_queue.get()
if isinstance(item, KeyAndTypes):
if item.key in collected_args:
# Previous call didn't get a corresponding return, perhaps because we
# stopped collecting types in the middle of a call or because of
# a recursive function.
_flush_signature(item.key, UnknownType)
collected_args[item.key] = ArgTypes(item.types)
else:
assert isinstance(item, KeyAndReturn)
if item.key in collected_args:
_flush_signature(item.key, item.return_type)
_task_queue.task_done() | [
"def",
"type_consumer",
"(",
")",
":",
"# type: () -> None",
"# we are not interested in profiling type_consumer itself",
"# but we start it before any other thread",
"while",
"True",
":",
"item",
"=",
"_task_queue",
".",
"get",
"(",
")",
"if",
"isinstance",
"(",
"item",
",",
"KeyAndTypes",
")",
":",
"if",
"item",
".",
"key",
"in",
"collected_args",
":",
"# Previous call didn't get a corresponding return, perhaps because we",
"# stopped collecting types in the middle of a call or because of",
"# a recursive function.",
"_flush_signature",
"(",
"item",
".",
"key",
",",
"UnknownType",
")",
"collected_args",
"[",
"item",
".",
"key",
"]",
"=",
"ArgTypes",
"(",
"item",
".",
"types",
")",
"else",
":",
"assert",
"isinstance",
"(",
"item",
",",
"KeyAndReturn",
")",
"if",
"item",
".",
"key",
"in",
"collected_args",
":",
"_flush_signature",
"(",
"item",
".",
"key",
",",
"item",
".",
"return_type",
")",
"_task_queue",
".",
"task_done",
"(",
")"
]
| Infinite loop of the type consumer thread.
It gets types to process from the task query. | [
"Infinite",
"loop",
"of",
"the",
"type",
"consumer",
"thread",
".",
"It",
"gets",
"types",
"to",
"process",
"from",
"the",
"task",
"query",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L674-L696 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | _make_sampling_sequence | def _make_sampling_sequence(n):
# type: (int) -> List[int]
"""
Return a list containing the proposed call event sampling sequence.
Return events are paired with call events and not counted separately.
This is 0, 1, 2, ..., 4 plus 50, 100, 150, 200, etc.
The total list size is n.
"""
seq = list(range(5))
i = 50
while len(seq) < n:
seq.append(i)
i += 50
return seq | python | def _make_sampling_sequence(n):
# type: (int) -> List[int]
"""
Return a list containing the proposed call event sampling sequence.
Return events are paired with call events and not counted separately.
This is 0, 1, 2, ..., 4 plus 50, 100, 150, 200, etc.
The total list size is n.
"""
seq = list(range(5))
i = 50
while len(seq) < n:
seq.append(i)
i += 50
return seq | [
"def",
"_make_sampling_sequence",
"(",
"n",
")",
":",
"# type: (int) -> List[int]",
"seq",
"=",
"list",
"(",
"range",
"(",
"5",
")",
")",
"i",
"=",
"50",
"while",
"len",
"(",
"seq",
")",
"<",
"n",
":",
"seq",
".",
"append",
"(",
"i",
")",
"i",
"+=",
"50",
"return",
"seq"
]
| Return a list containing the proposed call event sampling sequence.
Return events are paired with call events and not counted separately.
This is 0, 1, 2, ..., 4 plus 50, 100, 150, 200, etc.
The total list size is n. | [
"Return",
"a",
"list",
"containing",
"the",
"proposed",
"call",
"event",
"sampling",
"sequence",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L711-L727 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | default_filter_filename | def default_filter_filename(filename):
# type: (Optional[str]) -> Optional[str]
"""Default filter for filenames.
Returns either a normalized filename or None.
You can pass your own filter to init_types_collection().
"""
if filename is None:
return None
elif filename.startswith(TOP_DIR):
if filename.startswith(TOP_DIR_DOT):
# Skip subdirectories starting with dot (e.g. .vagrant).
return None
else:
# Strip current directory and following slashes.
return filename[TOP_DIR_LEN:].lstrip(os.sep)
elif filename.startswith(os.sep):
# Skip absolute paths not under current directory.
return None
else:
return filename | python | def default_filter_filename(filename):
# type: (Optional[str]) -> Optional[str]
"""Default filter for filenames.
Returns either a normalized filename or None.
You can pass your own filter to init_types_collection().
"""
if filename is None:
return None
elif filename.startswith(TOP_DIR):
if filename.startswith(TOP_DIR_DOT):
# Skip subdirectories starting with dot (e.g. .vagrant).
return None
else:
# Strip current directory and following slashes.
return filename[TOP_DIR_LEN:].lstrip(os.sep)
elif filename.startswith(os.sep):
# Skip absolute paths not under current directory.
return None
else:
return filename | [
"def",
"default_filter_filename",
"(",
"filename",
")",
":",
"# type: (Optional[str]) -> Optional[str]",
"if",
"filename",
"is",
"None",
":",
"return",
"None",
"elif",
"filename",
".",
"startswith",
"(",
"TOP_DIR",
")",
":",
"if",
"filename",
".",
"startswith",
"(",
"TOP_DIR_DOT",
")",
":",
"# Skip subdirectories starting with dot (e.g. .vagrant).",
"return",
"None",
"else",
":",
"# Strip current directory and following slashes.",
"return",
"filename",
"[",
"TOP_DIR_LEN",
":",
"]",
".",
"lstrip",
"(",
"os",
".",
"sep",
")",
"elif",
"filename",
".",
"startswith",
"(",
"os",
".",
"sep",
")",
":",
"# Skip absolute paths not under current directory.",
"return",
"None",
"else",
":",
"return",
"filename"
]
| Default filter for filenames.
Returns either a normalized filename or None.
You can pass your own filter to init_types_collection(). | [
"Default",
"filter",
"for",
"filenames",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L787-L807 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | _filter_types | def _filter_types(types_dict):
# type: (Dict[FunctionKey, T]) -> Dict[FunctionKey, T]
"""Filter type info before dumping it to the file."""
def exclude(k):
# type: (FunctionKey) -> bool
"""Exclude filter"""
return k.path.startswith('<') or k.func_name == '<module>'
return {k: v for k, v in iteritems(types_dict) if not exclude(k)} | python | def _filter_types(types_dict):
# type: (Dict[FunctionKey, T]) -> Dict[FunctionKey, T]
"""Filter type info before dumping it to the file."""
def exclude(k):
# type: (FunctionKey) -> bool
"""Exclude filter"""
return k.path.startswith('<') or k.func_name == '<module>'
return {k: v for k, v in iteritems(types_dict) if not exclude(k)} | [
"def",
"_filter_types",
"(",
"types_dict",
")",
":",
"# type: (Dict[FunctionKey, T]) -> Dict[FunctionKey, T]",
"def",
"exclude",
"(",
"k",
")",
":",
"# type: (FunctionKey) -> bool",
"\"\"\"Exclude filter\"\"\"",
"return",
"k",
".",
"path",
".",
"startswith",
"(",
"'<'",
")",
"or",
"k",
".",
"func_name",
"==",
"'<module>'",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"types_dict",
")",
"if",
"not",
"exclude",
"(",
"k",
")",
"}"
]
| Filter type info before dumping it to the file. | [
"Filter",
"type",
"info",
"before",
"dumping",
"it",
"to",
"the",
"file",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L909-L918 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | _dump_impl | def _dump_impl():
# type: () -> List[FunctionData]
"""Internal implementation for dump_stats and dumps_stats"""
filtered_signatures = _filter_types(collected_signatures)
sorted_by_file = sorted(iteritems(filtered_signatures),
key=(lambda p: (p[0].path, p[0].line, p[0].func_name)))
res = [] # type: List[FunctionData]
for function_key, signatures in sorted_by_file:
comments = [_make_type_comment(args, ret_type) for args, ret_type in signatures]
res.append(
{
'path': function_key.path,
'line': function_key.line,
'func_name': function_key.func_name,
'type_comments': comments,
'samples': num_samples.get(function_key, 0),
}
)
return res | python | def _dump_impl():
# type: () -> List[FunctionData]
"""Internal implementation for dump_stats and dumps_stats"""
filtered_signatures = _filter_types(collected_signatures)
sorted_by_file = sorted(iteritems(filtered_signatures),
key=(lambda p: (p[0].path, p[0].line, p[0].func_name)))
res = [] # type: List[FunctionData]
for function_key, signatures in sorted_by_file:
comments = [_make_type_comment(args, ret_type) for args, ret_type in signatures]
res.append(
{
'path': function_key.path,
'line': function_key.line,
'func_name': function_key.func_name,
'type_comments': comments,
'samples': num_samples.get(function_key, 0),
}
)
return res | [
"def",
"_dump_impl",
"(",
")",
":",
"# type: () -> List[FunctionData]",
"filtered_signatures",
"=",
"_filter_types",
"(",
"collected_signatures",
")",
"sorted_by_file",
"=",
"sorted",
"(",
"iteritems",
"(",
"filtered_signatures",
")",
",",
"key",
"=",
"(",
"lambda",
"p",
":",
"(",
"p",
"[",
"0",
"]",
".",
"path",
",",
"p",
"[",
"0",
"]",
".",
"line",
",",
"p",
"[",
"0",
"]",
".",
"func_name",
")",
")",
")",
"res",
"=",
"[",
"]",
"# type: List[FunctionData]",
"for",
"function_key",
",",
"signatures",
"in",
"sorted_by_file",
":",
"comments",
"=",
"[",
"_make_type_comment",
"(",
"args",
",",
"ret_type",
")",
"for",
"args",
",",
"ret_type",
"in",
"signatures",
"]",
"res",
".",
"append",
"(",
"{",
"'path'",
":",
"function_key",
".",
"path",
",",
"'line'",
":",
"function_key",
".",
"line",
",",
"'func_name'",
":",
"function_key",
".",
"func_name",
",",
"'type_comments'",
":",
"comments",
",",
"'samples'",
":",
"num_samples",
".",
"get",
"(",
"function_key",
",",
"0",
")",
",",
"}",
")",
"return",
"res"
]
| Internal implementation for dump_stats and dumps_stats | [
"Internal",
"implementation",
"for",
"dump_stats",
"and",
"dumps_stats"
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L921-L939 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | dump_stats | def dump_stats(filename):
# type: (str) -> None
"""
Write collected information to file.
Args:
filename: absolute filename
"""
res = _dump_impl()
f = open(filename, 'w')
json.dump(res, f, indent=4)
f.close() | python | def dump_stats(filename):
# type: (str) -> None
"""
Write collected information to file.
Args:
filename: absolute filename
"""
res = _dump_impl()
f = open(filename, 'w')
json.dump(res, f, indent=4)
f.close() | [
"def",
"dump_stats",
"(",
"filename",
")",
":",
"# type: (str) -> None",
"res",
"=",
"_dump_impl",
"(",
")",
"f",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"json",
".",
"dump",
"(",
"res",
",",
"f",
",",
"indent",
"=",
"4",
")",
"f",
".",
"close",
"(",
")"
]
| Write collected information to file.
Args:
filename: absolute filename | [
"Write",
"collected",
"information",
"to",
"file",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L942-L953 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | init_types_collection | def init_types_collection(filter_filename=default_filter_filename):
# type: (Callable[[Optional[str]], Optional[str]]) -> None
"""
Setup profiler hooks to enable type collection.
Call this one time from the main thread.
The optional argument is a filter that maps a filename (from
code.co_filename) to either a normalized filename or None.
For the default filter see default_filter_filename().
"""
global _filter_filename
_filter_filename = filter_filename
sys.setprofile(_trace_dispatch)
threading.setprofile(_trace_dispatch) | python | def init_types_collection(filter_filename=default_filter_filename):
# type: (Callable[[Optional[str]], Optional[str]]) -> None
"""
Setup profiler hooks to enable type collection.
Call this one time from the main thread.
The optional argument is a filter that maps a filename (from
code.co_filename) to either a normalized filename or None.
For the default filter see default_filter_filename().
"""
global _filter_filename
_filter_filename = filter_filename
sys.setprofile(_trace_dispatch)
threading.setprofile(_trace_dispatch) | [
"def",
"init_types_collection",
"(",
"filter_filename",
"=",
"default_filter_filename",
")",
":",
"# type: (Callable[[Optional[str]], Optional[str]]) -> None",
"global",
"_filter_filename",
"_filter_filename",
"=",
"filter_filename",
"sys",
".",
"setprofile",
"(",
"_trace_dispatch",
")",
"threading",
".",
"setprofile",
"(",
"_trace_dispatch",
")"
]
| Setup profiler hooks to enable type collection.
Call this one time from the main thread.
The optional argument is a filter that maps a filename (from
code.co_filename) to either a normalized filename or None.
For the default filter see default_filter_filename(). | [
"Setup",
"profiler",
"hooks",
"to",
"enable",
"type",
"collection",
".",
"Call",
"this",
"one",
"time",
"from",
"the",
"main",
"thread",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L965-L978 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | TentativeType.add | def add(self, type):
# type: (InternalType) -> None
"""
Add type to the runtime type samples.
"""
try:
if isinstance(type, SetType):
if EMPTY_SET_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_SET_TYPE)
elif isinstance(type, ListType):
if EMPTY_LIST_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_LIST_TYPE)
elif isinstance(type, IteratorType):
if EMPTY_ITERATOR_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_ITERATOR_TYPE)
elif isinstance(type, DictType):
if EMPTY_DICT_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_DICT_TYPE)
for item in self.types_hashable:
if isinstance(item, DictType):
if item.key_type == type.key_type:
item.val_type.merge(type.val_type)
return
self.types_hashable.add(type)
except (TypeError, AttributeError):
try:
if type not in self.types:
self.types.append(type)
except AttributeError:
if TypeWasIncomparable not in self.types:
self.types.append(TypeWasIncomparable) | python | def add(self, type):
# type: (InternalType) -> None
"""
Add type to the runtime type samples.
"""
try:
if isinstance(type, SetType):
if EMPTY_SET_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_SET_TYPE)
elif isinstance(type, ListType):
if EMPTY_LIST_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_LIST_TYPE)
elif isinstance(type, IteratorType):
if EMPTY_ITERATOR_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_ITERATOR_TYPE)
elif isinstance(type, DictType):
if EMPTY_DICT_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_DICT_TYPE)
for item in self.types_hashable:
if isinstance(item, DictType):
if item.key_type == type.key_type:
item.val_type.merge(type.val_type)
return
self.types_hashable.add(type)
except (TypeError, AttributeError):
try:
if type not in self.types:
self.types.append(type)
except AttributeError:
if TypeWasIncomparable not in self.types:
self.types.append(TypeWasIncomparable) | [
"def",
"add",
"(",
"self",
",",
"type",
")",
":",
"# type: (InternalType) -> None",
"try",
":",
"if",
"isinstance",
"(",
"type",
",",
"SetType",
")",
":",
"if",
"EMPTY_SET_TYPE",
"in",
"self",
".",
"types_hashable",
":",
"self",
".",
"types_hashable",
".",
"remove",
"(",
"EMPTY_SET_TYPE",
")",
"elif",
"isinstance",
"(",
"type",
",",
"ListType",
")",
":",
"if",
"EMPTY_LIST_TYPE",
"in",
"self",
".",
"types_hashable",
":",
"self",
".",
"types_hashable",
".",
"remove",
"(",
"EMPTY_LIST_TYPE",
")",
"elif",
"isinstance",
"(",
"type",
",",
"IteratorType",
")",
":",
"if",
"EMPTY_ITERATOR_TYPE",
"in",
"self",
".",
"types_hashable",
":",
"self",
".",
"types_hashable",
".",
"remove",
"(",
"EMPTY_ITERATOR_TYPE",
")",
"elif",
"isinstance",
"(",
"type",
",",
"DictType",
")",
":",
"if",
"EMPTY_DICT_TYPE",
"in",
"self",
".",
"types_hashable",
":",
"self",
".",
"types_hashable",
".",
"remove",
"(",
"EMPTY_DICT_TYPE",
")",
"for",
"item",
"in",
"self",
".",
"types_hashable",
":",
"if",
"isinstance",
"(",
"item",
",",
"DictType",
")",
":",
"if",
"item",
".",
"key_type",
"==",
"type",
".",
"key_type",
":",
"item",
".",
"val_type",
".",
"merge",
"(",
"type",
".",
"val_type",
")",
"return",
"self",
".",
"types_hashable",
".",
"add",
"(",
"type",
")",
"except",
"(",
"TypeError",
",",
"AttributeError",
")",
":",
"try",
":",
"if",
"type",
"not",
"in",
"self",
".",
"types",
":",
"self",
".",
"types",
".",
"append",
"(",
"type",
")",
"except",
"AttributeError",
":",
"if",
"TypeWasIncomparable",
"not",
"in",
"self",
".",
"types",
":",
"self",
".",
"types",
".",
"append",
"(",
"TypeWasIncomparable",
")"
]
| Add type to the runtime type samples. | [
"Add",
"type",
"to",
"the",
"runtime",
"type",
"samples",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L336-L367 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | TentativeType.merge | def merge(self, other):
# type: (TentativeType) -> None
"""
Merge two TentativeType instances
"""
for hashables in other.types_hashable:
self.add(hashables)
for non_hashbles in other.types:
self.add(non_hashbles) | python | def merge(self, other):
# type: (TentativeType) -> None
"""
Merge two TentativeType instances
"""
for hashables in other.types_hashable:
self.add(hashables)
for non_hashbles in other.types:
self.add(non_hashbles) | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"# type: (TentativeType) -> None",
"for",
"hashables",
"in",
"other",
".",
"types_hashable",
":",
"self",
".",
"add",
"(",
"hashables",
")",
"for",
"non_hashbles",
"in",
"other",
".",
"types",
":",
"self",
".",
"add",
"(",
"non_hashbles",
")"
]
| Merge two TentativeType instances | [
"Merge",
"two",
"TentativeType",
"instances"
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L369-L377 | train |
dropbox/pyannotate | pyannotate_tools/annotations/infer.py | infer_annotation | def infer_annotation(type_comments):
# type: (List[str]) -> Tuple[List[Argument], AbstractType]
"""Given some type comments, return a single inferred signature.
Args:
type_comments: Strings of form '(arg1, ... argN) -> ret'
Returns: Tuple of (argument types and kinds, return type).
"""
assert type_comments
args = {} # type: Dict[int, Set[Argument]]
returns = set()
for comment in type_comments:
arg_types, return_type = parse_type_comment(comment)
for i, arg_type in enumerate(arg_types):
args.setdefault(i, set()).add(arg_type)
returns.add(return_type)
combined_args = []
for i in sorted(args):
arg_infos = list(args[i])
kind = argument_kind(arg_infos)
if kind is None:
raise InferError('Ambiguous argument kinds:\n' + '\n'.join(type_comments))
types = [arg.type for arg in arg_infos]
combined = combine_types(types)
if str(combined) == 'None':
# It's very rare for an argument to actually be typed `None`, more likely than
# not we simply don't have any data points for this argument.
combined = UnionType([ClassType('None'), AnyType()])
if kind != ARG_POS and (len(str(combined)) > 120 or isinstance(combined, UnionType)):
# Avoid some noise.
combined = AnyType()
combined_args.append(Argument(combined, kind))
combined_return = combine_types(returns)
return combined_args, combined_return | python | def infer_annotation(type_comments):
# type: (List[str]) -> Tuple[List[Argument], AbstractType]
"""Given some type comments, return a single inferred signature.
Args:
type_comments: Strings of form '(arg1, ... argN) -> ret'
Returns: Tuple of (argument types and kinds, return type).
"""
assert type_comments
args = {} # type: Dict[int, Set[Argument]]
returns = set()
for comment in type_comments:
arg_types, return_type = parse_type_comment(comment)
for i, arg_type in enumerate(arg_types):
args.setdefault(i, set()).add(arg_type)
returns.add(return_type)
combined_args = []
for i in sorted(args):
arg_infos = list(args[i])
kind = argument_kind(arg_infos)
if kind is None:
raise InferError('Ambiguous argument kinds:\n' + '\n'.join(type_comments))
types = [arg.type for arg in arg_infos]
combined = combine_types(types)
if str(combined) == 'None':
# It's very rare for an argument to actually be typed `None`, more likely than
# not we simply don't have any data points for this argument.
combined = UnionType([ClassType('None'), AnyType()])
if kind != ARG_POS and (len(str(combined)) > 120 or isinstance(combined, UnionType)):
# Avoid some noise.
combined = AnyType()
combined_args.append(Argument(combined, kind))
combined_return = combine_types(returns)
return combined_args, combined_return | [
"def",
"infer_annotation",
"(",
"type_comments",
")",
":",
"# type: (List[str]) -> Tuple[List[Argument], AbstractType]",
"assert",
"type_comments",
"args",
"=",
"{",
"}",
"# type: Dict[int, Set[Argument]]",
"returns",
"=",
"set",
"(",
")",
"for",
"comment",
"in",
"type_comments",
":",
"arg_types",
",",
"return_type",
"=",
"parse_type_comment",
"(",
"comment",
")",
"for",
"i",
",",
"arg_type",
"in",
"enumerate",
"(",
"arg_types",
")",
":",
"args",
".",
"setdefault",
"(",
"i",
",",
"set",
"(",
")",
")",
".",
"add",
"(",
"arg_type",
")",
"returns",
".",
"add",
"(",
"return_type",
")",
"combined_args",
"=",
"[",
"]",
"for",
"i",
"in",
"sorted",
"(",
"args",
")",
":",
"arg_infos",
"=",
"list",
"(",
"args",
"[",
"i",
"]",
")",
"kind",
"=",
"argument_kind",
"(",
"arg_infos",
")",
"if",
"kind",
"is",
"None",
":",
"raise",
"InferError",
"(",
"'Ambiguous argument kinds:\\n'",
"+",
"'\\n'",
".",
"join",
"(",
"type_comments",
")",
")",
"types",
"=",
"[",
"arg",
".",
"type",
"for",
"arg",
"in",
"arg_infos",
"]",
"combined",
"=",
"combine_types",
"(",
"types",
")",
"if",
"str",
"(",
"combined",
")",
"==",
"'None'",
":",
"# It's very rare for an argument to actually be typed `None`, more likely than",
"# not we simply don't have any data points for this argument.",
"combined",
"=",
"UnionType",
"(",
"[",
"ClassType",
"(",
"'None'",
")",
",",
"AnyType",
"(",
")",
"]",
")",
"if",
"kind",
"!=",
"ARG_POS",
"and",
"(",
"len",
"(",
"str",
"(",
"combined",
")",
")",
">",
"120",
"or",
"isinstance",
"(",
"combined",
",",
"UnionType",
")",
")",
":",
"# Avoid some noise.",
"combined",
"=",
"AnyType",
"(",
")",
"combined_args",
".",
"append",
"(",
"Argument",
"(",
"combined",
",",
"kind",
")",
")",
"combined_return",
"=",
"combine_types",
"(",
"returns",
")",
"return",
"combined_args",
",",
"combined_return"
]
| Given some type comments, return a single inferred signature.
Args:
type_comments: Strings of form '(arg1, ... argN) -> ret'
Returns: Tuple of (argument types and kinds, return type). | [
"Given",
"some",
"type",
"comments",
"return",
"a",
"single",
"inferred",
"signature",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L32-L66 | train |
dropbox/pyannotate | pyannotate_tools/annotations/infer.py | argument_kind | def argument_kind(args):
# type: (List[Argument]) -> Optional[str]
"""Return the kind of an argument, based on one or more descriptions of the argument.
Return None if every item does not have the same kind.
"""
kinds = set(arg.kind for arg in args)
if len(kinds) != 1:
return None
return kinds.pop() | python | def argument_kind(args):
# type: (List[Argument]) -> Optional[str]
"""Return the kind of an argument, based on one or more descriptions of the argument.
Return None if every item does not have the same kind.
"""
kinds = set(arg.kind for arg in args)
if len(kinds) != 1:
return None
return kinds.pop() | [
"def",
"argument_kind",
"(",
"args",
")",
":",
"# type: (List[Argument]) -> Optional[str]",
"kinds",
"=",
"set",
"(",
"arg",
".",
"kind",
"for",
"arg",
"in",
"args",
")",
"if",
"len",
"(",
"kinds",
")",
"!=",
"1",
":",
"return",
"None",
"return",
"kinds",
".",
"pop",
"(",
")"
]
| Return the kind of an argument, based on one or more descriptions of the argument.
Return None if every item does not have the same kind. | [
"Return",
"the",
"kind",
"of",
"an",
"argument",
"based",
"on",
"one",
"or",
"more",
"descriptions",
"of",
"the",
"argument",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L69-L78 | train |
dropbox/pyannotate | pyannotate_tools/annotations/infer.py | combine_types | def combine_types(types):
# type: (Iterable[AbstractType]) -> AbstractType
"""Given some types, return a combined and simplified type.
For example, if given 'int' and 'List[int]', return Union[int, List[int]]. If given
'int' and 'int', return just 'int'.
"""
items = simplify_types(types)
if len(items) == 1:
return items[0]
else:
return UnionType(items) | python | def combine_types(types):
# type: (Iterable[AbstractType]) -> AbstractType
"""Given some types, return a combined and simplified type.
For example, if given 'int' and 'List[int]', return Union[int, List[int]]. If given
'int' and 'int', return just 'int'.
"""
items = simplify_types(types)
if len(items) == 1:
return items[0]
else:
return UnionType(items) | [
"def",
"combine_types",
"(",
"types",
")",
":",
"# type: (Iterable[AbstractType]) -> AbstractType",
"items",
"=",
"simplify_types",
"(",
"types",
")",
"if",
"len",
"(",
"items",
")",
"==",
"1",
":",
"return",
"items",
"[",
"0",
"]",
"else",
":",
"return",
"UnionType",
"(",
"items",
")"
]
| Given some types, return a combined and simplified type.
For example, if given 'int' and 'List[int]', return Union[int, List[int]]. If given
'int' and 'int', return just 'int'. | [
"Given",
"some",
"types",
"return",
"a",
"combined",
"and",
"simplified",
"type",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L81-L92 | train |
dropbox/pyannotate | pyannotate_tools/annotations/infer.py | simplify_types | def simplify_types(types):
# type: (Iterable[AbstractType]) -> List[AbstractType]
"""Given some types, give simplified types representing the union of types."""
flattened = flatten_types(types)
items = filter_ignored_items(flattened)
items = [simplify_recursive(item) for item in items]
items = merge_items(items)
items = dedupe_types(items)
# We have to remove reundant items after everything has been simplified and
# merged as this simplification may be what makes items redundant.
items = remove_redundant_items(items)
if len(items) > 3:
return [AnyType()]
else:
return items | python | def simplify_types(types):
# type: (Iterable[AbstractType]) -> List[AbstractType]
"""Given some types, give simplified types representing the union of types."""
flattened = flatten_types(types)
items = filter_ignored_items(flattened)
items = [simplify_recursive(item) for item in items]
items = merge_items(items)
items = dedupe_types(items)
# We have to remove reundant items after everything has been simplified and
# merged as this simplification may be what makes items redundant.
items = remove_redundant_items(items)
if len(items) > 3:
return [AnyType()]
else:
return items | [
"def",
"simplify_types",
"(",
"types",
")",
":",
"# type: (Iterable[AbstractType]) -> List[AbstractType]",
"flattened",
"=",
"flatten_types",
"(",
"types",
")",
"items",
"=",
"filter_ignored_items",
"(",
"flattened",
")",
"items",
"=",
"[",
"simplify_recursive",
"(",
"item",
")",
"for",
"item",
"in",
"items",
"]",
"items",
"=",
"merge_items",
"(",
"items",
")",
"items",
"=",
"dedupe_types",
"(",
"items",
")",
"# We have to remove reundant items after everything has been simplified and",
"# merged as this simplification may be what makes items redundant.",
"items",
"=",
"remove_redundant_items",
"(",
"items",
")",
"if",
"len",
"(",
"items",
")",
">",
"3",
":",
"return",
"[",
"AnyType",
"(",
")",
"]",
"else",
":",
"return",
"items"
]
| Given some types, give simplified types representing the union of types. | [
"Given",
"some",
"types",
"give",
"simplified",
"types",
"representing",
"the",
"union",
"of",
"types",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L95-L109 | train |
dropbox/pyannotate | pyannotate_tools/annotations/infer.py | simplify_recursive | def simplify_recursive(typ):
# type: (AbstractType) -> AbstractType
"""Simplify all components of a type."""
if isinstance(typ, UnionType):
return combine_types(typ.items)
elif isinstance(typ, ClassType):
simplified = ClassType(typ.name, [simplify_recursive(arg) for arg in typ.args])
args = simplified.args
if (simplified.name == 'Dict' and len(args) == 2
and isinstance(args[0], ClassType) and args[0].name in ('str', 'Text')
and isinstance(args[1], UnionType) and not is_optional(args[1])):
# Looks like a potential case for TypedDict, which we don't properly support yet.
return ClassType('Dict', [args[0], AnyType()])
return simplified
elif isinstance(typ, TupleType):
return TupleType([simplify_recursive(item) for item in typ.items])
return typ | python | def simplify_recursive(typ):
# type: (AbstractType) -> AbstractType
"""Simplify all components of a type."""
if isinstance(typ, UnionType):
return combine_types(typ.items)
elif isinstance(typ, ClassType):
simplified = ClassType(typ.name, [simplify_recursive(arg) for arg in typ.args])
args = simplified.args
if (simplified.name == 'Dict' and len(args) == 2
and isinstance(args[0], ClassType) and args[0].name in ('str', 'Text')
and isinstance(args[1], UnionType) and not is_optional(args[1])):
# Looks like a potential case for TypedDict, which we don't properly support yet.
return ClassType('Dict', [args[0], AnyType()])
return simplified
elif isinstance(typ, TupleType):
return TupleType([simplify_recursive(item) for item in typ.items])
return typ | [
"def",
"simplify_recursive",
"(",
"typ",
")",
":",
"# type: (AbstractType) -> AbstractType",
"if",
"isinstance",
"(",
"typ",
",",
"UnionType",
")",
":",
"return",
"combine_types",
"(",
"typ",
".",
"items",
")",
"elif",
"isinstance",
"(",
"typ",
",",
"ClassType",
")",
":",
"simplified",
"=",
"ClassType",
"(",
"typ",
".",
"name",
",",
"[",
"simplify_recursive",
"(",
"arg",
")",
"for",
"arg",
"in",
"typ",
".",
"args",
"]",
")",
"args",
"=",
"simplified",
".",
"args",
"if",
"(",
"simplified",
".",
"name",
"==",
"'Dict'",
"and",
"len",
"(",
"args",
")",
"==",
"2",
"and",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"ClassType",
")",
"and",
"args",
"[",
"0",
"]",
".",
"name",
"in",
"(",
"'str'",
",",
"'Text'",
")",
"and",
"isinstance",
"(",
"args",
"[",
"1",
"]",
",",
"UnionType",
")",
"and",
"not",
"is_optional",
"(",
"args",
"[",
"1",
"]",
")",
")",
":",
"# Looks like a potential case for TypedDict, which we don't properly support yet.",
"return",
"ClassType",
"(",
"'Dict'",
",",
"[",
"args",
"[",
"0",
"]",
",",
"AnyType",
"(",
")",
"]",
")",
"return",
"simplified",
"elif",
"isinstance",
"(",
"typ",
",",
"TupleType",
")",
":",
"return",
"TupleType",
"(",
"[",
"simplify_recursive",
"(",
"item",
")",
"for",
"item",
"in",
"typ",
".",
"items",
"]",
")",
"return",
"typ"
]
| Simplify all components of a type. | [
"Simplify",
"all",
"components",
"of",
"a",
"type",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L112-L128 | train |
dropbox/pyannotate | pyannotate_tools/annotations/infer.py | remove_redundant_items | def remove_redundant_items(items):
# type: (List[AbstractType]) -> List[AbstractType]
"""Filter out redundant union items."""
result = []
for item in items:
for other in items:
if item is not other and is_redundant_union_item(item, other):
break
else:
result.append(item)
return result | python | def remove_redundant_items(items):
# type: (List[AbstractType]) -> List[AbstractType]
"""Filter out redundant union items."""
result = []
for item in items:
for other in items:
if item is not other and is_redundant_union_item(item, other):
break
else:
result.append(item)
return result | [
"def",
"remove_redundant_items",
"(",
"items",
")",
":",
"# type: (List[AbstractType]) -> List[AbstractType]",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"for",
"other",
"in",
"items",
":",
"if",
"item",
"is",
"not",
"other",
"and",
"is_redundant_union_item",
"(",
"item",
",",
"other",
")",
":",
"break",
"else",
":",
"result",
".",
"append",
"(",
"item",
")",
"return",
"result"
]
| Filter out redundant union items. | [
"Filter",
"out",
"redundant",
"union",
"items",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L153-L163 | train |
dropbox/pyannotate | pyannotate_tools/annotations/infer.py | is_redundant_union_item | def is_redundant_union_item(first, other):
# type: (AbstractType, AbstractType) -> bool
"""If union has both items, is the first one redundant?
For example, if first is 'str' and the other is 'Text', return True.
If items are equal, return False.
"""
if isinstance(first, ClassType) and isinstance(other, ClassType):
if first.name == 'str' and other.name == 'Text':
return True
elif first.name == 'bool' and other.name == 'int':
return True
elif first.name == 'int' and other.name == 'float':
return True
elif (first.name in ('List', 'Dict', 'Set') and
other.name == first.name):
if not first.args and other.args:
return True
elif len(first.args) == len(other.args) and first.args:
result = all(first_arg == other_arg or other_arg == AnyType()
for first_arg, other_arg
in zip(first.args, other.args))
return result
return False | python | def is_redundant_union_item(first, other):
# type: (AbstractType, AbstractType) -> bool
"""If union has both items, is the first one redundant?
For example, if first is 'str' and the other is 'Text', return True.
If items are equal, return False.
"""
if isinstance(first, ClassType) and isinstance(other, ClassType):
if first.name == 'str' and other.name == 'Text':
return True
elif first.name == 'bool' and other.name == 'int':
return True
elif first.name == 'int' and other.name == 'float':
return True
elif (first.name in ('List', 'Dict', 'Set') and
other.name == first.name):
if not first.args and other.args:
return True
elif len(first.args) == len(other.args) and first.args:
result = all(first_arg == other_arg or other_arg == AnyType()
for first_arg, other_arg
in zip(first.args, other.args))
return result
return False | [
"def",
"is_redundant_union_item",
"(",
"first",
",",
"other",
")",
":",
"# type: (AbstractType, AbstractType) -> bool",
"if",
"isinstance",
"(",
"first",
",",
"ClassType",
")",
"and",
"isinstance",
"(",
"other",
",",
"ClassType",
")",
":",
"if",
"first",
".",
"name",
"==",
"'str'",
"and",
"other",
".",
"name",
"==",
"'Text'",
":",
"return",
"True",
"elif",
"first",
".",
"name",
"==",
"'bool'",
"and",
"other",
".",
"name",
"==",
"'int'",
":",
"return",
"True",
"elif",
"first",
".",
"name",
"==",
"'int'",
"and",
"other",
".",
"name",
"==",
"'float'",
":",
"return",
"True",
"elif",
"(",
"first",
".",
"name",
"in",
"(",
"'List'",
",",
"'Dict'",
",",
"'Set'",
")",
"and",
"other",
".",
"name",
"==",
"first",
".",
"name",
")",
":",
"if",
"not",
"first",
".",
"args",
"and",
"other",
".",
"args",
":",
"return",
"True",
"elif",
"len",
"(",
"first",
".",
"args",
")",
"==",
"len",
"(",
"other",
".",
"args",
")",
"and",
"first",
".",
"args",
":",
"result",
"=",
"all",
"(",
"first_arg",
"==",
"other_arg",
"or",
"other_arg",
"==",
"AnyType",
"(",
")",
"for",
"first_arg",
",",
"other_arg",
"in",
"zip",
"(",
"first",
".",
"args",
",",
"other",
".",
"args",
")",
")",
"return",
"result",
"return",
"False"
]
| If union has both items, is the first one redundant?
For example, if first is 'str' and the other is 'Text', return True.
If items are equal, return False. | [
"If",
"union",
"has",
"both",
"items",
"is",
"the",
"first",
"one",
"redundant?"
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L166-L191 | train |
dropbox/pyannotate | pyannotate_tools/annotations/infer.py | merge_items | def merge_items(items):
# type: (List[AbstractType]) -> List[AbstractType]
"""Merge union items that can be merged."""
result = []
while items:
item = items.pop()
merged = None
for i, other in enumerate(items):
merged = merged_type(item, other)
if merged:
break
if merged:
del items[i]
items.append(merged)
else:
result.append(item)
return list(reversed(result)) | python | def merge_items(items):
# type: (List[AbstractType]) -> List[AbstractType]
"""Merge union items that can be merged."""
result = []
while items:
item = items.pop()
merged = None
for i, other in enumerate(items):
merged = merged_type(item, other)
if merged:
break
if merged:
del items[i]
items.append(merged)
else:
result.append(item)
return list(reversed(result)) | [
"def",
"merge_items",
"(",
"items",
")",
":",
"# type: (List[AbstractType]) -> List[AbstractType]",
"result",
"=",
"[",
"]",
"while",
"items",
":",
"item",
"=",
"items",
".",
"pop",
"(",
")",
"merged",
"=",
"None",
"for",
"i",
",",
"other",
"in",
"enumerate",
"(",
"items",
")",
":",
"merged",
"=",
"merged_type",
"(",
"item",
",",
"other",
")",
"if",
"merged",
":",
"break",
"if",
"merged",
":",
"del",
"items",
"[",
"i",
"]",
"items",
".",
"append",
"(",
"merged",
")",
"else",
":",
"result",
".",
"append",
"(",
"item",
")",
"return",
"list",
"(",
"reversed",
"(",
"result",
")",
")"
]
| Merge union items that can be merged. | [
"Merge",
"union",
"items",
"that",
"can",
"be",
"merged",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L194-L210 | train |
dropbox/pyannotate | pyannotate_tools/annotations/infer.py | merged_type | def merged_type(t, s):
# type: (AbstractType, AbstractType) -> Optional[AbstractType]
"""Return merged type if two items can be merged in to a different, more general type.
Return None if merging is not possible.
"""
if isinstance(t, TupleType) and isinstance(s, TupleType):
if len(t.items) == len(s.items):
return TupleType([combine_types([ti, si]) for ti, si in zip(t.items, s.items)])
all_items = t.items + s.items
if all_items and all(item == all_items[0] for item in all_items[1:]):
# Merge multiple compatible fixed-length tuples into a variable-length tuple type.
return ClassType('Tuple', [all_items[0]])
elif (isinstance(t, TupleType) and isinstance(s, ClassType) and s.name == 'Tuple'
and len(s.args) == 1):
if all(item == s.args[0] for item in t.items):
# Merge fixed-length tuple and variable-length tuple.
return s
elif isinstance(s, TupleType) and isinstance(t, ClassType) and t.name == 'Tuple':
return merged_type(s, t)
elif isinstance(s, NoReturnType):
return t
elif isinstance(t, NoReturnType):
return s
elif isinstance(s, AnyType):
# This seems to be usually desirable, since Anys tend to come from unknown types.
return t
elif isinstance(t, AnyType):
# Similar to above.
return s
return None | python | def merged_type(t, s):
# type: (AbstractType, AbstractType) -> Optional[AbstractType]
"""Return merged type if two items can be merged in to a different, more general type.
Return None if merging is not possible.
"""
if isinstance(t, TupleType) and isinstance(s, TupleType):
if len(t.items) == len(s.items):
return TupleType([combine_types([ti, si]) for ti, si in zip(t.items, s.items)])
all_items = t.items + s.items
if all_items and all(item == all_items[0] for item in all_items[1:]):
# Merge multiple compatible fixed-length tuples into a variable-length tuple type.
return ClassType('Tuple', [all_items[0]])
elif (isinstance(t, TupleType) and isinstance(s, ClassType) and s.name == 'Tuple'
and len(s.args) == 1):
if all(item == s.args[0] for item in t.items):
# Merge fixed-length tuple and variable-length tuple.
return s
elif isinstance(s, TupleType) and isinstance(t, ClassType) and t.name == 'Tuple':
return merged_type(s, t)
elif isinstance(s, NoReturnType):
return t
elif isinstance(t, NoReturnType):
return s
elif isinstance(s, AnyType):
# This seems to be usually desirable, since Anys tend to come from unknown types.
return t
elif isinstance(t, AnyType):
# Similar to above.
return s
return None | [
"def",
"merged_type",
"(",
"t",
",",
"s",
")",
":",
"# type: (AbstractType, AbstractType) -> Optional[AbstractType]",
"if",
"isinstance",
"(",
"t",
",",
"TupleType",
")",
"and",
"isinstance",
"(",
"s",
",",
"TupleType",
")",
":",
"if",
"len",
"(",
"t",
".",
"items",
")",
"==",
"len",
"(",
"s",
".",
"items",
")",
":",
"return",
"TupleType",
"(",
"[",
"combine_types",
"(",
"[",
"ti",
",",
"si",
"]",
")",
"for",
"ti",
",",
"si",
"in",
"zip",
"(",
"t",
".",
"items",
",",
"s",
".",
"items",
")",
"]",
")",
"all_items",
"=",
"t",
".",
"items",
"+",
"s",
".",
"items",
"if",
"all_items",
"and",
"all",
"(",
"item",
"==",
"all_items",
"[",
"0",
"]",
"for",
"item",
"in",
"all_items",
"[",
"1",
":",
"]",
")",
":",
"# Merge multiple compatible fixed-length tuples into a variable-length tuple type.",
"return",
"ClassType",
"(",
"'Tuple'",
",",
"[",
"all_items",
"[",
"0",
"]",
"]",
")",
"elif",
"(",
"isinstance",
"(",
"t",
",",
"TupleType",
")",
"and",
"isinstance",
"(",
"s",
",",
"ClassType",
")",
"and",
"s",
".",
"name",
"==",
"'Tuple'",
"and",
"len",
"(",
"s",
".",
"args",
")",
"==",
"1",
")",
":",
"if",
"all",
"(",
"item",
"==",
"s",
".",
"args",
"[",
"0",
"]",
"for",
"item",
"in",
"t",
".",
"items",
")",
":",
"# Merge fixed-length tuple and variable-length tuple.",
"return",
"s",
"elif",
"isinstance",
"(",
"s",
",",
"TupleType",
")",
"and",
"isinstance",
"(",
"t",
",",
"ClassType",
")",
"and",
"t",
".",
"name",
"==",
"'Tuple'",
":",
"return",
"merged_type",
"(",
"s",
",",
"t",
")",
"elif",
"isinstance",
"(",
"s",
",",
"NoReturnType",
")",
":",
"return",
"t",
"elif",
"isinstance",
"(",
"t",
",",
"NoReturnType",
")",
":",
"return",
"s",
"elif",
"isinstance",
"(",
"s",
",",
"AnyType",
")",
":",
"# This seems to be usually desirable, since Anys tend to come from unknown types.",
"return",
"t",
"elif",
"isinstance",
"(",
"t",
",",
"AnyType",
")",
":",
"# Similar to above.",
"return",
"s",
"return",
"None"
]
| Return merged type if two items can be merged in to a different, more general type.
Return None if merging is not possible. | [
"Return",
"merged",
"type",
"if",
"two",
"items",
"can",
"be",
"merged",
"in",
"to",
"a",
"different",
"more",
"general",
"type",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L213-L243 | train |
dropbox/pyannotate | pyannotate_tools/annotations/__main__.py | dump_annotations | def dump_annotations(type_info, files):
"""Dump annotations out of type_info, filtered by files.
If files is non-empty, only dump items either if the path in the
item matches one of the files exactly, or else if one of the files
is a path prefix of the path.
"""
with open(type_info) as f:
data = json.load(f)
for item in data:
path, line, func_name = item['path'], item['line'], item['func_name']
if files and path not in files:
for f in files:
if path.startswith(os.path.join(f, '')):
break
else:
continue # Outer loop
print("%s:%d: in %s:" % (path, line, func_name))
type_comments = item['type_comments']
signature = unify_type_comments(type_comments)
arg_types = signature['arg_types']
return_type = signature['return_type']
print(" # type: (%s) -> %s" % (", ".join(arg_types), return_type)) | python | def dump_annotations(type_info, files):
"""Dump annotations out of type_info, filtered by files.
If files is non-empty, only dump items either if the path in the
item matches one of the files exactly, or else if one of the files
is a path prefix of the path.
"""
with open(type_info) as f:
data = json.load(f)
for item in data:
path, line, func_name = item['path'], item['line'], item['func_name']
if files and path not in files:
for f in files:
if path.startswith(os.path.join(f, '')):
break
else:
continue # Outer loop
print("%s:%d: in %s:" % (path, line, func_name))
type_comments = item['type_comments']
signature = unify_type_comments(type_comments)
arg_types = signature['arg_types']
return_type = signature['return_type']
print(" # type: (%s) -> %s" % (", ".join(arg_types), return_type)) | [
"def",
"dump_annotations",
"(",
"type_info",
",",
"files",
")",
":",
"with",
"open",
"(",
"type_info",
")",
"as",
"f",
":",
"data",
"=",
"json",
".",
"load",
"(",
"f",
")",
"for",
"item",
"in",
"data",
":",
"path",
",",
"line",
",",
"func_name",
"=",
"item",
"[",
"'path'",
"]",
",",
"item",
"[",
"'line'",
"]",
",",
"item",
"[",
"'func_name'",
"]",
"if",
"files",
"and",
"path",
"not",
"in",
"files",
":",
"for",
"f",
"in",
"files",
":",
"if",
"path",
".",
"startswith",
"(",
"os",
".",
"path",
".",
"join",
"(",
"f",
",",
"''",
")",
")",
":",
"break",
"else",
":",
"continue",
"# Outer loop",
"print",
"(",
"\"%s:%d: in %s:\"",
"%",
"(",
"path",
",",
"line",
",",
"func_name",
")",
")",
"type_comments",
"=",
"item",
"[",
"'type_comments'",
"]",
"signature",
"=",
"unify_type_comments",
"(",
"type_comments",
")",
"arg_types",
"=",
"signature",
"[",
"'arg_types'",
"]",
"return_type",
"=",
"signature",
"[",
"'return_type'",
"]",
"print",
"(",
"\" # type: (%s) -> %s\"",
"%",
"(",
"\", \"",
".",
"join",
"(",
"arg_types",
")",
",",
"return_type",
")",
")"
]
| Dump annotations out of type_info, filtered by files.
If files is non-empty, only dump items either if the path in the
item matches one of the files exactly, or else if one of the files
is a path prefix of the path. | [
"Dump",
"annotations",
"out",
"of",
"type_info",
"filtered",
"by",
"files",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/__main__.py#L60-L82 | train |
dropbox/pyannotate | pyannotate_tools/fixes/fix_annotate_json.py | strip_py | def strip_py(arg):
# type: (str) -> Optional[str]
"""Strip a trailing .py or .pyi suffix.
Return None if no such suffix is found.
"""
for ext in PY_EXTENSIONS:
if arg.endswith(ext):
return arg[:-len(ext)]
return None | python | def strip_py(arg):
# type: (str) -> Optional[str]
"""Strip a trailing .py or .pyi suffix.
Return None if no such suffix is found.
"""
for ext in PY_EXTENSIONS:
if arg.endswith(ext):
return arg[:-len(ext)]
return None | [
"def",
"strip_py",
"(",
"arg",
")",
":",
"# type: (str) -> Optional[str]",
"for",
"ext",
"in",
"PY_EXTENSIONS",
":",
"if",
"arg",
".",
"endswith",
"(",
"ext",
")",
":",
"return",
"arg",
"[",
":",
"-",
"len",
"(",
"ext",
")",
"]",
"return",
"None"
]
| Strip a trailing .py or .pyi suffix.
Return None if no such suffix is found. | [
"Strip",
"a",
"trailing",
".",
"py",
"or",
".",
"pyi",
"suffix",
".",
"Return",
"None",
"if",
"no",
"such",
"suffix",
"is",
"found",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/fixes/fix_annotate_json.py#L61-L69 | train |
dropbox/pyannotate | pyannotate_tools/fixes/fix_annotate.py | FixAnnotate.get_decorators | def get_decorators(self, node):
"""Return a list of decorators found on a function definition.
This is a list of strings; only simple decorators
(e.g. @staticmethod) are returned.
If the function is undecorated or only non-simple decorators
are found, return [].
"""
if node.parent is None:
return []
results = {}
if not self.decorated.match(node.parent, results):
return []
decorators = results.get('dd') or [results['d']]
decs = []
for d in decorators:
for child in d.children:
if isinstance(child, Leaf) and child.type == token.NAME:
decs.append(child.value)
return decs | python | def get_decorators(self, node):
"""Return a list of decorators found on a function definition.
This is a list of strings; only simple decorators
(e.g. @staticmethod) are returned.
If the function is undecorated or only non-simple decorators
are found, return [].
"""
if node.parent is None:
return []
results = {}
if not self.decorated.match(node.parent, results):
return []
decorators = results.get('dd') or [results['d']]
decs = []
for d in decorators:
for child in d.children:
if isinstance(child, Leaf) and child.type == token.NAME:
decs.append(child.value)
return decs | [
"def",
"get_decorators",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"parent",
"is",
"None",
":",
"return",
"[",
"]",
"results",
"=",
"{",
"}",
"if",
"not",
"self",
".",
"decorated",
".",
"match",
"(",
"node",
".",
"parent",
",",
"results",
")",
":",
"return",
"[",
"]",
"decorators",
"=",
"results",
".",
"get",
"(",
"'dd'",
")",
"or",
"[",
"results",
"[",
"'d'",
"]",
"]",
"decs",
"=",
"[",
"]",
"for",
"d",
"in",
"decorators",
":",
"for",
"child",
"in",
"d",
".",
"children",
":",
"if",
"isinstance",
"(",
"child",
",",
"Leaf",
")",
"and",
"child",
".",
"type",
"==",
"token",
".",
"NAME",
":",
"decs",
".",
"append",
"(",
"child",
".",
"value",
")",
"return",
"decs"
]
| Return a list of decorators found on a function definition.
This is a list of strings; only simple decorators
(e.g. @staticmethod) are returned.
If the function is undecorated or only non-simple decorators
are found, return []. | [
"Return",
"a",
"list",
"of",
"decorators",
"found",
"on",
"a",
"function",
"definition",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/fixes/fix_annotate.py#L418-L438 | train |
dropbox/pyannotate | pyannotate_tools/fixes/fix_annotate.py | FixAnnotate.has_return_exprs | def has_return_exprs(self, node):
"""Traverse the tree below node looking for 'return expr'.
Return True if at least 'return expr' is found, False if not.
(If both 'return' and 'return expr' are found, return True.)
"""
results = {}
if self.return_expr.match(node, results):
return True
for child in node.children:
if child.type not in (syms.funcdef, syms.classdef):
if self.has_return_exprs(child):
return True
return False | python | def has_return_exprs(self, node):
"""Traverse the tree below node looking for 'return expr'.
Return True if at least 'return expr' is found, False if not.
(If both 'return' and 'return expr' are found, return True.)
"""
results = {}
if self.return_expr.match(node, results):
return True
for child in node.children:
if child.type not in (syms.funcdef, syms.classdef):
if self.has_return_exprs(child):
return True
return False | [
"def",
"has_return_exprs",
"(",
"self",
",",
"node",
")",
":",
"results",
"=",
"{",
"}",
"if",
"self",
".",
"return_expr",
".",
"match",
"(",
"node",
",",
"results",
")",
":",
"return",
"True",
"for",
"child",
"in",
"node",
".",
"children",
":",
"if",
"child",
".",
"type",
"not",
"in",
"(",
"syms",
".",
"funcdef",
",",
"syms",
".",
"classdef",
")",
":",
"if",
"self",
".",
"has_return_exprs",
"(",
"child",
")",
":",
"return",
"True",
"return",
"False"
]
| Traverse the tree below node looking for 'return expr'.
Return True if at least 'return expr' is found, False if not.
(If both 'return' and 'return expr' are found, return True.) | [
"Traverse",
"the",
"tree",
"below",
"node",
"looking",
"for",
"return",
"expr",
"."
]
| d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/fixes/fix_annotate.py#L454-L467 | train |
srsudar/eg | eg/config.py | inform_if_paths_invalid | def inform_if_paths_invalid(egrc_path, examples_dir, custom_dir, debug=True):
"""
If egrc_path, examples_dir, or custom_dir is truthy and debug is True,
informs the user that a path is not set.
This should be used to verify input arguments from the command line.
"""
if (not debug):
return
if (egrc_path):
_inform_if_path_does_not_exist(egrc_path)
if (examples_dir):
_inform_if_path_does_not_exist(examples_dir)
if (custom_dir):
_inform_if_path_does_not_exist(custom_dir) | python | def inform_if_paths_invalid(egrc_path, examples_dir, custom_dir, debug=True):
"""
If egrc_path, examples_dir, or custom_dir is truthy and debug is True,
informs the user that a path is not set.
This should be used to verify input arguments from the command line.
"""
if (not debug):
return
if (egrc_path):
_inform_if_path_does_not_exist(egrc_path)
if (examples_dir):
_inform_if_path_does_not_exist(examples_dir)
if (custom_dir):
_inform_if_path_does_not_exist(custom_dir) | [
"def",
"inform_if_paths_invalid",
"(",
"egrc_path",
",",
"examples_dir",
",",
"custom_dir",
",",
"debug",
"=",
"True",
")",
":",
"if",
"(",
"not",
"debug",
")",
":",
"return",
"if",
"(",
"egrc_path",
")",
":",
"_inform_if_path_does_not_exist",
"(",
"egrc_path",
")",
"if",
"(",
"examples_dir",
")",
":",
"_inform_if_path_does_not_exist",
"(",
"examples_dir",
")",
"if",
"(",
"custom_dir",
")",
":",
"_inform_if_path_does_not_exist",
"(",
"custom_dir",
")"
]
| If egrc_path, examples_dir, or custom_dir is truthy and debug is True,
informs the user that a path is not set.
This should be used to verify input arguments from the command line. | [
"If",
"egrc_path",
"examples_dir",
"or",
"custom_dir",
"is",
"truthy",
"and",
"debug",
"is",
"True",
"informs",
"the",
"user",
"that",
"a",
"path",
"is",
"not",
"set",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L131-L148 | train |
srsudar/eg | eg/config.py | get_egrc_config | def get_egrc_config(cli_egrc_path):
"""
Return a Config namedtuple based on the contents of the egrc.
If the egrc is not present, it returns an empty default Config.
This method tries to use the egrc at cli_egrc_path, then the default path.
cli_egrc_path: the path to the egrc as given on the command line via
--config-file
"""
resolved_path = get_priority(cli_egrc_path, DEFAULT_EGRC_PATH, None)
expanded_path = get_expanded_path(resolved_path)
# Start as if nothing was defined in the egrc.
egrc_config = get_empty_config()
if os.path.isfile(expanded_path):
egrc_config = get_config_tuple_from_egrc(expanded_path)
return egrc_config | python | def get_egrc_config(cli_egrc_path):
"""
Return a Config namedtuple based on the contents of the egrc.
If the egrc is not present, it returns an empty default Config.
This method tries to use the egrc at cli_egrc_path, then the default path.
cli_egrc_path: the path to the egrc as given on the command line via
--config-file
"""
resolved_path = get_priority(cli_egrc_path, DEFAULT_EGRC_PATH, None)
expanded_path = get_expanded_path(resolved_path)
# Start as if nothing was defined in the egrc.
egrc_config = get_empty_config()
if os.path.isfile(expanded_path):
egrc_config = get_config_tuple_from_egrc(expanded_path)
return egrc_config | [
"def",
"get_egrc_config",
"(",
"cli_egrc_path",
")",
":",
"resolved_path",
"=",
"get_priority",
"(",
"cli_egrc_path",
",",
"DEFAULT_EGRC_PATH",
",",
"None",
")",
"expanded_path",
"=",
"get_expanded_path",
"(",
"resolved_path",
")",
"# Start as if nothing was defined in the egrc.",
"egrc_config",
"=",
"get_empty_config",
"(",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"expanded_path",
")",
":",
"egrc_config",
"=",
"get_config_tuple_from_egrc",
"(",
"expanded_path",
")",
"return",
"egrc_config"
]
| Return a Config namedtuple based on the contents of the egrc.
If the egrc is not present, it returns an empty default Config.
This method tries to use the egrc at cli_egrc_path, then the default path.
cli_egrc_path: the path to the egrc as given on the command line via
--config-file | [
"Return",
"a",
"Config",
"namedtuple",
"based",
"on",
"the",
"contents",
"of",
"the",
"egrc",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L151-L171 | train |
srsudar/eg | eg/config.py | get_resolved_config | def get_resolved_config(
egrc_path,
examples_dir,
custom_dir,
use_color,
pager_cmd,
squeeze,
debug=True,
):
"""
Create a Config namedtuple. Passed in values will override defaults.
This function is responsible for producing a Config that is correct for the
passed in arguments. In general, it prefers first command line options,
then values from the egrc, and finally defaults.
examples_dir and custom_dir when returned from this function are fully
expanded.
"""
# Call this with the passed in values, NOT the resolved values. We are
# informing the caller only if values passed in at the command line are
# invalid. If you pass a path to a nonexistent egrc, for example, it's
# helpful to know. If you don't have an egrc, and thus one isn't found
# later at the default location, we don't want to notify them.
inform_if_paths_invalid(egrc_path, examples_dir, custom_dir)
# Expand the paths so we can use them with impunity later.
examples_dir = get_expanded_path(examples_dir)
custom_dir = get_expanded_path(custom_dir)
# The general rule is: caller-defined, egrc-defined, defaults. We'll try
# and get all three then use get_priority to choose the right one.
egrc_config = get_egrc_config(egrc_path)
resolved_examples_dir = get_priority(
examples_dir,
egrc_config.examples_dir,
DEFAULT_EXAMPLES_DIR
)
resolved_examples_dir = get_expanded_path(resolved_examples_dir)
resolved_custom_dir = get_priority(
custom_dir,
egrc_config.custom_dir,
DEFAULT_CUSTOM_DIR
)
resolved_custom_dir = get_expanded_path(resolved_custom_dir)
resolved_use_color = get_priority(
use_color,
egrc_config.use_color,
DEFAULT_USE_COLOR
)
resolved_pager_cmd = get_priority(
pager_cmd,
egrc_config.pager_cmd,
DEFAULT_PAGER_CMD
)
# There is no command line option for this, so in this case we will use the
# priority: egrc, environment, DEFAULT.
environment_editor_cmd = get_editor_cmd_from_environment()
resolved_editor_cmd = get_priority(
egrc_config.editor_cmd,
environment_editor_cmd,
DEFAULT_EDITOR_CMD
)
color_config = None
if resolved_use_color:
default_color_config = get_default_color_config()
color_config = merge_color_configs(
egrc_config.color_config,
default_color_config
)
resolved_squeeze = get_priority(
squeeze,
egrc_config.squeeze,
DEFAULT_SQUEEZE
)
# Pass in None, as subs can't be specified at the command line.
resolved_subs = get_priority(
None,
egrc_config.subs,
get_default_subs()
)
result = Config(
examples_dir=resolved_examples_dir,
custom_dir=resolved_custom_dir,
color_config=color_config,
use_color=resolved_use_color,
pager_cmd=resolved_pager_cmd,
editor_cmd=resolved_editor_cmd,
squeeze=resolved_squeeze,
subs=resolved_subs,
)
return result | python | def get_resolved_config(
egrc_path,
examples_dir,
custom_dir,
use_color,
pager_cmd,
squeeze,
debug=True,
):
"""
Create a Config namedtuple. Passed in values will override defaults.
This function is responsible for producing a Config that is correct for the
passed in arguments. In general, it prefers first command line options,
then values from the egrc, and finally defaults.
examples_dir and custom_dir when returned from this function are fully
expanded.
"""
# Call this with the passed in values, NOT the resolved values. We are
# informing the caller only if values passed in at the command line are
# invalid. If you pass a path to a nonexistent egrc, for example, it's
# helpful to know. If you don't have an egrc, and thus one isn't found
# later at the default location, we don't want to notify them.
inform_if_paths_invalid(egrc_path, examples_dir, custom_dir)
# Expand the paths so we can use them with impunity later.
examples_dir = get_expanded_path(examples_dir)
custom_dir = get_expanded_path(custom_dir)
# The general rule is: caller-defined, egrc-defined, defaults. We'll try
# and get all three then use get_priority to choose the right one.
egrc_config = get_egrc_config(egrc_path)
resolved_examples_dir = get_priority(
examples_dir,
egrc_config.examples_dir,
DEFAULT_EXAMPLES_DIR
)
resolved_examples_dir = get_expanded_path(resolved_examples_dir)
resolved_custom_dir = get_priority(
custom_dir,
egrc_config.custom_dir,
DEFAULT_CUSTOM_DIR
)
resolved_custom_dir = get_expanded_path(resolved_custom_dir)
resolved_use_color = get_priority(
use_color,
egrc_config.use_color,
DEFAULT_USE_COLOR
)
resolved_pager_cmd = get_priority(
pager_cmd,
egrc_config.pager_cmd,
DEFAULT_PAGER_CMD
)
# There is no command line option for this, so in this case we will use the
# priority: egrc, environment, DEFAULT.
environment_editor_cmd = get_editor_cmd_from_environment()
resolved_editor_cmd = get_priority(
egrc_config.editor_cmd,
environment_editor_cmd,
DEFAULT_EDITOR_CMD
)
color_config = None
if resolved_use_color:
default_color_config = get_default_color_config()
color_config = merge_color_configs(
egrc_config.color_config,
default_color_config
)
resolved_squeeze = get_priority(
squeeze,
egrc_config.squeeze,
DEFAULT_SQUEEZE
)
# Pass in None, as subs can't be specified at the command line.
resolved_subs = get_priority(
None,
egrc_config.subs,
get_default_subs()
)
result = Config(
examples_dir=resolved_examples_dir,
custom_dir=resolved_custom_dir,
color_config=color_config,
use_color=resolved_use_color,
pager_cmd=resolved_pager_cmd,
editor_cmd=resolved_editor_cmd,
squeeze=resolved_squeeze,
subs=resolved_subs,
)
return result | [
"def",
"get_resolved_config",
"(",
"egrc_path",
",",
"examples_dir",
",",
"custom_dir",
",",
"use_color",
",",
"pager_cmd",
",",
"squeeze",
",",
"debug",
"=",
"True",
",",
")",
":",
"# Call this with the passed in values, NOT the resolved values. We are",
"# informing the caller only if values passed in at the command line are",
"# invalid. If you pass a path to a nonexistent egrc, for example, it's",
"# helpful to know. If you don't have an egrc, and thus one isn't found",
"# later at the default location, we don't want to notify them.",
"inform_if_paths_invalid",
"(",
"egrc_path",
",",
"examples_dir",
",",
"custom_dir",
")",
"# Expand the paths so we can use them with impunity later.",
"examples_dir",
"=",
"get_expanded_path",
"(",
"examples_dir",
")",
"custom_dir",
"=",
"get_expanded_path",
"(",
"custom_dir",
")",
"# The general rule is: caller-defined, egrc-defined, defaults. We'll try",
"# and get all three then use get_priority to choose the right one.",
"egrc_config",
"=",
"get_egrc_config",
"(",
"egrc_path",
")",
"resolved_examples_dir",
"=",
"get_priority",
"(",
"examples_dir",
",",
"egrc_config",
".",
"examples_dir",
",",
"DEFAULT_EXAMPLES_DIR",
")",
"resolved_examples_dir",
"=",
"get_expanded_path",
"(",
"resolved_examples_dir",
")",
"resolved_custom_dir",
"=",
"get_priority",
"(",
"custom_dir",
",",
"egrc_config",
".",
"custom_dir",
",",
"DEFAULT_CUSTOM_DIR",
")",
"resolved_custom_dir",
"=",
"get_expanded_path",
"(",
"resolved_custom_dir",
")",
"resolved_use_color",
"=",
"get_priority",
"(",
"use_color",
",",
"egrc_config",
".",
"use_color",
",",
"DEFAULT_USE_COLOR",
")",
"resolved_pager_cmd",
"=",
"get_priority",
"(",
"pager_cmd",
",",
"egrc_config",
".",
"pager_cmd",
",",
"DEFAULT_PAGER_CMD",
")",
"# There is no command line option for this, so in this case we will use the",
"# priority: egrc, environment, DEFAULT.",
"environment_editor_cmd",
"=",
"get_editor_cmd_from_environment",
"(",
")",
"resolved_editor_cmd",
"=",
"get_priority",
"(",
"egrc_config",
".",
"editor_cmd",
",",
"environment_editor_cmd",
",",
"DEFAULT_EDITOR_CMD",
")",
"color_config",
"=",
"None",
"if",
"resolved_use_color",
":",
"default_color_config",
"=",
"get_default_color_config",
"(",
")",
"color_config",
"=",
"merge_color_configs",
"(",
"egrc_config",
".",
"color_config",
",",
"default_color_config",
")",
"resolved_squeeze",
"=",
"get_priority",
"(",
"squeeze",
",",
"egrc_config",
".",
"squeeze",
",",
"DEFAULT_SQUEEZE",
")",
"# Pass in None, as subs can't be specified at the command line.",
"resolved_subs",
"=",
"get_priority",
"(",
"None",
",",
"egrc_config",
".",
"subs",
",",
"get_default_subs",
"(",
")",
")",
"result",
"=",
"Config",
"(",
"examples_dir",
"=",
"resolved_examples_dir",
",",
"custom_dir",
"=",
"resolved_custom_dir",
",",
"color_config",
"=",
"color_config",
",",
"use_color",
"=",
"resolved_use_color",
",",
"pager_cmd",
"=",
"resolved_pager_cmd",
",",
"editor_cmd",
"=",
"resolved_editor_cmd",
",",
"squeeze",
"=",
"resolved_squeeze",
",",
"subs",
"=",
"resolved_subs",
",",
")",
"return",
"result"
]
| Create a Config namedtuple. Passed in values will override defaults.
This function is responsible for producing a Config that is correct for the
passed in arguments. In general, it prefers first command line options,
then values from the egrc, and finally defaults.
examples_dir and custom_dir when returned from this function are fully
expanded. | [
"Create",
"a",
"Config",
"namedtuple",
".",
"Passed",
"in",
"values",
"will",
"override",
"defaults",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L174-L276 | train |
srsudar/eg | eg/config.py | get_config_tuple_from_egrc | def get_config_tuple_from_egrc(egrc_path):
"""
Create a Config named tuple from the values specified in the .egrc. Expands
any paths as necessary.
egrc_path must exist and point a file.
If not present in the .egrc, properties of the Config are returned as None.
"""
with open(egrc_path, 'r') as egrc:
try:
config = ConfigParser.RawConfigParser()
except AttributeError:
config = ConfigParser()
config.readfp(egrc)
# default to None
examples_dir = None
custom_dir = None
use_color = None
pager_cmd = None
squeeze = None
subs = None
editor_cmd = None
if config.has_option(DEFAULT_SECTION, EG_EXAMPLES_DIR):
examples_dir = config.get(DEFAULT_SECTION, EG_EXAMPLES_DIR)
examples_dir = get_expanded_path(examples_dir)
if config.has_option(DEFAULT_SECTION, CUSTOM_EXAMPLES_DIR):
custom_dir = config.get(DEFAULT_SECTION, CUSTOM_EXAMPLES_DIR)
custom_dir = get_expanded_path(custom_dir)
if config.has_option(DEFAULT_SECTION, USE_COLOR):
use_color_raw = config.get(DEFAULT_SECTION, USE_COLOR)
use_color = _parse_bool_from_raw_egrc_value(use_color_raw)
if config.has_option(DEFAULT_SECTION, PAGER_CMD):
pager_cmd_raw = config.get(DEFAULT_SECTION, PAGER_CMD)
pager_cmd = ast.literal_eval(pager_cmd_raw)
if config.has_option(DEFAULT_SECTION, EDITOR_CMD):
editor_cmd_raw = config.get(DEFAULT_SECTION, EDITOR_CMD)
editor_cmd = ast.literal_eval(editor_cmd_raw)
color_config = get_custom_color_config_from_egrc(config)
if config.has_option(DEFAULT_SECTION, SQUEEZE):
squeeze_raw = config.get(DEFAULT_SECTION, SQUEEZE)
squeeze = _parse_bool_from_raw_egrc_value(squeeze_raw)
if config.has_section(SUBSTITUTION_SECTION):
subs = get_substitutions_from_config(config)
return Config(
examples_dir=examples_dir,
custom_dir=custom_dir,
color_config=color_config,
use_color=use_color,
pager_cmd=pager_cmd,
editor_cmd=editor_cmd,
squeeze=squeeze,
subs=subs,
) | python | def get_config_tuple_from_egrc(egrc_path):
"""
Create a Config named tuple from the values specified in the .egrc. Expands
any paths as necessary.
egrc_path must exist and point a file.
If not present in the .egrc, properties of the Config are returned as None.
"""
with open(egrc_path, 'r') as egrc:
try:
config = ConfigParser.RawConfigParser()
except AttributeError:
config = ConfigParser()
config.readfp(egrc)
# default to None
examples_dir = None
custom_dir = None
use_color = None
pager_cmd = None
squeeze = None
subs = None
editor_cmd = None
if config.has_option(DEFAULT_SECTION, EG_EXAMPLES_DIR):
examples_dir = config.get(DEFAULT_SECTION, EG_EXAMPLES_DIR)
examples_dir = get_expanded_path(examples_dir)
if config.has_option(DEFAULT_SECTION, CUSTOM_EXAMPLES_DIR):
custom_dir = config.get(DEFAULT_SECTION, CUSTOM_EXAMPLES_DIR)
custom_dir = get_expanded_path(custom_dir)
if config.has_option(DEFAULT_SECTION, USE_COLOR):
use_color_raw = config.get(DEFAULT_SECTION, USE_COLOR)
use_color = _parse_bool_from_raw_egrc_value(use_color_raw)
if config.has_option(DEFAULT_SECTION, PAGER_CMD):
pager_cmd_raw = config.get(DEFAULT_SECTION, PAGER_CMD)
pager_cmd = ast.literal_eval(pager_cmd_raw)
if config.has_option(DEFAULT_SECTION, EDITOR_CMD):
editor_cmd_raw = config.get(DEFAULT_SECTION, EDITOR_CMD)
editor_cmd = ast.literal_eval(editor_cmd_raw)
color_config = get_custom_color_config_from_egrc(config)
if config.has_option(DEFAULT_SECTION, SQUEEZE):
squeeze_raw = config.get(DEFAULT_SECTION, SQUEEZE)
squeeze = _parse_bool_from_raw_egrc_value(squeeze_raw)
if config.has_section(SUBSTITUTION_SECTION):
subs = get_substitutions_from_config(config)
return Config(
examples_dir=examples_dir,
custom_dir=custom_dir,
color_config=color_config,
use_color=use_color,
pager_cmd=pager_cmd,
editor_cmd=editor_cmd,
squeeze=squeeze,
subs=subs,
) | [
"def",
"get_config_tuple_from_egrc",
"(",
"egrc_path",
")",
":",
"with",
"open",
"(",
"egrc_path",
",",
"'r'",
")",
"as",
"egrc",
":",
"try",
":",
"config",
"=",
"ConfigParser",
".",
"RawConfigParser",
"(",
")",
"except",
"AttributeError",
":",
"config",
"=",
"ConfigParser",
"(",
")",
"config",
".",
"readfp",
"(",
"egrc",
")",
"# default to None",
"examples_dir",
"=",
"None",
"custom_dir",
"=",
"None",
"use_color",
"=",
"None",
"pager_cmd",
"=",
"None",
"squeeze",
"=",
"None",
"subs",
"=",
"None",
"editor_cmd",
"=",
"None",
"if",
"config",
".",
"has_option",
"(",
"DEFAULT_SECTION",
",",
"EG_EXAMPLES_DIR",
")",
":",
"examples_dir",
"=",
"config",
".",
"get",
"(",
"DEFAULT_SECTION",
",",
"EG_EXAMPLES_DIR",
")",
"examples_dir",
"=",
"get_expanded_path",
"(",
"examples_dir",
")",
"if",
"config",
".",
"has_option",
"(",
"DEFAULT_SECTION",
",",
"CUSTOM_EXAMPLES_DIR",
")",
":",
"custom_dir",
"=",
"config",
".",
"get",
"(",
"DEFAULT_SECTION",
",",
"CUSTOM_EXAMPLES_DIR",
")",
"custom_dir",
"=",
"get_expanded_path",
"(",
"custom_dir",
")",
"if",
"config",
".",
"has_option",
"(",
"DEFAULT_SECTION",
",",
"USE_COLOR",
")",
":",
"use_color_raw",
"=",
"config",
".",
"get",
"(",
"DEFAULT_SECTION",
",",
"USE_COLOR",
")",
"use_color",
"=",
"_parse_bool_from_raw_egrc_value",
"(",
"use_color_raw",
")",
"if",
"config",
".",
"has_option",
"(",
"DEFAULT_SECTION",
",",
"PAGER_CMD",
")",
":",
"pager_cmd_raw",
"=",
"config",
".",
"get",
"(",
"DEFAULT_SECTION",
",",
"PAGER_CMD",
")",
"pager_cmd",
"=",
"ast",
".",
"literal_eval",
"(",
"pager_cmd_raw",
")",
"if",
"config",
".",
"has_option",
"(",
"DEFAULT_SECTION",
",",
"EDITOR_CMD",
")",
":",
"editor_cmd_raw",
"=",
"config",
".",
"get",
"(",
"DEFAULT_SECTION",
",",
"EDITOR_CMD",
")",
"editor_cmd",
"=",
"ast",
".",
"literal_eval",
"(",
"editor_cmd_raw",
")",
"color_config",
"=",
"get_custom_color_config_from_egrc",
"(",
"config",
")",
"if",
"config",
".",
"has_option",
"(",
"DEFAULT_SECTION",
",",
"SQUEEZE",
")",
":",
"squeeze_raw",
"=",
"config",
".",
"get",
"(",
"DEFAULT_SECTION",
",",
"SQUEEZE",
")",
"squeeze",
"=",
"_parse_bool_from_raw_egrc_value",
"(",
"squeeze_raw",
")",
"if",
"config",
".",
"has_section",
"(",
"SUBSTITUTION_SECTION",
")",
":",
"subs",
"=",
"get_substitutions_from_config",
"(",
"config",
")",
"return",
"Config",
"(",
"examples_dir",
"=",
"examples_dir",
",",
"custom_dir",
"=",
"custom_dir",
",",
"color_config",
"=",
"color_config",
",",
"use_color",
"=",
"use_color",
",",
"pager_cmd",
"=",
"pager_cmd",
",",
"editor_cmd",
"=",
"editor_cmd",
",",
"squeeze",
"=",
"squeeze",
",",
"subs",
"=",
"subs",
",",
")"
]
| Create a Config named tuple from the values specified in the .egrc. Expands
any paths as necessary.
egrc_path must exist and point a file.
If not present in the .egrc, properties of the Config are returned as None. | [
"Create",
"a",
"Config",
"named",
"tuple",
"from",
"the",
"values",
"specified",
"in",
"the",
".",
"egrc",
".",
"Expands",
"any",
"paths",
"as",
"necessary",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L279-L342 | train |
srsudar/eg | eg/config.py | get_expanded_path | def get_expanded_path(path):
"""Expand ~ and variables in a path. If path is not truthy, return None."""
if path:
result = path
result = os.path.expanduser(result)
result = os.path.expandvars(result)
return result
else:
return None | python | def get_expanded_path(path):
"""Expand ~ and variables in a path. If path is not truthy, return None."""
if path:
result = path
result = os.path.expanduser(result)
result = os.path.expandvars(result)
return result
else:
return None | [
"def",
"get_expanded_path",
"(",
"path",
")",
":",
"if",
"path",
":",
"result",
"=",
"path",
"result",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"result",
")",
"result",
"=",
"os",
".",
"path",
".",
"expandvars",
"(",
"result",
")",
"return",
"result",
"else",
":",
"return",
"None"
]
| Expand ~ and variables in a path. If path is not truthy, return None. | [
"Expand",
"~",
"and",
"variables",
"in",
"a",
"path",
".",
"If",
"path",
"is",
"not",
"truthy",
"return",
"None",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L345-L353 | train |
srsudar/eg | eg/config.py | get_editor_cmd_from_environment | def get_editor_cmd_from_environment():
"""
Gets and editor command from environment variables.
It first tries $VISUAL, then $EDITOR, following the same order git uses
when it looks up edits. If neither is available, it returns None.
"""
result = os.getenv(ENV_VISUAL)
if (not result):
result = os.getenv(ENV_EDITOR)
return result | python | def get_editor_cmd_from_environment():
"""
Gets and editor command from environment variables.
It first tries $VISUAL, then $EDITOR, following the same order git uses
when it looks up edits. If neither is available, it returns None.
"""
result = os.getenv(ENV_VISUAL)
if (not result):
result = os.getenv(ENV_EDITOR)
return result | [
"def",
"get_editor_cmd_from_environment",
"(",
")",
":",
"result",
"=",
"os",
".",
"getenv",
"(",
"ENV_VISUAL",
")",
"if",
"(",
"not",
"result",
")",
":",
"result",
"=",
"os",
".",
"getenv",
"(",
"ENV_EDITOR",
")",
"return",
"result"
]
| Gets and editor command from environment variables.
It first tries $VISUAL, then $EDITOR, following the same order git uses
when it looks up edits. If neither is available, it returns None. | [
"Gets",
"and",
"editor",
"command",
"from",
"environment",
"variables",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L356-L366 | train |
srsudar/eg | eg/config.py | _inform_if_path_does_not_exist | def _inform_if_path_does_not_exist(path):
"""
If the path does not exist, print a message saying so. This is intended to
be helpful to users if they specify a custom path that eg cannot find.
"""
expanded_path = get_expanded_path(path)
if not os.path.exists(expanded_path):
print('Could not find custom path at: {}'.format(expanded_path)) | python | def _inform_if_path_does_not_exist(path):
"""
If the path does not exist, print a message saying so. This is intended to
be helpful to users if they specify a custom path that eg cannot find.
"""
expanded_path = get_expanded_path(path)
if not os.path.exists(expanded_path):
print('Could not find custom path at: {}'.format(expanded_path)) | [
"def",
"_inform_if_path_does_not_exist",
"(",
"path",
")",
":",
"expanded_path",
"=",
"get_expanded_path",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"expanded_path",
")",
":",
"print",
"(",
"'Could not find custom path at: {}'",
".",
"format",
"(",
"expanded_path",
")",
")"
]
| If the path does not exist, print a message saying so. This is intended to
be helpful to users if they specify a custom path that eg cannot find. | [
"If",
"the",
"path",
"does",
"not",
"exist",
"print",
"a",
"message",
"saying",
"so",
".",
"This",
"is",
"intended",
"to",
"be",
"helpful",
"to",
"users",
"if",
"they",
"specify",
"a",
"custom",
"path",
"that",
"eg",
"cannot",
"find",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L383-L390 | train |
srsudar/eg | eg/config.py | get_custom_color_config_from_egrc | def get_custom_color_config_from_egrc(config):
"""
Get the ColorConfig from the egrc config object. Any colors not defined
will be None.
"""
pound = _get_color_from_config(config, CONFIG_NAMES.pound)
heading = _get_color_from_config(config, CONFIG_NAMES.heading)
code = _get_color_from_config(config, CONFIG_NAMES.code)
backticks = _get_color_from_config(config, CONFIG_NAMES.backticks)
prompt = _get_color_from_config(config, CONFIG_NAMES.prompt)
pound_reset = _get_color_from_config(config, CONFIG_NAMES.pound_reset)
heading_reset = _get_color_from_config(
config,
CONFIG_NAMES.heading_reset
)
code_reset = _get_color_from_config(config, CONFIG_NAMES.code_reset)
backticks_reset = _get_color_from_config(
config,
CONFIG_NAMES.backticks_reset
)
prompt_reset = _get_color_from_config(config, CONFIG_NAMES.prompt_reset)
result = ColorConfig(
pound=pound,
heading=heading,
code=code,
backticks=backticks,
prompt=prompt,
pound_reset=pound_reset,
heading_reset=heading_reset,
code_reset=code_reset,
backticks_reset=backticks_reset,
prompt_reset=prompt_reset
)
return result | python | def get_custom_color_config_from_egrc(config):
"""
Get the ColorConfig from the egrc config object. Any colors not defined
will be None.
"""
pound = _get_color_from_config(config, CONFIG_NAMES.pound)
heading = _get_color_from_config(config, CONFIG_NAMES.heading)
code = _get_color_from_config(config, CONFIG_NAMES.code)
backticks = _get_color_from_config(config, CONFIG_NAMES.backticks)
prompt = _get_color_from_config(config, CONFIG_NAMES.prompt)
pound_reset = _get_color_from_config(config, CONFIG_NAMES.pound_reset)
heading_reset = _get_color_from_config(
config,
CONFIG_NAMES.heading_reset
)
code_reset = _get_color_from_config(config, CONFIG_NAMES.code_reset)
backticks_reset = _get_color_from_config(
config,
CONFIG_NAMES.backticks_reset
)
prompt_reset = _get_color_from_config(config, CONFIG_NAMES.prompt_reset)
result = ColorConfig(
pound=pound,
heading=heading,
code=code,
backticks=backticks,
prompt=prompt,
pound_reset=pound_reset,
heading_reset=heading_reset,
code_reset=code_reset,
backticks_reset=backticks_reset,
prompt_reset=prompt_reset
)
return result | [
"def",
"get_custom_color_config_from_egrc",
"(",
"config",
")",
":",
"pound",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"pound",
")",
"heading",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"heading",
")",
"code",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"code",
")",
"backticks",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"backticks",
")",
"prompt",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"prompt",
")",
"pound_reset",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"pound_reset",
")",
"heading_reset",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"heading_reset",
")",
"code_reset",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"code_reset",
")",
"backticks_reset",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"backticks_reset",
")",
"prompt_reset",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"prompt_reset",
")",
"result",
"=",
"ColorConfig",
"(",
"pound",
"=",
"pound",
",",
"heading",
"=",
"heading",
",",
"code",
"=",
"code",
",",
"backticks",
"=",
"backticks",
",",
"prompt",
"=",
"prompt",
",",
"pound_reset",
"=",
"pound_reset",
",",
"heading_reset",
"=",
"heading_reset",
",",
"code_reset",
"=",
"code_reset",
",",
"backticks_reset",
"=",
"backticks_reset",
",",
"prompt_reset",
"=",
"prompt_reset",
")",
"return",
"result"
]
| Get the ColorConfig from the egrc config object. Any colors not defined
will be None. | [
"Get",
"the",
"ColorConfig",
"from",
"the",
"egrc",
"config",
"object",
".",
"Any",
"colors",
"not",
"defined",
"will",
"be",
"None",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L393-L428 | train |
srsudar/eg | eg/config.py | _get_color_from_config | def _get_color_from_config(config, option):
"""
Helper method to uet an option from the COLOR_SECTION of the config.
Returns None if the value is not present. If the value is present, it tries
to parse the value as a raw string literal, allowing escape sequences in
the egrc.
"""
if not config.has_option(COLOR_SECTION, option):
return None
else:
return ast.literal_eval(config.get(COLOR_SECTION, option)) | python | def _get_color_from_config(config, option):
"""
Helper method to uet an option from the COLOR_SECTION of the config.
Returns None if the value is not present. If the value is present, it tries
to parse the value as a raw string literal, allowing escape sequences in
the egrc.
"""
if not config.has_option(COLOR_SECTION, option):
return None
else:
return ast.literal_eval(config.get(COLOR_SECTION, option)) | [
"def",
"_get_color_from_config",
"(",
"config",
",",
"option",
")",
":",
"if",
"not",
"config",
".",
"has_option",
"(",
"COLOR_SECTION",
",",
"option",
")",
":",
"return",
"None",
"else",
":",
"return",
"ast",
".",
"literal_eval",
"(",
"config",
".",
"get",
"(",
"COLOR_SECTION",
",",
"option",
")",
")"
]
| Helper method to uet an option from the COLOR_SECTION of the config.
Returns None if the value is not present. If the value is present, it tries
to parse the value as a raw string literal, allowing escape sequences in
the egrc. | [
"Helper",
"method",
"to",
"uet",
"an",
"option",
"from",
"the",
"COLOR_SECTION",
"of",
"the",
"config",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L431-L442 | train |
srsudar/eg | eg/config.py | parse_substitution_from_list | def parse_substitution_from_list(list_rep):
"""
Parse a substitution from the list representation in the config file.
"""
# We are expecting [pattern, replacement [, is_multiline]]
if type(list_rep) is not list:
raise SyntaxError('Substitution must be a list')
if len(list_rep) < 2:
raise SyntaxError('Substitution must be a list of size 2')
pattern = list_rep[0]
replacement = list_rep[1]
# By default, substitutions are not multiline.
is_multiline = False
if (len(list_rep) > 2):
is_multiline = list_rep[2]
if type(is_multiline) is not bool:
raise SyntaxError('is_multiline must be a boolean')
result = substitute.Substitution(pattern, replacement, is_multiline)
return result | python | def parse_substitution_from_list(list_rep):
"""
Parse a substitution from the list representation in the config file.
"""
# We are expecting [pattern, replacement [, is_multiline]]
if type(list_rep) is not list:
raise SyntaxError('Substitution must be a list')
if len(list_rep) < 2:
raise SyntaxError('Substitution must be a list of size 2')
pattern = list_rep[0]
replacement = list_rep[1]
# By default, substitutions are not multiline.
is_multiline = False
if (len(list_rep) > 2):
is_multiline = list_rep[2]
if type(is_multiline) is not bool:
raise SyntaxError('is_multiline must be a boolean')
result = substitute.Substitution(pattern, replacement, is_multiline)
return result | [
"def",
"parse_substitution_from_list",
"(",
"list_rep",
")",
":",
"# We are expecting [pattern, replacement [, is_multiline]]",
"if",
"type",
"(",
"list_rep",
")",
"is",
"not",
"list",
":",
"raise",
"SyntaxError",
"(",
"'Substitution must be a list'",
")",
"if",
"len",
"(",
"list_rep",
")",
"<",
"2",
":",
"raise",
"SyntaxError",
"(",
"'Substitution must be a list of size 2'",
")",
"pattern",
"=",
"list_rep",
"[",
"0",
"]",
"replacement",
"=",
"list_rep",
"[",
"1",
"]",
"# By default, substitutions are not multiline.",
"is_multiline",
"=",
"False",
"if",
"(",
"len",
"(",
"list_rep",
")",
">",
"2",
")",
":",
"is_multiline",
"=",
"list_rep",
"[",
"2",
"]",
"if",
"type",
"(",
"is_multiline",
")",
"is",
"not",
"bool",
":",
"raise",
"SyntaxError",
"(",
"'is_multiline must be a boolean'",
")",
"result",
"=",
"substitute",
".",
"Substitution",
"(",
"pattern",
",",
"replacement",
",",
"is_multiline",
")",
"return",
"result"
]
| Parse a substitution from the list representation in the config file. | [
"Parse",
"a",
"substitution",
"from",
"the",
"list",
"representation",
"in",
"the",
"config",
"file",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L445-L466 | train |
srsudar/eg | eg/config.py | get_substitutions_from_config | def get_substitutions_from_config(config):
"""
Return a list of Substitution objects from the config, sorted
alphabetically by pattern name. Returns an empty list if no Substitutions
are specified. If there are problems parsing the values, a help message
will be printed and an error will be thrown.
"""
result = []
pattern_names = config.options(SUBSTITUTION_SECTION)
pattern_names.sort()
for name in pattern_names:
pattern_val = config.get(SUBSTITUTION_SECTION, name)
list_rep = ast.literal_eval(pattern_val)
substitution = parse_substitution_from_list(list_rep)
result.append(substitution)
return result | python | def get_substitutions_from_config(config):
"""
Return a list of Substitution objects from the config, sorted
alphabetically by pattern name. Returns an empty list if no Substitutions
are specified. If there are problems parsing the values, a help message
will be printed and an error will be thrown.
"""
result = []
pattern_names = config.options(SUBSTITUTION_SECTION)
pattern_names.sort()
for name in pattern_names:
pattern_val = config.get(SUBSTITUTION_SECTION, name)
list_rep = ast.literal_eval(pattern_val)
substitution = parse_substitution_from_list(list_rep)
result.append(substitution)
return result | [
"def",
"get_substitutions_from_config",
"(",
"config",
")",
":",
"result",
"=",
"[",
"]",
"pattern_names",
"=",
"config",
".",
"options",
"(",
"SUBSTITUTION_SECTION",
")",
"pattern_names",
".",
"sort",
"(",
")",
"for",
"name",
"in",
"pattern_names",
":",
"pattern_val",
"=",
"config",
".",
"get",
"(",
"SUBSTITUTION_SECTION",
",",
"name",
")",
"list_rep",
"=",
"ast",
".",
"literal_eval",
"(",
"pattern_val",
")",
"substitution",
"=",
"parse_substitution_from_list",
"(",
"list_rep",
")",
"result",
".",
"append",
"(",
"substitution",
")",
"return",
"result"
]
| Return a list of Substitution objects from the config, sorted
alphabetically by pattern name. Returns an empty list if no Substitutions
are specified. If there are problems parsing the values, a help message
will be printed and an error will be thrown. | [
"Return",
"a",
"list",
"of",
"Substitution",
"objects",
"from",
"the",
"config",
"sorted",
"alphabetically",
"by",
"pattern",
"name",
".",
"Returns",
"an",
"empty",
"list",
"if",
"no",
"Substitutions",
"are",
"specified",
".",
"If",
"there",
"are",
"problems",
"parsing",
"the",
"values",
"a",
"help",
"message",
"will",
"be",
"printed",
"and",
"an",
"error",
"will",
"be",
"thrown",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L469-L484 | train |
srsudar/eg | eg/config.py | get_default_color_config | def get_default_color_config():
"""Get a color config object with all the defaults."""
result = ColorConfig(
pound=DEFAULT_COLOR_POUND,
heading=DEFAULT_COLOR_HEADING,
code=DEFAULT_COLOR_CODE,
backticks=DEFAULT_COLOR_BACKTICKS,
prompt=DEFAULT_COLOR_PROMPT,
pound_reset=DEFAULT_COLOR_POUND_RESET,
heading_reset=DEFAULT_COLOR_HEADING_RESET,
code_reset=DEFAULT_COLOR_CODE_RESET,
backticks_reset=DEFAULT_COLOR_BACKTICKS_RESET,
prompt_reset=DEFAULT_COLOR_PROMPT_RESET
)
return result | python | def get_default_color_config():
"""Get a color config object with all the defaults."""
result = ColorConfig(
pound=DEFAULT_COLOR_POUND,
heading=DEFAULT_COLOR_HEADING,
code=DEFAULT_COLOR_CODE,
backticks=DEFAULT_COLOR_BACKTICKS,
prompt=DEFAULT_COLOR_PROMPT,
pound_reset=DEFAULT_COLOR_POUND_RESET,
heading_reset=DEFAULT_COLOR_HEADING_RESET,
code_reset=DEFAULT_COLOR_CODE_RESET,
backticks_reset=DEFAULT_COLOR_BACKTICKS_RESET,
prompt_reset=DEFAULT_COLOR_PROMPT_RESET
)
return result | [
"def",
"get_default_color_config",
"(",
")",
":",
"result",
"=",
"ColorConfig",
"(",
"pound",
"=",
"DEFAULT_COLOR_POUND",
",",
"heading",
"=",
"DEFAULT_COLOR_HEADING",
",",
"code",
"=",
"DEFAULT_COLOR_CODE",
",",
"backticks",
"=",
"DEFAULT_COLOR_BACKTICKS",
",",
"prompt",
"=",
"DEFAULT_COLOR_PROMPT",
",",
"pound_reset",
"=",
"DEFAULT_COLOR_POUND_RESET",
",",
"heading_reset",
"=",
"DEFAULT_COLOR_HEADING_RESET",
",",
"code_reset",
"=",
"DEFAULT_COLOR_CODE_RESET",
",",
"backticks_reset",
"=",
"DEFAULT_COLOR_BACKTICKS_RESET",
",",
"prompt_reset",
"=",
"DEFAULT_COLOR_PROMPT_RESET",
")",
"return",
"result"
]
| Get a color config object with all the defaults. | [
"Get",
"a",
"color",
"config",
"object",
"with",
"all",
"the",
"defaults",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L487-L501 | train |
srsudar/eg | eg/config.py | get_empty_config | def get_empty_config():
"""
Return an empty Config object with no options set.
"""
empty_color_config = get_empty_color_config()
result = Config(
examples_dir=None,
custom_dir=None,
color_config=empty_color_config,
use_color=None,
pager_cmd=None,
editor_cmd=None,
squeeze=None,
subs=None
)
return result | python | def get_empty_config():
"""
Return an empty Config object with no options set.
"""
empty_color_config = get_empty_color_config()
result = Config(
examples_dir=None,
custom_dir=None,
color_config=empty_color_config,
use_color=None,
pager_cmd=None,
editor_cmd=None,
squeeze=None,
subs=None
)
return result | [
"def",
"get_empty_config",
"(",
")",
":",
"empty_color_config",
"=",
"get_empty_color_config",
"(",
")",
"result",
"=",
"Config",
"(",
"examples_dir",
"=",
"None",
",",
"custom_dir",
"=",
"None",
",",
"color_config",
"=",
"empty_color_config",
",",
"use_color",
"=",
"None",
",",
"pager_cmd",
"=",
"None",
",",
"editor_cmd",
"=",
"None",
",",
"squeeze",
"=",
"None",
",",
"subs",
"=",
"None",
")",
"return",
"result"
]
| Return an empty Config object with no options set. | [
"Return",
"an",
"empty",
"Config",
"object",
"with",
"no",
"options",
"set",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L504-L519 | train |
srsudar/eg | eg/config.py | get_empty_color_config | def get_empty_color_config():
"""Return a color_config with all values set to None."""
empty_color_config = ColorConfig(
pound=None,
heading=None,
code=None,
backticks=None,
prompt=None,
pound_reset=None,
heading_reset=None,
code_reset=None,
backticks_reset=None,
prompt_reset=None
)
return empty_color_config | python | def get_empty_color_config():
"""Return a color_config with all values set to None."""
empty_color_config = ColorConfig(
pound=None,
heading=None,
code=None,
backticks=None,
prompt=None,
pound_reset=None,
heading_reset=None,
code_reset=None,
backticks_reset=None,
prompt_reset=None
)
return empty_color_config | [
"def",
"get_empty_color_config",
"(",
")",
":",
"empty_color_config",
"=",
"ColorConfig",
"(",
"pound",
"=",
"None",
",",
"heading",
"=",
"None",
",",
"code",
"=",
"None",
",",
"backticks",
"=",
"None",
",",
"prompt",
"=",
"None",
",",
"pound_reset",
"=",
"None",
",",
"heading_reset",
"=",
"None",
",",
"code_reset",
"=",
"None",
",",
"backticks_reset",
"=",
"None",
",",
"prompt_reset",
"=",
"None",
")",
"return",
"empty_color_config"
]
| Return a color_config with all values set to None. | [
"Return",
"a",
"color_config",
"with",
"all",
"values",
"set",
"to",
"None",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L522-L536 | train |
srsudar/eg | eg/config.py | merge_color_configs | def merge_color_configs(first, second):
"""
Merge the color configs.
Values in the first will overwrite non-None values in the second.
"""
# We have to get the desired values first and simultaneously, as nametuple
# is immutable.
pound = get_priority(first.pound, second.pound, None)
heading = get_priority(first.heading, second.heading, None)
code = get_priority(first.code, second.code, None)
backticks = get_priority(first.backticks, second.backticks, None)
prompt = get_priority(first.prompt, second.prompt, None)
pound_reset = get_priority(
first.pound_reset,
second.pound_reset,
None
)
heading_reset = get_priority(
first.heading_reset,
second.heading_reset,
None
)
code_reset = get_priority(
first.code_reset,
second.code_reset,
None
)
backticks_reset = get_priority(
first.backticks_reset,
second.backticks_reset,
None
)
prompt_reset = get_priority(
first.prompt_reset,
second.prompt_reset,
None
)
result = ColorConfig(
pound=pound,
heading=heading,
code=code,
backticks=backticks,
prompt=prompt,
pound_reset=pound_reset,
heading_reset=heading_reset,
code_reset=code_reset,
backticks_reset=backticks_reset,
prompt_reset=prompt_reset
)
return result | python | def merge_color_configs(first, second):
"""
Merge the color configs.
Values in the first will overwrite non-None values in the second.
"""
# We have to get the desired values first and simultaneously, as nametuple
# is immutable.
pound = get_priority(first.pound, second.pound, None)
heading = get_priority(first.heading, second.heading, None)
code = get_priority(first.code, second.code, None)
backticks = get_priority(first.backticks, second.backticks, None)
prompt = get_priority(first.prompt, second.prompt, None)
pound_reset = get_priority(
first.pound_reset,
second.pound_reset,
None
)
heading_reset = get_priority(
first.heading_reset,
second.heading_reset,
None
)
code_reset = get_priority(
first.code_reset,
second.code_reset,
None
)
backticks_reset = get_priority(
first.backticks_reset,
second.backticks_reset,
None
)
prompt_reset = get_priority(
first.prompt_reset,
second.prompt_reset,
None
)
result = ColorConfig(
pound=pound,
heading=heading,
code=code,
backticks=backticks,
prompt=prompt,
pound_reset=pound_reset,
heading_reset=heading_reset,
code_reset=code_reset,
backticks_reset=backticks_reset,
prompt_reset=prompt_reset
)
return result | [
"def",
"merge_color_configs",
"(",
"first",
",",
"second",
")",
":",
"# We have to get the desired values first and simultaneously, as nametuple",
"# is immutable.",
"pound",
"=",
"get_priority",
"(",
"first",
".",
"pound",
",",
"second",
".",
"pound",
",",
"None",
")",
"heading",
"=",
"get_priority",
"(",
"first",
".",
"heading",
",",
"second",
".",
"heading",
",",
"None",
")",
"code",
"=",
"get_priority",
"(",
"first",
".",
"code",
",",
"second",
".",
"code",
",",
"None",
")",
"backticks",
"=",
"get_priority",
"(",
"first",
".",
"backticks",
",",
"second",
".",
"backticks",
",",
"None",
")",
"prompt",
"=",
"get_priority",
"(",
"first",
".",
"prompt",
",",
"second",
".",
"prompt",
",",
"None",
")",
"pound_reset",
"=",
"get_priority",
"(",
"first",
".",
"pound_reset",
",",
"second",
".",
"pound_reset",
",",
"None",
")",
"heading_reset",
"=",
"get_priority",
"(",
"first",
".",
"heading_reset",
",",
"second",
".",
"heading_reset",
",",
"None",
")",
"code_reset",
"=",
"get_priority",
"(",
"first",
".",
"code_reset",
",",
"second",
".",
"code_reset",
",",
"None",
")",
"backticks_reset",
"=",
"get_priority",
"(",
"first",
".",
"backticks_reset",
",",
"second",
".",
"backticks_reset",
",",
"None",
")",
"prompt_reset",
"=",
"get_priority",
"(",
"first",
".",
"prompt_reset",
",",
"second",
".",
"prompt_reset",
",",
"None",
")",
"result",
"=",
"ColorConfig",
"(",
"pound",
"=",
"pound",
",",
"heading",
"=",
"heading",
",",
"code",
"=",
"code",
",",
"backticks",
"=",
"backticks",
",",
"prompt",
"=",
"prompt",
",",
"pound_reset",
"=",
"pound_reset",
",",
"heading_reset",
"=",
"heading_reset",
",",
"code_reset",
"=",
"code_reset",
",",
"backticks_reset",
"=",
"backticks_reset",
",",
"prompt_reset",
"=",
"prompt_reset",
")",
"return",
"result"
]
| Merge the color configs.
Values in the first will overwrite non-None values in the second. | [
"Merge",
"the",
"color",
"configs",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L539-L591 | train |
srsudar/eg | eg/substitute.py | Substitution.apply_and_get_result | def apply_and_get_result(self, string):
"""
Perform the substitution represented by this object on string and return
the result.
"""
if self.is_multiline:
compiled_pattern = re.compile(self.pattern, re.MULTILINE)
else:
compiled_pattern = re.compile(self.pattern)
result = re.sub(compiled_pattern, self.repl, string)
return result | python | def apply_and_get_result(self, string):
"""
Perform the substitution represented by this object on string and return
the result.
"""
if self.is_multiline:
compiled_pattern = re.compile(self.pattern, re.MULTILINE)
else:
compiled_pattern = re.compile(self.pattern)
result = re.sub(compiled_pattern, self.repl, string)
return result | [
"def",
"apply_and_get_result",
"(",
"self",
",",
"string",
")",
":",
"if",
"self",
".",
"is_multiline",
":",
"compiled_pattern",
"=",
"re",
".",
"compile",
"(",
"self",
".",
"pattern",
",",
"re",
".",
"MULTILINE",
")",
"else",
":",
"compiled_pattern",
"=",
"re",
".",
"compile",
"(",
"self",
".",
"pattern",
")",
"result",
"=",
"re",
".",
"sub",
"(",
"compiled_pattern",
",",
"self",
".",
"repl",
",",
"string",
")",
"return",
"result"
]
| Perform the substitution represented by this object on string and return
the result. | [
"Perform",
"the",
"substitution",
"represented",
"by",
"this",
"object",
"on",
"string",
"and",
"return",
"the",
"result",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/substitute.py#L23-L34 | train |
srsudar/eg | eg/color.py | EgColorizer.colorize_text | def colorize_text(self, text):
"""Colorize the text."""
# As originally implemented, this method acts upon all the contents of
# the file as a single string using the MULTILINE option of the re
# package. I believe this was ostensibly for performance reasons, but
# it has a few side effects that are less than ideal. It's non-trivial
# to avoid some substitutions based on other matches using this
# technique, for example. In the case of block indents, e.g., backticks
# that occur in the example ($ pwd is `pwd`) should not be escaped.
# With the MULTILINE flag that is not simple. colorize_backticks() is
# currently operating on a line by line basis and special casing for
# this scenario. If these special cases proliferate, the line breaking
# should occur here in order to minimize the number of iterations.
result = text
result = self.colorize_heading(result)
result = self.colorize_block_indent(result)
result = self.colorize_backticks(result)
return result | python | def colorize_text(self, text):
"""Colorize the text."""
# As originally implemented, this method acts upon all the contents of
# the file as a single string using the MULTILINE option of the re
# package. I believe this was ostensibly for performance reasons, but
# it has a few side effects that are less than ideal. It's non-trivial
# to avoid some substitutions based on other matches using this
# technique, for example. In the case of block indents, e.g., backticks
# that occur in the example ($ pwd is `pwd`) should not be escaped.
# With the MULTILINE flag that is not simple. colorize_backticks() is
# currently operating on a line by line basis and special casing for
# this scenario. If these special cases proliferate, the line breaking
# should occur here in order to minimize the number of iterations.
result = text
result = self.colorize_heading(result)
result = self.colorize_block_indent(result)
result = self.colorize_backticks(result)
return result | [
"def",
"colorize_text",
"(",
"self",
",",
"text",
")",
":",
"# As originally implemented, this method acts upon all the contents of",
"# the file as a single string using the MULTILINE option of the re",
"# package. I believe this was ostensibly for performance reasons, but",
"# it has a few side effects that are less than ideal. It's non-trivial",
"# to avoid some substitutions based on other matches using this",
"# technique, for example. In the case of block indents, e.g., backticks",
"# that occur in the example ($ pwd is `pwd`) should not be escaped.",
"# With the MULTILINE flag that is not simple. colorize_backticks() is",
"# currently operating on a line by line basis and special casing for",
"# this scenario. If these special cases proliferate, the line breaking",
"# should occur here in order to minimize the number of iterations.",
"result",
"=",
"text",
"result",
"=",
"self",
".",
"colorize_heading",
"(",
"result",
")",
"result",
"=",
"self",
".",
"colorize_block_indent",
"(",
"result",
")",
"result",
"=",
"self",
".",
"colorize_backticks",
"(",
"result",
")",
"return",
"result"
]
| Colorize the text. | [
"Colorize",
"the",
"text",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/color.py#L67-L85 | train |
srsudar/eg | eg/util.py | _recursive_get_all_file_names | def _recursive_get_all_file_names(dir):
"""
Get all the file names in the directory. Gets all the top level file names
only, not the full path.
dir: a directory or string, as to hand to os.walk(). If None, returns empty
list.
"""
if not dir:
return []
result = []
for basedir, dirs, files in os.walk(dir):
result.extend(files)
return result | python | def _recursive_get_all_file_names(dir):
"""
Get all the file names in the directory. Gets all the top level file names
only, not the full path.
dir: a directory or string, as to hand to os.walk(). If None, returns empty
list.
"""
if not dir:
return []
result = []
for basedir, dirs, files in os.walk(dir):
result.extend(files)
return result | [
"def",
"_recursive_get_all_file_names",
"(",
"dir",
")",
":",
"if",
"not",
"dir",
":",
"return",
"[",
"]",
"result",
"=",
"[",
"]",
"for",
"basedir",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dir",
")",
":",
"result",
".",
"extend",
"(",
"files",
")",
"return",
"result"
]
| Get all the file names in the directory. Gets all the top level file names
only, not the full path.
dir: a directory or string, as to hand to os.walk(). If None, returns empty
list. | [
"Get",
"all",
"the",
"file",
"names",
"in",
"the",
"directory",
".",
"Gets",
"all",
"the",
"top",
"level",
"file",
"names",
"only",
"not",
"the",
"full",
"path",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L49-L64 | train |
srsudar/eg | eg/util.py | edit_custom_examples | def edit_custom_examples(program, config):
"""
Edit custom examples for the given program, creating the file if it does
not exist.
"""
if (not config.custom_dir) or (not os.path.exists(config.custom_dir)):
_inform_cannot_edit_no_custom_dir()
return
# resolve aliases
resolved_program = get_resolved_program(program, config)
custom_file_paths = get_file_paths_for_program(
resolved_program,
config.custom_dir
)
if (len(custom_file_paths) > 0):
path_to_edit = custom_file_paths[0]
else:
# A new file.
path_to_edit = os.path.join(config.custom_dir, resolved_program + '.md')
# Edit the first. Handles the base case.
subprocess.call([config.editor_cmd, path_to_edit]) | python | def edit_custom_examples(program, config):
"""
Edit custom examples for the given program, creating the file if it does
not exist.
"""
if (not config.custom_dir) or (not os.path.exists(config.custom_dir)):
_inform_cannot_edit_no_custom_dir()
return
# resolve aliases
resolved_program = get_resolved_program(program, config)
custom_file_paths = get_file_paths_for_program(
resolved_program,
config.custom_dir
)
if (len(custom_file_paths) > 0):
path_to_edit = custom_file_paths[0]
else:
# A new file.
path_to_edit = os.path.join(config.custom_dir, resolved_program + '.md')
# Edit the first. Handles the base case.
subprocess.call([config.editor_cmd, path_to_edit]) | [
"def",
"edit_custom_examples",
"(",
"program",
",",
"config",
")",
":",
"if",
"(",
"not",
"config",
".",
"custom_dir",
")",
"or",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config",
".",
"custom_dir",
")",
")",
":",
"_inform_cannot_edit_no_custom_dir",
"(",
")",
"return",
"# resolve aliases",
"resolved_program",
"=",
"get_resolved_program",
"(",
"program",
",",
"config",
")",
"custom_file_paths",
"=",
"get_file_paths_for_program",
"(",
"resolved_program",
",",
"config",
".",
"custom_dir",
")",
"if",
"(",
"len",
"(",
"custom_file_paths",
")",
">",
"0",
")",
":",
"path_to_edit",
"=",
"custom_file_paths",
"[",
"0",
"]",
"else",
":",
"# A new file.",
"path_to_edit",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"custom_dir",
",",
"resolved_program",
"+",
"'.md'",
")",
"# Edit the first. Handles the base case.",
"subprocess",
".",
"call",
"(",
"[",
"config",
".",
"editor_cmd",
",",
"path_to_edit",
"]",
")"
]
| Edit custom examples for the given program, creating the file if it does
not exist. | [
"Edit",
"custom",
"examples",
"for",
"the",
"given",
"program",
"creating",
"the",
"file",
"if",
"it",
"does",
"not",
"exist",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L67-L90 | train |
srsudar/eg | eg/util.py | get_file_paths_for_program | def get_file_paths_for_program(program, dir_to_search):
"""
Return an array of full paths matching the given program. If no directory is
present, returns an empty list.
Path is not guaranteed to exist. Just says where it should be if it
existed. Paths must be fully expanded before being passed in (i.e. no ~ or
variables).
"""
if dir_to_search is None:
return []
else:
wanted_file_name = program + EXAMPLE_FILE_SUFFIX
result = []
for basedir, dirs, file_names in os.walk(dir_to_search):
for file_name in file_names:
if file_name == wanted_file_name:
result.append(os.path.join(basedir, file_name))
return result | python | def get_file_paths_for_program(program, dir_to_search):
"""
Return an array of full paths matching the given program. If no directory is
present, returns an empty list.
Path is not guaranteed to exist. Just says where it should be if it
existed. Paths must be fully expanded before being passed in (i.e. no ~ or
variables).
"""
if dir_to_search is None:
return []
else:
wanted_file_name = program + EXAMPLE_FILE_SUFFIX
result = []
for basedir, dirs, file_names in os.walk(dir_to_search):
for file_name in file_names:
if file_name == wanted_file_name:
result.append(os.path.join(basedir, file_name))
return result | [
"def",
"get_file_paths_for_program",
"(",
"program",
",",
"dir_to_search",
")",
":",
"if",
"dir_to_search",
"is",
"None",
":",
"return",
"[",
"]",
"else",
":",
"wanted_file_name",
"=",
"program",
"+",
"EXAMPLE_FILE_SUFFIX",
"result",
"=",
"[",
"]",
"for",
"basedir",
",",
"dirs",
",",
"file_names",
"in",
"os",
".",
"walk",
"(",
"dir_to_search",
")",
":",
"for",
"file_name",
"in",
"file_names",
":",
"if",
"file_name",
"==",
"wanted_file_name",
":",
"result",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"basedir",
",",
"file_name",
")",
")",
"return",
"result"
]
| Return an array of full paths matching the given program. If no directory is
present, returns an empty list.
Path is not guaranteed to exist. Just says where it should be if it
existed. Paths must be fully expanded before being passed in (i.e. no ~ or
variables). | [
"Return",
"an",
"array",
"of",
"full",
"paths",
"matching",
"the",
"given",
"program",
".",
"If",
"no",
"directory",
"is",
"present",
"returns",
"an",
"empty",
"list",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L131-L150 | train |
srsudar/eg | eg/util.py | page_string | def page_string(str_to_page, pager_cmd):
"""
Page str_to_page via the pager.
"""
# By default, we expect the command to be `less -R`. If that is the
# pager_cmd, but they don't have less on their machine, odds are they're
# just using the default value. In this case the pager will fail, so we'll
# just go via pydoc.pager, which tries to do smarter checking that we don't
# want to bother trying to replicate.
use_fallback_page_function = False
if pager_cmd is None:
use_fallback_page_function = True
elif pager_cmd == FLAG_FALLBACK:
use_fallback_page_function = True
try:
if use_fallback_page_function:
pydoc.pager(str_to_page)
else:
# Otherwise, obey the user.
pydoc.pipepager(str_to_page, cmd=pager_cmd)
except KeyboardInterrupt:
pass | python | def page_string(str_to_page, pager_cmd):
"""
Page str_to_page via the pager.
"""
# By default, we expect the command to be `less -R`. If that is the
# pager_cmd, but they don't have less on their machine, odds are they're
# just using the default value. In this case the pager will fail, so we'll
# just go via pydoc.pager, which tries to do smarter checking that we don't
# want to bother trying to replicate.
use_fallback_page_function = False
if pager_cmd is None:
use_fallback_page_function = True
elif pager_cmd == FLAG_FALLBACK:
use_fallback_page_function = True
try:
if use_fallback_page_function:
pydoc.pager(str_to_page)
else:
# Otherwise, obey the user.
pydoc.pipepager(str_to_page, cmd=pager_cmd)
except KeyboardInterrupt:
pass | [
"def",
"page_string",
"(",
"str_to_page",
",",
"pager_cmd",
")",
":",
"# By default, we expect the command to be `less -R`. If that is the",
"# pager_cmd, but they don't have less on their machine, odds are they're",
"# just using the default value. In this case the pager will fail, so we'll",
"# just go via pydoc.pager, which tries to do smarter checking that we don't",
"# want to bother trying to replicate.",
"use_fallback_page_function",
"=",
"False",
"if",
"pager_cmd",
"is",
"None",
":",
"use_fallback_page_function",
"=",
"True",
"elif",
"pager_cmd",
"==",
"FLAG_FALLBACK",
":",
"use_fallback_page_function",
"=",
"True",
"try",
":",
"if",
"use_fallback_page_function",
":",
"pydoc",
".",
"pager",
"(",
"str_to_page",
")",
"else",
":",
"# Otherwise, obey the user.",
"pydoc",
".",
"pipepager",
"(",
"str_to_page",
",",
"cmd",
"=",
"pager_cmd",
")",
"except",
"KeyboardInterrupt",
":",
"pass"
]
| Page str_to_page via the pager. | [
"Page",
"str_to_page",
"via",
"the",
"pager",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L167-L189 | train |
srsudar/eg | eg/util.py | get_list_of_all_supported_commands | def get_list_of_all_supported_commands(config):
"""
Generate a list of all the commands that have examples known to eg. The
format of the list is the command names. The fact that there are examples
for 'cp', for example, would mean that 'cp' was in the list.
The format of the list contains additional information to say if there are
only default examples, only custom examples, or both:
cp (only default)
cp * (only custom)
cp + (default and custom)
Aliases are shown as
alias -> resolved, with resolved having its '*' or '+' as expected. Aliases
that shadow custom-only file names are expected to be shown instead of the
custom file names. This is intentional, as that is the behavior for file
resolution--an alias will hide a custom file.
"""
default_files = _recursive_get_all_file_names(config.examples_dir)
custom_files = _recursive_get_all_file_names(config.custom_dir)
# Now filter so we only have example files, not things like aliases.json.
default_files = [path for path in default_files if _is_example_file(path)]
custom_files = [path for path in custom_files if _is_example_file(path)]
def get_without_suffix(file_name):
"""
Return the file name without the suffix, or the file name itself
if it does not have the suffix.
"""
return file_name.split(EXAMPLE_FILE_SUFFIX)[0]
default_files = [get_without_suffix(f) for f in default_files]
custom_files = [get_without_suffix(f) for f in custom_files]
set_default_commands = set(default_files)
set_custom_commands = set(custom_files)
alias_dict = get_alias_dict(config)
both_defined = set_default_commands & set_custom_commands
only_default = set_default_commands - set_custom_commands
only_custom = set_custom_commands - set_default_commands
all_commands = both_defined | only_default | only_custom
command_to_rep = {}
for command in all_commands:
rep = None
if command in both_defined:
rep = command + ' ' + FLAG_CUSTOM_AND_DEFAULT
elif command in only_default:
rep = command
elif command in only_custom:
rep = command + ' ' + FLAG_ONLY_CUSTOM
else:
raise NameError('command not in known set: ' + str(command))
command_to_rep[command] = rep
result = []
all_commands_and_aliases = all_commands.union(alias_dict.keys())
for command in all_commands_and_aliases:
if command in alias_dict:
# aliases get precedence
target = alias_dict[command]
rep_of_target = command_to_rep[target]
result.append(command + ' -> ' + rep_of_target)
else:
rep = command_to_rep[command]
result.append(rep)
result.sort()
return result | python | def get_list_of_all_supported_commands(config):
"""
Generate a list of all the commands that have examples known to eg. The
format of the list is the command names. The fact that there are examples
for 'cp', for example, would mean that 'cp' was in the list.
The format of the list contains additional information to say if there are
only default examples, only custom examples, or both:
cp (only default)
cp * (only custom)
cp + (default and custom)
Aliases are shown as
alias -> resolved, with resolved having its '*' or '+' as expected. Aliases
that shadow custom-only file names are expected to be shown instead of the
custom file names. This is intentional, as that is the behavior for file
resolution--an alias will hide a custom file.
"""
default_files = _recursive_get_all_file_names(config.examples_dir)
custom_files = _recursive_get_all_file_names(config.custom_dir)
# Now filter so we only have example files, not things like aliases.json.
default_files = [path for path in default_files if _is_example_file(path)]
custom_files = [path for path in custom_files if _is_example_file(path)]
def get_without_suffix(file_name):
"""
Return the file name without the suffix, or the file name itself
if it does not have the suffix.
"""
return file_name.split(EXAMPLE_FILE_SUFFIX)[0]
default_files = [get_without_suffix(f) for f in default_files]
custom_files = [get_without_suffix(f) for f in custom_files]
set_default_commands = set(default_files)
set_custom_commands = set(custom_files)
alias_dict = get_alias_dict(config)
both_defined = set_default_commands & set_custom_commands
only_default = set_default_commands - set_custom_commands
only_custom = set_custom_commands - set_default_commands
all_commands = both_defined | only_default | only_custom
command_to_rep = {}
for command in all_commands:
rep = None
if command in both_defined:
rep = command + ' ' + FLAG_CUSTOM_AND_DEFAULT
elif command in only_default:
rep = command
elif command in only_custom:
rep = command + ' ' + FLAG_ONLY_CUSTOM
else:
raise NameError('command not in known set: ' + str(command))
command_to_rep[command] = rep
result = []
all_commands_and_aliases = all_commands.union(alias_dict.keys())
for command in all_commands_and_aliases:
if command in alias_dict:
# aliases get precedence
target = alias_dict[command]
rep_of_target = command_to_rep[target]
result.append(command + ' -> ' + rep_of_target)
else:
rep = command_to_rep[command]
result.append(rep)
result.sort()
return result | [
"def",
"get_list_of_all_supported_commands",
"(",
"config",
")",
":",
"default_files",
"=",
"_recursive_get_all_file_names",
"(",
"config",
".",
"examples_dir",
")",
"custom_files",
"=",
"_recursive_get_all_file_names",
"(",
"config",
".",
"custom_dir",
")",
"# Now filter so we only have example files, not things like aliases.json.",
"default_files",
"=",
"[",
"path",
"for",
"path",
"in",
"default_files",
"if",
"_is_example_file",
"(",
"path",
")",
"]",
"custom_files",
"=",
"[",
"path",
"for",
"path",
"in",
"custom_files",
"if",
"_is_example_file",
"(",
"path",
")",
"]",
"def",
"get_without_suffix",
"(",
"file_name",
")",
":",
"\"\"\"\n Return the file name without the suffix, or the file name itself\n if it does not have the suffix.\n \"\"\"",
"return",
"file_name",
".",
"split",
"(",
"EXAMPLE_FILE_SUFFIX",
")",
"[",
"0",
"]",
"default_files",
"=",
"[",
"get_without_suffix",
"(",
"f",
")",
"for",
"f",
"in",
"default_files",
"]",
"custom_files",
"=",
"[",
"get_without_suffix",
"(",
"f",
")",
"for",
"f",
"in",
"custom_files",
"]",
"set_default_commands",
"=",
"set",
"(",
"default_files",
")",
"set_custom_commands",
"=",
"set",
"(",
"custom_files",
")",
"alias_dict",
"=",
"get_alias_dict",
"(",
"config",
")",
"both_defined",
"=",
"set_default_commands",
"&",
"set_custom_commands",
"only_default",
"=",
"set_default_commands",
"-",
"set_custom_commands",
"only_custom",
"=",
"set_custom_commands",
"-",
"set_default_commands",
"all_commands",
"=",
"both_defined",
"|",
"only_default",
"|",
"only_custom",
"command_to_rep",
"=",
"{",
"}",
"for",
"command",
"in",
"all_commands",
":",
"rep",
"=",
"None",
"if",
"command",
"in",
"both_defined",
":",
"rep",
"=",
"command",
"+",
"' '",
"+",
"FLAG_CUSTOM_AND_DEFAULT",
"elif",
"command",
"in",
"only_default",
":",
"rep",
"=",
"command",
"elif",
"command",
"in",
"only_custom",
":",
"rep",
"=",
"command",
"+",
"' '",
"+",
"FLAG_ONLY_CUSTOM",
"else",
":",
"raise",
"NameError",
"(",
"'command not in known set: '",
"+",
"str",
"(",
"command",
")",
")",
"command_to_rep",
"[",
"command",
"]",
"=",
"rep",
"result",
"=",
"[",
"]",
"all_commands_and_aliases",
"=",
"all_commands",
".",
"union",
"(",
"alias_dict",
".",
"keys",
"(",
")",
")",
"for",
"command",
"in",
"all_commands_and_aliases",
":",
"if",
"command",
"in",
"alias_dict",
":",
"# aliases get precedence",
"target",
"=",
"alias_dict",
"[",
"command",
"]",
"rep_of_target",
"=",
"command_to_rep",
"[",
"target",
"]",
"result",
".",
"append",
"(",
"command",
"+",
"' -> '",
"+",
"rep_of_target",
")",
"else",
":",
"rep",
"=",
"command_to_rep",
"[",
"command",
"]",
"result",
".",
"append",
"(",
"rep",
")",
"result",
".",
"sort",
"(",
")",
"return",
"result"
]
| Generate a list of all the commands that have examples known to eg. The
format of the list is the command names. The fact that there are examples
for 'cp', for example, would mean that 'cp' was in the list.
The format of the list contains additional information to say if there are
only default examples, only custom examples, or both:
cp (only default)
cp * (only custom)
cp + (default and custom)
Aliases are shown as
alias -> resolved, with resolved having its '*' or '+' as expected. Aliases
that shadow custom-only file names are expected to be shown instead of the
custom file names. This is intentional, as that is the behavior for file
resolution--an alias will hide a custom file. | [
"Generate",
"a",
"list",
"of",
"all",
"the",
"commands",
"that",
"have",
"examples",
"known",
"to",
"eg",
".",
"The",
"format",
"of",
"the",
"list",
"is",
"the",
"command",
"names",
".",
"The",
"fact",
"that",
"there",
"are",
"examples",
"for",
"cp",
"for",
"example",
"would",
"mean",
"that",
"cp",
"was",
"in",
"the",
"list",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L206-L280 | train |
srsudar/eg | eg/util.py | get_squeezed_contents | def get_squeezed_contents(contents):
"""
Squeeze the contents by removing blank lines between definition and example
and remove duplicate blank lines except between sections.
"""
line_between_example_code = substitute.Substitution(
'\n\n ',
'\n ',
True
)
lines_between_examples = substitute.Substitution('\n\n\n', '\n\n', True)
lines_between_sections = substitute.Substitution(
'\n\n\n\n', '\n\n\n', True
)
result = contents
result = line_between_example_code.apply_and_get_result(result)
result = lines_between_examples.apply_and_get_result(result)
result = lines_between_sections.apply_and_get_result(result)
return result | python | def get_squeezed_contents(contents):
"""
Squeeze the contents by removing blank lines between definition and example
and remove duplicate blank lines except between sections.
"""
line_between_example_code = substitute.Substitution(
'\n\n ',
'\n ',
True
)
lines_between_examples = substitute.Substitution('\n\n\n', '\n\n', True)
lines_between_sections = substitute.Substitution(
'\n\n\n\n', '\n\n\n', True
)
result = contents
result = line_between_example_code.apply_and_get_result(result)
result = lines_between_examples.apply_and_get_result(result)
result = lines_between_sections.apply_and_get_result(result)
return result | [
"def",
"get_squeezed_contents",
"(",
"contents",
")",
":",
"line_between_example_code",
"=",
"substitute",
".",
"Substitution",
"(",
"'\\n\\n '",
",",
"'\\n '",
",",
"True",
")",
"lines_between_examples",
"=",
"substitute",
".",
"Substitution",
"(",
"'\\n\\n\\n'",
",",
"'\\n\\n'",
",",
"True",
")",
"lines_between_sections",
"=",
"substitute",
".",
"Substitution",
"(",
"'\\n\\n\\n\\n'",
",",
"'\\n\\n\\n'",
",",
"True",
")",
"result",
"=",
"contents",
"result",
"=",
"line_between_example_code",
".",
"apply_and_get_result",
"(",
"result",
")",
"result",
"=",
"lines_between_examples",
".",
"apply_and_get_result",
"(",
"result",
")",
"result",
"=",
"lines_between_sections",
".",
"apply_and_get_result",
"(",
"result",
")",
"return",
"result"
]
| Squeeze the contents by removing blank lines between definition and example
and remove duplicate blank lines except between sections. | [
"Squeeze",
"the",
"contents",
"by",
"removing",
"blank",
"lines",
"between",
"definition",
"and",
"example",
"and",
"remove",
"duplicate",
"blank",
"lines",
"except",
"between",
"sections",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L283-L302 | train |
srsudar/eg | eg/util.py | get_colorized_contents | def get_colorized_contents(contents, color_config):
"""Colorize the contents based on the color_config."""
colorizer = color.EgColorizer(color_config)
result = colorizer.colorize_text(contents)
return result | python | def get_colorized_contents(contents, color_config):
"""Colorize the contents based on the color_config."""
colorizer = color.EgColorizer(color_config)
result = colorizer.colorize_text(contents)
return result | [
"def",
"get_colorized_contents",
"(",
"contents",
",",
"color_config",
")",
":",
"colorizer",
"=",
"color",
".",
"EgColorizer",
"(",
"color_config",
")",
"result",
"=",
"colorizer",
".",
"colorize_text",
"(",
"contents",
")",
"return",
"result"
]
| Colorize the contents based on the color_config. | [
"Colorize",
"the",
"contents",
"based",
"on",
"the",
"color_config",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L305-L309 | train |
srsudar/eg | eg/util.py | get_substituted_contents | def get_substituted_contents(contents, substitutions):
"""
Perform a list of substitutions and return the result.
contents: the starting string on which to beging substitutions
substitutions: list of Substitution objects to call, in order, with the
result of the previous substitution.
"""
result = contents
for sub in substitutions:
result = sub.apply_and_get_result(result)
return result | python | def get_substituted_contents(contents, substitutions):
"""
Perform a list of substitutions and return the result.
contents: the starting string on which to beging substitutions
substitutions: list of Substitution objects to call, in order, with the
result of the previous substitution.
"""
result = contents
for sub in substitutions:
result = sub.apply_and_get_result(result)
return result | [
"def",
"get_substituted_contents",
"(",
"contents",
",",
"substitutions",
")",
":",
"result",
"=",
"contents",
"for",
"sub",
"in",
"substitutions",
":",
"result",
"=",
"sub",
".",
"apply_and_get_result",
"(",
"result",
")",
"return",
"result"
]
| Perform a list of substitutions and return the result.
contents: the starting string on which to beging substitutions
substitutions: list of Substitution objects to call, in order, with the
result of the previous substitution. | [
"Perform",
"a",
"list",
"of",
"substitutions",
"and",
"return",
"the",
"result",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L312-L323 | train |
srsudar/eg | eg/util.py | get_resolved_program | def get_resolved_program(program, config_obj):
"""
Take a program that may be an alias for another program and return the
resolved program.
It only ever resolves a single level of aliasing, so does not support
aliasing to an alias.
Returns the original program if the program is not an alias.
"""
alias_dict = get_alias_dict(config_obj)
if program in alias_dict:
return alias_dict[program]
else:
return program | python | def get_resolved_program(program, config_obj):
"""
Take a program that may be an alias for another program and return the
resolved program.
It only ever resolves a single level of aliasing, so does not support
aliasing to an alias.
Returns the original program if the program is not an alias.
"""
alias_dict = get_alias_dict(config_obj)
if program in alias_dict:
return alias_dict[program]
else:
return program | [
"def",
"get_resolved_program",
"(",
"program",
",",
"config_obj",
")",
":",
"alias_dict",
"=",
"get_alias_dict",
"(",
"config_obj",
")",
"if",
"program",
"in",
"alias_dict",
":",
"return",
"alias_dict",
"[",
"program",
"]",
"else",
":",
"return",
"program"
]
| Take a program that may be an alias for another program and return the
resolved program.
It only ever resolves a single level of aliasing, so does not support
aliasing to an alias.
Returns the original program if the program is not an alias. | [
"Take",
"a",
"program",
"that",
"may",
"be",
"an",
"alias",
"for",
"another",
"program",
"and",
"return",
"the",
"resolved",
"program",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L351-L365 | train |
srsudar/eg | eg/util.py | get_alias_dict | def get_alias_dict(config_obj):
"""
Return a dictionary consisting of all aliases known to eg.
The format is {'alias': 'resolved_program'}.
If the aliases file does not exist, returns an empty dict.
"""
if not config_obj.examples_dir:
return {}
alias_file_path = _get_alias_file_path(config_obj)
if not os.path.isfile(alias_file_path):
return {}
alias_file_contents = _get_contents_of_file(alias_file_path)
result = json.loads(alias_file_contents)
return result | python | def get_alias_dict(config_obj):
"""
Return a dictionary consisting of all aliases known to eg.
The format is {'alias': 'resolved_program'}.
If the aliases file does not exist, returns an empty dict.
"""
if not config_obj.examples_dir:
return {}
alias_file_path = _get_alias_file_path(config_obj)
if not os.path.isfile(alias_file_path):
return {}
alias_file_contents = _get_contents_of_file(alias_file_path)
result = json.loads(alias_file_contents)
return result | [
"def",
"get_alias_dict",
"(",
"config_obj",
")",
":",
"if",
"not",
"config_obj",
".",
"examples_dir",
":",
"return",
"{",
"}",
"alias_file_path",
"=",
"_get_alias_file_path",
"(",
"config_obj",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"alias_file_path",
")",
":",
"return",
"{",
"}",
"alias_file_contents",
"=",
"_get_contents_of_file",
"(",
"alias_file_path",
")",
"result",
"=",
"json",
".",
"loads",
"(",
"alias_file_contents",
")",
"return",
"result"
]
| Return a dictionary consisting of all aliases known to eg.
The format is {'alias': 'resolved_program'}.
If the aliases file does not exist, returns an empty dict. | [
"Return",
"a",
"dictionary",
"consisting",
"of",
"all",
"aliases",
"known",
"to",
"eg",
"."
]
| 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L368-L385 | train |
testing-cabal/mock | mock/mock.py | NonCallableMock.assert_not_called | def assert_not_called(_mock_self):
"""assert that the mock was never called.
"""
self = _mock_self
if self.call_count != 0:
msg = ("Expected '%s' to not have been called. Called %s times." %
(self._mock_name or 'mock', self.call_count))
raise AssertionError(msg) | python | def assert_not_called(_mock_self):
"""assert that the mock was never called.
"""
self = _mock_self
if self.call_count != 0:
msg = ("Expected '%s' to not have been called. Called %s times." %
(self._mock_name or 'mock', self.call_count))
raise AssertionError(msg) | [
"def",
"assert_not_called",
"(",
"_mock_self",
")",
":",
"self",
"=",
"_mock_self",
"if",
"self",
".",
"call_count",
"!=",
"0",
":",
"msg",
"=",
"(",
"\"Expected '%s' to not have been called. Called %s times.\"",
"%",
"(",
"self",
".",
"_mock_name",
"or",
"'mock'",
",",
"self",
".",
"call_count",
")",
")",
"raise",
"AssertionError",
"(",
"msg",
")"
]
| assert that the mock was never called. | [
"assert",
"that",
"the",
"mock",
"was",
"never",
"called",
"."
]
| 2f356b28d42a1fd0057c9d8763d3a2cac2284165 | https://github.com/testing-cabal/mock/blob/2f356b28d42a1fd0057c9d8763d3a2cac2284165/mock/mock.py#L889-L896 | train |
testing-cabal/mock | mock/mock.py | NonCallableMock.assert_called | def assert_called(_mock_self):
"""assert that the mock was called at least once
"""
self = _mock_self
if self.call_count == 0:
msg = ("Expected '%s' to have been called." %
self._mock_name or 'mock')
raise AssertionError(msg) | python | def assert_called(_mock_self):
"""assert that the mock was called at least once
"""
self = _mock_self
if self.call_count == 0:
msg = ("Expected '%s' to have been called." %
self._mock_name or 'mock')
raise AssertionError(msg) | [
"def",
"assert_called",
"(",
"_mock_self",
")",
":",
"self",
"=",
"_mock_self",
"if",
"self",
".",
"call_count",
"==",
"0",
":",
"msg",
"=",
"(",
"\"Expected '%s' to have been called.\"",
"%",
"self",
".",
"_mock_name",
"or",
"'mock'",
")",
"raise",
"AssertionError",
"(",
"msg",
")"
]
| assert that the mock was called at least once | [
"assert",
"that",
"the",
"mock",
"was",
"called",
"at",
"least",
"once"
]
| 2f356b28d42a1fd0057c9d8763d3a2cac2284165 | https://github.com/testing-cabal/mock/blob/2f356b28d42a1fd0057c9d8763d3a2cac2284165/mock/mock.py#L898-L905 | train |
testing-cabal/mock | mock/mock.py | NonCallableMock.assert_called_once | def assert_called_once(_mock_self):
"""assert that the mock was called only once.
"""
self = _mock_self
if not self.call_count == 1:
msg = ("Expected '%s' to have been called once. Called %s times." %
(self._mock_name or 'mock', self.call_count))
raise AssertionError(msg) | python | def assert_called_once(_mock_self):
"""assert that the mock was called only once.
"""
self = _mock_self
if not self.call_count == 1:
msg = ("Expected '%s' to have been called once. Called %s times." %
(self._mock_name or 'mock', self.call_count))
raise AssertionError(msg) | [
"def",
"assert_called_once",
"(",
"_mock_self",
")",
":",
"self",
"=",
"_mock_self",
"if",
"not",
"self",
".",
"call_count",
"==",
"1",
":",
"msg",
"=",
"(",
"\"Expected '%s' to have been called once. Called %s times.\"",
"%",
"(",
"self",
".",
"_mock_name",
"or",
"'mock'",
",",
"self",
".",
"call_count",
")",
")",
"raise",
"AssertionError",
"(",
"msg",
")"
]
| assert that the mock was called only once. | [
"assert",
"that",
"the",
"mock",
"was",
"called",
"only",
"once",
"."
]
| 2f356b28d42a1fd0057c9d8763d3a2cac2284165 | https://github.com/testing-cabal/mock/blob/2f356b28d42a1fd0057c9d8763d3a2cac2284165/mock/mock.py#L907-L914 | train |
testing-cabal/mock | mock/mock.py | NonCallableMock.assert_called_once_with | def assert_called_once_with(_mock_self, *args, **kwargs):
"""assert that the mock was called exactly once and with the specified
arguments."""
self = _mock_self
if not self.call_count == 1:
msg = ("Expected '%s' to be called once. Called %s times." %
(self._mock_name or 'mock', self.call_count))
raise AssertionError(msg)
return self.assert_called_with(*args, **kwargs) | python | def assert_called_once_with(_mock_self, *args, **kwargs):
"""assert that the mock was called exactly once and with the specified
arguments."""
self = _mock_self
if not self.call_count == 1:
msg = ("Expected '%s' to be called once. Called %s times." %
(self._mock_name or 'mock', self.call_count))
raise AssertionError(msg)
return self.assert_called_with(*args, **kwargs) | [
"def",
"assert_called_once_with",
"(",
"_mock_self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"_mock_self",
"if",
"not",
"self",
".",
"call_count",
"==",
"1",
":",
"msg",
"=",
"(",
"\"Expected '%s' to be called once. Called %s times.\"",
"%",
"(",
"self",
".",
"_mock_name",
"or",
"'mock'",
",",
"self",
".",
"call_count",
")",
")",
"raise",
"AssertionError",
"(",
"msg",
")",
"return",
"self",
".",
"assert_called_with",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
]
| assert that the mock was called exactly once and with the specified
arguments. | [
"assert",
"that",
"the",
"mock",
"was",
"called",
"exactly",
"once",
"and",
"with",
"the",
"specified",
"arguments",
"."
]
| 2f356b28d42a1fd0057c9d8763d3a2cac2284165 | https://github.com/testing-cabal/mock/blob/2f356b28d42a1fd0057c9d8763d3a2cac2284165/mock/mock.py#L939-L947 | train |
earwig/mwparserfromhell | mwparserfromhell/nodes/html_entity.py | HTMLEntity.normalize | def normalize(self):
"""Return the unicode character represented by the HTML entity."""
chrfunc = chr if py3k else HTMLEntity._unichr
if self.named:
return chrfunc(htmlentities.name2codepoint[self.value])
if self.hexadecimal:
return chrfunc(int(self.value, 16))
return chrfunc(int(self.value)) | python | def normalize(self):
"""Return the unicode character represented by the HTML entity."""
chrfunc = chr if py3k else HTMLEntity._unichr
if self.named:
return chrfunc(htmlentities.name2codepoint[self.value])
if self.hexadecimal:
return chrfunc(int(self.value, 16))
return chrfunc(int(self.value)) | [
"def",
"normalize",
"(",
"self",
")",
":",
"chrfunc",
"=",
"chr",
"if",
"py3k",
"else",
"HTMLEntity",
".",
"_unichr",
"if",
"self",
".",
"named",
":",
"return",
"chrfunc",
"(",
"htmlentities",
".",
"name2codepoint",
"[",
"self",
".",
"value",
"]",
")",
"if",
"self",
".",
"hexadecimal",
":",
"return",
"chrfunc",
"(",
"int",
"(",
"self",
".",
"value",
",",
"16",
")",
")",
"return",
"chrfunc",
"(",
"int",
"(",
"self",
".",
"value",
")",
")"
]
| Return the unicode character represented by the HTML entity. | [
"Return",
"the",
"unicode",
"character",
"represented",
"by",
"the",
"HTML",
"entity",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/nodes/html_entity.py#L174-L181 | train |
earwig/mwparserfromhell | mwparserfromhell/smart_list.py | SmartList._detach_children | def _detach_children(self):
"""Remove all children and give them independent parent copies."""
children = [val[0] for val in self._children.values()]
for child in children:
child()._parent = list(self)
self._children.clear() | python | def _detach_children(self):
"""Remove all children and give them independent parent copies."""
children = [val[0] for val in self._children.values()]
for child in children:
child()._parent = list(self)
self._children.clear() | [
"def",
"_detach_children",
"(",
"self",
")",
":",
"children",
"=",
"[",
"val",
"[",
"0",
"]",
"for",
"val",
"in",
"self",
".",
"_children",
".",
"values",
"(",
")",
"]",
"for",
"child",
"in",
"children",
":",
"child",
"(",
")",
".",
"_parent",
"=",
"list",
"(",
"self",
")",
"self",
".",
"_children",
".",
"clear",
"(",
")"
]
| Remove all children and give them independent parent copies. | [
"Remove",
"all",
"children",
"and",
"give",
"them",
"independent",
"parent",
"copies",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/smart_list.py#L158-L163 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_parameter | def _handle_parameter(self, default):
"""Handle a case where a parameter is at the head of the tokens.
*default* is the value to use if no parameter name is defined.
"""
key = None
showkey = False
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.TemplateParamEquals):
key = self._pop()
showkey = True
self._push()
elif isinstance(token, (tokens.TemplateParamSeparator,
tokens.TemplateClose)):
self._tokens.append(token)
value = self._pop()
if key is None:
key = Wikicode(SmartList([Text(str(default))]))
return Parameter(key, value, showkey)
else:
self._write(self._handle_token(token))
raise ParserError("_handle_parameter() missed a close token") | python | def _handle_parameter(self, default):
"""Handle a case where a parameter is at the head of the tokens.
*default* is the value to use if no parameter name is defined.
"""
key = None
showkey = False
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.TemplateParamEquals):
key = self._pop()
showkey = True
self._push()
elif isinstance(token, (tokens.TemplateParamSeparator,
tokens.TemplateClose)):
self._tokens.append(token)
value = self._pop()
if key is None:
key = Wikicode(SmartList([Text(str(default))]))
return Parameter(key, value, showkey)
else:
self._write(self._handle_token(token))
raise ParserError("_handle_parameter() missed a close token") | [
"def",
"_handle_parameter",
"(",
"self",
",",
"default",
")",
":",
"key",
"=",
"None",
"showkey",
"=",
"False",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"TemplateParamEquals",
")",
":",
"key",
"=",
"self",
".",
"_pop",
"(",
")",
"showkey",
"=",
"True",
"self",
".",
"_push",
"(",
")",
"elif",
"isinstance",
"(",
"token",
",",
"(",
"tokens",
".",
"TemplateParamSeparator",
",",
"tokens",
".",
"TemplateClose",
")",
")",
":",
"self",
".",
"_tokens",
".",
"append",
"(",
"token",
")",
"value",
"=",
"self",
".",
"_pop",
"(",
")",
"if",
"key",
"is",
"None",
":",
"key",
"=",
"Wikicode",
"(",
"SmartList",
"(",
"[",
"Text",
"(",
"str",
"(",
"default",
")",
")",
"]",
")",
")",
"return",
"Parameter",
"(",
"key",
",",
"value",
",",
"showkey",
")",
"else",
":",
"self",
".",
"_write",
"(",
"self",
".",
"_handle_token",
"(",
"token",
")",
")",
"raise",
"ParserError",
"(",
"\"_handle_parameter() missed a close token\"",
")"
]
| Handle a case where a parameter is at the head of the tokens.
*default* is the value to use if no parameter name is defined. | [
"Handle",
"a",
"case",
"where",
"a",
"parameter",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L76-L99 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_template | def _handle_template(self, token):
"""Handle a case where a template is at the head of the tokens."""
params = []
default = 1
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.TemplateParamSeparator):
if not params:
name = self._pop()
param = self._handle_parameter(default)
params.append(param)
if not param.showkey:
default += 1
elif isinstance(token, tokens.TemplateClose):
if not params:
name = self._pop()
return Template(name, params)
else:
self._write(self._handle_token(token))
raise ParserError("_handle_template() missed a close token") | python | def _handle_template(self, token):
"""Handle a case where a template is at the head of the tokens."""
params = []
default = 1
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.TemplateParamSeparator):
if not params:
name = self._pop()
param = self._handle_parameter(default)
params.append(param)
if not param.showkey:
default += 1
elif isinstance(token, tokens.TemplateClose):
if not params:
name = self._pop()
return Template(name, params)
else:
self._write(self._handle_token(token))
raise ParserError("_handle_template() missed a close token") | [
"def",
"_handle_template",
"(",
"self",
",",
"token",
")",
":",
"params",
"=",
"[",
"]",
"default",
"=",
"1",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"TemplateParamSeparator",
")",
":",
"if",
"not",
"params",
":",
"name",
"=",
"self",
".",
"_pop",
"(",
")",
"param",
"=",
"self",
".",
"_handle_parameter",
"(",
"default",
")",
"params",
".",
"append",
"(",
"param",
")",
"if",
"not",
"param",
".",
"showkey",
":",
"default",
"+=",
"1",
"elif",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"TemplateClose",
")",
":",
"if",
"not",
"params",
":",
"name",
"=",
"self",
".",
"_pop",
"(",
")",
"return",
"Template",
"(",
"name",
",",
"params",
")",
"else",
":",
"self",
".",
"_write",
"(",
"self",
".",
"_handle_token",
"(",
"token",
")",
")",
"raise",
"ParserError",
"(",
"\"_handle_template() missed a close token\"",
")"
]
| Handle a case where a template is at the head of the tokens. | [
"Handle",
"a",
"case",
"where",
"a",
"template",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L102-L122 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_argument | def _handle_argument(self, token):
"""Handle a case where an argument is at the head of the tokens."""
name = None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.ArgumentSeparator):
name = self._pop()
self._push()
elif isinstance(token, tokens.ArgumentClose):
if name is not None:
return Argument(name, self._pop())
return Argument(self._pop())
else:
self._write(self._handle_token(token))
raise ParserError("_handle_argument() missed a close token") | python | def _handle_argument(self, token):
"""Handle a case where an argument is at the head of the tokens."""
name = None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.ArgumentSeparator):
name = self._pop()
self._push()
elif isinstance(token, tokens.ArgumentClose):
if name is not None:
return Argument(name, self._pop())
return Argument(self._pop())
else:
self._write(self._handle_token(token))
raise ParserError("_handle_argument() missed a close token") | [
"def",
"_handle_argument",
"(",
"self",
",",
"token",
")",
":",
"name",
"=",
"None",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"ArgumentSeparator",
")",
":",
"name",
"=",
"self",
".",
"_pop",
"(",
")",
"self",
".",
"_push",
"(",
")",
"elif",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"ArgumentClose",
")",
":",
"if",
"name",
"is",
"not",
"None",
":",
"return",
"Argument",
"(",
"name",
",",
"self",
".",
"_pop",
"(",
")",
")",
"return",
"Argument",
"(",
"self",
".",
"_pop",
"(",
")",
")",
"else",
":",
"self",
".",
"_write",
"(",
"self",
".",
"_handle_token",
"(",
"token",
")",
")",
"raise",
"ParserError",
"(",
"\"_handle_argument() missed a close token\"",
")"
]
| Handle a case where an argument is at the head of the tokens. | [
"Handle",
"a",
"case",
"where",
"an",
"argument",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L125-L140 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_wikilink | def _handle_wikilink(self, token):
"""Handle a case where a wikilink is at the head of the tokens."""
title = None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.WikilinkSeparator):
title = self._pop()
self._push()
elif isinstance(token, tokens.WikilinkClose):
if title is not None:
return Wikilink(title, self._pop())
return Wikilink(self._pop())
else:
self._write(self._handle_token(token))
raise ParserError("_handle_wikilink() missed a close token") | python | def _handle_wikilink(self, token):
"""Handle a case where a wikilink is at the head of the tokens."""
title = None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.WikilinkSeparator):
title = self._pop()
self._push()
elif isinstance(token, tokens.WikilinkClose):
if title is not None:
return Wikilink(title, self._pop())
return Wikilink(self._pop())
else:
self._write(self._handle_token(token))
raise ParserError("_handle_wikilink() missed a close token") | [
"def",
"_handle_wikilink",
"(",
"self",
",",
"token",
")",
":",
"title",
"=",
"None",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"WikilinkSeparator",
")",
":",
"title",
"=",
"self",
".",
"_pop",
"(",
")",
"self",
".",
"_push",
"(",
")",
"elif",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"WikilinkClose",
")",
":",
"if",
"title",
"is",
"not",
"None",
":",
"return",
"Wikilink",
"(",
"title",
",",
"self",
".",
"_pop",
"(",
")",
")",
"return",
"Wikilink",
"(",
"self",
".",
"_pop",
"(",
")",
")",
"else",
":",
"self",
".",
"_write",
"(",
"self",
".",
"_handle_token",
"(",
"token",
")",
")",
"raise",
"ParserError",
"(",
"\"_handle_wikilink() missed a close token\"",
")"
]
| Handle a case where a wikilink is at the head of the tokens. | [
"Handle",
"a",
"case",
"where",
"a",
"wikilink",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L143-L158 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_external_link | def _handle_external_link(self, token):
"""Handle when an external link is at the head of the tokens."""
brackets, url = token.brackets, None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.ExternalLinkSeparator):
url = self._pop()
self._push()
elif isinstance(token, tokens.ExternalLinkClose):
if url is not None:
return ExternalLink(url, self._pop(), brackets)
return ExternalLink(self._pop(), brackets=brackets)
else:
self._write(self._handle_token(token))
raise ParserError("_handle_external_link() missed a close token") | python | def _handle_external_link(self, token):
"""Handle when an external link is at the head of the tokens."""
brackets, url = token.brackets, None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.ExternalLinkSeparator):
url = self._pop()
self._push()
elif isinstance(token, tokens.ExternalLinkClose):
if url is not None:
return ExternalLink(url, self._pop(), brackets)
return ExternalLink(self._pop(), brackets=brackets)
else:
self._write(self._handle_token(token))
raise ParserError("_handle_external_link() missed a close token") | [
"def",
"_handle_external_link",
"(",
"self",
",",
"token",
")",
":",
"brackets",
",",
"url",
"=",
"token",
".",
"brackets",
",",
"None",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"ExternalLinkSeparator",
")",
":",
"url",
"=",
"self",
".",
"_pop",
"(",
")",
"self",
".",
"_push",
"(",
")",
"elif",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"ExternalLinkClose",
")",
":",
"if",
"url",
"is",
"not",
"None",
":",
"return",
"ExternalLink",
"(",
"url",
",",
"self",
".",
"_pop",
"(",
")",
",",
"brackets",
")",
"return",
"ExternalLink",
"(",
"self",
".",
"_pop",
"(",
")",
",",
"brackets",
"=",
"brackets",
")",
"else",
":",
"self",
".",
"_write",
"(",
"self",
".",
"_handle_token",
"(",
"token",
")",
")",
"raise",
"ParserError",
"(",
"\"_handle_external_link() missed a close token\"",
")"
]
| Handle when an external link is at the head of the tokens. | [
"Handle",
"when",
"an",
"external",
"link",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L161-L176 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_entity | def _handle_entity(self, token):
"""Handle a case where an HTML entity is at the head of the tokens."""
token = self._tokens.pop()
if isinstance(token, tokens.HTMLEntityNumeric):
token = self._tokens.pop()
if isinstance(token, tokens.HTMLEntityHex):
text = self._tokens.pop()
self._tokens.pop() # Remove HTMLEntityEnd
return HTMLEntity(text.text, named=False, hexadecimal=True,
hex_char=token.char)
self._tokens.pop() # Remove HTMLEntityEnd
return HTMLEntity(token.text, named=False, hexadecimal=False)
self._tokens.pop() # Remove HTMLEntityEnd
return HTMLEntity(token.text, named=True, hexadecimal=False) | python | def _handle_entity(self, token):
"""Handle a case where an HTML entity is at the head of the tokens."""
token = self._tokens.pop()
if isinstance(token, tokens.HTMLEntityNumeric):
token = self._tokens.pop()
if isinstance(token, tokens.HTMLEntityHex):
text = self._tokens.pop()
self._tokens.pop() # Remove HTMLEntityEnd
return HTMLEntity(text.text, named=False, hexadecimal=True,
hex_char=token.char)
self._tokens.pop() # Remove HTMLEntityEnd
return HTMLEntity(token.text, named=False, hexadecimal=False)
self._tokens.pop() # Remove HTMLEntityEnd
return HTMLEntity(token.text, named=True, hexadecimal=False) | [
"def",
"_handle_entity",
"(",
"self",
",",
"token",
")",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"HTMLEntityNumeric",
")",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"HTMLEntityHex",
")",
":",
"text",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"# Remove HTMLEntityEnd",
"return",
"HTMLEntity",
"(",
"text",
".",
"text",
",",
"named",
"=",
"False",
",",
"hexadecimal",
"=",
"True",
",",
"hex_char",
"=",
"token",
".",
"char",
")",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"# Remove HTMLEntityEnd",
"return",
"HTMLEntity",
"(",
"token",
".",
"text",
",",
"named",
"=",
"False",
",",
"hexadecimal",
"=",
"False",
")",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"# Remove HTMLEntityEnd",
"return",
"HTMLEntity",
"(",
"token",
".",
"text",
",",
"named",
"=",
"True",
",",
"hexadecimal",
"=",
"False",
")"
]
| Handle a case where an HTML entity is at the head of the tokens. | [
"Handle",
"a",
"case",
"where",
"an",
"HTML",
"entity",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L179-L192 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_heading | def _handle_heading(self, token):
"""Handle a case where a heading is at the head of the tokens."""
level = token.level
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.HeadingEnd):
title = self._pop()
return Heading(title, level)
else:
self._write(self._handle_token(token))
raise ParserError("_handle_heading() missed a close token") | python | def _handle_heading(self, token):
"""Handle a case where a heading is at the head of the tokens."""
level = token.level
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.HeadingEnd):
title = self._pop()
return Heading(title, level)
else:
self._write(self._handle_token(token))
raise ParserError("_handle_heading() missed a close token") | [
"def",
"_handle_heading",
"(",
"self",
",",
"token",
")",
":",
"level",
"=",
"token",
".",
"level",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"HeadingEnd",
")",
":",
"title",
"=",
"self",
".",
"_pop",
"(",
")",
"return",
"Heading",
"(",
"title",
",",
"level",
")",
"else",
":",
"self",
".",
"_write",
"(",
"self",
".",
"_handle_token",
"(",
"token",
")",
")",
"raise",
"ParserError",
"(",
"\"_handle_heading() missed a close token\"",
")"
]
| Handle a case where a heading is at the head of the tokens. | [
"Handle",
"a",
"case",
"where",
"a",
"heading",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L195-L206 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_comment | def _handle_comment(self, token):
"""Handle a case where an HTML comment is at the head of the tokens."""
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.CommentEnd):
contents = self._pop()
return Comment(contents)
else:
self._write(self._handle_token(token))
raise ParserError("_handle_comment() missed a close token") | python | def _handle_comment(self, token):
"""Handle a case where an HTML comment is at the head of the tokens."""
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.CommentEnd):
contents = self._pop()
return Comment(contents)
else:
self._write(self._handle_token(token))
raise ParserError("_handle_comment() missed a close token") | [
"def",
"_handle_comment",
"(",
"self",
",",
"token",
")",
":",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"CommentEnd",
")",
":",
"contents",
"=",
"self",
".",
"_pop",
"(",
")",
"return",
"Comment",
"(",
"contents",
")",
"else",
":",
"self",
".",
"_write",
"(",
"self",
".",
"_handle_token",
"(",
"token",
")",
")",
"raise",
"ParserError",
"(",
"\"_handle_comment() missed a close token\"",
")"
]
| Handle a case where an HTML comment is at the head of the tokens. | [
"Handle",
"a",
"case",
"where",
"an",
"HTML",
"comment",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L209-L219 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_attribute | def _handle_attribute(self, start):
"""Handle a case where a tag attribute is at the head of the tokens."""
name = quotes = None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.TagAttrEquals):
name = self._pop()
self._push()
elif isinstance(token, tokens.TagAttrQuote):
quotes = token.char
elif isinstance(token, (tokens.TagAttrStart, tokens.TagCloseOpen,
tokens.TagCloseSelfclose)):
self._tokens.append(token)
if name:
value = self._pop()
else:
name, value = self._pop(), None
return Attribute(name, value, quotes, start.pad_first,
start.pad_before_eq, start.pad_after_eq)
else:
self._write(self._handle_token(token))
raise ParserError("_handle_attribute() missed a close token") | python | def _handle_attribute(self, start):
"""Handle a case where a tag attribute is at the head of the tokens."""
name = quotes = None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.TagAttrEquals):
name = self._pop()
self._push()
elif isinstance(token, tokens.TagAttrQuote):
quotes = token.char
elif isinstance(token, (tokens.TagAttrStart, tokens.TagCloseOpen,
tokens.TagCloseSelfclose)):
self._tokens.append(token)
if name:
value = self._pop()
else:
name, value = self._pop(), None
return Attribute(name, value, quotes, start.pad_first,
start.pad_before_eq, start.pad_after_eq)
else:
self._write(self._handle_token(token))
raise ParserError("_handle_attribute() missed a close token") | [
"def",
"_handle_attribute",
"(",
"self",
",",
"start",
")",
":",
"name",
"=",
"quotes",
"=",
"None",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"TagAttrEquals",
")",
":",
"name",
"=",
"self",
".",
"_pop",
"(",
")",
"self",
".",
"_push",
"(",
")",
"elif",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"TagAttrQuote",
")",
":",
"quotes",
"=",
"token",
".",
"char",
"elif",
"isinstance",
"(",
"token",
",",
"(",
"tokens",
".",
"TagAttrStart",
",",
"tokens",
".",
"TagCloseOpen",
",",
"tokens",
".",
"TagCloseSelfclose",
")",
")",
":",
"self",
".",
"_tokens",
".",
"append",
"(",
"token",
")",
"if",
"name",
":",
"value",
"=",
"self",
".",
"_pop",
"(",
")",
"else",
":",
"name",
",",
"value",
"=",
"self",
".",
"_pop",
"(",
")",
",",
"None",
"return",
"Attribute",
"(",
"name",
",",
"value",
",",
"quotes",
",",
"start",
".",
"pad_first",
",",
"start",
".",
"pad_before_eq",
",",
"start",
".",
"pad_after_eq",
")",
"else",
":",
"self",
".",
"_write",
"(",
"self",
".",
"_handle_token",
"(",
"token",
")",
")",
"raise",
"ParserError",
"(",
"\"_handle_attribute() missed a close token\"",
")"
]
| Handle a case where a tag attribute is at the head of the tokens. | [
"Handle",
"a",
"case",
"where",
"a",
"tag",
"attribute",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L221-L243 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_tag | def _handle_tag(self, token):
"""Handle a case where a tag is at the head of the tokens."""
close_tokens = (tokens.TagCloseSelfclose, tokens.TagCloseClose)
implicit, attrs, contents, closing_tag = False, [], None, None
wiki_markup, invalid = token.wiki_markup, token.invalid or False
wiki_style_separator, closing_wiki_markup = None, wiki_markup
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.TagAttrStart):
attrs.append(self._handle_attribute(token))
elif isinstance(token, tokens.TagCloseOpen):
wiki_style_separator = token.wiki_markup
padding = token.padding or ""
tag = self._pop()
self._push()
elif isinstance(token, tokens.TagOpenClose):
closing_wiki_markup = token.wiki_markup
contents = self._pop()
self._push()
elif isinstance(token, close_tokens):
if isinstance(token, tokens.TagCloseSelfclose):
closing_wiki_markup = token.wiki_markup
tag = self._pop()
self_closing = True
padding = token.padding or ""
implicit = token.implicit or False
else:
self_closing = False
closing_tag = self._pop()
return Tag(tag, contents, attrs, wiki_markup, self_closing,
invalid, implicit, padding, closing_tag,
wiki_style_separator, closing_wiki_markup)
else:
self._write(self._handle_token(token))
raise ParserError("_handle_tag() missed a close token") | python | def _handle_tag(self, token):
"""Handle a case where a tag is at the head of the tokens."""
close_tokens = (tokens.TagCloseSelfclose, tokens.TagCloseClose)
implicit, attrs, contents, closing_tag = False, [], None, None
wiki_markup, invalid = token.wiki_markup, token.invalid or False
wiki_style_separator, closing_wiki_markup = None, wiki_markup
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.TagAttrStart):
attrs.append(self._handle_attribute(token))
elif isinstance(token, tokens.TagCloseOpen):
wiki_style_separator = token.wiki_markup
padding = token.padding or ""
tag = self._pop()
self._push()
elif isinstance(token, tokens.TagOpenClose):
closing_wiki_markup = token.wiki_markup
contents = self._pop()
self._push()
elif isinstance(token, close_tokens):
if isinstance(token, tokens.TagCloseSelfclose):
closing_wiki_markup = token.wiki_markup
tag = self._pop()
self_closing = True
padding = token.padding or ""
implicit = token.implicit or False
else:
self_closing = False
closing_tag = self._pop()
return Tag(tag, contents, attrs, wiki_markup, self_closing,
invalid, implicit, padding, closing_tag,
wiki_style_separator, closing_wiki_markup)
else:
self._write(self._handle_token(token))
raise ParserError("_handle_tag() missed a close token") | [
"def",
"_handle_tag",
"(",
"self",
",",
"token",
")",
":",
"close_tokens",
"=",
"(",
"tokens",
".",
"TagCloseSelfclose",
",",
"tokens",
".",
"TagCloseClose",
")",
"implicit",
",",
"attrs",
",",
"contents",
",",
"closing_tag",
"=",
"False",
",",
"[",
"]",
",",
"None",
",",
"None",
"wiki_markup",
",",
"invalid",
"=",
"token",
".",
"wiki_markup",
",",
"token",
".",
"invalid",
"or",
"False",
"wiki_style_separator",
",",
"closing_wiki_markup",
"=",
"None",
",",
"wiki_markup",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"TagAttrStart",
")",
":",
"attrs",
".",
"append",
"(",
"self",
".",
"_handle_attribute",
"(",
"token",
")",
")",
"elif",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"TagCloseOpen",
")",
":",
"wiki_style_separator",
"=",
"token",
".",
"wiki_markup",
"padding",
"=",
"token",
".",
"padding",
"or",
"\"\"",
"tag",
"=",
"self",
".",
"_pop",
"(",
")",
"self",
".",
"_push",
"(",
")",
"elif",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"TagOpenClose",
")",
":",
"closing_wiki_markup",
"=",
"token",
".",
"wiki_markup",
"contents",
"=",
"self",
".",
"_pop",
"(",
")",
"self",
".",
"_push",
"(",
")",
"elif",
"isinstance",
"(",
"token",
",",
"close_tokens",
")",
":",
"if",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"TagCloseSelfclose",
")",
":",
"closing_wiki_markup",
"=",
"token",
".",
"wiki_markup",
"tag",
"=",
"self",
".",
"_pop",
"(",
")",
"self_closing",
"=",
"True",
"padding",
"=",
"token",
".",
"padding",
"or",
"\"\"",
"implicit",
"=",
"token",
".",
"implicit",
"or",
"False",
"else",
":",
"self_closing",
"=",
"False",
"closing_tag",
"=",
"self",
".",
"_pop",
"(",
")",
"return",
"Tag",
"(",
"tag",
",",
"contents",
",",
"attrs",
",",
"wiki_markup",
",",
"self_closing",
",",
"invalid",
",",
"implicit",
",",
"padding",
",",
"closing_tag",
",",
"wiki_style_separator",
",",
"closing_wiki_markup",
")",
"else",
":",
"self",
".",
"_write",
"(",
"self",
".",
"_handle_token",
"(",
"token",
")",
")",
"raise",
"ParserError",
"(",
"\"_handle_tag() missed a close token\"",
")"
]
| Handle a case where a tag is at the head of the tokens. | [
"Handle",
"a",
"case",
"where",
"a",
"tag",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L246-L281 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_token | def _handle_token(self, token):
"""Handle a single token."""
try:
return _HANDLERS[type(token)](self, token)
except KeyError:
err = "_handle_token() got unexpected {0}"
raise ParserError(err.format(type(token).__name__)) | python | def _handle_token(self, token):
"""Handle a single token."""
try:
return _HANDLERS[type(token)](self, token)
except KeyError:
err = "_handle_token() got unexpected {0}"
raise ParserError(err.format(type(token).__name__)) | [
"def",
"_handle_token",
"(",
"self",
",",
"token",
")",
":",
"try",
":",
"return",
"_HANDLERS",
"[",
"type",
"(",
"token",
")",
"]",
"(",
"self",
",",
"token",
")",
"except",
"KeyError",
":",
"err",
"=",
"\"_handle_token() got unexpected {0}\"",
"raise",
"ParserError",
"(",
"err",
".",
"format",
"(",
"type",
"(",
"token",
")",
".",
"__name__",
")",
")"
]
| Handle a single token. | [
"Handle",
"a",
"single",
"token",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L283-L289 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder.build | def build(self, tokenlist):
"""Build a Wikicode object from a list tokens and return it."""
self._tokens = tokenlist
self._tokens.reverse()
self._push()
while self._tokens:
node = self._handle_token(self._tokens.pop())
self._write(node)
return self._pop() | python | def build(self, tokenlist):
"""Build a Wikicode object from a list tokens and return it."""
self._tokens = tokenlist
self._tokens.reverse()
self._push()
while self._tokens:
node = self._handle_token(self._tokens.pop())
self._write(node)
return self._pop() | [
"def",
"build",
"(",
"self",
",",
"tokenlist",
")",
":",
"self",
".",
"_tokens",
"=",
"tokenlist",
"self",
".",
"_tokens",
".",
"reverse",
"(",
")",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"node",
"=",
"self",
".",
"_handle_token",
"(",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
")",
"self",
".",
"_write",
"(",
"node",
")",
"return",
"self",
".",
"_pop",
"(",
")"
]
| Build a Wikicode object from a list tokens and return it. | [
"Build",
"a",
"Wikicode",
"object",
"from",
"a",
"list",
"tokens",
"and",
"return",
"it",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L291-L299 | train |
earwig/mwparserfromhell | mwparserfromhell/nodes/template.py | Template._select_theory | def _select_theory(theories):
"""Return the most likely spacing convention given different options.
Given a dictionary of convention options as keys and their occurrence
as values, return the convention that occurs the most, or ``None`` if
there is no clear preferred style.
"""
if theories:
values = tuple(theories.values())
best = max(values)
confidence = float(best) / sum(values)
if confidence > 0.5:
return tuple(theories.keys())[values.index(best)] | python | def _select_theory(theories):
"""Return the most likely spacing convention given different options.
Given a dictionary of convention options as keys and their occurrence
as values, return the convention that occurs the most, or ``None`` if
there is no clear preferred style.
"""
if theories:
values = tuple(theories.values())
best = max(values)
confidence = float(best) / sum(values)
if confidence > 0.5:
return tuple(theories.keys())[values.index(best)] | [
"def",
"_select_theory",
"(",
"theories",
")",
":",
"if",
"theories",
":",
"values",
"=",
"tuple",
"(",
"theories",
".",
"values",
"(",
")",
")",
"best",
"=",
"max",
"(",
"values",
")",
"confidence",
"=",
"float",
"(",
"best",
")",
"/",
"sum",
"(",
"values",
")",
"if",
"confidence",
">",
"0.5",
":",
"return",
"tuple",
"(",
"theories",
".",
"keys",
"(",
")",
")",
"[",
"values",
".",
"index",
"(",
"best",
")",
"]"
]
| Return the most likely spacing convention given different options.
Given a dictionary of convention options as keys and their occurrence
as values, return the convention that occurs the most, or ``None`` if
there is no clear preferred style. | [
"Return",
"the",
"most",
"likely",
"spacing",
"convention",
"given",
"different",
"options",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/nodes/template.py#L93-L105 | train |
earwig/mwparserfromhell | mwparserfromhell/nodes/template.py | Template._get_spacing_conventions | def _get_spacing_conventions(self, use_names):
"""Try to determine the whitespace conventions for parameters.
This will examine the existing parameters and use
:meth:`_select_theory` to determine if there are any preferred styles
for how much whitespace to put before or after the value.
"""
before_theories = defaultdict(lambda: 0)
after_theories = defaultdict(lambda: 0)
for param in self.params:
if not param.showkey:
continue
if use_names:
component = str(param.name)
else:
component = str(param.value)
match = re.search(r"^(\s*).*?(\s*)$", component, FLAGS)
before, after = match.group(1), match.group(2)
if not use_names and component.isspace() and "\n" in before:
# If the value is empty, we expect newlines in the whitespace
# to be after the content, not before it:
before, after = before.split("\n", 1)
after = "\n" + after
before_theories[before] += 1
after_theories[after] += 1
before = self._select_theory(before_theories)
after = self._select_theory(after_theories)
return before, after | python | def _get_spacing_conventions(self, use_names):
"""Try to determine the whitespace conventions for parameters.
This will examine the existing parameters and use
:meth:`_select_theory` to determine if there are any preferred styles
for how much whitespace to put before or after the value.
"""
before_theories = defaultdict(lambda: 0)
after_theories = defaultdict(lambda: 0)
for param in self.params:
if not param.showkey:
continue
if use_names:
component = str(param.name)
else:
component = str(param.value)
match = re.search(r"^(\s*).*?(\s*)$", component, FLAGS)
before, after = match.group(1), match.group(2)
if not use_names and component.isspace() and "\n" in before:
# If the value is empty, we expect newlines in the whitespace
# to be after the content, not before it:
before, after = before.split("\n", 1)
after = "\n" + after
before_theories[before] += 1
after_theories[after] += 1
before = self._select_theory(before_theories)
after = self._select_theory(after_theories)
return before, after | [
"def",
"_get_spacing_conventions",
"(",
"self",
",",
"use_names",
")",
":",
"before_theories",
"=",
"defaultdict",
"(",
"lambda",
":",
"0",
")",
"after_theories",
"=",
"defaultdict",
"(",
"lambda",
":",
"0",
")",
"for",
"param",
"in",
"self",
".",
"params",
":",
"if",
"not",
"param",
".",
"showkey",
":",
"continue",
"if",
"use_names",
":",
"component",
"=",
"str",
"(",
"param",
".",
"name",
")",
"else",
":",
"component",
"=",
"str",
"(",
"param",
".",
"value",
")",
"match",
"=",
"re",
".",
"search",
"(",
"r\"^(\\s*).*?(\\s*)$\"",
",",
"component",
",",
"FLAGS",
")",
"before",
",",
"after",
"=",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"2",
")",
"if",
"not",
"use_names",
"and",
"component",
".",
"isspace",
"(",
")",
"and",
"\"\\n\"",
"in",
"before",
":",
"# If the value is empty, we expect newlines in the whitespace",
"# to be after the content, not before it:",
"before",
",",
"after",
"=",
"before",
".",
"split",
"(",
"\"\\n\"",
",",
"1",
")",
"after",
"=",
"\"\\n\"",
"+",
"after",
"before_theories",
"[",
"before",
"]",
"+=",
"1",
"after_theories",
"[",
"after",
"]",
"+=",
"1",
"before",
"=",
"self",
".",
"_select_theory",
"(",
"before_theories",
")",
"after",
"=",
"self",
".",
"_select_theory",
"(",
"after_theories",
")",
"return",
"before",
",",
"after"
]
| Try to determine the whitespace conventions for parameters.
This will examine the existing parameters and use
:meth:`_select_theory` to determine if there are any preferred styles
for how much whitespace to put before or after the value. | [
"Try",
"to",
"determine",
"the",
"whitespace",
"conventions",
"for",
"parameters",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/nodes/template.py#L123-L151 | train |
earwig/mwparserfromhell | mwparserfromhell/nodes/template.py | Template._should_remove | def _should_remove(self, i, name):
"""Look ahead for a parameter with the same name, but hidden.
If one exists, we should remove the given one rather than blanking it.
"""
if self.params[i].showkey:
following = self.params[i + 1:]
better_matches = [after.name.strip() == name and not after.showkey
for after in following]
return any(better_matches)
return False | python | def _should_remove(self, i, name):
"""Look ahead for a parameter with the same name, but hidden.
If one exists, we should remove the given one rather than blanking it.
"""
if self.params[i].showkey:
following = self.params[i + 1:]
better_matches = [after.name.strip() == name and not after.showkey
for after in following]
return any(better_matches)
return False | [
"def",
"_should_remove",
"(",
"self",
",",
"i",
",",
"name",
")",
":",
"if",
"self",
".",
"params",
"[",
"i",
"]",
".",
"showkey",
":",
"following",
"=",
"self",
".",
"params",
"[",
"i",
"+",
"1",
":",
"]",
"better_matches",
"=",
"[",
"after",
".",
"name",
".",
"strip",
"(",
")",
"==",
"name",
"and",
"not",
"after",
".",
"showkey",
"for",
"after",
"in",
"following",
"]",
"return",
"any",
"(",
"better_matches",
")",
"return",
"False"
]
| Look ahead for a parameter with the same name, but hidden.
If one exists, we should remove the given one rather than blanking it. | [
"Look",
"ahead",
"for",
"a",
"parameter",
"with",
"the",
"same",
"name",
"but",
"hidden",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/nodes/template.py#L172-L182 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._push | def _push(self, context=0):
"""Add a new token stack, context, and textbuffer to the list."""
new_ident = (self._head, context)
if new_ident in self._bad_routes:
raise BadRoute(context)
self._stacks.append([[], context, [], new_ident])
self._depth += 1 | python | def _push(self, context=0):
"""Add a new token stack, context, and textbuffer to the list."""
new_ident = (self._head, context)
if new_ident in self._bad_routes:
raise BadRoute(context)
self._stacks.append([[], context, [], new_ident])
self._depth += 1 | [
"def",
"_push",
"(",
"self",
",",
"context",
"=",
"0",
")",
":",
"new_ident",
"=",
"(",
"self",
".",
"_head",
",",
"context",
")",
"if",
"new_ident",
"in",
"self",
".",
"_bad_routes",
":",
"raise",
"BadRoute",
"(",
"context",
")",
"self",
".",
"_stacks",
".",
"append",
"(",
"[",
"[",
"]",
",",
"context",
",",
"[",
"]",
",",
"new_ident",
"]",
")",
"self",
".",
"_depth",
"+=",
"1"
]
| Add a new token stack, context, and textbuffer to the list. | [
"Add",
"a",
"new",
"token",
"stack",
"context",
"and",
"textbuffer",
"to",
"the",
"list",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L113-L120 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._push_textbuffer | def _push_textbuffer(self):
"""Push the textbuffer onto the stack as a Text node and clear it."""
if self._textbuffer:
self._stack.append(tokens.Text(text="".join(self._textbuffer)))
self._textbuffer = [] | python | def _push_textbuffer(self):
"""Push the textbuffer onto the stack as a Text node and clear it."""
if self._textbuffer:
self._stack.append(tokens.Text(text="".join(self._textbuffer)))
self._textbuffer = [] | [
"def",
"_push_textbuffer",
"(",
"self",
")",
":",
"if",
"self",
".",
"_textbuffer",
":",
"self",
".",
"_stack",
".",
"append",
"(",
"tokens",
".",
"Text",
"(",
"text",
"=",
"\"\"",
".",
"join",
"(",
"self",
".",
"_textbuffer",
")",
")",
")",
"self",
".",
"_textbuffer",
"=",
"[",
"]"
]
| Push the textbuffer onto the stack as a Text node and clear it. | [
"Push",
"the",
"textbuffer",
"onto",
"the",
"stack",
"as",
"a",
"Text",
"node",
"and",
"clear",
"it",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L122-L126 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._fail_route | def _fail_route(self):
"""Fail the current tokenization route.
Discards the current stack/context/textbuffer and raises
:exc:`.BadRoute`.
"""
context = self._context
self._memoize_bad_route()
self._pop()
raise BadRoute(context) | python | def _fail_route(self):
"""Fail the current tokenization route.
Discards the current stack/context/textbuffer and raises
:exc:`.BadRoute`.
"""
context = self._context
self._memoize_bad_route()
self._pop()
raise BadRoute(context) | [
"def",
"_fail_route",
"(",
"self",
")",
":",
"context",
"=",
"self",
".",
"_context",
"self",
".",
"_memoize_bad_route",
"(",
")",
"self",
".",
"_pop",
"(",
")",
"raise",
"BadRoute",
"(",
"context",
")"
]
| Fail the current tokenization route.
Discards the current stack/context/textbuffer and raises
:exc:`.BadRoute`. | [
"Fail",
"the",
"current",
"tokenization",
"route",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L155-L164 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._emit_all | def _emit_all(self, tokenlist):
"""Write a series of tokens to the current stack at once."""
if tokenlist and isinstance(tokenlist[0], tokens.Text):
self._emit_text(tokenlist.pop(0).text)
self._push_textbuffer()
self._stack.extend(tokenlist) | python | def _emit_all(self, tokenlist):
"""Write a series of tokens to the current stack at once."""
if tokenlist and isinstance(tokenlist[0], tokens.Text):
self._emit_text(tokenlist.pop(0).text)
self._push_textbuffer()
self._stack.extend(tokenlist) | [
"def",
"_emit_all",
"(",
"self",
",",
"tokenlist",
")",
":",
"if",
"tokenlist",
"and",
"isinstance",
"(",
"tokenlist",
"[",
"0",
"]",
",",
"tokens",
".",
"Text",
")",
":",
"self",
".",
"_emit_text",
"(",
"tokenlist",
".",
"pop",
"(",
"0",
")",
".",
"text",
")",
"self",
".",
"_push_textbuffer",
"(",
")",
"self",
".",
"_stack",
".",
"extend",
"(",
"tokenlist",
")"
]
| Write a series of tokens to the current stack at once. | [
"Write",
"a",
"series",
"of",
"tokens",
"to",
"the",
"current",
"stack",
"at",
"once",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L180-L185 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._read | def _read(self, delta=0, wrap=False, strict=False):
"""Read the value at a relative point in the wikicode.
The value is read from :attr:`self._head <_head>` plus the value of
*delta* (which can be negative). If *wrap* is ``False``, we will not
allow attempts to read from the end of the string if ``self._head +
delta`` is negative. If *strict* is ``True``, the route will be failed
(with :meth:`_fail_route`) if we try to read from past the end of the
string; otherwise, :attr:`self.END <END>` is returned. If we try to
read from before the start of the string, :attr:`self.START <START>` is
returned.
"""
index = self._head + delta
if index < 0 and (not wrap or abs(index) > len(self._text)):
return self.START
try:
return self._text[index]
except IndexError:
if strict:
self._fail_route()
return self.END | python | def _read(self, delta=0, wrap=False, strict=False):
"""Read the value at a relative point in the wikicode.
The value is read from :attr:`self._head <_head>` plus the value of
*delta* (which can be negative). If *wrap* is ``False``, we will not
allow attempts to read from the end of the string if ``self._head +
delta`` is negative. If *strict* is ``True``, the route will be failed
(with :meth:`_fail_route`) if we try to read from past the end of the
string; otherwise, :attr:`self.END <END>` is returned. If we try to
read from before the start of the string, :attr:`self.START <START>` is
returned.
"""
index = self._head + delta
if index < 0 and (not wrap or abs(index) > len(self._text)):
return self.START
try:
return self._text[index]
except IndexError:
if strict:
self._fail_route()
return self.END | [
"def",
"_read",
"(",
"self",
",",
"delta",
"=",
"0",
",",
"wrap",
"=",
"False",
",",
"strict",
"=",
"False",
")",
":",
"index",
"=",
"self",
".",
"_head",
"+",
"delta",
"if",
"index",
"<",
"0",
"and",
"(",
"not",
"wrap",
"or",
"abs",
"(",
"index",
")",
">",
"len",
"(",
"self",
".",
"_text",
")",
")",
":",
"return",
"self",
".",
"START",
"try",
":",
"return",
"self",
".",
"_text",
"[",
"index",
"]",
"except",
"IndexError",
":",
"if",
"strict",
":",
"self",
".",
"_fail_route",
"(",
")",
"return",
"self",
".",
"END"
]
| Read the value at a relative point in the wikicode.
The value is read from :attr:`self._head <_head>` plus the value of
*delta* (which can be negative). If *wrap* is ``False``, we will not
allow attempts to read from the end of the string if ``self._head +
delta`` is negative. If *strict* is ``True``, the route will be failed
(with :meth:`_fail_route`) if we try to read from past the end of the
string; otherwise, :attr:`self.END <END>` is returned. If we try to
read from before the start of the string, :attr:`self.START <START>` is
returned. | [
"Read",
"the",
"value",
"at",
"a",
"relative",
"point",
"in",
"the",
"wikicode",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L195-L215 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._parse_template | def _parse_template(self, has_content):
"""Parse a template at the head of the wikicode string."""
reset = self._head
context = contexts.TEMPLATE_NAME
if has_content:
context |= contexts.HAS_TEMPLATE
try:
template = self._parse(context)
except BadRoute:
self._head = reset
raise
self._emit_first(tokens.TemplateOpen())
self._emit_all(template)
self._emit(tokens.TemplateClose()) | python | def _parse_template(self, has_content):
"""Parse a template at the head of the wikicode string."""
reset = self._head
context = contexts.TEMPLATE_NAME
if has_content:
context |= contexts.HAS_TEMPLATE
try:
template = self._parse(context)
except BadRoute:
self._head = reset
raise
self._emit_first(tokens.TemplateOpen())
self._emit_all(template)
self._emit(tokens.TemplateClose()) | [
"def",
"_parse_template",
"(",
"self",
",",
"has_content",
")",
":",
"reset",
"=",
"self",
".",
"_head",
"context",
"=",
"contexts",
".",
"TEMPLATE_NAME",
"if",
"has_content",
":",
"context",
"|=",
"contexts",
".",
"HAS_TEMPLATE",
"try",
":",
"template",
"=",
"self",
".",
"_parse",
"(",
"context",
")",
"except",
"BadRoute",
":",
"self",
".",
"_head",
"=",
"reset",
"raise",
"self",
".",
"_emit_first",
"(",
"tokens",
".",
"TemplateOpen",
"(",
")",
")",
"self",
".",
"_emit_all",
"(",
"template",
")",
"self",
".",
"_emit",
"(",
"tokens",
".",
"TemplateClose",
"(",
")",
")"
]
| Parse a template at the head of the wikicode string. | [
"Parse",
"a",
"template",
"at",
"the",
"head",
"of",
"the",
"wikicode",
"string",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L217-L230 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._parse_argument | def _parse_argument(self):
"""Parse an argument at the head of the wikicode string."""
reset = self._head
try:
argument = self._parse(contexts.ARGUMENT_NAME)
except BadRoute:
self._head = reset
raise
self._emit_first(tokens.ArgumentOpen())
self._emit_all(argument)
self._emit(tokens.ArgumentClose()) | python | def _parse_argument(self):
"""Parse an argument at the head of the wikicode string."""
reset = self._head
try:
argument = self._parse(contexts.ARGUMENT_NAME)
except BadRoute:
self._head = reset
raise
self._emit_first(tokens.ArgumentOpen())
self._emit_all(argument)
self._emit(tokens.ArgumentClose()) | [
"def",
"_parse_argument",
"(",
"self",
")",
":",
"reset",
"=",
"self",
".",
"_head",
"try",
":",
"argument",
"=",
"self",
".",
"_parse",
"(",
"contexts",
".",
"ARGUMENT_NAME",
")",
"except",
"BadRoute",
":",
"self",
".",
"_head",
"=",
"reset",
"raise",
"self",
".",
"_emit_first",
"(",
"tokens",
".",
"ArgumentOpen",
"(",
")",
")",
"self",
".",
"_emit_all",
"(",
"argument",
")",
"self",
".",
"_emit",
"(",
"tokens",
".",
"ArgumentClose",
"(",
")",
")"
]
| Parse an argument at the head of the wikicode string. | [
"Parse",
"an",
"argument",
"at",
"the",
"head",
"of",
"the",
"wikicode",
"string",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L232-L242 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._parse_template_or_argument | def _parse_template_or_argument(self):
"""Parse a template or argument at the head of the wikicode string."""
self._head += 2
braces = 2
while self._read() == "{":
self._head += 1
braces += 1
has_content = False
self._push()
while braces:
if braces == 1:
return self._emit_text_then_stack("{")
if braces == 2:
try:
self._parse_template(has_content)
except BadRoute:
return self._emit_text_then_stack("{{")
break
try:
self._parse_argument()
braces -= 3
except BadRoute:
try:
self._parse_template(has_content)
braces -= 2
except BadRoute:
return self._emit_text_then_stack("{" * braces)
if braces:
has_content = True
self._head += 1
self._emit_all(self._pop())
if self._context & contexts.FAIL_NEXT:
self._context ^= contexts.FAIL_NEXT | python | def _parse_template_or_argument(self):
"""Parse a template or argument at the head of the wikicode string."""
self._head += 2
braces = 2
while self._read() == "{":
self._head += 1
braces += 1
has_content = False
self._push()
while braces:
if braces == 1:
return self._emit_text_then_stack("{")
if braces == 2:
try:
self._parse_template(has_content)
except BadRoute:
return self._emit_text_then_stack("{{")
break
try:
self._parse_argument()
braces -= 3
except BadRoute:
try:
self._parse_template(has_content)
braces -= 2
except BadRoute:
return self._emit_text_then_stack("{" * braces)
if braces:
has_content = True
self._head += 1
self._emit_all(self._pop())
if self._context & contexts.FAIL_NEXT:
self._context ^= contexts.FAIL_NEXT | [
"def",
"_parse_template_or_argument",
"(",
"self",
")",
":",
"self",
".",
"_head",
"+=",
"2",
"braces",
"=",
"2",
"while",
"self",
".",
"_read",
"(",
")",
"==",
"\"{\"",
":",
"self",
".",
"_head",
"+=",
"1",
"braces",
"+=",
"1",
"has_content",
"=",
"False",
"self",
".",
"_push",
"(",
")",
"while",
"braces",
":",
"if",
"braces",
"==",
"1",
":",
"return",
"self",
".",
"_emit_text_then_stack",
"(",
"\"{\"",
")",
"if",
"braces",
"==",
"2",
":",
"try",
":",
"self",
".",
"_parse_template",
"(",
"has_content",
")",
"except",
"BadRoute",
":",
"return",
"self",
".",
"_emit_text_then_stack",
"(",
"\"{{\"",
")",
"break",
"try",
":",
"self",
".",
"_parse_argument",
"(",
")",
"braces",
"-=",
"3",
"except",
"BadRoute",
":",
"try",
":",
"self",
".",
"_parse_template",
"(",
"has_content",
")",
"braces",
"-=",
"2",
"except",
"BadRoute",
":",
"return",
"self",
".",
"_emit_text_then_stack",
"(",
"\"{\"",
"*",
"braces",
")",
"if",
"braces",
":",
"has_content",
"=",
"True",
"self",
".",
"_head",
"+=",
"1",
"self",
".",
"_emit_all",
"(",
"self",
".",
"_pop",
"(",
")",
")",
"if",
"self",
".",
"_context",
"&",
"contexts",
".",
"FAIL_NEXT",
":",
"self",
".",
"_context",
"^=",
"contexts",
".",
"FAIL_NEXT"
]
| Parse a template or argument at the head of the wikicode string. | [
"Parse",
"a",
"template",
"or",
"argument",
"at",
"the",
"head",
"of",
"the",
"wikicode",
"string",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L244-L278 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_template_param | def _handle_template_param(self):
"""Handle a template parameter at the head of the string."""
if self._context & contexts.TEMPLATE_NAME:
if not self._context & (contexts.HAS_TEXT | contexts.HAS_TEMPLATE):
self._fail_route()
self._context ^= contexts.TEMPLATE_NAME
elif self._context & contexts.TEMPLATE_PARAM_VALUE:
self._context ^= contexts.TEMPLATE_PARAM_VALUE
else:
self._emit_all(self._pop())
self._context |= contexts.TEMPLATE_PARAM_KEY
self._emit(tokens.TemplateParamSeparator())
self._push(self._context) | python | def _handle_template_param(self):
"""Handle a template parameter at the head of the string."""
if self._context & contexts.TEMPLATE_NAME:
if not self._context & (contexts.HAS_TEXT | contexts.HAS_TEMPLATE):
self._fail_route()
self._context ^= contexts.TEMPLATE_NAME
elif self._context & contexts.TEMPLATE_PARAM_VALUE:
self._context ^= contexts.TEMPLATE_PARAM_VALUE
else:
self._emit_all(self._pop())
self._context |= contexts.TEMPLATE_PARAM_KEY
self._emit(tokens.TemplateParamSeparator())
self._push(self._context) | [
"def",
"_handle_template_param",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"&",
"contexts",
".",
"TEMPLATE_NAME",
":",
"if",
"not",
"self",
".",
"_context",
"&",
"(",
"contexts",
".",
"HAS_TEXT",
"|",
"contexts",
".",
"HAS_TEMPLATE",
")",
":",
"self",
".",
"_fail_route",
"(",
")",
"self",
".",
"_context",
"^=",
"contexts",
".",
"TEMPLATE_NAME",
"elif",
"self",
".",
"_context",
"&",
"contexts",
".",
"TEMPLATE_PARAM_VALUE",
":",
"self",
".",
"_context",
"^=",
"contexts",
".",
"TEMPLATE_PARAM_VALUE",
"else",
":",
"self",
".",
"_emit_all",
"(",
"self",
".",
"_pop",
"(",
")",
")",
"self",
".",
"_context",
"|=",
"contexts",
".",
"TEMPLATE_PARAM_KEY",
"self",
".",
"_emit",
"(",
"tokens",
".",
"TemplateParamSeparator",
"(",
")",
")",
"self",
".",
"_push",
"(",
"self",
".",
"_context",
")"
]
| Handle a template parameter at the head of the string. | [
"Handle",
"a",
"template",
"parameter",
"at",
"the",
"head",
"of",
"the",
"string",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L280-L292 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_template_param_value | def _handle_template_param_value(self):
"""Handle a template parameter's value at the head of the string."""
self._emit_all(self._pop())
self._context ^= contexts.TEMPLATE_PARAM_KEY
self._context |= contexts.TEMPLATE_PARAM_VALUE
self._emit(tokens.TemplateParamEquals()) | python | def _handle_template_param_value(self):
"""Handle a template parameter's value at the head of the string."""
self._emit_all(self._pop())
self._context ^= contexts.TEMPLATE_PARAM_KEY
self._context |= contexts.TEMPLATE_PARAM_VALUE
self._emit(tokens.TemplateParamEquals()) | [
"def",
"_handle_template_param_value",
"(",
"self",
")",
":",
"self",
".",
"_emit_all",
"(",
"self",
".",
"_pop",
"(",
")",
")",
"self",
".",
"_context",
"^=",
"contexts",
".",
"TEMPLATE_PARAM_KEY",
"self",
".",
"_context",
"|=",
"contexts",
".",
"TEMPLATE_PARAM_VALUE",
"self",
".",
"_emit",
"(",
"tokens",
".",
"TemplateParamEquals",
"(",
")",
")"
]
| Handle a template parameter's value at the head of the string. | [
"Handle",
"a",
"template",
"parameter",
"s",
"value",
"at",
"the",
"head",
"of",
"the",
"string",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L294-L299 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_template_end | def _handle_template_end(self):
"""Handle the end of a template at the head of the string."""
if self._context & contexts.TEMPLATE_NAME:
if not self._context & (contexts.HAS_TEXT | contexts.HAS_TEMPLATE):
self._fail_route()
elif self._context & contexts.TEMPLATE_PARAM_KEY:
self._emit_all(self._pop())
self._head += 1
return self._pop() | python | def _handle_template_end(self):
"""Handle the end of a template at the head of the string."""
if self._context & contexts.TEMPLATE_NAME:
if not self._context & (contexts.HAS_TEXT | contexts.HAS_TEMPLATE):
self._fail_route()
elif self._context & contexts.TEMPLATE_PARAM_KEY:
self._emit_all(self._pop())
self._head += 1
return self._pop() | [
"def",
"_handle_template_end",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"&",
"contexts",
".",
"TEMPLATE_NAME",
":",
"if",
"not",
"self",
".",
"_context",
"&",
"(",
"contexts",
".",
"HAS_TEXT",
"|",
"contexts",
".",
"HAS_TEMPLATE",
")",
":",
"self",
".",
"_fail_route",
"(",
")",
"elif",
"self",
".",
"_context",
"&",
"contexts",
".",
"TEMPLATE_PARAM_KEY",
":",
"self",
".",
"_emit_all",
"(",
"self",
".",
"_pop",
"(",
")",
")",
"self",
".",
"_head",
"+=",
"1",
"return",
"self",
".",
"_pop",
"(",
")"
]
| Handle the end of a template at the head of the string. | [
"Handle",
"the",
"end",
"of",
"a",
"template",
"at",
"the",
"head",
"of",
"the",
"string",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L301-L309 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_argument_separator | def _handle_argument_separator(self):
"""Handle the separator between an argument's name and default."""
self._context ^= contexts.ARGUMENT_NAME
self._context |= contexts.ARGUMENT_DEFAULT
self._emit(tokens.ArgumentSeparator()) | python | def _handle_argument_separator(self):
"""Handle the separator between an argument's name and default."""
self._context ^= contexts.ARGUMENT_NAME
self._context |= contexts.ARGUMENT_DEFAULT
self._emit(tokens.ArgumentSeparator()) | [
"def",
"_handle_argument_separator",
"(",
"self",
")",
":",
"self",
".",
"_context",
"^=",
"contexts",
".",
"ARGUMENT_NAME",
"self",
".",
"_context",
"|=",
"contexts",
".",
"ARGUMENT_DEFAULT",
"self",
".",
"_emit",
"(",
"tokens",
".",
"ArgumentSeparator",
"(",
")",
")"
]
| Handle the separator between an argument's name and default. | [
"Handle",
"the",
"separator",
"between",
"an",
"argument",
"s",
"name",
"and",
"default",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L311-L315 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._parse_wikilink | def _parse_wikilink(self):
"""Parse an internal wikilink at the head of the wikicode string."""
reset = self._head + 1
self._head += 2
try:
# If the wikilink looks like an external link, parse it as such:
link, extra, delta = self._really_parse_external_link(True)
except BadRoute:
self._head = reset + 1
try:
# Otherwise, actually parse it as a wikilink:
wikilink = self._parse(contexts.WIKILINK_TITLE)
except BadRoute:
self._head = reset
self._emit_text("[[")
else:
self._emit(tokens.WikilinkOpen())
self._emit_all(wikilink)
self._emit(tokens.WikilinkClose())
else:
if self._context & contexts.EXT_LINK_TITLE:
# In this exceptional case, an external link that looks like a
# wikilink inside of an external link is parsed as text:
self._head = reset
self._emit_text("[[")
return
self._emit_text("[")
self._emit(tokens.ExternalLinkOpen(brackets=True))
self._emit_all(link)
self._emit(tokens.ExternalLinkClose()) | python | def _parse_wikilink(self):
"""Parse an internal wikilink at the head of the wikicode string."""
reset = self._head + 1
self._head += 2
try:
# If the wikilink looks like an external link, parse it as such:
link, extra, delta = self._really_parse_external_link(True)
except BadRoute:
self._head = reset + 1
try:
# Otherwise, actually parse it as a wikilink:
wikilink = self._parse(contexts.WIKILINK_TITLE)
except BadRoute:
self._head = reset
self._emit_text("[[")
else:
self._emit(tokens.WikilinkOpen())
self._emit_all(wikilink)
self._emit(tokens.WikilinkClose())
else:
if self._context & contexts.EXT_LINK_TITLE:
# In this exceptional case, an external link that looks like a
# wikilink inside of an external link is parsed as text:
self._head = reset
self._emit_text("[[")
return
self._emit_text("[")
self._emit(tokens.ExternalLinkOpen(brackets=True))
self._emit_all(link)
self._emit(tokens.ExternalLinkClose()) | [
"def",
"_parse_wikilink",
"(",
"self",
")",
":",
"reset",
"=",
"self",
".",
"_head",
"+",
"1",
"self",
".",
"_head",
"+=",
"2",
"try",
":",
"# If the wikilink looks like an external link, parse it as such:",
"link",
",",
"extra",
",",
"delta",
"=",
"self",
".",
"_really_parse_external_link",
"(",
"True",
")",
"except",
"BadRoute",
":",
"self",
".",
"_head",
"=",
"reset",
"+",
"1",
"try",
":",
"# Otherwise, actually parse it as a wikilink:",
"wikilink",
"=",
"self",
".",
"_parse",
"(",
"contexts",
".",
"WIKILINK_TITLE",
")",
"except",
"BadRoute",
":",
"self",
".",
"_head",
"=",
"reset",
"self",
".",
"_emit_text",
"(",
"\"[[\"",
")",
"else",
":",
"self",
".",
"_emit",
"(",
"tokens",
".",
"WikilinkOpen",
"(",
")",
")",
"self",
".",
"_emit_all",
"(",
"wikilink",
")",
"self",
".",
"_emit",
"(",
"tokens",
".",
"WikilinkClose",
"(",
")",
")",
"else",
":",
"if",
"self",
".",
"_context",
"&",
"contexts",
".",
"EXT_LINK_TITLE",
":",
"# In this exceptional case, an external link that looks like a",
"# wikilink inside of an external link is parsed as text:",
"self",
".",
"_head",
"=",
"reset",
"self",
".",
"_emit_text",
"(",
"\"[[\"",
")",
"return",
"self",
".",
"_emit_text",
"(",
"\"[\"",
")",
"self",
".",
"_emit",
"(",
"tokens",
".",
"ExternalLinkOpen",
"(",
"brackets",
"=",
"True",
")",
")",
"self",
".",
"_emit_all",
"(",
"link",
")",
"self",
".",
"_emit",
"(",
"tokens",
".",
"ExternalLinkClose",
"(",
")",
")"
]
| Parse an internal wikilink at the head of the wikicode string. | [
"Parse",
"an",
"internal",
"wikilink",
"at",
"the",
"head",
"of",
"the",
"wikicode",
"string",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L322-L351 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_wikilink_separator | def _handle_wikilink_separator(self):
"""Handle the separator between a wikilink's title and its text."""
self._context ^= contexts.WIKILINK_TITLE
self._context |= contexts.WIKILINK_TEXT
self._emit(tokens.WikilinkSeparator()) | python | def _handle_wikilink_separator(self):
"""Handle the separator between a wikilink's title and its text."""
self._context ^= contexts.WIKILINK_TITLE
self._context |= contexts.WIKILINK_TEXT
self._emit(tokens.WikilinkSeparator()) | [
"def",
"_handle_wikilink_separator",
"(",
"self",
")",
":",
"self",
".",
"_context",
"^=",
"contexts",
".",
"WIKILINK_TITLE",
"self",
".",
"_context",
"|=",
"contexts",
".",
"WIKILINK_TEXT",
"self",
".",
"_emit",
"(",
"tokens",
".",
"WikilinkSeparator",
"(",
")",
")"
]
| Handle the separator between a wikilink's title and its text. | [
"Handle",
"the",
"separator",
"between",
"a",
"wikilink",
"s",
"title",
"and",
"its",
"text",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L353-L357 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.