INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Create a summary string for the accessible fields in a model. Unlike `_toolkit_repr_print`, this function does not look up the values of the fields, it just formats the names and descriptions. Parameters ---------- field_descriptions : dict{str: str} Name of each field and its description, ...
def _summarize_accessible_fields(field_descriptions, width=40, section_title='Accessible fields'): """ Create a summary string for the accessible fields in a model. Unlike `_toolkit_repr_print`, this function does not look up the values of the fields, it just formats the...
Returns true if datatype_instance is a valid datatype object and false otherwise.
def _is_valid_datatype(datatype_instance): """ Returns true if datatype_instance is a valid datatype object and false otherwise. """ # Remap so we can still use the python types for the simple cases global _simple_type_remap if datatype_instance in _simple_type_remap: return True #...
Translates a user specified datatype to an instance of the ones defined above. Valid data types are passed through, and the following type specifications are translated to the proper instances: str, "String" -> String() int, "Int64" -> Int64() float, "Double" -> Double() If a data type is not...
def _normalize_datatype(datatype_instance): """ Translates a user specified datatype to an instance of the ones defined above. Valid data types are passed through, and the following type specifications are translated to the proper instances: str, "String" -> String() int, "Int64" -> Int64() ...
Convert a boosted tree model to protobuf format. Parameters ---------- decision_tree : GradientBoostingClassifier A trained scikit-learn tree model. feature_names: [str] Name of the input columns. target: str Name of the output column. Returns ------- model_sp...
def convert(model, feature_names, target): """Convert a boosted tree model to protobuf format. Parameters ---------- decision_tree : GradientBoostingClassifier A trained scikit-learn tree model. feature_names: [str] Name of the input columns. target: str Name of the ou...
Returns all symbols defined in an ast node. if ctx_types is given, then restrict the symbols to ones with that context. :param node: ast node :param ctx_types: type or tuple of types that may be found assigned to the `ctx` attribute of an ast Name node.
def get_symbols(node, ctx_types=(ast.Load, ast.Store)): ''' Returns all symbols defined in an ast node. if ctx_types is given, then restrict the symbols to ones with that context. :param node: ast node :param ctx_types: type or tuple of types that may be found assigned to the `ctx` attrib...
Given a list of objects, reorder them so that the constains specified by 'add_pair' are satisfied. The algorithm was adopted from an awk script by Nikita Youshchenko (yoush at cs dot msu dot su)
def order (self, objects): """ Given a list of objects, reorder them so that the constains specified by 'add_pair' are satisfied. The algorithm was adopted from an awk script by Nikita Youshchenko (yoush at cs dot msu dot su) """ # The algorithm used is the s...
Eliminate constraints which mention objects not in 'objects'. In graph-theory terms, this is finding subgraph induced by ordered vertices.
def __eliminate_unused_constraits (self, objects): """ Eliminate constraints which mention objects not in 'objects'. In graph-theory terms, this is finding subgraph induced by ordered vertices. """ result = [] for c in self.constraints_: if c [0] in ob...
Returns true if there's no constraint in 'constraints' where 'obj' comes second.
def __has_no_dependents (self, obj, constraints): """ Returns true if there's no constraint in 'constraints' where 'obj' comes second. """ failed = False while constraints and not failed: c = constraints [0] if c [1] == obj: failed = T...
Helper for as_path, below. Orders properties with the implicit ones first, and within the two sections in alphabetical order of feature name.
def path_order (x, y): """ Helper for as_path, below. Orders properties with the implicit ones first, and within the two sections in alphabetical order of feature name. """ if x == y: return 0 xg = get_grist (x) yg = get_grist (y) if yg and not xg: return -1 ...
Refines 'properties' by overriding any non-free properties for which a different value is specified in 'requirements'. Conditional requirements are just added without modification. Returns the resulting list of properties.
def refine (properties, requirements): """ Refines 'properties' by overriding any non-free properties for which a different value is specified in 'requirements'. Conditional requirements are just added without modification. Returns the resulting list of properties. """ assert is_iter...
Interpret all path properties in 'properties' as relative to 'path' The property values are assumed to be in system-specific form, and will be translated into normalized form.
def translate_paths (properties, path): """ Interpret all path properties in 'properties' as relative to 'path' The property values are assumed to be in system-specific form, and will be translated into normalized form. """ assert is_iterable_typed(properties, Property) result = [] ...
Assumes that all feature values that start with '@' are names of rules, used in 'context-module'. Such rules can be either local to the module or global. Qualified local rules with the name of the module.
def translate_indirect(properties, context_module): """Assumes that all feature values that start with '@' are names of rules, used in 'context-module'. Such rules can be either local to the module or global. Qualified local rules with the name of the module.""" assert is_iterable_typed(properties, ...
Exit with error if any of the properties is not valid. properties may be a single property or a sequence of properties.
def validate (properties): """ Exit with error if any of the properties is not valid. properties may be a single property or a sequence of properties. """ if isinstance(properties, Property): properties = [properties] assert is_iterable_typed(properties, Property) for p in properties...
If 'property' is conditional property, returns condition and the property, e.g <variant>debug,<toolset>gcc:<inlining>full will become <variant>debug,<toolset>gcc <inlining>full. Otherwise, returns empty string.
def split_conditional (property): """ If 'property' is conditional property, returns condition and the property, e.g <variant>debug,<toolset>gcc:<inlining>full will become <variant>debug,<toolset>gcc <inlining>full. Otherwise, returns empty string. """ assert isinstance(prope...
Selects properties which correspond to any of the given features.
def select (features, properties): """ Selects properties which correspond to any of the given features. """ assert is_iterable_typed(properties, basestring) result = [] # add any missing angle brackets features = add_grist (features) return [p for p in properties if get_grist(p) in featur...
Removes all conditional properties which conditions are not met For those with met conditions, removes the condition. Properies in conditions are looked up in 'context'
def evaluate_conditionals_in_context (properties, context): """ Removes all conditional properties which conditions are not met For those with met conditions, removes the condition. Properies in conditions are looked up in 'context' """ if __debug__: from .property_set import Propert...
Returns a modified version of properties with all values of the given feature replaced by the given value. If 'value' is None the feature will be removed.
def change (properties, feature, value = None): """ Returns a modified version of properties with all values of the given feature replaced by the given value. If 'value' is None the feature will be removed. """ assert is_iterable_typed(properties, basestring) assert isinstance(feature, b...
Exit with error if property is not valid.
def __validate1 (property): """ Exit with error if property is not valid. """ assert isinstance(property, Property) msg = None if not property.feature.free: feature.validate_value_string (property.feature, property.value)
Returns a property sets which include all the elements in 'properties' that do not have attributes listed in 'attributes'.
def remove(attributes, properties): """Returns a property sets which include all the elements in 'properties' that do not have attributes listed in 'attributes'.""" if isinstance(attributes, basestring): attributes = [attributes] assert is_iterable_typed(attributes, basestring) assert is_ite...
Returns a property set which include all properties in 'properties' that have any of 'attributes'.
def take(attributes, properties): """Returns a property set which include all properties in 'properties' that have any of 'attributes'.""" assert is_iterable_typed(attributes, basestring) assert is_iterable_typed(properties, basestring) result = [] for e in properties: if b2.util.set.int...
Associate value with properties.
def insert (self, properties, value): """ Associate value with properties. """ assert is_iterable_typed(properties, basestring) assert isinstance(value, basestring) self.__properties.append(properties) self.__values.append(value)
Benchmark one command execution
def benchmark_command(cmd, progress): """Benchmark one command execution""" full_cmd = '/usr/bin/time --format="%U %M" {0}'.format(cmd) print '{0:6.2f}% Running {1}'.format(100.0 * progress, full_cmd) (_, err) = subprocess.Popen( ['/bin/sh', '-c', full_cmd], stdin=subprocess.PIPE, ...
Benchmark one file
def benchmark_file( filename, compiler, include_dirs, (progress_from, progress_to), iter_count, extra_flags = ''): """Benchmark one file""" time_sum = 0 mem_sum = 0 for nth_run in xrange(0, iter_count): (time_spent, mem_used) = benchmark_command( '{0} -std=c++11 {1} -...
Determine the name + version of the compiler
def compiler_info(compiler): """Determine the name + version of the compiler""" (out, err) = subprocess.Popen( ['/bin/sh', '-c', '{0} -v'.format(compiler)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ).communicate('') gcc_clang = re.compile('(g...
Enumartes the files in path with the given extension
def files_in_dir(path, extension): """Enumartes the files in path with the given extension""" ends = '.{0}'.format(extension) return (f for f in os.listdir(path) if f.endswith(ends))
Format a duration
def format_time(seconds): """Format a duration""" minute = 60 hour = minute * 60 day = hour * 24 week = day * 7 result = [] for name, dur in [ ('week', week), ('day', day), ('hour', hour), ('minute', minute), ('second', 1) ]: if seconds > dur: ...
Do the benchmarking
def benchmark(src_dir, compiler, include_dirs, iter_count): """Do the benchmarking""" files = list(files_in_dir(src_dir, 'cpp')) random.shuffle(files) has_string_templates = True string_template_file_cnt = sum(1 for file in files if 'bmp' in file) file_count = len(files) + string_template_file_...
Plot a diagram
def plot(values, mode_names, title, (xlabel, ylabel), out_file): """Plot a diagram""" matplotlib.pyplot.clf() for mode, mode_name in mode_names.iteritems(): vals = values[mode] matplotlib.pyplot.plot( [x for x, _ in vals], [y for _, y in vals], label=mode_...
Enumerate all configs in src_dir
def configs_in(src_dir): """Enumerate all configs in src_dir""" for filename in files_in_dir(src_dir, 'json'): with open(os.path.join(src_dir, filename), 'rb') as in_f: yield json.load(in_f)
Join the list of images into the out file
def join_images(img_files, out_file): """Join the list of images into the out file""" images = [PIL.Image.open(f) for f in img_files] joined = PIL.Image.new( 'RGB', (sum(i.size[0] for i in images), max(i.size[1] for i in images)) ) left = 0 for img in images: joined.paste...
Plot temporary diagrams
def plot_temp_diagrams(config, results, temp_dir): """Plot temporary diagrams""" display_name = { 'time': 'Compilation time (s)', 'memory': 'Compiler memory usage (MB)', } files = config['files'] img_files = [] if any('slt' in result for result in results) and 'bmp' in files.va...
Plot one diagram
def plot_diagram(config, results, images_dir, out_filename): """Plot one diagram""" img_files = plot_temp_diagrams(config, results, images_dir) join_images(img_files, out_filename) for img_file in img_files: os.remove(img_file)
Plot all diagrams specified by the configs
def plot_diagrams(results, configs, compiler, out_dir): """Plot all diagrams specified by the configs""" compiler_fn = make_filename(compiler) total = psutil.virtual_memory().total # pylint:disable=I0011,E1101 memory = int(math.ceil(byte_to_gb(total))) images_dir = os.path.join(out_dir, 'images') ...
The main function of the script
def main(): """The main function of the script""" desc = 'Benchmark the files generated by generate.py' parser = argparse.ArgumentParser(description=desc) parser.add_argument( '--src', dest='src_dir', default='generated', help='The directory containing the sources to benc...
Load any Turi Create model that was previously saved. This function assumes the model (can be any model) was previously saved in Turi Create model format with model.save(filename). Parameters ---------- location : string Location of the model to load. Can be a local path or a remote URL. ...
def load_model(location): """ Load any Turi Create model that was previously saved. This function assumes the model (can be any model) was previously saved in Turi Create model format with model.save(filename). Parameters ---------- location : string Location of the model to load. ...
Internal function to return a get_default_options function. Parameters ---------- unity_server_model_name: str Name of the class/toolkit as registered with the unity server module_name: str, optional Name of the module. python_class_name: str, optional Name of the Python c...
def _get_default_options_wrapper(unity_server_model_name, module_name='', python_class_name='', sdk_model = False): """ Internal function to return a get_default_options function. Parameters ---------- u...
Clear the module state. This is mainly for testing purposes. Note that this must be called _after_ resetting the module 'feature'.
def reset (): """ Clear the module state. This is mainly for testing purposes. Note that this must be called _after_ resetting the module 'feature'. """ global __had_unspecified_value, __had_value, __declared_subfeature global __init_loc global __all_signatures, __debug_configuration, __show...
The rule for checking toolset parameters. Trailing parameters should all be parameter name/value pairs. The rule will check that each parameter either has a value in each invocation or has no value in each invocation. Also, the rule will check that the combination of all parameter values is uniq...
def check_init_parameters(toolset, requirement, *args): """ The rule for checking toolset parameters. Trailing parameters should all be parameter name/value pairs. The rule will check that each parameter either has a value in each invocation or has no value in each invocation. Also, the rule ...
A helper rule to get the command to invoke some tool. If 'user-provided-command' is not given, tries to find binary named 'tool' in PATH and in the passed 'additional-path'. Otherwise, verifies that the first element of 'user-provided-command' is an existing program. This rule returns t...
def get_invocation_command_nodefault( toolset, tool, user_provided_command=[], additional_paths=[], path_last=False): """ A helper rule to get the command to invoke some tool. If 'user-provided-command' is not given, tries to find binary named 'tool' in PATH and in the passed 'additional...
Same as get_invocation_command_nodefault, except that if no tool is found, returns either the user-provided-command, if present, or the 'tool' parameter.
def get_invocation_command(toolset, tool, user_provided_command = [], additional_paths = [], path_last = False): """ Same as get_invocation_command_nodefault, except that if no tool is found, returns either the user-provided-command, if present, or the 'tool' parameter. """ ...
Given an invocation command, return the absolute path to the command. This works even if commnad has not path element and is present in PATH.
def get_absolute_tool_path(command): """ Given an invocation command, return the absolute path to the command. This works even if commnad has not path element and is present in PATH. """ assert isinstance(command, basestring) if os.path.dirname(command): return os.path.di...
Attempts to find tool (binary) named 'name' in PATH and in 'additional-paths'. If found in path, returns 'name'. If found in additional paths, returns full name. If the tool is found in several directories, returns the first path found. Otherwise, returns the empty string. If 'path_l...
def find_tool(name, additional_paths = [], path_last = False): """ Attempts to find tool (binary) named 'name' in PATH and in 'additional-paths'. If found in path, returns 'name'. If found in additional paths, returns full name. If the tool is found in several directories, returns the fir...
Checks if 'command' can be found either in path or is a full name to an existing file.
def check_tool_aux(command): """ Checks if 'command' can be found either in path or is a full name to an existing file. """ assert isinstance(command, basestring) dirname = os.path.dirname(command) if dirname: if os.path.exists(command): return command # Both NT a...
Checks that a tool can be invoked by 'command'. If command is not an absolute path, checks if it can be found in 'path'. If comand is absolute path, check that it exists. Returns 'command' if ok and empty string otherwise.
def check_tool(command): """ Checks that a tool can be invoked by 'command'. If command is not an absolute path, checks if it can be found in 'path'. If comand is absolute path, check that it exists. Returns 'command' if ok and empty string otherwise. """ assert is_iterable_typed(com...
Handle common options for toolset, specifically sets the following flag variables: - CONFIG_COMMAND to 'command' - OPTIOns for compile to the value of <compileflags> in options - OPTIONS for compile.c to the value of <cflags> in options - OPTIONS for compile.c++ to the value of <...
def handle_options(tool, condition, command, options): """ Handle common options for toolset, specifically sets the following flag variables: - CONFIG_COMMAND to 'command' - OPTIOns for compile to the value of <compileflags> in options - OPTIONS for compile.c to the value of <cflags>...
returns the location of the "program files" directory on a windows platform
def get_program_files_dir(): """ returns the location of the "program files" directory on a windows platform """ ProgramFiles = bjam.variable("ProgramFiles") if ProgramFiles: ProgramFiles = ' '.join(ProgramFiles) else: ProgramFiles = "c:\\Program Files" return ProgramFile...
Returns the command needed to set an environment variable on the current platform. The variable setting persists through all following commands and is visible in the environment seen by subsequently executed commands. In other words, on Unix systems, the variable is exported, which is consistent...
def variable_setting_command(variable, value): """ Returns the command needed to set an environment variable on the current platform. The variable setting persists through all following commands and is visible in the environment seen by subsequently executed commands. In other words,...
Returns a command to sets a named shell path variable to the given NATIVE paths on the current platform.
def path_variable_setting_command(variable, paths): """ Returns a command to sets a named shell path variable to the given NATIVE paths on the current platform. """ assert isinstance(variable, basestring) assert is_iterable_typed(paths, basestring) sep = os.path.pathsep return va...
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(variable, basestring) assert is_iterable_typed(paths, basestring) return path_variable_setting_command( ...
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...
def format_name(format, name, target_type, prop_set): """ 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 informatio...
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 and False if it already exists. Reports an error if the configuration is 'used'. """ assert isinstance(id, basestring) if id in self.used_: ...
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, {})[id] = value
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_indices = get_gpu_ids_in_use(max_devices=max_devices) gpus = _get_cuda_gpus() return [gpus[index] ...
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 ...
def make_unity_server_env(): """ 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: ...
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)) def errcheck_bool(result, func, args): if not result: ...
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, along with the output of os.lstat for each. This is useful for debugging purposes. """ "Dumping Installation Directory Structure for Debugging: " import sys,...
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_classpath(classpath): """ 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...
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.modules[__name__].__file__))[0])[1] assert __lib_name in ["sframe", "turicreate"] return __...
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_name = get_library_name() assert __lib_name in ["sframe", "turicreate"] __default_config_...
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 to test it. """ from os.path import exists config_file = get_config_file() if not exists(config_file): return ...
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 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. """ filename = get_confi...
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 wrapper function exists only to be able to pass the service # instance to the method that ...
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...
def _CallMethod(self, srvc, method_descriptor, rpc_controller, request, callback): """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. ...
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_descriptor): """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 ...
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_descriptor): """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 specifie...
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 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. """ return l...
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 cls.__init__ = _ServiceStubInit for method in self.descriptor.methods: ...
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...
def _StubMethod(self, stub, method_descriptor, rpc_controller, request, callback): """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 me...
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' ...
def MessageToString(message, as_utf8=False, as_one_line=False, pointy_brackets=False, use_index_order=False, float_format=None, use_field_number=False, descriptor_pool=None, ...
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, float_format=None): """Print ...
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(type_name, descriptor_pool): """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 wa...
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 ...
def Parse(text, message, allow_unknown_extension=False, allow_field_number=False, descriptor_pool=None): """Parses a text representation of a protocol message into a message. Args: text: Message text representation. message: A protocol buffer message to merge into. ...
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 of this field. # If this field is not a message, there should be a ":" between the # field name and the field value and a...
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('['): # Consume extension name. tokenizer.ConsumeIdentifier() while tokenizer.TryConsume('.'): tokenizer.Consume...
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.Consume('{') delimiter = '}' while not tokenizer.LookingAt('>') and not tokenizer.LookingAt('...
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: ParseError: In case an invalid field value is found. """ # String/bytes tokens can come in multiple adjacent string literals. # If we can consume one, consume as ma...
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...
def _ConsumeInteger(tokenizer, is_signed=False, is_long=False): """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. ...
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=False): """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 val...
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): """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. ...
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: ValueError: If a floating point number couldn't be parsed. """ try: # Assume Python compatible syntax. return float(text) except ValueError: # Check alternative...
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): """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 pa...
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: packed_message.MergeFromString(message.value) ...
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.descriptor_pool and self._TryPrintAsAnyMessage(message)): return fields = message.ListFi...
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.containing_type.GetOptions().message_se...
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 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. """ tokenizer = ...
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 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. """ message_...
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() tokenizer.Consume('.') tokenizer.ConsumeIdentifier() 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...
def _MergeScalarField(self, tokenizer, message, field): """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 cas...
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 identifier couldn't be consumed. """ result = self.token if not self._IDENTIFIER_OR_NUMBER.match(result): raise self.ParseError('Expected ...
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 self.token == token: self.NextToken() return True return False
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 previous token on the line. just_started = self._line == 0 and self....
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: True if the value should be returned as a long integer. Returns: The integer parsed. Raises: ParseError: If an integer couldn't be consumed. """ try: result = _ParseAbstractInteger(se...
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_bytes = self.ConsumeByteString() try: return six.text_type(the_bytes, 'utf-8') except UnicodeDecodeError as e: raise ...
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 value couldn't be consumed. """ the_list = [self._ConsumeSingleByteString()] while self.token and self.token[0] in _QUOTES: the_list.appen...
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 = self._TOKEN.match(self._current_line...
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 ...
def create(dataset, target, features=None, validation_set='auto', max_depth=6, min_loss_reduction=0.0, min_child_weight=0.1, verbose=True, random_seed = None, metric = 'auto', **kwargs): """ Create a :class:`~turicreate.deci...