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 _load_version(cls, state, version): """ A function to load a previously saved SoundClassifier instance. """
from ._audio_feature_extractor import _get_feature_extractor from .._mxnet import _mxnet_utils state['_feature_extractor'] = _get_feature_extractor(state['feature_extractor_name']) # Load the custom nerual network num_classes = state['num_classes'] num_inputs = state['...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def classify(self, dataset, verbose=True, batch_size=64): """ Return the classification for each examples in the ``dataset``. The output SFrame contains predicte...
prob_vector = self.predict(dataset, output_type='probability_vector', verbose=verbose, batch_size=batch_size) id_to_label = self._id_to_class_label return _tc.SFrame({ 'class': prob_vector.apply(lambda v: id_to_label[_np.argmax(v)]), '...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_data(data, allow_empty, default_name): """Convert data into canonical form."""
assert (data is not None) or allow_empty if data is None: data = [] if isinstance(data, (np.ndarray, NDArray)): data = [data] if isinstance(data, list): if not allow_empty: assert(len(data) > 0) if len(data) == 1: data = OrderedDict([(default_nam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def provide_data(self): """The name and shape of data provided by this iterator"""
return [(k, tuple([self.batch_size] + list(v.shape[1:]))) for k, v in self.data]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def provide_label(self): """The name and shape of label provided by this iterator"""
return [(k, tuple([self.batch_size] + list(v.shape[1:]))) for k, v in self.label]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register (g): """ Registers new generator instance 'g'. """
assert isinstance(g, Generator) id = g.id() __generators [id] = g # A generator can produce several targets of the # same type. We want unique occurence of that generator # in .generators.$(t) in that case, otherwise, it will # be tried twice and we'll get false ambiguity. for t in se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def override (overrider_id, overridee_id): """Make generator 'overrider-id' be preferred to 'overridee-id'. If, when searching for generators that could produce ...
assert isinstance(overrider_id, basestring) assert isinstance(overridee_id, basestring) __overrides.setdefault(overrider_id, []).append(overridee_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __viable_source_types_real (target_type): """ Returns a list of source type which can possibly be converted to 'target_type' by some chain of generator invoc...
assert isinstance(target_type, basestring) generators = [] # 't0' is the initial list of target types we need to process to get a list # of their viable source target types. New target types will not be added to # this list. t0 = type.all_bases (target_type) # 't' is the list of target 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 viable_source_types_for_generator (generator): """ Caches the result of 'viable_source_types_for_generator'. """
assert isinstance(generator, Generator) if generator not in __viable_source_types_cache: __vstg_cached_generators.append(generator) __viable_source_types_cache[generator] = viable_source_types_for_generator_real (generator) return __viable_source_types_cache[generator]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def try_one_generator_really (project, name, generator, target_type, properties, sources): """ Returns usage requirements + list of created targets. """
if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or name is None assert isinstance(generator, Generator) assert isinstance(target_type, basestring) assert isinstance(properties, property_se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def try_one_generator (project, name, generator, target_type, properties, sources): """ Checks if generator invocation can be pruned, because it's guaranteed to ...
if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or name is None assert isinstance(generator, Generator) assert isinstance(target_type, basestring) assert isinstance(properties, property_se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __ensure_type (targets): """ Ensures all 'targets' have types. If this is not so, exists with error. """
assert is_iterable_typed(targets, virtual_target.VirtualTarget) for t in targets: if not t.type (): get_manager().errors()("target '%s' has no type" % str (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 __construct_really (project, name, target_type, prop_set, sources): """ Attempts to construct target by finding viable generators, running them and selecting...
if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or name is None assert isinstance(target_type, basestring) assert isinstance(prop_set, property_set.PropertySet) assert is_iterable_typed(so...
<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_rank (self, ps): """ Returns true if the generator can be run with the specified properties. """
# See if generator's requirements are satisfied by # 'properties'. Treat a feature name in requirements # (i.e. grist-only element), as matching any value of the # feature. assert isinstance(ps, property_set.PropertySet) all_requirements = self.requirements () ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def determine_output_name(self, sources): """Determine the name of the produced target from the names of the sources."""
assert is_iterable_typed(sources, virtual_target.VirtualTarget) # The simple case if when a name # of source has single dot. Then, we take the part before # dot. Several dots can be caused by: # - Using source file like a.host.cpp # - A type which suffix has a dot. Say,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generated_targets (self, sources, prop_set, project, name): """ Constructs targets that are created after consuming 'sources'. The result will be the list of...
if __debug__: from .targets import ProjectTarget assert is_iterable_typed(sources, virtual_target.VirtualTarget) assert isinstance(prop_set, property_set.PropertySet) assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or nam...
<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_multiple_sources_to_consumable_types (self, project, prop_set, sources): """ Converts several files to consumable types. """
if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(prop_set, property_set.PropertySet) assert is_iterable_typed(sources, virtual_target.VirtualTarget) if not self.source_types_: 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 element_sub_sketch(self, keys = None): """ Returns the sketch summary for the given set of keys. This is only applicable for sketch summary created from SArr...
single_val = False if keys is None: keys = [] else: if not isinstance(keys, list): single_val = True keys = [keys] value_types = set([type(i) for i in keys]) if (len(value_types) > 1): raise ValueErr...
<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_global_dbapi_info(dbapi_module, conn): """ Fetches all needed information from the top-level DBAPI module, guessing at the module if it wasn't passed as...
module_given_msg = "The DBAPI2 module given ({0}) is missing the global\n"+\ "variable '{1}'. Please make sure you are supplying a module that\n"+\ "conforms to the DBAPI 2.0 standard (PEP 0249)." module_not_given_msg = "Hello! I gave my best effort to find the\n"+\ "top-level module that the conne...
<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_csv_with_errors(cls, url, delimiter=',', header=True, comment_char='', escape_char='\\', double_quote=True, quote_char='\"', skip_initial_space=True, col...
return cls._read_csv_impl(url, delimiter=delimiter, header=header, error_bad_lines=False, # we are storing errors, # thus we must not fail ...
<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_json(cls, url, orient='records'): """ Reads a JSON file representing a table into an SFrame. Parameters url : string Location of the CSV file or directo...
if orient == "records": g = SArray.read_json(url) if len(g) == 0: return SFrame() g = SFrame({'X1':g}) return g.unpack('X1','') elif orient == "lines": g = cls.read_csv(url, header=False,na_values=['null'],true_values=['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 to_sql(self, conn, table_name, dbapi_module=None, use_python_type_specifiers=False, use_exact_column_names=True): """ Convert an SFrame to a single table in ...
mod_info = _get_global_dbapi_info(dbapi_module, conn) c = conn.cursor() col_info = list(zip(self.column_names(), self.column_types())) if not use_python_type_specifiers: _pytype_to_printf = lambda x: 's' # DBAPI2 standard allows for five different ways to specify ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_rows(self, num_rows=10, num_columns=40, max_column_width=30, max_row_width=80, output_file=None): """ Print the first M rows and N columns of the SFram...
if output_file is None: output_file = sys.stdout max_row_width = max(max_row_width, max_column_width + 1) printed_sf = self._imagecols_to_stringcols(num_rows) row_of_tables = printed_sf.__get_pretty_tables__(wrap_text=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 _row_selector(self, other): """ Where other is an SArray of identical length as the current Frame, this returns a selection of a subset of rows in the curren...
if type(other) is SArray: if self.__has_size__() and other.__has_size__() and len(other) != len(self): raise IndexError("Cannot perform logical indexing on arrays of different length.") with cython_context(): return SFrame(_proxy=self.__proxy__.logical_fi...
<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_dataframe(self): """ Convert this SFrame to pandas.DataFrame. This operation will construct a pandas.DataFrame in memory. Care must be taken when size of ...
assert HAS_PANDAS, 'pandas is not installed.' df = pandas.DataFrame() for i in range(self.num_columns()): column_name = self.column_names()[i] df[column_name] = list(self[column_name]) if len(df[column_name]) == 0: df[column_name] = df[column_...
<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_numpy(self): """ Converts this SFrame to a numpy array This operation will construct a numpy array in memory. Care must be taken when size of the returned...
assert HAS_NUMPY, 'numpy is not installed.' import numpy return numpy.transpose(numpy.asarray([self[x] for x in self.column_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 flat_map(self, column_names, fn, column_types='auto', seed=None): """ Map each row of the SFrame to multiple rows in a new SFrame via a function. will be a s...
assert callable(fn), "Input must be callable" if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) # determine the column_types if column_types == 'auto': types = set() sample = self[0:10] results = [fn(row) for row in 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 sample(self, fraction, seed=None, exact=False): """ Sample a fraction of the current SFrame's rows. Parameters fraction : float Fraction of the rows to fetch...
if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) if (fraction > 1 or fraction < 0): raise ValueError('Invalid sampling rate: ' + str(fraction)) if (self.num_rows() == 0 or self.num_columns() == 0): return self 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 save(self, filename, format=None): """ Save the SFrame to a file system for later use. Parameters filename : string The location to save the SFrame. Either a...
if format is None: if filename.endswith(('.csv', '.csv.gz')): format = 'csv' elif filename.endswith(('.json')): format = 'json' else: format = 'binary' else: if format is 'csv': if not filen...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export_csv(self, filename, delimiter=',', line_terminator='\n', header=True, quote_level=csv.QUOTE_NONNUMERIC, double_quote=True, escape_char='\\', quote_char...
# Pandas argument compatibility if "sep" in kwargs: delimiter = kwargs['sep'] del kwargs['sep'] if "quotechar" in kwargs: quote_char = kwargs['quotechar'] del kwargs['quotechar'] if "doublequote" in kwargs: double_quote = kwarg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export_json(self, filename, orient='records'): """ Writes an SFrame to a JSON file. Parameters filename : string The location to save the JSON file. orient :...
if orient == "records": self.pack_columns(dtype=dict).export_csv( filename, file_header='[', file_footer=']', header=False, double_quote=False, quote_level=csv.QUOTE_NONE, line_prefix=',', _no_prefix...
<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_reference(self, filename): """ Performs an incomplete save of an existing SFrame into a directory. This saved SFrame may reference SFrames in other loc...
## Save the SFrame url = _make_internal_url(filename) with cython_context(): self.__proxy__.save_reference(url)
<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_column(self, data, column_name="", inplace=False): """ Returns an SFrame with a new column. The number of elements in the data given must match the lengt...
# Check type for pandas dataframe or SArray? if not isinstance(data, SArray): if isinstance(data, _Iterable): data = SArray(data) else: if self.num_columns() == 0: data = SArray([data]) 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 add_columns(self, data, column_names=None, inplace=False): """ Returns an SFrame with multiple columns added. The number of elements in all columns must matc...
datalist = data if isinstance(data, SFrame): other = data datalist = [other.select_column(name) for name in other.column_names()] column_names = other.column_names() my_columns = set(self.column_names()) for name in column_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 remove_column(self, column_name, inplace=False): """ Returns an SFrame with a column removed. If inplace == False (default) this operation does not modify th...
column_name = str(column_name) if column_name not in self.column_names(): raise KeyError('Cannot find column %s' % column_name) colid = self.column_names().index(column_name) if inplace: ret = self else: ret = self.copy() with cython...
<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_columns(self, column_names, inplace=False): """ Returns an SFrame with one or more columns removed. If inplace == False (default) this operation does ...
column_names = list(column_names) existing_columns = dict((k, i) for i, k in enumerate(self.column_names())) for name in column_names: if name not in existing_columns: raise KeyError('Cannot find column %s' % name) # Delete it going backwards so we don't in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def swap_columns(self, column_name_1, column_name_2, inplace=False): """ Returns an SFrame with two column positions swapped. If inplace == False (default) this ...
colnames = self.column_names() colid_1 = colnames.index(column_name_1) colid_2 = colnames.index(column_name_2) if inplace: ret = self else: ret = self.copy() with cython_context(): ret.__proxy__.swap_columns(colid_1, colid_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 rename(self, names, inplace=False): """ Returns an SFrame with columns renamed. ``names`` is expected to be a dict specifying the old and new names. This cha...
if (type(names) is not dict): raise TypeError('names must be a dictionary: oldname -> newname') all_columns = set(self.column_names()) for k in names: if not k in all_columns: raise ValueError('Cannot find column %s in the SFrame' % k) if inplace...
<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): """ Add the rows of an SFrame to the end of this SFrame. Both SFrames must have the same set of columns with the same column names and c...
if type(other) is not SFrame: raise RuntimeError("SFrame append can only work with SFrame") left_empty = len(self.column_names()) == 0 right_empty = len(other.column_names()) == 0 if (left_empty and right_empty): return SFrame() if (left_empty or 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 explore(self, title=None): """ Explore the SFrame in an interactive GUI. Opens a new app window. Parameters title : str The plot title to show for the result...
import sys import os if sys.platform != 'darwin' and sys.platform != 'linux2' and sys.platform != 'linux': raise NotImplementedError('Visualization is currently supported only on macOS and Linux.') path_to_client = _get_client_app_path() if title is 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 split_datetime(self, column_name, column_name_prefix=None, limit=None, timezone=False): """ Splits a datetime column of SFrame to multiple columns, with each...
if column_name not in self.column_names(): raise KeyError("column '" + column_name + "' does not exist in current SFrame") if column_name_prefix is None: column_name_prefix = column_name new_sf = self[column_name].split_datetime(column_name_prefix, limit, timezone) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stack(self, column_name, new_column_name=None, drop_na=False, new_column_type=None): """ Convert a "wide" column of an SFrame to one or two "tall" columns by...
# validate column_name column_name = str(column_name) if column_name not in self.column_names(): raise ValueError("Cannot find column '" + str(column_name) + "' in the SFrame.") stack_column_type = self[column_name].dtype if (stack_column_type not in [dict, array.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 unstack(self, column_names, new_column_name=None): """ Concatenate values from one or two columns into one column, grouping by all other columns. The resulti...
if (type(column_names) != str and len(column_names) != 2): raise TypeError("'column_names' parameter has to be either a string or a list of two strings.") with cython_context(): if type(column_names) == str: key_columns = [i for i in self.column_names() if 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 sort(self, key_column_names, ascending=True): """ Sort current SFrame by the given columns, using the given sort order. Only columns that are type of str, in...
sort_column_names = [] sort_column_orders = [] # validate key_column_names if (type(key_column_names) == str): sort_column_names = [key_column_names] elif (type(key_column_names) == list): if (len(key_column_names) == 0): raise ValueError...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dropna(self, columns=None, how='any'): """ Remove missing values from an SFrame. A missing value is either ``None`` or ``NaN``. If ``how`` is 'any', a row wi...
# If the user gives me an empty list (the indicator to use all columns) # NA values being dropped would not be the expected behavior. This # is a NOOP, so let's not bother the server if type(columns) is list and len(columns) == 0: return SFrame(_proxy=self.__proxy__) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fillna(self, column_name, value): """ Fill all missing values with a given value in a given column. If the ``value`` is not the same type as the values in ``...
# Normal error checking if type(column_name) is not str: raise TypeError("column_name must be a str") ret = self[self.column_names()] ret[column_name] = ret[column_name].fillna(value) 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 add_row_number(self, column_name='id', start=0, inplace=False): """ Returns an SFrame with a new column that numbers each row sequentially. By default the co...
if type(column_name) is not str: raise TypeError("Must give column_name as strs") if type(start) is not int: raise TypeError("Must give start as int") if column_name in self.column_names(): raise RuntimeError("Column '" + column_name + "' already exists in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def AddSerializedFile(self, serialized_file_desc_proto): """Adds the FileDescriptorProto and its types to this pool. Args: serialized_file_desc_proto: A bytes st...
# pylint: disable=g-import-not-at-top from google.protobuf import descriptor_pb2 file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString( serialized_file_desc_proto) self.Add(file_desc_proto)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def AddDescriptor(self, desc): """Adds a Descriptor to the pool, non-recursively. If the Descriptor contains nested messages or enums, the caller must explicitly...
if not isinstance(desc, descriptor.Descriptor): raise TypeError('Expected instance of descriptor.Descriptor.') self._descriptors[desc.full_name] = desc self._AddFileDescriptor(desc.file)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def AddServiceDescriptor(self, service_desc): """Adds a ServiceDescriptor to the pool. Args: service_desc: A ServiceDescriptor. """
if not isinstance(service_desc, descriptor.ServiceDescriptor): raise TypeError('Expected instance of descriptor.ServiceDescriptor.') self._service_descriptors[service_desc.full_name] = service_desc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def AddExtensionDescriptor(self, extension): """Adds a FieldDescriptor describing an extension to the pool. Args: extension: A FieldDescriptor. Raises: Assertion...
if not (isinstance(extension, descriptor.FieldDescriptor) and extension.is_extension): raise TypeError('Expected an extension descriptor.') if extension.extension_scope is None: self._toplevel_extensions[extension.full_name] = extension try: existing_desc = self._extensions_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FindFileByName(self, file_name): """Gets a FileDescriptor by file name. Args: file_name: The path to the file to get a descriptor for. Returns: A FileDescrip...
try: return self._file_descriptors[file_name] except KeyError: pass try: file_proto = self._internal_db.FindFileByName(file_name) except KeyError as error: if self._descriptor_db: file_proto = self._descriptor_db.FindFileByName(file_name) else: raise erro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FindFileContainingSymbol(self, symbol): """Gets the FileDescriptor for the file containing the specified symbol. Args: symbol: The name of the symbol to sear...
symbol = _NormalizeFullyQualifiedName(symbol) try: return self._descriptors[symbol].file except KeyError: pass try: return self._enum_descriptors[symbol].file except KeyError: pass try: return self._FindFileContainingSymbolInDb(symbol) except KeyError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FindMessageTypeByName(self, full_name): """Loads the named descriptor from the pool. Args: full_name: The full name of the descriptor to load. Returns: The d...
full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._descriptors: self._FindFileContainingSymbolInDb(full_name) return self._descriptors[full_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 FindEnumTypeByName(self, full_name): """Loads the named enum descriptor from the pool. Args: full_name: The full name of the enum descriptor to load. Returns...
full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._enum_descriptors: self._FindFileContainingSymbolInDb(full_name) return self._enum_descriptors[full_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 FindFieldByName(self, full_name): """Loads the named field descriptor from the pool. Args: full_name: The full name of the field descriptor to load. Returns:...
full_name = _NormalizeFullyQualifiedName(full_name) message_name, _, field_name = full_name.rpartition('.') message_descriptor = self.FindMessageTypeByName(message_name) return message_descriptor.fields_by_name[field_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 FindServiceByName(self, full_name): """Loads the named service descriptor from the pool. Args: full_name: The full name of the service descriptor to load. Re...
full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._service_descriptors: self._FindFileContainingSymbolInDb(full_name) return self._service_descriptors[full_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 _FindFileContainingSymbolInDb(self, symbol): """Finds the file in descriptor DB containing the specified symbol. Args: symbol: The name of the symbol to sear...
try: file_proto = self._internal_db.FindFileContainingSymbol(symbol) except KeyError as error: if self._descriptor_db: file_proto = self._descriptor_db.FindFileContainingSymbol(symbol) else: raise error if not file_proto: raise KeyError('Cannot find a file containing...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ConvertFileProtoToFileDescriptor(self, file_proto): """Creates a FileDescriptor from a proto or returns a cached copy. This method also has the side effect ...
if file_proto.name not in self._file_descriptors: built_deps = list(self._GetDeps(file_proto.dependency)) direct_deps = [self.FindFileByName(n) for n in file_proto.dependency] public_deps = [direct_deps[i] for i in file_proto.public_dependency] file_descriptor = descriptor.FileDescriptor(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None, scope=None, syntax=None): """Adds the proto to the pool in the specified package. A...
if package: desc_name = '.'.join((package, desc_proto.name)) else: desc_name = desc_proto.name if file_desc is None: file_name = None else: file_name = file_desc.name if scope is None: scope = {} nested = [ self._ConvertMessageDescriptor( ne...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _SetAllFieldTypes(self, package, desc_proto, scope): """Sets all the descriptor's fields's types. This method also sets the containing types on any extension...
package = _PrefixWithDot(package) main_desc = self._GetTypeFromScope(package, desc_proto.name, scope) if package == '.': nested_package = _PrefixWithDot(desc_proto.name) else: nested_package = '.'.join([package, desc_proto.name]) for field_proto, field_desc in zip(desc_proto.field, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _SetFieldType(self, field_proto, field_desc, package, scope): """Sets the field's type, cpp_type, message_type and enum_type. Args: field_proto: Data about t...
if field_proto.type_name: desc = self._GetTypeFromScope(package, field_proto.type_name, scope) else: desc = None if not field_proto.HasField('type'): if isinstance(desc, descriptor.Descriptor): field_proto.type = descriptor.FieldDescriptor.TYPE_MESSAGE else: field_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 _MakeEnumValueDescriptor(self, value_proto, index): """Creates a enum value descriptor object from a enum value proto. Args: value_proto: The proto describin...
return descriptor.EnumValueDescriptor( name=value_proto.name, index=index, number=value_proto.number, options=_OptionsOrNone(value_proto), type=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 _MakeServiceDescriptor(self, service_proto, service_index, scope, package, file_desc): """Make a protobuf ServiceDescriptor given a ServiceDescriptorProto. A...
if package: service_name = '.'.join((package, service_proto.name)) else: service_name = service_proto.name methods = [self._MakeMethodDescriptor(method_proto, service_name, package, scope, index) for index, method_proto in enumerate(ser...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _MakeMethodDescriptor(self, method_proto, service_name, package, scope, index): """Creates a method descriptor from a MethodDescriptorProto. Args: method_pro...
full_name = '.'.join((service_name, method_proto.name)) input_type = self._GetTypeFromScope( package, method_proto.input_type, scope) output_type = self._GetTypeFromScope( package, method_proto.output_type, scope) return descriptor.MethodDescriptor(name=method_proto.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 _ExtractSymbols(self, descriptors): """Pulls out all the symbols from descriptor protos. Args: descriptors: The messages to extract descriptors from. Yields:...
for desc in descriptors: yield (_PrefixWithDot(desc.full_name), desc) for symbol in self._ExtractSymbols(desc.nested_types): yield symbol for enum in desc.enum_types: yield (_PrefixWithDot(enum.full_name), enum)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _GetDeps(self, dependencies): """Recursively finds dependencies for file protos. Args: dependencies: The names of the files being depended on. Yields: Each d...
for dependency in dependencies: dep_desc = self.FindFileByName(dependency) yield dep_desc for parent_dep in dep_desc.dependencies: yield parent_dep
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _GetTypeFromScope(self, package, type_name, scope): """Finds a given type name in the current scope. Args: package: The package the proto should be located i...
if type_name not in scope: components = _PrefixWithDot(package).split('.') while components: possible_match = '.'.join(components + [type_name]) if possible_match in scope: type_name = possible_match break else: components.pop(-1) return scope[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 max_element (elements, ordered = None): """ Returns the maximum number in 'elements'. Uses 'ordered' for comparisons, or '<' is none is provided. """
assert is_iterable(elements) assert callable(ordered) or ordered is None if not ordered: ordered = operator.lt max = elements [0] for e in elements [1:]: if ordered (max, e): max = e return max
<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_highest_ranked (elements, ranks): """ Returns all of 'elements' for which corresponding element in parallel list 'rank' is equal to the maximum value ...
assert is_iterable(elements) assert is_iterable(ranks) if not elements: return [] max_rank = max_element (ranks) result = [] while elements: if ranks [0] == max_rank: result.append (elements [0]) elements = elements [1:] ranks = ranks [1:] 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 CopyFrom(self, other_msg): """Copies the content of the specified message into the current message. The method clears the current message and then merges the...
if self is other_msg: return self.Clear() self.MergeFrom(other_msg)
<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_tree_ensemble(model, feature_names, target, force_32bit_float): """Convert a generic tree model to the protobuf spec. This currently supports: * Deci...
if not(_HAS_XGBOOST): raise RuntimeError('xgboost not found. xgboost conversion API is disabled.') import json import os feature_map = None if isinstance(model, (_xgboost.core.Booster, _xgboost.XGBRegressor)): # Testing a few corner cases that we don't support if isinstan...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_dimension(model, input_dimension): """ Given a model that takes an array of dimension input_dimension, returns the output dimension. """
if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') _sklearn_util.check_fitted(model, lambda m: hasattr(m, 'active_features_')) _sklearn_util.check_fitted(model, lambda m: hasattr(m, 'n_values_')) if model.categorical_features == 'all':...
<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_elementwise_mul_scalar(net, node, module, builder): """Convert a scalar multiplication from mxnet to coreml. Parameters net: network A mxnet network ...
import numpy input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) mult = literal_eval(param['scalar']) builder.add_scale(name=name, W=numpy.array([mult]), b=0, has_bias=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 convert_dense(net, node, module, builder): """Convert a dense layer from mxnet to coreml. Parameters net: network A mxnet network object. node: layer Node to...
input_name, output_name = _get_input_output_name(net, node) has_bias = True name = node['name'] inputs = node['inputs'] args, _ = module.get_params() W = args[_get_node_name(net, inputs[1][0])].asnumpy() if has_bias: Wb = args[_get_node_name(net, inputs[2][0])].asnumpy() 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 convert_padding(net, node, module, builder): """Convert a padding layer from mxnet to coreml. Parameters net: network A mxnet network object. node: layer Nod...
input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) pad = literal_eval(param['pad_width']) pad_left = pad[4] pad_top = pad[5] pad_right = pad[6] pad_bottom = pad[7] if param['mode'] == 'reflect': builder.add_padding( ...
<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_upsample(net, node, module, builder): """Convert a UpSampling layer from mxnet to coreml. Parameters net: network A mxnet network object. node: layer...
input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) inputs = node['inputs'] args, _ = module.get_params() scale = literal_eval(param['scale']) #method if 'sample_type' in param.keys(): method = param['sample_type'] 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_custom(net, node, module, builder): """Convert highly specific ops"""
input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) if param['op_type'] == 'special-darknet-maxpool': _add_pooling.add_pooling_with_padding_types( builder=builder, name=name, height=2, width=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 convert_embedding(net, node, model, builder): """Convert an embedding layer from mxnet to coreml. Parameters net: network A mxnet network object. node: layer...
input_name, output_name = _get_input_output_name(net, node) name = node['name'] inputs = node['inputs'] outputs = node['outputs'] arg_params, aux_params = model.get_params() W = arg_params[_get_node_name(net, inputs[1][0])].asnumpy() if not ONE_HOT_ENCODE_HACK: nC, nB = W.shape ...
<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_scalar_add(net, node, model, builder): """Convert a scalar add layer from mxnet to coreml. Parameters net: network A mxnet network object. node: laye...
import numpy as _np input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) mode = 'ADD' alpha = _np.array([float(param['scalar'])]) builder.add_scale(name = name, input_name = input_name, output_name = output_name, W = _np.array([...
<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_scalar_multiply(net, node, model, builder): """Convert a scalar multiply layer from mxnet to coreml. Parameters net: network A mxnet network object. ...
import numpy as _np input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) alpha = _np.array([float(param['scalar'])]) builder.add_scale(name = name, input_name = input_name, output_name = output_name, W = alpha, has_bias=False, b=Non...
<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_instancenorm(net, node, model, builder): """Convert an instance norm layer from mxnet to coreml. Parameters net: network A mxnet network object. node...
import numpy as _np input_name, output_name = _get_input_output_name(net, node) name = node['name'] inputs = node['inputs'] outputs = node['outputs'] data_blob_name = _get_node_name(net, inputs[0][0]) gamma_blob_name = _get_node_name(net, inputs[1][0]) beta_blob_name = _get_node_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 _get_aws_credentials(): """ Returns the values stored in the AWS credential environment variables. Returns the value stored in the AWS_ACCESS_KEY_ID environm...
if (not 'AWS_ACCESS_KEY_ID' in _os.environ): raise KeyError('No access key found. Please set the environment variable AWS_ACCESS_KEY_ID.') if (not 'AWS_SECRET_ACCESS_KEY' in _os.environ): raise KeyError('No secret key found. Please set the environment variable AWS_SECRET_ACCESS_KEY.') 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 is_directory_archive(path): """ Utility function that returns True if the path provided is a directory that has an SFrame or SGraph in it. SFrames are writte...
if path is None: return False if not _os.path.isdir(path): return False ini_path = '/'.join([_convert_slashes(path), 'dir_archive.ini']) if not _os.path.exists(ini_path): return False if _os.path.isfile(ini_path): 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 get_archive_type(path): """ Returns the contents type for the provided archive path. Parameters path : string Directory to evaluate. Returns ------- Returns ...
if not is_directory_archive(path): raise TypeError('Unable to determine the type of archive at path: %s' % path) try: ini_path = '/'.join([_convert_slashes(path), 'dir_archive.ini']) parser = _ConfigParser.SafeConfigParser() parser.read(ini_path) contents = parser.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 crossproduct(d): """ Create an SFrame containing the crossproduct of all provided options. Parameters d : dict Each key is the name of an option, and each va...
from .. import SArray d = [list(zip(list(d.keys()), x)) for x in _itertools.product(*list(d.values()))] sa = [{k:v for (k,v) in x} for x in d] return SArray(sa).unpack(column_name_prefix='')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _assert_sframe_equal(sf1, sf2, check_column_names=True, check_column_order=True, check_row_order=True, float_column_delta=None): """ Assert the two SFrames a...
from .. import SFrame as _SFrame if (type(sf1) is not _SFrame) or (type(sf2) is not _SFrame): raise TypeError("Cannot function on types other than SFrames.") if not check_column_order and not check_column_names: raise ValueError("Cannot ignore both column order and column names.") sf1...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _make_temp_directory(prefix): ''' Generate a temporary directory that would not live beyond the lifetime of unity_server. Caller is expected to clean up the temp file as soon as the directory is no longer needed. But the directory will be cleaned as unity_server restarts ''' temp_dir = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _make_temp_filename(prefix): ''' Generate a temporary file that would not live beyond the lifetime of unity_server. Caller is expected to clean up the temp file as soon as the file is no longer needed. But temp files created using this method will be cleaned up when unity_server restarts ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ParameterDecorator(naming_type, testcases): """Implementation of the parameterization decorators. Args: naming_type: The naming type. testcases: Testcase pa...
def _Apply(obj): if isinstance(obj, type): _ModifyClass( obj, list(testcases) if not isinstance(testcases, collections.Sequence) else testcases, naming_type) return obj else: return _ParameterizedTestIter(obj, testcases, naming_type) if _IsSingleto...
<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_header_comment(filename): """Checks if the header-comment of the given file needs fixing."""
# Check input file. name = os.path.basename( filename ) # Read content of input file. sourcefile = open( filename, "rU" ) content = sourcefile.read() sourcefile.close() # Search content for '$Id$'. match = re.search(r'\$Id\$', content) if match == None: # Make sure that 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 check_input_files_for_variadic_seq(headerDir, sourceDir): """Checks if files, used as input when pre-processing MPL-containers in their variadic form, need f...
# Check input files in include/source-directories. files = glob.glob( os.path.join( headerDir, "*.hpp" ) ) files += glob.glob( os.path.join( headerDir, "aux_", "*.hpp" ) ) files += glob.glob( os.path.join( sourceDir, "src", "*" ) ) for currentFile in sorted( files ): if check_header_commen...
<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_input_files_for_numbered_seq(sourceDir, suffix, containers): """Check if files, used as input when pre-processing MPL-containers in their numbered form...
# Check input files for each MPL-container type. for container in containers: files = glob.glob( os.path.join( sourceDir, container, container + '*' + suffix ) ) for currentFile in sorted( files ): if check_header_comment( currentFile ): 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 check_input_files(headerDir, sourceDir, containers=['vector', 'list', 'set', 'map'], seqType='both', verbose=False): """Checks if source- and header-files, u...
# Check the input files for containers in their variadic form. result1 = False if seqType == "both" or seqType == "variadic": if verbose: print "Check if input files for pre-processing Boost.MPL variadic containers need fixing." result1 = check_input_files_for_variadic_seq(heade...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_header_comment(filename, timestamp): """Fixes the header-comment of the given file."""
# Fix input file. name = os.path.basename( filename ) for line in fileinput.input( filename, inplace=1, mode="rU" ): # If header-comment already contains anything for '$Id$', remove it. line = re.sub(r'\$Id:[^$]+\$', r'$Id$', line.rstrip()) # Replace '$Id$' by a string containing 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 fix_input_files_for_variadic_seq(headerDir, sourceDir, timestamp): """Fixes files used as input when pre-processing MPL-containers in their variadic form."""
# Fix files in include/source-directories. files = glob.glob( os.path.join( headerDir, "*.hpp" ) ) files += glob.glob( os.path.join( headerDir, "aux_", "*.hpp" ) ) files += glob.glob( os.path.join( sourceDir, "src", "*" ) ) for currentFile in sorted( files ): fix_header_comment( currentFil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_input_files_for_numbered_seq(sourceDir, suffix, timestamp, containers): """Fixes files used as input when pre-processing MPL-containers in their numbered...
# Fix input files for each MPL-container type. for container in containers: files = glob.glob( os.path.join( sourceDir, container, container + '*' + suffix ) ) for currentFile in sorted( files ): fix_header_comment( currentFile, timestamp )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_input_files(headerDir, sourceDir, containers=['vector', 'list', 'set', 'map'], seqType='both', verbose=False): """Fixes source- and header-files used as ...
# The new modification time. timestamp = datetime.datetime.now(); # Fix the input files for containers in their variadic form. if seqType == "both" or seqType == "variadic": if verbose: print "Fix input files for pre-processing Boost.MPL variadic containers." fix_input_files...
<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_existing_absolute_path(string): """Converts a path into its absolute path and verifies that it exists or throws an exception."""
value = os.path.abspath(string) if not os.path.exists( value ) or not os.path.isdir( value ): msg = '"%r" is not a valid path to a directory.' % string raise argparse.ArgumentTypeError(msg) return 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 query(self, dataset, label=None, k=5, radius=None, verbose=True, batch_size=64): """ For each image, retrieve the nearest neighbors from the model's stored d...
if not isinstance(dataset, (_tc.SFrame, _tc.SArray, _tc.Image)): raise TypeError('dataset must be either an SFrame, SArray or turicreate.Image') if(batch_size < 1): raise ValueError("'batch_size' must be greater than or equal to 1") if isinstance(dataset, _tc.SArray): ...