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 predict(self, data, useCPUOnly=False, **kwargs):
""" Return predictions for the model. The kwargs gets passed into the model as a dictionary. Parameters data... |
if self.__proxy__:
return self.__proxy__.predict(data,useCPUOnly)
else:
if _macos_version() < (10, 13):
raise Exception('Model prediction is only supported on macOS version 10.13 or later.')
try:
from ..libcoremlpython import _MLMode... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visualize_spec(self, port=None, input_shape_dict=None):
""" Visualize the model. Parameters port : int if server is to be hosted on specific localhost port i... |
spec = self._spec
model_type = spec.WhichOneof('Type')
model_description = spec.description
input_spec = model_description.input
output_spec = model_description.output
spec_inputs = []
for model_input in input_spec:
spec_inputs.append((model_input.n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _construct_auto_distance(feature_names, column_names, column_types, sample):
""" Construct composite distance parameters based on selected features and their... |
## Make a dictionary from the column_names and column_types
col_type_dict = {k: v for k, v in zip(column_names, column_types)}
## Loop through feature names, appending a distance component if the
# feature's type is *not* numeric. If the type *is* numeric, append it to
# the numeric_cols list, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _list_fields(self):
""" List the fields stored in the model, including data, model, and training options. Each field can be queried with the ``get`` method. ... |
opts = {'model': self.__proxy__, 'model_name': self.__name__}
response = _turicreate.extensions._nearest_neighbors.list_fields(opts)
return sorted(response.keys()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query(self, dataset, label=None, k=5, radius=None, verbose=True):
""" For each row of the input 'dataset', retrieve the nearest neighbors from the model's st... |
## Validate the 'dataset' input
_tkutl._raise_error_if_not_sframe(dataset, "dataset")
_tkutl._raise_error_if_sframe_empty(dataset, "dataset")
## Get model features
ref_features = self.features
sf_features = _tkutl._toolkits_select_columns(dataset, ref_features)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def similarity_graph(self, k=5, radius=None, include_self_edges=False, output_type='SGraph', verbose=True):
""" Construct the similarity graph on the reference d... |
## Validate inputs.
if k is not None:
if not isinstance(k, int):
raise ValueError("Input 'k' must be an integer.")
if k <= 0:
raise ValueError("Input 'k' must be larger than 0.")
if radius is not None:
if not isinstance(radiu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def random_split_by_session(dataset, session_id, fraction=0.9, seed=None):
""" Randomly split an SFrame into two SFrames based on the `session_id` such that one ... |
from random import Random
_raise_error_if_not_of_type(dataset, _SFrame, 'dataset')
_raise_error_if_not_of_type(session_id, str, 'session_id')
_raise_error_if_not_of_type(fraction, float, 'fraction')
_raise_error_if_not_of_type(seed, [int, type(None)], 'seed')
_numeric_param_check_range('fracti... |
<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_msbuild_xml(path, values={}):
"""Reads the MS Build XML file at the path and returns its contents. Keyword arguments: values -- The map to append the co... |
# Attempt to read the file contents
try:
document = parse(path)
except Exception as e:
logging.exception('Could not read MS Build XML file at %s', path)
return values
# Convert the XML to JSON format
logging.info('Processing MS Build XML file at %s', path)
# Get the r... |
<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_msbuild_json(path, values=[]):
"""Reads the MS Build JSON file at the path and returns its contents. Keyword arguments: values -- The list to append the... |
if not os.path.exists(path):
logging.info('Could not find MS Build JSON file at %s', path)
return values
try:
values.extend(__read_json_file(path))
except Exception as e:
logging.exception('Could not read MS Build JSON file at %s', path)
return values
logging.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 main():
"""Script entrypoint.""" |
# Parse the arguments
parser = argparse.ArgumentParser(
description='Convert MSBuild XML to JSON format')
parser.add_argument(
'-t', '--toolchain', help='The name of the toolchain', required=True)
parser.add_argument(
'-o', '--output', help='The output directory', default='')
... |
<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_json_values(current, previous):
"""Merges the values between the current and previous run of the script.""" |
for value in current:
name = value['name']
# Find the previous value
previous_value = __find_and_remove_value(previous, value)
if previous_value is not None:
flags = value['flags']
previous_flags = previous_value['flags']
if flags != previous_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 __find_and_remove_value(list, compare):
"""Finds the value in the list that corresponds with the value of compare.""" |
# next throws if there are no matches
try:
found = next(value for value in list
if value['name'] == compare['name'] and value['switch'] ==
compare['switch'])
except:
return None
list.remove(found)
return found |
<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(root, tag, values, func):
"""Converts the tag type found in the root and converts them using the func and appends them to the values. """ |
elements = root.getElementsByTagName(tag)
for element in elements:
converted = func(element)
# Append to the list
__append_list(values, converted) |
<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_enum(node):
"""Converts an EnumProperty node to JSON format.""" |
name = __get_attribute(node, 'Name')
logging.debug('Found EnumProperty named %s', name)
converted_values = []
for value in node.getElementsByTagName('EnumValue'):
converted = __convert_node(value)
converted['value'] = converted['name']
converted['name'] = name
# Modi... |
<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_bool(node):
"""Converts an BoolProperty node to JSON format.""" |
converted = __convert_node(node, default_value='true')
# Check for a switch for reversing the value
reverse_switch = __get_attribute(node, 'ReverseSwitch')
if reverse_switch:
converted_reverse = copy.deepcopy(converted)
converted_reverse['switch'] = reverse_switch
converted_r... |
<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_string_list(node):
"""Converts a StringListProperty node to JSON format.""" |
converted = __convert_node(node)
# Determine flags for the string list
flags = vsflags(VSFlags.UserValue)
# Check for a separator to determine if it is semicolon appendable
# If not present assume the value should be ;
separator = __get_attribute(node, 'Separator', default_value=';')
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 __convert_string(node):
"""Converts a StringProperty node to JSON format.""" |
converted = __convert_node(node, default_flags=vsflags(VSFlags.UserValue))
return __check_for_flag(converted) |
<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_node(node, default_value='', default_flags=vsflags()):
"""Converts a XML node to a JSON equivalent.""" |
name = __get_attribute(node, 'Name')
logging.debug('Found %s named %s', node.tagName, name)
converted = {}
converted['name'] = name
converted['switch'] = __get_attribute(node, 'Switch')
converted['comment'] = __get_attribute(node, 'DisplayName')
converted['value'] = default_value
# 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 __with_argument(node, value):
"""Modifies the flags in value if the node contains an Argument.""" |
arguments = node.getElementsByTagName('Argument')
if arguments:
logging.debug('Found argument within %s', value['name'])
value['flags'] = vsflags(VSFlags.UserValueIgnored, VSFlags.Continue) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __preprocess_arguments(root):
"""Preprocesses occurrences of Argument within the root. Argument XML values reference other values within the document by name... |
# Set the flags to require a value
flags = ','.join(vsflags(VSFlags.UserValueRequired))
# Search through the arguments
arguments = root.getElementsByTagName('Argument')
for argument in arguments:
reference = __get_attribute(argument, 'Property')
found = None
# Look for th... |
<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_attribute(node, name, default_value=''):
"""Retrieves the attribute of the given name from the node. If not present then the default_value is used. """ |
if node.hasAttribute(name):
return node.attributes[name].value.strip()
else:
return default_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 __get_path(path):
"""Gets the path to the file.""" |
if not os.path.isabs(path):
path = os.path.join(os.getcwd(), path)
return os.path.normpath(path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __output_path(toolchain, rule, output_dir):
"""Gets the output path for a file given the toolchain, rule and output_dir""" |
filename = '%s_%s.json' % (toolchain, rule)
return os.path.join(output_dir, filename) |
<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_json_file(path, values):
"""Writes a JSON file at the path with the values provided.""" |
# Sort the keys to ensure ordering
sort_order = ['name', 'switch', 'comment', 'value', 'flags']
sorted_values = [
OrderedDict(
sorted(
value.items(), key=lambda value: sort_order.index(value[0])))
for value in values
]
with open(path, 'w') as 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 __append_list(append_to, value):
"""Appends the value to the list.""" |
if value is not None:
if isinstance(value, list):
append_to.extend(value)
else:
append_to.append(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 ParseInput(self, a_file):
"""Consumes input extracting definitions. Args: a_file: The file like stream to parse. Raises: PDDMError if there are any issues. "... |
input_lines = a_file.read().splitlines()
self.ParseLines(input_lines) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ParseLines(self, input_lines):
"""Parses list of lines. Args: input_lines: A list of strings of input to parse (no newlines on the strings). Raises: PDDMErro... |
current_macro = None
for line in input_lines:
if line.startswith('PDDM-'):
directive = line.split(' ', 1)[0]
if directive == 'PDDM-DEFINE':
name, args = self._ParseDefineLine(line)
if self._macros.get(name):
raise PDDMError('Attempt to redefine macro: "%s"'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Expand(self, macro_ref_str):
"""Expands the macro reference. Args: macro_ref_str: String of a macro reference (i.e. foo(a, b)). Returns: The text from the ex... |
match = _MACRO_RE.match(macro_ref_str)
if match is None or match.group(0) != macro_ref_str:
raise PDDMError('Failed to parse macro reference: "%s"' % macro_ref_str)
if match.group('name') not in self._macros:
raise PDDMError('No macro named "%s".' % match.group('name'))
return self._Expand(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ProcessContent(self, strip_expansion=False):
"""Processes the file contents.""" |
self._ParseFile()
if strip_expansion:
# Without a collection the expansions become blank, removing them.
collection = None
else:
collection = MacroCollection()
for section in self._sections:
section.BindMacroCollection(collection)
result = ''
for section in self._section... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def defaults(features):
""" Returns the default property values for the given features. """ |
assert is_iterable_typed(features, Feature)
# FIXME: should merge feature and property modules.
from . import property
result = []
for f in features:
if not f.free and not f.optional and f.default:
result.append(property.Property(f, f.default))
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 valid (names):
""" Returns true iff all elements of names are valid features. """ |
if isinstance(names, str):
names = [names]
assert is_iterable_typed(names, basestring)
return all(name in __all_features for name in names) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def values (feature):
""" Return the values of the given feature. """ |
assert isinstance(feature, basestring)
validate_feature (feature)
return __all_features[feature].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 is_implicit_value (value_string):
""" Returns true iff 'value_string' is a value_string of an implicit feature. """ |
assert isinstance(value_string, basestring)
if value_string in __implicit_features:
return __implicit_features[value_string]
v = value_string.split('-')
if v[0] not in __implicit_features:
return False
feature = __implicit_features[v[0]]
for subvalue in (v[1:]):
if n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def implied_feature (implicit_value):
""" Returns the implicit feature associated with the given implicit value. """ |
assert isinstance(implicit_value, basestring)
components = implicit_value.split('-')
if components[0] not in __implicit_features:
raise InvalidValue ("'%s' is not a value of an implicit feature" % implicit_value)
return __implicit_features[components[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 validate_feature (name):
""" Checks if all name is a valid feature. Otherwise, raises an exception. """ |
assert isinstance(name, basestring)
if name not in __all_features:
raise InvalidFeature ("'%s' is not a valid feature name" % name)
else:
return __all_features[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 expand_subfeatures(properties, dont_validate = False):
""" Make all elements of properties corresponding to implicit features explicit, and express all subfe... |
if __debug__:
from .property import Property
assert is_iterable_typed(properties, Property)
assert isinstance(dont_validate, int) # matches bools
result = []
for p in properties:
# Don't expand subfeatures in subfeatures
if p.feature.subfeature:
result.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 extend (name, values):
""" Adds the given values to the given feature. """ |
assert isinstance(name, basestring)
assert is_iterable_typed(values, basestring)
name = add_grist (name)
__validate_feature (name)
feature = __all_features [name]
if feature.implicit:
for v in values:
if v in __implicit_features:
raise BaseException ("'%s' 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 validate_value_string (f, value_string):
""" Checks that value-string is a valid value-string for the given feature. """ |
assert isinstance(f, Feature)
assert isinstance(value_string, basestring)
if f.free or value_string in f.values:
return
values = [value_string]
if f.subfeatures:
if not value_string in f.values and \
not value_string in f.subfeatures:
values = value_stri... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compose (composite_property_s, component_properties_s):
""" Sets the components of the given composite property. All parameters are <feature>value strings ""... |
from . import property
component_properties_s = to_seq (component_properties_s)
composite_property = property.create_from_string(composite_property_s)
f = composite_property.feature
if len(component_properties_s) > 0 and isinstance(component_properties_s[0], property.Property):
component_... |
<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_values (feature, properties):
""" Returns all values of the given feature specified by the given property set. """ |
if feature[0] != '<':
feature = '<' + feature + '>'
result = []
for p in properties:
if get_grist (p) == feature:
result.append (replace_grist (p, ''))
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 expand_composites (properties):
""" Expand all composite properties in the set so that all components are explicitly expressed. """ |
if __debug__:
from .property import Property
assert is_iterable_typed(properties, Property)
explicit_features = set(p.feature for p in properties)
result = []
# now expand composite features
for p in properties:
expanded = expand_composite(p)
for x in expanded:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_subfeature_of (parent_property, f):
""" Return true iff f is an ordinary subfeature of the parent_property's feature, or if f is a subfeature of the paren... |
if __debug__:
from .property import Property
assert isinstance(parent_property, Property)
assert isinstance(f, Feature)
if not f.subfeature:
return False
p = f.parent
if not p:
return False
parent_feature = p[0]
parent_value = p[1]
if parent_featu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __is_subproperty_of (parent_property, p):
""" As is_subfeature_of, for subproperties. """ |
if __debug__:
from .property import Property
assert isinstance(parent_property, Property)
assert isinstance(p, Property)
return is_subfeature_of (parent_property, p.feature) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expand (properties):
""" Given a property set which may consist of composite and implicit properties and combined subfeature values, returns an expanded, nor... |
if __debug__:
from .property import Property
assert is_iterable_typed(properties, Property)
expanded = expand_subfeatures(properties)
return expand_composites (expanded) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compress_subproperties (properties):
""" Combine all subproperties into their parent properties Requires: for every subproperty, there is a parent property. ... |
from .property import Property
assert is_iterable_typed(properties, Property)
result = []
matched_subs = set()
all_subs = set()
for p in properties:
f = p.feature
if not f.subfeature:
subs = [x for x in properties if is_subfeature_of(p, x.feature)]
if su... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __select_subfeatures (parent_property, features):
""" Given a property, return the subset of features consisting of all ordinary subfeatures of the property'... |
if __debug__:
from .property import Property
assert isinstance(parent_property, Property)
assert is_iterable_typed(features, Feature)
return [f for f in features if is_subfeature_of (parent_property, 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 _get_interpretation_function(interpretation, dtype):
""" Retrieves the interpretation function used. """ |
type_string = dtype.__name__
name = "%s__%s" % (interpretation, type_string)
global _interpretations
if not hasattr(_interpretations, name):
raise ValueError("No transform available for type '%s' with interpretation '%s'."
% (type_string, interpretation))
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 _get_interpretation_description_and_output_type(interpretation, dtype):
""" Returns the description and output type for a given interpretation. """ |
type_string = dtype.__name__
name = "%s__%s" % (interpretation, type_string)
if not hasattr(_interpretations_class, name):
raise ValueError("No transform available for type '%s' with interpretation '%s'."
% (type_string, interpretation))
# Need unbound method to get ... |
<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_embeddable_interpretation_doc(indent = 0):
""" Returns a list of the available interpretations and what they do. If indent is specified, then the entire... |
output_rows = []
# Pull out the doc string and put it in a table.
for name in sorted(dir(_interpretations)):
if name.startswith("_") or "__" not in name:
continue
interpretation, type_str = name.split("__")
func = getattr(_interpretations, name)
output_rows.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_version(cls, unpickler, version):
""" A function to load a previously saved SentenceSplitter instance. Parameters unpickler : GLUnpickler A GLUnpickler... |
state, _exclude, _features = unpickler.load()
features = state['features']
excluded_features = state['excluded_features']
model = cls.__new__(cls)
model._setup()
model.__proxy__.update(state)
model._exclude = _exclude
model._features = _features
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit(self, data):
""" Fits the transformer using the given data. """ |
_raise_error_if_not_sframe(data, "data")
fitted_state = {}
feature_columns = _internal_utils.get_column_names(data, self._exclude, self._features)
if not feature_columns:
raise RuntimeError("No valid feature columns specified in transformation.")
fitted_state['fe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform(self, data):
""" Transforms the data. """ |
if not self._get("fitted"):
raise RuntimeError("`transform` called before `fit` or `fit_transform`.")
data = data.copy()
output_column_prefix = self._get("output_column_prefix")
if output_column_prefix is None:
prefix = ""
else:
prefix = ou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def short_text__str(self, column_name, output_column_prefix):
""" Transforms short text into a dictionary of TFIDF-weighted 3-gram character counts. """ |
from ._ngram_counter import NGramCounter
from ._tfidf import TFIDF
return [NGramCounter(features=[column_name],
n = 3,
method = "character",
output_column_prefix = output_column_prefix),
T... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def categorical__int(self, column_name, output_column_prefix):
""" Interprets an integer column as a categorical variable. """ |
return [_ColumnFunctionTransformation(
features = [column_name],
output_column_prefix = output_column_prefix,
transform_function = lambda col: col.astype(str),
transform_function_name = "astype(str)")] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _setup_from_data(self, data):
""" Sets up the content transforms. """ |
fitted_state = {}
_raise_error_if_not_of_type(data, [_SFrame])
feature_columns = _internal_utils.get_column_names(data, self._exclude, self._features)
if not feature_columns:
raise RuntimeError("No valid feature columns specified in transformation.")
fitted_stat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit_transform(self, data):
""" Fits and transforms the SFrame `data` using a fitted model. Parameters data : SFrame The data to be transformed. Returns -----... |
self._setup_from_data(data)
ret = self.transform_chain.fit_transform(data)
self.__proxy__.update({"fitted" : True})
return 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 CreateMock(self, class_to_mock):
"""Create a new mock object. Args: # class_to_mock: the class to be mocked class_to_mock: class Returns: MockObject that can... |
new_mock = MockObject(class_to_mock)
self._mock_objects.append(new_mock)
return new_mock |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def StubOutWithMock(self, obj, attr_name, use_mock_anything=False):
"""Replace a method, attribute, etc. with a Mock. This will replace a class or module with a ... |
attr_to_replace = getattr(obj, attr_name)
if type(attr_to_replace) in self._USE_MOCK_OBJECT and not use_mock_anything:
stub = self.CreateMock(attr_to_replace)
else:
stub = self.CreateMockAnything()
self.stubs.Set(obj, attr_name, stub) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _Verify(self):
"""Verify that all of the expected calls have been made. Raises: ExpectedMethodCallsError: if there are still more method calls in the expecte... |
# If the list of expected calls is not empty, raise an exception
if self._expected_calls_queue:
# The last MultipleTimesGroup is not popped from the queue.
if (len(self._expected_calls_queue) == 1 and
isinstance(self._expected_calls_queue[0], MultipleTimesGroup) and
self._expec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _VerifyMethodCall(self):
"""Verify the called method is expected. This can be an ordered method, or part of an unordered set. Returns: The expected mock meth... |
expected = self._PopNextMethod()
# Loop here, because we might have a MethodGroup followed by another
# group.
while isinstance(expected, MethodGroup):
expected, method = expected.MethodCalled(self)
if method is not None:
return method
# This is a mock method, so just check 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 GetPossibleGroup(self):
"""Returns a possible group from the end of the call queue or None if no other methods are on the stack. """ |
# Remove this method from the tail of the queue so we can add it to a group.
this_method = self._call_queue.pop()
assert this_method == self
# Determine if the tail of the queue is a group, or just a regular ordered
# mock method.
group = None
try:
group = self._call_queue[-1]
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 equals(self, rhs):
"""Check to see if the RHS is an instance of class_name. Args: # rhs: the right hand side of the test rhs: object Returns: bool """ |
try:
return isinstance(rhs, self._class_name)
except TypeError:
# Check raw types if there was a type error. This is helpful for
# things like cStringIO.StringIO.
return type(rhs) == type(self._class_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 equals(self, rhs):
"""Check to see if RHS is almost equal to float_value Args: rhs: the value to compare to float_value Returns: bool """ |
try:
return round(rhs-self._float_value, self._places) == 0
except TypeError:
# This is probably because either float_value or rhs is not a number.
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 equals(self, actual_seq):
"""Check to see whether actual_seq has same elements as expected_seq. Args: actual_seq: sequence Returns: bool """ |
try:
expected = dict([(element, None) for element in self._expected_seq])
actual = dict([(element, None) for element in actual_seq])
except TypeError:
# Fall back to slower list-compare if any of the objects are unhashable.
expected = list(self._expected_seq)
actual = list(actual... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def equals(self, rhs):
"""Checks whether any Comparator is equal to rhs. Args: # rhs: can be anything Returns: bool """ |
for comparator in self._comparators:
if comparator.equals(rhs):
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 IsSatisfied(self):
"""Return True if all methods in this group are called at least once.""" |
# NOTE(psycho): We can't use the simple set difference here because we want
# to match different parameters which are considered the same e.g. IsA(str)
# and some string. This solution is O(n^2) but n should be small.
tmp = self._methods.copy()
for called in self._methods_called:
for expected... |
<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_classifier_interface_params(spec, features, class_labels, model_accessor_for_class_labels, output_features = None):
""" Common utilities to set the regre... |
# Normalize the features list.
features = _fm.process_or_validate_features(features)
if class_labels is None:
raise ValueError("List of class labels must be provided.")
n_classes = len(class_labels)
output_features = _fm.process_or_validate_classifier_output_features(output_features, cla... |
<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_regressor_interface_params(spec, features, output_features):
""" Common utilities to set the regressor interface params. """ |
if output_features is None:
output_features = [("predicted_class", datatypes.Double())]
else:
output_features = _fm.process_or_validate_features(output_features, 1)
if len(output_features) != 1:
raise ValueError("Provided output features for a regressor must be "
... |
<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_transform_interface_params(spec, input_features, output_features, are_optional = False):
""" Common utilities to set transform interface params. """ |
input_features = _fm.process_or_validate_features(input_features)
output_features = _fm.process_or_validate_features(output_features)
# Add input and output features
for (fname, ftype) in input_features:
input_ = spec.description.input.add()
input_.name = fname
datatypes._set_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 _load_into_numpy(sf, np_array, start, end, strides=None, shape=None):
"""Loads into numpy array from SFrame, assuming SFrame stores data flattened""" |
np_array[:] = 0.0
np_array_2d = np_array.reshape((np_array.shape[0], np_array.shape[1] * np_array.shape[2]))
_extensions.sframe_load_to_numpy(sf, np_array.ctypes.data,
np_array_2d.strides, np_array_2d.shape,
start, 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 set_input(self, input_names, input_dims):
""" Set the inputs of the network spec. Parameters input_names: [str] List of input names of the network. input_dim... |
spec = self.spec
nn_spec = self.nn_spec
for idx, dim in enumerate(input_dims):
if len(dim) == 3:
input_shape = (dim[0], dim[1], dim[2])
elif len(dim) == 2:
input_shape = (dim[1], )
elif len(dim) == 1:
input_shap... |
<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_output(self, output_names, output_dims):
""" Set the outputs of the network spec. Parameters output_names: [str] List of output names of the network. out... |
spec = self.spec
nn_spec = self.nn_spec
for idx, dim in enumerate(output_dims):
spec.description.output[idx].type.multiArrayType.ClearField("shape")
spec.description.output[idx].type.multiArrayType.shape.extend(dim)
spec.description.output[idx].type.multiArra... |
<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_class_labels(self, class_labels, predicted_feature_name = 'classLabel', prediction_blob = ''):
""" Set class labels to the model spec to make it a neural... |
spec = self.spec
nn_spec = self.nn_spec
if len(spec.description.output) == 0:
raise ValueError(
"Model should have at least one output (the probabilities) to automatically make it a classifier.")
probOutput = spec.description.output[0]
probOutput.typ... |
<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_optionals(self, optionals_in, optionals_out):
""" Add optional inputs and outputs to the model spec. Parameters optionals_in: [str] List of inputs that a... |
spec = self.spec
if (not optionals_in) and (not optionals_out):
return
# assuming single sizes here
input_types = [datatypes.Array(dim) for (name, dim) in optionals_in]
output_types = [datatypes.Array(dim) for (name, dim) in optionals_out]
input_names = [st... |
<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_embedding(self, name, W, b, input_dim, output_channels, has_bias, input_name, output_name):
""" Add an embedding layer to the model. Parameters name: str... |
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
# Fill in the parameters
spec_layer_params = spec_layer... |
<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_softmax(self, name, input_name, output_name):
""" Add a softmax layer to the model. Parameters name: str The name of this layer. input_name: str The inpu... |
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.softmax.MergeFromString(b'') |
<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_activation(self, name, non_linearity, input_name, output_name, params=None):
""" Add an activation layer to the model. Parameters name: str The name of t... |
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.activation
# Fill in 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 add_elementwise(self, name, input_names, output_name, mode, alpha = None):
""" Add an element-wise operation layer to the model. Parameters The name of this ... |
spec = self.spec
nn_spec = self.nn_spec
spec_layer = nn_spec.layers.add()
spec_layer.name = name
if isinstance(input_names, list):
for input_name in input_names:
spec_layer.input.append(input_name)
else:
spec_layer.input.append(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 add_upsample(self, name, scaling_factor_h, scaling_factor_w, input_name, output_name, mode = 'NN'):
""" Add upsample layer to the model. Parameters name: str... |
spec = self.spec
nn_spec = self.nn_spec
# Add a new inner-product layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.upsample
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 add_scale(self, name, W, b, has_bias, input_name, output_name, shape_scale = [1], shape_bias = [1]):
""" Add scale layer to the model. Parameters name: str T... |
spec = self.spec
nn_spec = self.nn_spec
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.scale
spec_layer_params.hasBias = has_bias
... |
<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_bias(self, name, b, input_name, output_name, shape_bias = [1]):
""" Add bias layer to the model. Parameters name: str The name of this layer. b: int | nu... |
spec = self.spec
nn_spec = self.nn_spec
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.bias
#add bias and its shape
bias = spec_la... |
<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_sequence_repeat(self, name, nrep, input_name, output_name):
""" Add sequence repeat layer to the model. Parameters name: str The name of this layer. nrep... |
spec = self.spec
nn_spec = self.nn_spec
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.sequenceRepeat
spec_layer_params.nRepetitions = nrep |
<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_padding(self, name, left = 0, right = 0, top = 0, bottom = 0, value = 0, input_name = 'data', output_name = 'out', padding_type = 'constant'):
""" Add a ... |
# Currently only constant padding is supported.
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
spec_laye... |
<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_simple_rnn(self,name, W_h, W_x, b, hidden_size, input_size, activation, input_names, output_names, output_all = False, reverse_input = False):
""" Add a ... |
spec = self.spec
nn_spec = self.nn_spec
# Add a new Layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
for name in input_names:
spec_layer.input.append(name)
for name in output_names:
spec_layer.output.append(name)
sp... |
<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_flatten(self, name, mode, input_name, output_name):
""" Add a flatten layer. Only flattens the channel, height and width axis. Leaves the sequence axis a... |
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.flatten
# Set the paramet... |
<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_reorganize_data(self, name, input_name, output_name, mode = 'SPACE_TO_DEPTH', block_size = 2):
""" Add a data reorganization layer of type "SPACE_TO_DEPT... |
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.reorganizeData
# Set 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 add_reshape(self, name, input_name, output_name, target_shape, mode):
""" Add a reshape layer. Kindly refer to NeuralNetwork.proto for details. Parameters na... |
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.reshape
spec_layer_param... |
<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_l2_normalize(self, name, input_name, output_name, epsilon = 1e-5):
""" Add L2 normalize layer. Normalizes the input by the L2 norm, i.e. divides by the t... |
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.l2normalize
spec_layer_p... |
<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_split(self, name, input_name, output_names):
""" Add a Split layer that uniformly splits the input along the channel dimension to produce multiple output... |
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.extend(output_names)
spec_layer_params = spec_layer.split
spec_layer_params... |
<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_load_constant(self, name, output_name, constant_value, shape):
""" Add a load constant layer. Parameters name: str The name of this layer. output_name: s... |
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.loadConstant
data = spec_layer_params.data
data.floatValue.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 add_custom(self, name, input_names, output_names, custom_proto_spec = None):
""" Add a custom layer. Parameters name: str The name of this layer. input_names... |
spec = self.spec
nn_spec = self.nn_spec
# custom layers require a newer specification version
from coremltools import _MINIMUM_CUSTOM_LAYER_SPEC_VERSION
spec.specificationVersion = max(spec.specificationVersion, _MINIMUM_CUSTOM_LAYER_SPEC_VERSION)
spec_layer = nn_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 set_pre_processing_parameters(self, image_input_names = [], is_bgr = False, red_bias = 0.0, green_bias = 0.0, blue_bias = 0.0, gray_bias = 0.0, image_scale = ... |
spec = self.spec
if not image_input_names:
return # nothing to do here
if not isinstance(is_bgr, dict): is_bgr = dict.fromkeys(image_input_names, is_bgr)
if not isinstance(red_bias, dict): red_bias = dict.fromkeys(image_input_names, red_bias)
if not isinstance(blue... |
<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(scanner_class, properties):
""" Returns an instance of previously registered scanner with the specified properties. """ |
assert issubclass(scanner_class, Scanner)
assert is_iterable_typed(properties, basestring)
scanner_name = str(scanner_class)
if not registered(scanner_name):
raise BaseException ("attempt to get unregisted scanner: %s" % scanner_name)
relevant_properties = __scanners[scanner_name]
r =... |
<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_subimports(self, code, top_level_dependencies):
""" Ensure de-pickler imports any package child-modules that are needed by the function """ |
# check if any known dependency is an imported package
for x in top_level_dependencies:
if isinstance(x, types.ModuleType) and hasattr(x, '__package__') and x.__package__:
# check if the package has any currently loaded sub-imports
prefix = x.__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 extract_code_globals(cls, co):
""" Find all globals names read or written to by codeblock co """ |
out_names = cls._extract_code_globals_cache.get(co)
if out_names is None:
try:
names = co.co_names
except AttributeError:
# PyPy "builtin-code" object
out_names = set()
else:
out_names = set(names[oparg]... |
<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_file(self, obj):
"""Save a file""" |
try:
import StringIO as pystringIO #we can't use cStringIO as it lacks the name attribute
except ImportError:
import io as pystringIO
if not hasattr(obj, 'name') or not hasattr(obj, 'mode'):
raise pickle.PicklingError("Cannot pickle files that do not map to... |
<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_ufunc(self, obj):
"""Hack function for saving numpy ufunc objects""" |
name = obj.__name__
numpy_tst_mods = ['numpy', 'scipy.special']
for tst_mod_name in numpy_tst_mods:
tst_mod = sys.modules.get(tst_mod_name, None)
if tst_mod and name in tst_mod.__dict__:
return self.save_reduce(_getobject, (tst_mod_name, name))
ra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ExtractSymbols(desc_proto, package):
"""Pulls out all the symbols from a descriptor proto. Args: desc_proto: The proto to extract symbols from. package: The... |
message_name = '.'.join((package, desc_proto.name))
yield message_name
for nested_type in desc_proto.nested_type:
for symbol in _ExtractSymbols(nested_type, message_name):
yield symbol
for enum_type in desc_proto.enum_type:
yield '.'.join((message_name, enum_type.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 Add(self, file_desc_proto):
"""Adds the FileDescriptorProto and its types to this database. Args: file_desc_proto: The FileDescriptorProto to add. Raises: De... |
proto_name = file_desc_proto.name
if proto_name not in self._file_desc_protos_by_file:
self._file_desc_protos_by_file[proto_name] = file_desc_proto
elif self._file_desc_protos_by_file[proto_name] != file_desc_proto:
raise DescriptorDatabaseConflictingDefinitionError(
'%s already added... |
<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(model, input_features, output_features):
"""Convert a normalizer model to the protobuf spec. Parameters model: Normalizer A Normalizer. input_feature... |
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
# Test the scikit-learn model
_sklearn_util.check_expected_type(model, Normalizer)
_sklearn_util.check_fitted(model, lambda m: hasattr(m, 'norm'))
# Set the interface params.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.