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 consume(self): ''' Consume byte-code ''' generic_consume = getattr(self, 'generic_consume', None) for instr in disassembler(self.code): method_name = 'consume_%s' % (instr.opname) method = getattr(self, method_name, generic_consume) ...
<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_lib_path(): """Load find the path to xgboost dynamic library files. Returns ------- lib_path: list(string) List of all found library path to xgboost """
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) # make pythonpack hack: copy this directory one level upper for setup.py dll_path = [curr_path, os.path.join(curr_path, '../../wrapper/'), os.path.join(curr_path, './wrapper/')] if os.name == 'nt': if pla...
<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_expected_type(model, expected_type): """Check if a model is of the right type. Raise error if not. Parameters model: model Any scikit-learn model expec...
if (model.__class__.__name__ != expected_type.__name__): raise TypeError("Expected model of type '%s' (got %s)" % \ (expected_type.__name__, model.__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 convert(model, input_names='input', target_name='target', probability='classProbability', input_length='auto'): """ Convert a LIBSVM model to Core ML format....
if not(_HAS_LIBSVM): raise RuntimeError('libsvm not found. libsvm conversion API is disabled.') if isinstance(model, _string_types): libsvm_model = _libsvm_util.load_model(model) else: libsvm_model = model if not isinstance(libsvm_model, _libsvm.svm_model): raise TypeEr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def MergeFrom(self, other): """Appends the contents of another repeated field of the same type to this one. We do not check the types of the individual fields. "...
self._values.extend(other._values) self._message_listener.Modified()
<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, **kwargs): """Adds a new element at the end of the list and returns it. Keyword arguments may be used to initialize the element. """
new_element = self._message_descriptor._concrete_class(**kwargs) new_element._SetListener(self._message_listener) self._values.append(new_element) if not self._message_listener.dirty: self._message_listener.Modified() return new_element
<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(self, elem_seq): """Extends by appending the given sequence of elements of the same type as this one, copying each individual message. """
message_class = self._message_descriptor._concrete_class listener = self._message_listener values = self._values for message in elem_seq: new_element = message_class() new_element._SetListener(listener) new_element.MergeFrom(message) values.append(new_element) listener.Modif...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def difference (b, a): """ Returns the elements of B that are not in A. """
a = set(a) result = [] for item in b: if item not in a: result.append(item) 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 intersection (set1, set2): """ Removes from set1 any items which don't appear in set2 and returns the result. """
assert is_iterable(set1) assert is_iterable(set2) result = [] for v in set1: if v in set2: result.append (v) 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 contains (small, large): """ Returns true iff all elements of 'small' exist in 'large'. """
small = to_seq (small) large = to_seq (large) for s in small: if not s in large: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def annotate(data, image_column=None, annotation_column='annotations'): """ Annotate your images loaded in either an SFrame or SArray Format The annotate util is...
# Check Value of Column Variables if image_column == None: image_column = _tkutl._find_only_image_column(data) if image_column == None: raise ValueError("'image_column' cannot be 'None'") if type(image_column) != str: raise TypeError("'image_column' has to be of type '...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert(model, input_features, output_features): """Convert a DictVectorizer model to the protobuf spec. Parameters model: DictVectorizer A fitted DictVector...
if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') # Set the interface params. spec = _Model_pb2.Model() spec.specificationVersion = SPECIFICATION_VERSION assert len(input_features) == 1 assert isinstance(input_features[0][1], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_callback(val): """ Internal function. This function is called via a call back returning from IPC to Cython to Python. It tries to perform incremental p...
success = False try: # for reasons I cannot fathom, regular printing, even directly # to io.stdout does not work. # I have to intrude rather deep into IPython to make it behave if have_ipython: if InteractiveShell.initialized(): IPython.display.publis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(toolkit_name, options, verbose=True, show_progress=False): """ Internal function to execute toolkit on the turicreate server. Parameters toolkit_name : s...
unity = glconnect.get_unity() if (not verbose): glconnect.get_server().set_log_progress(False) (success, message, params) = unity.run_toolkit(toolkit_name, options) if (len(message) > 0): logging.getLogger(__name__).error("Toolkit error: " + message) # set the verbose level back ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _RoundTowardZero(value, divider): """Truncates the remainder part after division."""
# For some languanges, the sign of the remainder is implementation # dependent if any of the operands is negative. Here we enforce # "rounded toward zero" semantics. For example, for (-5) / 2 an # implementation may give -3 as the result with the remainder being # 1. This function ensures we always return -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 _IsValidPath(message_descriptor, path): """Checks whether the path is valid for Message Descriptor."""
parts = path.split('.') last = parts.pop() for name in parts: field = message_descriptor.fields_by_name[name] if (field is None or field.label == FieldDescriptor.LABEL_REPEATED or field.type != FieldDescriptor.TYPE_MESSAGE): return False message_descriptor = field.message_type ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _CheckFieldMaskMessage(message): """Raises ValueError if message is not a FieldMask."""
message_descriptor = message.DESCRIPTOR if (message_descriptor.name != 'FieldMask' or message_descriptor.file.name != 'google/protobuf/field_mask.proto'): raise ValueError('Message {0} is not a FieldMask.'.format( message_descriptor.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 _SnakeCaseToCamelCase(path_name): """Converts a path name from snake_case to camelCase."""
result = [] after_underscore = False for c in path_name: if c.isupper(): raise Error('Fail to print FieldMask to Json string: Path name ' '{0} must not contain uppercase letters.'.format(path_name)) if after_underscore: if c.islower(): result.append(c.upper()) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _CamelCaseToSnakeCase(path_name): """Converts a field name from camelCase to snake_case."""
result = [] for c in path_name: if c == '_': raise ParseError('Fail to parse FieldMask: Path name ' '{0} must not contain "_"s.'.format(path_name)) if c.isupper(): result += '_' result += c.lower() else: result += c return ''.join(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 _MergeMessage( node, source, destination, replace_message, replace_repeated): """Merge all fields specified by a sub-tree from source to destination."""
source_descriptor = source.DESCRIPTOR for name in node: child = node[name] field = source_descriptor.fields_by_name[name] if field is None: raise ValueError('Error: Can\'t find field {0} in message {1}.'.format( name, source_descriptor.full_name)) if child: # Sub-paths are onl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _AddFieldPaths(node, prefix, field_mask): """Adds the field paths descended from node to field_mask."""
if not node: field_mask.paths.append(prefix) return for name in sorted(node): if prefix: child_path = prefix + '.' + name else: child_path = name _AddFieldPaths(node[name], child_path, field_mask)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Pack(self, msg, type_url_prefix='type.googleapis.com/'): """Packs the specified message into current Any message."""
if len(type_url_prefix) < 1 or type_url_prefix[-1] != '/': self.type_url = '%s/%s' % (type_url_prefix, msg.DESCRIPTOR.full_name) else: self.type_url = '%s%s' % (type_url_prefix, msg.DESCRIPTOR.full_name) self.value = msg.SerializeToString()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Unpack(self, msg): """Unpacks the current Any message into specified message."""
descriptor = msg.DESCRIPTOR if not self.Is(descriptor): return False msg.ParseFromString(self.value) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ToJsonString(self): """Converts Timestamp to RFC 3339 date string format. Returns: A string converted from timestamp. The string is always Z-normalized and u...
nanos = self.nanos % _NANOS_PER_SECOND total_sec = self.seconds + (self.nanos - nanos) // _NANOS_PER_SECOND seconds = total_sec % _SECONDS_PER_DAY days = (total_sec - seconds) // _SECONDS_PER_DAY dt = datetime(1970, 1, 1) + timedelta(days, seconds) result = dt.isoformat() if (nanos % 1e9) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FromJsonString(self, value): """Parse a RFC 3339 date string format to Timestamp. Args: value: A date string. Any fractional digits (or none) and any offset ...
timezone_offset = value.find('Z') if timezone_offset == -1: timezone_offset = value.find('+') if timezone_offset == -1: timezone_offset = value.rfind('-') if timezone_offset == -1: raise ParseError( 'Failed to parse timestamp: missing valid timezone offset.') time_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 FromNanoseconds(self, nanos): """Converts nanoseconds since epoch to Timestamp."""
self.seconds = nanos // _NANOS_PER_SECOND self.nanos = nanos % _NANOS_PER_SECOND
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FromMicroseconds(self, micros): """Converts microseconds since epoch to Timestamp."""
self.seconds = micros // _MICROS_PER_SECOND self.nanos = (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FromMilliseconds(self, millis): """Converts milliseconds since epoch to Timestamp."""
self.seconds = millis // _MILLIS_PER_SECOND self.nanos = (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ToDatetime(self): """Converts Timestamp to datetime."""
return datetime.utcfromtimestamp( self.seconds + self.nanos / float(_NANOS_PER_SECOND))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FromDatetime(self, dt): """Converts datetime to Timestamp."""
td = dt - datetime(1970, 1, 1) self.seconds = td.seconds + td.days * _SECONDS_PER_DAY self.nanos = td.microseconds * _NANOS_PER_MICROSECOND
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ToMicroseconds(self): """Converts a Duration to microseconds."""
micros = _RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND) return self.seconds * _MICROS_PER_SECOND + micros
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ToMilliseconds(self): """Converts a Duration to milliseconds."""
millis = _RoundTowardZero(self.nanos, _NANOS_PER_MILLISECOND) return self.seconds * _MILLIS_PER_SECOND + millis
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FromMicroseconds(self, micros): """Converts microseconds to Duration."""
self._NormalizeDuration( micros // _MICROS_PER_SECOND, (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FromMilliseconds(self, millis): """Converts milliseconds to Duration."""
self._NormalizeDuration( millis // _MILLIS_PER_SECOND, (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ToTimedelta(self): """Converts Duration to timedelta."""
return timedelta( seconds=self.seconds, microseconds=_RoundTowardZero( self.nanos, _NANOS_PER_MICROSECOND))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FromTimedelta(self, td): """Convertd timedelta to Duration."""
self._NormalizeDuration(td.seconds + td.days * _SECONDS_PER_DAY, td.microseconds * _NANOS_PER_MICROSECOND)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _NormalizeDuration(self, seconds, nanos): """Set Duration by seconds and nonas."""
# Force nanos to be negative if the duration is negative. if seconds < 0 and nanos > 0: seconds += 1 nanos -= _NANOS_PER_SECOND self.seconds = seconds self.nanos = nanos
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ToJsonString(self): """Converts FieldMask to string according to proto3 JSON spec."""
camelcase_paths = [] for path in self.paths: camelcase_paths.append(_SnakeCaseToCamelCase(path)) return ','.join(camelcase_paths)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def IsValidForDescriptor(self, message_descriptor): """Checks whether the FieldMask is valid for Message Descriptor."""
for path in self.paths: if not _IsValidPath(message_descriptor, path): return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def AllFieldsFromDescriptor(self, message_descriptor): """Gets all direct fields of Message Descriptor to FieldMask."""
self.Clear() for field in message_descriptor.fields: self.paths.append(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 Union(self, mask1, mask2): """Merges mask1 and mask2 into this FieldMask."""
_CheckFieldMaskMessage(mask1) _CheckFieldMaskMessage(mask2) tree = _FieldMaskTree(mask1) tree.MergeFromFieldMask(mask2) tree.ToFieldMask(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Intersect(self, mask1, mask2): """Intersects mask1 and mask2 into this FieldMask."""
_CheckFieldMaskMessage(mask1) _CheckFieldMaskMessage(mask2) tree = _FieldMaskTree(mask1) intersection = _FieldMaskTree() for path in mask2.paths: tree.IntersectPath(path, intersection) intersection.ToFieldMask(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def MergeMessage( self, source, destination, replace_message_field=False, replace_repeated_field=False): """Merges fields specified in FieldMask from source to d...
tree = _FieldMaskTree(self) tree.MergeMessage( source, destination, replace_message_field, replace_repeated_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 AddPath(self, path): """Adds a field path into the tree. If the field path to add is a sub-path of an existing field path in the tree (i.e., a leaf node), it...
node = self._root for name in path.split('.'): if name not in node: node[name] = {} elif not node[name]: # Pre-existing empty node implies we already have this entire tree. return node = node[name] # Remove any sub-trees we might have had. node.clear()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def IntersectPath(self, path, intersection): """Calculates the intersection part of a field path with this tree. Args: path: The field path to calculates. inters...
node = self._root for name in path.split('.'): if name not in node: return elif not node[name]: intersection.AddPath(path) return node = node[name] intersection.AddLeafNodes(path, node)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def AddLeafNodes(self, prefix, node): """Adds leaf nodes begin with prefix to this tree."""
if not node: self.AddPath(prefix) for name in node: child_path = prefix + '.' + name self.AddLeafNodes(child_path, 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 MergeMessage( self, source, destination, replace_message, replace_repeated): """Merge all fields specified by this tree from source to destination."""
_MergeMessage( self._root, source, destination, replace_message, replace_repeated)
<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, dataset, missing_value_action='auto'): """ Return target value predictions for ``dataset``, using the trained linear regression model. This met...
return super(LinearRegression, self).predict(dataset, missing_value_action=missing_value_action)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate(self, dataset, metric='auto', missing_value_action='auto'): r"""Evaluate the model by making target value predictions and comparing to actual values...
_raise_error_evaluation_metric_is_valid(metric, ['auto', 'rmse', 'max_error']) return super(LinearRegression, self).evaluate(dataset, missing_value_action=missing_value_action, metric=metric)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def frame(data, window_length, hop_length): """Convert array into a sequence of successive possibly overlapping frames. starts hop_length points after the preced...
num_samples = data.shape[0] num_frames = 1 + int(np.floor((num_samples - window_length) / hop_length)) shape = (num_frames, window_length) + data.shape[1:] strides = (data.strides[0] * hop_length,) + data.strides return np.lib.stride_tricks.as_strided(data, shape=shape, strides=strides)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def periodic_hann(window_length): """Calculate a "periodic" Hann window. The classic Hann window is defined as a raised cosine that starts and ends on zero, and ...
return 0.5 - (0.5 * np.cos(2 * np.pi / window_length * np.arange(window_length)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stft_magnitude(signal, fft_length, hop_length=None, window_length=None): """Calculate the short-time Fourier transform magnitude. Args: signal: 1D np.array o...
frames = frame(signal, window_length, hop_length) # Apply frame window to each frame. We use a periodic Hann (cosine of period # window_length) instead of the symmetric Hann of np.hanning (period # window_length-1). window = periodic_hann(window_length) windowed_frames = frames * window return np.abs(np....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spectrogram_to_mel_matrix(num_mel_bins=20, num_spectrogram_bins=129, audio_sample_rate=8000, lower_edge_hertz=125.0, upper_edge_hertz=3800.0): """Return a ma...
nyquist_hertz = audio_sample_rate / 2. if lower_edge_hertz < 0.0: raise ValueError("lower_edge_hertz %.1f must be >= 0" % lower_edge_hertz) if lower_edge_hertz >= upper_edge_hertz: raise ValueError("lower_edge_hertz %.1f >= upper_edge_hertz %.1f" % (lower_edge_hertz, upper_edge_hertz...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_mel_spectrogram(data, audio_sample_rate=8000, log_offset=0.0, window_length_secs=0.025, hop_length_secs=0.010, **kwargs): """Convert waveform to a log ma...
window_length_samples = int(round(audio_sample_rate * window_length_secs)) hop_length_samples = int(round(audio_sample_rate * hop_length_secs)) fft_length = 2 ** int(np.ceil(np.log(window_length_samples) / np.log(2.0))) spectrogram = stft_magnitude( data, fft_length=fft_length, hop_length=hop...
<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, output_frequency='per_row'): """ Return a classification, for each ``prediction_window`` examples in the ``dataset``, using the train...
_tkutl._check_categorical_option_type( 'output_frequency', output_frequency, ['per_window', 'per_row']) id_target_map = self._id_target_map preds = self.predict( dataset, output_type='probability_vector', output_frequency=output_frequency) if output_frequency ==...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count_characters(root, out): """Count the occurrances of the different characters in the files"""
if os.path.isfile(root): with open(root, 'rb') as in_f: for line in in_f: for char in line: if char not in out: out[char] = 0 out[char] = out[char] + 1 elif os.path.isdir(root): for filename in os.listdi...
<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_spec(spec, filename): """ Save a protobuf model specification to file. Parameters spec: Model_pb Protobuf representation of the model filename: str File...
name, ext = _os.path.splitext(filename) if not ext: filename = "%s.mlmodel" % filename else: if ext != '.mlmodel': raise Exception("Extension must be .mlmodel (not %s)" % ext) with open(filename, 'wb') as f: s = spec.SerializeToString() f.write(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 load_spec(filename): """ Load a protobuf model specification from file Parameters filename: str Location on disk (a valid filepath) from which the file is lo...
from ..proto import Model_pb2 spec = Model_pb2.Model() with open(filename, 'rb') as f: contents = f.read() spec.ParseFromString(contents) return 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 _get_nn_layers(spec): """ Returns a list of neural network layers if the model contains any. Parameters spec: Model_pb A model protobuf specification. Return...
layers = [] if spec.WhichOneof('Type') == 'pipeline': layers = [] for model_spec in spec.pipeline.models: if not layers: return _get_nn_layers(model_spec) else: layers.extend(_get_nn_layers(model_spec)) elif spec.WhichOneof('Type') 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 evaluate_classifier_with_probabilities(model, data, probabilities='probabilities', verbose = False): """ Evaluate a classifier specification for testing. Par...
model = _get_model(model) if verbose: print("") print("Other Framework\t\tPredicted") max_probability_error, num_key_mismatch = 0, 0 for _,row in data.iterrows(): predicted_values = model.predict(dict(row))[_to_unicode(probabilities)] other_values = row[probabilities]...
<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_feature(spec, current_name, new_name, rename_inputs=True, rename_outputs=True): """ Rename a feature in the specification. Parameters spec: Model_pb T...
from coremltools.models import MLModel if not rename_inputs and not rename_outputs: return changed_input = False changed_output = False if rename_inputs: for input in spec.description.input: if input.name == current_name: input.name = new_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 _sanitize_value(x): """ Performs cleaning steps on the data so various type comparisons can be performed correctly. """
if isinstance(x, _six.string_types + _six.integer_types + (float,)): return x elif _HAS_SKLEARN and _sp.issparse(x): return x.todense() elif isinstance(x, _np.ndarray): return x elif isinstance(x, tuple): return (_sanitize_value(v) for v in x) elif isinstance(x, 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 _element_equal(x, y): """ Performs a robust equality test between elements. """
if isinstance(x, _np.ndarray) or isinstance(y, _np.ndarray): try: return (abs(_np.asarray(x) - _np.asarray(y)) < 1e-5).all() except: return False elif isinstance(x, dict): return (isinstance(y, dict) and _element_equal(x.keys(), y.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 evaluate_transformer(model, input_data, reference_output, verbose=False): """ Evaluate a transformer specification for testing. Parameters spec: [str | MLMod...
model = _get_model(model) if verbose: print(model) print("") print("Other Framework\t\tPredicted") num_errors = 0 for index, row in enumerate(input_data): assert isinstance(row, dict) sanitized_row = _sanitize_value(row) ref_data = _sanitize_value(refere...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(graph, verbose=True): """ Compute the in degree, out degree and total degree of each vertex. Parameters graph : SGraph The graph on which to compute d...
from turicreate._cython.cy_server import QuietProgress if not isinstance(graph, _SGraph): raise TypeError('"graph" input must be a SGraph object.') with QuietProgress(verbose): params = _tc.extensions._toolkits.graph.degree_count.create( {'graph': graph.__proxy__}) 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 replace_emphasis(self, s, index = 0): """replace the index'th emphasized text with s"""
e = self.emphasized[index] self.body[e[0]:e[1]] = [s] del self.emphasized[index]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _execute(self, code): """Override of litre._execute; sets up variable context before evaluating code """
self.globals['example'] = self.example eval(code, self.globals)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile( self , howmany = 1 , pop = -1 , expect_error = False , extension = '.o' , options = ['-c'] , built_handler = lambda built_file: None , source_file = ...
# Grab one example by default if howmany == 'all': howmany = len(self.stack) source = '\n'.join( self.prefix + [str(x) for x in self.stack[-howmany:]] ) source = reduce(lambda s, f: f(s), self.preprocessors, source) 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 load (self, jamfile_location): """Loads jamfile at the given location. After loading, project global file and jamfile needed by the loaded one will be loaded...
assert isinstance(jamfile_location, basestring) absolute = os.path.join(os.getcwd(), jamfile_location) absolute = os.path.normpath(absolute) jamfile_location = b2.util.path.relpath(os.getcwd(), absolute) mname = self.module_name(jamfile_location) # If Jamfile is alread...
<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_parent(self, location): """Loads parent of Jamfile at 'location'. Issues an error if nothing is found."""
assert isinstance(location, basestring) found = b2.util.path.glob_in_parents( location, self.JAMROOT + self.JAMFILE) if not found: print "error: Could not find parent for project at '%s'" % location print "error: Did not find Jamfile.jam or Jamroot.jam in an...
<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(self, name, current_location): """Given 'name' which can be project-id or plain directory name, return project module corresponding to that id or direct...
assert isinstance(name, basestring) assert isinstance(current_location, basestring) project_module = None # Try interpreting name as project id. if name[0] == '/': project_module = self.id2module.get(name) if not project_module: location = os.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 module_name(self, jamfile_location): """Returns the name of module corresponding to 'jamfile-location'. If no module corresponds to location yet, associates ...
assert isinstance(jamfile_location, basestring) module = self.location2module.get(jamfile_location) if not module: # Root the path, so that locations are always umbiguious. # Without this, we can't decide if '../../exe/program1' and '.' # are the same paths, ...
<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_standalone(self, jamfile_module, file): """Loads 'file' as standalone project that has no location associated with it. This is mostly useful for user-co...
assert isinstance(jamfile_module, basestring) assert isinstance(file, basestring) self.used_projects[jamfile_module] = [] bjam.call("load", jamfile_module, file) self.load_used_projects(jamfile_module)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize(self, module_name, location=None, basename=None, standalone_path=''): """Initialize the module for a project. module-name is the name of the proje...
assert isinstance(module_name, basestring) assert isinstance(location, basestring) or location is None assert isinstance(basename, basestring) or basename is None jamroot = False parent_module = None if module_name == "test-config": # No parent pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inherit_attributes(self, project_module, parent_module): """Make 'project-module' inherit attributes of project root and parent module."""
assert isinstance(project_module, basestring) assert isinstance(parent_module, basestring) attributes = self.module2attributes[project_module] pattributes = self.module2attributes[parent_module] # Parent module might be locationless user-config. # FIXME: #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 register_id(self, id, module): """Associate the given id with the given project module."""
assert isinstance(id, basestring) assert isinstance(module, basestring) self.id2module[id] = module
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def push_current(self, project): """Temporary changes the current project to 'project'. Should be followed by 'pop-current'."""
if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) self.saved_current_project.append(self.current_project) self.current_project = project
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def target(self, project_module): """Returns the project target corresponding to the 'project-module'."""
assert isinstance(project_module, basestring) if project_module not in self.module2target: self.module2target[project_module] = \ b2.build.targets.ProjectTarget(project_module, project_module, self.attribute(project_module, "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 add_rule(self, name, callable_): """Makes rule 'name' available to all subsequently loaded Jamfiles. Calling that rule wil relay to 'callable'."""
assert isinstance(name, basestring) assert callable(callable_) self.project_rules_.add_rule(name, callable_)
<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_module(self, name, extra_path=None): """Load a Python module that should be useable from Jamfiles. There are generally two types of modules Jamfiles mig...
assert isinstance(name, basestring) assert is_iterable_typed(extra_path, basestring) or extra_path is None # See if we loaded module of this name already existing = self.loaded_tool_modules_.get(name) if existing: return existing # check the extra path as we...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump(self): """Prints the project attributes."""
id = self.get("id") if not id: id = "(none)" else: id = id[0] parent = self.get("parent") if not parent: parent = "(none)" else: parent = parent[0] print "'%s'" % id print "Parent project:%s", parent ...
<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_wrapper(self, callable_): """Given a free-standing function 'callable', return a new callable that will call 'callable' and report all exceptins, using ...
assert callable(callable_) def wrapper(*args, **kw): return self.call_and_report_errors(callable_, *args, **kw) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def constant(self, name, value): """Declare and set a project global constant. Project global constants are normal variables but should not be changed. They are ...
assert is_iterable_typed(name, basestring) assert is_iterable_typed(value, basestring) self.registry.current().add_constant(name[0], 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 path_constant(self, name, value): """Declare and set a project global constant, whose value is a path. The path is adjusted to be relative to the invocation ...
assert is_iterable_typed(name, basestring) assert is_iterable_typed(value, basestring) if len(value) > 1: self.registry.manager.errors()("path constant should have one element") self.registry.current().add_constant(name[0], value, path=1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_array_feature_extractor(input_features, output_name, extract_indices, output_type = None): """ Creates a feature extractor from an input array feature...
# Make sure that our starting stuff is in the proper form. assert len(input_features) == 1 assert isinstance(input_features[0][1], datatypes.Array) # Create the model. spec = _Model_pb2.Model() spec.specificationVersion = SPECIFICATION_VERSION if isinstance(extract_indices, _integer_type...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def add_input(self, input): ''' Add a single build XML output file to our data. ''' events = xml.dom.pulldom.parse(input) context = [] for (event,node) in events: if event == xml.dom.pulldom.START_ELEMENT: context.append(node) 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 x_build_targets_target( self, node ): ''' Process the target dependency DAG into an ancestry tree so we can look up which top-level library and test targets specific build actions correspond to. ''' target_node = node name = self.get_child_data(target_node,tag='name',...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def x_build_action( self, node ): ''' Given a build action log, process into the corresponding test log and specific test log sub-part. ''' action_node = node name = self.get_child(action_node,tag='name') if name: name = self.get_data(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 x_build_timestamp( self, node ): ''' The time-stamp goes to the corresponding attribute in the result. ''' self.timestamps.append(self.get_data(node).strip()) return 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 print_action(self, test_succeed, action): ''' Print the detailed info of failed or always print tests. ''' #self.info_print(">>> {0}",action.keys()) if not test_succeed or action['info']['always_show_run_output']: output = action['output'].strip() if o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _generate_base_svm_classifier_spec(model): """ Takes an SVM classifier produces a starting spec using the parts. that are shared between all SVMs. """
if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') check_fitted(model, lambda m: hasattr(m, 'support_vectors_')) spec = _Model_pb2.Model() spec.specificationVersion = SPECIFICATION_VERSION svm = spec.supportVectorClassifier _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 _insert_layer_after(self, layer_idx, new_layer, new_keras_layer): """ Insert the new_layer after layer, whose position is layer_idx. The new layer's paramete...
# reminder: new_keras_layer is not part of the original Keras network, # so it's input / output blob information is missing. It serves only as # a parameter holder. layer = self.layer_list[layer_idx] self.layer_list.insert(layer_idx+1, new_layer) self.keras_layer_map[new...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _insert_layer_between(self, src, snk, new_layer, new_keras_layer): """ Insert the new_layer before layer, whose position is layer_idx. The new layer's parame...
if snk is None: insert_pos = self.layer_list.index(src) + 1 else: insert_pos = self.layer_list.index(snk) # insert position self.layer_list.insert(insert_pos, new_layer) self.keras_layer_map[new_layer] = new_keras_layer if src is None: # snk is an input l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert_1d_permute_layers(self): """ Insert permutation layers before a 1D start point or after 1D end point """
idx, nb_layers = 0, len(self.layer_list) in_edges, out_edges = self._get_1d_interface_edges() # Hacky Warning: (1) use a 4-D permute, which is not likely to happen in Keras, # to represent actual permutation needed for (seq, c, h, w) in CoreML # (2) Assume 2-D input shape has m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_component_configuration(component, message): """Report something about component configuration that the user should better know."""
assert isinstance(component, basestring) assert isinstance(message, basestring) __component_logs.setdefault(component, []).append(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(dataset, transformers): """ Create a Transformer object to transform data for feature engineering. Parameters dataset : SFrame The dataset to use for ...
err_msg = "The parameters 'transformers' must be a valid Transformer object." cls = transformers.__class__ _raise_error_if_not_sframe(dataset, "dataset") # List of transformers. if (cls == list): transformers = TransformerChain(transformers) # Transformer. else: if not iss...
<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_data(audio_data, verbose=True): ''' Preprocess each example, breaking it up into frames. Returns two numpy arrays: preprocessed frame and their indexes ''' from .vggish_input import waveform_to_examples last_progress_update = _time.time() progres...
<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_deep_features(self, audio_data, verbose): ''' Performs both audio preprocessing and VGGish deep feature extraction. ''' preprocessed_data, row_ids = self._preprocess_data(audio_data, verbose) deep_features = self._extract_features(preprocessed_data, verbose) outp...
<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_spec(self): """ Return the Core ML spec """
if _mac_ver() >= (10, 14): return self.vggish_model.get_spec() else: vggish_model_file = VGGish() coreml_model_path = vggish_model_file.get_model_path(format='coreml') return MLModel(coreml_model_path).get_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 value_to_jam(value, methods=False): """Makes a token to refer to a Python value inside Jam language code. The token is merely a string that can be passed aro...
global __value_id r = __python_to_jam.get(value, None) if r: return r exported_name = '###_' + str(__value_id) __value_id = __value_id + 1 __python_to_jam[value] = exported_name __jam_to_python[exported_name] = value if methods and type(value) == types.InstanceType: ...