text
stringlengths
81
112k
Returns a command that prepends the given paths to the named path variable on the current platform. def prepend_path_variable_command(variable, paths): """ Returns a command that prepends the given paths to the named path variable on the current platform. """ assert isinstance(varia...
Given a target, as given to a custom tag rule, returns a string formatted according to the passed format. Format is a list of properties that is represented in the result. For each element of format the corresponding target information is obtained and added to the result string. For all, but the...
Registers a configuration. Returns True if the configuration has been added and False if it already exists. Reports an error if the configuration is 'used'. def register(self, id): """ Registers a configuration. Returns True if the configuration has been added ...
Returns the value of a configuration parameter. def get(self, id, param): """ Returns the value of a configuration parameter. """ assert isinstance(id, basestring) assert isinstance(param, basestring) return self.params_.get(param, {}).get(id)
Sets the value of a configuration parameter. def set (self, id, param, value): """ Sets the value of a configuration parameter. """ assert isinstance(id, basestring) assert isinstance(param, basestring) assert is_iterable_typed(value, basestring) self.params_.setdefault(param, {...
Like get_num_gpus_in_use, but returns a list of dictionaries with just queried GPU information. def get_gpus_in_use(max_devices=None): """ Like get_num_gpus_in_use, but returns a list of dictionaries with just queried GPU information. """ from turicreate.util import _get_cuda_gpus gpu_indic...
Returns the environment for unity_server. The environment is necessary to start the unity_server by setting the proper environments for shared libraries, hadoop classpath, and module search paths for python lambda workers. The environment has 3 components: 1. CLASSPATH, contains hadoop class path ...
Sets the dll load path so that things are resolved correctly. def set_windows_dll_path(): """ Sets the dll load path so that things are resolved correctly. """ lib_path = os.path.dirname(os.path.abspath(_pylambda_worker.__file__)) lib_path = os.path.abspath(os.path.join(lib_path, os.pardir)) ...
Dumps a detailed report of the turicreate/sframe directory structure and files, along with the output of os.lstat for each. This is useful for debugging purposes. def dump_directory_structure(out = sys.stdout): """ Dumps a detailed report of the turicreate/sframe directory structure and files, alo...
Take a classpath of the form: /etc/hadoop/conf:/usr/lib/hadoop/lib/*:/usr/lib/hadoop/.//*: ... and return it expanded to all the JARs (and nothing else): /etc/hadoop/conf:/usr/lib/hadoop/lib/netty-3.6.2.Final.jar:/usr/lib/hadoop/lib/jaxb-api-2.2.2.jar: ... mentioned in the path def _get_expanded_...
Returns either sframe or turicreate depending on which library this file is bundled with. def get_library_name(): """ Returns either sframe or turicreate depending on which library this file is bundled with. """ from os.path import split, abspath __lib_name = split(split(abspath(sys.module...
Returns the file name of the config file from which the environment variables are written. def get_config_file(): """ Returns the file name of the config file from which the environment variables are written. """ import os from os.path import abspath, expanduser, join, exists __lib_nam...
Imports the environmental configuration settings from the config file, if present, and sets the environment variables to test it. def setup_environment_from_config_file(): """ Imports the environmental configuration settings from the config file, if present, and sets the environment variables t...
Writes an environment variable configuration to the current config file. This will be read in on the next restart. The config file is created if not present. Note: The variables will not take effect until after restart. def write_config_file_value(key, value): """ Writes an environment variable c...
Constructs the service class. Args: cls: The class that will be constructed. def BuildService(self, cls): """Constructs the service class. Args: cls: The class that will be constructed. """ # CallMethod needs to operate with an instance of the Service class. This # internal wrapp...
Calls the method described by a given method descriptor. Args: srvc: Instance of the service for which this method is called. method_descriptor: Descriptor that represent the method to call. rpc_controller: RPC controller to use for this method's execution. request: Request protocol message...
Returns the class of the request protocol message. Args: method_descriptor: Descriptor of the method for which to return the request protocol message class. Returns: A class that represents the input protocol message of the specified method. def _GetRequestClass(self, method_descrip...
Returns the class of the response protocol message. Args: method_descriptor: Descriptor of the method for which to return the response protocol message class. Returns: A class that represents the output protocol message of the specified method. def _GetResponseClass(self, method_des...
Generates and returns a method that can be set for a service methods. Args: method: Descriptor of the service method for which a method is to be generated. Returns: A method that can be added to the service class. def _GenerateNonImplementedMethod(self, method): """Generates and retur...
Constructs the stub class. Args: cls: The class that will be constructed. def BuildServiceStub(self, cls): """Constructs the stub class. Args: cls: The class that will be constructed. """ def _ServiceStubInit(stub, rpc_channel): stub.rpc_channel = rpc_channel self.cls = cls...
The body of all service methods in the generated stub class. Args: stub: Stub instance. method_descriptor: Descriptor of the invoked method. rpc_controller: Rpc controller to execute the method. request: Request protocol message. callback: A callback to execute when the method finishe...
Convert protobuf message to text format. Floating point values can be formatted compactly with 15 digits of precision (which is the most that IEEE 754 "double" can guarantee) using float_format='.15g'. To ensure that converting to text and back to a proto will result in an identical value, float_format='.17g' ...
Print a single field value (not including name). def PrintFieldValue(field, value, out, indent=0, as_utf8=False, as_one_line=False, pointy_brackets=False, use_index_order=False, ...
Returns a protobuf message instance. Args: type_name: Fully-qualified protobuf message type name string. descriptor_pool: DescriptorPool instance. Returns: A Message instance of type matching type_name, or None if the a Descriptor wasn't found matching type_name. def _BuildMessageFromTypeName(ty...
Parses a text representation of a protocol message into a message. Args: text: Message text representation. message: A protocol buffer message to merge into. allow_unknown_extension: if True, skip over missing extensions and keep parsing allow_field_number: if True, both field number and field ...
Skips over contents (value or message) of a field. Args: tokenizer: A tokenizer to parse the field name and values. def _SkipFieldContents(tokenizer): """Skips over contents (value or message) of a field. Args: tokenizer: A tokenizer to parse the field name and values. """ # Try to guess the type o...
Skips over a complete field (name and value/message). Args: tokenizer: A tokenizer to parse the field name and values. def _SkipField(tokenizer): """Skips over a complete field (name and value/message). Args: tokenizer: A tokenizer to parse the field name and values. """ if tokenizer.TryConsume('['...
Skips over a field message. Args: tokenizer: A tokenizer to parse the field name and values. def _SkipFieldMessage(tokenizer): """Skips over a field message. Args: tokenizer: A tokenizer to parse the field name and values. """ if tokenizer.TryConsume('<'): delimiter = '>' else: tokenizer...
Skips over a field value. Args: tokenizer: A tokenizer to parse the field name and values. Raises: ParseError: In case an invalid field value is found. def _SkipFieldValue(tokenizer): """Skips over a field value. Args: tokenizer: A tokenizer to parse the field name and values. Raises: Par...
Consumes an integer number from tokenizer. Args: tokenizer: A tokenizer used to parse the number. is_signed: True if a signed integer must be parsed. is_long: True if a long integer must be parsed. Returns: The integer parsed. Raises: ParseError: If an integer with given characteristics cou...
Parses an integer. Args: text: The text to parse. is_signed: True if a signed integer must be parsed. is_long: True if a long integer must be parsed. Returns: The integer value. Raises: ValueError: Thrown Iff the text is not a valid integer. def ParseInteger(text, is_signed=False, is_long=...
Parses an integer without checking size/signedness. Args: text: The text to parse. is_long: True if the value should be returned as a long integer. Returns: The integer value. Raises: ValueError: Thrown Iff the text is not a valid integer. def _ParseAbstractInteger(text, is_long=False): """P...
Parse a floating point number. Args: text: Text to parse. Returns: The number parsed. Raises: ValueError: If a floating point number couldn't be parsed. def ParseFloat(text): """Parse a floating point number. Args: text: Text to parse. Returns: The number parsed. Raises: Val...
Parse an enum value. The value can be specified by a number (the enum value), or by a string literal (the enum name). Args: field: Enum field descriptor. value: String value. Returns: Enum value number. Raises: ValueError: If the enum value could not be parsed. def ParseEnum(field, value)...
Serializes if message is a google.protobuf.Any field. def _TryPrintAsAnyMessage(self, message): """Serializes if message is a google.protobuf.Any field.""" packed_message = _BuildMessageFromTypeName(message.TypeName(), self.descriptor_pool) if packed_message: ...
Convert protobuf message to text format. Args: message: The protocol buffers message. def PrintMessage(self, message): """Convert protobuf message to text format. Args: message: The protocol buffers message. """ if (message.DESCRIPTOR.full_name == _ANY_FULL_TYPE_NAME and self....
Print a single field name/value pair. def PrintField(self, field, value): """Print a single field name/value pair.""" out = self.out out.write(' ' * self.indent) if self.use_field_number: out.write(str(field.number)) else: if field.is_extension: out.write('[') if (field....
Parses a text representation of a protocol message into a message. def ParseFromString(self, text, message): """Parses a text representation of a protocol message into a message.""" if not isinstance(text, str): text = text.decode('utf-8') return self.ParseLines(text.split('\n'), message)
Parses a text representation of a protocol message into a message. def ParseLines(self, lines, message): """Parses a text representation of a protocol message into a message.""" self._allow_multiple_scalars = False self._ParseOrMerge(lines, message) return message
Merges a text representation of a protocol message into a message. def MergeLines(self, lines, message): """Merges a text representation of a protocol message into a message.""" self._allow_multiple_scalars = True self._ParseOrMerge(lines, message) return message
Converts a text representation of a protocol message into a message. Args: lines: Lines of a message's text representation. message: A protocol buffer message to merge into. Raises: ParseError: On text parsing problems. def _ParseOrMerge(self, lines, message): """Converts a text represe...
Merges a single protocol message field into a message. Args: tokenizer: A tokenizer to parse the field name and values. message: A protocol message to record the data. Raises: ParseError: In case of text parsing problems. def _MergeField(self, tokenizer, message): """Merges a single pro...
Consumes a google.protobuf.Any type URL and returns the type name. def _ConsumeAnyTypeUrl(self, tokenizer): """Consumes a google.protobuf.Any type URL and returns the type name.""" # Consume "type.googleapis.com/". tokenizer.ConsumeIdentifier() tokenizer.Consume('.') tokenizer.ConsumeIdentifier() ...
Merges a single scalar field into a message. Args: tokenizer: A tokenizer to parse the field value. message: The message of which field is a member. field: The descriptor of the field to be merged. Raises: ParseError: In case of text parsing problems. def _MergeMessageField(self, toke...
Merges a single scalar field into a message. Args: tokenizer: A tokenizer to parse the field value. message: A protocol message to record the data. field: The descriptor of the field to be merged. Raises: ParseError: In case of text parsing problems. RuntimeError: On runtime erro...
Tries to consume a given piece of text. Args: token: Text to consume. Returns: True iff the text was consumed. def TryConsume(self, token): """Tries to consume a given piece of text. Args: token: Text to consume. Returns: True iff the text was consumed. """ if se...
Consumes a comment, returns a 2-tuple (trailing bool, comment str). def ConsumeCommentOrTrailingComment(self): """Consumes a comment, returns a 2-tuple (trailing bool, comment str).""" # Tokenizer initializes _previous_line and _previous_column to 0. As the # tokenizer starts, it looks like there is a pre...
Consumes protocol message field identifier. Returns: Identifier string. Raises: ParseError: If an identifier couldn't be consumed. def ConsumeIdentifier(self): """Consumes protocol message field identifier. Returns: Identifier string. Raises: ParseError: If an identifier...
Consumes protocol message field identifier. Returns: Identifier string. Raises: ParseError: If an identifier couldn't be consumed. def ConsumeIdentifierOrNumber(self): """Consumes protocol message field identifier. Returns: Identifier string. Raises: ParseError: If an id...
Consumes an integer number. Args: is_long: True if the value should be returned as a long integer. Returns: The integer parsed. Raises: ParseError: If an integer couldn't be consumed. def ConsumeInteger(self, is_long=False): """Consumes an integer number. Args: is_long: T...
Consumes a string value. Returns: The string parsed. Raises: ParseError: If a string value couldn't be consumed. def ConsumeString(self): """Consumes a string value. Returns: The string parsed. Raises: ParseError: If a string value couldn't be consumed. """ the_b...
Consumes a byte array value. Returns: The array parsed (as a string). Raises: ParseError: If a byte array value couldn't be consumed. def ConsumeByteString(self): """Consumes a byte array value. Returns: The array parsed (as a string). Raises: ParseError: If a byte array...
Reads the next meaningful token. def NextToken(self): """Reads the next meaningful token.""" self._previous_line = self._line self._previous_column = self._column self._column += len(self.token) self._SkipWhitespace() if not self._more_lines: self.token = '' return match = se...
Create a :class:`~turicreate.decision_tree_regression.DecisionTreeRegression` to predict a scalar target variable using 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. Parameters ...
Evaluate the model on the given dataset. Parameters ---------- dataset : SFrame Dataset in the same format used for training. The columns names and types of the dataset must be the same as that used in training. metric : str, optional Name of the eva...
Predict the target column of the given dataset. The target column is provided during :func:`~turicreate.decision_tree_regression.create`. If the target column is in the `dataset` it will be ignored. Parameters ---------- dataset : SFrame A dataset that has the...
Compute the value of a composite distance function on two dictionaries, typically SFrame rows. Parameters ---------- distance : list[list] A composite distance function. Composite distance functions are a weighted sum of standard distance functions, each of which applies to its ...
Check that composite distance function is in valid form. Don't modify the composite distance in any way. def _validate_composite_distance(distance): """ Check that composite distance function is in valid form. Don't modify the composite distance in any way. """ if not isinstance(distance, list...
Remove feature names from the feature lists in a composite distance function. def _scrub_composite_distance_features(distance, feature_blacklist): """ Remove feature names from the feature lists in a composite distance function. """ dist_out = [] for i, d in enumerate(distance): ft...
Convert function names in a composite distance function into function handles. def _convert_distance_names_to_functions(distance): """ Convert function names in a composite distance function into function handles. """ dist_out = _copy.deepcopy(distance) for i, d in enumerate(distance): ...
Construct a composite distance appropriate for matching address data. NOTE: this utility function does not guarantee that the output composite distance will work with a particular dataset and model. When the composite distance is applied in a particular context, the feature types and individual distance...
Builds a dictionary of all the messages available in a set of files. Args: file_protos: A sequence of file protos to build messages out of. Returns: A dictionary mapping proto names to the message classes. This will include any dependent messages as well as any messages defined in the same file as ...
Builds a proto2 message class based on the passed in descriptor. Passing a descriptor with a fully qualified name matching a previous invocation will cause the same class to be returned. Args: descriptor: The descriptor to build from. Returns: A class describing the passed in descriptor. ...
Gets all the messages from a specified file. This will find and resolve dependencies, failing if the descriptor pool cannot satisfy them. Args: files: The file names to extract messages from. Returns: A dictionary mapping proto names to the message classes. This will include any dep...
for if statements in list comprehension def refactor_ifs(stmnt, ifs): ''' for if statements in list comprehension ''' if isinstance(stmnt, _ast.BoolOp): test, right = stmnt.values if isinstance(stmnt.op, _ast.Or): test = _ast.UnaryOp(op=_ast.Not(), operand=test, lineno=0, co...
NOP def MAP_ADD(self, instr): key = self.ast_stack.pop() value = self.ast_stack.pop() self.ast_stack.append((key, value)) 'NOP'
Initializes an MpsGraphAPI for object detection. def _get_mps_od_net(input_image_shape, batch_size, output_size, anchors, config, weights={}): """ Initializes an MpsGraphAPI for object detection. """ network = _MpsGraphAPI(network_id=_MpsGraphNetworkType.kODGraphNet) c_in, h_in...
Create a :class:`ObjectDetector` model. Parameters ---------- dataset : SFrame Input data. The columns named by the ``feature`` and ``annotations`` parameters will be extracted for training the detector. annotations : string Name of the column containing the object detection an...
Predict with options for what kind of SFrame should be returned. If postprocess is False, a single numpy array with raw unprocessed results will be returned. def _predict_with_options(self, dataset, with_ground_truth, postprocess=True, confidence_threshold=0.001, ...
Takes input and returns tuple of the input in canonical form (SFrame) along with an unpack callback function that can be applied to prediction results to "undo" the canonization. def _canonize_input(self, dataset): """ Takes input and returns tuple of the input in canonical form (SFrame...
Predict object instances in an sframe of images. Parameters ---------- dataset : SFrame | SArray | turicreate.Image The images on which to perform object detection. If dataset is an SFrame, it must have a column with the same name as the feature column during...
Evaluate the model by making predictions and comparing these to ground truth bounding box annotations. Parameters ---------- dataset : SFrame Dataset of new observations. Must include columns with the same names as the annotations and feature used for model train...
Save the model in Core ML format. The Core ML model takes an image of fixed size as input and produces two output arrays: `confidence` and `coordinates`. The first one, `confidence` is an `N`-by-`C` array, where `N` is the number of instances predicted and `C` is the number of classes. ...
Parse a document title as the first line starting in [A-Za-z0-9<] or fall back to the document basename if no such line exists. The cmake --help-*-list commands also depend on this convention. Return the title or False if the document file does not exist. def parse_title(self, docname)...
Register a Python written function to for error reporting. The function is called back as f(ctx, error). def registerErrorHandler(f, ctx): """Register a Python written function to for error reporting. The function is called back as f(ctx, error). """ import sys if 'libxslt' not in sys.modules...
Intermediate callback to wrap the locator def _xmlTextReaderErrorFunc(xxx_todo_changeme,msg,severity,locator): """Intermediate callback to wrap the locator""" (f,arg) = xxx_todo_changeme return f(arg,msg,severity,xmlTextReaderLocator(locator))
Create a parser context for an HTML in-memory document. def htmlCreateMemoryParserCtxt(buffer, size): """Create a parser context for an HTML in-memory document. """ ret = libxml2mod.htmlCreateMemoryParserCtxt(buffer, size) if ret is None:raise parserError('htmlCreateMemoryParserCtxt() failed') return p...
parse an HTML in-memory document and build a tree. def htmlParseDoc(cur, encoding): """parse an HTML in-memory document and build a tree. """ ret = libxml2mod.htmlParseDoc(cur, encoding) if ret is None:raise parserError('htmlParseDoc() failed') return xmlDoc(_obj=ret)
parse an HTML file and build a tree. Automatic support for ZLIB/Compress compressed document is provided by default if found at compile-time. def htmlParseFile(filename, encoding): """parse an HTML file and build a tree. Automatic support for ZLIB/Compress compressed document is provided by defa...
parse an XML in-memory document and build a tree. def htmlReadDoc(cur, URL, encoding, options): """parse an XML in-memory document and build a tree. """ ret = libxml2mod.htmlReadDoc(cur, URL, encoding, options) if ret is None:raise treeError('htmlReadDoc() failed') return xmlDoc(_obj=ret)
parse an XML from a file descriptor and build a tree. def htmlReadFd(fd, URL, encoding, options): """parse an XML from a file descriptor and build a tree. """ ret = libxml2mod.htmlReadFd(fd, URL, encoding, options) if ret is None:raise treeError('htmlReadFd() failed') return xmlDoc(_obj=ret)
parse an XML file from the filesystem or the network. def htmlReadFile(filename, encoding, options): """parse an XML file from the filesystem or the network. """ ret = libxml2mod.htmlReadFile(filename, encoding, options) if ret is None:raise treeError('htmlReadFile() failed') return xmlDoc(_obj=ret)
parse an XML in-memory document and build a tree. def htmlReadMemory(buffer, size, URL, encoding, options): """parse an XML in-memory document and build a tree. """ ret = libxml2mod.htmlReadMemory(buffer, size, URL, encoding, options) if ret is None:raise treeError('htmlReadMemory() failed') return xml...
Creates a new HTML document def htmlNewDoc(URI, ExternalID): """Creates a new HTML document """ ret = libxml2mod.htmlNewDoc(URI, ExternalID) if ret is None:raise treeError('htmlNewDoc() failed') return xmlDoc(_obj=ret)
Creates a new HTML document without a DTD node if @URI and @ExternalID are None def htmlNewDocNoDtD(URI, ExternalID): """Creates a new HTML document without a DTD node if @URI and @ExternalID are None """ ret = libxml2mod.htmlNewDocNoDtD(URI, ExternalID) if ret is None:raise treeError('htmlNe...
Add an entry in the catalog, it may overwrite existing but different entries. If called before any other catalog routine, allows to override the default shared catalog put in place by xmlInitializeCatalog(); def catalogAdd(type, orig, replace): """Add an entry in the catalog, it may overwrite ex...
Load the catalog and build the associated data structures. This can be either an XML Catalog or an SGML Catalog It will recurse in SGML CATALOG entries. On the other hand XML Catalogs are not handled recursively. def loadACatalog(filename): """Load the catalog and build the associated data struc...
Load an SGML super catalog. It won't expand CATALOG or DELEGATE references. This is only needed for manipulating SGML Super Catalogs like adding and removing CATALOG or DELEGATE entries. def loadSGMLSuperCatalog(filename): """Load an SGML super catalog. It won't expand CATALOG or DELEGATE ...
create a new Catalog. def newCatalog(sgml): """create a new Catalog. """ ret = libxml2mod.xmlNewCatalog(sgml) if ret is None:raise treeError('xmlNewCatalog() failed') return catalog(_obj=ret)
parse an XML file and build a tree. It's like xmlParseFile() except it bypass all catalog lookups. def parseCatalogFile(filename): """parse an XML file and build a tree. It's like xmlParseFile() except it bypass all catalog lookups. """ ret = libxml2mod.xmlParseCatalogFile(filename) if ret is...
Dumps informations about the string, shorten it if necessary def debugDumpString(output, str): """Dumps informations about the string, shorten it if necessary """ if output is not None: output.flush() libxml2mod.xmlDebugDumpString(output, str)
Check whether this name is an predefined entity. def predefinedEntity(name): """Check whether this name is an predefined entity. """ ret = libxml2mod.xmlGetPredefinedEntity(name) if ret is None:raise treeError('xmlGetPredefinedEntity() failed') return xmlEntity(_obj=ret)
Setup the FTP proxy informations. This can also be done by using ftp_proxy ftp_proxy_user and ftp_proxy_password environment variables. def nanoFTPProxy(host, port, user, passwd, type): """Setup the FTP proxy informations. This can also be done by using ftp_proxy ftp_proxy_user and ftp_proxy_pas...
Creates a parser context for an XML in-memory document. def createDocParserCtxt(cur): """Creates a parser context for an XML in-memory document. """ ret = libxml2mod.xmlCreateDocParserCtxt(cur) if ret is None:raise parserError('xmlCreateDocParserCtxt() failed') return parserCtxt(_obj=ret)
Load and parse an external subset. def parseDTD(ExternalID, SystemID): """Load and parse an external subset. """ ret = libxml2mod.xmlParseDTD(ExternalID, SystemID) if ret is None:raise parserError('xmlParseDTD() failed') return xmlDtd(_obj=ret)
parse an XML in-memory document and build a tree. def parseDoc(cur): """parse an XML in-memory document and build a tree. """ ret = libxml2mod.xmlParseDoc(cur) if ret is None:raise parserError('xmlParseDoc() failed') return xmlDoc(_obj=ret)
parse an XML external entity out of context and build a tree. [78] extParsedEnt ::= TextDecl? content This correspond to a "Well Balanced" chunk def parseEntity(filename): """parse an XML external entity out of context and build a tree. [78] extParsedEnt ::= TextDecl? content This cor...
parse an XML file and build a tree. Automatic support for ZLIB/Compress compressed document is provided by default if found at compile-time. def parseFile(filename): """parse an XML file and build a tree. Automatic support for ZLIB/Compress compressed document is provided by default if fo...
parse an XML in-memory block and build a tree. def parseMemory(buffer, size): """parse an XML in-memory block and build a tree. """ ret = libxml2mod.xmlParseMemory(buffer, size) if ret is None:raise parserError('xmlParseMemory() failed') return xmlDoc(_obj=ret)
parse an XML in-memory document and build a tree. def readDoc(cur, URL, encoding, options): """parse an XML in-memory document and build a tree. """ ret = libxml2mod.xmlReadDoc(cur, URL, encoding, options) if ret is None:raise treeError('xmlReadDoc() failed') return xmlDoc(_obj=ret)