sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def remove_comments(xml):
"""
Remove comments, as they can break the xml parser.
See html5lib issue #122 ( http://code.google.com/p/html5lib/issues/detail?id=122 ).
>>> remove_comments('<!-- -->')
''
>>> remove_comments('<!--\\n-->')
''
>>> remove_comments('<p>stuff<!-- \\n -->stuff</p... | Remove comments, as they can break the xml parser.
See html5lib issue #122 ( http://code.google.com/p/html5lib/issues/detail?id=122 ).
>>> remove_comments('<!-- -->')
''
>>> remove_comments('<!--\\n-->')
''
>>> remove_comments('<p>stuff<!-- \\n -->stuff</p>')
'<p>stuffstuff</p>' | entailment |
def remove_newlines(xml):
r"""Remove newlines in the xml.
If the newline separates words in text, then replace with a space instead.
>>> remove_newlines('<p>para one</p>\n<p>para two</p>')
'<p>para one</p><p>para two</p>'
>>> remove_newlines('<p>line one\nline two</p>')
'<p>line one line two</... | r"""Remove newlines in the xml.
If the newline separates words in text, then replace with a space instead.
>>> remove_newlines('<p>para one</p>\n<p>para two</p>')
'<p>para one</p><p>para two</p>'
>>> remove_newlines('<p>line one\nline two</p>')
'<p>line one line two</p>'
>>> remove_newlines('o... | entailment |
def remove_insignificant_text_nodes(dom):
"""
For html elements that should not have text nodes inside them, remove all
whitespace. For elements that may have text, collapse multiple spaces to a
single space.
"""
nodes_to_remove = []
for node in walk_dom(dom):
if is_text(node):
... | For html elements that should not have text nodes inside them, remove all
whitespace. For elements that may have text, collapse multiple spaces to a
single space. | entailment |
def get_child(parent, child_index):
"""
Get the child at the given index, or return None if it doesn't exist.
"""
if child_index < 0 or child_index >= len(parent.childNodes):
return None
return parent.childNodes[child_index] | Get the child at the given index, or return None if it doesn't exist. | entailment |
def get_location(dom, location):
"""
Get the node at the specified location in the dom.
Location is a sequence of child indices, starting at the children of the
root element. If there is no node at this location, raise a ValueError.
"""
node = dom.documentElement
for i in location:
n... | Get the node at the specified location in the dom.
Location is a sequence of child indices, starting at the children of the
root element. If there is no node at this location, raise a ValueError. | entailment |
def check_text_similarity(a_dom, b_dom, cutoff):
"""Check whether two dom trees have similar text or not."""
a_words = list(tree_words(a_dom))
b_words = list(tree_words(b_dom))
sm = WordMatcher(a=a_words, b=b_words)
if sm.text_ratio() >= cutoff:
return True
return False | Check whether two dom trees have similar text or not. | entailment |
def tree_words(node):
"""Return all the significant text below the given node as a list of words.
>>> list(tree_words(parse_minidom('<h1>one</h1> two <div>three<em>four</em></div>')))
['one', 'two', 'three', 'four']
"""
for word in split_text(tree_text(node)):
word = word.strip()
if ... | Return all the significant text below the given node as a list of words.
>>> list(tree_words(parse_minidom('<h1>one</h1> two <div>three<em>four</em></div>')))
['one', 'two', 'three', 'four'] | entailment |
def tree_text(node):
"""
>>> tree_text(parse_minidom('<h1>one</h1>two<div>three<em>four</em></div>'))
'one two three four'
"""
text = []
for descendant in walk_dom(node):
if is_text(descendant):
text.append(descendant.nodeValue)
return ' '.join(text) | >>> tree_text(parse_minidom('<h1>one</h1>two<div>three<em>four</em></div>'))
'one two three four' | entailment |
def insert_or_append(parent, node, next_sibling):
"""
Insert the node before next_sibling. If next_sibling is None, append the node last instead.
"""
# simple insert
if next_sibling:
parent.insertBefore(node, next_sibling)
else:
parent.appendChild(node) | Insert the node before next_sibling. If next_sibling is None, append the node last instead. | entailment |
def wrap(node, tag):
"""Wrap the given tag around a node."""
wrap_node = node.ownerDocument.createElement(tag)
parent = node.parentNode
if parent:
parent.replaceChild(wrap_node, node)
wrap_node.appendChild(node)
return wrap_node | Wrap the given tag around a node. | entailment |
def wrap_inner(node, tag):
"""Wrap the given tag around the contents of a node."""
children = list(node.childNodes)
wrap_node = node.ownerDocument.createElement(tag)
for c in children:
wrap_node.appendChild(c)
node.appendChild(wrap_node) | Wrap the given tag around the contents of a node. | entailment |
def unwrap(node):
"""Remove a node, replacing it with its children."""
for child in list(node.childNodes):
node.parentNode.insertBefore(child, node)
remove_node(node) | Remove a node, replacing it with its children. | entailment |
def full_split(text, regex):
"""
Split the text by the regex, keeping all parts.
The parts should re-join back into the original text.
>>> list(full_split('word', re.compile('&.*?')))
['word']
"""
while text:
m = regex.search(text)
if not m:
yield text
... | Split the text by the regex, keeping all parts.
The parts should re-join back into the original text.
>>> list(full_split('word', re.compile('&.*?')))
['word'] | entailment |
def multi_split(text, regexes):
"""
Split the text by the given regexes, in priority order.
Make sure that the regex is parenthesized so that matches are returned in
re.split().
Splitting on a single regex works like normal split.
>>> '|'.join(multi_split('one two three', [r'\w+']))
'one| ... | Split the text by the given regexes, in priority order.
Make sure that the regex is parenthesized so that matches are returned in
re.split().
Splitting on a single regex works like normal split.
>>> '|'.join(multi_split('one two three', [r'\w+']))
'one| |two| |three'
Splitting on digits first... | entailment |
def text_ratio(self):
"""Return a measure of the sequences' word similarity (float in [0,1]).
Each word has weight equal to its length for this measure
>>> m = WordMatcher(a=['abcdef', '12'], b=['abcdef', '34']) # 3/4 of the text is the same
>>> '%.3f' % m.ratio() # normal ratio fails
... | Return a measure of the sequences' word similarity (float in [0,1]).
Each word has weight equal to its length for this measure
>>> m = WordMatcher(a=['abcdef', '12'], b=['abcdef', '34']) # 3/4 of the text is the same
>>> '%.3f' % m.ratio() # normal ratio fails
'0.500'
>>> '%.3f... | entailment |
def match_length(self):
""" Find the total length of all words that match between the two sequences."""
length = 0
for match in self.get_matching_blocks():
a, b, size = match
length += self._text_length(self.a[a:a+size])
return length | Find the total length of all words that match between the two sequences. | entailment |
def run_edit_script(self):
"""
Run an xml edit script, and return the new html produced.
"""
for action, location, properties in self.edit_script:
if action == 'delete':
node = get_location(self.dom, location)
self.action_delete(node)
... | Run an xml edit script, and return the new html produced. | entailment |
def add_changes_markup(dom, ins_nodes, del_nodes):
"""
Add <ins> and <del> tags to the dom to show changes.
"""
# add markup for inserted and deleted sections
for node in reversed(del_nodes):
# diff algorithm deletes nodes in reverse order, so un-reverse the
# order for this iteratio... | Add <ins> and <del> tags to the dom to show changes. | entailment |
def remove_nesting(dom, tag_name):
"""
Unwrap items in the node list that have ancestors with the same tag.
"""
for node in dom.getElementsByTagName(tag_name):
for ancestor in ancestors(node):
if ancestor is node:
continue
if ancestor is dom.documentElemen... | Unwrap items in the node list that have ancestors with the same tag. | entailment |
def sort_nodes(dom, cmp_func):
"""
Sort the nodes of the dom in-place, based on a comparison function.
"""
dom.normalize()
for node in list(walk_dom(dom, elements_only=True)):
prev_sib = node.previousSibling
while prev_sib and cmp_func(prev_sib, node) == 1:
node.parentNod... | Sort the nodes of the dom in-place, based on a comparison function. | entailment |
def merge_adjacent(dom, tag_name):
"""
Merge all adjacent tags with the specified tag name.
Return the number of merges performed.
"""
for node in dom.getElementsByTagName(tag_name):
prev_sib = node.previousSibling
if prev_sib and prev_sib.nodeName == node.tagName:
for ch... | Merge all adjacent tags with the specified tag name.
Return the number of merges performed. | entailment |
def distribute(node):
"""
Wrap a copy of the given element around the contents of each of its
children, removing the node in the process.
"""
children = list(c for c in node.childNodes if is_element(c))
unwrap(node)
tag_name = node.tagName
for c in children:
wrap_inner(c, tag_nam... | Wrap a copy of the given element around the contents of each of its
children, removing the node in the process. | entailment |
def save(self, *args, **kwargs):
"""
Save object to the database. Removes all other entries if there
are any.
"""
self.__class__.objects.exclude(id=self.id).delete()
super(SingletonModel, self).save(*args, **kwargs) | Save object to the database. Removes all other entries if there
are any. | entailment |
def get_magicc_region_to_openscm_region_mapping(inverse=False):
"""Get the mappings from MAGICC to OpenSCM regions.
This is not a pure inverse of the other way around. For example, we never provide
"GLOBAL" as a MAGICC return value because it's unnecesarily confusing when we also
have "World". Fortunat... | Get the mappings from MAGICC to OpenSCM regions.
This is not a pure inverse of the other way around. For example, we never provide
"GLOBAL" as a MAGICC return value because it's unnecesarily confusing when we also
have "World". Fortunately MAGICC doesn't ever read the name "GLOBAL" so this
shouldn't ma... | entailment |
def convert_magicc_to_openscm_regions(regions, inverse=False):
"""
Convert MAGICC regions to OpenSCM regions
Parameters
----------
regions : list_like, str
Regions to convert
inverse : bool
If True, convert the other way i.e. convert OpenSCM regions to MAGICC7
regions
... | Convert MAGICC regions to OpenSCM regions
Parameters
----------
regions : list_like, str
Regions to convert
inverse : bool
If True, convert the other way i.e. convert OpenSCM regions to MAGICC7
regions
Returns
-------
``type(regions)``
Set of converted regi... | entailment |
def get_magicc7_to_openscm_variable_mapping(inverse=False):
"""Get the mappings from MAGICC7 to OpenSCM variables.
Parameters
----------
inverse : bool
If True, return the inverse mappings i.e. OpenSCM to MAGICC7 mappings
Returns
-------
dict
Dictionary of mappings
"""
... | Get the mappings from MAGICC7 to OpenSCM variables.
Parameters
----------
inverse : bool
If True, return the inverse mappings i.e. OpenSCM to MAGICC7 mappings
Returns
-------
dict
Dictionary of mappings | entailment |
def convert_magicc7_to_openscm_variables(variables, inverse=False):
"""
Convert MAGICC7 variables to OpenSCM variables
Parameters
----------
variables : list_like, str
Variables to convert
inverse : bool
If True, convert the other way i.e. convert OpenSCM variables to MAGICC7
... | Convert MAGICC7 variables to OpenSCM variables
Parameters
----------
variables : list_like, str
Variables to convert
inverse : bool
If True, convert the other way i.e. convert OpenSCM variables to MAGICC7
variables
Returns
-------
``type(variables)``
Set of... | entailment |
def get_magicc6_to_magicc7_variable_mapping(inverse=False):
"""Get the mappings from MAGICC6 to MAGICC7 variables.
Note that this mapping is not one to one. For example, "HFC4310", "HFC43-10" and
"HFC-43-10" in MAGICC6 both map to "HFC4310" in MAGICC7 but "HFC4310" in
MAGICC7 maps back to "HFC4310".
... | Get the mappings from MAGICC6 to MAGICC7 variables.
Note that this mapping is not one to one. For example, "HFC4310", "HFC43-10" and
"HFC-43-10" in MAGICC6 both map to "HFC4310" in MAGICC7 but "HFC4310" in
MAGICC7 maps back to "HFC4310".
Note that HFC-245fa was mistakenly labelled as HFC-245ca in MAGI... | entailment |
def convert_magicc6_to_magicc7_variables(variables, inverse=False):
"""
Convert MAGICC6 variables to MAGICC7 variables
Parameters
----------
variables : list_like, str
Variables to convert
inverse : bool
If True, convert the other way i.e. convert MAGICC7 variables to MAGICC6
... | Convert MAGICC6 variables to MAGICC7 variables
Parameters
----------
variables : list_like, str
Variables to convert
inverse : bool
If True, convert the other way i.e. convert MAGICC7 variables to MAGICC6
variables
Raises
------
ValueError
If you try to con... | entailment |
def get_pint_to_fortran_safe_units_mapping(inverse=False):
"""Get the mappings from Pint to Fortran safe units.
Fortran can't handle special characters like "^" or "/" in names, but we need
these in Pint. Conversely, Pint stores variables with spaces by default e.g. "Mt
CO2 / yr" but we don't want thes... | Get the mappings from Pint to Fortran safe units.
Fortran can't handle special characters like "^" or "/" in names, but we need
these in Pint. Conversely, Pint stores variables with spaces by default e.g. "Mt
CO2 / yr" but we don't want these in the input files as Fortran is likely to think
the whitesp... | entailment |
def convert_pint_to_fortran_safe_units(units, inverse=False):
"""
Convert Pint units to Fortran safe units
Parameters
----------
units : list_like, str
Units to convert
inverse : bool
If True, convert the other way i.e. convert Fortran safe units to Pint units
Returns
... | Convert Pint units to Fortran safe units
Parameters
----------
units : list_like, str
Units to convert
inverse : bool
If True, convert the other way i.e. convert Fortran safe units to Pint units
Returns
-------
``type(units)``
Set of converted units | entailment |
def run_evaluate(self) -> None:
"""
Overrides the base evaluation to set the value to the evaluation result of the value
expression in the schema
"""
result = None
self.eval_error = False
if self._needs_evaluation:
result = self._schema.value.evaluate(... | Overrides the base evaluation to set the value to the evaluation result of the value
expression in the schema | entailment |
def set(self, key: Any, value: Any) -> None:
""" Sets the value of a key to a supplied value """
if key is not None:
self[key] = value | Sets the value of a key to a supplied value | entailment |
def increment(self, key: Any, by: int = 1) -> None:
""" Increments the value set against a key. If the key is not present, 0 is assumed as the initial state """
if key is not None:
self[key] = self.get(key, 0) + by | Increments the value set against a key. If the key is not present, 0 is assumed as the initial state | entailment |
def insert(self, index: int, obj: Any) -> None:
""" Inserts an item to the list as long as it is not None """
if obj is not None:
super().insert(index, obj) | Inserts an item to the list as long as it is not None | entailment |
def get_dattype_regionmode(regions, scen7=False):
"""
Get the THISFILE_DATTYPE and THISFILE_REGIONMODE flags for a given region set.
In all MAGICC input files, there are two flags: THISFILE_DATTYPE and
THISFILE_REGIONMODE. These tell MAGICC how to read in a given input file. This
function maps the ... | Get the THISFILE_DATTYPE and THISFILE_REGIONMODE flags for a given region set.
In all MAGICC input files, there are two flags: THISFILE_DATTYPE and
THISFILE_REGIONMODE. These tell MAGICC how to read in a given input file. This
function maps the regions which are in a given file to the value of these flags
... | entailment |
def get_region_order(regions, scen7=False):
"""
Get the region order expected by MAGICC.
Parameters
----------
regions : list_like
The regions to get THISFILE_DATTYPE and THISFILE_REGIONMODE flags for.
scen7 : bool, optional
Whether the file we are getting the flags for is a SC... | Get the region order expected by MAGICC.
Parameters
----------
regions : list_like
The regions to get THISFILE_DATTYPE and THISFILE_REGIONMODE flags for.
scen7 : bool, optional
Whether the file we are getting the flags for is a SCEN7 file or not.
Returns
-------
list
... | entailment |
def get_special_scen_code(regions, emissions):
"""
Get special code for MAGICC6 SCEN files.
At the top of every MAGICC6 and MAGICC5 SCEN file there is a two digit
number. The first digit, the 'scenfile_region_code' tells MAGICC how many regions
data is being provided for. The second digit, the 'sce... | Get special code for MAGICC6 SCEN files.
At the top of every MAGICC6 and MAGICC5 SCEN file there is a two digit
number. The first digit, the 'scenfile_region_code' tells MAGICC how many regions
data is being provided for. The second digit, the 'scenfile_emissions_code', tells
MAGICC which gases are in ... | entailment |
def determine_tool(filepath, tool_to_get):
"""
Determine the tool to use for reading/writing.
The function uses an internally defined set of mappings between filepaths,
regular expresions and readers/writers to work out which tool to use
for a given task, given the filepath.
It is intended for... | Determine the tool to use for reading/writing.
The function uses an internally defined set of mappings between filepaths,
regular expresions and readers/writers to work out which tool to use
for a given task, given the filepath.
It is intended for internal use only, but is public because of its
im... | entailment |
def pull_cfg_from_parameters_out(parameters_out, namelist_to_read="nml_allcfgs"):
"""Pull out a single config set from a parameters_out namelist.
This function returns a single file with the config that needs to be passed to
MAGICC in order to do the same run as is represented by the values in
``parame... | Pull out a single config set from a parameters_out namelist.
This function returns a single file with the config that needs to be passed to
MAGICC in order to do the same run as is represented by the values in
``parameters_out``.
Parameters
----------
parameters_out : dict, f90nml.Namelist
... | entailment |
def pull_cfg_from_parameters_out_file(
parameters_out_file, namelist_to_read="nml_allcfgs"
):
"""Pull out a single config set from a MAGICC ``PARAMETERS.OUT`` file.
This function reads in the ``PARAMETERS.OUT`` file and returns a single file with
the config that needs to be passed to MAGICC in order to... | Pull out a single config set from a MAGICC ``PARAMETERS.OUT`` file.
This function reads in the ``PARAMETERS.OUT`` file and returns a single file with
the config that needs to be passed to MAGICC in order to do the same run as is
represented by the values in ``PARAMETERS.OUT``.
Parameters
---------... | entailment |
def get_generic_rcp_name(inname):
"""Convert an RCP name into the generic Pymagicc RCP name
The conversion is case insensitive.
Parameters
----------
inname : str
The name for which to get the generic Pymagicc RCP name
Returns
-------
str
The generic Pymagicc RCP name
... | Convert an RCP name into the generic Pymagicc RCP name
The conversion is case insensitive.
Parameters
----------
inname : str
The name for which to get the generic Pymagicc RCP name
Returns
-------
str
The generic Pymagicc RCP name
Examples
--------
>>> get_ge... | entailment |
def join_timeseries(base, overwrite, join_linear=None):
"""Join two sets of timeseries
Parameters
----------
base : :obj:`MAGICCData`, :obj:`pd.DataFrame`, filepath
Base timeseries to use. If a filepath, the data will first be loaded from disk.
overwrite : :obj:`MAGICCData`, :obj:`pd.DataF... | Join two sets of timeseries
Parameters
----------
base : :obj:`MAGICCData`, :obj:`pd.DataFrame`, filepath
Base timeseries to use. If a filepath, the data will first be loaded from disk.
overwrite : :obj:`MAGICCData`, :obj:`pd.DataFrame`, filepath
Timeseries to join onto base. Any point... | entailment |
def read_scen_file(
filepath,
columns={
"model": ["unspecified"],
"scenario": ["unspecified"],
"climate_model": ["unspecified"],
},
**kwargs
):
"""
Read a MAGICC .SCEN file.
Parameters
----------
filepath : str
Filepath of the .SCEN file to read
... | Read a MAGICC .SCEN file.
Parameters
----------
filepath : str
Filepath of the .SCEN file to read
columns : dict
Passed to ``__init__`` method of MAGICCData. See
``MAGICCData.__init__`` for details.
kwargs
Passed to ``__init__`` method of MAGICCData. See
``... | entailment |
def _get_openscm_var_from_filepath(filepath):
"""
Determine the OpenSCM variable from a filepath.
Uses MAGICC's internal, implicit, filenaming conventions.
Parameters
----------
filepath : str
Filepath from which to determine the OpenSCM variable.
Returns
-------
str
... | Determine the OpenSCM variable from a filepath.
Uses MAGICC's internal, implicit, filenaming conventions.
Parameters
----------
filepath : str
Filepath from which to determine the OpenSCM variable.
Returns
-------
str
The OpenSCM variable implied by the filepath. | entailment |
def _find_nml(self):
"""
Find the start and end of the embedded namelist.
Returns
-------
(int, int)
start and end index for the namelist
"""
nml_start = None
nml_end = None
for i in range(len(self.lines)):
if self.lines[i]... | Find the start and end of the embedded namelist.
Returns
-------
(int, int)
start and end index for the namelist | entailment |
def process_data(self, stream, metadata):
"""
Extract the tabulated data from the input file.
Parameters
----------
stream : Streamlike object
A Streamlike object (nominally StringIO)
containing the table to be extracted
metadata : dict
... | Extract the tabulated data from the input file.
Parameters
----------
stream : Streamlike object
A Streamlike object (nominally StringIO)
containing the table to be extracted
metadata : dict
Metadata read in from the header and the namelist
R... | entailment |
def _convert_data_block_and_headers_to_df(self, stream):
"""
stream : Streamlike object
A Streamlike object (nominally StringIO) containing the data to be
extracted
ch : dict
Column headers to use for the output pd.DataFrame
Returns
-------
... | stream : Streamlike object
A Streamlike object (nominally StringIO) containing the data to be
extracted
ch : dict
Column headers to use for the output pd.DataFrame
Returns
-------
:obj:`pd.DataFrame`
Dataframe with processed datablock | entailment |
def _get_variable_from_filepath(self):
"""
Determine the file variable from the filepath.
Returns
-------
str
Best guess of variable name from the filepath
"""
try:
return self.regexp_capture_variable.search(self.filepath).group(1)
... | Determine the file variable from the filepath.
Returns
-------
str
Best guess of variable name from the filepath | entailment |
def process_header(self, header):
"""
Parse the header for additional metadata.
Parameters
----------
header : str
All the lines in the header.
Returns
-------
dict
The metadata in the header.
"""
metadata = {}
... | Parse the header for additional metadata.
Parameters
----------
header : str
All the lines in the header.
Returns
-------
dict
The metadata in the header. | entailment |
def _read_data_header_line(self, stream, expected_header):
"""Read a data header line, ensuring that it starts with the expected header
Parameters
----------
stream : :obj:`StreamIO`
Stream object containing the text to read
expected_header : str, list of strs
... | Read a data header line, ensuring that it starts with the expected header
Parameters
----------
stream : :obj:`StreamIO`
Stream object containing the text to read
expected_header : str, list of strs
Expected header of the data header line | entailment |
def read_chunk(self, t):
"""
Read out the next chunk of memory
Values in fortran binary streams begin and end with the number of bytes
:param t: Data type (same format as used by struct).
:return: Numpy array if the variable is an array, otherwise a scalar.
"""
s... | Read out the next chunk of memory
Values in fortran binary streams begin and end with the number of bytes
:param t: Data type (same format as used by struct).
:return: Numpy array if the variable is an array, otherwise a scalar. | entailment |
def process_data(self, stream, metadata):
"""
Extract the tabulated data from the input file
# Arguments
stream (Streamlike object): A Streamlike object (nominally StringIO)
containing the table to be extracted
metadata (dict): metadata read in from the header and th... | Extract the tabulated data from the input file
# Arguments
stream (Streamlike object): A Streamlike object (nominally StringIO)
containing the table to be extracted
metadata (dict): metadata read in from the header and the namelist
# Returns
df (pandas.DataFrame): c... | entailment |
def process_header(self, data):
"""
Reads the first part of the file to get some essential metadata
# Returns
return (dict): the metadata in the header
"""
metadata = {
"datacolumns": data.read_chunk("I"),
"firstyear": data.read_chunk("I"),
... | Reads the first part of the file to get some essential metadata
# Returns
return (dict): the metadata in the header | entailment |
def write(self, magicc_input, filepath):
"""
Write a MAGICC input file from df and metadata
Parameters
----------
magicc_input : :obj:`pymagicc.io.MAGICCData`
MAGICCData object which holds the data to write
filepath : str
Filepath of the file to ... | Write a MAGICC input file from df and metadata
Parameters
----------
magicc_input : :obj:`pymagicc.io.MAGICCData`
MAGICCData object which holds the data to write
filepath : str
Filepath of the file to write to. | entailment |
def append(self, other, inplace=False, **kwargs):
"""
Append any input which can be converted to MAGICCData to self.
Parameters
----------
other : MAGICCData, pd.DataFrame, pd.Series, str
Source of data to append.
inplace : bool
If True, append `... | Append any input which can be converted to MAGICCData to self.
Parameters
----------
other : MAGICCData, pd.DataFrame, pd.Series, str
Source of data to append.
inplace : bool
If True, append ``other`` inplace, otherwise return a new ``MAGICCData``
in... | entailment |
def write(self, filepath, magicc_version):
"""
Write an input file to disk.
Parameters
----------
filepath : str
Filepath of the file to write.
magicc_version : int
The MAGICC version for which we want to write files. MAGICC7 and MAGICC6
... | Write an input file to disk.
Parameters
----------
filepath : str
Filepath of the file to write.
magicc_version : int
The MAGICC version for which we want to write files. MAGICC7 and MAGICC6
namelists are incompatible hence we need to know which one ... | entailment |
def validate_python_identifier_attributes(fully_qualified_name: str, spec: Dict[str, Any],
*attributes: str) -> List[InvalidIdentifierError]:
""" Validates a set of attributes as identifiers in a spec """
errors: List[InvalidIdentifierError] = []
checks: List[Tuple... | Validates a set of attributes as identifiers in a spec | entailment |
def validate_required_attributes(fully_qualified_name: str, spec: Dict[str, Any],
*attributes: str) -> List[RequiredAttributeError]:
""" Validates to ensure that a set of attributes are present in spec """
return [
RequiredAttributeError(fully_qualified_name, spec, attri... | Validates to ensure that a set of attributes are present in spec | entailment |
def validate_empty_attributes(fully_qualified_name: str, spec: Dict[str, Any],
*attributes: str) -> List[EmptyAttributeError]:
""" Validates to ensure that a set of attributes do not contain empty values """
return [
EmptyAttributeError(fully_qualified_name, spec, attribute... | Validates to ensure that a set of attributes do not contain empty values | entailment |
def validate_number_attribute(
fully_qualified_name: str,
spec: Dict[str, Any],
attribute: str,
value_type: Union[Type[int], Type[float]] = int,
minimum: Optional[Union[int, float]] = None,
maximum: Optional[Union[int, float]] = None) -> Optional[InvalidNumberError]:
... | Validates to ensure that the value is a number of the specified type, and lies with the specified range | entailment |
def validate_enum_attribute(fully_qualified_name: str, spec: Dict[str, Any], attribute: str,
candidates: Set[Union[str, int, float]]) -> Optional[InvalidValueError]:
""" Validates to ensure that the value of an attribute lies within an allowed set of candidates """
if attribute not ... | Validates to ensure that the value of an attribute lies within an allowed set of candidates | entailment |
def parse(key_string: str) -> 'Key':
""" Parses a flat key string and returns a key """
parts = key_string.split(Key.PARTITION)
key_type = KeyType.DIMENSION
if parts[3]:
key_type = KeyType.TIMESTAMP
return Key(key_type, parts[0], parts[1], parts[2].split(Key.DIMENSION... | Parses a flat key string and returns a key | entailment |
def parse_sort_key(identity: str, sort_key_string: str) -> 'Key':
""" Parses a flat key string and returns a key """
parts = sort_key_string.split(Key.PARTITION)
key_type = KeyType.DIMENSION
if parts[2]:
key_type = KeyType.TIMESTAMP
return Key(key_type, identity, part... | Parses a flat key string and returns a key | entailment |
def starts_with(self, other: 'Key') -> bool:
"""
Checks if this key starts with the other key provided. Returns False if key_type, identity
or group are different.
For `KeyType.TIMESTAMP` returns True.
For `KeyType.DIMENSION` does prefix match between the two dimensions property.... | Checks if this key starts with the other key provided. Returns False if key_type, identity
or group are different.
For `KeyType.TIMESTAMP` returns True.
For `KeyType.DIMENSION` does prefix match between the two dimensions property. | entailment |
def _evaluate_dimension_fields(self) -> bool:
"""
Evaluates the dimension fields. Returns False if any of the fields could not be evaluated.
"""
for _, item in self._dimension_fields.items():
item.run_evaluate()
if item.eval_error:
return False
... | Evaluates the dimension fields. Returns False if any of the fields could not be evaluated. | entailment |
def _compare_dimensions_to_fields(self) -> bool:
""" Compares the dimension field values to the value in regular fields."""
for name, item in self._dimension_fields.items():
if item.value != self._nested_items[name].value:
return False
return True | Compares the dimension field values to the value in regular fields. | entailment |
def _key(self):
""" Generates the Key object based on dimension fields. """
return Key(self._schema.key_type, self._identity, self._name,
[str(item.value) for item in self._dimension_fields.values()]) | Generates the Key object based on dimension fields. | entailment |
def run(scenario, magicc_version=6, **kwargs):
"""
Run a MAGICC scenario and return output data and (optionally) config parameters.
As a reminder, putting ``out_parameters=1`` will cause MAGICC to write out its
parameters into ``out/PARAMETERS.OUT`` and they will then be read into
``output.metadata... | Run a MAGICC scenario and return output data and (optionally) config parameters.
As a reminder, putting ``out_parameters=1`` will cause MAGICC to write out its
parameters into ``out/PARAMETERS.OUT`` and they will then be read into
``output.metadata["parameters"]`` where ``output`` is the returned object.
... | entailment |
def run_evaluate(self, block: TimeAggregate) -> bool:
"""
Evaluates the anchor condition against the specified block.
:param block: Block to run the anchor condition against.
:return: True, if the anchor condition is met, otherwise, False.
"""
if self._anchor.evaluate_anc... | Evaluates the anchor condition against the specified block.
:param block: Block to run the anchor condition against.
:return: True, if the anchor condition is met, otherwise, False. | entailment |
def extend_schema_spec(self) -> None:
""" Injects the block start and end times """
super().extend_schema_spec()
if self.ATTRIBUTE_FIELDS in self._spec:
# Add new fields to the schema spec. Since `_identity` is added by the super, new elements are added after
predefined_... | Injects the block start and end times | entailment |
def _build_time_fields_spec(name_in_context: str) -> List[Dict[str, Any]]:
"""
Constructs the spec for predefined fields that are to be included in the master spec prior to schema load
:param name_in_context: Name of the current object in the context
:return:
"""
return [... | Constructs the spec for predefined fields that are to be included in the master spec prior to schema load
:param name_in_context: Name of the current object in the context
:return: | entailment |
def apply_string_substitutions(
inputs,
substitutions,
inverse=False,
case_insensitive=False,
unused_substitutions="ignore",
):
"""Apply a number of substitutions to a string(s).
The substitutions are applied effectively all at once. This means that conflicting
substitutions don't inter... | Apply a number of substitutions to a string(s).
The substitutions are applied effectively all at once. This means that conflicting
substitutions don't interact. Where substitutions are conflicting, the one which
is longer takes precedance. This is confusing so we recommend that you look at
the examples... | entailment |
def get_range(self,
base_key: Key,
start_time: datetime,
end_time: datetime = None,
count: int = 0) -> List[Tuple[Key, Any]]:
"""
Returns the list of items from the store based on the given time range or count.
:param base_k... | Returns the list of items from the store based on the given time range or count.
:param base_key: Items which don't start with the base_key are filtered out.
:param start_time: Start time to for the range query
:param end_time: End time of the range query. If None count is used.
:param c... | entailment |
def _get_range_timestamp_key(self, start: Key, end: Key,
count: int = 0) -> List[Tuple[Key, Any]]:
"""
Returns the list of items from the store based on the given time range or count.
This is used when the key being used is a TIMESTAMP key.
"""
r... | Returns the list of items from the store based on the given time range or count.
This is used when the key being used is a TIMESTAMP key. | entailment |
def _get_range_dimension_key(self,
base_key: Key,
start_time: datetime,
end_time: datetime,
count: int = 0) -> List[Tuple[Key, Any]]:
"""
Returns the list of items from the... | Returns the list of items from the store based on the given time range or count.
This is used when the key being used is a DIMENSION key. | entailment |
def _restrict_items_to_count(items: List[Tuple[Key, Any]], count: int) -> List[Tuple[Key, Any]]:
"""
Restricts items to count number if len(items) is larger than abs(count). This function
assumes that items is sorted by time.
:param items: The items to restrict.
:param count: Th... | Restricts items to count number if len(items) is larger than abs(count). This function
assumes that items is sorted by time.
:param items: The items to restrict.
:param count: The number of items returned. | entailment |
def build_expression(self, attribute: str) -> Optional[Expression]:
""" Builds an expression object. Adds an error if expression creation has errors. """
expression_string = self._spec.get(attribute, None)
if expression_string:
try:
return Expression(str(expression_... | Builds an expression object. Adds an error if expression creation has errors. | entailment |
def add_errors(self, *errors: Union[BaseSchemaError, List[BaseSchemaError]]) -> None:
""" Adds errors to the error repository in schema loader """
self.schema_loader.add_errors(*errors) | Adds errors to the error repository in schema loader | entailment |
def validate_required_attributes(self, *attributes: str) -> None:
""" Validates that the schema contains a series of required attributes """
self.add_errors(
validate_required_attributes(self.fully_qualified_name, self._spec, *attributes)) | Validates that the schema contains a series of required attributes | entailment |
def validate_number_attribute(self,
attribute: str,
value_type: Union[Type[int], Type[float]] = int,
minimum: Optional[Union[int, float]] = None,
maximum: Optional[Union[int, float]] =... | Validates that the attribute contains a numeric value within boundaries if specified | entailment |
def validate_enum_attribute(self, attribute: str,
candidates: Set[Union[str, int, float]]) -> None:
""" Validates that the attribute value is among the candidates """
self.add_errors(
validate_enum_attribute(self.fully_qualified_name, self._spec, attribute, ca... | Validates that the attribute value is among the candidates | entailment |
def validate_schema_spec(self) -> None:
""" Contains the validation routines that are to be executed as part of initialization by subclasses.
When this method is being extended, the first line should always be: ```super().validate_schema_spec()``` """
self.add_errors(
validate_empty_... | Contains the validation routines that are to be executed as part of initialization by subclasses.
When this method is being extended, the first line should always be: ```super().validate_schema_spec()``` | entailment |
def _needs_evaluation(self) -> bool:
"""
Returns True when:
1. Where clause is not specified
2. Where WHERE clause is specified and it evaluates to True
Returns false if a where clause is specified and it evaluates to False
"""
return self._schema.when is ... | Returns True when:
1. Where clause is not specified
2. Where WHERE clause is specified and it evaluates to True
Returns false if a where clause is specified and it evaluates to False | entailment |
def run_evaluate(self, *args, **kwargs) -> None:
"""
Evaluates the current item
:returns An evaluation result object containing the result, or reasons why
evaluation failed
"""
if self._needs_evaluation:
for _, item in self._nested_items.items():
... | Evaluates the current item
:returns An evaluation result object containing the result, or reasons why
evaluation failed | entailment |
def _snapshot(self) -> Dict[str, Any]:
"""
Implements snapshot for collections by recursively invoking snapshot of all child items
"""
try:
return {name: item._snapshot for name, item in self._nested_items.items()}
except Exception as e:
raise SnapshotErro... | Implements snapshot for collections by recursively invoking snapshot of all child items | entailment |
def run_restore(self, snapshot: Dict[Union[str, Key], Any]) -> 'BaseItemCollection':
"""
Restores the state of a collection from a snapshot
"""
try:
for name, snap in snapshot.items():
if isinstance(name, Key):
self._nested_items[name.grou... | Restores the state of a collection from a snapshot | entailment |
def _prepare_window(self, start_time: datetime) -> None:
"""
Prepares window if any is specified.
:param start_time: The anchor block start_time from where the window
should be generated.
"""
# evaluate window first which sets the correct window in the store
store... | Prepares window if any is specified.
:param start_time: The anchor block start_time from where the window
should be generated. | entailment |
def _get_end_time(self, start_time: datetime) -> datetime:
"""
Generates the end time to be used for the store range query.
:param start_time: Start time to use as an offset to calculate the end time
based on the window type in the schema.
:return:
"""
if Type.is_... | Generates the end time to be used for the store range query.
:param start_time: Start time to use as an offset to calculate the end time
based on the window type in the schema.
:return: | entailment |
def _load_blocks(self, blocks: List[Tuple[Key, Any]]) -> List[TimeAggregate]:
"""
Converts [(Key, block)] to [BlockAggregate]
:param blocks: List of (Key, block) blocks.
:return: List of BlockAggregate
"""
return [
TypeLoader.load_item(self._schema.source.type... | Converts [(Key, block)] to [BlockAggregate]
:param blocks: List of (Key, block) blocks.
:return: List of BlockAggregate | entailment |
def execute_per_identity_records(
self,
identity: str,
records: List[TimeAndRecord],
old_state: Optional[Dict[Key, Any]] = None) -> Tuple[str, Tuple[Dict, List]]:
"""
Executes the streaming and window BTS on the given records. An option old state can provi... | Executes the streaming and window BTS on the given records. An option old state can provided
which initializes the state for execution. This is useful for batch execution where the
previous state is written out to storage and can be loaded for the next batch run.
:param identity: Identity of th... | entailment |
def get_per_identity_records(self, events: Iterable, data_processor: DataProcessor
) -> Generator[Tuple[str, TimeAndRecord], None, None]:
"""
Uses the given iteratable events and the data processor convert the event into a list of
Records along with its identity ... | Uses the given iteratable events and the data processor convert the event into a list of
Records along with its identity and time.
:param events: iteratable events.
:param data_processor: DataProcessor to process each event in events.
:return: yields Tuple[Identity, TimeAndRecord] for al... | entailment |
def to_string(self, hdr, other):
"""String representation with additional information"""
result = "%s[%s,%s" % (
hdr, self.get_type(self.type), self.get_clazz(self.clazz))
if self.unique:
result += "-unique,"
else:
result += ","
result += s... | String representation with additional information | entailment |
def answered_by(self, rec):
"""Returns true if the question is answered by the record"""
return self.clazz == rec.clazz and \
(self.type == rec.type or self.type == _TYPE_ANY) and \
self.name == rec.name | Returns true if the question is answered by the record | entailment |
def reset_ttl(self, other):
"""Sets this record's TTL and created time to that of
another record."""
self.created = other.created
self.ttl = other.ttl | Sets this record's TTL and created time to that of
another record. | entailment |
def to_string(self, other):
"""String representation with addtional information"""
arg = "%s/%s,%s" % (
self.ttl, self.get_remaining_ttl(current_time_millis()), other)
return DNSEntry.to_string(self, "record", arg) | String representation with addtional information | entailment |
def write(self, out):
"""Used in constructing an outgoing packet"""
out.write_string(self.address, len(self.address)) | Used in constructing an outgoing packet | entailment |
def write(self, out):
"""Used in constructing an outgoing packet"""
out.write_string(self.cpu, len(self.cpu))
out.write_string(self.os, len(self.os)) | Used in constructing an outgoing packet | entailment |
def write(self, out):
"""Used in constructing an outgoing packet"""
out.write_string(self.text, len(self.text)) | Used in constructing an outgoing packet | entailment |
def set_property(self, key, value):
"""
Update only one property in the dict
"""
self.properties[key] = value
self.sync_properties() | Update only one property in the dict | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.