Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def FromDatetime(self, dt): td = dt - datetime(1970, 1, 1) self.seconds = td.seconds + td.days * _SECONDS_PER_DAY self.nanos = td.microseconds * _NANOS_PER_MICROSECOND
[ "Converts datetime to Timestamp." ]
Please provide a description of the function:def ToMicroseconds(self): micros = _RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND) return self.seconds * _MICROS_PER_SECOND + micros
[ "Converts a Duration to microseconds." ]
Please provide a description of the function:def ToMilliseconds(self): millis = _RoundTowardZero(self.nanos, _NANOS_PER_MILLISECOND) return self.seconds * _MILLIS_PER_SECOND + millis
[ "Converts a Duration to milliseconds." ]
Please provide a description of the function:def FromMicroseconds(self, micros): self._NormalizeDuration( micros // _MICROS_PER_SECOND, (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND)
[ "Converts microseconds to Duration." ]
Please provide a description of the function:def FromMilliseconds(self, millis): self._NormalizeDuration( millis // _MILLIS_PER_SECOND, (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND)
[ "Converts milliseconds to Duration." ]
Please provide a description of the function:def ToTimedelta(self): return timedelta( seconds=self.seconds, microseconds=_RoundTowardZero( self.nanos, _NANOS_PER_MICROSECOND))
[ "Converts Duration to timedelta." ]
Please provide a description of the function:def FromTimedelta(self, td): self._NormalizeDuration(td.seconds + td.days * _SECONDS_PER_DAY, td.microseconds * _NANOS_PER_MICROSECOND)
[ "Convertd timedelta to Duration." ]
Please provide a description of the function:def _NormalizeDuration(self, seconds, nanos): # 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
[ "Set Duration by seconds and nonas." ]
Please provide a description of the function:def ToJsonString(self): camelcase_paths = [] for path in self.paths: camelcase_paths.append(_SnakeCaseToCamelCase(path)) return ','.join(camelcase_paths)
[ "Converts FieldMask to string according to proto3 JSON spec." ]
Please provide a description of the function:def IsValidForDescriptor(self, message_descriptor): for path in self.paths: if not _IsValidPath(message_descriptor, path): return False return True
[ "Checks whether the FieldMask is valid for Message Descriptor." ]
Please provide a description of the function:def AllFieldsFromDescriptor(self, message_descriptor): self.Clear() for field in message_descriptor.fields: self.paths.append(field.name)
[ "Gets all direct fields of Message Descriptor to FieldMask." ]
Please provide a description of the function:def Union(self, mask1, mask2): _CheckFieldMaskMessage(mask1) _CheckFieldMaskMessage(mask2) tree = _FieldMaskTree(mask1) tree.MergeFromFieldMask(mask2) tree.ToFieldMask(self)
[ "Merges mask1 and mask2 into this FieldMask." ]
Please provide a description of the function:def Intersect(self, mask1, mask2): _CheckFieldMaskMessage(mask1) _CheckFieldMaskMessage(mask2) tree = _FieldMaskTree(mask1) intersection = _FieldMaskTree() for path in mask2.paths: tree.IntersectPath(path, intersection) intersection.ToField...
[ "Intersects mask1 and mask2 into this FieldMask." ]
Please provide a description of the function:def MergeMessage( self, source, destination, replace_message_field=False, replace_repeated_field=False): tree = _FieldMaskTree(self) tree.MergeMessage( source, destination, replace_message_field, replace_repeated_field)
[ "Merges fields specified in FieldMask from source to destination.\n\n Args:\n source: Source message.\n destination: The destination message to be merged into.\n replace_message_field: Replace message field if True. Merge message\n field if False.\n replace_repeated_field: Replace re...
Please provide a description of the function:def AddPath(self, path): 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[nam...
[ "Adds a field path into the tree.\n\n If the field path to add is a sub-path of an existing field path\n in the tree (i.e., a leaf node), it means the tree already matches\n the given path so nothing will be added to the tree. If the path\n matches an existing non-leaf node in the tree, that non-leaf no...
Please provide a description of the function:def IntersectPath(self, path, intersection): 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.AddLeafNod...
[ "Calculates the intersection part of a field path with this tree.\n\n Args:\n path: The field path to calculates.\n intersection: The out tree to record the intersection part.\n " ]
Please provide a description of the function:def AddLeafNodes(self, prefix, node): if not node: self.AddPath(prefix) for name in node: child_path = prefix + '.' + name self.AddLeafNodes(child_path, node[name])
[ "Adds leaf nodes begin with prefix to this tree." ]
Please provide a description of the function:def MergeMessage( self, source, destination, replace_message, replace_repeated): _MergeMessage( self._root, source, destination, replace_message, replace_repeated)
[ "Merge all fields specified by this tree from source to destination." ]
Please provide a description of the function:def configure (command = None, condition = None, options = None): rc_type = feature.get_values('<rc-type>', options) if rc_type: assert(len(rc_type) == 1) rc_type = rc_type[0] if command and condition and rc_type: flags('rc.compile.r...
[ "\n Configures a new resource compilation command specific to a condition,\n usually a toolset selection condition. The possible options are:\n\n * <rc-type>(rc|windres) - Indicates the type of options the command\n accepts.\n\n Even though the arguments are all optional...
Please provide a description of the function:def convert(model, feature_names, target): if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') _sklearn_util.check_expected_type(model, _NuSVR) return _SVR.convert(model, feature_names, target...
[ "Convert a Nu Support Vector Regression (NuSVR) model to the protobuf spec.\n Parameters\n ----------\n model: NuSVR\n A trained NuSVR encoder model.\n\n feature_names: [str]\n Name of the input columns.\n\n target: str\n Name of the output column.\n\n Returns\n -------\n ...
Please provide a description of the function:def create(dataset, target, features=None, l2_penalty=1e-2, l1_penalty=0.0, solver='auto', feature_rescaling=True, convergence_threshold = _DEFAULT_SOLVER_OPTIONS['convergence_threshold'], step_size = _DEFAULT_SOLVER_OPTIONS['step_size'], lbfgs_memory_level =...
[ "\n Create a :class:`~turicreate.linear_regression.LinearRegression` to\n predict a scalar target variable as a linear function of one or more\n features. In addition to standard numeric and categorical types, features\n can also be extracted automatically from list- or dictionary-type SFrame\n colum...
Please provide a description of the function:def export_coreml(self, filename): from turicreate.extensions import _linear_regression_export_as_model_asset from turicreate.toolkits import _coreml_utils display_name = "linear regression" short_description = _coreml_utils._mlmodel_...
[ "\n Export the model in Core ML format.\n\n Parameters\n ----------\n filename: str\n A valid filename where the model can be saved.\n\n Examples\n --------\n >>> model.export_coreml(\"MyModel.mlmodel\")\n " ]
Please provide a description of the function:def predict(self, dataset, missing_value_action='auto'): return super(LinearRegression, self).predict(dataset, missing_value_action=missing_value_action)
[ "\n Return target value predictions for ``dataset``, using the trained\n linear regression model. This method can be used to get fitted values\n for the model by inputting the training dataset.\n\n Parameters\n ----------\n dataset : SFrame | pandas.Dataframe\n D...
Please provide a description of the function:def evaluate(self, dataset, metric='auto', missing_value_action='auto'): r _raise_error_evaluation_metric_is_valid(metric, ['auto', 'rmse', 'max_error']) return super(LinearRegression, self).evaluate(dataset,...
[ "Evaluate the model by making target value predictions and comparing\n to actual values.\n\n Two metrics are used to evaluate linear regression models. The first\n is root-mean-squared error (RMSE) while the second is the absolute\n value of the maximum error between the actual and pred...
Please provide a description of the function:def frame(data, window_length, hop_length): 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 retur...
[ "Convert array into a sequence of successive possibly overlapping frames.\n\n An n-dimensional array of shape (num_samples, ...) is converted into an\n (n+1)-D array of shape (num_frames, window_length, ...), where each frame\n starts hop_length points after the preceding one.\n\n This is accomplished using str...
Please provide a description of the function:def periodic_hann(window_length): return 0.5 - (0.5 * np.cos(2 * np.pi / window_length * np.arange(window_length)))
[ "Calculate a \"periodic\" Hann window.\n\n The classic Hann window is defined as a raised cosine that starts and\n ends on zero, and where every value appears twice, except the middle\n point for an odd-length window. Matlab calls this a \"symmetric\" window\n and np.hanning() returns it. However, for Fourier...
Please provide a description of the function:def stft_magnitude(signal, fft_length, hop_length=None, window_length=None): frames = frame(signal, window_length, hop_length) # Apply frame window to each frame. We use a periodic Hann (cosine of period # window_length) instead...
[ "Calculate the short-time Fourier transform magnitude.\n\n Args:\n signal: 1D np.array of the input time-domain signal.\n fft_length: Size of the FFT to apply.\n hop_length: Advance (in samples) between each frame passed to FFT.\n window_length: Length of each block of samples to pass to FFT.\n\n Retu...
Please provide a description of the function: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): nyq...
[ "Return a matrix that can post-multiply spectrogram rows to make mel.\n\n Returns a np.array matrix A that can be used to post-multiply a matrix S of\n spectrogram values (STFT magnitudes) arranged as frames x bins to generate a\n \"mel spectrogram\" M of frames x num_mel_bins. M = S A.\n\n The classic HTK alg...
Please provide a description of the function:def log_mel_spectrogram(data, audio_sample_rate=8000, log_offset=0.0, window_length_secs=0.025, hop_length_secs=0.010, **kwargs): window_length_sample...
[ "Convert waveform to a log magnitude mel-frequency spectrogram.\n\n Args:\n data: 1D np.array of waveform data.\n audio_sample_rate: The sampling rate of data.\n log_offset: Add this to values when taking log to avoid -Infs.\n window_length_secs: Duration of each window to analyze.\n hop_length_secs...
Please provide a description of the function:def generate_random_sframe(num_rows, column_codes, random_seed = 0): from ..extensions import _generate_random_sframe assert isinstance(column_codes, str) assert isinstance(num_rows, int) assert isinstance(random_seed, int) X = _generate_rando...
[ "\n Creates a random SFrame with `num_rows` rows and randomly\n generated column types determined by `column_codes`. The output\n SFrame is deterministic based on `random_seed`.\n \n `column_types` is a string with each character denoting one type\n of column, with the output SFrame having one col...
Please provide a description of the function:def generate_random_regression_sframe(num_rows, column_codes, random_seed = 0, target_noise_level = 0.25): from ..extensions import _generate_random_sframe assert isinstance(column_codes, str) assert isinstance(num_rows, int) assert isinstance(random_s...
[ "\n Creates a random SFrame with `num_rows` rows and randomly\n generated column types determined by `column_codes`. The output\n SFrame is deterministic based on `random_seed`. In addition, a\n target column is generated with values dependent on the randomly\n generated features in a given row.\n ...
Please provide a description of the function:def generate_random_classification_sframe(num_rows, column_codes, num_classes, misclassification_spread = 0.25, num_extra_class_bins = None, random_s...
[ "\n Creates a random SFrame with `num_rows` rows and randomly\n generated column types determined by `column_codes`. The output\n SFrame is deterministic based on `random_seed`. In addition, a\n target column is generated with values dependent on the randomly\n generated features in a given row.\n ...
Please provide a description of the function:def infer_shapes(nn_spec, input_spec, input_shape_dict = None): shape_dict = {} if input_shape_dict: for key, value in input_shape_dict.items(): assert len(value) == 5, 'Shape of the input must be of length 5' shape_dict[key] = ...
[ "\n Input:\n\n spec : mlmodel spec\n input_shape_dict: dictionary of string --> tuple\n string: input name\n tuple: input shape as a 5 length tuple in order (Seq, Batch, C, H, W)\n\n If input_shape_dict is not provided, input shapes are inferred fr...
Please provide a description of the function:def convert(libsvm_model, feature_names, target, input_length, probability): if not(HAS_LIBSVM): raise RuntimeError('libsvm not found. libsvm conversion API is disabled.') import svm as libsvm from ...proto import SVM_pb2 from ...proto import Mo...
[ "Convert a svm model to the protobuf spec.\n\n This currently supports:\n * C-SVC\n * nu-SVC\n * Epsilon-SVR\n * nu-SVR\n\n Parameters\n ----------\n model_path: libsvm_model\n Libsvm representation of the model.\n\n feature_names : [str] | str\n Names of each of the ...
Please provide a description of the function:def create(dataset, session_id, target, features=None, prediction_window=100, validation_set='auto', max_iterations=10, batch_size=32, verbose=True): _tkutl._raise_error_if_not_sframe(dataset, "dataset") from .._mxnet import _mxnet_utils from ._mx...
[ "\n Create an :class:`ActivityClassifier` model.\n\n Parameters\n ----------\n dataset : SFrame\n Input data which consists of `sessions` of data where each session is\n a sequence of data. The data must be in `stacked` format, grouped by\n session. Within each session, the data is ...
Please provide a description of the function:def _encode_target(data, target, mapping=None): if mapping is None: mapping = {t: i for i, t in enumerate(sorted(data[target].unique()))} data[target] = data[target].apply(lambda t: mapping[t]) return data, mapping
[ " Encode targets to integers in [0, num_classes - 1] " ]
Please provide a description of the function:def export_coreml(self, filename): import coremltools as _cmt import mxnet as _mx from ._mx_model_architecture import _net_params prob_name = self.target + 'Probability' label_name = self.target input_features = [ ...
[ "\n Export the model in Core ML format.\n\n Parameters\n ----------\n filename: str\n A valid filename where the model can be saved.\n\n Examples\n --------\n >>> model.export_coreml(\"MyModel.mlmodel\")\n " ]
Please provide a description of the function:def predict(self, dataset, output_type='class', output_frequency='per_row'): _tkutl._raise_error_if_not_sframe(dataset, 'dataset') _tkutl._check_categorical_option_type( 'output_frequency', output_frequency, ['per_window', 'per_row']) ...
[ "\n Return predictions for ``dataset``, using the trained activity classifier.\n Predictions can be generated as class labels, or as a probability\n vector with probabilities for each class.\n\n The activity classifier generates a single prediction for each\n ``prediction_window``...
Please provide a description of the function:def evaluate(self, dataset, metric='auto'): avail_metrics = ['accuracy', 'auc', 'precision', 'recall', 'f1_score', 'log_loss', 'confusion_matrix', 'roc_curve'] _tkutl._check_categorical_option_type( 'metric', met...
[ "\n Evaluate the model by making predictions of target values and comparing\n these to actual values.\n\n Parameters\n ----------\n dataset : SFrame\n Dataset of new observations. Must include columns with the same\n names as the session_id, target and featur...
Please provide a description of the function:def classify(self, dataset, output_frequency='per_row'): _tkutl._check_categorical_option_type( 'output_frequency', output_frequency, ['per_window', 'per_row']) id_target_map = self._id_target_map preds = self.predict( ...
[ "\n Return a classification, for each ``prediction_window`` examples in the\n ``dataset``, using the trained activity classification model. The output\n SFrame contains predictions as both class labels as well as probabilities \n that the predicted value is the associated label.\n\n ...
Please provide a description of the function:def predict_topk(self, dataset, output_type='probability', k=3, output_frequency='per_row'): _tkutl._check_categorical_option_type('output_type', output_type, ['probability', 'rank']) id_target_map = self._id_target_map preds = self.predict( ...
[ "\n Return top-k predictions for the ``dataset``, using the trained model.\n Predictions are returned as an SFrame with three columns: `prediction_id`, \n `class`, and `probability`, or `rank`, depending on the ``output_type``\n parameter.\n\n Parameters\n ----------\n ...
Please provide a description of the function:def count_characters(root, out): 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[cha...
[ "Count the occurrances of the different characters in the files" ]
Please provide a description of the function:def main(): desc = 'Generate character statistics from a source tree' parser = argparse.ArgumentParser(description=desc) parser.add_argument( '--src', dest='src', required=True, help='The root of the source tree' ) par...
[ "The main function of the script" ]
Please provide a description of the function:def save_spec(spec, filename): 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...
[ "\n Save a protobuf model specification to file.\n\n Parameters\n ----------\n spec: Model_pb\n Protobuf representation of the model\n\n filename: str\n File path where the spec gets saved.\n\n Examples\n --------\n .. sourcecode:: python\n\n >>> coremltools.utils.save_...
Please provide a description of the function:def load_spec(filename): from ..proto import Model_pb2 spec = Model_pb2.Model() with open(filename, 'rb') as f: contents = f.read() spec.ParseFromString(contents) return spec
[ "\n Load a protobuf model specification from file\n\n Parameters\n ----------\n filename: str\n Location on disk (a valid filepath) from which the file is loaded\n as a protobuf spec.\n\n Returns\n -------\n model_spec: Model_pb\n Protobuf representation of the model\n\n ...
Please provide a description of the function:def _get_nn_layers(spec): layers = [] if spec.WhichOneof('Type') == 'pipeline': layers = [] for model_spec in spec.pipeline.models: if not layers: return _get_nn_layers(model_spec) else: la...
[ "\n Returns a list of neural network layers if the model contains any.\n\n Parameters\n ----------\n spec: Model_pb\n A model protobuf specification.\n\n Returns\n -------\n [NN layer]\n list of all layers (including layers from elements of a pipeline\n\n " ]
Please provide a description of the function:def evaluate_regressor(model, data, target="target", verbose=False): model = _get_model(model) if verbose: print("") print("Other Framework\t\tPredicted\t\tDelta") max_error = 0 error_squared = 0 for index,row in data.iterrows(): ...
[ "\n Evaluate a CoreML regression model and compare against predictions\n from the original framework (for testing correctness of conversion)\n\n Parameters\n ----------\n filename: [str | MLModel]\n File path from which to load the MLModel from (OR) a loaded version of\n MLModel.\n\n ...
Please provide a description of the function:def evaluate_classifier(model, data, target='target', verbose=False): model = _get_model(model) if verbose: print("") print("Other Framework\t\tPredicted") num_errors = 0 for index,row in data.iterrows(): predicted = model.predi...
[ "\n Evaluate a CoreML classifier model and compare against predictions\n from the original framework (for testing correctness of conversion). Use\n this evaluation for models that don't deal with probabilities.\n\n Parameters\n ----------\n filename: [str | MLModel]\n File from where to loa...
Please provide a description of the function:def evaluate_classifier_with_probabilities(model, data, probabilities='probabilities', verbose = False): model = _get_model(model) if verbose: print("") print(...
[ "\n Evaluate a classifier specification for testing.\n\n Parameters\n ----------\n filename: [str | Model]\n File from where to load the model from (OR) a loaded\n version of the MLModel.\n\n data: [str | Dataframe]\n Test data on which to evaluate the models (dataframe,\n ...
Please provide a description of the function:def rename_feature(spec, current_name, new_name, rename_inputs=True, rename_outputs=True): from coremltools.models import MLModel if not rename_inputs and not rename_outputs: return changed_input = False changed_output = Fals...
[ "\n Rename a feature in the specification.\n\n Parameters\n ----------\n spec: Model_pb\n The specification containing the feature to rename.\n\n current_name: str\n Current name of the feature. If this feature doesn't exist, the rename\n is a no-op.\n\n new_name: str\n ...
Please provide a description of the function:def _sanitize_value(x): 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): ...
[ "\n Performs cleaning steps on the data so various type comparisons can\n be performed correctly.\n " ]
Please provide a description of the function:def _element_equal(x, y): 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 (isinstan...
[ "\n Performs a robust equality test between elements.\n " ]
Please provide a description of the function:def evaluate_transformer(model, input_data, reference_output, verbose=False): model = _get_model(model) if verbose: print(model) print("") print("Other Framework\t\tPredicted") num_errors = 0 for index, r...
[ "\n Evaluate a transformer specification for testing.\n\n Parameters\n ----------\n spec: [str | MLModel]\n File from where to load the Model from (OR) a loaded\n version of MLModel.\n\n input_data: list[dict]\n Test data on which to evaluate the models.\n\n reference_output: ...
Please provide a description of the function:def _get_input_names(spec): retval = [feature.name for feature in spec.description.input] return retval
[ "\n Returns a list of the names of the inputs to this model.\n :param spec: The model protobuf specification\n :return: [str] A list of input feature names\n " ]
Please provide a description of the function:def create(graph, verbose=True): 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._toolk...
[ "\n Compute the in degree, out degree and total degree of each vertex.\n\n Parameters\n ----------\n graph : SGraph\n The graph on which to compute degree counts.\n\n verbose : bool, optional\n If True, print progress updates.\n\n Returns\n -------\n out : DegreeCountingModel\n...
Please provide a description of the function:def replace_emphasis(self, s, index = 0): e = self.emphasized[index] self.body[e[0]:e[1]] = [s] del self.emphasized[index]
[ "replace the index'th emphasized text with s" ]
Please provide a description of the function:def _execute(self, code): self.globals['example'] = self.example eval(code, self.globals)
[ "Override of litre._execute; sets up variable context before\n evaluating code\n " ]
Please provide a description of the function:def compile( self , howmany = 1 , pop = -1 , expect_error = False , extension = '.o' , options = ['-c'] , built_handler = lambda built_file: None , source_file = None , source_suffix = '.cpp' ...
[ "\n Compile examples on the stack, whose topmost item is the last example\n seen but not yet handled so far.\n\n :howmany: How many of the topmost examples on the stack to compile.\n You can pass a number, or 'all' to indicate that all examples should\n be compiled.\n\n ...
Please provide a description of the function:def load (self, jamfile_location): 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(), abso...
[ "Loads jamfile at the given location. After loading, project global\n file and jamfile needed by the loaded one will be loaded recursively.\n If the jamfile at that location is loaded already, does nothing.\n Returns the project module for the Jamfile." ]
Please provide a description of the function:def load_parent(self, location): 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 '%...
[ "Loads parent of Jamfile at 'location'.\n Issues an error if nothing is found." ]
Please provide a description of the function:def find(self, name, current_location): assert isinstance(name, basestring) assert isinstance(current_location, basestring) project_module = None # Try interpreting name as project id. if name[0] == '/': project_...
[ "Given 'name' which can be project-id or plain directory name,\n return project module corresponding to that id or directory.\n Returns nothing of project is not found." ]
Please provide a description of the function:def module_name(self, jamfile_location): assert isinstance(jamfile_location, basestring) module = self.location2module.get(jamfile_location) if not module: # Root the path, so that locations are always umbiguious. # Wi...
[ "Returns the name of module corresponding to 'jamfile-location'.\n If no module corresponds to location yet, associates default\n module name with that location." ]
Please provide a description of the function:def find_jamfile (self, dir, parent_root=0, no_errors=0): assert isinstance(dir, basestring) assert isinstance(parent_root, (int, bool)) assert isinstance(no_errors, (int, bool)) # Glob for all the possible Jamfiles according to the ...
[ "Find the Jamfile at the given location. This returns the\n exact names of all the Jamfiles in the given directory. The optional\n parent-root argument causes this to search not the given directory\n but the ones above it up to the directory given in it.", "warning: Found multiple Jamfiles at...
Please provide a description of the function:def load_jamfile(self, dir, jamfile_module): assert isinstance(dir, basestring) assert isinstance(jamfile_module, basestring) # See if the Jamfile is where it should be. is_jamroot = False jamfile_to_load = b2.util.path.glob(...
[ "Load a Jamfile at the given directory. Returns nothing.\n Will attempt to load the file as indicated by the JAMFILE patterns.\n Effect of calling this rule twice with the same 'dir' is underfined.", "\n The value of the .current-project variable has magically changed\n ...
Please provide a description of the function:def load_standalone(self, jamfile_module, file): assert isinstance(jamfile_module, basestring) assert isinstance(file, basestring) self.used_projects[jamfile_module] = [] bjam.call("load", jamfile_module, file) self.load_used...
[ "Loads 'file' as standalone project that has no location\n associated with it. This is mostly useful for user-config.jam,\n which should be able to define targets, but although it has\n some location in filesystem, we do not want any build to\n happen in user's HOME, for example.\n\n ...
Please provide a description of the function:def initialize(self, module_name, location=None, basename=None, standalone_path=''): assert isinstance(module_name, basestring) assert isinstance(location, basestring) or location is None assert isinstance(basename, basestring) or basename is...
[ "Initialize the module for a project.\n\n module-name is the name of the project module.\n location is the location (directory) of the project to initialize.\n If not specified, standalone project will be initialized\n standalone_path is the path to the source-location.\n ...
Please provide a description of the function:def inherit_attributes(self, project_module, parent_module): assert isinstance(project_module, basestring) assert isinstance(parent_module, basestring) attributes = self.module2attributes[project_module] pattributes = self.module2att...
[ "Make 'project-module' inherit attributes of project\n root and parent module." ]
Please provide a description of the function:def register_id(self, id, module): assert isinstance(id, basestring) assert isinstance(module, basestring) self.id2module[id] = module
[ "Associate the given id with the given project module." ]
Please provide a description of the function:def push_current(self, project): if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) self.saved_current_project.append(self.current_project) self.current_project = project
[ "Temporary changes the current project to 'project'. Should\n be followed by 'pop-current'." ]
Please provide a description of the function:def attribute(self, project, attribute): assert isinstance(project, basestring) assert isinstance(attribute, basestring) try: return self.module2attributes[project].get(attribute) except: raise BaseException("N...
[ "Returns the value of the specified attribute in the\n specified jamfile module." ]
Please provide a description of the function:def attributeDefault(self, project, attribute, default): assert isinstance(project, basestring) assert isinstance(attribute, basestring) assert isinstance(default, basestring) or default is None return self.module2attributes[project]....
[ "Returns the value of the specified attribute in the\n specified jamfile module." ]
Please provide a description of the function:def target(self, 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_mod...
[ "Returns the project target corresponding to the 'project-module'." ]
Please provide a description of the function:def add_rule(self, name, callable_): assert isinstance(name, basestring) assert callable(callable_) self.project_rules_.add_rule(name, callable_)
[ "Makes rule 'name' available to all subsequently loaded Jamfiles.\n\n Calling that rule wil relay to 'callable'." ]
Please provide a description of the function:def __build_python_module_cache(self): cache = {} for importer, mname, ispkg in pkgutil.walk_packages(b2.__path__, prefix='b2.'): basename = mname.split('.')[-1] # since the jam code is only going to have "import toolset ;" ...
[ "Recursively walks through the b2/src subdirectories and\n creates an index of base module name to package name. The\n index is stored within self.__python_module_cache and allows\n for an O(1) module lookup.\n\n For example, given the base module name `toolset`,\n self.__python_m...
Please provide a description of the function:def load_module(self, name, extra_path=None): 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_module...
[ "Load a Python module that should be useable from Jamfiles.\n\n There are generally two types of modules Jamfiles might want to\n use:\n - Core Boost.Build. Those are imported using plain names, e.g.\n 'toolset', so this function checks if we have module named\n b2.package.module ...
Please provide a description of the function:def set(self, attribute, specification, exact=False): assert isinstance(attribute, basestring) assert isinstance(exact, (int, bool)) if __debug__ and not exact: if attribute == 'requirements': assert (isinstance(sp...
[ "Set the named attribute from the specification given by the user.\n The value actually set may be different.", "Invalid project attribute '%s' specified\nfor project at '%s'" ]
Please provide a description of the function:def dump(self): 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] ...
[ "Prints the project attributes." ]
Please provide a description of the function:def make_wrapper(self, callable_): assert callable(callable_) def wrapper(*args, **kw): return self.call_and_report_errors(callable_, *args, **kw) return wrapper
[ "Given a free-standing function 'callable', return a new\n callable that will call 'callable' and report all exceptins,\n using 'call_and_report_errors'." ]
Please provide a description of the function:def constant(self, name, value): assert is_iterable_typed(name, basestring) assert is_iterable_typed(value, basestring) self.registry.current().add_constant(name[0], value)
[ "Declare and set a project global constant.\n Project global constants are normal variables but should\n not be changed. They are applied to every child Jamfile." ]
Please provide a description of the function:def path_constant(self, name, value): 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.r...
[ "Declare and set a project global constant, whose value is a path. The\n path is adjusted to be relative to the invocation directory. The given\n value path is taken to be either absolute, or relative to this project\n root." ]
Please provide a description of the function:def conditional(self, condition, requirements): assert is_iterable_typed(condition, basestring) assert is_iterable_typed(requirements, basestring) c = string.join(condition, ",") if c.find(":") != -1: return [c + r for r i...
[ "Calculates conditional requirements for multiple requirements\n at once. This is a shorthand to be reduce duplication and to\n keep an inline declarative syntax. For example:\n\n lib x : x.cpp : [ conditional <toolset>gcc <variant>debug :\n <define>DEBUG_EXCEPTION <define>DE...
Please provide a description of the function:def create_array_feature_extractor(input_features, output_name, extract_indices, output_type = None): # Make sure that our starting stuff is in the proper form. assert len(input_features) == 1 assert isinstance(input_featu...
[ "\n Creates a feature extractor from an input array feature, return\n\n input_features is a list of one (name, array) tuple.\n\n extract_indices is either an integer or a list. If it's an integer,\n the output type is by default a double (but may also be an integer).\n If a list, the output type is ...
Please provide a description of the function: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: ...
[]
Please provide a description of the function: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 ...
[]
Please provide a description of the function: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: ...
[]
Please provide a description of the function: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
[]
Please provide a description of the function: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']: outpu...
[]
Please provide a description of the function:def _get_weight_param_summary(wp): summary_str = '' if wp.HasField('quantization'): nbits = wp.quantization.numberOfBits quant_type = 'linearly' if wp.quantization.HasField('linearQuantization') else 'lookup-table' summary_str += '{}-bit ...
[ "Get a summary of _NeuralNetwork_pb2.WeightParams\n Args:\n wp : _NeuralNetwork_pb2.WeightParams - the _NeuralNetwork_pb2.WeightParams message to display\n Returns:\n a str summary for wp\n " ]
Please provide a description of the function:def _summarize_network_layer_info(layer): layer_type_str = layer.WhichOneof('layer') layer_name = layer.name layer_inputs = list(layer.input) layer_outputs = list(layer.output) typed_layer = getattr(layer, layer_type_str) layer_field_names = [l...
[ "\n Args:\n layer - an MLModel NeuralNetwork Layer protobuf message\n Returns:\n layer_type : str - type of layer\n layer_name : str - name of the layer\n layer_inputs : list[str] - a list of strings representing input blobs of the layer\n layer_outputs : list[str] - a list of strings represent...
Please provide a description of the function:def summarize_neural_network_spec(mlmodel_spec): inputs = [(blob.name, _get_feature_description_summary(blob)) for blob in mlmodel_spec.description.input] outputs = [(blob.name, _get_feature_description_summary(blob)) for blob in mlmodel_spec.description.output]...
[ " Summarize network into the following structure.\n Args:\n mlmodel_spec : mlmodel spec\n Returns:\n inputs : list[(str, str)] - a list of two tuple (name, descriptor) for each input blob.\n outputs : list[(str, str)] - a list of two tuple (name, descriptor) for each output blob\n layers : list[(s...
Please provide a description of the function:def print_network_spec(mlmodel_spec, interface_only=False): inputs, outputs, layers_info = summarize_neural_network_spec(mlmodel_spec) print('Inputs:') for i in inputs: name, description = i print(' {} {}'.format(name, description)) pr...
[ " Print the network information summary.\n Args:\n mlmodel_spec : the mlmodel spec\n interface_only : Shows only the input and output of the network\n " ]
Please provide a description of the function:def _generate_base_svm_classifier_spec(model): 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() ...
[ "\n Takes an SVM classifier produces a starting spec using the parts. that are\n shared between all SVMs.\n " ]
Please provide a description of the function:def convert(model, feature_names, target): if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') spec = _generate_base_svm_classifier_spec(model) spec = set_classifier_interface_params(spec, feat...
[ "Convert a Support Vector Classtion (SVC) model to the protobuf spec.\n Parameters\n ----------\n model: SVC\n A trained SVC encoder model.\n\n feature_names: [str], optional (default=None)\n Name of the input columns.\n\n target: str, optional (default=None)\n Name of the output...
Please provide a description of the function:def make_input_layers(self): self.input_layers = [] if hasattr(self.model, 'input_layers'): input_keras_layers = self.model.input_layers[:] self.input_layers = [None] * len(input_keras_layers) for layer in self.lay...
[ "\n Extract the ordering of the input layers.\n " ]
Please provide a description of the function:def make_output_layers(self): # TODO # use successors == 0 as the criteria for output layer # will fail when some intermediate layers also generate output. # However, because the possibility of having inserted layers, # it's m...
[ "\n Extract the ordering of output layers.\n " ]
Please provide a description of the function:def generate_blob_names(self): # generate blob names that represent edges in blob_name_map # because of the InputLayers, input blobs are also generated. # Generate each layer's input / output blob names for layer in self.layer_list: ...
[ "\n Generate blob names for each one of the edge. At this time, Keras does not\n support \"fork\" operation (a layer with more than 1 blob output). So we just\n use names of the src layer to identify a blob. We also assume all neural\n networks are singly-connected graphs - which shoul...
Please provide a description of the function:def _remove_layer(self, layer): successors = self.get_successors(layer) predecessors = self.get_predecessors(layer) # remove all edges for succ in successors: self._remove_edge(layer, succ) for pred in predecessors...
[ "\n remove the layer and its input/output edges\n " ]
Please provide a description of the function:def _insert_layer_after(self, layer_idx, new_layer, new_keras_layer): # 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. ...
[ "\n Insert the new_layer after layer, whose position is layer_idx. The new layer's\n parameter is stored in a Keras layer called new_keras_layer\n " ]
Please provide a description of the function:def _insert_layer_between(self, src, snk, new_layer, new_keras_layer): 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(...
[ "\n Insert the new_layer before layer, whose position is layer_idx. The new layer's\n parameter is stored in a Keras layer called new_keras_layer\n " ]
Please provide a description of the function:def defuse_activation(self): idx, nb_layers = 0, len(self.layer_list) while idx < nb_layers: layer = self.layer_list[idx] k_layer = self.keras_layer_map[layer] # unwrap time-distributed layers if (isins...
[ "\n Defuse the fused activation layers in the network.\n " ]