repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
apple/turicreate
src/unity/python/turicreate/visualization/show.py
box_plot
def box_plot(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d box and whiskers plot, and returns the resulting Plot object. The function x as SArray of dtype str and y as SArray of dtype: int, float. Parameters ---------- x : SArray The data to plot on the X axis of the box and whiskers plot. Must be an SArray with dtype string. y : SArray The data to plot on the Y axis of the box and whiskers plot. Must be numeric (int/float) and must be the same length as `x`. xlabel : str (optional) The text label for the X axis. Defaults to "X". ylabel : str (optional) The text label for the Y axis. Defaults to "Y". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Returns ------- out : Plot A :class: Plot object that is the box and whiskers plot. Examples -------- Make a box and whiskers plot. >>> bp = turicreate.visualization.box_plot(tc.SArray(['a','b','c','a','a']),tc.SArray([4.0,3.25,2.1,2.0,1.0])) """ if (not isinstance(x, tc.data_structures.sarray.SArray) or not isinstance(y, tc.data_structures.sarray.SArray) or x.dtype != str or y.dtype not in [int, float]): raise ValueError("turicreate.visualization.box_plot supports " + "x as SArray of dtype str and y as SArray of dtype: int, float." + "\nExample: turicreate.visualization.box_plot(tc.SArray(['a','b','c','a','a']),tc.SArray([4.0,3.25,2.1,2.0,1.0]))") title = _get_title(title) plt_ref = tc.extensions.plot_boxes_and_whiskers(x, y, xlabel, ylabel, title) return Plot(plt_ref)
python
def box_plot(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d box and whiskers plot, and returns the resulting Plot object. The function x as SArray of dtype str and y as SArray of dtype: int, float. Parameters ---------- x : SArray The data to plot on the X axis of the box and whiskers plot. Must be an SArray with dtype string. y : SArray The data to plot on the Y axis of the box and whiskers plot. Must be numeric (int/float) and must be the same length as `x`. xlabel : str (optional) The text label for the X axis. Defaults to "X". ylabel : str (optional) The text label for the Y axis. Defaults to "Y". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Returns ------- out : Plot A :class: Plot object that is the box and whiskers plot. Examples -------- Make a box and whiskers plot. >>> bp = turicreate.visualization.box_plot(tc.SArray(['a','b','c','a','a']),tc.SArray([4.0,3.25,2.1,2.0,1.0])) """ if (not isinstance(x, tc.data_structures.sarray.SArray) or not isinstance(y, tc.data_structures.sarray.SArray) or x.dtype != str or y.dtype not in [int, float]): raise ValueError("turicreate.visualization.box_plot supports " + "x as SArray of dtype str and y as SArray of dtype: int, float." + "\nExample: turicreate.visualization.box_plot(tc.SArray(['a','b','c','a','a']),tc.SArray([4.0,3.25,2.1,2.0,1.0]))") title = _get_title(title) plt_ref = tc.extensions.plot_boxes_and_whiskers(x, y, xlabel, ylabel, title) return Plot(plt_ref)
[ "def", "box_plot", "(", "x", ",", "y", ",", "xlabel", "=", "LABEL_DEFAULT", ",", "ylabel", "=", "LABEL_DEFAULT", ",", "title", "=", "LABEL_DEFAULT", ")", ":", "if", "(", "not", "isinstance", "(", "x", ",", "tc", ".", "data_structures", ".", "sarray", ".", "SArray", ")", "or", "not", "isinstance", "(", "y", ",", "tc", ".", "data_structures", ".", "sarray", ".", "SArray", ")", "or", "x", ".", "dtype", "!=", "str", "or", "y", ".", "dtype", "not", "in", "[", "int", ",", "float", "]", ")", ":", "raise", "ValueError", "(", "\"turicreate.visualization.box_plot supports \"", "+", "\"x as SArray of dtype str and y as SArray of dtype: int, float.\"", "+", "\"\\nExample: turicreate.visualization.box_plot(tc.SArray(['a','b','c','a','a']),tc.SArray([4.0,3.25,2.1,2.0,1.0]))\"", ")", "title", "=", "_get_title", "(", "title", ")", "plt_ref", "=", "tc", ".", "extensions", ".", "plot_boxes_and_whiskers", "(", "x", ",", "y", ",", "xlabel", ",", "ylabel", ",", "title", ")", "return", "Plot", "(", "plt_ref", ")" ]
Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d box and whiskers plot, and returns the resulting Plot object. The function x as SArray of dtype str and y as SArray of dtype: int, float. Parameters ---------- x : SArray The data to plot on the X axis of the box and whiskers plot. Must be an SArray with dtype string. y : SArray The data to plot on the Y axis of the box and whiskers plot. Must be numeric (int/float) and must be the same length as `x`. xlabel : str (optional) The text label for the X axis. Defaults to "X". ylabel : str (optional) The text label for the Y axis. Defaults to "Y". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Returns ------- out : Plot A :class: Plot object that is the box and whiskers plot. Examples -------- Make a box and whiskers plot. >>> bp = turicreate.visualization.box_plot(tc.SArray(['a','b','c','a','a']),tc.SArray([4.0,3.25,2.1,2.0,1.0]))
[ "Plots", "the", "data", "in", "x", "on", "the", "X", "axis", "and", "the", "data", "in", "y", "on", "the", "Y", "axis", "in", "a", "2d", "box", "and", "whiskers", "plot", "and", "returns", "the", "resulting", "Plot", "object", ".", "The", "function", "x", "as", "SArray", "of", "dtype", "str", "and", "y", "as", "SArray", "of", "dtype", ":", "int", "float", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/visualization/show.py#L292-L337
train
apple/turicreate
src/unity/python/turicreate/visualization/show.py
columnwise_summary
def columnwise_summary(sf): """ Plots a columnwise summary of the sframe provided as input, and returns the resulting Plot object. The function supports SFrames. Parameters ---------- sf : SFrame The data to get a columnwise summary for. Returns ------- out : Plot A :class: Plot object that is the columnwise summary plot. Examples -------- Make a columnwise summary of an SFrame. >>> x = turicreate.SArray([1,2,3,4,5]) >>> s = turicreate.SArray(['a','b','c','a','a']) >>> sf_test = turicreate.SFrame([x,x,x,x,s,s,s,x,s,x,s,s,s,x,x]) >>> colsum = turicreate.visualization.columnwise_summary(sf_test) """ if not isinstance(sf, tc.data_structures.sframe.SFrame): raise ValueError("turicreate.visualization.columnwise_summary " + "supports SFrame") plt_ref = tc.extensions.plot_columnwise_summary(sf) return Plot(plt_ref)
python
def columnwise_summary(sf): """ Plots a columnwise summary of the sframe provided as input, and returns the resulting Plot object. The function supports SFrames. Parameters ---------- sf : SFrame The data to get a columnwise summary for. Returns ------- out : Plot A :class: Plot object that is the columnwise summary plot. Examples -------- Make a columnwise summary of an SFrame. >>> x = turicreate.SArray([1,2,3,4,5]) >>> s = turicreate.SArray(['a','b','c','a','a']) >>> sf_test = turicreate.SFrame([x,x,x,x,s,s,s,x,s,x,s,s,s,x,x]) >>> colsum = turicreate.visualization.columnwise_summary(sf_test) """ if not isinstance(sf, tc.data_structures.sframe.SFrame): raise ValueError("turicreate.visualization.columnwise_summary " + "supports SFrame") plt_ref = tc.extensions.plot_columnwise_summary(sf) return Plot(plt_ref)
[ "def", "columnwise_summary", "(", "sf", ")", ":", "if", "not", "isinstance", "(", "sf", ",", "tc", ".", "data_structures", ".", "sframe", ".", "SFrame", ")", ":", "raise", "ValueError", "(", "\"turicreate.visualization.columnwise_summary \"", "+", "\"supports SFrame\"", ")", "plt_ref", "=", "tc", ".", "extensions", ".", "plot_columnwise_summary", "(", "sf", ")", "return", "Plot", "(", "plt_ref", ")" ]
Plots a columnwise summary of the sframe provided as input, and returns the resulting Plot object. The function supports SFrames. Parameters ---------- sf : SFrame The data to get a columnwise summary for. Returns ------- out : Plot A :class: Plot object that is the columnwise summary plot. Examples -------- Make a columnwise summary of an SFrame. >>> x = turicreate.SArray([1,2,3,4,5]) >>> s = turicreate.SArray(['a','b','c','a','a']) >>> sf_test = turicreate.SFrame([x,x,x,x,s,s,s,x,s,x,s,s,s,x,x]) >>> colsum = turicreate.visualization.columnwise_summary(sf_test)
[ "Plots", "a", "columnwise", "summary", "of", "the", "sframe", "provided", "as", "input", "and", "returns", "the", "resulting", "Plot", "object", ".", "The", "function", "supports", "SFrames", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/visualization/show.py#L339-L369
train
apple/turicreate
src/unity/python/turicreate/visualization/show.py
histogram
def histogram(sa, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots a histogram of the sarray provided as input, and returns the resulting Plot object. The function supports numeric SArrays with dtypes int or float. Parameters ---------- sa : SArray The data to get a histogram for. Must be numeric (int/float). xlabel : str (optional) The text label for the X axis. Defaults to "Values". ylabel : str (optional) The text label for the Y axis. Defaults to "Count". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Returns ------- out : Plot A :class: Plot object that is the histogram. Examples -------- Make a histogram of an SArray. >>> x = turicreate.SArray([1,2,3,4,5,1,1,1,1,2,2,3,2,3,1,1,1,4]) >>> hist = turicreate.visualization.histogram(x) """ if (not isinstance(sa, tc.data_structures.sarray.SArray) or sa.dtype not in [int, float]): raise ValueError("turicreate.visualization.histogram supports " + "SArrays of dtypes: int, float") title = _get_title(title) plt_ref = tc.extensions.plot_histogram(sa, xlabel, ylabel, title) return Plot(plt_ref)
python
def histogram(sa, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots a histogram of the sarray provided as input, and returns the resulting Plot object. The function supports numeric SArrays with dtypes int or float. Parameters ---------- sa : SArray The data to get a histogram for. Must be numeric (int/float). xlabel : str (optional) The text label for the X axis. Defaults to "Values". ylabel : str (optional) The text label for the Y axis. Defaults to "Count". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Returns ------- out : Plot A :class: Plot object that is the histogram. Examples -------- Make a histogram of an SArray. >>> x = turicreate.SArray([1,2,3,4,5,1,1,1,1,2,2,3,2,3,1,1,1,4]) >>> hist = turicreate.visualization.histogram(x) """ if (not isinstance(sa, tc.data_structures.sarray.SArray) or sa.dtype not in [int, float]): raise ValueError("turicreate.visualization.histogram supports " + "SArrays of dtypes: int, float") title = _get_title(title) plt_ref = tc.extensions.plot_histogram(sa, xlabel, ylabel, title) return Plot(plt_ref)
[ "def", "histogram", "(", "sa", ",", "xlabel", "=", "LABEL_DEFAULT", ",", "ylabel", "=", "LABEL_DEFAULT", ",", "title", "=", "LABEL_DEFAULT", ")", ":", "if", "(", "not", "isinstance", "(", "sa", ",", "tc", ".", "data_structures", ".", "sarray", ".", "SArray", ")", "or", "sa", ".", "dtype", "not", "in", "[", "int", ",", "float", "]", ")", ":", "raise", "ValueError", "(", "\"turicreate.visualization.histogram supports \"", "+", "\"SArrays of dtypes: int, float\"", ")", "title", "=", "_get_title", "(", "title", ")", "plt_ref", "=", "tc", ".", "extensions", ".", "plot_histogram", "(", "sa", ",", "xlabel", ",", "ylabel", ",", "title", ")", "return", "Plot", "(", "plt_ref", ")" ]
Plots a histogram of the sarray provided as input, and returns the resulting Plot object. The function supports numeric SArrays with dtypes int or float. Parameters ---------- sa : SArray The data to get a histogram for. Must be numeric (int/float). xlabel : str (optional) The text label for the X axis. Defaults to "Values". ylabel : str (optional) The text label for the Y axis. Defaults to "Count". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Returns ------- out : Plot A :class: Plot object that is the histogram. Examples -------- Make a histogram of an SArray. >>> x = turicreate.SArray([1,2,3,4,5,1,1,1,1,2,2,3,2,3,1,1,1,4]) >>> hist = turicreate.visualization.histogram(x)
[ "Plots", "a", "histogram", "of", "the", "sarray", "provided", "as", "input", "and", "returns", "the", "resulting", "Plot", "object", ".", "The", "function", "supports", "numeric", "SArrays", "with", "dtypes", "int", "or", "float", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/visualization/show.py#L371-L411
train
apple/turicreate
src/unity/python/turicreate/visualization/show.py
item_frequency
def item_frequency(sa, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots an item frequency of the sarray provided as input, and returns the resulting Plot object. The function supports SArrays with dtype str. Parameters ---------- sa : SArray The data to get an item frequency for. Must have dtype str xlabel : str (optional) The text label for the X axis. Defaults to "Values". ylabel : str (optional) The text label for the Y axis. Defaults to "Count". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Returns ------- out : Plot A :class: Plot object that is the item frequency plot. Examples -------- Make an item frequency of an SArray. >>> x = turicreate.SArray(['a','ab','acd','ab','a','a','a','ab','cd']) >>> ifplt = turicreate.visualization.item_frequency(x) """ if (not isinstance(sa, tc.data_structures.sarray.SArray) or sa.dtype != str): raise ValueError("turicreate.visualization.item_frequency supports " + "SArrays of dtype str") title = _get_title(title) plt_ref = tc.extensions.plot_item_frequency(sa, xlabel, ylabel, title) return Plot(plt_ref)
python
def item_frequency(sa, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots an item frequency of the sarray provided as input, and returns the resulting Plot object. The function supports SArrays with dtype str. Parameters ---------- sa : SArray The data to get an item frequency for. Must have dtype str xlabel : str (optional) The text label for the X axis. Defaults to "Values". ylabel : str (optional) The text label for the Y axis. Defaults to "Count". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Returns ------- out : Plot A :class: Plot object that is the item frequency plot. Examples -------- Make an item frequency of an SArray. >>> x = turicreate.SArray(['a','ab','acd','ab','a','a','a','ab','cd']) >>> ifplt = turicreate.visualization.item_frequency(x) """ if (not isinstance(sa, tc.data_structures.sarray.SArray) or sa.dtype != str): raise ValueError("turicreate.visualization.item_frequency supports " + "SArrays of dtype str") title = _get_title(title) plt_ref = tc.extensions.plot_item_frequency(sa, xlabel, ylabel, title) return Plot(plt_ref)
[ "def", "item_frequency", "(", "sa", ",", "xlabel", "=", "LABEL_DEFAULT", ",", "ylabel", "=", "LABEL_DEFAULT", ",", "title", "=", "LABEL_DEFAULT", ")", ":", "if", "(", "not", "isinstance", "(", "sa", ",", "tc", ".", "data_structures", ".", "sarray", ".", "SArray", ")", "or", "sa", ".", "dtype", "!=", "str", ")", ":", "raise", "ValueError", "(", "\"turicreate.visualization.item_frequency supports \"", "+", "\"SArrays of dtype str\"", ")", "title", "=", "_get_title", "(", "title", ")", "plt_ref", "=", "tc", ".", "extensions", ".", "plot_item_frequency", "(", "sa", ",", "xlabel", ",", "ylabel", ",", "title", ")", "return", "Plot", "(", "plt_ref", ")" ]
Plots an item frequency of the sarray provided as input, and returns the resulting Plot object. The function supports SArrays with dtype str. Parameters ---------- sa : SArray The data to get an item frequency for. Must have dtype str xlabel : str (optional) The text label for the X axis. Defaults to "Values". ylabel : str (optional) The text label for the Y axis. Defaults to "Count". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Returns ------- out : Plot A :class: Plot object that is the item frequency plot. Examples -------- Make an item frequency of an SArray. >>> x = turicreate.SArray(['a','ab','acd','ab','a','a','a','ab','cd']) >>> ifplt = turicreate.visualization.item_frequency(x)
[ "Plots", "an", "item", "frequency", "of", "the", "sarray", "provided", "as", "input", "and", "returns", "the", "resulting", "Plot", "object", ".", "The", "function", "supports", "SArrays", "with", "dtype", "str", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/visualization/show.py#L413-L453
train
apple/turicreate
deps/src/libevent-2.0.18-stable/event_rpcgen.py
Parse
def Parse(factory, file): """ Parses the input file and returns C code and corresponding header file. """ entities = [] while 1: # Just gets the whole struct nicely formatted data = GetNextStruct(file) if not data: break entities.extend(ProcessStruct(factory, data)) return entities
python
def Parse(factory, file): """ Parses the input file and returns C code and corresponding header file. """ entities = [] while 1: # Just gets the whole struct nicely formatted data = GetNextStruct(file) if not data: break entities.extend(ProcessStruct(factory, data)) return entities
[ "def", "Parse", "(", "factory", ",", "file", ")", ":", "entities", "=", "[", "]", "while", "1", ":", "# Just gets the whole struct nicely formatted", "data", "=", "GetNextStruct", "(", "file", ")", "if", "not", "data", ":", "break", "entities", ".", "extend", "(", "ProcessStruct", "(", "factory", ",", "data", ")", ")", "return", "entities" ]
Parses the input file and returns C code and corresponding header file.
[ "Parses", "the", "input", "file", "and", "returns", "C", "code", "and", "corresponding", "header", "file", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libevent-2.0.18-stable/event_rpcgen.py#L1509-L1525
train
apple/turicreate
deps/src/libevent-2.0.18-stable/event_rpcgen.py
Struct.EntryTagName
def EntryTagName(self, entry): """Creates the name inside an enumeration for distinguishing data types.""" name = "%s_%s" % (self._name, entry.Name()) return name.upper()
python
def EntryTagName(self, entry): """Creates the name inside an enumeration for distinguishing data types.""" name = "%s_%s" % (self._name, entry.Name()) return name.upper()
[ "def", "EntryTagName", "(", "self", ",", "entry", ")", ":", "name", "=", "\"%s_%s\"", "%", "(", "self", ".", "_name", ",", "entry", ".", "Name", "(", ")", ")", "return", "name", ".", "upper", "(", ")" ]
Creates the name inside an enumeration for distinguishing data types.
[ "Creates", "the", "name", "inside", "an", "enumeration", "for", "distinguishing", "data", "types", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libevent-2.0.18-stable/event_rpcgen.py#L66-L70
train
apple/turicreate
deps/src/libevent-2.0.18-stable/event_rpcgen.py
Struct.PrintIndented
def PrintIndented(self, file, ident, code): """Takes an array, add indentation to each entry and prints it.""" for entry in code: print >>file, '%s%s' % (ident, entry)
python
def PrintIndented(self, file, ident, code): """Takes an array, add indentation to each entry and prints it.""" for entry in code: print >>file, '%s%s' % (ident, entry)
[ "def", "PrintIndented", "(", "self", ",", "file", ",", "ident", ",", "code", ")", ":", "for", "entry", "in", "code", ":", "print", ">>", "file", ",", "'%s%s'", "%", "(", "ident", ",", "entry", ")" ]
Takes an array, add indentation to each entry and prints it.
[ "Takes", "an", "array", "add", "indentation", "to", "each", "entry", "and", "prints", "it", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libevent-2.0.18-stable/event_rpcgen.py#L72-L75
train
apple/turicreate
deps/src/libevent-2.0.18-stable/event_rpcgen.py
StructCCode.PrintTags
def PrintTags(self, file): """Prints the tag definitions for a structure.""" print >>file, '/* Tag definition for %s */' % self._name print >>file, 'enum %s_ {' % self._name.lower() for entry in self._entries: print >>file, ' %s=%d,' % (self.EntryTagName(entry), entry.Tag()) print >>file, ' %s_MAX_TAGS' % (self._name.upper()) print >>file, '};\n'
python
def PrintTags(self, file): """Prints the tag definitions for a structure.""" print >>file, '/* Tag definition for %s */' % self._name print >>file, 'enum %s_ {' % self._name.lower() for entry in self._entries: print >>file, ' %s=%d,' % (self.EntryTagName(entry), entry.Tag()) print >>file, ' %s_MAX_TAGS' % (self._name.upper()) print >>file, '};\n'
[ "def", "PrintTags", "(", "self", ",", "file", ")", ":", "print", ">>", "file", ",", "'/* Tag definition for %s */'", "%", "self", ".", "_name", "print", ">>", "file", ",", "'enum %s_ {'", "%", "self", ".", "_name", ".", "lower", "(", ")", "for", "entry", "in", "self", ".", "_entries", ":", "print", ">>", "file", ",", "' %s=%d,'", "%", "(", "self", ".", "EntryTagName", "(", "entry", ")", ",", "entry", ".", "Tag", "(", ")", ")", "print", ">>", "file", ",", "' %s_MAX_TAGS'", "%", "(", "self", ".", "_name", ".", "upper", "(", ")", ")", "print", ">>", "file", ",", "'};\\n'" ]
Prints the tag definitions for a structure.
[ "Prints", "the", "tag", "definitions", "for", "a", "structure", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libevent-2.0.18-stable/event_rpcgen.py#L83-L91
train
apple/turicreate
src/unity/python/turicreate/aggregate.py
QUANTILE
def QUANTILE(src_column, *args): """ Builtin approximate quantile aggregator for groupby. Accepts as an argument, one or more of a list of quantiles to query. For instance: To extract the median >>> sf.groupby("user", ... {'rating_quantiles':tc.aggregate.QUANTILE('rating', 0.5)}) To extract a few quantiles >>> sf.groupby("user", ... {'rating_quantiles':tc.aggregate.QUANTILE('rating', [0.25,0.5,0.75])}) Or equivalently >>> sf.groupby("user", ... {'rating_quantiles':tc.aggregate.QUANTILE('rating', 0.25,0.5,0.75)}) The returned quantiles are guaranteed to have 0.5% accuracy. That is to say, if the requested quantile is 0.50, the resultant quantile value may be between 0.495 and 0.505 of the true quantile. """ if len(args) == 1: quantiles = args[0] else: quantiles = list(args) if not _is_non_string_iterable(quantiles): quantiles = [quantiles] query = ",".join([str(i) for i in quantiles]) return ("__builtin__quantile__[" + query + "]", [src_column])
python
def QUANTILE(src_column, *args): """ Builtin approximate quantile aggregator for groupby. Accepts as an argument, one or more of a list of quantiles to query. For instance: To extract the median >>> sf.groupby("user", ... {'rating_quantiles':tc.aggregate.QUANTILE('rating', 0.5)}) To extract a few quantiles >>> sf.groupby("user", ... {'rating_quantiles':tc.aggregate.QUANTILE('rating', [0.25,0.5,0.75])}) Or equivalently >>> sf.groupby("user", ... {'rating_quantiles':tc.aggregate.QUANTILE('rating', 0.25,0.5,0.75)}) The returned quantiles are guaranteed to have 0.5% accuracy. That is to say, if the requested quantile is 0.50, the resultant quantile value may be between 0.495 and 0.505 of the true quantile. """ if len(args) == 1: quantiles = args[0] else: quantiles = list(args) if not _is_non_string_iterable(quantiles): quantiles = [quantiles] query = ",".join([str(i) for i in quantiles]) return ("__builtin__quantile__[" + query + "]", [src_column])
[ "def", "QUANTILE", "(", "src_column", ",", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "quantiles", "=", "args", "[", "0", "]", "else", ":", "quantiles", "=", "list", "(", "args", ")", "if", "not", "_is_non_string_iterable", "(", "quantiles", ")", ":", "quantiles", "=", "[", "quantiles", "]", "query", "=", "\",\"", ".", "join", "(", "[", "str", "(", "i", ")", "for", "i", "in", "quantiles", "]", ")", "return", "(", "\"__builtin__quantile__[\"", "+", "query", "+", "\"]\"", ",", "[", "src_column", "]", ")" ]
Builtin approximate quantile aggregator for groupby. Accepts as an argument, one or more of a list of quantiles to query. For instance: To extract the median >>> sf.groupby("user", ... {'rating_quantiles':tc.aggregate.QUANTILE('rating', 0.5)}) To extract a few quantiles >>> sf.groupby("user", ... {'rating_quantiles':tc.aggregate.QUANTILE('rating', [0.25,0.5,0.75])}) Or equivalently >>> sf.groupby("user", ... {'rating_quantiles':tc.aggregate.QUANTILE('rating', 0.25,0.5,0.75)}) The returned quantiles are guaranteed to have 0.5% accuracy. That is to say, if the requested quantile is 0.50, the resultant quantile value may be between 0.495 and 0.505 of the true quantile.
[ "Builtin", "approximate", "quantile", "aggregator", "for", "groupby", ".", "Accepts", "as", "an", "argument", "one", "or", "more", "of", "a", "list", "of", "quantiles", "to", "query", ".", "For", "instance", ":" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/aggregate.py#L226-L259
train
apple/turicreate
src/unity/python/turicreate/toolkits/graph_analytics/kcore.py
create
def create(graph, kmin=0, kmax=10, verbose=True): """ Compute the K-core decomposition of the graph. Return a model object with total number of cores as well as the core id for each vertex in the graph. Parameters ---------- graph : SGraph The graph on which to compute the k-core decomposition. kmin : int, optional Minimum core id. Vertices having smaller core id than `kmin` will be assigned with core_id = `kmin`. kmax : int, optional Maximum core id. Vertices having larger core id than `kmax` will be assigned with core_id=`kmax`. verbose : bool, optional If True, print progress updates. Returns ------- out : KcoreModel References ---------- - Alvarez-Hamelin, J.I., et al. (2005) `K-Core Decomposition: A Tool for the Visualization of Large Networks <http://arxiv.org/abs/cs/0504107>`_. Examples -------- If given an :class:`~turicreate.SGraph` ``g``, we can create a :class:`~turicreate.kcore.KcoreModel` as follows: >>> g = turicreate.load_sgraph('http://snap.stanford.edu/data/email-Enron.txt.gz', format='snap') >>> kc = turicreate.kcore.create(g) We can obtain the ``core id`` corresponding to each vertex in the graph ``g`` using: >>> kcore_id = kc['core_id'] # SFrame We can add the new core id field to the original graph g using: >>> g.vertices['core_id'] = kc['graph'].vertices['core_id'] Note that the task above does not require a join because the vertex ordering is preserved through ``create()``. See Also -------- KcoreModel """ from turicreate._cython.cy_server import QuietProgress if not isinstance(graph, _SGraph): raise TypeError('graph input must be a SGraph object.') opts = {'graph': graph.__proxy__, 'kmin': kmin, 'kmax': kmax} with QuietProgress(verbose): params = _tc.extensions._toolkits.graph.kcore.create(opts) return KcoreModel(params['model'])
python
def create(graph, kmin=0, kmax=10, verbose=True): """ Compute the K-core decomposition of the graph. Return a model object with total number of cores as well as the core id for each vertex in the graph. Parameters ---------- graph : SGraph The graph on which to compute the k-core decomposition. kmin : int, optional Minimum core id. Vertices having smaller core id than `kmin` will be assigned with core_id = `kmin`. kmax : int, optional Maximum core id. Vertices having larger core id than `kmax` will be assigned with core_id=`kmax`. verbose : bool, optional If True, print progress updates. Returns ------- out : KcoreModel References ---------- - Alvarez-Hamelin, J.I., et al. (2005) `K-Core Decomposition: A Tool for the Visualization of Large Networks <http://arxiv.org/abs/cs/0504107>`_. Examples -------- If given an :class:`~turicreate.SGraph` ``g``, we can create a :class:`~turicreate.kcore.KcoreModel` as follows: >>> g = turicreate.load_sgraph('http://snap.stanford.edu/data/email-Enron.txt.gz', format='snap') >>> kc = turicreate.kcore.create(g) We can obtain the ``core id`` corresponding to each vertex in the graph ``g`` using: >>> kcore_id = kc['core_id'] # SFrame We can add the new core id field to the original graph g using: >>> g.vertices['core_id'] = kc['graph'].vertices['core_id'] Note that the task above does not require a join because the vertex ordering is preserved through ``create()``. See Also -------- KcoreModel """ from turicreate._cython.cy_server import QuietProgress if not isinstance(graph, _SGraph): raise TypeError('graph input must be a SGraph object.') opts = {'graph': graph.__proxy__, 'kmin': kmin, 'kmax': kmax} with QuietProgress(verbose): params = _tc.extensions._toolkits.graph.kcore.create(opts) return KcoreModel(params['model'])
[ "def", "create", "(", "graph", ",", "kmin", "=", "0", ",", "kmax", "=", "10", ",", "verbose", "=", "True", ")", ":", "from", "turicreate", ".", "_cython", ".", "cy_server", "import", "QuietProgress", "if", "not", "isinstance", "(", "graph", ",", "_SGraph", ")", ":", "raise", "TypeError", "(", "'graph input must be a SGraph object.'", ")", "opts", "=", "{", "'graph'", ":", "graph", ".", "__proxy__", ",", "'kmin'", ":", "kmin", ",", "'kmax'", ":", "kmax", "}", "with", "QuietProgress", "(", "verbose", ")", ":", "params", "=", "_tc", ".", "extensions", ".", "_toolkits", ".", "graph", ".", "kcore", ".", "create", "(", "opts", ")", "return", "KcoreModel", "(", "params", "[", "'model'", "]", ")" ]
Compute the K-core decomposition of the graph. Return a model object with total number of cores as well as the core id for each vertex in the graph. Parameters ---------- graph : SGraph The graph on which to compute the k-core decomposition. kmin : int, optional Minimum core id. Vertices having smaller core id than `kmin` will be assigned with core_id = `kmin`. kmax : int, optional Maximum core id. Vertices having larger core id than `kmax` will be assigned with core_id=`kmax`. verbose : bool, optional If True, print progress updates. Returns ------- out : KcoreModel References ---------- - Alvarez-Hamelin, J.I., et al. (2005) `K-Core Decomposition: A Tool for the Visualization of Large Networks <http://arxiv.org/abs/cs/0504107>`_. Examples -------- If given an :class:`~turicreate.SGraph` ``g``, we can create a :class:`~turicreate.kcore.KcoreModel` as follows: >>> g = turicreate.load_sgraph('http://snap.stanford.edu/data/email-Enron.txt.gz', format='snap') >>> kc = turicreate.kcore.create(g) We can obtain the ``core id`` corresponding to each vertex in the graph ``g`` using: >>> kcore_id = kc['core_id'] # SFrame We can add the new core id field to the original graph g using: >>> g.vertices['core_id'] = kc['graph'].vertices['core_id'] Note that the task above does not require a join because the vertex ordering is preserved through ``create()``. See Also -------- KcoreModel
[ "Compute", "the", "K", "-", "core", "decomposition", "of", "the", "graph", ".", "Return", "a", "model", "object", "with", "total", "number", "of", "cores", "as", "well", "as", "the", "core", "id", "for", "each", "vertex", "in", "the", "graph", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/graph_analytics/kcore.py#L86-L150
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_utils.py
raise_error_unsupported_categorical_option
def raise_error_unsupported_categorical_option(option_name, option_value, layer_type, layer_name): """ Raise an error if an option is not supported. """ raise RuntimeError("Unsupported option %s=%s in layer %s(%s)" % (option_name, option_value, layer_type, layer_name))
python
def raise_error_unsupported_categorical_option(option_name, option_value, layer_type, layer_name): """ Raise an error if an option is not supported. """ raise RuntimeError("Unsupported option %s=%s in layer %s(%s)" % (option_name, option_value, layer_type, layer_name))
[ "def", "raise_error_unsupported_categorical_option", "(", "option_name", ",", "option_value", ",", "layer_type", ",", "layer_name", ")", ":", "raise", "RuntimeError", "(", "\"Unsupported option %s=%s in layer %s(%s)\"", "%", "(", "option_name", ",", "option_value", ",", "layer_type", ",", "layer_name", ")", ")" ]
Raise an error if an option is not supported.
[ "Raise", "an", "error", "if", "an", "option", "is", "not", "supported", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_utils.py#L7-L12
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/models/_feature_management.py
process_or_validate_classifier_output_features
def process_or_validate_classifier_output_features( output_features, class_labels, supports_class_scores = True): """ Given a list of class labels and a list of output_features, validate the list and return a valid version of output_features with all the correct data type information included. """ def raise_error(msg): raise ValueError("Classifier error: %s" % msg) class_labels = list(class_labels) # First, we need to determine the type of the classes. _int_types = _integer_types + (bool, _np.bool_, _np.int32, _np.int64) if all(isinstance(cl, _int_types) for cl in class_labels): output_class_type = datatypes.Int64() elif all(isinstance(cl, _string_types) for cl in class_labels): output_class_type = datatypes.String() else: raise ValueError('Class labels must be all of type int or all of type string.') if output_features is None: out = [("classLabel", output_class_type)] if supports_class_scores: out += [("classProbability", datatypes.Dictionary(output_class_type))] elif isinstance(output_features, _string_types): out = [(output_features, output_class_type)] if supports_class_scores: out += [("classProbability", datatypes.Dictionary(output_class_type))] elif (isinstance(output_features, (list, tuple)) and all(isinstance(fn, _string_types) for fn in output_features) and len(output_features) == 2): if supports_class_scores: out = [(output_features[0], output_class_type), (output_features[1], datatypes.Dictionary(output_class_type))] else: raise ValueError("Classifier model (as trained) does not support output scores for classes.") elif is_valid_feature_list(output_features): output_features = [(k, datatypes._normalize_datatype(dt)) for k, dt in output_features] if len(output_features) == 1 or not supports_class_scores: if not output_features[0][1] == output_class_type: raise ValueError("Type of output class feature does not match type of class labels.") else: # Make sure the first two output features specified give the output # class field and the output class scores dictionary field if (isinstance(output_features[0][1], datatypes.Dictionary) and isinstance(output_features[1][1], output_class_type)): output_features[0], output_features[1] = output_features[1], output_features[0] if not isinstance(output_features[1][1], datatypes.Dictionary): raise_error("Output features class scores should be dictionary type.") if output_features[1][1].key_type != output_class_type: raise_error("Class scores dictionary key type does not match type of class labels.") if output_features[0][1] != output_class_type: raise_error("Specified type of output class does not match type of class labels.") # NOTE: We are intentionally allowing the case where additional fields are allowed # beyond the original two features. out = output_features else: raise_error("Form of output features not recognized") return out
python
def process_or_validate_classifier_output_features( output_features, class_labels, supports_class_scores = True): """ Given a list of class labels and a list of output_features, validate the list and return a valid version of output_features with all the correct data type information included. """ def raise_error(msg): raise ValueError("Classifier error: %s" % msg) class_labels = list(class_labels) # First, we need to determine the type of the classes. _int_types = _integer_types + (bool, _np.bool_, _np.int32, _np.int64) if all(isinstance(cl, _int_types) for cl in class_labels): output_class_type = datatypes.Int64() elif all(isinstance(cl, _string_types) for cl in class_labels): output_class_type = datatypes.String() else: raise ValueError('Class labels must be all of type int or all of type string.') if output_features is None: out = [("classLabel", output_class_type)] if supports_class_scores: out += [("classProbability", datatypes.Dictionary(output_class_type))] elif isinstance(output_features, _string_types): out = [(output_features, output_class_type)] if supports_class_scores: out += [("classProbability", datatypes.Dictionary(output_class_type))] elif (isinstance(output_features, (list, tuple)) and all(isinstance(fn, _string_types) for fn in output_features) and len(output_features) == 2): if supports_class_scores: out = [(output_features[0], output_class_type), (output_features[1], datatypes.Dictionary(output_class_type))] else: raise ValueError("Classifier model (as trained) does not support output scores for classes.") elif is_valid_feature_list(output_features): output_features = [(k, datatypes._normalize_datatype(dt)) for k, dt in output_features] if len(output_features) == 1 or not supports_class_scores: if not output_features[0][1] == output_class_type: raise ValueError("Type of output class feature does not match type of class labels.") else: # Make sure the first two output features specified give the output # class field and the output class scores dictionary field if (isinstance(output_features[0][1], datatypes.Dictionary) and isinstance(output_features[1][1], output_class_type)): output_features[0], output_features[1] = output_features[1], output_features[0] if not isinstance(output_features[1][1], datatypes.Dictionary): raise_error("Output features class scores should be dictionary type.") if output_features[1][1].key_type != output_class_type: raise_error("Class scores dictionary key type does not match type of class labels.") if output_features[0][1] != output_class_type: raise_error("Specified type of output class does not match type of class labels.") # NOTE: We are intentionally allowing the case where additional fields are allowed # beyond the original two features. out = output_features else: raise_error("Form of output features not recognized") return out
[ "def", "process_or_validate_classifier_output_features", "(", "output_features", ",", "class_labels", ",", "supports_class_scores", "=", "True", ")", ":", "def", "raise_error", "(", "msg", ")", ":", "raise", "ValueError", "(", "\"Classifier error: %s\"", "%", "msg", ")", "class_labels", "=", "list", "(", "class_labels", ")", "# First, we need to determine the type of the classes.", "_int_types", "=", "_integer_types", "+", "(", "bool", ",", "_np", ".", "bool_", ",", "_np", ".", "int32", ",", "_np", ".", "int64", ")", "if", "all", "(", "isinstance", "(", "cl", ",", "_int_types", ")", "for", "cl", "in", "class_labels", ")", ":", "output_class_type", "=", "datatypes", ".", "Int64", "(", ")", "elif", "all", "(", "isinstance", "(", "cl", ",", "_string_types", ")", "for", "cl", "in", "class_labels", ")", ":", "output_class_type", "=", "datatypes", ".", "String", "(", ")", "else", ":", "raise", "ValueError", "(", "'Class labels must be all of type int or all of type string.'", ")", "if", "output_features", "is", "None", ":", "out", "=", "[", "(", "\"classLabel\"", ",", "output_class_type", ")", "]", "if", "supports_class_scores", ":", "out", "+=", "[", "(", "\"classProbability\"", ",", "datatypes", ".", "Dictionary", "(", "output_class_type", ")", ")", "]", "elif", "isinstance", "(", "output_features", ",", "_string_types", ")", ":", "out", "=", "[", "(", "output_features", ",", "output_class_type", ")", "]", "if", "supports_class_scores", ":", "out", "+=", "[", "(", "\"classProbability\"", ",", "datatypes", ".", "Dictionary", "(", "output_class_type", ")", ")", "]", "elif", "(", "isinstance", "(", "output_features", ",", "(", "list", ",", "tuple", ")", ")", "and", "all", "(", "isinstance", "(", "fn", ",", "_string_types", ")", "for", "fn", "in", "output_features", ")", "and", "len", "(", "output_features", ")", "==", "2", ")", ":", "if", "supports_class_scores", ":", "out", "=", "[", "(", "output_features", "[", "0", "]", ",", "output_class_type", ")", ",", "(", "output_features", "[", "1", "]", ",", "datatypes", ".", "Dictionary", "(", "output_class_type", ")", ")", "]", "else", ":", "raise", "ValueError", "(", "\"Classifier model (as trained) does not support output scores for classes.\"", ")", "elif", "is_valid_feature_list", "(", "output_features", ")", ":", "output_features", "=", "[", "(", "k", ",", "datatypes", ".", "_normalize_datatype", "(", "dt", ")", ")", "for", "k", ",", "dt", "in", "output_features", "]", "if", "len", "(", "output_features", ")", "==", "1", "or", "not", "supports_class_scores", ":", "if", "not", "output_features", "[", "0", "]", "[", "1", "]", "==", "output_class_type", ":", "raise", "ValueError", "(", "\"Type of output class feature does not match type of class labels.\"", ")", "else", ":", "# Make sure the first two output features specified give the output", "# class field and the output class scores dictionary field", "if", "(", "isinstance", "(", "output_features", "[", "0", "]", "[", "1", "]", ",", "datatypes", ".", "Dictionary", ")", "and", "isinstance", "(", "output_features", "[", "1", "]", "[", "1", "]", ",", "output_class_type", ")", ")", ":", "output_features", "[", "0", "]", ",", "output_features", "[", "1", "]", "=", "output_features", "[", "1", "]", ",", "output_features", "[", "0", "]", "if", "not", "isinstance", "(", "output_features", "[", "1", "]", "[", "1", "]", ",", "datatypes", ".", "Dictionary", ")", ":", "raise_error", "(", "\"Output features class scores should be dictionary type.\"", ")", "if", "output_features", "[", "1", "]", "[", "1", "]", ".", "key_type", "!=", "output_class_type", ":", "raise_error", "(", "\"Class scores dictionary key type does not match type of class labels.\"", ")", "if", "output_features", "[", "0", "]", "[", "1", "]", "!=", "output_class_type", ":", "raise_error", "(", "\"Specified type of output class does not match type of class labels.\"", ")", "# NOTE: We are intentionally allowing the case where additional fields are allowed", "# beyond the original two features.", "out", "=", "output_features", "else", ":", "raise_error", "(", "\"Form of output features not recognized\"", ")", "return", "out" ]
Given a list of class labels and a list of output_features, validate the list and return a valid version of output_features with all the correct data type information included.
[ "Given", "a", "list", "of", "class", "labels", "and", "a", "list", "of", "output_features", "validate", "the", "list", "and", "return", "a", "valid", "version", "of", "output_features", "with", "all", "the", "correct", "data", "type", "information", "included", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/_feature_management.py#L19-L103
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/models/_feature_management.py
process_or_validate_features
def process_or_validate_features(features, num_dimensions = None, feature_type_map = {}): """ Puts features into a standard form from a number of different possible forms. The standard form is a list of 2-tuples of (name, datatype) pairs. The name is a string and the datatype is an object as defined in the _datatype module. The possible input forms are as follows: * A list of strings. in this case, the overall dimension is assumed to be the length of the list. If neighboring names are identical, they are assumed to be an input array of that length. For example: ["a", "b", "c"] resolves to [("a", Double), ("b", Double), ("c", Double)]. And: ["a", "a", "b"] resolves to [("a", Array(2)), ("b", Double)]. * A dictionary of keys to indices or ranges of feature indices. In this case, it's presented as a mapping from keys to indices or ranges of contiguous indices. For example, {"a" : 0, "b" : [2,3], "c" : 1} Resolves to [("a", Double), ("c", Double), ("b", Array(2))]. Note that the ordering is determined by the indices. * A single string. In this case, the input is assumed to be a single array, with the number of dimensions set using num_dimensions. Notes: If the features variable is in the standard form, it is simply checked and returned. If num_dimensions is given, it is used to check against the existing features, or fill in missing information in the case when features is a single string. """ original_features = copy(features) if num_dimensions is not None and not isinstance(num_dimensions, _integer_types): raise TypeError("num_dimensions must be None, an integer or a long, not '%s'" % str(type(num_dimensions))) def raise_type_error(additional_msg): raise TypeError("Error processing feature list: %s\nfeatures = %s" % (additional_msg, str(original_features))) if type(features) is dict and is_valid_feature_list(features.items()): features = features.items() # First, see if the features are already in the correct form. If they are, # then we if is_valid_feature_list(features): if num_dimensions is not None: try: feature_dims = dimension_of_array_features(features) except ValueError: feature_dims = None if feature_dims is not None and feature_dims != num_dimensions: raise_type_error("Dimension mismatch.") # We may need to translate some parts of this back to the actual # datatype class -- e.g. translate str to datatypes.String(). return [(k, datatypes._normalize_datatype(dt)) for k, dt in features] if isinstance(features, _string_types): if num_dimensions is None: raise_type_error("If a single feature name is given, then " "num_dimensions must be provided.") features = {features : range(num_dimensions)} if isinstance(features, (list, tuple, _np.ndarray)): # Change this into a dictionary mapping = defaultdict(lambda: []) for i, k in enumerate(features): if not isinstance(k, _string_types): raise_type_error("List of feature names must be list of strings.") if num_dimensions is not None and len(features) != num_dimensions: raise_type_error(("List of feature names has wrong length; " "%d required, %d provided.") % (num_dimensions, len(features))) for i, k in enumerate(features): mapping[k].append(i) # Replace the features features = mapping if not isinstance(features, dict): raise_type_error("features must be either a list of feature names " "or a dictionary of feature names to ranges.") # We'll be invasive here so make a copy. features = copy(features) for k, v in list(features.items()): if not isinstance(k, str): raise_type_error("Feature names must be strings.") def test_index(val): error = False try: if val != int(val): error = True except: error = True if error: raise_type_error("Specified indices for feature %s must be integers." % k) if val < 0 or (num_dimensions is not None and val >= num_dimensions): raise_type_error("Index in feature %s out of range." % k) iterable_types = [tuple, list, set] if _PY3: iterable_types.append(range) else: iterable_types.append(xrange) if isinstance(v, tuple(iterable_types)): for idx in v: test_index(idx) # Replace and update features[k] = v = list(sorted(v)) elif isinstance(v, (int, long)): test_index(v) features[k] = v = [v] else: raise_type_error(("Value type for feature %s not recognized; " "values must be either integers, lists or range objects.") % k) # check to make sure things are contiguous if v != list(range(v[0], v[-1] + 1)): raise_type_error("Index list for feature %s must consist of " "a contiguous range of indices." % k) if len(set(v)) != len(v): raise_type_error("Index list for feature %s contains duplicates." % k) # Now, set num dimensions from the list if it's actually None if num_dimensions is None: from itertools import chain num_dimensions = 1 + max(chain(*[il for k, il in features.items()])) if (set().union(*features.values()) != set(range(num_dimensions)) or sum(len(v) for v in features.values()) != num_dimensions): raise_type_error("Supplied indices must cover entire range of 0, ..., num_dimensions-1.") # Define the output feature types output_features = [None]*len(features) # Finally, go through and map all these things out as types. # Sort by first value of the index range. for i, (k, v) in enumerate(sorted(features.items(), key = lambda t: t[1][0])): if k in feature_type_map: output_features[i] = (k, feature_type_map[k]) elif len(v) == 1: output_features[i] = (k, datatypes.Double()) else: output_features[i] = (k, datatypes.Array(len(v))) return output_features
python
def process_or_validate_features(features, num_dimensions = None, feature_type_map = {}): """ Puts features into a standard form from a number of different possible forms. The standard form is a list of 2-tuples of (name, datatype) pairs. The name is a string and the datatype is an object as defined in the _datatype module. The possible input forms are as follows: * A list of strings. in this case, the overall dimension is assumed to be the length of the list. If neighboring names are identical, they are assumed to be an input array of that length. For example: ["a", "b", "c"] resolves to [("a", Double), ("b", Double), ("c", Double)]. And: ["a", "a", "b"] resolves to [("a", Array(2)), ("b", Double)]. * A dictionary of keys to indices or ranges of feature indices. In this case, it's presented as a mapping from keys to indices or ranges of contiguous indices. For example, {"a" : 0, "b" : [2,3], "c" : 1} Resolves to [("a", Double), ("c", Double), ("b", Array(2))]. Note that the ordering is determined by the indices. * A single string. In this case, the input is assumed to be a single array, with the number of dimensions set using num_dimensions. Notes: If the features variable is in the standard form, it is simply checked and returned. If num_dimensions is given, it is used to check against the existing features, or fill in missing information in the case when features is a single string. """ original_features = copy(features) if num_dimensions is not None and not isinstance(num_dimensions, _integer_types): raise TypeError("num_dimensions must be None, an integer or a long, not '%s'" % str(type(num_dimensions))) def raise_type_error(additional_msg): raise TypeError("Error processing feature list: %s\nfeatures = %s" % (additional_msg, str(original_features))) if type(features) is dict and is_valid_feature_list(features.items()): features = features.items() # First, see if the features are already in the correct form. If they are, # then we if is_valid_feature_list(features): if num_dimensions is not None: try: feature_dims = dimension_of_array_features(features) except ValueError: feature_dims = None if feature_dims is not None and feature_dims != num_dimensions: raise_type_error("Dimension mismatch.") # We may need to translate some parts of this back to the actual # datatype class -- e.g. translate str to datatypes.String(). return [(k, datatypes._normalize_datatype(dt)) for k, dt in features] if isinstance(features, _string_types): if num_dimensions is None: raise_type_error("If a single feature name is given, then " "num_dimensions must be provided.") features = {features : range(num_dimensions)} if isinstance(features, (list, tuple, _np.ndarray)): # Change this into a dictionary mapping = defaultdict(lambda: []) for i, k in enumerate(features): if not isinstance(k, _string_types): raise_type_error("List of feature names must be list of strings.") if num_dimensions is not None and len(features) != num_dimensions: raise_type_error(("List of feature names has wrong length; " "%d required, %d provided.") % (num_dimensions, len(features))) for i, k in enumerate(features): mapping[k].append(i) # Replace the features features = mapping if not isinstance(features, dict): raise_type_error("features must be either a list of feature names " "or a dictionary of feature names to ranges.") # We'll be invasive here so make a copy. features = copy(features) for k, v in list(features.items()): if not isinstance(k, str): raise_type_error("Feature names must be strings.") def test_index(val): error = False try: if val != int(val): error = True except: error = True if error: raise_type_error("Specified indices for feature %s must be integers." % k) if val < 0 or (num_dimensions is not None and val >= num_dimensions): raise_type_error("Index in feature %s out of range." % k) iterable_types = [tuple, list, set] if _PY3: iterable_types.append(range) else: iterable_types.append(xrange) if isinstance(v, tuple(iterable_types)): for idx in v: test_index(idx) # Replace and update features[k] = v = list(sorted(v)) elif isinstance(v, (int, long)): test_index(v) features[k] = v = [v] else: raise_type_error(("Value type for feature %s not recognized; " "values must be either integers, lists or range objects.") % k) # check to make sure things are contiguous if v != list(range(v[0], v[-1] + 1)): raise_type_error("Index list for feature %s must consist of " "a contiguous range of indices." % k) if len(set(v)) != len(v): raise_type_error("Index list for feature %s contains duplicates." % k) # Now, set num dimensions from the list if it's actually None if num_dimensions is None: from itertools import chain num_dimensions = 1 + max(chain(*[il for k, il in features.items()])) if (set().union(*features.values()) != set(range(num_dimensions)) or sum(len(v) for v in features.values()) != num_dimensions): raise_type_error("Supplied indices must cover entire range of 0, ..., num_dimensions-1.") # Define the output feature types output_features = [None]*len(features) # Finally, go through and map all these things out as types. # Sort by first value of the index range. for i, (k, v) in enumerate(sorted(features.items(), key = lambda t: t[1][0])): if k in feature_type_map: output_features[i] = (k, feature_type_map[k]) elif len(v) == 1: output_features[i] = (k, datatypes.Double()) else: output_features[i] = (k, datatypes.Array(len(v))) return output_features
[ "def", "process_or_validate_features", "(", "features", ",", "num_dimensions", "=", "None", ",", "feature_type_map", "=", "{", "}", ")", ":", "original_features", "=", "copy", "(", "features", ")", "if", "num_dimensions", "is", "not", "None", "and", "not", "isinstance", "(", "num_dimensions", ",", "_integer_types", ")", ":", "raise", "TypeError", "(", "\"num_dimensions must be None, an integer or a long, not '%s'\"", "%", "str", "(", "type", "(", "num_dimensions", ")", ")", ")", "def", "raise_type_error", "(", "additional_msg", ")", ":", "raise", "TypeError", "(", "\"Error processing feature list: %s\\nfeatures = %s\"", "%", "(", "additional_msg", ",", "str", "(", "original_features", ")", ")", ")", "if", "type", "(", "features", ")", "is", "dict", "and", "is_valid_feature_list", "(", "features", ".", "items", "(", ")", ")", ":", "features", "=", "features", ".", "items", "(", ")", "# First, see if the features are already in the correct form. If they are,", "# then we", "if", "is_valid_feature_list", "(", "features", ")", ":", "if", "num_dimensions", "is", "not", "None", ":", "try", ":", "feature_dims", "=", "dimension_of_array_features", "(", "features", ")", "except", "ValueError", ":", "feature_dims", "=", "None", "if", "feature_dims", "is", "not", "None", "and", "feature_dims", "!=", "num_dimensions", ":", "raise_type_error", "(", "\"Dimension mismatch.\"", ")", "# We may need to translate some parts of this back to the actual", "# datatype class -- e.g. translate str to datatypes.String().", "return", "[", "(", "k", ",", "datatypes", ".", "_normalize_datatype", "(", "dt", ")", ")", "for", "k", ",", "dt", "in", "features", "]", "if", "isinstance", "(", "features", ",", "_string_types", ")", ":", "if", "num_dimensions", "is", "None", ":", "raise_type_error", "(", "\"If a single feature name is given, then \"", "\"num_dimensions must be provided.\"", ")", "features", "=", "{", "features", ":", "range", "(", "num_dimensions", ")", "}", "if", "isinstance", "(", "features", ",", "(", "list", ",", "tuple", ",", "_np", ".", "ndarray", ")", ")", ":", "# Change this into a dictionary", "mapping", "=", "defaultdict", "(", "lambda", ":", "[", "]", ")", "for", "i", ",", "k", "in", "enumerate", "(", "features", ")", ":", "if", "not", "isinstance", "(", "k", ",", "_string_types", ")", ":", "raise_type_error", "(", "\"List of feature names must be list of strings.\"", ")", "if", "num_dimensions", "is", "not", "None", "and", "len", "(", "features", ")", "!=", "num_dimensions", ":", "raise_type_error", "(", "(", "\"List of feature names has wrong length; \"", "\"%d required, %d provided.\"", ")", "%", "(", "num_dimensions", ",", "len", "(", "features", ")", ")", ")", "for", "i", ",", "k", "in", "enumerate", "(", "features", ")", ":", "mapping", "[", "k", "]", ".", "append", "(", "i", ")", "# Replace the features", "features", "=", "mapping", "if", "not", "isinstance", "(", "features", ",", "dict", ")", ":", "raise_type_error", "(", "\"features must be either a list of feature names \"", "\"or a dictionary of feature names to ranges.\"", ")", "# We'll be invasive here so make a copy.", "features", "=", "copy", "(", "features", ")", "for", "k", ",", "v", "in", "list", "(", "features", ".", "items", "(", ")", ")", ":", "if", "not", "isinstance", "(", "k", ",", "str", ")", ":", "raise_type_error", "(", "\"Feature names must be strings.\"", ")", "def", "test_index", "(", "val", ")", ":", "error", "=", "False", "try", ":", "if", "val", "!=", "int", "(", "val", ")", ":", "error", "=", "True", "except", ":", "error", "=", "True", "if", "error", ":", "raise_type_error", "(", "\"Specified indices for feature %s must be integers.\"", "%", "k", ")", "if", "val", "<", "0", "or", "(", "num_dimensions", "is", "not", "None", "and", "val", ">=", "num_dimensions", ")", ":", "raise_type_error", "(", "\"Index in feature %s out of range.\"", "%", "k", ")", "iterable_types", "=", "[", "tuple", ",", "list", ",", "set", "]", "if", "_PY3", ":", "iterable_types", ".", "append", "(", "range", ")", "else", ":", "iterable_types", ".", "append", "(", "xrange", ")", "if", "isinstance", "(", "v", ",", "tuple", "(", "iterable_types", ")", ")", ":", "for", "idx", "in", "v", ":", "test_index", "(", "idx", ")", "# Replace and update", "features", "[", "k", "]", "=", "v", "=", "list", "(", "sorted", "(", "v", ")", ")", "elif", "isinstance", "(", "v", ",", "(", "int", ",", "long", ")", ")", ":", "test_index", "(", "v", ")", "features", "[", "k", "]", "=", "v", "=", "[", "v", "]", "else", ":", "raise_type_error", "(", "(", "\"Value type for feature %s not recognized; \"", "\"values must be either integers, lists or range objects.\"", ")", "%", "k", ")", "# check to make sure things are contiguous", "if", "v", "!=", "list", "(", "range", "(", "v", "[", "0", "]", ",", "v", "[", "-", "1", "]", "+", "1", ")", ")", ":", "raise_type_error", "(", "\"Index list for feature %s must consist of \"", "\"a contiguous range of indices.\"", "%", "k", ")", "if", "len", "(", "set", "(", "v", ")", ")", "!=", "len", "(", "v", ")", ":", "raise_type_error", "(", "\"Index list for feature %s contains duplicates.\"", "%", "k", ")", "# Now, set num dimensions from the list if it's actually None", "if", "num_dimensions", "is", "None", ":", "from", "itertools", "import", "chain", "num_dimensions", "=", "1", "+", "max", "(", "chain", "(", "*", "[", "il", "for", "k", ",", "il", "in", "features", ".", "items", "(", ")", "]", ")", ")", "if", "(", "set", "(", ")", ".", "union", "(", "*", "features", ".", "values", "(", ")", ")", "!=", "set", "(", "range", "(", "num_dimensions", ")", ")", "or", "sum", "(", "len", "(", "v", ")", "for", "v", "in", "features", ".", "values", "(", ")", ")", "!=", "num_dimensions", ")", ":", "raise_type_error", "(", "\"Supplied indices must cover entire range of 0, ..., num_dimensions-1.\"", ")", "# Define the output feature types", "output_features", "=", "[", "None", "]", "*", "len", "(", "features", ")", "# Finally, go through and map all these things out as types.", "# Sort by first value of the index range.", "for", "i", ",", "(", "k", ",", "v", ")", "in", "enumerate", "(", "sorted", "(", "features", ".", "items", "(", ")", ",", "key", "=", "lambda", "t", ":", "t", "[", "1", "]", "[", "0", "]", ")", ")", ":", "if", "k", "in", "feature_type_map", ":", "output_features", "[", "i", "]", "=", "(", "k", ",", "feature_type_map", "[", "k", "]", ")", "elif", "len", "(", "v", ")", "==", "1", ":", "output_features", "[", "i", "]", "=", "(", "k", ",", "datatypes", ".", "Double", "(", ")", ")", "else", ":", "output_features", "[", "i", "]", "=", "(", "k", ",", "datatypes", ".", "Array", "(", "len", "(", "v", ")", ")", ")", "return", "output_features" ]
Puts features into a standard form from a number of different possible forms. The standard form is a list of 2-tuples of (name, datatype) pairs. The name is a string and the datatype is an object as defined in the _datatype module. The possible input forms are as follows: * A list of strings. in this case, the overall dimension is assumed to be the length of the list. If neighboring names are identical, they are assumed to be an input array of that length. For example: ["a", "b", "c"] resolves to [("a", Double), ("b", Double), ("c", Double)]. And: ["a", "a", "b"] resolves to [("a", Array(2)), ("b", Double)]. * A dictionary of keys to indices or ranges of feature indices. In this case, it's presented as a mapping from keys to indices or ranges of contiguous indices. For example, {"a" : 0, "b" : [2,3], "c" : 1} Resolves to [("a", Double), ("c", Double), ("b", Array(2))]. Note that the ordering is determined by the indices. * A single string. In this case, the input is assumed to be a single array, with the number of dimensions set using num_dimensions. Notes: If the features variable is in the standard form, it is simply checked and returned. If num_dimensions is given, it is used to check against the existing features, or fill in missing information in the case when features is a single string.
[ "Puts", "features", "into", "a", "standard", "form", "from", "a", "number", "of", "different", "possible", "forms", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/_feature_management.py#L130-L317
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/kernel/bootstrap.py
bootstrap
def bootstrap(root_path): """Performs python-side bootstrapping of Boost.Build/Python. This function arranges for 'b2.whatever' package names to work, while also allowing to put python files alongside corresponding jam modules. """ m = imp.new_module("b2") # Note that: # 1. If __path__ is not list of strings, nothing will work # 2. root_path is already list of strings. m.__path__ = root_path sys.modules["b2"] = m import b2.build_system return b2.build_system.main()
python
def bootstrap(root_path): """Performs python-side bootstrapping of Boost.Build/Python. This function arranges for 'b2.whatever' package names to work, while also allowing to put python files alongside corresponding jam modules. """ m = imp.new_module("b2") # Note that: # 1. If __path__ is not list of strings, nothing will work # 2. root_path is already list of strings. m.__path__ = root_path sys.modules["b2"] = m import b2.build_system return b2.build_system.main()
[ "def", "bootstrap", "(", "root_path", ")", ":", "m", "=", "imp", ".", "new_module", "(", "\"b2\"", ")", "# Note that:", "# 1. If __path__ is not list of strings, nothing will work", "# 2. root_path is already list of strings.", "m", ".", "__path__", "=", "root_path", "sys", ".", "modules", "[", "\"b2\"", "]", "=", "m", "import", "b2", ".", "build_system", "return", "b2", ".", "build_system", ".", "main", "(", ")" ]
Performs python-side bootstrapping of Boost.Build/Python. This function arranges for 'b2.whatever' package names to work, while also allowing to put python files alongside corresponding jam modules.
[ "Performs", "python", "-", "side", "bootstrapping", "of", "Boost", ".", "Build", "/", "Python", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/kernel/bootstrap.py#L9-L24
train
apple/turicreate
deps/src/boost_1_68_0/libs/metaparse/tools/build_environment.py
main
def main(): """The main function of the utility""" parser = argparse.ArgumentParser( description='Manage the build environment of Boost.Metaparse' ) parser.add_argument( '--dep_json', required=True, help='The json file describing the dependencies' ) parser.add_argument( '--git', required=False, default='git', help='The git command to use' ) parser.add_argument( '--out', required=False, default='boost', help='The directory to clone into' ) parser.add_argument( '--action', required=True, choices=['update', 'checkout'], help='The action to do with the dependencies' ) parser.add_argument( '--boost_repository', required=False, default='https://github.com/boostorg/boost.git', help='The Boost repository to clone' ) parser.add_argument( '--ref', required=False, default='origin/master', help='The reference to set to in update' ) args = parser.parse_args() build_environment( args.dep_json, args.out, ChildProcess([args.git]), args.boost_repository, args.action, args.ref )
python
def main(): """The main function of the utility""" parser = argparse.ArgumentParser( description='Manage the build environment of Boost.Metaparse' ) parser.add_argument( '--dep_json', required=True, help='The json file describing the dependencies' ) parser.add_argument( '--git', required=False, default='git', help='The git command to use' ) parser.add_argument( '--out', required=False, default='boost', help='The directory to clone into' ) parser.add_argument( '--action', required=True, choices=['update', 'checkout'], help='The action to do with the dependencies' ) parser.add_argument( '--boost_repository', required=False, default='https://github.com/boostorg/boost.git', help='The Boost repository to clone' ) parser.add_argument( '--ref', required=False, default='origin/master', help='The reference to set to in update' ) args = parser.parse_args() build_environment( args.dep_json, args.out, ChildProcess([args.git]), args.boost_repository, args.action, args.ref )
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Manage the build environment of Boost.Metaparse'", ")", "parser", ".", "add_argument", "(", "'--dep_json'", ",", "required", "=", "True", ",", "help", "=", "'The json file describing the dependencies'", ")", "parser", ".", "add_argument", "(", "'--git'", ",", "required", "=", "False", ",", "default", "=", "'git'", ",", "help", "=", "'The git command to use'", ")", "parser", ".", "add_argument", "(", "'--out'", ",", "required", "=", "False", ",", "default", "=", "'boost'", ",", "help", "=", "'The directory to clone into'", ")", "parser", ".", "add_argument", "(", "'--action'", ",", "required", "=", "True", ",", "choices", "=", "[", "'update'", ",", "'checkout'", "]", ",", "help", "=", "'The action to do with the dependencies'", ")", "parser", ".", "add_argument", "(", "'--boost_repository'", ",", "required", "=", "False", ",", "default", "=", "'https://github.com/boostorg/boost.git'", ",", "help", "=", "'The Boost repository to clone'", ")", "parser", ".", "add_argument", "(", "'--ref'", ",", "required", "=", "False", ",", "default", "=", "'origin/master'", ",", "help", "=", "'The reference to set to in update'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "build_environment", "(", "args", ".", "dep_json", ",", "args", ".", "out", ",", "ChildProcess", "(", "[", "args", ".", "git", "]", ")", ",", "args", ".", "boost_repository", ",", "args", ".", "action", ",", "args", ".", "ref", ")" ]
The main function of the utility
[ "The", "main", "function", "of", "the", "utility" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/metaparse/tools/build_environment.py#L81-L130
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray_builder.py
SArrayBuilder.read_history
def read_history(self, num=10, segment=0): """ Outputs the last `num` elements that were appended either by `append` or `append_multiple`. Returns ------- out : list """ if num < 0: num = 0 if segment < 0: raise TypeError("segment must be >= 0") return self._builder.read_history(num, segment)
python
def read_history(self, num=10, segment=0): """ Outputs the last `num` elements that were appended either by `append` or `append_multiple`. Returns ------- out : list """ if num < 0: num = 0 if segment < 0: raise TypeError("segment must be >= 0") return self._builder.read_history(num, segment)
[ "def", "read_history", "(", "self", ",", "num", "=", "10", ",", "segment", "=", "0", ")", ":", "if", "num", "<", "0", ":", "num", "=", "0", "if", "segment", "<", "0", ":", "raise", "TypeError", "(", "\"segment must be >= 0\"", ")", "return", "self", ".", "_builder", ".", "read_history", "(", "num", ",", "segment", ")" ]
Outputs the last `num` elements that were appended either by `append` or `append_multiple`. Returns ------- out : list
[ "Outputs", "the", "last", "num", "elements", "that", "were", "appended", "either", "by", "append", "or", "append_multiple", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray_builder.py#L114-L128
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/toolset.py
flags
def flags(rule_or_module, variable_name, condition, values = []): """ Specifies the flags (variables) that must be set on targets under certain conditions, described by arguments. rule_or_module: If contains dot, should be a rule name. The flags will be applied when that rule is used to set up build actions. If does not contain dot, should be a module name. The flags will be applied for all rules in that module. If module for rule is different from the calling module, an error is issued. variable_name: Variable that should be set on target condition A condition when this flag should be applied. Should be set of property sets. If one of those property sets is contained in build properties, the flag will be used. Implied values are not allowed: "<toolset>gcc" should be used, not just "gcc". Subfeatures, like in "<toolset>gcc-3.2" are allowed. If left empty, the flag will always used. Propery sets may use value-less properties ('<a>' vs. '<a>value') to match absent properties. This allows to separately match <architecture>/<address-model>64 <architecture>ia64/<address-model> Where both features are optional. Without this syntax we'd be forced to define "default" value. values: The value to add to variable. If <feature> is specified, then the value of 'feature' will be added. """ assert isinstance(rule_or_module, basestring) assert isinstance(variable_name, basestring) assert is_iterable_typed(condition, basestring) assert is_iterable(values) and all(isinstance(v, (basestring, type(None))) for v in values) caller = bjam.caller() if not '.' in rule_or_module and caller and caller[:-1].startswith("Jamfile"): # Unqualified rule name, used inside Jamfile. Most likely used with # 'make' or 'notfile' rules. This prevents setting flags on the entire # Jamfile module (this will be considered as rule), but who cares? # Probably, 'flags' rule should be split into 'flags' and # 'flags-on-module'. rule_or_module = qualify_jam_action(rule_or_module, caller) else: # FIXME: revive checking that we don't set flags for a different # module unintentionally pass if condition and not replace_grist (condition, ''): # We have condition in the form '<feature>', that is, without # value. That's a previous syntax: # # flags gcc.link RPATH <dll-path> ; # for compatibility, convert it to # flags gcc.link RPATH : <dll-path> ; values = [ condition ] condition = None if condition: transformed = [] for c in condition: # FIXME: 'split' might be a too raw tool here. pl = [property.create_from_string(s,False,True) for s in c.split('/')] pl = feature.expand_subfeatures(pl); transformed.append(property_set.create(pl)) condition = transformed property.validate_property_sets(condition) __add_flag (rule_or_module, variable_name, condition, values)
python
def flags(rule_or_module, variable_name, condition, values = []): """ Specifies the flags (variables) that must be set on targets under certain conditions, described by arguments. rule_or_module: If contains dot, should be a rule name. The flags will be applied when that rule is used to set up build actions. If does not contain dot, should be a module name. The flags will be applied for all rules in that module. If module for rule is different from the calling module, an error is issued. variable_name: Variable that should be set on target condition A condition when this flag should be applied. Should be set of property sets. If one of those property sets is contained in build properties, the flag will be used. Implied values are not allowed: "<toolset>gcc" should be used, not just "gcc". Subfeatures, like in "<toolset>gcc-3.2" are allowed. If left empty, the flag will always used. Propery sets may use value-less properties ('<a>' vs. '<a>value') to match absent properties. This allows to separately match <architecture>/<address-model>64 <architecture>ia64/<address-model> Where both features are optional. Without this syntax we'd be forced to define "default" value. values: The value to add to variable. If <feature> is specified, then the value of 'feature' will be added. """ assert isinstance(rule_or_module, basestring) assert isinstance(variable_name, basestring) assert is_iterable_typed(condition, basestring) assert is_iterable(values) and all(isinstance(v, (basestring, type(None))) for v in values) caller = bjam.caller() if not '.' in rule_or_module and caller and caller[:-1].startswith("Jamfile"): # Unqualified rule name, used inside Jamfile. Most likely used with # 'make' or 'notfile' rules. This prevents setting flags on the entire # Jamfile module (this will be considered as rule), but who cares? # Probably, 'flags' rule should be split into 'flags' and # 'flags-on-module'. rule_or_module = qualify_jam_action(rule_or_module, caller) else: # FIXME: revive checking that we don't set flags for a different # module unintentionally pass if condition and not replace_grist (condition, ''): # We have condition in the form '<feature>', that is, without # value. That's a previous syntax: # # flags gcc.link RPATH <dll-path> ; # for compatibility, convert it to # flags gcc.link RPATH : <dll-path> ; values = [ condition ] condition = None if condition: transformed = [] for c in condition: # FIXME: 'split' might be a too raw tool here. pl = [property.create_from_string(s,False,True) for s in c.split('/')] pl = feature.expand_subfeatures(pl); transformed.append(property_set.create(pl)) condition = transformed property.validate_property_sets(condition) __add_flag (rule_or_module, variable_name, condition, values)
[ "def", "flags", "(", "rule_or_module", ",", "variable_name", ",", "condition", ",", "values", "=", "[", "]", ")", ":", "assert", "isinstance", "(", "rule_or_module", ",", "basestring", ")", "assert", "isinstance", "(", "variable_name", ",", "basestring", ")", "assert", "is_iterable_typed", "(", "condition", ",", "basestring", ")", "assert", "is_iterable", "(", "values", ")", "and", "all", "(", "isinstance", "(", "v", ",", "(", "basestring", ",", "type", "(", "None", ")", ")", ")", "for", "v", "in", "values", ")", "caller", "=", "bjam", ".", "caller", "(", ")", "if", "not", "'.'", "in", "rule_or_module", "and", "caller", "and", "caller", "[", ":", "-", "1", "]", ".", "startswith", "(", "\"Jamfile\"", ")", ":", "# Unqualified rule name, used inside Jamfile. Most likely used with", "# 'make' or 'notfile' rules. This prevents setting flags on the entire", "# Jamfile module (this will be considered as rule), but who cares?", "# Probably, 'flags' rule should be split into 'flags' and", "# 'flags-on-module'.", "rule_or_module", "=", "qualify_jam_action", "(", "rule_or_module", ",", "caller", ")", "else", ":", "# FIXME: revive checking that we don't set flags for a different", "# module unintentionally", "pass", "if", "condition", "and", "not", "replace_grist", "(", "condition", ",", "''", ")", ":", "# We have condition in the form '<feature>', that is, without", "# value. That's a previous syntax:", "#", "# flags gcc.link RPATH <dll-path> ;", "# for compatibility, convert it to", "# flags gcc.link RPATH : <dll-path> ;", "values", "=", "[", "condition", "]", "condition", "=", "None", "if", "condition", ":", "transformed", "=", "[", "]", "for", "c", "in", "condition", ":", "# FIXME: 'split' might be a too raw tool here.", "pl", "=", "[", "property", ".", "create_from_string", "(", "s", ",", "False", ",", "True", ")", "for", "s", "in", "c", ".", "split", "(", "'/'", ")", "]", "pl", "=", "feature", ".", "expand_subfeatures", "(", "pl", ")", "transformed", ".", "append", "(", "property_set", ".", "create", "(", "pl", ")", ")", "condition", "=", "transformed", "property", ".", "validate_property_sets", "(", "condition", ")", "__add_flag", "(", "rule_or_module", ",", "variable_name", ",", "condition", ",", "values", ")" ]
Specifies the flags (variables) that must be set on targets under certain conditions, described by arguments. rule_or_module: If contains dot, should be a rule name. The flags will be applied when that rule is used to set up build actions. If does not contain dot, should be a module name. The flags will be applied for all rules in that module. If module for rule is different from the calling module, an error is issued. variable_name: Variable that should be set on target condition A condition when this flag should be applied. Should be set of property sets. If one of those property sets is contained in build properties, the flag will be used. Implied values are not allowed: "<toolset>gcc" should be used, not just "gcc". Subfeatures, like in "<toolset>gcc-3.2" are allowed. If left empty, the flag will always used. Propery sets may use value-less properties ('<a>' vs. '<a>value') to match absent properties. This allows to separately match <architecture>/<address-model>64 <architecture>ia64/<address-model> Where both features are optional. Without this syntax we'd be forced to define "default" value. values: The value to add to variable. If <feature> is specified, then the value of 'feature' will be added.
[ "Specifies", "the", "flags", "(", "variables", ")", "that", "must", "be", "set", "on", "targets", "under", "certain", "conditions", "described", "by", "arguments", ".", "rule_or_module", ":", "If", "contains", "dot", "should", "be", "a", "rule", "name", ".", "The", "flags", "will", "be", "applied", "when", "that", "rule", "is", "used", "to", "set", "up", "build", "actions", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/toolset.py#L92-L169
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/toolset.py
find_satisfied_condition
def find_satisfied_condition(conditions, ps): """Returns the first element of 'property-sets' which is a subset of 'properties', or an empty list if no such element exists.""" assert is_iterable_typed(conditions, property_set.PropertySet) assert isinstance(ps, property_set.PropertySet) for condition in conditions: found_all = True for i in condition.all(): if i.value: found = i.value in ps.get(i.feature) else: # Handle value-less properties like '<architecture>' (compare with # '<architecture>x86'). # If $(i) is a value-less property it should match default # value of an optional property. See the first line in the # example below: # # property set properties result # <a> <b>foo <b>foo match # <a> <b>foo <a>foo <b>foo no match # <a>foo <b>foo <b>foo no match # <a>foo <b>foo <a>foo <b>foo match found = not ps.get(i.feature) found_all = found_all and found if found_all: return condition return None
python
def find_satisfied_condition(conditions, ps): """Returns the first element of 'property-sets' which is a subset of 'properties', or an empty list if no such element exists.""" assert is_iterable_typed(conditions, property_set.PropertySet) assert isinstance(ps, property_set.PropertySet) for condition in conditions: found_all = True for i in condition.all(): if i.value: found = i.value in ps.get(i.feature) else: # Handle value-less properties like '<architecture>' (compare with # '<architecture>x86'). # If $(i) is a value-less property it should match default # value of an optional property. See the first line in the # example below: # # property set properties result # <a> <b>foo <b>foo match # <a> <b>foo <a>foo <b>foo no match # <a>foo <b>foo <b>foo no match # <a>foo <b>foo <a>foo <b>foo match found = not ps.get(i.feature) found_all = found_all and found if found_all: return condition return None
[ "def", "find_satisfied_condition", "(", "conditions", ",", "ps", ")", ":", "assert", "is_iterable_typed", "(", "conditions", ",", "property_set", ".", "PropertySet", ")", "assert", "isinstance", "(", "ps", ",", "property_set", ".", "PropertySet", ")", "for", "condition", "in", "conditions", ":", "found_all", "=", "True", "for", "i", "in", "condition", ".", "all", "(", ")", ":", "if", "i", ".", "value", ":", "found", "=", "i", ".", "value", "in", "ps", ".", "get", "(", "i", ".", "feature", ")", "else", ":", "# Handle value-less properties like '<architecture>' (compare with", "# '<architecture>x86').", "# If $(i) is a value-less property it should match default", "# value of an optional property. See the first line in the", "# example below:", "#", "# property set properties result", "# <a> <b>foo <b>foo match", "# <a> <b>foo <a>foo <b>foo no match", "# <a>foo <b>foo <b>foo no match", "# <a>foo <b>foo <a>foo <b>foo match", "found", "=", "not", "ps", ".", "get", "(", "i", ".", "feature", ")", "found_all", "=", "found_all", "and", "found", "if", "found_all", ":", "return", "condition", "return", "None" ]
Returns the first element of 'property-sets' which is a subset of 'properties', or an empty list if no such element exists.
[ "Returns", "the", "first", "element", "of", "property", "-", "sets", "which", "is", "a", "subset", "of", "properties", "or", "an", "empty", "list", "if", "no", "such", "element", "exists", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/toolset.py#L184-L216
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/toolset.py
inherit_flags
def inherit_flags(toolset, base, prohibited_properties = []): """Brings all flag definitions from the 'base' toolset into the 'toolset' toolset. Flag definitions whose conditions make use of properties in 'prohibited-properties' are ignored. Don't confuse property and feature, for example <debug-symbols>on and <debug-symbols>off, so blocking one of them does not block the other one. The flag conditions are not altered at all, so if a condition includes a name, or version of a base toolset, it won't ever match the inheriting toolset. When such flag settings must be inherited, define a rule in base toolset module and call it as needed.""" assert isinstance(toolset, basestring) assert isinstance(base, basestring) assert is_iterable_typed(prohibited_properties, basestring) for f in __module_flags.get(base, []): if not f.condition or b2.util.set.difference(f.condition, prohibited_properties): match = __re_first_group.match(f.rule) rule_ = None if match: rule_ = match.group(1) new_rule_or_module = '' if rule_: new_rule_or_module = toolset + '.' + rule_ else: new_rule_or_module = toolset __add_flag (new_rule_or_module, f.variable_name, f.condition, f.values)
python
def inherit_flags(toolset, base, prohibited_properties = []): """Brings all flag definitions from the 'base' toolset into the 'toolset' toolset. Flag definitions whose conditions make use of properties in 'prohibited-properties' are ignored. Don't confuse property and feature, for example <debug-symbols>on and <debug-symbols>off, so blocking one of them does not block the other one. The flag conditions are not altered at all, so if a condition includes a name, or version of a base toolset, it won't ever match the inheriting toolset. When such flag settings must be inherited, define a rule in base toolset module and call it as needed.""" assert isinstance(toolset, basestring) assert isinstance(base, basestring) assert is_iterable_typed(prohibited_properties, basestring) for f in __module_flags.get(base, []): if not f.condition or b2.util.set.difference(f.condition, prohibited_properties): match = __re_first_group.match(f.rule) rule_ = None if match: rule_ = match.group(1) new_rule_or_module = '' if rule_: new_rule_or_module = toolset + '.' + rule_ else: new_rule_or_module = toolset __add_flag (new_rule_or_module, f.variable_name, f.condition, f.values)
[ "def", "inherit_flags", "(", "toolset", ",", "base", ",", "prohibited_properties", "=", "[", "]", ")", ":", "assert", "isinstance", "(", "toolset", ",", "basestring", ")", "assert", "isinstance", "(", "base", ",", "basestring", ")", "assert", "is_iterable_typed", "(", "prohibited_properties", ",", "basestring", ")", "for", "f", "in", "__module_flags", ".", "get", "(", "base", ",", "[", "]", ")", ":", "if", "not", "f", ".", "condition", "or", "b2", ".", "util", ".", "set", ".", "difference", "(", "f", ".", "condition", ",", "prohibited_properties", ")", ":", "match", "=", "__re_first_group", ".", "match", "(", "f", ".", "rule", ")", "rule_", "=", "None", "if", "match", ":", "rule_", "=", "match", ".", "group", "(", "1", ")", "new_rule_or_module", "=", "''", "if", "rule_", ":", "new_rule_or_module", "=", "toolset", "+", "'.'", "+", "rule_", "else", ":", "new_rule_or_module", "=", "toolset", "__add_flag", "(", "new_rule_or_module", ",", "f", ".", "variable_name", ",", "f", ".", "condition", ",", "f", ".", "values", ")" ]
Brings all flag definitions from the 'base' toolset into the 'toolset' toolset. Flag definitions whose conditions make use of properties in 'prohibited-properties' are ignored. Don't confuse property and feature, for example <debug-symbols>on and <debug-symbols>off, so blocking one of them does not block the other one. The flag conditions are not altered at all, so if a condition includes a name, or version of a base toolset, it won't ever match the inheriting toolset. When such flag settings must be inherited, define a rule in base toolset module and call it as needed.
[ "Brings", "all", "flag", "definitions", "from", "the", "base", "toolset", "into", "the", "toolset", "toolset", ".", "Flag", "definitions", "whose", "conditions", "make", "use", "of", "properties", "in", "prohibited", "-", "properties", "are", "ignored", ".", "Don", "t", "confuse", "property", "and", "feature", "for", "example", "<debug", "-", "symbols", ">", "on", "and", "<debug", "-", "symbols", ">", "off", "so", "blocking", "one", "of", "them", "does", "not", "block", "the", "other", "one", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/toolset.py#L251-L280
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/toolset.py
__set_target_variables_aux
def __set_target_variables_aux (manager, rule_or_module, ps): """ Given a rule name and a property set, returns a list of tuples of variables names and values, which must be set on targets for that rule/properties combination. """ assert isinstance(rule_or_module, basestring) assert isinstance(ps, property_set.PropertySet) result = [] for f in __flags.get(rule_or_module, []): if not f.condition or find_satisfied_condition (f.condition, ps): processed = [] for v in f.values: # The value might be <feature-name> so needs special # treatment. processed += __handle_flag_value (manager, v, ps) for r in processed: result.append ((f.variable_name, r)) # strip away last dot separated part and recurse. next = __re_split_last_segment.match(rule_or_module) if next: result.extend(__set_target_variables_aux( manager, next.group(1), ps)) return result
python
def __set_target_variables_aux (manager, rule_or_module, ps): """ Given a rule name and a property set, returns a list of tuples of variables names and values, which must be set on targets for that rule/properties combination. """ assert isinstance(rule_or_module, basestring) assert isinstance(ps, property_set.PropertySet) result = [] for f in __flags.get(rule_or_module, []): if not f.condition or find_satisfied_condition (f.condition, ps): processed = [] for v in f.values: # The value might be <feature-name> so needs special # treatment. processed += __handle_flag_value (manager, v, ps) for r in processed: result.append ((f.variable_name, r)) # strip away last dot separated part and recurse. next = __re_split_last_segment.match(rule_or_module) if next: result.extend(__set_target_variables_aux( manager, next.group(1), ps)) return result
[ "def", "__set_target_variables_aux", "(", "manager", ",", "rule_or_module", ",", "ps", ")", ":", "assert", "isinstance", "(", "rule_or_module", ",", "basestring", ")", "assert", "isinstance", "(", "ps", ",", "property_set", ".", "PropertySet", ")", "result", "=", "[", "]", "for", "f", "in", "__flags", ".", "get", "(", "rule_or_module", ",", "[", "]", ")", ":", "if", "not", "f", ".", "condition", "or", "find_satisfied_condition", "(", "f", ".", "condition", ",", "ps", ")", ":", "processed", "=", "[", "]", "for", "v", "in", "f", ".", "values", ":", "# The value might be <feature-name> so needs special", "# treatment.", "processed", "+=", "__handle_flag_value", "(", "manager", ",", "v", ",", "ps", ")", "for", "r", "in", "processed", ":", "result", ".", "append", "(", "(", "f", ".", "variable_name", ",", "r", ")", ")", "# strip away last dot separated part and recurse.", "next", "=", "__re_split_last_segment", ".", "match", "(", "rule_or_module", ")", "if", "next", ":", "result", ".", "extend", "(", "__set_target_variables_aux", "(", "manager", ",", "next", ".", "group", "(", "1", ")", ",", "ps", ")", ")", "return", "result" ]
Given a rule name and a property set, returns a list of tuples of variables names and values, which must be set on targets for that rule/properties combination.
[ "Given", "a", "rule", "name", "and", "a", "property", "set", "returns", "a", "list", "of", "tuples", "of", "variables", "names", "and", "values", "which", "must", "be", "set", "on", "targets", "for", "that", "rule", "/", "properties", "combination", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/toolset.py#L301-L329
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/toolset.py
__add_flag
def __add_flag (rule_or_module, variable_name, condition, values): """ Adds a new flag setting with the specified values. Does no checking. """ assert isinstance(rule_or_module, basestring) assert isinstance(variable_name, basestring) assert is_iterable_typed(condition, property_set.PropertySet) assert is_iterable(values) and all( isinstance(v, (basestring, type(None))) for v in values) f = Flag(variable_name, values, condition, rule_or_module) # Grab the name of the module m = __re_first_segment.match (rule_or_module) assert m module = m.group(1) __module_flags.setdefault(module, []).append(f) __flags.setdefault(rule_or_module, []).append(f)
python
def __add_flag (rule_or_module, variable_name, condition, values): """ Adds a new flag setting with the specified values. Does no checking. """ assert isinstance(rule_or_module, basestring) assert isinstance(variable_name, basestring) assert is_iterable_typed(condition, property_set.PropertySet) assert is_iterable(values) and all( isinstance(v, (basestring, type(None))) for v in values) f = Flag(variable_name, values, condition, rule_or_module) # Grab the name of the module m = __re_first_segment.match (rule_or_module) assert m module = m.group(1) __module_flags.setdefault(module, []).append(f) __flags.setdefault(rule_or_module, []).append(f)
[ "def", "__add_flag", "(", "rule_or_module", ",", "variable_name", ",", "condition", ",", "values", ")", ":", "assert", "isinstance", "(", "rule_or_module", ",", "basestring", ")", "assert", "isinstance", "(", "variable_name", ",", "basestring", ")", "assert", "is_iterable_typed", "(", "condition", ",", "property_set", ".", "PropertySet", ")", "assert", "is_iterable", "(", "values", ")", "and", "all", "(", "isinstance", "(", "v", ",", "(", "basestring", ",", "type", "(", "None", ")", ")", ")", "for", "v", "in", "values", ")", "f", "=", "Flag", "(", "variable_name", ",", "values", ",", "condition", ",", "rule_or_module", ")", "# Grab the name of the module", "m", "=", "__re_first_segment", ".", "match", "(", "rule_or_module", ")", "assert", "m", "module", "=", "m", ".", "group", "(", "1", ")", "__module_flags", ".", "setdefault", "(", "module", ",", "[", "]", ")", ".", "append", "(", "f", ")", "__flags", ".", "setdefault", "(", "rule_or_module", ",", "[", "]", ")", ".", "append", "(", "f", ")" ]
Adds a new flag setting with the specified values. Does no checking.
[ "Adds", "a", "new", "flag", "setting", "with", "the", "specified", "values", ".", "Does", "no", "checking", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/toolset.py#L365-L382
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_logistic_regression.py
convert
def convert(model, feature_names, target): """Convert a Logistic Regression model to the protobuf spec. Parameters ---------- model: LogisticRegression A trained LogisticRegression model. feature_names: [str], optional (default=None) Name of the input columns. target: str, optional (default=None) Name of the output column. Returns ------- model_spec: An object of type Model_pb. Protobuf representation of the model """ if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') _sklearn_util.check_expected_type(model, LogisticRegression) _sklearn_util.check_fitted(model, lambda m: hasattr(m, 'coef_')) return _MLModel(_convert(model, feature_names, target))
python
def convert(model, feature_names, target): """Convert a Logistic Regression model to the protobuf spec. Parameters ---------- model: LogisticRegression A trained LogisticRegression model. feature_names: [str], optional (default=None) Name of the input columns. target: str, optional (default=None) Name of the output column. Returns ------- model_spec: An object of type Model_pb. Protobuf representation of the model """ if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') _sklearn_util.check_expected_type(model, LogisticRegression) _sklearn_util.check_fitted(model, lambda m: hasattr(m, 'coef_')) return _MLModel(_convert(model, feature_names, target))
[ "def", "convert", "(", "model", ",", "feature_names", ",", "target", ")", ":", "if", "not", "(", "_HAS_SKLEARN", ")", ":", "raise", "RuntimeError", "(", "'scikit-learn not found. scikit-learn conversion API is disabled.'", ")", "_sklearn_util", ".", "check_expected_type", "(", "model", ",", "LogisticRegression", ")", "_sklearn_util", ".", "check_fitted", "(", "model", ",", "lambda", "m", ":", "hasattr", "(", "m", ",", "'coef_'", ")", ")", "return", "_MLModel", "(", "_convert", "(", "model", ",", "feature_names", ",", "target", ")", ")" ]
Convert a Logistic Regression model to the protobuf spec. Parameters ---------- model: LogisticRegression A trained LogisticRegression model. feature_names: [str], optional (default=None) Name of the input columns. target: str, optional (default=None) Name of the output column. Returns ------- model_spec: An object of type Model_pb. Protobuf representation of the model
[ "Convert", "a", "Logistic", "Regression", "model", "to", "the", "protobuf", "spec", ".", "Parameters", "----------", "model", ":", "LogisticRegression", "A", "trained", "LogisticRegression", "model", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_logistic_regression.py#L21-L45
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/util/path.py
root
def root (path, root): """ If 'path' is relative, it is rooted at 'root'. Otherwise, it's unchanged. """ if os.path.isabs (path): return path else: return os.path.join (root, path)
python
def root (path, root): """ If 'path' is relative, it is rooted at 'root'. Otherwise, it's unchanged. """ if os.path.isabs (path): return path else: return os.path.join (root, path)
[ "def", "root", "(", "path", ",", "root", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "return", "path", "else", ":", "return", "os", ".", "path", ".", "join", "(", "root", ",", "path", ")" ]
If 'path' is relative, it is rooted at 'root'. Otherwise, it's unchanged.
[ "If", "path", "is", "relative", "it", "is", "rooted", "at", "root", ".", "Otherwise", "it", "s", "unchanged", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/path.py#L28-L34
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/util/path.py
reverse
def reverse(path): """Returns path2 such that `os.path.join(path, path2) == '.'`. `path` may not contain '..' or be rooted. Args: path (str): the path to reverse Returns: the string of the reversed path Example: >>> p1 = 'path/to/somewhere' >>> p2 = reverse('path/to/somewhere') >>> p2 '../../..' >>> os.path.normpath(os.path.join(p1, p2)) '.' """ if is_rooted(path) or '..' in path: from b2.manager import get_manager get_manager().errors()( 'reverse(path): path is either rooted or contains ".." in the path') if path == '.': return path path = os.path.normpath(path) # os.sep.join() is being used over os.path.join() due # to an extra '..' that is created by os.path.join() return os.sep.join('..' for t in path.split(os.sep))
python
def reverse(path): """Returns path2 such that `os.path.join(path, path2) == '.'`. `path` may not contain '..' or be rooted. Args: path (str): the path to reverse Returns: the string of the reversed path Example: >>> p1 = 'path/to/somewhere' >>> p2 = reverse('path/to/somewhere') >>> p2 '../../..' >>> os.path.normpath(os.path.join(p1, p2)) '.' """ if is_rooted(path) or '..' in path: from b2.manager import get_manager get_manager().errors()( 'reverse(path): path is either rooted or contains ".." in the path') if path == '.': return path path = os.path.normpath(path) # os.sep.join() is being used over os.path.join() due # to an extra '..' that is created by os.path.join() return os.sep.join('..' for t in path.split(os.sep))
[ "def", "reverse", "(", "path", ")", ":", "if", "is_rooted", "(", "path", ")", "or", "'..'", "in", "path", ":", "from", "b2", ".", "manager", "import", "get_manager", "get_manager", "(", ")", ".", "errors", "(", ")", "(", "'reverse(path): path is either rooted or contains \"..\" in the path'", ")", "if", "path", "==", "'.'", ":", "return", "path", "path", "=", "os", ".", "path", ".", "normpath", "(", "path", ")", "# os.sep.join() is being used over os.path.join() due", "# to an extra '..' that is created by os.path.join()", "return", "os", ".", "sep", ".", "join", "(", "'..'", "for", "t", "in", "path", ".", "split", "(", "os", ".", "sep", ")", ")" ]
Returns path2 such that `os.path.join(path, path2) == '.'`. `path` may not contain '..' or be rooted. Args: path (str): the path to reverse Returns: the string of the reversed path Example: >>> p1 = 'path/to/somewhere' >>> p2 = reverse('path/to/somewhere') >>> p2 '../../..' >>> os.path.normpath(os.path.join(p1, p2)) '.'
[ "Returns", "path2", "such", "that", "os", ".", "path", ".", "join", "(", "path", "path2", ")", "==", ".", ".", "path", "may", "not", "contain", "..", "or", "be", "rooted", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/path.py#L197-L225
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/util/path.py
glob
def glob (dirs, patterns): """ Returns the list of files matching the given pattern in the specified directory. Both directories and patterns are supplied as portable paths. Each pattern should be non-absolute path, and can't contain "." or ".." elements. Each slash separated element of pattern can contain the following special characters: - '?', which match any character - '*', which matches arbitrary number of characters. A file $(d)/e1/e2/e3 (where 'd' is in $(dirs)) matches pattern p1/p2/p3 if and only if e1 matches p1, e2 matches p2 and so on. For example: [ glob . : *.cpp ] [ glob . : */build/Jamfile ] """ # { # local result ; # if $(patterns:D) # { # # When a pattern has a directory element, we first glob for # # directory, and then glob for file name is the found directories. # for local p in $(patterns) # { # # First glob for directory part. # local globbed-dirs = [ glob $(dirs) : $(p:D) ] ; # result += [ glob $(globbed-dirs) : $(p:D="") ] ; # } # } # else # { # # When a pattern has not directory, we glob directly. # # Take care of special ".." value. The "GLOB" rule simply ignores # # the ".." element (and ".") element in directory listings. This is # # needed so that # # # # [ glob libs/*/Jamfile ] # # # # don't return # # # # libs/../Jamfile (which is the same as ./Jamfile) # # # # On the other hand, when ".." is explicitly present in the pattern # # we need to return it. # # # for local dir in $(dirs) # { # for local p in $(patterns) # { # if $(p) != ".." # { # result += [ sequence.transform make # : [ GLOB [ native $(dir) ] : $(p) ] ] ; # } # else # { # result += [ path.join $(dir) .. ] ; # } # } # } # } # return $(result) ; # } # # TODO: (PF) I replaced the code above by this. I think it should work but needs to be tested. result = [] dirs = to_seq (dirs) patterns = to_seq (patterns) splitdirs = [] for dir in dirs: splitdirs += dir.split (os.pathsep) for dir in splitdirs: for pattern in patterns: p = os.path.join (dir, pattern) import glob result.extend (glob.glob (p)) return result
python
def glob (dirs, patterns): """ Returns the list of files matching the given pattern in the specified directory. Both directories and patterns are supplied as portable paths. Each pattern should be non-absolute path, and can't contain "." or ".." elements. Each slash separated element of pattern can contain the following special characters: - '?', which match any character - '*', which matches arbitrary number of characters. A file $(d)/e1/e2/e3 (where 'd' is in $(dirs)) matches pattern p1/p2/p3 if and only if e1 matches p1, e2 matches p2 and so on. For example: [ glob . : *.cpp ] [ glob . : */build/Jamfile ] """ # { # local result ; # if $(patterns:D) # { # # When a pattern has a directory element, we first glob for # # directory, and then glob for file name is the found directories. # for local p in $(patterns) # { # # First glob for directory part. # local globbed-dirs = [ glob $(dirs) : $(p:D) ] ; # result += [ glob $(globbed-dirs) : $(p:D="") ] ; # } # } # else # { # # When a pattern has not directory, we glob directly. # # Take care of special ".." value. The "GLOB" rule simply ignores # # the ".." element (and ".") element in directory listings. This is # # needed so that # # # # [ glob libs/*/Jamfile ] # # # # don't return # # # # libs/../Jamfile (which is the same as ./Jamfile) # # # # On the other hand, when ".." is explicitly present in the pattern # # we need to return it. # # # for local dir in $(dirs) # { # for local p in $(patterns) # { # if $(p) != ".." # { # result += [ sequence.transform make # : [ GLOB [ native $(dir) ] : $(p) ] ] ; # } # else # { # result += [ path.join $(dir) .. ] ; # } # } # } # } # return $(result) ; # } # # TODO: (PF) I replaced the code above by this. I think it should work but needs to be tested. result = [] dirs = to_seq (dirs) patterns = to_seq (patterns) splitdirs = [] for dir in dirs: splitdirs += dir.split (os.pathsep) for dir in splitdirs: for pattern in patterns: p = os.path.join (dir, pattern) import glob result.extend (glob.glob (p)) return result
[ "def", "glob", "(", "dirs", ",", "patterns", ")", ":", "# {", "# local result ;", "# if $(patterns:D)", "# {", "# # When a pattern has a directory element, we first glob for", "# # directory, and then glob for file name is the found directories.", "# for local p in $(patterns)", "# {", "# # First glob for directory part.", "# local globbed-dirs = [ glob $(dirs) : $(p:D) ] ;", "# result += [ glob $(globbed-dirs) : $(p:D=\"\") ] ;", "# }", "# }", "# else", "# {", "# # When a pattern has not directory, we glob directly.", "# # Take care of special \"..\" value. The \"GLOB\" rule simply ignores", "# # the \"..\" element (and \".\") element in directory listings. This is", "# # needed so that", "# #", "# # [ glob libs/*/Jamfile ]", "# #", "# # don't return", "# #", "# # libs/../Jamfile (which is the same as ./Jamfile)", "# #", "# # On the other hand, when \"..\" is explicitly present in the pattern", "# # we need to return it.", "# #", "# for local dir in $(dirs)", "# {", "# for local p in $(patterns)", "# {", "# if $(p) != \"..\"", "# {", "# result += [ sequence.transform make", "# : [ GLOB [ native $(dir) ] : $(p) ] ] ;", "# }", "# else", "# {", "# result += [ path.join $(dir) .. ] ;", "# }", "# }", "# }", "# }", "# return $(result) ;", "# }", "#", "# TODO: (PF) I replaced the code above by this. I think it should work but needs to be tested.", "result", "=", "[", "]", "dirs", "=", "to_seq", "(", "dirs", ")", "patterns", "=", "to_seq", "(", "patterns", ")", "splitdirs", "=", "[", "]", "for", "dir", "in", "dirs", ":", "splitdirs", "+=", "dir", ".", "split", "(", "os", ".", "pathsep", ")", "for", "dir", "in", "splitdirs", ":", "for", "pattern", "in", "patterns", ":", "p", "=", "os", ".", "path", ".", "join", "(", "dir", ",", "pattern", ")", "import", "glob", "result", ".", "extend", "(", "glob", ".", "glob", "(", "p", ")", ")", "return", "result" ]
Returns the list of files matching the given pattern in the specified directory. Both directories and patterns are supplied as portable paths. Each pattern should be non-absolute path, and can't contain "." or ".." elements. Each slash separated element of pattern can contain the following special characters: - '?', which match any character - '*', which matches arbitrary number of characters. A file $(d)/e1/e2/e3 (where 'd' is in $(dirs)) matches pattern p1/p2/p3 if and only if e1 matches p1, e2 matches p2 and so on. For example: [ glob . : *.cpp ] [ glob . : */build/Jamfile ]
[ "Returns", "the", "list", "of", "files", "matching", "the", "given", "pattern", "in", "the", "specified", "directory", ".", "Both", "directories", "and", "patterns", "are", "supplied", "as", "portable", "paths", ".", "Each", "pattern", "should", "be", "non", "-", "absolute", "path", "and", "can", "t", "contain", ".", "or", "..", "elements", ".", "Each", "slash", "separated", "element", "of", "pattern", "can", "contain", "the", "following", "special", "characters", ":", "-", "?", "which", "match", "any", "character", "-", "*", "which", "matches", "arbitrary", "number", "of", "characters", ".", "A", "file", "$", "(", "d", ")", "/", "e1", "/", "e2", "/", "e3", "(", "where", "d", "is", "in", "$", "(", "dirs", "))", "matches", "pattern", "p1", "/", "p2", "/", "p3", "if", "and", "only", "if", "e1", "matches", "p1", "e2", "matches", "p2", "and", "so", "on", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/path.py#L260-L338
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/util/path.py
glob
def glob(dirs, patterns, exclude_patterns=None): """Returns the list of files matching the given pattern in the specified directory. Both directories and patterns are supplied as portable paths. Each pattern should be non-absolute path, and can't contain '.' or '..' elements. Each slash separated element of pattern can contain the following special characters: - '?', which match any character - '*', which matches arbitrary number of characters. A file $(d)/e1/e2/e3 (where 'd' is in $(dirs)) matches pattern p1/p2/p3 if and only if e1 matches p1, e2 matches p2 and so on. For example: [ glob . : *.cpp ] [ glob . : */build/Jamfile ] """ assert(isinstance(patterns, list)) assert(isinstance(dirs, list)) if not exclude_patterns: exclude_patterns = [] else: assert(isinstance(exclude_patterns, list)) real_patterns = [os.path.join(d, p) for p in patterns for d in dirs] real_exclude_patterns = [os.path.join(d, p) for p in exclude_patterns for d in dirs] inc = [os.path.normpath(name) for p in real_patterns for name in builtin_glob(p)] exc = [os.path.normpath(name) for p in real_exclude_patterns for name in builtin_glob(p)] return [x for x in inc if x not in exc]
python
def glob(dirs, patterns, exclude_patterns=None): """Returns the list of files matching the given pattern in the specified directory. Both directories and patterns are supplied as portable paths. Each pattern should be non-absolute path, and can't contain '.' or '..' elements. Each slash separated element of pattern can contain the following special characters: - '?', which match any character - '*', which matches arbitrary number of characters. A file $(d)/e1/e2/e3 (where 'd' is in $(dirs)) matches pattern p1/p2/p3 if and only if e1 matches p1, e2 matches p2 and so on. For example: [ glob . : *.cpp ] [ glob . : */build/Jamfile ] """ assert(isinstance(patterns, list)) assert(isinstance(dirs, list)) if not exclude_patterns: exclude_patterns = [] else: assert(isinstance(exclude_patterns, list)) real_patterns = [os.path.join(d, p) for p in patterns for d in dirs] real_exclude_patterns = [os.path.join(d, p) for p in exclude_patterns for d in dirs] inc = [os.path.normpath(name) for p in real_patterns for name in builtin_glob(p)] exc = [os.path.normpath(name) for p in real_exclude_patterns for name in builtin_glob(p)] return [x for x in inc if x not in exc]
[ "def", "glob", "(", "dirs", ",", "patterns", ",", "exclude_patterns", "=", "None", ")", ":", "assert", "(", "isinstance", "(", "patterns", ",", "list", ")", ")", "assert", "(", "isinstance", "(", "dirs", ",", "list", ")", ")", "if", "not", "exclude_patterns", ":", "exclude_patterns", "=", "[", "]", "else", ":", "assert", "(", "isinstance", "(", "exclude_patterns", ",", "list", ")", ")", "real_patterns", "=", "[", "os", ".", "path", ".", "join", "(", "d", ",", "p", ")", "for", "p", "in", "patterns", "for", "d", "in", "dirs", "]", "real_exclude_patterns", "=", "[", "os", ".", "path", ".", "join", "(", "d", ",", "p", ")", "for", "p", "in", "exclude_patterns", "for", "d", "in", "dirs", "]", "inc", "=", "[", "os", ".", "path", ".", "normpath", "(", "name", ")", "for", "p", "in", "real_patterns", "for", "name", "in", "builtin_glob", "(", "p", ")", "]", "exc", "=", "[", "os", ".", "path", ".", "normpath", "(", "name", ")", "for", "p", "in", "real_exclude_patterns", "for", "name", "in", "builtin_glob", "(", "p", ")", "]", "return", "[", "x", "for", "x", "in", "inc", "if", "x", "not", "in", "exc", "]" ]
Returns the list of files matching the given pattern in the specified directory. Both directories and patterns are supplied as portable paths. Each pattern should be non-absolute path, and can't contain '.' or '..' elements. Each slash separated element of pattern can contain the following special characters: - '?', which match any character - '*', which matches arbitrary number of characters. A file $(d)/e1/e2/e3 (where 'd' is in $(dirs)) matches pattern p1/p2/p3 if and only if e1 matches p1, e2 matches p2 and so on. For example: [ glob . : *.cpp ] [ glob . : */build/Jamfile ]
[ "Returns", "the", "list", "of", "files", "matching", "the", "given", "pattern", "in", "the", "specified", "directory", ".", "Both", "directories", "and", "patterns", "are", "supplied", "as", "portable", "paths", ".", "Each", "pattern", "should", "be", "non", "-", "absolute", "path", "and", "can", "t", "contain", ".", "or", "..", "elements", ".", "Each", "slash", "separated", "element", "of", "pattern", "can", "contain", "the", "following", "special", "characters", ":", "-", "?", "which", "match", "any", "character", "-", "*", "which", "matches", "arbitrary", "number", "of", "characters", ".", "A", "file", "$", "(", "d", ")", "/", "e1", "/", "e2", "/", "e3", "(", "where", "d", "is", "in", "$", "(", "dirs", "))", "matches", "pattern", "p1", "/", "p2", "/", "p3", "if", "and", "only", "if", "e1", "matches", "p1", "e2", "matches", "p2", "and", "so", "on", ".", "For", "example", ":", "[", "glob", ".", ":", "*", ".", "cpp", "]", "[", "glob", ".", ":", "*", "/", "build", "/", "Jamfile", "]" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/path.py#L839-L870
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/util/path.py
glob_tree
def glob_tree(roots, patterns, exclude_patterns=None): """Recursive version of GLOB. Builds the glob of files while also searching in the subdirectories of the given roots. An optional set of exclusion patterns will filter out the matching entries from the result. The exclusions also apply to the subdirectory scanning, such that directories that match the exclusion patterns will not be searched.""" if not exclude_patterns: exclude_patterns = [] result = glob(roots, patterns, exclude_patterns) subdirs = [s for s in glob(roots, ["*"], exclude_patterns) if s != "." and s != ".." and os.path.isdir(s)] if subdirs: result.extend(glob_tree(subdirs, patterns, exclude_patterns)) return result
python
def glob_tree(roots, patterns, exclude_patterns=None): """Recursive version of GLOB. Builds the glob of files while also searching in the subdirectories of the given roots. An optional set of exclusion patterns will filter out the matching entries from the result. The exclusions also apply to the subdirectory scanning, such that directories that match the exclusion patterns will not be searched.""" if not exclude_patterns: exclude_patterns = [] result = glob(roots, patterns, exclude_patterns) subdirs = [s for s in glob(roots, ["*"], exclude_patterns) if s != "." and s != ".." and os.path.isdir(s)] if subdirs: result.extend(glob_tree(subdirs, patterns, exclude_patterns)) return result
[ "def", "glob_tree", "(", "roots", ",", "patterns", ",", "exclude_patterns", "=", "None", ")", ":", "if", "not", "exclude_patterns", ":", "exclude_patterns", "=", "[", "]", "result", "=", "glob", "(", "roots", ",", "patterns", ",", "exclude_patterns", ")", "subdirs", "=", "[", "s", "for", "s", "in", "glob", "(", "roots", ",", "[", "\"*\"", "]", ",", "exclude_patterns", ")", "if", "s", "!=", "\".\"", "and", "s", "!=", "\"..\"", "and", "os", ".", "path", ".", "isdir", "(", "s", ")", "]", "if", "subdirs", ":", "result", ".", "extend", "(", "glob_tree", "(", "subdirs", ",", "patterns", ",", "exclude_patterns", ")", ")", "return", "result" ]
Recursive version of GLOB. Builds the glob of files while also searching in the subdirectories of the given roots. An optional set of exclusion patterns will filter out the matching entries from the result. The exclusions also apply to the subdirectory scanning, such that directories that match the exclusion patterns will not be searched.
[ "Recursive", "version", "of", "GLOB", ".", "Builds", "the", "glob", "of", "files", "while", "also", "searching", "in", "the", "subdirectories", "of", "the", "given", "roots", ".", "An", "optional", "set", "of", "exclusion", "patterns", "will", "filter", "out", "the", "matching", "entries", "from", "the", "result", ".", "The", "exclusions", "also", "apply", "to", "the", "subdirectory", "scanning", "such", "that", "directories", "that", "match", "the", "exclusion", "patterns", "will", "not", "be", "searched", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/path.py#L872-L888
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/util/path.py
glob_in_parents
def glob_in_parents(dir, patterns, upper_limit=None): """Recursive version of GLOB which glob sall parent directories of dir until the first match is found. Returns an empty result if no match is found""" assert(isinstance(dir, str)) assert(isinstance(patterns, list)) result = [] absolute_dir = os.path.join(os.getcwd(), dir) absolute_dir = os.path.normpath(absolute_dir) while absolute_dir: new_dir = os.path.split(absolute_dir)[0] if new_dir == absolute_dir: break result = glob([new_dir], patterns) if result: break absolute_dir = new_dir return result
python
def glob_in_parents(dir, patterns, upper_limit=None): """Recursive version of GLOB which glob sall parent directories of dir until the first match is found. Returns an empty result if no match is found""" assert(isinstance(dir, str)) assert(isinstance(patterns, list)) result = [] absolute_dir = os.path.join(os.getcwd(), dir) absolute_dir = os.path.normpath(absolute_dir) while absolute_dir: new_dir = os.path.split(absolute_dir)[0] if new_dir == absolute_dir: break result = glob([new_dir], patterns) if result: break absolute_dir = new_dir return result
[ "def", "glob_in_parents", "(", "dir", ",", "patterns", ",", "upper_limit", "=", "None", ")", ":", "assert", "(", "isinstance", "(", "dir", ",", "str", ")", ")", "assert", "(", "isinstance", "(", "patterns", ",", "list", ")", ")", "result", "=", "[", "]", "absolute_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "dir", ")", "absolute_dir", "=", "os", ".", "path", ".", "normpath", "(", "absolute_dir", ")", "while", "absolute_dir", ":", "new_dir", "=", "os", ".", "path", ".", "split", "(", "absolute_dir", ")", "[", "0", "]", "if", "new_dir", "==", "absolute_dir", ":", "break", "result", "=", "glob", "(", "[", "new_dir", "]", ",", "patterns", ")", "if", "result", ":", "break", "absolute_dir", "=", "new_dir", "return", "result" ]
Recursive version of GLOB which glob sall parent directories of dir until the first match is found. Returns an empty result if no match is found
[ "Recursive", "version", "of", "GLOB", "which", "glob", "sall", "parent", "directories", "of", "dir", "until", "the", "first", "match", "is", "found", ".", "Returns", "an", "empty", "result", "if", "no", "match", "is", "found" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/path.py#L890-L911
train
apple/turicreate
src/unity/python/turicreate/extensions.py
_wrap_function_return
def _wrap_function_return(val): """ Recursively walks each thing in val, opening lists and dictionaries, converting all occurrences of UnityGraphProxy to an SGraph, UnitySFrameProxy to SFrame, and UnitySArrayProxy to SArray. """ if type(val) is _UnityGraphProxy: return _SGraph(_proxy = val) elif type(val) is _UnitySFrameProxy: return _SFrame(_proxy = val) elif type(val) is _UnitySArrayProxy: return _SArray(_proxy = val) elif type(val) is _UnityModel: # we need to cast it up to the appropriate type uid = val.get_uid() if uid in class_uid_to_class: return class_uid_to_class[uid](_proxy=val) else: return val elif type(val) is list: return [_wrap_function_return(i) for i in val] elif type(val) is dict: return dict( (i, _wrap_function_return(val[i])) for i in val) else: return val
python
def _wrap_function_return(val): """ Recursively walks each thing in val, opening lists and dictionaries, converting all occurrences of UnityGraphProxy to an SGraph, UnitySFrameProxy to SFrame, and UnitySArrayProxy to SArray. """ if type(val) is _UnityGraphProxy: return _SGraph(_proxy = val) elif type(val) is _UnitySFrameProxy: return _SFrame(_proxy = val) elif type(val) is _UnitySArrayProxy: return _SArray(_proxy = val) elif type(val) is _UnityModel: # we need to cast it up to the appropriate type uid = val.get_uid() if uid in class_uid_to_class: return class_uid_to_class[uid](_proxy=val) else: return val elif type(val) is list: return [_wrap_function_return(i) for i in val] elif type(val) is dict: return dict( (i, _wrap_function_return(val[i])) for i in val) else: return val
[ "def", "_wrap_function_return", "(", "val", ")", ":", "if", "type", "(", "val", ")", "is", "_UnityGraphProxy", ":", "return", "_SGraph", "(", "_proxy", "=", "val", ")", "elif", "type", "(", "val", ")", "is", "_UnitySFrameProxy", ":", "return", "_SFrame", "(", "_proxy", "=", "val", ")", "elif", "type", "(", "val", ")", "is", "_UnitySArrayProxy", ":", "return", "_SArray", "(", "_proxy", "=", "val", ")", "elif", "type", "(", "val", ")", "is", "_UnityModel", ":", "# we need to cast it up to the appropriate type", "uid", "=", "val", ".", "get_uid", "(", ")", "if", "uid", "in", "class_uid_to_class", ":", "return", "class_uid_to_class", "[", "uid", "]", "(", "_proxy", "=", "val", ")", "else", ":", "return", "val", "elif", "type", "(", "val", ")", "is", "list", ":", "return", "[", "_wrap_function_return", "(", "i", ")", "for", "i", "in", "val", "]", "elif", "type", "(", "val", ")", "is", "dict", ":", "return", "dict", "(", "(", "i", ",", "_wrap_function_return", "(", "val", "[", "i", "]", ")", ")", "for", "i", "in", "val", ")", "else", ":", "return", "val" ]
Recursively walks each thing in val, opening lists and dictionaries, converting all occurrences of UnityGraphProxy to an SGraph, UnitySFrameProxy to SFrame, and UnitySArrayProxy to SArray.
[ "Recursively", "walks", "each", "thing", "in", "val", "opening", "lists", "and", "dictionaries", "converting", "all", "occurrences", "of", "UnityGraphProxy", "to", "an", "SGraph", "UnitySFrameProxy", "to", "SFrame", "and", "UnitySArrayProxy", "to", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/extensions.py#L82-L107
train
apple/turicreate
src/unity/python/turicreate/extensions.py
_setattr_wrapper
def _setattr_wrapper(mod, key, value): """ A setattr wrapper call used only by _publish(). This ensures that anything published into this module is also published into tc.extensions """ setattr(mod, key, value) if mod == _thismodule: setattr(_sys.modules[__name__], key, value)
python
def _setattr_wrapper(mod, key, value): """ A setattr wrapper call used only by _publish(). This ensures that anything published into this module is also published into tc.extensions """ setattr(mod, key, value) if mod == _thismodule: setattr(_sys.modules[__name__], key, value)
[ "def", "_setattr_wrapper", "(", "mod", ",", "key", ",", "value", ")", ":", "setattr", "(", "mod", ",", "key", ",", "value", ")", "if", "mod", "==", "_thismodule", ":", "setattr", "(", "_sys", ".", "modules", "[", "__name__", "]", ",", "key", ",", "value", ")" ]
A setattr wrapper call used only by _publish(). This ensures that anything published into this module is also published into tc.extensions
[ "A", "setattr", "wrapper", "call", "used", "only", "by", "_publish", "()", ".", "This", "ensures", "that", "anything", "published", "into", "this", "module", "is", "also", "published", "into", "tc", ".", "extensions" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/extensions.py#L109-L116
train
apple/turicreate
src/unity/python/turicreate/extensions.py
_run_toolkit_function
def _run_toolkit_function(fnname, arguments, args, kwargs): """ Dispatches arguments to a toolkit function. Parameters ---------- fnname : string The toolkit function to run arguments : list[string] The list of all the arguments the function takes. args : list The arguments that were passed kwargs : dictionary The keyword arguments that were passed """ # scan for all the arguments in args num_args_got = len(args) + len(kwargs) num_args_required = len(arguments) if num_args_got != num_args_required: raise TypeError("Expecting " + str(num_args_required) + " arguments, got " + str(num_args_got)) ## fill the dict first with the regular args argument_dict = {} for i in range(len(args)): argument_dict[arguments[i]] = args[i] # now fill with the kwargs. for k in kwargs.keys(): if k in argument_dict: raise TypeError("Got multiple values for keyword argument '" + k + "'") argument_dict[k] = kwargs[k] # unwrap it with cython_context(): ret = _get_unity().run_toolkit(fnname, argument_dict) # handle errors if not ret[0]: if len(ret[1]) > 0: raise _ToolkitError(ret[1]) else: raise _ToolkitError("Toolkit failed with unknown error") ret = _wrap_function_return(ret[2]) if type(ret) is dict and 'return_value' in ret: return ret['return_value'] else: return ret
python
def _run_toolkit_function(fnname, arguments, args, kwargs): """ Dispatches arguments to a toolkit function. Parameters ---------- fnname : string The toolkit function to run arguments : list[string] The list of all the arguments the function takes. args : list The arguments that were passed kwargs : dictionary The keyword arguments that were passed """ # scan for all the arguments in args num_args_got = len(args) + len(kwargs) num_args_required = len(arguments) if num_args_got != num_args_required: raise TypeError("Expecting " + str(num_args_required) + " arguments, got " + str(num_args_got)) ## fill the dict first with the regular args argument_dict = {} for i in range(len(args)): argument_dict[arguments[i]] = args[i] # now fill with the kwargs. for k in kwargs.keys(): if k in argument_dict: raise TypeError("Got multiple values for keyword argument '" + k + "'") argument_dict[k] = kwargs[k] # unwrap it with cython_context(): ret = _get_unity().run_toolkit(fnname, argument_dict) # handle errors if not ret[0]: if len(ret[1]) > 0: raise _ToolkitError(ret[1]) else: raise _ToolkitError("Toolkit failed with unknown error") ret = _wrap_function_return(ret[2]) if type(ret) is dict and 'return_value' in ret: return ret['return_value'] else: return ret
[ "def", "_run_toolkit_function", "(", "fnname", ",", "arguments", ",", "args", ",", "kwargs", ")", ":", "# scan for all the arguments in args", "num_args_got", "=", "len", "(", "args", ")", "+", "len", "(", "kwargs", ")", "num_args_required", "=", "len", "(", "arguments", ")", "if", "num_args_got", "!=", "num_args_required", ":", "raise", "TypeError", "(", "\"Expecting \"", "+", "str", "(", "num_args_required", ")", "+", "\" arguments, got \"", "+", "str", "(", "num_args_got", ")", ")", "## fill the dict first with the regular args", "argument_dict", "=", "{", "}", "for", "i", "in", "range", "(", "len", "(", "args", ")", ")", ":", "argument_dict", "[", "arguments", "[", "i", "]", "]", "=", "args", "[", "i", "]", "# now fill with the kwargs.", "for", "k", "in", "kwargs", ".", "keys", "(", ")", ":", "if", "k", "in", "argument_dict", ":", "raise", "TypeError", "(", "\"Got multiple values for keyword argument '\"", "+", "k", "+", "\"'\"", ")", "argument_dict", "[", "k", "]", "=", "kwargs", "[", "k", "]", "# unwrap it", "with", "cython_context", "(", ")", ":", "ret", "=", "_get_unity", "(", ")", ".", "run_toolkit", "(", "fnname", ",", "argument_dict", ")", "# handle errors", "if", "not", "ret", "[", "0", "]", ":", "if", "len", "(", "ret", "[", "1", "]", ")", ">", "0", ":", "raise", "_ToolkitError", "(", "ret", "[", "1", "]", ")", "else", ":", "raise", "_ToolkitError", "(", "\"Toolkit failed with unknown error\"", ")", "ret", "=", "_wrap_function_return", "(", "ret", "[", "2", "]", ")", "if", "type", "(", "ret", ")", "is", "dict", "and", "'return_value'", "in", "ret", ":", "return", "ret", "[", "'return_value'", "]", "else", ":", "return", "ret" ]
Dispatches arguments to a toolkit function. Parameters ---------- fnname : string The toolkit function to run arguments : list[string] The list of all the arguments the function takes. args : list The arguments that were passed kwargs : dictionary The keyword arguments that were passed
[ "Dispatches", "arguments", "to", "a", "toolkit", "function", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/extensions.py#L118-L167
train
apple/turicreate
src/unity/python/turicreate/extensions.py
_class_instance_from_name
def _class_instance_from_name(class_name, *arg, **kwarg): """ class_name is of the form modA.modB.modC.class module_path splits on "." and the import_path is then ['modA','modB','modC'] the __import__ call is really annoying but essentially it reads like: import class from modA.modB.modC - Then the module variable points to modC - Then you get the class from the module. """ # we first look in tc.extensions for the class name module_path = class_name.split('.') import_path = module_path[0:-1] module = __import__('.'.join(import_path), fromlist=[module_path[-1]]) class_ = getattr(module, module_path[-1]) instance = class_(*arg, **kwarg) return instance
python
def _class_instance_from_name(class_name, *arg, **kwarg): """ class_name is of the form modA.modB.modC.class module_path splits on "." and the import_path is then ['modA','modB','modC'] the __import__ call is really annoying but essentially it reads like: import class from modA.modB.modC - Then the module variable points to modC - Then you get the class from the module. """ # we first look in tc.extensions for the class name module_path = class_name.split('.') import_path = module_path[0:-1] module = __import__('.'.join(import_path), fromlist=[module_path[-1]]) class_ = getattr(module, module_path[-1]) instance = class_(*arg, **kwarg) return instance
[ "def", "_class_instance_from_name", "(", "class_name", ",", "*", "arg", ",", "*", "*", "kwarg", ")", ":", "# we first look in tc.extensions for the class name", "module_path", "=", "class_name", ".", "split", "(", "'.'", ")", "import_path", "=", "module_path", "[", "0", ":", "-", "1", "]", "module", "=", "__import__", "(", "'.'", ".", "join", "(", "import_path", ")", ",", "fromlist", "=", "[", "module_path", "[", "-", "1", "]", "]", ")", "class_", "=", "getattr", "(", "module", ",", "module_path", "[", "-", "1", "]", ")", "instance", "=", "class_", "(", "*", "arg", ",", "*", "*", "kwarg", ")", "return", "instance" ]
class_name is of the form modA.modB.modC.class module_path splits on "." and the import_path is then ['modA','modB','modC'] the __import__ call is really annoying but essentially it reads like: import class from modA.modB.modC - Then the module variable points to modC - Then you get the class from the module.
[ "class_name", "is", "of", "the", "form", "modA", ".", "modB", ".", "modC", ".", "class", "module_path", "splits", "on", ".", "and", "the", "import_path", "is", "then", "[", "modA", "modB", "modC", "]", "the", "__import__", "call", "is", "really", "annoying", "but", "essentially", "it", "reads", "like", ":" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/extensions.py#L172-L190
train
apple/turicreate
src/unity/python/turicreate/extensions.py
_create_class_instance
def _create_class_instance(class_name, _proxy): """ Look for the class in .extensions in case it has already been imported (perhaps as a builtin extensions hard compiled into unity_server). """ try: return _class_instance_from_name('turicreate.extensions.' + class_name, _proxy=_proxy) except: pass return _class_instance_from_name(class_name, _proxy=_proxy)
python
def _create_class_instance(class_name, _proxy): """ Look for the class in .extensions in case it has already been imported (perhaps as a builtin extensions hard compiled into unity_server). """ try: return _class_instance_from_name('turicreate.extensions.' + class_name, _proxy=_proxy) except: pass return _class_instance_from_name(class_name, _proxy=_proxy)
[ "def", "_create_class_instance", "(", "class_name", ",", "_proxy", ")", ":", "try", ":", "return", "_class_instance_from_name", "(", "'turicreate.extensions.'", "+", "class_name", ",", "_proxy", "=", "_proxy", ")", "except", ":", "pass", "return", "_class_instance_from_name", "(", "class_name", ",", "_proxy", "=", "_proxy", ")" ]
Look for the class in .extensions in case it has already been imported (perhaps as a builtin extensions hard compiled into unity_server).
[ "Look", "for", "the", "class", "in", ".", "extensions", "in", "case", "it", "has", "already", "been", "imported", "(", "perhaps", "as", "a", "builtin", "extensions", "hard", "compiled", "into", "unity_server", ")", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/extensions.py#L192-L201
train
apple/turicreate
src/unity/python/turicreate/extensions.py
_publish
def _publish(): import copy """ Publishes all functions and classes registered in unity_server. The functions and classes will appear in the module turicreate.extensions """ unity = _get_unity() fnlist = unity.list_toolkit_functions() # Loop through all the functions and inject it into # turicreate.extensions.[blah] # Note that [blah] may be somemodule.somefunction # and so the injection has to be # turicreate.extensions.somemodule.somefunction for fn in fnlist: props = unity.describe_toolkit_function(fn) # quit if there is nothing we can process if 'arguments' not in props: continue arguments = props['arguments'] newfunc = _make_injected_function(fn, arguments) newfunc.__doc__ = "Name: " + fn + "\nParameters: " + str(arguments) + "\n" if 'documentation' in props: newfunc.__doc__ += props['documentation'] + "\n" newfunc.__dict__['__glmeta__'] = {'extension_name':fn} modpath = fn.split('.') # walk the module tree mod = _thismodule for path in modpath[:-1]: try: getattr(mod, path) except: _setattr_wrapper(mod, path, _types.ModuleType(name=path)) mod = getattr(mod, path) _setattr_wrapper(mod, modpath[-1], newfunc) # Repeat for classes tkclasslist = unity.list_toolkit_classes() for tkclass in tkclasslist: m = unity.describe_toolkit_class(tkclass) # of v2 type if not ('functions' in m and 'get_properties' in m and 'set_properties' in m and 'uid' in m): continue # create a new class if _version_info.major == 3: new_class = _ToolkitClass.__dict__.copy() del new_class['__dict__'] del new_class['__weakref__'] else: new_class = copy.deepcopy(_ToolkitClass.__dict__) new_class['__init__'] = _types.FunctionType(new_class['__init__'].__code__, new_class['__init__'].__globals__, name='__init__', argdefs=(), closure=()) # rewrite the init method to add the toolkit class name so it will # default construct correctly new_class['__init__'].tkclass_name = tkclass newclass = _class_type(tkclass, (), new_class) setattr(newclass, '__glmeta__', {'extension_name':tkclass}) class_uid_to_class[m['uid']] = newclass modpath = tkclass.split('.') # walk the module tree mod = _thismodule for path in modpath[:-1]: try: getattr(mod, path) except: _setattr_wrapper(mod, path, _types.ModuleType(name=path)) mod = getattr(mod, path) _setattr_wrapper(mod, modpath[-1], newclass)
python
def _publish(): import copy """ Publishes all functions and classes registered in unity_server. The functions and classes will appear in the module turicreate.extensions """ unity = _get_unity() fnlist = unity.list_toolkit_functions() # Loop through all the functions and inject it into # turicreate.extensions.[blah] # Note that [blah] may be somemodule.somefunction # and so the injection has to be # turicreate.extensions.somemodule.somefunction for fn in fnlist: props = unity.describe_toolkit_function(fn) # quit if there is nothing we can process if 'arguments' not in props: continue arguments = props['arguments'] newfunc = _make_injected_function(fn, arguments) newfunc.__doc__ = "Name: " + fn + "\nParameters: " + str(arguments) + "\n" if 'documentation' in props: newfunc.__doc__ += props['documentation'] + "\n" newfunc.__dict__['__glmeta__'] = {'extension_name':fn} modpath = fn.split('.') # walk the module tree mod = _thismodule for path in modpath[:-1]: try: getattr(mod, path) except: _setattr_wrapper(mod, path, _types.ModuleType(name=path)) mod = getattr(mod, path) _setattr_wrapper(mod, modpath[-1], newfunc) # Repeat for classes tkclasslist = unity.list_toolkit_classes() for tkclass in tkclasslist: m = unity.describe_toolkit_class(tkclass) # of v2 type if not ('functions' in m and 'get_properties' in m and 'set_properties' in m and 'uid' in m): continue # create a new class if _version_info.major == 3: new_class = _ToolkitClass.__dict__.copy() del new_class['__dict__'] del new_class['__weakref__'] else: new_class = copy.deepcopy(_ToolkitClass.__dict__) new_class['__init__'] = _types.FunctionType(new_class['__init__'].__code__, new_class['__init__'].__globals__, name='__init__', argdefs=(), closure=()) # rewrite the init method to add the toolkit class name so it will # default construct correctly new_class['__init__'].tkclass_name = tkclass newclass = _class_type(tkclass, (), new_class) setattr(newclass, '__glmeta__', {'extension_name':tkclass}) class_uid_to_class[m['uid']] = newclass modpath = tkclass.split('.') # walk the module tree mod = _thismodule for path in modpath[:-1]: try: getattr(mod, path) except: _setattr_wrapper(mod, path, _types.ModuleType(name=path)) mod = getattr(mod, path) _setattr_wrapper(mod, modpath[-1], newclass)
[ "def", "_publish", "(", ")", ":", "import", "copy", "unity", "=", "_get_unity", "(", ")", "fnlist", "=", "unity", ".", "list_toolkit_functions", "(", ")", "# Loop through all the functions and inject it into", "# turicreate.extensions.[blah]", "# Note that [blah] may be somemodule.somefunction", "# and so the injection has to be", "# turicreate.extensions.somemodule.somefunction", "for", "fn", "in", "fnlist", ":", "props", "=", "unity", ".", "describe_toolkit_function", "(", "fn", ")", "# quit if there is nothing we can process", "if", "'arguments'", "not", "in", "props", ":", "continue", "arguments", "=", "props", "[", "'arguments'", "]", "newfunc", "=", "_make_injected_function", "(", "fn", ",", "arguments", ")", "newfunc", ".", "__doc__", "=", "\"Name: \"", "+", "fn", "+", "\"\\nParameters: \"", "+", "str", "(", "arguments", ")", "+", "\"\\n\"", "if", "'documentation'", "in", "props", ":", "newfunc", ".", "__doc__", "+=", "props", "[", "'documentation'", "]", "+", "\"\\n\"", "newfunc", ".", "__dict__", "[", "'__glmeta__'", "]", "=", "{", "'extension_name'", ":", "fn", "}", "modpath", "=", "fn", ".", "split", "(", "'.'", ")", "# walk the module tree", "mod", "=", "_thismodule", "for", "path", "in", "modpath", "[", ":", "-", "1", "]", ":", "try", ":", "getattr", "(", "mod", ",", "path", ")", "except", ":", "_setattr_wrapper", "(", "mod", ",", "path", ",", "_types", ".", "ModuleType", "(", "name", "=", "path", ")", ")", "mod", "=", "getattr", "(", "mod", ",", "path", ")", "_setattr_wrapper", "(", "mod", ",", "modpath", "[", "-", "1", "]", ",", "newfunc", ")", "# Repeat for classes", "tkclasslist", "=", "unity", ".", "list_toolkit_classes", "(", ")", "for", "tkclass", "in", "tkclasslist", ":", "m", "=", "unity", ".", "describe_toolkit_class", "(", "tkclass", ")", "# of v2 type", "if", "not", "(", "'functions'", "in", "m", "and", "'get_properties'", "in", "m", "and", "'set_properties'", "in", "m", "and", "'uid'", "in", "m", ")", ":", "continue", "# create a new class", "if", "_version_info", ".", "major", "==", "3", ":", "new_class", "=", "_ToolkitClass", ".", "__dict__", ".", "copy", "(", ")", "del", "new_class", "[", "'__dict__'", "]", "del", "new_class", "[", "'__weakref__'", "]", "else", ":", "new_class", "=", "copy", ".", "deepcopy", "(", "_ToolkitClass", ".", "__dict__", ")", "new_class", "[", "'__init__'", "]", "=", "_types", ".", "FunctionType", "(", "new_class", "[", "'__init__'", "]", ".", "__code__", ",", "new_class", "[", "'__init__'", "]", ".", "__globals__", ",", "name", "=", "'__init__'", ",", "argdefs", "=", "(", ")", ",", "closure", "=", "(", ")", ")", "# rewrite the init method to add the toolkit class name so it will", "# default construct correctly", "new_class", "[", "'__init__'", "]", ".", "tkclass_name", "=", "tkclass", "newclass", "=", "_class_type", "(", "tkclass", ",", "(", ")", ",", "new_class", ")", "setattr", "(", "newclass", ",", "'__glmeta__'", ",", "{", "'extension_name'", ":", "tkclass", "}", ")", "class_uid_to_class", "[", "m", "[", "'uid'", "]", "]", "=", "newclass", "modpath", "=", "tkclass", ".", "split", "(", "'.'", ")", "# walk the module tree", "mod", "=", "_thismodule", "for", "path", "in", "modpath", "[", ":", "-", "1", "]", ":", "try", ":", "getattr", "(", "mod", ",", "path", ")", "except", ":", "_setattr_wrapper", "(", "mod", ",", "path", ",", "_types", ".", "ModuleType", "(", "name", "=", "path", ")", ")", "mod", "=", "getattr", "(", "mod", ",", "path", ")", "_setattr_wrapper", "(", "mod", ",", "modpath", "[", "-", "1", "]", ",", "newclass", ")" ]
Publishes all functions and classes registered in unity_server. The functions and classes will appear in the module turicreate.extensions
[ "Publishes", "all", "functions", "and", "classes", "registered", "in", "unity_server", ".", "The", "functions", "and", "classes", "will", "appear", "in", "the", "module", "turicreate", ".", "extensions" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/extensions.py#L319-L396
train
apple/turicreate
src/unity/python/turicreate/extensions.py
ext_import
def ext_import(soname, module_subpath=""): """ Loads a turicreate toolkit module (a shared library) into the tc.extensions namespace. Toolkit module created via SDK can either be directly imported, e.g. ``import example`` or via this function, e.g. ``turicreate.ext_import("example.so")``. Use ``ext_import`` when you need more namespace control, or when the shared library is not local, e.g. in http, s3 or hdfs. Parameters ---------- soname : string The filename of the shared library to load. This can be a URL, or a HDFS location. For instance if soname is somewhere/outthere/toolkit.so The functions in toolkit.so will appear in tc.extensions.toolkit.* module_subpath : string, optional Any additional module paths to prepend to the toolkit module after it is imported. For instance if soname is somewhere/outthere/toolkit.so, by default the functions in toolkit.so will appear in tc.extensions.toolkit.*. However, if I module_subpath="somewhere.outthere", the functions in toolkit.so will appear in tc.extensions.somewhere.outthere.toolkit.* Returns ------- out : a list of functions and classes loaded. Examples -------- For instance, given a module which implements the function "square_root", .. code-block:: c++ #include <cmath> #include <turicreate/sdk/toolkit_function_macros.hpp> double square_root(double a) { return sqrt(a); } BEGIN_FUNCTION_REGISTRATION REGISTER_FUNCTION(square_root, "a"); END_FUNCTION_REGISTRATION compiled into example.so >>> turicreate.ext_import('example1.so') ['example1.square_root'] >>> turicreate.extensions.example1.square_root(9) 3.0 We can customize the import location with module_subpath which can be used to avoid namespace conflicts when you have multiple toolkits with the same filename. >>> turicreate.ext_import('example1.so', 'math') ['math.example1.square_root'] >>> turicreate.extensions.math.example1.square_root(9) 3.0 The module can also be imported directly, but turicreate *must* be imported first. turicreate will intercept the module loading process to load the toolkit. >>> import turicreate >>> import example1 #searches for example1.so in all the python paths >>> example1.square_root(9) 3.0 """ unity = _get_unity() import os if os.path.exists(soname): soname = os.path.abspath(soname) else: soname = _make_internal_url(soname) ret = unity.load_toolkit(soname, module_subpath) if len(ret) > 0: raise RuntimeError(ret) _publish() # push the functions into the corresponding module namespace return unity.list_toolkit_functions_in_dynamic_module(soname) + unity.list_toolkit_classes_in_dynamic_module(soname)
python
def ext_import(soname, module_subpath=""): """ Loads a turicreate toolkit module (a shared library) into the tc.extensions namespace. Toolkit module created via SDK can either be directly imported, e.g. ``import example`` or via this function, e.g. ``turicreate.ext_import("example.so")``. Use ``ext_import`` when you need more namespace control, or when the shared library is not local, e.g. in http, s3 or hdfs. Parameters ---------- soname : string The filename of the shared library to load. This can be a URL, or a HDFS location. For instance if soname is somewhere/outthere/toolkit.so The functions in toolkit.so will appear in tc.extensions.toolkit.* module_subpath : string, optional Any additional module paths to prepend to the toolkit module after it is imported. For instance if soname is somewhere/outthere/toolkit.so, by default the functions in toolkit.so will appear in tc.extensions.toolkit.*. However, if I module_subpath="somewhere.outthere", the functions in toolkit.so will appear in tc.extensions.somewhere.outthere.toolkit.* Returns ------- out : a list of functions and classes loaded. Examples -------- For instance, given a module which implements the function "square_root", .. code-block:: c++ #include <cmath> #include <turicreate/sdk/toolkit_function_macros.hpp> double square_root(double a) { return sqrt(a); } BEGIN_FUNCTION_REGISTRATION REGISTER_FUNCTION(square_root, "a"); END_FUNCTION_REGISTRATION compiled into example.so >>> turicreate.ext_import('example1.so') ['example1.square_root'] >>> turicreate.extensions.example1.square_root(9) 3.0 We can customize the import location with module_subpath which can be used to avoid namespace conflicts when you have multiple toolkits with the same filename. >>> turicreate.ext_import('example1.so', 'math') ['math.example1.square_root'] >>> turicreate.extensions.math.example1.square_root(9) 3.0 The module can also be imported directly, but turicreate *must* be imported first. turicreate will intercept the module loading process to load the toolkit. >>> import turicreate >>> import example1 #searches for example1.so in all the python paths >>> example1.square_root(9) 3.0 """ unity = _get_unity() import os if os.path.exists(soname): soname = os.path.abspath(soname) else: soname = _make_internal_url(soname) ret = unity.load_toolkit(soname, module_subpath) if len(ret) > 0: raise RuntimeError(ret) _publish() # push the functions into the corresponding module namespace return unity.list_toolkit_functions_in_dynamic_module(soname) + unity.list_toolkit_classes_in_dynamic_module(soname)
[ "def", "ext_import", "(", "soname", ",", "module_subpath", "=", "\"\"", ")", ":", "unity", "=", "_get_unity", "(", ")", "import", "os", "if", "os", ".", "path", ".", "exists", "(", "soname", ")", ":", "soname", "=", "os", ".", "path", ".", "abspath", "(", "soname", ")", "else", ":", "soname", "=", "_make_internal_url", "(", "soname", ")", "ret", "=", "unity", ".", "load_toolkit", "(", "soname", ",", "module_subpath", ")", "if", "len", "(", "ret", ")", ">", "0", ":", "raise", "RuntimeError", "(", "ret", ")", "_publish", "(", ")", "# push the functions into the corresponding module namespace", "return", "unity", ".", "list_toolkit_functions_in_dynamic_module", "(", "soname", ")", "+", "unity", ".", "list_toolkit_classes_in_dynamic_module", "(", "soname", ")" ]
Loads a turicreate toolkit module (a shared library) into the tc.extensions namespace. Toolkit module created via SDK can either be directly imported, e.g. ``import example`` or via this function, e.g. ``turicreate.ext_import("example.so")``. Use ``ext_import`` when you need more namespace control, or when the shared library is not local, e.g. in http, s3 or hdfs. Parameters ---------- soname : string The filename of the shared library to load. This can be a URL, or a HDFS location. For instance if soname is somewhere/outthere/toolkit.so The functions in toolkit.so will appear in tc.extensions.toolkit.* module_subpath : string, optional Any additional module paths to prepend to the toolkit module after it is imported. For instance if soname is somewhere/outthere/toolkit.so, by default the functions in toolkit.so will appear in tc.extensions.toolkit.*. However, if I module_subpath="somewhere.outthere", the functions in toolkit.so will appear in tc.extensions.somewhere.outthere.toolkit.* Returns ------- out : a list of functions and classes loaded. Examples -------- For instance, given a module which implements the function "square_root", .. code-block:: c++ #include <cmath> #include <turicreate/sdk/toolkit_function_macros.hpp> double square_root(double a) { return sqrt(a); } BEGIN_FUNCTION_REGISTRATION REGISTER_FUNCTION(square_root, "a"); END_FUNCTION_REGISTRATION compiled into example.so >>> turicreate.ext_import('example1.so') ['example1.square_root'] >>> turicreate.extensions.example1.square_root(9) 3.0 We can customize the import location with module_subpath which can be used to avoid namespace conflicts when you have multiple toolkits with the same filename. >>> turicreate.ext_import('example1.so', 'math') ['math.example1.square_root'] >>> turicreate.extensions.math.example1.square_root(9) 3.0 The module can also be imported directly, but turicreate *must* be imported first. turicreate will intercept the module loading process to load the toolkit. >>> import turicreate >>> import example1 #searches for example1.so in all the python paths >>> example1.square_root(9) 3.0
[ "Loads", "a", "turicreate", "toolkit", "module", "(", "a", "shared", "library", ")", "into", "the", "tc", ".", "extensions", "namespace", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/extensions.py#L501-L584
train
apple/turicreate
src/unity/python/turicreate/extensions.py
_get_argument_list_from_toolkit_function_name
def _get_argument_list_from_toolkit_function_name(fn): """ Given a toolkit function name, return the argument list """ unity = _get_unity() fnprops = unity.describe_toolkit_function(fn) argnames = fnprops['arguments'] return argnames
python
def _get_argument_list_from_toolkit_function_name(fn): """ Given a toolkit function name, return the argument list """ unity = _get_unity() fnprops = unity.describe_toolkit_function(fn) argnames = fnprops['arguments'] return argnames
[ "def", "_get_argument_list_from_toolkit_function_name", "(", "fn", ")", ":", "unity", "=", "_get_unity", "(", ")", "fnprops", "=", "unity", ".", "describe_toolkit_function", "(", "fn", ")", "argnames", "=", "fnprops", "[", "'arguments'", "]", "return", "argnames" ]
Given a toolkit function name, return the argument list
[ "Given", "a", "toolkit", "function", "name", "return", "the", "argument", "list" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/extensions.py#L602-L609
train
apple/turicreate
src/unity/python/turicreate/extensions.py
_descend_namespace
def _descend_namespace(caller_globals, name): """ Given a globals dictionary, and a name of the form "a.b.c.d", recursively walk the globals expanding caller_globals['a']['b']['c']['d'] returning the result. Raises an exception (IndexError) on failure. """ names = name.split('.') cur = caller_globals for i in names: if type(cur) is dict: cur = cur[i] else: cur = getattr(cur, i) return cur
python
def _descend_namespace(caller_globals, name): """ Given a globals dictionary, and a name of the form "a.b.c.d", recursively walk the globals expanding caller_globals['a']['b']['c']['d'] returning the result. Raises an exception (IndexError) on failure. """ names = name.split('.') cur = caller_globals for i in names: if type(cur) is dict: cur = cur[i] else: cur = getattr(cur, i) return cur
[ "def", "_descend_namespace", "(", "caller_globals", ",", "name", ")", ":", "names", "=", "name", ".", "split", "(", "'.'", ")", "cur", "=", "caller_globals", "for", "i", "in", "names", ":", "if", "type", "(", "cur", ")", "is", "dict", ":", "cur", "=", "cur", "[", "i", "]", "else", ":", "cur", "=", "getattr", "(", "cur", ",", "i", ")", "return", "cur" ]
Given a globals dictionary, and a name of the form "a.b.c.d", recursively walk the globals expanding caller_globals['a']['b']['c']['d'] returning the result. Raises an exception (IndexError) on failure.
[ "Given", "a", "globals", "dictionary", "and", "a", "name", "of", "the", "form", "a", ".", "b", ".", "c", ".", "d", "recursively", "walk", "the", "globals", "expanding", "caller_globals", "[", "a", "]", "[", "b", "]", "[", "c", "]", "[", "d", "]", "returning", "the", "result", ".", "Raises", "an", "exception", "(", "IndexError", ")", "on", "failure", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/extensions.py#L639-L652
train
apple/turicreate
src/unity/python/turicreate/extensions.py
_build_native_function_call
def _build_native_function_call(fn): """ If fn can be interpreted and handled as a native function: i.e. fn is one of the extensions, or fn is a simple lambda closure using one of the extensions. fn = tc.extensions.add fn = lambda x: tc.extensions.add(5) Then, this returns a closure object, which describes the function call which can then be passed to C++. Returns a _Closure object on success, raises an exception on failure. """ # See if fn is the native function itself native_function_name = _get_toolkit_function_name_from_function(fn) if native_function_name != "": # yup! # generate an "identity" argument list argnames = _get_argument_list_from_toolkit_function_name(native_function_name) arglist = [[0, i] for i in range(len(argnames))] return _Closure(native_function_name, arglist) # ok. its not a native function from .util.lambda_closure_capture import translate from .util.lambda_closure_capture import Parameter # Lets see if it is a simple lambda capture = translate(fn) # ok. build up the closure arguments # Try to pick up the lambda function = _descend_namespace(capture.caller_globals, capture.closure_fn_name) native_function_name = _get_toolkit_function_name_from_function(function) if native_function_name == "": raise RuntimeError("Lambda does not contain a native function") argnames = _get_argument_list_from_toolkit_function_name(native_function_name) # ok. build up the argument list. this is mildly annoying due to the mix of # positional and named arguments # make an argument list with a placeholder for everything first arglist = [[-1, i] for i in argnames] # loop through the positional arguments for i in range(len(capture.positional_args)): arg = capture.positional_args[i] if type(arg) is Parameter: # This is a lambda argument # arg.name is the actual string of the argument # here we need the index arglist[i] = [0, capture.input_arg_names.index(arg.name)] else: # this is a captured value arglist[i] = [1, arg] # now. the named arguments are somewhat annoying for i in capture.named_args: arg = capture.named_args[i] if type(arg) is Parameter: # This is a lambda argument # arg.name is the actual string of the argument # here we need the index arglist[argnames.index(i)] = [0, capture.input_arg_names.index(arg.name)] else: # this is a captured value arglist[argnames.index(i)] = [1, arg] # done. Make sure all arguments are filled for i in arglist: if i[0] == -1: raise RuntimeError("Incomplete function specification") # attempt to recursively break down any other functions import inspect for i in range(len(arglist)): if arglist[i][0] == 1 and inspect.isfunction(arglist[i][1]): try: arglist[i][1] = _build_native_function_call(arglist[i][1]) except: pass return _Closure(native_function_name, arglist)
python
def _build_native_function_call(fn): """ If fn can be interpreted and handled as a native function: i.e. fn is one of the extensions, or fn is a simple lambda closure using one of the extensions. fn = tc.extensions.add fn = lambda x: tc.extensions.add(5) Then, this returns a closure object, which describes the function call which can then be passed to C++. Returns a _Closure object on success, raises an exception on failure. """ # See if fn is the native function itself native_function_name = _get_toolkit_function_name_from_function(fn) if native_function_name != "": # yup! # generate an "identity" argument list argnames = _get_argument_list_from_toolkit_function_name(native_function_name) arglist = [[0, i] for i in range(len(argnames))] return _Closure(native_function_name, arglist) # ok. its not a native function from .util.lambda_closure_capture import translate from .util.lambda_closure_capture import Parameter # Lets see if it is a simple lambda capture = translate(fn) # ok. build up the closure arguments # Try to pick up the lambda function = _descend_namespace(capture.caller_globals, capture.closure_fn_name) native_function_name = _get_toolkit_function_name_from_function(function) if native_function_name == "": raise RuntimeError("Lambda does not contain a native function") argnames = _get_argument_list_from_toolkit_function_name(native_function_name) # ok. build up the argument list. this is mildly annoying due to the mix of # positional and named arguments # make an argument list with a placeholder for everything first arglist = [[-1, i] for i in argnames] # loop through the positional arguments for i in range(len(capture.positional_args)): arg = capture.positional_args[i] if type(arg) is Parameter: # This is a lambda argument # arg.name is the actual string of the argument # here we need the index arglist[i] = [0, capture.input_arg_names.index(arg.name)] else: # this is a captured value arglist[i] = [1, arg] # now. the named arguments are somewhat annoying for i in capture.named_args: arg = capture.named_args[i] if type(arg) is Parameter: # This is a lambda argument # arg.name is the actual string of the argument # here we need the index arglist[argnames.index(i)] = [0, capture.input_arg_names.index(arg.name)] else: # this is a captured value arglist[argnames.index(i)] = [1, arg] # done. Make sure all arguments are filled for i in arglist: if i[0] == -1: raise RuntimeError("Incomplete function specification") # attempt to recursively break down any other functions import inspect for i in range(len(arglist)): if arglist[i][0] == 1 and inspect.isfunction(arglist[i][1]): try: arglist[i][1] = _build_native_function_call(arglist[i][1]) except: pass return _Closure(native_function_name, arglist)
[ "def", "_build_native_function_call", "(", "fn", ")", ":", "# See if fn is the native function itself", "native_function_name", "=", "_get_toolkit_function_name_from_function", "(", "fn", ")", "if", "native_function_name", "!=", "\"\"", ":", "# yup!", "# generate an \"identity\" argument list", "argnames", "=", "_get_argument_list_from_toolkit_function_name", "(", "native_function_name", ")", "arglist", "=", "[", "[", "0", ",", "i", "]", "for", "i", "in", "range", "(", "len", "(", "argnames", ")", ")", "]", "return", "_Closure", "(", "native_function_name", ",", "arglist", ")", "# ok. its not a native function", "from", ".", "util", ".", "lambda_closure_capture", "import", "translate", "from", ".", "util", ".", "lambda_closure_capture", "import", "Parameter", "# Lets see if it is a simple lambda", "capture", "=", "translate", "(", "fn", ")", "# ok. build up the closure arguments", "# Try to pick up the lambda", "function", "=", "_descend_namespace", "(", "capture", ".", "caller_globals", ",", "capture", ".", "closure_fn_name", ")", "native_function_name", "=", "_get_toolkit_function_name_from_function", "(", "function", ")", "if", "native_function_name", "==", "\"\"", ":", "raise", "RuntimeError", "(", "\"Lambda does not contain a native function\"", ")", "argnames", "=", "_get_argument_list_from_toolkit_function_name", "(", "native_function_name", ")", "# ok. build up the argument list. this is mildly annoying due to the mix of", "# positional and named arguments", "# make an argument list with a placeholder for everything first", "arglist", "=", "[", "[", "-", "1", ",", "i", "]", "for", "i", "in", "argnames", "]", "# loop through the positional arguments", "for", "i", "in", "range", "(", "len", "(", "capture", ".", "positional_args", ")", ")", ":", "arg", "=", "capture", ".", "positional_args", "[", "i", "]", "if", "type", "(", "arg", ")", "is", "Parameter", ":", "# This is a lambda argument", "# arg.name is the actual string of the argument", "# here we need the index", "arglist", "[", "i", "]", "=", "[", "0", ",", "capture", ".", "input_arg_names", ".", "index", "(", "arg", ".", "name", ")", "]", "else", ":", "# this is a captured value", "arglist", "[", "i", "]", "=", "[", "1", ",", "arg", "]", "# now. the named arguments are somewhat annoying", "for", "i", "in", "capture", ".", "named_args", ":", "arg", "=", "capture", ".", "named_args", "[", "i", "]", "if", "type", "(", "arg", ")", "is", "Parameter", ":", "# This is a lambda argument", "# arg.name is the actual string of the argument", "# here we need the index", "arglist", "[", "argnames", ".", "index", "(", "i", ")", "]", "=", "[", "0", ",", "capture", ".", "input_arg_names", ".", "index", "(", "arg", ".", "name", ")", "]", "else", ":", "# this is a captured value", "arglist", "[", "argnames", ".", "index", "(", "i", ")", "]", "=", "[", "1", ",", "arg", "]", "# done. Make sure all arguments are filled", "for", "i", "in", "arglist", ":", "if", "i", "[", "0", "]", "==", "-", "1", ":", "raise", "RuntimeError", "(", "\"Incomplete function specification\"", ")", "# attempt to recursively break down any other functions", "import", "inspect", "for", "i", "in", "range", "(", "len", "(", "arglist", ")", ")", ":", "if", "arglist", "[", "i", "]", "[", "0", "]", "==", "1", "and", "inspect", ".", "isfunction", "(", "arglist", "[", "i", "]", "[", "1", "]", ")", ":", "try", ":", "arglist", "[", "i", "]", "[", "1", "]", "=", "_build_native_function_call", "(", "arglist", "[", "i", "]", "[", "1", "]", ")", "except", ":", "pass", "return", "_Closure", "(", "native_function_name", ",", "arglist", ")" ]
If fn can be interpreted and handled as a native function: i.e. fn is one of the extensions, or fn is a simple lambda closure using one of the extensions. fn = tc.extensions.add fn = lambda x: tc.extensions.add(5) Then, this returns a closure object, which describes the function call which can then be passed to C++. Returns a _Closure object on success, raises an exception on failure.
[ "If", "fn", "can", "be", "interpreted", "and", "handled", "as", "a", "native", "function", ":", "i", ".", "e", ".", "fn", "is", "one", "of", "the", "extensions", "or", "fn", "is", "a", "simple", "lambda", "closure", "using", "one", "of", "the", "extensions", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/extensions.py#L654-L734
train
apple/turicreate
src/unity/python/turicreate/extensions.py
_ExtMetaPath.find_module
def find_module(self, fullname, submodule_path=None): """ We have to see if fullname refers to a module we can import. Some care is needed here because: import xxx # tries to load xxx.so from any of the python import paths import aaa.bbb.xxx # tries to load aaa/bbb/xxx.so from any of the python import paths """ # first see if we have this particular so has been loaded by # turicreate's extension library before ret = self.try_find_module(fullname, submodule_path) if ret is not None: return ret # nope. has not been loaded before # lets try to find a ".so" or a ".dylib" if any of the python # locations import sys import os # This drops the last "." So if I am importing aaa.bbb.xxx # module_subpath is aaa.bbb module_subpath = ".".join(fullname.split('.')[:-1]) for path in sys.path: # joins the path to aaa/bbb/xxx pathname = os.path.join(path, os.sep.join(fullname.split('.'))) # try to laod the ".so" extension try: if os.path.exists(pathname + '.so'): ext_import(pathname + '.so', module_subpath) break except: pass # try to laod the ".dylib" extension try: if os.path.exists(pathname + '.dylib'): ext_import(pathname + '.dylib', module_subpath) break except: pass ret = self.try_find_module(fullname, submodule_path) if ret is not None: return ret
python
def find_module(self, fullname, submodule_path=None): """ We have to see if fullname refers to a module we can import. Some care is needed here because: import xxx # tries to load xxx.so from any of the python import paths import aaa.bbb.xxx # tries to load aaa/bbb/xxx.so from any of the python import paths """ # first see if we have this particular so has been loaded by # turicreate's extension library before ret = self.try_find_module(fullname, submodule_path) if ret is not None: return ret # nope. has not been loaded before # lets try to find a ".so" or a ".dylib" if any of the python # locations import sys import os # This drops the last "." So if I am importing aaa.bbb.xxx # module_subpath is aaa.bbb module_subpath = ".".join(fullname.split('.')[:-1]) for path in sys.path: # joins the path to aaa/bbb/xxx pathname = os.path.join(path, os.sep.join(fullname.split('.'))) # try to laod the ".so" extension try: if os.path.exists(pathname + '.so'): ext_import(pathname + '.so', module_subpath) break except: pass # try to laod the ".dylib" extension try: if os.path.exists(pathname + '.dylib'): ext_import(pathname + '.dylib', module_subpath) break except: pass ret = self.try_find_module(fullname, submodule_path) if ret is not None: return ret
[ "def", "find_module", "(", "self", ",", "fullname", ",", "submodule_path", "=", "None", ")", ":", "# first see if we have this particular so has been loaded by", "# turicreate's extension library before", "ret", "=", "self", ".", "try_find_module", "(", "fullname", ",", "submodule_path", ")", "if", "ret", "is", "not", "None", ":", "return", "ret", "# nope. has not been loaded before", "# lets try to find a \".so\" or a \".dylib\" if any of the python", "# locations", "import", "sys", "import", "os", "# This drops the last \".\" So if I am importing aaa.bbb.xxx", "# module_subpath is aaa.bbb", "module_subpath", "=", "\".\"", ".", "join", "(", "fullname", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "for", "path", "in", "sys", ".", "path", ":", "# joins the path to aaa/bbb/xxx", "pathname", "=", "os", ".", "path", ".", "join", "(", "path", ",", "os", ".", "sep", ".", "join", "(", "fullname", ".", "split", "(", "'.'", ")", ")", ")", "# try to laod the \".so\" extension", "try", ":", "if", "os", ".", "path", ".", "exists", "(", "pathname", "+", "'.so'", ")", ":", "ext_import", "(", "pathname", "+", "'.so'", ",", "module_subpath", ")", "break", "except", ":", "pass", "# try to laod the \".dylib\" extension", "try", ":", "if", "os", ".", "path", ".", "exists", "(", "pathname", "+", "'.dylib'", ")", ":", "ext_import", "(", "pathname", "+", "'.dylib'", ",", "module_subpath", ")", "break", "except", ":", "pass", "ret", "=", "self", ".", "try_find_module", "(", "fullname", ",", "submodule_path", ")", "if", "ret", "is", "not", "None", ":", "return", "ret" ]
We have to see if fullname refers to a module we can import. Some care is needed here because: import xxx # tries to load xxx.so from any of the python import paths import aaa.bbb.xxx # tries to load aaa/bbb/xxx.so from any of the python import paths
[ "We", "have", "to", "see", "if", "fullname", "refers", "to", "a", "module", "we", "can", "import", ".", "Some", "care", "is", "needed", "here", "because", ":" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/extensions.py#L409-L450
train
apple/turicreate
src/unity/python/doc/source/sphinx_turicreate_ext/pycon.py
main
def main(): """ Print lines of input along with output. """ source_lines = (line.rstrip() for line in sys.stdin) console = InteractiveInterpreter() console.runsource('import turicreate') source = '' try: while True: source = source_lines.next() more = console.runsource(source) while more: next_line = source_lines.next() print '...', next_line source += '\n' + next_line more = console.runsource(source) except StopIteration: if more: print '... ' more = console.runsource(source + '\n')
python
def main(): """ Print lines of input along with output. """ source_lines = (line.rstrip() for line in sys.stdin) console = InteractiveInterpreter() console.runsource('import turicreate') source = '' try: while True: source = source_lines.next() more = console.runsource(source) while more: next_line = source_lines.next() print '...', next_line source += '\n' + next_line more = console.runsource(source) except StopIteration: if more: print '... ' more = console.runsource(source + '\n')
[ "def", "main", "(", ")", ":", "source_lines", "=", "(", "line", ".", "rstrip", "(", ")", "for", "line", "in", "sys", ".", "stdin", ")", "console", "=", "InteractiveInterpreter", "(", ")", "console", ".", "runsource", "(", "'import turicreate'", ")", "source", "=", "''", "try", ":", "while", "True", ":", "source", "=", "source_lines", ".", "next", "(", ")", "more", "=", "console", ".", "runsource", "(", "source", ")", "while", "more", ":", "next_line", "=", "source_lines", ".", "next", "(", ")", "print", "'...'", ",", "next_line", "source", "+=", "'\\n'", "+", "next_line", "more", "=", "console", ".", "runsource", "(", "source", ")", "except", "StopIteration", ":", "if", "more", ":", "print", "'... '", "more", "=", "console", ".", "runsource", "(", "source", "+", "'\\n'", ")" ]
Print lines of input along with output.
[ "Print", "lines", "of", "input", "along", "with", "output", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/doc/source/sphinx_turicreate_ext/pycon.py#L10-L30
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/type_checkers.py
GetTypeChecker
def GetTypeChecker(field): """Returns a type checker for a message field of the specified types. Args: field: FieldDescriptor object for this field. Returns: An instance of TypeChecker which can be used to verify the types of values assigned to a field of the specified type. """ if (field.cpp_type == _FieldDescriptor.CPPTYPE_STRING and field.type == _FieldDescriptor.TYPE_STRING): return UnicodeValueChecker() if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM: if SupportsOpenEnums(field): # When open enums are supported, any int32 can be assigned. return _VALUE_CHECKERS[_FieldDescriptor.CPPTYPE_INT32] else: return EnumValueChecker(field.enum_type) return _VALUE_CHECKERS[field.cpp_type]
python
def GetTypeChecker(field): """Returns a type checker for a message field of the specified types. Args: field: FieldDescriptor object for this field. Returns: An instance of TypeChecker which can be used to verify the types of values assigned to a field of the specified type. """ if (field.cpp_type == _FieldDescriptor.CPPTYPE_STRING and field.type == _FieldDescriptor.TYPE_STRING): return UnicodeValueChecker() if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM: if SupportsOpenEnums(field): # When open enums are supported, any int32 can be assigned. return _VALUE_CHECKERS[_FieldDescriptor.CPPTYPE_INT32] else: return EnumValueChecker(field.enum_type) return _VALUE_CHECKERS[field.cpp_type]
[ "def", "GetTypeChecker", "(", "field", ")", ":", "if", "(", "field", ".", "cpp_type", "==", "_FieldDescriptor", ".", "CPPTYPE_STRING", "and", "field", ".", "type", "==", "_FieldDescriptor", ".", "TYPE_STRING", ")", ":", "return", "UnicodeValueChecker", "(", ")", "if", "field", ".", "cpp_type", "==", "_FieldDescriptor", ".", "CPPTYPE_ENUM", ":", "if", "SupportsOpenEnums", "(", "field", ")", ":", "# When open enums are supported, any int32 can be assigned.", "return", "_VALUE_CHECKERS", "[", "_FieldDescriptor", ".", "CPPTYPE_INT32", "]", "else", ":", "return", "EnumValueChecker", "(", "field", ".", "enum_type", ")", "return", "_VALUE_CHECKERS", "[", "field", ".", "cpp_type", "]" ]
Returns a type checker for a message field of the specified types. Args: field: FieldDescriptor object for this field. Returns: An instance of TypeChecker which can be used to verify the types of values assigned to a field of the specified type.
[ "Returns", "a", "type", "checker", "for", "a", "message", "field", "of", "the", "specified", "types", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/type_checkers.py#L65-L84
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/type_checkers.py
TypeChecker.CheckValue
def CheckValue(self, proposed_value): """Type check the provided value and return it. The returned value might have been normalized to another type. """ if not isinstance(proposed_value, self._acceptable_types): message = ('%.1024r has type %s, but expected one of: %s' % (proposed_value, type(proposed_value), self._acceptable_types)) raise TypeError(message) return proposed_value
python
def CheckValue(self, proposed_value): """Type check the provided value and return it. The returned value might have been normalized to another type. """ if not isinstance(proposed_value, self._acceptable_types): message = ('%.1024r has type %s, but expected one of: %s' % (proposed_value, type(proposed_value), self._acceptable_types)) raise TypeError(message) return proposed_value
[ "def", "CheckValue", "(", "self", ",", "proposed_value", ")", ":", "if", "not", "isinstance", "(", "proposed_value", ",", "self", ".", "_acceptable_types", ")", ":", "message", "=", "(", "'%.1024r has type %s, but expected one of: %s'", "%", "(", "proposed_value", ",", "type", "(", "proposed_value", ")", ",", "self", ".", "_acceptable_types", ")", ")", "raise", "TypeError", "(", "message", ")", "return", "proposed_value" ]
Type check the provided value and return it. The returned value might have been normalized to another type.
[ "Type", "check", "the", "provided", "value", "and", "return", "it", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/type_checkers.py#L101-L110
train
apple/turicreate
src/unity/python/turicreate/meta/asttools/visitors/pysourcegen.py
python_source
def python_source(ast, file=sys.stdout): ''' Generate executable python source code from an ast node. :param ast: ast node :param file: file to write output to. ''' gen = SourceGen() gen.visit(ast) gen.dump(file)
python
def python_source(ast, file=sys.stdout): ''' Generate executable python source code from an ast node. :param ast: ast node :param file: file to write output to. ''' gen = SourceGen() gen.visit(ast) gen.dump(file)
[ "def", "python_source", "(", "ast", ",", "file", "=", "sys", ".", "stdout", ")", ":", "gen", "=", "SourceGen", "(", ")", "gen", ".", "visit", "(", "ast", ")", "gen", ".", "dump", "(", "file", ")" ]
Generate executable python source code from an ast node. :param ast: ast node :param file: file to write output to.
[ "Generate", "executable", "python", "source", "code", "from", "an", "ast", "node", ".", ":", "param", "ast", ":", "ast", "node", ":", "param", "file", ":", "file", "to", "write", "output", "to", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/asttools/visitors/pysourcegen.py#L854-L863
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_encoding.py
CEscape
def CEscape(text, as_utf8): """Escape a bytes string for use in an ascii protocol buffer. text.encode('string_escape') does not seem to satisfy our needs as it encodes unprintable characters using two-digit hex escapes whereas our C++ unescaping function allows hex escapes to be any length. So, "\0011".encode('string_escape') ends up being "\\x011", which will be decoded in C++ as a single-character string with char code 0x11. Args: text: A byte string to be escaped as_utf8: Specifies if result should be returned in UTF-8 encoding Returns: Escaped string """ # PY3 hack: make Ord work for str and bytes: # //platforms/networking/data uses unicode here, hence basestring. Ord = ord if isinstance(text, six.string_types) else lambda x: x if as_utf8: return ''.join(_cescape_utf8_to_str[Ord(c)] for c in text) return ''.join(_cescape_byte_to_str[Ord(c)] for c in text)
python
def CEscape(text, as_utf8): """Escape a bytes string for use in an ascii protocol buffer. text.encode('string_escape') does not seem to satisfy our needs as it encodes unprintable characters using two-digit hex escapes whereas our C++ unescaping function allows hex escapes to be any length. So, "\0011".encode('string_escape') ends up being "\\x011", which will be decoded in C++ as a single-character string with char code 0x11. Args: text: A byte string to be escaped as_utf8: Specifies if result should be returned in UTF-8 encoding Returns: Escaped string """ # PY3 hack: make Ord work for str and bytes: # //platforms/networking/data uses unicode here, hence basestring. Ord = ord if isinstance(text, six.string_types) else lambda x: x if as_utf8: return ''.join(_cescape_utf8_to_str[Ord(c)] for c in text) return ''.join(_cescape_byte_to_str[Ord(c)] for c in text)
[ "def", "CEscape", "(", "text", ",", "as_utf8", ")", ":", "# PY3 hack: make Ord work for str and bytes:", "# //platforms/networking/data uses unicode here, hence basestring.", "Ord", "=", "ord", "if", "isinstance", "(", "text", ",", "six", ".", "string_types", ")", "else", "lambda", "x", ":", "x", "if", "as_utf8", ":", "return", "''", ".", "join", "(", "_cescape_utf8_to_str", "[", "Ord", "(", "c", ")", "]", "for", "c", "in", "text", ")", "return", "''", ".", "join", "(", "_cescape_byte_to_str", "[", "Ord", "(", "c", ")", "]", "for", "c", "in", "text", ")" ]
Escape a bytes string for use in an ascii protocol buffer. text.encode('string_escape') does not seem to satisfy our needs as it encodes unprintable characters using two-digit hex escapes whereas our C++ unescaping function allows hex escapes to be any length. So, "\0011".encode('string_escape') ends up being "\\x011", which will be decoded in C++ as a single-character string with char code 0x11. Args: text: A byte string to be escaped as_utf8: Specifies if result should be returned in UTF-8 encoding Returns: Escaped string
[ "Escape", "a", "bytes", "string", "for", "use", "in", "an", "ascii", "protocol", "buffer", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_encoding.py#L59-L79
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_encoding.py
CUnescape
def CUnescape(text): """Unescape a text string with C-style escape sequences to UTF-8 bytes.""" def ReplaceHex(m): # Only replace the match if the number of leading back slashes is odd. i.e. # the slash itself is not escaped. if len(m.group(1)) & 1: return m.group(1) + 'x0' + m.group(2) return m.group(0) # This is required because the 'string_escape' encoding doesn't # allow single-digit hex escapes (like '\xf'). result = _CUNESCAPE_HEX.sub(ReplaceHex, text) if str is bytes: # PY2 return result.decode('string_escape') result = ''.join(_cescape_highbit_to_str[ord(c)] for c in result) return (result.encode('ascii') # Make it bytes to allow decode. .decode('unicode_escape') # Make it bytes again to return the proper type. .encode('raw_unicode_escape'))
python
def CUnescape(text): """Unescape a text string with C-style escape sequences to UTF-8 bytes.""" def ReplaceHex(m): # Only replace the match if the number of leading back slashes is odd. i.e. # the slash itself is not escaped. if len(m.group(1)) & 1: return m.group(1) + 'x0' + m.group(2) return m.group(0) # This is required because the 'string_escape' encoding doesn't # allow single-digit hex escapes (like '\xf'). result = _CUNESCAPE_HEX.sub(ReplaceHex, text) if str is bytes: # PY2 return result.decode('string_escape') result = ''.join(_cescape_highbit_to_str[ord(c)] for c in result) return (result.encode('ascii') # Make it bytes to allow decode. .decode('unicode_escape') # Make it bytes again to return the proper type. .encode('raw_unicode_escape'))
[ "def", "CUnescape", "(", "text", ")", ":", "def", "ReplaceHex", "(", "m", ")", ":", "# Only replace the match if the number of leading back slashes is odd. i.e.", "# the slash itself is not escaped.", "if", "len", "(", "m", ".", "group", "(", "1", ")", ")", "&", "1", ":", "return", "m", ".", "group", "(", "1", ")", "+", "'x0'", "+", "m", ".", "group", "(", "2", ")", "return", "m", ".", "group", "(", "0", ")", "# This is required because the 'string_escape' encoding doesn't", "# allow single-digit hex escapes (like '\\xf').", "result", "=", "_CUNESCAPE_HEX", ".", "sub", "(", "ReplaceHex", ",", "text", ")", "if", "str", "is", "bytes", ":", "# PY2", "return", "result", ".", "decode", "(", "'string_escape'", ")", "result", "=", "''", ".", "join", "(", "_cescape_highbit_to_str", "[", "ord", "(", "c", ")", "]", "for", "c", "in", "result", ")", "return", "(", "result", ".", "encode", "(", "'ascii'", ")", "# Make it bytes to allow decode.", ".", "decode", "(", "'unicode_escape'", ")", "# Make it bytes again to return the proper type.", ".", "encode", "(", "'raw_unicode_escape'", ")", ")" ]
Unescape a text string with C-style escape sequences to UTF-8 bytes.
[ "Unescape", "a", "text", "string", "with", "C", "-", "style", "escape", "sequences", "to", "UTF", "-", "8", "bytes", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_encoding.py#L87-L107
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/type.py
reset
def reset (): """ Clear the module state. This is mainly for testing purposes. Note that this must be called _after_ resetting the module 'feature'. """ global __prefixes_suffixes, __suffixes_to_types, __types, __rule_names_to_types, __target_suffixes_cache __register_features () # Stores suffixes for generated targets. __prefixes_suffixes = [property.PropertyMap(), property.PropertyMap()] # Maps suffixes to types __suffixes_to_types = {} # A map with all the registered types, indexed by the type name # Each entry is a dictionary with following values: # 'base': the name of base type or None if type has no base # 'derived': a list of names of type which derive from this one # 'scanner': the scanner class registered for this type, if any __types = {} # Caches suffixes for targets with certain properties. __target_suffixes_cache = {}
python
def reset (): """ Clear the module state. This is mainly for testing purposes. Note that this must be called _after_ resetting the module 'feature'. """ global __prefixes_suffixes, __suffixes_to_types, __types, __rule_names_to_types, __target_suffixes_cache __register_features () # Stores suffixes for generated targets. __prefixes_suffixes = [property.PropertyMap(), property.PropertyMap()] # Maps suffixes to types __suffixes_to_types = {} # A map with all the registered types, indexed by the type name # Each entry is a dictionary with following values: # 'base': the name of base type or None if type has no base # 'derived': a list of names of type which derive from this one # 'scanner': the scanner class registered for this type, if any __types = {} # Caches suffixes for targets with certain properties. __target_suffixes_cache = {}
[ "def", "reset", "(", ")", ":", "global", "__prefixes_suffixes", ",", "__suffixes_to_types", ",", "__types", ",", "__rule_names_to_types", ",", "__target_suffixes_cache", "__register_features", "(", ")", "# Stores suffixes for generated targets.", "__prefixes_suffixes", "=", "[", "property", ".", "PropertyMap", "(", ")", ",", "property", ".", "PropertyMap", "(", ")", "]", "# Maps suffixes to types", "__suffixes_to_types", "=", "{", "}", "# A map with all the registered types, indexed by the type name", "# Each entry is a dictionary with following values:", "# 'base': the name of base type or None if type has no base", "# 'derived': a list of names of type which derive from this one", "# 'scanner': the scanner class registered for this type, if any", "__types", "=", "{", "}", "# Caches suffixes for targets with certain properties.", "__target_suffixes_cache", "=", "{", "}" ]
Clear the module state. This is mainly for testing purposes. Note that this must be called _after_ resetting the module 'feature'.
[ "Clear", "the", "module", "state", ".", "This", "is", "mainly", "for", "testing", "purposes", ".", "Note", "that", "this", "must", "be", "called", "_after_", "resetting", "the", "module", "feature", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/type.py#L32-L54
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/type.py
register
def register (type, suffixes = [], base_type = None): """ Registers a target type, possibly derived from a 'base-type'. If 'suffixes' are provided, they list all the suffixes that mean a file is of 'type'. Also, the first element gives the suffix to be used when constructing and object of 'type'. type: a string suffixes: None or a sequence of strings base_type: None or a string """ # Type names cannot contain hyphens, because when used as # feature-values they will be interpreted as composite features # which need to be decomposed. if __re_hyphen.search (type): raise BaseException ('type name "%s" contains a hyphen' % type) # it's possible for a type to be registered with a # base type that hasn't been registered yet. in the # check for base_type below and the following calls to setdefault() # the key `type` will be added to __types. When the base type # actually gets registered, it would fail after the simple check # of "type in __types"; thus the check for "'base' in __types[type]" if type in __types and 'base' in __types[type]: raise BaseException ('Type "%s" is already registered.' % type) entry = __types.setdefault(type, {}) entry['base'] = base_type entry.setdefault('derived', []) entry.setdefault('scanner', None) if base_type: __types.setdefault(base_type, {}).setdefault('derived', []).append(type) if len (suffixes) > 0: # Generated targets of 'type' will use the first of 'suffixes' # (this may be overriden) set_generated_target_suffix (type, [], suffixes [0]) # Specify mapping from suffixes to type register_suffixes (suffixes, type) feature.extend('target-type', [type]) feature.extend('main-target-type', [type]) feature.extend('base-target-type', [type]) if base_type: feature.compose ('<target-type>' + type, [replace_grist (base_type, '<base-target-type>')]) feature.compose ('<base-target-type>' + type, ['<base-target-type>' + base_type]) import b2.build.generators as generators # Adding a new derived type affects generator selection so we need to # make the generator selection module update any of its cached # information related to a new derived type being defined. generators.update_cached_information_with_a_new_type(type) # FIXME: resolving recursive dependency. from b2.manager import get_manager get_manager().projects().project_rules().add_rule_for_type(type)
python
def register (type, suffixes = [], base_type = None): """ Registers a target type, possibly derived from a 'base-type'. If 'suffixes' are provided, they list all the suffixes that mean a file is of 'type'. Also, the first element gives the suffix to be used when constructing and object of 'type'. type: a string suffixes: None or a sequence of strings base_type: None or a string """ # Type names cannot contain hyphens, because when used as # feature-values they will be interpreted as composite features # which need to be decomposed. if __re_hyphen.search (type): raise BaseException ('type name "%s" contains a hyphen' % type) # it's possible for a type to be registered with a # base type that hasn't been registered yet. in the # check for base_type below and the following calls to setdefault() # the key `type` will be added to __types. When the base type # actually gets registered, it would fail after the simple check # of "type in __types"; thus the check for "'base' in __types[type]" if type in __types and 'base' in __types[type]: raise BaseException ('Type "%s" is already registered.' % type) entry = __types.setdefault(type, {}) entry['base'] = base_type entry.setdefault('derived', []) entry.setdefault('scanner', None) if base_type: __types.setdefault(base_type, {}).setdefault('derived', []).append(type) if len (suffixes) > 0: # Generated targets of 'type' will use the first of 'suffixes' # (this may be overriden) set_generated_target_suffix (type, [], suffixes [0]) # Specify mapping from suffixes to type register_suffixes (suffixes, type) feature.extend('target-type', [type]) feature.extend('main-target-type', [type]) feature.extend('base-target-type', [type]) if base_type: feature.compose ('<target-type>' + type, [replace_grist (base_type, '<base-target-type>')]) feature.compose ('<base-target-type>' + type, ['<base-target-type>' + base_type]) import b2.build.generators as generators # Adding a new derived type affects generator selection so we need to # make the generator selection module update any of its cached # information related to a new derived type being defined. generators.update_cached_information_with_a_new_type(type) # FIXME: resolving recursive dependency. from b2.manager import get_manager get_manager().projects().project_rules().add_rule_for_type(type)
[ "def", "register", "(", "type", ",", "suffixes", "=", "[", "]", ",", "base_type", "=", "None", ")", ":", "# Type names cannot contain hyphens, because when used as", "# feature-values they will be interpreted as composite features", "# which need to be decomposed.", "if", "__re_hyphen", ".", "search", "(", "type", ")", ":", "raise", "BaseException", "(", "'type name \"%s\" contains a hyphen'", "%", "type", ")", "# it's possible for a type to be registered with a", "# base type that hasn't been registered yet. in the", "# check for base_type below and the following calls to setdefault()", "# the key `type` will be added to __types. When the base type", "# actually gets registered, it would fail after the simple check", "# of \"type in __types\"; thus the check for \"'base' in __types[type]\"", "if", "type", "in", "__types", "and", "'base'", "in", "__types", "[", "type", "]", ":", "raise", "BaseException", "(", "'Type \"%s\" is already registered.'", "%", "type", ")", "entry", "=", "__types", ".", "setdefault", "(", "type", ",", "{", "}", ")", "entry", "[", "'base'", "]", "=", "base_type", "entry", ".", "setdefault", "(", "'derived'", ",", "[", "]", ")", "entry", ".", "setdefault", "(", "'scanner'", ",", "None", ")", "if", "base_type", ":", "__types", ".", "setdefault", "(", "base_type", ",", "{", "}", ")", ".", "setdefault", "(", "'derived'", ",", "[", "]", ")", ".", "append", "(", "type", ")", "if", "len", "(", "suffixes", ")", ">", "0", ":", "# Generated targets of 'type' will use the first of 'suffixes'", "# (this may be overriden)", "set_generated_target_suffix", "(", "type", ",", "[", "]", ",", "suffixes", "[", "0", "]", ")", "# Specify mapping from suffixes to type", "register_suffixes", "(", "suffixes", ",", "type", ")", "feature", ".", "extend", "(", "'target-type'", ",", "[", "type", "]", ")", "feature", ".", "extend", "(", "'main-target-type'", ",", "[", "type", "]", ")", "feature", ".", "extend", "(", "'base-target-type'", ",", "[", "type", "]", ")", "if", "base_type", ":", "feature", ".", "compose", "(", "'<target-type>'", "+", "type", ",", "[", "replace_grist", "(", "base_type", ",", "'<base-target-type>'", ")", "]", ")", "feature", ".", "compose", "(", "'<base-target-type>'", "+", "type", ",", "[", "'<base-target-type>'", "+", "base_type", "]", ")", "import", "b2", ".", "build", ".", "generators", "as", "generators", "# Adding a new derived type affects generator selection so we need to", "# make the generator selection module update any of its cached", "# information related to a new derived type being defined.", "generators", ".", "update_cached_information_with_a_new_type", "(", "type", ")", "# FIXME: resolving recursive dependency.", "from", "b2", ".", "manager", "import", "get_manager", "get_manager", "(", ")", ".", "projects", "(", ")", ".", "project_rules", "(", ")", ".", "add_rule_for_type", "(", "type", ")" ]
Registers a target type, possibly derived from a 'base-type'. If 'suffixes' are provided, they list all the suffixes that mean a file is of 'type'. Also, the first element gives the suffix to be used when constructing and object of 'type'. type: a string suffixes: None or a sequence of strings base_type: None or a string
[ "Registers", "a", "target", "type", "possibly", "derived", "from", "a", "base", "-", "type", ".", "If", "suffixes", "are", "provided", "they", "list", "all", "the", "suffixes", "that", "mean", "a", "file", "is", "of", "type", ".", "Also", "the", "first", "element", "gives", "the", "suffix", "to", "be", "used", "when", "constructing", "and", "object", "of", "type", ".", "type", ":", "a", "string", "suffixes", ":", "None", "or", "a", "sequence", "of", "strings", "base_type", ":", "None", "or", "a", "string" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/type.py#L59-L115
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/type.py
register_suffixes
def register_suffixes (suffixes, type): """ Specifies that targets with suffix from 'suffixes' have the type 'type'. If a different type is already specified for any of syffixes, issues an error. """ assert is_iterable_typed(suffixes, basestring) assert isinstance(type, basestring) for s in suffixes: if s in __suffixes_to_types: old_type = __suffixes_to_types [s] if old_type != type: raise BaseException ('Attempting to specify type for suffix "%s"\nOld type: "%s", New type "%s"' % (s, old_type, type)) else: __suffixes_to_types [s] = type
python
def register_suffixes (suffixes, type): """ Specifies that targets with suffix from 'suffixes' have the type 'type'. If a different type is already specified for any of syffixes, issues an error. """ assert is_iterable_typed(suffixes, basestring) assert isinstance(type, basestring) for s in suffixes: if s in __suffixes_to_types: old_type = __suffixes_to_types [s] if old_type != type: raise BaseException ('Attempting to specify type for suffix "%s"\nOld type: "%s", New type "%s"' % (s, old_type, type)) else: __suffixes_to_types [s] = type
[ "def", "register_suffixes", "(", "suffixes", ",", "type", ")", ":", "assert", "is_iterable_typed", "(", "suffixes", ",", "basestring", ")", "assert", "isinstance", "(", "type", ",", "basestring", ")", "for", "s", "in", "suffixes", ":", "if", "s", "in", "__suffixes_to_types", ":", "old_type", "=", "__suffixes_to_types", "[", "s", "]", "if", "old_type", "!=", "type", ":", "raise", "BaseException", "(", "'Attempting to specify type for suffix \"%s\"\\nOld type: \"%s\", New type \"%s\"'", "%", "(", "s", ",", "old_type", ",", "type", ")", ")", "else", ":", "__suffixes_to_types", "[", "s", "]", "=", "type" ]
Specifies that targets with suffix from 'suffixes' have the type 'type'. If a different type is already specified for any of syffixes, issues an error.
[ "Specifies", "that", "targets", "with", "suffix", "from", "suffixes", "have", "the", "type", "type", ".", "If", "a", "different", "type", "is", "already", "specified", "for", "any", "of", "syffixes", "issues", "an", "error", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/type.py#L123-L135
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/type.py
set_scanner
def set_scanner (type, scanner): """ Sets a scanner class that will be used for this 'type'. """ if __debug__: from .scanner import Scanner assert isinstance(type, basestring) assert issubclass(scanner, Scanner) validate (type) __types [type]['scanner'] = scanner
python
def set_scanner (type, scanner): """ Sets a scanner class that will be used for this 'type'. """ if __debug__: from .scanner import Scanner assert isinstance(type, basestring) assert issubclass(scanner, Scanner) validate (type) __types [type]['scanner'] = scanner
[ "def", "set_scanner", "(", "type", ",", "scanner", ")", ":", "if", "__debug__", ":", "from", ".", "scanner", "import", "Scanner", "assert", "isinstance", "(", "type", ",", "basestring", ")", "assert", "issubclass", "(", "scanner", ",", "Scanner", ")", "validate", "(", "type", ")", "__types", "[", "type", "]", "[", "'scanner'", "]", "=", "scanner" ]
Sets a scanner class that will be used for this 'type'.
[ "Sets", "a", "scanner", "class", "that", "will", "be", "used", "for", "this", "type", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/type.py#L150-L158
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/type.py
get_scanner
def get_scanner (type, prop_set): """ Returns a scanner instance appropriate to 'type' and 'property_set'. """ if __debug__: from .property_set import PropertySet assert isinstance(type, basestring) assert isinstance(prop_set, PropertySet) if registered (type): scanner_type = __types [type]['scanner'] if scanner_type: return scanner.get (scanner_type, prop_set.raw ()) pass return None
python
def get_scanner (type, prop_set): """ Returns a scanner instance appropriate to 'type' and 'property_set'. """ if __debug__: from .property_set import PropertySet assert isinstance(type, basestring) assert isinstance(prop_set, PropertySet) if registered (type): scanner_type = __types [type]['scanner'] if scanner_type: return scanner.get (scanner_type, prop_set.raw ()) pass return None
[ "def", "get_scanner", "(", "type", ",", "prop_set", ")", ":", "if", "__debug__", ":", "from", ".", "property_set", "import", "PropertySet", "assert", "isinstance", "(", "type", ",", "basestring", ")", "assert", "isinstance", "(", "prop_set", ",", "PropertySet", ")", "if", "registered", "(", "type", ")", ":", "scanner_type", "=", "__types", "[", "type", "]", "[", "'scanner'", "]", "if", "scanner_type", ":", "return", "scanner", ".", "get", "(", "scanner_type", ",", "prop_set", ".", "raw", "(", ")", ")", "pass", "return", "None" ]
Returns a scanner instance appropriate to 'type' and 'property_set'.
[ "Returns", "a", "scanner", "instance", "appropriate", "to", "type", "and", "property_set", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/type.py#L160-L173
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/type.py
all_bases
def all_bases (type): """ Returns type and all of its bases, in the order of their distance from type. """ assert isinstance(type, basestring) result = [] while type: result.append (type) type = __types [type]['base'] return result
python
def all_bases (type): """ Returns type and all of its bases, in the order of their distance from type. """ assert isinstance(type, basestring) result = [] while type: result.append (type) type = __types [type]['base'] return result
[ "def", "all_bases", "(", "type", ")", ":", "assert", "isinstance", "(", "type", ",", "basestring", ")", "result", "=", "[", "]", "while", "type", ":", "result", ".", "append", "(", "type", ")", "type", "=", "__types", "[", "type", "]", "[", "'base'", "]", "return", "result" ]
Returns type and all of its bases, in the order of their distance from type.
[ "Returns", "type", "and", "all", "of", "its", "bases", "in", "the", "order", "of", "their", "distance", "from", "type", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/type.py#L181-L190
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/type.py
all_derived
def all_derived (type): """ Returns type and all classes that derive from it, in the order of their distance from type. """ assert isinstance(type, basestring) result = [type] for d in __types [type]['derived']: result.extend (all_derived (d)) return result
python
def all_derived (type): """ Returns type and all classes that derive from it, in the order of their distance from type. """ assert isinstance(type, basestring) result = [type] for d in __types [type]['derived']: result.extend (all_derived (d)) return result
[ "def", "all_derived", "(", "type", ")", ":", "assert", "isinstance", "(", "type", ",", "basestring", ")", "result", "=", "[", "type", "]", "for", "d", "in", "__types", "[", "type", "]", "[", "'derived'", "]", ":", "result", ".", "extend", "(", "all_derived", "(", "d", ")", ")", "return", "result" ]
Returns type and all classes that derive from it, in the order of their distance from type.
[ "Returns", "type", "and", "all", "classes", "that", "derive", "from", "it", "in", "the", "order", "of", "their", "distance", "from", "type", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/type.py#L192-L200
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/type.py
is_derived
def is_derived (type, base): """ Returns true if 'type' is 'base' or has 'base' as its direct or indirect base. """ assert isinstance(type, basestring) assert isinstance(base, basestring) # TODO: this isn't very efficient, especially for bases close to type if base in all_bases (type): return True else: return False
python
def is_derived (type, base): """ Returns true if 'type' is 'base' or has 'base' as its direct or indirect base. """ assert isinstance(type, basestring) assert isinstance(base, basestring) # TODO: this isn't very efficient, especially for bases close to type if base in all_bases (type): return True else: return False
[ "def", "is_derived", "(", "type", ",", "base", ")", ":", "assert", "isinstance", "(", "type", ",", "basestring", ")", "assert", "isinstance", "(", "base", ",", "basestring", ")", "# TODO: this isn't very efficient, especially for bases close to type", "if", "base", "in", "all_bases", "(", "type", ")", ":", "return", "True", "else", ":", "return", "False" ]
Returns true if 'type' is 'base' or has 'base' as its direct or indirect base.
[ "Returns", "true", "if", "type", "is", "base", "or", "has", "base", "as", "its", "direct", "or", "indirect", "base", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/type.py#L202-L211
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/type.py
is_subtype
def is_subtype (type, base): """ Same as is_derived. Should be removed. """ assert isinstance(type, basestring) assert isinstance(base, basestring) # TODO: remove this method return is_derived (type, base)
python
def is_subtype (type, base): """ Same as is_derived. Should be removed. """ assert isinstance(type, basestring) assert isinstance(base, basestring) # TODO: remove this method return is_derived (type, base)
[ "def", "is_subtype", "(", "type", ",", "base", ")", ":", "assert", "isinstance", "(", "type", ",", "basestring", ")", "assert", "isinstance", "(", "base", ",", "basestring", ")", "# TODO: remove this method", "return", "is_derived", "(", "type", ",", "base", ")" ]
Same as is_derived. Should be removed.
[ "Same", "as", "is_derived", ".", "Should", "be", "removed", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/type.py#L213-L219
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/type.py
set_generated_target_suffix
def set_generated_target_suffix (type, properties, suffix): """ Sets a target suffix that should be used when generating target of 'type' with the specified properties. Can be called with empty properties if no suffix for 'type' was specified yet. This does not automatically specify that files 'suffix' have 'type' --- two different types can use the same suffix for generating, but only one type should be auto-detected for a file with that suffix. User should explicitly specify which one. The 'suffix' parameter can be empty string ("") to indicate that no suffix should be used. """ assert isinstance(type, basestring) assert is_iterable_typed(properties, basestring) assert isinstance(suffix, basestring) set_generated_target_ps(1, type, properties, suffix)
python
def set_generated_target_suffix (type, properties, suffix): """ Sets a target suffix that should be used when generating target of 'type' with the specified properties. Can be called with empty properties if no suffix for 'type' was specified yet. This does not automatically specify that files 'suffix' have 'type' --- two different types can use the same suffix for generating, but only one type should be auto-detected for a file with that suffix. User should explicitly specify which one. The 'suffix' parameter can be empty string ("") to indicate that no suffix should be used. """ assert isinstance(type, basestring) assert is_iterable_typed(properties, basestring) assert isinstance(suffix, basestring) set_generated_target_ps(1, type, properties, suffix)
[ "def", "set_generated_target_suffix", "(", "type", ",", "properties", ",", "suffix", ")", ":", "assert", "isinstance", "(", "type", ",", "basestring", ")", "assert", "is_iterable_typed", "(", "properties", ",", "basestring", ")", "assert", "isinstance", "(", "suffix", ",", "basestring", ")", "set_generated_target_ps", "(", "1", ",", "type", ",", "properties", ",", "suffix", ")" ]
Sets a target suffix that should be used when generating target of 'type' with the specified properties. Can be called with empty properties if no suffix for 'type' was specified yet. This does not automatically specify that files 'suffix' have 'type' --- two different types can use the same suffix for generating, but only one type should be auto-detected for a file with that suffix. User should explicitly specify which one. The 'suffix' parameter can be empty string ("") to indicate that no suffix should be used.
[ "Sets", "a", "target", "suffix", "that", "should", "be", "used", "when", "generating", "target", "of", "type", "with", "the", "specified", "properties", ".", "Can", "be", "called", "with", "empty", "properties", "if", "no", "suffix", "for", "type", "was", "specified", "yet", ".", "This", "does", "not", "automatically", "specify", "that", "files", "suffix", "have", "type", "---", "two", "different", "types", "can", "use", "the", "same", "suffix", "for", "generating", "but", "only", "one", "type", "should", "be", "auto", "-", "detected", "for", "a", "file", "with", "that", "suffix", ".", "User", "should", "explicitly", "specify", "which", "one", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/type.py#L222-L238
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/type.py
change_generated_target_suffix
def change_generated_target_suffix (type, properties, suffix): """ Change the suffix previously registered for this type/properties combination. If suffix is not yet specified, sets it. """ assert isinstance(type, basestring) assert is_iterable_typed(properties, basestring) assert isinstance(suffix, basestring) change_generated_target_ps(1, type, properties, suffix)
python
def change_generated_target_suffix (type, properties, suffix): """ Change the suffix previously registered for this type/properties combination. If suffix is not yet specified, sets it. """ assert isinstance(type, basestring) assert is_iterable_typed(properties, basestring) assert isinstance(suffix, basestring) change_generated_target_ps(1, type, properties, suffix)
[ "def", "change_generated_target_suffix", "(", "type", ",", "properties", ",", "suffix", ")", ":", "assert", "isinstance", "(", "type", ",", "basestring", ")", "assert", "is_iterable_typed", "(", "properties", ",", "basestring", ")", "assert", "isinstance", "(", "suffix", ",", "basestring", ")", "change_generated_target_ps", "(", "1", ",", "type", ",", "properties", ",", "suffix", ")" ]
Change the suffix previously registered for this type/properties combination. If suffix is not yet specified, sets it.
[ "Change", "the", "suffix", "previously", "registered", "for", "this", "type", "/", "properties", "combination", ".", "If", "suffix", "is", "not", "yet", "specified", "sets", "it", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/type.py#L242-L249
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/type.py
generated_target_ps
def generated_target_ps(is_suffix, type, prop_set): """ Returns suffix that should be used when generating target of 'type', with the specified properties. If not suffix were specified for 'type', returns suffix for base type, if any. """ if __debug__: from .property_set import PropertySet assert isinstance(is_suffix, (int, bool)) assert isinstance(type, basestring) assert isinstance(prop_set, PropertySet) key = (is_suffix, type, prop_set) v = __target_suffixes_cache.get(key, None) if not v: v = generated_target_ps_real(is_suffix, type, prop_set.raw()) __target_suffixes_cache [key] = v return v
python
def generated_target_ps(is_suffix, type, prop_set): """ Returns suffix that should be used when generating target of 'type', with the specified properties. If not suffix were specified for 'type', returns suffix for base type, if any. """ if __debug__: from .property_set import PropertySet assert isinstance(is_suffix, (int, bool)) assert isinstance(type, basestring) assert isinstance(prop_set, PropertySet) key = (is_suffix, type, prop_set) v = __target_suffixes_cache.get(key, None) if not v: v = generated_target_ps_real(is_suffix, type, prop_set.raw()) __target_suffixes_cache [key] = v return v
[ "def", "generated_target_ps", "(", "is_suffix", ",", "type", ",", "prop_set", ")", ":", "if", "__debug__", ":", "from", ".", "property_set", "import", "PropertySet", "assert", "isinstance", "(", "is_suffix", ",", "(", "int", ",", "bool", ")", ")", "assert", "isinstance", "(", "type", ",", "basestring", ")", "assert", "isinstance", "(", "prop_set", ",", "PropertySet", ")", "key", "=", "(", "is_suffix", ",", "type", ",", "prop_set", ")", "v", "=", "__target_suffixes_cache", ".", "get", "(", "key", ",", "None", ")", "if", "not", "v", ":", "v", "=", "generated_target_ps_real", "(", "is_suffix", ",", "type", ",", "prop_set", ".", "raw", "(", ")", ")", "__target_suffixes_cache", "[", "key", "]", "=", "v", "return", "v" ]
Returns suffix that should be used when generating target of 'type', with the specified properties. If not suffix were specified for 'type', returns suffix for base type, if any.
[ "Returns", "suffix", "that", "should", "be", "used", "when", "generating", "target", "of", "type", "with", "the", "specified", "properties", ".", "If", "not", "suffix", "were", "specified", "for", "type", "returns", "suffix", "for", "base", "type", "if", "any", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/type.py#L334-L351
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/type.py
type
def type(filename): """ Returns file type given it's name. If there are several dots in filename, tries each suffix. E.g. for name of "file.so.1.2" suffixes "2", "1", and "so" will be tried. """ assert isinstance(filename, basestring) while 1: filename, suffix = os.path.splitext (filename) if not suffix: return None suffix = suffix[1:] if suffix in __suffixes_to_types: return __suffixes_to_types[suffix]
python
def type(filename): """ Returns file type given it's name. If there are several dots in filename, tries each suffix. E.g. for name of "file.so.1.2" suffixes "2", "1", and "so" will be tried. """ assert isinstance(filename, basestring) while 1: filename, suffix = os.path.splitext (filename) if not suffix: return None suffix = suffix[1:] if suffix in __suffixes_to_types: return __suffixes_to_types[suffix]
[ "def", "type", "(", "filename", ")", ":", "assert", "isinstance", "(", "filename", ",", "basestring", ")", "while", "1", ":", "filename", ",", "suffix", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "not", "suffix", ":", "return", "None", "suffix", "=", "suffix", "[", "1", ":", "]", "if", "suffix", "in", "__suffixes_to_types", ":", "return", "__suffixes_to_types", "[", "suffix", "]" ]
Returns file type given it's name. If there are several dots in filename, tries each suffix. E.g. for name of "file.so.1.2" suffixes "2", "1", and "so" will be tried.
[ "Returns", "file", "type", "given", "it", "s", "name", ".", "If", "there", "are", "several", "dots", "in", "filename", "tries", "each", "suffix", ".", "E", ".", "g", ".", "for", "name", "of", "file", ".", "so", ".", "1", ".", "2", "suffixes", "2", "1", "and", "so", "will", "be", "tried", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/type.py#L353-L365
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/type.py
register_type
def register_type (type, suffixes, base_type = None, os = []): """ Register the given type on the specified OSes, or on remaining OSes if os is not specified. This rule is injected into each of the type modules for the sake of convenience. """ assert isinstance(type, basestring) assert is_iterable_typed(suffixes, basestring) assert isinstance(base_type, basestring) or base_type is None assert is_iterable_typed(os, basestring) if registered (type): return if not os or os_name () in os: register (type, suffixes, base_type)
python
def register_type (type, suffixes, base_type = None, os = []): """ Register the given type on the specified OSes, or on remaining OSes if os is not specified. This rule is injected into each of the type modules for the sake of convenience. """ assert isinstance(type, basestring) assert is_iterable_typed(suffixes, basestring) assert isinstance(base_type, basestring) or base_type is None assert is_iterable_typed(os, basestring) if registered (type): return if not os or os_name () in os: register (type, suffixes, base_type)
[ "def", "register_type", "(", "type", ",", "suffixes", ",", "base_type", "=", "None", ",", "os", "=", "[", "]", ")", ":", "assert", "isinstance", "(", "type", ",", "basestring", ")", "assert", "is_iterable_typed", "(", "suffixes", ",", "basestring", ")", "assert", "isinstance", "(", "base_type", ",", "basestring", ")", "or", "base_type", "is", "None", "assert", "is_iterable_typed", "(", "os", ",", "basestring", ")", "if", "registered", "(", "type", ")", ":", "return", "if", "not", "os", "or", "os_name", "(", ")", "in", "os", ":", "register", "(", "type", ",", "suffixes", ",", "base_type", ")" ]
Register the given type on the specified OSes, or on remaining OSes if os is not specified. This rule is injected into each of the type modules for the sake of convenience.
[ "Register", "the", "given", "type", "on", "the", "specified", "OSes", "or", "on", "remaining", "OSes", "if", "os", "is", "not", "specified", ".", "This", "rule", "is", "injected", "into", "each", "of", "the", "type", "modules", "for", "the", "sake", "of", "convenience", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/type.py#L368-L381
train
apple/turicreate
src/unity/python/turicreate/util/_progress_table_printer.py
ProgressTablePrinter.print_row
def print_row(self, **kwargs): ''' keys of kwargs must be the names passed to __init__(...) as `column_names` ''' meta_string = '|' for key in self.column_names: float_specifier = '' if isinstance(kwargs[key], float): float_specifier = '.3f' meta_string += " {%s:<{width}%s}|" % (key, float_specifier) kwargs['width'] = self.column_width - 1 print(meta_string.format(**kwargs)) print(self.hr)
python
def print_row(self, **kwargs): ''' keys of kwargs must be the names passed to __init__(...) as `column_names` ''' meta_string = '|' for key in self.column_names: float_specifier = '' if isinstance(kwargs[key], float): float_specifier = '.3f' meta_string += " {%s:<{width}%s}|" % (key, float_specifier) kwargs['width'] = self.column_width - 1 print(meta_string.format(**kwargs)) print(self.hr)
[ "def", "print_row", "(", "self", ",", "*", "*", "kwargs", ")", ":", "meta_string", "=", "'|'", "for", "key", "in", "self", ".", "column_names", ":", "float_specifier", "=", "''", "if", "isinstance", "(", "kwargs", "[", "key", "]", ",", "float", ")", ":", "float_specifier", "=", "'.3f'", "meta_string", "+=", "\" {%s:<{width}%s}|\"", "%", "(", "key", ",", "float_specifier", ")", "kwargs", "[", "'width'", "]", "=", "self", ".", "column_width", "-", "1", "print", "(", "meta_string", ".", "format", "(", "*", "*", "kwargs", ")", ")", "print", "(", "self", ".", "hr", ")" ]
keys of kwargs must be the names passed to __init__(...) as `column_names`
[ "keys", "of", "kwargs", "must", "be", "the", "names", "passed", "to", "__init__", "(", "...", ")", "as", "column_names" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/_progress_table_printer.py#L27-L40
train
apple/turicreate
src/unity/python/turicreate/toolkits/_feature_engineering/_internal_utils.py
process_features
def process_features(features, exclude): """ Parameters ---------- features : list[str] | str | None, optional Column names of features to be transformed. If None, all columns are selected. If string, that column is transformed. If list of strings, this list of column names is selected. exclude : list[str] | str | None, optional Column names of features to be ignored in transformation. Can be string or list of strings. Either 'exclude' or 'features' can be passed, but not both. Returns ------- (features, exclude) that are processed. """ # Check types _raise_error_if_not_of_type(features, [NoneType, str, list], 'features') _raise_error_if_not_of_type(exclude, [NoneType, str, list], 'exclude') # Make a copy of the parameters. _features = _copy.copy(features) _exclude = _copy.copy(exclude) # Check of both are None or empty. if _features and _exclude: raise ValueError("The parameters 'features' and 'exclude' cannot both be set." " Please set one or the other.") if _features == [] and not _exclude: raise ValueError("Features cannot be an empty list.") # Allow a single list _features = [_features] if type(_features) == str else _features _exclude = [_exclude] if type(_exclude) == str else _exclude # Type check each feature/exclude if _features: for f in _features: _raise_error_if_not_of_type(f, str, "Feature names") if _exclude: for e in _exclude: _raise_error_if_not_of_type(e, str, "Excluded feature names") if _exclude is not None and _features is not None: feature_set = set(_features) for col_name in _exclude: if col_name in feature_set: raise ValueError("'%s' appears in both features and excluded_features." % col_name) return _features, _exclude
python
def process_features(features, exclude): """ Parameters ---------- features : list[str] | str | None, optional Column names of features to be transformed. If None, all columns are selected. If string, that column is transformed. If list of strings, this list of column names is selected. exclude : list[str] | str | None, optional Column names of features to be ignored in transformation. Can be string or list of strings. Either 'exclude' or 'features' can be passed, but not both. Returns ------- (features, exclude) that are processed. """ # Check types _raise_error_if_not_of_type(features, [NoneType, str, list], 'features') _raise_error_if_not_of_type(exclude, [NoneType, str, list], 'exclude') # Make a copy of the parameters. _features = _copy.copy(features) _exclude = _copy.copy(exclude) # Check of both are None or empty. if _features and _exclude: raise ValueError("The parameters 'features' and 'exclude' cannot both be set." " Please set one or the other.") if _features == [] and not _exclude: raise ValueError("Features cannot be an empty list.") # Allow a single list _features = [_features] if type(_features) == str else _features _exclude = [_exclude] if type(_exclude) == str else _exclude # Type check each feature/exclude if _features: for f in _features: _raise_error_if_not_of_type(f, str, "Feature names") if _exclude: for e in _exclude: _raise_error_if_not_of_type(e, str, "Excluded feature names") if _exclude is not None and _features is not None: feature_set = set(_features) for col_name in _exclude: if col_name in feature_set: raise ValueError("'%s' appears in both features and excluded_features." % col_name) return _features, _exclude
[ "def", "process_features", "(", "features", ",", "exclude", ")", ":", "# Check types", "_raise_error_if_not_of_type", "(", "features", ",", "[", "NoneType", ",", "str", ",", "list", "]", ",", "'features'", ")", "_raise_error_if_not_of_type", "(", "exclude", ",", "[", "NoneType", ",", "str", ",", "list", "]", ",", "'exclude'", ")", "# Make a copy of the parameters.", "_features", "=", "_copy", ".", "copy", "(", "features", ")", "_exclude", "=", "_copy", ".", "copy", "(", "exclude", ")", "# Check of both are None or empty.", "if", "_features", "and", "_exclude", ":", "raise", "ValueError", "(", "\"The parameters 'features' and 'exclude' cannot both be set.\"", "\" Please set one or the other.\"", ")", "if", "_features", "==", "[", "]", "and", "not", "_exclude", ":", "raise", "ValueError", "(", "\"Features cannot be an empty list.\"", ")", "# Allow a single list", "_features", "=", "[", "_features", "]", "if", "type", "(", "_features", ")", "==", "str", "else", "_features", "_exclude", "=", "[", "_exclude", "]", "if", "type", "(", "_exclude", ")", "==", "str", "else", "_exclude", "# Type check each feature/exclude", "if", "_features", ":", "for", "f", "in", "_features", ":", "_raise_error_if_not_of_type", "(", "f", ",", "str", ",", "\"Feature names\"", ")", "if", "_exclude", ":", "for", "e", "in", "_exclude", ":", "_raise_error_if_not_of_type", "(", "e", ",", "str", ",", "\"Excluded feature names\"", ")", "if", "_exclude", "is", "not", "None", "and", "_features", "is", "not", "None", ":", "feature_set", "=", "set", "(", "_features", ")", "for", "col_name", "in", "_exclude", ":", "if", "col_name", "in", "feature_set", ":", "raise", "ValueError", "(", "\"'%s' appears in both features and excluded_features.\"", "%", "col_name", ")", "return", "_features", ",", "_exclude" ]
Parameters ---------- features : list[str] | str | None, optional Column names of features to be transformed. If None, all columns are selected. If string, that column is transformed. If list of strings, this list of column names is selected. exclude : list[str] | str | None, optional Column names of features to be ignored in transformation. Can be string or list of strings. Either 'exclude' or 'features' can be passed, but not both. Returns ------- (features, exclude) that are processed.
[ "Parameters", "----------", "features", ":", "list", "[", "str", "]", "|", "str", "|", "None", "optional", "Column", "names", "of", "features", "to", "be", "transformed", ".", "If", "None", "all", "columns", "are", "selected", ".", "If", "string", "that", "column", "is", "transformed", ".", "If", "list", "of", "strings", "this", "list", "of", "column", "names", "is", "selected", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_feature_engineering/_internal_utils.py#L83-L137
train
apple/turicreate
src/unity/python/turicreate/toolkits/_feature_engineering/_internal_utils.py
pretty_print_list
def pretty_print_list(lst, name = 'features', repr_format=True): """ Pretty print a list to be readable. """ if not lst or len(lst) < 8: if repr_format: return lst.__repr__() else: return ', '.join(map(str, lst)) else: topk = ', '.join(map(str, lst[:3])) if repr_format: lst_separator = "[" lst_end_separator = "]" else: lst_separator = "" lst_end_separator = "" return "{start}{topk}, ... {last}{end} (total {size} {name})".format(\ topk = topk, last = lst[-1], name = name, size = len(lst), start = lst_separator, end = lst_end_separator)
python
def pretty_print_list(lst, name = 'features', repr_format=True): """ Pretty print a list to be readable. """ if not lst or len(lst) < 8: if repr_format: return lst.__repr__() else: return ', '.join(map(str, lst)) else: topk = ', '.join(map(str, lst[:3])) if repr_format: lst_separator = "[" lst_end_separator = "]" else: lst_separator = "" lst_end_separator = "" return "{start}{topk}, ... {last}{end} (total {size} {name})".format(\ topk = topk, last = lst[-1], name = name, size = len(lst), start = lst_separator, end = lst_end_separator)
[ "def", "pretty_print_list", "(", "lst", ",", "name", "=", "'features'", ",", "repr_format", "=", "True", ")", ":", "if", "not", "lst", "or", "len", "(", "lst", ")", "<", "8", ":", "if", "repr_format", ":", "return", "lst", ".", "__repr__", "(", ")", "else", ":", "return", "', '", ".", "join", "(", "map", "(", "str", ",", "lst", ")", ")", "else", ":", "topk", "=", "', '", ".", "join", "(", "map", "(", "str", ",", "lst", "[", ":", "3", "]", ")", ")", "if", "repr_format", ":", "lst_separator", "=", "\"[\"", "lst_end_separator", "=", "\"]\"", "else", ":", "lst_separator", "=", "\"\"", "lst_end_separator", "=", "\"\"", "return", "\"{start}{topk}, ... {last}{end} (total {size} {name})\"", ".", "format", "(", "topk", "=", "topk", ",", "last", "=", "lst", "[", "-", "1", "]", ",", "name", "=", "name", ",", "size", "=", "len", "(", "lst", ")", ",", "start", "=", "lst_separator", ",", "end", "=", "lst_end_separator", ")" ]
Pretty print a list to be readable.
[ "Pretty", "print", "a", "list", "to", "be", "readable", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_feature_engineering/_internal_utils.py#L140-L159
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py
_get_elementwise_name_from_keras_layer
def _get_elementwise_name_from_keras_layer(keras_layer): """ Get the keras layer name from the activation name. """ mode = keras_layer.mode if mode == 'sum': return 'ADD' elif mode == 'mul': return 'MULTIPLY' elif mode == 'concat': if len(keras_layer.input_shape[0]) == 3 and (keras_layer.concat_axis == 1 or keras_layer.concat_axis == -2): return 'SEQUENCE_CONCAT' elif len(keras_layer.input_shape[0]) == 4 and (keras_layer.concat_axis == 3 or keras_layer.concat_axis == -1): return 'CONCAT' elif len(keras_layer.input_shape[0]) == 2 and (keras_layer.concat_axis == 1 or keras_layer.concat_axis == -1): return 'CONCAT' else: option = "input_shape = %s concat_axis = %s" % (str(keras_layer.input_shape[0]), str(keras_layer.concat_axis)) _utils.raise_error_unsupported_option(option, mode, keras_layer.name) elif mode == 'cos': if len(keras_layer.input_shape[0]) == 2: return 'COS' else: option = "input_shape = %s" % (str(keras_layer.input_shape[0])) _utils.raise_error_unsupported_option(option, mode, keras_layer.name) elif mode == 'dot': if len(keras_layer.input_shape[0]) == 2: return 'DOT' else: option = "input_shape = %s" % (str(keras_layer.input_shape[0])) _utils.raise_error_unsupported_option(option, mode, keras_layer.name) elif mode == 'max': return 'MAX' elif mode == 'ave': return 'AVE' else: _utils.raise_error_unsupported_categorical_option('mode', mode, 'Merge', keras_layer.name)
python
def _get_elementwise_name_from_keras_layer(keras_layer): """ Get the keras layer name from the activation name. """ mode = keras_layer.mode if mode == 'sum': return 'ADD' elif mode == 'mul': return 'MULTIPLY' elif mode == 'concat': if len(keras_layer.input_shape[0]) == 3 and (keras_layer.concat_axis == 1 or keras_layer.concat_axis == -2): return 'SEQUENCE_CONCAT' elif len(keras_layer.input_shape[0]) == 4 and (keras_layer.concat_axis == 3 or keras_layer.concat_axis == -1): return 'CONCAT' elif len(keras_layer.input_shape[0]) == 2 and (keras_layer.concat_axis == 1 or keras_layer.concat_axis == -1): return 'CONCAT' else: option = "input_shape = %s concat_axis = %s" % (str(keras_layer.input_shape[0]), str(keras_layer.concat_axis)) _utils.raise_error_unsupported_option(option, mode, keras_layer.name) elif mode == 'cos': if len(keras_layer.input_shape[0]) == 2: return 'COS' else: option = "input_shape = %s" % (str(keras_layer.input_shape[0])) _utils.raise_error_unsupported_option(option, mode, keras_layer.name) elif mode == 'dot': if len(keras_layer.input_shape[0]) == 2: return 'DOT' else: option = "input_shape = %s" % (str(keras_layer.input_shape[0])) _utils.raise_error_unsupported_option(option, mode, keras_layer.name) elif mode == 'max': return 'MAX' elif mode == 'ave': return 'AVE' else: _utils.raise_error_unsupported_categorical_option('mode', mode, 'Merge', keras_layer.name)
[ "def", "_get_elementwise_name_from_keras_layer", "(", "keras_layer", ")", ":", "mode", "=", "keras_layer", ".", "mode", "if", "mode", "==", "'sum'", ":", "return", "'ADD'", "elif", "mode", "==", "'mul'", ":", "return", "'MULTIPLY'", "elif", "mode", "==", "'concat'", ":", "if", "len", "(", "keras_layer", ".", "input_shape", "[", "0", "]", ")", "==", "3", "and", "(", "keras_layer", ".", "concat_axis", "==", "1", "or", "keras_layer", ".", "concat_axis", "==", "-", "2", ")", ":", "return", "'SEQUENCE_CONCAT'", "elif", "len", "(", "keras_layer", ".", "input_shape", "[", "0", "]", ")", "==", "4", "and", "(", "keras_layer", ".", "concat_axis", "==", "3", "or", "keras_layer", ".", "concat_axis", "==", "-", "1", ")", ":", "return", "'CONCAT'", "elif", "len", "(", "keras_layer", ".", "input_shape", "[", "0", "]", ")", "==", "2", "and", "(", "keras_layer", ".", "concat_axis", "==", "1", "or", "keras_layer", ".", "concat_axis", "==", "-", "1", ")", ":", "return", "'CONCAT'", "else", ":", "option", "=", "\"input_shape = %s concat_axis = %s\"", "%", "(", "str", "(", "keras_layer", ".", "input_shape", "[", "0", "]", ")", ",", "str", "(", "keras_layer", ".", "concat_axis", ")", ")", "_utils", ".", "raise_error_unsupported_option", "(", "option", ",", "mode", ",", "keras_layer", ".", "name", ")", "elif", "mode", "==", "'cos'", ":", "if", "len", "(", "keras_layer", ".", "input_shape", "[", "0", "]", ")", "==", "2", ":", "return", "'COS'", "else", ":", "option", "=", "\"input_shape = %s\"", "%", "(", "str", "(", "keras_layer", ".", "input_shape", "[", "0", "]", ")", ")", "_utils", ".", "raise_error_unsupported_option", "(", "option", ",", "mode", ",", "keras_layer", ".", "name", ")", "elif", "mode", "==", "'dot'", ":", "if", "len", "(", "keras_layer", ".", "input_shape", "[", "0", "]", ")", "==", "2", ":", "return", "'DOT'", "else", ":", "option", "=", "\"input_shape = %s\"", "%", "(", "str", "(", "keras_layer", ".", "input_shape", "[", "0", "]", ")", ")", "_utils", ".", "raise_error_unsupported_option", "(", "option", ",", "mode", ",", "keras_layer", ".", "name", ")", "elif", "mode", "==", "'max'", ":", "return", "'MAX'", "elif", "mode", "==", "'ave'", ":", "return", "'AVE'", "else", ":", "_utils", ".", "raise_error_unsupported_categorical_option", "(", "'mode'", ",", "mode", ",", "'Merge'", ",", "keras_layer", ".", "name", ")" ]
Get the keras layer name from the activation name.
[ "Get", "the", "keras", "layer", "name", "from", "the", "activation", "name", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L68-L105
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py
_same_elements_per_channel
def _same_elements_per_channel(x): """ Test if a 3D (H,W,C) matrix x has the same element in each (H,W) matrix for each channel """ eps = 1e-5 dims = x.shape for c in range(dims[-1]): xc = x[:,:,c].flatten() if not np.all(np.absolute(xc - xc[0]) < eps): return False return True
python
def _same_elements_per_channel(x): """ Test if a 3D (H,W,C) matrix x has the same element in each (H,W) matrix for each channel """ eps = 1e-5 dims = x.shape for c in range(dims[-1]): xc = x[:,:,c].flatten() if not np.all(np.absolute(xc - xc[0]) < eps): return False return True
[ "def", "_same_elements_per_channel", "(", "x", ")", ":", "eps", "=", "1e-5", "dims", "=", "x", ".", "shape", "for", "c", "in", "range", "(", "dims", "[", "-", "1", "]", ")", ":", "xc", "=", "x", "[", ":", ",", ":", ",", "c", "]", ".", "flatten", "(", ")", "if", "not", "np", ".", "all", "(", "np", ".", "absolute", "(", "xc", "-", "xc", "[", "0", "]", ")", "<", "eps", ")", ":", "return", "False", "return", "True" ]
Test if a 3D (H,W,C) matrix x has the same element in each (H,W) matrix for each channel
[ "Test", "if", "a", "3D", "(", "H", "W", "C", ")", "matrix", "x", "has", "the", "same", "element", "in", "each", "(", "H", "W", ")", "matrix", "for", "each", "channel" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L107-L117
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py
convert_dense
def convert_dense(builder, layer, input_names, output_names, keras_layer): """Convert a dense layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names input_name, output_name = (input_names[0], output_names[0]) has_bias = keras_layer.bias # Get the weights from keras W = keras_layer.get_weights ()[0].T Wb = keras_layer.get_weights ()[1].T if has_bias else None builder.add_inner_product(name = layer, W = W, b = Wb, input_channels = keras_layer.input_dim, output_channels = keras_layer.output_dim, has_bias = has_bias, input_name = input_name, output_name = output_name)
python
def convert_dense(builder, layer, input_names, output_names, keras_layer): """Convert a dense layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names input_name, output_name = (input_names[0], output_names[0]) has_bias = keras_layer.bias # Get the weights from keras W = keras_layer.get_weights ()[0].T Wb = keras_layer.get_weights ()[1].T if has_bias else None builder.add_inner_product(name = layer, W = W, b = Wb, input_channels = keras_layer.input_dim, output_channels = keras_layer.output_dim, has_bias = has_bias, input_name = input_name, output_name = output_name)
[ "def", "convert_dense", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "# Get input and output names", "input_name", ",", "output_name", "=", "(", "input_names", "[", "0", "]", ",", "output_names", "[", "0", "]", ")", "has_bias", "=", "keras_layer", ".", "bias", "# Get the weights from keras", "W", "=", "keras_layer", ".", "get_weights", "(", ")", "[", "0", "]", ".", "T", "Wb", "=", "keras_layer", ".", "get_weights", "(", ")", "[", "1", "]", ".", "T", "if", "has_bias", "else", "None", "builder", ".", "add_inner_product", "(", "name", "=", "layer", ",", "W", "=", "W", ",", "b", "=", "Wb", ",", "input_channels", "=", "keras_layer", ".", "input_dim", ",", "output_channels", "=", "keras_layer", ".", "output_dim", ",", "has_bias", "=", "has_bias", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ")" ]
Convert a dense layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "a", "dense", "layer", "from", "keras", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L119-L145
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py
convert_activation
def convert_activation(builder, layer, input_names, output_names, keras_layer): """Convert an activation layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names input_name, output_name = (input_names[0], output_names[0]) non_linearity = _get_activation_name_from_keras_layer(keras_layer) # Add a non-linearity layer if non_linearity == 'SOFTMAX': builder.add_softmax(name = layer, input_name = input_name, output_name = output_name) return params = None if non_linearity == 'LEAKYRELU': params = [keras_layer.alpha] elif non_linearity == 'PRELU': # In Keras 1.2 PReLU layer's weights are stored as a # backend tensor, not a numpy array as it claims in documentation. shared_axes = list(keras_layer.shared_axes) if not (shared_axes == [1,2,3] or shared_axes == [1,2]): _utils.raise_error_unsupported_scenario("Shared axis not being [1,2,3] or [1,2]", 'parametric_relu', layer) params = keras.backend.eval(keras_layer.weights[0]) elif non_linearity == 'ELU': params = keras_layer.alpha elif non_linearity == 'PARAMETRICSOFTPLUS': # In Keras 1.2 Parametric Softplus layer's weights are stored as a # backend tensor, not a numpy array as it claims in documentation. alphas = keras.backend.eval(keras_layer.weights[0]) betas = keras.backend.eval(keras_layer.weights[1]) if len(alphas.shape) == 3: # (H,W,C) if not (_same_elements_per_channel(alphas) and _same_elements_per_channel(betas)): _utils.raise_error_unsupported_scenario("Different parameter values", 'parametric_softplus', layer) alphas = alphas[0,0,:] betas = betas[0,0,:] params = [alphas, betas] elif non_linearity == 'THRESHOLDEDRELU': params = keras_layer.theta else: pass # do nothing to parameters builder.add_activation(name = layer, non_linearity = non_linearity, input_name = input_name, output_name = output_name, params = params)
python
def convert_activation(builder, layer, input_names, output_names, keras_layer): """Convert an activation layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names input_name, output_name = (input_names[0], output_names[0]) non_linearity = _get_activation_name_from_keras_layer(keras_layer) # Add a non-linearity layer if non_linearity == 'SOFTMAX': builder.add_softmax(name = layer, input_name = input_name, output_name = output_name) return params = None if non_linearity == 'LEAKYRELU': params = [keras_layer.alpha] elif non_linearity == 'PRELU': # In Keras 1.2 PReLU layer's weights are stored as a # backend tensor, not a numpy array as it claims in documentation. shared_axes = list(keras_layer.shared_axes) if not (shared_axes == [1,2,3] or shared_axes == [1,2]): _utils.raise_error_unsupported_scenario("Shared axis not being [1,2,3] or [1,2]", 'parametric_relu', layer) params = keras.backend.eval(keras_layer.weights[0]) elif non_linearity == 'ELU': params = keras_layer.alpha elif non_linearity == 'PARAMETRICSOFTPLUS': # In Keras 1.2 Parametric Softplus layer's weights are stored as a # backend tensor, not a numpy array as it claims in documentation. alphas = keras.backend.eval(keras_layer.weights[0]) betas = keras.backend.eval(keras_layer.weights[1]) if len(alphas.shape) == 3: # (H,W,C) if not (_same_elements_per_channel(alphas) and _same_elements_per_channel(betas)): _utils.raise_error_unsupported_scenario("Different parameter values", 'parametric_softplus', layer) alphas = alphas[0,0,:] betas = betas[0,0,:] params = [alphas, betas] elif non_linearity == 'THRESHOLDEDRELU': params = keras_layer.theta else: pass # do nothing to parameters builder.add_activation(name = layer, non_linearity = non_linearity, input_name = input_name, output_name = output_name, params = params)
[ "def", "convert_activation", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "# Get input and output names", "input_name", ",", "output_name", "=", "(", "input_names", "[", "0", "]", ",", "output_names", "[", "0", "]", ")", "non_linearity", "=", "_get_activation_name_from_keras_layer", "(", "keras_layer", ")", "# Add a non-linearity layer", "if", "non_linearity", "==", "'SOFTMAX'", ":", "builder", ".", "add_softmax", "(", "name", "=", "layer", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ")", "return", "params", "=", "None", "if", "non_linearity", "==", "'LEAKYRELU'", ":", "params", "=", "[", "keras_layer", ".", "alpha", "]", "elif", "non_linearity", "==", "'PRELU'", ":", "# In Keras 1.2 PReLU layer's weights are stored as a", "# backend tensor, not a numpy array as it claims in documentation.", "shared_axes", "=", "list", "(", "keras_layer", ".", "shared_axes", ")", "if", "not", "(", "shared_axes", "==", "[", "1", ",", "2", ",", "3", "]", "or", "shared_axes", "==", "[", "1", ",", "2", "]", ")", ":", "_utils", ".", "raise_error_unsupported_scenario", "(", "\"Shared axis not being [1,2,3] or [1,2]\"", ",", "'parametric_relu'", ",", "layer", ")", "params", "=", "keras", ".", "backend", ".", "eval", "(", "keras_layer", ".", "weights", "[", "0", "]", ")", "elif", "non_linearity", "==", "'ELU'", ":", "params", "=", "keras_layer", ".", "alpha", "elif", "non_linearity", "==", "'PARAMETRICSOFTPLUS'", ":", "# In Keras 1.2 Parametric Softplus layer's weights are stored as a", "# backend tensor, not a numpy array as it claims in documentation.", "alphas", "=", "keras", ".", "backend", ".", "eval", "(", "keras_layer", ".", "weights", "[", "0", "]", ")", "betas", "=", "keras", ".", "backend", ".", "eval", "(", "keras_layer", ".", "weights", "[", "1", "]", ")", "if", "len", "(", "alphas", ".", "shape", ")", "==", "3", ":", "# (H,W,C)", "if", "not", "(", "_same_elements_per_channel", "(", "alphas", ")", "and", "_same_elements_per_channel", "(", "betas", ")", ")", ":", "_utils", ".", "raise_error_unsupported_scenario", "(", "\"Different parameter values\"", ",", "'parametric_softplus'", ",", "layer", ")", "alphas", "=", "alphas", "[", "0", ",", "0", ",", ":", "]", "betas", "=", "betas", "[", "0", ",", "0", ",", ":", "]", "params", "=", "[", "alphas", ",", "betas", "]", "elif", "non_linearity", "==", "'THRESHOLDEDRELU'", ":", "params", "=", "keras_layer", ".", "theta", "else", ":", "pass", "# do nothing to parameters", "builder", ".", "add_activation", "(", "name", "=", "layer", ",", "non_linearity", "=", "non_linearity", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ",", "params", "=", "params", ")" ]
Convert an activation layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "an", "activation", "layer", "from", "keras", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L147-L202
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py
convert_padding
def convert_padding(builder, layer, input_names, output_names, keras_layer): """Convert padding layer from keras to coreml. Keras only supports zero padding at this time. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names input_name, output_name = (input_names[0], output_names[0]) if isinstance(keras_layer, keras.layers.convolutional.ZeroPadding1D): left, right = keras_layer.padding top, bottom = (0, 0) else: # 2D top, left = keras_layer.padding bottom, right = keras_layer.padding # Now add the layer builder.add_padding(name = layer, left = left, right=right, top=top, bottom=bottom, value = 0, input_name = input_name, output_name=output_name )
python
def convert_padding(builder, layer, input_names, output_names, keras_layer): """Convert padding layer from keras to coreml. Keras only supports zero padding at this time. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names input_name, output_name = (input_names[0], output_names[0]) if isinstance(keras_layer, keras.layers.convolutional.ZeroPadding1D): left, right = keras_layer.padding top, bottom = (0, 0) else: # 2D top, left = keras_layer.padding bottom, right = keras_layer.padding # Now add the layer builder.add_padding(name = layer, left = left, right=right, top=top, bottom=bottom, value = 0, input_name = input_name, output_name=output_name )
[ "def", "convert_padding", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "# Get input and output names", "input_name", ",", "output_name", "=", "(", "input_names", "[", "0", "]", ",", "output_names", "[", "0", "]", ")", "if", "isinstance", "(", "keras_layer", ",", "keras", ".", "layers", ".", "convolutional", ".", "ZeroPadding1D", ")", ":", "left", ",", "right", "=", "keras_layer", ".", "padding", "top", ",", "bottom", "=", "(", "0", ",", "0", ")", "else", ":", "# 2D", "top", ",", "left", "=", "keras_layer", ".", "padding", "bottom", ",", "right", "=", "keras_layer", ".", "padding", "# Now add the layer", "builder", ".", "add_padding", "(", "name", "=", "layer", ",", "left", "=", "left", ",", "right", "=", "right", ",", "top", "=", "top", ",", "bottom", "=", "bottom", ",", "value", "=", "0", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ")" ]
Convert padding layer from keras to coreml. Keras only supports zero padding at this time. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "padding", "layer", "from", "keras", "to", "coreml", ".", "Keras", "only", "supports", "zero", "padding", "at", "this", "time", ".", "Parameters", "----------", "keras_layer", ":", "layer", "A", "keras", "layer", "object", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L309-L334
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py
convert_cropping
def convert_cropping(builder, layer, input_names, output_names, keras_layer): """Convert padding layer from keras to coreml. Keras only supports zero padding at this time. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names input_name, output_name = (input_names[0], output_names[0]) if isinstance(keras_layer, keras.layers.convolutional.Cropping1D): left, right = keras_layer.cropping top, bottom = (0, 0) else: # 2D left, right = keras_layer.cropping[0] top, bottom = keras_layer.cropping[1] # Now add the layer builder.add_crop(name = layer, left = left, right=right, top=top, bottom=bottom, offset = [0,0], input_names = [input_name], output_name=output_name )
python
def convert_cropping(builder, layer, input_names, output_names, keras_layer): """Convert padding layer from keras to coreml. Keras only supports zero padding at this time. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names input_name, output_name = (input_names[0], output_names[0]) if isinstance(keras_layer, keras.layers.convolutional.Cropping1D): left, right = keras_layer.cropping top, bottom = (0, 0) else: # 2D left, right = keras_layer.cropping[0] top, bottom = keras_layer.cropping[1] # Now add the layer builder.add_crop(name = layer, left = left, right=right, top=top, bottom=bottom, offset = [0,0], input_names = [input_name], output_name=output_name )
[ "def", "convert_cropping", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "# Get input and output names", "input_name", ",", "output_name", "=", "(", "input_names", "[", "0", "]", ",", "output_names", "[", "0", "]", ")", "if", "isinstance", "(", "keras_layer", ",", "keras", ".", "layers", ".", "convolutional", ".", "Cropping1D", ")", ":", "left", ",", "right", "=", "keras_layer", ".", "cropping", "top", ",", "bottom", "=", "(", "0", ",", "0", ")", "else", ":", "# 2D", "left", ",", "right", "=", "keras_layer", ".", "cropping", "[", "0", "]", "top", ",", "bottom", "=", "keras_layer", ".", "cropping", "[", "1", "]", "# Now add the layer", "builder", ".", "add_crop", "(", "name", "=", "layer", ",", "left", "=", "left", ",", "right", "=", "right", ",", "top", "=", "top", ",", "bottom", "=", "bottom", ",", "offset", "=", "[", "0", ",", "0", "]", ",", "input_names", "=", "[", "input_name", "]", ",", "output_name", "=", "output_name", ")" ]
Convert padding layer from keras to coreml. Keras only supports zero padding at this time. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "padding", "layer", "from", "keras", "to", "coreml", ".", "Keras", "only", "supports", "zero", "padding", "at", "this", "time", ".", "Parameters", "----------", "keras_layer", ":", "layer", "A", "keras", "layer", "object", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L336-L361
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py
convert_upsample
def convert_upsample(builder, layer, input_names, output_names, keras_layer): """Convert convolution layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names input_name, output_name = (input_names[0], output_names[0]) if isinstance(keras_layer, keras.layers.convolutional.UpSampling1D): fh, fw = 1, keras_layer.length else: # 2D fh, fw = keras_layer.size builder.add_upsample(name = layer, scaling_factor_h = fh, scaling_factor_w = fw, input_name = input_name, output_name = output_name)
python
def convert_upsample(builder, layer, input_names, output_names, keras_layer): """Convert convolution layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names input_name, output_name = (input_names[0], output_names[0]) if isinstance(keras_layer, keras.layers.convolutional.UpSampling1D): fh, fw = 1, keras_layer.length else: # 2D fh, fw = keras_layer.size builder.add_upsample(name = layer, scaling_factor_h = fh, scaling_factor_w = fw, input_name = input_name, output_name = output_name)
[ "def", "convert_upsample", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "# Get input and output names", "input_name", ",", "output_name", "=", "(", "input_names", "[", "0", "]", ",", "output_names", "[", "0", "]", ")", "if", "isinstance", "(", "keras_layer", ",", "keras", ".", "layers", ".", "convolutional", ".", "UpSampling1D", ")", ":", "fh", ",", "fw", "=", "1", ",", "keras_layer", ".", "length", "else", ":", "# 2D", "fh", ",", "fw", "=", "keras_layer", ".", "size", "builder", ".", "add_upsample", "(", "name", "=", "layer", ",", "scaling_factor_h", "=", "fh", ",", "scaling_factor_w", "=", "fw", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ")" ]
Convert convolution layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "convolution", "layer", "from", "keras", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L396-L419
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py
convert_convolution
def convert_convolution(builder, layer, input_names, output_names, keras_layer): """Convert convolution layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names input_name, output_name = (input_names[0], output_names[0]) has_bias = keras_layer.bias is_deconv = isinstance(keras_layer, keras.layers.convolutional.Deconvolution2D) # Get the weights from keras. # Keras stores convolution weights as list of numpy arrays weightList = keras_layer.get_weights() output_shape = list(filter(None, keras_layer.output_shape))[:-1] # Parameter height, width, channels, n_filters = weightList[0].shape stride_height, stride_width = keras_layer.subsample # Weights and bias terms W = weightList[0] b = weightList[1] if has_bias else None # dilation factors dilation_factors = [1,1] if isinstance(keras_layer, keras.layers.convolutional.AtrousConvolution2D): dilation_factors = list(keras_layer.atrous_rate) builder.add_convolution(name = layer, kernel_channels = channels, output_channels = n_filters, height = height, width = width, stride_height = stride_height, stride_width = stride_width, border_mode = keras_layer.border_mode, groups = 1, W = W, b = b, has_bias = has_bias, is_deconv = is_deconv, output_shape = output_shape, input_name = input_name, output_name = output_name, dilation_factors = dilation_factors)
python
def convert_convolution(builder, layer, input_names, output_names, keras_layer): """Convert convolution layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names input_name, output_name = (input_names[0], output_names[0]) has_bias = keras_layer.bias is_deconv = isinstance(keras_layer, keras.layers.convolutional.Deconvolution2D) # Get the weights from keras. # Keras stores convolution weights as list of numpy arrays weightList = keras_layer.get_weights() output_shape = list(filter(None, keras_layer.output_shape))[:-1] # Parameter height, width, channels, n_filters = weightList[0].shape stride_height, stride_width = keras_layer.subsample # Weights and bias terms W = weightList[0] b = weightList[1] if has_bias else None # dilation factors dilation_factors = [1,1] if isinstance(keras_layer, keras.layers.convolutional.AtrousConvolution2D): dilation_factors = list(keras_layer.atrous_rate) builder.add_convolution(name = layer, kernel_channels = channels, output_channels = n_filters, height = height, width = width, stride_height = stride_height, stride_width = stride_width, border_mode = keras_layer.border_mode, groups = 1, W = W, b = b, has_bias = has_bias, is_deconv = is_deconv, output_shape = output_shape, input_name = input_name, output_name = output_name, dilation_factors = dilation_factors)
[ "def", "convert_convolution", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "# Get input and output names", "input_name", ",", "output_name", "=", "(", "input_names", "[", "0", "]", ",", "output_names", "[", "0", "]", ")", "has_bias", "=", "keras_layer", ".", "bias", "is_deconv", "=", "isinstance", "(", "keras_layer", ",", "keras", ".", "layers", ".", "convolutional", ".", "Deconvolution2D", ")", "# Get the weights from keras.", "# Keras stores convolution weights as list of numpy arrays", "weightList", "=", "keras_layer", ".", "get_weights", "(", ")", "output_shape", "=", "list", "(", "filter", "(", "None", ",", "keras_layer", ".", "output_shape", ")", ")", "[", ":", "-", "1", "]", "# Parameter", "height", ",", "width", ",", "channels", ",", "n_filters", "=", "weightList", "[", "0", "]", ".", "shape", "stride_height", ",", "stride_width", "=", "keras_layer", ".", "subsample", "# Weights and bias terms", "W", "=", "weightList", "[", "0", "]", "b", "=", "weightList", "[", "1", "]", "if", "has_bias", "else", "None", "# dilation factors", "dilation_factors", "=", "[", "1", ",", "1", "]", "if", "isinstance", "(", "keras_layer", ",", "keras", ".", "layers", ".", "convolutional", ".", "AtrousConvolution2D", ")", ":", "dilation_factors", "=", "list", "(", "keras_layer", ".", "atrous_rate", ")", "builder", ".", "add_convolution", "(", "name", "=", "layer", ",", "kernel_channels", "=", "channels", ",", "output_channels", "=", "n_filters", ",", "height", "=", "height", ",", "width", "=", "width", ",", "stride_height", "=", "stride_height", ",", "stride_width", "=", "stride_width", ",", "border_mode", "=", "keras_layer", ".", "border_mode", ",", "groups", "=", "1", ",", "W", "=", "W", ",", "b", "=", "b", ",", "has_bias", "=", "has_bias", ",", "is_deconv", "=", "is_deconv", ",", "output_shape", "=", "output_shape", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ",", "dilation_factors", "=", "dilation_factors", ")" ]
Convert convolution layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "convolution", "layer", "from", "keras", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L421-L472
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py
convert_convolution1d
def convert_convolution1d(builder, layer, input_names, output_names, keras_layer): """Convert convolution layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names input_name, output_name = (input_names[0], output_names[0]) has_bias = keras_layer.bias # Get the weights from keras. # Keras stores convolution weights as list of numpy arrays weightList = keras_layer.get_weights() output_shape = list(filter(None, keras_layer.output_shape))[:-1] # Parameter # weightList[0].shape = [kernel_length, input_length(time_step), input_dim, num_kernels] filter_length, input_length, input_dim, n_filters = weightList[0].shape stride_width = keras_layer.subsample[0] # Weights and bias terms W = weightList[0] b = weightList[1] if has_bias else None dilation_factors = [1,1] if isinstance(keras_layer, keras.layers.convolutional.AtrousConvolution1D): dilation_factors[-1] = keras_layer.atrous_rate builder.add_convolution(name = layer, kernel_channels = input_dim, output_channels = n_filters, height = 1, width = filter_length, stride_height = 1, stride_width = stride_width, border_mode = keras_layer.border_mode, groups = 1, W = W, b = b, has_bias = has_bias, is_deconv = False, output_shape = output_shape, input_name = input_name, output_name = output_name, dilation_factors = dilation_factors)
python
def convert_convolution1d(builder, layer, input_names, output_names, keras_layer): """Convert convolution layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names input_name, output_name = (input_names[0], output_names[0]) has_bias = keras_layer.bias # Get the weights from keras. # Keras stores convolution weights as list of numpy arrays weightList = keras_layer.get_weights() output_shape = list(filter(None, keras_layer.output_shape))[:-1] # Parameter # weightList[0].shape = [kernel_length, input_length(time_step), input_dim, num_kernels] filter_length, input_length, input_dim, n_filters = weightList[0].shape stride_width = keras_layer.subsample[0] # Weights and bias terms W = weightList[0] b = weightList[1] if has_bias else None dilation_factors = [1,1] if isinstance(keras_layer, keras.layers.convolutional.AtrousConvolution1D): dilation_factors[-1] = keras_layer.atrous_rate builder.add_convolution(name = layer, kernel_channels = input_dim, output_channels = n_filters, height = 1, width = filter_length, stride_height = 1, stride_width = stride_width, border_mode = keras_layer.border_mode, groups = 1, W = W, b = b, has_bias = has_bias, is_deconv = False, output_shape = output_shape, input_name = input_name, output_name = output_name, dilation_factors = dilation_factors)
[ "def", "convert_convolution1d", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "# Get input and output names", "input_name", ",", "output_name", "=", "(", "input_names", "[", "0", "]", ",", "output_names", "[", "0", "]", ")", "has_bias", "=", "keras_layer", ".", "bias", "# Get the weights from keras.", "# Keras stores convolution weights as list of numpy arrays", "weightList", "=", "keras_layer", ".", "get_weights", "(", ")", "output_shape", "=", "list", "(", "filter", "(", "None", ",", "keras_layer", ".", "output_shape", ")", ")", "[", ":", "-", "1", "]", "# Parameter", "# weightList[0].shape = [kernel_length, input_length(time_step), input_dim, num_kernels]", "filter_length", ",", "input_length", ",", "input_dim", ",", "n_filters", "=", "weightList", "[", "0", "]", ".", "shape", "stride_width", "=", "keras_layer", ".", "subsample", "[", "0", "]", "# Weights and bias terms", "W", "=", "weightList", "[", "0", "]", "b", "=", "weightList", "[", "1", "]", "if", "has_bias", "else", "None", "dilation_factors", "=", "[", "1", ",", "1", "]", "if", "isinstance", "(", "keras_layer", ",", "keras", ".", "layers", ".", "convolutional", ".", "AtrousConvolution1D", ")", ":", "dilation_factors", "[", "-", "1", "]", "=", "keras_layer", ".", "atrous_rate", "builder", ".", "add_convolution", "(", "name", "=", "layer", ",", "kernel_channels", "=", "input_dim", ",", "output_channels", "=", "n_filters", ",", "height", "=", "1", ",", "width", "=", "filter_length", ",", "stride_height", "=", "1", ",", "stride_width", "=", "stride_width", ",", "border_mode", "=", "keras_layer", ".", "border_mode", ",", "groups", "=", "1", ",", "W", "=", "W", ",", "b", "=", "b", ",", "has_bias", "=", "has_bias", ",", "is_deconv", "=", "False", ",", "output_shape", "=", "output_shape", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ",", "dilation_factors", "=", "dilation_factors", ")" ]
Convert convolution layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "convolution", "layer", "from", "keras", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L474-L524
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py
convert_lstm
def convert_lstm(builder, layer, input_names, output_names, keras_layer): """Convert an LSTM layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ hidden_size = keras_layer.output_dim input_size = keras_layer.input_shape[-1] if keras_layer.consume_less not in ['cpu', 'gpu']: raise ValueError('Cannot convert Keras layer with consume_less = %s' % keras_layer.consume_less) output_all = keras_layer.return_sequences reverse_input = keras_layer.go_backwards # Keras: I C F O; W_x, W_h, b # CoreML: I F O G; W_h and W_x are separated W_h, W_x, b = ([], [], []) if keras_layer.consume_less == 'cpu': W_h.append(keras_layer.get_weights()[1].T) W_h.append(keras_layer.get_weights()[7].T) W_h.append(keras_layer.get_weights()[10].T) W_h.append(keras_layer.get_weights()[4].T) W_x.append(keras_layer.get_weights()[0].T) W_x.append(keras_layer.get_weights()[6].T) W_x.append(keras_layer.get_weights()[9].T) W_x.append(keras_layer.get_weights()[3].T) b.append(keras_layer.get_weights()[2]) b.append(keras_layer.get_weights()[8]) b.append(keras_layer.get_weights()[11]) b.append(keras_layer.get_weights()[5]) else: keras_W_h = keras_layer.get_weights()[1].T W_h.append(keras_W_h[0 * hidden_size:][:hidden_size]) W_h.append(keras_W_h[1 * hidden_size:][:hidden_size]) W_h.append(keras_W_h[3 * hidden_size:][:hidden_size]) W_h.append(keras_W_h[2 * hidden_size:][:hidden_size]) keras_W_x = keras_layer.get_weights()[0].T W_x.append(keras_W_x[0 * hidden_size:][:hidden_size]) W_x.append(keras_W_x[1 * hidden_size:][:hidden_size]) W_x.append(keras_W_x[3 * hidden_size:][:hidden_size]) W_x.append(keras_W_x[2 * hidden_size:][:hidden_size]) keras_b = keras_layer.get_weights()[2] b.append(keras_b[0 * hidden_size:][:hidden_size]) b.append(keras_b[1 * hidden_size:][:hidden_size]) b.append(keras_b[3 * hidden_size:][:hidden_size]) b.append(keras_b[2 * hidden_size:][:hidden_size]) # Set activation type inner_activation_str = _get_recurrent_activation_name_from_keras(keras_layer.inner_activation) activation_str = _get_recurrent_activation_name_from_keras(keras_layer.activation) # Add to the network builder.add_unilstm( name = layer, W_h = W_h, W_x = W_x, b = b, hidden_size = hidden_size, input_size = input_size, input_names = input_names, output_names = output_names, inner_activation = inner_activation_str, cell_state_update_activation = activation_str, output_activation = activation_str, output_all = output_all, reverse_input = reverse_input)
python
def convert_lstm(builder, layer, input_names, output_names, keras_layer): """Convert an LSTM layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ hidden_size = keras_layer.output_dim input_size = keras_layer.input_shape[-1] if keras_layer.consume_less not in ['cpu', 'gpu']: raise ValueError('Cannot convert Keras layer with consume_less = %s' % keras_layer.consume_less) output_all = keras_layer.return_sequences reverse_input = keras_layer.go_backwards # Keras: I C F O; W_x, W_h, b # CoreML: I F O G; W_h and W_x are separated W_h, W_x, b = ([], [], []) if keras_layer.consume_less == 'cpu': W_h.append(keras_layer.get_weights()[1].T) W_h.append(keras_layer.get_weights()[7].T) W_h.append(keras_layer.get_weights()[10].T) W_h.append(keras_layer.get_weights()[4].T) W_x.append(keras_layer.get_weights()[0].T) W_x.append(keras_layer.get_weights()[6].T) W_x.append(keras_layer.get_weights()[9].T) W_x.append(keras_layer.get_weights()[3].T) b.append(keras_layer.get_weights()[2]) b.append(keras_layer.get_weights()[8]) b.append(keras_layer.get_weights()[11]) b.append(keras_layer.get_weights()[5]) else: keras_W_h = keras_layer.get_weights()[1].T W_h.append(keras_W_h[0 * hidden_size:][:hidden_size]) W_h.append(keras_W_h[1 * hidden_size:][:hidden_size]) W_h.append(keras_W_h[3 * hidden_size:][:hidden_size]) W_h.append(keras_W_h[2 * hidden_size:][:hidden_size]) keras_W_x = keras_layer.get_weights()[0].T W_x.append(keras_W_x[0 * hidden_size:][:hidden_size]) W_x.append(keras_W_x[1 * hidden_size:][:hidden_size]) W_x.append(keras_W_x[3 * hidden_size:][:hidden_size]) W_x.append(keras_W_x[2 * hidden_size:][:hidden_size]) keras_b = keras_layer.get_weights()[2] b.append(keras_b[0 * hidden_size:][:hidden_size]) b.append(keras_b[1 * hidden_size:][:hidden_size]) b.append(keras_b[3 * hidden_size:][:hidden_size]) b.append(keras_b[2 * hidden_size:][:hidden_size]) # Set activation type inner_activation_str = _get_recurrent_activation_name_from_keras(keras_layer.inner_activation) activation_str = _get_recurrent_activation_name_from_keras(keras_layer.activation) # Add to the network builder.add_unilstm( name = layer, W_h = W_h, W_x = W_x, b = b, hidden_size = hidden_size, input_size = input_size, input_names = input_names, output_names = output_names, inner_activation = inner_activation_str, cell_state_update_activation = activation_str, output_activation = activation_str, output_all = output_all, reverse_input = reverse_input)
[ "def", "convert_lstm", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "hidden_size", "=", "keras_layer", ".", "output_dim", "input_size", "=", "keras_layer", ".", "input_shape", "[", "-", "1", "]", "if", "keras_layer", ".", "consume_less", "not", "in", "[", "'cpu'", ",", "'gpu'", "]", ":", "raise", "ValueError", "(", "'Cannot convert Keras layer with consume_less = %s'", "%", "keras_layer", ".", "consume_less", ")", "output_all", "=", "keras_layer", ".", "return_sequences", "reverse_input", "=", "keras_layer", ".", "go_backwards", "# Keras: I C F O; W_x, W_h, b", "# CoreML: I F O G; W_h and W_x are separated", "W_h", ",", "W_x", ",", "b", "=", "(", "[", "]", ",", "[", "]", ",", "[", "]", ")", "if", "keras_layer", ".", "consume_less", "==", "'cpu'", ":", "W_h", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "1", "]", ".", "T", ")", "W_h", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "7", "]", ".", "T", ")", "W_h", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "10", "]", ".", "T", ")", "W_h", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "4", "]", ".", "T", ")", "W_x", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "0", "]", ".", "T", ")", "W_x", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "6", "]", ".", "T", ")", "W_x", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "9", "]", ".", "T", ")", "W_x", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "3", "]", ".", "T", ")", "b", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "2", "]", ")", "b", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "8", "]", ")", "b", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "11", "]", ")", "b", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "5", "]", ")", "else", ":", "keras_W_h", "=", "keras_layer", ".", "get_weights", "(", ")", "[", "1", "]", ".", "T", "W_h", ".", "append", "(", "keras_W_h", "[", "0", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_h", ".", "append", "(", "keras_W_h", "[", "1", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_h", ".", "append", "(", "keras_W_h", "[", "3", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_h", ".", "append", "(", "keras_W_h", "[", "2", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "keras_W_x", "=", "keras_layer", ".", "get_weights", "(", ")", "[", "0", "]", ".", "T", "W_x", ".", "append", "(", "keras_W_x", "[", "0", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_x", ".", "append", "(", "keras_W_x", "[", "1", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_x", ".", "append", "(", "keras_W_x", "[", "3", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_x", ".", "append", "(", "keras_W_x", "[", "2", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "keras_b", "=", "keras_layer", ".", "get_weights", "(", ")", "[", "2", "]", "b", ".", "append", "(", "keras_b", "[", "0", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "b", ".", "append", "(", "keras_b", "[", "1", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "b", ".", "append", "(", "keras_b", "[", "3", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "b", ".", "append", "(", "keras_b", "[", "2", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "# Set activation type", "inner_activation_str", "=", "_get_recurrent_activation_name_from_keras", "(", "keras_layer", ".", "inner_activation", ")", "activation_str", "=", "_get_recurrent_activation_name_from_keras", "(", "keras_layer", ".", "activation", ")", "# Add to the network", "builder", ".", "add_unilstm", "(", "name", "=", "layer", ",", "W_h", "=", "W_h", ",", "W_x", "=", "W_x", ",", "b", "=", "b", ",", "hidden_size", "=", "hidden_size", ",", "input_size", "=", "input_size", ",", "input_names", "=", "input_names", ",", "output_names", "=", "output_names", ",", "inner_activation", "=", "inner_activation_str", ",", "cell_state_update_activation", "=", "activation_str", ",", "output_activation", "=", "activation_str", ",", "output_all", "=", "output_all", ",", "reverse_input", "=", "reverse_input", ")" ]
Convert an LSTM layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "an", "LSTM", "layer", "from", "keras", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L526-L599
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py
convert_simple_rnn
def convert_simple_rnn(builder, layer, input_names, output_names, keras_layer): """Convert an SimpleRNN layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names hidden_size = keras_layer.output_dim input_size = keras_layer.input_shape[-1] output_all = keras_layer.return_sequences reverse_input = keras_layer.go_backwards if keras_layer.consume_less not in ['cpu', 'gpu']: raise ValueError('Cannot convert Keras layer with consume_less = %s' % keras_layer.consume_less) W_h = np.zeros((hidden_size, hidden_size)) W_x = np.zeros((hidden_size, input_size)) b = np.zeros((hidden_size,)) if keras_layer.consume_less == 'cpu': W_h = keras_layer.get_weights()[1].T W_x = keras_layer.get_weights()[0].T b = keras_layer.get_weights()[2] else: W_h = keras_layer.get_weights()[1].T W_x = keras_layer.get_weights()[0].T b = keras_layer.get_weights()[2] # Set actication type activation_str = _get_recurrent_activation_name_from_keras(keras_layer.activation) # Add to the network builder.add_simple_rnn( name = layer, W_h = W_h, W_x = W_x, b = b, hidden_size = hidden_size, input_size = input_size, activation = activation_str, input_names = input_names, output_names = output_names, output_all=output_all, reverse_input=reverse_input)
python
def convert_simple_rnn(builder, layer, input_names, output_names, keras_layer): """Convert an SimpleRNN layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names hidden_size = keras_layer.output_dim input_size = keras_layer.input_shape[-1] output_all = keras_layer.return_sequences reverse_input = keras_layer.go_backwards if keras_layer.consume_less not in ['cpu', 'gpu']: raise ValueError('Cannot convert Keras layer with consume_less = %s' % keras_layer.consume_less) W_h = np.zeros((hidden_size, hidden_size)) W_x = np.zeros((hidden_size, input_size)) b = np.zeros((hidden_size,)) if keras_layer.consume_less == 'cpu': W_h = keras_layer.get_weights()[1].T W_x = keras_layer.get_weights()[0].T b = keras_layer.get_weights()[2] else: W_h = keras_layer.get_weights()[1].T W_x = keras_layer.get_weights()[0].T b = keras_layer.get_weights()[2] # Set actication type activation_str = _get_recurrent_activation_name_from_keras(keras_layer.activation) # Add to the network builder.add_simple_rnn( name = layer, W_h = W_h, W_x = W_x, b = b, hidden_size = hidden_size, input_size = input_size, activation = activation_str, input_names = input_names, output_names = output_names, output_all=output_all, reverse_input=reverse_input)
[ "def", "convert_simple_rnn", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "# Get input and output names", "hidden_size", "=", "keras_layer", ".", "output_dim", "input_size", "=", "keras_layer", ".", "input_shape", "[", "-", "1", "]", "output_all", "=", "keras_layer", ".", "return_sequences", "reverse_input", "=", "keras_layer", ".", "go_backwards", "if", "keras_layer", ".", "consume_less", "not", "in", "[", "'cpu'", ",", "'gpu'", "]", ":", "raise", "ValueError", "(", "'Cannot convert Keras layer with consume_less = %s'", "%", "keras_layer", ".", "consume_less", ")", "W_h", "=", "np", ".", "zeros", "(", "(", "hidden_size", ",", "hidden_size", ")", ")", "W_x", "=", "np", ".", "zeros", "(", "(", "hidden_size", ",", "input_size", ")", ")", "b", "=", "np", ".", "zeros", "(", "(", "hidden_size", ",", ")", ")", "if", "keras_layer", ".", "consume_less", "==", "'cpu'", ":", "W_h", "=", "keras_layer", ".", "get_weights", "(", ")", "[", "1", "]", ".", "T", "W_x", "=", "keras_layer", ".", "get_weights", "(", ")", "[", "0", "]", ".", "T", "b", "=", "keras_layer", ".", "get_weights", "(", ")", "[", "2", "]", "else", ":", "W_h", "=", "keras_layer", ".", "get_weights", "(", ")", "[", "1", "]", ".", "T", "W_x", "=", "keras_layer", ".", "get_weights", "(", ")", "[", "0", "]", ".", "T", "b", "=", "keras_layer", ".", "get_weights", "(", ")", "[", "2", "]", "# Set actication type", "activation_str", "=", "_get_recurrent_activation_name_from_keras", "(", "keras_layer", ".", "activation", ")", "# Add to the network", "builder", ".", "add_simple_rnn", "(", "name", "=", "layer", ",", "W_h", "=", "W_h", ",", "W_x", "=", "W_x", ",", "b", "=", "b", ",", "hidden_size", "=", "hidden_size", ",", "input_size", "=", "input_size", ",", "activation", "=", "activation_str", ",", "input_names", "=", "input_names", ",", "output_names", "=", "output_names", ",", "output_all", "=", "output_all", ",", "reverse_input", "=", "reverse_input", ")" ]
Convert an SimpleRNN layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "an", "SimpleRNN", "layer", "from", "keras", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L602-L649
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py
convert_gru
def convert_gru(builder, layer, input_names, output_names, keras_layer): """Convert a GRU layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ hidden_size = keras_layer.output_dim input_size = keras_layer.input_shape[-1] output_all = keras_layer.return_sequences reverse_input = keras_layer.go_backwards if keras_layer.consume_less not in ['cpu', 'gpu']: raise ValueError('Cannot convert Keras layer with consume_less = %s' % keras_layer.consume_less) # Keras: Z R O # CoreML: Z R O W_h, W_x, b = ([], [], []) if keras_layer.consume_less == 'cpu': W_x.append(keras_layer.get_weights()[0].T) W_x.append(keras_layer.get_weights()[3].T) W_x.append(keras_layer.get_weights()[6].T) W_h.append(keras_layer.get_weights()[1].T) W_h.append(keras_layer.get_weights()[4].T) W_h.append(keras_layer.get_weights()[7].T) b.append(keras_layer.get_weights()[2]) b.append(keras_layer.get_weights()[5]) b.append(keras_layer.get_weights()[8]) else: print('consume less not implemented') # Set actication type inner_activation_str = _get_recurrent_activation_name_from_keras(keras_layer.inner_activation) activation_str = _get_recurrent_activation_name_from_keras(keras_layer.activation) # Add to the network builder.add_gru( name = layer, W_h = W_h, W_x = W_x, b = b, input_size = input_size, hidden_size = hidden_size, input_names = input_names, output_names = output_names, activation = activation_str, inner_activation = inner_activation_str, output_all=output_all, reverse_input = reverse_input)
python
def convert_gru(builder, layer, input_names, output_names, keras_layer): """Convert a GRU layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ hidden_size = keras_layer.output_dim input_size = keras_layer.input_shape[-1] output_all = keras_layer.return_sequences reverse_input = keras_layer.go_backwards if keras_layer.consume_less not in ['cpu', 'gpu']: raise ValueError('Cannot convert Keras layer with consume_less = %s' % keras_layer.consume_less) # Keras: Z R O # CoreML: Z R O W_h, W_x, b = ([], [], []) if keras_layer.consume_less == 'cpu': W_x.append(keras_layer.get_weights()[0].T) W_x.append(keras_layer.get_weights()[3].T) W_x.append(keras_layer.get_weights()[6].T) W_h.append(keras_layer.get_weights()[1].T) W_h.append(keras_layer.get_weights()[4].T) W_h.append(keras_layer.get_weights()[7].T) b.append(keras_layer.get_weights()[2]) b.append(keras_layer.get_weights()[5]) b.append(keras_layer.get_weights()[8]) else: print('consume less not implemented') # Set actication type inner_activation_str = _get_recurrent_activation_name_from_keras(keras_layer.inner_activation) activation_str = _get_recurrent_activation_name_from_keras(keras_layer.activation) # Add to the network builder.add_gru( name = layer, W_h = W_h, W_x = W_x, b = b, input_size = input_size, hidden_size = hidden_size, input_names = input_names, output_names = output_names, activation = activation_str, inner_activation = inner_activation_str, output_all=output_all, reverse_input = reverse_input)
[ "def", "convert_gru", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "hidden_size", "=", "keras_layer", ".", "output_dim", "input_size", "=", "keras_layer", ".", "input_shape", "[", "-", "1", "]", "output_all", "=", "keras_layer", ".", "return_sequences", "reverse_input", "=", "keras_layer", ".", "go_backwards", "if", "keras_layer", ".", "consume_less", "not", "in", "[", "'cpu'", ",", "'gpu'", "]", ":", "raise", "ValueError", "(", "'Cannot convert Keras layer with consume_less = %s'", "%", "keras_layer", ".", "consume_less", ")", "# Keras: Z R O", "# CoreML: Z R O", "W_h", ",", "W_x", ",", "b", "=", "(", "[", "]", ",", "[", "]", ",", "[", "]", ")", "if", "keras_layer", ".", "consume_less", "==", "'cpu'", ":", "W_x", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "0", "]", ".", "T", ")", "W_x", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "3", "]", ".", "T", ")", "W_x", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "6", "]", ".", "T", ")", "W_h", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "1", "]", ".", "T", ")", "W_h", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "4", "]", ".", "T", ")", "W_h", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "7", "]", ".", "T", ")", "b", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "2", "]", ")", "b", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "5", "]", ")", "b", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "8", "]", ")", "else", ":", "print", "(", "'consume less not implemented'", ")", "# Set actication type", "inner_activation_str", "=", "_get_recurrent_activation_name_from_keras", "(", "keras_layer", ".", "inner_activation", ")", "activation_str", "=", "_get_recurrent_activation_name_from_keras", "(", "keras_layer", ".", "activation", ")", "# Add to the network", "builder", ".", "add_gru", "(", "name", "=", "layer", ",", "W_h", "=", "W_h", ",", "W_x", "=", "W_x", ",", "b", "=", "b", ",", "input_size", "=", "input_size", ",", "hidden_size", "=", "hidden_size", ",", "input_names", "=", "input_names", ",", "output_names", "=", "output_names", ",", "activation", "=", "activation_str", ",", "inner_activation", "=", "inner_activation_str", ",", "output_all", "=", "output_all", ",", "reverse_input", "=", "reverse_input", ")" ]
Convert a GRU layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "a", "GRU", "layer", "from", "keras", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L651-L705
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py
convert_bidirectional
def convert_bidirectional(builder, layer, input_names, output_names, keras_layer): """Convert a bidirectional layer from keras to coreml. Currently assumes the units are LSTMs. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ input_size = keras_layer.input_shape[-1] lstm_layer = keras_layer.forward_layer if (type(lstm_layer) != keras.layers.recurrent.LSTM): raise TypeError('Bidirectional layers only supported with LSTM') if lstm_layer.go_backwards: raise TypeError(' \'go_backwards\' mode not supported with Bidirectional layers') output_all = keras_layer.return_sequences hidden_size = lstm_layer.output_dim #output_size = lstm_layer.output_dim * 2 if lstm_layer.consume_less not in ['cpu', 'gpu']: raise ValueError('Cannot convert Keras layer with consume_less = %s' % keras_layer.consume_less) # Keras: I C F O; W_x, W_h, b # CoreML: I F O G; W_h and W_x are separated # Keras has all forward weights, followed by backward in the same order W_h, W_x, b = ([], [], []) if lstm_layer.consume_less == 'cpu': W_h.append(keras_layer.get_weights()[1].T) W_h.append(keras_layer.get_weights()[7].T) W_h.append(keras_layer.get_weights()[10].T) W_h.append(keras_layer.get_weights()[4].T) W_x.append(keras_layer.get_weights()[0].T) W_x.append(keras_layer.get_weights()[6].T) W_x.append(keras_layer.get_weights()[9].T) W_x.append(keras_layer.get_weights()[3].T) b.append(keras_layer.get_weights()[2]) b.append(keras_layer.get_weights()[8]) b.append(keras_layer.get_weights()[11]) b.append(keras_layer.get_weights()[5]) else: keras_W_h = keras_layer.get_weights()[1].T W_h.append(keras_W_h[0 * hidden_size:][:hidden_size]) W_h.append(keras_W_h[1 * hidden_size:][:hidden_size]) W_h.append(keras_W_h[3 * hidden_size:][:hidden_size]) W_h.append(keras_W_h[2 * hidden_size:][:hidden_size]) keras_W_x = keras_layer.get_weights()[0].T W_x.append(keras_W_x[0 * hidden_size:][:hidden_size]) W_x.append(keras_W_x[1 * hidden_size:][:hidden_size]) W_x.append(keras_W_x[3 * hidden_size:][:hidden_size]) W_x.append(keras_W_x[2 * hidden_size:][:hidden_size]) keras_b = keras_layer.get_weights()[2] b.append(keras_b[0 * hidden_size:][:hidden_size]) b.append(keras_b[1 * hidden_size:][:hidden_size]) b.append(keras_b[3 * hidden_size:][:hidden_size]) b.append(keras_b[2 * hidden_size:][:hidden_size]) W_h_back, W_x_back, b_back = ([],[],[]) if keras_layer.backward_layer.consume_less == 'cpu': back_weights = keras_layer.backward_layer.get_weights() W_h_back.append(back_weights[1].T) W_h_back.append(back_weights[7].T) W_h_back.append(back_weights[10].T) W_h_back.append(back_weights[4].T) W_x_back.append(back_weights[0].T) W_x_back.append(back_weights[6].T) W_x_back.append(back_weights[9].T) W_x_back.append(back_weights[3].T) b_back.append(back_weights[2]) b_back.append(back_weights[8]) b_back.append(back_weights[11]) b_back.append(back_weights[5]) else: keras_W_h = keras_layer.backward_layer.get_weights()[1].T W_h_back.append(keras_W_h[0 * hidden_size:][:hidden_size]) W_h_back.append(keras_W_h[1 * hidden_size:][:hidden_size]) W_h_back.append(keras_W_h[3 * hidden_size:][:hidden_size]) W_h_back.append(keras_W_h[2 * hidden_size:][:hidden_size]) keras_W_x = keras_layer.backward_layer.get_weights()[0].T W_x_back.append(keras_W_x[0 * hidden_size:][:hidden_size]) W_x_back.append(keras_W_x[1 * hidden_size:][:hidden_size]) W_x_back.append(keras_W_x[3 * hidden_size:][:hidden_size]) W_x_back.append(keras_W_x[2 * hidden_size:][:hidden_size]) keras_b = keras_layer.backward_layer.get_weights()[2] b_back.append(keras_b[0 * hidden_size:][:hidden_size]) b_back.append(keras_b[1 * hidden_size:][:hidden_size]) b_back.append(keras_b[3 * hidden_size:][:hidden_size]) b_back.append(keras_b[2 * hidden_size:][:hidden_size]) # Set activation type inner_activation_str = _get_recurrent_activation_name_from_keras(lstm_layer.inner_activation) activation_str = _get_recurrent_activation_name_from_keras(lstm_layer.activation) # Add to the network builder.add_bidirlstm( name = layer, W_h = W_h, W_x = W_x, b = b, W_h_back = W_h_back, W_x_back = W_x_back, b_back = b_back, hidden_size=hidden_size, input_size=input_size, input_names=input_names, output_names=output_names, inner_activation = inner_activation_str, cell_state_update_activation = activation_str, output_activation = activation_str, output_all = output_all)
python
def convert_bidirectional(builder, layer, input_names, output_names, keras_layer): """Convert a bidirectional layer from keras to coreml. Currently assumes the units are LSTMs. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ input_size = keras_layer.input_shape[-1] lstm_layer = keras_layer.forward_layer if (type(lstm_layer) != keras.layers.recurrent.LSTM): raise TypeError('Bidirectional layers only supported with LSTM') if lstm_layer.go_backwards: raise TypeError(' \'go_backwards\' mode not supported with Bidirectional layers') output_all = keras_layer.return_sequences hidden_size = lstm_layer.output_dim #output_size = lstm_layer.output_dim * 2 if lstm_layer.consume_less not in ['cpu', 'gpu']: raise ValueError('Cannot convert Keras layer with consume_less = %s' % keras_layer.consume_less) # Keras: I C F O; W_x, W_h, b # CoreML: I F O G; W_h and W_x are separated # Keras has all forward weights, followed by backward in the same order W_h, W_x, b = ([], [], []) if lstm_layer.consume_less == 'cpu': W_h.append(keras_layer.get_weights()[1].T) W_h.append(keras_layer.get_weights()[7].T) W_h.append(keras_layer.get_weights()[10].T) W_h.append(keras_layer.get_weights()[4].T) W_x.append(keras_layer.get_weights()[0].T) W_x.append(keras_layer.get_weights()[6].T) W_x.append(keras_layer.get_weights()[9].T) W_x.append(keras_layer.get_weights()[3].T) b.append(keras_layer.get_weights()[2]) b.append(keras_layer.get_weights()[8]) b.append(keras_layer.get_weights()[11]) b.append(keras_layer.get_weights()[5]) else: keras_W_h = keras_layer.get_weights()[1].T W_h.append(keras_W_h[0 * hidden_size:][:hidden_size]) W_h.append(keras_W_h[1 * hidden_size:][:hidden_size]) W_h.append(keras_W_h[3 * hidden_size:][:hidden_size]) W_h.append(keras_W_h[2 * hidden_size:][:hidden_size]) keras_W_x = keras_layer.get_weights()[0].T W_x.append(keras_W_x[0 * hidden_size:][:hidden_size]) W_x.append(keras_W_x[1 * hidden_size:][:hidden_size]) W_x.append(keras_W_x[3 * hidden_size:][:hidden_size]) W_x.append(keras_W_x[2 * hidden_size:][:hidden_size]) keras_b = keras_layer.get_weights()[2] b.append(keras_b[0 * hidden_size:][:hidden_size]) b.append(keras_b[1 * hidden_size:][:hidden_size]) b.append(keras_b[3 * hidden_size:][:hidden_size]) b.append(keras_b[2 * hidden_size:][:hidden_size]) W_h_back, W_x_back, b_back = ([],[],[]) if keras_layer.backward_layer.consume_less == 'cpu': back_weights = keras_layer.backward_layer.get_weights() W_h_back.append(back_weights[1].T) W_h_back.append(back_weights[7].T) W_h_back.append(back_weights[10].T) W_h_back.append(back_weights[4].T) W_x_back.append(back_weights[0].T) W_x_back.append(back_weights[6].T) W_x_back.append(back_weights[9].T) W_x_back.append(back_weights[3].T) b_back.append(back_weights[2]) b_back.append(back_weights[8]) b_back.append(back_weights[11]) b_back.append(back_weights[5]) else: keras_W_h = keras_layer.backward_layer.get_weights()[1].T W_h_back.append(keras_W_h[0 * hidden_size:][:hidden_size]) W_h_back.append(keras_W_h[1 * hidden_size:][:hidden_size]) W_h_back.append(keras_W_h[3 * hidden_size:][:hidden_size]) W_h_back.append(keras_W_h[2 * hidden_size:][:hidden_size]) keras_W_x = keras_layer.backward_layer.get_weights()[0].T W_x_back.append(keras_W_x[0 * hidden_size:][:hidden_size]) W_x_back.append(keras_W_x[1 * hidden_size:][:hidden_size]) W_x_back.append(keras_W_x[3 * hidden_size:][:hidden_size]) W_x_back.append(keras_W_x[2 * hidden_size:][:hidden_size]) keras_b = keras_layer.backward_layer.get_weights()[2] b_back.append(keras_b[0 * hidden_size:][:hidden_size]) b_back.append(keras_b[1 * hidden_size:][:hidden_size]) b_back.append(keras_b[3 * hidden_size:][:hidden_size]) b_back.append(keras_b[2 * hidden_size:][:hidden_size]) # Set activation type inner_activation_str = _get_recurrent_activation_name_from_keras(lstm_layer.inner_activation) activation_str = _get_recurrent_activation_name_from_keras(lstm_layer.activation) # Add to the network builder.add_bidirlstm( name = layer, W_h = W_h, W_x = W_x, b = b, W_h_back = W_h_back, W_x_back = W_x_back, b_back = b_back, hidden_size=hidden_size, input_size=input_size, input_names=input_names, output_names=output_names, inner_activation = inner_activation_str, cell_state_update_activation = activation_str, output_activation = activation_str, output_all = output_all)
[ "def", "convert_bidirectional", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "input_size", "=", "keras_layer", ".", "input_shape", "[", "-", "1", "]", "lstm_layer", "=", "keras_layer", ".", "forward_layer", "if", "(", "type", "(", "lstm_layer", ")", "!=", "keras", ".", "layers", ".", "recurrent", ".", "LSTM", ")", ":", "raise", "TypeError", "(", "'Bidirectional layers only supported with LSTM'", ")", "if", "lstm_layer", ".", "go_backwards", ":", "raise", "TypeError", "(", "' \\'go_backwards\\' mode not supported with Bidirectional layers'", ")", "output_all", "=", "keras_layer", ".", "return_sequences", "hidden_size", "=", "lstm_layer", ".", "output_dim", "#output_size = lstm_layer.output_dim * 2", "if", "lstm_layer", ".", "consume_less", "not", "in", "[", "'cpu'", ",", "'gpu'", "]", ":", "raise", "ValueError", "(", "'Cannot convert Keras layer with consume_less = %s'", "%", "keras_layer", ".", "consume_less", ")", "# Keras: I C F O; W_x, W_h, b", "# CoreML: I F O G; W_h and W_x are separated", "# Keras has all forward weights, followed by backward in the same order", "W_h", ",", "W_x", ",", "b", "=", "(", "[", "]", ",", "[", "]", ",", "[", "]", ")", "if", "lstm_layer", ".", "consume_less", "==", "'cpu'", ":", "W_h", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "1", "]", ".", "T", ")", "W_h", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "7", "]", ".", "T", ")", "W_h", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "10", "]", ".", "T", ")", "W_h", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "4", "]", ".", "T", ")", "W_x", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "0", "]", ".", "T", ")", "W_x", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "6", "]", ".", "T", ")", "W_x", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "9", "]", ".", "T", ")", "W_x", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "3", "]", ".", "T", ")", "b", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "2", "]", ")", "b", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "8", "]", ")", "b", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "11", "]", ")", "b", ".", "append", "(", "keras_layer", ".", "get_weights", "(", ")", "[", "5", "]", ")", "else", ":", "keras_W_h", "=", "keras_layer", ".", "get_weights", "(", ")", "[", "1", "]", ".", "T", "W_h", ".", "append", "(", "keras_W_h", "[", "0", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_h", ".", "append", "(", "keras_W_h", "[", "1", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_h", ".", "append", "(", "keras_W_h", "[", "3", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_h", ".", "append", "(", "keras_W_h", "[", "2", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "keras_W_x", "=", "keras_layer", ".", "get_weights", "(", ")", "[", "0", "]", ".", "T", "W_x", ".", "append", "(", "keras_W_x", "[", "0", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_x", ".", "append", "(", "keras_W_x", "[", "1", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_x", ".", "append", "(", "keras_W_x", "[", "3", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_x", ".", "append", "(", "keras_W_x", "[", "2", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "keras_b", "=", "keras_layer", ".", "get_weights", "(", ")", "[", "2", "]", "b", ".", "append", "(", "keras_b", "[", "0", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "b", ".", "append", "(", "keras_b", "[", "1", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "b", ".", "append", "(", "keras_b", "[", "3", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "b", ".", "append", "(", "keras_b", "[", "2", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_h_back", ",", "W_x_back", ",", "b_back", "=", "(", "[", "]", ",", "[", "]", ",", "[", "]", ")", "if", "keras_layer", ".", "backward_layer", ".", "consume_less", "==", "'cpu'", ":", "back_weights", "=", "keras_layer", ".", "backward_layer", ".", "get_weights", "(", ")", "W_h_back", ".", "append", "(", "back_weights", "[", "1", "]", ".", "T", ")", "W_h_back", ".", "append", "(", "back_weights", "[", "7", "]", ".", "T", ")", "W_h_back", ".", "append", "(", "back_weights", "[", "10", "]", ".", "T", ")", "W_h_back", ".", "append", "(", "back_weights", "[", "4", "]", ".", "T", ")", "W_x_back", ".", "append", "(", "back_weights", "[", "0", "]", ".", "T", ")", "W_x_back", ".", "append", "(", "back_weights", "[", "6", "]", ".", "T", ")", "W_x_back", ".", "append", "(", "back_weights", "[", "9", "]", ".", "T", ")", "W_x_back", ".", "append", "(", "back_weights", "[", "3", "]", ".", "T", ")", "b_back", ".", "append", "(", "back_weights", "[", "2", "]", ")", "b_back", ".", "append", "(", "back_weights", "[", "8", "]", ")", "b_back", ".", "append", "(", "back_weights", "[", "11", "]", ")", "b_back", ".", "append", "(", "back_weights", "[", "5", "]", ")", "else", ":", "keras_W_h", "=", "keras_layer", ".", "backward_layer", ".", "get_weights", "(", ")", "[", "1", "]", ".", "T", "W_h_back", ".", "append", "(", "keras_W_h", "[", "0", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_h_back", ".", "append", "(", "keras_W_h", "[", "1", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_h_back", ".", "append", "(", "keras_W_h", "[", "3", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_h_back", ".", "append", "(", "keras_W_h", "[", "2", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "keras_W_x", "=", "keras_layer", ".", "backward_layer", ".", "get_weights", "(", ")", "[", "0", "]", ".", "T", "W_x_back", ".", "append", "(", "keras_W_x", "[", "0", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_x_back", ".", "append", "(", "keras_W_x", "[", "1", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_x_back", ".", "append", "(", "keras_W_x", "[", "3", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_x_back", ".", "append", "(", "keras_W_x", "[", "2", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "keras_b", "=", "keras_layer", ".", "backward_layer", ".", "get_weights", "(", ")", "[", "2", "]", "b_back", ".", "append", "(", "keras_b", "[", "0", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "b_back", ".", "append", "(", "keras_b", "[", "1", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "b_back", ".", "append", "(", "keras_b", "[", "3", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "b_back", ".", "append", "(", "keras_b", "[", "2", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "# Set activation type", "inner_activation_str", "=", "_get_recurrent_activation_name_from_keras", "(", "lstm_layer", ".", "inner_activation", ")", "activation_str", "=", "_get_recurrent_activation_name_from_keras", "(", "lstm_layer", ".", "activation", ")", "# Add to the network", "builder", ".", "add_bidirlstm", "(", "name", "=", "layer", ",", "W_h", "=", "W_h", ",", "W_x", "=", "W_x", ",", "b", "=", "b", ",", "W_h_back", "=", "W_h_back", ",", "W_x_back", "=", "W_x_back", ",", "b_back", "=", "b_back", ",", "hidden_size", "=", "hidden_size", ",", "input_size", "=", "input_size", ",", "input_names", "=", "input_names", ",", "output_names", "=", "output_names", ",", "inner_activation", "=", "inner_activation_str", ",", "cell_state_update_activation", "=", "activation_str", ",", "output_activation", "=", "activation_str", ",", "output_all", "=", "output_all", ")" ]
Convert a bidirectional layer from keras to coreml. Currently assumes the units are LSTMs. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "a", "bidirectional", "layer", "from", "keras", "to", "coreml", ".", "Currently", "assumes", "the", "units", "are", "LSTMs", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L708-L830
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py
convert_batchnorm
def convert_batchnorm(builder, layer, input_names, output_names, keras_layer): """ Parameters keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names input_name, output_name = (input_names[0], output_names[0]) # Currently CoreML supports only per-channel batch-norm if keras_layer.mode != 0: raise NotImplementedError( 'Currently supports only per-feature normalization') axis = keras_layer.axis nb_channels = keras_layer.input_shape[axis] # Set parameters # Parameter arrangement in Keras: gamma, beta, mean, variance gamma = keras_layer.get_weights()[0] beta = keras_layer.get_weights()[1] mean = keras_layer.get_weights()[2] std = keras_layer.get_weights()[3] # compute adjusted parameters variance = std * std f = 1.0 / np.sqrt(std + keras_layer.epsilon) gamma1 = gamma*f beta1 = beta - gamma*mean*f mean[:] = 0.0 #mean variance[:] = 1.0 - .00001 #stddev builder.add_batchnorm( name = layer, channels = nb_channels, gamma = gamma1, beta = beta1, mean = mean, variance = variance, input_name = input_name, output_name = output_name)
python
def convert_batchnorm(builder, layer, input_names, output_names, keras_layer): """ Parameters keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names input_name, output_name = (input_names[0], output_names[0]) # Currently CoreML supports only per-channel batch-norm if keras_layer.mode != 0: raise NotImplementedError( 'Currently supports only per-feature normalization') axis = keras_layer.axis nb_channels = keras_layer.input_shape[axis] # Set parameters # Parameter arrangement in Keras: gamma, beta, mean, variance gamma = keras_layer.get_weights()[0] beta = keras_layer.get_weights()[1] mean = keras_layer.get_weights()[2] std = keras_layer.get_weights()[3] # compute adjusted parameters variance = std * std f = 1.0 / np.sqrt(std + keras_layer.epsilon) gamma1 = gamma*f beta1 = beta - gamma*mean*f mean[:] = 0.0 #mean variance[:] = 1.0 - .00001 #stddev builder.add_batchnorm( name = layer, channels = nb_channels, gamma = gamma1, beta = beta1, mean = mean, variance = variance, input_name = input_name, output_name = output_name)
[ "def", "convert_batchnorm", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "# Get input and output names", "input_name", ",", "output_name", "=", "(", "input_names", "[", "0", "]", ",", "output_names", "[", "0", "]", ")", "# Currently CoreML supports only per-channel batch-norm", "if", "keras_layer", ".", "mode", "!=", "0", ":", "raise", "NotImplementedError", "(", "'Currently supports only per-feature normalization'", ")", "axis", "=", "keras_layer", ".", "axis", "nb_channels", "=", "keras_layer", ".", "input_shape", "[", "axis", "]", "# Set parameters", "# Parameter arrangement in Keras: gamma, beta, mean, variance", "gamma", "=", "keras_layer", ".", "get_weights", "(", ")", "[", "0", "]", "beta", "=", "keras_layer", ".", "get_weights", "(", ")", "[", "1", "]", "mean", "=", "keras_layer", ".", "get_weights", "(", ")", "[", "2", "]", "std", "=", "keras_layer", ".", "get_weights", "(", ")", "[", "3", "]", "# compute adjusted parameters", "variance", "=", "std", "*", "std", "f", "=", "1.0", "/", "np", ".", "sqrt", "(", "std", "+", "keras_layer", ".", "epsilon", ")", "gamma1", "=", "gamma", "*", "f", "beta1", "=", "beta", "-", "gamma", "*", "mean", "*", "f", "mean", "[", ":", "]", "=", "0.0", "#mean", "variance", "[", ":", "]", "=", "1.0", "-", ".00001", "#stddev", "builder", ".", "add_batchnorm", "(", "name", "=", "layer", ",", "channels", "=", "nb_channels", ",", "gamma", "=", "gamma1", ",", "beta", "=", "beta1", ",", "mean", "=", "mean", ",", "variance", "=", "variance", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ")" ]
Parameters keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object.
[ "Parameters", "keras_layer", ":", "layer", "A", "keras", "layer", "object", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L832-L876
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py
convert_flatten
def convert_flatten(builder, layer, input_names, output_names, keras_layer): """Convert a flatten layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = (input_names[0], output_names[0]) # blob_order == 0 if the input blob needs not be rearranged # blob_order == 1 if the input blob needs to be rearranged blob_order = 0 # using keras_layer.input.shape have a "?" (Dimension[None] at the front), # making a 3D tensor with unknown batch size 4D if len(keras_layer.input.shape) == 4: blob_order = 1 builder.add_flatten(name=layer, mode=blob_order, input_name=input_name, output_name=output_name)
python
def convert_flatten(builder, layer, input_names, output_names, keras_layer): """Convert a flatten layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = (input_names[0], output_names[0]) # blob_order == 0 if the input blob needs not be rearranged # blob_order == 1 if the input blob needs to be rearranged blob_order = 0 # using keras_layer.input.shape have a "?" (Dimension[None] at the front), # making a 3D tensor with unknown batch size 4D if len(keras_layer.input.shape) == 4: blob_order = 1 builder.add_flatten(name=layer, mode=blob_order, input_name=input_name, output_name=output_name)
[ "def", "convert_flatten", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "input_name", ",", "output_name", "=", "(", "input_names", "[", "0", "]", ",", "output_names", "[", "0", "]", ")", "# blob_order == 0 if the input blob needs not be rearranged", "# blob_order == 1 if the input blob needs to be rearranged", "blob_order", "=", "0", "# using keras_layer.input.shape have a \"?\" (Dimension[None] at the front),", "# making a 3D tensor with unknown batch size 4D", "if", "len", "(", "keras_layer", ".", "input", ".", "shape", ")", "==", "4", ":", "blob_order", "=", "1", "builder", ".", "add_flatten", "(", "name", "=", "layer", ",", "mode", "=", "blob_order", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ")" ]
Convert a flatten layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "a", "flatten", "layer", "from", "keras", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L878-L900
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py
convert_softmax
def convert_softmax(builder, layer, input_names, output_names, keras_layer): """Convert a softmax layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = (input_names[0], output_names[0]) builder.add_softmax(name = layer, input_name = input_name, output_name = output_name)
python
def convert_softmax(builder, layer, input_names, output_names, keras_layer): """Convert a softmax layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = (input_names[0], output_names[0]) builder.add_softmax(name = layer, input_name = input_name, output_name = output_name)
[ "def", "convert_softmax", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "input_name", ",", "output_name", "=", "(", "input_names", "[", "0", "]", ",", "output_names", "[", "0", "]", ")", "builder", ".", "add_softmax", "(", "name", "=", "layer", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ")" ]
Convert a softmax layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "a", "softmax", "layer", "from", "keras", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L902-L916
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py
convert_permute
def convert_permute(builder, layer, input_names, output_names, keras_layer): """Convert a softmax layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = (input_names[0], output_names[0]) keras_dims = keras_layer.dims # Keras permute layer index begins at 1 if len(keras_dims) == 3: # Keras input tensor interpret as (H,W,C) x = list(np.array(keras_dims)) i1, i2, i3 = x.index(1), x.index(2), x.index(3) x[i1], x[i2], x[i3] = 2, 3, 1 # add a sequence axis x = [0] + x dim = tuple(x) elif len(keras_dims) == 4: # Here we use Keras converter as a place holder for inserting # permutations - the values here are not valid Keras dim parameters # but parameters we need to use to convert to CoreML model dim = keras_dims else: raise NotImplementedError('Supports only 3d permutation.') builder.add_permute(name = layer, dim=dim, input_name = input_name, output_name = output_name)
python
def convert_permute(builder, layer, input_names, output_names, keras_layer): """Convert a softmax layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = (input_names[0], output_names[0]) keras_dims = keras_layer.dims # Keras permute layer index begins at 1 if len(keras_dims) == 3: # Keras input tensor interpret as (H,W,C) x = list(np.array(keras_dims)) i1, i2, i3 = x.index(1), x.index(2), x.index(3) x[i1], x[i2], x[i3] = 2, 3, 1 # add a sequence axis x = [0] + x dim = tuple(x) elif len(keras_dims) == 4: # Here we use Keras converter as a place holder for inserting # permutations - the values here are not valid Keras dim parameters # but parameters we need to use to convert to CoreML model dim = keras_dims else: raise NotImplementedError('Supports only 3d permutation.') builder.add_permute(name = layer, dim=dim, input_name = input_name, output_name = output_name)
[ "def", "convert_permute", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "input_name", ",", "output_name", "=", "(", "input_names", "[", "0", "]", ",", "output_names", "[", "0", "]", ")", "keras_dims", "=", "keras_layer", ".", "dims", "# Keras permute layer index begins at 1", "if", "len", "(", "keras_dims", ")", "==", "3", ":", "# Keras input tensor interpret as (H,W,C)", "x", "=", "list", "(", "np", ".", "array", "(", "keras_dims", ")", ")", "i1", ",", "i2", ",", "i3", "=", "x", ".", "index", "(", "1", ")", ",", "x", ".", "index", "(", "2", ")", ",", "x", ".", "index", "(", "3", ")", "x", "[", "i1", "]", ",", "x", "[", "i2", "]", ",", "x", "[", "i3", "]", "=", "2", ",", "3", ",", "1", "# add a sequence axis", "x", "=", "[", "0", "]", "+", "x", "dim", "=", "tuple", "(", "x", ")", "elif", "len", "(", "keras_dims", ")", "==", "4", ":", "# Here we use Keras converter as a place holder for inserting", "# permutations - the values here are not valid Keras dim parameters", "# but parameters we need to use to convert to CoreML model", "dim", "=", "keras_dims", "else", ":", "raise", "NotImplementedError", "(", "'Supports only 3d permutation.'", ")", "builder", ".", "add_permute", "(", "name", "=", "layer", ",", "dim", "=", "dim", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ")" ]
Convert a softmax layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "a", "softmax", "layer", "from", "keras", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L918-L950
train
apple/turicreate
src/external/xgboost/subtree/rabit/tracker/rabit_sge.py
sge_submit
def sge_submit(nslave, worker_args, worker_envs): """ customized submit script, that submit nslave jobs, each must contain args as parameter note this can be a lambda function containing additional parameters in input Parameters nslave number of slave process to start up args arguments to launch each job this usually includes the parameters of master_uri and parameters passed into submit """ env_arg = ','.join(['%s=\"%s\"' % (k, str(v)) for k, v in worker_envs.items()]) cmd = 'qsub -cwd -t 1-%d -S /bin/bash' % nslave if args.queue != 'default': cmd += '-q %s' % args.queue cmd += ' -N %s ' % args.jobname cmd += ' -e %s -o %s' % (args.logdir, args.logdir) cmd += ' -pe orte %d' % (args.vcores) cmd += ' -v %s,PATH=${PATH}:.' % env_arg cmd += ' %s %s' % (runscript, ' '.join(args.command + worker_args)) print cmd subprocess.check_call(cmd, shell = True) print 'Waiting for the jobs to get up...'
python
def sge_submit(nslave, worker_args, worker_envs): """ customized submit script, that submit nslave jobs, each must contain args as parameter note this can be a lambda function containing additional parameters in input Parameters nslave number of slave process to start up args arguments to launch each job this usually includes the parameters of master_uri and parameters passed into submit """ env_arg = ','.join(['%s=\"%s\"' % (k, str(v)) for k, v in worker_envs.items()]) cmd = 'qsub -cwd -t 1-%d -S /bin/bash' % nslave if args.queue != 'default': cmd += '-q %s' % args.queue cmd += ' -N %s ' % args.jobname cmd += ' -e %s -o %s' % (args.logdir, args.logdir) cmd += ' -pe orte %d' % (args.vcores) cmd += ' -v %s,PATH=${PATH}:.' % env_arg cmd += ' %s %s' % (runscript, ' '.join(args.command + worker_args)) print cmd subprocess.check_call(cmd, shell = True) print 'Waiting for the jobs to get up...'
[ "def", "sge_submit", "(", "nslave", ",", "worker_args", ",", "worker_envs", ")", ":", "env_arg", "=", "','", ".", "join", "(", "[", "'%s=\\\"%s\\\"'", "%", "(", "k", ",", "str", "(", "v", ")", ")", "for", "k", ",", "v", "in", "worker_envs", ".", "items", "(", ")", "]", ")", "cmd", "=", "'qsub -cwd -t 1-%d -S /bin/bash'", "%", "nslave", "if", "args", ".", "queue", "!=", "'default'", ":", "cmd", "+=", "'-q %s'", "%", "args", ".", "queue", "cmd", "+=", "' -N %s '", "%", "args", ".", "jobname", "cmd", "+=", "' -e %s -o %s'", "%", "(", "args", ".", "logdir", ",", "args", ".", "logdir", ")", "cmd", "+=", "' -pe orte %d'", "%", "(", "args", ".", "vcores", ")", "cmd", "+=", "' -v %s,PATH=${PATH}:.'", "%", "env_arg", "cmd", "+=", "' %s %s'", "%", "(", "runscript", ",", "' '", ".", "join", "(", "args", ".", "command", "+", "worker_args", ")", ")", "print", "cmd", "subprocess", ".", "check_call", "(", "cmd", ",", "shell", "=", "True", ")", "print", "'Waiting for the jobs to get up...'" ]
customized submit script, that submit nslave jobs, each must contain args as parameter note this can be a lambda function containing additional parameters in input Parameters nslave number of slave process to start up args arguments to launch each job this usually includes the parameters of master_uri and parameters passed into submit
[ "customized", "submit", "script", "that", "submit", "nslave", "jobs", "each", "must", "contain", "args", "as", "parameter", "note", "this", "can", "be", "a", "lambda", "function", "containing", "additional", "parameters", "in", "input", "Parameters", "nslave", "number", "of", "slave", "process", "to", "start", "up", "args", "arguments", "to", "launch", "each", "job", "this", "usually", "includes", "the", "parameters", "of", "master_uri", "and", "parameters", "passed", "into", "submit" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/subtree/rabit/tracker/rabit_sge.py#L47-L67
train
apple/turicreate
src/unity/python/turicreate/meta/asttools/visitors/print_visitor.py
dump_ast
def dump_ast(ast, indent=' ', newline='\n'): ''' Returns a string representing the ast. :param ast: the ast to print. :param indent: how far to indent a newline. :param newline: The newline character. ''' visitor = ASTPrinter(indent=indent, level=0, newline=newline) visitor.visit(ast) return visitor.dumps()
python
def dump_ast(ast, indent=' ', newline='\n'): ''' Returns a string representing the ast. :param ast: the ast to print. :param indent: how far to indent a newline. :param newline: The newline character. ''' visitor = ASTPrinter(indent=indent, level=0, newline=newline) visitor.visit(ast) return visitor.dumps()
[ "def", "dump_ast", "(", "ast", ",", "indent", "=", "' '", ",", "newline", "=", "'\\n'", ")", ":", "visitor", "=", "ASTPrinter", "(", "indent", "=", "indent", ",", "level", "=", "0", ",", "newline", "=", "newline", ")", "visitor", ".", "visit", "(", "ast", ")", "return", "visitor", ".", "dumps", "(", ")" ]
Returns a string representing the ast. :param ast: the ast to print. :param indent: how far to indent a newline. :param newline: The newline character.
[ "Returns", "a", "string", "representing", "the", "ast", ".", ":", "param", "ast", ":", "the", "ast", "to", "print", ".", ":", "param", "indent", ":", "how", "far", "to", "indent", "a", "newline", ".", ":", "param", "newline", ":", "The", "newline", "character", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/asttools/visitors/print_visitor.py#L151-L164
train
apple/turicreate
src/unity/python/turicreate/meta/asttools/visitors/print_visitor.py
print_ast
def print_ast(ast, indent=' ', initlevel=0, newline='\n', file=sys.stdout): ''' Pretty print an ast node. :param ast: the ast to print. :param indent: how far to indent a newline. :param initlevel: starting indent level :param newline: The newline character. :param file: file object to print to To print a short ast you may want to use:: node = ast.parse(source) print_ast(node, indent='', newline='') ''' visitor = ASTPrinter(indent=indent, level=initlevel, newline=newline) visitor.visit(ast) visitor.dump(file=file)
python
def print_ast(ast, indent=' ', initlevel=0, newline='\n', file=sys.stdout): ''' Pretty print an ast node. :param ast: the ast to print. :param indent: how far to indent a newline. :param initlevel: starting indent level :param newline: The newline character. :param file: file object to print to To print a short ast you may want to use:: node = ast.parse(source) print_ast(node, indent='', newline='') ''' visitor = ASTPrinter(indent=indent, level=initlevel, newline=newline) visitor.visit(ast) visitor.dump(file=file)
[ "def", "print_ast", "(", "ast", ",", "indent", "=", "' '", ",", "initlevel", "=", "0", ",", "newline", "=", "'\\n'", ",", "file", "=", "sys", ".", "stdout", ")", ":", "visitor", "=", "ASTPrinter", "(", "indent", "=", "indent", ",", "level", "=", "initlevel", ",", "newline", "=", "newline", ")", "visitor", ".", "visit", "(", "ast", ")", "visitor", ".", "dump", "(", "file", "=", "file", ")" ]
Pretty print an ast node. :param ast: the ast to print. :param indent: how far to indent a newline. :param initlevel: starting indent level :param newline: The newline character. :param file: file object to print to To print a short ast you may want to use:: node = ast.parse(source) print_ast(node, indent='', newline='')
[ "Pretty", "print", "an", "ast", "node", ".", ":", "param", "ast", ":", "the", "ast", "to", "print", ".", ":", "param", "indent", ":", "how", "far", "to", "indent", "a", "newline", ".", ":", "param", "initlevel", ":", "starting", "indent", "level", ":", "param", "newline", ":", "The", "newline", "character", ".", ":", "param", "file", ":", "file", "object", "to", "print", "to", "To", "print", "a", "short", "ast", "you", "may", "want", "to", "use", "::", "node", "=", "ast", ".", "parse", "(", "source", ")", "print_ast", "(", "node", "indent", "=", "newline", "=", ")" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/asttools/visitors/print_visitor.py#L166-L185
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
ctypes2numpy
def ctypes2numpy(cptr, length, dtype): """Convert a ctypes pointer array to a numpy array. """ if not isinstance(cptr, ctypes.POINTER(ctypes.c_float)): raise RuntimeError('expected float pointer') res = np.zeros(length, dtype=dtype) if not ctypes.memmove(res.ctypes.data, cptr, length * res.strides[0]): raise RuntimeError('memmove failed') return res
python
def ctypes2numpy(cptr, length, dtype): """Convert a ctypes pointer array to a numpy array. """ if not isinstance(cptr, ctypes.POINTER(ctypes.c_float)): raise RuntimeError('expected float pointer') res = np.zeros(length, dtype=dtype) if not ctypes.memmove(res.ctypes.data, cptr, length * res.strides[0]): raise RuntimeError('memmove failed') return res
[ "def", "ctypes2numpy", "(", "cptr", ",", "length", ",", "dtype", ")", ":", "if", "not", "isinstance", "(", "cptr", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_float", ")", ")", ":", "raise", "RuntimeError", "(", "'expected float pointer'", ")", "res", "=", "np", ".", "zeros", "(", "length", ",", "dtype", "=", "dtype", ")", "if", "not", "ctypes", ".", "memmove", "(", "res", ".", "ctypes", ".", "data", ",", "cptr", ",", "length", "*", "res", ".", "strides", "[", "0", "]", ")", ":", "raise", "RuntimeError", "(", "'memmove failed'", ")", "return", "res" ]
Convert a ctypes pointer array to a numpy array.
[ "Convert", "a", "ctypes", "pointer", "array", "to", "a", "numpy", "array", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L109-L117
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
_maybe_from_pandas
def _maybe_from_pandas(data, feature_names, feature_types): """ Extract internal data from pd.DataFrame """ try: import pandas as pd except ImportError: return data, feature_names, feature_types if not isinstance(data, pd.DataFrame): return data, feature_names, feature_types dtypes = data.dtypes if not all(dtype.name in ('int64', 'float64', 'bool') for dtype in dtypes): raise ValueError('DataFrame.dtypes must be int, float or bool') if feature_names is None: feature_names = data.columns.format() if feature_types is None: mapper = {'int64': 'int', 'float64': 'q', 'bool': 'i'} feature_types = [mapper[dtype.name] for dtype in dtypes] data = data.values.astype('float') return data, feature_names, feature_types
python
def _maybe_from_pandas(data, feature_names, feature_types): """ Extract internal data from pd.DataFrame """ try: import pandas as pd except ImportError: return data, feature_names, feature_types if not isinstance(data, pd.DataFrame): return data, feature_names, feature_types dtypes = data.dtypes if not all(dtype.name in ('int64', 'float64', 'bool') for dtype in dtypes): raise ValueError('DataFrame.dtypes must be int, float or bool') if feature_names is None: feature_names = data.columns.format() if feature_types is None: mapper = {'int64': 'int', 'float64': 'q', 'bool': 'i'} feature_types = [mapper[dtype.name] for dtype in dtypes] data = data.values.astype('float') return data, feature_names, feature_types
[ "def", "_maybe_from_pandas", "(", "data", ",", "feature_names", ",", "feature_types", ")", ":", "try", ":", "import", "pandas", "as", "pd", "except", "ImportError", ":", "return", "data", ",", "feature_names", ",", "feature_types", "if", "not", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", ":", "return", "data", ",", "feature_names", ",", "feature_types", "dtypes", "=", "data", ".", "dtypes", "if", "not", "all", "(", "dtype", ".", "name", "in", "(", "'int64'", ",", "'float64'", ",", "'bool'", ")", "for", "dtype", "in", "dtypes", ")", ":", "raise", "ValueError", "(", "'DataFrame.dtypes must be int, float or bool'", ")", "if", "feature_names", "is", "None", ":", "feature_names", "=", "data", ".", "columns", ".", "format", "(", ")", "if", "feature_types", "is", "None", ":", "mapper", "=", "{", "'int64'", ":", "'int'", ",", "'float64'", ":", "'q'", ",", "'bool'", ":", "'i'", "}", "feature_types", "=", "[", "mapper", "[", "dtype", ".", "name", "]", "for", "dtype", "in", "dtypes", "]", "data", "=", "data", ".", "values", ".", "astype", "(", "'float'", ")", "return", "data", ",", "feature_names", ",", "feature_types" ]
Extract internal data from pd.DataFrame
[ "Extract", "internal", "data", "from", "pd", ".", "DataFrame" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L141-L161
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
DMatrix._init_from_csr
def _init_from_csr(self, csr): """ Initialize data from a CSR matrix. """ if len(csr.indices) != len(csr.data): raise ValueError('length mismatch: {} vs {}'.format(len(csr.indices), len(csr.data))) self.handle = ctypes.c_void_p() _check_call(_LIB.XGDMatrixCreateFromCSR(c_array(ctypes.c_ulong, csr.indptr), c_array(ctypes.c_uint, csr.indices), c_array(ctypes.c_float, csr.data), len(csr.indptr), len(csr.data), ctypes.byref(self.handle)))
python
def _init_from_csr(self, csr): """ Initialize data from a CSR matrix. """ if len(csr.indices) != len(csr.data): raise ValueError('length mismatch: {} vs {}'.format(len(csr.indices), len(csr.data))) self.handle = ctypes.c_void_p() _check_call(_LIB.XGDMatrixCreateFromCSR(c_array(ctypes.c_ulong, csr.indptr), c_array(ctypes.c_uint, csr.indices), c_array(ctypes.c_float, csr.data), len(csr.indptr), len(csr.data), ctypes.byref(self.handle)))
[ "def", "_init_from_csr", "(", "self", ",", "csr", ")", ":", "if", "len", "(", "csr", ".", "indices", ")", "!=", "len", "(", "csr", ".", "data", ")", ":", "raise", "ValueError", "(", "'length mismatch: {} vs {}'", ".", "format", "(", "len", "(", "csr", ".", "indices", ")", ",", "len", "(", "csr", ".", "data", ")", ")", ")", "self", ".", "handle", "=", "ctypes", ".", "c_void_p", "(", ")", "_check_call", "(", "_LIB", ".", "XGDMatrixCreateFromCSR", "(", "c_array", "(", "ctypes", ".", "c_ulong", ",", "csr", ".", "indptr", ")", ",", "c_array", "(", "ctypes", ".", "c_uint", ",", "csr", ".", "indices", ")", ",", "c_array", "(", "ctypes", ".", "c_float", ",", "csr", ".", "data", ")", ",", "len", "(", "csr", ".", "indptr", ")", ",", "len", "(", "csr", ".", "data", ")", ",", "ctypes", ".", "byref", "(", "self", ".", "handle", ")", ")", ")" ]
Initialize data from a CSR matrix.
[ "Initialize", "data", "from", "a", "CSR", "matrix", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L235-L246
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
DMatrix._init_from_csc
def _init_from_csc(self, csc): """ Initialize data from a CSC matrix. """ if len(csc.indices) != len(csc.data): raise ValueError('length mismatch: {} vs {}'.format(len(csc.indices), len(csc.data))) self.handle = ctypes.c_void_p() _check_call(_LIB.XGDMatrixCreateFromCSC(c_array(ctypes.c_ulong, csc.indptr), c_array(ctypes.c_uint, csc.indices), c_array(ctypes.c_float, csc.data), len(csc.indptr), len(csc.data), ctypes.byref(self.handle)))
python
def _init_from_csc(self, csc): """ Initialize data from a CSC matrix. """ if len(csc.indices) != len(csc.data): raise ValueError('length mismatch: {} vs {}'.format(len(csc.indices), len(csc.data))) self.handle = ctypes.c_void_p() _check_call(_LIB.XGDMatrixCreateFromCSC(c_array(ctypes.c_ulong, csc.indptr), c_array(ctypes.c_uint, csc.indices), c_array(ctypes.c_float, csc.data), len(csc.indptr), len(csc.data), ctypes.byref(self.handle)))
[ "def", "_init_from_csc", "(", "self", ",", "csc", ")", ":", "if", "len", "(", "csc", ".", "indices", ")", "!=", "len", "(", "csc", ".", "data", ")", ":", "raise", "ValueError", "(", "'length mismatch: {} vs {}'", ".", "format", "(", "len", "(", "csc", ".", "indices", ")", ",", "len", "(", "csc", ".", "data", ")", ")", ")", "self", ".", "handle", "=", "ctypes", ".", "c_void_p", "(", ")", "_check_call", "(", "_LIB", ".", "XGDMatrixCreateFromCSC", "(", "c_array", "(", "ctypes", ".", "c_ulong", ",", "csc", ".", "indptr", ")", ",", "c_array", "(", "ctypes", ".", "c_uint", ",", "csc", ".", "indices", ")", ",", "c_array", "(", "ctypes", ".", "c_float", ",", "csc", ".", "data", ")", ",", "len", "(", "csc", ".", "indptr", ")", ",", "len", "(", "csc", ".", "data", ")", ",", "ctypes", ".", "byref", "(", "self", ".", "handle", ")", ")", ")" ]
Initialize data from a CSC matrix.
[ "Initialize", "data", "from", "a", "CSC", "matrix", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L248-L259
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
DMatrix._init_from_npy2d
def _init_from_npy2d(self, mat, missing): """ Initialize data from a 2-D numpy matrix. """ if len(mat.shape) != 2: raise ValueError('Input numpy.ndarray must be 2 dimensional') data = np.array(mat.reshape(mat.size), dtype=np.float32) self.handle = ctypes.c_void_p() _check_call(_LIB.XGDMatrixCreateFromMat(data.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), mat.shape[0], mat.shape[1], ctypes.c_float(missing), ctypes.byref(self.handle)))
python
def _init_from_npy2d(self, mat, missing): """ Initialize data from a 2-D numpy matrix. """ if len(mat.shape) != 2: raise ValueError('Input numpy.ndarray must be 2 dimensional') data = np.array(mat.reshape(mat.size), dtype=np.float32) self.handle = ctypes.c_void_p() _check_call(_LIB.XGDMatrixCreateFromMat(data.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), mat.shape[0], mat.shape[1], ctypes.c_float(missing), ctypes.byref(self.handle)))
[ "def", "_init_from_npy2d", "(", "self", ",", "mat", ",", "missing", ")", ":", "if", "len", "(", "mat", ".", "shape", ")", "!=", "2", ":", "raise", "ValueError", "(", "'Input numpy.ndarray must be 2 dimensional'", ")", "data", "=", "np", ".", "array", "(", "mat", ".", "reshape", "(", "mat", ".", "size", ")", ",", "dtype", "=", "np", ".", "float32", ")", "self", ".", "handle", "=", "ctypes", ".", "c_void_p", "(", ")", "_check_call", "(", "_LIB", ".", "XGDMatrixCreateFromMat", "(", "data", ".", "ctypes", ".", "data_as", "(", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_float", ")", ")", ",", "mat", ".", "shape", "[", "0", "]", ",", "mat", ".", "shape", "[", "1", "]", ",", "ctypes", ".", "c_float", "(", "missing", ")", ",", "ctypes", ".", "byref", "(", "self", ".", "handle", ")", ")", ")" ]
Initialize data from a 2-D numpy matrix.
[ "Initialize", "data", "from", "a", "2", "-", "D", "numpy", "matrix", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L261-L272
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
DMatrix.get_float_info
def get_float_info(self, field): """Get float property from the DMatrix. Parameters ---------- field: str The field name of the information Returns ------- info : array a numpy array of float information of the data """ length = ctypes.c_ulong() ret = ctypes.POINTER(ctypes.c_float)() _check_call(_LIB.XGDMatrixGetFloatInfo(self.handle, c_str(field), ctypes.byref(length), ctypes.byref(ret))) return ctypes2numpy(ret, length.value, np.float32)
python
def get_float_info(self, field): """Get float property from the DMatrix. Parameters ---------- field: str The field name of the information Returns ------- info : array a numpy array of float information of the data """ length = ctypes.c_ulong() ret = ctypes.POINTER(ctypes.c_float)() _check_call(_LIB.XGDMatrixGetFloatInfo(self.handle, c_str(field), ctypes.byref(length), ctypes.byref(ret))) return ctypes2numpy(ret, length.value, np.float32)
[ "def", "get_float_info", "(", "self", ",", "field", ")", ":", "length", "=", "ctypes", ".", "c_ulong", "(", ")", "ret", "=", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_float", ")", "(", ")", "_check_call", "(", "_LIB", ".", "XGDMatrixGetFloatInfo", "(", "self", ".", "handle", ",", "c_str", "(", "field", ")", ",", "ctypes", ".", "byref", "(", "length", ")", ",", "ctypes", ".", "byref", "(", "ret", ")", ")", ")", "return", "ctypes2numpy", "(", "ret", ",", "length", ".", "value", ",", "np", ".", "float32", ")" ]
Get float property from the DMatrix. Parameters ---------- field: str The field name of the information Returns ------- info : array a numpy array of float information of the data
[ "Get", "float", "property", "from", "the", "DMatrix", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L277-L296
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
DMatrix.get_uint_info
def get_uint_info(self, field): """Get unsigned integer property from the DMatrix. Parameters ---------- field: str The field name of the information Returns ------- info : array a numpy array of float information of the data """ length = ctypes.c_ulong() ret = ctypes.POINTER(ctypes.c_uint)() _check_call(_LIB.XGDMatrixGetUIntInfo(self.handle, c_str(field), ctypes.byref(length), ctypes.byref(ret))) return ctypes2numpy(ret, length.value, np.uint32)
python
def get_uint_info(self, field): """Get unsigned integer property from the DMatrix. Parameters ---------- field: str The field name of the information Returns ------- info : array a numpy array of float information of the data """ length = ctypes.c_ulong() ret = ctypes.POINTER(ctypes.c_uint)() _check_call(_LIB.XGDMatrixGetUIntInfo(self.handle, c_str(field), ctypes.byref(length), ctypes.byref(ret))) return ctypes2numpy(ret, length.value, np.uint32)
[ "def", "get_uint_info", "(", "self", ",", "field", ")", ":", "length", "=", "ctypes", ".", "c_ulong", "(", ")", "ret", "=", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_uint", ")", "(", ")", "_check_call", "(", "_LIB", ".", "XGDMatrixGetUIntInfo", "(", "self", ".", "handle", ",", "c_str", "(", "field", ")", ",", "ctypes", ".", "byref", "(", "length", ")", ",", "ctypes", ".", "byref", "(", "ret", ")", ")", ")", "return", "ctypes2numpy", "(", "ret", ",", "length", ".", "value", ",", "np", ".", "uint32", ")" ]
Get unsigned integer property from the DMatrix. Parameters ---------- field: str The field name of the information Returns ------- info : array a numpy array of float information of the data
[ "Get", "unsigned", "integer", "property", "from", "the", "DMatrix", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L298-L317
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
DMatrix.set_float_info
def set_float_info(self, field, data): """Set float type property into the DMatrix. Parameters ---------- field: str The field name of the information data: numpy array The array ofdata to be set """ _check_call(_LIB.XGDMatrixSetFloatInfo(self.handle, c_str(field), c_array(ctypes.c_float, data), len(data)))
python
def set_float_info(self, field, data): """Set float type property into the DMatrix. Parameters ---------- field: str The field name of the information data: numpy array The array ofdata to be set """ _check_call(_LIB.XGDMatrixSetFloatInfo(self.handle, c_str(field), c_array(ctypes.c_float, data), len(data)))
[ "def", "set_float_info", "(", "self", ",", "field", ",", "data", ")", ":", "_check_call", "(", "_LIB", ".", "XGDMatrixSetFloatInfo", "(", "self", ".", "handle", ",", "c_str", "(", "field", ")", ",", "c_array", "(", "ctypes", ".", "c_float", ",", "data", ")", ",", "len", "(", "data", ")", ")", ")" ]
Set float type property into the DMatrix. Parameters ---------- field: str The field name of the information data: numpy array The array ofdata to be set
[ "Set", "float", "type", "property", "into", "the", "DMatrix", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L319-L333
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
DMatrix.set_uint_info
def set_uint_info(self, field, data): """Set uint type property into the DMatrix. Parameters ---------- field: str The field name of the information data: numpy array The array ofdata to be set """ _check_call(_LIB.XGDMatrixSetUIntInfo(self.handle, c_str(field), c_array(ctypes.c_uint, data), len(data)))
python
def set_uint_info(self, field, data): """Set uint type property into the DMatrix. Parameters ---------- field: str The field name of the information data: numpy array The array ofdata to be set """ _check_call(_LIB.XGDMatrixSetUIntInfo(self.handle, c_str(field), c_array(ctypes.c_uint, data), len(data)))
[ "def", "set_uint_info", "(", "self", ",", "field", ",", "data", ")", ":", "_check_call", "(", "_LIB", ".", "XGDMatrixSetUIntInfo", "(", "self", ".", "handle", ",", "c_str", "(", "field", ")", ",", "c_array", "(", "ctypes", ".", "c_uint", ",", "data", ")", ",", "len", "(", "data", ")", ")", ")" ]
Set uint type property into the DMatrix. Parameters ---------- field: str The field name of the information data: numpy array The array ofdata to be set
[ "Set", "uint", "type", "property", "into", "the", "DMatrix", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L335-L349
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
DMatrix.save_binary
def save_binary(self, fname, silent=True): """Save DMatrix to an XGBoost buffer. Parameters ---------- fname : string Name of the output buffer file. silent : bool (optional; default: True) If set, the output is suppressed. """ _check_call(_LIB.XGDMatrixSaveBinary(self.handle, c_str(fname), int(silent)))
python
def save_binary(self, fname, silent=True): """Save DMatrix to an XGBoost buffer. Parameters ---------- fname : string Name of the output buffer file. silent : bool (optional; default: True) If set, the output is suppressed. """ _check_call(_LIB.XGDMatrixSaveBinary(self.handle, c_str(fname), int(silent)))
[ "def", "save_binary", "(", "self", ",", "fname", ",", "silent", "=", "True", ")", ":", "_check_call", "(", "_LIB", ".", "XGDMatrixSaveBinary", "(", "self", ".", "handle", ",", "c_str", "(", "fname", ")", ",", "int", "(", "silent", ")", ")", ")" ]
Save DMatrix to an XGBoost buffer. Parameters ---------- fname : string Name of the output buffer file. silent : bool (optional; default: True) If set, the output is suppressed.
[ "Save", "DMatrix", "to", "an", "XGBoost", "buffer", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L351-L363
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
DMatrix.num_row
def num_row(self): """Get the number of rows in the DMatrix. Returns ------- number of rows : int """ ret = ctypes.c_ulong() _check_call(_LIB.XGDMatrixNumRow(self.handle, ctypes.byref(ret))) return ret.value
python
def num_row(self): """Get the number of rows in the DMatrix. Returns ------- number of rows : int """ ret = ctypes.c_ulong() _check_call(_LIB.XGDMatrixNumRow(self.handle, ctypes.byref(ret))) return ret.value
[ "def", "num_row", "(", "self", ")", ":", "ret", "=", "ctypes", ".", "c_ulong", "(", ")", "_check_call", "(", "_LIB", ".", "XGDMatrixNumRow", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "ret", ")", ")", ")", "return", "ret", ".", "value" ]
Get the number of rows in the DMatrix. Returns ------- number of rows : int
[ "Get", "the", "number", "of", "rows", "in", "the", "DMatrix", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L440-L450
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
DMatrix.num_col
def num_col(self): """Get the number of columns (features) in the DMatrix. Returns ------- number of columns : int """ ret = ctypes.c_uint() _check_call(_LIB.XGDMatrixNumCol(self.handle, ctypes.byref(ret))) return ret.value
python
def num_col(self): """Get the number of columns (features) in the DMatrix. Returns ------- number of columns : int """ ret = ctypes.c_uint() _check_call(_LIB.XGDMatrixNumCol(self.handle, ctypes.byref(ret))) return ret.value
[ "def", "num_col", "(", "self", ")", ":", "ret", "=", "ctypes", ".", "c_uint", "(", ")", "_check_call", "(", "_LIB", ".", "XGDMatrixNumCol", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "ret", ")", ")", ")", "return", "ret", ".", "value" ]
Get the number of columns (features) in the DMatrix. Returns ------- number of columns : int
[ "Get", "the", "number", "of", "columns", "(", "features", ")", "in", "the", "DMatrix", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L452-L462
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
DMatrix.slice
def slice(self, rindex): """Slice the DMatrix and return a new DMatrix that only contains `rindex`. Parameters ---------- rindex : list List of indices to be selected. Returns ------- res : DMatrix A new DMatrix containing only selected indices. """ res = DMatrix(None, feature_names=self.feature_names) res.handle = ctypes.c_void_p() _check_call(_LIB.XGDMatrixSliceDMatrix(self.handle, c_array(ctypes.c_int, rindex), len(rindex), ctypes.byref(res.handle))) return res
python
def slice(self, rindex): """Slice the DMatrix and return a new DMatrix that only contains `rindex`. Parameters ---------- rindex : list List of indices to be selected. Returns ------- res : DMatrix A new DMatrix containing only selected indices. """ res = DMatrix(None, feature_names=self.feature_names) res.handle = ctypes.c_void_p() _check_call(_LIB.XGDMatrixSliceDMatrix(self.handle, c_array(ctypes.c_int, rindex), len(rindex), ctypes.byref(res.handle))) return res
[ "def", "slice", "(", "self", ",", "rindex", ")", ":", "res", "=", "DMatrix", "(", "None", ",", "feature_names", "=", "self", ".", "feature_names", ")", "res", ".", "handle", "=", "ctypes", ".", "c_void_p", "(", ")", "_check_call", "(", "_LIB", ".", "XGDMatrixSliceDMatrix", "(", "self", ".", "handle", ",", "c_array", "(", "ctypes", ".", "c_int", ",", "rindex", ")", ",", "len", "(", "rindex", ")", ",", "ctypes", ".", "byref", "(", "res", ".", "handle", ")", ")", ")", "return", "res" ]
Slice the DMatrix and return a new DMatrix that only contains `rindex`. Parameters ---------- rindex : list List of indices to be selected. Returns ------- res : DMatrix A new DMatrix containing only selected indices.
[ "Slice", "the", "DMatrix", "and", "return", "a", "new", "DMatrix", "that", "only", "contains", "rindex", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L464-L483
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
DMatrix.feature_names
def feature_names(self, feature_names): """Set feature names (column labels). Parameters ---------- feature_names : list or None Labels for features. None will reset existing feature names """ if not feature_names is None: # validate feature name if not isinstance(feature_names, list): feature_names = list(feature_names) if len(feature_names) != len(set(feature_names)): raise ValueError('feature_names must be unique') if len(feature_names) != self.num_col(): msg = 'feature_names must have the same length as data' raise ValueError(msg) # prohibit to use symbols may affect to parse. e.g. ``[]=.`` if not all(isinstance(f, STRING_TYPES) and f.isalnum() for f in feature_names): raise ValueError('all feature_names must be alphanumerics') else: # reset feature_types also self.feature_types = None self._feature_names = feature_names
python
def feature_names(self, feature_names): """Set feature names (column labels). Parameters ---------- feature_names : list or None Labels for features. None will reset existing feature names """ if not feature_names is None: # validate feature name if not isinstance(feature_names, list): feature_names = list(feature_names) if len(feature_names) != len(set(feature_names)): raise ValueError('feature_names must be unique') if len(feature_names) != self.num_col(): msg = 'feature_names must have the same length as data' raise ValueError(msg) # prohibit to use symbols may affect to parse. e.g. ``[]=.`` if not all(isinstance(f, STRING_TYPES) and f.isalnum() for f in feature_names): raise ValueError('all feature_names must be alphanumerics') else: # reset feature_types also self.feature_types = None self._feature_names = feature_names
[ "def", "feature_names", "(", "self", ",", "feature_names", ")", ":", "if", "not", "feature_names", "is", "None", ":", "# validate feature name", "if", "not", "isinstance", "(", "feature_names", ",", "list", ")", ":", "feature_names", "=", "list", "(", "feature_names", ")", "if", "len", "(", "feature_names", ")", "!=", "len", "(", "set", "(", "feature_names", ")", ")", ":", "raise", "ValueError", "(", "'feature_names must be unique'", ")", "if", "len", "(", "feature_names", ")", "!=", "self", ".", "num_col", "(", ")", ":", "msg", "=", "'feature_names must have the same length as data'", "raise", "ValueError", "(", "msg", ")", "# prohibit to use symbols may affect to parse. e.g. ``[]=.``", "if", "not", "all", "(", "isinstance", "(", "f", ",", "STRING_TYPES", ")", "and", "f", ".", "isalnum", "(", ")", "for", "f", "in", "feature_names", ")", ":", "raise", "ValueError", "(", "'all feature_names must be alphanumerics'", ")", "else", ":", "# reset feature_types also", "self", ".", "feature_types", "=", "None", "self", ".", "_feature_names", "=", "feature_names" ]
Set feature names (column labels). Parameters ---------- feature_names : list or None Labels for features. None will reset existing feature names
[ "Set", "feature", "names", "(", "column", "labels", ")", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L506-L530
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
DMatrix.feature_types
def feature_types(self, feature_types): """Set feature types (column types). This is for displaying the results and unrelated to the learning process. Parameters ---------- feature_types : list or None Labels for features. None will reset existing feature names """ if not feature_types is None: if self.feature_names is None: msg = 'Unable to set feature types before setting names' raise ValueError(msg) if isinstance(feature_types, STRING_TYPES): # single string will be applied to all columns feature_types = [feature_types] * self.num_col() if not isinstance(feature_types, list): feature_types = list(feature_types) if len(feature_types) != self.num_col(): msg = 'feature_types must have the same length as data' raise ValueError(msg) # prohibit to use symbols may affect to parse. e.g. ``[]=.`` valid = ('q', 'i', 'int', 'float') if not all(isinstance(f, STRING_TYPES) and f in valid for f in feature_types): raise ValueError('all feature_names must be {i, q, int, float}') self._feature_types = feature_types
python
def feature_types(self, feature_types): """Set feature types (column types). This is for displaying the results and unrelated to the learning process. Parameters ---------- feature_types : list or None Labels for features. None will reset existing feature names """ if not feature_types is None: if self.feature_names is None: msg = 'Unable to set feature types before setting names' raise ValueError(msg) if isinstance(feature_types, STRING_TYPES): # single string will be applied to all columns feature_types = [feature_types] * self.num_col() if not isinstance(feature_types, list): feature_types = list(feature_types) if len(feature_types) != self.num_col(): msg = 'feature_types must have the same length as data' raise ValueError(msg) # prohibit to use symbols may affect to parse. e.g. ``[]=.`` valid = ('q', 'i', 'int', 'float') if not all(isinstance(f, STRING_TYPES) and f in valid for f in feature_types): raise ValueError('all feature_names must be {i, q, int, float}') self._feature_types = feature_types
[ "def", "feature_types", "(", "self", ",", "feature_types", ")", ":", "if", "not", "feature_types", "is", "None", ":", "if", "self", ".", "feature_names", "is", "None", ":", "msg", "=", "'Unable to set feature types before setting names'", "raise", "ValueError", "(", "msg", ")", "if", "isinstance", "(", "feature_types", ",", "STRING_TYPES", ")", ":", "# single string will be applied to all columns", "feature_types", "=", "[", "feature_types", "]", "*", "self", ".", "num_col", "(", ")", "if", "not", "isinstance", "(", "feature_types", ",", "list", ")", ":", "feature_types", "=", "list", "(", "feature_types", ")", "if", "len", "(", "feature_types", ")", "!=", "self", ".", "num_col", "(", ")", ":", "msg", "=", "'feature_types must have the same length as data'", "raise", "ValueError", "(", "msg", ")", "# prohibit to use symbols may affect to parse. e.g. ``[]=.``", "valid", "=", "(", "'q'", ",", "'i'", ",", "'int'", ",", "'float'", ")", "if", "not", "all", "(", "isinstance", "(", "f", ",", "STRING_TYPES", ")", "and", "f", "in", "valid", "for", "f", "in", "feature_types", ")", ":", "raise", "ValueError", "(", "'all feature_names must be {i, q, int, float}'", ")", "self", ".", "_feature_types", "=", "feature_types" ]
Set feature types (column types). This is for displaying the results and unrelated to the learning process. Parameters ---------- feature_types : list or None Labels for features. None will reset existing feature names
[ "Set", "feature", "types", "(", "column", "types", ")", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L533-L565
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
Booster.update
def update(self, dtrain, iteration, fobj=None): """ Update for one iteration, with objective function calculated internally. Parameters ---------- dtrain : DMatrix Training data. iteration : int Current iteration number. fobj : function Customized objective function. """ if not isinstance(dtrain, DMatrix): raise TypeError('invalid training matrix: {}'.format(type(dtrain).__name__)) self._validate_features(dtrain) if fobj is None: _check_call(_LIB.XGBoosterUpdateOneIter(self.handle, iteration, dtrain.handle)) else: pred = self.predict(dtrain) grad, hess = fobj(pred, dtrain) self.boost(dtrain, grad, hess)
python
def update(self, dtrain, iteration, fobj=None): """ Update for one iteration, with objective function calculated internally. Parameters ---------- dtrain : DMatrix Training data. iteration : int Current iteration number. fobj : function Customized objective function. """ if not isinstance(dtrain, DMatrix): raise TypeError('invalid training matrix: {}'.format(type(dtrain).__name__)) self._validate_features(dtrain) if fobj is None: _check_call(_LIB.XGBoosterUpdateOneIter(self.handle, iteration, dtrain.handle)) else: pred = self.predict(dtrain) grad, hess = fobj(pred, dtrain) self.boost(dtrain, grad, hess)
[ "def", "update", "(", "self", ",", "dtrain", ",", "iteration", ",", "fobj", "=", "None", ")", ":", "if", "not", "isinstance", "(", "dtrain", ",", "DMatrix", ")", ":", "raise", "TypeError", "(", "'invalid training matrix: {}'", ".", "format", "(", "type", "(", "dtrain", ")", ".", "__name__", ")", ")", "self", ".", "_validate_features", "(", "dtrain", ")", "if", "fobj", "is", "None", ":", "_check_call", "(", "_LIB", ".", "XGBoosterUpdateOneIter", "(", "self", ".", "handle", ",", "iteration", ",", "dtrain", ".", "handle", ")", ")", "else", ":", "pred", "=", "self", ".", "predict", "(", "dtrain", ")", "grad", ",", "hess", "=", "fobj", "(", "pred", ",", "dtrain", ")", "self", ".", "boost", "(", "dtrain", ",", "grad", ",", "hess", ")" ]
Update for one iteration, with objective function calculated internally. Parameters ---------- dtrain : DMatrix Training data. iteration : int Current iteration number. fobj : function Customized objective function.
[ "Update", "for", "one", "iteration", "with", "objective", "function", "calculated", "internally", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L664-L686
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
Booster.boost
def boost(self, dtrain, grad, hess): """ Boost the booster for one iteration, with customized gradient statistics. Parameters ---------- dtrain : DMatrix The training DMatrix. grad : list The first order of gradient. hess : list The second order of gradient. """ if len(grad) != len(hess): raise ValueError('grad / hess length mismatch: {} / {}'.format(len(grad), len(hess))) if not isinstance(dtrain, DMatrix): raise TypeError('invalid training matrix: {}'.format(type(dtrain).__name__)) self._validate_features(dtrain) _check_call(_LIB.XGBoosterBoostOneIter(self.handle, dtrain.handle, c_array(ctypes.c_float, grad), c_array(ctypes.c_float, hess), len(grad)))
python
def boost(self, dtrain, grad, hess): """ Boost the booster for one iteration, with customized gradient statistics. Parameters ---------- dtrain : DMatrix The training DMatrix. grad : list The first order of gradient. hess : list The second order of gradient. """ if len(grad) != len(hess): raise ValueError('grad / hess length mismatch: {} / {}'.format(len(grad), len(hess))) if not isinstance(dtrain, DMatrix): raise TypeError('invalid training matrix: {}'.format(type(dtrain).__name__)) self._validate_features(dtrain) _check_call(_LIB.XGBoosterBoostOneIter(self.handle, dtrain.handle, c_array(ctypes.c_float, grad), c_array(ctypes.c_float, hess), len(grad)))
[ "def", "boost", "(", "self", ",", "dtrain", ",", "grad", ",", "hess", ")", ":", "if", "len", "(", "grad", ")", "!=", "len", "(", "hess", ")", ":", "raise", "ValueError", "(", "'grad / hess length mismatch: {} / {}'", ".", "format", "(", "len", "(", "grad", ")", ",", "len", "(", "hess", ")", ")", ")", "if", "not", "isinstance", "(", "dtrain", ",", "DMatrix", ")", ":", "raise", "TypeError", "(", "'invalid training matrix: {}'", ".", "format", "(", "type", "(", "dtrain", ")", ".", "__name__", ")", ")", "self", ".", "_validate_features", "(", "dtrain", ")", "_check_call", "(", "_LIB", ".", "XGBoosterBoostOneIter", "(", "self", ".", "handle", ",", "dtrain", ".", "handle", ",", "c_array", "(", "ctypes", ".", "c_float", ",", "grad", ")", ",", "c_array", "(", "ctypes", ".", "c_float", ",", "hess", ")", ",", "len", "(", "grad", ")", ")", ")" ]
Boost the booster for one iteration, with customized gradient statistics. Parameters ---------- dtrain : DMatrix The training DMatrix. grad : list The first order of gradient. hess : list The second order of gradient.
[ "Boost", "the", "booster", "for", "one", "iteration", "with", "customized", "gradient", "statistics", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L688-L710
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
Booster.eval_set
def eval_set(self, evals, iteration=0, feval=None): # pylint: disable=invalid-name """Evaluate a set of data. Parameters ---------- evals : list of tuples (DMatrix, string) List of items to be evaluated. iteration : int Current iteration. feval : function Custom evaluation function. Returns ------- result: str Evaluation result string. """ if feval is None: for d in evals: if not isinstance(d[0], DMatrix): raise TypeError('expected DMatrix, got {}'.format(type(d[0]).__name__)) if not isinstance(d[1], STRING_TYPES): raise TypeError('expected string, got {}'.format(type(d[1]).__name__)) self._validate_features(d[0]) dmats = c_array(ctypes.c_void_p, [d[0].handle for d in evals]) evnames = c_array(ctypes.c_char_p, [c_str(d[1]) for d in evals]) msg = ctypes.c_char_p() _check_call(_LIB.XGBoosterEvalOneIter(self.handle, iteration, dmats, evnames, len(evals), ctypes.byref(msg))) return msg.value else: res = '[%d]' % iteration for dmat, evname in evals: name, val = feval(self.predict(dmat), dmat) res += '\t%s-%s:%f' % (evname, name, val) return res
python
def eval_set(self, evals, iteration=0, feval=None): # pylint: disable=invalid-name """Evaluate a set of data. Parameters ---------- evals : list of tuples (DMatrix, string) List of items to be evaluated. iteration : int Current iteration. feval : function Custom evaluation function. Returns ------- result: str Evaluation result string. """ if feval is None: for d in evals: if not isinstance(d[0], DMatrix): raise TypeError('expected DMatrix, got {}'.format(type(d[0]).__name__)) if not isinstance(d[1], STRING_TYPES): raise TypeError('expected string, got {}'.format(type(d[1]).__name__)) self._validate_features(d[0]) dmats = c_array(ctypes.c_void_p, [d[0].handle for d in evals]) evnames = c_array(ctypes.c_char_p, [c_str(d[1]) for d in evals]) msg = ctypes.c_char_p() _check_call(_LIB.XGBoosterEvalOneIter(self.handle, iteration, dmats, evnames, len(evals), ctypes.byref(msg))) return msg.value else: res = '[%d]' % iteration for dmat, evname in evals: name, val = feval(self.predict(dmat), dmat) res += '\t%s-%s:%f' % (evname, name, val) return res
[ "def", "eval_set", "(", "self", ",", "evals", ",", "iteration", "=", "0", ",", "feval", "=", "None", ")", ":", "# pylint: disable=invalid-name", "if", "feval", "is", "None", ":", "for", "d", "in", "evals", ":", "if", "not", "isinstance", "(", "d", "[", "0", "]", ",", "DMatrix", ")", ":", "raise", "TypeError", "(", "'expected DMatrix, got {}'", ".", "format", "(", "type", "(", "d", "[", "0", "]", ")", ".", "__name__", ")", ")", "if", "not", "isinstance", "(", "d", "[", "1", "]", ",", "STRING_TYPES", ")", ":", "raise", "TypeError", "(", "'expected string, got {}'", ".", "format", "(", "type", "(", "d", "[", "1", "]", ")", ".", "__name__", ")", ")", "self", ".", "_validate_features", "(", "d", "[", "0", "]", ")", "dmats", "=", "c_array", "(", "ctypes", ".", "c_void_p", ",", "[", "d", "[", "0", "]", ".", "handle", "for", "d", "in", "evals", "]", ")", "evnames", "=", "c_array", "(", "ctypes", ".", "c_char_p", ",", "[", "c_str", "(", "d", "[", "1", "]", ")", "for", "d", "in", "evals", "]", ")", "msg", "=", "ctypes", ".", "c_char_p", "(", ")", "_check_call", "(", "_LIB", ".", "XGBoosterEvalOneIter", "(", "self", ".", "handle", ",", "iteration", ",", "dmats", ",", "evnames", ",", "len", "(", "evals", ")", ",", "ctypes", ".", "byref", "(", "msg", ")", ")", ")", "return", "msg", ".", "value", "else", ":", "res", "=", "'[%d]'", "%", "iteration", "for", "dmat", ",", "evname", "in", "evals", ":", "name", ",", "val", "=", "feval", "(", "self", ".", "predict", "(", "dmat", ")", ",", "dmat", ")", "res", "+=", "'\\t%s-%s:%f'", "%", "(", "evname", ",", "name", ",", "val", ")", "return", "res" ]
Evaluate a set of data. Parameters ---------- evals : list of tuples (DMatrix, string) List of items to be evaluated. iteration : int Current iteration. feval : function Custom evaluation function. Returns ------- result: str Evaluation result string.
[ "Evaluate", "a", "set", "of", "data", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L712-L750
train