Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def check_header_comment(filename): # Check input file. name = os.path.basename( filename ) # Read content of input file. sourcefile = open( filename, "rU" ) content = sourcefile.read() sourcefile.close() # Search content for '$Id$'. matc...
[ "Checks if the header-comment of the given file needs fixing." ]
Please provide a description of the function:def check_input_files_for_variadic_seq(headerDir, sourceDir): # Check input files in include/source-directories. files = glob.glob( os.path.join( headerDir, "*.hpp" ) ) files += glob.glob( os.path.join( headerDir, "aux_", "*.hpp" ) ) files += glob.glob(...
[ "Checks if files, used as input when pre-processing MPL-containers in their variadic form, need fixing." ]
Please provide a description of the function:def check_input_files_for_numbered_seq(sourceDir, suffix, containers): # Check input files for each MPL-container type. for container in containers: files = glob.glob( os.path.join( sourceDir, container, container + '*' + suffix ) ) for currentFi...
[ "Check if files, used as input when pre-processing MPL-containers in their numbered form, need fixing." ]
Please provide a description of the function:def check_input_files(headerDir, sourceDir, containers=['vector', 'list', 'set', 'map'], seqType='both', verbose=False): # Check the input files for containers in their variadic form. result1 = False if seqType == "both" or seqType == "...
[ "Checks if source- and header-files, used as input when pre-processing MPL-containers, need fixing." ]
Please provide a description of the function:def fix_header_comment(filename, timestamp): # Fix input file. name = os.path.basename( filename ) for line in fileinput.input( filename, inplace=1, mode="rU" ): # If header-comment already contains anything for '$Id$', remove it. line = re.s...
[ "Fixes the header-comment of the given file." ]
Please provide a description of the function:def fix_input_files_for_variadic_seq(headerDir, sourceDir, timestamp): # Fix files in include/source-directories. files = glob.glob( os.path.join( headerDir, "*.hpp" ) ) files += glob.glob( os.path.join( headerDir, "aux_", "*.hpp" ) ) files += glob.glob...
[ "Fixes files used as input when pre-processing MPL-containers in their variadic form." ]
Please provide a description of the function:def fix_input_files_for_numbered_seq(sourceDir, suffix, timestamp, containers): # Fix input files for each MPL-container type. for container in containers: files = glob.glob( os.path.join( sourceDir, container, container + '*' + suffix ) ) for cu...
[ "Fixes files used as input when pre-processing MPL-containers in their numbered form." ]
Please provide a description of the function:def fix_input_files(headerDir, sourceDir, containers=['vector', 'list', 'set', 'map'], seqType='both', verbose=False): # The new modification time. timestamp = datetime.datetime.now(); # Fix the input files for containers in their variadi...
[ "Fixes source- and header-files used as input when pre-processing MPL-containers." ]
Please provide a description of the function:def to_existing_absolute_path(string): value = os.path.abspath(string) if not os.path.exists( value ) or not os.path.isdir( value ): msg = '"%r" is not a valid path to a directory.' % string raise argparse.ArgumentTypeError(msg) return value
[ "Converts a path into its absolute path and verifies that it exists or throws an exception." ]
Please provide a description of the function:def main(): # Prepare and run cmdline-parser. cmdlineParser = argparse.ArgumentParser( description="Fixes the input files used for pre-processing of Boost.MPL headers.") cmdlineParser.add_argument("-v", "--verbose", dest='verbose', actio...
[ "The main function." ]
Please provide a description of the function:def create(dataset, label = None, feature = None, model = 'resnet-50', verbose = True, batch_size = 64): start_time = _time.time() # Check parameters allowed_models = list(_pre_trained_models.MODELS.keys()) if _mac_ver() >= (10,14): a...
[ "\n Create a :class:`ImageSimilarityModel` model.\n\n Parameters\n ----------\n dataset : SFrame\n Input data. The column named by the 'feature' parameter will be\n extracted for modeling.\n\n label : string\n Name of the SFrame column with row labels to be used as uuid's to\n ...
Please provide a description of the function:def _load_version(cls, state, version): _tkutl._model_version_check(version, cls._PYTHON_IMAGE_SIMILARITY_VERSION) from turicreate.toolkits.nearest_neighbors import NearestNeighborsModel state['similarity_model'] = NearestNeighborsModel(state...
[ "\n A function to load a previously saved ImageClassifier\n instance.\n\n Parameters\n ----------\n unpickler : GLUnpickler\n A GLUnpickler file handler.\n\n version : int\n Version number maintained by the class writer.\n " ]
Please provide a description of the function:def query(self, dataset, label=None, k=5, radius=None, verbose=True, batch_size=64): if not isinstance(dataset, (_tc.SFrame, _tc.SArray, _tc.Image)): raise TypeError('dataset must be either an SFrame, SArray or turicreate.Image') if(batch...
[ "\n For each image, retrieve the nearest neighbors from the model's stored\n data. In general, the query dataset does not need to be the same as\n the reference data stored in the model.\n\n Parameters\n ----------\n dataset : SFrame | SArray | turicreate.Image\n ...
Please provide a description of the function:def similarity_graph(self, k=5, radius=None, include_self_edges=False, output_type='SGraph', verbose=True): return self.similarity_model.similarity_graph(k, radius, include_self_edges, output_type, verbose)
[ "\n Construct the similarity graph on the reference dataset, which is\n already stored in the model to find the top `k` similar images for each\n image in your input dataset.\n\n This is conceptually very similar to running `query` with the reference\n set, but this method is opti...
Please provide a description of the function:def export_coreml(self, filename): import numpy as _np import coremltools as _cmt from coremltools.models import datatypes as _datatypes, neural_network as _neural_network from .._mxnet._mxnet_to_coreml import _mxnet_converter ...
[ "\n Save the model in Core ML format.\n The exported model calculates the distance between a query image and\n each row of the model's stored data. It does not sort and retrieve\n the k nearest neighbors of the query image.\n\n See Also\n --------\n save\n\n E...
Please provide a description of the function:def make_graph(node, call_deps=False): ''' Create a dependency graph from an ast node. :param node: ast node. :param call_deps: if true, then the graph will create a cyclic dependence for all function calls. (i.e for `a.b(c)` a depe...
[]
Please provide a description of the function:def extract(binary): ''' Extract a code object from a binary pyc file. :param binary: a sequence of bytes from a pyc file. ''' if len(binary) <= 8: raise Exception("Binary pyc must be greater than 8 bytes (got %i)" % len(binary)) mag...
[]
Please provide a description of the function:def _VarintSize(value): if value <= 0x7f: return 1 if value <= 0x3fff: return 2 if value <= 0x1fffff: return 3 if value <= 0xfffffff: return 4 if value <= 0x7ffffffff: return 5 if value <= 0x3ffffffffff: return 6 if value <= 0x1ffffffffffff: return 7 if va...
[ "Compute the size of a varint value." ]
Please provide a description of the function:def _SignedVarintSize(value): if value < 0: return 10 if value <= 0x7f: return 1 if value <= 0x3fff: return 2 if value <= 0x1fffff: return 3 if value <= 0xfffffff: return 4 if value <= 0x7ffffffff: return 5 if value <= 0x3ffffffffff: return 6 if value <= 0...
[ "Compute the size of a signed varint value." ]
Please provide a description of the function:def _SimpleSizer(compute_value_size): def SpecificSizer(field_number, is_repeated, is_packed): tag_size = _TagSize(field_number) if is_packed: local_VarintSize = _VarintSize def PackedFieldSize(value): result = 0 for element in value...
[ "A sizer which uses the function compute_value_size to compute the size of\n each value. Typically compute_value_size is _VarintSize." ]
Please provide a description of the function:def _FixedSizer(value_size): def SpecificSizer(field_number, is_repeated, is_packed): tag_size = _TagSize(field_number) if is_packed: local_VarintSize = _VarintSize def PackedFieldSize(value): result = len(value) * value_size return ...
[ "Like _SimpleSizer except for a fixed-size field. The input is the size\n of one value." ]
Please provide a description of the function:def BytesSizer(field_number, is_repeated, is_packed): tag_size = _TagSize(field_number) local_VarintSize = _VarintSize local_len = len assert not is_packed if is_repeated: def RepeatedFieldSize(value): result = tag_size * len(value) for element ...
[ "Returns a sizer for a bytes field." ]
Please provide a description of the function:def GroupSizer(field_number, is_repeated, is_packed): tag_size = _TagSize(field_number) * 2 assert not is_packed if is_repeated: def RepeatedFieldSize(value): result = tag_size * len(value) for element in value: result += element.ByteSize() ...
[ "Returns a sizer for a group field." ]
Please provide a description of the function:def MessageSizer(field_number, is_repeated, is_packed): tag_size = _TagSize(field_number) local_VarintSize = _VarintSize assert not is_packed if is_repeated: def RepeatedFieldSize(value): result = tag_size * len(value) for element in value: ...
[ "Returns a sizer for a message field." ]
Please provide a description of the function:def MessageSetItemSizer(field_number): static_size = (_TagSize(1) * 2 + _TagSize(2) + _VarintSize(field_number) + _TagSize(3)) local_VarintSize = _VarintSize def FieldSize(value): l = value.ByteSize() return static_size + local_VarintSize(l...
[ "Returns a sizer for extensions of MessageSet.\n\n The message set message looks like this:\n message MessageSet {\n repeated group Item = 1 {\n required int32 type_id = 2;\n required string message = 3;\n }\n }\n " ]
Please provide a description of the function:def MapSizer(field_descriptor, is_message_map): # Can't look at field_descriptor.message_type._concrete_class because it may # not have been initialized yet. message_type = field_descriptor.message_type message_sizer = MessageSizer(field_descriptor.number, False,...
[ "Returns a sizer for a map field." ]
Please provide a description of the function:def _VarintEncoder(): def EncodeVarint(write, value): bits = value & 0x7f value >>= 7 while value: write(six.int2byte(0x80|bits)) bits = value & 0x7f value >>= 7 return write(six.int2byte(bits)) return EncodeVarint
[ "Return an encoder for a basic varint value (does not include tag)." ]
Please provide a description of the function:def _SignedVarintEncoder(): def EncodeSignedVarint(write, value): if value < 0: value += (1 << 64) bits = value & 0x7f value >>= 7 while value: write(six.int2byte(0x80|bits)) bits = value & 0x7f value >>= 7 return write(six.i...
[ "Return an encoder for a basic signed varint value (does not include\n tag)." ]
Please provide a description of the function:def _VarintBytes(value): pieces = [] _EncodeVarint(pieces.append, value) return b"".join(pieces)
[ "Encode the given integer as a varint and return the bytes. This is only\n called at startup time so it doesn't need to be fast." ]
Please provide a description of the function:def _SimpleEncoder(wire_type, encode_value, compute_value_size): def SpecificEncoder(field_number, is_repeated, is_packed): if is_packed: tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) local_EncodeVarint = _EncodeVarint ...
[ "Return a constructor for an encoder for fields of a particular type.\n\n Args:\n wire_type: The field's wire type, for encoding tags.\n encode_value: A function which encodes an individual value, e.g.\n _EncodeVarint().\n compute_value_size: A function which computes the size of an indivi...
Please provide a description of the function:def _StructPackEncoder(wire_type, format): value_size = struct.calcsize(format) def SpecificEncoder(field_number, is_repeated, is_packed): local_struct_pack = struct.pack if is_packed: tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELI...
[ "Return a constructor for an encoder for a fixed-width field.\n\n Args:\n wire_type: The field's wire type, for encoding tags.\n format: The format string to pass to struct.pack().\n " ]
Please provide a description of the function:def _FloatingPointEncoder(wire_type, format): value_size = struct.calcsize(format) if value_size == 4: def EncodeNonFiniteOrRaise(write, value): # Remember that the serialized form uses little-endian byte order. if value == _POS_INF: write(b'\...
[ "Return a constructor for an encoder for float fields.\n\n This is like StructPackEncoder, but catches errors that may be due to\n passing non-finite floating-point values to struct.pack, and makes a\n second attempt to encode those values.\n\n Args:\n wire_type: The field's wire type, for encoding tags.\...
Please provide a description of the function:def BoolEncoder(field_number, is_repeated, is_packed): false_byte = b'\x00' true_byte = b'\x01' if is_packed: tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) local_EncodeVarint = _EncodeVarint def EncodePackedField(write, value...
[ "Returns an encoder for a boolean field." ]
Please provide a description of the function:def StringEncoder(field_number, is_repeated, is_packed): tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) local_EncodeVarint = _EncodeVarint local_len = len assert not is_packed if is_repeated: def EncodeRepeatedField(write, value): ...
[ "Returns an encoder for a string field." ]
Please provide a description of the function:def GroupEncoder(field_number, is_repeated, is_packed): start_tag = TagBytes(field_number, wire_format.WIRETYPE_START_GROUP) end_tag = TagBytes(field_number, wire_format.WIRETYPE_END_GROUP) assert not is_packed if is_repeated: def EncodeRepeatedField(write, v...
[ "Returns an encoder for a group field." ]
Please provide a description of the function:def MessageEncoder(field_number, is_repeated, is_packed): tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) local_EncodeVarint = _EncodeVarint assert not is_packed if is_repeated: def EncodeRepeatedField(write, value): for element in v...
[ "Returns an encoder for a message field." ]
Please provide a description of the function:def MessageSetItemEncoder(field_number): start_bytes = b"".join([ TagBytes(1, wire_format.WIRETYPE_START_GROUP), TagBytes(2, wire_format.WIRETYPE_VARINT), _VarintBytes(field_number), TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED)]) end_byte...
[ "Encoder for extensions of MessageSet.\n\n The message set message looks like this:\n message MessageSet {\n repeated group Item = 1 {\n required int32 type_id = 2;\n required string message = 3;\n }\n }\n " ]
Please provide a description of the function:def MapEncoder(field_descriptor): # Can't look at field_descriptor.message_type._concrete_class because it may # not have been initialized yet. message_type = field_descriptor.message_type encode_message = MessageEncoder(field_descriptor.number, False, False) d...
[ "Encoder for extensions of MessageSet.\n\n Maps always have a wire format like this:\n message MapEntry {\n key_type key = 1;\n value_type value = 2;\n }\n repeated MapEntry map = N;\n " ]
Please provide a description of the function:def convert(model, image_input_names=[], is_bgr=False, red_bias=0.0, blue_bias=0.0, green_bias=0.0, gray_bias=0.0, image_scale=1.0, class_labels=None, predicted_feature_name=None, model_precision=_MLMODEL_FULL_PRECISION): from ...models impor...
[ "\n Convert a Caffe model to Core ML format.\n\n Parameters\n ----------\n model: str | (str, str) | (str, str, str) | (str, str, dict)\n\n A trained Caffe neural network model which can be represented as:\n\n - Path on disk to a trained Caffe model (.caffemodel)\n - A tuple of two ...
Please provide a description of the function:def _set_kernel(model, spec): def gamma_value(model): if(model.gamma == 'auto'): # auto gamma value is 1/num_features return 1/float(len(model.support_vectors_[0])) else: return model.gamma result = None ...
[ "\n Takes the sklearn SVM model and returns the spec with the protobuf kernel for that model.\n " ]
Please provide a description of the function:def append(self, data, segment=0): # Assume this case refers to an SFrame with a single column if not hasattr(data, '__iter__'): data = [data] self._builder.append(data, segment)
[ "\n Append a single row to an SFrame.\n\n Throws a RuntimeError if one or more column's type is incompatible with\n a type appended.\n\n Parameters\n ----------\n data : iterable\n An iterable representation of a single row.\n\n segment : int\n ...
Please provide a description of the function:def append_multiple(self, data, segment=0): if not hasattr(data, '__iter__'): raise TypeError("append_multiple must be passed an iterable object") tmp_list = [] # Avoid copy in cases that we are passed materialized data that is ...
[ "\n Append multiple rows to an SFrame.\n\n Throws a RuntimeError if one or more column's type is incompatible with\n a type appended.\n\n Parameters\n ----------\n data : iterable[iterable]\n A collection of multiple iterables, each representing a single row.\n\...
Please provide a description of the function:def update_location(self, ps): loc = ps.get('location') if not loc: loc = os.path.join(self.project().get('location'), self.name()) ps = ps.add_raw(["<location>" + loc]) return ps
[ "If <location> is not set, sets it based on the project data." ]
Please provide a description of the function:def targets_to_stage(self, source_targets, ps): result = [] # Traverse the dependencies, if needed. if ps.get('install-dependencies') == ['on']: source_targets = self.collect_targets(source_targets) # Filter the target ...
[ "Given the list of source targets explicitly passed to 'stage', returns the\n list of targets which must be staged." ]
Please provide a description of the function:def init_logger(): import logging as _logging import logging.config # Package level logger _logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'f...
[ "\n Initialize the logging configuration for the turicreate package.\n\n This does not affect the root logging config.\n " ]
Please provide a description of the function:def get_environment_config(): from .._connect import main as _glconnect unity = _glconnect.get_unity() return unity.list_globals(False)
[ "\n Returns all the Turi Create configuration variables that can only\n be set via environment variables.\n\n - *TURI_FILEIO_WRITER_BUFFER_SIZE*: The file write buffer size.\n - *TURI_FILEIO_READER_BUFFER_SIZE*: The file read buffer size.\n - *OMP_NUM_THREADS*: The maximum number of threads to use fo...
Please provide a description of the function:def set_log_level(level): from .._connect import main as _glconnect unity = _glconnect.get_unity() return unity.set_log_level(level)
[ "\n Sets the log level.\n Lower log levels log more.\n if level is 8, nothing is logged. If level is 0, everything is logged.\n " ]
Please provide a description of the function:def get_runtime_config(): from .._connect import main as _glconnect unity = _glconnect.get_unity() return unity.list_globals(True)
[ "\n Returns all the Turi Create configuration variables that can be set\n at runtime. See :py:func:`turicreate.config.set_runtime_config()` to set these\n values and for documentation on the effect of each variable.\n\n Returns\n -------\n Returns a dictionary of {key:value,..}\n\n See Also\n ...
Please provide a description of the function:def set_runtime_config(name, value): from .._connect import main as _glconnect unity = _glconnect.get_unity() ret = unity.set_global(name, value) if ret != "": raise RuntimeError(ret)
[ "\n Configures system behavior at runtime. These configuration values are also\n read from environment variables at program startup if available. See\n :py:func:`turicreate.config.get_runtime_config()` to get the current values for\n each variable.\n\n Note that defaults may change across versions an...
Please provide a description of the function:def load_sgraph(filename, format='binary', delimiter='auto'): if not format in ['binary', 'snap', 'csv', 'tsv']: raise ValueError('Invalid format: %s' % format) with cython_context(): g = None if format is 'binary': proxy =...
[ "\n Load SGraph from text file or previously saved SGraph binary.\n\n Parameters\n ----------\n filename : string\n Location of the file. Can be a local path or a remote URL.\n\n format : {'binary', 'snap', 'csv', 'tsv'}, optional\n Format to of the file to load.\n\n - 'binary': ...
Please provide a description of the function:def _vertex_list_to_dataframe(ls, id_column_name): assert HAS_PANDAS, 'Cannot use dataframe because Pandas is not available or version is too low.' cols = reduce(set.union, (set(v.attr.keys()) for v in ls)) df = pd.DataFrame({id_column_name: [v.vid for v in ...
[ "\n Convert a list of vertices into dataframe.\n " ]
Please provide a description of the function:def _vertex_list_to_sframe(ls, id_column_name): sf = SFrame() if type(ls) == list: cols = reduce(set.union, (set(v.attr.keys()) for v in ls)) sf[id_column_name] = [v.vid for v in ls] for c in cols: sf[c] = [v.attr.get(c) for ...
[ "\n Convert a list of vertices into an SFrame.\n " ]
Please provide a description of the function:def _edge_list_to_dataframe(ls, src_column_name, dst_column_name): assert HAS_PANDAS, 'Cannot use dataframe because Pandas is not available or version is too low.' cols = reduce(set.union, (set(e.attr.keys()) for e in ls)) df = pd.DataFrame({ src_col...
[ "\n Convert a list of edges into dataframe.\n " ]
Please provide a description of the function:def _edge_list_to_sframe(ls, src_column_name, dst_column_name): sf = SFrame() if type(ls) == list: cols = reduce(set.union, (set(v.attr.keys()) for v in ls)) sf[src_column_name] = [e.src_vid for e in ls] sf[dst_column_name] = [e.dst_vid ...
[ "\n Convert a list of edges into an SFrame.\n " ]
Please provide a description of the function:def _dataframe_to_vertex_list(df): cols = df.columns if len(cols): assert _VID_COLUMN in cols, "Vertex DataFrame must contain column %s" % _VID_COLUMN df = df[cols].T ret = [Vertex(None, _series=df[col]) for col in df] return ret ...
[ "\n Convert dataframe into list of vertices, assuming that vertex ids are stored in _VID_COLUMN.\n " ]
Please provide a description of the function:def _dataframe_to_edge_list(df): cols = df.columns if len(cols): assert _SRC_VID_COLUMN in cols, "Vertex DataFrame must contain column %s" % _SRC_VID_COLUMN assert _DST_VID_COLUMN in cols, "Vertex DataFrame must contain column %s" % _DST_VID_COLU...
[ "\n Convert dataframe into list of edges, assuming that source and target ids are stored in _SRC_VID_COLUMN, and _DST_VID_COLUMN respectively.\n " ]
Please provide a description of the function:def _vertex_data_to_sframe(data, vid_field): if isinstance(data, SFrame): # '__id' already in the sframe, and it is ok to not specify vid_field if vid_field is None and _VID_COLUMN in data.column_names(): return data if vid_field ...
[ "\n Convert data into a vertex data sframe. Using vid_field to identify the id\n column. The returned sframe will have id column name '__id'.\n " ]
Please provide a description of the function:def _edge_data_to_sframe(data, src_field, dst_field): if isinstance(data, SFrame): # '__src_vid' and '__dst_vid' already in the sframe, and # it is ok to not specify src_field and dst_field if src_field is None and dst_field is None and \ ...
[ "\n Convert data into an edge data sframe. Using src_field and dst_field to\n identify the source and target id column. The returned sframe will have id\n column name '__src_id', '__dst_id'\n " ]
Please provide a description of the function:def get_vertices(self, ids=[], fields={}, format='sframe'): if not _is_non_string_iterable(ids): ids = [ids] if type(ids) not in (list, SArray): raise TypeError('ids must be list or SArray type') with cython_context...
[ "\n get_vertices(self, ids=list(), fields={}, format='sframe')\n Return a collection of vertices and their attributes.\n\n Parameters\n ----------\n\n ids : list [int | float | str] or SArray\n List of vertex IDs to retrieve. Only vertices in this list will be\n ...
Please provide a description of the function:def get_edges(self, src_ids=[], dst_ids=[], fields={}, format='sframe'): if not _is_non_string_iterable(src_ids): src_ids = [src_ids] if not _is_non_string_iterable(dst_ids): dst_ids = [dst_ids] if type(src_ids) not ...
[ "\n get_edges(self, src_ids=list(), dst_ids=list(), fields={}, format='sframe')\n Return a collection of edges and their attributes. This function is used\n to find edges by vertex IDs, filter on edge attributes, or list in-out\n neighbors of vertex sets.\n\n Parameters\n -...
Please provide a description of the function:def add_vertices(self, vertices, vid_field=None): sf = _vertex_data_to_sframe(vertices, vid_field) with cython_context(): proxy = self.__proxy__.add_vertices(sf.__proxy__, _VID_COLUMN) return SGraph(_proxy=proxy)
[ "\n Add vertices to the SGraph. Vertices should be input as a list of\n :class:`~turicreate.Vertex` objects, an :class:`~turicreate.SFrame`, or a\n pandas DataFrame. If vertices are specified by SFrame or DataFrame,\n ``vid_field`` specifies which column contains the vertex ID. Remaining...
Please provide a description of the function:def add_edges(self, edges, src_field=None, dst_field=None): sf = _edge_data_to_sframe(edges, src_field, dst_field) with cython_context(): proxy = self.__proxy__.add_edges(sf.__proxy__, _SRC_VID_COLUMN, _DST_VID_COLUMN) retur...
[ "\n Add edges to the SGraph. Edges should be input as a list of\n :class:`~turicreate.Edge` objects, an :class:`~turicreate.SFrame`, or a\n Pandas DataFrame. If the new edges are in an SFrame or DataFrame, then\n ``src_field`` and ``dst_field`` are required to specify the columns that\n ...
Please provide a description of the function:def select_fields(self, fields): if (type(fields) is str): fields = [fields] if not isinstance(fields, list) or not all(type(x) is str for x in fields): raise TypeError('\"fields\" must be a str or list[str]') vfield...
[ "\n Return a new SGraph with only the selected fields. Other fields are\n discarded, while fields that do not exist in the SGraph are ignored.\n\n Parameters\n ----------\n fields : string | list [string]\n A single field name or a list of field names to select.\n\n ...
Please provide a description of the function:def triple_apply(self, triple_apply_fn, mutated_fields, input_fields=None): ''' Apply a transform function to each edge and its associated source and target vertices in parallel. Each edge is visited once and in parallel. Modification to verte...
[]
Please provide a description of the function:def save(self, filename, format='auto'): if format is 'auto': if filename.endswith(('.json', '.json.gz')): format = 'json' else: format = 'binary' if format not in ['binary', 'json', 'csv']: ...
[ "\n Save the SGraph to disk. If the graph is saved in binary format, the\n graph can be re-loaded using the :py:func:`load_sgraph` method.\n Alternatively, the SGraph can be saved in JSON format for a\n human-readable and portable representation.\n\n Parameters\n ----------...
Please provide a description of the function:def get_neighborhood(self, ids, radius=1, full_subgraph=True): verts = ids ## find the vertices within radius (and the path edges) for i in range(radius): edges_out = self.get_edges(src_ids=verts) edges_in = self.ge...
[ "\n Retrieve the graph neighborhood around a set of vertices, ignoring edge\n directions. Note that setting radius greater than two often results in a\n time-consuming query for a very large subgraph.\n\n Parameters\n ----------\n ids : list [int | float | str]\n ...
Please provide a description of the function:def create(dataset, target, features=None, max_iterations=10, validation_set='auto', class_weights = None, max_depth=6, step_size=0.3, min_loss_reduction=0.0, min_child_weight=0.1, row_subsample=1.0, column_su...
[ "\n Create a (binary or multi-class) classifier model of type\n :class:`~turicreate.boosted_trees_classifier.BoostedTreesClassifier` using\n gradient boosted trees (sometimes known as GBMs).\n\n Parameters\n ----------\n dataset : SFrame\n A training dataset containing feature columns and a...
Please provide a description of the function:def classify(self, dataset, missing_value_action='auto'): return super(BoostedTreesClassifier, self).classify(dataset, missing_value_action=missing_value_action)
[ "\n Return a classification, for each example in the ``dataset``, using the\n trained boosted trees model. The output SFrame contains predictions\n as class labels (0 or 1) and probabilities associated with the the example.\n\n Parameters\n ----------\n dataset : SFrame\n ...
Please provide a description of the function:def export_coreml(self, filename): from turicreate.toolkits import _coreml_utils display_name = "boosted trees classifier" short_description = _coreml_utils._mlmodel_short_description(display_name) context = {"mode" : "classification"...
[ "\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 _get(self, field): if field in self._list_fields(): return self.__proxy__.get(field) else: raise KeyError('Key \"%s\" not in model. Available fields are %s.' % (field, ', '.join(self._list_fields())))
[ "\n Return the value for the queried field.\n\n Get the value of a given field. The list of all queryable fields is\n documented in the beginning of the model class.\n\n >>> out = m._get('graph')\n\n Parameters\n ----------\n field : string\n Name of the f...
Please provide a description of the function:def _describe_fields(cls): dispatch_table = { 'ShortestPathModel': 'sssp', 'GraphColoringModel': 'graph_coloring', 'PagerankModel': 'pagerank', 'ConnectedComponentsModel': 'connected_components', 'T...
[ "\n Return a dictionary for the class fields description.\n Fields should NOT be wrapped by _precomputed_field, if necessary\n " ]
Please provide a description of the function:def _get_summary_struct(self): g = self.graph section_titles = ['Graph'] graph_summary = [(k, _precomputed_field(v)) for k, v in six.iteritems(g.summary())] sections = [graph_summary] # collect other sections resul...
[ "\n Returns a structured description of the model, including (where relevant)\n the schema of the training data, description of the training data,\n training statistics, and model hyperparameters.\n\n Returns\n -------\n sections : list (of list of tuples)\n A li...
Please provide a description of the function:def _raise_error_if_not_of_type(arg, expected_type, arg_name=None): display_name = "%s " % arg_name if arg_name is not None else "Argument " lst_expected_type = [expected_type] if \ type(expected_type) == type else expected_type err...
[ "\n Check if the input is of expected type.\n\n Parameters\n ----------\n arg : Input argument.\n\n expected_type : A type OR a list of types that the argument is expected\n to be.\n\n arg_name : The name of the variable in the function being used. No\n ...
Please provide a description of the function:def waveform_to_examples(data, sample_rate): import resampy # Convert to mono. if len(data.shape) > 1: data = np.mean(data, axis=1) # Resample to the rate assumed by VGGish. if sample_rate != vggish_params.SAMPLE_RATE: data = resampy.resample(data, s...
[ "Converts audio waveform into an array of examples for VGGish.\n\n Args:\n data: np.array of either one dimension (mono) or two dimensions\n (multi-channel, with the outer dimension representing channels).\n Each sample is generally expected to lie in the range [-1.0, +1.0],\n although this is no...
Please provide a description of the function:def wavfile_to_examples(wav_file): from scipy.io import wavfile sr, wav_data = wavfile.read(wav_file) assert wav_data.dtype == np.int16, 'Bad sample type: %r' % wav_data.dtype samples = wav_data / 32768.0 # Convert to [-1.0, +1.0] return waveform_to_examples(sa...
[ "Convenience wrapper around waveform_to_examples() for a common WAV format.\n\n Args:\n wav_file: String path to a file, or a file-like object. The file\n is assumed to contain WAV audio data with signed 16-bit PCM samples.\n\n Returns:\n See waveform_to_examples.\n " ]
Please provide a description of the function:def expand_no_defaults (property_sets): assert is_iterable_typed(property_sets, property_set.PropertySet) # First make all features and subfeatures explicit expanded_property_sets = [ps.expand_subfeatures() for ps in property_sets] # Now combine all of ...
[ " Expand the given build request by combining all property_sets which don't\n specify conflicting non-free features.\n " ]
Please provide a description of the function:def __x_product (property_sets): assert is_iterable_typed(property_sets, property_set.PropertySet) x_product_seen = set() return __x_product_aux (property_sets, x_product_seen)[0]
[ " Return the cross-product of all elements of property_sets, less any\n that would contain conflicting values for single-valued features.\n " ]
Please provide a description of the function:def __x_product_aux (property_sets, seen_features): assert is_iterable_typed(property_sets, property_set.PropertySet) assert isinstance(seen_features, set) if not property_sets: return ([], set()) properties = property_sets[0].all() these_f...
[ "Returns non-conflicting combinations of property sets.\n\n property_sets is a list of PropertySet instances. seen_features is a set of Property\n instances.\n\n Returns a tuple of:\n - list of lists of Property instances, such that within each list, no two Property instance\n have the same feature, ...
Please provide a description of the function:def looks_like_implicit_value(v): assert isinstance(v, basestring) if feature.is_implicit_value(v): return 1 else: split = v.split("-") if feature.is_implicit_value(split[0]): return 1 return 0
[ "Returns true if 'v' is either implicit value, or\n the part before the first '-' symbol is implicit value." ]
Please provide a description of the function:def from_command_line(command_line): assert is_iterable_typed(command_line, basestring) targets = [] properties = [] for e in command_line: if e[:1] != "-": # Build request spec either has "=" in it, or completely # consi...
[ "Takes the command line tokens (such as taken from ARGV rule)\n and constructs build request from it. Returns a list of two\n lists. First is the set of targets specified in the command line,\n and second is the set of requested build properties." ]
Please provide a description of the function:def regex_to_error_msg(regex): return re.sub('([^\\\\])[()]', '\\1', regex) \ .replace('[ \t]*$', '') \ .replace('^', '') \ .replace('$', '') \ .replace('[ \t]*', ' ') \ .replace('[ \t]+', ' ') \ .replace('[0-9]+', 'X'...
[ "Format a human-readable error message from a regex" ]
Please provide a description of the function:def random_chars(number): char_map = { k: v for k, v in chars.CHARS.iteritems() if not format_character(k).startswith('\\x') } char_num = sum(char_map.values()) return ( format_character(nth_char(char_map, random.randint(0, char_...
[ "Generate random characters" ]
Please provide a description of the function:def templates_in(path): ext = '.cpp' return ( Template(f[0:-len(ext)], load_file(os.path.join(path, f))) for f in os.listdir(path) if f.endswith(ext) )
[ "Enumerate the templates found in path" ]
Please provide a description of the function:def nth_char(char_map, index): for char in char_map: if index < char_map[char]: return char index = index - char_map[char] return None
[ "Returns the nth character of a character->occurrence map" ]
Please provide a description of the function:def format_character(char): if \ char in string.ascii_letters \ or char in string.digits \ or char in [ '_', '.', ':', ';', ' ', '!', '?', '+', '-', '/', '=', '<', '>', '$', '(', ')', '@', '~', '`', '|', '#', '...
[ "Returns the C-formatting of the character" ]
Please provide a description of the function:def write_file(filename, content): print 'Generating {0}'.format(filename) with open(filename, 'wb') as out_f: out_f.write(content)
[ "Create the file with the given content" ]
Please provide a description of the function:def out_filename(template, n_val, mode): return '{0}_{1}_{2}.cpp'.format(template.name, n_val, mode.identifier)
[ "Determine the output filename" ]
Please provide a description of the function:def main(): desc = 'Generate files to benchmark' parser = argparse.ArgumentParser(description=desc) parser.add_argument( '--src', dest='src_dir', default='src', help='The directory containing the templates' ) parser.ad...
[ "The main function of the script" ]
Please provide a description of the function:def convert_from(self, base): if self.identifier == 'bmp': return base elif self.identifier == 'man': result = [] prefix = 'BOOST_METAPARSE_STRING("' while True: bmp_at = base.find(prefi...
[ "Convert a BOOST_METAPARSE_STRING mode document into one with\n this mode" ]
Please provide a description of the function:def instantiate(self, value_of_n): template = Cheetah.Template.Template( self.content, searchList={'n': value_of_n} ) template.random_string = random_string return str(template)
[ "Instantiates the template" ]
Please provide a description of the function:def range(self): match = self._match(in_comment( 'n[ \t]+in[ \t]*\\[([0-9]+)\\.\\.([0-9]+)\\),[ \t]+' 'step[ \t]+([0-9]+)' )) return range( int(match.group(1)), int(match.group(2)), ...
[ "Returns the range for N" ]
Please provide a description of the function:def _match(self, regex): cregex = re.compile(regex) for line in self.content.splitlines(): match = cregex.match(line) if match: return match raise Exception('No "{0}" line in {1}.cpp'.format( ...
[ "Find the first line matching regex and return the match object" ]
Please provide a description of the function:def add_model(self, spec): if isinstance(spec, _model.MLModel): spec = spec._spec pipeline = self.spec.pipeline step_spec = pipeline.models.add() step_spec.CopyFrom(spec)
[ "\n Add a protobuf spec or :py:class:`models.MLModel` instance to the pipeline.\n\n All input features of this model must either match the input_features\n of the pipeline, or match the outputs of a previous model.\n\n Parameters\n ----------\n spec: [MLModel, Model_pb2]\n ...
Please provide a description of the function:def GetVersion(): with open(os.path.join('google', 'protobuf', '__init__.py')) as version_file: exec(version_file.read(), globals()) return __version__
[ "Gets the version from google/protobuf/__init__.py\n\n Do not import google.protobuf.__init__ directly, because an installed\n protobuf library may be loaded instead." ]
Please provide a description of the function:def generate_proto(source, require = True): if not require and not os.path.exists(source): return output = source.replace(".proto", "_pb2.py").replace("../src/", "") if (not os.path.exists(output) or (os.path.exists(source) and os.path.getmtime(s...
[ "Invokes the Protocol Compiler to generate a _pb2.py from the given\n .proto file. Does nothing if the output already exists and is newer than\n the input." ]
Please provide a description of the function:def _validate_row_label(label, column_type_map): if not isinstance(label, str): raise TypeError("The row label column name must be a string.") if not label in column_type_map.keys(): raise ToolkitError("Row label column not found in the dataset....
[ "\n Validate a row label column.\n\n Parameters\n ----------\n label : str\n Name of the row label column.\n\n column_type_map : dict[str, type]\n Dictionary mapping the name of each column in an SFrame to the type of\n the values in the column.\n " ]
Please provide a description of the function:def _robust_column_name(base_name, column_names): robust_name = base_name i = 1 while robust_name in column_names: robust_name = base_name + '.{}'.format(i) i += 1 return robust_name
[ "\n Generate a new column name that is guaranteed not to conflict with an\n existing set of column names.\n\n Parameters\n ----------\n base_name : str\n The base of the new column name. Usually this does not conflict with\n the existing column names, in which case this function simply ...
Please provide a description of the function:def _select_valid_features(dataset, features, valid_feature_types, target_column=None): if features is not None: if not hasattr(features, '__iter__'): raise TypeError("Input 'features' must be an iterable type.") ...
[ "\n Utility function for selecting columns of only valid feature types.\n\n Parameters\n ----------\n dataset: SFrame\n The input SFrame containing columns of potential features.\n\n features: list[str]\n List of feature column names. If None, the candidate feature set is\n take...
Please provide a description of the function:def _check_elements_equal(lst): assert isinstance(lst, list), "Input value must be a list." return not lst or lst.count(lst[0]) == len(lst)
[ "\n Returns true if all of the elements in the list are equal.\n " ]
Please provide a description of the function:def _validate_lists(sa, allowed_types=[str], require_same_type=True, require_equal_length=False, num_to_check=10): if len(sa) == 0: return True first_elements = sa.head(num_to_check) if first_elements.dtype != list: raise...
[ "\n For a list-typed SArray, check whether the first elements are lists that\n - contain only the provided types\n - all have the same lengths (optionally)\n\n Parameters\n ----------\n sa : SArray\n An SArray containing lists.\n\n allowed_types : list\n A list of types that are a...