id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
29,500 | apple/turicreate | src/external/xgboost/python-package/xgboost/training.py | cv | def cv(params, dtrain, num_boost_round=10, nfold=3, metrics=(),
obj=None, feval=None, fpreproc=None, as_pandas=True,
show_progress=None, show_stdv=True, seed=0):
# pylint: disable = invalid-name
"""Cross-validation with given paramaters.
Parameters
----------
params : dict
Booster params.
dtrain : DMatrix
Data to be trained.
num_boost_round : int
Number of boosting iterations.
nfold : int
Number of folds in CV.
metrics : list of strings
Evaluation metrics to be watched in CV.
obj : function
Custom objective function.
feval : function
Custom evaluation function.
fpreproc : function
Preprocessing function that takes (dtrain, dtest, param) and returns
transformed versions of those.
as_pandas : bool, default True
Return pd.DataFrame when pandas is installed.
If False or pandas is not installed, return np.ndarray
show_progress : bool or None, default None
Whether to display the progress. If None, progress will be displayed
when np.ndarray is returned.
show_stdv : bool, default True
Whether to display the standard deviation in progress.
Results are not affected, and always contains std.
seed : int
Seed used to generate the folds (passed to numpy.random.seed).
Returns
-------
evaluation history : list(string)
"""
results = []
cvfolds = mknfold(dtrain, nfold, params, seed, metrics, fpreproc)
for i in range(num_boost_round):
for fold in cvfolds:
fold.update(i, obj)
res = aggcv([f.eval(i, feval) for f in cvfolds],
show_stdv=show_stdv, show_progress=show_progress,
as_pandas=as_pandas)
results.append(res)
if as_pandas:
try:
import pandas as pd
results = pd.DataFrame(results)
except ImportError:
results = np.array(results)
else:
results = np.array(results)
return results | python | def cv(params, dtrain, num_boost_round=10, nfold=3, metrics=(),
obj=None, feval=None, fpreproc=None, as_pandas=True,
show_progress=None, show_stdv=True, seed=0):
# pylint: disable = invalid-name
"""Cross-validation with given paramaters.
Parameters
----------
params : dict
Booster params.
dtrain : DMatrix
Data to be trained.
num_boost_round : int
Number of boosting iterations.
nfold : int
Number of folds in CV.
metrics : list of strings
Evaluation metrics to be watched in CV.
obj : function
Custom objective function.
feval : function
Custom evaluation function.
fpreproc : function
Preprocessing function that takes (dtrain, dtest, param) and returns
transformed versions of those.
as_pandas : bool, default True
Return pd.DataFrame when pandas is installed.
If False or pandas is not installed, return np.ndarray
show_progress : bool or None, default None
Whether to display the progress. If None, progress will be displayed
when np.ndarray is returned.
show_stdv : bool, default True
Whether to display the standard deviation in progress.
Results are not affected, and always contains std.
seed : int
Seed used to generate the folds (passed to numpy.random.seed).
Returns
-------
evaluation history : list(string)
"""
results = []
cvfolds = mknfold(dtrain, nfold, params, seed, metrics, fpreproc)
for i in range(num_boost_round):
for fold in cvfolds:
fold.update(i, obj)
res = aggcv([f.eval(i, feval) for f in cvfolds],
show_stdv=show_stdv, show_progress=show_progress,
as_pandas=as_pandas)
results.append(res)
if as_pandas:
try:
import pandas as pd
results = pd.DataFrame(results)
except ImportError:
results = np.array(results)
else:
results = np.array(results)
return results | [
"def",
"cv",
"(",
"params",
",",
"dtrain",
",",
"num_boost_round",
"=",
"10",
",",
"nfold",
"=",
"3",
",",
"metrics",
"=",
"(",
")",
",",
"obj",
"=",
"None",
",",
"feval",
"=",
"None",
",",
"fpreproc",
"=",
"None",
",",
"as_pandas",
"=",
"True",
... | Cross-validation with given paramaters.
Parameters
----------
params : dict
Booster params.
dtrain : DMatrix
Data to be trained.
num_boost_round : int
Number of boosting iterations.
nfold : int
Number of folds in CV.
metrics : list of strings
Evaluation metrics to be watched in CV.
obj : function
Custom objective function.
feval : function
Custom evaluation function.
fpreproc : function
Preprocessing function that takes (dtrain, dtest, param) and returns
transformed versions of those.
as_pandas : bool, default True
Return pd.DataFrame when pandas is installed.
If False or pandas is not installed, return np.ndarray
show_progress : bool or None, default None
Whether to display the progress. If None, progress will be displayed
when np.ndarray is returned.
show_stdv : bool, default True
Whether to display the standard deviation in progress.
Results are not affected, and always contains std.
seed : int
Seed used to generate the folds (passed to numpy.random.seed).
Returns
-------
evaluation history : list(string) | [
"Cross",
"-",
"validation",
"with",
"given",
"paramaters",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/training.py#L294-L354 |
29,501 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology2.py | NetGraph._remove_layer_and_reconnect | def _remove_layer_and_reconnect(self, layer):
""" Remove the layer, and reconnect each of its predecessor to each of
its successor
"""
successors = self.get_successors(layer)
predecessors = self.get_predecessors(layer)
# remove layer's edges
for succ in successors:
self._remove_edge(layer, succ)
for pred in predecessors:
self._remove_edge(pred, layer)
# connect predecessors and successors
for pred in predecessors:
for succ in successors:
self._add_edge(pred, succ)
# remove layer in the data structures
self.layer_list.remove(layer)
self.keras_layer_map.pop(layer)
# re-assign input and output layers if layer happens to be an
# input / output layer
if layer in self.input_layers:
idx = self.input_layers.index(layer)
self.input_layers.pop(idx)
for pred in predecessors:
self.input_layers.insert(idx, pred)
idx += 1
if layer in self.output_layers:
idx = self.output_layers.index(layer)
self.output_layers.pop(idx)
for succ in successors:
self.output_layers.insert(idx, succ)
idx += 1 | python | def _remove_layer_and_reconnect(self, layer):
""" Remove the layer, and reconnect each of its predecessor to each of
its successor
"""
successors = self.get_successors(layer)
predecessors = self.get_predecessors(layer)
# remove layer's edges
for succ in successors:
self._remove_edge(layer, succ)
for pred in predecessors:
self._remove_edge(pred, layer)
# connect predecessors and successors
for pred in predecessors:
for succ in successors:
self._add_edge(pred, succ)
# remove layer in the data structures
self.layer_list.remove(layer)
self.keras_layer_map.pop(layer)
# re-assign input and output layers if layer happens to be an
# input / output layer
if layer in self.input_layers:
idx = self.input_layers.index(layer)
self.input_layers.pop(idx)
for pred in predecessors:
self.input_layers.insert(idx, pred)
idx += 1
if layer in self.output_layers:
idx = self.output_layers.index(layer)
self.output_layers.pop(idx)
for succ in successors:
self.output_layers.insert(idx, succ)
idx += 1 | [
"def",
"_remove_layer_and_reconnect",
"(",
"self",
",",
"layer",
")",
":",
"successors",
"=",
"self",
".",
"get_successors",
"(",
"layer",
")",
"predecessors",
"=",
"self",
".",
"get_predecessors",
"(",
"layer",
")",
"# remove layer's edges",
"for",
"succ",
"in"... | Remove the layer, and reconnect each of its predecessor to each of
its successor | [
"Remove",
"the",
"layer",
"and",
"reconnect",
"each",
"of",
"its",
"predecessor",
"to",
"each",
"of",
"its",
"successor"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology2.py#L387-L421 |
29,502 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.date_range | def date_range(cls,start_time,end_time,freq):
'''
Returns a new SArray that represents a fixed frequency datetime index.
Parameters
----------
start_time : datetime.datetime
Left bound for generating dates.
end_time : datetime.datetime
Right bound for generating dates.
freq : datetime.timedelta
Fixed frequency between two consecutive data points.
Returns
-------
out : SArray
Examples
--------
>>> import datetime as dt
>>> start = dt.datetime(2013, 5, 7, 10, 4, 10)
>>> end = dt.datetime(2013, 5, 10, 10, 4, 10)
>>> sa = tc.SArray.date_range(start,end,dt.timedelta(1))
>>> print sa
dtype: datetime
Rows: 4
[datetime.datetime(2013, 5, 7, 10, 4, 10),
datetime.datetime(2013, 5, 8, 10, 4, 10),
datetime.datetime(2013, 5, 9, 10, 4, 10),
datetime.datetime(2013, 5, 10, 10, 4, 10)]
'''
if not isinstance(start_time,datetime.datetime):
raise TypeError("The ``start_time`` argument must be from type datetime.datetime.")
if not isinstance(end_time,datetime.datetime):
raise TypeError("The ``end_time`` argument must be from type datetime.datetime.")
if not isinstance(freq,datetime.timedelta):
raise TypeError("The ``freq`` argument must be from type datetime.timedelta.")
from .. import extensions
return extensions.date_range(start_time,end_time,freq.total_seconds()) | python | def date_range(cls,start_time,end_time,freq):
'''
Returns a new SArray that represents a fixed frequency datetime index.
Parameters
----------
start_time : datetime.datetime
Left bound for generating dates.
end_time : datetime.datetime
Right bound for generating dates.
freq : datetime.timedelta
Fixed frequency between two consecutive data points.
Returns
-------
out : SArray
Examples
--------
>>> import datetime as dt
>>> start = dt.datetime(2013, 5, 7, 10, 4, 10)
>>> end = dt.datetime(2013, 5, 10, 10, 4, 10)
>>> sa = tc.SArray.date_range(start,end,dt.timedelta(1))
>>> print sa
dtype: datetime
Rows: 4
[datetime.datetime(2013, 5, 7, 10, 4, 10),
datetime.datetime(2013, 5, 8, 10, 4, 10),
datetime.datetime(2013, 5, 9, 10, 4, 10),
datetime.datetime(2013, 5, 10, 10, 4, 10)]
'''
if not isinstance(start_time,datetime.datetime):
raise TypeError("The ``start_time`` argument must be from type datetime.datetime.")
if not isinstance(end_time,datetime.datetime):
raise TypeError("The ``end_time`` argument must be from type datetime.datetime.")
if not isinstance(freq,datetime.timedelta):
raise TypeError("The ``freq`` argument must be from type datetime.timedelta.")
from .. import extensions
return extensions.date_range(start_time,end_time,freq.total_seconds()) | [
"def",
"date_range",
"(",
"cls",
",",
"start_time",
",",
"end_time",
",",
"freq",
")",
":",
"if",
"not",
"isinstance",
"(",
"start_time",
",",
"datetime",
".",
"datetime",
")",
":",
"raise",
"TypeError",
"(",
"\"The ``start_time`` argument must be from type dateti... | Returns a new SArray that represents a fixed frequency datetime index.
Parameters
----------
start_time : datetime.datetime
Left bound for generating dates.
end_time : datetime.datetime
Right bound for generating dates.
freq : datetime.timedelta
Fixed frequency between two consecutive data points.
Returns
-------
out : SArray
Examples
--------
>>> import datetime as dt
>>> start = dt.datetime(2013, 5, 7, 10, 4, 10)
>>> end = dt.datetime(2013, 5, 10, 10, 4, 10)
>>> sa = tc.SArray.date_range(start,end,dt.timedelta(1))
>>> print sa
dtype: datetime
Rows: 4
[datetime.datetime(2013, 5, 7, 10, 4, 10),
datetime.datetime(2013, 5, 8, 10, 4, 10),
datetime.datetime(2013, 5, 9, 10, 4, 10),
datetime.datetime(2013, 5, 10, 10, 4, 10)] | [
"Returns",
"a",
"new",
"SArray",
"that",
"represents",
"a",
"fixed",
"frequency",
"datetime",
"index",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L431-L475 |
29,503 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.from_const | def from_const(cls, value, size, dtype=type(None)):
"""
Constructs an SArray of size with a const value.
Parameters
----------
value : [int | float | str | array.array | list | dict | datetime]
The value to fill the SArray
size : int
The size of the SArray
dtype : type
The type of the SArray. If not specified, is automatically detected
from the value. This should be specified if value=None since the
actual type of the SArray can be anything.
Examples
--------
Construct an SArray consisting of 10 zeroes:
>>> turicreate.SArray.from_const(0, 10)
Construct an SArray consisting of 10 missing string values:
>>> turicreate.SArray.from_const(None, 10, str)
"""
assert isinstance(size, (int, long)) and size >= 0, "size must be a positive int"
if not isinstance(value, (type(None), int, float, str, array.array, list, dict, datetime.datetime)):
raise TypeError('Cannot create sarray of value type %s' % str(type(value)))
proxy = UnitySArrayProxy()
proxy.load_from_const(value, size, dtype)
return cls(_proxy=proxy) | python | def from_const(cls, value, size, dtype=type(None)):
"""
Constructs an SArray of size with a const value.
Parameters
----------
value : [int | float | str | array.array | list | dict | datetime]
The value to fill the SArray
size : int
The size of the SArray
dtype : type
The type of the SArray. If not specified, is automatically detected
from the value. This should be specified if value=None since the
actual type of the SArray can be anything.
Examples
--------
Construct an SArray consisting of 10 zeroes:
>>> turicreate.SArray.from_const(0, 10)
Construct an SArray consisting of 10 missing string values:
>>> turicreate.SArray.from_const(None, 10, str)
"""
assert isinstance(size, (int, long)) and size >= 0, "size must be a positive int"
if not isinstance(value, (type(None), int, float, str, array.array, list, dict, datetime.datetime)):
raise TypeError('Cannot create sarray of value type %s' % str(type(value)))
proxy = UnitySArrayProxy()
proxy.load_from_const(value, size, dtype)
return cls(_proxy=proxy) | [
"def",
"from_const",
"(",
"cls",
",",
"value",
",",
"size",
",",
"dtype",
"=",
"type",
"(",
"None",
")",
")",
":",
"assert",
"isinstance",
"(",
"size",
",",
"(",
"int",
",",
"long",
")",
")",
"and",
"size",
">=",
"0",
",",
"\"size must be a positive ... | Constructs an SArray of size with a const value.
Parameters
----------
value : [int | float | str | array.array | list | dict | datetime]
The value to fill the SArray
size : int
The size of the SArray
dtype : type
The type of the SArray. If not specified, is automatically detected
from the value. This should be specified if value=None since the
actual type of the SArray can be anything.
Examples
--------
Construct an SArray consisting of 10 zeroes:
>>> turicreate.SArray.from_const(0, 10)
Construct an SArray consisting of 10 missing string values:
>>> turicreate.SArray.from_const(None, 10, str) | [
"Constructs",
"an",
"SArray",
"of",
"size",
"with",
"a",
"const",
"value",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L478-L508 |
29,504 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.read_json | def read_json(cls, filename):
"""
Construct an SArray from a json file or glob of json files.
The json file must contain a list of dictionaries. The returned
SArray type will be of dict type
Parameters
----------
filename : str
The filename or glob to load into an SArray.
Examples
--------
Construct an SArray from a local JSON file named 'data.json':
>>> turicreate.SArray.read_json('/data/data.json')
Construct an SArray from all JSON files /data/data*.json
>>> turicreate.SArray.read_json('/data/data*.json')
"""
proxy = UnitySArrayProxy()
proxy.load_from_json_record_files(_make_internal_url(filename))
return cls(_proxy = proxy) | python | def read_json(cls, filename):
"""
Construct an SArray from a json file or glob of json files.
The json file must contain a list of dictionaries. The returned
SArray type will be of dict type
Parameters
----------
filename : str
The filename or glob to load into an SArray.
Examples
--------
Construct an SArray from a local JSON file named 'data.json':
>>> turicreate.SArray.read_json('/data/data.json')
Construct an SArray from all JSON files /data/data*.json
>>> turicreate.SArray.read_json('/data/data*.json')
"""
proxy = UnitySArrayProxy()
proxy.load_from_json_record_files(_make_internal_url(filename))
return cls(_proxy = proxy) | [
"def",
"read_json",
"(",
"cls",
",",
"filename",
")",
":",
"proxy",
"=",
"UnitySArrayProxy",
"(",
")",
"proxy",
".",
"load_from_json_record_files",
"(",
"_make_internal_url",
"(",
"filename",
")",
")",
"return",
"cls",
"(",
"_proxy",
"=",
"proxy",
")"
] | Construct an SArray from a json file or glob of json files.
The json file must contain a list of dictionaries. The returned
SArray type will be of dict type
Parameters
----------
filename : str
The filename or glob to load into an SArray.
Examples
--------
Construct an SArray from a local JSON file named 'data.json':
>>> turicreate.SArray.read_json('/data/data.json')
Construct an SArray from all JSON files /data/data*.json
>>> turicreate.SArray.read_json('/data/data*.json') | [
"Construct",
"an",
"SArray",
"from",
"a",
"json",
"file",
"or",
"glob",
"of",
"json",
"files",
".",
"The",
"json",
"file",
"must",
"contain",
"a",
"list",
"of",
"dictionaries",
".",
"The",
"returned",
"SArray",
"type",
"will",
"be",
"of",
"dict",
"type"
... | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L566-L590 |
29,505 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.where | def where(cls, condition, istrue, isfalse, dtype=None):
"""
Selects elements from either istrue or isfalse depending on the value
of the condition SArray.
Parameters
----------
condition : SArray
An SArray of values such that for each value, if non-zero, yields a
value from istrue, otherwise from isfalse.
istrue : SArray or constant
The elements selected if condition is true. If istrue is an SArray,
this must be of the same length as condition.
isfalse : SArray or constant
The elements selected if condition is false. If istrue is an SArray,
this must be of the same length as condition.
dtype : type
The type of result SArray. This is required if both istrue and isfalse
are constants of ambiguous types.
Examples
--------
Returns an SArray with the same values as g with values above 10
clipped to 10
>>> g = SArray([6,7,8,9,10,11,12,13])
>>> SArray.where(g > 10, 10, g)
dtype: int
Rows: 8
[6, 7, 8, 9, 10, 10, 10, 10]
Returns an SArray with the same values as g with values below 10
clipped to 10
>>> SArray.where(g > 10, g, 10)
dtype: int
Rows: 8
[10, 10, 10, 10, 10, 11, 12, 13]
Returns an SArray with the same values of g with all values == 1
replaced by None
>>> g = SArray([1,2,3,4,1,2,3,4])
>>> SArray.where(g == 1, None, g)
dtype: int
Rows: 8
[None, 2, 3, 4, None, 2, 3, 4]
Returns an SArray with the same values of g, but with each missing value
replaced by its corresponding element in replace_none
>>> g = SArray([1,2,None,None])
>>> replace_none = SArray([3,3,2,2])
>>> SArray.where(g != None, g, replace_none)
dtype: int
Rows: 4
[1, 2, 2, 2]
"""
true_is_sarray = isinstance(istrue, SArray)
false_is_sarray = isinstance(isfalse, SArray)
if not true_is_sarray and false_is_sarray:
istrue = cls(_proxy=condition.__proxy__.to_const(istrue, isfalse.dtype))
if true_is_sarray and not false_is_sarray:
isfalse = cls(_proxy=condition.__proxy__.to_const(isfalse, istrue.dtype))
if not true_is_sarray and not false_is_sarray:
if dtype is None:
if istrue is None:
dtype = type(isfalse)
elif isfalse is None:
dtype = type(istrue)
elif type(istrue) != type(isfalse):
raise TypeError("true and false inputs are of different types")
elif type(istrue) == type(isfalse):
dtype = type(istrue)
if dtype is None:
raise TypeError("Both true and false are None. Resultant type cannot be inferred.")
istrue = cls(_proxy=condition.__proxy__.to_const(istrue, dtype))
isfalse = cls(_proxy=condition.__proxy__.to_const(isfalse, dtype))
return cls(_proxy=condition.__proxy__.ternary_operator(istrue.__proxy__, isfalse.__proxy__)) | python | def where(cls, condition, istrue, isfalse, dtype=None):
"""
Selects elements from either istrue or isfalse depending on the value
of the condition SArray.
Parameters
----------
condition : SArray
An SArray of values such that for each value, if non-zero, yields a
value from istrue, otherwise from isfalse.
istrue : SArray or constant
The elements selected if condition is true. If istrue is an SArray,
this must be of the same length as condition.
isfalse : SArray or constant
The elements selected if condition is false. If istrue is an SArray,
this must be of the same length as condition.
dtype : type
The type of result SArray. This is required if both istrue and isfalse
are constants of ambiguous types.
Examples
--------
Returns an SArray with the same values as g with values above 10
clipped to 10
>>> g = SArray([6,7,8,9,10,11,12,13])
>>> SArray.where(g > 10, 10, g)
dtype: int
Rows: 8
[6, 7, 8, 9, 10, 10, 10, 10]
Returns an SArray with the same values as g with values below 10
clipped to 10
>>> SArray.where(g > 10, g, 10)
dtype: int
Rows: 8
[10, 10, 10, 10, 10, 11, 12, 13]
Returns an SArray with the same values of g with all values == 1
replaced by None
>>> g = SArray([1,2,3,4,1,2,3,4])
>>> SArray.where(g == 1, None, g)
dtype: int
Rows: 8
[None, 2, 3, 4, None, 2, 3, 4]
Returns an SArray with the same values of g, but with each missing value
replaced by its corresponding element in replace_none
>>> g = SArray([1,2,None,None])
>>> replace_none = SArray([3,3,2,2])
>>> SArray.where(g != None, g, replace_none)
dtype: int
Rows: 4
[1, 2, 2, 2]
"""
true_is_sarray = isinstance(istrue, SArray)
false_is_sarray = isinstance(isfalse, SArray)
if not true_is_sarray and false_is_sarray:
istrue = cls(_proxy=condition.__proxy__.to_const(istrue, isfalse.dtype))
if true_is_sarray and not false_is_sarray:
isfalse = cls(_proxy=condition.__proxy__.to_const(isfalse, istrue.dtype))
if not true_is_sarray and not false_is_sarray:
if dtype is None:
if istrue is None:
dtype = type(isfalse)
elif isfalse is None:
dtype = type(istrue)
elif type(istrue) != type(isfalse):
raise TypeError("true and false inputs are of different types")
elif type(istrue) == type(isfalse):
dtype = type(istrue)
if dtype is None:
raise TypeError("Both true and false are None. Resultant type cannot be inferred.")
istrue = cls(_proxy=condition.__proxy__.to_const(istrue, dtype))
isfalse = cls(_proxy=condition.__proxy__.to_const(isfalse, dtype))
return cls(_proxy=condition.__proxy__.ternary_operator(istrue.__proxy__, isfalse.__proxy__)) | [
"def",
"where",
"(",
"cls",
",",
"condition",
",",
"istrue",
",",
"isfalse",
",",
"dtype",
"=",
"None",
")",
":",
"true_is_sarray",
"=",
"isinstance",
"(",
"istrue",
",",
"SArray",
")",
"false_is_sarray",
"=",
"isinstance",
"(",
"isfalse",
",",
"SArray",
... | Selects elements from either istrue or isfalse depending on the value
of the condition SArray.
Parameters
----------
condition : SArray
An SArray of values such that for each value, if non-zero, yields a
value from istrue, otherwise from isfalse.
istrue : SArray or constant
The elements selected if condition is true. If istrue is an SArray,
this must be of the same length as condition.
isfalse : SArray or constant
The elements selected if condition is false. If istrue is an SArray,
this must be of the same length as condition.
dtype : type
The type of result SArray. This is required if both istrue and isfalse
are constants of ambiguous types.
Examples
--------
Returns an SArray with the same values as g with values above 10
clipped to 10
>>> g = SArray([6,7,8,9,10,11,12,13])
>>> SArray.where(g > 10, 10, g)
dtype: int
Rows: 8
[6, 7, 8, 9, 10, 10, 10, 10]
Returns an SArray with the same values as g with values below 10
clipped to 10
>>> SArray.where(g > 10, g, 10)
dtype: int
Rows: 8
[10, 10, 10, 10, 10, 11, 12, 13]
Returns an SArray with the same values of g with all values == 1
replaced by None
>>> g = SArray([1,2,3,4,1,2,3,4])
>>> SArray.where(g == 1, None, g)
dtype: int
Rows: 8
[None, 2, 3, 4, None, 2, 3, 4]
Returns an SArray with the same values of g, but with each missing value
replaced by its corresponding element in replace_none
>>> g = SArray([1,2,None,None])
>>> replace_none = SArray([3,3,2,2])
>>> SArray.where(g != None, g, replace_none)
dtype: int
Rows: 4
[1, 2, 2, 2] | [
"Selects",
"elements",
"from",
"either",
"istrue",
"or",
"isfalse",
"depending",
"on",
"the",
"value",
"of",
"the",
"condition",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L593-L675 |
29,506 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.save | def save(self, filename, format=None):
"""
Saves the SArray to file.
The saved SArray will be in a directory named with the `targetfile`
parameter.
Parameters
----------
filename : string
A local path or a remote URL. If format is 'text', it will be
saved as a text file. If format is 'binary', a directory will be
created at the location which will contain the SArray.
format : {'binary', 'text', 'csv'}, optional
Format in which to save the SFrame. Binary saved SArrays can be
loaded much faster and without any format conversion losses.
'text' and 'csv' are synonymous: Each SArray row will be written
as a single line in an output text file. If not
given, will try to infer the format from filename given. If file
name ends with 'csv', 'txt' or '.csv.gz', then save as 'csv' format,
otherwise save as 'binary' format.
"""
from .sframe import SFrame as _SFrame
if format is None:
if filename.endswith(('.csv', '.csv.gz', 'txt')):
format = 'text'
else:
format = 'binary'
if format == 'binary':
with cython_context():
self.__proxy__.save(_make_internal_url(filename))
elif format == 'text' or format == 'csv':
sf = _SFrame({'X1':self})
with cython_context():
sf.__proxy__.save_as_csv(_make_internal_url(filename), {'header':False})
else:
raise ValueError("Unsupported format: {}".format(format)) | python | def save(self, filename, format=None):
"""
Saves the SArray to file.
The saved SArray will be in a directory named with the `targetfile`
parameter.
Parameters
----------
filename : string
A local path or a remote URL. If format is 'text', it will be
saved as a text file. If format is 'binary', a directory will be
created at the location which will contain the SArray.
format : {'binary', 'text', 'csv'}, optional
Format in which to save the SFrame. Binary saved SArrays can be
loaded much faster and without any format conversion losses.
'text' and 'csv' are synonymous: Each SArray row will be written
as a single line in an output text file. If not
given, will try to infer the format from filename given. If file
name ends with 'csv', 'txt' or '.csv.gz', then save as 'csv' format,
otherwise save as 'binary' format.
"""
from .sframe import SFrame as _SFrame
if format is None:
if filename.endswith(('.csv', '.csv.gz', 'txt')):
format = 'text'
else:
format = 'binary'
if format == 'binary':
with cython_context():
self.__proxy__.save(_make_internal_url(filename))
elif format == 'text' or format == 'csv':
sf = _SFrame({'X1':self})
with cython_context():
sf.__proxy__.save_as_csv(_make_internal_url(filename), {'header':False})
else:
raise ValueError("Unsupported format: {}".format(format)) | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"format",
"=",
"None",
")",
":",
"from",
".",
"sframe",
"import",
"SFrame",
"as",
"_SFrame",
"if",
"format",
"is",
"None",
":",
"if",
"filename",
".",
"endswith",
"(",
"(",
"'.csv'",
",",
"'.csv.gz'",
... | Saves the SArray to file.
The saved SArray will be in a directory named with the `targetfile`
parameter.
Parameters
----------
filename : string
A local path or a remote URL. If format is 'text', it will be
saved as a text file. If format is 'binary', a directory will be
created at the location which will contain the SArray.
format : {'binary', 'text', 'csv'}, optional
Format in which to save the SFrame. Binary saved SArrays can be
loaded much faster and without any format conversion losses.
'text' and 'csv' are synonymous: Each SArray row will be written
as a single line in an output text file. If not
given, will try to infer the format from filename given. If file
name ends with 'csv', 'txt' or '.csv.gz', then save as 'csv' format,
otherwise save as 'binary' format. | [
"Saves",
"the",
"SArray",
"to",
"file",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L705-L743 |
29,507 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray._count_words | def _count_words(self, to_lower=True, delimiters=["\r", "\v", "\n", "\f", "\t", " "]):
"""
This returns an SArray with, for each input string, a dict from the unique,
delimited substrings to their number of occurrences within the original
string.
The SArray must be of type string.
..WARNING:: This function is deprecated, and will be removed in future
versions of Turi Create. Please use the `text_analytics.count_words`
function instead.
Parameters
----------
to_lower : bool, optional
"to_lower" indicates whether to map the input strings to lower case
before counts
delimiters: list[string], optional
"delimiters" is a list of which characters to delimit on to find tokens
Returns
-------
out : SArray
for each input string, a dict from the unique, delimited substrings
to their number of occurrences within the original string.
Examples
--------
>>> sa = turicreate.SArray(["The quick brown fox jumps.",
"Word word WORD, word!!!word"])
>>> sa._count_words()
dtype: dict
Rows: 2
[{'quick': 1, 'brown': 1, 'jumps': 1, 'fox': 1, 'the': 1},
{'word': 2, 'word,': 1, 'word!!!word': 1}]
"""
if (self.dtype != str):
raise TypeError("Only SArray of string type is supported for counting bag of words")
if (not all([len(delim) == 1 for delim in delimiters])):
raise ValueError("Delimiters must be single-character strings")
# construct options, will extend over time
options = dict()
options["to_lower"] = to_lower == True
# defaults to std::isspace whitespace delimiters if no others passed in
options["delimiters"] = delimiters
with cython_context():
return SArray(_proxy=self.__proxy__.count_bag_of_words(options)) | python | def _count_words(self, to_lower=True, delimiters=["\r", "\v", "\n", "\f", "\t", " "]):
"""
This returns an SArray with, for each input string, a dict from the unique,
delimited substrings to their number of occurrences within the original
string.
The SArray must be of type string.
..WARNING:: This function is deprecated, and will be removed in future
versions of Turi Create. Please use the `text_analytics.count_words`
function instead.
Parameters
----------
to_lower : bool, optional
"to_lower" indicates whether to map the input strings to lower case
before counts
delimiters: list[string], optional
"delimiters" is a list of which characters to delimit on to find tokens
Returns
-------
out : SArray
for each input string, a dict from the unique, delimited substrings
to their number of occurrences within the original string.
Examples
--------
>>> sa = turicreate.SArray(["The quick brown fox jumps.",
"Word word WORD, word!!!word"])
>>> sa._count_words()
dtype: dict
Rows: 2
[{'quick': 1, 'brown': 1, 'jumps': 1, 'fox': 1, 'the': 1},
{'word': 2, 'word,': 1, 'word!!!word': 1}]
"""
if (self.dtype != str):
raise TypeError("Only SArray of string type is supported for counting bag of words")
if (not all([len(delim) == 1 for delim in delimiters])):
raise ValueError("Delimiters must be single-character strings")
# construct options, will extend over time
options = dict()
options["to_lower"] = to_lower == True
# defaults to std::isspace whitespace delimiters if no others passed in
options["delimiters"] = delimiters
with cython_context():
return SArray(_proxy=self.__proxy__.count_bag_of_words(options)) | [
"def",
"_count_words",
"(",
"self",
",",
"to_lower",
"=",
"True",
",",
"delimiters",
"=",
"[",
"\"\\r\"",
",",
"\"\\v\"",
",",
"\"\\n\"",
",",
"\"\\f\"",
",",
"\"\\t\"",
",",
"\" \"",
"]",
")",
":",
"if",
"(",
"self",
".",
"dtype",
"!=",
"str",
")",
... | This returns an SArray with, for each input string, a dict from the unique,
delimited substrings to their number of occurrences within the original
string.
The SArray must be of type string.
..WARNING:: This function is deprecated, and will be removed in future
versions of Turi Create. Please use the `text_analytics.count_words`
function instead.
Parameters
----------
to_lower : bool, optional
"to_lower" indicates whether to map the input strings to lower case
before counts
delimiters: list[string], optional
"delimiters" is a list of which characters to delimit on to find tokens
Returns
-------
out : SArray
for each input string, a dict from the unique, delimited substrings
to their number of occurrences within the original string.
Examples
--------
>>> sa = turicreate.SArray(["The quick brown fox jumps.",
"Word word WORD, word!!!word"])
>>> sa._count_words()
dtype: dict
Rows: 2
[{'quick': 1, 'brown': 1, 'jumps': 1, 'fox': 1, 'the': 1},
{'word': 2, 'word,': 1, 'word!!!word': 1}] | [
"This",
"returns",
"an",
"SArray",
"with",
"for",
"each",
"input",
"string",
"a",
"dict",
"from",
"the",
"unique",
"delimited",
"substrings",
"to",
"their",
"number",
"of",
"occurrences",
"within",
"the",
"original",
"string",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L1506-L1558 |
29,508 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.dict_has_any_keys | def dict_has_any_keys(self, keys):
"""
Create a boolean SArray by checking the keys of an SArray of
dictionaries. An element of the output SArray is True if the
corresponding input element's dictionary has any of the given keys.
Fails on SArrays whose data type is not ``dict``.
Parameters
----------
keys : list
A list of key values to check each dictionary against.
Returns
-------
out : SArray
A SArray of int type, where each element indicates whether the
input SArray element contains any key in the input list.
See Also
--------
dict_has_all_keys
Examples
--------
>>> sa = turicreate.SArray([{"this":1, "is":5, "dog":7}, {"animal":1},
{"this": 2, "are": 1, "cat": 5}])
>>> sa.dict_has_any_keys(["is", "this", "are"])
dtype: int
Rows: 3
[1, 0, 1]
"""
if not _is_non_string_iterable(keys):
keys = [keys]
with cython_context():
return SArray(_proxy=self.__proxy__.dict_has_any_keys(keys)) | python | def dict_has_any_keys(self, keys):
"""
Create a boolean SArray by checking the keys of an SArray of
dictionaries. An element of the output SArray is True if the
corresponding input element's dictionary has any of the given keys.
Fails on SArrays whose data type is not ``dict``.
Parameters
----------
keys : list
A list of key values to check each dictionary against.
Returns
-------
out : SArray
A SArray of int type, where each element indicates whether the
input SArray element contains any key in the input list.
See Also
--------
dict_has_all_keys
Examples
--------
>>> sa = turicreate.SArray([{"this":1, "is":5, "dog":7}, {"animal":1},
{"this": 2, "are": 1, "cat": 5}])
>>> sa.dict_has_any_keys(["is", "this", "are"])
dtype: int
Rows: 3
[1, 0, 1]
"""
if not _is_non_string_iterable(keys):
keys = [keys]
with cython_context():
return SArray(_proxy=self.__proxy__.dict_has_any_keys(keys)) | [
"def",
"dict_has_any_keys",
"(",
"self",
",",
"keys",
")",
":",
"if",
"not",
"_is_non_string_iterable",
"(",
"keys",
")",
":",
"keys",
"=",
"[",
"keys",
"]",
"with",
"cython_context",
"(",
")",
":",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
... | Create a boolean SArray by checking the keys of an SArray of
dictionaries. An element of the output SArray is True if the
corresponding input element's dictionary has any of the given keys.
Fails on SArrays whose data type is not ``dict``.
Parameters
----------
keys : list
A list of key values to check each dictionary against.
Returns
-------
out : SArray
A SArray of int type, where each element indicates whether the
input SArray element contains any key in the input list.
See Also
--------
dict_has_all_keys
Examples
--------
>>> sa = turicreate.SArray([{"this":1, "is":5, "dog":7}, {"animal":1},
{"this": 2, "are": 1, "cat": 5}])
>>> sa.dict_has_any_keys(["is", "this", "are"])
dtype: int
Rows: 3
[1, 0, 1] | [
"Create",
"a",
"boolean",
"SArray",
"by",
"checking",
"the",
"keys",
"of",
"an",
"SArray",
"of",
"dictionaries",
".",
"An",
"element",
"of",
"the",
"output",
"SArray",
"is",
"True",
"if",
"the",
"corresponding",
"input",
"element",
"s",
"dictionary",
"has",
... | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L1745-L1781 |
29,509 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.dict_has_all_keys | def dict_has_all_keys(self, keys):
"""
Create a boolean SArray by checking the keys of an SArray of
dictionaries. An element of the output SArray is True if the
corresponding input element's dictionary has all of the given keys.
Fails on SArrays whose data type is not ``dict``.
Parameters
----------
keys : list
A list of key values to check each dictionary against.
Returns
-------
out : SArray
A SArray of int type, where each element indicates whether the
input SArray element contains all keys in the input list.
See Also
--------
dict_has_any_keys
Examples
--------
>>> sa = turicreate.SArray([{"this":1, "is":5, "dog":7},
{"this": 2, "are": 1, "cat": 5}])
>>> sa.dict_has_all_keys(["is", "this"])
dtype: int
Rows: 2
[1, 0]
"""
if not _is_non_string_iterable(keys):
keys = [keys]
with cython_context():
return SArray(_proxy=self.__proxy__.dict_has_all_keys(keys)) | python | def dict_has_all_keys(self, keys):
"""
Create a boolean SArray by checking the keys of an SArray of
dictionaries. An element of the output SArray is True if the
corresponding input element's dictionary has all of the given keys.
Fails on SArrays whose data type is not ``dict``.
Parameters
----------
keys : list
A list of key values to check each dictionary against.
Returns
-------
out : SArray
A SArray of int type, where each element indicates whether the
input SArray element contains all keys in the input list.
See Also
--------
dict_has_any_keys
Examples
--------
>>> sa = turicreate.SArray([{"this":1, "is":5, "dog":7},
{"this": 2, "are": 1, "cat": 5}])
>>> sa.dict_has_all_keys(["is", "this"])
dtype: int
Rows: 2
[1, 0]
"""
if not _is_non_string_iterable(keys):
keys = [keys]
with cython_context():
return SArray(_proxy=self.__proxy__.dict_has_all_keys(keys)) | [
"def",
"dict_has_all_keys",
"(",
"self",
",",
"keys",
")",
":",
"if",
"not",
"_is_non_string_iterable",
"(",
"keys",
")",
":",
"keys",
"=",
"[",
"keys",
"]",
"with",
"cython_context",
"(",
")",
":",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
... | Create a boolean SArray by checking the keys of an SArray of
dictionaries. An element of the output SArray is True if the
corresponding input element's dictionary has all of the given keys.
Fails on SArrays whose data type is not ``dict``.
Parameters
----------
keys : list
A list of key values to check each dictionary against.
Returns
-------
out : SArray
A SArray of int type, where each element indicates whether the
input SArray element contains all keys in the input list.
See Also
--------
dict_has_any_keys
Examples
--------
>>> sa = turicreate.SArray([{"this":1, "is":5, "dog":7},
{"this": 2, "are": 1, "cat": 5}])
>>> sa.dict_has_all_keys(["is", "this"])
dtype: int
Rows: 2
[1, 0] | [
"Create",
"a",
"boolean",
"SArray",
"by",
"checking",
"the",
"keys",
"of",
"an",
"SArray",
"of",
"dictionaries",
".",
"An",
"element",
"of",
"the",
"output",
"SArray",
"is",
"True",
"if",
"the",
"corresponding",
"input",
"element",
"s",
"dictionary",
"has",
... | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L1783-L1819 |
29,510 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.filter | def filter(self, fn, skip_na=True, seed=None):
"""
Filter this SArray by a function.
Returns a new SArray filtered by this SArray. If `fn` evaluates an
element to true, this element is copied to the new SArray. If not, it
isn't. Throws an exception if the return type of `fn` is not castable
to a boolean value.
Parameters
----------
fn : function
Function that filters the SArray. Must evaluate to bool or int.
skip_na : bool, optional
If True, will not apply fn to any undefined values.
seed : int, optional
Used as the seed if a random number generator is included in fn.
Returns
-------
out : SArray
The SArray filtered by fn. Each element of the SArray is of
type int.
Examples
--------
>>> sa = turicreate.SArray([1,2,3])
>>> sa.filter(lambda x: x < 3)
dtype: int
Rows: 2
[1, 2]
"""
assert callable(fn), "Input must be callable"
if seed is None:
seed = abs(hash("%0.20f" % time.time())) % (2 ** 31)
with cython_context():
return SArray(_proxy=self.__proxy__.filter(fn, skip_na, seed)) | python | def filter(self, fn, skip_na=True, seed=None):
"""
Filter this SArray by a function.
Returns a new SArray filtered by this SArray. If `fn` evaluates an
element to true, this element is copied to the new SArray. If not, it
isn't. Throws an exception if the return type of `fn` is not castable
to a boolean value.
Parameters
----------
fn : function
Function that filters the SArray. Must evaluate to bool or int.
skip_na : bool, optional
If True, will not apply fn to any undefined values.
seed : int, optional
Used as the seed if a random number generator is included in fn.
Returns
-------
out : SArray
The SArray filtered by fn. Each element of the SArray is of
type int.
Examples
--------
>>> sa = turicreate.SArray([1,2,3])
>>> sa.filter(lambda x: x < 3)
dtype: int
Rows: 2
[1, 2]
"""
assert callable(fn), "Input must be callable"
if seed is None:
seed = abs(hash("%0.20f" % time.time())) % (2 ** 31)
with cython_context():
return SArray(_proxy=self.__proxy__.filter(fn, skip_na, seed)) | [
"def",
"filter",
"(",
"self",
",",
"fn",
",",
"skip_na",
"=",
"True",
",",
"seed",
"=",
"None",
")",
":",
"assert",
"callable",
"(",
"fn",
")",
",",
"\"Input must be callable\"",
"if",
"seed",
"is",
"None",
":",
"seed",
"=",
"abs",
"(",
"hash",
"(",
... | Filter this SArray by a function.
Returns a new SArray filtered by this SArray. If `fn` evaluates an
element to true, this element is copied to the new SArray. If not, it
isn't. Throws an exception if the return type of `fn` is not castable
to a boolean value.
Parameters
----------
fn : function
Function that filters the SArray. Must evaluate to bool or int.
skip_na : bool, optional
If True, will not apply fn to any undefined values.
seed : int, optional
Used as the seed if a random number generator is included in fn.
Returns
-------
out : SArray
The SArray filtered by fn. Each element of the SArray is of
type int.
Examples
--------
>>> sa = turicreate.SArray([1,2,3])
>>> sa.filter(lambda x: x < 3)
dtype: int
Rows: 2
[1, 2] | [
"Filter",
"this",
"SArray",
"by",
"a",
"function",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L1923-L1963 |
29,511 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.sample | def sample(self, fraction, seed=None, exact=False):
"""
Create an SArray which contains a subsample of the current SArray.
Parameters
----------
fraction : float
Fraction of the rows to fetch. Must be between 0 and 1.
if exact is False (default), the number of rows returned is
approximately the fraction times the number of rows.
seed : int, optional
The random seed for the random number generator.
exact: bool, optional
Defaults to False. If exact=True, an exact fraction is returned,
but at a performance penalty.
Returns
-------
out : SArray
The new SArray which contains the subsampled rows.
Examples
--------
>>> sa = turicreate.SArray(range(10))
>>> sa.sample(.3)
dtype: int
Rows: 3
[2, 6, 9]
"""
if (fraction > 1 or fraction < 0):
raise ValueError('Invalid sampling rate: ' + str(fraction))
if (len(self) == 0):
return SArray()
if seed is None:
seed = abs(hash("%0.20f" % time.time())) % (2 ** 31)
with cython_context():
return SArray(_proxy=self.__proxy__.sample(fraction, seed, exact)) | python | def sample(self, fraction, seed=None, exact=False):
"""
Create an SArray which contains a subsample of the current SArray.
Parameters
----------
fraction : float
Fraction of the rows to fetch. Must be between 0 and 1.
if exact is False (default), the number of rows returned is
approximately the fraction times the number of rows.
seed : int, optional
The random seed for the random number generator.
exact: bool, optional
Defaults to False. If exact=True, an exact fraction is returned,
but at a performance penalty.
Returns
-------
out : SArray
The new SArray which contains the subsampled rows.
Examples
--------
>>> sa = turicreate.SArray(range(10))
>>> sa.sample(.3)
dtype: int
Rows: 3
[2, 6, 9]
"""
if (fraction > 1 or fraction < 0):
raise ValueError('Invalid sampling rate: ' + str(fraction))
if (len(self) == 0):
return SArray()
if seed is None:
seed = abs(hash("%0.20f" % time.time())) % (2 ** 31)
with cython_context():
return SArray(_proxy=self.__proxy__.sample(fraction, seed, exact)) | [
"def",
"sample",
"(",
"self",
",",
"fraction",
",",
"seed",
"=",
"None",
",",
"exact",
"=",
"False",
")",
":",
"if",
"(",
"fraction",
">",
"1",
"or",
"fraction",
"<",
"0",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid sampling rate: '",
"+",
"str",
... | Create an SArray which contains a subsample of the current SArray.
Parameters
----------
fraction : float
Fraction of the rows to fetch. Must be between 0 and 1.
if exact is False (default), the number of rows returned is
approximately the fraction times the number of rows.
seed : int, optional
The random seed for the random number generator.
exact: bool, optional
Defaults to False. If exact=True, an exact fraction is returned,
but at a performance penalty.
Returns
-------
out : SArray
The new SArray which contains the subsampled rows.
Examples
--------
>>> sa = turicreate.SArray(range(10))
>>> sa.sample(.3)
dtype: int
Rows: 3
[2, 6, 9] | [
"Create",
"an",
"SArray",
"which",
"contains",
"a",
"subsample",
"of",
"the",
"current",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L1966-L2006 |
29,512 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.hash | def hash(self, seed=0):
"""
Returns an SArray with a hash of each element. seed can be used
to change the hash function to allow this method to be used for
random number generation.
Parameters
----------
seed : int
Defaults to 0. Can be changed to different values to get
different hash results.
Returns
-------
out : SArray
An integer SArray with a hash value for each element. Identical
elements are hashed to the same value
"""
with cython_context():
return SArray(_proxy=self.__proxy__.hash(seed)) | python | def hash(self, seed=0):
"""
Returns an SArray with a hash of each element. seed can be used
to change the hash function to allow this method to be used for
random number generation.
Parameters
----------
seed : int
Defaults to 0. Can be changed to different values to get
different hash results.
Returns
-------
out : SArray
An integer SArray with a hash value for each element. Identical
elements are hashed to the same value
"""
with cython_context():
return SArray(_proxy=self.__proxy__.hash(seed)) | [
"def",
"hash",
"(",
"self",
",",
"seed",
"=",
"0",
")",
":",
"with",
"cython_context",
"(",
")",
":",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
"__proxy__",
".",
"hash",
"(",
"seed",
")",
")"
] | Returns an SArray with a hash of each element. seed can be used
to change the hash function to allow this method to be used for
random number generation.
Parameters
----------
seed : int
Defaults to 0. Can be changed to different values to get
different hash results.
Returns
-------
out : SArray
An integer SArray with a hash value for each element. Identical
elements are hashed to the same value | [
"Returns",
"an",
"SArray",
"with",
"a",
"hash",
"of",
"each",
"element",
".",
"seed",
"can",
"be",
"used",
"to",
"change",
"the",
"hash",
"function",
"to",
"allow",
"this",
"method",
"to",
"be",
"used",
"for",
"random",
"number",
"generation",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2008-L2027 |
29,513 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.random_integers | def random_integers(cls, size, seed=None):
"""
Returns an SArray with random integer values.
"""
if seed is None:
seed = abs(hash("%0.20f" % time.time())) % (2 ** 31)
return cls.from_sequence(size).hash(seed) | python | def random_integers(cls, size, seed=None):
"""
Returns an SArray with random integer values.
"""
if seed is None:
seed = abs(hash("%0.20f" % time.time())) % (2 ** 31)
return cls.from_sequence(size).hash(seed) | [
"def",
"random_integers",
"(",
"cls",
",",
"size",
",",
"seed",
"=",
"None",
")",
":",
"if",
"seed",
"is",
"None",
":",
"seed",
"=",
"abs",
"(",
"hash",
"(",
"\"%0.20f\"",
"%",
"time",
".",
"time",
"(",
")",
")",
")",
"%",
"(",
"2",
"**",
"31",... | Returns an SArray with random integer values. | [
"Returns",
"an",
"SArray",
"with",
"random",
"integer",
"values",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2030-L2036 |
29,514 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.argmin | def argmin(self):
"""
Get the index of the minimum numeric value in SArray.
Returns None on an empty SArray. Raises an exception if called on an
SArray with non-numeric type.
Returns
-------
out : int
index of the minimum value of SArray
See Also
--------
argmax
Examples
--------
>>> turicreate.SArray([14, 62, 83, 72, 77, 96, 5, 25, 69, 66]).argmin()
"""
from .sframe import SFrame as _SFrame
if len(self) == 0:
return None
if not any([isinstance(self[0], i) for i in [int,float,long]]):
raise TypeError("SArray must be of type 'int', 'long', or 'float'.")
sf = _SFrame(self).add_row_number()
sf_out = sf.groupby(key_column_names=[],operations={'minimum_x1': _aggregate.ARGMIN('X1','id')})
return sf_out['minimum_x1'][0] | python | def argmin(self):
"""
Get the index of the minimum numeric value in SArray.
Returns None on an empty SArray. Raises an exception if called on an
SArray with non-numeric type.
Returns
-------
out : int
index of the minimum value of SArray
See Also
--------
argmax
Examples
--------
>>> turicreate.SArray([14, 62, 83, 72, 77, 96, 5, 25, 69, 66]).argmin()
"""
from .sframe import SFrame as _SFrame
if len(self) == 0:
return None
if not any([isinstance(self[0], i) for i in [int,float,long]]):
raise TypeError("SArray must be of type 'int', 'long', or 'float'.")
sf = _SFrame(self).add_row_number()
sf_out = sf.groupby(key_column_names=[],operations={'minimum_x1': _aggregate.ARGMIN('X1','id')})
return sf_out['minimum_x1'][0] | [
"def",
"argmin",
"(",
"self",
")",
":",
"from",
".",
"sframe",
"import",
"SFrame",
"as",
"_SFrame",
"if",
"len",
"(",
"self",
")",
"==",
"0",
":",
"return",
"None",
"if",
"not",
"any",
"(",
"[",
"isinstance",
"(",
"self",
"[",
"0",
"]",
",",
"i",... | Get the index of the minimum numeric value in SArray.
Returns None on an empty SArray. Raises an exception if called on an
SArray with non-numeric type.
Returns
-------
out : int
index of the minimum value of SArray
See Also
--------
argmax
Examples
--------
>>> turicreate.SArray([14, 62, 83, 72, 77, 96, 5, 25, 69, 66]).argmin() | [
"Get",
"the",
"index",
"of",
"the",
"minimum",
"numeric",
"value",
"in",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2201-L2231 |
29,515 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.mean | def mean(self):
"""
Mean of all the values in the SArray, or mean image.
Returns None on an empty SArray. Raises an exception if called on an
SArray with non-numeric type or non-Image type.
Returns
-------
out : float | turicreate.Image
Mean of all values in SArray, or image holding per-pixel mean
across the input SArray.
"""
with cython_context():
if self.dtype == _Image:
from .. import extensions
return extensions.generate_mean(self)
else:
return self.__proxy__.mean() | python | def mean(self):
"""
Mean of all the values in the SArray, or mean image.
Returns None on an empty SArray. Raises an exception if called on an
SArray with non-numeric type or non-Image type.
Returns
-------
out : float | turicreate.Image
Mean of all values in SArray, or image holding per-pixel mean
across the input SArray.
"""
with cython_context():
if self.dtype == _Image:
from .. import extensions
return extensions.generate_mean(self)
else:
return self.__proxy__.mean() | [
"def",
"mean",
"(",
"self",
")",
":",
"with",
"cython_context",
"(",
")",
":",
"if",
"self",
".",
"dtype",
"==",
"_Image",
":",
"from",
".",
".",
"import",
"extensions",
"return",
"extensions",
".",
"generate_mean",
"(",
"self",
")",
"else",
":",
"retu... | Mean of all the values in the SArray, or mean image.
Returns None on an empty SArray. Raises an exception if called on an
SArray with non-numeric type or non-Image type.
Returns
-------
out : float | turicreate.Image
Mean of all values in SArray, or image holding per-pixel mean
across the input SArray. | [
"Mean",
"of",
"all",
"the",
"values",
"in",
"the",
"SArray",
"or",
"mean",
"image",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2252-L2270 |
29,516 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.datetime_to_str | def datetime_to_str(self,format="%Y-%m-%dT%H:%M:%S%ZP"):
"""
Create a new SArray with all the values cast to str. The string format is
specified by the 'format' parameter.
Parameters
----------
format : str
The format to output the string. Default format is "%Y-%m-%dT%H:%M:%S%ZP".
Returns
-------
out : SArray[str]
The SArray converted to the type 'str'.
Examples
--------
>>> dt = datetime.datetime(2011, 10, 20, 9, 30, 10, tzinfo=GMT(-5))
>>> sa = turicreate.SArray([dt])
>>> sa.datetime_to_str("%e %b %Y %T %ZP")
dtype: str
Rows: 1
[20 Oct 2011 09:30:10 GMT-05:00]
See Also
----------
str_to_datetime
References
----------
[1] Boost date time from string conversion guide (http://www.boost.org/doc/libs/1_48_0/doc/html/date_time/date_time_io.html)
"""
if(self.dtype != datetime.datetime):
raise TypeError("datetime_to_str expects SArray of datetime as input SArray")
with cython_context():
return SArray(_proxy=self.__proxy__.datetime_to_str(format)) | python | def datetime_to_str(self,format="%Y-%m-%dT%H:%M:%S%ZP"):
"""
Create a new SArray with all the values cast to str. The string format is
specified by the 'format' parameter.
Parameters
----------
format : str
The format to output the string. Default format is "%Y-%m-%dT%H:%M:%S%ZP".
Returns
-------
out : SArray[str]
The SArray converted to the type 'str'.
Examples
--------
>>> dt = datetime.datetime(2011, 10, 20, 9, 30, 10, tzinfo=GMT(-5))
>>> sa = turicreate.SArray([dt])
>>> sa.datetime_to_str("%e %b %Y %T %ZP")
dtype: str
Rows: 1
[20 Oct 2011 09:30:10 GMT-05:00]
See Also
----------
str_to_datetime
References
----------
[1] Boost date time from string conversion guide (http://www.boost.org/doc/libs/1_48_0/doc/html/date_time/date_time_io.html)
"""
if(self.dtype != datetime.datetime):
raise TypeError("datetime_to_str expects SArray of datetime as input SArray")
with cython_context():
return SArray(_proxy=self.__proxy__.datetime_to_str(format)) | [
"def",
"datetime_to_str",
"(",
"self",
",",
"format",
"=",
"\"%Y-%m-%dT%H:%M:%S%ZP\"",
")",
":",
"if",
"(",
"self",
".",
"dtype",
"!=",
"datetime",
".",
"datetime",
")",
":",
"raise",
"TypeError",
"(",
"\"datetime_to_str expects SArray of datetime as input SArray\"",
... | Create a new SArray with all the values cast to str. The string format is
specified by the 'format' parameter.
Parameters
----------
format : str
The format to output the string. Default format is "%Y-%m-%dT%H:%M:%S%ZP".
Returns
-------
out : SArray[str]
The SArray converted to the type 'str'.
Examples
--------
>>> dt = datetime.datetime(2011, 10, 20, 9, 30, 10, tzinfo=GMT(-5))
>>> sa = turicreate.SArray([dt])
>>> sa.datetime_to_str("%e %b %Y %T %ZP")
dtype: str
Rows: 1
[20 Oct 2011 09:30:10 GMT-05:00]
See Also
----------
str_to_datetime
References
----------
[1] Boost date time from string conversion guide (http://www.boost.org/doc/libs/1_48_0/doc/html/date_time/date_time_io.html) | [
"Create",
"a",
"new",
"SArray",
"with",
"all",
"the",
"values",
"cast",
"to",
"str",
".",
"The",
"string",
"format",
"is",
"specified",
"by",
"the",
"format",
"parameter",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2338-L2375 |
29,517 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.str_to_datetime | def str_to_datetime(self,format="%Y-%m-%dT%H:%M:%S%ZP"):
"""
Create a new SArray with all the values cast to datetime. The string format is
specified by the 'format' parameter.
Parameters
----------
format : str
The string format of the input SArray. Default format is "%Y-%m-%dT%H:%M:%S%ZP".
If format is "ISO", the the format is "%Y%m%dT%H%M%S%F%q"
Returns
-------
out : SArray[datetime.datetime]
The SArray converted to the type 'datetime'.
Examples
--------
>>> sa = turicreate.SArray(["20-Oct-2011 09:30:10 GMT-05:30"])
>>> sa.str_to_datetime("%d-%b-%Y %H:%M:%S %ZP")
dtype: datetime
Rows: 1
datetime.datetime(2011, 10, 20, 9, 30, 10, tzinfo=GMT(-5.5))
See Also
----------
datetime_to_str
References
----------
[1] boost date time to string conversion guide (http://www.boost.org/doc/libs/1_48_0/doc/html/date_time/date_time_io.html)
"""
if(self.dtype != str):
raise TypeError("str_to_datetime expects SArray of str as input SArray")
with cython_context():
return SArray(_proxy=self.__proxy__.str_to_datetime(format)) | python | def str_to_datetime(self,format="%Y-%m-%dT%H:%M:%S%ZP"):
"""
Create a new SArray with all the values cast to datetime. The string format is
specified by the 'format' parameter.
Parameters
----------
format : str
The string format of the input SArray. Default format is "%Y-%m-%dT%H:%M:%S%ZP".
If format is "ISO", the the format is "%Y%m%dT%H%M%S%F%q"
Returns
-------
out : SArray[datetime.datetime]
The SArray converted to the type 'datetime'.
Examples
--------
>>> sa = turicreate.SArray(["20-Oct-2011 09:30:10 GMT-05:30"])
>>> sa.str_to_datetime("%d-%b-%Y %H:%M:%S %ZP")
dtype: datetime
Rows: 1
datetime.datetime(2011, 10, 20, 9, 30, 10, tzinfo=GMT(-5.5))
See Also
----------
datetime_to_str
References
----------
[1] boost date time to string conversion guide (http://www.boost.org/doc/libs/1_48_0/doc/html/date_time/date_time_io.html)
"""
if(self.dtype != str):
raise TypeError("str_to_datetime expects SArray of str as input SArray")
with cython_context():
return SArray(_proxy=self.__proxy__.str_to_datetime(format)) | [
"def",
"str_to_datetime",
"(",
"self",
",",
"format",
"=",
"\"%Y-%m-%dT%H:%M:%S%ZP\"",
")",
":",
"if",
"(",
"self",
".",
"dtype",
"!=",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"str_to_datetime expects SArray of str as input SArray\"",
")",
"with",
"cython_cont... | Create a new SArray with all the values cast to datetime. The string format is
specified by the 'format' parameter.
Parameters
----------
format : str
The string format of the input SArray. Default format is "%Y-%m-%dT%H:%M:%S%ZP".
If format is "ISO", the the format is "%Y%m%dT%H%M%S%F%q"
Returns
-------
out : SArray[datetime.datetime]
The SArray converted to the type 'datetime'.
Examples
--------
>>> sa = turicreate.SArray(["20-Oct-2011 09:30:10 GMT-05:30"])
>>> sa.str_to_datetime("%d-%b-%Y %H:%M:%S %ZP")
dtype: datetime
Rows: 1
datetime.datetime(2011, 10, 20, 9, 30, 10, tzinfo=GMT(-5.5))
See Also
----------
datetime_to_str
References
----------
[1] boost date time to string conversion guide (http://www.boost.org/doc/libs/1_48_0/doc/html/date_time/date_time_io.html) | [
"Create",
"a",
"new",
"SArray",
"with",
"all",
"the",
"values",
"cast",
"to",
"datetime",
".",
"The",
"string",
"format",
"is",
"specified",
"by",
"the",
"format",
"parameter",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2377-L2413 |
29,518 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.astype | def astype(self, dtype, undefined_on_failure=False):
"""
Create a new SArray with all values cast to the given type. Throws an
exception if the types are not castable to the given type.
Parameters
----------
dtype : {int, float, str, list, array.array, dict, datetime.datetime}
The type to cast the elements to in SArray
undefined_on_failure: bool, optional
If set to True, runtime cast failures will be emitted as missing
values rather than failing.
Returns
-------
out : SArray [dtype]
The SArray converted to the type ``dtype``.
Notes
-----
- The string parsing techniques used to handle conversion to dictionary
and list types are quite generic and permit a variety of interesting
formats to be interpreted. For instance, a JSON string can usually be
interpreted as a list or a dictionary type. See the examples below.
- For datetime-to-string and string-to-datetime conversions,
use sa.datetime_to_str() and sa.str_to_datetime() functions.
- For array.array to turicreate.Image conversions, use sa.pixel_array_to_image()
Examples
--------
>>> sa = turicreate.SArray(['1','2','3','4'])
>>> sa.astype(int)
dtype: int
Rows: 4
[1, 2, 3, 4]
Given an SArray of strings that look like dicts, convert to a dictionary
type:
>>> sa = turicreate.SArray(['{1:2 3:4}', '{a:b c:d}'])
>>> sa.astype(dict)
dtype: dict
Rows: 2
[{1: 2, 3: 4}, {'a': 'b', 'c': 'd'}]
"""
if (dtype == _Image) and (self.dtype == array.array):
raise TypeError("Cannot cast from image type to array with sarray.astype(). Please use sarray.pixel_array_to_image() instead.")
with cython_context():
return SArray(_proxy=self.__proxy__.astype(dtype, undefined_on_failure)) | python | def astype(self, dtype, undefined_on_failure=False):
"""
Create a new SArray with all values cast to the given type. Throws an
exception if the types are not castable to the given type.
Parameters
----------
dtype : {int, float, str, list, array.array, dict, datetime.datetime}
The type to cast the elements to in SArray
undefined_on_failure: bool, optional
If set to True, runtime cast failures will be emitted as missing
values rather than failing.
Returns
-------
out : SArray [dtype]
The SArray converted to the type ``dtype``.
Notes
-----
- The string parsing techniques used to handle conversion to dictionary
and list types are quite generic and permit a variety of interesting
formats to be interpreted. For instance, a JSON string can usually be
interpreted as a list or a dictionary type. See the examples below.
- For datetime-to-string and string-to-datetime conversions,
use sa.datetime_to_str() and sa.str_to_datetime() functions.
- For array.array to turicreate.Image conversions, use sa.pixel_array_to_image()
Examples
--------
>>> sa = turicreate.SArray(['1','2','3','4'])
>>> sa.astype(int)
dtype: int
Rows: 4
[1, 2, 3, 4]
Given an SArray of strings that look like dicts, convert to a dictionary
type:
>>> sa = turicreate.SArray(['{1:2 3:4}', '{a:b c:d}'])
>>> sa.astype(dict)
dtype: dict
Rows: 2
[{1: 2, 3: 4}, {'a': 'b', 'c': 'd'}]
"""
if (dtype == _Image) and (self.dtype == array.array):
raise TypeError("Cannot cast from image type to array with sarray.astype(). Please use sarray.pixel_array_to_image() instead.")
with cython_context():
return SArray(_proxy=self.__proxy__.astype(dtype, undefined_on_failure)) | [
"def",
"astype",
"(",
"self",
",",
"dtype",
",",
"undefined_on_failure",
"=",
"False",
")",
":",
"if",
"(",
"dtype",
"==",
"_Image",
")",
"and",
"(",
"self",
".",
"dtype",
"==",
"array",
".",
"array",
")",
":",
"raise",
"TypeError",
"(",
"\"Cannot cast... | Create a new SArray with all values cast to the given type. Throws an
exception if the types are not castable to the given type.
Parameters
----------
dtype : {int, float, str, list, array.array, dict, datetime.datetime}
The type to cast the elements to in SArray
undefined_on_failure: bool, optional
If set to True, runtime cast failures will be emitted as missing
values rather than failing.
Returns
-------
out : SArray [dtype]
The SArray converted to the type ``dtype``.
Notes
-----
- The string parsing techniques used to handle conversion to dictionary
and list types are quite generic and permit a variety of interesting
formats to be interpreted. For instance, a JSON string can usually be
interpreted as a list or a dictionary type. See the examples below.
- For datetime-to-string and string-to-datetime conversions,
use sa.datetime_to_str() and sa.str_to_datetime() functions.
- For array.array to turicreate.Image conversions, use sa.pixel_array_to_image()
Examples
--------
>>> sa = turicreate.SArray(['1','2','3','4'])
>>> sa.astype(int)
dtype: int
Rows: 4
[1, 2, 3, 4]
Given an SArray of strings that look like dicts, convert to a dictionary
type:
>>> sa = turicreate.SArray(['{1:2 3:4}', '{a:b c:d}'])
>>> sa.astype(dict)
dtype: dict
Rows: 2
[{1: 2, 3: 4}, {'a': 'b', 'c': 'd'}] | [
"Create",
"a",
"new",
"SArray",
"with",
"all",
"values",
"cast",
"to",
"the",
"given",
"type",
".",
"Throws",
"an",
"exception",
"if",
"the",
"types",
"are",
"not",
"castable",
"to",
"the",
"given",
"type",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2480-L2531 |
29,519 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.clip | def clip(self, lower=float('nan'), upper=float('nan')):
"""
Create a new SArray with each value clipped to be within the given
bounds.
In this case, "clipped" means that values below the lower bound will be
set to the lower bound value. Values above the upper bound will be set
to the upper bound value. This function can operate on SArrays of
numeric type as well as array type, in which case each individual
element in each array is clipped. By default ``lower`` and ``upper`` are
set to ``float('nan')`` which indicates the respective bound should be
ignored. The method fails if invoked on an SArray of non-numeric type.
Parameters
----------
lower : int, optional
The lower bound used to clip. Ignored if equal to ``float('nan')``
(the default).
upper : int, optional
The upper bound used to clip. Ignored if equal to ``float('nan')``
(the default).
Returns
-------
out : SArray
See Also
--------
clip_lower, clip_upper
Examples
--------
>>> sa = turicreate.SArray([1,2,3])
>>> sa.clip(2,2)
dtype: int
Rows: 3
[2, 2, 2]
"""
with cython_context():
return SArray(_proxy=self.__proxy__.clip(lower, upper)) | python | def clip(self, lower=float('nan'), upper=float('nan')):
"""
Create a new SArray with each value clipped to be within the given
bounds.
In this case, "clipped" means that values below the lower bound will be
set to the lower bound value. Values above the upper bound will be set
to the upper bound value. This function can operate on SArrays of
numeric type as well as array type, in which case each individual
element in each array is clipped. By default ``lower`` and ``upper`` are
set to ``float('nan')`` which indicates the respective bound should be
ignored. The method fails if invoked on an SArray of non-numeric type.
Parameters
----------
lower : int, optional
The lower bound used to clip. Ignored if equal to ``float('nan')``
(the default).
upper : int, optional
The upper bound used to clip. Ignored if equal to ``float('nan')``
(the default).
Returns
-------
out : SArray
See Also
--------
clip_lower, clip_upper
Examples
--------
>>> sa = turicreate.SArray([1,2,3])
>>> sa.clip(2,2)
dtype: int
Rows: 3
[2, 2, 2]
"""
with cython_context():
return SArray(_proxy=self.__proxy__.clip(lower, upper)) | [
"def",
"clip",
"(",
"self",
",",
"lower",
"=",
"float",
"(",
"'nan'",
")",
",",
"upper",
"=",
"float",
"(",
"'nan'",
")",
")",
":",
"with",
"cython_context",
"(",
")",
":",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
"__proxy__",
".",
"cli... | Create a new SArray with each value clipped to be within the given
bounds.
In this case, "clipped" means that values below the lower bound will be
set to the lower bound value. Values above the upper bound will be set
to the upper bound value. This function can operate on SArrays of
numeric type as well as array type, in which case each individual
element in each array is clipped. By default ``lower`` and ``upper`` are
set to ``float('nan')`` which indicates the respective bound should be
ignored. The method fails if invoked on an SArray of non-numeric type.
Parameters
----------
lower : int, optional
The lower bound used to clip. Ignored if equal to ``float('nan')``
(the default).
upper : int, optional
The upper bound used to clip. Ignored if equal to ``float('nan')``
(the default).
Returns
-------
out : SArray
See Also
--------
clip_lower, clip_upper
Examples
--------
>>> sa = turicreate.SArray([1,2,3])
>>> sa.clip(2,2)
dtype: int
Rows: 3
[2, 2, 2] | [
"Create",
"a",
"new",
"SArray",
"with",
"each",
"value",
"clipped",
"to",
"be",
"within",
"the",
"given",
"bounds",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2533-L2573 |
29,520 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.clip_lower | def clip_lower(self, threshold):
"""
Create new SArray with all values clipped to the given lower bound. This
function can operate on numeric arrays, as well as vector arrays, in
which case each individual element in each vector is clipped. Throws an
exception if the SArray is empty or the types are non-numeric.
Parameters
----------
threshold : float
The lower bound used to clip values.
Returns
-------
out : SArray
See Also
--------
clip, clip_upper
Examples
--------
>>> sa = turicreate.SArray([1,2,3])
>>> sa.clip_lower(2)
dtype: int
Rows: 3
[2, 2, 3]
"""
with cython_context():
return SArray(_proxy=self.__proxy__.clip(threshold, float('nan'))) | python | def clip_lower(self, threshold):
"""
Create new SArray with all values clipped to the given lower bound. This
function can operate on numeric arrays, as well as vector arrays, in
which case each individual element in each vector is clipped. Throws an
exception if the SArray is empty or the types are non-numeric.
Parameters
----------
threshold : float
The lower bound used to clip values.
Returns
-------
out : SArray
See Also
--------
clip, clip_upper
Examples
--------
>>> sa = turicreate.SArray([1,2,3])
>>> sa.clip_lower(2)
dtype: int
Rows: 3
[2, 2, 3]
"""
with cython_context():
return SArray(_proxy=self.__proxy__.clip(threshold, float('nan'))) | [
"def",
"clip_lower",
"(",
"self",
",",
"threshold",
")",
":",
"with",
"cython_context",
"(",
")",
":",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
"__proxy__",
".",
"clip",
"(",
"threshold",
",",
"float",
"(",
"'nan'",
")",
")",
")"
] | Create new SArray with all values clipped to the given lower bound. This
function can operate on numeric arrays, as well as vector arrays, in
which case each individual element in each vector is clipped. Throws an
exception if the SArray is empty or the types are non-numeric.
Parameters
----------
threshold : float
The lower bound used to clip values.
Returns
-------
out : SArray
See Also
--------
clip, clip_upper
Examples
--------
>>> sa = turicreate.SArray([1,2,3])
>>> sa.clip_lower(2)
dtype: int
Rows: 3
[2, 2, 3] | [
"Create",
"new",
"SArray",
"with",
"all",
"values",
"clipped",
"to",
"the",
"given",
"lower",
"bound",
".",
"This",
"function",
"can",
"operate",
"on",
"numeric",
"arrays",
"as",
"well",
"as",
"vector",
"arrays",
"in",
"which",
"case",
"each",
"individual",
... | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2575-L2604 |
29,521 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.tail | def tail(self, n=10):
"""
Get an SArray that contains the last n elements in the SArray.
Parameters
----------
n : int
The number of elements to fetch
Returns
-------
out : SArray
A new SArray which contains the last n rows of the current SArray.
"""
with cython_context():
return SArray(_proxy=self.__proxy__.tail(n)) | python | def tail(self, n=10):
"""
Get an SArray that contains the last n elements in the SArray.
Parameters
----------
n : int
The number of elements to fetch
Returns
-------
out : SArray
A new SArray which contains the last n rows of the current SArray.
"""
with cython_context():
return SArray(_proxy=self.__proxy__.tail(n)) | [
"def",
"tail",
"(",
"self",
",",
"n",
"=",
"10",
")",
":",
"with",
"cython_context",
"(",
")",
":",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
"__proxy__",
".",
"tail",
"(",
"n",
")",
")"
] | Get an SArray that contains the last n elements in the SArray.
Parameters
----------
n : int
The number of elements to fetch
Returns
-------
out : SArray
A new SArray which contains the last n rows of the current SArray. | [
"Get",
"an",
"SArray",
"that",
"contains",
"the",
"last",
"n",
"elements",
"in",
"the",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2637-L2652 |
29,522 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.is_topk | def is_topk(self, topk=10, reverse=False):
"""
Create an SArray indicating which elements are in the top k.
Entries are '1' if the corresponding element in the current SArray is a
part of the top k elements, and '0' if that corresponding element is
not. Order is descending by default.
Parameters
----------
topk : int
The number of elements to determine if 'top'
reverse : bool
If True, return the topk elements in ascending order
Returns
-------
out : SArray (of type int)
Notes
-----
This is used internally by SFrame's topk function.
"""
with cython_context():
return SArray(_proxy = self.__proxy__.topk_index(topk, reverse)) | python | def is_topk(self, topk=10, reverse=False):
"""
Create an SArray indicating which elements are in the top k.
Entries are '1' if the corresponding element in the current SArray is a
part of the top k elements, and '0' if that corresponding element is
not. Order is descending by default.
Parameters
----------
topk : int
The number of elements to determine if 'top'
reverse : bool
If True, return the topk elements in ascending order
Returns
-------
out : SArray (of type int)
Notes
-----
This is used internally by SFrame's topk function.
"""
with cython_context():
return SArray(_proxy = self.__proxy__.topk_index(topk, reverse)) | [
"def",
"is_topk",
"(",
"self",
",",
"topk",
"=",
"10",
",",
"reverse",
"=",
"False",
")",
":",
"with",
"cython_context",
"(",
")",
":",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
"__proxy__",
".",
"topk_index",
"(",
"topk",
",",
"reverse",
... | Create an SArray indicating which elements are in the top k.
Entries are '1' if the corresponding element in the current SArray is a
part of the top k elements, and '0' if that corresponding element is
not. Order is descending by default.
Parameters
----------
topk : int
The number of elements to determine if 'top'
reverse : bool
If True, return the topk elements in ascending order
Returns
-------
out : SArray (of type int)
Notes
-----
This is used internally by SFrame's topk function. | [
"Create",
"an",
"SArray",
"indicating",
"which",
"elements",
"are",
"in",
"the",
"top",
"k",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2697-L2722 |
29,523 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.summary | def summary(self, background=False, sub_sketch_keys=None):
"""
Summary statistics that can be calculated with one pass over the SArray.
Returns a turicreate.Sketch object which can be further queried for many
descriptive statistics over this SArray. Many of the statistics are
approximate. See the :class:`~turicreate.Sketch` documentation for more
detail.
Parameters
----------
background : boolean, optional
If True, the sketch construction will return immediately and the
sketch will be constructed in the background. While this is going on,
the sketch can be queried incrementally, but at a performance penalty.
Defaults to False.
sub_sketch_keys : int | str | list of int | list of str, optional
For SArray of dict type, also constructs sketches for a given set of keys,
For SArray of array type, also constructs sketches for the given indexes.
The sub sketches may be queried using: :py:func:`~turicreate.Sketch.element_sub_sketch()`.
Defaults to None in which case no subsketches will be constructed.
Returns
-------
out : Sketch
Sketch object that contains descriptive statistics for this SArray.
Many of the statistics are approximate.
"""
from ..data_structures.sketch import Sketch
if (self.dtype == _Image):
raise TypeError("summary() is not supported for arrays of image type")
if (type(background) != bool):
raise TypeError("'background' parameter has to be a boolean value")
if (sub_sketch_keys is not None):
if (self.dtype != dict and self.dtype != array.array):
raise TypeError("sub_sketch_keys is only supported for SArray of dictionary or array type")
if not _is_non_string_iterable(sub_sketch_keys):
sub_sketch_keys = [sub_sketch_keys]
value_types = set([type(i) for i in sub_sketch_keys])
if (len(value_types) != 1):
raise ValueError("sub_sketch_keys member values need to have the same type.")
value_type = value_types.pop()
if (self.dtype == dict and value_type != str):
raise TypeError("Only string value(s) can be passed to sub_sketch_keys for SArray of dictionary type. "+
"For dictionary types, sketch summary is computed by casting keys to string values.")
if (self.dtype == array.array and value_type != int):
raise TypeError("Only int value(s) can be passed to sub_sketch_keys for SArray of array type")
else:
sub_sketch_keys = list()
return Sketch(self, background, sub_sketch_keys = sub_sketch_keys) | python | def summary(self, background=False, sub_sketch_keys=None):
"""
Summary statistics that can be calculated with one pass over the SArray.
Returns a turicreate.Sketch object which can be further queried for many
descriptive statistics over this SArray. Many of the statistics are
approximate. See the :class:`~turicreate.Sketch` documentation for more
detail.
Parameters
----------
background : boolean, optional
If True, the sketch construction will return immediately and the
sketch will be constructed in the background. While this is going on,
the sketch can be queried incrementally, but at a performance penalty.
Defaults to False.
sub_sketch_keys : int | str | list of int | list of str, optional
For SArray of dict type, also constructs sketches for a given set of keys,
For SArray of array type, also constructs sketches for the given indexes.
The sub sketches may be queried using: :py:func:`~turicreate.Sketch.element_sub_sketch()`.
Defaults to None in which case no subsketches will be constructed.
Returns
-------
out : Sketch
Sketch object that contains descriptive statistics for this SArray.
Many of the statistics are approximate.
"""
from ..data_structures.sketch import Sketch
if (self.dtype == _Image):
raise TypeError("summary() is not supported for arrays of image type")
if (type(background) != bool):
raise TypeError("'background' parameter has to be a boolean value")
if (sub_sketch_keys is not None):
if (self.dtype != dict and self.dtype != array.array):
raise TypeError("sub_sketch_keys is only supported for SArray of dictionary or array type")
if not _is_non_string_iterable(sub_sketch_keys):
sub_sketch_keys = [sub_sketch_keys]
value_types = set([type(i) for i in sub_sketch_keys])
if (len(value_types) != 1):
raise ValueError("sub_sketch_keys member values need to have the same type.")
value_type = value_types.pop()
if (self.dtype == dict and value_type != str):
raise TypeError("Only string value(s) can be passed to sub_sketch_keys for SArray of dictionary type. "+
"For dictionary types, sketch summary is computed by casting keys to string values.")
if (self.dtype == array.array and value_type != int):
raise TypeError("Only int value(s) can be passed to sub_sketch_keys for SArray of array type")
else:
sub_sketch_keys = list()
return Sketch(self, background, sub_sketch_keys = sub_sketch_keys) | [
"def",
"summary",
"(",
"self",
",",
"background",
"=",
"False",
",",
"sub_sketch_keys",
"=",
"None",
")",
":",
"from",
".",
".",
"data_structures",
".",
"sketch",
"import",
"Sketch",
"if",
"(",
"self",
".",
"dtype",
"==",
"_Image",
")",
":",
"raise",
"... | Summary statistics that can be calculated with one pass over the SArray.
Returns a turicreate.Sketch object which can be further queried for many
descriptive statistics over this SArray. Many of the statistics are
approximate. See the :class:`~turicreate.Sketch` documentation for more
detail.
Parameters
----------
background : boolean, optional
If True, the sketch construction will return immediately and the
sketch will be constructed in the background. While this is going on,
the sketch can be queried incrementally, but at a performance penalty.
Defaults to False.
sub_sketch_keys : int | str | list of int | list of str, optional
For SArray of dict type, also constructs sketches for a given set of keys,
For SArray of array type, also constructs sketches for the given indexes.
The sub sketches may be queried using: :py:func:`~turicreate.Sketch.element_sub_sketch()`.
Defaults to None in which case no subsketches will be constructed.
Returns
-------
out : Sketch
Sketch object that contains descriptive statistics for this SArray.
Many of the statistics are approximate. | [
"Summary",
"statistics",
"that",
"can",
"be",
"calculated",
"with",
"one",
"pass",
"over",
"the",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2724-L2775 |
29,524 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.value_counts | def value_counts(self):
"""
Return an SFrame containing counts of unique values. The resulting
SFrame will be sorted in descending frequency.
Returns
-------
out : SFrame
An SFrame containing 2 columns : 'value', and 'count'. The SFrame will
be sorted in descending order by the column 'count'.
See Also
--------
SFrame.summary
Examples
--------
>>> sa = turicreate.SArray([1,1,2,2,2,2,3,3,3,3,3,3,3])
>>> sa.value_counts()
Columns:
value int
count int
Rows: 3
Data:
+-------+-------+
| value | count |
+-------+-------+
| 3 | 7 |
| 2 | 4 |
| 1 | 2 |
+-------+-------+
[3 rows x 2 columns]
"""
from .sframe import SFrame as _SFrame
return _SFrame({'value':self}).groupby('value', {'count':_aggregate.COUNT}).sort('count', ascending=False) | python | def value_counts(self):
"""
Return an SFrame containing counts of unique values. The resulting
SFrame will be sorted in descending frequency.
Returns
-------
out : SFrame
An SFrame containing 2 columns : 'value', and 'count'. The SFrame will
be sorted in descending order by the column 'count'.
See Also
--------
SFrame.summary
Examples
--------
>>> sa = turicreate.SArray([1,1,2,2,2,2,3,3,3,3,3,3,3])
>>> sa.value_counts()
Columns:
value int
count int
Rows: 3
Data:
+-------+-------+
| value | count |
+-------+-------+
| 3 | 7 |
| 2 | 4 |
| 1 | 2 |
+-------+-------+
[3 rows x 2 columns]
"""
from .sframe import SFrame as _SFrame
return _SFrame({'value':self}).groupby('value', {'count':_aggregate.COUNT}).sort('count', ascending=False) | [
"def",
"value_counts",
"(",
"self",
")",
":",
"from",
".",
"sframe",
"import",
"SFrame",
"as",
"_SFrame",
"return",
"_SFrame",
"(",
"{",
"'value'",
":",
"self",
"}",
")",
".",
"groupby",
"(",
"'value'",
",",
"{",
"'count'",
":",
"_aggregate",
".",
"COU... | Return an SFrame containing counts of unique values. The resulting
SFrame will be sorted in descending frequency.
Returns
-------
out : SFrame
An SFrame containing 2 columns : 'value', and 'count'. The SFrame will
be sorted in descending order by the column 'count'.
See Also
--------
SFrame.summary
Examples
--------
>>> sa = turicreate.SArray([1,1,2,2,2,2,3,3,3,3,3,3,3])
>>> sa.value_counts()
Columns:
value int
count int
Rows: 3
Data:
+-------+-------+
| value | count |
+-------+-------+
| 3 | 7 |
| 2 | 4 |
| 1 | 2 |
+-------+-------+
[3 rows x 2 columns] | [
"Return",
"an",
"SFrame",
"containing",
"counts",
"of",
"unique",
"values",
".",
"The",
"resulting",
"SFrame",
"will",
"be",
"sorted",
"in",
"descending",
"frequency",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2777-L2811 |
29,525 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.append | def append(self, other):
"""
Append an SArray to the current SArray. Creates a new SArray with the
rows from both SArrays. Both SArrays must be of the same type.
Parameters
----------
other : SArray
Another SArray whose rows are appended to current SArray.
Returns
-------
out : SArray
A new SArray that contains rows from both SArrays, with rows from
the ``other`` SArray coming after all rows from the current SArray.
See Also
--------
SFrame.append
Examples
--------
>>> sa = turicreate.SArray([1, 2, 3])
>>> sa2 = turicreate.SArray([4, 5, 6])
>>> sa.append(sa2)
dtype: int
Rows: 6
[1, 2, 3, 4, 5, 6]
"""
if type(other) is not SArray:
raise RuntimeError("SArray append can only work with SArray")
if self.dtype != other.dtype:
raise RuntimeError("Data types in both SArrays have to be the same")
with cython_context():
return SArray(_proxy = self.__proxy__.append(other.__proxy__)) | python | def append(self, other):
"""
Append an SArray to the current SArray. Creates a new SArray with the
rows from both SArrays. Both SArrays must be of the same type.
Parameters
----------
other : SArray
Another SArray whose rows are appended to current SArray.
Returns
-------
out : SArray
A new SArray that contains rows from both SArrays, with rows from
the ``other`` SArray coming after all rows from the current SArray.
See Also
--------
SFrame.append
Examples
--------
>>> sa = turicreate.SArray([1, 2, 3])
>>> sa2 = turicreate.SArray([4, 5, 6])
>>> sa.append(sa2)
dtype: int
Rows: 6
[1, 2, 3, 4, 5, 6]
"""
if type(other) is not SArray:
raise RuntimeError("SArray append can only work with SArray")
if self.dtype != other.dtype:
raise RuntimeError("Data types in both SArrays have to be the same")
with cython_context():
return SArray(_proxy = self.__proxy__.append(other.__proxy__)) | [
"def",
"append",
"(",
"self",
",",
"other",
")",
":",
"if",
"type",
"(",
"other",
")",
"is",
"not",
"SArray",
":",
"raise",
"RuntimeError",
"(",
"\"SArray append can only work with SArray\"",
")",
"if",
"self",
".",
"dtype",
"!=",
"other",
".",
"dtype",
":... | Append an SArray to the current SArray. Creates a new SArray with the
rows from both SArrays. Both SArrays must be of the same type.
Parameters
----------
other : SArray
Another SArray whose rows are appended to current SArray.
Returns
-------
out : SArray
A new SArray that contains rows from both SArrays, with rows from
the ``other`` SArray coming after all rows from the current SArray.
See Also
--------
SFrame.append
Examples
--------
>>> sa = turicreate.SArray([1, 2, 3])
>>> sa2 = turicreate.SArray([4, 5, 6])
>>> sa.append(sa2)
dtype: int
Rows: 6
[1, 2, 3, 4, 5, 6] | [
"Append",
"an",
"SArray",
"to",
"the",
"current",
"SArray",
".",
"Creates",
"a",
"new",
"SArray",
"with",
"the",
"rows",
"from",
"both",
"SArrays",
".",
"Both",
"SArrays",
"must",
"be",
"of",
"the",
"same",
"type",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2814-L2850 |
29,526 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.unique | def unique(self):
"""
Get all unique values in the current SArray.
Raises a TypeError if the SArray is of dictionary type. Will not
necessarily preserve the order of the given SArray in the new SArray.
Returns
-------
out : SArray
A new SArray that contains the unique values of the current SArray.
See Also
--------
SFrame.unique
"""
from .sframe import SFrame as _SFrame
tmp_sf = _SFrame()
tmp_sf.add_column(self, 'X1', inplace=True)
res = tmp_sf.groupby('X1',{})
return SArray(_proxy=res['X1'].__proxy__) | python | def unique(self):
"""
Get all unique values in the current SArray.
Raises a TypeError if the SArray is of dictionary type. Will not
necessarily preserve the order of the given SArray in the new SArray.
Returns
-------
out : SArray
A new SArray that contains the unique values of the current SArray.
See Also
--------
SFrame.unique
"""
from .sframe import SFrame as _SFrame
tmp_sf = _SFrame()
tmp_sf.add_column(self, 'X1', inplace=True)
res = tmp_sf.groupby('X1',{})
return SArray(_proxy=res['X1'].__proxy__) | [
"def",
"unique",
"(",
"self",
")",
":",
"from",
".",
"sframe",
"import",
"SFrame",
"as",
"_SFrame",
"tmp_sf",
"=",
"_SFrame",
"(",
")",
"tmp_sf",
".",
"add_column",
"(",
"self",
",",
"'X1'",
",",
"inplace",
"=",
"True",
")",
"res",
"=",
"tmp_sf",
"."... | Get all unique values in the current SArray.
Raises a TypeError if the SArray is of dictionary type. Will not
necessarily preserve the order of the given SArray in the new SArray.
Returns
-------
out : SArray
A new SArray that contains the unique values of the current SArray.
See Also
--------
SFrame.unique | [
"Get",
"all",
"unique",
"values",
"in",
"the",
"current",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2852-L2876 |
29,527 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.show | def show(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT):
"""
Visualize the SArray.
Notes
-----
- The plot will render either inline in a Jupyter Notebook, or in a
native GUI window, depending on the value provided in
`turicreate.visualization.set_target` (defaults to 'auto').
Parameters
----------
title : str
The plot title to show for the resulting visualization.
If the title is None, the title will be omitted.
xlabel : str
The X axis label to show for the resulting visualization.
If the xlabel is None, the X axis label will be omitted.
ylabel : str
The Y axis label to show for the resulting visualization.
If the ylabel is None, the Y axis label will be omitted.
Returns
-------
None
Examples
--------
Suppose 'sa' is an SArray, we can view it using:
>>> sa.show()
To override the default plot title and axis labels:
>>> sa.show(title="My Plot Title", xlabel="My X Axis", ylabel="My Y Axis")
"""
returned_plot = self.plot(title, xlabel, ylabel)
returned_plot.show() | python | def show(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT):
"""
Visualize the SArray.
Notes
-----
- The plot will render either inline in a Jupyter Notebook, or in a
native GUI window, depending on the value provided in
`turicreate.visualization.set_target` (defaults to 'auto').
Parameters
----------
title : str
The plot title to show for the resulting visualization.
If the title is None, the title will be omitted.
xlabel : str
The X axis label to show for the resulting visualization.
If the xlabel is None, the X axis label will be omitted.
ylabel : str
The Y axis label to show for the resulting visualization.
If the ylabel is None, the Y axis label will be omitted.
Returns
-------
None
Examples
--------
Suppose 'sa' is an SArray, we can view it using:
>>> sa.show()
To override the default plot title and axis labels:
>>> sa.show(title="My Plot Title", xlabel="My X Axis", ylabel="My Y Axis")
"""
returned_plot = self.plot(title, xlabel, ylabel)
returned_plot.show() | [
"def",
"show",
"(",
"self",
",",
"title",
"=",
"LABEL_DEFAULT",
",",
"xlabel",
"=",
"LABEL_DEFAULT",
",",
"ylabel",
"=",
"LABEL_DEFAULT",
")",
":",
"returned_plot",
"=",
"self",
".",
"plot",
"(",
"title",
",",
"xlabel",
",",
"ylabel",
")",
"returned_plot",... | Visualize the SArray.
Notes
-----
- The plot will render either inline in a Jupyter Notebook, or in a
native GUI window, depending on the value provided in
`turicreate.visualization.set_target` (defaults to 'auto').
Parameters
----------
title : str
The plot title to show for the resulting visualization.
If the title is None, the title will be omitted.
xlabel : str
The X axis label to show for the resulting visualization.
If the xlabel is None, the X axis label will be omitted.
ylabel : str
The Y axis label to show for the resulting visualization.
If the ylabel is None, the Y axis label will be omitted.
Returns
-------
None
Examples
--------
Suppose 'sa' is an SArray, we can view it using:
>>> sa.show()
To override the default plot title and axis labels:
>>> sa.show(title="My Plot Title", xlabel="My X Axis", ylabel="My Y Axis") | [
"Visualize",
"the",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2905-L2946 |
29,528 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.plot | def plot(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT):
"""
Create a Plot object representing the SArray.
Notes
-----
- The plot will render either inline in a Jupyter Notebook, or in a
native GUI window, depending on the value provided in
`turicreate.visualization.set_target` (defaults to 'auto').
Parameters
----------
title : str
The plot title to show for the resulting visualization.
If the title is None, the title will be omitted.
xlabel : str
The X axis label to show for the resulting visualization.
If the xlabel is None, the X axis label will be omitted.
ylabel : str
The Y axis label to show for the resulting visualization.
If the ylabel is None, the Y axis label will be omitted.
Returns
-------
out : Plot
A :class: Plot object that is the visualization of the SArray.
Examples
--------
Suppose 'sa' is an SArray, we can create a plot of it using:
>>> plt = sa.plot()
To override the default plot title and axis labels:
>>> plt = sa.plot(title="My Plot Title", xlabel="My X Axis", ylabel="My Y Axis")
We can then visualize the plot using:
>>> plt.show()
"""
if title == "":
title = " "
if xlabel == "":
xlabel = " "
if ylabel == "":
ylabel = " "
if title is None:
title = "" # C++ otherwise gets "None" as std::string
if xlabel is None:
xlabel = ""
if ylabel is None:
ylabel = ""
return Plot(self.__proxy__.plot(title, xlabel, ylabel)) | python | def plot(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT):
"""
Create a Plot object representing the SArray.
Notes
-----
- The plot will render either inline in a Jupyter Notebook, or in a
native GUI window, depending on the value provided in
`turicreate.visualization.set_target` (defaults to 'auto').
Parameters
----------
title : str
The plot title to show for the resulting visualization.
If the title is None, the title will be omitted.
xlabel : str
The X axis label to show for the resulting visualization.
If the xlabel is None, the X axis label will be omitted.
ylabel : str
The Y axis label to show for the resulting visualization.
If the ylabel is None, the Y axis label will be omitted.
Returns
-------
out : Plot
A :class: Plot object that is the visualization of the SArray.
Examples
--------
Suppose 'sa' is an SArray, we can create a plot of it using:
>>> plt = sa.plot()
To override the default plot title and axis labels:
>>> plt = sa.plot(title="My Plot Title", xlabel="My X Axis", ylabel="My Y Axis")
We can then visualize the plot using:
>>> plt.show()
"""
if title == "":
title = " "
if xlabel == "":
xlabel = " "
if ylabel == "":
ylabel = " "
if title is None:
title = "" # C++ otherwise gets "None" as std::string
if xlabel is None:
xlabel = ""
if ylabel is None:
ylabel = ""
return Plot(self.__proxy__.plot(title, xlabel, ylabel)) | [
"def",
"plot",
"(",
"self",
",",
"title",
"=",
"LABEL_DEFAULT",
",",
"xlabel",
"=",
"LABEL_DEFAULT",
",",
"ylabel",
"=",
"LABEL_DEFAULT",
")",
":",
"if",
"title",
"==",
"\"\"",
":",
"title",
"=",
"\" \"",
"if",
"xlabel",
"==",
"\"\"",
":",
"xlabel",
"=... | Create a Plot object representing the SArray.
Notes
-----
- The plot will render either inline in a Jupyter Notebook, or in a
native GUI window, depending on the value provided in
`turicreate.visualization.set_target` (defaults to 'auto').
Parameters
----------
title : str
The plot title to show for the resulting visualization.
If the title is None, the title will be omitted.
xlabel : str
The X axis label to show for the resulting visualization.
If the xlabel is None, the X axis label will be omitted.
ylabel : str
The Y axis label to show for the resulting visualization.
If the ylabel is None, the Y axis label will be omitted.
Returns
-------
out : Plot
A :class: Plot object that is the visualization of the SArray.
Examples
--------
Suppose 'sa' is an SArray, we can create a plot of it using:
>>> plt = sa.plot()
To override the default plot title and axis labels:
>>> plt = sa.plot(title="My Plot Title", xlabel="My X Axis", ylabel="My Y Axis")
We can then visualize the plot using:
>>> plt.show() | [
"Create",
"a",
"Plot",
"object",
"representing",
"the",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2948-L3006 |
29,529 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.item_length | def item_length(self):
"""
Length of each element in the current SArray.
Only works on SArrays of dict, array, or list type. If a given element
is a missing value, then the output elements is also a missing value.
This function is equivalent to the following but more performant:
sa_item_len = sa.apply(lambda x: len(x) if x is not None else None)
Returns
-------
out_sf : SArray
A new SArray, each element in the SArray is the len of the corresponding
items in original SArray.
Examples
--------
>>> sa = SArray([
... {"is_restaurant": 1, "is_electronics": 0},
... {"is_restaurant": 1, "is_retail": 1, "is_electronics": 0},
... {"is_restaurant": 0, "is_retail": 1, "is_electronics": 0},
... {"is_restaurant": 0},
... {"is_restaurant": 1, "is_electronics": 1},
... None])
>>> sa.item_length()
dtype: int
Rows: 6
[2, 3, 3, 1, 2, None]
"""
if (self.dtype not in [list, dict, array.array]):
raise TypeError("item_length() is only applicable for SArray of type list, dict and array.")
with cython_context():
return SArray(_proxy = self.__proxy__.item_length()) | python | def item_length(self):
"""
Length of each element in the current SArray.
Only works on SArrays of dict, array, or list type. If a given element
is a missing value, then the output elements is also a missing value.
This function is equivalent to the following but more performant:
sa_item_len = sa.apply(lambda x: len(x) if x is not None else None)
Returns
-------
out_sf : SArray
A new SArray, each element in the SArray is the len of the corresponding
items in original SArray.
Examples
--------
>>> sa = SArray([
... {"is_restaurant": 1, "is_electronics": 0},
... {"is_restaurant": 1, "is_retail": 1, "is_electronics": 0},
... {"is_restaurant": 0, "is_retail": 1, "is_electronics": 0},
... {"is_restaurant": 0},
... {"is_restaurant": 1, "is_electronics": 1},
... None])
>>> sa.item_length()
dtype: int
Rows: 6
[2, 3, 3, 1, 2, None]
"""
if (self.dtype not in [list, dict, array.array]):
raise TypeError("item_length() is only applicable for SArray of type list, dict and array.")
with cython_context():
return SArray(_proxy = self.__proxy__.item_length()) | [
"def",
"item_length",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"dtype",
"not",
"in",
"[",
"list",
",",
"dict",
",",
"array",
".",
"array",
"]",
")",
":",
"raise",
"TypeError",
"(",
"\"item_length() is only applicable for SArray of type list, dict and array... | Length of each element in the current SArray.
Only works on SArrays of dict, array, or list type. If a given element
is a missing value, then the output elements is also a missing value.
This function is equivalent to the following but more performant:
sa_item_len = sa.apply(lambda x: len(x) if x is not None else None)
Returns
-------
out_sf : SArray
A new SArray, each element in the SArray is the len of the corresponding
items in original SArray.
Examples
--------
>>> sa = SArray([
... {"is_restaurant": 1, "is_electronics": 0},
... {"is_restaurant": 1, "is_retail": 1, "is_electronics": 0},
... {"is_restaurant": 0, "is_retail": 1, "is_electronics": 0},
... {"is_restaurant": 0},
... {"is_restaurant": 1, "is_electronics": 1},
... None])
>>> sa.item_length()
dtype: int
Rows: 6
[2, 3, 3, 1, 2, None] | [
"Length",
"of",
"each",
"element",
"in",
"the",
"current",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L3008-L3043 |
29,530 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.stack | def stack(self, new_column_name=None, drop_na=False, new_column_type=None):
"""
Convert a "wide" SArray to one or two "tall" columns in an SFrame by
stacking all values.
The stack works only for columns of dict, list, or array type. If the
column is dict type, two new columns are created as a result of
stacking: one column holds the key and another column holds the value.
The rest of the columns are repeated for each key/value pair.
If the column is array or list type, one new column is created as a
result of stacking. With each row holds one element of the array or list
value, and the rest columns from the same original row repeated.
The returned SFrame includes the newly created column(s).
Parameters
--------------
new_column_name : str | list of str, optional
The new column name(s). If original column is list/array type,
new_column_name must a string. If original column is dict type,
new_column_name must be a list of two strings. If not given, column
names are generated automatically.
drop_na : boolean, optional
If True, missing values and empty list/array/dict are all dropped
from the resulting column(s). If False, missing values are
maintained in stacked column(s).
new_column_type : type | list of types, optional
The new column types. If original column is a list/array type
new_column_type must be a single type, or a list of one type. If
original column is of dict type, new_column_type must be a list of
two types. If not provided, the types are automatically inferred
from the first 100 values of the SFrame.
Returns
-------
out : SFrame
A new SFrame that contains the newly stacked column(s).
Examples
---------
Suppose 'sa' is an SArray of dict type:
>>> sa = turicreate.SArray([{'a':3, 'cat':2},
... {'a':1, 'the':2},
... {'the':1, 'dog':3},
... {}])
[{'a': 3, 'cat': 2}, {'a': 1, 'the': 2}, {'the': 1, 'dog': 3}, {}]
Stack would stack all keys in one column and all values in another
column:
>>> sa.stack(new_column_name=['word', 'count'])
+------+-------+
| word | count |
+------+-------+
| a | 3 |
| cat | 2 |
| a | 1 |
| the | 2 |
| the | 1 |
| dog | 3 |
| None | None |
+------+-------+
[7 rows x 2 columns]
Observe that since topic 4 had no words, an empty row is inserted.
To drop that row, set drop_na=True in the parameters to stack.
"""
from .sframe import SFrame as _SFrame
return _SFrame({'SArray': self}).stack('SArray',
new_column_name=new_column_name,
drop_na=drop_na,
new_column_type=new_column_type) | python | def stack(self, new_column_name=None, drop_na=False, new_column_type=None):
"""
Convert a "wide" SArray to one or two "tall" columns in an SFrame by
stacking all values.
The stack works only for columns of dict, list, or array type. If the
column is dict type, two new columns are created as a result of
stacking: one column holds the key and another column holds the value.
The rest of the columns are repeated for each key/value pair.
If the column is array or list type, one new column is created as a
result of stacking. With each row holds one element of the array or list
value, and the rest columns from the same original row repeated.
The returned SFrame includes the newly created column(s).
Parameters
--------------
new_column_name : str | list of str, optional
The new column name(s). If original column is list/array type,
new_column_name must a string. If original column is dict type,
new_column_name must be a list of two strings. If not given, column
names are generated automatically.
drop_na : boolean, optional
If True, missing values and empty list/array/dict are all dropped
from the resulting column(s). If False, missing values are
maintained in stacked column(s).
new_column_type : type | list of types, optional
The new column types. If original column is a list/array type
new_column_type must be a single type, or a list of one type. If
original column is of dict type, new_column_type must be a list of
two types. If not provided, the types are automatically inferred
from the first 100 values of the SFrame.
Returns
-------
out : SFrame
A new SFrame that contains the newly stacked column(s).
Examples
---------
Suppose 'sa' is an SArray of dict type:
>>> sa = turicreate.SArray([{'a':3, 'cat':2},
... {'a':1, 'the':2},
... {'the':1, 'dog':3},
... {}])
[{'a': 3, 'cat': 2}, {'a': 1, 'the': 2}, {'the': 1, 'dog': 3}, {}]
Stack would stack all keys in one column and all values in another
column:
>>> sa.stack(new_column_name=['word', 'count'])
+------+-------+
| word | count |
+------+-------+
| a | 3 |
| cat | 2 |
| a | 1 |
| the | 2 |
| the | 1 |
| dog | 3 |
| None | None |
+------+-------+
[7 rows x 2 columns]
Observe that since topic 4 had no words, an empty row is inserted.
To drop that row, set drop_na=True in the parameters to stack.
"""
from .sframe import SFrame as _SFrame
return _SFrame({'SArray': self}).stack('SArray',
new_column_name=new_column_name,
drop_na=drop_na,
new_column_type=new_column_type) | [
"def",
"stack",
"(",
"self",
",",
"new_column_name",
"=",
"None",
",",
"drop_na",
"=",
"False",
",",
"new_column_type",
"=",
"None",
")",
":",
"from",
".",
"sframe",
"import",
"SFrame",
"as",
"_SFrame",
"return",
"_SFrame",
"(",
"{",
"'SArray'",
":",
"se... | Convert a "wide" SArray to one or two "tall" columns in an SFrame by
stacking all values.
The stack works only for columns of dict, list, or array type. If the
column is dict type, two new columns are created as a result of
stacking: one column holds the key and another column holds the value.
The rest of the columns are repeated for each key/value pair.
If the column is array or list type, one new column is created as a
result of stacking. With each row holds one element of the array or list
value, and the rest columns from the same original row repeated.
The returned SFrame includes the newly created column(s).
Parameters
--------------
new_column_name : str | list of str, optional
The new column name(s). If original column is list/array type,
new_column_name must a string. If original column is dict type,
new_column_name must be a list of two strings. If not given, column
names are generated automatically.
drop_na : boolean, optional
If True, missing values and empty list/array/dict are all dropped
from the resulting column(s). If False, missing values are
maintained in stacked column(s).
new_column_type : type | list of types, optional
The new column types. If original column is a list/array type
new_column_type must be a single type, or a list of one type. If
original column is of dict type, new_column_type must be a list of
two types. If not provided, the types are automatically inferred
from the first 100 values of the SFrame.
Returns
-------
out : SFrame
A new SFrame that contains the newly stacked column(s).
Examples
---------
Suppose 'sa' is an SArray of dict type:
>>> sa = turicreate.SArray([{'a':3, 'cat':2},
... {'a':1, 'the':2},
... {'the':1, 'dog':3},
... {}])
[{'a': 3, 'cat': 2}, {'a': 1, 'the': 2}, {'the': 1, 'dog': 3}, {}]
Stack would stack all keys in one column and all values in another
column:
>>> sa.stack(new_column_name=['word', 'count'])
+------+-------+
| word | count |
+------+-------+
| a | 3 |
| cat | 2 |
| a | 1 |
| the | 2 |
| the | 1 |
| dog | 3 |
| None | None |
+------+-------+
[7 rows x 2 columns]
Observe that since topic 4 had no words, an empty row is inserted.
To drop that row, set drop_na=True in the parameters to stack. | [
"Convert",
"a",
"wide",
"SArray",
"to",
"one",
"or",
"two",
"tall",
"columns",
"in",
"an",
"SFrame",
"by",
"stacking",
"all",
"values",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L3219-L3294 |
29,531 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.sort | def sort(self, ascending=True):
"""
Sort all values in this SArray.
Sort only works for sarray of type str, int and float, otherwise TypeError
will be raised. Creates a new, sorted SArray.
Parameters
----------
ascending: boolean, optional
If true, the sarray values are sorted in ascending order, otherwise,
descending order.
Returns
-------
out: SArray
Examples
--------
>>> sa = SArray([3,2,1])
>>> sa.sort()
dtype: int
Rows: 3
[1, 2, 3]
"""
from .sframe import SFrame as _SFrame
if self.dtype not in (int, float, str, datetime.datetime):
raise TypeError("Only sarray with type (int, float, str, datetime.datetime) can be sorted")
sf = _SFrame()
sf['a'] = self
return sf.sort('a', ascending)['a'] | python | def sort(self, ascending=True):
"""
Sort all values in this SArray.
Sort only works for sarray of type str, int and float, otherwise TypeError
will be raised. Creates a new, sorted SArray.
Parameters
----------
ascending: boolean, optional
If true, the sarray values are sorted in ascending order, otherwise,
descending order.
Returns
-------
out: SArray
Examples
--------
>>> sa = SArray([3,2,1])
>>> sa.sort()
dtype: int
Rows: 3
[1, 2, 3]
"""
from .sframe import SFrame as _SFrame
if self.dtype not in (int, float, str, datetime.datetime):
raise TypeError("Only sarray with type (int, float, str, datetime.datetime) can be sorted")
sf = _SFrame()
sf['a'] = self
return sf.sort('a', ascending)['a'] | [
"def",
"sort",
"(",
"self",
",",
"ascending",
"=",
"True",
")",
":",
"from",
".",
"sframe",
"import",
"SFrame",
"as",
"_SFrame",
"if",
"self",
".",
"dtype",
"not",
"in",
"(",
"int",
",",
"float",
",",
"str",
",",
"datetime",
".",
"datetime",
")",
"... | Sort all values in this SArray.
Sort only works for sarray of type str, int and float, otherwise TypeError
will be raised. Creates a new, sorted SArray.
Parameters
----------
ascending: boolean, optional
If true, the sarray values are sorted in ascending order, otherwise,
descending order.
Returns
-------
out: SArray
Examples
--------
>>> sa = SArray([3,2,1])
>>> sa.sort()
dtype: int
Rows: 3
[1, 2, 3] | [
"Sort",
"all",
"values",
"in",
"this",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L3495-L3526 |
29,532 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.rolling_sum | def rolling_sum(self, window_start, window_end, min_observations=None):
"""
Calculate a new SArray of the sum of different subsets over this
SArray.
Also known as a "moving sum" or "running sum". The subset that
the sum is calculated over is defined as an inclusive range relative
to the position to each value in the SArray, using `window_start` and
`window_end`. For a better understanding of this, see the examples
below.
Parameters
----------
window_start : int
The start of the subset to calculate the sum relative to the
current value.
window_end : int
The end of the subset to calculate the sum relative to the current
value. Must be greater than `window_start`.
min_observations : int
Minimum number of non-missing observations in window required to
calculate the sum (otherwise result is None). None signifies that
the entire window must not include a missing value. A negative
number throws an error.
Returns
-------
out : SArray
Examples
--------
>>> import pandas
>>> sa = SArray([1,2,3,4,5])
>>> series = pandas.Series([1,2,3,4,5])
A rolling sum with a window including the previous 2 entries including
the current:
>>> sa.rolling_sum(-2,0)
dtype: int
Rows: 5
[None, None, 6, 9, 12]
Pandas equivalent:
>>> pandas.rolling_sum(series, 3)
0 NaN
1 NaN
2 6
3 9
4 12
dtype: float64
Same rolling sum operation, but 2 minimum observations:
>>> sa.rolling_sum(-2,0,min_observations=2)
dtype: int
Rows: 5
[None, 3, 6, 9, 12]
Pandas equivalent:
>>> pandas.rolling_sum(series, 3, min_periods=2)
0 NaN
1 3
2 6
3 9
4 12
dtype: float64
A rolling sum with a size of 3, centered around the current:
>>> sa.rolling_sum(-1,1)
dtype: int
Rows: 5
[None, 6, 9, 12, None]
Pandas equivalent:
>>> pandas.rolling_sum(series, 3, center=True)
0 NaN
1 6
2 9
3 12
4 NaN
dtype: float64
A rolling sum with a window including the current and the 2 entries
following:
>>> sa.rolling_sum(0,2)
dtype: int
Rows: 5
[6, 9, 12, None, None]
A rolling sum with a window including the previous 2 entries NOT
including the current:
>>> sa.rolling_sum(-2,-1)
dtype: int
Rows: 5
[None, None, 3, 5, 7]
"""
min_observations = self.__check_min_observations(min_observations)
agg_op = None
if self.dtype is array.array:
agg_op = '__builtin__vector__sum__'
else:
agg_op = '__builtin__sum__'
return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, min_observations)) | python | def rolling_sum(self, window_start, window_end, min_observations=None):
"""
Calculate a new SArray of the sum of different subsets over this
SArray.
Also known as a "moving sum" or "running sum". The subset that
the sum is calculated over is defined as an inclusive range relative
to the position to each value in the SArray, using `window_start` and
`window_end`. For a better understanding of this, see the examples
below.
Parameters
----------
window_start : int
The start of the subset to calculate the sum relative to the
current value.
window_end : int
The end of the subset to calculate the sum relative to the current
value. Must be greater than `window_start`.
min_observations : int
Minimum number of non-missing observations in window required to
calculate the sum (otherwise result is None). None signifies that
the entire window must not include a missing value. A negative
number throws an error.
Returns
-------
out : SArray
Examples
--------
>>> import pandas
>>> sa = SArray([1,2,3,4,5])
>>> series = pandas.Series([1,2,3,4,5])
A rolling sum with a window including the previous 2 entries including
the current:
>>> sa.rolling_sum(-2,0)
dtype: int
Rows: 5
[None, None, 6, 9, 12]
Pandas equivalent:
>>> pandas.rolling_sum(series, 3)
0 NaN
1 NaN
2 6
3 9
4 12
dtype: float64
Same rolling sum operation, but 2 minimum observations:
>>> sa.rolling_sum(-2,0,min_observations=2)
dtype: int
Rows: 5
[None, 3, 6, 9, 12]
Pandas equivalent:
>>> pandas.rolling_sum(series, 3, min_periods=2)
0 NaN
1 3
2 6
3 9
4 12
dtype: float64
A rolling sum with a size of 3, centered around the current:
>>> sa.rolling_sum(-1,1)
dtype: int
Rows: 5
[None, 6, 9, 12, None]
Pandas equivalent:
>>> pandas.rolling_sum(series, 3, center=True)
0 NaN
1 6
2 9
3 12
4 NaN
dtype: float64
A rolling sum with a window including the current and the 2 entries
following:
>>> sa.rolling_sum(0,2)
dtype: int
Rows: 5
[6, 9, 12, None, None]
A rolling sum with a window including the previous 2 entries NOT
including the current:
>>> sa.rolling_sum(-2,-1)
dtype: int
Rows: 5
[None, None, 3, 5, 7]
"""
min_observations = self.__check_min_observations(min_observations)
agg_op = None
if self.dtype is array.array:
agg_op = '__builtin__vector__sum__'
else:
agg_op = '__builtin__sum__'
return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, min_observations)) | [
"def",
"rolling_sum",
"(",
"self",
",",
"window_start",
",",
"window_end",
",",
"min_observations",
"=",
"None",
")",
":",
"min_observations",
"=",
"self",
".",
"__check_min_observations",
"(",
"min_observations",
")",
"agg_op",
"=",
"None",
"if",
"self",
".",
... | Calculate a new SArray of the sum of different subsets over this
SArray.
Also known as a "moving sum" or "running sum". The subset that
the sum is calculated over is defined as an inclusive range relative
to the position to each value in the SArray, using `window_start` and
`window_end`. For a better understanding of this, see the examples
below.
Parameters
----------
window_start : int
The start of the subset to calculate the sum relative to the
current value.
window_end : int
The end of the subset to calculate the sum relative to the current
value. Must be greater than `window_start`.
min_observations : int
Minimum number of non-missing observations in window required to
calculate the sum (otherwise result is None). None signifies that
the entire window must not include a missing value. A negative
number throws an error.
Returns
-------
out : SArray
Examples
--------
>>> import pandas
>>> sa = SArray([1,2,3,4,5])
>>> series = pandas.Series([1,2,3,4,5])
A rolling sum with a window including the previous 2 entries including
the current:
>>> sa.rolling_sum(-2,0)
dtype: int
Rows: 5
[None, None, 6, 9, 12]
Pandas equivalent:
>>> pandas.rolling_sum(series, 3)
0 NaN
1 NaN
2 6
3 9
4 12
dtype: float64
Same rolling sum operation, but 2 minimum observations:
>>> sa.rolling_sum(-2,0,min_observations=2)
dtype: int
Rows: 5
[None, 3, 6, 9, 12]
Pandas equivalent:
>>> pandas.rolling_sum(series, 3, min_periods=2)
0 NaN
1 3
2 6
3 9
4 12
dtype: float64
A rolling sum with a size of 3, centered around the current:
>>> sa.rolling_sum(-1,1)
dtype: int
Rows: 5
[None, 6, 9, 12, None]
Pandas equivalent:
>>> pandas.rolling_sum(series, 3, center=True)
0 NaN
1 6
2 9
3 12
4 NaN
dtype: float64
A rolling sum with a window including the current and the 2 entries
following:
>>> sa.rolling_sum(0,2)
dtype: int
Rows: 5
[6, 9, 12, None, None]
A rolling sum with a window including the previous 2 entries NOT
including the current:
>>> sa.rolling_sum(-2,-1)
dtype: int
Rows: 5
[None, None, 3, 5, 7] | [
"Calculate",
"a",
"new",
"SArray",
"of",
"the",
"sum",
"of",
"different",
"subsets",
"over",
"this",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L3640-L3743 |
29,533 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.rolling_max | def rolling_max(self, window_start, window_end, min_observations=None):
"""
Calculate a new SArray of the maximum value of different subsets over
this SArray.
The subset that the maximum is calculated over is defined as an
inclusive range relative to the position to each value in the SArray,
using `window_start` and `window_end`. For a better understanding of
this, see the examples below.
Parameters
----------
window_start : int
The start of the subset to calculate the maximum relative to the
current value.
window_end : int
The end of the subset to calculate the maximum relative to the current
value. Must be greater than `window_start`.
min_observations : int
Minimum number of non-missing observations in window required to
calculate the maximum (otherwise result is None). None signifies that
the entire window must not include a missing value. A negative
number throws an error.
Returns
-------
out : SArray
Examples
--------
>>> import pandas
>>> sa = SArray([1,2,3,4,5])
>>> series = pandas.Series([1,2,3,4,5])
A rolling max with a window including the previous 2 entries including
the current:
>>> sa.rolling_max(-2,0)
dtype: int
Rows: 5
[None, None, 3, 4, 5]
Pandas equivalent:
>>> pandas.rolling_max(series, 3)
0 NaN
1 NaN
2 3
3 4
4 5
dtype: float64
Same rolling max operation, but 2 minimum observations:
>>> sa.rolling_max(-2,0,min_observations=2)
dtype: int
Rows: 5
[None, 2, 3, 4, 5]
Pandas equivalent:
>>> pandas.rolling_max(series, 3, min_periods=2)
0 NaN
1 2
2 3
3 4
4 5
dtype: float64
A rolling max with a size of 3, centered around the current:
>>> sa.rolling_max(-1,1)
dtype: int
Rows: 5
[None, 3, 4, 5, None]
Pandas equivalent:
>>> pandas.rolling_max(series, 3, center=True)
0 NaN
1 3
2 4
3 5
4 NaN
dtype: float64
A rolling max with a window including the current and the 2 entries
following:
>>> sa.rolling_max(0,2)
dtype: int
Rows: 5
[3, 4, 5, None, None]
A rolling max with a window including the previous 2 entries NOT
including the current:
>>> sa.rolling_max(-2,-1)
dtype: int
Rows: 5
[None, None, 2, 3, 4]
"""
min_observations = self.__check_min_observations(min_observations)
agg_op = '__builtin__max__'
return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, min_observations)) | python | def rolling_max(self, window_start, window_end, min_observations=None):
"""
Calculate a new SArray of the maximum value of different subsets over
this SArray.
The subset that the maximum is calculated over is defined as an
inclusive range relative to the position to each value in the SArray,
using `window_start` and `window_end`. For a better understanding of
this, see the examples below.
Parameters
----------
window_start : int
The start of the subset to calculate the maximum relative to the
current value.
window_end : int
The end of the subset to calculate the maximum relative to the current
value. Must be greater than `window_start`.
min_observations : int
Minimum number of non-missing observations in window required to
calculate the maximum (otherwise result is None). None signifies that
the entire window must not include a missing value. A negative
number throws an error.
Returns
-------
out : SArray
Examples
--------
>>> import pandas
>>> sa = SArray([1,2,3,4,5])
>>> series = pandas.Series([1,2,3,4,5])
A rolling max with a window including the previous 2 entries including
the current:
>>> sa.rolling_max(-2,0)
dtype: int
Rows: 5
[None, None, 3, 4, 5]
Pandas equivalent:
>>> pandas.rolling_max(series, 3)
0 NaN
1 NaN
2 3
3 4
4 5
dtype: float64
Same rolling max operation, but 2 minimum observations:
>>> sa.rolling_max(-2,0,min_observations=2)
dtype: int
Rows: 5
[None, 2, 3, 4, 5]
Pandas equivalent:
>>> pandas.rolling_max(series, 3, min_periods=2)
0 NaN
1 2
2 3
3 4
4 5
dtype: float64
A rolling max with a size of 3, centered around the current:
>>> sa.rolling_max(-1,1)
dtype: int
Rows: 5
[None, 3, 4, 5, None]
Pandas equivalent:
>>> pandas.rolling_max(series, 3, center=True)
0 NaN
1 3
2 4
3 5
4 NaN
dtype: float64
A rolling max with a window including the current and the 2 entries
following:
>>> sa.rolling_max(0,2)
dtype: int
Rows: 5
[3, 4, 5, None, None]
A rolling max with a window including the previous 2 entries NOT
including the current:
>>> sa.rolling_max(-2,-1)
dtype: int
Rows: 5
[None, None, 2, 3, 4]
"""
min_observations = self.__check_min_observations(min_observations)
agg_op = '__builtin__max__'
return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, min_observations)) | [
"def",
"rolling_max",
"(",
"self",
",",
"window_start",
",",
"window_end",
",",
"min_observations",
"=",
"None",
")",
":",
"min_observations",
"=",
"self",
".",
"__check_min_observations",
"(",
"min_observations",
")",
"agg_op",
"=",
"'__builtin__max__'",
"return",
... | Calculate a new SArray of the maximum value of different subsets over
this SArray.
The subset that the maximum is calculated over is defined as an
inclusive range relative to the position to each value in the SArray,
using `window_start` and `window_end`. For a better understanding of
this, see the examples below.
Parameters
----------
window_start : int
The start of the subset to calculate the maximum relative to the
current value.
window_end : int
The end of the subset to calculate the maximum relative to the current
value. Must be greater than `window_start`.
min_observations : int
Minimum number of non-missing observations in window required to
calculate the maximum (otherwise result is None). None signifies that
the entire window must not include a missing value. A negative
number throws an error.
Returns
-------
out : SArray
Examples
--------
>>> import pandas
>>> sa = SArray([1,2,3,4,5])
>>> series = pandas.Series([1,2,3,4,5])
A rolling max with a window including the previous 2 entries including
the current:
>>> sa.rolling_max(-2,0)
dtype: int
Rows: 5
[None, None, 3, 4, 5]
Pandas equivalent:
>>> pandas.rolling_max(series, 3)
0 NaN
1 NaN
2 3
3 4
4 5
dtype: float64
Same rolling max operation, but 2 minimum observations:
>>> sa.rolling_max(-2,0,min_observations=2)
dtype: int
Rows: 5
[None, 2, 3, 4, 5]
Pandas equivalent:
>>> pandas.rolling_max(series, 3, min_periods=2)
0 NaN
1 2
2 3
3 4
4 5
dtype: float64
A rolling max with a size of 3, centered around the current:
>>> sa.rolling_max(-1,1)
dtype: int
Rows: 5
[None, 3, 4, 5, None]
Pandas equivalent:
>>> pandas.rolling_max(series, 3, center=True)
0 NaN
1 3
2 4
3 5
4 NaN
dtype: float64
A rolling max with a window including the current and the 2 entries
following:
>>> sa.rolling_max(0,2)
dtype: int
Rows: 5
[3, 4, 5, None, None]
A rolling max with a window including the previous 2 entries NOT
including the current:
>>> sa.rolling_max(-2,-1)
dtype: int
Rows: 5
[None, None, 2, 3, 4] | [
"Calculate",
"a",
"new",
"SArray",
"of",
"the",
"maximum",
"value",
"of",
"different",
"subsets",
"over",
"this",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L3745-L3843 |
29,534 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.rolling_count | def rolling_count(self, window_start, window_end):
"""
Count the number of non-NULL values of different subsets over this
SArray.
The subset that the count is executed on is defined as an inclusive
range relative to the position to each value in the SArray, using
`window_start` and `window_end`. For a better understanding of this,
see the examples below.
Parameters
----------
window_start : int
The start of the subset to count relative to the current value.
window_end : int
The end of the subset to count relative to the current value. Must
be greater than `window_start`.
Returns
-------
out : SArray
Examples
--------
>>> import pandas
>>> sa = SArray([1,2,3,None,5])
>>> series = pandas.Series([1,2,3,None,5])
A rolling count with a window including the previous 2 entries including
the current:
>>> sa.rolling_count(-2,0)
dtype: int
Rows: 5
[1, 2, 3, 2, 2]
Pandas equivalent:
>>> pandas.rolling_count(series, 3)
0 1
1 2
2 3
3 2
4 2
dtype: float64
A rolling count with a size of 3, centered around the current:
>>> sa.rolling_count(-1,1)
dtype: int
Rows: 5
[2, 3, 2, 2, 1]
Pandas equivalent:
>>> pandas.rolling_count(series, 3, center=True)
0 2
1 3
2 2
3 2
4 1
dtype: float64
A rolling count with a window including the current and the 2 entries
following:
>>> sa.rolling_count(0,2)
dtype: int
Rows: 5
[3, 2, 2, 1, 1]
A rolling count with a window including the previous 2 entries NOT
including the current:
>>> sa.rolling_count(-2,-1)
dtype: int
Rows: 5
[0, 1, 2, 2, 1]
"""
agg_op = '__builtin__nonnull__count__'
return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, 0)) | python | def rolling_count(self, window_start, window_end):
"""
Count the number of non-NULL values of different subsets over this
SArray.
The subset that the count is executed on is defined as an inclusive
range relative to the position to each value in the SArray, using
`window_start` and `window_end`. For a better understanding of this,
see the examples below.
Parameters
----------
window_start : int
The start of the subset to count relative to the current value.
window_end : int
The end of the subset to count relative to the current value. Must
be greater than `window_start`.
Returns
-------
out : SArray
Examples
--------
>>> import pandas
>>> sa = SArray([1,2,3,None,5])
>>> series = pandas.Series([1,2,3,None,5])
A rolling count with a window including the previous 2 entries including
the current:
>>> sa.rolling_count(-2,0)
dtype: int
Rows: 5
[1, 2, 3, 2, 2]
Pandas equivalent:
>>> pandas.rolling_count(series, 3)
0 1
1 2
2 3
3 2
4 2
dtype: float64
A rolling count with a size of 3, centered around the current:
>>> sa.rolling_count(-1,1)
dtype: int
Rows: 5
[2, 3, 2, 2, 1]
Pandas equivalent:
>>> pandas.rolling_count(series, 3, center=True)
0 2
1 3
2 2
3 2
4 1
dtype: float64
A rolling count with a window including the current and the 2 entries
following:
>>> sa.rolling_count(0,2)
dtype: int
Rows: 5
[3, 2, 2, 1, 1]
A rolling count with a window including the previous 2 entries NOT
including the current:
>>> sa.rolling_count(-2,-1)
dtype: int
Rows: 5
[0, 1, 2, 2, 1]
"""
agg_op = '__builtin__nonnull__count__'
return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, 0)) | [
"def",
"rolling_count",
"(",
"self",
",",
"window_start",
",",
"window_end",
")",
":",
"agg_op",
"=",
"'__builtin__nonnull__count__'",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
"__proxy__",
".",
"builtin_rolling_apply",
"(",
"agg_op",
",",
"window_start... | Count the number of non-NULL values of different subsets over this
SArray.
The subset that the count is executed on is defined as an inclusive
range relative to the position to each value in the SArray, using
`window_start` and `window_end`. For a better understanding of this,
see the examples below.
Parameters
----------
window_start : int
The start of the subset to count relative to the current value.
window_end : int
The end of the subset to count relative to the current value. Must
be greater than `window_start`.
Returns
-------
out : SArray
Examples
--------
>>> import pandas
>>> sa = SArray([1,2,3,None,5])
>>> series = pandas.Series([1,2,3,None,5])
A rolling count with a window including the previous 2 entries including
the current:
>>> sa.rolling_count(-2,0)
dtype: int
Rows: 5
[1, 2, 3, 2, 2]
Pandas equivalent:
>>> pandas.rolling_count(series, 3)
0 1
1 2
2 3
3 2
4 2
dtype: float64
A rolling count with a size of 3, centered around the current:
>>> sa.rolling_count(-1,1)
dtype: int
Rows: 5
[2, 3, 2, 2, 1]
Pandas equivalent:
>>> pandas.rolling_count(series, 3, center=True)
0 2
1 3
2 2
3 2
4 1
dtype: float64
A rolling count with a window including the current and the 2 entries
following:
>>> sa.rolling_count(0,2)
dtype: int
Rows: 5
[3, 2, 2, 1, 1]
A rolling count with a window including the previous 2 entries NOT
including the current:
>>> sa.rolling_count(-2,-1)
dtype: int
Rows: 5
[0, 1, 2, 2, 1] | [
"Count",
"the",
"number",
"of",
"non",
"-",
"NULL",
"values",
"of",
"different",
"subsets",
"over",
"this",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L4146-L4221 |
29,535 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.cumulative_sum | def cumulative_sum(self):
"""
Return the cumulative sum of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
sum of all the elements preceding and including it. The SArray is
expected to be of numeric type (int, float), or a numeric vector type.
Returns
-------
out : sarray[int, float, array.array]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
- For SArray's of type array.array, all entries are expected to
be of the same size.
Examples
--------
>>> sa = SArray([1, 2, 3, 4, 5])
>>> sa.cumulative_sum()
dtype: int
rows: 3
[1, 3, 6, 10, 15]
"""
from .. import extensions
agg_op = "__builtin__cum_sum__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | python | def cumulative_sum(self):
"""
Return the cumulative sum of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
sum of all the elements preceding and including it. The SArray is
expected to be of numeric type (int, float), or a numeric vector type.
Returns
-------
out : sarray[int, float, array.array]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
- For SArray's of type array.array, all entries are expected to
be of the same size.
Examples
--------
>>> sa = SArray([1, 2, 3, 4, 5])
>>> sa.cumulative_sum()
dtype: int
rows: 3
[1, 3, 6, 10, 15]
"""
from .. import extensions
agg_op = "__builtin__cum_sum__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | [
"def",
"cumulative_sum",
"(",
"self",
")",
":",
"from",
".",
".",
"import",
"extensions",
"agg_op",
"=",
"\"__builtin__cum_sum__\"",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
"__proxy__",
".",
"builtin_cumulative_aggregate",
"(",
"agg_op",
")",
")"
] | Return the cumulative sum of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
sum of all the elements preceding and including it. The SArray is
expected to be of numeric type (int, float), or a numeric vector type.
Returns
-------
out : sarray[int, float, array.array]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
- For SArray's of type array.array, all entries are expected to
be of the same size.
Examples
--------
>>> sa = SArray([1, 2, 3, 4, 5])
>>> sa.cumulative_sum()
dtype: int
rows: 3
[1, 3, 6, 10, 15] | [
"Return",
"the",
"cumulative",
"sum",
"of",
"the",
"elements",
"in",
"the",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L4223-L4252 |
29,536 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.cumulative_mean | def cumulative_mean(self):
"""
Return the cumulative mean of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
mean value of all the elements preceding and including it. The SArray
is expected to be of numeric type (int, float), or a numeric vector
type.
Returns
-------
out : Sarray[float, array.array]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
- For SArray's of type array.array, all entries are expected to
be of the same size.
Examples
--------
>>> sa = SArray([1, 2, 3, 4, 5])
>>> sa.cumulative_mean()
dtype: float
rows: 3
[1, 1.5, 2, 2.5, 3]
"""
from .. import extensions
agg_op = "__builtin__cum_avg__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | python | def cumulative_mean(self):
"""
Return the cumulative mean of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
mean value of all the elements preceding and including it. The SArray
is expected to be of numeric type (int, float), or a numeric vector
type.
Returns
-------
out : Sarray[float, array.array]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
- For SArray's of type array.array, all entries are expected to
be of the same size.
Examples
--------
>>> sa = SArray([1, 2, 3, 4, 5])
>>> sa.cumulative_mean()
dtype: float
rows: 3
[1, 1.5, 2, 2.5, 3]
"""
from .. import extensions
agg_op = "__builtin__cum_avg__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | [
"def",
"cumulative_mean",
"(",
"self",
")",
":",
"from",
".",
".",
"import",
"extensions",
"agg_op",
"=",
"\"__builtin__cum_avg__\"",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
"__proxy__",
".",
"builtin_cumulative_aggregate",
"(",
"agg_op",
")",
")"
] | Return the cumulative mean of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
mean value of all the elements preceding and including it. The SArray
is expected to be of numeric type (int, float), or a numeric vector
type.
Returns
-------
out : Sarray[float, array.array]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
- For SArray's of type array.array, all entries are expected to
be of the same size.
Examples
--------
>>> sa = SArray([1, 2, 3, 4, 5])
>>> sa.cumulative_mean()
dtype: float
rows: 3
[1, 1.5, 2, 2.5, 3] | [
"Return",
"the",
"cumulative",
"mean",
"of",
"the",
"elements",
"in",
"the",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L4254-L4284 |
29,537 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.cumulative_min | def cumulative_min(self):
"""
Return the cumulative minimum value of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
minimum value of all the elements preceding and including it. The
SArray is expected to be of numeric type (int, float).
Returns
-------
out : SArray[int, float]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
Examples
--------
>>> sa = SArray([1, 2, 3, 4, 0])
>>> sa.cumulative_min()
dtype: int
rows: 3
[1, 1, 1, 1, 0]
"""
from .. import extensions
agg_op = "__builtin__cum_min__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | python | def cumulative_min(self):
"""
Return the cumulative minimum value of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
minimum value of all the elements preceding and including it. The
SArray is expected to be of numeric type (int, float).
Returns
-------
out : SArray[int, float]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
Examples
--------
>>> sa = SArray([1, 2, 3, 4, 0])
>>> sa.cumulative_min()
dtype: int
rows: 3
[1, 1, 1, 1, 0]
"""
from .. import extensions
agg_op = "__builtin__cum_min__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | [
"def",
"cumulative_min",
"(",
"self",
")",
":",
"from",
".",
".",
"import",
"extensions",
"agg_op",
"=",
"\"__builtin__cum_min__\"",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
"__proxy__",
".",
"builtin_cumulative_aggregate",
"(",
"agg_op",
")",
")"
] | Return the cumulative minimum value of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
minimum value of all the elements preceding and including it. The
SArray is expected to be of numeric type (int, float).
Returns
-------
out : SArray[int, float]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
Examples
--------
>>> sa = SArray([1, 2, 3, 4, 0])
>>> sa.cumulative_min()
dtype: int
rows: 3
[1, 1, 1, 1, 0] | [
"Return",
"the",
"cumulative",
"minimum",
"value",
"of",
"the",
"elements",
"in",
"the",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L4286-L4313 |
29,538 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.cumulative_max | def cumulative_max(self):
"""
Return the cumulative maximum value of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
maximum value of all the elements preceding and including it. The
SArray is expected to be of numeric type (int, float).
Returns
-------
out : SArray[int, float]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
Examples
--------
>>> sa = SArray([1, 0, 3, 4, 2])
>>> sa.cumulative_max()
dtype: int
rows: 3
[1, 1, 3, 4, 4]
"""
from .. import extensions
agg_op = "__builtin__cum_max__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | python | def cumulative_max(self):
"""
Return the cumulative maximum value of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
maximum value of all the elements preceding and including it. The
SArray is expected to be of numeric type (int, float).
Returns
-------
out : SArray[int, float]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
Examples
--------
>>> sa = SArray([1, 0, 3, 4, 2])
>>> sa.cumulative_max()
dtype: int
rows: 3
[1, 1, 3, 4, 4]
"""
from .. import extensions
agg_op = "__builtin__cum_max__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | [
"def",
"cumulative_max",
"(",
"self",
")",
":",
"from",
".",
".",
"import",
"extensions",
"agg_op",
"=",
"\"__builtin__cum_max__\"",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
"__proxy__",
".",
"builtin_cumulative_aggregate",
"(",
"agg_op",
")",
")"
] | Return the cumulative maximum value of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
maximum value of all the elements preceding and including it. The
SArray is expected to be of numeric type (int, float).
Returns
-------
out : SArray[int, float]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
Examples
--------
>>> sa = SArray([1, 0, 3, 4, 2])
>>> sa.cumulative_max()
dtype: int
rows: 3
[1, 1, 3, 4, 4] | [
"Return",
"the",
"cumulative",
"maximum",
"value",
"of",
"the",
"elements",
"in",
"the",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L4315-L4342 |
29,539 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.cumulative_std | def cumulative_std(self):
"""
Return the cumulative standard deviation of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
standard deviation of all the elements preceding and including it. The
SArray is expected to be of numeric type, or a numeric vector type.
Returns
-------
out : SArray[int, float]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
Examples
--------
>>> sa = SArray([1, 2, 3, 4, 0])
>>> sa.cumulative_std()
dtype: float
rows: 3
[0.0, 0.5, 0.816496580927726, 1.118033988749895, 1.4142135623730951]
"""
from .. import extensions
agg_op = "__builtin__cum_std__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | python | def cumulative_std(self):
"""
Return the cumulative standard deviation of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
standard deviation of all the elements preceding and including it. The
SArray is expected to be of numeric type, or a numeric vector type.
Returns
-------
out : SArray[int, float]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
Examples
--------
>>> sa = SArray([1, 2, 3, 4, 0])
>>> sa.cumulative_std()
dtype: float
rows: 3
[0.0, 0.5, 0.816496580927726, 1.118033988749895, 1.4142135623730951]
"""
from .. import extensions
agg_op = "__builtin__cum_std__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | [
"def",
"cumulative_std",
"(",
"self",
")",
":",
"from",
".",
".",
"import",
"extensions",
"agg_op",
"=",
"\"__builtin__cum_std__\"",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
"__proxy__",
".",
"builtin_cumulative_aggregate",
"(",
"agg_op",
")",
")"
] | Return the cumulative standard deviation of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
standard deviation of all the elements preceding and including it. The
SArray is expected to be of numeric type, or a numeric vector type.
Returns
-------
out : SArray[int, float]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
Examples
--------
>>> sa = SArray([1, 2, 3, 4, 0])
>>> sa.cumulative_std()
dtype: float
rows: 3
[0.0, 0.5, 0.816496580927726, 1.118033988749895, 1.4142135623730951] | [
"Return",
"the",
"cumulative",
"standard",
"deviation",
"of",
"the",
"elements",
"in",
"the",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L4344-L4371 |
29,540 | apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | SArray.cumulative_var | def cumulative_var(self):
"""
Return the cumulative variance of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
variance of all the elements preceding and including it. The SArray is
expected to be of numeric type, or a numeric vector type.
Returns
-------
out : SArray[int, float]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
Examples
--------
>>> sa = SArray([1, 2, 3, 4, 0])
>>> sa.cumulative_var()
dtype: float
rows: 3
[0.0, 0.25, 0.6666666666666666, 1.25, 2.0]
"""
from .. import extensions
agg_op = "__builtin__cum_var__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | python | def cumulative_var(self):
"""
Return the cumulative variance of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
variance of all the elements preceding and including it. The SArray is
expected to be of numeric type, or a numeric vector type.
Returns
-------
out : SArray[int, float]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
Examples
--------
>>> sa = SArray([1, 2, 3, 4, 0])
>>> sa.cumulative_var()
dtype: float
rows: 3
[0.0, 0.25, 0.6666666666666666, 1.25, 2.0]
"""
from .. import extensions
agg_op = "__builtin__cum_var__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | [
"def",
"cumulative_var",
"(",
"self",
")",
":",
"from",
".",
".",
"import",
"extensions",
"agg_op",
"=",
"\"__builtin__cum_var__\"",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
"__proxy__",
".",
"builtin_cumulative_aggregate",
"(",
"agg_op",
")",
")"
] | Return the cumulative variance of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
variance of all the elements preceding and including it. The SArray is
expected to be of numeric type, or a numeric vector type.
Returns
-------
out : SArray[int, float]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
Examples
--------
>>> sa = SArray([1, 2, 3, 4, 0])
>>> sa.cumulative_var()
dtype: float
rows: 3
[0.0, 0.25, 0.6666666666666666, 1.25, 2.0] | [
"Return",
"the",
"cumulative",
"variance",
"of",
"the",
"elements",
"in",
"the",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L4373-L4400 |
29,541 | apple/turicreate | src/external/xgboost/subtree/rabit/doc/conf.py | generate_doxygen_xml | def generate_doxygen_xml(app):
"""Run the doxygen make commands if we're on the ReadTheDocs server"""
read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True'
if read_the_docs_build:
run_doxygen('..')
sys.stderr.write('Check if shared lib exists\n')
run_build_lib('..')
sys.stderr.write('The wrapper path: %s\n' % str(os.listdir('../wrapper')))
rabit._loadlib() | python | def generate_doxygen_xml(app):
"""Run the doxygen make commands if we're on the ReadTheDocs server"""
read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True'
if read_the_docs_build:
run_doxygen('..')
sys.stderr.write('Check if shared lib exists\n')
run_build_lib('..')
sys.stderr.write('The wrapper path: %s\n' % str(os.listdir('../wrapper')))
rabit._loadlib() | [
"def",
"generate_doxygen_xml",
"(",
"app",
")",
":",
"read_the_docs_build",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'READTHEDOCS'",
",",
"None",
")",
"==",
"'True'",
"if",
"read_the_docs_build",
":",
"run_doxygen",
"(",
"'..'",
")",
"sys",
".",
"stderr"... | Run the doxygen make commands if we're on the ReadTheDocs server | [
"Run",
"the",
"doxygen",
"make",
"commands",
"if",
"we",
"re",
"on",
"the",
"ReadTheDocs",
"server"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/subtree/rabit/doc/conf.py#L167-L175 |
29,542 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py | MessageToJson | def MessageToJson(message,
including_default_value_fields=False,
preserving_proto_field_name=False):
"""Converts protobuf message to JSON format.
Args:
message: The protocol buffers message instance to serialize.
including_default_value_fields: If True, singular primitive fields,
repeated fields, and map fields will always be serialized. If
False, only serialize non-empty fields. Singular message fields
and oneof fields are not affected by this option.
preserving_proto_field_name: If True, use the original proto field
names as defined in the .proto file. If False, convert the field
names to lowerCamelCase.
Returns:
A string containing the JSON formatted protocol buffer message.
"""
printer = _Printer(including_default_value_fields,
preserving_proto_field_name)
return printer.ToJsonString(message) | python | def MessageToJson(message,
including_default_value_fields=False,
preserving_proto_field_name=False):
"""Converts protobuf message to JSON format.
Args:
message: The protocol buffers message instance to serialize.
including_default_value_fields: If True, singular primitive fields,
repeated fields, and map fields will always be serialized. If
False, only serialize non-empty fields. Singular message fields
and oneof fields are not affected by this option.
preserving_proto_field_name: If True, use the original proto field
names as defined in the .proto file. If False, convert the field
names to lowerCamelCase.
Returns:
A string containing the JSON formatted protocol buffer message.
"""
printer = _Printer(including_default_value_fields,
preserving_proto_field_name)
return printer.ToJsonString(message) | [
"def",
"MessageToJson",
"(",
"message",
",",
"including_default_value_fields",
"=",
"False",
",",
"preserving_proto_field_name",
"=",
"False",
")",
":",
"printer",
"=",
"_Printer",
"(",
"including_default_value_fields",
",",
"preserving_proto_field_name",
")",
"return",
... | Converts protobuf message to JSON format.
Args:
message: The protocol buffers message instance to serialize.
including_default_value_fields: If True, singular primitive fields,
repeated fields, and map fields will always be serialized. If
False, only serialize non-empty fields. Singular message fields
and oneof fields are not affected by this option.
preserving_proto_field_name: If True, use the original proto field
names as defined in the .proto file. If False, convert the field
names to lowerCamelCase.
Returns:
A string containing the JSON formatted protocol buffer message. | [
"Converts",
"protobuf",
"message",
"to",
"JSON",
"format",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L89-L109 |
29,543 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py | MessageToDict | def MessageToDict(message,
including_default_value_fields=False,
preserving_proto_field_name=False):
"""Converts protobuf message to a JSON dictionary.
Args:
message: The protocol buffers message instance to serialize.
including_default_value_fields: If True, singular primitive fields,
repeated fields, and map fields will always be serialized. If
False, only serialize non-empty fields. Singular message fields
and oneof fields are not affected by this option.
preserving_proto_field_name: If True, use the original proto field
names as defined in the .proto file. If False, convert the field
names to lowerCamelCase.
Returns:
A dict representation of the JSON formatted protocol buffer message.
"""
printer = _Printer(including_default_value_fields,
preserving_proto_field_name)
# pylint: disable=protected-access
return printer._MessageToJsonObject(message) | python | def MessageToDict(message,
including_default_value_fields=False,
preserving_proto_field_name=False):
"""Converts protobuf message to a JSON dictionary.
Args:
message: The protocol buffers message instance to serialize.
including_default_value_fields: If True, singular primitive fields,
repeated fields, and map fields will always be serialized. If
False, only serialize non-empty fields. Singular message fields
and oneof fields are not affected by this option.
preserving_proto_field_name: If True, use the original proto field
names as defined in the .proto file. If False, convert the field
names to lowerCamelCase.
Returns:
A dict representation of the JSON formatted protocol buffer message.
"""
printer = _Printer(including_default_value_fields,
preserving_proto_field_name)
# pylint: disable=protected-access
return printer._MessageToJsonObject(message) | [
"def",
"MessageToDict",
"(",
"message",
",",
"including_default_value_fields",
"=",
"False",
",",
"preserving_proto_field_name",
"=",
"False",
")",
":",
"printer",
"=",
"_Printer",
"(",
"including_default_value_fields",
",",
"preserving_proto_field_name",
")",
"# pylint: ... | Converts protobuf message to a JSON dictionary.
Args:
message: The protocol buffers message instance to serialize.
including_default_value_fields: If True, singular primitive fields,
repeated fields, and map fields will always be serialized. If
False, only serialize non-empty fields. Singular message fields
and oneof fields are not affected by this option.
preserving_proto_field_name: If True, use the original proto field
names as defined in the .proto file. If False, convert the field
names to lowerCamelCase.
Returns:
A dict representation of the JSON formatted protocol buffer message. | [
"Converts",
"protobuf",
"message",
"to",
"a",
"JSON",
"dictionary",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L112-L133 |
29,544 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py | ParseDict | def ParseDict(js_dict, message, ignore_unknown_fields=False):
"""Parses a JSON dictionary representation into a message.
Args:
js_dict: Dict representation of a JSON message.
message: A protocol buffer message to merge into.
ignore_unknown_fields: If True, do not raise errors for unknown fields.
Returns:
The same message passed as argument.
"""
parser = _Parser(ignore_unknown_fields)
parser.ConvertMessage(js_dict, message)
return message | python | def ParseDict(js_dict, message, ignore_unknown_fields=False):
"""Parses a JSON dictionary representation into a message.
Args:
js_dict: Dict representation of a JSON message.
message: A protocol buffer message to merge into.
ignore_unknown_fields: If True, do not raise errors for unknown fields.
Returns:
The same message passed as argument.
"""
parser = _Parser(ignore_unknown_fields)
parser.ConvertMessage(js_dict, message)
return message | [
"def",
"ParseDict",
"(",
"js_dict",
",",
"message",
",",
"ignore_unknown_fields",
"=",
"False",
")",
":",
"parser",
"=",
"_Parser",
"(",
"ignore_unknown_fields",
")",
"parser",
".",
"ConvertMessage",
"(",
"js_dict",
",",
"message",
")",
"return",
"message"
] | Parses a JSON dictionary representation into a message.
Args:
js_dict: Dict representation of a JSON message.
message: A protocol buffer message to merge into.
ignore_unknown_fields: If True, do not raise errors for unknown fields.
Returns:
The same message passed as argument. | [
"Parses",
"a",
"JSON",
"dictionary",
"representation",
"into",
"a",
"message",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L372-L385 |
29,545 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py | _ConvertScalarFieldValue | def _ConvertScalarFieldValue(value, field, require_str=False):
"""Convert a single scalar field value.
Args:
value: A scalar value to convert the scalar field value.
field: The descriptor of the field to convert.
require_str: If True, the field value must be a str.
Returns:
The converted scalar field value
Raises:
ParseError: In case of convert problems.
"""
if field.cpp_type in _INT_TYPES:
return _ConvertInteger(value)
elif field.cpp_type in _FLOAT_TYPES:
return _ConvertFloat(value)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
return _ConvertBool(value, require_str)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
return base64.b64decode(value)
else:
# Checking for unpaired surrogates appears to be unreliable,
# depending on the specific Python version, so we check manually.
if _UNPAIRED_SURROGATE_PATTERN.search(value):
raise ParseError('Unpaired surrogate')
return value
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
# Convert an enum value.
enum_value = field.enum_type.values_by_name.get(value, None)
if enum_value is None:
try:
number = int(value)
enum_value = field.enum_type.values_by_number.get(number, None)
except ValueError:
raise ParseError('Invalid enum value {0} for enum type {1}.'.format(
value, field.enum_type.full_name))
if enum_value is None:
raise ParseError('Invalid enum value {0} for enum type {1}.'.format(
value, field.enum_type.full_name))
return enum_value.number | python | def _ConvertScalarFieldValue(value, field, require_str=False):
"""Convert a single scalar field value.
Args:
value: A scalar value to convert the scalar field value.
field: The descriptor of the field to convert.
require_str: If True, the field value must be a str.
Returns:
The converted scalar field value
Raises:
ParseError: In case of convert problems.
"""
if field.cpp_type in _INT_TYPES:
return _ConvertInteger(value)
elif field.cpp_type in _FLOAT_TYPES:
return _ConvertFloat(value)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
return _ConvertBool(value, require_str)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
return base64.b64decode(value)
else:
# Checking for unpaired surrogates appears to be unreliable,
# depending on the specific Python version, so we check manually.
if _UNPAIRED_SURROGATE_PATTERN.search(value):
raise ParseError('Unpaired surrogate')
return value
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
# Convert an enum value.
enum_value = field.enum_type.values_by_name.get(value, None)
if enum_value is None:
try:
number = int(value)
enum_value = field.enum_type.values_by_number.get(number, None)
except ValueError:
raise ParseError('Invalid enum value {0} for enum type {1}.'.format(
value, field.enum_type.full_name))
if enum_value is None:
raise ParseError('Invalid enum value {0} for enum type {1}.'.format(
value, field.enum_type.full_name))
return enum_value.number | [
"def",
"_ConvertScalarFieldValue",
"(",
"value",
",",
"field",
",",
"require_str",
"=",
"False",
")",
":",
"if",
"field",
".",
"cpp_type",
"in",
"_INT_TYPES",
":",
"return",
"_ConvertInteger",
"(",
"value",
")",
"elif",
"field",
".",
"cpp_type",
"in",
"_FLOA... | Convert a single scalar field value.
Args:
value: A scalar value to convert the scalar field value.
field: The descriptor of the field to convert.
require_str: If True, the field value must be a str.
Returns:
The converted scalar field value
Raises:
ParseError: In case of convert problems. | [
"Convert",
"a",
"single",
"scalar",
"field",
"value",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L606-L648 |
29,546 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py | _ConvertInteger | def _ConvertInteger(value):
"""Convert an integer.
Args:
value: A scalar value to convert.
Returns:
The integer value.
Raises:
ParseError: If an integer couldn't be consumed.
"""
if isinstance(value, float) and not value.is_integer():
raise ParseError('Couldn\'t parse integer: {0}.'.format(value))
if isinstance(value, six.text_type) and value.find(' ') != -1:
raise ParseError('Couldn\'t parse integer: "{0}".'.format(value))
return int(value) | python | def _ConvertInteger(value):
"""Convert an integer.
Args:
value: A scalar value to convert.
Returns:
The integer value.
Raises:
ParseError: If an integer couldn't be consumed.
"""
if isinstance(value, float) and not value.is_integer():
raise ParseError('Couldn\'t parse integer: {0}.'.format(value))
if isinstance(value, six.text_type) and value.find(' ') != -1:
raise ParseError('Couldn\'t parse integer: "{0}".'.format(value))
return int(value) | [
"def",
"_ConvertInteger",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"float",
")",
"and",
"not",
"value",
".",
"is_integer",
"(",
")",
":",
"raise",
"ParseError",
"(",
"'Couldn\\'t parse integer: {0}.'",
".",
"format",
"(",
"value",
")",
... | Convert an integer.
Args:
value: A scalar value to convert.
Returns:
The integer value.
Raises:
ParseError: If an integer couldn't be consumed. | [
"Convert",
"an",
"integer",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L651-L669 |
29,547 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py | _ConvertFloat | def _ConvertFloat(value):
"""Convert an floating point number."""
if value == 'nan':
raise ParseError('Couldn\'t parse float "nan", use "NaN" instead.')
try:
# Assume Python compatible syntax.
return float(value)
except ValueError:
# Check alternative spellings.
if value == _NEG_INFINITY:
return float('-inf')
elif value == _INFINITY:
return float('inf')
elif value == _NAN:
return float('nan')
else:
raise ParseError('Couldn\'t parse float: {0}.'.format(value)) | python | def _ConvertFloat(value):
"""Convert an floating point number."""
if value == 'nan':
raise ParseError('Couldn\'t parse float "nan", use "NaN" instead.')
try:
# Assume Python compatible syntax.
return float(value)
except ValueError:
# Check alternative spellings.
if value == _NEG_INFINITY:
return float('-inf')
elif value == _INFINITY:
return float('inf')
elif value == _NAN:
return float('nan')
else:
raise ParseError('Couldn\'t parse float: {0}.'.format(value)) | [
"def",
"_ConvertFloat",
"(",
"value",
")",
":",
"if",
"value",
"==",
"'nan'",
":",
"raise",
"ParseError",
"(",
"'Couldn\\'t parse float \"nan\", use \"NaN\" instead.'",
")",
"try",
":",
"# Assume Python compatible syntax.",
"return",
"float",
"(",
"value",
")",
"excep... | Convert an floating point number. | [
"Convert",
"an",
"floating",
"point",
"number",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L672-L688 |
29,548 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py | _ConvertBool | def _ConvertBool(value, require_str):
"""Convert a boolean value.
Args:
value: A scalar value to convert.
require_str: If True, value must be a str.
Returns:
The bool parsed.
Raises:
ParseError: If a boolean value couldn't be consumed.
"""
if require_str:
if value == 'true':
return True
elif value == 'false':
return False
else:
raise ParseError('Expected "true" or "false", not {0}.'.format(value))
if not isinstance(value, bool):
raise ParseError('Expected true or false without quotes.')
return value | python | def _ConvertBool(value, require_str):
"""Convert a boolean value.
Args:
value: A scalar value to convert.
require_str: If True, value must be a str.
Returns:
The bool parsed.
Raises:
ParseError: If a boolean value couldn't be consumed.
"""
if require_str:
if value == 'true':
return True
elif value == 'false':
return False
else:
raise ParseError('Expected "true" or "false", not {0}.'.format(value))
if not isinstance(value, bool):
raise ParseError('Expected true or false without quotes.')
return value | [
"def",
"_ConvertBool",
"(",
"value",
",",
"require_str",
")",
":",
"if",
"require_str",
":",
"if",
"value",
"==",
"'true'",
":",
"return",
"True",
"elif",
"value",
"==",
"'false'",
":",
"return",
"False",
"else",
":",
"raise",
"ParseError",
"(",
"'Expected... | Convert a boolean value.
Args:
value: A scalar value to convert.
require_str: If True, value must be a str.
Returns:
The bool parsed.
Raises:
ParseError: If a boolean value couldn't be consumed. | [
"Convert",
"a",
"boolean",
"value",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L691-L714 |
29,549 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py | _Printer._MessageToJsonObject | def _MessageToJsonObject(self, message):
"""Converts message to an object according to Proto3 JSON Specification."""
message_descriptor = message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
return self._WrapperMessageToJsonObject(message)
if full_name in _WKTJSONMETHODS:
return methodcaller(_WKTJSONMETHODS[full_name][0], message)(self)
js = {}
return self._RegularMessageToJsonObject(message, js) | python | def _MessageToJsonObject(self, message):
"""Converts message to an object according to Proto3 JSON Specification."""
message_descriptor = message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
return self._WrapperMessageToJsonObject(message)
if full_name in _WKTJSONMETHODS:
return methodcaller(_WKTJSONMETHODS[full_name][0], message)(self)
js = {}
return self._RegularMessageToJsonObject(message, js) | [
"def",
"_MessageToJsonObject",
"(",
"self",
",",
"message",
")",
":",
"message_descriptor",
"=",
"message",
".",
"DESCRIPTOR",
"full_name",
"=",
"message_descriptor",
".",
"full_name",
"if",
"_IsWrapperMessage",
"(",
"message_descriptor",
")",
":",
"return",
"self",... | Converts message to an object according to Proto3 JSON Specification. | [
"Converts",
"message",
"to",
"an",
"object",
"according",
"to",
"Proto3",
"JSON",
"Specification",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L155-L164 |
29,550 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py | _Printer._RegularMessageToJsonObject | def _RegularMessageToJsonObject(self, message, js):
"""Converts normal message according to Proto3 JSON Specification."""
fields = message.ListFields()
try:
for field, value in fields:
if self.preserving_proto_field_name:
name = field.name
else:
name = field.json_name
if _IsMapEntry(field):
# Convert a map field.
v_field = field.message_type.fields_by_name['value']
js_map = {}
for key in value:
if isinstance(key, bool):
if key:
recorded_key = 'true'
else:
recorded_key = 'false'
else:
recorded_key = key
js_map[recorded_key] = self._FieldToJsonObject(
v_field, value[key])
js[name] = js_map
elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
# Convert a repeated field.
js[name] = [self._FieldToJsonObject(field, k)
for k in value]
else:
js[name] = self._FieldToJsonObject(field, value)
# Serialize default value if including_default_value_fields is True.
if self.including_default_value_fields:
message_descriptor = message.DESCRIPTOR
for field in message_descriptor.fields:
# Singular message fields and oneof fields will not be affected.
if ((field.label != descriptor.FieldDescriptor.LABEL_REPEATED and
field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE) or
field.containing_oneof):
continue
if self.preserving_proto_field_name:
name = field.name
else:
name = field.json_name
if name in js:
# Skip the field which has been serailized already.
continue
if _IsMapEntry(field):
js[name] = {}
elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
js[name] = []
else:
js[name] = self._FieldToJsonObject(field, field.default_value)
except ValueError as e:
raise SerializeToJsonError(
'Failed to serialize {0} field: {1}.'.format(field.name, e))
return js | python | def _RegularMessageToJsonObject(self, message, js):
"""Converts normal message according to Proto3 JSON Specification."""
fields = message.ListFields()
try:
for field, value in fields:
if self.preserving_proto_field_name:
name = field.name
else:
name = field.json_name
if _IsMapEntry(field):
# Convert a map field.
v_field = field.message_type.fields_by_name['value']
js_map = {}
for key in value:
if isinstance(key, bool):
if key:
recorded_key = 'true'
else:
recorded_key = 'false'
else:
recorded_key = key
js_map[recorded_key] = self._FieldToJsonObject(
v_field, value[key])
js[name] = js_map
elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
# Convert a repeated field.
js[name] = [self._FieldToJsonObject(field, k)
for k in value]
else:
js[name] = self._FieldToJsonObject(field, value)
# Serialize default value if including_default_value_fields is True.
if self.including_default_value_fields:
message_descriptor = message.DESCRIPTOR
for field in message_descriptor.fields:
# Singular message fields and oneof fields will not be affected.
if ((field.label != descriptor.FieldDescriptor.LABEL_REPEATED and
field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE) or
field.containing_oneof):
continue
if self.preserving_proto_field_name:
name = field.name
else:
name = field.json_name
if name in js:
# Skip the field which has been serailized already.
continue
if _IsMapEntry(field):
js[name] = {}
elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
js[name] = []
else:
js[name] = self._FieldToJsonObject(field, field.default_value)
except ValueError as e:
raise SerializeToJsonError(
'Failed to serialize {0} field: {1}.'.format(field.name, e))
return js | [
"def",
"_RegularMessageToJsonObject",
"(",
"self",
",",
"message",
",",
"js",
")",
":",
"fields",
"=",
"message",
".",
"ListFields",
"(",
")",
"try",
":",
"for",
"field",
",",
"value",
"in",
"fields",
":",
"if",
"self",
".",
"preserving_proto_field_name",
... | Converts normal message according to Proto3 JSON Specification. | [
"Converts",
"normal",
"message",
"according",
"to",
"Proto3",
"JSON",
"Specification",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L166-L225 |
29,551 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py | _Printer._FieldToJsonObject | def _FieldToJsonObject(self, field, value):
"""Converts field value according to Proto3 JSON Specification."""
if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
return self._MessageToJsonObject(value)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
enum_value = field.enum_type.values_by_number.get(value, None)
if enum_value is not None:
return enum_value.name
else:
raise SerializeToJsonError('Enum field contains an integer value '
'which can not mapped to an enum value.')
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
# Use base64 Data encoding for bytes
return base64.b64encode(value).decode('utf-8')
else:
return value
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
return bool(value)
elif field.cpp_type in _INT64_TYPES:
return str(value)
elif field.cpp_type in _FLOAT_TYPES:
if math.isinf(value):
if value < 0.0:
return _NEG_INFINITY
else:
return _INFINITY
if math.isnan(value):
return _NAN
return value | python | def _FieldToJsonObject(self, field, value):
"""Converts field value according to Proto3 JSON Specification."""
if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
return self._MessageToJsonObject(value)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
enum_value = field.enum_type.values_by_number.get(value, None)
if enum_value is not None:
return enum_value.name
else:
raise SerializeToJsonError('Enum field contains an integer value '
'which can not mapped to an enum value.')
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
# Use base64 Data encoding for bytes
return base64.b64encode(value).decode('utf-8')
else:
return value
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
return bool(value)
elif field.cpp_type in _INT64_TYPES:
return str(value)
elif field.cpp_type in _FLOAT_TYPES:
if math.isinf(value):
if value < 0.0:
return _NEG_INFINITY
else:
return _INFINITY
if math.isnan(value):
return _NAN
return value | [
"def",
"_FieldToJsonObject",
"(",
"self",
",",
"field",
",",
"value",
")",
":",
"if",
"field",
".",
"cpp_type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"CPPTYPE_MESSAGE",
":",
"return",
"self",
".",
"_MessageToJsonObject",
"(",
"value",
")",
"elif",
... | Converts field value according to Proto3 JSON Specification. | [
"Converts",
"field",
"value",
"according",
"to",
"Proto3",
"JSON",
"Specification",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L227-L256 |
29,552 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py | _Printer._AnyMessageToJsonObject | def _AnyMessageToJsonObject(self, message):
"""Converts Any message according to Proto3 JSON Specification."""
if not message.ListFields():
return {}
# Must print @type first, use OrderedDict instead of {}
js = OrderedDict()
type_url = message.type_url
js['@type'] = type_url
sub_message = _CreateMessageFromTypeUrl(type_url)
sub_message.ParseFromString(message.value)
message_descriptor = sub_message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
js['value'] = self._WrapperMessageToJsonObject(sub_message)
return js
if full_name in _WKTJSONMETHODS:
js['value'] = methodcaller(_WKTJSONMETHODS[full_name][0],
sub_message)(self)
return js
return self._RegularMessageToJsonObject(sub_message, js) | python | def _AnyMessageToJsonObject(self, message):
"""Converts Any message according to Proto3 JSON Specification."""
if not message.ListFields():
return {}
# Must print @type first, use OrderedDict instead of {}
js = OrderedDict()
type_url = message.type_url
js['@type'] = type_url
sub_message = _CreateMessageFromTypeUrl(type_url)
sub_message.ParseFromString(message.value)
message_descriptor = sub_message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
js['value'] = self._WrapperMessageToJsonObject(sub_message)
return js
if full_name in _WKTJSONMETHODS:
js['value'] = methodcaller(_WKTJSONMETHODS[full_name][0],
sub_message)(self)
return js
return self._RegularMessageToJsonObject(sub_message, js) | [
"def",
"_AnyMessageToJsonObject",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"message",
".",
"ListFields",
"(",
")",
":",
"return",
"{",
"}",
"# Must print @type first, use OrderedDict instead of {}",
"js",
"=",
"OrderedDict",
"(",
")",
"type_url",
"=",
... | Converts Any message according to Proto3 JSON Specification. | [
"Converts",
"Any",
"message",
"according",
"to",
"Proto3",
"JSON",
"Specification",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L258-L277 |
29,553 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py | _Printer._ValueMessageToJsonObject | def _ValueMessageToJsonObject(self, message):
"""Converts Value message according to Proto3 JSON Specification."""
which = message.WhichOneof('kind')
# If the Value message is not set treat as null_value when serialize
# to JSON. The parse back result will be different from original message.
if which is None or which == 'null_value':
return None
if which == 'list_value':
return self._ListValueMessageToJsonObject(message.list_value)
if which == 'struct_value':
value = message.struct_value
else:
value = getattr(message, which)
oneof_descriptor = message.DESCRIPTOR.fields_by_name[which]
return self._FieldToJsonObject(oneof_descriptor, value) | python | def _ValueMessageToJsonObject(self, message):
"""Converts Value message according to Proto3 JSON Specification."""
which = message.WhichOneof('kind')
# If the Value message is not set treat as null_value when serialize
# to JSON. The parse back result will be different from original message.
if which is None or which == 'null_value':
return None
if which == 'list_value':
return self._ListValueMessageToJsonObject(message.list_value)
if which == 'struct_value':
value = message.struct_value
else:
value = getattr(message, which)
oneof_descriptor = message.DESCRIPTOR.fields_by_name[which]
return self._FieldToJsonObject(oneof_descriptor, value) | [
"def",
"_ValueMessageToJsonObject",
"(",
"self",
",",
"message",
")",
":",
"which",
"=",
"message",
".",
"WhichOneof",
"(",
"'kind'",
")",
"# If the Value message is not set treat as null_value when serialize",
"# to JSON. The parse back result will be different from original messa... | Converts Value message according to Proto3 JSON Specification. | [
"Converts",
"Value",
"message",
"according",
"to",
"Proto3",
"JSON",
"Specification",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L285-L299 |
29,554 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py | _Printer._StructMessageToJsonObject | def _StructMessageToJsonObject(self, message):
"""Converts Struct message according to Proto3 JSON Specification."""
fields = message.fields
ret = {}
for key in fields:
ret[key] = self._ValueMessageToJsonObject(fields[key])
return ret | python | def _StructMessageToJsonObject(self, message):
"""Converts Struct message according to Proto3 JSON Specification."""
fields = message.fields
ret = {}
for key in fields:
ret[key] = self._ValueMessageToJsonObject(fields[key])
return ret | [
"def",
"_StructMessageToJsonObject",
"(",
"self",
",",
"message",
")",
":",
"fields",
"=",
"message",
".",
"fields",
"ret",
"=",
"{",
"}",
"for",
"key",
"in",
"fields",
":",
"ret",
"[",
"key",
"]",
"=",
"self",
".",
"_ValueMessageToJsonObject",
"(",
"fie... | Converts Struct message according to Proto3 JSON Specification. | [
"Converts",
"Struct",
"message",
"according",
"to",
"Proto3",
"JSON",
"Specification",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L306-L312 |
29,555 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py | _Parser.ConvertMessage | def ConvertMessage(self, value, message):
"""Convert a JSON object into a message.
Args:
value: A JSON object.
message: A WKT or regular protocol message to record the data.
Raises:
ParseError: In case of convert problems.
"""
message_descriptor = message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
self._ConvertWrapperMessage(value, message)
elif full_name in _WKTJSONMETHODS:
methodcaller(_WKTJSONMETHODS[full_name][1], value, message)(self)
else:
self._ConvertFieldValuePair(value, message) | python | def ConvertMessage(self, value, message):
"""Convert a JSON object into a message.
Args:
value: A JSON object.
message: A WKT or regular protocol message to record the data.
Raises:
ParseError: In case of convert problems.
"""
message_descriptor = message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
self._ConvertWrapperMessage(value, message)
elif full_name in _WKTJSONMETHODS:
methodcaller(_WKTJSONMETHODS[full_name][1], value, message)(self)
else:
self._ConvertFieldValuePair(value, message) | [
"def",
"ConvertMessage",
"(",
"self",
",",
"value",
",",
"message",
")",
":",
"message_descriptor",
"=",
"message",
".",
"DESCRIPTOR",
"full_name",
"=",
"message_descriptor",
".",
"full_name",
"if",
"_IsWrapperMessage",
"(",
"message_descriptor",
")",
":",
"self",... | Convert a JSON object into a message.
Args:
value: A JSON object.
message: A WKT or regular protocol message to record the data.
Raises:
ParseError: In case of convert problems. | [
"Convert",
"a",
"JSON",
"object",
"into",
"a",
"message",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L398-L415 |
29,556 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py | _Parser._ConvertAnyMessage | def _ConvertAnyMessage(self, value, message):
"""Convert a JSON representation into Any message."""
if isinstance(value, dict) and not value:
return
try:
type_url = value['@type']
except KeyError:
raise ParseError('@type is missing when parsing any message.')
sub_message = _CreateMessageFromTypeUrl(type_url)
message_descriptor = sub_message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
self._ConvertWrapperMessage(value['value'], sub_message)
elif full_name in _WKTJSONMETHODS:
methodcaller(
_WKTJSONMETHODS[full_name][1], value['value'], sub_message)(self)
else:
del value['@type']
self._ConvertFieldValuePair(value, sub_message)
# Sets Any message
message.value = sub_message.SerializeToString()
message.type_url = type_url | python | def _ConvertAnyMessage(self, value, message):
"""Convert a JSON representation into Any message."""
if isinstance(value, dict) and not value:
return
try:
type_url = value['@type']
except KeyError:
raise ParseError('@type is missing when parsing any message.')
sub_message = _CreateMessageFromTypeUrl(type_url)
message_descriptor = sub_message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
self._ConvertWrapperMessage(value['value'], sub_message)
elif full_name in _WKTJSONMETHODS:
methodcaller(
_WKTJSONMETHODS[full_name][1], value['value'], sub_message)(self)
else:
del value['@type']
self._ConvertFieldValuePair(value, sub_message)
# Sets Any message
message.value = sub_message.SerializeToString()
message.type_url = type_url | [
"def",
"_ConvertAnyMessage",
"(",
"self",
",",
"value",
",",
"message",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
"and",
"not",
"value",
":",
"return",
"try",
":",
"type_url",
"=",
"value",
"[",
"'@type'",
"]",
"except",
"KeyError",
... | Convert a JSON representation into Any message. | [
"Convert",
"a",
"JSON",
"representation",
"into",
"Any",
"message",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L509-L531 |
29,557 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py | _Parser._ConvertWrapperMessage | def _ConvertWrapperMessage(self, value, message):
"""Convert a JSON representation into Wrapper message."""
field = message.DESCRIPTOR.fields_by_name['value']
setattr(message, 'value', _ConvertScalarFieldValue(value, field)) | python | def _ConvertWrapperMessage(self, value, message):
"""Convert a JSON representation into Wrapper message."""
field = message.DESCRIPTOR.fields_by_name['value']
setattr(message, 'value', _ConvertScalarFieldValue(value, field)) | [
"def",
"_ConvertWrapperMessage",
"(",
"self",
",",
"value",
",",
"message",
")",
":",
"field",
"=",
"message",
".",
"DESCRIPTOR",
".",
"fields_by_name",
"[",
"'value'",
"]",
"setattr",
"(",
"message",
",",
"'value'",
",",
"_ConvertScalarFieldValue",
"(",
"valu... | Convert a JSON representation into Wrapper message. | [
"Convert",
"a",
"JSON",
"representation",
"into",
"Wrapper",
"message",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L574-L577 |
29,558 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py | _Parser._ConvertMapFieldValue | def _ConvertMapFieldValue(self, value, message, field):
"""Convert map field value for a message map field.
Args:
value: A JSON object to convert the map field value.
message: A protocol message to record the converted data.
field: The descriptor of the map field to be converted.
Raises:
ParseError: In case of convert problems.
"""
if not isinstance(value, dict):
raise ParseError(
'Map field {0} must be in a dict which is {1}.'.format(
field.name, value))
key_field = field.message_type.fields_by_name['key']
value_field = field.message_type.fields_by_name['value']
for key in value:
key_value = _ConvertScalarFieldValue(key, key_field, True)
if value_field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
self.ConvertMessage(value[key], getattr(
message, field.name)[key_value])
else:
getattr(message, field.name)[key_value] = _ConvertScalarFieldValue(
value[key], value_field) | python | def _ConvertMapFieldValue(self, value, message, field):
"""Convert map field value for a message map field.
Args:
value: A JSON object to convert the map field value.
message: A protocol message to record the converted data.
field: The descriptor of the map field to be converted.
Raises:
ParseError: In case of convert problems.
"""
if not isinstance(value, dict):
raise ParseError(
'Map field {0} must be in a dict which is {1}.'.format(
field.name, value))
key_field = field.message_type.fields_by_name['key']
value_field = field.message_type.fields_by_name['value']
for key in value:
key_value = _ConvertScalarFieldValue(key, key_field, True)
if value_field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
self.ConvertMessage(value[key], getattr(
message, field.name)[key_value])
else:
getattr(message, field.name)[key_value] = _ConvertScalarFieldValue(
value[key], value_field) | [
"def",
"_ConvertMapFieldValue",
"(",
"self",
",",
"value",
",",
"message",
",",
"field",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"raise",
"ParseError",
"(",
"'Map field {0} must be in a dict which is {1}.'",
".",
"format",
"(",
... | Convert map field value for a message map field.
Args:
value: A JSON object to convert the map field value.
message: A protocol message to record the converted data.
field: The descriptor of the map field to be converted.
Raises:
ParseError: In case of convert problems. | [
"Convert",
"map",
"field",
"value",
"for",
"a",
"message",
"map",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L579-L603 |
29,559 | apple/turicreate | src/unity/python/turicreate/visualization/show.py | categorical_heatmap | def categorical_heatmap(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 categorical heatmap, and returns the resulting Plot object.
The function supports SArrays of dtypes str.
Parameters
----------
x : SArray
The data to plot on the X axis of the categorical heatmap.
Must be string SArray
y : SArray
The data to plot on the Y axis of the categorical heatmap.
Must be string SArray 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 categorical heatmap.
Examples
--------
Make a categorical heatmap.
>>> x = turicreate.SArray(['1','2','3','4','5'])
>>> y = turicreate.SArray(['a','b','c','d','e'])
>>> catheat = turicreate.visualization.categorical_heatmap(x, y)
"""
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 != str):
raise ValueError("turicreate.visualization.categorical_heatmap supports " +
"SArrays of dtype: str")
# legit input
title = _get_title(title)
plt_ref = tc.extensions.plot_categorical_heatmap(x, y,
xlabel, ylabel, title)
return Plot(plt_ref) | python | def categorical_heatmap(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 categorical heatmap, and returns the resulting Plot object.
The function supports SArrays of dtypes str.
Parameters
----------
x : SArray
The data to plot on the X axis of the categorical heatmap.
Must be string SArray
y : SArray
The data to plot on the Y axis of the categorical heatmap.
Must be string SArray 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 categorical heatmap.
Examples
--------
Make a categorical heatmap.
>>> x = turicreate.SArray(['1','2','3','4','5'])
>>> y = turicreate.SArray(['a','b','c','d','e'])
>>> catheat = turicreate.visualization.categorical_heatmap(x, y)
"""
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 != str):
raise ValueError("turicreate.visualization.categorical_heatmap supports " +
"SArrays of dtype: str")
# legit input
title = _get_title(title)
plt_ref = tc.extensions.plot_categorical_heatmap(x, y,
xlabel, ylabel, title)
return Plot(plt_ref) | [
"def",
"categorical_heatmap",
"(",
"x",
",",
"y",
",",
"xlabel",
"=",
"LABEL_DEFAULT",
",",
"ylabel",
"=",
"LABEL_DEFAULT",
",",
"title",
"=",
"LABEL_DEFAULT",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"x",
",",
"tc",
".",
"data_structures",
".",
"s... | Plots the data in `x` on the X axis and the data in `y` on the Y axis
in a 2d categorical heatmap, and returns the resulting Plot object.
The function supports SArrays of dtypes str.
Parameters
----------
x : SArray
The data to plot on the X axis of the categorical heatmap.
Must be string SArray
y : SArray
The data to plot on the Y axis of the categorical heatmap.
Must be string SArray 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 categorical heatmap.
Examples
--------
Make a categorical heatmap.
>>> x = turicreate.SArray(['1','2','3','4','5'])
>>> y = turicreate.SArray(['a','b','c','d','e'])
>>> catheat = turicreate.visualization.categorical_heatmap(x, y) | [
"Plots",
"the",
"data",
"in",
"x",
"on",
"the",
"X",
"axis",
"and",
"the",
"data",
"in",
"y",
"on",
"the",
"Y",
"axis",
"in",
"a",
"2d",
"categorical",
"heatmap",
"and",
"returns",
"the",
"resulting",
"Plot",
"object",
".",
"The",
"function",
"supports... | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/visualization/show.py#L195-L242 |
29,560 | 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 SFra... | 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 |
29,561 | 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",
".",
"SArr... | 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 |
29,562 | 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",
".",
... | 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 |
29,563 | 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"... | 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 |
29,564 | 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 |
29,565 | 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 |
29,566 | 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",... | 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 |
29,567 | 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",
",",
"_SGra... | 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 |
29,568 | 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",
",",
"... | 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 |
29,569 | 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",
"... | 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 |
29,570 | 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 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 |
29,571 | 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",
... | 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 |
29,572 | 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",
"co... | 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 |
29,573 | 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",
"i... | 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 |
29,574 | 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 |
29,575 | 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",
")",
... | 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... | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/path.py#L872-L888 |
29,576 | 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",
"=",
"[",
... | 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 |
29,577 | 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",
... | 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 |
29,578 | 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",
"(",
"... | 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 |
29,579 | 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 som... | 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 |
29,580 | 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 |
29,581 | 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'",
")",
"sou... | 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 |
29,582 | 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",
"(",
")... | 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 |
29,583 | 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 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 |
29,584 | 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",... | 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 |
29,585 | 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"... | 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 |
29,586 | 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",
"__... | 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 |
29,587 | 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",
")",
"val... | 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 |
29,588 | 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"... | 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 |
29,589 | 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'",... | 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 |
29,590 | 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_d... | 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 |
29,591 | 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",
... | 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 |
29,592 | 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 |
29,593 | 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",
... | 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",
"an... | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/type.py#L334-L351 |
29,594 | 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"... | 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",
... | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/type.py#L353-L365 |
29,595 | 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",
")",
... | 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"... | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/type.py#L368-L381 |
29,596 | 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__",
"(",
")",
... | 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 |
29,597 | 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 ==... | 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 |
29,598 | 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",
"... | 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 |
29,599 | 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",... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.