text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(fs, channels): """Allocates and initializes a decoder state"""
result_code = ctypes.c_int() result = _create(fs, channels, ctypes.byref(result_code)) if result_code.value is not 0: raise OpusError(result_code.value) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def packet_get_bandwidth(data): """Gets the bandwidth of an Opus packet."""
data_pointer = ctypes.c_char_p(data) result = _packet_get_bandwidth(data_pointer) if result < 0: raise OpusError(result) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def packet_get_nb_channels(data): """Gets the number of channels from an Opus packet"""
data_pointer = ctypes.c_char_p(data) result = _packet_get_nb_channels(data_pointer) if result < 0: raise OpusError(result) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def packet_get_nb_frames(data, length=None): """Gets the number of frames in an Opus packet"""
data_pointer = ctypes.c_char_p(data) if length is None: length = len(data) result = _packet_get_nb_frames(data_pointer, ctypes.c_int(length)) if result < 0: raise OpusError(result) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def packet_get_samples_per_frame(data, fs): """Gets the number of samples per frame from an Opus packet"""
data_pointer = ctypes.c_char_p(data) result = _packet_get_nb_frames(data_pointer, ctypes.c_int(fs)) if result < 0: raise OpusError(result) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(decoder, data, length, frame_size, decode_fec, channels=2): """Decode an Opus frame Unlike the `opus_decode` function , this function takes an additio...
pcm_size = frame_size * channels * ctypes.sizeof(ctypes.c_int16) pcm = (ctypes.c_int16 * pcm_size)() pcm_pointer = ctypes.cast(pcm, c_int16_pointer) # Converting from a boolean to int decode_fec = int(bool(decode_fec)) result = _decode(decoder, data, length, pcm_pointer, frame_size, decode_f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diff(old_html, new_html, cutoff=0.0, plaintext=False, pretty=False): """Show the differences between the old and new html document, as html. Return the docum...
if plaintext: old_dom = parse_text(old_html) new_dom = parse_text(new_html) else: old_dom = parse_minidom(old_html) new_dom = parse_minidom(new_html) # If the two documents are not similar enough, don't show the changes. if not check_text_similarity(old_dom, new_dom, cu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adjusted_ops(opcodes): """ Iterate through opcodes, turning them into a series of insert and delete operations, adjusting indices to account for the size of ...
while opcodes: op = opcodes.pop(0) tag, i1, i2, j1, j2 = op shift = 0 if tag == 'equal': continue if tag == 'replace': # change the single replace op into a delete then insert # pay careful attention to the variables here, there's no typo ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_opcodes(matching_blocks): """Use difflib to get the opcodes for a set of matching blocks."""
sm = difflib.SequenceMatcher(a=[], b=[]) sm.matching_blocks = matching_blocks return sm.get_opcodes()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match_blocks(hash_func, old_children, new_children): """Use difflib to find matching blocks."""
sm = difflib.SequenceMatcher( _is_junk, a=[hash_func(c) for c in old_children], b=[hash_func(c) for c in new_children], ) return sm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_nonmatching_blocks(matching_blocks): """Given a list of matching blocks, output the gaps between them. Non-matches have the format (alo, ahi, blo, bhi). ...
i = j = 0 for match in matching_blocks: a, b, size = match yield (i, a, j, b) i = a + size j = b + size
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_blocks(a_blocks, b_blocks): """Given two lists of blocks, combine them, in the proper order. Ensure that there are no overlaps, and that they are for s...
# Check sentinels for sequence length. assert a_blocks[-1][2] == b_blocks[-1][2] == 0 # sentinel size is 0 assert a_blocks[-1] == b_blocks[-1] combined_blocks = sorted(list(set(a_blocks + b_blocks))) # Check for overlaps. i = j = 0 for a, b, size in combined_blocks: assert i <= a ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
regex = re.compile(r'<!--.*?-->', re.DOTALL) return regex.sub('', xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_newlines(xml): r"""Remove newlines in the xml. If the newline separates words in text, then replace with a space instead. '<p>para one</p><p>para two<...
# Normalize newlines. xml = xml.replace('\r\n', '\n') xml = xml.replace('\r', '\n') # Remove newlines that don't separate text. The remaining ones do separate text. xml = re.sub(r'(?<=[>\s])\n(?=[<\s])', '', xml) xml = xml.replace('\n', ' ') return xml.strip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 te...
nodes_to_remove = [] for node in walk_dom(dom): if is_text(node): text = node.nodeValue if node.parentNode.tagName in _non_text_node_tags: nodes_to_remove.append(node) else: node.nodeValue = re.sub(r'\s+', ' ', text) for node in no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
node = dom.documentElement for i in location: node = get_child(node, i) if not node: raise ValueError('Node at location %s does not exist.' % location) #TODO: line not covered return node
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def full_split(text, regex): """ Split the text by the regex, keeping all parts. The parts should re-join back into the original text. ['word'] """
while text: m = regex.search(text) if not m: yield text break left = text[:m.start()] middle = text[m.start():m.end()] right = text[m.end():] if left: yield left if middle: yield middle text = right
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 returne...
def make_regex(s): return re.compile(s) if isinstance(s, basestring) else s regexes = [make_regex(r) for r in regexes] # Run the list of pieces through the regex split, splitting it into more # pieces. Once a piece has been matched, add it to finished_pieces and # don't split it again. The...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) elif action == 'insert': parent = get_location(self.dom, location[:-1]) child_ind...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.documentElement: break if ancestor.tagName == tag_name: unwrap(node) break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.parentNode.insertBefore(node, prev_sib) prev_sib = node.previousSibling
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 child in list(node.childNodes): prev_sib.appendChild(child) remove_node(node)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 a...
def get_openscm_replacement(in_region): world = "World" if in_region in ("WORLD", "GLOBAL"): return world if in_region in ("BUNKERS"): return DATA_HIERARCHY_SEPARATOR.join([world, "Bunkers"]) elif in_region.startswith(("NH", "SH")): in_region = i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_magicc_to_openscm_regions(regions, inverse=False): """ Convert MAGICC regions to OpenSCM regions Parameters regions : list_like, str Regions to conve...
if isinstance(regions, (list, pd.Index)): return [_apply_convert_magicc_to_openscm_regions(r, inverse) for r in regions] else: return _apply_convert_magicc_to_openscm_regions(regions, inverse)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_magicc7_to_openscm_variables(variables, inverse=False): """ Convert MAGICC7 variables to OpenSCM variables Parameters variables : list_like, str Vari...
if isinstance(variables, (list, pd.Index)): return [ _apply_convert_magicc7_to_openscm_variables(v, inverse) for v in variables ] else: return _apply_convert_magicc7_to_openscm_variables(variables, inverse)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
# we generate the mapping dynamically, the first name in the list # is the one which will be used for inverse mappings magicc6_simple_mapping_vars = [ "KYOTO-CO2EQ", "CO2I", "CO2B", "CH4", "N2O", "BC", "OC", "SOx", "NOx", "NMVO...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_magicc6_to_magicc7_variables(variables, inverse=False): """ Convert MAGICC6 variables to MAGICC7 variables Parameters variables : list_like, str Vari...
if isinstance(variables, (list, pd.Index)): return [ _apply_convert_magicc6_to_magicc7_variables(v, inverse) for v in variables ] else: return _apply_convert_magicc6_to_magicc7_variables(variables, inverse)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 "^" ...
replacements = {"^": "super", "/": "per", " ": ""} if inverse: replacements = {v: k for k, v in replacements.items()} # mapping nothing to something is obviously not going to work in the inverse # hence remove replacements.pop("") return replacements
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 inv...
if inverse: return apply_string_substitutions(units, FORTRAN_SAFE_TO_PINT_UNITS_MAPPING) else: return apply_string_substitutions(units, PINT_TO_FORTRAN_SAFE_UNITS_MAPPING)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(self._evaluation_context) self.eval_error = result is None if self.eval_error: return # Only set the value if it conforms to the field type ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, t...
dattype_flag = "THISFILE_DATTYPE" regionmode_flag = "THISFILE_REGIONMODE" region_dattype_row = _get_dattype_regionmode_regions_row(regions, scen7=scen7) dattype = DATTYPE_REGIONMODE_REGIONS[dattype_flag.lower()][region_dattype_row].iloc[ 0 ] regionmode = DATTYPE_REGIONMODE_REGIONS[regi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 T...
region_dattype_row = _get_dattype_regionmode_regions_row(regions, scen7=scen7) region_order = DATTYPE_REGIONMODE_REGIONS["regions"][region_dattype_row].iloc[0] return region_order
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 digi...
if sorted(set(PART_OF_SCENFILE_WITH_EMISSIONS_CODE_0)) == sorted(set(emissions)): scenfile_emissions_code = 0 elif sorted(set(PART_OF_SCENFILE_WITH_EMISSIONS_CODE_1)) == sorted(set(emissions)): scenfile_emissions_code = 1 else: msg = "Could not determine scen special code for emissi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 r...
single_cfg = Namelist({namelist_to_read: {}}) for key, value in parameters_out[namelist_to_read].items(): if "file_tuning" in key: single_cfg[namelist_to_read][key] = "" else: try: if isinstance(value, str): single_cfg[namelist_to_read...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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`` fi...
parameters_out = read_cfg_file(parameters_out_file) return pull_cfg_from_parameters_out( parameters_out, namelist_to_read=namelist_to_read )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
# TODO: move into OpenSCM mapping = { "rcp26": "rcp26", "rcp3pd": "rcp26", "rcp45": "rcp45", "rcp6": "rcp60", "rcp60": "rcp60", "rcp85": "rcp85", } try: return mapping[inname.lower()] except KeyError: error_msg = "No generic name for i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def join_timeseries(base, overwrite, join_linear=None): """Join two sets of timeseries Parameters base : :obj:`MAGICCData`, :obj:`pd.DataFrame`, filepath Base ti...
if join_linear is not None: if len(join_linear) != 2: raise ValueError("join_linear must have a length of 2") if isinstance(base, str): base = MAGICCData(base) elif isinstance(base, MAGICCData): base = deepcopy(base) if isinstance(overwrite, str): overwrite...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_scen_file( filepath, columns={ "model": ["unspecified"], "scenario": ["unspecified"], "climate_model": ["unspecified"], }, **kwargs ): """ Read a MAGICC...
mdata = MAGICCData(filepath, columns=columns, **kwargs) return mdata
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_openscm_var_from_filepath(filepath): """ Determine the OpenSCM variable from a filepath. Uses MAGICC's internal, implicit, filenaming conventions. Param...
reader = determine_tool(filepath, "reader")(filepath) openscm_var = convert_magicc7_to_openscm_variables( convert_magicc6_to_magicc7_variables(reader._get_variable_from_filepath()) ) return openscm_var
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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].strip().startswith("&"): nml_start = i if self.lines[i].strip().startswith("/"): nml_end = i assert ( nml_start is not None and nml_end ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_data(self, stream, metadata): """ Extract the tabulated data from the input file. Parameters stream : Streamlike object A Streamlike object (nominall...
ch, metadata = self._get_column_headers_and_update_metadata(stream, metadata) df = self._convert_data_block_and_headers_to_df(stream) return df, metadata, ch
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) except AttributeError: self._raise_cannot_determine_variable_from_filepath_error()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_header(self, header): """ Parse the header for additional metadata. Parameters header : str All the lines in the header. Returns ------- dict The met...
metadata = {} for line in header.split("\n"): line = line.strip() for tag in self.header_tags: tag_text = "{}:".format(tag) if line.lower().startswith(tag_text): metadata[tag] = line[len(tag_text) + 1 :].strip() return...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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:...
pos = stream.tell() expected_header = ( [expected_header] if isinstance(expected_header, str) else expected_header ) for exp_hd in expected_header: tokens = stream.readline().split() try: assert tokens[0] == exp_hd retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
size = self.data[self.pos : self.pos + 4].cast("i")[0] d = self.data[self.pos + 4 : self.pos + 4 + size] assert ( self.data[self.pos + 4 + size : self.pos + 4 + size + 4].cast("i")[0] == size ) self.pos = self.pos + 4 + size + 4 res = np.array(d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_data(self, stream, metadata): """ Extract the tabulated data from the input file # Arguments stream (Streamlike object): A Streamlike object (nomina...
index = np.arange(metadata["firstyear"], metadata["lastyear"] + 1) # The first variable is the global values globe = stream.read_chunk("d") assert len(globe) == len(index) regions = stream.read_chunk("d") num_regions = int(len(regions) / len(index)) regions = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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"), "lastyear": data.read_chunk("I"), "annualsteps": data.read_chunk("I"), } if metadata["annualsteps"] != 1: raise InvalidTemporalResError( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, magicc_input, filepath): """ Write a MAGICC input file from df and metadata Parameters magicc_input : :obj:`pymagicc.io.MAGICCData` MAGICCData ob...
self._filepath = filepath # TODO: make copy attribute for MAGICCData self.minput = deepcopy(magicc_input) self.data_block = self._get_data_block() output = StringIO() output = self._write_header(output) output = self._write_namelist(output) output = sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, other, inplace=False, **kwargs): """ Append any input which can be converted to MAGICCData to self. Parameters other : MAGICCData, pd.DataFrame,...
if not isinstance(other, MAGICCData): other = MAGICCData(other, **kwargs) if inplace: super().append(other, inplace=inplace) self.metadata.update(other.metadata) else: res = super().append(other, inplace=inplace) res.metadata = deepco...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 MAG...
writer = determine_tool(filepath, "writer")(magicc_version=magicc_version) writer.write(self, filepath)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_python_identifier_attributes(fully_qualified_name: str, spec: Dict[str, Any], *attributes: str) -> List[InvalidIdentifierError]: """ Validates a set ...
errors: List[InvalidIdentifierError] = [] checks: List[Tuple[Callable, InvalidIdentifierError.Reason]] = [ (lambda x: x.startswith('_'), InvalidIdentifierError.Reason.STARTS_WITH_UNDERSCORE), (lambda x: x.startswith('run_'), InvalidIdentifierError.Reason.STARTS_WITH_RUN), (lambda x: no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_required_attributes(fully_qualified_name: str, spec: Dict[str, Any], *attributes: str) -> List[RequiredAttributeError]: """ Validates to ensure that ...
return [ RequiredAttributeError(fully_qualified_name, spec, attribute) for attribute in attributes if attribute not in spec ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_empty_attributes(fully_qualified_name: str, spec: Dict[str, Any], *attributes: str) -> List[EmptyAttributeError]: """ Validates to ensure that a set ...
return [ EmptyAttributeError(fully_qualified_name, spec, attribute) for attribute in attributes if not spec.get(attribute, None) ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_number_attribute( fully_qualified_name: str, spec: Dict[str, Any], attribute: str, value_type: Union[Type[int], Type[float]] = int, minimum: Optional...
if attribute not in spec: return try: value = value_type(spec[attribute]) if (minimum is not None and value < minimum) or (maximum is not None and value > maximum): raise None except: return InvalidNumberError(fully_qualified_name, spec, attribute, value_type, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_enum_attribute(fully_qualified_name: str, spec: Dict[str, Any], attribute: str, candidates: Set[Union[str, int, float]]) -> Optional[InvalidValueErro...
if attribute not in spec: return if spec[attribute] not in candidates: return InvalidValueError(fully_qualified_name, spec, attribute, candidates)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
if (self.key_type, self.identity, self.group) != (other.key_type, other.identity, other.group): return False if self.key_type == KeyType.TIMESTAMP: return True if self.key_type == KeyType.DIMENSION: if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_field = self._build_time_fields_spec(self._spec[self.ATTRIBUTE_NAME]) self._spe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_string)) except Exception as err: self.add_errors( InvalidExpressionError(self.fully_qualified_name, self._spec, a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_number_attribute(self, attribute: str, value_type: Union[Type[int], Type[float]] = int, minimum: Optional[Union[int, float]] = None, maximum: Optiona...
self.add_errors( validate_number_attribute(self.fully_qualified_name, self._spec, attribute, value_type, minimum, maximum))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, candidates))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 SnapshotError('Error while creating snapshot for {}'.format(self._name)) from e
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.group].run_restore(snap) else: self._nested_items[name].run_restore(snap) return self except Exception as e: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_per_identity_records( self, identity: str, records: List[TimeAndRecord], old_state: Optional[Dict[Key, Any]] = None) -> Tuple[str, Tuple[Dict, List]]:...
schema_loader = SchemaLoader() if records: records.sort(key=lambda x: x[0]) else: records = [] block_data = self._execute_stream_bts(records, identity, schema_loader, old_state) window_data = self._execute_window_bts(identity, schema_loader) ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 += self.name if other is not None: result += ",%s]" % (other) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_property(self, key, value): """ Update only one property in the dict """
self.properties[key] = value self.sync_properties()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_header(self): """Reads header portion of packet"""
format = '!HHHHHH' length = struct.calcsize(format) info = struct.unpack(format, self.data[self.offset:self.offset + length]) self.offset += length self.id = info[0] self.flags = info[1] self.num_questions = info[2] self.num_answers = inf...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_questions(self): """Reads questions section of packet"""
format = '!HH' length = struct.calcsize(format) for i in range(0, self.num_questions): name = self.read_name() info = struct.unpack(format, self.data[self.offset:self.offset + length]) self.offset += length question = DNSQuest...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_int(self): """Reads an integer from the packet"""
format = '!I' length = struct.calcsize(format) info = struct.unpack(format, self.data[self.offset:self.offset + length]) self.offset += length return info[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_character_string(self): """Reads a character string from the packet"""
length = ord(self.data[self.offset]) self.offset += 1 return self.read_string(length)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_string(self, len): """Reads a string of a given length from the packet"""
format = '!' + str(len) + 's' length = struct.calcsize(format) info = struct.unpack(format, self.data[self.offset:self.offset + length]) self.offset += length return info[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_others(self): """Reads the answers, authorities and additionals section of the packet"""
format = '!HHiH' length = struct.calcsize(format) n = self.num_answers + self.num_authorities + self.num_additionals for i in range(0, n): domain = self.read_name() info = struct.unpack(format, self.data[self.offset:self.offset + length]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_utf(self, offset, len): """Reads a UTF-8 string of a given length from the packet"""
try: result = self.data[offset:offset + len].decode('utf-8') except UnicodeDecodeError: result = str('') return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_name(self): """Reads a domain name from the packet"""
result = '' off = self.offset next = -1 first = off while 1: len = ord(self.data[off]) off += 1 if len == 0: break t = len & 0xC0 if t == 0x00: result = ''.join((result, self.read_utf(of...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_answer(self, inp, record): """Adds an answer"""
if not record.suppressed_by(inp): self.add_answer_at_time(record, 0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_answer_at_time(self, record, now): """Adds an answer if if does not expire by a certain time"""
if record is not None: if now == 0 or not record.is_expired(now): self.answers.append((record, now)) if record.rrsig is not None: self.answers.append((record.rrsig, now))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_byte(self, value): """Writes a single byte to the packet"""
format = '!B' self.data.append(struct.pack(format, value)) self.size += 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert_short(self, index, value): """Inserts an unsigned short in a certain position in the packet"""
format = '!H' self.data.insert(index, struct.pack(format, value)) self.size += 2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_int(self, value): """Writes an unsigned integer to the packet"""
format = '!I' self.data.append(struct.pack(format, int(value))) self.size += 4
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_string(self, value, length): """Writes a string to the packet"""
format = '!' + str(length) + 's' self.data.append(struct.pack(format, value)) self.size += length
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_utf(self, s): """Writes a UTF-8 string of a given length to the packet"""
utfstr = s.encode('utf-8') length = len(utfstr) if length > 64: raise NamePartTooLongException self.write_byte(length) self.write_string(utfstr, length)