id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
29,200 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/common.py | get_invocation_command | 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.
"""
assert isinstance(toolset, basestring)
assert isinstance(tool, basestring)
assert is_iterable_typed(user_provided_command, basestring)
assert is_iterable_typed(additional_paths, basestring) or additional_paths is None
assert isinstance(path_last, (int, bool))
result = get_invocation_command_nodefault(toolset, tool,
user_provided_command,
additional_paths,
path_last)
if not result:
if user_provided_command:
result = user_provided_command[0]
else:
result = tool
assert(isinstance(result, str))
return result | python | 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.
"""
assert isinstance(toolset, basestring)
assert isinstance(tool, basestring)
assert is_iterable_typed(user_provided_command, basestring)
assert is_iterable_typed(additional_paths, basestring) or additional_paths is None
assert isinstance(path_last, (int, bool))
result = get_invocation_command_nodefault(toolset, tool,
user_provided_command,
additional_paths,
path_last)
if not result:
if user_provided_command:
result = user_provided_command[0]
else:
result = tool
assert(isinstance(result, str))
return result | [
"def",
"get_invocation_command",
"(",
"toolset",
",",
"tool",
",",
"user_provided_command",
"=",
"[",
"]",
",",
"additional_paths",
"=",
"[",
"]",
",",
"path_last",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"toolset",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"tool",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"user_provided_command",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"additional_paths",
",",
"basestring",
")",
"or",
"additional_paths",
"is",
"None",
"assert",
"isinstance",
"(",
"path_last",
",",
"(",
"int",
",",
"bool",
")",
")",
"result",
"=",
"get_invocation_command_nodefault",
"(",
"toolset",
",",
"tool",
",",
"user_provided_command",
",",
"additional_paths",
",",
"path_last",
")",
"if",
"not",
"result",
":",
"if",
"user_provided_command",
":",
"result",
"=",
"user_provided_command",
"[",
"0",
"]",
"else",
":",
"result",
"=",
"tool",
"assert",
"(",
"isinstance",
"(",
"result",
",",
"str",
")",
")",
"return",
"result"
] | 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. | [
"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",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/common.py#L323-L347 |
29,201 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/common.py | get_absolute_tool_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.dirname(command)
else:
programs = path.programs_path()
m = path.glob(programs, [command, command + '.exe' ])
if not len(m):
if __debug_configuration:
print "Could not find:", command, "in", programs
return None
return os.path.dirname(m[0]) | python | 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.dirname(command)
else:
programs = path.programs_path()
m = path.glob(programs, [command, command + '.exe' ])
if not len(m):
if __debug_configuration:
print "Could not find:", command, "in", programs
return None
return os.path.dirname(m[0]) | [
"def",
"get_absolute_tool_path",
"(",
"command",
")",
":",
"assert",
"isinstance",
"(",
"command",
",",
"basestring",
")",
"if",
"os",
".",
"path",
".",
"dirname",
"(",
"command",
")",
":",
"return",
"os",
".",
"path",
".",
"dirname",
"(",
"command",
")",
"else",
":",
"programs",
"=",
"path",
".",
"programs_path",
"(",
")",
"m",
"=",
"path",
".",
"glob",
"(",
"programs",
",",
"[",
"command",
",",
"command",
"+",
"'.exe'",
"]",
")",
"if",
"not",
"len",
"(",
"m",
")",
":",
"if",
"__debug_configuration",
":",
"print",
"\"Could not find:\"",
",",
"command",
",",
"\"in\"",
",",
"programs",
"return",
"None",
"return",
"os",
".",
"path",
".",
"dirname",
"(",
"m",
"[",
"0",
"]",
")"
] | 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. | [
"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",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/common.py#L350-L366 |
29,202 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/common.py | check_tool_aux | 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 and Cygwin will run .exe files by their unqualified names.
elif on_windows() and os.path.exists(command + '.exe'):
return command
# Only NT will run .bat files by their unqualified names.
elif os_name() == 'NT' and os.path.exists(command + '.bat'):
return command
else:
paths = path.programs_path()
if path.glob(paths, [command]):
return command | python | 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 and Cygwin will run .exe files by their unqualified names.
elif on_windows() and os.path.exists(command + '.exe'):
return command
# Only NT will run .bat files by their unqualified names.
elif os_name() == 'NT' and os.path.exists(command + '.bat'):
return command
else:
paths = path.programs_path()
if path.glob(paths, [command]):
return command | [
"def",
"check_tool_aux",
"(",
"command",
")",
":",
"assert",
"isinstance",
"(",
"command",
",",
"basestring",
")",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"command",
")",
"if",
"dirname",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"command",
")",
":",
"return",
"command",
"# Both NT and Cygwin will run .exe files by their unqualified names.",
"elif",
"on_windows",
"(",
")",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"command",
"+",
"'.exe'",
")",
":",
"return",
"command",
"# Only NT will run .bat files by their unqualified names.",
"elif",
"os_name",
"(",
")",
"==",
"'NT'",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"command",
"+",
"'.bat'",
")",
":",
"return",
"command",
"else",
":",
"paths",
"=",
"path",
".",
"programs_path",
"(",
")",
"if",
"path",
".",
"glob",
"(",
"paths",
",",
"[",
"command",
"]",
")",
":",
"return",
"command"
] | Checks if 'command' can be found either in path
or is a full name to an existing file. | [
"Checks",
"if",
"command",
"can",
"be",
"found",
"either",
"in",
"path",
"or",
"is",
"a",
"full",
"name",
"to",
"an",
"existing",
"file",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/common.py#L404-L422 |
29,203 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/common.py | check_tool | 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(command, basestring)
#FIXME: why do we check the first and last elements????
if check_tool_aux(command[0]) or check_tool_aux(command[-1]):
return command | python | 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(command, basestring)
#FIXME: why do we check the first and last elements????
if check_tool_aux(command[0]) or check_tool_aux(command[-1]):
return command | [
"def",
"check_tool",
"(",
"command",
")",
":",
"assert",
"is_iterable_typed",
"(",
"command",
",",
"basestring",
")",
"#FIXME: why do we check the first and last elements????",
"if",
"check_tool_aux",
"(",
"command",
"[",
"0",
"]",
")",
"or",
"check_tool_aux",
"(",
"command",
"[",
"-",
"1",
"]",
")",
":",
"return",
"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. | [
"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",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/common.py#L425-L434 |
29,204 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/common.py | get_program_files_dir | 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 ProgramFiles | python | 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 ProgramFiles | [
"def",
"get_program_files_dir",
"(",
")",
":",
"ProgramFiles",
"=",
"bjam",
".",
"variable",
"(",
"\"ProgramFiles\"",
")",
"if",
"ProgramFiles",
":",
"ProgramFiles",
"=",
"' '",
".",
"join",
"(",
"ProgramFiles",
")",
"else",
":",
"ProgramFiles",
"=",
"\"c:\\\\Program Files\"",
"return",
"ProgramFiles"
] | returns the location of the "program files" directory on a windows
platform | [
"returns",
"the",
"location",
"of",
"the",
"program",
"files",
"directory",
"on",
"a",
"windows",
"platform"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/common.py#L461-L470 |
29,205 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/common.py | variable_setting_command | 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, on Unix systems, the variable is exported, which is consistent with the
only possible behavior on Windows systems.
"""
assert isinstance(variable, basestring)
assert isinstance(value, basestring)
if os_name() == 'NT':
return "set " + variable + "=" + value + os.linesep
else:
# (todo)
# The following does not work on CYGWIN and needs to be fixed. On
# CYGWIN the $(nl) variable holds a Windows new-line \r\n sequence that
# messes up the executed export command which then reports that the
# passed variable name is incorrect. This is most likely due to the
# extra \r character getting interpreted as a part of the variable name.
#
# Several ideas pop to mind on how to fix this:
# * One way would be to separate the commands using the ; shell
# command separator. This seems like the quickest possible
# solution but I do not know whether this would break code on any
# platforms I I have no access to.
# * Another would be to not use the terminating $(nl) but that would
# require updating all the using code so it does not simply
# prepend this variable to its own commands.
# * I guess the cleanest solution would be to update Boost Jam to
# allow explicitly specifying \n & \r characters in its scripts
# instead of always relying only on the 'current OS native newline
# sequence'.
#
# Some code found to depend on this behaviour:
# * This Boost Build module.
# * __test__ rule.
# * path-variable-setting-command rule.
# * python.jam toolset.
# * xsltproc.jam toolset.
# * fop.jam toolset.
# (todo) (07.07.2008.) (Jurko)
#
# I think that this works correctly in python -- Steven Watanabe
return variable + "=" + value + os.linesep + "export " + variable + os.linesep | python | 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, on Unix systems, the variable is exported, which is consistent with the
only possible behavior on Windows systems.
"""
assert isinstance(variable, basestring)
assert isinstance(value, basestring)
if os_name() == 'NT':
return "set " + variable + "=" + value + os.linesep
else:
# (todo)
# The following does not work on CYGWIN and needs to be fixed. On
# CYGWIN the $(nl) variable holds a Windows new-line \r\n sequence that
# messes up the executed export command which then reports that the
# passed variable name is incorrect. This is most likely due to the
# extra \r character getting interpreted as a part of the variable name.
#
# Several ideas pop to mind on how to fix this:
# * One way would be to separate the commands using the ; shell
# command separator. This seems like the quickest possible
# solution but I do not know whether this would break code on any
# platforms I I have no access to.
# * Another would be to not use the terminating $(nl) but that would
# require updating all the using code so it does not simply
# prepend this variable to its own commands.
# * I guess the cleanest solution would be to update Boost Jam to
# allow explicitly specifying \n & \r characters in its scripts
# instead of always relying only on the 'current OS native newline
# sequence'.
#
# Some code found to depend on this behaviour:
# * This Boost Build module.
# * __test__ rule.
# * path-variable-setting-command rule.
# * python.jam toolset.
# * xsltproc.jam toolset.
# * fop.jam toolset.
# (todo) (07.07.2008.) (Jurko)
#
# I think that this works correctly in python -- Steven Watanabe
return variable + "=" + value + os.linesep + "export " + variable + os.linesep | [
"def",
"variable_setting_command",
"(",
"variable",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"variable",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"value",
",",
"basestring",
")",
"if",
"os_name",
"(",
")",
"==",
"'NT'",
":",
"return",
"\"set \"",
"+",
"variable",
"+",
"\"=\"",
"+",
"value",
"+",
"os",
".",
"linesep",
"else",
":",
"# (todo)",
"# The following does not work on CYGWIN and needs to be fixed. On",
"# CYGWIN the $(nl) variable holds a Windows new-line \\r\\n sequence that",
"# messes up the executed export command which then reports that the",
"# passed variable name is incorrect. This is most likely due to the",
"# extra \\r character getting interpreted as a part of the variable name.",
"#",
"# Several ideas pop to mind on how to fix this:",
"# * One way would be to separate the commands using the ; shell",
"# command separator. This seems like the quickest possible",
"# solution but I do not know whether this would break code on any",
"# platforms I I have no access to.",
"# * Another would be to not use the terminating $(nl) but that would",
"# require updating all the using code so it does not simply",
"# prepend this variable to its own commands.",
"# * I guess the cleanest solution would be to update Boost Jam to",
"# allow explicitly specifying \\n & \\r characters in its scripts",
"# instead of always relying only on the 'current OS native newline",
"# sequence'.",
"#",
"# Some code found to depend on this behaviour:",
"# * This Boost Build module.",
"# * __test__ rule.",
"# * path-variable-setting-command rule.",
"# * python.jam toolset.",
"# * xsltproc.jam toolset.",
"# * fop.jam toolset.",
"# (todo) (07.07.2008.) (Jurko)",
"#",
"# I think that this works correctly in python -- Steven Watanabe",
"return",
"variable",
"+",
"\"=\"",
"+",
"value",
"+",
"os",
".",
"linesep",
"+",
"\"export \"",
"+",
"variable",
"+",
"os",
".",
"linesep"
] | 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 with the
only possible behavior on Windows systems. | [
"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",
"with",
"the",
"only",
"possible",
"behavior",
"on",
"Windows",
"systems",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/common.py#L481-L525 |
29,206 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/common.py | path_variable_setting_command | 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 variable_setting_command(variable, sep.join(paths)) | python | 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 variable_setting_command(variable, sep.join(paths)) | [
"def",
"path_variable_setting_command",
"(",
"variable",
",",
"paths",
")",
":",
"assert",
"isinstance",
"(",
"variable",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"paths",
",",
"basestring",
")",
"sep",
"=",
"os",
".",
"path",
".",
"pathsep",
"return",
"variable_setting_command",
"(",
"variable",
",",
"sep",
".",
"join",
"(",
"paths",
")",
")"
] | Returns a command to sets a named shell path variable to the given NATIVE
paths on the current platform. | [
"Returns",
"a",
"command",
"to",
"sets",
"a",
"named",
"shell",
"path",
"variable",
"to",
"the",
"given",
"NATIVE",
"paths",
"on",
"the",
"current",
"platform",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/common.py#L527-L535 |
29,207 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/common.py | prepend_path_variable_command | 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(
variable, paths + [expand_variable(variable)]) | python | 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(
variable, paths + [expand_variable(variable)]) | [
"def",
"prepend_path_variable_command",
"(",
"variable",
",",
"paths",
")",
":",
"assert",
"isinstance",
"(",
"variable",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"paths",
",",
"basestring",
")",
"return",
"path_variable_setting_command",
"(",
"variable",
",",
"paths",
"+",
"[",
"expand_variable",
"(",
"variable",
")",
"]",
")"
] | Returns a command that prepends the given paths to the named path variable on
the current platform. | [
"Returns",
"a",
"command",
"that",
"prepends",
"the",
"given",
"paths",
"to",
"the",
"named",
"path",
"variable",
"on",
"the",
"current",
"platform",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/common.py#L537-L545 |
29,208 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/common.py | format_name | 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
information is obtained and added to the result string. For all, but the
literal, the format value is taken as the as string to prepend to the output
to join the item to the rest of the result. If not given "-" is used as a
joiner.
The format options can be:
<base>[joiner]
:: The basename of the target name.
<toolset>[joiner]
:: The abbreviated toolset tag being used to build the target.
<threading>[joiner]
:: Indication of a multi-threaded build.
<runtime>[joiner]
:: Collective tag of the build runtime.
<version:/version-feature | X.Y[.Z]/>[joiner]
:: Short version tag taken from the given "version-feature"
in the build properties. Or if not present, the literal
value as the version number.
<property:/property-name/>[joiner]
:: Direct lookup of the given property-name value in the
build properties. /property-name/ is a regular expression.
e.g. <property:toolset-.*:flavor> will match every toolset.
/otherwise/
:: The literal value of the format argument.
For example this format:
boost_ <base> <toolset> <threading> <runtime> <version:boost-version>
Might return:
boost_thread-vc80-mt-gd-1_33.dll, or
boost_regex-vc80-gd-1_33.dll
The returned name also has the target type specific prefix and suffix which
puts it in a ready form to use as the value from a custom tag rule.
"""
if __debug__:
from ..build.property_set import PropertySet
assert is_iterable_typed(format, basestring)
assert isinstance(name, basestring)
assert isinstance(target_type, basestring)
assert isinstance(prop_set, PropertySet)
# assert(isinstance(prop_set, property_set.PropertySet))
if type.is_derived(target_type, 'LIB'):
result = "" ;
for f in format:
grist = get_grist(f)
if grist == '<base>':
result += os.path.basename(name)
elif grist == '<toolset>':
result += join_tag(get_value(f),
toolset_tag(name, target_type, prop_set))
elif grist == '<threading>':
result += join_tag(get_value(f),
threading_tag(name, target_type, prop_set))
elif grist == '<runtime>':
result += join_tag(get_value(f),
runtime_tag(name, target_type, prop_set))
elif grist.startswith('<version:'):
key = grist[len('<version:'):-1]
version = prop_set.get('<' + key + '>')
if not version:
version = key
version = __re_version.match(version)
result += join_tag(get_value(f), version[1] + '_' + version[2])
elif grist.startswith('<property:'):
key = grist[len('<property:'):-1]
property_re = re.compile('<(' + key + ')>')
p0 = None
for prop in prop_set.raw():
match = property_re.match(prop)
if match:
p0 = match[1]
break
if p0:
p = prop_set.get('<' + p0 + '>')
if p:
assert(len(p) == 1)
result += join_tag(ungrist(f), p)
else:
result += f
result = b2.build.virtual_target.add_prefix_and_suffix(
''.join(result), target_type, prop_set)
return result | python | 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
information is obtained and added to the result string. For all, but the
literal, the format value is taken as the as string to prepend to the output
to join the item to the rest of the result. If not given "-" is used as a
joiner.
The format options can be:
<base>[joiner]
:: The basename of the target name.
<toolset>[joiner]
:: The abbreviated toolset tag being used to build the target.
<threading>[joiner]
:: Indication of a multi-threaded build.
<runtime>[joiner]
:: Collective tag of the build runtime.
<version:/version-feature | X.Y[.Z]/>[joiner]
:: Short version tag taken from the given "version-feature"
in the build properties. Or if not present, the literal
value as the version number.
<property:/property-name/>[joiner]
:: Direct lookup of the given property-name value in the
build properties. /property-name/ is a regular expression.
e.g. <property:toolset-.*:flavor> will match every toolset.
/otherwise/
:: The literal value of the format argument.
For example this format:
boost_ <base> <toolset> <threading> <runtime> <version:boost-version>
Might return:
boost_thread-vc80-mt-gd-1_33.dll, or
boost_regex-vc80-gd-1_33.dll
The returned name also has the target type specific prefix and suffix which
puts it in a ready form to use as the value from a custom tag rule.
"""
if __debug__:
from ..build.property_set import PropertySet
assert is_iterable_typed(format, basestring)
assert isinstance(name, basestring)
assert isinstance(target_type, basestring)
assert isinstance(prop_set, PropertySet)
# assert(isinstance(prop_set, property_set.PropertySet))
if type.is_derived(target_type, 'LIB'):
result = "" ;
for f in format:
grist = get_grist(f)
if grist == '<base>':
result += os.path.basename(name)
elif grist == '<toolset>':
result += join_tag(get_value(f),
toolset_tag(name, target_type, prop_set))
elif grist == '<threading>':
result += join_tag(get_value(f),
threading_tag(name, target_type, prop_set))
elif grist == '<runtime>':
result += join_tag(get_value(f),
runtime_tag(name, target_type, prop_set))
elif grist.startswith('<version:'):
key = grist[len('<version:'):-1]
version = prop_set.get('<' + key + '>')
if not version:
version = key
version = __re_version.match(version)
result += join_tag(get_value(f), version[1] + '_' + version[2])
elif grist.startswith('<property:'):
key = grist[len('<property:'):-1]
property_re = re.compile('<(' + key + ')>')
p0 = None
for prop in prop_set.raw():
match = property_re.match(prop)
if match:
p0 = match[1]
break
if p0:
p = prop_set.get('<' + p0 + '>')
if p:
assert(len(p) == 1)
result += join_tag(ungrist(f), p)
else:
result += f
result = b2.build.virtual_target.add_prefix_and_suffix(
''.join(result), target_type, prop_set)
return result | [
"def",
"format_name",
"(",
"format",
",",
"name",
",",
"target_type",
",",
"prop_set",
")",
":",
"if",
"__debug__",
":",
"from",
".",
".",
"build",
".",
"property_set",
"import",
"PropertySet",
"assert",
"is_iterable_typed",
"(",
"format",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"name",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"target_type",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"prop_set",
",",
"PropertySet",
")",
"# assert(isinstance(prop_set, property_set.PropertySet))",
"if",
"type",
".",
"is_derived",
"(",
"target_type",
",",
"'LIB'",
")",
":",
"result",
"=",
"\"\"",
"for",
"f",
"in",
"format",
":",
"grist",
"=",
"get_grist",
"(",
"f",
")",
"if",
"grist",
"==",
"'<base>'",
":",
"result",
"+=",
"os",
".",
"path",
".",
"basename",
"(",
"name",
")",
"elif",
"grist",
"==",
"'<toolset>'",
":",
"result",
"+=",
"join_tag",
"(",
"get_value",
"(",
"f",
")",
",",
"toolset_tag",
"(",
"name",
",",
"target_type",
",",
"prop_set",
")",
")",
"elif",
"grist",
"==",
"'<threading>'",
":",
"result",
"+=",
"join_tag",
"(",
"get_value",
"(",
"f",
")",
",",
"threading_tag",
"(",
"name",
",",
"target_type",
",",
"prop_set",
")",
")",
"elif",
"grist",
"==",
"'<runtime>'",
":",
"result",
"+=",
"join_tag",
"(",
"get_value",
"(",
"f",
")",
",",
"runtime_tag",
"(",
"name",
",",
"target_type",
",",
"prop_set",
")",
")",
"elif",
"grist",
".",
"startswith",
"(",
"'<version:'",
")",
":",
"key",
"=",
"grist",
"[",
"len",
"(",
"'<version:'",
")",
":",
"-",
"1",
"]",
"version",
"=",
"prop_set",
".",
"get",
"(",
"'<'",
"+",
"key",
"+",
"'>'",
")",
"if",
"not",
"version",
":",
"version",
"=",
"key",
"version",
"=",
"__re_version",
".",
"match",
"(",
"version",
")",
"result",
"+=",
"join_tag",
"(",
"get_value",
"(",
"f",
")",
",",
"version",
"[",
"1",
"]",
"+",
"'_'",
"+",
"version",
"[",
"2",
"]",
")",
"elif",
"grist",
".",
"startswith",
"(",
"'<property:'",
")",
":",
"key",
"=",
"grist",
"[",
"len",
"(",
"'<property:'",
")",
":",
"-",
"1",
"]",
"property_re",
"=",
"re",
".",
"compile",
"(",
"'<('",
"+",
"key",
"+",
"')>'",
")",
"p0",
"=",
"None",
"for",
"prop",
"in",
"prop_set",
".",
"raw",
"(",
")",
":",
"match",
"=",
"property_re",
".",
"match",
"(",
"prop",
")",
"if",
"match",
":",
"p0",
"=",
"match",
"[",
"1",
"]",
"break",
"if",
"p0",
":",
"p",
"=",
"prop_set",
".",
"get",
"(",
"'<'",
"+",
"p0",
"+",
"'>'",
")",
"if",
"p",
":",
"assert",
"(",
"len",
"(",
"p",
")",
"==",
"1",
")",
"result",
"+=",
"join_tag",
"(",
"ungrist",
"(",
"f",
")",
",",
"p",
")",
"else",
":",
"result",
"+=",
"f",
"result",
"=",
"b2",
".",
"build",
".",
"virtual_target",
".",
"add_prefix_and_suffix",
"(",
"''",
".",
"join",
"(",
"result",
")",
",",
"target_type",
",",
"prop_set",
")",
"return",
"result"
] | 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
literal, the format value is taken as the as string to prepend to the output
to join the item to the rest of the result. If not given "-" is used as a
joiner.
The format options can be:
<base>[joiner]
:: The basename of the target name.
<toolset>[joiner]
:: The abbreviated toolset tag being used to build the target.
<threading>[joiner]
:: Indication of a multi-threaded build.
<runtime>[joiner]
:: Collective tag of the build runtime.
<version:/version-feature | X.Y[.Z]/>[joiner]
:: Short version tag taken from the given "version-feature"
in the build properties. Or if not present, the literal
value as the version number.
<property:/property-name/>[joiner]
:: Direct lookup of the given property-name value in the
build properties. /property-name/ is a regular expression.
e.g. <property:toolset-.*:flavor> will match every toolset.
/otherwise/
:: The literal value of the format argument.
For example this format:
boost_ <base> <toolset> <threading> <runtime> <version:boost-version>
Might return:
boost_thread-vc80-mt-gd-1_33.dll, or
boost_regex-vc80-gd-1_33.dll
The returned name also has the target type specific prefix and suffix which
puts it in a ready form to use as the value from a custom tag rule. | [
"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",
"literal",
"the",
"format",
"value",
"is",
"taken",
"as",
"the",
"as",
"string",
"to",
"prepend",
"to",
"the",
"output",
"to",
"join",
"the",
"item",
"to",
"the",
"rest",
"of",
"the",
"result",
".",
"If",
"not",
"given",
"-",
"is",
"used",
"as",
"a",
"joiner",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/common.py#L607-L697 |
29,209 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/common.py | Configurations.register | 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_:
#FIXME
errors.error("common: the configuration '$(id)' is in use")
if id not in self.all_:
self.all_.add(id)
# Indicate that a new configuration has been added.
return True
else:
return False | python | 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_:
#FIXME
errors.error("common: the configuration '$(id)' is in use")
if id not in self.all_:
self.all_.add(id)
# Indicate that a new configuration has been added.
return True
else:
return False | [
"def",
"register",
"(",
"self",
",",
"id",
")",
":",
"assert",
"isinstance",
"(",
"id",
",",
"basestring",
")",
"if",
"id",
"in",
"self",
".",
"used_",
":",
"#FIXME",
"errors",
".",
"error",
"(",
"\"common: the configuration '$(id)' is in use\"",
")",
"if",
"id",
"not",
"in",
"self",
".",
"all_",
":",
"self",
".",
"all_",
".",
"add",
"(",
"id",
")",
"# Indicate that a new configuration has been added.",
"return",
"True",
"else",
":",
"return",
"False"
] | 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'. | [
"Registers",
"a",
"configuration",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/common.py#L108-L126 |
29,210 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/common.py | Configurations.get | 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) | python | 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) | [
"def",
"get",
"(",
"self",
",",
"id",
",",
"param",
")",
":",
"assert",
"isinstance",
"(",
"id",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"param",
",",
"basestring",
")",
"return",
"self",
".",
"params_",
".",
"get",
"(",
"param",
",",
"{",
"}",
")",
".",
"get",
"(",
"id",
")"
] | Returns the value of a configuration parameter. | [
"Returns",
"the",
"value",
"of",
"a",
"configuration",
"parameter",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/common.py#L157-L161 |
29,211 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/common.py | Configurations.set | 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 | python | 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 | [
"def",
"set",
"(",
"self",
",",
"id",
",",
"param",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"id",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"param",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"value",
",",
"basestring",
")",
"self",
".",
"params_",
".",
"setdefault",
"(",
"param",
",",
"{",
"}",
")",
"[",
"id",
"]",
"=",
"value"
] | Sets the value of a configuration parameter. | [
"Sets",
"the",
"value",
"of",
"a",
"configuration",
"parameter",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/common.py#L163-L168 |
29,212 | apple/turicreate | src/unity/python/turicreate/toolkits/_mxnet/_mxnet_utils.py | get_gpus_in_use | 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] for index in gpu_indices] | python | 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] for index in gpu_indices] | [
"def",
"get_gpus_in_use",
"(",
"max_devices",
"=",
"None",
")",
":",
"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",
"]",
"for",
"index",
"in",
"gpu_indices",
"]"
] | Like get_num_gpus_in_use, but returns a list of dictionaries with just
queried GPU information. | [
"Like",
"get_num_gpus_in_use",
"but",
"returns",
"a",
"list",
"of",
"dictionaries",
"with",
"just",
"queried",
"GPU",
"information",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_utils.py#L100-L108 |
29,213 | apple/turicreate | src/unity/python/turicreate/_sys_util.py | make_unity_server_env | 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:
1. CLASSPATH, contains hadoop class path
2. __GL_PYTHON_EXECUTABLE__, path to the python executable
3. __GL_PYLAMBDA_SCRIPT__, path to the lambda worker executable
4. __GL_SYS_PATH__: contains the python sys.path of the interpreter
"""
env = os.environ.copy()
# Add hadoop class path
classpath = get_hadoop_class_path()
if ("CLASSPATH" in env):
env["CLASSPATH"] = env['CLASSPATH'] + (os.path.pathsep + classpath if classpath != '' else '')
else:
env["CLASSPATH"] = classpath
# Add python syspath
env['__GL_SYS_PATH__'] = (os.path.pathsep).join(sys.path + [os.getcwd()])
# Add the python executable to the runtime config
env['__GL_PYTHON_EXECUTABLE__'] = os.path.abspath(sys.executable)
# Add the pylambda execution script to the runtime config
env['__GL_PYLAMBDA_SCRIPT__'] = os.path.abspath(_pylambda_worker.__file__)
#### Remove PYTHONEXECUTABLE ####
# Anaconda overwrites this environment variable
# which forces all python sub-processes to use the same binary.
# When using virtualenv with ipython (which is outside virtualenv),
# all subprocess launched under unity_server will use the
# conda binary outside of virtualenv, which lacks the access
# to all packages installed inside virtualenv.
if 'PYTHONEXECUTABLE' in env:
del env['PYTHONEXECUTABLE']
# Set mxnet envvars
if 'MXNET_CPU_WORKER_NTHREADS' not in env:
from multiprocessing import cpu_count
num_cpus = int(env.get('OMP_NUM_THREADS', cpu_count()))
if sys.platform == 'darwin':
num_workers = num_cpus
else:
# On Linux, BLAS doesn't seem to tolerate larger numbers of workers.
num_workers = min(2, num_cpus)
env['MXNET_CPU_WORKER_NTHREADS'] = str(num_workers)
## set local to be c standard so that unity_server will run ##
env['LC_ALL']='C'
# add certificate file
if 'TURI_FILEIO_ALTERNATIVE_SSL_CERT_FILE' not in env and \
'TURI_FILEIO_ALTERNATIVE_SSL_CERT_DIR' not in env:
try:
import certifi
env['TURI_FILEIO_ALTERNATIVE_SSL_CERT_FILE'] = certifi.where()
env['TURI_FILEIO_ALTERNATIVE_SSL_CERT_DIR'] = ""
except:
pass
return env | python | 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:
1. CLASSPATH, contains hadoop class path
2. __GL_PYTHON_EXECUTABLE__, path to the python executable
3. __GL_PYLAMBDA_SCRIPT__, path to the lambda worker executable
4. __GL_SYS_PATH__: contains the python sys.path of the interpreter
"""
env = os.environ.copy()
# Add hadoop class path
classpath = get_hadoop_class_path()
if ("CLASSPATH" in env):
env["CLASSPATH"] = env['CLASSPATH'] + (os.path.pathsep + classpath if classpath != '' else '')
else:
env["CLASSPATH"] = classpath
# Add python syspath
env['__GL_SYS_PATH__'] = (os.path.pathsep).join(sys.path + [os.getcwd()])
# Add the python executable to the runtime config
env['__GL_PYTHON_EXECUTABLE__'] = os.path.abspath(sys.executable)
# Add the pylambda execution script to the runtime config
env['__GL_PYLAMBDA_SCRIPT__'] = os.path.abspath(_pylambda_worker.__file__)
#### Remove PYTHONEXECUTABLE ####
# Anaconda overwrites this environment variable
# which forces all python sub-processes to use the same binary.
# When using virtualenv with ipython (which is outside virtualenv),
# all subprocess launched under unity_server will use the
# conda binary outside of virtualenv, which lacks the access
# to all packages installed inside virtualenv.
if 'PYTHONEXECUTABLE' in env:
del env['PYTHONEXECUTABLE']
# Set mxnet envvars
if 'MXNET_CPU_WORKER_NTHREADS' not in env:
from multiprocessing import cpu_count
num_cpus = int(env.get('OMP_NUM_THREADS', cpu_count()))
if sys.platform == 'darwin':
num_workers = num_cpus
else:
# On Linux, BLAS doesn't seem to tolerate larger numbers of workers.
num_workers = min(2, num_cpus)
env['MXNET_CPU_WORKER_NTHREADS'] = str(num_workers)
## set local to be c standard so that unity_server will run ##
env['LC_ALL']='C'
# add certificate file
if 'TURI_FILEIO_ALTERNATIVE_SSL_CERT_FILE' not in env and \
'TURI_FILEIO_ALTERNATIVE_SSL_CERT_DIR' not in env:
try:
import certifi
env['TURI_FILEIO_ALTERNATIVE_SSL_CERT_FILE'] = certifi.where()
env['TURI_FILEIO_ALTERNATIVE_SSL_CERT_DIR'] = ""
except:
pass
return env | [
"def",
"make_unity_server_env",
"(",
")",
":",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"# Add hadoop class path",
"classpath",
"=",
"get_hadoop_class_path",
"(",
")",
"if",
"(",
"\"CLASSPATH\"",
"in",
"env",
")",
":",
"env",
"[",
"\"CLASSPATH\"",
"]",
"=",
"env",
"[",
"'CLASSPATH'",
"]",
"+",
"(",
"os",
".",
"path",
".",
"pathsep",
"+",
"classpath",
"if",
"classpath",
"!=",
"''",
"else",
"''",
")",
"else",
":",
"env",
"[",
"\"CLASSPATH\"",
"]",
"=",
"classpath",
"# Add python syspath",
"env",
"[",
"'__GL_SYS_PATH__'",
"]",
"=",
"(",
"os",
".",
"path",
".",
"pathsep",
")",
".",
"join",
"(",
"sys",
".",
"path",
"+",
"[",
"os",
".",
"getcwd",
"(",
")",
"]",
")",
"# Add the python executable to the runtime config",
"env",
"[",
"'__GL_PYTHON_EXECUTABLE__'",
"]",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"sys",
".",
"executable",
")",
"# Add the pylambda execution script to the runtime config",
"env",
"[",
"'__GL_PYLAMBDA_SCRIPT__'",
"]",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"_pylambda_worker",
".",
"__file__",
")",
"#### Remove PYTHONEXECUTABLE ####",
"# Anaconda overwrites this environment variable",
"# which forces all python sub-processes to use the same binary.",
"# When using virtualenv with ipython (which is outside virtualenv),",
"# all subprocess launched under unity_server will use the",
"# conda binary outside of virtualenv, which lacks the access",
"# to all packages installed inside virtualenv.",
"if",
"'PYTHONEXECUTABLE'",
"in",
"env",
":",
"del",
"env",
"[",
"'PYTHONEXECUTABLE'",
"]",
"# Set mxnet envvars",
"if",
"'MXNET_CPU_WORKER_NTHREADS'",
"not",
"in",
"env",
":",
"from",
"multiprocessing",
"import",
"cpu_count",
"num_cpus",
"=",
"int",
"(",
"env",
".",
"get",
"(",
"'OMP_NUM_THREADS'",
",",
"cpu_count",
"(",
")",
")",
")",
"if",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"num_workers",
"=",
"num_cpus",
"else",
":",
"# On Linux, BLAS doesn't seem to tolerate larger numbers of workers.",
"num_workers",
"=",
"min",
"(",
"2",
",",
"num_cpus",
")",
"env",
"[",
"'MXNET_CPU_WORKER_NTHREADS'",
"]",
"=",
"str",
"(",
"num_workers",
")",
"## set local to be c standard so that unity_server will run ##",
"env",
"[",
"'LC_ALL'",
"]",
"=",
"'C'",
"# add certificate file",
"if",
"'TURI_FILEIO_ALTERNATIVE_SSL_CERT_FILE'",
"not",
"in",
"env",
"and",
"'TURI_FILEIO_ALTERNATIVE_SSL_CERT_DIR'",
"not",
"in",
"env",
":",
"try",
":",
"import",
"certifi",
"env",
"[",
"'TURI_FILEIO_ALTERNATIVE_SSL_CERT_FILE'",
"]",
"=",
"certifi",
".",
"where",
"(",
")",
"env",
"[",
"'TURI_FILEIO_ALTERNATIVE_SSL_CERT_DIR'",
"]",
"=",
"\"\"",
"except",
":",
"pass",
"return",
"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:
1. CLASSPATH, contains hadoop class path
2. __GL_PYTHON_EXECUTABLE__, path to the python executable
3. __GL_PYLAMBDA_SCRIPT__, path to the lambda worker executable
4. __GL_SYS_PATH__: contains the python sys.path of the interpreter | [
"Returns",
"the",
"environment",
"for",
"unity_server",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/_sys_util.py#L22-L86 |
29,214 | apple/turicreate | src/unity/python/turicreate/_sys_util.py | set_windows_dll_path | 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:
last_error = ctypes.get_last_error()
if last_error != 0:
raise ctypes.WinError(last_error)
else:
raise OSError
return args
# Also need to set the dll loading directory to the main
# folder so windows attempts to load all DLLs from this
# directory.
import ctypes.wintypes as wintypes
try:
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
kernel32.SetDllDirectoryW.errcheck = errcheck_bool
kernel32.SetDllDirectoryW.argtypes = (wintypes.LPCWSTR,)
kernel32.SetDllDirectoryW(lib_path)
except Exception as e:
logging.getLogger(__name__).warning(
"Error setting DLL load orders: %s (things should still work)." % str(e)) | python | 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:
last_error = ctypes.get_last_error()
if last_error != 0:
raise ctypes.WinError(last_error)
else:
raise OSError
return args
# Also need to set the dll loading directory to the main
# folder so windows attempts to load all DLLs from this
# directory.
import ctypes.wintypes as wintypes
try:
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
kernel32.SetDllDirectoryW.errcheck = errcheck_bool
kernel32.SetDllDirectoryW.argtypes = (wintypes.LPCWSTR,)
kernel32.SetDllDirectoryW(lib_path)
except Exception as e:
logging.getLogger(__name__).warning(
"Error setting DLL load orders: %s (things should still work)." % str(e)) | [
"def",
"set_windows_dll_path",
"(",
")",
":",
"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",
":",
"last_error",
"=",
"ctypes",
".",
"get_last_error",
"(",
")",
"if",
"last_error",
"!=",
"0",
":",
"raise",
"ctypes",
".",
"WinError",
"(",
"last_error",
")",
"else",
":",
"raise",
"OSError",
"return",
"args",
"# Also need to set the dll loading directory to the main",
"# folder so windows attempts to load all DLLs from this",
"# directory.",
"import",
"ctypes",
".",
"wintypes",
"as",
"wintypes",
"try",
":",
"kernel32",
"=",
"ctypes",
".",
"WinDLL",
"(",
"'kernel32'",
",",
"use_last_error",
"=",
"True",
")",
"kernel32",
".",
"SetDllDirectoryW",
".",
"errcheck",
"=",
"errcheck_bool",
"kernel32",
".",
"SetDllDirectoryW",
".",
"argtypes",
"=",
"(",
"wintypes",
".",
"LPCWSTR",
",",
")",
"kernel32",
".",
"SetDllDirectoryW",
"(",
"lib_path",
")",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
".",
"warning",
"(",
"\"Error setting DLL load orders: %s (things should still work).\"",
"%",
"str",
"(",
"e",
")",
")"
] | Sets the dll load path so that things are resolved correctly. | [
"Sets",
"the",
"dll",
"load",
"path",
"so",
"that",
"things",
"are",
"resolved",
"correctly",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/_sys_util.py#L88-L117 |
29,215 | apple/turicreate | src/unity/python/turicreate/_sys_util.py | get_library_name | 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 __lib_name | python | 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 __lib_name | [
"def",
"get_library_name",
"(",
")",
":",
"from",
"os",
".",
"path",
"import",
"split",
",",
"abspath",
"__lib_name",
"=",
"split",
"(",
"split",
"(",
"abspath",
"(",
"sys",
".",
"modules",
"[",
"__name__",
"]",
".",
"__file__",
")",
")",
"[",
"0",
"]",
")",
"[",
"1",
"]",
"assert",
"__lib_name",
"in",
"[",
"\"sframe\"",
",",
"\"turicreate\"",
"]",
"return",
"__lib_name"
] | Returns either sframe or turicreate depending on which library
this file is bundled with. | [
"Returns",
"either",
"sframe",
"or",
"turicreate",
"depending",
"on",
"which",
"library",
"this",
"file",
"is",
"bundled",
"with",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/_sys_util.py#L452-L463 |
29,216 | apple/turicreate | src/unity/python/turicreate/_sys_util.py | get_config_file | 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_path = join(expanduser("~"), ".%s" % __lib_name, "config")
if "TURI_CONFIG_FILE" in os.environ:
__default_config_path = abspath(expanduser(os.environ["TURI_CONFIG_FILE"]))
if not exists(__default_config_path):
print(("WARNING: Config file specified in environment variable "
"'TURI_CONFIG_FILE' as "
"'%s', but this path does not exist.") % __default_config_path)
return __default_config_path | python | 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_path = join(expanduser("~"), ".%s" % __lib_name, "config")
if "TURI_CONFIG_FILE" in os.environ:
__default_config_path = abspath(expanduser(os.environ["TURI_CONFIG_FILE"]))
if not exists(__default_config_path):
print(("WARNING: Config file specified in environment variable "
"'TURI_CONFIG_FILE' as "
"'%s', but this path does not exist.") % __default_config_path)
return __default_config_path | [
"def",
"get_config_file",
"(",
")",
":",
"import",
"os",
"from",
"os",
".",
"path",
"import",
"abspath",
",",
"expanduser",
",",
"join",
",",
"exists",
"__lib_name",
"=",
"get_library_name",
"(",
")",
"assert",
"__lib_name",
"in",
"[",
"\"sframe\"",
",",
"\"turicreate\"",
"]",
"__default_config_path",
"=",
"join",
"(",
"expanduser",
"(",
"\"~\"",
")",
",",
"\".%s\"",
"%",
"__lib_name",
",",
"\"config\"",
")",
"if",
"\"TURI_CONFIG_FILE\"",
"in",
"os",
".",
"environ",
":",
"__default_config_path",
"=",
"abspath",
"(",
"expanduser",
"(",
"os",
".",
"environ",
"[",
"\"TURI_CONFIG_FILE\"",
"]",
")",
")",
"if",
"not",
"exists",
"(",
"__default_config_path",
")",
":",
"print",
"(",
"(",
"\"WARNING: Config file specified in environment variable \"",
"\"'TURI_CONFIG_FILE' as \"",
"\"'%s', but this path does not exist.\"",
")",
"%",
"__default_config_path",
")",
"return",
"__default_config_path"
] | Returns the file name of the config file from which the environment
variables are written. | [
"Returns",
"the",
"file",
"name",
"of",
"the",
"config",
"file",
"from",
"which",
"the",
"environment",
"variables",
"are",
"written",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/_sys_util.py#L466-L488 |
29,217 | apple/turicreate | src/unity/python/turicreate/_sys_util.py | setup_environment_from_config_file | 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
try:
config = _ConfigParser.SafeConfigParser()
config.read(config_file)
__section = "Environment"
if config.has_section(__section):
items = config.items(__section)
for k, v in items:
try:
os.environ[k.upper()] = v
except Exception as e:
print(("WARNING: Error setting environment variable "
"'%s = %s' from config file '%s': %s.")
% (k, str(v), config_file, str(e)) )
except Exception as e:
print("WARNING: Error reading config file '%s': %s." % (config_file, str(e))) | python | 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
try:
config = _ConfigParser.SafeConfigParser()
config.read(config_file)
__section = "Environment"
if config.has_section(__section):
items = config.items(__section)
for k, v in items:
try:
os.environ[k.upper()] = v
except Exception as e:
print(("WARNING: Error setting environment variable "
"'%s = %s' from config file '%s': %s.")
% (k, str(v), config_file, str(e)) )
except Exception as e:
print("WARNING: Error reading config file '%s': %s." % (config_file, str(e))) | [
"def",
"setup_environment_from_config_file",
"(",
")",
":",
"from",
"os",
".",
"path",
"import",
"exists",
"config_file",
"=",
"get_config_file",
"(",
")",
"if",
"not",
"exists",
"(",
"config_file",
")",
":",
"return",
"try",
":",
"config",
"=",
"_ConfigParser",
".",
"SafeConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"config_file",
")",
"__section",
"=",
"\"Environment\"",
"if",
"config",
".",
"has_section",
"(",
"__section",
")",
":",
"items",
"=",
"config",
".",
"items",
"(",
"__section",
")",
"for",
"k",
",",
"v",
"in",
"items",
":",
"try",
":",
"os",
".",
"environ",
"[",
"k",
".",
"upper",
"(",
")",
"]",
"=",
"v",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"(",
"\"WARNING: Error setting environment variable \"",
"\"'%s = %s' from config file '%s': %s.\"",
")",
"%",
"(",
"k",
",",
"str",
"(",
"v",
")",
",",
"config_file",
",",
"str",
"(",
"e",
")",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"\"WARNING: Error reading config file '%s': %s.\"",
"%",
"(",
"config_file",
",",
"str",
"(",
"e",
")",
")",
")"
] | Imports the environmental configuration settings from the
config file, if present, and sets the environment
variables to test it. | [
"Imports",
"the",
"environmental",
"configuration",
"settings",
"from",
"the",
"config",
"file",
"if",
"present",
"and",
"sets",
"the",
"environment",
"variables",
"to",
"test",
"it",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/_sys_util.py#L491-L522 |
29,218 | apple/turicreate | src/unity/python/turicreate/_sys_util.py | write_config_file_value | 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_config_file()
config = _ConfigParser.SafeConfigParser()
config.read(filename)
__section = "Environment"
if not(config.has_section(__section)):
config.add_section(__section)
config.set(__section, key, value)
with open(filename, 'w') as config_file:
config.write(config_file) | python | 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_config_file()
config = _ConfigParser.SafeConfigParser()
config.read(filename)
__section = "Environment"
if not(config.has_section(__section)):
config.add_section(__section)
config.set(__section, key, value)
with open(filename, 'w') as config_file:
config.write(config_file) | [
"def",
"write_config_file_value",
"(",
"key",
",",
"value",
")",
":",
"filename",
"=",
"get_config_file",
"(",
")",
"config",
"=",
"_ConfigParser",
".",
"SafeConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"filename",
")",
"__section",
"=",
"\"Environment\"",
"if",
"not",
"(",
"config",
".",
"has_section",
"(",
"__section",
")",
")",
":",
"config",
".",
"add_section",
"(",
"__section",
")",
"config",
".",
"set",
"(",
"__section",
",",
"key",
",",
"value",
")",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"config_file",
":",
"config",
".",
"write",
"(",
"config_file",
")"
] | 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. | [
"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",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/_sys_util.py#L525-L547 |
29,219 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/service_reflection.py | _ServiceBuilder.BuildService | 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 does the real CallMethod work.
def _WrapCallMethod(srvc, method_descriptor,
rpc_controller, request, callback):
return self._CallMethod(srvc, method_descriptor,
rpc_controller, request, callback)
self.cls = cls
cls.CallMethod = _WrapCallMethod
cls.GetDescriptor = staticmethod(lambda: self.descriptor)
cls.GetDescriptor.__doc__ = "Returns the service descriptor."
cls.GetRequestClass = self._GetRequestClass
cls.GetResponseClass = self._GetResponseClass
for method in self.descriptor.methods:
setattr(cls, method.name, self._GenerateNonImplementedMethod(method)) | python | 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 does the real CallMethod work.
def _WrapCallMethod(srvc, method_descriptor,
rpc_controller, request, callback):
return self._CallMethod(srvc, method_descriptor,
rpc_controller, request, callback)
self.cls = cls
cls.CallMethod = _WrapCallMethod
cls.GetDescriptor = staticmethod(lambda: self.descriptor)
cls.GetDescriptor.__doc__ = "Returns the service descriptor."
cls.GetRequestClass = self._GetRequestClass
cls.GetResponseClass = self._GetResponseClass
for method in self.descriptor.methods:
setattr(cls, method.name, self._GenerateNonImplementedMethod(method)) | [
"def",
"BuildService",
"(",
"self",
",",
"cls",
")",
":",
"# 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 does the real CallMethod work.",
"def",
"_WrapCallMethod",
"(",
"srvc",
",",
"method_descriptor",
",",
"rpc_controller",
",",
"request",
",",
"callback",
")",
":",
"return",
"self",
".",
"_CallMethod",
"(",
"srvc",
",",
"method_descriptor",
",",
"rpc_controller",
",",
"request",
",",
"callback",
")",
"self",
".",
"cls",
"=",
"cls",
"cls",
".",
"CallMethod",
"=",
"_WrapCallMethod",
"cls",
".",
"GetDescriptor",
"=",
"staticmethod",
"(",
"lambda",
":",
"self",
".",
"descriptor",
")",
"cls",
".",
"GetDescriptor",
".",
"__doc__",
"=",
"\"Returns the service descriptor.\"",
"cls",
".",
"GetRequestClass",
"=",
"self",
".",
"_GetRequestClass",
"cls",
".",
"GetResponseClass",
"=",
"self",
".",
"_GetResponseClass",
"for",
"method",
"in",
"self",
".",
"descriptor",
".",
"methods",
":",
"setattr",
"(",
"cls",
",",
"method",
".",
"name",
",",
"self",
".",
"_GenerateNonImplementedMethod",
"(",
"method",
")",
")"
] | Constructs the service class.
Args:
cls: The class that will be constructed. | [
"Constructs",
"the",
"service",
"class",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/service_reflection.py#L133-L154 |
29,220 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/service_reflection.py | _ServiceBuilder._CallMethod | 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.
rpc_controller: RPC controller to use for this method's execution.
request: Request protocol message.
callback: A callback to invoke after the method has completed.
"""
if method_descriptor.containing_service != self.descriptor:
raise RuntimeError(
'CallMethod() given method descriptor for wrong service type.')
method = getattr(srvc, method_descriptor.name)
return method(rpc_controller, request, callback) | python | 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.
rpc_controller: RPC controller to use for this method's execution.
request: Request protocol message.
callback: A callback to invoke after the method has completed.
"""
if method_descriptor.containing_service != self.descriptor:
raise RuntimeError(
'CallMethod() given method descriptor for wrong service type.')
method = getattr(srvc, method_descriptor.name)
return method(rpc_controller, request, callback) | [
"def",
"_CallMethod",
"(",
"self",
",",
"srvc",
",",
"method_descriptor",
",",
"rpc_controller",
",",
"request",
",",
"callback",
")",
":",
"if",
"method_descriptor",
".",
"containing_service",
"!=",
"self",
".",
"descriptor",
":",
"raise",
"RuntimeError",
"(",
"'CallMethod() given method descriptor for wrong service type.'",
")",
"method",
"=",
"getattr",
"(",
"srvc",
",",
"method_descriptor",
".",
"name",
")",
"return",
"method",
"(",
"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.
rpc_controller: RPC controller to use for this method's execution.
request: Request protocol message.
callback: A callback to invoke after the method has completed. | [
"Calls",
"the",
"method",
"described",
"by",
"a",
"given",
"method",
"descriptor",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/service_reflection.py#L156-L171 |
29,221 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/service_reflection.py | _ServiceBuilder._GetRequestClass | 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
method.
"""
if method_descriptor.containing_service != self.descriptor:
raise RuntimeError(
'GetRequestClass() given method descriptor for wrong service type.')
return method_descriptor.input_type._concrete_class | python | 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
method.
"""
if method_descriptor.containing_service != self.descriptor:
raise RuntimeError(
'GetRequestClass() given method descriptor for wrong service type.')
return method_descriptor.input_type._concrete_class | [
"def",
"_GetRequestClass",
"(",
"self",
",",
"method_descriptor",
")",
":",
"if",
"method_descriptor",
".",
"containing_service",
"!=",
"self",
".",
"descriptor",
":",
"raise",
"RuntimeError",
"(",
"'GetRequestClass() given method descriptor for wrong service type.'",
")",
"return",
"method_descriptor",
".",
"input_type",
".",
"_concrete_class"
] | 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. | [
"Returns",
"the",
"class",
"of",
"the",
"request",
"protocol",
"message",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/service_reflection.py#L173-L187 |
29,222 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/service_reflection.py | _ServiceBuilder._GetResponseClass | 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 specified
method.
"""
if method_descriptor.containing_service != self.descriptor:
raise RuntimeError(
'GetResponseClass() given method descriptor for wrong service type.')
return method_descriptor.output_type._concrete_class | python | 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 specified
method.
"""
if method_descriptor.containing_service != self.descriptor:
raise RuntimeError(
'GetResponseClass() given method descriptor for wrong service type.')
return method_descriptor.output_type._concrete_class | [
"def",
"_GetResponseClass",
"(",
"self",
",",
"method_descriptor",
")",
":",
"if",
"method_descriptor",
".",
"containing_service",
"!=",
"self",
".",
"descriptor",
":",
"raise",
"RuntimeError",
"(",
"'GetResponseClass() given method descriptor for wrong service type.'",
")",
"return",
"method_descriptor",
".",
"output_type",
".",
"_concrete_class"
] | 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. | [
"Returns",
"the",
"class",
"of",
"the",
"response",
"protocol",
"message",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/service_reflection.py#L189-L203 |
29,223 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/service_reflection.py | _ServiceBuilder._GenerateNonImplementedMethod | 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 lambda inst, rpc_controller, request, callback: (
self._NonImplementedMethod(method.name, rpc_controller, callback)) | python | 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 lambda inst, rpc_controller, request, callback: (
self._NonImplementedMethod(method.name, rpc_controller, callback)) | [
"def",
"_GenerateNonImplementedMethod",
"(",
"self",
",",
"method",
")",
":",
"return",
"lambda",
"inst",
",",
"rpc_controller",
",",
"request",
",",
"callback",
":",
"(",
"self",
".",
"_NonImplementedMethod",
"(",
"method",
".",
"name",
",",
"rpc_controller",
",",
"callback",
")",
")"
] | 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. | [
"Generates",
"and",
"returns",
"a",
"method",
"that",
"can",
"be",
"set",
"for",
"a",
"service",
"methods",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/service_reflection.py#L205-L216 |
29,224 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/service_reflection.py | _ServiceStubBuilder.BuildServiceStub | 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:
setattr(cls, method.name, self._GenerateStubMethod(method)) | python | 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:
setattr(cls, method.name, self._GenerateStubMethod(method)) | [
"def",
"BuildServiceStub",
"(",
"self",
",",
"cls",
")",
":",
"def",
"_ServiceStubInit",
"(",
"stub",
",",
"rpc_channel",
")",
":",
"stub",
".",
"rpc_channel",
"=",
"rpc_channel",
"self",
".",
"cls",
"=",
"cls",
"cls",
".",
"__init__",
"=",
"_ServiceStubInit",
"for",
"method",
"in",
"self",
".",
"descriptor",
".",
"methods",
":",
"setattr",
"(",
"cls",
",",
"method",
".",
"name",
",",
"self",
".",
"_GenerateStubMethod",
"(",
"method",
")",
")"
] | Constructs the stub class.
Args:
cls: The class that will be constructed. | [
"Constructs",
"the",
"stub",
"class",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/service_reflection.py#L251-L263 |
29,225 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/service_reflection.py | _ServiceStubBuilder._StubMethod | 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 method.
request: Request protocol message.
callback: A callback to execute when the method finishes.
Returns:
Response message (in case of blocking call).
"""
return stub.rpc_channel.CallMethod(
method_descriptor, rpc_controller, request,
method_descriptor.output_type._concrete_class, callback) | python | 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 method.
request: Request protocol message.
callback: A callback to execute when the method finishes.
Returns:
Response message (in case of blocking call).
"""
return stub.rpc_channel.CallMethod(
method_descriptor, rpc_controller, request,
method_descriptor.output_type._concrete_class, callback) | [
"def",
"_StubMethod",
"(",
"self",
",",
"stub",
",",
"method_descriptor",
",",
"rpc_controller",
",",
"request",
",",
"callback",
")",
":",
"return",
"stub",
".",
"rpc_channel",
".",
"CallMethod",
"(",
"method_descriptor",
",",
"rpc_controller",
",",
"request",
",",
"method_descriptor",
".",
"output_type",
".",
"_concrete_class",
",",
"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 method.
request: Request protocol message.
callback: A callback to execute when the method finishes.
Returns:
Response message (in case of blocking call). | [
"The",
"body",
"of",
"all",
"service",
"methods",
"in",
"the",
"generated",
"stub",
"class",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/service_reflection.py#L269-L284 |
29,226 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py | _BuildMessageFromTypeName | 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
wasn't found matching type_name.
"""
# pylint: disable=g-import-not-at-top
from google.protobuf import symbol_database
database = symbol_database.Default()
try:
message_descriptor = descriptor_pool.FindMessageTypeByName(type_name)
except KeyError:
return None
message_type = database.GetPrototype(message_descriptor)
return message_type() | python | 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
wasn't found matching type_name.
"""
# pylint: disable=g-import-not-at-top
from google.protobuf import symbol_database
database = symbol_database.Default()
try:
message_descriptor = descriptor_pool.FindMessageTypeByName(type_name)
except KeyError:
return None
message_type = database.GetPrototype(message_descriptor)
return message_type() | [
"def",
"_BuildMessageFromTypeName",
"(",
"type_name",
",",
"descriptor_pool",
")",
":",
"# pylint: disable=g-import-not-at-top",
"from",
"google",
".",
"protobuf",
"import",
"symbol_database",
"database",
"=",
"symbol_database",
".",
"Default",
"(",
")",
"try",
":",
"message_descriptor",
"=",
"descriptor_pool",
".",
"FindMessageTypeByName",
"(",
"type_name",
")",
"except",
"KeyError",
":",
"return",
"None",
"message_type",
"=",
"database",
".",
"GetPrototype",
"(",
"message_descriptor",
")",
"return",
"message_type",
"(",
")"
] | 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. | [
"Returns",
"a",
"protobuf",
"message",
"instance",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L219-L238 |
29,227 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py | _SkipFieldMessage | 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('}'):
_SkipField(tokenizer)
tokenizer.Consume(delimiter) | python | 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('}'):
_SkipField(tokenizer)
tokenizer.Consume(delimiter) | [
"def",
"_SkipFieldMessage",
"(",
"tokenizer",
")",
":",
"if",
"tokenizer",
".",
"TryConsume",
"(",
"'<'",
")",
":",
"delimiter",
"=",
"'>'",
"else",
":",
"tokenizer",
".",
"Consume",
"(",
"'{'",
")",
"delimiter",
"=",
"'}'",
"while",
"not",
"tokenizer",
".",
"LookingAt",
"(",
"'>'",
")",
"and",
"not",
"tokenizer",
".",
"LookingAt",
"(",
"'}'",
")",
":",
"_SkipField",
"(",
"tokenizer",
")",
"tokenizer",
".",
"Consume",
"(",
"delimiter",
")"
] | Skips over a field message.
Args:
tokenizer: A tokenizer to parse the field name and values. | [
"Skips",
"over",
"a",
"field",
"message",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L890-L906 |
29,228 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py | _SkipFieldValue | 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 many as we can.
if tokenizer.TryConsumeByteString():
while tokenizer.TryConsumeByteString():
pass
return
if (not tokenizer.TryConsumeIdentifier() and
not _TryConsumeInt64(tokenizer) and not _TryConsumeUint64(tokenizer) and
not tokenizer.TryConsumeFloat()):
raise ParseError('Invalid field value: ' + tokenizer.token) | python | 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 many as we can.
if tokenizer.TryConsumeByteString():
while tokenizer.TryConsumeByteString():
pass
return
if (not tokenizer.TryConsumeIdentifier() and
not _TryConsumeInt64(tokenizer) and not _TryConsumeUint64(tokenizer) and
not tokenizer.TryConsumeFloat()):
raise ParseError('Invalid field value: ' + tokenizer.token) | [
"def",
"_SkipFieldValue",
"(",
"tokenizer",
")",
":",
"# String/bytes tokens can come in multiple adjacent string literals.",
"# If we can consume one, consume as many as we can.",
"if",
"tokenizer",
".",
"TryConsumeByteString",
"(",
")",
":",
"while",
"tokenizer",
".",
"TryConsumeByteString",
"(",
")",
":",
"pass",
"return",
"if",
"(",
"not",
"tokenizer",
".",
"TryConsumeIdentifier",
"(",
")",
"and",
"not",
"_TryConsumeInt64",
"(",
"tokenizer",
")",
"and",
"not",
"_TryConsumeUint64",
"(",
"tokenizer",
")",
"and",
"not",
"tokenizer",
".",
"TryConsumeFloat",
"(",
")",
")",
":",
"raise",
"ParseError",
"(",
"'Invalid field value: '",
"+",
"tokenizer",
".",
"token",
")"
] | 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. | [
"Skips",
"over",
"a",
"field",
"value",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L909-L928 |
29,229 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py | _ConsumeInteger | 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.
Raises:
ParseError: If an integer with given characteristics couldn't be consumed.
"""
try:
result = ParseInteger(tokenizer.token, is_signed=is_signed, is_long=is_long)
except ValueError as e:
raise tokenizer.ParseError(str(e))
tokenizer.NextToken()
return result | python | 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.
Raises:
ParseError: If an integer with given characteristics couldn't be consumed.
"""
try:
result = ParseInteger(tokenizer.token, is_signed=is_signed, is_long=is_long)
except ValueError as e:
raise tokenizer.ParseError(str(e))
tokenizer.NextToken()
return result | [
"def",
"_ConsumeInteger",
"(",
"tokenizer",
",",
"is_signed",
"=",
"False",
",",
"is_long",
"=",
"False",
")",
":",
"try",
":",
"result",
"=",
"ParseInteger",
"(",
"tokenizer",
".",
"token",
",",
"is_signed",
"=",
"is_signed",
",",
"is_long",
"=",
"is_long",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"tokenizer",
".",
"ParseError",
"(",
"str",
"(",
"e",
")",
")",
"tokenizer",
".",
"NextToken",
"(",
")",
"return",
"result"
] | 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 couldn't be consumed. | [
"Consumes",
"an",
"integer",
"number",
"from",
"tokenizer",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L1359-L1378 |
29,230 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py | ParseInteger | 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 valid integer.
"""
# Do the actual parsing. Exception handling is propagated to caller.
result = _ParseAbstractInteger(text, is_long=is_long)
# Check if the integer is sane. Exceptions handled by callers.
checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)]
checker.CheckValue(result)
return result | python | 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 valid integer.
"""
# Do the actual parsing. Exception handling is propagated to caller.
result = _ParseAbstractInteger(text, is_long=is_long)
# Check if the integer is sane. Exceptions handled by callers.
checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)]
checker.CheckValue(result)
return result | [
"def",
"ParseInteger",
"(",
"text",
",",
"is_signed",
"=",
"False",
",",
"is_long",
"=",
"False",
")",
":",
"# Do the actual parsing. Exception handling is propagated to caller.",
"result",
"=",
"_ParseAbstractInteger",
"(",
"text",
",",
"is_long",
"=",
"is_long",
")",
"# Check if the integer is sane. Exceptions handled by callers.",
"checker",
"=",
"_INTEGER_CHECKERS",
"[",
"2",
"*",
"int",
"(",
"is_long",
")",
"+",
"int",
"(",
"is_signed",
")",
"]",
"checker",
".",
"CheckValue",
"(",
"result",
")",
"return",
"result"
] | 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. | [
"Parses",
"an",
"integer",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L1381-L1401 |
29,231 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py | ParseFloat | 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 spellings.
if _FLOAT_INFINITY.match(text):
if text[0] == '-':
return float('-inf')
else:
return float('inf')
elif _FLOAT_NAN.match(text):
return float('nan')
else:
# assume '1.0f' format
try:
return float(text.rstrip('f'))
except ValueError:
raise ValueError('Couldn\'t parse float: %s' % text) | python | 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 spellings.
if _FLOAT_INFINITY.match(text):
if text[0] == '-':
return float('-inf')
else:
return float('inf')
elif _FLOAT_NAN.match(text):
return float('nan')
else:
# assume '1.0f' format
try:
return float(text.rstrip('f'))
except ValueError:
raise ValueError('Couldn\'t parse float: %s' % text) | [
"def",
"ParseFloat",
"(",
"text",
")",
":",
"try",
":",
"# Assume Python compatible syntax.",
"return",
"float",
"(",
"text",
")",
"except",
"ValueError",
":",
"# Check alternative spellings.",
"if",
"_FLOAT_INFINITY",
".",
"match",
"(",
"text",
")",
":",
"if",
"text",
"[",
"0",
"]",
"==",
"'-'",
":",
"return",
"float",
"(",
"'-inf'",
")",
"else",
":",
"return",
"float",
"(",
"'inf'",
")",
"elif",
"_FLOAT_NAN",
".",
"match",
"(",
"text",
")",
":",
"return",
"float",
"(",
"'nan'",
")",
"else",
":",
"# assume '1.0f' format",
"try",
":",
"return",
"float",
"(",
"text",
".",
"rstrip",
"(",
"'f'",
")",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'Couldn\\'t parse float: %s'",
"%",
"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. | [
"Parse",
"a",
"floating",
"point",
"number",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L1430-L1459 |
29,232 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py | ParseEnum | 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 parsed.
"""
enum_descriptor = field.enum_type
try:
number = int(value, 0)
except ValueError:
# Identifier.
enum_value = enum_descriptor.values_by_name.get(value, None)
if enum_value is None:
raise ValueError('Enum type "%s" has no value named %s.' %
(enum_descriptor.full_name, value))
else:
# Numeric value.
enum_value = enum_descriptor.values_by_number.get(number, None)
if enum_value is None:
raise ValueError('Enum type "%s" has no value with number %d.' %
(enum_descriptor.full_name, number))
return enum_value.number | python | 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 parsed.
"""
enum_descriptor = field.enum_type
try:
number = int(value, 0)
except ValueError:
# Identifier.
enum_value = enum_descriptor.values_by_name.get(value, None)
if enum_value is None:
raise ValueError('Enum type "%s" has no value named %s.' %
(enum_descriptor.full_name, value))
else:
# Numeric value.
enum_value = enum_descriptor.values_by_number.get(number, None)
if enum_value is None:
raise ValueError('Enum type "%s" has no value with number %d.' %
(enum_descriptor.full_name, number))
return enum_value.number | [
"def",
"ParseEnum",
"(",
"field",
",",
"value",
")",
":",
"enum_descriptor",
"=",
"field",
".",
"enum_type",
"try",
":",
"number",
"=",
"int",
"(",
"value",
",",
"0",
")",
"except",
"ValueError",
":",
"# Identifier.",
"enum_value",
"=",
"enum_descriptor",
".",
"values_by_name",
".",
"get",
"(",
"value",
",",
"None",
")",
"if",
"enum_value",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Enum type \"%s\" has no value named %s.'",
"%",
"(",
"enum_descriptor",
".",
"full_name",
",",
"value",
")",
")",
"else",
":",
"# Numeric value.",
"enum_value",
"=",
"enum_descriptor",
".",
"values_by_number",
".",
"get",
"(",
"number",
",",
"None",
")",
"if",
"enum_value",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Enum type \"%s\" has no value with number %d.'",
"%",
"(",
"enum_descriptor",
".",
"full_name",
",",
"number",
")",
")",
"return",
"enum_value",
".",
"number"
] | 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. | [
"Parse",
"an",
"enum",
"value",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L1482-L1513 |
29,233 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py | _Printer._TryPrintAsAnyMessage | 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)
self.out.write('%s[%s]' % (self.indent * ' ', message.type_url))
self._PrintMessageFieldValue(packed_message)
self.out.write(' ' if self.as_one_line else '\n')
return True
else:
return False | python | 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)
self.out.write('%s[%s]' % (self.indent * ' ', message.type_url))
self._PrintMessageFieldValue(packed_message)
self.out.write(' ' if self.as_one_line else '\n')
return True
else:
return False | [
"def",
"_TryPrintAsAnyMessage",
"(",
"self",
",",
"message",
")",
":",
"packed_message",
"=",
"_BuildMessageFromTypeName",
"(",
"message",
".",
"TypeName",
"(",
")",
",",
"self",
".",
"descriptor_pool",
")",
"if",
"packed_message",
":",
"packed_message",
".",
"MergeFromString",
"(",
"message",
".",
"value",
")",
"self",
".",
"out",
".",
"write",
"(",
"'%s[%s]'",
"%",
"(",
"self",
".",
"indent",
"*",
"' '",
",",
"message",
".",
"type_url",
")",
")",
"self",
".",
"_PrintMessageFieldValue",
"(",
"packed_message",
")",
"self",
".",
"out",
".",
"write",
"(",
"' '",
"if",
"self",
".",
"as_one_line",
"else",
"'\\n'",
")",
"return",
"True",
"else",
":",
"return",
"False"
] | Serializes if message is a google.protobuf.Any field. | [
"Serializes",
"if",
"message",
"is",
"a",
"google",
".",
"protobuf",
".",
"Any",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L287-L298 |
29,234 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py | _Parser.MergeLines | 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 | python | 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 | [
"def",
"MergeLines",
"(",
"self",
",",
"lines",
",",
"message",
")",
":",
"self",
".",
"_allow_multiple_scalars",
"=",
"True",
"self",
".",
"_ParseOrMerge",
"(",
"lines",
",",
"message",
")",
"return",
"message"
] | Merges a text representation of a protocol message into a message. | [
"Merges",
"a",
"text",
"representation",
"of",
"a",
"protocol",
"message",
"into",
"a",
"message",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L565-L569 |
29,235 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py | _Parser._ParseOrMerge | 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 = Tokenizer(lines)
while not tokenizer.AtEnd():
self._MergeField(tokenizer, message) | python | 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 = Tokenizer(lines)
while not tokenizer.AtEnd():
self._MergeField(tokenizer, message) | [
"def",
"_ParseOrMerge",
"(",
"self",
",",
"lines",
",",
"message",
")",
":",
"tokenizer",
"=",
"Tokenizer",
"(",
"lines",
")",
"while",
"not",
"tokenizer",
".",
"AtEnd",
"(",
")",
":",
"self",
".",
"_MergeField",
"(",
"tokenizer",
",",
"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. | [
"Converts",
"a",
"text",
"representation",
"of",
"a",
"protocol",
"message",
"into",
"a",
"message",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L571-L583 |
29,236 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py | _Parser._ConsumeAnyTypeUrl | 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()
tokenizer.Consume('/')
# Consume the fully-qualified type name.
name = [tokenizer.ConsumeIdentifier()]
while tokenizer.TryConsume('.'):
name.append(tokenizer.ConsumeIdentifier())
return '.'.join(name) | python | 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()
tokenizer.Consume('/')
# Consume the fully-qualified type name.
name = [tokenizer.ConsumeIdentifier()]
while tokenizer.TryConsume('.'):
name.append(tokenizer.ConsumeIdentifier())
return '.'.join(name) | [
"def",
"_ConsumeAnyTypeUrl",
"(",
"self",
",",
"tokenizer",
")",
":",
"# Consume \"type.googleapis.com/\".",
"tokenizer",
".",
"ConsumeIdentifier",
"(",
")",
"tokenizer",
".",
"Consume",
"(",
"'.'",
")",
"tokenizer",
".",
"ConsumeIdentifier",
"(",
")",
"tokenizer",
".",
"Consume",
"(",
"'.'",
")",
"tokenizer",
".",
"ConsumeIdentifier",
"(",
")",
"tokenizer",
".",
"Consume",
"(",
"'/'",
")",
"# Consume the fully-qualified type name.",
"name",
"=",
"[",
"tokenizer",
".",
"ConsumeIdentifier",
"(",
")",
"]",
"while",
"tokenizer",
".",
"TryConsume",
"(",
"'.'",
")",
":",
"name",
".",
"append",
"(",
"tokenizer",
".",
"ConsumeIdentifier",
"(",
")",
")",
"return",
"'.'",
".",
"join",
"(",
"name",
")"
] | Consumes a google.protobuf.Any type URL and returns the type name. | [
"Consumes",
"a",
"google",
".",
"protobuf",
".",
"Any",
"type",
"URL",
"and",
"returns",
"the",
"type",
"name",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L695-L708 |
29,237 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py | Tokenizer.TryConsume | 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 | python | 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 | [
"def",
"TryConsume",
"(",
"self",
",",
"token",
")",
":",
"if",
"self",
".",
"token",
"==",
"token",
":",
"self",
".",
"NextToken",
"(",
")",
"return",
"True",
"return",
"False"
] | Tries to consume a given piece of text.
Args:
token: Text to consume.
Returns:
True iff the text was consumed. | [
"Tries",
"to",
"consume",
"a",
"given",
"piece",
"of",
"text",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L1002-L1014 |
29,238 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py | Tokenizer.ConsumeInteger | 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(self.token, is_long=is_long)
except ValueError as e:
raise self.ParseError(str(e))
self.NextToken()
return result | python | 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(self.token, is_long=is_long)
except ValueError as e:
raise self.ParseError(str(e))
self.NextToken()
return result | [
"def",
"ConsumeInteger",
"(",
"self",
",",
"is_long",
"=",
"False",
")",
":",
"try",
":",
"result",
"=",
"_ParseAbstractInteger",
"(",
"self",
".",
"token",
",",
"is_long",
"=",
"is_long",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"self",
".",
"ParseError",
"(",
"str",
"(",
"e",
")",
")",
"self",
".",
"NextToken",
"(",
")",
"return",
"result"
] | 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. | [
"Consumes",
"an",
"integer",
"number",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L1103-L1119 |
29,239 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py | Tokenizer.ConsumeString | 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 self._StringParseError(e) | python | 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 self._StringParseError(e) | [
"def",
"ConsumeString",
"(",
"self",
")",
":",
"the_bytes",
"=",
"self",
".",
"ConsumeByteString",
"(",
")",
"try",
":",
"return",
"six",
".",
"text_type",
"(",
"the_bytes",
",",
"'utf-8'",
")",
"except",
"UnicodeDecodeError",
"as",
"e",
":",
"raise",
"self",
".",
"_StringParseError",
"(",
"e",
")"
] | Consumes a string value.
Returns:
The string parsed.
Raises:
ParseError: If a string value couldn't be consumed. | [
"Consumes",
"a",
"string",
"value",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L1167-L1180 |
29,240 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py | Tokenizer.ConsumeByteString | 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.append(self._ConsumeSingleByteString())
return b''.join(the_list) | python | 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.append(self._ConsumeSingleByteString())
return b''.join(the_list) | [
"def",
"ConsumeByteString",
"(",
"self",
")",
":",
"the_list",
"=",
"[",
"self",
".",
"_ConsumeSingleByteString",
"(",
")",
"]",
"while",
"self",
".",
"token",
"and",
"self",
".",
"token",
"[",
"0",
"]",
"in",
"_QUOTES",
":",
"the_list",
".",
"append",
"(",
"self",
".",
"_ConsumeSingleByteString",
"(",
")",
")",
"return",
"b''",
".",
"join",
"(",
"the_list",
")"
] | Consumes a byte array value.
Returns:
The array parsed (as a string).
Raises:
ParseError: If a byte array value couldn't be consumed. | [
"Consumes",
"a",
"byte",
"array",
"value",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L1182-L1194 |
29,241 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py | Tokenizer.NextToken | 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, self._column)
if not match and not self._skip_comments:
match = self._COMMENT.match(self._current_line, self._column)
if match:
token = match.group(0)
self.token = token
else:
self.token = self._current_line[self._column] | python | 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, self._column)
if not match and not self._skip_comments:
match = self._COMMENT.match(self._current_line, self._column)
if match:
token = match.group(0)
self.token = token
else:
self.token = self._current_line[self._column] | [
"def",
"NextToken",
"(",
"self",
")",
":",
"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",
",",
"self",
".",
"_column",
")",
"if",
"not",
"match",
"and",
"not",
"self",
".",
"_skip_comments",
":",
"match",
"=",
"self",
".",
"_COMMENT",
".",
"match",
"(",
"self",
".",
"_current_line",
",",
"self",
".",
"_column",
")",
"if",
"match",
":",
"token",
"=",
"match",
".",
"group",
"(",
"0",
")",
"self",
".",
"token",
"=",
"token",
"else",
":",
"self",
".",
"token",
"=",
"self",
".",
"_current_line",
"[",
"self",
".",
"_column",
"]"
] | Reads the next meaningful token. | [
"Reads",
"the",
"next",
"meaningful",
"token",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L1249-L1268 |
29,242 | apple/turicreate | src/unity/python/turicreate/toolkits/distances/_util.py | compute_composite_distance | def compute_composite_distance(distance, x, y):
"""
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 own subset of features. Composite distance functions are specified
as a list of distance components, each of which is itself a list
containing three items:
1. list or tuple of feature names (strings)
2. standard distance name (string)
3. scaling factor (int or float)
x, y : dict
Individual observations, typically rows of an SFrame, in dictionary
form. Must include the features specified by `distance`.
Returns
-------
out : float
The distance between `x` and `y`, as specified by `distance`.
Examples
--------
>>> sf = turicreate.SFrame({'X1': [0.98, 0.62, 0.11],
... 'X2': [0.69, 0.58, 0.36],
... 'species': ['cat', 'dog', 'fossa']})
...
>>> dist_spec = [[('X1', 'X2'), 'euclidean', 2],
... [('species',), 'levenshtein', 0.4]]
...
>>> d = turicreate.distances.compute_composite_distance(dist_spec, sf[0], sf[1])
>>> print d
1.95286120899
"""
## Validate inputs
_validate_composite_distance(distance)
distance = _convert_distance_names_to_functions(distance)
if not isinstance(x, dict) or not isinstance(y, dict):
raise TypeError("Inputs 'x' and 'y' must be in dictionary form. " +
"Selecting individual rows of an SFrame yields the " +
"correct format.")
ans = 0.
for d in distance:
ftrs, dist, weight = d
## Special check for multiple columns with levenshtein distance.
if dist == _tc.distances.levenshtein and len(ftrs) > 1:
raise ValueError("levenshtein distance cannot be used with multiple" +
"columns. Please concatenate strings into a single " +
"column before computing the distance.")
## Extract values for specified features.
a = {}
b = {}
for ftr in ftrs:
if type(x[ftr]) != type(y[ftr]):
if not isinstance(x[ftr], (int, float)) or not isinstance(y[ftr], (int, float)):
raise ValueError("Input data has different types.")
if isinstance(x[ftr], (int, float, str)):
a[ftr] = x[ftr]
b[ftr] = y[ftr]
elif isinstance(x[ftr], dict):
for key, val in _six.iteritems(x[ftr]):
a['{}.{}'.format(ftr, key)] = val
for key, val in _six.iteritems(y[ftr]):
b['{}.{}'.format(ftr, key)] = val
elif isinstance(x[ftr], (list, _array.array)):
for i, val in enumerate(x[ftr]):
a[i] = val
for i, val in enumerate(y[ftr]):
b[i] = val
else:
raise TypeError("Type of feature '{}' not understood.".format(ftr))
## Pull out the raw values for levenshtein
if dist == _tc.distances.levenshtein:
a = list(a.values())[0]
b = list(b.values())[0]
## Compute component distance and add to the total distance.
ans += weight * dist(a, b)
return ans | python | def compute_composite_distance(distance, x, y):
"""
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 own subset of features. Composite distance functions are specified
as a list of distance components, each of which is itself a list
containing three items:
1. list or tuple of feature names (strings)
2. standard distance name (string)
3. scaling factor (int or float)
x, y : dict
Individual observations, typically rows of an SFrame, in dictionary
form. Must include the features specified by `distance`.
Returns
-------
out : float
The distance between `x` and `y`, as specified by `distance`.
Examples
--------
>>> sf = turicreate.SFrame({'X1': [0.98, 0.62, 0.11],
... 'X2': [0.69, 0.58, 0.36],
... 'species': ['cat', 'dog', 'fossa']})
...
>>> dist_spec = [[('X1', 'X2'), 'euclidean', 2],
... [('species',), 'levenshtein', 0.4]]
...
>>> d = turicreate.distances.compute_composite_distance(dist_spec, sf[0], sf[1])
>>> print d
1.95286120899
"""
## Validate inputs
_validate_composite_distance(distance)
distance = _convert_distance_names_to_functions(distance)
if not isinstance(x, dict) or not isinstance(y, dict):
raise TypeError("Inputs 'x' and 'y' must be in dictionary form. " +
"Selecting individual rows of an SFrame yields the " +
"correct format.")
ans = 0.
for d in distance:
ftrs, dist, weight = d
## Special check for multiple columns with levenshtein distance.
if dist == _tc.distances.levenshtein and len(ftrs) > 1:
raise ValueError("levenshtein distance cannot be used with multiple" +
"columns. Please concatenate strings into a single " +
"column before computing the distance.")
## Extract values for specified features.
a = {}
b = {}
for ftr in ftrs:
if type(x[ftr]) != type(y[ftr]):
if not isinstance(x[ftr], (int, float)) or not isinstance(y[ftr], (int, float)):
raise ValueError("Input data has different types.")
if isinstance(x[ftr], (int, float, str)):
a[ftr] = x[ftr]
b[ftr] = y[ftr]
elif isinstance(x[ftr], dict):
for key, val in _six.iteritems(x[ftr]):
a['{}.{}'.format(ftr, key)] = val
for key, val in _six.iteritems(y[ftr]):
b['{}.{}'.format(ftr, key)] = val
elif isinstance(x[ftr], (list, _array.array)):
for i, val in enumerate(x[ftr]):
a[i] = val
for i, val in enumerate(y[ftr]):
b[i] = val
else:
raise TypeError("Type of feature '{}' not understood.".format(ftr))
## Pull out the raw values for levenshtein
if dist == _tc.distances.levenshtein:
a = list(a.values())[0]
b = list(b.values())[0]
## Compute component distance and add to the total distance.
ans += weight * dist(a, b)
return ans | [
"def",
"compute_composite_distance",
"(",
"distance",
",",
"x",
",",
"y",
")",
":",
"## Validate inputs",
"_validate_composite_distance",
"(",
"distance",
")",
"distance",
"=",
"_convert_distance_names_to_functions",
"(",
"distance",
")",
"if",
"not",
"isinstance",
"(",
"x",
",",
"dict",
")",
"or",
"not",
"isinstance",
"(",
"y",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"Inputs 'x' and 'y' must be in dictionary form. \"",
"+",
"\"Selecting individual rows of an SFrame yields the \"",
"+",
"\"correct format.\"",
")",
"ans",
"=",
"0.",
"for",
"d",
"in",
"distance",
":",
"ftrs",
",",
"dist",
",",
"weight",
"=",
"d",
"## Special check for multiple columns with levenshtein distance.",
"if",
"dist",
"==",
"_tc",
".",
"distances",
".",
"levenshtein",
"and",
"len",
"(",
"ftrs",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"levenshtein distance cannot be used with multiple\"",
"+",
"\"columns. Please concatenate strings into a single \"",
"+",
"\"column before computing the distance.\"",
")",
"## Extract values for specified features.",
"a",
"=",
"{",
"}",
"b",
"=",
"{",
"}",
"for",
"ftr",
"in",
"ftrs",
":",
"if",
"type",
"(",
"x",
"[",
"ftr",
"]",
")",
"!=",
"type",
"(",
"y",
"[",
"ftr",
"]",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
"[",
"ftr",
"]",
",",
"(",
"int",
",",
"float",
")",
")",
"or",
"not",
"isinstance",
"(",
"y",
"[",
"ftr",
"]",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Input data has different types.\"",
")",
"if",
"isinstance",
"(",
"x",
"[",
"ftr",
"]",
",",
"(",
"int",
",",
"float",
",",
"str",
")",
")",
":",
"a",
"[",
"ftr",
"]",
"=",
"x",
"[",
"ftr",
"]",
"b",
"[",
"ftr",
"]",
"=",
"y",
"[",
"ftr",
"]",
"elif",
"isinstance",
"(",
"x",
"[",
"ftr",
"]",
",",
"dict",
")",
":",
"for",
"key",
",",
"val",
"in",
"_six",
".",
"iteritems",
"(",
"x",
"[",
"ftr",
"]",
")",
":",
"a",
"[",
"'{}.{}'",
".",
"format",
"(",
"ftr",
",",
"key",
")",
"]",
"=",
"val",
"for",
"key",
",",
"val",
"in",
"_six",
".",
"iteritems",
"(",
"y",
"[",
"ftr",
"]",
")",
":",
"b",
"[",
"'{}.{}'",
".",
"format",
"(",
"ftr",
",",
"key",
")",
"]",
"=",
"val",
"elif",
"isinstance",
"(",
"x",
"[",
"ftr",
"]",
",",
"(",
"list",
",",
"_array",
".",
"array",
")",
")",
":",
"for",
"i",
",",
"val",
"in",
"enumerate",
"(",
"x",
"[",
"ftr",
"]",
")",
":",
"a",
"[",
"i",
"]",
"=",
"val",
"for",
"i",
",",
"val",
"in",
"enumerate",
"(",
"y",
"[",
"ftr",
"]",
")",
":",
"b",
"[",
"i",
"]",
"=",
"val",
"else",
":",
"raise",
"TypeError",
"(",
"\"Type of feature '{}' not understood.\"",
".",
"format",
"(",
"ftr",
")",
")",
"## Pull out the raw values for levenshtein",
"if",
"dist",
"==",
"_tc",
".",
"distances",
".",
"levenshtein",
":",
"a",
"=",
"list",
"(",
"a",
".",
"values",
"(",
")",
")",
"[",
"0",
"]",
"b",
"=",
"list",
"(",
"b",
".",
"values",
"(",
")",
")",
"[",
"0",
"]",
"## Compute component distance and add to the total distance.",
"ans",
"+=",
"weight",
"*",
"dist",
"(",
"a",
",",
"b",
")",
"return",
"ans"
] | 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 own subset of features. Composite distance functions are specified
as a list of distance components, each of which is itself a list
containing three items:
1. list or tuple of feature names (strings)
2. standard distance name (string)
3. scaling factor (int or float)
x, y : dict
Individual observations, typically rows of an SFrame, in dictionary
form. Must include the features specified by `distance`.
Returns
-------
out : float
The distance between `x` and `y`, as specified by `distance`.
Examples
--------
>>> sf = turicreate.SFrame({'X1': [0.98, 0.62, 0.11],
... 'X2': [0.69, 0.58, 0.36],
... 'species': ['cat', 'dog', 'fossa']})
...
>>> dist_spec = [[('X1', 'X2'), 'euclidean', 2],
... [('species',), 'levenshtein', 0.4]]
...
>>> d = turicreate.distances.compute_composite_distance(dist_spec, sf[0], sf[1])
>>> print d
1.95286120899 | [
"Compute",
"the",
"value",
"of",
"a",
"composite",
"distance",
"function",
"on",
"two",
"dictionaries",
"typically",
"SFrame",
"rows",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/distances/_util.py#L24-L126 |
29,243 | apple/turicreate | src/unity/python/turicreate/toolkits/distances/_util.py | _validate_composite_distance | 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):
raise TypeError("Input 'distance' must be a composite distance.")
if len(distance) < 1:
raise ValueError("Composite distances must have a least one distance "
"component, consisting of a list of feature names, "
"a distance function (string or function handle), "
"and a weight.")
for d in distance:
## Extract individual pieces of the distance component
try:
ftrs, dist, weight = d
except:
raise TypeError("Elements of a composite distance function must " +
"have three items: a set of feature names (tuple or list), " +
"a distance function (string or function handle), " +
"and a weight.")
## Validate feature names
if len(ftrs) == 0:
raise ValueError("An empty list of features cannot be passed " +\
"as part of a composite distance function.")
if not isinstance(ftrs, (list, tuple)):
raise TypeError("Feature names must be specified in a list or tuple.")
if not all([isinstance(x, str) for x in ftrs]):
raise TypeError("Feature lists must contain only strings.")
## Validate standard distance function
if not isinstance(dist, str) and not hasattr(dist, '__call__'):
raise ValueError("Standard distances must be the name of a distance " +
"function (string) or a distance function handle")
if isinstance(dist, str):
try:
_tc.distances.__dict__[dist]
except:
raise ValueError("Distance '{}' not recognized".format(dist))
## Validate weight
if not isinstance(weight, (int, float)):
raise ValueError(
"The weight of each distance component must be a single " +\
"integer or a float value.")
if weight < 0:
raise ValueError("The weight on each distance component must be " +
"greater than or equal to zero.") | python | 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):
raise TypeError("Input 'distance' must be a composite distance.")
if len(distance) < 1:
raise ValueError("Composite distances must have a least one distance "
"component, consisting of a list of feature names, "
"a distance function (string or function handle), "
"and a weight.")
for d in distance:
## Extract individual pieces of the distance component
try:
ftrs, dist, weight = d
except:
raise TypeError("Elements of a composite distance function must " +
"have three items: a set of feature names (tuple or list), " +
"a distance function (string or function handle), " +
"and a weight.")
## Validate feature names
if len(ftrs) == 0:
raise ValueError("An empty list of features cannot be passed " +\
"as part of a composite distance function.")
if not isinstance(ftrs, (list, tuple)):
raise TypeError("Feature names must be specified in a list or tuple.")
if not all([isinstance(x, str) for x in ftrs]):
raise TypeError("Feature lists must contain only strings.")
## Validate standard distance function
if not isinstance(dist, str) and not hasattr(dist, '__call__'):
raise ValueError("Standard distances must be the name of a distance " +
"function (string) or a distance function handle")
if isinstance(dist, str):
try:
_tc.distances.__dict__[dist]
except:
raise ValueError("Distance '{}' not recognized".format(dist))
## Validate weight
if not isinstance(weight, (int, float)):
raise ValueError(
"The weight of each distance component must be a single " +\
"integer or a float value.")
if weight < 0:
raise ValueError("The weight on each distance component must be " +
"greater than or equal to zero.") | [
"def",
"_validate_composite_distance",
"(",
"distance",
")",
":",
"if",
"not",
"isinstance",
"(",
"distance",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"Input 'distance' must be a composite distance.\"",
")",
"if",
"len",
"(",
"distance",
")",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"Composite distances must have a least one distance \"",
"\"component, consisting of a list of feature names, \"",
"\"a distance function (string or function handle), \"",
"\"and a weight.\"",
")",
"for",
"d",
"in",
"distance",
":",
"## Extract individual pieces of the distance component",
"try",
":",
"ftrs",
",",
"dist",
",",
"weight",
"=",
"d",
"except",
":",
"raise",
"TypeError",
"(",
"\"Elements of a composite distance function must \"",
"+",
"\"have three items: a set of feature names (tuple or list), \"",
"+",
"\"a distance function (string or function handle), \"",
"+",
"\"and a weight.\"",
")",
"## Validate feature names",
"if",
"len",
"(",
"ftrs",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"An empty list of features cannot be passed \"",
"+",
"\"as part of a composite distance function.\"",
")",
"if",
"not",
"isinstance",
"(",
"ftrs",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Feature names must be specified in a list or tuple.\"",
")",
"if",
"not",
"all",
"(",
"[",
"isinstance",
"(",
"x",
",",
"str",
")",
"for",
"x",
"in",
"ftrs",
"]",
")",
":",
"raise",
"TypeError",
"(",
"\"Feature lists must contain only strings.\"",
")",
"## Validate standard distance function",
"if",
"not",
"isinstance",
"(",
"dist",
",",
"str",
")",
"and",
"not",
"hasattr",
"(",
"dist",
",",
"'__call__'",
")",
":",
"raise",
"ValueError",
"(",
"\"Standard distances must be the name of a distance \"",
"+",
"\"function (string) or a distance function handle\"",
")",
"if",
"isinstance",
"(",
"dist",
",",
"str",
")",
":",
"try",
":",
"_tc",
".",
"distances",
".",
"__dict__",
"[",
"dist",
"]",
"except",
":",
"raise",
"ValueError",
"(",
"\"Distance '{}' not recognized\"",
".",
"format",
"(",
"dist",
")",
")",
"## Validate weight",
"if",
"not",
"isinstance",
"(",
"weight",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"The weight of each distance component must be a single \"",
"+",
"\"integer or a float value.\"",
")",
"if",
"weight",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"The weight on each distance component must be \"",
"+",
"\"greater than or equal to zero.\"",
")"
] | Check that composite distance function is in valid form. Don't modify the
composite distance in any way. | [
"Check",
"that",
"composite",
"distance",
"function",
"is",
"in",
"valid",
"form",
".",
"Don",
"t",
"modify",
"the",
"composite",
"distance",
"in",
"any",
"way",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/distances/_util.py#L129-L187 |
29,244 | apple/turicreate | src/unity/python/turicreate/toolkits/distances/_util.py | _scrub_composite_distance_features | 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):
ftrs, dist, weight = d
new_ftrs = [x for x in ftrs if x not in feature_blacklist]
if len(new_ftrs) > 0:
dist_out.append([new_ftrs, dist, weight])
return dist_out | python | 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):
ftrs, dist, weight = d
new_ftrs = [x for x in ftrs if x not in feature_blacklist]
if len(new_ftrs) > 0:
dist_out.append([new_ftrs, dist, weight])
return dist_out | [
"def",
"_scrub_composite_distance_features",
"(",
"distance",
",",
"feature_blacklist",
")",
":",
"dist_out",
"=",
"[",
"]",
"for",
"i",
",",
"d",
"in",
"enumerate",
"(",
"distance",
")",
":",
"ftrs",
",",
"dist",
",",
"weight",
"=",
"d",
"new_ftrs",
"=",
"[",
"x",
"for",
"x",
"in",
"ftrs",
"if",
"x",
"not",
"in",
"feature_blacklist",
"]",
"if",
"len",
"(",
"new_ftrs",
")",
">",
"0",
":",
"dist_out",
".",
"append",
"(",
"[",
"new_ftrs",
",",
"dist",
",",
"weight",
"]",
")",
"return",
"dist_out"
] | Remove feature names from the feature lists in a composite distance
function. | [
"Remove",
"feature",
"names",
"from",
"the",
"feature",
"lists",
"in",
"a",
"composite",
"distance",
"function",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/distances/_util.py#L190-L203 |
29,245 | apple/turicreate | src/unity/python/turicreate/toolkits/distances/_util.py | _convert_distance_names_to_functions | 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):
_, dist, _ = d
if isinstance(dist, str):
try:
dist_out[i][1] = _tc.distances.__dict__[dist]
except:
raise ValueError("Distance '{}' not recognized.".format(dist))
return dist_out | python | 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):
_, dist, _ = d
if isinstance(dist, str):
try:
dist_out[i][1] = _tc.distances.__dict__[dist]
except:
raise ValueError("Distance '{}' not recognized.".format(dist))
return dist_out | [
"def",
"_convert_distance_names_to_functions",
"(",
"distance",
")",
":",
"dist_out",
"=",
"_copy",
".",
"deepcopy",
"(",
"distance",
")",
"for",
"i",
",",
"d",
"in",
"enumerate",
"(",
"distance",
")",
":",
"_",
",",
"dist",
",",
"_",
"=",
"d",
"if",
"isinstance",
"(",
"dist",
",",
"str",
")",
":",
"try",
":",
"dist_out",
"[",
"i",
"]",
"[",
"1",
"]",
"=",
"_tc",
".",
"distances",
".",
"__dict__",
"[",
"dist",
"]",
"except",
":",
"raise",
"ValueError",
"(",
"\"Distance '{}' not recognized.\"",
".",
"format",
"(",
"dist",
")",
")",
"return",
"dist_out"
] | Convert function names in a composite distance function into function
handles. | [
"Convert",
"function",
"names",
"in",
"a",
"composite",
"distance",
"function",
"into",
"function",
"handles",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/distances/_util.py#L206-L221 |
29,246 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/message_factory.py | GetMessages | def GetMessages(file_protos):
"""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
a specified message.
"""
for file_proto in file_protos:
_FACTORY.pool.Add(file_proto)
return _FACTORY.GetMessages([file_proto.name for file_proto in file_protos]) | python | def GetMessages(file_protos):
"""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
a specified message.
"""
for file_proto in file_protos:
_FACTORY.pool.Add(file_proto)
return _FACTORY.GetMessages([file_proto.name for file_proto in file_protos]) | [
"def",
"GetMessages",
"(",
"file_protos",
")",
":",
"for",
"file_proto",
"in",
"file_protos",
":",
"_FACTORY",
".",
"pool",
".",
"Add",
"(",
"file_proto",
")",
"return",
"_FACTORY",
".",
"GetMessages",
"(",
"[",
"file_proto",
".",
"name",
"for",
"file_proto",
"in",
"file_protos",
"]",
")"
] | 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
a specified message. | [
"Builds",
"a",
"dictionary",
"of",
"all",
"the",
"messages",
"available",
"in",
"a",
"set",
"of",
"files",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/message_factory.py#L129-L142 |
29,247 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/message_factory.py | MessageFactory.GetPrototype | def GetPrototype(self, descriptor):
"""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.
"""
if descriptor.full_name not in self._classes:
descriptor_name = descriptor.name
if str is bytes: # PY2
descriptor_name = descriptor.name.encode('ascii', 'ignore')
result_class = reflection.GeneratedProtocolMessageType(
descriptor_name,
(message.Message,),
{'DESCRIPTOR': descriptor, '__module__': None})
# If module not set, it wrongly points to the reflection.py module.
self._classes[descriptor.full_name] = result_class
for field in descriptor.fields:
if field.message_type:
self.GetPrototype(field.message_type)
for extension in result_class.DESCRIPTOR.extensions:
if extension.containing_type.full_name not in self._classes:
self.GetPrototype(extension.containing_type)
extended_class = self._classes[extension.containing_type.full_name]
extended_class.RegisterExtension(extension)
return self._classes[descriptor.full_name] | python | def GetPrototype(self, descriptor):
"""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.
"""
if descriptor.full_name not in self._classes:
descriptor_name = descriptor.name
if str is bytes: # PY2
descriptor_name = descriptor.name.encode('ascii', 'ignore')
result_class = reflection.GeneratedProtocolMessageType(
descriptor_name,
(message.Message,),
{'DESCRIPTOR': descriptor, '__module__': None})
# If module not set, it wrongly points to the reflection.py module.
self._classes[descriptor.full_name] = result_class
for field in descriptor.fields:
if field.message_type:
self.GetPrototype(field.message_type)
for extension in result_class.DESCRIPTOR.extensions:
if extension.containing_type.full_name not in self._classes:
self.GetPrototype(extension.containing_type)
extended_class = self._classes[extension.containing_type.full_name]
extended_class.RegisterExtension(extension)
return self._classes[descriptor.full_name] | [
"def",
"GetPrototype",
"(",
"self",
",",
"descriptor",
")",
":",
"if",
"descriptor",
".",
"full_name",
"not",
"in",
"self",
".",
"_classes",
":",
"descriptor_name",
"=",
"descriptor",
".",
"name",
"if",
"str",
"is",
"bytes",
":",
"# PY2",
"descriptor_name",
"=",
"descriptor",
".",
"name",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")",
"result_class",
"=",
"reflection",
".",
"GeneratedProtocolMessageType",
"(",
"descriptor_name",
",",
"(",
"message",
".",
"Message",
",",
")",
",",
"{",
"'DESCRIPTOR'",
":",
"descriptor",
",",
"'__module__'",
":",
"None",
"}",
")",
"# If module not set, it wrongly points to the reflection.py module.",
"self",
".",
"_classes",
"[",
"descriptor",
".",
"full_name",
"]",
"=",
"result_class",
"for",
"field",
"in",
"descriptor",
".",
"fields",
":",
"if",
"field",
".",
"message_type",
":",
"self",
".",
"GetPrototype",
"(",
"field",
".",
"message_type",
")",
"for",
"extension",
"in",
"result_class",
".",
"DESCRIPTOR",
".",
"extensions",
":",
"if",
"extension",
".",
"containing_type",
".",
"full_name",
"not",
"in",
"self",
".",
"_classes",
":",
"self",
".",
"GetPrototype",
"(",
"extension",
".",
"containing_type",
")",
"extended_class",
"=",
"self",
".",
"_classes",
"[",
"extension",
".",
"containing_type",
".",
"full_name",
"]",
"extended_class",
".",
"RegisterExtension",
"(",
"extension",
")",
"return",
"self",
".",
"_classes",
"[",
"descriptor",
".",
"full_name",
"]"
] | 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. | [
"Builds",
"a",
"proto2",
"message",
"class",
"based",
"on",
"the",
"passed",
"in",
"descriptor",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/message_factory.py#L57-L87 |
29,248 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/message_factory.py | MessageFactory.GetMessages | def GetMessages(self, files):
"""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 dependent messages as well as any messages defined in the same file as
a specified message.
"""
result = {}
for file_name in files:
file_desc = self.pool.FindFileByName(file_name)
for desc in file_desc.message_types_by_name.values():
result[desc.full_name] = self.GetPrototype(desc)
# While the extension FieldDescriptors are created by the descriptor pool,
# the python classes created in the factory need them to be registered
# explicitly, which is done below.
#
# The call to RegisterExtension will specifically check if the
# extension was already registered on the object and either
# ignore the registration if the original was the same, or raise
# an error if they were different.
for extension in file_desc.extensions_by_name.values():
if extension.containing_type.full_name not in self._classes:
self.GetPrototype(extension.containing_type)
extended_class = self._classes[extension.containing_type.full_name]
extended_class.RegisterExtension(extension)
return result | python | def GetMessages(self, files):
"""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 dependent messages as well as any messages defined in the same file as
a specified message.
"""
result = {}
for file_name in files:
file_desc = self.pool.FindFileByName(file_name)
for desc in file_desc.message_types_by_name.values():
result[desc.full_name] = self.GetPrototype(desc)
# While the extension FieldDescriptors are created by the descriptor pool,
# the python classes created in the factory need them to be registered
# explicitly, which is done below.
#
# The call to RegisterExtension will specifically check if the
# extension was already registered on the object and either
# ignore the registration if the original was the same, or raise
# an error if they were different.
for extension in file_desc.extensions_by_name.values():
if extension.containing_type.full_name not in self._classes:
self.GetPrototype(extension.containing_type)
extended_class = self._classes[extension.containing_type.full_name]
extended_class.RegisterExtension(extension)
return result | [
"def",
"GetMessages",
"(",
"self",
",",
"files",
")",
":",
"result",
"=",
"{",
"}",
"for",
"file_name",
"in",
"files",
":",
"file_desc",
"=",
"self",
".",
"pool",
".",
"FindFileByName",
"(",
"file_name",
")",
"for",
"desc",
"in",
"file_desc",
".",
"message_types_by_name",
".",
"values",
"(",
")",
":",
"result",
"[",
"desc",
".",
"full_name",
"]",
"=",
"self",
".",
"GetPrototype",
"(",
"desc",
")",
"# While the extension FieldDescriptors are created by the descriptor pool,",
"# the python classes created in the factory need them to be registered",
"# explicitly, which is done below.",
"#",
"# The call to RegisterExtension will specifically check if the",
"# extension was already registered on the object and either",
"# ignore the registration if the original was the same, or raise",
"# an error if they were different.",
"for",
"extension",
"in",
"file_desc",
".",
"extensions_by_name",
".",
"values",
"(",
")",
":",
"if",
"extension",
".",
"containing_type",
".",
"full_name",
"not",
"in",
"self",
".",
"_classes",
":",
"self",
".",
"GetPrototype",
"(",
"extension",
".",
"containing_type",
")",
"extended_class",
"=",
"self",
".",
"_classes",
"[",
"extension",
".",
"containing_type",
".",
"full_name",
"]",
"extended_class",
".",
"RegisterExtension",
"(",
"extension",
")",
"return",
"result"
] | 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 dependent messages as well as any messages defined in the same file as
a specified message. | [
"Gets",
"all",
"the",
"messages",
"from",
"a",
"specified",
"file",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/message_factory.py#L89-L123 |
29,249 | apple/turicreate | src/unity/python/turicreate/meta/decompiler/control_flow_instructions.py | refactor_ifs | 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, col_offset=0)
ifs.append(test)
return refactor_ifs(right, ifs)
return stmnt | python | 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, col_offset=0)
ifs.append(test)
return refactor_ifs(right, ifs)
return stmnt | [
"def",
"refactor_ifs",
"(",
"stmnt",
",",
"ifs",
")",
":",
"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",
",",
"col_offset",
"=",
"0",
")",
"ifs",
".",
"append",
"(",
"test",
")",
"return",
"refactor_ifs",
"(",
"right",
",",
"ifs",
")",
"return",
"stmnt"
] | for if statements in list comprehension | [
"for",
"if",
"statements",
"in",
"list",
"comprehension"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/decompiler/control_flow_instructions.py#L58-L70 |
29,250 | apple/turicreate | src/unity/python/turicreate/toolkits/object_detector/object_detector.py | _get_mps_od_net | 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, w_in = input_image_shape
c_out = output_size
h_out = h_in // 32
w_out = w_in // 32
c_view = c_in
h_view = h_in
w_view = w_in
network.init(batch_size, c_in, h_in, w_in, c_out, h_out, w_out,
weights=weights, config=config)
return network | python | 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, w_in = input_image_shape
c_out = output_size
h_out = h_in // 32
w_out = w_in // 32
c_view = c_in
h_view = h_in
w_view = w_in
network.init(batch_size, c_in, h_in, w_in, c_out, h_out, w_out,
weights=weights, config=config)
return network | [
"def",
"_get_mps_od_net",
"(",
"input_image_shape",
",",
"batch_size",
",",
"output_size",
",",
"anchors",
",",
"config",
",",
"weights",
"=",
"{",
"}",
")",
":",
"network",
"=",
"_MpsGraphAPI",
"(",
"network_id",
"=",
"_MpsGraphNetworkType",
".",
"kODGraphNet",
")",
"c_in",
",",
"h_in",
",",
"w_in",
"=",
"input_image_shape",
"c_out",
"=",
"output_size",
"h_out",
"=",
"h_in",
"//",
"32",
"w_out",
"=",
"w_in",
"//",
"32",
"c_view",
"=",
"c_in",
"h_view",
"=",
"h_in",
"w_view",
"=",
"w_in",
"network",
".",
"init",
"(",
"batch_size",
",",
"c_in",
",",
"h_in",
",",
"w_in",
",",
"c_out",
",",
"h_out",
",",
"w_out",
",",
"weights",
"=",
"weights",
",",
"config",
"=",
"config",
")",
"return",
"network"
] | Initializes an MpsGraphAPI for object detection. | [
"Initializes",
"an",
"MpsGraphAPI",
"for",
"object",
"detection",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/object_detector/object_detector.py#L44-L62 |
29,251 | apple/turicreate | src/unity/python/turicreate/toolkits/object_detector/object_detector.py | ObjectDetector.predict | def predict(self, dataset, confidence_threshold=0.25, iou_threshold=None, verbose=True):
"""
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 training. Additional columns are
ignored.
confidence_threshold : float
Only return predictions above this level of confidence. The
threshold can range from 0 to 1.
iou_threshold : float
Threshold value for non-maximum suppression. Non-maximum suppression
prevents multiple bounding boxes appearing over a single object.
This threshold, set between 0 and 1, controls how aggressive this
suppression is. A value of 1 means no maximum suppression will
occur, while a value of 0 will maximally suppress neighboring
boxes around a prediction.
verbose : bool
If True, prints prediction progress.
Returns
-------
out : SArray
An SArray with model predictions. Each element corresponds to
an image and contains a list of dictionaries. Each dictionary
describes an object instances that was found in the image. If
`dataset` is a single image, the return value will be a single
prediction.
See Also
--------
evaluate
Examples
--------
.. sourcecode:: python
# Make predictions
>>> pred = model.predict(data)
# Stack predictions, for a better overview
>>> turicreate.object_detector.util.stack_annotations(pred)
Data:
+--------+------------+-------+-------+-------+-------+--------+
| row_id | confidence | label | x | y | width | height |
+--------+------------+-------+-------+-------+-------+--------+
| 0 | 0.98 | dog | 123.0 | 128.0 | 80.0 | 182.0 |
| 0 | 0.67 | cat | 150.0 | 183.0 | 129.0 | 101.0 |
| 1 | 0.8 | dog | 50.0 | 432.0 | 65.0 | 98.0 |
+--------+------------+-------+-------+-------+-------+--------+
[3 rows x 7 columns]
# Visualize predictions by generating a new column of marked up images
>>> data['image_pred'] = turicreate.object_detector.util.draw_bounding_boxes(data['image'], data['predictions'])
"""
_numeric_param_check_range('confidence_threshold', confidence_threshold, 0.0, 1.0)
dataset, unpack = self._canonize_input(dataset)
stacked_pred = self._predict_with_options(dataset, with_ground_truth=False,
confidence_threshold=confidence_threshold,
iou_threshold=iou_threshold,
verbose=verbose)
from . import util
return unpack(util.unstack_annotations(stacked_pred, num_rows=len(dataset))) | python | def predict(self, dataset, confidence_threshold=0.25, iou_threshold=None, verbose=True):
"""
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 training. Additional columns are
ignored.
confidence_threshold : float
Only return predictions above this level of confidence. The
threshold can range from 0 to 1.
iou_threshold : float
Threshold value for non-maximum suppression. Non-maximum suppression
prevents multiple bounding boxes appearing over a single object.
This threshold, set between 0 and 1, controls how aggressive this
suppression is. A value of 1 means no maximum suppression will
occur, while a value of 0 will maximally suppress neighboring
boxes around a prediction.
verbose : bool
If True, prints prediction progress.
Returns
-------
out : SArray
An SArray with model predictions. Each element corresponds to
an image and contains a list of dictionaries. Each dictionary
describes an object instances that was found in the image. If
`dataset` is a single image, the return value will be a single
prediction.
See Also
--------
evaluate
Examples
--------
.. sourcecode:: python
# Make predictions
>>> pred = model.predict(data)
# Stack predictions, for a better overview
>>> turicreate.object_detector.util.stack_annotations(pred)
Data:
+--------+------------+-------+-------+-------+-------+--------+
| row_id | confidence | label | x | y | width | height |
+--------+------------+-------+-------+-------+-------+--------+
| 0 | 0.98 | dog | 123.0 | 128.0 | 80.0 | 182.0 |
| 0 | 0.67 | cat | 150.0 | 183.0 | 129.0 | 101.0 |
| 1 | 0.8 | dog | 50.0 | 432.0 | 65.0 | 98.0 |
+--------+------------+-------+-------+-------+-------+--------+
[3 rows x 7 columns]
# Visualize predictions by generating a new column of marked up images
>>> data['image_pred'] = turicreate.object_detector.util.draw_bounding_boxes(data['image'], data['predictions'])
"""
_numeric_param_check_range('confidence_threshold', confidence_threshold, 0.0, 1.0)
dataset, unpack = self._canonize_input(dataset)
stacked_pred = self._predict_with_options(dataset, with_ground_truth=False,
confidence_threshold=confidence_threshold,
iou_threshold=iou_threshold,
verbose=verbose)
from . import util
return unpack(util.unstack_annotations(stacked_pred, num_rows=len(dataset))) | [
"def",
"predict",
"(",
"self",
",",
"dataset",
",",
"confidence_threshold",
"=",
"0.25",
",",
"iou_threshold",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"_numeric_param_check_range",
"(",
"'confidence_threshold'",
",",
"confidence_threshold",
",",
"0.0",
",",
"1.0",
")",
"dataset",
",",
"unpack",
"=",
"self",
".",
"_canonize_input",
"(",
"dataset",
")",
"stacked_pred",
"=",
"self",
".",
"_predict_with_options",
"(",
"dataset",
",",
"with_ground_truth",
"=",
"False",
",",
"confidence_threshold",
"=",
"confidence_threshold",
",",
"iou_threshold",
"=",
"iou_threshold",
",",
"verbose",
"=",
"verbose",
")",
"from",
".",
"import",
"util",
"return",
"unpack",
"(",
"util",
".",
"unstack_annotations",
"(",
"stacked_pred",
",",
"num_rows",
"=",
"len",
"(",
"dataset",
")",
")",
")"
] | 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 training. Additional columns are
ignored.
confidence_threshold : float
Only return predictions above this level of confidence. The
threshold can range from 0 to 1.
iou_threshold : float
Threshold value for non-maximum suppression. Non-maximum suppression
prevents multiple bounding boxes appearing over a single object.
This threshold, set between 0 and 1, controls how aggressive this
suppression is. A value of 1 means no maximum suppression will
occur, while a value of 0 will maximally suppress neighboring
boxes around a prediction.
verbose : bool
If True, prints prediction progress.
Returns
-------
out : SArray
An SArray with model predictions. Each element corresponds to
an image and contains a list of dictionaries. Each dictionary
describes an object instances that was found in the image. If
`dataset` is a single image, the return value will be a single
prediction.
See Also
--------
evaluate
Examples
--------
.. sourcecode:: python
# Make predictions
>>> pred = model.predict(data)
# Stack predictions, for a better overview
>>> turicreate.object_detector.util.stack_annotations(pred)
Data:
+--------+------------+-------+-------+-------+-------+--------+
| row_id | confidence | label | x | y | width | height |
+--------+------------+-------+-------+-------+-------+--------+
| 0 | 0.98 | dog | 123.0 | 128.0 | 80.0 | 182.0 |
| 0 | 0.67 | cat | 150.0 | 183.0 | 129.0 | 101.0 |
| 1 | 0.8 | dog | 50.0 | 432.0 | 65.0 | 98.0 |
+--------+------------+-------+-------+-------+-------+--------+
[3 rows x 7 columns]
# Visualize predictions by generating a new column of marked up images
>>> data['image_pred'] = turicreate.object_detector.util.draw_bounding_boxes(data['image'], data['predictions']) | [
"Predict",
"object",
"instances",
"in",
"an",
"sframe",
"of",
"images",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/object_detector/object_detector.py#L934-L1004 |
29,252 | apple/turicreate | src/unity/python/turicreate/toolkits/object_detector/object_detector.py | ObjectDetector.evaluate | def evaluate(self, dataset, metric='auto',
output_type='dict', iou_threshold=None,
confidence_threshold=None, verbose=True):
"""
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 training.
Additional columns are ignored.
metric : str or list, optional
Name of the evaluation metric or list of several names. The primary
metric is average precision, which is the area under the
precision/recall curve and reported as a value between 0 and 1 (1
being perfect). Possible values are:
- 'auto' : Returns all primary metrics.
- 'all' : Returns all available metrics.
- 'average_precision_50' : Average precision per class with
intersection-over-union threshold at
50% (PASCAL VOC metric).
- 'average_precision' : Average precision per class calculated over multiple
intersection-over-union thresholds
(at 50%, 55%, ..., 95%) and averaged.
- 'mean_average_precision_50' : Mean over all classes (for ``'average_precision_50'``).
This is the primary single-value metric.
- 'mean_average_precision' : Mean over all classes (for ``'average_precision'``)
output_type : str
Type of output:
- 'dict' : You are given a dictionary where each key is a metric name and the
value is another dictionary containing class-to-metric entries.
- 'sframe' : All metrics are returned as a single `SFrame`, where each row is a
class and each column is a metric. Metrics that are averaged over
class cannot be returned and are ignored under this format.
However, these are easily computed from the `SFrame` (e.g.
``results['average_precision'].mean()``).
iou_threshold : float
Threshold value for non-maximum suppression. Non-maximum suppression
prevents multiple bounding boxes appearing over a single object.
This threshold, set between 0 and 1, controls how aggressive this
suppression is. A value of 1 means no maximum suppression will
occur, while a value of 0 will maximally suppress neighboring
boxes around a prediction.
confidence_threshold : float
Only return predictions above this level of confidence. The
threshold can range from 0 to 1.
verbose : bool
If True, prints evaluation progress.
Returns
-------
out : dict / SFrame
Output type depends on the option `output_type`.
See Also
--------
create, predict
Examples
--------
>>> results = model.evaluate(data)
>>> print('mAP: {:.1%}'.format(results['mean_average_precision']))
mAP: 43.2%
"""
if iou_threshold is None: iou_threshold = self.non_maximum_suppression_threshold
if confidence_threshold is None: confidence_threshold = 0.001
AP = 'average_precision'
MAP = 'mean_average_precision'
AP50 = 'average_precision_50'
MAP50 = 'mean_average_precision_50'
ALL_METRICS = {AP, MAP, AP50, MAP50}
if isinstance(metric, (list, tuple, set)):
metrics = metric
elif metric == 'all':
metrics = ALL_METRICS
elif metric == 'auto':
metrics = {AP50, MAP50}
elif metric in ALL_METRICS:
metrics = {metric}
else:
raise _ToolkitError("Metric '{}' not supported".format(metric))
pred, gt = self._predict_with_options(dataset, with_ground_truth=True,
confidence_threshold=confidence_threshold,
iou_threshold=iou_threshold,
verbose=verbose)
pred_df = pred.to_dataframe()
gt_df = gt.to_dataframe()
thresholds = _np.arange(0.5, 1.0, 0.05)
all_th_aps = _average_precision(pred_df, gt_df,
class_to_index=self._class_to_index,
iou_thresholds=thresholds)
def class_dict(aps):
return {classname: aps[index]
for classname, index in self._class_to_index.items()}
if output_type == 'dict':
ret = {}
if AP50 in metrics:
ret[AP50] = class_dict(all_th_aps[0])
if AP in metrics:
ret[AP] = class_dict(all_th_aps.mean(0))
if MAP50 in metrics:
ret[MAP50] = all_th_aps[0].mean()
if MAP in metrics:
ret[MAP] = all_th_aps.mean()
elif output_type == 'sframe':
ret = _tc.SFrame({'label': self.classes})
if AP50 in metrics:
ret[AP50] = all_th_aps[0]
if AP in metrics:
ret[AP] = all_th_aps.mean(0)
else:
raise _ToolkitError("Output type '{}' not supported".format(output_type))
return ret | python | def evaluate(self, dataset, metric='auto',
output_type='dict', iou_threshold=None,
confidence_threshold=None, verbose=True):
"""
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 training.
Additional columns are ignored.
metric : str or list, optional
Name of the evaluation metric or list of several names. The primary
metric is average precision, which is the area under the
precision/recall curve and reported as a value between 0 and 1 (1
being perfect). Possible values are:
- 'auto' : Returns all primary metrics.
- 'all' : Returns all available metrics.
- 'average_precision_50' : Average precision per class with
intersection-over-union threshold at
50% (PASCAL VOC metric).
- 'average_precision' : Average precision per class calculated over multiple
intersection-over-union thresholds
(at 50%, 55%, ..., 95%) and averaged.
- 'mean_average_precision_50' : Mean over all classes (for ``'average_precision_50'``).
This is the primary single-value metric.
- 'mean_average_precision' : Mean over all classes (for ``'average_precision'``)
output_type : str
Type of output:
- 'dict' : You are given a dictionary where each key is a metric name and the
value is another dictionary containing class-to-metric entries.
- 'sframe' : All metrics are returned as a single `SFrame`, where each row is a
class and each column is a metric. Metrics that are averaged over
class cannot be returned and are ignored under this format.
However, these are easily computed from the `SFrame` (e.g.
``results['average_precision'].mean()``).
iou_threshold : float
Threshold value for non-maximum suppression. Non-maximum suppression
prevents multiple bounding boxes appearing over a single object.
This threshold, set between 0 and 1, controls how aggressive this
suppression is. A value of 1 means no maximum suppression will
occur, while a value of 0 will maximally suppress neighboring
boxes around a prediction.
confidence_threshold : float
Only return predictions above this level of confidence. The
threshold can range from 0 to 1.
verbose : bool
If True, prints evaluation progress.
Returns
-------
out : dict / SFrame
Output type depends on the option `output_type`.
See Also
--------
create, predict
Examples
--------
>>> results = model.evaluate(data)
>>> print('mAP: {:.1%}'.format(results['mean_average_precision']))
mAP: 43.2%
"""
if iou_threshold is None: iou_threshold = self.non_maximum_suppression_threshold
if confidence_threshold is None: confidence_threshold = 0.001
AP = 'average_precision'
MAP = 'mean_average_precision'
AP50 = 'average_precision_50'
MAP50 = 'mean_average_precision_50'
ALL_METRICS = {AP, MAP, AP50, MAP50}
if isinstance(metric, (list, tuple, set)):
metrics = metric
elif metric == 'all':
metrics = ALL_METRICS
elif metric == 'auto':
metrics = {AP50, MAP50}
elif metric in ALL_METRICS:
metrics = {metric}
else:
raise _ToolkitError("Metric '{}' not supported".format(metric))
pred, gt = self._predict_with_options(dataset, with_ground_truth=True,
confidence_threshold=confidence_threshold,
iou_threshold=iou_threshold,
verbose=verbose)
pred_df = pred.to_dataframe()
gt_df = gt.to_dataframe()
thresholds = _np.arange(0.5, 1.0, 0.05)
all_th_aps = _average_precision(pred_df, gt_df,
class_to_index=self._class_to_index,
iou_thresholds=thresholds)
def class_dict(aps):
return {classname: aps[index]
for classname, index in self._class_to_index.items()}
if output_type == 'dict':
ret = {}
if AP50 in metrics:
ret[AP50] = class_dict(all_th_aps[0])
if AP in metrics:
ret[AP] = class_dict(all_th_aps.mean(0))
if MAP50 in metrics:
ret[MAP50] = all_th_aps[0].mean()
if MAP in metrics:
ret[MAP] = all_th_aps.mean()
elif output_type == 'sframe':
ret = _tc.SFrame({'label': self.classes})
if AP50 in metrics:
ret[AP50] = all_th_aps[0]
if AP in metrics:
ret[AP] = all_th_aps.mean(0)
else:
raise _ToolkitError("Output type '{}' not supported".format(output_type))
return ret | [
"def",
"evaluate",
"(",
"self",
",",
"dataset",
",",
"metric",
"=",
"'auto'",
",",
"output_type",
"=",
"'dict'",
",",
"iou_threshold",
"=",
"None",
",",
"confidence_threshold",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"iou_threshold",
"is",
"None",
":",
"iou_threshold",
"=",
"self",
".",
"non_maximum_suppression_threshold",
"if",
"confidence_threshold",
"is",
"None",
":",
"confidence_threshold",
"=",
"0.001",
"AP",
"=",
"'average_precision'",
"MAP",
"=",
"'mean_average_precision'",
"AP50",
"=",
"'average_precision_50'",
"MAP50",
"=",
"'mean_average_precision_50'",
"ALL_METRICS",
"=",
"{",
"AP",
",",
"MAP",
",",
"AP50",
",",
"MAP50",
"}",
"if",
"isinstance",
"(",
"metric",
",",
"(",
"list",
",",
"tuple",
",",
"set",
")",
")",
":",
"metrics",
"=",
"metric",
"elif",
"metric",
"==",
"'all'",
":",
"metrics",
"=",
"ALL_METRICS",
"elif",
"metric",
"==",
"'auto'",
":",
"metrics",
"=",
"{",
"AP50",
",",
"MAP50",
"}",
"elif",
"metric",
"in",
"ALL_METRICS",
":",
"metrics",
"=",
"{",
"metric",
"}",
"else",
":",
"raise",
"_ToolkitError",
"(",
"\"Metric '{}' not supported\"",
".",
"format",
"(",
"metric",
")",
")",
"pred",
",",
"gt",
"=",
"self",
".",
"_predict_with_options",
"(",
"dataset",
",",
"with_ground_truth",
"=",
"True",
",",
"confidence_threshold",
"=",
"confidence_threshold",
",",
"iou_threshold",
"=",
"iou_threshold",
",",
"verbose",
"=",
"verbose",
")",
"pred_df",
"=",
"pred",
".",
"to_dataframe",
"(",
")",
"gt_df",
"=",
"gt",
".",
"to_dataframe",
"(",
")",
"thresholds",
"=",
"_np",
".",
"arange",
"(",
"0.5",
",",
"1.0",
",",
"0.05",
")",
"all_th_aps",
"=",
"_average_precision",
"(",
"pred_df",
",",
"gt_df",
",",
"class_to_index",
"=",
"self",
".",
"_class_to_index",
",",
"iou_thresholds",
"=",
"thresholds",
")",
"def",
"class_dict",
"(",
"aps",
")",
":",
"return",
"{",
"classname",
":",
"aps",
"[",
"index",
"]",
"for",
"classname",
",",
"index",
"in",
"self",
".",
"_class_to_index",
".",
"items",
"(",
")",
"}",
"if",
"output_type",
"==",
"'dict'",
":",
"ret",
"=",
"{",
"}",
"if",
"AP50",
"in",
"metrics",
":",
"ret",
"[",
"AP50",
"]",
"=",
"class_dict",
"(",
"all_th_aps",
"[",
"0",
"]",
")",
"if",
"AP",
"in",
"metrics",
":",
"ret",
"[",
"AP",
"]",
"=",
"class_dict",
"(",
"all_th_aps",
".",
"mean",
"(",
"0",
")",
")",
"if",
"MAP50",
"in",
"metrics",
":",
"ret",
"[",
"MAP50",
"]",
"=",
"all_th_aps",
"[",
"0",
"]",
".",
"mean",
"(",
")",
"if",
"MAP",
"in",
"metrics",
":",
"ret",
"[",
"MAP",
"]",
"=",
"all_th_aps",
".",
"mean",
"(",
")",
"elif",
"output_type",
"==",
"'sframe'",
":",
"ret",
"=",
"_tc",
".",
"SFrame",
"(",
"{",
"'label'",
":",
"self",
".",
"classes",
"}",
")",
"if",
"AP50",
"in",
"metrics",
":",
"ret",
"[",
"AP50",
"]",
"=",
"all_th_aps",
"[",
"0",
"]",
"if",
"AP",
"in",
"metrics",
":",
"ret",
"[",
"AP",
"]",
"=",
"all_th_aps",
".",
"mean",
"(",
"0",
")",
"else",
":",
"raise",
"_ToolkitError",
"(",
"\"Output type '{}' not supported\"",
".",
"format",
"(",
"output_type",
")",
")",
"return",
"ret"
] | 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 training.
Additional columns are ignored.
metric : str or list, optional
Name of the evaluation metric or list of several names. The primary
metric is average precision, which is the area under the
precision/recall curve and reported as a value between 0 and 1 (1
being perfect). Possible values are:
- 'auto' : Returns all primary metrics.
- 'all' : Returns all available metrics.
- 'average_precision_50' : Average precision per class with
intersection-over-union threshold at
50% (PASCAL VOC metric).
- 'average_precision' : Average precision per class calculated over multiple
intersection-over-union thresholds
(at 50%, 55%, ..., 95%) and averaged.
- 'mean_average_precision_50' : Mean over all classes (for ``'average_precision_50'``).
This is the primary single-value metric.
- 'mean_average_precision' : Mean over all classes (for ``'average_precision'``)
output_type : str
Type of output:
- 'dict' : You are given a dictionary where each key is a metric name and the
value is another dictionary containing class-to-metric entries.
- 'sframe' : All metrics are returned as a single `SFrame`, where each row is a
class and each column is a metric. Metrics that are averaged over
class cannot be returned and are ignored under this format.
However, these are easily computed from the `SFrame` (e.g.
``results['average_precision'].mean()``).
iou_threshold : float
Threshold value for non-maximum suppression. Non-maximum suppression
prevents multiple bounding boxes appearing over a single object.
This threshold, set between 0 and 1, controls how aggressive this
suppression is. A value of 1 means no maximum suppression will
occur, while a value of 0 will maximally suppress neighboring
boxes around a prediction.
confidence_threshold : float
Only return predictions above this level of confidence. The
threshold can range from 0 to 1.
verbose : bool
If True, prints evaluation progress.
Returns
-------
out : dict / SFrame
Output type depends on the option `output_type`.
See Also
--------
create, predict
Examples
--------
>>> results = model.evaluate(data)
>>> print('mAP: {:.1%}'.format(results['mean_average_precision']))
mAP: 43.2% | [
"Evaluate",
"the",
"model",
"by",
"making",
"predictions",
"and",
"comparing",
"these",
"to",
"ground",
"truth",
"bounding",
"box",
"annotations",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/object_detector/object_detector.py#L1006-L1134 |
29,253 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | _xmlTextReaderErrorFunc | 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)) | python | 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)) | [
"def",
"_xmlTextReaderErrorFunc",
"(",
"xxx_todo_changeme",
",",
"msg",
",",
"severity",
",",
"locator",
")",
":",
"(",
"f",
",",
"arg",
")",
"=",
"xxx_todo_changeme",
"return",
"f",
"(",
"arg",
",",
"msg",
",",
"severity",
",",
"xmlTextReaderLocator",
"(",
"locator",
")",
")"
] | Intermediate callback to wrap the locator | [
"Intermediate",
"callback",
"to",
"wrap",
"the",
"locator"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L713-L716 |
29,254 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | htmlCreateMemoryParserCtxt | 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 parserCtxt(_obj=ret) | python | 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 parserCtxt(_obj=ret) | [
"def",
"htmlCreateMemoryParserCtxt",
"(",
"buffer",
",",
"size",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"htmlCreateMemoryParserCtxt",
"(",
"buffer",
",",
"size",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"parserError",
"(",
"'htmlCreateMemoryParserCtxt() failed'",
")",
"return",
"parserCtxt",
"(",
"_obj",
"=",
"ret",
")"
] | Create a parser context for an HTML in-memory document. | [
"Create",
"a",
"parser",
"context",
"for",
"an",
"HTML",
"in",
"-",
"memory",
"document",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L791-L795 |
29,255 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | htmlParseDoc | 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) | python | 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) | [
"def",
"htmlParseDoc",
"(",
"cur",
",",
"encoding",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"htmlParseDoc",
"(",
"cur",
",",
"encoding",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"parserError",
"(",
"'htmlParseDoc() failed'",
")",
"return",
"xmlDoc",
"(",
"_obj",
"=",
"ret",
")"
] | parse an HTML in-memory document and build a tree. | [
"parse",
"an",
"HTML",
"in",
"-",
"memory",
"document",
"and",
"build",
"a",
"tree",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L814-L818 |
29,256 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | htmlReadFd | 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) | python | 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) | [
"def",
"htmlReadFd",
"(",
"fd",
",",
"URL",
",",
"encoding",
",",
"options",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"htmlReadFd",
"(",
"fd",
",",
"URL",
",",
"encoding",
",",
"options",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'htmlReadFd() failed'",
")",
"return",
"xmlDoc",
"(",
"_obj",
"=",
"ret",
")"
] | parse an XML from a file descriptor and build a tree. | [
"parse",
"an",
"XML",
"from",
"a",
"file",
"descriptor",
"and",
"build",
"a",
"tree",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L834-L838 |
29,257 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | htmlNewDoc | 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) | python | 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) | [
"def",
"htmlNewDoc",
"(",
"URI",
",",
"ExternalID",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"htmlNewDoc",
"(",
"URI",
",",
"ExternalID",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'htmlNewDoc() failed'",
")",
"return",
"xmlDoc",
"(",
"_obj",
"=",
"ret",
")"
] | Creates a new HTML document | [
"Creates",
"a",
"new",
"HTML",
"document"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L861-L865 |
29,258 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | htmlNewDocNoDtD | 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('htmlNewDocNoDtD() failed')
return xmlDoc(_obj=ret) | python | 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('htmlNewDocNoDtD() failed')
return xmlDoc(_obj=ret) | [
"def",
"htmlNewDocNoDtD",
"(",
"URI",
",",
"ExternalID",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"htmlNewDocNoDtD",
"(",
"URI",
",",
"ExternalID",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'htmlNewDocNoDtD() failed'",
")",
"return",
"xmlDoc",
"(",
"_obj",
"=",
"ret",
")"
] | Creates a new HTML document without a DTD node if @URI and
@ExternalID are None | [
"Creates",
"a",
"new",
"HTML",
"document",
"without",
"a",
"DTD",
"node",
"if"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L867-L872 |
29,259 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | loadACatalog | def loadACatalog(filename):
"""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. """
ret = libxml2mod.xmlLoadACatalog(filename)
if ret is None:raise treeError('xmlLoadACatalog() failed')
return catalog(_obj=ret) | python | def loadACatalog(filename):
"""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. """
ret = libxml2mod.xmlLoadACatalog(filename)
if ret is None:raise treeError('xmlLoadACatalog() failed')
return catalog(_obj=ret) | [
"def",
"loadACatalog",
"(",
"filename",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlLoadACatalog",
"(",
"filename",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlLoadACatalog() failed'",
")",
"return",
"catalog",
"(",
"_obj",
"=",
"ret",
")"
] | 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. | [
"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",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L975-L982 |
29,260 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | loadSGMLSuperCatalog | def loadSGMLSuperCatalog(filename):
"""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. """
ret = libxml2mod.xmlLoadSGMLSuperCatalog(filename)
if ret is None:raise treeError('xmlLoadSGMLSuperCatalog() failed')
return catalog(_obj=ret) | python | def loadSGMLSuperCatalog(filename):
"""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. """
ret = libxml2mod.xmlLoadSGMLSuperCatalog(filename)
if ret is None:raise treeError('xmlLoadSGMLSuperCatalog() failed')
return catalog(_obj=ret) | [
"def",
"loadSGMLSuperCatalog",
"(",
"filename",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlLoadSGMLSuperCatalog",
"(",
"filename",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlLoadSGMLSuperCatalog() failed'",
")",
"return",
"catalog",
"(",
"_obj",
"=",
"ret",
")"
] | 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. | [
"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",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L999-L1006 |
29,261 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | newCatalog | def newCatalog(sgml):
"""create a new Catalog. """
ret = libxml2mod.xmlNewCatalog(sgml)
if ret is None:raise treeError('xmlNewCatalog() failed')
return catalog(_obj=ret) | python | def newCatalog(sgml):
"""create a new Catalog. """
ret = libxml2mod.xmlNewCatalog(sgml)
if ret is None:raise treeError('xmlNewCatalog() failed')
return catalog(_obj=ret) | [
"def",
"newCatalog",
"(",
"sgml",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewCatalog",
"(",
"sgml",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewCatalog() failed'",
")",
"return",
"catalog",
"(",
"_obj",
"=",
"ret",
")"
] | create a new Catalog. | [
"create",
"a",
"new",
"Catalog",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1008-L1012 |
29,262 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | debugDumpString | def debugDumpString(output, str):
"""Dumps informations about the string, shorten it if necessary """
if output is not None: output.flush()
libxml2mod.xmlDebugDumpString(output, str) | python | def debugDumpString(output, str):
"""Dumps informations about the string, shorten it if necessary """
if output is not None: output.flush()
libxml2mod.xmlDebugDumpString(output, str) | [
"def",
"debugDumpString",
"(",
"output",
",",
"str",
")",
":",
"if",
"output",
"is",
"not",
"None",
":",
"output",
".",
"flush",
"(",
")",
"libxml2mod",
".",
"xmlDebugDumpString",
"(",
"output",
",",
"str",
")"
] | Dumps informations about the string, shorten it if necessary | [
"Dumps",
"informations",
"about",
"the",
"string",
"shorten",
"it",
"if",
"necessary"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1080-L1083 |
29,263 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | predefinedEntity | 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) | python | 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) | [
"def",
"predefinedEntity",
"(",
"name",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlGetPredefinedEntity",
"(",
"name",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlGetPredefinedEntity() failed'",
")",
"return",
"xmlEntity",
"(",
"_obj",
"=",
"ret",
")"
] | Check whether this name is an predefined entity. | [
"Check",
"whether",
"this",
"name",
"is",
"an",
"predefined",
"entity",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1152-L1156 |
29,264 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | nanoFTPProxy | 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_password
environment variables. """
libxml2mod.xmlNanoFTPProxy(host, port, user, passwd, type) | python | 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_password
environment variables. """
libxml2mod.xmlNanoFTPProxy(host, port, user, passwd, type) | [
"def",
"nanoFTPProxy",
"(",
"host",
",",
"port",
",",
"user",
",",
"passwd",
",",
"type",
")",
":",
"libxml2mod",
".",
"xmlNanoFTPProxy",
"(",
"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_password
environment variables. | [
"Setup",
"the",
"FTP",
"proxy",
"informations",
".",
"This",
"can",
"also",
"be",
"done",
"by",
"using",
"ftp_proxy",
"ftp_proxy_user",
"and",
"ftp_proxy_password",
"environment",
"variables",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1232-L1236 |
29,265 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | createDocParserCtxt | 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) | python | 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) | [
"def",
"createDocParserCtxt",
"(",
"cur",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlCreateDocParserCtxt",
"(",
"cur",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"parserError",
"(",
"'xmlCreateDocParserCtxt() failed'",
")",
"return",
"parserCtxt",
"(",
"_obj",
"=",
"ret",
")"
] | Creates a parser context for an XML in-memory document. | [
"Creates",
"a",
"parser",
"context",
"for",
"an",
"XML",
"in",
"-",
"memory",
"document",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1269-L1273 |
29,266 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | parseDTD | 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) | python | 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) | [
"def",
"parseDTD",
"(",
"ExternalID",
",",
"SystemID",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlParseDTD",
"(",
"ExternalID",
",",
"SystemID",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"parserError",
"(",
"'xmlParseDTD() failed'",
")",
"return",
"xmlDtd",
"(",
"_obj",
"=",
"ret",
")"
] | Load and parse an external subset. | [
"Load",
"and",
"parse",
"an",
"external",
"subset",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1316-L1320 |
29,267 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | parseMemory | 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) | python | 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) | [
"def",
"parseMemory",
"(",
"buffer",
",",
"size",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlParseMemory",
"(",
"buffer",
",",
"size",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"parserError",
"(",
"'xmlParseMemory() failed'",
")",
"return",
"xmlDoc",
"(",
"_obj",
"=",
"ret",
")"
] | parse an XML in-memory block and build a tree. | [
"parse",
"an",
"XML",
"in",
"-",
"memory",
"block",
"and",
"build",
"a",
"tree",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1344-L1348 |
29,268 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | readFd | def readFd(fd, URL, encoding, options):
"""parse an XML from a file descriptor and build a tree. NOTE
that the file descriptor will not be closed when the reader
is closed or reset. """
ret = libxml2mod.xmlReadFd(fd, URL, encoding, options)
if ret is None:raise treeError('xmlReadFd() failed')
return xmlDoc(_obj=ret) | python | def readFd(fd, URL, encoding, options):
"""parse an XML from a file descriptor and build a tree. NOTE
that the file descriptor will not be closed when the reader
is closed or reset. """
ret = libxml2mod.xmlReadFd(fd, URL, encoding, options)
if ret is None:raise treeError('xmlReadFd() failed')
return xmlDoc(_obj=ret) | [
"def",
"readFd",
"(",
"fd",
",",
"URL",
",",
"encoding",
",",
"options",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlReadFd",
"(",
"fd",
",",
"URL",
",",
"encoding",
",",
"options",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlReadFd() failed'",
")",
"return",
"xmlDoc",
"(",
"_obj",
"=",
"ret",
")"
] | parse an XML from a file descriptor and build a tree. NOTE
that the file descriptor will not be closed when the reader
is closed or reset. | [
"parse",
"an",
"XML",
"from",
"a",
"file",
"descriptor",
"and",
"build",
"a",
"tree",
".",
"NOTE",
"that",
"the",
"file",
"descriptor",
"will",
"not",
"be",
"closed",
"when",
"the",
"reader",
"is",
"closed",
"or",
"reset",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1362-L1368 |
29,269 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | recoverDoc | def recoverDoc(cur):
"""parse an XML in-memory document and build a tree. In the
case the document is not Well Formed, a attempt to build a
tree is tried anyway """
ret = libxml2mod.xmlRecoverDoc(cur)
if ret is None:raise treeError('xmlRecoverDoc() failed')
return xmlDoc(_obj=ret) | python | def recoverDoc(cur):
"""parse an XML in-memory document and build a tree. In the
case the document is not Well Formed, a attempt to build a
tree is tried anyway """
ret = libxml2mod.xmlRecoverDoc(cur)
if ret is None:raise treeError('xmlRecoverDoc() failed')
return xmlDoc(_obj=ret) | [
"def",
"recoverDoc",
"(",
"cur",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlRecoverDoc",
"(",
"cur",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlRecoverDoc() failed'",
")",
"return",
"xmlDoc",
"(",
"_obj",
"=",
"ret",
")"
] | parse an XML in-memory document and build a tree. In the
case the document is not Well Formed, a attempt to build a
tree is tried anyway | [
"parse",
"an",
"XML",
"in",
"-",
"memory",
"document",
"and",
"build",
"a",
"tree",
".",
"In",
"the",
"case",
"the",
"document",
"is",
"not",
"Well",
"Formed",
"a",
"attempt",
"to",
"build",
"a",
"tree",
"is",
"tried",
"anyway"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1382-L1388 |
29,270 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | recoverMemory | def recoverMemory(buffer, size):
"""parse an XML in-memory block and build a tree. In the case
the document is not Well Formed, an attempt to build a tree
is tried anyway """
ret = libxml2mod.xmlRecoverMemory(buffer, size)
if ret is None:raise treeError('xmlRecoverMemory() failed')
return xmlDoc(_obj=ret) | python | def recoverMemory(buffer, size):
"""parse an XML in-memory block and build a tree. In the case
the document is not Well Formed, an attempt to build a tree
is tried anyway """
ret = libxml2mod.xmlRecoverMemory(buffer, size)
if ret is None:raise treeError('xmlRecoverMemory() failed')
return xmlDoc(_obj=ret) | [
"def",
"recoverMemory",
"(",
"buffer",
",",
"size",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlRecoverMemory",
"(",
"buffer",
",",
"size",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlRecoverMemory() failed'",
")",
"return",
"xmlDoc",
"(",
"_obj",
"=",
"ret",
")"
] | parse an XML in-memory block and build a tree. In the case
the document is not Well Formed, an attempt to build a tree
is tried anyway | [
"parse",
"an",
"XML",
"in",
"-",
"memory",
"block",
"and",
"build",
"a",
"tree",
".",
"In",
"the",
"case",
"the",
"document",
"is",
"not",
"Well",
"Formed",
"an",
"attempt",
"to",
"build",
"a",
"tree",
"is",
"tried",
"anyway"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1399-L1405 |
29,271 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | copyChar | def copyChar(len, out, val):
"""append the char value in the array """
ret = libxml2mod.xmlCopyChar(len, out, val)
return ret | python | def copyChar(len, out, val):
"""append the char value in the array """
ret = libxml2mod.xmlCopyChar(len, out, val)
return ret | [
"def",
"copyChar",
"(",
"len",
",",
"out",
",",
"val",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlCopyChar",
"(",
"len",
",",
"out",
",",
"val",
")",
"return",
"ret"
] | append the char value in the array | [
"append",
"the",
"char",
"value",
"in",
"the",
"array"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1455-L1458 |
29,272 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | createMemoryParserCtxt | def createMemoryParserCtxt(buffer, size):
"""Create a parser context for an XML in-memory document. """
ret = libxml2mod.xmlCreateMemoryParserCtxt(buffer, size)
if ret is None:raise parserError('xmlCreateMemoryParserCtxt() failed')
return parserCtxt(_obj=ret) | python | def createMemoryParserCtxt(buffer, size):
"""Create a parser context for an XML in-memory document. """
ret = libxml2mod.xmlCreateMemoryParserCtxt(buffer, size)
if ret is None:raise parserError('xmlCreateMemoryParserCtxt() failed')
return parserCtxt(_obj=ret) | [
"def",
"createMemoryParserCtxt",
"(",
"buffer",
",",
"size",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlCreateMemoryParserCtxt",
"(",
"buffer",
",",
"size",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"parserError",
"(",
"'xmlCreateMemoryParserCtxt() failed'",
")",
"return",
"parserCtxt",
"(",
"_obj",
"=",
"ret",
")"
] | Create a parser context for an XML in-memory document. | [
"Create",
"a",
"parser",
"context",
"for",
"an",
"XML",
"in",
"-",
"memory",
"document",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1481-L1485 |
29,273 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | namePop | def namePop(ctxt):
"""Pops the top element name from the name stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.namePop(ctxt__o)
return ret | python | def namePop(ctxt):
"""Pops the top element name from the name stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.namePop(ctxt__o)
return ret | [
"def",
"namePop",
"(",
"ctxt",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"namePop",
"(",
"ctxt__o",
")",
"return",
"ret"
] | Pops the top element name from the name stack | [
"Pops",
"the",
"top",
"element",
"name",
"from",
"the",
"name",
"stack"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1517-L1522 |
29,274 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | namePush | def namePush(ctxt, value):
"""Pushes a new element name on top of the name stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.namePush(ctxt__o, value)
return ret | python | def namePush(ctxt, value):
"""Pushes a new element name on top of the name stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.namePush(ctxt__o, value)
return ret | [
"def",
"namePush",
"(",
"ctxt",
",",
"value",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"namePush",
"(",
"ctxt__o",
",",
"value",
")",
"return",
"ret"
] | Pushes a new element name on top of the name stack | [
"Pushes",
"a",
"new",
"element",
"name",
"on",
"top",
"of",
"the",
"name",
"stack"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1524-L1529 |
29,275 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | nodePop | def nodePop(ctxt):
"""Pops the top element node from the node stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.nodePop(ctxt__o)
if ret is None:raise treeError('nodePop() failed')
return xmlNode(_obj=ret) | python | def nodePop(ctxt):
"""Pops the top element node from the node stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.nodePop(ctxt__o)
if ret is None:raise treeError('nodePop() failed')
return xmlNode(_obj=ret) | [
"def",
"nodePop",
"(",
"ctxt",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"nodePop",
"(",
"ctxt__o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'nodePop() failed'",
")",
"return",
"xmlNode",
"(",
"_obj",
"=",
"ret",
")"
] | Pops the top element node from the node stack | [
"Pops",
"the",
"top",
"element",
"node",
"from",
"the",
"node",
"stack"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1531-L1537 |
29,276 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | nodePush | def nodePush(ctxt, value):
"""Pushes a new element node on top of the node stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
if value is None: value__o = None
else: value__o = value._o
ret = libxml2mod.nodePush(ctxt__o, value__o)
return ret | python | def nodePush(ctxt, value):
"""Pushes a new element node on top of the node stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
if value is None: value__o = None
else: value__o = value._o
ret = libxml2mod.nodePush(ctxt__o, value__o)
return ret | [
"def",
"nodePush",
"(",
"ctxt",
",",
"value",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"if",
"value",
"is",
"None",
":",
"value__o",
"=",
"None",
"else",
":",
"value__o",
"=",
"value",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"nodePush",
"(",
"ctxt__o",
",",
"value__o",
")",
"return",
"ret"
] | Pushes a new element node on top of the node stack | [
"Pushes",
"a",
"new",
"element",
"node",
"on",
"top",
"of",
"the",
"node",
"stack"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1539-L1546 |
29,277 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | createInputBuffer | def createInputBuffer(file, encoding):
"""Create a libxml2 input buffer from a Python file """
ret = libxml2mod.xmlCreateInputBuffer(file, encoding)
if ret is None:raise treeError('xmlCreateInputBuffer() failed')
return inputBuffer(_obj=ret) | python | def createInputBuffer(file, encoding):
"""Create a libxml2 input buffer from a Python file """
ret = libxml2mod.xmlCreateInputBuffer(file, encoding)
if ret is None:raise treeError('xmlCreateInputBuffer() failed')
return inputBuffer(_obj=ret) | [
"def",
"createInputBuffer",
"(",
"file",
",",
"encoding",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlCreateInputBuffer",
"(",
"file",
",",
"encoding",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlCreateInputBuffer() failed'",
")",
"return",
"inputBuffer",
"(",
"_obj",
"=",
"ret",
")"
] | Create a libxml2 input buffer from a Python file | [
"Create",
"a",
"libxml2",
"input",
"buffer",
"from",
"a",
"Python",
"file"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1557-L1561 |
29,278 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | createOutputBuffer | def createOutputBuffer(file, encoding):
"""Create a libxml2 output buffer from a Python file """
ret = libxml2mod.xmlCreateOutputBuffer(file, encoding)
if ret is None:raise treeError('xmlCreateOutputBuffer() failed')
return outputBuffer(_obj=ret) | python | def createOutputBuffer(file, encoding):
"""Create a libxml2 output buffer from a Python file """
ret = libxml2mod.xmlCreateOutputBuffer(file, encoding)
if ret is None:raise treeError('xmlCreateOutputBuffer() failed')
return outputBuffer(_obj=ret) | [
"def",
"createOutputBuffer",
"(",
"file",
",",
"encoding",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlCreateOutputBuffer",
"(",
"file",
",",
"encoding",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlCreateOutputBuffer() failed'",
")",
"return",
"outputBuffer",
"(",
"_obj",
"=",
"ret",
")"
] | Create a libxml2 output buffer from a Python file | [
"Create",
"a",
"libxml2",
"output",
"buffer",
"from",
"a",
"Python",
"file"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1563-L1567 |
29,279 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | createPushParser | def createPushParser(SAX, chunk, size, URI):
"""Create a progressive XML parser context to build either an
event flow if the SAX object is not None, or a DOM tree
otherwise. """
ret = libxml2mod.xmlCreatePushParser(SAX, chunk, size, URI)
if ret is None:raise parserError('xmlCreatePushParser() failed')
return parserCtxt(_obj=ret) | python | def createPushParser(SAX, chunk, size, URI):
"""Create a progressive XML parser context to build either an
event flow if the SAX object is not None, or a DOM tree
otherwise. """
ret = libxml2mod.xmlCreatePushParser(SAX, chunk, size, URI)
if ret is None:raise parserError('xmlCreatePushParser() failed')
return parserCtxt(_obj=ret) | [
"def",
"createPushParser",
"(",
"SAX",
",",
"chunk",
",",
"size",
",",
"URI",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlCreatePushParser",
"(",
"SAX",
",",
"chunk",
",",
"size",
",",
"URI",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"parserError",
"(",
"'xmlCreatePushParser() failed'",
")",
"return",
"parserCtxt",
"(",
"_obj",
"=",
"ret",
")"
] | Create a progressive XML parser context to build either an
event flow if the SAX object is not None, or a DOM tree
otherwise. | [
"Create",
"a",
"progressive",
"XML",
"parser",
"context",
"to",
"build",
"either",
"an",
"event",
"flow",
"if",
"the",
"SAX",
"object",
"is",
"not",
"None",
"or",
"a",
"DOM",
"tree",
"otherwise",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1569-L1575 |
29,280 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | htmlCreatePushParser | def htmlCreatePushParser(SAX, chunk, size, URI):
"""Create a progressive HTML parser context to build either an
event flow if the SAX object is not None, or a DOM tree
otherwise. """
ret = libxml2mod.htmlCreatePushParser(SAX, chunk, size, URI)
if ret is None:raise parserError('htmlCreatePushParser() failed')
return parserCtxt(_obj=ret) | python | def htmlCreatePushParser(SAX, chunk, size, URI):
"""Create a progressive HTML parser context to build either an
event flow if the SAX object is not None, or a DOM tree
otherwise. """
ret = libxml2mod.htmlCreatePushParser(SAX, chunk, size, URI)
if ret is None:raise parserError('htmlCreatePushParser() failed')
return parserCtxt(_obj=ret) | [
"def",
"htmlCreatePushParser",
"(",
"SAX",
",",
"chunk",
",",
"size",
",",
"URI",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"htmlCreatePushParser",
"(",
"SAX",
",",
"chunk",
",",
"size",
",",
"URI",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"parserError",
"(",
"'htmlCreatePushParser() failed'",
")",
"return",
"parserCtxt",
"(",
"_obj",
"=",
"ret",
")"
] | Create a progressive HTML parser context to build either an
event flow if the SAX object is not None, or a DOM tree
otherwise. | [
"Create",
"a",
"progressive",
"HTML",
"parser",
"context",
"to",
"build",
"either",
"an",
"event",
"flow",
"if",
"the",
"SAX",
"object",
"is",
"not",
"None",
"or",
"a",
"DOM",
"tree",
"otherwise",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1588-L1594 |
29,281 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | newNode | def newNode(name):
"""Create a new Node """
ret = libxml2mod.xmlNewNode(name)
if ret is None:raise treeError('xmlNewNode() failed')
return xmlNode(_obj=ret) | python | def newNode(name):
"""Create a new Node """
ret = libxml2mod.xmlNewNode(name)
if ret is None:raise treeError('xmlNewNode() failed')
return xmlNode(_obj=ret) | [
"def",
"newNode",
"(",
"name",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewNode",
"(",
"name",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewNode() failed'",
")",
"return",
"xmlNode",
"(",
"_obj",
"=",
"ret",
")"
] | Create a new Node | [
"Create",
"a",
"new",
"Node"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1606-L1610 |
29,282 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | relaxNGNewMemParserCtxt | def relaxNGNewMemParserCtxt(buffer, size):
"""Create an XML RelaxNGs parse context for that memory buffer
expected to contain an XML RelaxNGs file. """
ret = libxml2mod.xmlRelaxNGNewMemParserCtxt(buffer, size)
if ret is None:raise parserError('xmlRelaxNGNewMemParserCtxt() failed')
return relaxNgParserCtxt(_obj=ret) | python | def relaxNGNewMemParserCtxt(buffer, size):
"""Create an XML RelaxNGs parse context for that memory buffer
expected to contain an XML RelaxNGs file. """
ret = libxml2mod.xmlRelaxNGNewMemParserCtxt(buffer, size)
if ret is None:raise parserError('xmlRelaxNGNewMemParserCtxt() failed')
return relaxNgParserCtxt(_obj=ret) | [
"def",
"relaxNGNewMemParserCtxt",
"(",
"buffer",
",",
"size",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlRelaxNGNewMemParserCtxt",
"(",
"buffer",
",",
"size",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"parserError",
"(",
"'xmlRelaxNGNewMemParserCtxt() failed'",
")",
"return",
"relaxNgParserCtxt",
"(",
"_obj",
"=",
"ret",
")"
] | Create an XML RelaxNGs parse context for that memory buffer
expected to contain an XML RelaxNGs file. | [
"Create",
"an",
"XML",
"RelaxNGs",
"parse",
"context",
"for",
"that",
"memory",
"buffer",
"expected",
"to",
"contain",
"an",
"XML",
"RelaxNGs",
"file",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1641-L1646 |
29,283 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | buildQName | def buildQName(ncname, prefix, memory, len):
"""Builds the QName @prefix:@ncname in @memory if there is
enough space and prefix is not None nor empty, otherwise
allocate a new string. If prefix is None or empty it
returns ncname. """
ret = libxml2mod.xmlBuildQName(ncname, prefix, memory, len)
return ret | python | def buildQName(ncname, prefix, memory, len):
"""Builds the QName @prefix:@ncname in @memory if there is
enough space and prefix is not None nor empty, otherwise
allocate a new string. If prefix is None or empty it
returns ncname. """
ret = libxml2mod.xmlBuildQName(ncname, prefix, memory, len)
return ret | [
"def",
"buildQName",
"(",
"ncname",
",",
"prefix",
",",
"memory",
",",
"len",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlBuildQName",
"(",
"ncname",
",",
"prefix",
",",
"memory",
",",
"len",
")",
"return",
"ret"
] | Builds the QName @prefix:@ncname in @memory if there is
enough space and prefix is not None nor empty, otherwise
allocate a new string. If prefix is None or empty it
returns ncname. | [
"Builds",
"the",
"QName"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1659-L1665 |
29,284 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | newComment | def newComment(content):
"""Creation of a new node containing a comment. """
ret = libxml2mod.xmlNewComment(content)
if ret is None:raise treeError('xmlNewComment() failed')
return xmlNode(_obj=ret) | python | def newComment(content):
"""Creation of a new node containing a comment. """
ret = libxml2mod.xmlNewComment(content)
if ret is None:raise treeError('xmlNewComment() failed')
return xmlNode(_obj=ret) | [
"def",
"newComment",
"(",
"content",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewComment",
"(",
"content",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewComment() failed'",
")",
"return",
"xmlNode",
"(",
"_obj",
"=",
"ret",
")"
] | Creation of a new node containing a comment. | [
"Creation",
"of",
"a",
"new",
"node",
"containing",
"a",
"comment",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1677-L1681 |
29,285 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | newDoc | def newDoc(version):
"""Creates a new XML document """
ret = libxml2mod.xmlNewDoc(version)
if ret is None:raise treeError('xmlNewDoc() failed')
return xmlDoc(_obj=ret) | python | def newDoc(version):
"""Creates a new XML document """
ret = libxml2mod.xmlNewDoc(version)
if ret is None:raise treeError('xmlNewDoc() failed')
return xmlDoc(_obj=ret) | [
"def",
"newDoc",
"(",
"version",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewDoc",
"(",
"version",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewDoc() failed'",
")",
"return",
"xmlDoc",
"(",
"_obj",
"=",
"ret",
")"
] | Creates a new XML document | [
"Creates",
"a",
"new",
"XML",
"document"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1683-L1687 |
29,286 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | newPI | def newPI(name, content):
"""Creation of a processing instruction element. Use
xmlDocNewPI preferably to get string interning """
ret = libxml2mod.xmlNewPI(name, content)
if ret is None:raise treeError('xmlNewPI() failed')
return xmlNode(_obj=ret) | python | def newPI(name, content):
"""Creation of a processing instruction element. Use
xmlDocNewPI preferably to get string interning """
ret = libxml2mod.xmlNewPI(name, content)
if ret is None:raise treeError('xmlNewPI() failed')
return xmlNode(_obj=ret) | [
"def",
"newPI",
"(",
"name",
",",
"content",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewPI",
"(",
"name",
",",
"content",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewPI() failed'",
")",
"return",
"xmlNode",
"(",
"_obj",
"=",
"ret",
")"
] | Creation of a processing instruction element. Use
xmlDocNewPI preferably to get string interning | [
"Creation",
"of",
"a",
"processing",
"instruction",
"element",
".",
"Use",
"xmlDocNewPI",
"preferably",
"to",
"get",
"string",
"interning"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1689-L1694 |
29,287 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | newText | def newText(content):
"""Creation of a new text node. """
ret = libxml2mod.xmlNewText(content)
if ret is None:raise treeError('xmlNewText() failed')
return xmlNode(_obj=ret) | python | def newText(content):
"""Creation of a new text node. """
ret = libxml2mod.xmlNewText(content)
if ret is None:raise treeError('xmlNewText() failed')
return xmlNode(_obj=ret) | [
"def",
"newText",
"(",
"content",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewText",
"(",
"content",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewText() failed'",
")",
"return",
"xmlNode",
"(",
"_obj",
"=",
"ret",
")"
] | Creation of a new text node. | [
"Creation",
"of",
"a",
"new",
"text",
"node",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1696-L1700 |
29,288 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | newTextLen | def newTextLen(content, len):
"""Creation of a new text node with an extra parameter for the
content's length """
ret = libxml2mod.xmlNewTextLen(content, len)
if ret is None:raise treeError('xmlNewTextLen() failed')
return xmlNode(_obj=ret) | python | def newTextLen(content, len):
"""Creation of a new text node with an extra parameter for the
content's length """
ret = libxml2mod.xmlNewTextLen(content, len)
if ret is None:raise treeError('xmlNewTextLen() failed')
return xmlNode(_obj=ret) | [
"def",
"newTextLen",
"(",
"content",
",",
"len",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewTextLen",
"(",
"content",
",",
"len",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewTextLen() failed'",
")",
"return",
"xmlNode",
"(",
"_obj",
"=",
"ret",
")"
] | Creation of a new text node with an extra parameter for the
content's length | [
"Creation",
"of",
"a",
"new",
"text",
"node",
"with",
"an",
"extra",
"parameter",
"for",
"the",
"content",
"s",
"length"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1702-L1707 |
29,289 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | newTextReaderFilename | def newTextReaderFilename(URI):
"""Create an xmlTextReader structure fed with the resource at
@URI """
ret = libxml2mod.xmlNewTextReaderFilename(URI)
if ret is None:raise treeError('xmlNewTextReaderFilename() failed')
return xmlTextReader(_obj=ret) | python | def newTextReaderFilename(URI):
"""Create an xmlTextReader structure fed with the resource at
@URI """
ret = libxml2mod.xmlNewTextReaderFilename(URI)
if ret is None:raise treeError('xmlNewTextReaderFilename() failed')
return xmlTextReader(_obj=ret) | [
"def",
"newTextReaderFilename",
"(",
"URI",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewTextReaderFilename",
"(",
"URI",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewTextReaderFilename() failed'",
")",
"return",
"xmlTextReader",
"(",
"_obj",
"=",
"ret",
")"
] | Create an xmlTextReader structure fed with the resource at
@URI | [
"Create",
"an",
"xmlTextReader",
"structure",
"fed",
"with",
"the",
"resource",
"at"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1941-L1946 |
29,290 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | readerForFd | def readerForFd(fd, URL, encoding, options):
"""Create an xmltextReader for an XML from a file descriptor.
The parsing flags @options are a combination of
xmlParserOption. NOTE that the file descriptor will not be
closed when the reader is closed or reset. """
ret = libxml2mod.xmlReaderForFd(fd, URL, encoding, options)
if ret is None:raise treeError('xmlReaderForFd() failed')
return xmlTextReader(_obj=ret) | python | def readerForFd(fd, URL, encoding, options):
"""Create an xmltextReader for an XML from a file descriptor.
The parsing flags @options are a combination of
xmlParserOption. NOTE that the file descriptor will not be
closed when the reader is closed or reset. """
ret = libxml2mod.xmlReaderForFd(fd, URL, encoding, options)
if ret is None:raise treeError('xmlReaderForFd() failed')
return xmlTextReader(_obj=ret) | [
"def",
"readerForFd",
"(",
"fd",
",",
"URL",
",",
"encoding",
",",
"options",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlReaderForFd",
"(",
"fd",
",",
"URL",
",",
"encoding",
",",
"options",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlReaderForFd() failed'",
")",
"return",
"xmlTextReader",
"(",
"_obj",
"=",
"ret",
")"
] | Create an xmltextReader for an XML from a file descriptor.
The parsing flags @options are a combination of
xmlParserOption. NOTE that the file descriptor will not be
closed when the reader is closed or reset. | [
"Create",
"an",
"xmltextReader",
"for",
"an",
"XML",
"from",
"a",
"file",
"descriptor",
".",
"The",
"parsing",
"flags"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1955-L1962 |
29,291 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | regexpCompile | def regexpCompile(regexp):
"""Parses a regular expression conforming to XML Schemas Part
2 Datatype Appendix F and builds an automata suitable for
testing strings against that regular expression """
ret = libxml2mod.xmlRegexpCompile(regexp)
if ret is None:raise treeError('xmlRegexpCompile() failed')
return xmlReg(_obj=ret) | python | def regexpCompile(regexp):
"""Parses a regular expression conforming to XML Schemas Part
2 Datatype Appendix F and builds an automata suitable for
testing strings against that regular expression """
ret = libxml2mod.xmlRegexpCompile(regexp)
if ret is None:raise treeError('xmlRegexpCompile() failed')
return xmlReg(_obj=ret) | [
"def",
"regexpCompile",
"(",
"regexp",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlRegexpCompile",
"(",
"regexp",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlRegexpCompile() failed'",
")",
"return",
"xmlReg",
"(",
"_obj",
"=",
"ret",
")"
] | Parses a regular expression conforming to XML Schemas Part
2 Datatype Appendix F and builds an automata suitable for
testing strings against that regular expression | [
"Parses",
"a",
"regular",
"expression",
"conforming",
"to",
"XML",
"Schemas",
"Part",
"2",
"Datatype",
"Appendix",
"F",
"and",
"builds",
"an",
"automata",
"suitable",
"for",
"testing",
"strings",
"against",
"that",
"regular",
"expression"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1982-L1988 |
29,292 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | schemaNewMemParserCtxt | def schemaNewMemParserCtxt(buffer, size):
"""Create an XML Schemas parse context for that memory buffer
expected to contain an XML Schemas file. """
ret = libxml2mod.xmlSchemaNewMemParserCtxt(buffer, size)
if ret is None:raise parserError('xmlSchemaNewMemParserCtxt() failed')
return SchemaParserCtxt(_obj=ret) | python | def schemaNewMemParserCtxt(buffer, size):
"""Create an XML Schemas parse context for that memory buffer
expected to contain an XML Schemas file. """
ret = libxml2mod.xmlSchemaNewMemParserCtxt(buffer, size)
if ret is None:raise parserError('xmlSchemaNewMemParserCtxt() failed')
return SchemaParserCtxt(_obj=ret) | [
"def",
"schemaNewMemParserCtxt",
"(",
"buffer",
",",
"size",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlSchemaNewMemParserCtxt",
"(",
"buffer",
",",
"size",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"parserError",
"(",
"'xmlSchemaNewMemParserCtxt() failed'",
")",
"return",
"SchemaParserCtxt",
"(",
"_obj",
"=",
"ret",
")"
] | Create an XML Schemas parse context for that memory buffer
expected to contain an XML Schemas file. | [
"Create",
"an",
"XML",
"Schemas",
"parse",
"context",
"for",
"that",
"memory",
"buffer",
"expected",
"to",
"contain",
"an",
"XML",
"Schemas",
"file",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L1994-L1999 |
29,293 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | valuePop | def valuePop(ctxt):
"""Pops the top XPath object from the value stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.valuePop(ctxt__o)
return ret | python | def valuePop(ctxt):
"""Pops the top XPath object from the value stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.valuePop(ctxt__o)
return ret | [
"def",
"valuePop",
"(",
"ctxt",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"valuePop",
"(",
"ctxt__o",
")",
"return",
"ret"
] | Pops the top XPath object from the value stack | [
"Pops",
"the",
"top",
"XPath",
"object",
"from",
"the",
"value",
"stack"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L3008-L3013 |
29,294 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | xmlCore.removeNsDef | def removeNsDef(self, href):
"""
Remove a namespace definition from a node. If href is None,
remove all of the ns definitions on that node. The removed
namespaces are returned as a linked list.
Note: If any child nodes referred to the removed namespaces,
they will be left with dangling links. You should call
renconciliateNs() to fix those pointers.
Note: This method does not free memory taken by the ns
definitions. You will need to free it manually with the
freeNsList() method on the returns xmlNs object.
"""
ret = libxml2mod.xmlNodeRemoveNsDef(self._o, href)
if ret is None:return None
__tmp = xmlNs(_obj=ret)
return __tmp | python | def removeNsDef(self, href):
"""
Remove a namespace definition from a node. If href is None,
remove all of the ns definitions on that node. The removed
namespaces are returned as a linked list.
Note: If any child nodes referred to the removed namespaces,
they will be left with dangling links. You should call
renconciliateNs() to fix those pointers.
Note: This method does not free memory taken by the ns
definitions. You will need to free it manually with the
freeNsList() method on the returns xmlNs object.
"""
ret = libxml2mod.xmlNodeRemoveNsDef(self._o, href)
if ret is None:return None
__tmp = xmlNs(_obj=ret)
return __tmp | [
"def",
"removeNsDef",
"(",
"self",
",",
"href",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNodeRemoveNsDef",
"(",
"self",
".",
"_o",
",",
"href",
")",
"if",
"ret",
"is",
"None",
":",
"return",
"None",
"__tmp",
"=",
"xmlNs",
"(",
"_obj",
"=",
"ret",
")",
"return",
"__tmp"
] | Remove a namespace definition from a node. If href is None,
remove all of the ns definitions on that node. The removed
namespaces are returned as a linked list.
Note: If any child nodes referred to the removed namespaces,
they will be left with dangling links. You should call
renconciliateNs() to fix those pointers.
Note: This method does not free memory taken by the ns
definitions. You will need to free it manually with the
freeNsList() method on the returns xmlNs object. | [
"Remove",
"a",
"namespace",
"definition",
"from",
"a",
"node",
".",
"If",
"href",
"is",
"None",
"remove",
"all",
"of",
"the",
"ns",
"definitions",
"on",
"that",
"node",
".",
"The",
"removed",
"namespaces",
"are",
"returned",
"as",
"a",
"linked",
"list",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L489-L507 |
29,295 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | xmlNode.debugDumpNode | def debugDumpNode(self, output, depth):
"""Dumps debug information for the element node, it is
recursive """
libxml2mod.xmlDebugDumpNode(output, self._o, depth) | python | def debugDumpNode(self, output, depth):
"""Dumps debug information for the element node, it is
recursive """
libxml2mod.xmlDebugDumpNode(output, self._o, depth) | [
"def",
"debugDumpNode",
"(",
"self",
",",
"output",
",",
"depth",
")",
":",
"libxml2mod",
".",
"xmlDebugDumpNode",
"(",
"output",
",",
"self",
".",
"_o",
",",
"depth",
")"
] | Dumps debug information for the element node, it is
recursive | [
"Dumps",
"debug",
"information",
"for",
"the",
"element",
"node",
"it",
"is",
"recursive"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L3043-L3046 |
29,296 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | xmlNode.debugDumpNodeList | def debugDumpNodeList(self, output, depth):
"""Dumps debug information for the list of element node, it is
recursive """
libxml2mod.xmlDebugDumpNodeList(output, self._o, depth) | python | def debugDumpNodeList(self, output, depth):
"""Dumps debug information for the list of element node, it is
recursive """
libxml2mod.xmlDebugDumpNodeList(output, self._o, depth) | [
"def",
"debugDumpNodeList",
"(",
"self",
",",
"output",
",",
"depth",
")",
":",
"libxml2mod",
".",
"xmlDebugDumpNodeList",
"(",
"output",
",",
"self",
".",
"_o",
",",
"depth",
")"
] | Dumps debug information for the list of element node, it is
recursive | [
"Dumps",
"debug",
"information",
"for",
"the",
"list",
"of",
"element",
"node",
"it",
"is",
"recursive"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L3048-L3051 |
29,297 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | xmlNode.debugDumpOneNode | def debugDumpOneNode(self, output, depth):
"""Dumps debug information for the element node, it is not
recursive """
libxml2mod.xmlDebugDumpOneNode(output, self._o, depth) | python | def debugDumpOneNode(self, output, depth):
"""Dumps debug information for the element node, it is not
recursive """
libxml2mod.xmlDebugDumpOneNode(output, self._o, depth) | [
"def",
"debugDumpOneNode",
"(",
"self",
",",
"output",
",",
"depth",
")",
":",
"libxml2mod",
".",
"xmlDebugDumpOneNode",
"(",
"output",
",",
"self",
".",
"_o",
",",
"depth",
")"
] | Dumps debug information for the element node, it is not
recursive | [
"Dumps",
"debug",
"information",
"for",
"the",
"element",
"node",
"it",
"is",
"not",
"recursive"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L3053-L3056 |
29,298 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | xmlNode.addChild | def addChild(self, cur):
"""Add a new node to @parent, at the end of the child (or
property) list merging adjacent TEXT nodes (in which case
@cur is freed) If the new node is ATTRIBUTE, it is added
into properties instead of children. If there is an
attribute with equal name, it is first destroyed. """
if cur is None: cur__o = None
else: cur__o = cur._o
ret = libxml2mod.xmlAddChild(self._o, cur__o)
if ret is None:raise treeError('xmlAddChild() failed')
__tmp = xmlNode(_obj=ret)
return __tmp | python | def addChild(self, cur):
"""Add a new node to @parent, at the end of the child (or
property) list merging adjacent TEXT nodes (in which case
@cur is freed) If the new node is ATTRIBUTE, it is added
into properties instead of children. If there is an
attribute with equal name, it is first destroyed. """
if cur is None: cur__o = None
else: cur__o = cur._o
ret = libxml2mod.xmlAddChild(self._o, cur__o)
if ret is None:raise treeError('xmlAddChild() failed')
__tmp = xmlNode(_obj=ret)
return __tmp | [
"def",
"addChild",
"(",
"self",
",",
"cur",
")",
":",
"if",
"cur",
"is",
"None",
":",
"cur__o",
"=",
"None",
"else",
":",
"cur__o",
"=",
"cur",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlAddChild",
"(",
"self",
".",
"_o",
",",
"cur__o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlAddChild() failed'",
")",
"__tmp",
"=",
"xmlNode",
"(",
"_obj",
"=",
"ret",
")",
"return",
"__tmp"
] | Add a new node to @parent, at the end of the child (or
property) list merging adjacent TEXT nodes (in which case
@cur is freed) If the new node is ATTRIBUTE, it is added
into properties instead of children. If there is an
attribute with equal name, it is first destroyed. | [
"Add",
"a",
"new",
"node",
"to"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L3075-L3086 |
29,299 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | xmlNode.addChildList | def addChildList(self, cur):
"""Add a list of node at the end of the child list of the
parent merging adjacent TEXT nodes (@cur may be freed) """
if cur is None: cur__o = None
else: cur__o = cur._o
ret = libxml2mod.xmlAddChildList(self._o, cur__o)
if ret is None:raise treeError('xmlAddChildList() failed')
__tmp = xmlNode(_obj=ret)
return __tmp | python | def addChildList(self, cur):
"""Add a list of node at the end of the child list of the
parent merging adjacent TEXT nodes (@cur may be freed) """
if cur is None: cur__o = None
else: cur__o = cur._o
ret = libxml2mod.xmlAddChildList(self._o, cur__o)
if ret is None:raise treeError('xmlAddChildList() failed')
__tmp = xmlNode(_obj=ret)
return __tmp | [
"def",
"addChildList",
"(",
"self",
",",
"cur",
")",
":",
"if",
"cur",
"is",
"None",
":",
"cur__o",
"=",
"None",
"else",
":",
"cur__o",
"=",
"cur",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlAddChildList",
"(",
"self",
".",
"_o",
",",
"cur__o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlAddChildList() failed'",
")",
"__tmp",
"=",
"xmlNode",
"(",
"_obj",
"=",
"ret",
")",
"return",
"__tmp"
] | Add a list of node at the end of the child list of the
parent merging adjacent TEXT nodes (@cur may be freed) | [
"Add",
"a",
"list",
"of",
"node",
"at",
"the",
"end",
"of",
"the",
"child",
"list",
"of",
"the",
"parent",
"merging",
"adjacent",
"TEXT",
"nodes",
"("
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L3088-L3096 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.