INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Adds a new element at the end of the list and returns it. Keyword arguments may be used to initialize the element.
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) ...
Extends by appending the given sequence of elements of the same type as this one copying each individual message.
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: ...
Returns the elements of B that are not in A.
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
Removes from set1 any items which don t appear in set2 and returns the result.
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
Returns true iff all elements of small exist in large.
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
Returns True iff a contains the same elements as b irrespective of their order. # TODO: Python 2. 4 has a proper set class.
def equal (a, b): """ Returns True iff 'a' contains the same elements as 'b', irrespective of their order. # TODO: Python 2.4 has a proper set class. """ assert is_iterable(a) assert is_iterable(b) return contains (a, b) and contains (b, a)
Annotate your images loaded in either an SFrame or SArray Format
def annotate(data, image_column=None, annotation_column='annotations'): """ Annotate your images loaded in either an SFrame or SArray Format The annotate util is a GUI assisted application used to create labels in SArray Image data. Specifying a column, with dtype Image, in an SFrame ...
Recover the last annotated SFrame. If you annotate an SFrame and forget to assign it to a variable this function allows you to recover the last annotated SFrame. Returns -------
def recover_annotation(): """ Recover the last annotated SFrame. If you annotate an SFrame and forget to assign it to a variable, this function allows you to recover the last annotated SFrame. Returns ------- out : SFrame A new SFrame th...
Convert a DictVectorizer model to the protobuf spec.
def convert(model, input_features, output_features): """Convert a DictVectorizer model to the protobuf spec. Parameters ---------- model: DictVectorizer A fitted DictVectorizer model. input_features: str Name of the input column. output_features: str Name of the output...
Internal function. This function is called via a call back returning from IPC to Cython to Python. It tries to perform incremental printing to IPython Notebook or Jupyter Notebook and when all else fails just prints locally.
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 printing to IPython Notebook or Jupyter Notebook and when all else fails, just prints locally. """ success = False try: ...
Internal function to execute toolkit on the turicreate server.
def run(toolkit_name, options, verbose=True, show_progress=False): """ Internal function to execute toolkit on the turicreate server. Parameters ---------- toolkit_name : string The name of the toolkit. options : dict A map containing the required input for the toolkit function...
Truncates the remainder part after division.
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 ...
Checks whether the path is valid for Message Descriptor.
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 f...
Raises ValueError if message is not a FieldMask.
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...
Converts a path name from snake_case to camelCase.
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(pa...
Converts a field name from camelCase to snake_case.
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 += '...
Merge all fields specified by a sub - tree from source to destination.
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: ...
Adds the field paths descended from node to field_mask.
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], c...
Packs the specified message into current Any message.
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_prefi...
Unpacks the current Any message into specified message.
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
Converts Timestamp to RFC 3339 date string format.
def ToJsonString(self): """Converts Timestamp to RFC 3339 date string format. Returns: A string converted from timestamp. The string is always Z-normalized and uses 3, 6 or 9 fractional digits as required to represent the exact time. Example of the return format: '1972-01-01T10:00:20.021Z' ...
Parse a RFC 3339 date string format to Timestamp.
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 are accepted as long as they fit into nano-seconds precision. Example of accepted format: '1972-01-01T10:00:20.021-05:00' ...
Converts nanoseconds since epoch to Timestamp.
def FromNanoseconds(self, nanos): """Converts nanoseconds since epoch to Timestamp.""" self.seconds = nanos // _NANOS_PER_SECOND self.nanos = nanos % _NANOS_PER_SECOND
Converts microseconds since epoch to Timestamp.
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
Converts milliseconds since epoch to Timestamp.
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
Converts Timestamp to datetime.
def ToDatetime(self): """Converts Timestamp to datetime.""" return datetime.utcfromtimestamp( self.seconds + self.nanos / float(_NANOS_PER_SECOND))
Converts datetime to Timestamp.
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
Converts a Duration to microseconds.
def ToMicroseconds(self): """Converts a Duration to microseconds.""" micros = _RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND) return self.seconds * _MICROS_PER_SECOND + micros
Converts a Duration to milliseconds.
def ToMilliseconds(self): """Converts a Duration to milliseconds.""" millis = _RoundTowardZero(self.nanos, _NANOS_PER_MILLISECOND) return self.seconds * _MILLIS_PER_SECOND + millis
Converts microseconds to Duration.
def FromMicroseconds(self, micros): """Converts microseconds to Duration.""" self._NormalizeDuration( micros // _MICROS_PER_SECOND, (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND)
Converts milliseconds to Duration.
def FromMilliseconds(self, millis): """Converts milliseconds to Duration.""" self._NormalizeDuration( millis // _MILLIS_PER_SECOND, (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND)
Converts Duration to timedelta.
def ToTimedelta(self): """Converts Duration to timedelta.""" return timedelta( seconds=self.seconds, microseconds=_RoundTowardZero( self.nanos, _NANOS_PER_MICROSECOND))
Convertd timedelta to Duration.
def FromTimedelta(self, td): """Convertd timedelta to Duration.""" self._NormalizeDuration(td.seconds + td.days * _SECONDS_PER_DAY, td.microseconds * _NANOS_PER_MICROSECOND)
Set Duration by seconds and nonas.
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
Converts FieldMask to string according to proto3 JSON spec.
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)
Checks whether the FieldMask is valid for Message Descriptor.
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
Gets all direct fields of Message Descriptor to FieldMask.
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)
Merges mask1 and mask2 into this FieldMask.
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)
Intersects mask1 and mask2 into this FieldMask.
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...
Merges fields specified in FieldMask from source to destination.
def MergeMessage( self, source, destination, replace_message_field=False, replace_repeated_field=False): """Merges fields specified in FieldMask from source to destination. Args: source: Source message. destination: The destination message to be merged into. replace_message_field:...
Adds a field path into the tree.
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 means the tree already matches the given path so nothing will be added to the tree. If the path matches an existing non-leaf node in the ...
Calculates the intersection part of a field path with this tree.
def IntersectPath(self, path, intersection): """Calculates the intersection part of a field path with this tree. Args: path: The field path to calculates. intersection: The out tree to record the intersection part. """ node = self._root for name in path.split('.'): if name not in ...
Adds leaf nodes begin with prefix to this tree.
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])
Merge all fields specified by this tree from source to destination.
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)
Configures a new resource compilation command specific to a condition usually a toolset selection condition. The possible options are:
def configure (command = None, condition = None, options = None): """ Configures a new resource compilation command specific to a condition, usually a toolset selection condition. The possible options are: * <rc-type>(rc|windres) - Indicates the type of options the command ...
Convert a Nu Support Vector Regression ( NuSVR ) model to the protobuf spec. Parameters ---------- model: NuSVR A trained NuSVR encoder model.
def convert(model, feature_names, target): """Convert a Nu Support Vector Regression (NuSVR) model to the protobuf spec. Parameters ---------- model: NuSVR A trained NuSVR encoder model. feature_names: [str] Name of the input columns. target: str Name of the output colu...
Create a: class: ~turicreate. linear_regression. LinearRegression to predict a scalar target variable as a linear function of one or more features. In addition to standard numeric and categorical types features can also be extracted automatically from list - or dictionary - type SFrame columns.
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 = _DEFAULT_SOLVER_OPTIONS['lbfgs_memory_level'...
Export the model in Core ML format.
def export_coreml(self, filename): """ Export the model in Core ML format. Parameters ---------- filename: str A valid filename where the model can be saved. Examples -------- >>> model.export_coreml("MyModel.mlmodel") """ from ...
Return target value predictions for dataset using the trained linear regression model. This method can be used to get fitted values for the model by inputting the training dataset.
def predict(self, dataset, missing_value_action='auto'): """ Return target value predictions for ``dataset``, using the trained linear regression model. This method can be used to get fitted values for the model by inputting the training dataset. Parameters ---------- ...
r Evaluate the model by making target value predictions and comparing to actual values.
def evaluate(self, dataset, metric='auto', missing_value_action='auto'): r"""Evaluate the model by making target value predictions and comparing to actual values. Two metrics are used to evaluate linear regression models. The first is root-mean-squared error (RMSE) while the second is ...
Convert array into a sequence of successive possibly overlapping frames.
def frame(data, window_length, hop_length): """Convert array into a sequence of successive possibly overlapping frames. An n-dimensional array of shape (num_samples, ...) is converted into an (n+1)-D array of shape (num_frames, window_length, ...), where each frame starts hop_length points after the preceding ...
Calculate a periodic Hann window.
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 where every value appears twice, except the middle point for an odd-length window. Matlab calls this a "symmetric" window and np.hanning() returns ...
Calculate the short - time Fourier transform magnitude.
def stft_magnitude(signal, fft_length, hop_length=None, window_length=None): """Calculate the short-time Fourier transform magnitude. Args: signal: 1D np.array of the input time-domain signal. fft_length: Size of the FFT to apply. hop_length: Advance (in samples) b...
Return a matrix that can post - multiply spectrogram rows to make mel.
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 matrix that can post-multiply spectrogr...
Convert waveform to a log magnitude mel - frequency spectrogram.
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 magnitude mel-frequency spectrogram. ...
Creates a random SFrame with num_rows rows and randomly generated column types determined by column_codes. The output SFrame is deterministic based on random_seed. column_types is a string with each character denoting one type of column with the output SFrame having one column for each character in the string. The lege...
def generate_random_sframe(num_rows, column_codes, random_seed = 0): """ Creates a random SFrame with `num_rows` rows and randomly generated column types determined by `column_codes`. The output SFrame is deterministic based on `random_seed`. `column_types` is a string with each character denoti...
Creates a random SFrame with num_rows rows and randomly generated column types determined by column_codes. The output SFrame is deterministic based on random_seed. In addition a target column is generated with values dependent on the randomly generated features in a given row. column_types is a string with each charact...
def generate_random_regression_sframe(num_rows, column_codes, random_seed = 0, target_noise_level = 0.25): """ Creates a random SFrame with `num_rows` rows and randomly generated column types determined by `column_codes`. The output SFrame is deterministic based on `random_seed`. In addition, a ta...
Creates a random SFrame with num_rows rows and randomly generated column types determined by column_codes. The output SFrame is deterministic based on random_seed. In addition a target column is generated with values dependent on the randomly generated features in a given row. column_types is a string with each charact...
def generate_random_classification_sframe(num_rows, column_codes, num_classes, misclassification_spread = 0.25, num_extra_class_bins = None, random_seed = 0): """ Creates a random SFrame...
Input:
def infer_shapes(nn_spec, input_spec, input_shape_dict = None): """ Input: spec : mlmodel spec input_shape_dict: dictionary of string --> tuple string: input name tuple: input shape as a 5 length tuple in order (Seq, Batch, C, H, W) If inp...
Convert a svm model to the protobuf spec.
def convert(libsvm_model, feature_names, target, input_length, probability): """Convert a svm model to the protobuf spec. This currently supports: * C-SVC * nu-SVC * Epsilon-SVR * nu-SVR Parameters ---------- model_path: libsvm_model Libsvm representation of the mode...
Create an: class: ActivityClassifier model.
def create(dataset, session_id, target, features=None, prediction_window=100, validation_set='auto', max_iterations=10, batch_size=32, verbose=True): """ Create an :class:`ActivityClassifier` model. Parameters ---------- dataset : SFrame Input data which consists of `sessions` of...
Encode targets to integers in [ 0 num_classes - 1 ]
def _encode_target(data, target, mapping=None): """ Encode targets to integers in [0, num_classes - 1] """ 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
Export the model in Core ML format.
def export_coreml(self, filename): """ Export the model in Core ML format. Parameters ---------- filename: str A valid filename where the model can be saved. Examples -------- >>> model.export_coreml("MyModel.mlmodel") """ impor...
Return predictions for dataset using the trained activity classifier. Predictions can be generated as class labels or as a probability vector with probabilities for each class.
def predict(self, dataset, output_type='class', output_frequency='per_row'): """ Return predictions for ``dataset``, using the trained activity classifier. Predictions can be generated as class labels, or as a probability vector with probabilities for each class. The activity cl...
Evaluate the model by making predictions of target values and comparing these to actual values.
def evaluate(self, dataset, metric='auto'): """ Evaluate the model by making predictions of target values and comparing these to actual values. Parameters ---------- dataset : SFrame Dataset of new observations. Must include columns with the same ...
Return a classification for each prediction_window examples in the dataset using the trained activity classification model. The output SFrame contains predictions as both class labels as well as probabilities that the predicted value is the associated label.
def classify(self, dataset, output_frequency='per_row'): """ Return a classification, for each ``prediction_window`` examples in the ``dataset``, using the trained activity classification model. The output SFrame contains predictions as both class labels as well as probabilities ...
Return top - k predictions for the dataset using the trained model. Predictions are returned as an SFrame with three columns: prediction_id class and probability or rank depending on the output_type parameter.
def predict_topk(self, dataset, output_type='probability', k=3, output_frequency='per_row'): """ Return top-k predictions for the ``dataset``, using the trained model. Predictions are returned as an SFrame with three columns: `prediction_id`, `class`, and `probability`, or `rank`, depen...
Count the occurrances of the different characters in the files
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 ...
The main function of the script
def main(): """The main function of the script""" 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' ) parser.add_...
Save a protobuf model specification to file.
def save_spec(spec, filename): """ Save a protobuf model specification to file. Parameters ---------- spec: Model_pb Protobuf representation of the model filename: str File path where the spec gets saved. Examples -------- .. sourcecode:: python >>> corem...
Load a protobuf model specification from file
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 loaded as a protobuf spec. Returns ------- model_spec: Model_pb Protobuf representation of t...
Returns a list of neural network layers if the model contains any.
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. Returns ------- [NN layer] list of all layers (including layers from elements of a pipeline """ ...
Evaluate a CoreML regression model and compare against predictions from the original framework ( for testing correctness of conversion )
def evaluate_regressor(model, data, target="target", verbose=False): """ Evaluate a CoreML regression model and compare against predictions from the original framework (for testing correctness of conversion) Parameters ---------- filename: [str | MLModel] File path from which to load th...
Evaluate a CoreML classifier model and compare against predictions from the original framework ( for testing correctness of conversion ). Use this evaluation for models that don t deal with probabilities.
def evaluate_classifier(model, data, target='target', verbose=False): """ Evaluate a CoreML classifier model and compare against predictions from the original framework (for testing correctness of conversion). Use this evaluation for models that don't deal with probabilities. Parameters -------...
Evaluate a classifier specification for testing.
def evaluate_classifier_with_probabilities(model, data, probabilities='probabilities', verbose = False): """ Evaluate a classifier specification for testing. Parameters ---------- filename: [str | Model] F...
Rename a feature in the specification.
def rename_feature(spec, current_name, new_name, rename_inputs=True, rename_outputs=True): """ Rename a feature in the specification. Parameters ---------- spec: Model_pb The specification containing the feature to rename. current_name: str Current name of th...
Performs cleaning steps on the data so various type comparisons can be performed correctly.
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(...
Performs a robust equality test between elements.
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): ...
Evaluate a transformer specification for testing.
def evaluate_transformer(model, input_data, reference_output, verbose=False): """ Evaluate a transformer specification for testing. Parameters ---------- spec: [str | MLModel] File from where to load the Model from (OR) a loaded version of MLModel. inpu...
Returns a list of the names of the inputs to this model.: param spec: The model protobuf specification: return: [ str ] A list of input feature names
def _get_input_names(spec): """ Returns a list of the names of the inputs to this model. :param spec: The model protobuf specification :return: [str] A list of input feature names """ retval = [feature.name for feature in spec.description.input] return retval
Compute the in degree out degree and total degree of each vertex.
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 degree counts. verbose : bool, optional If True, print progress updates. Returns ------- out :...
replace the index th emphasized text with s
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]
Override of litre. _execute ; sets up variable context before evaluating code
def _execute(self, code): """Override of litre._execute; sets up variable context before evaluating code """ self.globals['example'] = self.example eval(code, self.globals)
Compile examples on the stack whose topmost item is the last example seen but not yet handled so far.
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' # C-style comments by default; handles C++ a...
Loads jamfile at the given location. After loading project global file and jamfile needed by the loaded one will be loaded recursively. If the jamfile at that location is loaded already does nothing. Returns the project module for the Jamfile.
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 recursively. If the jamfile at that location is loaded already, does nothing. Returns the project module for the Jamfile.""" ...
Loads parent of Jamfile at location. Issues an error if nothing is found.
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 "er...
Given name which can be project - id or plain directory name return project module corresponding to that id or directory. Returns nothing of project is not found.
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 directory. Returns nothing of project is not found.""" assert isinstance(name, basestring) assert isinstance(current_location...
Returns the name of module corresponding to jamfile - location. If no module corresponds to location yet associates default module name with that location.
def module_name(self, jamfile_location): """Returns the name of module corresponding to 'jamfile-location'. If no module corresponds to location yet, associates default module name with that location.""" assert isinstance(jamfile_location, basestring) module = self.location2modul...
Find the Jamfile at the given location. This returns the exact names of all the Jamfiles in the given directory. The optional parent - root argument causes this to search not the given directory but the ones above it up to the directory given in it.
def find_jamfile (self, dir, parent_root=0, no_errors=0): """Find the Jamfile at the given location. This returns the exact names of all the Jamfiles in the given directory. The optional parent-root argument causes this to search not the given directory but the ones above it up to the di...
Load a Jamfile at the given directory. Returns nothing. Will attempt to load the file as indicated by the JAMFILE patterns. Effect of calling this rule twice with the same dir is underfined.
def load_jamfile(self, dir, jamfile_module): """Load a Jamfile at the given directory. Returns nothing. Will attempt to load the file as indicated by the JAMFILE patterns. Effect of calling this rule twice with the same 'dir' is underfined.""" assert isinstance(dir, basestring) a...
Loads file as standalone project that has no location associated with it. This is mostly useful for user - config. jam which should be able to define targets but although it has some location in filesystem we do not want any build to happen in user s HOME for example.
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-config.jam, which should be able to define targets, but although it has some location in filesystem, we do not want any build to...
Initialize the module for a project.
def initialize(self, module_name, location=None, basename=None, standalone_path=''): """Initialize the module for a project. module-name is the name of the project module. location is the location (directory) of the project to initialize. If not specified, standalone project wi...
Make project - module inherit attributes of project root and parent module.
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_m...
Associate the given id with the given project module.
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
Temporary changes the current project to project. Should be followed by pop - current.
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.curren...
Returns the value of the specified attribute in the specified jamfile module.
def attribute(self, project, attribute): """Returns the value of the specified attribute in the specified jamfile module.""" assert isinstance(project, basestring) assert isinstance(attribute, basestring) try: return self.module2attributes[project].get(attribute) ...
Returns the value of the specified attribute in the specified jamfile module.
def attributeDefault(self, project, attribute, default): """Returns the value of the specified attribute in the specified jamfile module.""" assert isinstance(project, basestring) assert isinstance(attribute, basestring) assert isinstance(default, basestring) or default is None ...
Returns the project target corresponding to the project - module.
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(p...
Makes rule name available to all subsequently loaded Jamfiles.
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_)
Recursively walks through the b2/ src subdirectories and creates an index of base module name to package name. The index is stored within self. __python_module_cache and allows for an O ( 1 ) module lookup.
def __build_python_module_cache(self): """Recursively walks through the b2/src subdirectories and creates an index of base module name to package name. The index is stored within self.__python_module_cache and allows for an O(1) module lookup. For example, given the base module ...