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,000
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/flexible_shape_utils.py
can_allow_multiple_input_shapes
def can_allow_multiple_input_shapes(spec): """ Examines a model specification and determines if it can compute results for more than one output shape. :param spec: MLModel The protobuf specification of the model. :return: Bool Returns True if the model can allow multiple input shapes, False otherwise. """ # First, check that the model actually has a neural network in it try: layers = _get_nn_layers(spec) except: raise Exception('Unable to verify that this model contains a neural network.') try: shaper = NeuralNetworkShaper(spec, False) except: raise Exception('Unable to compute shapes for this neural network.') inputs = _get_input_names(spec) for name in inputs: shape_dict = shaper.shape(name) shape = NeuralNetworkMultiArrayShapeRange(shape_dict) if (shape.isFlexible()): return True return False
python
def can_allow_multiple_input_shapes(spec): """ Examines a model specification and determines if it can compute results for more than one output shape. :param spec: MLModel The protobuf specification of the model. :return: Bool Returns True if the model can allow multiple input shapes, False otherwise. """ # First, check that the model actually has a neural network in it try: layers = _get_nn_layers(spec) except: raise Exception('Unable to verify that this model contains a neural network.') try: shaper = NeuralNetworkShaper(spec, False) except: raise Exception('Unable to compute shapes for this neural network.') inputs = _get_input_names(spec) for name in inputs: shape_dict = shaper.shape(name) shape = NeuralNetworkMultiArrayShapeRange(shape_dict) if (shape.isFlexible()): return True return False
[ "def", "can_allow_multiple_input_shapes", "(", "spec", ")", ":", "# First, check that the model actually has a neural network in it", "try", ":", "layers", "=", "_get_nn_layers", "(", "spec", ")", "except", ":", "raise", "Exception", "(", "'Unable to verify that this model contains a neural network.'", ")", "try", ":", "shaper", "=", "NeuralNetworkShaper", "(", "spec", ",", "False", ")", "except", ":", "raise", "Exception", "(", "'Unable to compute shapes for this neural network.'", ")", "inputs", "=", "_get_input_names", "(", "spec", ")", "for", "name", "in", "inputs", ":", "shape_dict", "=", "shaper", ".", "shape", "(", "name", ")", "shape", "=", "NeuralNetworkMultiArrayShapeRange", "(", "shape_dict", ")", "if", "(", "shape", ".", "isFlexible", "(", ")", ")", ":", "return", "True", "return", "False" ]
Examines a model specification and determines if it can compute results for more than one output shape. :param spec: MLModel The protobuf specification of the model. :return: Bool Returns True if the model can allow multiple input shapes, False otherwise.
[ "Examines", "a", "model", "specification", "and", "determines", "if", "it", "can", "compute", "results", "for", "more", "than", "one", "output", "shape", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/flexible_shape_utils.py#L575-L607
29,001
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/flexible_shape_utils.py
NeuralNetworkMultiArrayShapeRange.isFlexible
def isFlexible(self): """ Returns true if any one of the channel, height, or width ranges of this shape allow more than one input value. """ for key, value in self.arrayShapeRange.items(): if key in _CONSTRAINED_KEYS: if value.isFlexible: return True return False
python
def isFlexible(self): """ Returns true if any one of the channel, height, or width ranges of this shape allow more than one input value. """ for key, value in self.arrayShapeRange.items(): if key in _CONSTRAINED_KEYS: if value.isFlexible: return True return False
[ "def", "isFlexible", "(", "self", ")", ":", "for", "key", ",", "value", "in", "self", ".", "arrayShapeRange", ".", "items", "(", ")", ":", "if", "key", "in", "_CONSTRAINED_KEYS", ":", "if", "value", ".", "isFlexible", ":", "return", "True", "return", "False" ]
Returns true if any one of the channel, height, or width ranges of this shape allow more than one input value.
[ "Returns", "true", "if", "any", "one", "of", "the", "channel", "height", "or", "width", "ranges", "of", "this", "shape", "allow", "more", "than", "one", "input", "value", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/flexible_shape_utils.py#L220-L229
29,002
apple/turicreate
deps/src/boost_1_68_0/libs/metaparse/tools/string_headers.py
define_macro
def define_macro(out_f, (name, args, body), undefine=False, check=True): """Generate a macro definition or undefinition""" if undefine: out_f.write( '#undef {0}\n' .format(macro_name(name)) ) else: if args: arg_list = '({0})'.format(', '.join(args)) else: arg_list = '' if check: out_f.write( '#ifdef {0}\n' '# error {0} already defined.\n' '#endif\n' .format(macro_name(name)) ) out_f.write( '#define {0}{1} {2}\n'.format(macro_name(name), arg_list, body) )
python
def define_macro(out_f, (name, args, body), undefine=False, check=True): """Generate a macro definition or undefinition""" if undefine: out_f.write( '#undef {0}\n' .format(macro_name(name)) ) else: if args: arg_list = '({0})'.format(', '.join(args)) else: arg_list = '' if check: out_f.write( '#ifdef {0}\n' '# error {0} already defined.\n' '#endif\n' .format(macro_name(name)) ) out_f.write( '#define {0}{1} {2}\n'.format(macro_name(name), arg_list, body) )
[ "def", "define_macro", "(", "out_f", ",", "(", "name", ",", "args", ",", "body", ")", ",", "undefine", "=", "False", ",", "check", "=", "True", ")", ":", "if", "undefine", ":", "out_f", ".", "write", "(", "'#undef {0}\\n'", ".", "format", "(", "macro_name", "(", "name", ")", ")", ")", "else", ":", "if", "args", ":", "arg_list", "=", "'({0})'", ".", "format", "(", "', '", ".", "join", "(", "args", ")", ")", "else", ":", "arg_list", "=", "''", "if", "check", ":", "out_f", ".", "write", "(", "'#ifdef {0}\\n'", "'# error {0} already defined.\\n'", "'#endif\\n'", ".", "format", "(", "macro_name", "(", "name", ")", ")", ")", "out_f", ".", "write", "(", "'#define {0}{1} {2}\\n'", ".", "format", "(", "macro_name", "(", "name", ")", ",", "arg_list", ",", "body", ")", ")" ]
Generate a macro definition or undefinition
[ "Generate", "a", "macro", "definition", "or", "undefinition" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/metaparse/tools/string_headers.py#L92-L115
29,003
apple/turicreate
deps/src/boost_1_68_0/libs/metaparse/tools/string_headers.py
filename
def filename(out_dir, name, undefine=False): """Generate the filename""" if undefine: prefix = 'undef_' else: prefix = '' return os.path.join(out_dir, '{0}{1}.hpp'.format(prefix, name.lower()))
python
def filename(out_dir, name, undefine=False): """Generate the filename""" if undefine: prefix = 'undef_' else: prefix = '' return os.path.join(out_dir, '{0}{1}.hpp'.format(prefix, name.lower()))
[ "def", "filename", "(", "out_dir", ",", "name", ",", "undefine", "=", "False", ")", ":", "if", "undefine", ":", "prefix", "=", "'undef_'", "else", ":", "prefix", "=", "''", "return", "os", ".", "path", ".", "join", "(", "out_dir", ",", "'{0}{1}.hpp'", ".", "format", "(", "prefix", ",", "name", ".", "lower", "(", ")", ")", ")" ]
Generate the filename
[ "Generate", "the", "filename" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/metaparse/tools/string_headers.py#L118-L124
29,004
apple/turicreate
deps/src/boost_1_68_0/libs/metaparse/tools/string_headers.py
length_limits
def length_limits(max_length_limit, length_limit_step): """Generates the length limits""" string_len = len(str(max_length_limit)) return [ str(i).zfill(string_len) for i in xrange( length_limit_step, max_length_limit + length_limit_step - 1, length_limit_step ) ]
python
def length_limits(max_length_limit, length_limit_step): """Generates the length limits""" string_len = len(str(max_length_limit)) return [ str(i).zfill(string_len) for i in xrange( length_limit_step, max_length_limit + length_limit_step - 1, length_limit_step ) ]
[ "def", "length_limits", "(", "max_length_limit", ",", "length_limit_step", ")", ":", "string_len", "=", "len", "(", "str", "(", "max_length_limit", ")", ")", "return", "[", "str", "(", "i", ")", ".", "zfill", "(", "string_len", ")", "for", "i", "in", "xrange", "(", "length_limit_step", ",", "max_length_limit", "+", "length_limit_step", "-", "1", ",", "length_limit_step", ")", "]" ]
Generates the length limits
[ "Generates", "the", "length", "limits" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/metaparse/tools/string_headers.py#L127-L137
29,005
apple/turicreate
deps/src/boost_1_68_0/libs/metaparse/tools/string_headers.py
generate_take
def generate_take(out_f, steps, line_prefix): """Generate the take function""" out_f.write( '{0}constexpr inline int take(int n_)\n' '{0}{{\n' '{0} return {1} 0 {2};\n' '{0}}}\n' '\n'.format( line_prefix, ''.join('n_ >= {0} ? {0} : ('.format(s) for s in steps), ')' * len(steps) ) )
python
def generate_take(out_f, steps, line_prefix): """Generate the take function""" out_f.write( '{0}constexpr inline int take(int n_)\n' '{0}{{\n' '{0} return {1} 0 {2};\n' '{0}}}\n' '\n'.format( line_prefix, ''.join('n_ >= {0} ? {0} : ('.format(s) for s in steps), ')' * len(steps) ) )
[ "def", "generate_take", "(", "out_f", ",", "steps", ",", "line_prefix", ")", ":", "out_f", ".", "write", "(", "'{0}constexpr inline int take(int n_)\\n'", "'{0}{{\\n'", "'{0} return {1} 0 {2};\\n'", "'{0}}}\\n'", "'\\n'", ".", "format", "(", "line_prefix", ",", "''", ".", "join", "(", "'n_ >= {0} ? {0} : ('", ".", "format", "(", "s", ")", "for", "s", "in", "steps", ")", ",", "')'", "*", "len", "(", "steps", ")", ")", ")" ]
Generate the take function
[ "Generate", "the", "take", "function" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/metaparse/tools/string_headers.py#L145-L157
29,006
apple/turicreate
deps/src/boost_1_68_0/libs/metaparse/tools/string_headers.py
generate_make_string
def generate_make_string(out_f, max_step): """Generate the make_string template""" steps = [2 ** n for n in xrange(int(math.log(max_step, 2)), -1, -1)] with Namespace( out_f, ['boost', 'metaparse', 'v{0}'.format(VERSION), 'impl'] ) as nsp: generate_take(out_f, steps, nsp.prefix()) out_f.write( '{0}template <int LenNow, int LenRemaining, char... Cs>\n' '{0}struct make_string;\n' '\n' '{0}template <char... Cs>' ' struct make_string<0, 0, Cs...> : string<> {{}};\n' .format(nsp.prefix()) ) disable_sun = False for i in reversed(steps): if i > 64 and not disable_sun: out_f.write('#ifndef __SUNPRO_CC\n') disable_sun = True out_f.write( '{0}template <int LenRemaining,{1}char... Cs>' ' struct make_string<{2},LenRemaining,{3}Cs...> :' ' concat<string<{4}>,' ' typename make_string<take(LenRemaining),' 'LenRemaining-take(LenRemaining),Cs...>::type> {{}};\n' .format( nsp.prefix(), ''.join('char {0},'.format(n) for n in unique_names(i)), i, ''.join('{0},'.format(n) for n in unique_names(i)), ','.join(unique_names(i)) ) ) if disable_sun: out_f.write('#endif\n')
python
def generate_make_string(out_f, max_step): """Generate the make_string template""" steps = [2 ** n for n in xrange(int(math.log(max_step, 2)), -1, -1)] with Namespace( out_f, ['boost', 'metaparse', 'v{0}'.format(VERSION), 'impl'] ) as nsp: generate_take(out_f, steps, nsp.prefix()) out_f.write( '{0}template <int LenNow, int LenRemaining, char... Cs>\n' '{0}struct make_string;\n' '\n' '{0}template <char... Cs>' ' struct make_string<0, 0, Cs...> : string<> {{}};\n' .format(nsp.prefix()) ) disable_sun = False for i in reversed(steps): if i > 64 and not disable_sun: out_f.write('#ifndef __SUNPRO_CC\n') disable_sun = True out_f.write( '{0}template <int LenRemaining,{1}char... Cs>' ' struct make_string<{2},LenRemaining,{3}Cs...> :' ' concat<string<{4}>,' ' typename make_string<take(LenRemaining),' 'LenRemaining-take(LenRemaining),Cs...>::type> {{}};\n' .format( nsp.prefix(), ''.join('char {0},'.format(n) for n in unique_names(i)), i, ''.join('{0},'.format(n) for n in unique_names(i)), ','.join(unique_names(i)) ) ) if disable_sun: out_f.write('#endif\n')
[ "def", "generate_make_string", "(", "out_f", ",", "max_step", ")", ":", "steps", "=", "[", "2", "**", "n", "for", "n", "in", "xrange", "(", "int", "(", "math", ".", "log", "(", "max_step", ",", "2", ")", ")", ",", "-", "1", ",", "-", "1", ")", "]", "with", "Namespace", "(", "out_f", ",", "[", "'boost'", ",", "'metaparse'", ",", "'v{0}'", ".", "format", "(", "VERSION", ")", ",", "'impl'", "]", ")", "as", "nsp", ":", "generate_take", "(", "out_f", ",", "steps", ",", "nsp", ".", "prefix", "(", ")", ")", "out_f", ".", "write", "(", "'{0}template <int LenNow, int LenRemaining, char... Cs>\\n'", "'{0}struct make_string;\\n'", "'\\n'", "'{0}template <char... Cs>'", "' struct make_string<0, 0, Cs...> : string<> {{}};\\n'", ".", "format", "(", "nsp", ".", "prefix", "(", ")", ")", ")", "disable_sun", "=", "False", "for", "i", "in", "reversed", "(", "steps", ")", ":", "if", "i", ">", "64", "and", "not", "disable_sun", ":", "out_f", ".", "write", "(", "'#ifndef __SUNPRO_CC\\n'", ")", "disable_sun", "=", "True", "out_f", ".", "write", "(", "'{0}template <int LenRemaining,{1}char... Cs>'", "' struct make_string<{2},LenRemaining,{3}Cs...> :'", "' concat<string<{4}>,'", "' typename make_string<take(LenRemaining),'", "'LenRemaining-take(LenRemaining),Cs...>::type> {{}};\\n'", ".", "format", "(", "nsp", ".", "prefix", "(", ")", ",", "''", ".", "join", "(", "'char {0},'", ".", "format", "(", "n", ")", "for", "n", "in", "unique_names", "(", "i", ")", ")", ",", "i", ",", "''", ".", "join", "(", "'{0},'", ".", "format", "(", "n", ")", "for", "n", "in", "unique_names", "(", "i", ")", ")", ",", "','", ".", "join", "(", "unique_names", "(", "i", ")", ")", ")", ")", "if", "disable_sun", ":", "out_f", ".", "write", "(", "'#endif\\n'", ")" ]
Generate the make_string template
[ "Generate", "the", "make_string", "template" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/metaparse/tools/string_headers.py#L160-L199
29,007
apple/turicreate
deps/src/boost_1_68_0/libs/metaparse/tools/string_headers.py
generate_string
def generate_string(out_dir, limits): """Generate string.hpp""" max_limit = max((int(v) for v in limits)) with open(filename(out_dir, 'string'), 'wb') as out_f: with IncludeGuard(out_f): out_f.write( '\n' '#include <boost/metaparse/v{0}/cpp11/impl/concat.hpp>\n' '#include <boost/preprocessor/cat.hpp>\n' .format(VERSION) ) generate_make_string(out_f, 512) out_f.write( '\n' '#ifndef BOOST_METAPARSE_LIMIT_STRING_SIZE\n' '# error BOOST_METAPARSE_LIMIT_STRING_SIZE not defined\n' '#endif\n' '\n' '#if BOOST_METAPARSE_LIMIT_STRING_SIZE > {0}\n' '# error BOOST_METAPARSE_LIMIT_STRING_SIZE is greater than' ' {0}. To increase the limit run tools/string_headers.py of' ' Boost.Metaparse against your Boost headers.\n' '#endif\n' '\n' .format(max_limit) ) define_macro(out_f, ( 'STRING', ['s'], '{0}::make_string< ' '{0}::take(sizeof(s)-1), sizeof(s)-1-{0}::take(sizeof(s)-1),' 'BOOST_PP_CAT({1}, BOOST_METAPARSE_LIMIT_STRING_SIZE)(s)' '>::type' .format( '::boost::metaparse::v{0}::impl'.format(VERSION), macro_name('I') ) )) out_f.write('\n') for limit in xrange(0, max_limit + 1): out_f.write( '#define {0} {1}\n' .format( macro_name('I{0}'.format(limit)), macro_name('INDEX_STR{0}'.format( min(int(l) for l in limits if int(l) >= limit) )) ) ) out_f.write('\n') prev_macro = None prev_limit = 0 for length_limit in (int(l) for l in limits): this_macro = macro_name('INDEX_STR{0}'.format(length_limit)) out_f.write( '#define {0}(s) {1}{2}\n' .format( this_macro, '{0}(s),'.format(prev_macro) if prev_macro else '', ','.join( '{0}((s), {1})' .format(macro_name('STRING_AT'), i) for i in xrange(prev_limit, length_limit) ) ) ) prev_macro = this_macro prev_limit = length_limit
python
def generate_string(out_dir, limits): """Generate string.hpp""" max_limit = max((int(v) for v in limits)) with open(filename(out_dir, 'string'), 'wb') as out_f: with IncludeGuard(out_f): out_f.write( '\n' '#include <boost/metaparse/v{0}/cpp11/impl/concat.hpp>\n' '#include <boost/preprocessor/cat.hpp>\n' .format(VERSION) ) generate_make_string(out_f, 512) out_f.write( '\n' '#ifndef BOOST_METAPARSE_LIMIT_STRING_SIZE\n' '# error BOOST_METAPARSE_LIMIT_STRING_SIZE not defined\n' '#endif\n' '\n' '#if BOOST_METAPARSE_LIMIT_STRING_SIZE > {0}\n' '# error BOOST_METAPARSE_LIMIT_STRING_SIZE is greater than' ' {0}. To increase the limit run tools/string_headers.py of' ' Boost.Metaparse against your Boost headers.\n' '#endif\n' '\n' .format(max_limit) ) define_macro(out_f, ( 'STRING', ['s'], '{0}::make_string< ' '{0}::take(sizeof(s)-1), sizeof(s)-1-{0}::take(sizeof(s)-1),' 'BOOST_PP_CAT({1}, BOOST_METAPARSE_LIMIT_STRING_SIZE)(s)' '>::type' .format( '::boost::metaparse::v{0}::impl'.format(VERSION), macro_name('I') ) )) out_f.write('\n') for limit in xrange(0, max_limit + 1): out_f.write( '#define {0} {1}\n' .format( macro_name('I{0}'.format(limit)), macro_name('INDEX_STR{0}'.format( min(int(l) for l in limits if int(l) >= limit) )) ) ) out_f.write('\n') prev_macro = None prev_limit = 0 for length_limit in (int(l) for l in limits): this_macro = macro_name('INDEX_STR{0}'.format(length_limit)) out_f.write( '#define {0}(s) {1}{2}\n' .format( this_macro, '{0}(s),'.format(prev_macro) if prev_macro else '', ','.join( '{0}((s), {1})' .format(macro_name('STRING_AT'), i) for i in xrange(prev_limit, length_limit) ) ) ) prev_macro = this_macro prev_limit = length_limit
[ "def", "generate_string", "(", "out_dir", ",", "limits", ")", ":", "max_limit", "=", "max", "(", "(", "int", "(", "v", ")", "for", "v", "in", "limits", ")", ")", "with", "open", "(", "filename", "(", "out_dir", ",", "'string'", ")", ",", "'wb'", ")", "as", "out_f", ":", "with", "IncludeGuard", "(", "out_f", ")", ":", "out_f", ".", "write", "(", "'\\n'", "'#include <boost/metaparse/v{0}/cpp11/impl/concat.hpp>\\n'", "'#include <boost/preprocessor/cat.hpp>\\n'", ".", "format", "(", "VERSION", ")", ")", "generate_make_string", "(", "out_f", ",", "512", ")", "out_f", ".", "write", "(", "'\\n'", "'#ifndef BOOST_METAPARSE_LIMIT_STRING_SIZE\\n'", "'# error BOOST_METAPARSE_LIMIT_STRING_SIZE not defined\\n'", "'#endif\\n'", "'\\n'", "'#if BOOST_METAPARSE_LIMIT_STRING_SIZE > {0}\\n'", "'# error BOOST_METAPARSE_LIMIT_STRING_SIZE is greater than'", "' {0}. To increase the limit run tools/string_headers.py of'", "' Boost.Metaparse against your Boost headers.\\n'", "'#endif\\n'", "'\\n'", ".", "format", "(", "max_limit", ")", ")", "define_macro", "(", "out_f", ",", "(", "'STRING'", ",", "[", "'s'", "]", ",", "'{0}::make_string< '", "'{0}::take(sizeof(s)-1), sizeof(s)-1-{0}::take(sizeof(s)-1),'", "'BOOST_PP_CAT({1}, BOOST_METAPARSE_LIMIT_STRING_SIZE)(s)'", "'>::type'", ".", "format", "(", "'::boost::metaparse::v{0}::impl'", ".", "format", "(", "VERSION", ")", ",", "macro_name", "(", "'I'", ")", ")", ")", ")", "out_f", ".", "write", "(", "'\\n'", ")", "for", "limit", "in", "xrange", "(", "0", ",", "max_limit", "+", "1", ")", ":", "out_f", ".", "write", "(", "'#define {0} {1}\\n'", ".", "format", "(", "macro_name", "(", "'I{0}'", ".", "format", "(", "limit", ")", ")", ",", "macro_name", "(", "'INDEX_STR{0}'", ".", "format", "(", "min", "(", "int", "(", "l", ")", "for", "l", "in", "limits", "if", "int", "(", "l", ")", ">=", "limit", ")", ")", ")", ")", ")", "out_f", ".", "write", "(", "'\\n'", ")", "prev_macro", "=", "None", "prev_limit", "=", "0", "for", "length_limit", "in", "(", "int", "(", "l", ")", "for", "l", "in", "limits", ")", ":", "this_macro", "=", "macro_name", "(", "'INDEX_STR{0}'", ".", "format", "(", "length_limit", ")", ")", "out_f", ".", "write", "(", "'#define {0}(s) {1}{2}\\n'", ".", "format", "(", "this_macro", ",", "'{0}(s),'", ".", "format", "(", "prev_macro", ")", "if", "prev_macro", "else", "''", ",", "','", ".", "join", "(", "'{0}((s), {1})'", ".", "format", "(", "macro_name", "(", "'STRING_AT'", ")", ",", "i", ")", "for", "i", "in", "xrange", "(", "prev_limit", ",", "length_limit", ")", ")", ")", ")", "prev_macro", "=", "this_macro", "prev_limit", "=", "length_limit" ]
Generate string.hpp
[ "Generate", "string", ".", "hpp" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/metaparse/tools/string_headers.py#L202-L275
29,008
apple/turicreate
deps/src/boost_1_68_0/libs/metaparse/tools/string_headers.py
existing_path
def existing_path(value): """Throws when the path does not exist""" if os.path.exists(value): return value else: raise argparse.ArgumentTypeError("Path {0} not found".format(value))
python
def existing_path(value): """Throws when the path does not exist""" if os.path.exists(value): return value else: raise argparse.ArgumentTypeError("Path {0} not found".format(value))
[ "def", "existing_path", "(", "value", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "value", ")", ":", "return", "value", "else", ":", "raise", "argparse", ".", "ArgumentTypeError", "(", "\"Path {0} not found\"", ".", "format", "(", "value", ")", ")" ]
Throws when the path does not exist
[ "Throws", "when", "the", "path", "does", "not", "exist" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/metaparse/tools/string_headers.py#L287-L292
29,009
apple/turicreate
deps/src/boost_1_68_0/libs/metaparse/tools/string_headers.py
Namespace.end
def end(self): """Generate the closing part""" for depth in xrange(len(self.names) - 1, -1, -1): self.out_f.write('{0}}}\n'.format(self.prefix(depth)))
python
def end(self): """Generate the closing part""" for depth in xrange(len(self.names) - 1, -1, -1): self.out_f.write('{0}}}\n'.format(self.prefix(depth)))
[ "def", "end", "(", "self", ")", ":", "for", "depth", "in", "xrange", "(", "len", "(", "self", ".", "names", ")", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "self", ".", "out_f", ".", "write", "(", "'{0}}}\\n'", ".", "format", "(", "self", ".", "prefix", "(", "depth", ")", ")", ")" ]
Generate the closing part
[ "Generate", "the", "closing", "part" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/metaparse/tools/string_headers.py#L33-L36
29,010
apple/turicreate
src/unity/python/turicreate/toolkits/sound_classifier/sound_classifier.py
get_deep_features
def get_deep_features(audio_data, verbose=True): ''' Calculates the deep features used by the Sound Classifier. Internally the Sound Classifier calculates deep features for both model creation and predictions. If the same data will be used multiple times, calculating the deep features just once will result in a significant speed up. Parameters ---------- audio_data : SArray Audio data is represented as dicts with key 'data' and 'sample_rate', see `turicreate.load_audio(...)`. Examples -------- >>> my_audio_data['deep_features'] = get_deep_features(my_audio_data['audio']) >>> train, test = my_audio_data.random_split(.8) >>> model = tc.sound_classifier.create(train, 'label', 'deep_features') >>> predictions = model.predict(test) ''' from ._audio_feature_extractor import _get_feature_extractor if not _is_audio_data_sarray(audio_data): raise TypeError("Input must be audio data") feature_extractor_name = 'VGGish' feature_extractor = _get_feature_extractor(feature_extractor_name) return feature_extractor.get_deep_features(audio_data, verbose=verbose)
python
def get_deep_features(audio_data, verbose=True): ''' Calculates the deep features used by the Sound Classifier. Internally the Sound Classifier calculates deep features for both model creation and predictions. If the same data will be used multiple times, calculating the deep features just once will result in a significant speed up. Parameters ---------- audio_data : SArray Audio data is represented as dicts with key 'data' and 'sample_rate', see `turicreate.load_audio(...)`. Examples -------- >>> my_audio_data['deep_features'] = get_deep_features(my_audio_data['audio']) >>> train, test = my_audio_data.random_split(.8) >>> model = tc.sound_classifier.create(train, 'label', 'deep_features') >>> predictions = model.predict(test) ''' from ._audio_feature_extractor import _get_feature_extractor if not _is_audio_data_sarray(audio_data): raise TypeError("Input must be audio data") feature_extractor_name = 'VGGish' feature_extractor = _get_feature_extractor(feature_extractor_name) return feature_extractor.get_deep_features(audio_data, verbose=verbose)
[ "def", "get_deep_features", "(", "audio_data", ",", "verbose", "=", "True", ")", ":", "from", ".", "_audio_feature_extractor", "import", "_get_feature_extractor", "if", "not", "_is_audio_data_sarray", "(", "audio_data", ")", ":", "raise", "TypeError", "(", "\"Input must be audio data\"", ")", "feature_extractor_name", "=", "'VGGish'", "feature_extractor", "=", "_get_feature_extractor", "(", "feature_extractor_name", ")", "return", "feature_extractor", ".", "get_deep_features", "(", "audio_data", ",", "verbose", "=", "verbose", ")" ]
Calculates the deep features used by the Sound Classifier. Internally the Sound Classifier calculates deep features for both model creation and predictions. If the same data will be used multiple times, calculating the deep features just once will result in a significant speed up. Parameters ---------- audio_data : SArray Audio data is represented as dicts with key 'data' and 'sample_rate', see `turicreate.load_audio(...)`. Examples -------- >>> my_audio_data['deep_features'] = get_deep_features(my_audio_data['audio']) >>> train, test = my_audio_data.random_split(.8) >>> model = tc.sound_classifier.create(train, 'label', 'deep_features') >>> predictions = model.predict(test)
[ "Calculates", "the", "deep", "features", "used", "by", "the", "Sound", "Classifier", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/sound_classifier/sound_classifier.py#L45-L75
29,011
apple/turicreate
src/unity/python/turicreate/toolkits/sound_classifier/sound_classifier.py
SoundClassifier._load_version
def _load_version(cls, state, version): """ A function to load a previously saved SoundClassifier instance. """ from ._audio_feature_extractor import _get_feature_extractor from .._mxnet import _mxnet_utils state['_feature_extractor'] = _get_feature_extractor(state['feature_extractor_name']) # Load the custom nerual network num_classes = state['num_classes'] num_inputs = state['_feature_extractor'].output_length if 'custom_layer_sizes' in state: # These are deserialized as floats custom_layer_sizes = list(map(int, state['custom_layer_sizes'])) else: # Default value, was not part of state for only Turi Create 5.4 custom_layer_sizes = [100, 100] state['custom_layer_sizes'] = custom_layer_sizes net = SoundClassifier._build_custom_neural_network(num_inputs, num_classes, custom_layer_sizes) net_params = net.collect_params() ctx = _mxnet_utils.get_mxnet_context() _mxnet_utils.load_net_params_from_state(net_params, state['_custom_classifier'], ctx=ctx) state['_custom_classifier'] = net return SoundClassifier(state)
python
def _load_version(cls, state, version): """ A function to load a previously saved SoundClassifier instance. """ from ._audio_feature_extractor import _get_feature_extractor from .._mxnet import _mxnet_utils state['_feature_extractor'] = _get_feature_extractor(state['feature_extractor_name']) # Load the custom nerual network num_classes = state['num_classes'] num_inputs = state['_feature_extractor'].output_length if 'custom_layer_sizes' in state: # These are deserialized as floats custom_layer_sizes = list(map(int, state['custom_layer_sizes'])) else: # Default value, was not part of state for only Turi Create 5.4 custom_layer_sizes = [100, 100] state['custom_layer_sizes'] = custom_layer_sizes net = SoundClassifier._build_custom_neural_network(num_inputs, num_classes, custom_layer_sizes) net_params = net.collect_params() ctx = _mxnet_utils.get_mxnet_context() _mxnet_utils.load_net_params_from_state(net_params, state['_custom_classifier'], ctx=ctx) state['_custom_classifier'] = net return SoundClassifier(state)
[ "def", "_load_version", "(", "cls", ",", "state", ",", "version", ")", ":", "from", ".", "_audio_feature_extractor", "import", "_get_feature_extractor", "from", ".", ".", "_mxnet", "import", "_mxnet_utils", "state", "[", "'_feature_extractor'", "]", "=", "_get_feature_extractor", "(", "state", "[", "'feature_extractor_name'", "]", ")", "# Load the custom nerual network", "num_classes", "=", "state", "[", "'num_classes'", "]", "num_inputs", "=", "state", "[", "'_feature_extractor'", "]", ".", "output_length", "if", "'custom_layer_sizes'", "in", "state", ":", "# These are deserialized as floats", "custom_layer_sizes", "=", "list", "(", "map", "(", "int", ",", "state", "[", "'custom_layer_sizes'", "]", ")", ")", "else", ":", "# Default value, was not part of state for only Turi Create 5.4", "custom_layer_sizes", "=", "[", "100", ",", "100", "]", "state", "[", "'custom_layer_sizes'", "]", "=", "custom_layer_sizes", "net", "=", "SoundClassifier", ".", "_build_custom_neural_network", "(", "num_inputs", ",", "num_classes", ",", "custom_layer_sizes", ")", "net_params", "=", "net", ".", "collect_params", "(", ")", "ctx", "=", "_mxnet_utils", ".", "get_mxnet_context", "(", ")", "_mxnet_utils", ".", "load_net_params_from_state", "(", "net_params", ",", "state", "[", "'_custom_classifier'", "]", ",", "ctx", "=", "ctx", ")", "state", "[", "'_custom_classifier'", "]", "=", "net", "return", "SoundClassifier", "(", "state", ")" ]
A function to load a previously saved SoundClassifier instance.
[ "A", "function", "to", "load", "a", "previously", "saved", "SoundClassifier", "instance", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/sound_classifier/sound_classifier.py#L363-L388
29,012
apple/turicreate
src/unity/python/turicreate/toolkits/sound_classifier/sound_classifier.py
SoundClassifier.classify
def classify(self, dataset, verbose=True, batch_size=64): """ Return the classification for each examples in the ``dataset``. The output SFrame contains predicted class labels and its probability. Parameters ---------- dataset : SFrame | SArray | dict The audio data to be classified. If dataset is an SFrame, it must have a column with the same name as the feature used for model training, but does not require a target column. Additional columns are ignored. verbose : bool, optional If True, prints progress updates and model details. batch_size : int, optional If you are getting memory errors, try decreasing this value. If you have a powerful computer, increasing this value may improve performance. Returns ------- out : SFrame An SFrame with model predictions, both class labels and probabilities. See Also ---------- create, evaluate, predict Examples ---------- >>> classes = model.classify(data) """ prob_vector = self.predict(dataset, output_type='probability_vector', verbose=verbose, batch_size=batch_size) id_to_label = self._id_to_class_label return _tc.SFrame({ 'class': prob_vector.apply(lambda v: id_to_label[_np.argmax(v)]), 'probability': prob_vector.apply(_np.max) })
python
def classify(self, dataset, verbose=True, batch_size=64): """ Return the classification for each examples in the ``dataset``. The output SFrame contains predicted class labels and its probability. Parameters ---------- dataset : SFrame | SArray | dict The audio data to be classified. If dataset is an SFrame, it must have a column with the same name as the feature used for model training, but does not require a target column. Additional columns are ignored. verbose : bool, optional If True, prints progress updates and model details. batch_size : int, optional If you are getting memory errors, try decreasing this value. If you have a powerful computer, increasing this value may improve performance. Returns ------- out : SFrame An SFrame with model predictions, both class labels and probabilities. See Also ---------- create, evaluate, predict Examples ---------- >>> classes = model.classify(data) """ prob_vector = self.predict(dataset, output_type='probability_vector', verbose=verbose, batch_size=batch_size) id_to_label = self._id_to_class_label return _tc.SFrame({ 'class': prob_vector.apply(lambda v: id_to_label[_np.argmax(v)]), 'probability': prob_vector.apply(_np.max) })
[ "def", "classify", "(", "self", ",", "dataset", ",", "verbose", "=", "True", ",", "batch_size", "=", "64", ")", ":", "prob_vector", "=", "self", ".", "predict", "(", "dataset", ",", "output_type", "=", "'probability_vector'", ",", "verbose", "=", "verbose", ",", "batch_size", "=", "batch_size", ")", "id_to_label", "=", "self", ".", "_id_to_class_label", "return", "_tc", ".", "SFrame", "(", "{", "'class'", ":", "prob_vector", ".", "apply", "(", "lambda", "v", ":", "id_to_label", "[", "_np", ".", "argmax", "(", "v", ")", "]", ")", ",", "'probability'", ":", "prob_vector", ".", "apply", "(", "_np", ".", "max", ")", "}", ")" ]
Return the classification for each examples in the ``dataset``. The output SFrame contains predicted class labels and its probability. Parameters ---------- dataset : SFrame | SArray | dict The audio data to be classified. If dataset is an SFrame, it must have a column with the same name as the feature used for model training, but does not require a target column. Additional columns are ignored. verbose : bool, optional If True, prints progress updates and model details. batch_size : int, optional If you are getting memory errors, try decreasing this value. If you have a powerful computer, increasing this value may improve performance. Returns ------- out : SFrame An SFrame with model predictions, both class labels and probabilities. See Also ---------- create, evaluate, predict Examples ---------- >>> classes = model.classify(data)
[ "Return", "the", "classification", "for", "each", "examples", "in", "the", "dataset", ".", "The", "output", "SFrame", "contains", "predicted", "class", "labels", "and", "its", "probability", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/sound_classifier/sound_classifier.py#L447-L487
29,013
apple/turicreate
src/unity/python/turicreate/toolkits/_mxnet/_mx_sframe_iter.py
_init_data
def _init_data(data, allow_empty, default_name): """Convert data into canonical form.""" assert (data is not None) or allow_empty if data is None: data = [] if isinstance(data, (np.ndarray, NDArray)): data = [data] if isinstance(data, list): if not allow_empty: assert(len(data) > 0) if len(data) == 1: data = OrderedDict([(default_name, data[0])]) else: data = OrderedDict([('_%d_%s' % (i, default_name), d) for i, d in enumerate(data)]) if not isinstance(data, dict): raise TypeError("Input must be NDArray, numpy.ndarray, " + \ "a list of them or dict with them as values") for k, v in data.items(): if isinstance(v, NDArray): data[k] = v.asnumpy() for k, v in data.items(): if not isinstance(v, np.ndarray): raise TypeError(("Invalid type '%s' for %s, " % (type(v), k)) + \ "should be NDArray or numpy.ndarray") return list(data.items())
python
def _init_data(data, allow_empty, default_name): """Convert data into canonical form.""" assert (data is not None) or allow_empty if data is None: data = [] if isinstance(data, (np.ndarray, NDArray)): data = [data] if isinstance(data, list): if not allow_empty: assert(len(data) > 0) if len(data) == 1: data = OrderedDict([(default_name, data[0])]) else: data = OrderedDict([('_%d_%s' % (i, default_name), d) for i, d in enumerate(data)]) if not isinstance(data, dict): raise TypeError("Input must be NDArray, numpy.ndarray, " + \ "a list of them or dict with them as values") for k, v in data.items(): if isinstance(v, NDArray): data[k] = v.asnumpy() for k, v in data.items(): if not isinstance(v, np.ndarray): raise TypeError(("Invalid type '%s' for %s, " % (type(v), k)) + \ "should be NDArray or numpy.ndarray") return list(data.items())
[ "def", "_init_data", "(", "data", ",", "allow_empty", ",", "default_name", ")", ":", "assert", "(", "data", "is", "not", "None", ")", "or", "allow_empty", "if", "data", "is", "None", ":", "data", "=", "[", "]", "if", "isinstance", "(", "data", ",", "(", "np", ".", "ndarray", ",", "NDArray", ")", ")", ":", "data", "=", "[", "data", "]", "if", "isinstance", "(", "data", ",", "list", ")", ":", "if", "not", "allow_empty", ":", "assert", "(", "len", "(", "data", ")", ">", "0", ")", "if", "len", "(", "data", ")", "==", "1", ":", "data", "=", "OrderedDict", "(", "[", "(", "default_name", ",", "data", "[", "0", "]", ")", "]", ")", "else", ":", "data", "=", "OrderedDict", "(", "[", "(", "'_%d_%s'", "%", "(", "i", ",", "default_name", ")", ",", "d", ")", "for", "i", ",", "d", "in", "enumerate", "(", "data", ")", "]", ")", "if", "not", "isinstance", "(", "data", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"Input must be NDArray, numpy.ndarray, \"", "+", "\"a list of them or dict with them as values\"", ")", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "NDArray", ")", ":", "data", "[", "k", "]", "=", "v", ".", "asnumpy", "(", ")", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", ":", "if", "not", "isinstance", "(", "v", ",", "np", ".", "ndarray", ")", ":", "raise", "TypeError", "(", "(", "\"Invalid type '%s' for %s, \"", "%", "(", "type", "(", "v", ")", ",", "k", ")", ")", "+", "\"should be NDArray or numpy.ndarray\"", ")", "return", "list", "(", "data", ".", "items", "(", ")", ")" ]
Convert data into canonical form.
[ "Convert", "data", "into", "canonical", "form", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mx_sframe_iter.py#L37-L62
29,014
apple/turicreate
src/unity/python/turicreate/toolkits/_mxnet/_mx_sframe_iter.py
SFrameIter.provide_data
def provide_data(self): """The name and shape of data provided by this iterator""" return [(k, tuple([self.batch_size] + list(v.shape[1:]))) for k, v in self.data]
python
def provide_data(self): """The name and shape of data provided by this iterator""" return [(k, tuple([self.batch_size] + list(v.shape[1:]))) for k, v in self.data]
[ "def", "provide_data", "(", "self", ")", ":", "return", "[", "(", "k", ",", "tuple", "(", "[", "self", ".", "batch_size", "]", "+", "list", "(", "v", ".", "shape", "[", "1", ":", "]", ")", ")", ")", "for", "k", ",", "v", "in", "self", ".", "data", "]" ]
The name and shape of data provided by this iterator
[ "The", "name", "and", "shape", "of", "data", "provided", "by", "this", "iterator" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mx_sframe_iter.py#L134-L136
29,015
apple/turicreate
src/unity/python/turicreate/toolkits/_mxnet/_mx_sframe_iter.py
SFrameIter.provide_label
def provide_label(self): """The name and shape of label provided by this iterator""" return [(k, tuple([self.batch_size] + list(v.shape[1:]))) for k, v in self.label]
python
def provide_label(self): """The name and shape of label provided by this iterator""" return [(k, tuple([self.batch_size] + list(v.shape[1:]))) for k, v in self.label]
[ "def", "provide_label", "(", "self", ")", ":", "return", "[", "(", "k", ",", "tuple", "(", "[", "self", ".", "batch_size", "]", "+", "list", "(", "v", ".", "shape", "[", "1", ":", "]", ")", ")", ")", "for", "k", ",", "v", "in", "self", ".", "label", "]" ]
The name and shape of label provided by this iterator
[ "The", "name", "and", "shape", "of", "label", "provided", "by", "this", "iterator" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mx_sframe_iter.py#L139-L141
29,016
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/generators.py
register
def register (g): """ Registers new generator instance 'g'. """ assert isinstance(g, Generator) id = g.id() __generators [id] = g # A generator can produce several targets of the # same type. We want unique occurence of that generator # in .generators.$(t) in that case, otherwise, it will # be tried twice and we'll get false ambiguity. for t in sequence.unique(g.target_types()): __type_to_generators.setdefault(t, []).append(g) # Update the set of generators for toolset # TODO: should we check that generator with this id # is not already registered. For example, the fop.jam # module intentionally declared two generators with the # same id, so such check will break it. # Some generators have multiple periods in their name, so the # normal $(id:S=) won't generate the right toolset name. # e.g. if id = gcc.compile.c++, then # .generators-for-toolset.$(id:S=) will append to # .generators-for-toolset.gcc.compile, which is a separate # value from .generators-for-toolset.gcc. Correcting this # makes generator inheritance work properly. # See also inherit-generators in module toolset base = id.split ('.', 100) [0] __generators_for_toolset.setdefault(base, []).append(g) # After adding a new generator that can construct new target types, we need # to clear the related cached viable source target type information for # constructing a specific target type or using a specific generator. Cached # viable source target type lists affected by this are those containing any # of the target types constructed by the new generator or any of their base # target types. # # A more advanced alternative to clearing that cached viable source target # type information would be to expand it with additional source types or # even better - mark it as needing to be expanded on next use. # # For now we just clear all the cached viable source target type information # that does not simply state 'all types' and may implement a more detailed # algorithm later on if it becomes needed. invalidate_extendable_viable_source_target_type_cache()
python
def register (g): """ Registers new generator instance 'g'. """ assert isinstance(g, Generator) id = g.id() __generators [id] = g # A generator can produce several targets of the # same type. We want unique occurence of that generator # in .generators.$(t) in that case, otherwise, it will # be tried twice and we'll get false ambiguity. for t in sequence.unique(g.target_types()): __type_to_generators.setdefault(t, []).append(g) # Update the set of generators for toolset # TODO: should we check that generator with this id # is not already registered. For example, the fop.jam # module intentionally declared two generators with the # same id, so such check will break it. # Some generators have multiple periods in their name, so the # normal $(id:S=) won't generate the right toolset name. # e.g. if id = gcc.compile.c++, then # .generators-for-toolset.$(id:S=) will append to # .generators-for-toolset.gcc.compile, which is a separate # value from .generators-for-toolset.gcc. Correcting this # makes generator inheritance work properly. # See also inherit-generators in module toolset base = id.split ('.', 100) [0] __generators_for_toolset.setdefault(base, []).append(g) # After adding a new generator that can construct new target types, we need # to clear the related cached viable source target type information for # constructing a specific target type or using a specific generator. Cached # viable source target type lists affected by this are those containing any # of the target types constructed by the new generator or any of their base # target types. # # A more advanced alternative to clearing that cached viable source target # type information would be to expand it with additional source types or # even better - mark it as needing to be expanded on next use. # # For now we just clear all the cached viable source target type information # that does not simply state 'all types' and may implement a more detailed # algorithm later on if it becomes needed. invalidate_extendable_viable_source_target_type_cache()
[ "def", "register", "(", "g", ")", ":", "assert", "isinstance", "(", "g", ",", "Generator", ")", "id", "=", "g", ".", "id", "(", ")", "__generators", "[", "id", "]", "=", "g", "# A generator can produce several targets of the", "# same type. We want unique occurence of that generator", "# in .generators.$(t) in that case, otherwise, it will", "# be tried twice and we'll get false ambiguity.", "for", "t", "in", "sequence", ".", "unique", "(", "g", ".", "target_types", "(", ")", ")", ":", "__type_to_generators", ".", "setdefault", "(", "t", ",", "[", "]", ")", ".", "append", "(", "g", ")", "# Update the set of generators for toolset", "# TODO: should we check that generator with this id", "# is not already registered. For example, the fop.jam", "# module intentionally declared two generators with the", "# same id, so such check will break it.", "# Some generators have multiple periods in their name, so the", "# normal $(id:S=) won't generate the right toolset name.", "# e.g. if id = gcc.compile.c++, then", "# .generators-for-toolset.$(id:S=) will append to", "# .generators-for-toolset.gcc.compile, which is a separate", "# value from .generators-for-toolset.gcc. Correcting this", "# makes generator inheritance work properly.", "# See also inherit-generators in module toolset", "base", "=", "id", ".", "split", "(", "'.'", ",", "100", ")", "[", "0", "]", "__generators_for_toolset", ".", "setdefault", "(", "base", ",", "[", "]", ")", ".", "append", "(", "g", ")", "# After adding a new generator that can construct new target types, we need", "# to clear the related cached viable source target type information for", "# constructing a specific target type or using a specific generator. Cached", "# viable source target type lists affected by this are those containing any", "# of the target types constructed by the new generator or any of their base", "# target types.", "#", "# A more advanced alternative to clearing that cached viable source target", "# type information would be to expand it with additional source types or", "# even better - mark it as needing to be expanded on next use.", "#", "# For now we just clear all the cached viable source target type information", "# that does not simply state 'all types' and may implement a more detailed", "# algorithm later on if it becomes needed.", "invalidate_extendable_viable_source_target_type_cache", "(", ")" ]
Registers new generator instance 'g'.
[ "Registers", "new", "generator", "instance", "g", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/generators.py#L657-L706
29,017
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/generators.py
override
def override (overrider_id, overridee_id): """Make generator 'overrider-id' be preferred to 'overridee-id'. If, when searching for generators that could produce a target of certain type, both those generators are amoung viable generators, the overridden generator is immediately discarded. The overridden generators are discarded immediately after computing the list of viable generators, before running any of them.""" assert isinstance(overrider_id, basestring) assert isinstance(overridee_id, basestring) __overrides.setdefault(overrider_id, []).append(overridee_id)
python
def override (overrider_id, overridee_id): """Make generator 'overrider-id' be preferred to 'overridee-id'. If, when searching for generators that could produce a target of certain type, both those generators are amoung viable generators, the overridden generator is immediately discarded. The overridden generators are discarded immediately after computing the list of viable generators, before running any of them.""" assert isinstance(overrider_id, basestring) assert isinstance(overridee_id, basestring) __overrides.setdefault(overrider_id, []).append(overridee_id)
[ "def", "override", "(", "overrider_id", ",", "overridee_id", ")", ":", "assert", "isinstance", "(", "overrider_id", ",", "basestring", ")", "assert", "isinstance", "(", "overridee_id", ",", "basestring", ")", "__overrides", ".", "setdefault", "(", "overrider_id", ",", "[", "]", ")", ".", "append", "(", "overridee_id", ")" ]
Make generator 'overrider-id' be preferred to 'overridee-id'. If, when searching for generators that could produce a target of certain type, both those generators are amoung viable generators, the overridden generator is immediately discarded. The overridden generators are discarded immediately after computing the list of viable generators, before running any of them.
[ "Make", "generator", "overrider", "-", "id", "be", "preferred", "to", "overridee", "-", "id", ".", "If", "when", "searching", "for", "generators", "that", "could", "produce", "a", "target", "of", "certain", "type", "both", "those", "generators", "are", "amoung", "viable", "generators", "the", "overridden", "generator", "is", "immediately", "discarded", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/generators.py#L747-L760
29,018
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/generators.py
__viable_source_types_real
def __viable_source_types_real (target_type): """ Returns a list of source type which can possibly be converted to 'target_type' by some chain of generator invocation. More formally, takes all generators for 'target_type' and returns union of source types for those generators and result of calling itself recusrively on source types. """ assert isinstance(target_type, basestring) generators = [] # 't0' is the initial list of target types we need to process to get a list # of their viable source target types. New target types will not be added to # this list. t0 = type.all_bases (target_type) # 't' is the list of target types which have not yet been processed to get a # list of their viable source target types. This list will get expanded as # we locate more target types to process. t = t0 result = [] while t: # Find all generators for current type. # Unlike 'find_viable_generators' we don't care about prop_set. generators = __type_to_generators.get (t [0], []) t = t[1:] for g in generators: if not g.source_types(): # Empty source types -- everything can be accepted result = "*" # This will terminate outer loop. t = None break for source_type in g.source_types (): if not source_type in result: # If generator accepts 'source_type' it # will happily accept any type derived from it all = type.all_derived (source_type) for n in all: if not n in result: # Here there is no point in adding target types to # the list of types to process in case they are or # have already been on that list. We optimize this # check by realizing that we only need to avoid the # original target type's base types. Other target # types that are or have been on the list of target # types to process have been added to the 'result' # list as well and have thus already been eliminated # by the previous if. if not n in t0: t.append (n) result.append (n) return result
python
def __viable_source_types_real (target_type): """ Returns a list of source type which can possibly be converted to 'target_type' by some chain of generator invocation. More formally, takes all generators for 'target_type' and returns union of source types for those generators and result of calling itself recusrively on source types. """ assert isinstance(target_type, basestring) generators = [] # 't0' is the initial list of target types we need to process to get a list # of their viable source target types. New target types will not be added to # this list. t0 = type.all_bases (target_type) # 't' is the list of target types which have not yet been processed to get a # list of their viable source target types. This list will get expanded as # we locate more target types to process. t = t0 result = [] while t: # Find all generators for current type. # Unlike 'find_viable_generators' we don't care about prop_set. generators = __type_to_generators.get (t [0], []) t = t[1:] for g in generators: if not g.source_types(): # Empty source types -- everything can be accepted result = "*" # This will terminate outer loop. t = None break for source_type in g.source_types (): if not source_type in result: # If generator accepts 'source_type' it # will happily accept any type derived from it all = type.all_derived (source_type) for n in all: if not n in result: # Here there is no point in adding target types to # the list of types to process in case they are or # have already been on that list. We optimize this # check by realizing that we only need to avoid the # original target type's base types. Other target # types that are or have been on the list of target # types to process have been added to the 'result' # list as well and have thus already been eliminated # by the previous if. if not n in t0: t.append (n) result.append (n) return result
[ "def", "__viable_source_types_real", "(", "target_type", ")", ":", "assert", "isinstance", "(", "target_type", ",", "basestring", ")", "generators", "=", "[", "]", "# 't0' is the initial list of target types we need to process to get a list", "# of their viable source target types. New target types will not be added to", "# this list.", "t0", "=", "type", ".", "all_bases", "(", "target_type", ")", "# 't' is the list of target types which have not yet been processed to get a", "# list of their viable source target types. This list will get expanded as", "# we locate more target types to process.", "t", "=", "t0", "result", "=", "[", "]", "while", "t", ":", "# Find all generators for current type.", "# Unlike 'find_viable_generators' we don't care about prop_set.", "generators", "=", "__type_to_generators", ".", "get", "(", "t", "[", "0", "]", ",", "[", "]", ")", "t", "=", "t", "[", "1", ":", "]", "for", "g", "in", "generators", ":", "if", "not", "g", ".", "source_types", "(", ")", ":", "# Empty source types -- everything can be accepted", "result", "=", "\"*\"", "# This will terminate outer loop.", "t", "=", "None", "break", "for", "source_type", "in", "g", ".", "source_types", "(", ")", ":", "if", "not", "source_type", "in", "result", ":", "# If generator accepts 'source_type' it", "# will happily accept any type derived from it", "all", "=", "type", ".", "all_derived", "(", "source_type", ")", "for", "n", "in", "all", ":", "if", "not", "n", "in", "result", ":", "# Here there is no point in adding target types to", "# the list of types to process in case they are or", "# have already been on that list. We optimize this", "# check by realizing that we only need to avoid the", "# original target type's base types. Other target", "# types that are or have been on the list of target", "# types to process have been added to the 'result'", "# list as well and have thus already been eliminated", "# by the previous if.", "if", "not", "n", "in", "t0", ":", "t", ".", "append", "(", "n", ")", "result", ".", "append", "(", "n", ")", "return", "result" ]
Returns a list of source type which can possibly be converted to 'target_type' by some chain of generator invocation. More formally, takes all generators for 'target_type' and returns union of source types for those generators and result of calling itself recusrively on source types.
[ "Returns", "a", "list", "of", "source", "type", "which", "can", "possibly", "be", "converted", "to", "target_type", "by", "some", "chain", "of", "generator", "invocation", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/generators.py#L762-L820
29,019
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/generators.py
viable_source_types_for_generator
def viable_source_types_for_generator (generator): """ Caches the result of 'viable_source_types_for_generator'. """ assert isinstance(generator, Generator) if generator not in __viable_source_types_cache: __vstg_cached_generators.append(generator) __viable_source_types_cache[generator] = viable_source_types_for_generator_real (generator) return __viable_source_types_cache[generator]
python
def viable_source_types_for_generator (generator): """ Caches the result of 'viable_source_types_for_generator'. """ assert isinstance(generator, Generator) if generator not in __viable_source_types_cache: __vstg_cached_generators.append(generator) __viable_source_types_cache[generator] = viable_source_types_for_generator_real (generator) return __viable_source_types_cache[generator]
[ "def", "viable_source_types_for_generator", "(", "generator", ")", ":", "assert", "isinstance", "(", "generator", ",", "Generator", ")", "if", "generator", "not", "in", "__viable_source_types_cache", ":", "__vstg_cached_generators", ".", "append", "(", "generator", ")", "__viable_source_types_cache", "[", "generator", "]", "=", "viable_source_types_for_generator_real", "(", "generator", ")", "return", "__viable_source_types_cache", "[", "generator", "]" ]
Caches the result of 'viable_source_types_for_generator'.
[ "Caches", "the", "result", "of", "viable_source_types_for_generator", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/generators.py#L859-L867
29,020
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/generators.py
try_one_generator_really
def try_one_generator_really (project, name, generator, target_type, properties, sources): """ Returns usage requirements + list of created targets. """ if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or name is None assert isinstance(generator, Generator) assert isinstance(target_type, basestring) assert isinstance(properties, property_set.PropertySet) assert is_iterable_typed(sources, virtual_target.VirtualTarget) targets = generator.run (project, name, properties, sources) usage_requirements = [] success = False dout("returned " + str(targets)) if targets: success = True; if isinstance (targets[0], property_set.PropertySet): usage_requirements = targets [0] targets = targets [1] else: usage_requirements = property_set.empty () dout( " generator" + generator.id() + " spawned ") # generators.dout [ indent ] " " $(targets) ; # if $(usage-requirements) # { # generators.dout [ indent ] " with usage requirements:" $(x) ; # } if success: return (usage_requirements, targets) else: return None
python
def try_one_generator_really (project, name, generator, target_type, properties, sources): """ Returns usage requirements + list of created targets. """ if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or name is None assert isinstance(generator, Generator) assert isinstance(target_type, basestring) assert isinstance(properties, property_set.PropertySet) assert is_iterable_typed(sources, virtual_target.VirtualTarget) targets = generator.run (project, name, properties, sources) usage_requirements = [] success = False dout("returned " + str(targets)) if targets: success = True; if isinstance (targets[0], property_set.PropertySet): usage_requirements = targets [0] targets = targets [1] else: usage_requirements = property_set.empty () dout( " generator" + generator.id() + " spawned ") # generators.dout [ indent ] " " $(targets) ; # if $(usage-requirements) # { # generators.dout [ indent ] " with usage requirements:" $(x) ; # } if success: return (usage_requirements, targets) else: return None
[ "def", "try_one_generator_really", "(", "project", ",", "name", ",", "generator", ",", "target_type", ",", "properties", ",", "sources", ")", ":", "if", "__debug__", ":", "from", ".", "targets", "import", "ProjectTarget", "assert", "isinstance", "(", "project", ",", "ProjectTarget", ")", "assert", "isinstance", "(", "name", ",", "basestring", ")", "or", "name", "is", "None", "assert", "isinstance", "(", "generator", ",", "Generator", ")", "assert", "isinstance", "(", "target_type", ",", "basestring", ")", "assert", "isinstance", "(", "properties", ",", "property_set", ".", "PropertySet", ")", "assert", "is_iterable_typed", "(", "sources", ",", "virtual_target", ".", "VirtualTarget", ")", "targets", "=", "generator", ".", "run", "(", "project", ",", "name", ",", "properties", ",", "sources", ")", "usage_requirements", "=", "[", "]", "success", "=", "False", "dout", "(", "\"returned \"", "+", "str", "(", "targets", ")", ")", "if", "targets", ":", "success", "=", "True", "if", "isinstance", "(", "targets", "[", "0", "]", ",", "property_set", ".", "PropertySet", ")", ":", "usage_requirements", "=", "targets", "[", "0", "]", "targets", "=", "targets", "[", "1", "]", "else", ":", "usage_requirements", "=", "property_set", ".", "empty", "(", ")", "dout", "(", "\" generator\"", "+", "generator", ".", "id", "(", ")", "+", "\" spawned \"", ")", "# generators.dout [ indent ] \" \" $(targets) ;", "# if $(usage-requirements)", "# {", "# generators.dout [ indent ] \" with usage requirements:\" $(x) ;", "# }", "if", "success", ":", "return", "(", "usage_requirements", ",", "targets", ")", "else", ":", "return", "None" ]
Returns usage requirements + list of created targets.
[ "Returns", "usage", "requirements", "+", "list", "of", "created", "targets", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/generators.py#L869-L907
29,021
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/generators.py
try_one_generator
def try_one_generator (project, name, generator, target_type, properties, sources): """ Checks if generator invocation can be pruned, because it's guaranteed to fail. If so, quickly returns empty list. Otherwise, calls try_one_generator_really. """ if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or name is None assert isinstance(generator, Generator) assert isinstance(target_type, basestring) assert isinstance(properties, property_set.PropertySet) assert is_iterable_typed(sources, virtual_target.VirtualTarget) source_types = [] for s in sources: source_types.append (s.type ()) viable_source_types = viable_source_types_for_generator (generator) if source_types and viable_source_types != ['*'] and\ not set_.intersection (source_types, viable_source_types): if project.manager ().logger ().on (): id = generator.id () project.manager ().logger ().log (__name__, "generator '%s' pruned" % id) project.manager ().logger ().log (__name__, "source_types" '%s' % source_types) project.manager ().logger ().log (__name__, "viable_source_types '%s'" % viable_source_types) return [] else: return try_one_generator_really (project, name, generator, target_type, properties, sources)
python
def try_one_generator (project, name, generator, target_type, properties, sources): """ Checks if generator invocation can be pruned, because it's guaranteed to fail. If so, quickly returns empty list. Otherwise, calls try_one_generator_really. """ if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or name is None assert isinstance(generator, Generator) assert isinstance(target_type, basestring) assert isinstance(properties, property_set.PropertySet) assert is_iterable_typed(sources, virtual_target.VirtualTarget) source_types = [] for s in sources: source_types.append (s.type ()) viable_source_types = viable_source_types_for_generator (generator) if source_types and viable_source_types != ['*'] and\ not set_.intersection (source_types, viable_source_types): if project.manager ().logger ().on (): id = generator.id () project.manager ().logger ().log (__name__, "generator '%s' pruned" % id) project.manager ().logger ().log (__name__, "source_types" '%s' % source_types) project.manager ().logger ().log (__name__, "viable_source_types '%s'" % viable_source_types) return [] else: return try_one_generator_really (project, name, generator, target_type, properties, sources)
[ "def", "try_one_generator", "(", "project", ",", "name", ",", "generator", ",", "target_type", ",", "properties", ",", "sources", ")", ":", "if", "__debug__", ":", "from", ".", "targets", "import", "ProjectTarget", "assert", "isinstance", "(", "project", ",", "ProjectTarget", ")", "assert", "isinstance", "(", "name", ",", "basestring", ")", "or", "name", "is", "None", "assert", "isinstance", "(", "generator", ",", "Generator", ")", "assert", "isinstance", "(", "target_type", ",", "basestring", ")", "assert", "isinstance", "(", "properties", ",", "property_set", ".", "PropertySet", ")", "assert", "is_iterable_typed", "(", "sources", ",", "virtual_target", ".", "VirtualTarget", ")", "source_types", "=", "[", "]", "for", "s", "in", "sources", ":", "source_types", ".", "append", "(", "s", ".", "type", "(", ")", ")", "viable_source_types", "=", "viable_source_types_for_generator", "(", "generator", ")", "if", "source_types", "and", "viable_source_types", "!=", "[", "'*'", "]", "and", "not", "set_", ".", "intersection", "(", "source_types", ",", "viable_source_types", ")", ":", "if", "project", ".", "manager", "(", ")", ".", "logger", "(", ")", ".", "on", "(", ")", ":", "id", "=", "generator", ".", "id", "(", ")", "project", ".", "manager", "(", ")", ".", "logger", "(", ")", ".", "log", "(", "__name__", ",", "\"generator '%s' pruned\"", "%", "id", ")", "project", ".", "manager", "(", ")", ".", "logger", "(", ")", ".", "log", "(", "__name__", ",", "\"source_types\"", "'%s'", "%", "source_types", ")", "project", ".", "manager", "(", ")", ".", "logger", "(", ")", ".", "log", "(", "__name__", ",", "\"viable_source_types '%s'\"", "%", "viable_source_types", ")", "return", "[", "]", "else", ":", "return", "try_one_generator_really", "(", "project", ",", "name", ",", "generator", ",", "target_type", ",", "properties", ",", "sources", ")" ]
Checks if generator invocation can be pruned, because it's guaranteed to fail. If so, quickly returns empty list. Otherwise, calls try_one_generator_really.
[ "Checks", "if", "generator", "invocation", "can", "be", "pruned", "because", "it", "s", "guaranteed", "to", "fail", ".", "If", "so", "quickly", "returns", "empty", "list", ".", "Otherwise", "calls", "try_one_generator_really", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/generators.py#L909-L940
29,022
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/generators.py
__ensure_type
def __ensure_type (targets): """ Ensures all 'targets' have types. If this is not so, exists with error. """ assert is_iterable_typed(targets, virtual_target.VirtualTarget) for t in targets: if not t.type (): get_manager().errors()("target '%s' has no type" % str (t))
python
def __ensure_type (targets): """ Ensures all 'targets' have types. If this is not so, exists with error. """ assert is_iterable_typed(targets, virtual_target.VirtualTarget) for t in targets: if not t.type (): get_manager().errors()("target '%s' has no type" % str (t))
[ "def", "__ensure_type", "(", "targets", ")", ":", "assert", "is_iterable_typed", "(", "targets", ",", "virtual_target", ".", "VirtualTarget", ")", "for", "t", "in", "targets", ":", "if", "not", "t", ".", "type", "(", ")", ":", "get_manager", "(", ")", ".", "errors", "(", ")", "(", "\"target '%s' has no type\"", "%", "str", "(", "t", ")", ")" ]
Ensures all 'targets' have types. If this is not so, exists with error.
[ "Ensures", "all", "targets", "have", "types", ".", "If", "this", "is", "not", "so", "exists", "with", "error", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/generators.py#L978-L985
29,023
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/generators.py
__construct_really
def __construct_really (project, name, target_type, prop_set, sources): """ Attempts to construct target by finding viable generators, running them and selecting the dependency graph. """ if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or name is None assert isinstance(target_type, basestring) assert isinstance(prop_set, property_set.PropertySet) assert is_iterable_typed(sources, virtual_target.VirtualTarget) viable_generators = find_viable_generators (target_type, prop_set) result = [] dout(" *** %d viable generators" % len (viable_generators)) generators_that_succeeded = [] for g in viable_generators: __active_generators.append(g) r = try_one_generator (project, name, g, target_type, prop_set, sources) del __active_generators[-1] if r: generators_that_succeeded.append(g) if result: output = cStringIO.StringIO() print >>output, "ambiguity found when searching for best transformation" print >>output, "Trying to produce type '%s' from: " % (target_type) for s in sources: print >>output, " - " + s.str() print >>output, "Generators that succeeded:" for g in generators_that_succeeded: print >>output, " - " + g.id() print >>output, "First generator produced: " for t in result[1:]: print >>output, " - " + str(t) print >>output, "Second generator produced:" for t in r[1:]: print >>output, " - " + str(t) get_manager().errors()(output.getvalue()) else: result = r; return result;
python
def __construct_really (project, name, target_type, prop_set, sources): """ Attempts to construct target by finding viable generators, running them and selecting the dependency graph. """ if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or name is None assert isinstance(target_type, basestring) assert isinstance(prop_set, property_set.PropertySet) assert is_iterable_typed(sources, virtual_target.VirtualTarget) viable_generators = find_viable_generators (target_type, prop_set) result = [] dout(" *** %d viable generators" % len (viable_generators)) generators_that_succeeded = [] for g in viable_generators: __active_generators.append(g) r = try_one_generator (project, name, g, target_type, prop_set, sources) del __active_generators[-1] if r: generators_that_succeeded.append(g) if result: output = cStringIO.StringIO() print >>output, "ambiguity found when searching for best transformation" print >>output, "Trying to produce type '%s' from: " % (target_type) for s in sources: print >>output, " - " + s.str() print >>output, "Generators that succeeded:" for g in generators_that_succeeded: print >>output, " - " + g.id() print >>output, "First generator produced: " for t in result[1:]: print >>output, " - " + str(t) print >>output, "Second generator produced:" for t in r[1:]: print >>output, " - " + str(t) get_manager().errors()(output.getvalue()) else: result = r; return result;
[ "def", "__construct_really", "(", "project", ",", "name", ",", "target_type", ",", "prop_set", ",", "sources", ")", ":", "if", "__debug__", ":", "from", ".", "targets", "import", "ProjectTarget", "assert", "isinstance", "(", "project", ",", "ProjectTarget", ")", "assert", "isinstance", "(", "name", ",", "basestring", ")", "or", "name", "is", "None", "assert", "isinstance", "(", "target_type", ",", "basestring", ")", "assert", "isinstance", "(", "prop_set", ",", "property_set", ".", "PropertySet", ")", "assert", "is_iterable_typed", "(", "sources", ",", "virtual_target", ".", "VirtualTarget", ")", "viable_generators", "=", "find_viable_generators", "(", "target_type", ",", "prop_set", ")", "result", "=", "[", "]", "dout", "(", "\" *** %d viable generators\"", "%", "len", "(", "viable_generators", ")", ")", "generators_that_succeeded", "=", "[", "]", "for", "g", "in", "viable_generators", ":", "__active_generators", ".", "append", "(", "g", ")", "r", "=", "try_one_generator", "(", "project", ",", "name", ",", "g", ",", "target_type", ",", "prop_set", ",", "sources", ")", "del", "__active_generators", "[", "-", "1", "]", "if", "r", ":", "generators_that_succeeded", ".", "append", "(", "g", ")", "if", "result", ":", "output", "=", "cStringIO", ".", "StringIO", "(", ")", "print", ">>", "output", ",", "\"ambiguity found when searching for best transformation\"", "print", ">>", "output", ",", "\"Trying to produce type '%s' from: \"", "%", "(", "target_type", ")", "for", "s", "in", "sources", ":", "print", ">>", "output", ",", "\" - \"", "+", "s", ".", "str", "(", ")", "print", ">>", "output", ",", "\"Generators that succeeded:\"", "for", "g", "in", "generators_that_succeeded", ":", "print", ">>", "output", ",", "\" - \"", "+", "g", ".", "id", "(", ")", "print", ">>", "output", ",", "\"First generator produced: \"", "for", "t", "in", "result", "[", "1", ":", "]", ":", "print", ">>", "output", ",", "\" - \"", "+", "str", "(", "t", ")", "print", ">>", "output", ",", "\"Second generator produced:\"", "for", "t", "in", "r", "[", "1", ":", "]", ":", "print", ">>", "output", ",", "\" - \"", "+", "str", "(", "t", ")", "get_manager", "(", ")", ".", "errors", "(", ")", "(", "output", ".", "getvalue", "(", ")", ")", "else", ":", "result", "=", "r", "return", "result" ]
Attempts to construct target by finding viable generators, running them and selecting the dependency graph.
[ "Attempts", "to", "construct", "target", "by", "finding", "viable", "generators", "running", "them", "and", "selecting", "the", "dependency", "graph", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/generators.py#L1091-L1136
29,024
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/generators.py
Generator.match_rank
def match_rank (self, ps): """ Returns true if the generator can be run with the specified properties. """ # See if generator's requirements are satisfied by # 'properties'. Treat a feature name in requirements # (i.e. grist-only element), as matching any value of the # feature. assert isinstance(ps, property_set.PropertySet) all_requirements = self.requirements () property_requirements = [] feature_requirements = [] # This uses strings because genenator requirements allow # the '<feature>' syntax without value and regular validation # is not happy about that. for r in all_requirements: if get_value (r): property_requirements.append (r) else: feature_requirements.append (r) return all(ps.get(get_grist(s)) == [get_value(s)] for s in property_requirements) \ and all(ps.get(get_grist(s)) for s in feature_requirements)
python
def match_rank (self, ps): """ Returns true if the generator can be run with the specified properties. """ # See if generator's requirements are satisfied by # 'properties'. Treat a feature name in requirements # (i.e. grist-only element), as matching any value of the # feature. assert isinstance(ps, property_set.PropertySet) all_requirements = self.requirements () property_requirements = [] feature_requirements = [] # This uses strings because genenator requirements allow # the '<feature>' syntax without value and regular validation # is not happy about that. for r in all_requirements: if get_value (r): property_requirements.append (r) else: feature_requirements.append (r) return all(ps.get(get_grist(s)) == [get_value(s)] for s in property_requirements) \ and all(ps.get(get_grist(s)) for s in feature_requirements)
[ "def", "match_rank", "(", "self", ",", "ps", ")", ":", "# See if generator's requirements are satisfied by", "# 'properties'. Treat a feature name in requirements", "# (i.e. grist-only element), as matching any value of the", "# feature.", "assert", "isinstance", "(", "ps", ",", "property_set", ".", "PropertySet", ")", "all_requirements", "=", "self", ".", "requirements", "(", ")", "property_requirements", "=", "[", "]", "feature_requirements", "=", "[", "]", "# This uses strings because genenator requirements allow", "# the '<feature>' syntax without value and regular validation", "# is not happy about that.", "for", "r", "in", "all_requirements", ":", "if", "get_value", "(", "r", ")", ":", "property_requirements", ".", "append", "(", "r", ")", "else", ":", "feature_requirements", ".", "append", "(", "r", ")", "return", "all", "(", "ps", ".", "get", "(", "get_grist", "(", "s", ")", ")", "==", "[", "get_value", "(", "s", ")", "]", "for", "s", "in", "property_requirements", ")", "and", "all", "(", "ps", ".", "get", "(", "get_grist", "(", "s", ")", ")", "for", "s", "in", "feature_requirements", ")" ]
Returns true if the generator can be run with the specified properties.
[ "Returns", "true", "if", "the", "generator", "can", "be", "run", "with", "the", "specified", "properties", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/generators.py#L301-L325
29,025
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/generators.py
Generator.determine_output_name
def determine_output_name(self, sources): """Determine the name of the produced target from the names of the sources.""" assert is_iterable_typed(sources, virtual_target.VirtualTarget) # The simple case if when a name # of source has single dot. Then, we take the part before # dot. Several dots can be caused by: # - Using source file like a.host.cpp # - A type which suffix has a dot. Say, we can # type 'host_cpp' with extension 'host.cpp'. # In the first case, we want to take the part till the last # dot. In the second case -- no sure, but for now take # the part till the last dot too. name = os.path.splitext(sources[0].name())[0] for s in sources[1:]: n2 = os.path.splitext(s.name()) if n2 != name: get_manager().errors()( "%s: source targets have different names: cannot determine target name" % (self.id_)) # Names of sources might include directory. We should strip it. return self.determine_target_name(sources[0].name())
python
def determine_output_name(self, sources): """Determine the name of the produced target from the names of the sources.""" assert is_iterable_typed(sources, virtual_target.VirtualTarget) # The simple case if when a name # of source has single dot. Then, we take the part before # dot. Several dots can be caused by: # - Using source file like a.host.cpp # - A type which suffix has a dot. Say, we can # type 'host_cpp' with extension 'host.cpp'. # In the first case, we want to take the part till the last # dot. In the second case -- no sure, but for now take # the part till the last dot too. name = os.path.splitext(sources[0].name())[0] for s in sources[1:]: n2 = os.path.splitext(s.name()) if n2 != name: get_manager().errors()( "%s: source targets have different names: cannot determine target name" % (self.id_)) # Names of sources might include directory. We should strip it. return self.determine_target_name(sources[0].name())
[ "def", "determine_output_name", "(", "self", ",", "sources", ")", ":", "assert", "is_iterable_typed", "(", "sources", ",", "virtual_target", ".", "VirtualTarget", ")", "# The simple case if when a name", "# of source has single dot. Then, we take the part before", "# dot. Several dots can be caused by:", "# - Using source file like a.host.cpp", "# - A type which suffix has a dot. Say, we can", "# type 'host_cpp' with extension 'host.cpp'.", "# In the first case, we want to take the part till the last", "# dot. In the second case -- no sure, but for now take", "# the part till the last dot too.", "name", "=", "os", ".", "path", ".", "splitext", "(", "sources", "[", "0", "]", ".", "name", "(", ")", ")", "[", "0", "]", "for", "s", "in", "sources", "[", "1", ":", "]", ":", "n2", "=", "os", ".", "path", ".", "splitext", "(", "s", ".", "name", "(", ")", ")", "if", "n2", "!=", "name", ":", "get_manager", "(", ")", ".", "errors", "(", ")", "(", "\"%s: source targets have different names: cannot determine target name\"", "%", "(", "self", ".", "id_", ")", ")", "# Names of sources might include directory. We should strip it.", "return", "self", ".", "determine_target_name", "(", "sources", "[", "0", "]", ".", "name", "(", ")", ")" ]
Determine the name of the produced target from the names of the sources.
[ "Determine", "the", "name", "of", "the", "produced", "target", "from", "the", "names", "of", "the", "sources", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/generators.py#L451-L475
29,026
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/generators.py
Generator.generated_targets
def generated_targets (self, sources, prop_set, project, name): """ Constructs targets that are created after consuming 'sources'. The result will be the list of virtual-target, which the same length as 'target_types' attribute and with corresponding types. When 'name' is empty, all source targets must have the same value of the 'name' attribute, which will be used instead of the 'name' argument. The value of 'name' attribute for each generated target will be equal to the 'name' parameter if there's no name pattern for this type. Otherwise, the '%' symbol in the name pattern will be replaced with the 'name' parameter to obtain the 'name' attribute. For example, if targets types are T1 and T2(with name pattern "%_x"), suffixes for T1 and T2 are .t1 and t2, and source if foo.z, then created files would be "foo.t1" and "foo_x.t2". The 'name' attribute actually determined the basename of a file. Note that this pattern mechanism has nothing to do with implicit patterns in make. It's a way to produce target which name is different for name of source. """ if __debug__: from .targets import ProjectTarget assert is_iterable_typed(sources, virtual_target.VirtualTarget) assert isinstance(prop_set, property_set.PropertySet) assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or name is None if not name: name = self.determine_output_name(sources) # Assign an action for each target action = self.action_class() a = action(project.manager(), sources, self.id_, prop_set) # Create generated target for each target type. targets = [] pre = self.name_prefix_ post = self.name_postfix_ for t in self.target_types_: basename = os.path.basename(name) generated_name = pre[0] + basename + post[0] generated_name = os.path.join(os.path.dirname(name), generated_name) pre = pre[1:] post = post[1:] targets.append(virtual_target.FileTarget(generated_name, t, project, a)) return [ project.manager().virtual_targets().register(t) for t in targets ]
python
def generated_targets (self, sources, prop_set, project, name): """ Constructs targets that are created after consuming 'sources'. The result will be the list of virtual-target, which the same length as 'target_types' attribute and with corresponding types. When 'name' is empty, all source targets must have the same value of the 'name' attribute, which will be used instead of the 'name' argument. The value of 'name' attribute for each generated target will be equal to the 'name' parameter if there's no name pattern for this type. Otherwise, the '%' symbol in the name pattern will be replaced with the 'name' parameter to obtain the 'name' attribute. For example, if targets types are T1 and T2(with name pattern "%_x"), suffixes for T1 and T2 are .t1 and t2, and source if foo.z, then created files would be "foo.t1" and "foo_x.t2". The 'name' attribute actually determined the basename of a file. Note that this pattern mechanism has nothing to do with implicit patterns in make. It's a way to produce target which name is different for name of source. """ if __debug__: from .targets import ProjectTarget assert is_iterable_typed(sources, virtual_target.VirtualTarget) assert isinstance(prop_set, property_set.PropertySet) assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or name is None if not name: name = self.determine_output_name(sources) # Assign an action for each target action = self.action_class() a = action(project.manager(), sources, self.id_, prop_set) # Create generated target for each target type. targets = [] pre = self.name_prefix_ post = self.name_postfix_ for t in self.target_types_: basename = os.path.basename(name) generated_name = pre[0] + basename + post[0] generated_name = os.path.join(os.path.dirname(name), generated_name) pre = pre[1:] post = post[1:] targets.append(virtual_target.FileTarget(generated_name, t, project, a)) return [ project.manager().virtual_targets().register(t) for t in targets ]
[ "def", "generated_targets", "(", "self", ",", "sources", ",", "prop_set", ",", "project", ",", "name", ")", ":", "if", "__debug__", ":", "from", ".", "targets", "import", "ProjectTarget", "assert", "is_iterable_typed", "(", "sources", ",", "virtual_target", ".", "VirtualTarget", ")", "assert", "isinstance", "(", "prop_set", ",", "property_set", ".", "PropertySet", ")", "assert", "isinstance", "(", "project", ",", "ProjectTarget", ")", "assert", "isinstance", "(", "name", ",", "basestring", ")", "or", "name", "is", "None", "if", "not", "name", ":", "name", "=", "self", ".", "determine_output_name", "(", "sources", ")", "# Assign an action for each target", "action", "=", "self", ".", "action_class", "(", ")", "a", "=", "action", "(", "project", ".", "manager", "(", ")", ",", "sources", ",", "self", ".", "id_", ",", "prop_set", ")", "# Create generated target for each target type.", "targets", "=", "[", "]", "pre", "=", "self", ".", "name_prefix_", "post", "=", "self", ".", "name_postfix_", "for", "t", "in", "self", ".", "target_types_", ":", "basename", "=", "os", ".", "path", ".", "basename", "(", "name", ")", "generated_name", "=", "pre", "[", "0", "]", "+", "basename", "+", "post", "[", "0", "]", "generated_name", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "name", ")", ",", "generated_name", ")", "pre", "=", "pre", "[", "1", ":", "]", "post", "=", "post", "[", "1", ":", "]", "targets", ".", "append", "(", "virtual_target", ".", "FileTarget", "(", "generated_name", ",", "t", ",", "project", ",", "a", ")", ")", "return", "[", "project", ".", "manager", "(", ")", ".", "virtual_targets", "(", ")", ".", "register", "(", "t", ")", "for", "t", "in", "targets", "]" ]
Constructs targets that are created after consuming 'sources'. The result will be the list of virtual-target, which the same length as 'target_types' attribute and with corresponding types. When 'name' is empty, all source targets must have the same value of the 'name' attribute, which will be used instead of the 'name' argument. The value of 'name' attribute for each generated target will be equal to the 'name' parameter if there's no name pattern for this type. Otherwise, the '%' symbol in the name pattern will be replaced with the 'name' parameter to obtain the 'name' attribute. For example, if targets types are T1 and T2(with name pattern "%_x"), suffixes for T1 and T2 are .t1 and t2, and source if foo.z, then created files would be "foo.t1" and "foo_x.t2". The 'name' attribute actually determined the basename of a file. Note that this pattern mechanism has nothing to do with implicit patterns in make. It's a way to produce target which name is different for name of source.
[ "Constructs", "targets", "that", "are", "created", "after", "consuming", "sources", ".", "The", "result", "will", "be", "the", "list", "of", "virtual", "-", "target", "which", "the", "same", "length", "as", "target_types", "attribute", "and", "with", "corresponding", "types", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/generators.py#L478-L526
29,027
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/generators.py
Generator.convert_multiple_sources_to_consumable_types
def convert_multiple_sources_to_consumable_types (self, project, prop_set, sources): """ Converts several files to consumable types. """ if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(prop_set, property_set.PropertySet) assert is_iterable_typed(sources, virtual_target.VirtualTarget) if not self.source_types_: return list(sources) acceptable_types = set() for t in self.source_types_: acceptable_types.update(type.all_derived(t)) result = [] for source in sources: if source.type() not in acceptable_types: transformed = construct_types( project, None,self.source_types_, prop_set, [source]) # construct_types returns [prop_set, [targets]] for t in transformed[1]: if t.type() in self.source_types_: result.append(t) if not transformed: project.manager().logger().log(__name__, " failed to convert ", source) else: result.append(source) result = sequence.unique(result, stable=True) return result
python
def convert_multiple_sources_to_consumable_types (self, project, prop_set, sources): """ Converts several files to consumable types. """ if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(prop_set, property_set.PropertySet) assert is_iterable_typed(sources, virtual_target.VirtualTarget) if not self.source_types_: return list(sources) acceptable_types = set() for t in self.source_types_: acceptable_types.update(type.all_derived(t)) result = [] for source in sources: if source.type() not in acceptable_types: transformed = construct_types( project, None,self.source_types_, prop_set, [source]) # construct_types returns [prop_set, [targets]] for t in transformed[1]: if t.type() in self.source_types_: result.append(t) if not transformed: project.manager().logger().log(__name__, " failed to convert ", source) else: result.append(source) result = sequence.unique(result, stable=True) return result
[ "def", "convert_multiple_sources_to_consumable_types", "(", "self", ",", "project", ",", "prop_set", ",", "sources", ")", ":", "if", "__debug__", ":", "from", ".", "targets", "import", "ProjectTarget", "assert", "isinstance", "(", "project", ",", "ProjectTarget", ")", "assert", "isinstance", "(", "prop_set", ",", "property_set", ".", "PropertySet", ")", "assert", "is_iterable_typed", "(", "sources", ",", "virtual_target", ".", "VirtualTarget", ")", "if", "not", "self", ".", "source_types_", ":", "return", "list", "(", "sources", ")", "acceptable_types", "=", "set", "(", ")", "for", "t", "in", "self", ".", "source_types_", ":", "acceptable_types", ".", "update", "(", "type", ".", "all_derived", "(", "t", ")", ")", "result", "=", "[", "]", "for", "source", "in", "sources", ":", "if", "source", ".", "type", "(", ")", "not", "in", "acceptable_types", ":", "transformed", "=", "construct_types", "(", "project", ",", "None", ",", "self", ".", "source_types_", ",", "prop_set", ",", "[", "source", "]", ")", "# construct_types returns [prop_set, [targets]]", "for", "t", "in", "transformed", "[", "1", "]", ":", "if", "t", ".", "type", "(", ")", "in", "self", ".", "source_types_", ":", "result", ".", "append", "(", "t", ")", "if", "not", "transformed", ":", "project", ".", "manager", "(", ")", ".", "logger", "(", ")", ".", "log", "(", "__name__", ",", "\" failed to convert \"", ",", "source", ")", "else", ":", "result", ".", "append", "(", "source", ")", "result", "=", "sequence", ".", "unique", "(", "result", ",", "stable", "=", "True", ")", "return", "result" ]
Converts several files to consumable types.
[ "Converts", "several", "files", "to", "consumable", "types", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/generators.py#L588-L619
29,028
apple/turicreate
src/unity/python/turicreate/data_structures/sketch.py
Sketch.element_sub_sketch
def element_sub_sketch(self, keys = None): """ Returns the sketch summary for the given set of keys. This is only applicable for sketch summary created from SArray of sarray or dict type. For dict SArray, the keys are the keys in dict value. For array Sarray, the keys are indexes into the array value. The keys must be passed into original summary() call in order to be able to be retrieved later Parameters ----------- keys : list of str | str | list of int | int The list of dictionary keys or array index to get sub sketch from. if not given, then retrieve all sub sketches that are available Returns ------- A dictionary that maps from the key(index) to the actual sketch summary for that key(index) Examples -------- >>> sa = turicreate.SArray([{'a':1, 'b':2}, {'a':4, 'd':1}]) >>> s = sa.summary(sub_sketch_keys=['a','b']) >>> s.element_sub_sketch(['a']) {'a': +--------------------+-------+----------+ | item | value | is exact | +--------------------+-------+----------+ | Length | 2 | Yes | | Min | 1.0 | Yes | | Max | 4.0 | Yes | | Mean | 2.5 | Yes | | Sum | 5.0 | Yes | | Variance | 2.25 | Yes | | Standard Deviation | 1.5 | Yes | | # Missing Values | 0 | Yes | | # unique values | 2 | No | +--------------------+-------+----------+ Most frequent items: +-------+-----+-----+ | value | 1.0 | 4.0 | +-------+-----+-----+ | count | 1 | 1 | +-------+-----+-----+ Quantiles: +-----+-----+-----+-----+-----+-----+-----+-----+------+ | 0% | 1% | 5% | 25% | 50% | 75% | 95% | 99% | 100% | +-----+-----+-----+-----+-----+-----+-----+-----+------+ | 1.0 | 1.0 | 1.0 | 1.0 | 4.0 | 4.0 | 4.0 | 4.0 | 4.0 | +-----+-----+-----+-----+-----+-----+-----+-----+------+} """ single_val = False if keys is None: keys = [] else: if not isinstance(keys, list): single_val = True keys = [keys] value_types = set([type(i) for i in keys]) if (len(value_types) > 1): raise ValueError("All keys should have the same type.") with cython_context(): ret_sketches = self.__proxy__.element_sub_sketch(keys) ret = {} # check return key matches input key for key in keys: if key not in ret_sketches: raise KeyError("Cannot retrieve element sub sketch for key '" + str(key) + "'. Element sub sketch can only be retrieved when the summary object was created using the 'sub_sketch_keys' option.") for key in ret_sketches: ret[key] = Sketch(_proxy = ret_sketches[key]) if single_val: return ret[keys[0]] else: return ret
python
def element_sub_sketch(self, keys = None): """ Returns the sketch summary for the given set of keys. This is only applicable for sketch summary created from SArray of sarray or dict type. For dict SArray, the keys are the keys in dict value. For array Sarray, the keys are indexes into the array value. The keys must be passed into original summary() call in order to be able to be retrieved later Parameters ----------- keys : list of str | str | list of int | int The list of dictionary keys or array index to get sub sketch from. if not given, then retrieve all sub sketches that are available Returns ------- A dictionary that maps from the key(index) to the actual sketch summary for that key(index) Examples -------- >>> sa = turicreate.SArray([{'a':1, 'b':2}, {'a':4, 'd':1}]) >>> s = sa.summary(sub_sketch_keys=['a','b']) >>> s.element_sub_sketch(['a']) {'a': +--------------------+-------+----------+ | item | value | is exact | +--------------------+-------+----------+ | Length | 2 | Yes | | Min | 1.0 | Yes | | Max | 4.0 | Yes | | Mean | 2.5 | Yes | | Sum | 5.0 | Yes | | Variance | 2.25 | Yes | | Standard Deviation | 1.5 | Yes | | # Missing Values | 0 | Yes | | # unique values | 2 | No | +--------------------+-------+----------+ Most frequent items: +-------+-----+-----+ | value | 1.0 | 4.0 | +-------+-----+-----+ | count | 1 | 1 | +-------+-----+-----+ Quantiles: +-----+-----+-----+-----+-----+-----+-----+-----+------+ | 0% | 1% | 5% | 25% | 50% | 75% | 95% | 99% | 100% | +-----+-----+-----+-----+-----+-----+-----+-----+------+ | 1.0 | 1.0 | 1.0 | 1.0 | 4.0 | 4.0 | 4.0 | 4.0 | 4.0 | +-----+-----+-----+-----+-----+-----+-----+-----+------+} """ single_val = False if keys is None: keys = [] else: if not isinstance(keys, list): single_val = True keys = [keys] value_types = set([type(i) for i in keys]) if (len(value_types) > 1): raise ValueError("All keys should have the same type.") with cython_context(): ret_sketches = self.__proxy__.element_sub_sketch(keys) ret = {} # check return key matches input key for key in keys: if key not in ret_sketches: raise KeyError("Cannot retrieve element sub sketch for key '" + str(key) + "'. Element sub sketch can only be retrieved when the summary object was created using the 'sub_sketch_keys' option.") for key in ret_sketches: ret[key] = Sketch(_proxy = ret_sketches[key]) if single_val: return ret[keys[0]] else: return ret
[ "def", "element_sub_sketch", "(", "self", ",", "keys", "=", "None", ")", ":", "single_val", "=", "False", "if", "keys", "is", "None", ":", "keys", "=", "[", "]", "else", ":", "if", "not", "isinstance", "(", "keys", ",", "list", ")", ":", "single_val", "=", "True", "keys", "=", "[", "keys", "]", "value_types", "=", "set", "(", "[", "type", "(", "i", ")", "for", "i", "in", "keys", "]", ")", "if", "(", "len", "(", "value_types", ")", ">", "1", ")", ":", "raise", "ValueError", "(", "\"All keys should have the same type.\"", ")", "with", "cython_context", "(", ")", ":", "ret_sketches", "=", "self", ".", "__proxy__", ".", "element_sub_sketch", "(", "keys", ")", "ret", "=", "{", "}", "# check return key matches input key", "for", "key", "in", "keys", ":", "if", "key", "not", "in", "ret_sketches", ":", "raise", "KeyError", "(", "\"Cannot retrieve element sub sketch for key '\"", "+", "str", "(", "key", ")", "+", "\"'. Element sub sketch can only be retrieved when the summary object was created using the 'sub_sketch_keys' option.\"", ")", "for", "key", "in", "ret_sketches", ":", "ret", "[", "key", "]", "=", "Sketch", "(", "_proxy", "=", "ret_sketches", "[", "key", "]", ")", "if", "single_val", ":", "return", "ret", "[", "keys", "[", "0", "]", "]", "else", ":", "return", "ret" ]
Returns the sketch summary for the given set of keys. This is only applicable for sketch summary created from SArray of sarray or dict type. For dict SArray, the keys are the keys in dict value. For array Sarray, the keys are indexes into the array value. The keys must be passed into original summary() call in order to be able to be retrieved later Parameters ----------- keys : list of str | str | list of int | int The list of dictionary keys or array index to get sub sketch from. if not given, then retrieve all sub sketches that are available Returns ------- A dictionary that maps from the key(index) to the actual sketch summary for that key(index) Examples -------- >>> sa = turicreate.SArray([{'a':1, 'b':2}, {'a':4, 'd':1}]) >>> s = sa.summary(sub_sketch_keys=['a','b']) >>> s.element_sub_sketch(['a']) {'a': +--------------------+-------+----------+ | item | value | is exact | +--------------------+-------+----------+ | Length | 2 | Yes | | Min | 1.0 | Yes | | Max | 4.0 | Yes | | Mean | 2.5 | Yes | | Sum | 5.0 | Yes | | Variance | 2.25 | Yes | | Standard Deviation | 1.5 | Yes | | # Missing Values | 0 | Yes | | # unique values | 2 | No | +--------------------+-------+----------+ Most frequent items: +-------+-----+-----+ | value | 1.0 | 4.0 | +-------+-----+-----+ | count | 1 | 1 | +-------+-----+-----+ Quantiles: +-----+-----+-----+-----+-----+-----+-----+-----+------+ | 0% | 1% | 5% | 25% | 50% | 75% | 95% | 99% | 100% | +-----+-----+-----+-----+-----+-----+-----+-----+------+ | 1.0 | 1.0 | 1.0 | 1.0 | 4.0 | 4.0 | 4.0 | 4.0 | 4.0 | +-----+-----+-----+-----+-----+-----+-----+-----+------+}
[ "Returns", "the", "sketch", "summary", "for", "the", "given", "set", "of", "keys", ".", "This", "is", "only", "applicable", "for", "sketch", "summary", "created", "from", "SArray", "of", "sarray", "or", "dict", "type", ".", "For", "dict", "SArray", "the", "keys", "are", "the", "keys", "in", "dict", "value", ".", "For", "array", "Sarray", "the", "keys", "are", "indexes", "into", "the", "array", "value", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sketch.py#L662-L740
29,029
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
_get_global_dbapi_info
def _get_global_dbapi_info(dbapi_module, conn): """ Fetches all needed information from the top-level DBAPI module, guessing at the module if it wasn't passed as a parameter. Returns a dictionary of all the needed variables. This is put in one place to make sure the error message is clear if the module "guess" is wrong. """ module_given_msg = "The DBAPI2 module given ({0}) is missing the global\n"+\ "variable '{1}'. Please make sure you are supplying a module that\n"+\ "conforms to the DBAPI 2.0 standard (PEP 0249)." module_not_given_msg = "Hello! I gave my best effort to find the\n"+\ "top-level module that the connection object you gave me came from.\n"+\ "I found '{0}' which doesn't have the global variable '{1}'.\n"+\ "To avoid this confusion, you can pass the module as a parameter using\n"+\ "the 'dbapi_module' argument to either from_sql or to_sql." if dbapi_module is None: dbapi_module = _get_module_from_object(conn) module_given = False else: module_given = True module_name = dbapi_module.__name__ if hasattr(dbapi_module, '__name__') else None needed_vars = ['apilevel','paramstyle','Error','DATETIME','NUMBER','ROWID'] ret_dict = {} ret_dict['module_name'] = module_name for i in needed_vars: tmp = None try: tmp = eval("dbapi_module."+i) except AttributeError as e: # Some DBs don't actually care about types, so they won't define # the types. These are the ACTUALLY needed variables though if i not in ['apilevel','paramstyle','Error']: pass elif module_given: raise AttributeError(module_given_msg.format(module_name, i)) else: raise AttributeError(module_not_given_msg.format(module_name, i)) ret_dict[i] = tmp try: if ret_dict['apilevel'][0:3] != "2.0": raise NotImplementedError("Unsupported API version " +\ str(ret_dict['apilevel']) + ". Only DBAPI 2.0 is supported.") except TypeError as e: e.message = "Module's 'apilevel' value is invalid." raise e acceptable_paramstyles = ['qmark','numeric','named','format','pyformat'] try: if ret_dict['paramstyle'] not in acceptable_paramstyles: raise TypeError("Module's 'paramstyle' value is invalid.") except TypeError as e: raise TypeError("Module's 'paramstyle' value is invalid.") return ret_dict
python
def _get_global_dbapi_info(dbapi_module, conn): """ Fetches all needed information from the top-level DBAPI module, guessing at the module if it wasn't passed as a parameter. Returns a dictionary of all the needed variables. This is put in one place to make sure the error message is clear if the module "guess" is wrong. """ module_given_msg = "The DBAPI2 module given ({0}) is missing the global\n"+\ "variable '{1}'. Please make sure you are supplying a module that\n"+\ "conforms to the DBAPI 2.0 standard (PEP 0249)." module_not_given_msg = "Hello! I gave my best effort to find the\n"+\ "top-level module that the connection object you gave me came from.\n"+\ "I found '{0}' which doesn't have the global variable '{1}'.\n"+\ "To avoid this confusion, you can pass the module as a parameter using\n"+\ "the 'dbapi_module' argument to either from_sql or to_sql." if dbapi_module is None: dbapi_module = _get_module_from_object(conn) module_given = False else: module_given = True module_name = dbapi_module.__name__ if hasattr(dbapi_module, '__name__') else None needed_vars = ['apilevel','paramstyle','Error','DATETIME','NUMBER','ROWID'] ret_dict = {} ret_dict['module_name'] = module_name for i in needed_vars: tmp = None try: tmp = eval("dbapi_module."+i) except AttributeError as e: # Some DBs don't actually care about types, so they won't define # the types. These are the ACTUALLY needed variables though if i not in ['apilevel','paramstyle','Error']: pass elif module_given: raise AttributeError(module_given_msg.format(module_name, i)) else: raise AttributeError(module_not_given_msg.format(module_name, i)) ret_dict[i] = tmp try: if ret_dict['apilevel'][0:3] != "2.0": raise NotImplementedError("Unsupported API version " +\ str(ret_dict['apilevel']) + ". Only DBAPI 2.0 is supported.") except TypeError as e: e.message = "Module's 'apilevel' value is invalid." raise e acceptable_paramstyles = ['qmark','numeric','named','format','pyformat'] try: if ret_dict['paramstyle'] not in acceptable_paramstyles: raise TypeError("Module's 'paramstyle' value is invalid.") except TypeError as e: raise TypeError("Module's 'paramstyle' value is invalid.") return ret_dict
[ "def", "_get_global_dbapi_info", "(", "dbapi_module", ",", "conn", ")", ":", "module_given_msg", "=", "\"The DBAPI2 module given ({0}) is missing the global\\n\"", "+", "\"variable '{1}'. Please make sure you are supplying a module that\\n\"", "+", "\"conforms to the DBAPI 2.0 standard (PEP 0249).\"", "module_not_given_msg", "=", "\"Hello! I gave my best effort to find the\\n\"", "+", "\"top-level module that the connection object you gave me came from.\\n\"", "+", "\"I found '{0}' which doesn't have the global variable '{1}'.\\n\"", "+", "\"To avoid this confusion, you can pass the module as a parameter using\\n\"", "+", "\"the 'dbapi_module' argument to either from_sql or to_sql.\"", "if", "dbapi_module", "is", "None", ":", "dbapi_module", "=", "_get_module_from_object", "(", "conn", ")", "module_given", "=", "False", "else", ":", "module_given", "=", "True", "module_name", "=", "dbapi_module", ".", "__name__", "if", "hasattr", "(", "dbapi_module", ",", "'__name__'", ")", "else", "None", "needed_vars", "=", "[", "'apilevel'", ",", "'paramstyle'", ",", "'Error'", ",", "'DATETIME'", ",", "'NUMBER'", ",", "'ROWID'", "]", "ret_dict", "=", "{", "}", "ret_dict", "[", "'module_name'", "]", "=", "module_name", "for", "i", "in", "needed_vars", ":", "tmp", "=", "None", "try", ":", "tmp", "=", "eval", "(", "\"dbapi_module.\"", "+", "i", ")", "except", "AttributeError", "as", "e", ":", "# Some DBs don't actually care about types, so they won't define", "# the types. These are the ACTUALLY needed variables though", "if", "i", "not", "in", "[", "'apilevel'", ",", "'paramstyle'", ",", "'Error'", "]", ":", "pass", "elif", "module_given", ":", "raise", "AttributeError", "(", "module_given_msg", ".", "format", "(", "module_name", ",", "i", ")", ")", "else", ":", "raise", "AttributeError", "(", "module_not_given_msg", ".", "format", "(", "module_name", ",", "i", ")", ")", "ret_dict", "[", "i", "]", "=", "tmp", "try", ":", "if", "ret_dict", "[", "'apilevel'", "]", "[", "0", ":", "3", "]", "!=", "\"2.0\"", ":", "raise", "NotImplementedError", "(", "\"Unsupported API version \"", "+", "str", "(", "ret_dict", "[", "'apilevel'", "]", ")", "+", "\". Only DBAPI 2.0 is supported.\"", ")", "except", "TypeError", "as", "e", ":", "e", ".", "message", "=", "\"Module's 'apilevel' value is invalid.\"", "raise", "e", "acceptable_paramstyles", "=", "[", "'qmark'", ",", "'numeric'", ",", "'named'", ",", "'format'", ",", "'pyformat'", "]", "try", ":", "if", "ret_dict", "[", "'paramstyle'", "]", "not", "in", "acceptable_paramstyles", ":", "raise", "TypeError", "(", "\"Module's 'paramstyle' value is invalid.\"", ")", "except", "TypeError", "as", "e", ":", "raise", "TypeError", "(", "\"Module's 'paramstyle' value is invalid.\"", ")", "return", "ret_dict" ]
Fetches all needed information from the top-level DBAPI module, guessing at the module if it wasn't passed as a parameter. Returns a dictionary of all the needed variables. This is put in one place to make sure the error message is clear if the module "guess" is wrong.
[ "Fetches", "all", "needed", "information", "from", "the", "top", "-", "level", "DBAPI", "module", "guessing", "at", "the", "module", "if", "it", "wasn", "t", "passed", "as", "a", "parameter", ".", "Returns", "a", "dictionary", "of", "all", "the", "needed", "variables", ".", "This", "is", "put", "in", "one", "place", "to", "make", "sure", "the", "error", "message", "is", "clear", "if", "the", "module", "guess", "is", "wrong", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L86-L144
29,030
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.read_csv_with_errors
def read_csv_with_errors(cls, url, delimiter=',', header=True, comment_char='', escape_char='\\', double_quote=True, quote_char='\"', skip_initial_space=True, column_type_hints=None, na_values=["NA"], line_terminator='\n', usecols = [], nrows=None, skiprows=0, verbose=True, nrows_to_infer=100, true_values=[], false_values=[], _only_raw_string_substitutions=False, **kwargs): """ Constructs an SFrame from a CSV file or a path to multiple CSVs, and returns a pair containing the SFrame and a dict of filenames to SArrays indicating for each file, what are the incorrectly parsed lines encountered. Parameters ---------- url : string Location of the CSV file or directory to load. If URL is a directory or a "glob" pattern, all matching files will be loaded. delimiter : string, optional This describes the delimiter used for parsing csv files. header : bool, optional If true, uses the first row as the column names. Otherwise use the default column names: 'X1, X2, ...'. comment_char : string, optional The character which denotes that the remainder of the line is a comment. escape_char : string, optional Character which begins a C escape sequence. Defaults to backslash(\\) Set to None to disable. double_quote : bool, optional If True, two consecutive quotes in a string are parsed to a single quote. quote_char : string, optional Character sequence that indicates a quote. skip_initial_space : bool, optional Ignore extra spaces at the start of a field column_type_hints : None, type, list[type], dict[string, type], optional This provides type hints for each column. By default, this method attempts to detect the type of each column automatically. Supported types are int, float, str, list, dict, and array.array. * If a single type is provided, the type will be applied to all columns. For instance, column_type_hints=float will force all columns to be parsed as float. * If a list of types is provided, the types applies to each column in order, e.g.[int, float, str] will parse the first column as int, second as float and third as string. * If a dictionary of column name to type is provided, each type value in the dictionary is applied to the key it belongs to. For instance {'user':int} will hint that the column called "user" should be parsed as an integer, and the rest will be type inferred. na_values : str | list of str, optional A string or list of strings to be interpreted as missing values. true_values : str | list of str, optional A string or list of strings to be interpreted as 1 false_values : str | list of str, optional A string or list of strings to be interpreted as 0 line_terminator : str, optional A string to be interpreted as the line terminator. Defaults to "\\n" which will also correctly match Mac, Linux and Windows line endings ("\\r", "\\n" and "\\r\\n" respectively) usecols : list of str, optional A subset of column names to output. If unspecified (default), all columns will be read. This can provide performance gains if the number of columns are large. If the input file has no headers, usecols=['X1','X3'] will read columns 1 and 3. nrows : int, optional If set, only this many rows will be read from the file. skiprows : int, optional If set, this number of rows at the start of the file are skipped. verbose : bool, optional If True, print the progress. Returns ------- out : tuple The first element is the SFrame with good data. The second element is a dictionary of filenames to SArrays indicating for each file, what are the incorrectly parsed lines encountered. See Also -------- read_csv, SFrame Examples -------- >>> bad_url = 'https://static.turi.com/datasets/bad_csv_example.csv' >>> (sf, bad_lines) = turicreate.SFrame.read_csv_with_errors(bad_url) >>> sf +---------+----------+--------+ | user_id | movie_id | rating | +---------+----------+--------+ | 25904 | 1663 | 3 | | 25907 | 1663 | 3 | | 25923 | 1663 | 3 | | 25924 | 1663 | 3 | | 25928 | 1663 | 2 | | ... | ... | ... | +---------+----------+--------+ [98 rows x 3 columns] >>> bad_lines {'https://static.turi.com/datasets/bad_csv_example.csv': dtype: str Rows: 1 ['x,y,z,a,b,c']} """ return cls._read_csv_impl(url, delimiter=delimiter, header=header, error_bad_lines=False, # we are storing errors, # thus we must not fail # on bad lines comment_char=comment_char, escape_char=escape_char, double_quote=double_quote, quote_char=quote_char, skip_initial_space=skip_initial_space, column_type_hints=column_type_hints, na_values=na_values, line_terminator=line_terminator, usecols=usecols, nrows=nrows, verbose=verbose, skiprows=skiprows, store_errors=True, nrows_to_infer=nrows_to_infer, true_values=true_values, false_values=false_values, _only_raw_string_substitutions=_only_raw_string_substitutions, **kwargs)
python
def read_csv_with_errors(cls, url, delimiter=',', header=True, comment_char='', escape_char='\\', double_quote=True, quote_char='\"', skip_initial_space=True, column_type_hints=None, na_values=["NA"], line_terminator='\n', usecols = [], nrows=None, skiprows=0, verbose=True, nrows_to_infer=100, true_values=[], false_values=[], _only_raw_string_substitutions=False, **kwargs): """ Constructs an SFrame from a CSV file or a path to multiple CSVs, and returns a pair containing the SFrame and a dict of filenames to SArrays indicating for each file, what are the incorrectly parsed lines encountered. Parameters ---------- url : string Location of the CSV file or directory to load. If URL is a directory or a "glob" pattern, all matching files will be loaded. delimiter : string, optional This describes the delimiter used for parsing csv files. header : bool, optional If true, uses the first row as the column names. Otherwise use the default column names: 'X1, X2, ...'. comment_char : string, optional The character which denotes that the remainder of the line is a comment. escape_char : string, optional Character which begins a C escape sequence. Defaults to backslash(\\) Set to None to disable. double_quote : bool, optional If True, two consecutive quotes in a string are parsed to a single quote. quote_char : string, optional Character sequence that indicates a quote. skip_initial_space : bool, optional Ignore extra spaces at the start of a field column_type_hints : None, type, list[type], dict[string, type], optional This provides type hints for each column. By default, this method attempts to detect the type of each column automatically. Supported types are int, float, str, list, dict, and array.array. * If a single type is provided, the type will be applied to all columns. For instance, column_type_hints=float will force all columns to be parsed as float. * If a list of types is provided, the types applies to each column in order, e.g.[int, float, str] will parse the first column as int, second as float and third as string. * If a dictionary of column name to type is provided, each type value in the dictionary is applied to the key it belongs to. For instance {'user':int} will hint that the column called "user" should be parsed as an integer, and the rest will be type inferred. na_values : str | list of str, optional A string or list of strings to be interpreted as missing values. true_values : str | list of str, optional A string or list of strings to be interpreted as 1 false_values : str | list of str, optional A string or list of strings to be interpreted as 0 line_terminator : str, optional A string to be interpreted as the line terminator. Defaults to "\\n" which will also correctly match Mac, Linux and Windows line endings ("\\r", "\\n" and "\\r\\n" respectively) usecols : list of str, optional A subset of column names to output. If unspecified (default), all columns will be read. This can provide performance gains if the number of columns are large. If the input file has no headers, usecols=['X1','X3'] will read columns 1 and 3. nrows : int, optional If set, only this many rows will be read from the file. skiprows : int, optional If set, this number of rows at the start of the file are skipped. verbose : bool, optional If True, print the progress. Returns ------- out : tuple The first element is the SFrame with good data. The second element is a dictionary of filenames to SArrays indicating for each file, what are the incorrectly parsed lines encountered. See Also -------- read_csv, SFrame Examples -------- >>> bad_url = 'https://static.turi.com/datasets/bad_csv_example.csv' >>> (sf, bad_lines) = turicreate.SFrame.read_csv_with_errors(bad_url) >>> sf +---------+----------+--------+ | user_id | movie_id | rating | +---------+----------+--------+ | 25904 | 1663 | 3 | | 25907 | 1663 | 3 | | 25923 | 1663 | 3 | | 25924 | 1663 | 3 | | 25928 | 1663 | 2 | | ... | ... | ... | +---------+----------+--------+ [98 rows x 3 columns] >>> bad_lines {'https://static.turi.com/datasets/bad_csv_example.csv': dtype: str Rows: 1 ['x,y,z,a,b,c']} """ return cls._read_csv_impl(url, delimiter=delimiter, header=header, error_bad_lines=False, # we are storing errors, # thus we must not fail # on bad lines comment_char=comment_char, escape_char=escape_char, double_quote=double_quote, quote_char=quote_char, skip_initial_space=skip_initial_space, column_type_hints=column_type_hints, na_values=na_values, line_terminator=line_terminator, usecols=usecols, nrows=nrows, verbose=verbose, skiprows=skiprows, store_errors=True, nrows_to_infer=nrows_to_infer, true_values=true_values, false_values=false_values, _only_raw_string_substitutions=_only_raw_string_substitutions, **kwargs)
[ "def", "read_csv_with_errors", "(", "cls", ",", "url", ",", "delimiter", "=", "','", ",", "header", "=", "True", ",", "comment_char", "=", "''", ",", "escape_char", "=", "'\\\\'", ",", "double_quote", "=", "True", ",", "quote_char", "=", "'\\\"'", ",", "skip_initial_space", "=", "True", ",", "column_type_hints", "=", "None", ",", "na_values", "=", "[", "\"NA\"", "]", ",", "line_terminator", "=", "'\\n'", ",", "usecols", "=", "[", "]", ",", "nrows", "=", "None", ",", "skiprows", "=", "0", ",", "verbose", "=", "True", ",", "nrows_to_infer", "=", "100", ",", "true_values", "=", "[", "]", ",", "false_values", "=", "[", "]", ",", "_only_raw_string_substitutions", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "cls", ".", "_read_csv_impl", "(", "url", ",", "delimiter", "=", "delimiter", ",", "header", "=", "header", ",", "error_bad_lines", "=", "False", ",", "# we are storing errors,", "# thus we must not fail", "# on bad lines", "comment_char", "=", "comment_char", ",", "escape_char", "=", "escape_char", ",", "double_quote", "=", "double_quote", ",", "quote_char", "=", "quote_char", ",", "skip_initial_space", "=", "skip_initial_space", ",", "column_type_hints", "=", "column_type_hints", ",", "na_values", "=", "na_values", ",", "line_terminator", "=", "line_terminator", ",", "usecols", "=", "usecols", ",", "nrows", "=", "nrows", ",", "verbose", "=", "verbose", ",", "skiprows", "=", "skiprows", ",", "store_errors", "=", "True", ",", "nrows_to_infer", "=", "nrows_to_infer", ",", "true_values", "=", "true_values", ",", "false_values", "=", "false_values", ",", "_only_raw_string_substitutions", "=", "_only_raw_string_substitutions", ",", "*", "*", "kwargs", ")" ]
Constructs an SFrame from a CSV file or a path to multiple CSVs, and returns a pair containing the SFrame and a dict of filenames to SArrays indicating for each file, what are the incorrectly parsed lines encountered. Parameters ---------- url : string Location of the CSV file or directory to load. If URL is a directory or a "glob" pattern, all matching files will be loaded. delimiter : string, optional This describes the delimiter used for parsing csv files. header : bool, optional If true, uses the first row as the column names. Otherwise use the default column names: 'X1, X2, ...'. comment_char : string, optional The character which denotes that the remainder of the line is a comment. escape_char : string, optional Character which begins a C escape sequence. Defaults to backslash(\\) Set to None to disable. double_quote : bool, optional If True, two consecutive quotes in a string are parsed to a single quote. quote_char : string, optional Character sequence that indicates a quote. skip_initial_space : bool, optional Ignore extra spaces at the start of a field column_type_hints : None, type, list[type], dict[string, type], optional This provides type hints for each column. By default, this method attempts to detect the type of each column automatically. Supported types are int, float, str, list, dict, and array.array. * If a single type is provided, the type will be applied to all columns. For instance, column_type_hints=float will force all columns to be parsed as float. * If a list of types is provided, the types applies to each column in order, e.g.[int, float, str] will parse the first column as int, second as float and third as string. * If a dictionary of column name to type is provided, each type value in the dictionary is applied to the key it belongs to. For instance {'user':int} will hint that the column called "user" should be parsed as an integer, and the rest will be type inferred. na_values : str | list of str, optional A string or list of strings to be interpreted as missing values. true_values : str | list of str, optional A string or list of strings to be interpreted as 1 false_values : str | list of str, optional A string or list of strings to be interpreted as 0 line_terminator : str, optional A string to be interpreted as the line terminator. Defaults to "\\n" which will also correctly match Mac, Linux and Windows line endings ("\\r", "\\n" and "\\r\\n" respectively) usecols : list of str, optional A subset of column names to output. If unspecified (default), all columns will be read. This can provide performance gains if the number of columns are large. If the input file has no headers, usecols=['X1','X3'] will read columns 1 and 3. nrows : int, optional If set, only this many rows will be read from the file. skiprows : int, optional If set, this number of rows at the start of the file are skipped. verbose : bool, optional If True, print the progress. Returns ------- out : tuple The first element is the SFrame with good data. The second element is a dictionary of filenames to SArrays indicating for each file, what are the incorrectly parsed lines encountered. See Also -------- read_csv, SFrame Examples -------- >>> bad_url = 'https://static.turi.com/datasets/bad_csv_example.csv' >>> (sf, bad_lines) = turicreate.SFrame.read_csv_with_errors(bad_url) >>> sf +---------+----------+--------+ | user_id | movie_id | rating | +---------+----------+--------+ | 25904 | 1663 | 3 | | 25907 | 1663 | 3 | | 25923 | 1663 | 3 | | 25924 | 1663 | 3 | | 25928 | 1663 | 2 | | ... | ... | ... | +---------+----------+--------+ [98 rows x 3 columns] >>> bad_lines {'https://static.turi.com/datasets/bad_csv_example.csv': dtype: str Rows: 1 ['x,y,z,a,b,c']}
[ "Constructs", "an", "SFrame", "from", "a", "CSV", "file", "or", "a", "path", "to", "multiple", "CSVs", "and", "returns", "a", "pair", "containing", "the", "SFrame", "and", "a", "dict", "of", "filenames", "to", "SArrays", "indicating", "for", "each", "file", "what", "are", "the", "incorrectly", "parsed", "lines", "encountered", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L1066-L1228
29,031
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.read_json
def read_json(cls, url, orient='records'): """ Reads a JSON file representing a table into an SFrame. Parameters ---------- url : string Location of the CSV file or directory to load. If URL is a directory or a "glob" pattern, all matching files will be loaded. orient : string, optional. Either "records" or "lines" If orient="records" the file is expected to contain a single JSON array, where each array element is a dictionary. If orient="lines", the file is expected to contain a JSON element per line. Examples -------- The orient parameter describes the expected input format of the JSON file. If orient="records", the JSON file is expected to contain a single JSON Array where each array element is a dictionary describing the row. For instance: >>> !cat input.json [{'a':1,'b':1}, {'a':2,'b':2}, {'a':3,'b':3}] >>> SFrame.read_json('input.json', orient='records') Columns: a int b int Rows: 3 Data: +---+---+ | a | b | +---+---+ | 1 | 1 | | 2 | 2 | | 3 | 3 | +---+---+ If orient="lines", the JSON file is expected to contain a JSON element per line. If each line contains a dictionary, it is automatically unpacked. >>> !cat input.json {'a':1,'b':1} {'a':2,'b':2} {'a':3,'b':3} >>> g = SFrame.read_json('input.json', orient='lines') Columns: a int b int Rows: 3 Data: +---+---+ | a | b | +---+---+ | 1 | 1 | | 2 | 2 | | 3 | 3 | +---+---+ If the lines are not dictionaries, the original format is maintained. >>> !cat input.json ['a','b','c'] ['d','e','f'] ['g','h','i'] [1,2,3] >>> g = SFrame.read_json('input.json', orient='lines') Columns: X1 list Rows: 3 Data: +-----------+ | X1 | +-----------+ | [a, b, c] | | [d, e, f] | | [g, h, i] | +-----------+ [3 rows x 1 columns] """ if orient == "records": g = SArray.read_json(url) if len(g) == 0: return SFrame() g = SFrame({'X1':g}) return g.unpack('X1','') elif orient == "lines": g = cls.read_csv(url, header=False,na_values=['null'],true_values=['true'],false_values=['false'], _only_raw_string_substitutions=True) if g.num_rows() == 0: return SFrame() if g.num_columns() != 1: raise RuntimeError("Input JSON not of expected format") if g['X1'].dtype == dict: return g.unpack('X1','') else: return g else: raise ValueError("Invalid value for orient parameter (" + str(orient) + ")")
python
def read_json(cls, url, orient='records'): """ Reads a JSON file representing a table into an SFrame. Parameters ---------- url : string Location of the CSV file or directory to load. If URL is a directory or a "glob" pattern, all matching files will be loaded. orient : string, optional. Either "records" or "lines" If orient="records" the file is expected to contain a single JSON array, where each array element is a dictionary. If orient="lines", the file is expected to contain a JSON element per line. Examples -------- The orient parameter describes the expected input format of the JSON file. If orient="records", the JSON file is expected to contain a single JSON Array where each array element is a dictionary describing the row. For instance: >>> !cat input.json [{'a':1,'b':1}, {'a':2,'b':2}, {'a':3,'b':3}] >>> SFrame.read_json('input.json', orient='records') Columns: a int b int Rows: 3 Data: +---+---+ | a | b | +---+---+ | 1 | 1 | | 2 | 2 | | 3 | 3 | +---+---+ If orient="lines", the JSON file is expected to contain a JSON element per line. If each line contains a dictionary, it is automatically unpacked. >>> !cat input.json {'a':1,'b':1} {'a':2,'b':2} {'a':3,'b':3} >>> g = SFrame.read_json('input.json', orient='lines') Columns: a int b int Rows: 3 Data: +---+---+ | a | b | +---+---+ | 1 | 1 | | 2 | 2 | | 3 | 3 | +---+---+ If the lines are not dictionaries, the original format is maintained. >>> !cat input.json ['a','b','c'] ['d','e','f'] ['g','h','i'] [1,2,3] >>> g = SFrame.read_json('input.json', orient='lines') Columns: X1 list Rows: 3 Data: +-----------+ | X1 | +-----------+ | [a, b, c] | | [d, e, f] | | [g, h, i] | +-----------+ [3 rows x 1 columns] """ if orient == "records": g = SArray.read_json(url) if len(g) == 0: return SFrame() g = SFrame({'X1':g}) return g.unpack('X1','') elif orient == "lines": g = cls.read_csv(url, header=False,na_values=['null'],true_values=['true'],false_values=['false'], _only_raw_string_substitutions=True) if g.num_rows() == 0: return SFrame() if g.num_columns() != 1: raise RuntimeError("Input JSON not of expected format") if g['X1'].dtype == dict: return g.unpack('X1','') else: return g else: raise ValueError("Invalid value for orient parameter (" + str(orient) + ")")
[ "def", "read_json", "(", "cls", ",", "url", ",", "orient", "=", "'records'", ")", ":", "if", "orient", "==", "\"records\"", ":", "g", "=", "SArray", ".", "read_json", "(", "url", ")", "if", "len", "(", "g", ")", "==", "0", ":", "return", "SFrame", "(", ")", "g", "=", "SFrame", "(", "{", "'X1'", ":", "g", "}", ")", "return", "g", ".", "unpack", "(", "'X1'", ",", "''", ")", "elif", "orient", "==", "\"lines\"", ":", "g", "=", "cls", ".", "read_csv", "(", "url", ",", "header", "=", "False", ",", "na_values", "=", "[", "'null'", "]", ",", "true_values", "=", "[", "'true'", "]", ",", "false_values", "=", "[", "'false'", "]", ",", "_only_raw_string_substitutions", "=", "True", ")", "if", "g", ".", "num_rows", "(", ")", "==", "0", ":", "return", "SFrame", "(", ")", "if", "g", ".", "num_columns", "(", ")", "!=", "1", ":", "raise", "RuntimeError", "(", "\"Input JSON not of expected format\"", ")", "if", "g", "[", "'X1'", "]", ".", "dtype", "==", "dict", ":", "return", "g", ".", "unpack", "(", "'X1'", ",", "''", ")", "else", ":", "return", "g", "else", ":", "raise", "ValueError", "(", "\"Invalid value for orient parameter (\"", "+", "str", "(", "orient", ")", "+", "\")\"", ")" ]
Reads a JSON file representing a table into an SFrame. Parameters ---------- url : string Location of the CSV file or directory to load. If URL is a directory or a "glob" pattern, all matching files will be loaded. orient : string, optional. Either "records" or "lines" If orient="records" the file is expected to contain a single JSON array, where each array element is a dictionary. If orient="lines", the file is expected to contain a JSON element per line. Examples -------- The orient parameter describes the expected input format of the JSON file. If orient="records", the JSON file is expected to contain a single JSON Array where each array element is a dictionary describing the row. For instance: >>> !cat input.json [{'a':1,'b':1}, {'a':2,'b':2}, {'a':3,'b':3}] >>> SFrame.read_json('input.json', orient='records') Columns: a int b int Rows: 3 Data: +---+---+ | a | b | +---+---+ | 1 | 1 | | 2 | 2 | | 3 | 3 | +---+---+ If orient="lines", the JSON file is expected to contain a JSON element per line. If each line contains a dictionary, it is automatically unpacked. >>> !cat input.json {'a':1,'b':1} {'a':2,'b':2} {'a':3,'b':3} >>> g = SFrame.read_json('input.json', orient='lines') Columns: a int b int Rows: 3 Data: +---+---+ | a | b | +---+---+ | 1 | 1 | | 2 | 2 | | 3 | 3 | +---+---+ If the lines are not dictionaries, the original format is maintained. >>> !cat input.json ['a','b','c'] ['d','e','f'] ['g','h','i'] [1,2,3] >>> g = SFrame.read_json('input.json', orient='lines') Columns: X1 list Rows: 3 Data: +-----------+ | X1 | +-----------+ | [a, b, c] | | [d, e, f] | | [g, h, i] | +-----------+ [3 rows x 1 columns]
[ "Reads", "a", "JSON", "file", "representing", "a", "table", "into", "an", "SFrame", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L1516-L1619
29,032
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.to_sql
def to_sql(self, conn, table_name, dbapi_module=None, use_python_type_specifiers=False, use_exact_column_names=True): """ Convert an SFrame to a single table in a SQL database. This function does not attempt to create the table or check if a table named `table_name` exists in the database. It simply assumes that `table_name` exists in the database and appends to it. `to_sql` can be thought of as a convenience wrapper around parameterized SQL insert statements. Parameters ---------- conn : dbapi2.Connection A DBAPI2 connection object. Any connection object originating from the 'connect' method of a DBAPI2-compliant package can be used. table_name : str The name of the table to append the data in this SFrame. dbapi_module : module | package, optional The top-level DBAPI2 module/package that constructed the given connection object. By default, a best guess of which module the connection came from is made. In the event that this guess is wrong, this will need to be specified. use_python_type_specifiers : bool, optional If the DBAPI2 module's parameter marker style is 'format' or 'pyformat', attempt to use accurate type specifiers for each value ('s' for string, 'd' for integer, etc.). Many DBAPI2 modules simply use 's' for all types if they use these parameter markers, so this is False by default. use_exact_column_names : bool, optional Specify the column names of the SFrame when inserting its contents into the DB. If the specified table does not have the exact same column names as the SFrame, inserting the data will fail. If False, the columns in the SFrame are inserted in order without care of the schema of the DB table. True by default. """ mod_info = _get_global_dbapi_info(dbapi_module, conn) c = conn.cursor() col_info = list(zip(self.column_names(), self.column_types())) if not use_python_type_specifiers: _pytype_to_printf = lambda x: 's' # DBAPI2 standard allows for five different ways to specify parameters sql_param = { 'qmark' : lambda name,col_num,col_type: '?', 'numeric' : lambda name,col_num,col_type:':'+str(col_num+1), 'named' : lambda name,col_num,col_type:':'+str(name), 'format' : lambda name,col_num,col_type:'%'+_pytype_to_printf(col_type), 'pyformat': lambda name,col_num,col_type:'%('+str(name)+')'+_pytype_to_printf(col_type), } get_sql_param = sql_param[mod_info['paramstyle']] # form insert string ins_str = "INSERT INTO " + str(table_name) value_str = " VALUES (" col_str = " (" count = 0 for i in col_info: col_str += i[0] value_str += get_sql_param(i[0],count,i[1]) if count < len(col_info)-1: col_str += "," value_str += "," count += 1 col_str += ")" value_str += ")" if use_exact_column_names: ins_str += col_str ins_str += value_str # Some formats require values in an iterable, some a dictionary if (mod_info['paramstyle'] == 'named' or\ mod_info['paramstyle'] == 'pyformat'): prepare_sf_row = lambda x:x else: col_names = self.column_names() prepare_sf_row = lambda x: [x[i] for i in col_names] for i in self: try: c.execute(ins_str, prepare_sf_row(i)) except mod_info['Error'] as e: if hasattr(conn, 'rollback'): conn.rollback() raise e conn.commit() c.close()
python
def to_sql(self, conn, table_name, dbapi_module=None, use_python_type_specifiers=False, use_exact_column_names=True): """ Convert an SFrame to a single table in a SQL database. This function does not attempt to create the table or check if a table named `table_name` exists in the database. It simply assumes that `table_name` exists in the database and appends to it. `to_sql` can be thought of as a convenience wrapper around parameterized SQL insert statements. Parameters ---------- conn : dbapi2.Connection A DBAPI2 connection object. Any connection object originating from the 'connect' method of a DBAPI2-compliant package can be used. table_name : str The name of the table to append the data in this SFrame. dbapi_module : module | package, optional The top-level DBAPI2 module/package that constructed the given connection object. By default, a best guess of which module the connection came from is made. In the event that this guess is wrong, this will need to be specified. use_python_type_specifiers : bool, optional If the DBAPI2 module's parameter marker style is 'format' or 'pyformat', attempt to use accurate type specifiers for each value ('s' for string, 'd' for integer, etc.). Many DBAPI2 modules simply use 's' for all types if they use these parameter markers, so this is False by default. use_exact_column_names : bool, optional Specify the column names of the SFrame when inserting its contents into the DB. If the specified table does not have the exact same column names as the SFrame, inserting the data will fail. If False, the columns in the SFrame are inserted in order without care of the schema of the DB table. True by default. """ mod_info = _get_global_dbapi_info(dbapi_module, conn) c = conn.cursor() col_info = list(zip(self.column_names(), self.column_types())) if not use_python_type_specifiers: _pytype_to_printf = lambda x: 's' # DBAPI2 standard allows for five different ways to specify parameters sql_param = { 'qmark' : lambda name,col_num,col_type: '?', 'numeric' : lambda name,col_num,col_type:':'+str(col_num+1), 'named' : lambda name,col_num,col_type:':'+str(name), 'format' : lambda name,col_num,col_type:'%'+_pytype_to_printf(col_type), 'pyformat': lambda name,col_num,col_type:'%('+str(name)+')'+_pytype_to_printf(col_type), } get_sql_param = sql_param[mod_info['paramstyle']] # form insert string ins_str = "INSERT INTO " + str(table_name) value_str = " VALUES (" col_str = " (" count = 0 for i in col_info: col_str += i[0] value_str += get_sql_param(i[0],count,i[1]) if count < len(col_info)-1: col_str += "," value_str += "," count += 1 col_str += ")" value_str += ")" if use_exact_column_names: ins_str += col_str ins_str += value_str # Some formats require values in an iterable, some a dictionary if (mod_info['paramstyle'] == 'named' or\ mod_info['paramstyle'] == 'pyformat'): prepare_sf_row = lambda x:x else: col_names = self.column_names() prepare_sf_row = lambda x: [x[i] for i in col_names] for i in self: try: c.execute(ins_str, prepare_sf_row(i)) except mod_info['Error'] as e: if hasattr(conn, 'rollback'): conn.rollback() raise e conn.commit() c.close()
[ "def", "to_sql", "(", "self", ",", "conn", ",", "table_name", ",", "dbapi_module", "=", "None", ",", "use_python_type_specifiers", "=", "False", ",", "use_exact_column_names", "=", "True", ")", ":", "mod_info", "=", "_get_global_dbapi_info", "(", "dbapi_module", ",", "conn", ")", "c", "=", "conn", ".", "cursor", "(", ")", "col_info", "=", "list", "(", "zip", "(", "self", ".", "column_names", "(", ")", ",", "self", ".", "column_types", "(", ")", ")", ")", "if", "not", "use_python_type_specifiers", ":", "_pytype_to_printf", "=", "lambda", "x", ":", "'s'", "# DBAPI2 standard allows for five different ways to specify parameters", "sql_param", "=", "{", "'qmark'", ":", "lambda", "name", ",", "col_num", ",", "col_type", ":", "'?'", ",", "'numeric'", ":", "lambda", "name", ",", "col_num", ",", "col_type", ":", "':'", "+", "str", "(", "col_num", "+", "1", ")", ",", "'named'", ":", "lambda", "name", ",", "col_num", ",", "col_type", ":", "':'", "+", "str", "(", "name", ")", ",", "'format'", ":", "lambda", "name", ",", "col_num", ",", "col_type", ":", "'%'", "+", "_pytype_to_printf", "(", "col_type", ")", ",", "'pyformat'", ":", "lambda", "name", ",", "col_num", ",", "col_type", ":", "'%('", "+", "str", "(", "name", ")", "+", "')'", "+", "_pytype_to_printf", "(", "col_type", ")", ",", "}", "get_sql_param", "=", "sql_param", "[", "mod_info", "[", "'paramstyle'", "]", "]", "# form insert string", "ins_str", "=", "\"INSERT INTO \"", "+", "str", "(", "table_name", ")", "value_str", "=", "\" VALUES (\"", "col_str", "=", "\" (\"", "count", "=", "0", "for", "i", "in", "col_info", ":", "col_str", "+=", "i", "[", "0", "]", "value_str", "+=", "get_sql_param", "(", "i", "[", "0", "]", ",", "count", ",", "i", "[", "1", "]", ")", "if", "count", "<", "len", "(", "col_info", ")", "-", "1", ":", "col_str", "+=", "\",\"", "value_str", "+=", "\",\"", "count", "+=", "1", "col_str", "+=", "\")\"", "value_str", "+=", "\")\"", "if", "use_exact_column_names", ":", "ins_str", "+=", "col_str", "ins_str", "+=", "value_str", "# Some formats require values in an iterable, some a dictionary", "if", "(", "mod_info", "[", "'paramstyle'", "]", "==", "'named'", "or", "mod_info", "[", "'paramstyle'", "]", "==", "'pyformat'", ")", ":", "prepare_sf_row", "=", "lambda", "x", ":", "x", "else", ":", "col_names", "=", "self", ".", "column_names", "(", ")", "prepare_sf_row", "=", "lambda", "x", ":", "[", "x", "[", "i", "]", "for", "i", "in", "col_names", "]", "for", "i", "in", "self", ":", "try", ":", "c", ".", "execute", "(", "ins_str", ",", "prepare_sf_row", "(", "i", ")", ")", "except", "mod_info", "[", "'Error'", "]", "as", "e", ":", "if", "hasattr", "(", "conn", ",", "'rollback'", ")", ":", "conn", ".", "rollback", "(", ")", "raise", "e", "conn", ".", "commit", "(", ")", "c", ".", "close", "(", ")" ]
Convert an SFrame to a single table in a SQL database. This function does not attempt to create the table or check if a table named `table_name` exists in the database. It simply assumes that `table_name` exists in the database and appends to it. `to_sql` can be thought of as a convenience wrapper around parameterized SQL insert statements. Parameters ---------- conn : dbapi2.Connection A DBAPI2 connection object. Any connection object originating from the 'connect' method of a DBAPI2-compliant package can be used. table_name : str The name of the table to append the data in this SFrame. dbapi_module : module | package, optional The top-level DBAPI2 module/package that constructed the given connection object. By default, a best guess of which module the connection came from is made. In the event that this guess is wrong, this will need to be specified. use_python_type_specifiers : bool, optional If the DBAPI2 module's parameter marker style is 'format' or 'pyformat', attempt to use accurate type specifiers for each value ('s' for string, 'd' for integer, etc.). Many DBAPI2 modules simply use 's' for all types if they use these parameter markers, so this is False by default. use_exact_column_names : bool, optional Specify the column names of the SFrame when inserting its contents into the DB. If the specified table does not have the exact same column names as the SFrame, inserting the data will fail. If False, the columns in the SFrame are inserted in order without care of the schema of the DB table. True by default.
[ "Convert", "an", "SFrame", "to", "a", "single", "table", "in", "a", "SQL", "database", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L1845-L1942
29,033
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.print_rows
def print_rows(self, num_rows=10, num_columns=40, max_column_width=30, max_row_width=80, output_file=None): """ Print the first M rows and N columns of the SFrame in human readable format. Parameters ---------- num_rows : int, optional Number of rows to print. num_columns : int, optional Number of columns to print. max_column_width : int, optional Maximum width of a column. Columns use fewer characters if possible. max_row_width : int, optional Maximum width of a printed row. Columns beyond this width wrap to a new line. `max_row_width` is automatically reset to be the larger of itself and `max_column_width`. output_file: file, optional The stream or file that receives the output. By default the output goes to sys.stdout, but it can also be redirected to a file or a string (using an object of type StringIO). See Also -------- head, tail """ if output_file is None: output_file = sys.stdout max_row_width = max(max_row_width, max_column_width + 1) printed_sf = self._imagecols_to_stringcols(num_rows) row_of_tables = printed_sf.__get_pretty_tables__(wrap_text=False, max_rows_to_display=num_rows, max_columns=num_columns, max_column_width=max_column_width, max_row_width=max_row_width) footer = "[%d rows x %d columns]\n" % self.shape print('\n'.join([str(tb) for tb in row_of_tables]) + "\n" + footer, file=output_file)
python
def print_rows(self, num_rows=10, num_columns=40, max_column_width=30, max_row_width=80, output_file=None): """ Print the first M rows and N columns of the SFrame in human readable format. Parameters ---------- num_rows : int, optional Number of rows to print. num_columns : int, optional Number of columns to print. max_column_width : int, optional Maximum width of a column. Columns use fewer characters if possible. max_row_width : int, optional Maximum width of a printed row. Columns beyond this width wrap to a new line. `max_row_width` is automatically reset to be the larger of itself and `max_column_width`. output_file: file, optional The stream or file that receives the output. By default the output goes to sys.stdout, but it can also be redirected to a file or a string (using an object of type StringIO). See Also -------- head, tail """ if output_file is None: output_file = sys.stdout max_row_width = max(max_row_width, max_column_width + 1) printed_sf = self._imagecols_to_stringcols(num_rows) row_of_tables = printed_sf.__get_pretty_tables__(wrap_text=False, max_rows_to_display=num_rows, max_columns=num_columns, max_column_width=max_column_width, max_row_width=max_row_width) footer = "[%d rows x %d columns]\n" % self.shape print('\n'.join([str(tb) for tb in row_of_tables]) + "\n" + footer, file=output_file)
[ "def", "print_rows", "(", "self", ",", "num_rows", "=", "10", ",", "num_columns", "=", "40", ",", "max_column_width", "=", "30", ",", "max_row_width", "=", "80", ",", "output_file", "=", "None", ")", ":", "if", "output_file", "is", "None", ":", "output_file", "=", "sys", ".", "stdout", "max_row_width", "=", "max", "(", "max_row_width", ",", "max_column_width", "+", "1", ")", "printed_sf", "=", "self", ".", "_imagecols_to_stringcols", "(", "num_rows", ")", "row_of_tables", "=", "printed_sf", ".", "__get_pretty_tables__", "(", "wrap_text", "=", "False", ",", "max_rows_to_display", "=", "num_rows", ",", "max_columns", "=", "num_columns", ",", "max_column_width", "=", "max_column_width", ",", "max_row_width", "=", "max_row_width", ")", "footer", "=", "\"[%d rows x %d columns]\\n\"", "%", "self", ".", "shape", "print", "(", "'\\n'", ".", "join", "(", "[", "str", "(", "tb", ")", "for", "tb", "in", "row_of_tables", "]", ")", "+", "\"\\n\"", "+", "footer", ",", "file", "=", "output_file", ")" ]
Print the first M rows and N columns of the SFrame in human readable format. Parameters ---------- num_rows : int, optional Number of rows to print. num_columns : int, optional Number of columns to print. max_column_width : int, optional Maximum width of a column. Columns use fewer characters if possible. max_row_width : int, optional Maximum width of a printed row. Columns beyond this width wrap to a new line. `max_row_width` is automatically reset to be the larger of itself and `max_column_width`. output_file: file, optional The stream or file that receives the output. By default the output goes to sys.stdout, but it can also be redirected to a file or a string (using an object of type StringIO). See Also -------- head, tail
[ "Print", "the", "first", "M", "rows", "and", "N", "columns", "of", "the", "SFrame", "in", "human", "readable", "format", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L2117-L2160
29,034
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame._row_selector
def _row_selector(self, other): """ Where other is an SArray of identical length as the current Frame, this returns a selection of a subset of rows in the current SFrame where the corresponding row in the selector is non-zero. """ if type(other) is SArray: if self.__has_size__() and other.__has_size__() and len(other) != len(self): raise IndexError("Cannot perform logical indexing on arrays of different length.") with cython_context(): return SFrame(_proxy=self.__proxy__.logical_filter(other.__proxy__))
python
def _row_selector(self, other): """ Where other is an SArray of identical length as the current Frame, this returns a selection of a subset of rows in the current SFrame where the corresponding row in the selector is non-zero. """ if type(other) is SArray: if self.__has_size__() and other.__has_size__() and len(other) != len(self): raise IndexError("Cannot perform logical indexing on arrays of different length.") with cython_context(): return SFrame(_proxy=self.__proxy__.logical_filter(other.__proxy__))
[ "def", "_row_selector", "(", "self", ",", "other", ")", ":", "if", "type", "(", "other", ")", "is", "SArray", ":", "if", "self", ".", "__has_size__", "(", ")", "and", "other", ".", "__has_size__", "(", ")", "and", "len", "(", "other", ")", "!=", "len", "(", "self", ")", ":", "raise", "IndexError", "(", "\"Cannot perform logical indexing on arrays of different length.\"", ")", "with", "cython_context", "(", ")", ":", "return", "SFrame", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "logical_filter", "(", "other", ".", "__proxy__", ")", ")" ]
Where other is an SArray of identical length as the current Frame, this returns a selection of a subset of rows in the current SFrame where the corresponding row in the selector is non-zero.
[ "Where", "other", "is", "an", "SArray", "of", "identical", "length", "as", "the", "current", "Frame", "this", "returns", "a", "selection", "of", "a", "subset", "of", "rows", "in", "the", "current", "SFrame", "where", "the", "corresponding", "row", "in", "the", "selector", "is", "non", "-", "zero", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L2268-L2278
29,035
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.to_dataframe
def to_dataframe(self): """ Convert this SFrame to pandas.DataFrame. This operation will construct a pandas.DataFrame in memory. Care must be taken when size of the returned object is big. Returns ------- out : pandas.DataFrame The dataframe which contains all rows of SFrame """ assert HAS_PANDAS, 'pandas is not installed.' df = pandas.DataFrame() for i in range(self.num_columns()): column_name = self.column_names()[i] df[column_name] = list(self[column_name]) if len(df[column_name]) == 0: df[column_name] = df[column_name].astype(self.column_types()[i]) return df
python
def to_dataframe(self): """ Convert this SFrame to pandas.DataFrame. This operation will construct a pandas.DataFrame in memory. Care must be taken when size of the returned object is big. Returns ------- out : pandas.DataFrame The dataframe which contains all rows of SFrame """ assert HAS_PANDAS, 'pandas is not installed.' df = pandas.DataFrame() for i in range(self.num_columns()): column_name = self.column_names()[i] df[column_name] = list(self[column_name]) if len(df[column_name]) == 0: df[column_name] = df[column_name].astype(self.column_types()[i]) return df
[ "def", "to_dataframe", "(", "self", ")", ":", "assert", "HAS_PANDAS", ",", "'pandas is not installed.'", "df", "=", "pandas", ".", "DataFrame", "(", ")", "for", "i", "in", "range", "(", "self", ".", "num_columns", "(", ")", ")", ":", "column_name", "=", "self", ".", "column_names", "(", ")", "[", "i", "]", "df", "[", "column_name", "]", "=", "list", "(", "self", "[", "column_name", "]", ")", "if", "len", "(", "df", "[", "column_name", "]", ")", "==", "0", ":", "df", "[", "column_name", "]", "=", "df", "[", "column_name", "]", ".", "astype", "(", "self", ".", "column_types", "(", ")", "[", "i", "]", ")", "return", "df" ]
Convert this SFrame to pandas.DataFrame. This operation will construct a pandas.DataFrame in memory. Care must be taken when size of the returned object is big. Returns ------- out : pandas.DataFrame The dataframe which contains all rows of SFrame
[ "Convert", "this", "SFrame", "to", "pandas", ".", "DataFrame", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L2376-L2395
29,036
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.to_numpy
def to_numpy(self): """ Converts this SFrame to a numpy array This operation will construct a numpy array in memory. Care must be taken when size of the returned object is big. Returns ------- out : numpy.ndarray A Numpy Array containing all the values of the SFrame """ assert HAS_NUMPY, 'numpy is not installed.' import numpy return numpy.transpose(numpy.asarray([self[x] for x in self.column_names()]))
python
def to_numpy(self): """ Converts this SFrame to a numpy array This operation will construct a numpy array in memory. Care must be taken when size of the returned object is big. Returns ------- out : numpy.ndarray A Numpy Array containing all the values of the SFrame """ assert HAS_NUMPY, 'numpy is not installed.' import numpy return numpy.transpose(numpy.asarray([self[x] for x in self.column_names()]))
[ "def", "to_numpy", "(", "self", ")", ":", "assert", "HAS_NUMPY", ",", "'numpy is not installed.'", "import", "numpy", "return", "numpy", ".", "transpose", "(", "numpy", ".", "asarray", "(", "[", "self", "[", "x", "]", "for", "x", "in", "self", ".", "column_names", "(", ")", "]", ")", ")" ]
Converts this SFrame to a numpy array This operation will construct a numpy array in memory. Care must be taken when size of the returned object is big. Returns ------- out : numpy.ndarray A Numpy Array containing all the values of the SFrame
[ "Converts", "this", "SFrame", "to", "a", "numpy", "array" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L2397-L2412
29,037
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.flat_map
def flat_map(self, column_names, fn, column_types='auto', seed=None): """ Map each row of the SFrame to multiple rows in a new SFrame via a function. The output of `fn` must have type List[List[...]]. Each inner list will be a single row in the new output, and the collection of these rows within the outer list make up the data for the output SFrame. All rows must have the same length and the same order of types to make sure the result columns are homogeneously typed. For example, if the first element emitted into in the outer list by `fn` is [43, 2.3, 'string'], then all other elements emitted into the outer list must be a list with three elements, where the first is an int, second is a float, and third is a string. If column_types is not specified, the first 10 rows of the SFrame are used to determine the column types of the returned sframe. Parameters ---------- column_names : list[str] The column names for the returned SFrame. fn : function The function that maps each of the sframe row into multiple rows, returning List[List[...]]. All outputted rows must have the same length and order of types. column_types : list[type], optional The column types of the output SFrame. Default value will be automatically inferred by running `fn` on the first 10 rows of the input. If the types cannot be inferred from the first 10 rows, an error is raised. seed : int, optional Used as the seed if a random number generator is included in `fn`. Returns ------- out : SFrame A new SFrame containing the results of the flat_map of the original SFrame. Examples --------- Repeat each row according to the value in the 'number' column. >>> sf = turicreate.SFrame({'letter': ['a', 'b', 'c'], ... 'number': [1, 2, 3]}) >>> sf.flat_map(['number', 'letter'], ... lambda x: [list(x.itervalues()) for i in range(0, x['number'])]) +--------+--------+ | number | letter | +--------+--------+ | 1 | a | | 2 | b | | 2 | b | | 3 | c | | 3 | c | | 3 | c | +--------+--------+ [6 rows x 2 columns] """ assert callable(fn), "Input must be callable" if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) # determine the column_types if column_types == 'auto': types = set() sample = self[0:10] results = [fn(row) for row in sample] for rows in results: if type(rows) is not list: raise TypeError("Output type of the lambda function must be a list of lists") # note: this skips empty lists for row in rows: if type(row) is not list: raise TypeError("Output type of the lambda function must be a list of lists") types.add(tuple([type(v) for v in row])) if len(types) == 0: raise TypeError( "Could not infer output column types from the first ten rows " +\ "of the SFrame. Please use the 'column_types' parameter to " +\ "set the types.") if len(types) > 1: raise TypeError("Mapped rows must have the same length and types") column_types = list(types.pop()) assert type(column_types) is list, "'column_types' must be a list." assert len(column_types) == len(column_names), "Number of output columns must match the size of column names" with cython_context(): return SFrame(_proxy=self.__proxy__.flat_map(fn, column_names, column_types, seed))
python
def flat_map(self, column_names, fn, column_types='auto', seed=None): """ Map each row of the SFrame to multiple rows in a new SFrame via a function. The output of `fn` must have type List[List[...]]. Each inner list will be a single row in the new output, and the collection of these rows within the outer list make up the data for the output SFrame. All rows must have the same length and the same order of types to make sure the result columns are homogeneously typed. For example, if the first element emitted into in the outer list by `fn` is [43, 2.3, 'string'], then all other elements emitted into the outer list must be a list with three elements, where the first is an int, second is a float, and third is a string. If column_types is not specified, the first 10 rows of the SFrame are used to determine the column types of the returned sframe. Parameters ---------- column_names : list[str] The column names for the returned SFrame. fn : function The function that maps each of the sframe row into multiple rows, returning List[List[...]]. All outputted rows must have the same length and order of types. column_types : list[type], optional The column types of the output SFrame. Default value will be automatically inferred by running `fn` on the first 10 rows of the input. If the types cannot be inferred from the first 10 rows, an error is raised. seed : int, optional Used as the seed if a random number generator is included in `fn`. Returns ------- out : SFrame A new SFrame containing the results of the flat_map of the original SFrame. Examples --------- Repeat each row according to the value in the 'number' column. >>> sf = turicreate.SFrame({'letter': ['a', 'b', 'c'], ... 'number': [1, 2, 3]}) >>> sf.flat_map(['number', 'letter'], ... lambda x: [list(x.itervalues()) for i in range(0, x['number'])]) +--------+--------+ | number | letter | +--------+--------+ | 1 | a | | 2 | b | | 2 | b | | 3 | c | | 3 | c | | 3 | c | +--------+--------+ [6 rows x 2 columns] """ assert callable(fn), "Input must be callable" if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) # determine the column_types if column_types == 'auto': types = set() sample = self[0:10] results = [fn(row) for row in sample] for rows in results: if type(rows) is not list: raise TypeError("Output type of the lambda function must be a list of lists") # note: this skips empty lists for row in rows: if type(row) is not list: raise TypeError("Output type of the lambda function must be a list of lists") types.add(tuple([type(v) for v in row])) if len(types) == 0: raise TypeError( "Could not infer output column types from the first ten rows " +\ "of the SFrame. Please use the 'column_types' parameter to " +\ "set the types.") if len(types) > 1: raise TypeError("Mapped rows must have the same length and types") column_types = list(types.pop()) assert type(column_types) is list, "'column_types' must be a list." assert len(column_types) == len(column_names), "Number of output columns must match the size of column names" with cython_context(): return SFrame(_proxy=self.__proxy__.flat_map(fn, column_names, column_types, seed))
[ "def", "flat_map", "(", "self", ",", "column_names", ",", "fn", ",", "column_types", "=", "'auto'", ",", "seed", "=", "None", ")", ":", "assert", "callable", "(", "fn", ")", ",", "\"Input must be callable\"", "if", "seed", "is", "None", ":", "seed", "=", "abs", "(", "hash", "(", "\"%0.20f\"", "%", "time", ".", "time", "(", ")", ")", ")", "%", "(", "2", "**", "31", ")", "# determine the column_types", "if", "column_types", "==", "'auto'", ":", "types", "=", "set", "(", ")", "sample", "=", "self", "[", "0", ":", "10", "]", "results", "=", "[", "fn", "(", "row", ")", "for", "row", "in", "sample", "]", "for", "rows", "in", "results", ":", "if", "type", "(", "rows", ")", "is", "not", "list", ":", "raise", "TypeError", "(", "\"Output type of the lambda function must be a list of lists\"", ")", "# note: this skips empty lists", "for", "row", "in", "rows", ":", "if", "type", "(", "row", ")", "is", "not", "list", ":", "raise", "TypeError", "(", "\"Output type of the lambda function must be a list of lists\"", ")", "types", ".", "add", "(", "tuple", "(", "[", "type", "(", "v", ")", "for", "v", "in", "row", "]", ")", ")", "if", "len", "(", "types", ")", "==", "0", ":", "raise", "TypeError", "(", "\"Could not infer output column types from the first ten rows \"", "+", "\"of the SFrame. Please use the 'column_types' parameter to \"", "+", "\"set the types.\"", ")", "if", "len", "(", "types", ")", ">", "1", ":", "raise", "TypeError", "(", "\"Mapped rows must have the same length and types\"", ")", "column_types", "=", "list", "(", "types", ".", "pop", "(", ")", ")", "assert", "type", "(", "column_types", ")", "is", "list", ",", "\"'column_types' must be a list.\"", "assert", "len", "(", "column_types", ")", "==", "len", "(", "column_names", ")", ",", "\"Number of output columns must match the size of column names\"", "with", "cython_context", "(", ")", ":", "return", "SFrame", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "flat_map", "(", "fn", ",", "column_names", ",", "column_types", ",", "seed", ")", ")" ]
Map each row of the SFrame to multiple rows in a new SFrame via a function. The output of `fn` must have type List[List[...]]. Each inner list will be a single row in the new output, and the collection of these rows within the outer list make up the data for the output SFrame. All rows must have the same length and the same order of types to make sure the result columns are homogeneously typed. For example, if the first element emitted into in the outer list by `fn` is [43, 2.3, 'string'], then all other elements emitted into the outer list must be a list with three elements, where the first is an int, second is a float, and third is a string. If column_types is not specified, the first 10 rows of the SFrame are used to determine the column types of the returned sframe. Parameters ---------- column_names : list[str] The column names for the returned SFrame. fn : function The function that maps each of the sframe row into multiple rows, returning List[List[...]]. All outputted rows must have the same length and order of types. column_types : list[type], optional The column types of the output SFrame. Default value will be automatically inferred by running `fn` on the first 10 rows of the input. If the types cannot be inferred from the first 10 rows, an error is raised. seed : int, optional Used as the seed if a random number generator is included in `fn`. Returns ------- out : SFrame A new SFrame containing the results of the flat_map of the original SFrame. Examples --------- Repeat each row according to the value in the 'number' column. >>> sf = turicreate.SFrame({'letter': ['a', 'b', 'c'], ... 'number': [1, 2, 3]}) >>> sf.flat_map(['number', 'letter'], ... lambda x: [list(x.itervalues()) for i in range(0, x['number'])]) +--------+--------+ | number | letter | +--------+--------+ | 1 | a | | 2 | b | | 2 | b | | 3 | c | | 3 | c | | 3 | c | +--------+--------+ [6 rows x 2 columns]
[ "Map", "each", "row", "of", "the", "SFrame", "to", "multiple", "rows", "in", "a", "new", "SFrame", "via", "a", "function", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L2502-L2599
29,038
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.sample
def sample(self, fraction, seed=None, exact=False): """ Sample a fraction of the current SFrame's rows. 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 Seed for the random number generator used to sample. exact: bool, optional Defaults to False. If exact=True, an exact fraction is returned, but at a performance penalty. Returns ------- out : SFrame A new SFrame containing sampled rows of the current SFrame. Examples -------- Suppose we have an SFrame with 6,145 rows. >>> import random >>> sf = SFrame({'id': range(0, 6145)}) Retrieve about 30% of the SFrame rows with repeatable results by setting the random seed. >>> len(sf.sample(.3, seed=5)) 1783 """ if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) if (fraction > 1 or fraction < 0): raise ValueError('Invalid sampling rate: ' + str(fraction)) if (self.num_rows() == 0 or self.num_columns() == 0): return self else: with cython_context(): return SFrame(_proxy=self.__proxy__.sample(fraction, seed, exact))
python
def sample(self, fraction, seed=None, exact=False): """ Sample a fraction of the current SFrame's rows. 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 Seed for the random number generator used to sample. exact: bool, optional Defaults to False. If exact=True, an exact fraction is returned, but at a performance penalty. Returns ------- out : SFrame A new SFrame containing sampled rows of the current SFrame. Examples -------- Suppose we have an SFrame with 6,145 rows. >>> import random >>> sf = SFrame({'id': range(0, 6145)}) Retrieve about 30% of the SFrame rows with repeatable results by setting the random seed. >>> len(sf.sample(.3, seed=5)) 1783 """ if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) if (fraction > 1 or fraction < 0): raise ValueError('Invalid sampling rate: ' + str(fraction)) if (self.num_rows() == 0 or self.num_columns() == 0): return self else: with cython_context(): return SFrame(_proxy=self.__proxy__.sample(fraction, seed, exact))
[ "def", "sample", "(", "self", ",", "fraction", ",", "seed", "=", "None", ",", "exact", "=", "False", ")", ":", "if", "seed", "is", "None", ":", "seed", "=", "abs", "(", "hash", "(", "\"%0.20f\"", "%", "time", ".", "time", "(", ")", ")", ")", "%", "(", "2", "**", "31", ")", "if", "(", "fraction", ">", "1", "or", "fraction", "<", "0", ")", ":", "raise", "ValueError", "(", "'Invalid sampling rate: '", "+", "str", "(", "fraction", ")", ")", "if", "(", "self", ".", "num_rows", "(", ")", "==", "0", "or", "self", ".", "num_columns", "(", ")", "==", "0", ")", ":", "return", "self", "else", ":", "with", "cython_context", "(", ")", ":", "return", "SFrame", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "sample", "(", "fraction", ",", "seed", ",", "exact", ")", ")" ]
Sample a fraction of the current SFrame's rows. 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 Seed for the random number generator used to sample. exact: bool, optional Defaults to False. If exact=True, an exact fraction is returned, but at a performance penalty. Returns ------- out : SFrame A new SFrame containing sampled rows of the current SFrame. Examples -------- Suppose we have an SFrame with 6,145 rows. >>> import random >>> sf = SFrame({'id': range(0, 6145)}) Retrieve about 30% of the SFrame rows with repeatable results by setting the random seed. >>> len(sf.sample(.3, seed=5)) 1783
[ "Sample", "a", "fraction", "of", "the", "current", "SFrame", "s", "rows", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L2601-L2648
29,039
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.save
def save(self, filename, format=None): """ Save the SFrame to a file system for later use. Parameters ---------- filename : string The location to save the SFrame. Either a local directory or a remote URL. If the format is 'binary', a directory will be created at the location which will contain the sframe. format : {'binary', 'csv', 'json'}, optional Format in which to save the SFrame. Binary saved SFrames can be loaded much faster and without any format conversion losses. If not given, will try to infer the format from filename given. If file name ends with 'csv' or '.csv.gz', then save as 'csv' format, otherwise save as 'binary' format. See export_csv for more csv saving options. See Also -------- load_sframe, SFrame Examples -------- >>> # Save the sframe into binary format >>> sf.save('data/training_data_sframe') >>> # Save the sframe into csv format >>> sf.save('data/training_data.csv', format='csv') """ if format is None: if filename.endswith(('.csv', '.csv.gz')): format = 'csv' elif filename.endswith(('.json')): format = 'json' else: format = 'binary' else: if format is 'csv': if not filename.endswith(('.csv', '.csv.gz')): filename = filename + '.csv' elif format is not 'binary' and format is not 'json': raise ValueError("Invalid format: {}. Supported formats are 'csv' and 'binary' and 'json'".format(format)) ## Save the SFrame url = _make_internal_url(filename) with cython_context(): if format is 'binary': self.__proxy__.save(url) elif format is 'csv': assert filename.endswith(('.csv', '.csv.gz')) self.__proxy__.save_as_csv(url, {}) elif format is 'json': self.export_json(url) else: raise ValueError("Unsupported format: {}".format(format))
python
def save(self, filename, format=None): """ Save the SFrame to a file system for later use. Parameters ---------- filename : string The location to save the SFrame. Either a local directory or a remote URL. If the format is 'binary', a directory will be created at the location which will contain the sframe. format : {'binary', 'csv', 'json'}, optional Format in which to save the SFrame. Binary saved SFrames can be loaded much faster and without any format conversion losses. If not given, will try to infer the format from filename given. If file name ends with 'csv' or '.csv.gz', then save as 'csv' format, otherwise save as 'binary' format. See export_csv for more csv saving options. See Also -------- load_sframe, SFrame Examples -------- >>> # Save the sframe into binary format >>> sf.save('data/training_data_sframe') >>> # Save the sframe into csv format >>> sf.save('data/training_data.csv', format='csv') """ if format is None: if filename.endswith(('.csv', '.csv.gz')): format = 'csv' elif filename.endswith(('.json')): format = 'json' else: format = 'binary' else: if format is 'csv': if not filename.endswith(('.csv', '.csv.gz')): filename = filename + '.csv' elif format is not 'binary' and format is not 'json': raise ValueError("Invalid format: {}. Supported formats are 'csv' and 'binary' and 'json'".format(format)) ## Save the SFrame url = _make_internal_url(filename) with cython_context(): if format is 'binary': self.__proxy__.save(url) elif format is 'csv': assert filename.endswith(('.csv', '.csv.gz')) self.__proxy__.save_as_csv(url, {}) elif format is 'json': self.export_json(url) else: raise ValueError("Unsupported format: {}".format(format))
[ "def", "save", "(", "self", ",", "filename", ",", "format", "=", "None", ")", ":", "if", "format", "is", "None", ":", "if", "filename", ".", "endswith", "(", "(", "'.csv'", ",", "'.csv.gz'", ")", ")", ":", "format", "=", "'csv'", "elif", "filename", ".", "endswith", "(", "(", "'.json'", ")", ")", ":", "format", "=", "'json'", "else", ":", "format", "=", "'binary'", "else", ":", "if", "format", "is", "'csv'", ":", "if", "not", "filename", ".", "endswith", "(", "(", "'.csv'", ",", "'.csv.gz'", ")", ")", ":", "filename", "=", "filename", "+", "'.csv'", "elif", "format", "is", "not", "'binary'", "and", "format", "is", "not", "'json'", ":", "raise", "ValueError", "(", "\"Invalid format: {}. Supported formats are 'csv' and 'binary' and 'json'\"", ".", "format", "(", "format", ")", ")", "## Save the SFrame", "url", "=", "_make_internal_url", "(", "filename", ")", "with", "cython_context", "(", ")", ":", "if", "format", "is", "'binary'", ":", "self", ".", "__proxy__", ".", "save", "(", "url", ")", "elif", "format", "is", "'csv'", ":", "assert", "filename", ".", "endswith", "(", "(", "'.csv'", ",", "'.csv.gz'", ")", ")", "self", ".", "__proxy__", ".", "save_as_csv", "(", "url", ",", "{", "}", ")", "elif", "format", "is", "'json'", ":", "self", ".", "export_json", "(", "url", ")", "else", ":", "raise", "ValueError", "(", "\"Unsupported format: {}\"", ".", "format", "(", "format", ")", ")" ]
Save the SFrame to a file system for later use. Parameters ---------- filename : string The location to save the SFrame. Either a local directory or a remote URL. If the format is 'binary', a directory will be created at the location which will contain the sframe. format : {'binary', 'csv', 'json'}, optional Format in which to save the SFrame. Binary saved SFrames can be loaded much faster and without any format conversion losses. If not given, will try to infer the format from filename given. If file name ends with 'csv' or '.csv.gz', then save as 'csv' format, otherwise save as 'binary' format. See export_csv for more csv saving options. See Also -------- load_sframe, SFrame Examples -------- >>> # Save the sframe into binary format >>> sf.save('data/training_data_sframe') >>> # Save the sframe into csv format >>> sf.save('data/training_data.csv', format='csv')
[ "Save", "the", "SFrame", "to", "a", "file", "system", "for", "later", "use", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L2768-L2826
29,040
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.export_csv
def export_csv(self, filename, delimiter=',', line_terminator='\n', header=True, quote_level=csv.QUOTE_NONNUMERIC, double_quote=True, escape_char='\\', quote_char='\"', na_rep='', file_header='', file_footer='', line_prefix='', _no_prefix_on_first_value=False, **kwargs): """ Writes an SFrame to a CSV file. Parameters ---------- filename : string The location to save the CSV. delimiter : string, optional This describes the delimiter used for writing csv files. line_terminator: string, optional The newline character header : bool, optional If true, the column names are emitted as a header. quote_level: csv.QUOTE_ALL | csv.QUOTE_NONE | csv.QUOTE_NONNUMERIC, optional The quoting level. If csv.QUOTE_ALL, every field is quoted. if csv.quote_NONE, no field is quoted. If csv.QUOTE_NONNUMERIC, only non-numeric fileds are quoted. csv.QUOTE_MINIMAL is interpreted as csv.QUOTE_NONNUMERIC. double_quote : bool, optional If True, quotes are escaped as two consecutive quotes escape_char : string, optional Character which begins a C escape sequence quote_char: string, optional Character used to quote fields na_rep: string, optional The value used to denote a missing value. file_header: string, optional A string printed to the start of the file file_footer: string, optional A string printed to the end of the file line_prefix: string, optional A string printed at the start of each value line """ # Pandas argument compatibility if "sep" in kwargs: delimiter = kwargs['sep'] del kwargs['sep'] if "quotechar" in kwargs: quote_char = kwargs['quotechar'] del kwargs['quotechar'] if "doublequote" in kwargs: double_quote = kwargs['doublequote'] del kwargs['doublequote'] if "lineterminator" in kwargs: line_terminator = kwargs['lineterminator'] del kwargs['lineterminator'] if len(kwargs) > 0: raise TypeError("Unexpected keyword arguments " + str(list(kwargs.keys()))) write_csv_options = {} write_csv_options['delimiter'] = delimiter write_csv_options['escape_char'] = escape_char write_csv_options['double_quote'] = double_quote write_csv_options['quote_char'] = quote_char if quote_level == csv.QUOTE_MINIMAL: write_csv_options['quote_level'] = 0 elif quote_level == csv.QUOTE_ALL: write_csv_options['quote_level'] = 1 elif quote_level == csv.QUOTE_NONNUMERIC: write_csv_options['quote_level'] = 2 elif quote_level == csv.QUOTE_NONE: write_csv_options['quote_level'] = 3 write_csv_options['header'] = header write_csv_options['line_terminator'] = line_terminator write_csv_options['na_value'] = na_rep write_csv_options['file_header'] = file_header write_csv_options['file_footer'] = file_footer write_csv_options['line_prefix'] = line_prefix # undocumented option. Disables line prefix on the first value line write_csv_options['_no_prefix_on_first_value'] = _no_prefix_on_first_value url = _make_internal_url(filename) self.__proxy__.save_as_csv(url, write_csv_options)
python
def export_csv(self, filename, delimiter=',', line_terminator='\n', header=True, quote_level=csv.QUOTE_NONNUMERIC, double_quote=True, escape_char='\\', quote_char='\"', na_rep='', file_header='', file_footer='', line_prefix='', _no_prefix_on_first_value=False, **kwargs): """ Writes an SFrame to a CSV file. Parameters ---------- filename : string The location to save the CSV. delimiter : string, optional This describes the delimiter used for writing csv files. line_terminator: string, optional The newline character header : bool, optional If true, the column names are emitted as a header. quote_level: csv.QUOTE_ALL | csv.QUOTE_NONE | csv.QUOTE_NONNUMERIC, optional The quoting level. If csv.QUOTE_ALL, every field is quoted. if csv.quote_NONE, no field is quoted. If csv.QUOTE_NONNUMERIC, only non-numeric fileds are quoted. csv.QUOTE_MINIMAL is interpreted as csv.QUOTE_NONNUMERIC. double_quote : bool, optional If True, quotes are escaped as two consecutive quotes escape_char : string, optional Character which begins a C escape sequence quote_char: string, optional Character used to quote fields na_rep: string, optional The value used to denote a missing value. file_header: string, optional A string printed to the start of the file file_footer: string, optional A string printed to the end of the file line_prefix: string, optional A string printed at the start of each value line """ # Pandas argument compatibility if "sep" in kwargs: delimiter = kwargs['sep'] del kwargs['sep'] if "quotechar" in kwargs: quote_char = kwargs['quotechar'] del kwargs['quotechar'] if "doublequote" in kwargs: double_quote = kwargs['doublequote'] del kwargs['doublequote'] if "lineterminator" in kwargs: line_terminator = kwargs['lineterminator'] del kwargs['lineterminator'] if len(kwargs) > 0: raise TypeError("Unexpected keyword arguments " + str(list(kwargs.keys()))) write_csv_options = {} write_csv_options['delimiter'] = delimiter write_csv_options['escape_char'] = escape_char write_csv_options['double_quote'] = double_quote write_csv_options['quote_char'] = quote_char if quote_level == csv.QUOTE_MINIMAL: write_csv_options['quote_level'] = 0 elif quote_level == csv.QUOTE_ALL: write_csv_options['quote_level'] = 1 elif quote_level == csv.QUOTE_NONNUMERIC: write_csv_options['quote_level'] = 2 elif quote_level == csv.QUOTE_NONE: write_csv_options['quote_level'] = 3 write_csv_options['header'] = header write_csv_options['line_terminator'] = line_terminator write_csv_options['na_value'] = na_rep write_csv_options['file_header'] = file_header write_csv_options['file_footer'] = file_footer write_csv_options['line_prefix'] = line_prefix # undocumented option. Disables line prefix on the first value line write_csv_options['_no_prefix_on_first_value'] = _no_prefix_on_first_value url = _make_internal_url(filename) self.__proxy__.save_as_csv(url, write_csv_options)
[ "def", "export_csv", "(", "self", ",", "filename", ",", "delimiter", "=", "','", ",", "line_terminator", "=", "'\\n'", ",", "header", "=", "True", ",", "quote_level", "=", "csv", ".", "QUOTE_NONNUMERIC", ",", "double_quote", "=", "True", ",", "escape_char", "=", "'\\\\'", ",", "quote_char", "=", "'\\\"'", ",", "na_rep", "=", "''", ",", "file_header", "=", "''", ",", "file_footer", "=", "''", ",", "line_prefix", "=", "''", ",", "_no_prefix_on_first_value", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# Pandas argument compatibility", "if", "\"sep\"", "in", "kwargs", ":", "delimiter", "=", "kwargs", "[", "'sep'", "]", "del", "kwargs", "[", "'sep'", "]", "if", "\"quotechar\"", "in", "kwargs", ":", "quote_char", "=", "kwargs", "[", "'quotechar'", "]", "del", "kwargs", "[", "'quotechar'", "]", "if", "\"doublequote\"", "in", "kwargs", ":", "double_quote", "=", "kwargs", "[", "'doublequote'", "]", "del", "kwargs", "[", "'doublequote'", "]", "if", "\"lineterminator\"", "in", "kwargs", ":", "line_terminator", "=", "kwargs", "[", "'lineterminator'", "]", "del", "kwargs", "[", "'lineterminator'", "]", "if", "len", "(", "kwargs", ")", ">", "0", ":", "raise", "TypeError", "(", "\"Unexpected keyword arguments \"", "+", "str", "(", "list", "(", "kwargs", ".", "keys", "(", ")", ")", ")", ")", "write_csv_options", "=", "{", "}", "write_csv_options", "[", "'delimiter'", "]", "=", "delimiter", "write_csv_options", "[", "'escape_char'", "]", "=", "escape_char", "write_csv_options", "[", "'double_quote'", "]", "=", "double_quote", "write_csv_options", "[", "'quote_char'", "]", "=", "quote_char", "if", "quote_level", "==", "csv", ".", "QUOTE_MINIMAL", ":", "write_csv_options", "[", "'quote_level'", "]", "=", "0", "elif", "quote_level", "==", "csv", ".", "QUOTE_ALL", ":", "write_csv_options", "[", "'quote_level'", "]", "=", "1", "elif", "quote_level", "==", "csv", ".", "QUOTE_NONNUMERIC", ":", "write_csv_options", "[", "'quote_level'", "]", "=", "2", "elif", "quote_level", "==", "csv", ".", "QUOTE_NONE", ":", "write_csv_options", "[", "'quote_level'", "]", "=", "3", "write_csv_options", "[", "'header'", "]", "=", "header", "write_csv_options", "[", "'line_terminator'", "]", "=", "line_terminator", "write_csv_options", "[", "'na_value'", "]", "=", "na_rep", "write_csv_options", "[", "'file_header'", "]", "=", "file_header", "write_csv_options", "[", "'file_footer'", "]", "=", "file_footer", "write_csv_options", "[", "'line_prefix'", "]", "=", "line_prefix", "# undocumented option. Disables line prefix on the first value line", "write_csv_options", "[", "'_no_prefix_on_first_value'", "]", "=", "_no_prefix_on_first_value", "url", "=", "_make_internal_url", "(", "filename", ")", "self", ".", "__proxy__", ".", "save_as_csv", "(", "url", ",", "write_csv_options", ")" ]
Writes an SFrame to a CSV file. Parameters ---------- filename : string The location to save the CSV. delimiter : string, optional This describes the delimiter used for writing csv files. line_terminator: string, optional The newline character header : bool, optional If true, the column names are emitted as a header. quote_level: csv.QUOTE_ALL | csv.QUOTE_NONE | csv.QUOTE_NONNUMERIC, optional The quoting level. If csv.QUOTE_ALL, every field is quoted. if csv.quote_NONE, no field is quoted. If csv.QUOTE_NONNUMERIC, only non-numeric fileds are quoted. csv.QUOTE_MINIMAL is interpreted as csv.QUOTE_NONNUMERIC. double_quote : bool, optional If True, quotes are escaped as two consecutive quotes escape_char : string, optional Character which begins a C escape sequence quote_char: string, optional Character used to quote fields na_rep: string, optional The value used to denote a missing value. file_header: string, optional A string printed to the start of the file file_footer: string, optional A string printed to the end of the file line_prefix: string, optional A string printed at the start of each value line
[ "Writes", "an", "SFrame", "to", "a", "CSV", "file", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L2828-L2917
29,041
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.export_json
def export_json(self, filename, orient='records'): """ Writes an SFrame to a JSON file. Parameters ---------- filename : string The location to save the JSON file. orient : string, optional. Either "records" or "lines" If orient="records" the file is saved as a single JSON array. If orient="lines", the file is saves as a JSON value per line. Examples -------- The orient parameter describes the expected input format of the JSON file. If orient="records", the output will be a single JSON Array where each array element is a dictionary describing the row. >>> g Columns: a int b int Rows: 3 Data: +---+---+ | a | b | +---+---+ | 1 | 1 | | 2 | 2 | | 3 | 3 | +---+---+ >>> g.export('output.json', orient='records') >>> !cat output.json [ {'a':1,'b':1}, {'a':2,'b':2}, {'a':3,'b':3}, ] If orient="rows", each row will be emitted as a JSON dictionary to each file line. >>> g Columns: a int b int Rows: 3 Data: +---+---+ | a | b | +---+---+ | 1 | 1 | | 2 | 2 | | 3 | 3 | +---+---+ >>> g.export('output.json', orient='rows') >>> !cat output.json {'a':1,'b':1} {'a':2,'b':2} {'a':3,'b':3} """ if orient == "records": self.pack_columns(dtype=dict).export_csv( filename, file_header='[', file_footer=']', header=False, double_quote=False, quote_level=csv.QUOTE_NONE, line_prefix=',', _no_prefix_on_first_value=True) elif orient == "lines": self.pack_columns(dtype=dict).export_csv( filename, header=False, double_quote=False, quote_level=csv.QUOTE_NONE) else: raise ValueError("Invalid value for orient parameter (" + str(orient) + ")")
python
def export_json(self, filename, orient='records'): """ Writes an SFrame to a JSON file. Parameters ---------- filename : string The location to save the JSON file. orient : string, optional. Either "records" or "lines" If orient="records" the file is saved as a single JSON array. If orient="lines", the file is saves as a JSON value per line. Examples -------- The orient parameter describes the expected input format of the JSON file. If orient="records", the output will be a single JSON Array where each array element is a dictionary describing the row. >>> g Columns: a int b int Rows: 3 Data: +---+---+ | a | b | +---+---+ | 1 | 1 | | 2 | 2 | | 3 | 3 | +---+---+ >>> g.export('output.json', orient='records') >>> !cat output.json [ {'a':1,'b':1}, {'a':2,'b':2}, {'a':3,'b':3}, ] If orient="rows", each row will be emitted as a JSON dictionary to each file line. >>> g Columns: a int b int Rows: 3 Data: +---+---+ | a | b | +---+---+ | 1 | 1 | | 2 | 2 | | 3 | 3 | +---+---+ >>> g.export('output.json', orient='rows') >>> !cat output.json {'a':1,'b':1} {'a':2,'b':2} {'a':3,'b':3} """ if orient == "records": self.pack_columns(dtype=dict).export_csv( filename, file_header='[', file_footer=']', header=False, double_quote=False, quote_level=csv.QUOTE_NONE, line_prefix=',', _no_prefix_on_first_value=True) elif orient == "lines": self.pack_columns(dtype=dict).export_csv( filename, header=False, double_quote=False, quote_level=csv.QUOTE_NONE) else: raise ValueError("Invalid value for orient parameter (" + str(orient) + ")")
[ "def", "export_json", "(", "self", ",", "filename", ",", "orient", "=", "'records'", ")", ":", "if", "orient", "==", "\"records\"", ":", "self", ".", "pack_columns", "(", "dtype", "=", "dict", ")", ".", "export_csv", "(", "filename", ",", "file_header", "=", "'['", ",", "file_footer", "=", "']'", ",", "header", "=", "False", ",", "double_quote", "=", "False", ",", "quote_level", "=", "csv", ".", "QUOTE_NONE", ",", "line_prefix", "=", "','", ",", "_no_prefix_on_first_value", "=", "True", ")", "elif", "orient", "==", "\"lines\"", ":", "self", ".", "pack_columns", "(", "dtype", "=", "dict", ")", ".", "export_csv", "(", "filename", ",", "header", "=", "False", ",", "double_quote", "=", "False", ",", "quote_level", "=", "csv", ".", "QUOTE_NONE", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid value for orient parameter (\"", "+", "str", "(", "orient", ")", "+", "\")\"", ")" ]
Writes an SFrame to a JSON file. Parameters ---------- filename : string The location to save the JSON file. orient : string, optional. Either "records" or "lines" If orient="records" the file is saved as a single JSON array. If orient="lines", the file is saves as a JSON value per line. Examples -------- The orient parameter describes the expected input format of the JSON file. If orient="records", the output will be a single JSON Array where each array element is a dictionary describing the row. >>> g Columns: a int b int Rows: 3 Data: +---+---+ | a | b | +---+---+ | 1 | 1 | | 2 | 2 | | 3 | 3 | +---+---+ >>> g.export('output.json', orient='records') >>> !cat output.json [ {'a':1,'b':1}, {'a':2,'b':2}, {'a':3,'b':3}, ] If orient="rows", each row will be emitted as a JSON dictionary to each file line. >>> g Columns: a int b int Rows: 3 Data: +---+---+ | a | b | +---+---+ | 1 | 1 | | 2 | 2 | | 3 | 3 | +---+---+ >>> g.export('output.json', orient='rows') >>> !cat output.json {'a':1,'b':1} {'a':2,'b':2} {'a':3,'b':3}
[ "Writes", "an", "SFrame", "to", "a", "JSON", "file", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L2919-L2996
29,042
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame._save_reference
def _save_reference(self, filename): """ Performs an incomplete save of an existing SFrame into a directory. This saved SFrame may reference SFrames in other locations in the same filesystem for certain resources. Parameters ---------- filename : string The location to save the SFrame. Either a local directory or a remote URL. See Also -------- load_sframe, SFrame Examples -------- >>> # Save the sframe into binary format >>> sf.save_reference('data/training_data_sframe') """ ## Save the SFrame url = _make_internal_url(filename) with cython_context(): self.__proxy__.save_reference(url)
python
def _save_reference(self, filename): """ Performs an incomplete save of an existing SFrame into a directory. This saved SFrame may reference SFrames in other locations in the same filesystem for certain resources. Parameters ---------- filename : string The location to save the SFrame. Either a local directory or a remote URL. See Also -------- load_sframe, SFrame Examples -------- >>> # Save the sframe into binary format >>> sf.save_reference('data/training_data_sframe') """ ## Save the SFrame url = _make_internal_url(filename) with cython_context(): self.__proxy__.save_reference(url)
[ "def", "_save_reference", "(", "self", ",", "filename", ")", ":", "## Save the SFrame", "url", "=", "_make_internal_url", "(", "filename", ")", "with", "cython_context", "(", ")", ":", "self", ".", "__proxy__", ".", "save_reference", "(", "url", ")" ]
Performs an incomplete save of an existing SFrame into a directory. This saved SFrame may reference SFrames in other locations in the same filesystem for certain resources. Parameters ---------- filename : string The location to save the SFrame. Either a local directory or a remote URL. See Also -------- load_sframe, SFrame Examples -------- >>> # Save the sframe into binary format >>> sf.save_reference('data/training_data_sframe')
[ "Performs", "an", "incomplete", "save", "of", "an", "existing", "SFrame", "into", "a", "directory", ".", "This", "saved", "SFrame", "may", "reference", "SFrames", "in", "other", "locations", "in", "the", "same", "filesystem", "for", "certain", "resources", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L2998-L3023
29,043
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.add_column
def add_column(self, data, column_name="", inplace=False): """ Returns an SFrame with a new column. The number of elements in the data given must match the length of every other column of the SFrame. If no name is given, a default name is chosen. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- data : SArray The 'column' of data to add. column_name : string, optional The name of the column. If no name is given, a default name is chosen. inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The current SFrame. See Also -------- add_columns Examples -------- >>> sf = turicreate.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> sa = turicreate.SArray(['cat', 'dog', 'fossa']) >>> # This line is equivalent to `sf['species'] = sa` >>> res = sf.add_column(sa, 'species') >>> res +----+-----+---------+ | id | val | species | +----+-----+---------+ | 1 | A | cat | | 2 | B | dog | | 3 | C | fossa | +----+-----+---------+ [3 rows x 3 columns] """ # Check type for pandas dataframe or SArray? if not isinstance(data, SArray): if isinstance(data, _Iterable): data = SArray(data) else: if self.num_columns() == 0: data = SArray([data]) else: data = SArray.from_const(data, self.num_rows()) if not isinstance(column_name, str): raise TypeError("Invalid column name: must be str") if inplace: ret = self else: ret = self.copy() with cython_context(): ret.__proxy__.add_column(data.__proxy__, column_name) ret._cache = None return ret
python
def add_column(self, data, column_name="", inplace=False): """ Returns an SFrame with a new column. The number of elements in the data given must match the length of every other column of the SFrame. If no name is given, a default name is chosen. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- data : SArray The 'column' of data to add. column_name : string, optional The name of the column. If no name is given, a default name is chosen. inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The current SFrame. See Also -------- add_columns Examples -------- >>> sf = turicreate.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> sa = turicreate.SArray(['cat', 'dog', 'fossa']) >>> # This line is equivalent to `sf['species'] = sa` >>> res = sf.add_column(sa, 'species') >>> res +----+-----+---------+ | id | val | species | +----+-----+---------+ | 1 | A | cat | | 2 | B | dog | | 3 | C | fossa | +----+-----+---------+ [3 rows x 3 columns] """ # Check type for pandas dataframe or SArray? if not isinstance(data, SArray): if isinstance(data, _Iterable): data = SArray(data) else: if self.num_columns() == 0: data = SArray([data]) else: data = SArray.from_const(data, self.num_rows()) if not isinstance(column_name, str): raise TypeError("Invalid column name: must be str") if inplace: ret = self else: ret = self.copy() with cython_context(): ret.__proxy__.add_column(data.__proxy__, column_name) ret._cache = None return ret
[ "def", "add_column", "(", "self", ",", "data", ",", "column_name", "=", "\"\"", ",", "inplace", "=", "False", ")", ":", "# Check type for pandas dataframe or SArray?", "if", "not", "isinstance", "(", "data", ",", "SArray", ")", ":", "if", "isinstance", "(", "data", ",", "_Iterable", ")", ":", "data", "=", "SArray", "(", "data", ")", "else", ":", "if", "self", ".", "num_columns", "(", ")", "==", "0", ":", "data", "=", "SArray", "(", "[", "data", "]", ")", "else", ":", "data", "=", "SArray", ".", "from_const", "(", "data", ",", "self", ".", "num_rows", "(", ")", ")", "if", "not", "isinstance", "(", "column_name", ",", "str", ")", ":", "raise", "TypeError", "(", "\"Invalid column name: must be str\"", ")", "if", "inplace", ":", "ret", "=", "self", "else", ":", "ret", "=", "self", ".", "copy", "(", ")", "with", "cython_context", "(", ")", ":", "ret", ".", "__proxy__", ".", "add_column", "(", "data", ".", "__proxy__", ",", "column_name", ")", "ret", ".", "_cache", "=", "None", "return", "ret" ]
Returns an SFrame with a new column. The number of elements in the data given must match the length of every other column of the SFrame. If no name is given, a default name is chosen. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- data : SArray The 'column' of data to add. column_name : string, optional The name of the column. If no name is given, a default name is chosen. inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The current SFrame. See Also -------- add_columns Examples -------- >>> sf = turicreate.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> sa = turicreate.SArray(['cat', 'dog', 'fossa']) >>> # This line is equivalent to `sf['species'] = sa` >>> res = sf.add_column(sa, 'species') >>> res +----+-----+---------+ | id | val | species | +----+-----+---------+ | 1 | A | cat | | 2 | B | dog | | 3 | C | fossa | +----+-----+---------+ [3 rows x 3 columns]
[ "Returns", "an", "SFrame", "with", "a", "new", "column", ".", "The", "number", "of", "elements", "in", "the", "data", "given", "must", "match", "the", "length", "of", "every", "other", "column", "of", "the", "SFrame", ".", "If", "no", "name", "is", "given", "a", "default", "name", "is", "chosen", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L3139-L3212
29,044
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.add_columns
def add_columns(self, data, column_names=None, inplace=False): """ Returns an SFrame with multiple columns added. The number of elements in all columns must match the length of every other column of the SFrame. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- data : list[SArray] or SFrame The columns to add. column_names: list of string, optional A list of column names. All names must be specified. ``column_names`` is ignored if data is an SFrame. inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The current SFrame. See Also -------- add_column Examples -------- >>> sf = turicreate.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> sf2 = turicreate.SFrame({'species': ['cat', 'dog', 'fossa'], ... 'age': [3, 5, 9]}) >>> res = sf.add_columns(sf2) >>> res +----+-----+-----+---------+ | id | val | age | species | +----+-----+-----+---------+ | 1 | A | 3 | cat | | 2 | B | 5 | dog | | 3 | C | 9 | fossa | +----+-----+-----+---------+ [3 rows x 4 columns] """ datalist = data if isinstance(data, SFrame): other = data datalist = [other.select_column(name) for name in other.column_names()] column_names = other.column_names() my_columns = set(self.column_names()) for name in column_names: if name in my_columns: raise ValueError("Column '" + name + "' already exists in current SFrame") else: if not _is_non_string_iterable(datalist): raise TypeError("datalist must be an iterable") if not _is_non_string_iterable(column_names): raise TypeError("column_names must be an iterable") if not all([isinstance(x, SArray) for x in datalist]): raise TypeError("Must give column as SArray") if not all([isinstance(x, str) for x in column_names]): raise TypeError("Invalid column name in list : must all be str") if inplace: ret = self else: ret = self.copy() with cython_context(): ret.__proxy__.add_columns([x.__proxy__ for x in datalist], column_names) ret._cache = None return ret
python
def add_columns(self, data, column_names=None, inplace=False): """ Returns an SFrame with multiple columns added. The number of elements in all columns must match the length of every other column of the SFrame. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- data : list[SArray] or SFrame The columns to add. column_names: list of string, optional A list of column names. All names must be specified. ``column_names`` is ignored if data is an SFrame. inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The current SFrame. See Also -------- add_column Examples -------- >>> sf = turicreate.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> sf2 = turicreate.SFrame({'species': ['cat', 'dog', 'fossa'], ... 'age': [3, 5, 9]}) >>> res = sf.add_columns(sf2) >>> res +----+-----+-----+---------+ | id | val | age | species | +----+-----+-----+---------+ | 1 | A | 3 | cat | | 2 | B | 5 | dog | | 3 | C | 9 | fossa | +----+-----+-----+---------+ [3 rows x 4 columns] """ datalist = data if isinstance(data, SFrame): other = data datalist = [other.select_column(name) for name in other.column_names()] column_names = other.column_names() my_columns = set(self.column_names()) for name in column_names: if name in my_columns: raise ValueError("Column '" + name + "' already exists in current SFrame") else: if not _is_non_string_iterable(datalist): raise TypeError("datalist must be an iterable") if not _is_non_string_iterable(column_names): raise TypeError("column_names must be an iterable") if not all([isinstance(x, SArray) for x in datalist]): raise TypeError("Must give column as SArray") if not all([isinstance(x, str) for x in column_names]): raise TypeError("Invalid column name in list : must all be str") if inplace: ret = self else: ret = self.copy() with cython_context(): ret.__proxy__.add_columns([x.__proxy__ for x in datalist], column_names) ret._cache = None return ret
[ "def", "add_columns", "(", "self", ",", "data", ",", "column_names", "=", "None", ",", "inplace", "=", "False", ")", ":", "datalist", "=", "data", "if", "isinstance", "(", "data", ",", "SFrame", ")", ":", "other", "=", "data", "datalist", "=", "[", "other", ".", "select_column", "(", "name", ")", "for", "name", "in", "other", ".", "column_names", "(", ")", "]", "column_names", "=", "other", ".", "column_names", "(", ")", "my_columns", "=", "set", "(", "self", ".", "column_names", "(", ")", ")", "for", "name", "in", "column_names", ":", "if", "name", "in", "my_columns", ":", "raise", "ValueError", "(", "\"Column '\"", "+", "name", "+", "\"' already exists in current SFrame\"", ")", "else", ":", "if", "not", "_is_non_string_iterable", "(", "datalist", ")", ":", "raise", "TypeError", "(", "\"datalist must be an iterable\"", ")", "if", "not", "_is_non_string_iterable", "(", "column_names", ")", ":", "raise", "TypeError", "(", "\"column_names must be an iterable\"", ")", "if", "not", "all", "(", "[", "isinstance", "(", "x", ",", "SArray", ")", "for", "x", "in", "datalist", "]", ")", ":", "raise", "TypeError", "(", "\"Must give column as SArray\"", ")", "if", "not", "all", "(", "[", "isinstance", "(", "x", ",", "str", ")", "for", "x", "in", "column_names", "]", ")", ":", "raise", "TypeError", "(", "\"Invalid column name in list : must all be str\"", ")", "if", "inplace", ":", "ret", "=", "self", "else", ":", "ret", "=", "self", ".", "copy", "(", ")", "with", "cython_context", "(", ")", ":", "ret", ".", "__proxy__", ".", "add_columns", "(", "[", "x", ".", "__proxy__", "for", "x", "in", "datalist", "]", ",", "column_names", ")", "ret", ".", "_cache", "=", "None", "return", "ret" ]
Returns an SFrame with multiple columns added. The number of elements in all columns must match the length of every other column of the SFrame. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- data : list[SArray] or SFrame The columns to add. column_names: list of string, optional A list of column names. All names must be specified. ``column_names`` is ignored if data is an SFrame. inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The current SFrame. See Also -------- add_column Examples -------- >>> sf = turicreate.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> sf2 = turicreate.SFrame({'species': ['cat', 'dog', 'fossa'], ... 'age': [3, 5, 9]}) >>> res = sf.add_columns(sf2) >>> res +----+-----+-----+---------+ | id | val | age | species | +----+-----+-----+---------+ | 1 | A | 3 | cat | | 2 | B | 5 | dog | | 3 | C | 9 | fossa | +----+-----+-----+---------+ [3 rows x 4 columns]
[ "Returns", "an", "SFrame", "with", "multiple", "columns", "added", ".", "The", "number", "of", "elements", "in", "all", "columns", "must", "match", "the", "length", "of", "every", "other", "column", "of", "the", "SFrame", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L3214-L3293
29,045
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.remove_column
def remove_column(self, column_name, inplace=False): """ Returns an SFrame with a column removed. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- column_name : string The name of the column to remove. inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The SFrame with given column removed. Examples -------- >>> sf = turicreate.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> # This is equivalent to `del sf['val']` >>> res = sf.remove_column('val') >>> res +----+ | id | +----+ | 1 | | 2 | | 3 | +----+ [3 rows x 1 columns] """ column_name = str(column_name) if column_name not in self.column_names(): raise KeyError('Cannot find column %s' % column_name) colid = self.column_names().index(column_name) if inplace: ret = self else: ret = self.copy() with cython_context(): ret.__proxy__.remove_column(colid) ret._cache = None return ret
python
def remove_column(self, column_name, inplace=False): """ Returns an SFrame with a column removed. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- column_name : string The name of the column to remove. inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The SFrame with given column removed. Examples -------- >>> sf = turicreate.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> # This is equivalent to `del sf['val']` >>> res = sf.remove_column('val') >>> res +----+ | id | +----+ | 1 | | 2 | | 3 | +----+ [3 rows x 1 columns] """ column_name = str(column_name) if column_name not in self.column_names(): raise KeyError('Cannot find column %s' % column_name) colid = self.column_names().index(column_name) if inplace: ret = self else: ret = self.copy() with cython_context(): ret.__proxy__.remove_column(colid) ret._cache = None return ret
[ "def", "remove_column", "(", "self", ",", "column_name", ",", "inplace", "=", "False", ")", ":", "column_name", "=", "str", "(", "column_name", ")", "if", "column_name", "not", "in", "self", ".", "column_names", "(", ")", ":", "raise", "KeyError", "(", "'Cannot find column %s'", "%", "column_name", ")", "colid", "=", "self", ".", "column_names", "(", ")", ".", "index", "(", "column_name", ")", "if", "inplace", ":", "ret", "=", "self", "else", ":", "ret", "=", "self", ".", "copy", "(", ")", "with", "cython_context", "(", ")", ":", "ret", ".", "__proxy__", ".", "remove_column", "(", "colid", ")", "ret", ".", "_cache", "=", "None", "return", "ret" ]
Returns an SFrame with a column removed. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- column_name : string The name of the column to remove. inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The SFrame with given column removed. Examples -------- >>> sf = turicreate.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> # This is equivalent to `del sf['val']` >>> res = sf.remove_column('val') >>> res +----+ | id | +----+ | 1 | | 2 | | 3 | +----+ [3 rows x 1 columns]
[ "Returns", "an", "SFrame", "with", "a", "column", "removed", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L3295-L3347
29,046
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.remove_columns
def remove_columns(self, column_names, inplace=False): """ Returns an SFrame with one or more columns removed. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- column_names : list or iterable A list or iterable of column names. inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The SFrame with given columns removed. Examples -------- >>> sf = turicreate.SFrame({'id': [1, 2, 3], 'val1': ['A', 'B', 'C'], 'val2' : [10, 11, 12]}) >>> res = sf.remove_columns(['val1', 'val2']) >>> res +----+ | id | +----+ | 1 | | 2 | | 3 | +----+ [3 rows x 1 columns] """ column_names = list(column_names) existing_columns = dict((k, i) for i, k in enumerate(self.column_names())) for name in column_names: if name not in existing_columns: raise KeyError('Cannot find column %s' % name) # Delete it going backwards so we don't invalidate indices deletion_indices = sorted(existing_columns[name] for name in column_names) if inplace: ret = self else: ret = self.copy() for colid in reversed(deletion_indices): with cython_context(): ret.__proxy__.remove_column(colid) ret._cache = None return ret
python
def remove_columns(self, column_names, inplace=False): """ Returns an SFrame with one or more columns removed. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- column_names : list or iterable A list or iterable of column names. inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The SFrame with given columns removed. Examples -------- >>> sf = turicreate.SFrame({'id': [1, 2, 3], 'val1': ['A', 'B', 'C'], 'val2' : [10, 11, 12]}) >>> res = sf.remove_columns(['val1', 'val2']) >>> res +----+ | id | +----+ | 1 | | 2 | | 3 | +----+ [3 rows x 1 columns] """ column_names = list(column_names) existing_columns = dict((k, i) for i, k in enumerate(self.column_names())) for name in column_names: if name not in existing_columns: raise KeyError('Cannot find column %s' % name) # Delete it going backwards so we don't invalidate indices deletion_indices = sorted(existing_columns[name] for name in column_names) if inplace: ret = self else: ret = self.copy() for colid in reversed(deletion_indices): with cython_context(): ret.__proxy__.remove_column(colid) ret._cache = None return ret
[ "def", "remove_columns", "(", "self", ",", "column_names", ",", "inplace", "=", "False", ")", ":", "column_names", "=", "list", "(", "column_names", ")", "existing_columns", "=", "dict", "(", "(", "k", ",", "i", ")", "for", "i", ",", "k", "in", "enumerate", "(", "self", ".", "column_names", "(", ")", ")", ")", "for", "name", "in", "column_names", ":", "if", "name", "not", "in", "existing_columns", ":", "raise", "KeyError", "(", "'Cannot find column %s'", "%", "name", ")", "# Delete it going backwards so we don't invalidate indices", "deletion_indices", "=", "sorted", "(", "existing_columns", "[", "name", "]", "for", "name", "in", "column_names", ")", "if", "inplace", ":", "ret", "=", "self", "else", ":", "ret", "=", "self", ".", "copy", "(", ")", "for", "colid", "in", "reversed", "(", "deletion_indices", ")", ":", "with", "cython_context", "(", ")", ":", "ret", ".", "__proxy__", ".", "remove_column", "(", "colid", ")", "ret", ".", "_cache", "=", "None", "return", "ret" ]
Returns an SFrame with one or more columns removed. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- column_names : list or iterable A list or iterable of column names. inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The SFrame with given columns removed. Examples -------- >>> sf = turicreate.SFrame({'id': [1, 2, 3], 'val1': ['A', 'B', 'C'], 'val2' : [10, 11, 12]}) >>> res = sf.remove_columns(['val1', 'val2']) >>> res +----+ | id | +----+ | 1 | | 2 | | 3 | +----+ [3 rows x 1 columns]
[ "Returns", "an", "SFrame", "with", "one", "or", "more", "columns", "removed", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L3349-L3406
29,047
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.swap_columns
def swap_columns(self, column_name_1, column_name_2, inplace=False): """ Returns an SFrame with two column positions swapped. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- column_name_1 : string Name of column to swap column_name_2 : string Name of other column to swap inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The SFrame with swapped columns. Examples -------- >>> sf = turicreate.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> res = sf.swap_columns('id', 'val') >>> res +-----+-----+ | val | id | +-----+-----+ | A | 1 | | B | 2 | | C | 3 | +----+-----+ [3 rows x 2 columns] """ colnames = self.column_names() colid_1 = colnames.index(column_name_1) colid_2 = colnames.index(column_name_2) if inplace: ret = self else: ret = self.copy() with cython_context(): ret.__proxy__.swap_columns(colid_1, colid_2) ret._cache = None return ret
python
def swap_columns(self, column_name_1, column_name_2, inplace=False): """ Returns an SFrame with two column positions swapped. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- column_name_1 : string Name of column to swap column_name_2 : string Name of other column to swap inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The SFrame with swapped columns. Examples -------- >>> sf = turicreate.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> res = sf.swap_columns('id', 'val') >>> res +-----+-----+ | val | id | +-----+-----+ | A | 1 | | B | 2 | | C | 3 | +----+-----+ [3 rows x 2 columns] """ colnames = self.column_names() colid_1 = colnames.index(column_name_1) colid_2 = colnames.index(column_name_2) if inplace: ret = self else: ret = self.copy() with cython_context(): ret.__proxy__.swap_columns(colid_1, colid_2) ret._cache = None return ret
[ "def", "swap_columns", "(", "self", ",", "column_name_1", ",", "column_name_2", ",", "inplace", "=", "False", ")", ":", "colnames", "=", "self", ".", "column_names", "(", ")", "colid_1", "=", "colnames", ".", "index", "(", "column_name_1", ")", "colid_2", "=", "colnames", ".", "index", "(", "column_name_2", ")", "if", "inplace", ":", "ret", "=", "self", "else", ":", "ret", "=", "self", ".", "copy", "(", ")", "with", "cython_context", "(", ")", ":", "ret", ".", "__proxy__", ".", "swap_columns", "(", "colid_1", ",", "colid_2", ")", "ret", ".", "_cache", "=", "None", "return", "ret" ]
Returns an SFrame with two column positions swapped. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- column_name_1 : string Name of column to swap column_name_2 : string Name of other column to swap inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The SFrame with swapped columns. Examples -------- >>> sf = turicreate.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> res = sf.swap_columns('id', 'val') >>> res +-----+-----+ | val | id | +-----+-----+ | A | 1 | | B | 2 | | C | 3 | +----+-----+ [3 rows x 2 columns]
[ "Returns", "an", "SFrame", "with", "two", "column", "positions", "swapped", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L3409-L3462
29,048
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.rename
def rename(self, names, inplace=False): """ Returns an SFrame with columns renamed. ``names`` is expected to be a dict specifying the old and new names. This changes the names of the columns given as the keys and replaces them with the names given as the values. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- names : dict [string, string] Dictionary of [old_name, new_name] inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The current SFrame. See Also -------- column_names Examples -------- >>> sf = SFrame({'X1': ['Alice','Bob'], ... 'X2': ['123 Fake Street','456 Fake Street']}) >>> res = sf.rename({'X1': 'name', 'X2':'address'}) >>> res +-------+-----------------+ | name | address | +-------+-----------------+ | Alice | 123 Fake Street | | Bob | 456 Fake Street | +-------+-----------------+ [2 rows x 2 columns] """ if (type(names) is not dict): raise TypeError('names must be a dictionary: oldname -> newname') all_columns = set(self.column_names()) for k in names: if not k in all_columns: raise ValueError('Cannot find column %s in the SFrame' % k) if inplace: ret = self else: ret = self.copy() with cython_context(): for k in names: colid = ret.column_names().index(k) ret.__proxy__.set_column_name(colid, names[k]) ret._cache = None return ret
python
def rename(self, names, inplace=False): """ Returns an SFrame with columns renamed. ``names`` is expected to be a dict specifying the old and new names. This changes the names of the columns given as the keys and replaces them with the names given as the values. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- names : dict [string, string] Dictionary of [old_name, new_name] inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The current SFrame. See Also -------- column_names Examples -------- >>> sf = SFrame({'X1': ['Alice','Bob'], ... 'X2': ['123 Fake Street','456 Fake Street']}) >>> res = sf.rename({'X1': 'name', 'X2':'address'}) >>> res +-------+-----------------+ | name | address | +-------+-----------------+ | Alice | 123 Fake Street | | Bob | 456 Fake Street | +-------+-----------------+ [2 rows x 2 columns] """ if (type(names) is not dict): raise TypeError('names must be a dictionary: oldname -> newname') all_columns = set(self.column_names()) for k in names: if not k in all_columns: raise ValueError('Cannot find column %s in the SFrame' % k) if inplace: ret = self else: ret = self.copy() with cython_context(): for k in names: colid = ret.column_names().index(k) ret.__proxy__.set_column_name(colid, names[k]) ret._cache = None return ret
[ "def", "rename", "(", "self", ",", "names", ",", "inplace", "=", "False", ")", ":", "if", "(", "type", "(", "names", ")", "is", "not", "dict", ")", ":", "raise", "TypeError", "(", "'names must be a dictionary: oldname -> newname'", ")", "all_columns", "=", "set", "(", "self", ".", "column_names", "(", ")", ")", "for", "k", "in", "names", ":", "if", "not", "k", "in", "all_columns", ":", "raise", "ValueError", "(", "'Cannot find column %s in the SFrame'", "%", "k", ")", "if", "inplace", ":", "ret", "=", "self", "else", ":", "ret", "=", "self", ".", "copy", "(", ")", "with", "cython_context", "(", ")", ":", "for", "k", "in", "names", ":", "colid", "=", "ret", ".", "column_names", "(", ")", ".", "index", "(", "k", ")", "ret", ".", "__proxy__", ".", "set_column_name", "(", "colid", ",", "names", "[", "k", "]", ")", "ret", ".", "_cache", "=", "None", "return", "ret" ]
Returns an SFrame with columns renamed. ``names`` is expected to be a dict specifying the old and new names. This changes the names of the columns given as the keys and replaces them with the names given as the values. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- names : dict [string, string] Dictionary of [old_name, new_name] inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The current SFrame. See Also -------- column_names Examples -------- >>> sf = SFrame({'X1': ['Alice','Bob'], ... 'X2': ['123 Fake Street','456 Fake Street']}) >>> res = sf.rename({'X1': 'name', 'X2':'address'}) >>> res +-------+-----------------+ | name | address | +-------+-----------------+ | Alice | 123 Fake Street | | Bob | 456 Fake Street | +-------+-----------------+ [2 rows x 2 columns]
[ "Returns", "an", "SFrame", "with", "columns", "renamed", ".", "names", "is", "expected", "to", "be", "a", "dict", "specifying", "the", "old", "and", "new", "names", ".", "This", "changes", "the", "names", "of", "the", "columns", "given", "as", "the", "keys", "and", "replaces", "them", "with", "the", "names", "given", "as", "the", "values", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L3464-L3525
29,049
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.append
def append(self, other): """ Add the rows of an SFrame to the end of this SFrame. Both SFrames must have the same set of columns with the same column names and column types. Parameters ---------- other : SFrame Another SFrame whose rows are appended to the current SFrame. Returns ------- out : SFrame The result SFrame from the append operation. Examples -------- >>> sf = turicreate.SFrame({'id': [4, 6, 8], 'val': ['D', 'F', 'H']}) >>> sf2 = turicreate.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> sf = sf.append(sf2) >>> sf +----+-----+ | id | val | +----+-----+ | 4 | D | | 6 | F | | 8 | H | | 1 | A | | 2 | B | | 3 | C | +----+-----+ [6 rows x 2 columns] """ if type(other) is not SFrame: raise RuntimeError("SFrame append can only work with SFrame") left_empty = len(self.column_names()) == 0 right_empty = len(other.column_names()) == 0 if (left_empty and right_empty): return SFrame() if (left_empty or right_empty): non_empty_sframe = self if right_empty else other return non_empty_sframe.__copy__() my_column_names = self.column_names() my_column_types = self.column_types() other_column_names = other.column_names() if (len(my_column_names) != len(other_column_names)): raise RuntimeError("Two SFrames have to have the same number of columns") # check if the order of column name is the same column_name_order_match = True for i in range(len(my_column_names)): if other_column_names[i] != my_column_names[i]: column_name_order_match = False break processed_other_frame = other if not column_name_order_match: # we allow name order of two sframes to be different, so we create a new sframe from # "other" sframe to make it has exactly the same shape processed_other_frame = SFrame() for i in range(len(my_column_names)): col_name = my_column_names[i] if(col_name not in other_column_names): raise RuntimeError("Column " + my_column_names[i] + " does not exist in second SFrame") other_column = other.select_column(col_name) processed_other_frame.add_column(other_column, col_name, inplace=True) # check column type if my_column_types[i] != other_column.dtype: raise RuntimeError("Column " + my_column_names[i] + " type is not the same in two SFrames, one is " + str(my_column_types[i]) + ", the other is " + str(other_column.dtype)) with cython_context(): return SFrame(_proxy=self.__proxy__.append(processed_other_frame.__proxy__))
python
def append(self, other): """ Add the rows of an SFrame to the end of this SFrame. Both SFrames must have the same set of columns with the same column names and column types. Parameters ---------- other : SFrame Another SFrame whose rows are appended to the current SFrame. Returns ------- out : SFrame The result SFrame from the append operation. Examples -------- >>> sf = turicreate.SFrame({'id': [4, 6, 8], 'val': ['D', 'F', 'H']}) >>> sf2 = turicreate.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> sf = sf.append(sf2) >>> sf +----+-----+ | id | val | +----+-----+ | 4 | D | | 6 | F | | 8 | H | | 1 | A | | 2 | B | | 3 | C | +----+-----+ [6 rows x 2 columns] """ if type(other) is not SFrame: raise RuntimeError("SFrame append can only work with SFrame") left_empty = len(self.column_names()) == 0 right_empty = len(other.column_names()) == 0 if (left_empty and right_empty): return SFrame() if (left_empty or right_empty): non_empty_sframe = self if right_empty else other return non_empty_sframe.__copy__() my_column_names = self.column_names() my_column_types = self.column_types() other_column_names = other.column_names() if (len(my_column_names) != len(other_column_names)): raise RuntimeError("Two SFrames have to have the same number of columns") # check if the order of column name is the same column_name_order_match = True for i in range(len(my_column_names)): if other_column_names[i] != my_column_names[i]: column_name_order_match = False break processed_other_frame = other if not column_name_order_match: # we allow name order of two sframes to be different, so we create a new sframe from # "other" sframe to make it has exactly the same shape processed_other_frame = SFrame() for i in range(len(my_column_names)): col_name = my_column_names[i] if(col_name not in other_column_names): raise RuntimeError("Column " + my_column_names[i] + " does not exist in second SFrame") other_column = other.select_column(col_name) processed_other_frame.add_column(other_column, col_name, inplace=True) # check column type if my_column_types[i] != other_column.dtype: raise RuntimeError("Column " + my_column_names[i] + " type is not the same in two SFrames, one is " + str(my_column_types[i]) + ", the other is " + str(other_column.dtype)) with cython_context(): return SFrame(_proxy=self.__proxy__.append(processed_other_frame.__proxy__))
[ "def", "append", "(", "self", ",", "other", ")", ":", "if", "type", "(", "other", ")", "is", "not", "SFrame", ":", "raise", "RuntimeError", "(", "\"SFrame append can only work with SFrame\"", ")", "left_empty", "=", "len", "(", "self", ".", "column_names", "(", ")", ")", "==", "0", "right_empty", "=", "len", "(", "other", ".", "column_names", "(", ")", ")", "==", "0", "if", "(", "left_empty", "and", "right_empty", ")", ":", "return", "SFrame", "(", ")", "if", "(", "left_empty", "or", "right_empty", ")", ":", "non_empty_sframe", "=", "self", "if", "right_empty", "else", "other", "return", "non_empty_sframe", ".", "__copy__", "(", ")", "my_column_names", "=", "self", ".", "column_names", "(", ")", "my_column_types", "=", "self", ".", "column_types", "(", ")", "other_column_names", "=", "other", ".", "column_names", "(", ")", "if", "(", "len", "(", "my_column_names", ")", "!=", "len", "(", "other_column_names", ")", ")", ":", "raise", "RuntimeError", "(", "\"Two SFrames have to have the same number of columns\"", ")", "# check if the order of column name is the same", "column_name_order_match", "=", "True", "for", "i", "in", "range", "(", "len", "(", "my_column_names", ")", ")", ":", "if", "other_column_names", "[", "i", "]", "!=", "my_column_names", "[", "i", "]", ":", "column_name_order_match", "=", "False", "break", "processed_other_frame", "=", "other", "if", "not", "column_name_order_match", ":", "# we allow name order of two sframes to be different, so we create a new sframe from", "# \"other\" sframe to make it has exactly the same shape", "processed_other_frame", "=", "SFrame", "(", ")", "for", "i", "in", "range", "(", "len", "(", "my_column_names", ")", ")", ":", "col_name", "=", "my_column_names", "[", "i", "]", "if", "(", "col_name", "not", "in", "other_column_names", ")", ":", "raise", "RuntimeError", "(", "\"Column \"", "+", "my_column_names", "[", "i", "]", "+", "\" does not exist in second SFrame\"", ")", "other_column", "=", "other", ".", "select_column", "(", "col_name", ")", "processed_other_frame", ".", "add_column", "(", "other_column", ",", "col_name", ",", "inplace", "=", "True", ")", "# check column type", "if", "my_column_types", "[", "i", "]", "!=", "other_column", ".", "dtype", ":", "raise", "RuntimeError", "(", "\"Column \"", "+", "my_column_names", "[", "i", "]", "+", "\" type is not the same in two SFrames, one is \"", "+", "str", "(", "my_column_types", "[", "i", "]", ")", "+", "\", the other is \"", "+", "str", "(", "other_column", ".", "dtype", ")", ")", "with", "cython_context", "(", ")", ":", "return", "SFrame", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "append", "(", "processed_other_frame", ".", "__proxy__", ")", ")" ]
Add the rows of an SFrame to the end of this SFrame. Both SFrames must have the same set of columns with the same column names and column types. Parameters ---------- other : SFrame Another SFrame whose rows are appended to the current SFrame. Returns ------- out : SFrame The result SFrame from the append operation. Examples -------- >>> sf = turicreate.SFrame({'id': [4, 6, 8], 'val': ['D', 'F', 'H']}) >>> sf2 = turicreate.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> sf = sf.append(sf2) >>> sf +----+-----+ | id | val | +----+-----+ | 4 | D | | 6 | F | | 8 | H | | 1 | A | | 2 | B | | 3 | C | +----+-----+ [6 rows x 2 columns]
[ "Add", "the", "rows", "of", "an", "SFrame", "to", "the", "end", "of", "this", "SFrame", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L3737-L3816
29,050
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.explore
def explore(self, title=None): """ Explore the SFrame in an interactive GUI. Opens a new app window. Parameters ---------- title : str The plot title to show for the resulting visualization. Defaults to None. If the title is None, a default title will be provided. Returns ------- None Examples -------- Suppose 'sf' is an SFrame, we can view it using: >>> sf.explore() To override the default plot title and axis labels: >>> sf.explore(title="My Plot Title") """ import sys import os if sys.platform != 'darwin' and sys.platform != 'linux2' and sys.platform != 'linux': raise NotImplementedError('Visualization is currently supported only on macOS and Linux.') path_to_client = _get_client_app_path() if title is None: title = "" self.__proxy__.explore(path_to_client, title)
python
def explore(self, title=None): """ Explore the SFrame in an interactive GUI. Opens a new app window. Parameters ---------- title : str The plot title to show for the resulting visualization. Defaults to None. If the title is None, a default title will be provided. Returns ------- None Examples -------- Suppose 'sf' is an SFrame, we can view it using: >>> sf.explore() To override the default plot title and axis labels: >>> sf.explore(title="My Plot Title") """ import sys import os if sys.platform != 'darwin' and sys.platform != 'linux2' and sys.platform != 'linux': raise NotImplementedError('Visualization is currently supported only on macOS and Linux.') path_to_client = _get_client_app_path() if title is None: title = "" self.__proxy__.explore(path_to_client, title)
[ "def", "explore", "(", "self", ",", "title", "=", "None", ")", ":", "import", "sys", "import", "os", "if", "sys", ".", "platform", "!=", "'darwin'", "and", "sys", ".", "platform", "!=", "'linux2'", "and", "sys", ".", "platform", "!=", "'linux'", ":", "raise", "NotImplementedError", "(", "'Visualization is currently supported only on macOS and Linux.'", ")", "path_to_client", "=", "_get_client_app_path", "(", ")", "if", "title", "is", "None", ":", "title", "=", "\"\"", "self", ".", "__proxy__", ".", "explore", "(", "path_to_client", ",", "title", ")" ]
Explore the SFrame in an interactive GUI. Opens a new app window. Parameters ---------- title : str The plot title to show for the resulting visualization. Defaults to None. If the title is None, a default title will be provided. Returns ------- None Examples -------- Suppose 'sf' is an SFrame, we can view it using: >>> sf.explore() To override the default plot title and axis labels: >>> sf.explore(title="My Plot Title")
[ "Explore", "the", "SFrame", "in", "an", "interactive", "GUI", ".", "Opens", "a", "new", "app", "window", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L4451-L4486
29,051
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.split_datetime
def split_datetime(self, column_name, column_name_prefix=None, limit=None, timezone=False): """ Splits a datetime column of SFrame to multiple columns, with each value in a separate column. Returns a new SFrame with the expanded column replaced with a list of new columns. The expanded column must be of datetime type. For more details regarding name generation and other, refer to :py:func:`turicreate.SArray.split_datetime()` Parameters ---------- column_name : str Name of the unpacked column. column_name_prefix : str, optional If provided, expanded column names would start with the given prefix. If not provided, the default value is the name of the expanded column. limit: list[str], optional Limits the set of datetime elements to expand. Possible values are 'year','month','day','hour','minute','second', 'weekday', 'isoweekday', 'tmweekday', and 'us'. If not provided, only ['year','month','day','hour','minute','second'] are expanded. timezone : bool, optional A boolean parameter that determines whether to show the timezone column or not. Defaults to False. Returns ------- out : SFrame A new SFrame that contains rest of columns from original SFrame with the given column replaced with a collection of expanded columns. Examples --------- >>> sf Columns: id int submission datetime Rows: 2 Data: +----+-------------------------------------------------+ | id | submission | +----+-------------------------------------------------+ | 1 | datetime(2011, 1, 21, 7, 17, 21, tzinfo=GMT(+1))| | 2 | datetime(2011, 1, 21, 5, 43, 21, tzinfo=GMT(+1))| +----+-------------------------------------------------+ >>> sf.split_datetime('submission',limit=['hour','minute']) Columns: id int submission.hour int submission.minute int Rows: 2 Data: +----+-----------------+-------------------+ | id | submission.hour | submission.minute | +----+-----------------+-------------------+ | 1 | 7 | 17 | | 2 | 5 | 43 | +----+-----------------+-------------------+ """ if column_name not in self.column_names(): raise KeyError("column '" + column_name + "' does not exist in current SFrame") if column_name_prefix is None: column_name_prefix = column_name new_sf = self[column_name].split_datetime(column_name_prefix, limit, timezone) # construct return SFrame, check if there is conflict rest_columns = [name for name in self.column_names() if name != column_name] new_names = new_sf.column_names() while set(new_names).intersection(rest_columns): new_names = [name + ".1" for name in new_names] new_sf.rename(dict(list(zip(new_sf.column_names(), new_names))), inplace=True) ret_sf = self.select_columns(rest_columns) ret_sf.add_columns(new_sf, inplace=True) return ret_sf
python
def split_datetime(self, column_name, column_name_prefix=None, limit=None, timezone=False): """ Splits a datetime column of SFrame to multiple columns, with each value in a separate column. Returns a new SFrame with the expanded column replaced with a list of new columns. The expanded column must be of datetime type. For more details regarding name generation and other, refer to :py:func:`turicreate.SArray.split_datetime()` Parameters ---------- column_name : str Name of the unpacked column. column_name_prefix : str, optional If provided, expanded column names would start with the given prefix. If not provided, the default value is the name of the expanded column. limit: list[str], optional Limits the set of datetime elements to expand. Possible values are 'year','month','day','hour','minute','second', 'weekday', 'isoweekday', 'tmweekday', and 'us'. If not provided, only ['year','month','day','hour','minute','second'] are expanded. timezone : bool, optional A boolean parameter that determines whether to show the timezone column or not. Defaults to False. Returns ------- out : SFrame A new SFrame that contains rest of columns from original SFrame with the given column replaced with a collection of expanded columns. Examples --------- >>> sf Columns: id int submission datetime Rows: 2 Data: +----+-------------------------------------------------+ | id | submission | +----+-------------------------------------------------+ | 1 | datetime(2011, 1, 21, 7, 17, 21, tzinfo=GMT(+1))| | 2 | datetime(2011, 1, 21, 5, 43, 21, tzinfo=GMT(+1))| +----+-------------------------------------------------+ >>> sf.split_datetime('submission',limit=['hour','minute']) Columns: id int submission.hour int submission.minute int Rows: 2 Data: +----+-----------------+-------------------+ | id | submission.hour | submission.minute | +----+-----------------+-------------------+ | 1 | 7 | 17 | | 2 | 5 | 43 | +----+-----------------+-------------------+ """ if column_name not in self.column_names(): raise KeyError("column '" + column_name + "' does not exist in current SFrame") if column_name_prefix is None: column_name_prefix = column_name new_sf = self[column_name].split_datetime(column_name_prefix, limit, timezone) # construct return SFrame, check if there is conflict rest_columns = [name for name in self.column_names() if name != column_name] new_names = new_sf.column_names() while set(new_names).intersection(rest_columns): new_names = [name + ".1" for name in new_names] new_sf.rename(dict(list(zip(new_sf.column_names(), new_names))), inplace=True) ret_sf = self.select_columns(rest_columns) ret_sf.add_columns(new_sf, inplace=True) return ret_sf
[ "def", "split_datetime", "(", "self", ",", "column_name", ",", "column_name_prefix", "=", "None", ",", "limit", "=", "None", ",", "timezone", "=", "False", ")", ":", "if", "column_name", "not", "in", "self", ".", "column_names", "(", ")", ":", "raise", "KeyError", "(", "\"column '\"", "+", "column_name", "+", "\"' does not exist in current SFrame\"", ")", "if", "column_name_prefix", "is", "None", ":", "column_name_prefix", "=", "column_name", "new_sf", "=", "self", "[", "column_name", "]", ".", "split_datetime", "(", "column_name_prefix", ",", "limit", ",", "timezone", ")", "# construct return SFrame, check if there is conflict", "rest_columns", "=", "[", "name", "for", "name", "in", "self", ".", "column_names", "(", ")", "if", "name", "!=", "column_name", "]", "new_names", "=", "new_sf", ".", "column_names", "(", ")", "while", "set", "(", "new_names", ")", ".", "intersection", "(", "rest_columns", ")", ":", "new_names", "=", "[", "name", "+", "\".1\"", "for", "name", "in", "new_names", "]", "new_sf", ".", "rename", "(", "dict", "(", "list", "(", "zip", "(", "new_sf", ".", "column_names", "(", ")", ",", "new_names", ")", ")", ")", ",", "inplace", "=", "True", ")", "ret_sf", "=", "self", ".", "select_columns", "(", "rest_columns", ")", "ret_sf", ".", "add_columns", "(", "new_sf", ",", "inplace", "=", "True", ")", "return", "ret_sf" ]
Splits a datetime column of SFrame to multiple columns, with each value in a separate column. Returns a new SFrame with the expanded column replaced with a list of new columns. The expanded column must be of datetime type. For more details regarding name generation and other, refer to :py:func:`turicreate.SArray.split_datetime()` Parameters ---------- column_name : str Name of the unpacked column. column_name_prefix : str, optional If provided, expanded column names would start with the given prefix. If not provided, the default value is the name of the expanded column. limit: list[str], optional Limits the set of datetime elements to expand. Possible values are 'year','month','day','hour','minute','second', 'weekday', 'isoweekday', 'tmweekday', and 'us'. If not provided, only ['year','month','day','hour','minute','second'] are expanded. timezone : bool, optional A boolean parameter that determines whether to show the timezone column or not. Defaults to False. Returns ------- out : SFrame A new SFrame that contains rest of columns from original SFrame with the given column replaced with a collection of expanded columns. Examples --------- >>> sf Columns: id int submission datetime Rows: 2 Data: +----+-------------------------------------------------+ | id | submission | +----+-------------------------------------------------+ | 1 | datetime(2011, 1, 21, 7, 17, 21, tzinfo=GMT(+1))| | 2 | datetime(2011, 1, 21, 5, 43, 21, tzinfo=GMT(+1))| +----+-------------------------------------------------+ >>> sf.split_datetime('submission',limit=['hour','minute']) Columns: id int submission.hour int submission.minute int Rows: 2 Data: +----+-----------------+-------------------+ | id | submission.hour | submission.minute | +----+-----------------+-------------------+ | 1 | 7 | 17 | | 2 | 5 | 43 | +----+-----------------+-------------------+
[ "Splits", "a", "datetime", "column", "of", "SFrame", "to", "multiple", "columns", "with", "each", "value", "in", "a", "separate", "column", ".", "Returns", "a", "new", "SFrame", "with", "the", "expanded", "column", "replaced", "with", "a", "list", "of", "new", "columns", ".", "The", "expanded", "column", "must", "be", "of", "datetime", "type", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L4780-L4862
29,052
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.stack
def stack(self, column_name, new_column_name=None, drop_na=False, new_column_type=None): """ Convert a "wide" column of an SFrame to one or two "tall" columns 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) and all columns other than the one that is stacked. Parameters -------------- column_name : str The column to stack. This column must be of dict/list/array type 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 newly stacked column(s) plus columns in original SFrame other than the stacked column. See Also -------- unstack Examples --------- Suppose 'sf' is an SFrame that contains a column of dict type: >>> sf = turicreate.SFrame({'topic':[1,2,3,4], ... 'words': [{'a':3, 'cat':2}, ... {'a':1, 'the':2}, ... {'the':1, 'dog':3}, ... {}] ... }) +-------+----------------------+ | topic | words | +-------+----------------------+ | 1 | {'a': 3, 'cat': 2} | | 2 | {'a': 1, 'the': 2} | | 3 | {'the': 1, 'dog': 3} | | 4 | {} | +-------+----------------------+ [4 rows x 2 columns] Stack would stack all keys in one column and all values in another column: >>> sf.stack('words', new_column_name=['word', 'count']) +-------+------+-------+ | topic | word | count | +-------+------+-------+ | 1 | a | 3 | | 1 | cat | 2 | | 2 | a | 1 | | 2 | the | 2 | | 3 | the | 1 | | 3 | dog | 3 | | 4 | None | None | +-------+------+-------+ [7 rows x 3 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. Suppose 'sf' is an SFrame that contains a user and his/her friends, where 'friends' columns is an array type. Stack on 'friends' column would create a user/friend list for each user/friend pair: >>> sf = turicreate.SFrame({'topic':[1,2,3], ... 'friends':[[2,3,4], [5,6], ... [4,5,10,None]] ... }) >>> sf +-------+------------------+ | topic | friends | +-------+------------------+ | 1 | [2, 3, 4] | | 2 | [5, 6] | | 3 | [4, 5, 10, None] | +----- -+------------------+ [3 rows x 2 columns] >>> sf.stack('friends', new_column_name='friend') +-------+--------+ | topic | friend | +-------+--------+ | 1 | 2 | | 1 | 3 | | 1 | 4 | | 2 | 5 | | 2 | 6 | | 3 | 4 | | 3 | 5 | | 3 | 10 | | 3 | None | +-------+--------+ [9 rows x 2 columns] """ # validate column_name column_name = str(column_name) if column_name not in self.column_names(): raise ValueError("Cannot find column '" + str(column_name) + "' in the SFrame.") stack_column_type = self[column_name].dtype if (stack_column_type not in [dict, array.array, list]): raise TypeError("Stack is only supported for column of dict/list/array type.") # user defined types. do some checking if new_column_type is not None: # if new_column_type is a single type, just make it a list of one type if type(new_column_type) is type: new_column_type = [new_column_type] if (stack_column_type in [list, array.array]) and len(new_column_type) != 1: raise ValueError("Expecting a single column type to unpack list or array columns") if (stack_column_type in [dict]) and len(new_column_type) != 2: raise ValueError("Expecting two column types to unpack a dict column") if (new_column_name is not None): if stack_column_type == dict: if (type(new_column_name) is not list): raise TypeError("new_column_name has to be a list to stack dict type") elif (len(new_column_name) != 2): raise TypeError("new_column_name must have length of two") else: if (type(new_column_name) != str): raise TypeError("new_column_name has to be a str") new_column_name = [new_column_name] # check if the new column name conflicts with existing ones for name in new_column_name: if (name in self.column_names()) and (name != column_name): raise ValueError("Column with name '" + name + "' already exists, pick a new column name") else: if stack_column_type == dict: new_column_name = ["",""] else: new_column_name = [""] # infer column types head_row = SArray(self[column_name].head(100)).dropna() if (len(head_row) == 0): raise ValueError("Cannot infer column type because there is not enough rows to infer value") if new_column_type is None: # we have to perform type inference if stack_column_type == dict: # infer key/value type keys = []; values = [] for row in head_row: for val in row: keys.append(val) if val is not None: values.append(row[val]) new_column_type = [ infer_type_of_list(keys), infer_type_of_list(values) ] else: values = [v for v in itertools.chain.from_iterable(head_row)] new_column_type = [infer_type_of_list(values)] with cython_context(): return SFrame(_proxy=self.__proxy__.stack(column_name, new_column_name, new_column_type, drop_na))
python
def stack(self, column_name, new_column_name=None, drop_na=False, new_column_type=None): """ Convert a "wide" column of an SFrame to one or two "tall" columns 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) and all columns other than the one that is stacked. Parameters -------------- column_name : str The column to stack. This column must be of dict/list/array type 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 newly stacked column(s) plus columns in original SFrame other than the stacked column. See Also -------- unstack Examples --------- Suppose 'sf' is an SFrame that contains a column of dict type: >>> sf = turicreate.SFrame({'topic':[1,2,3,4], ... 'words': [{'a':3, 'cat':2}, ... {'a':1, 'the':2}, ... {'the':1, 'dog':3}, ... {}] ... }) +-------+----------------------+ | topic | words | +-------+----------------------+ | 1 | {'a': 3, 'cat': 2} | | 2 | {'a': 1, 'the': 2} | | 3 | {'the': 1, 'dog': 3} | | 4 | {} | +-------+----------------------+ [4 rows x 2 columns] Stack would stack all keys in one column and all values in another column: >>> sf.stack('words', new_column_name=['word', 'count']) +-------+------+-------+ | topic | word | count | +-------+------+-------+ | 1 | a | 3 | | 1 | cat | 2 | | 2 | a | 1 | | 2 | the | 2 | | 3 | the | 1 | | 3 | dog | 3 | | 4 | None | None | +-------+------+-------+ [7 rows x 3 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. Suppose 'sf' is an SFrame that contains a user and his/her friends, where 'friends' columns is an array type. Stack on 'friends' column would create a user/friend list for each user/friend pair: >>> sf = turicreate.SFrame({'topic':[1,2,3], ... 'friends':[[2,3,4], [5,6], ... [4,5,10,None]] ... }) >>> sf +-------+------------------+ | topic | friends | +-------+------------------+ | 1 | [2, 3, 4] | | 2 | [5, 6] | | 3 | [4, 5, 10, None] | +----- -+------------------+ [3 rows x 2 columns] >>> sf.stack('friends', new_column_name='friend') +-------+--------+ | topic | friend | +-------+--------+ | 1 | 2 | | 1 | 3 | | 1 | 4 | | 2 | 5 | | 2 | 6 | | 3 | 4 | | 3 | 5 | | 3 | 10 | | 3 | None | +-------+--------+ [9 rows x 2 columns] """ # validate column_name column_name = str(column_name) if column_name not in self.column_names(): raise ValueError("Cannot find column '" + str(column_name) + "' in the SFrame.") stack_column_type = self[column_name].dtype if (stack_column_type not in [dict, array.array, list]): raise TypeError("Stack is only supported for column of dict/list/array type.") # user defined types. do some checking if new_column_type is not None: # if new_column_type is a single type, just make it a list of one type if type(new_column_type) is type: new_column_type = [new_column_type] if (stack_column_type in [list, array.array]) and len(new_column_type) != 1: raise ValueError("Expecting a single column type to unpack list or array columns") if (stack_column_type in [dict]) and len(new_column_type) != 2: raise ValueError("Expecting two column types to unpack a dict column") if (new_column_name is not None): if stack_column_type == dict: if (type(new_column_name) is not list): raise TypeError("new_column_name has to be a list to stack dict type") elif (len(new_column_name) != 2): raise TypeError("new_column_name must have length of two") else: if (type(new_column_name) != str): raise TypeError("new_column_name has to be a str") new_column_name = [new_column_name] # check if the new column name conflicts with existing ones for name in new_column_name: if (name in self.column_names()) and (name != column_name): raise ValueError("Column with name '" + name + "' already exists, pick a new column name") else: if stack_column_type == dict: new_column_name = ["",""] else: new_column_name = [""] # infer column types head_row = SArray(self[column_name].head(100)).dropna() if (len(head_row) == 0): raise ValueError("Cannot infer column type because there is not enough rows to infer value") if new_column_type is None: # we have to perform type inference if stack_column_type == dict: # infer key/value type keys = []; values = [] for row in head_row: for val in row: keys.append(val) if val is not None: values.append(row[val]) new_column_type = [ infer_type_of_list(keys), infer_type_of_list(values) ] else: values = [v for v in itertools.chain.from_iterable(head_row)] new_column_type = [infer_type_of_list(values)] with cython_context(): return SFrame(_proxy=self.__proxy__.stack(column_name, new_column_name, new_column_type, drop_na))
[ "def", "stack", "(", "self", ",", "column_name", ",", "new_column_name", "=", "None", ",", "drop_na", "=", "False", ",", "new_column_type", "=", "None", ")", ":", "# validate column_name", "column_name", "=", "str", "(", "column_name", ")", "if", "column_name", "not", "in", "self", ".", "column_names", "(", ")", ":", "raise", "ValueError", "(", "\"Cannot find column '\"", "+", "str", "(", "column_name", ")", "+", "\"' in the SFrame.\"", ")", "stack_column_type", "=", "self", "[", "column_name", "]", ".", "dtype", "if", "(", "stack_column_type", "not", "in", "[", "dict", ",", "array", ".", "array", ",", "list", "]", ")", ":", "raise", "TypeError", "(", "\"Stack is only supported for column of dict/list/array type.\"", ")", "# user defined types. do some checking", "if", "new_column_type", "is", "not", "None", ":", "# if new_column_type is a single type, just make it a list of one type", "if", "type", "(", "new_column_type", ")", "is", "type", ":", "new_column_type", "=", "[", "new_column_type", "]", "if", "(", "stack_column_type", "in", "[", "list", ",", "array", ".", "array", "]", ")", "and", "len", "(", "new_column_type", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"Expecting a single column type to unpack list or array columns\"", ")", "if", "(", "stack_column_type", "in", "[", "dict", "]", ")", "and", "len", "(", "new_column_type", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"Expecting two column types to unpack a dict column\"", ")", "if", "(", "new_column_name", "is", "not", "None", ")", ":", "if", "stack_column_type", "==", "dict", ":", "if", "(", "type", "(", "new_column_name", ")", "is", "not", "list", ")", ":", "raise", "TypeError", "(", "\"new_column_name has to be a list to stack dict type\"", ")", "elif", "(", "len", "(", "new_column_name", ")", "!=", "2", ")", ":", "raise", "TypeError", "(", "\"new_column_name must have length of two\"", ")", "else", ":", "if", "(", "type", "(", "new_column_name", ")", "!=", "str", ")", ":", "raise", "TypeError", "(", "\"new_column_name has to be a str\"", ")", "new_column_name", "=", "[", "new_column_name", "]", "# check if the new column name conflicts with existing ones", "for", "name", "in", "new_column_name", ":", "if", "(", "name", "in", "self", ".", "column_names", "(", ")", ")", "and", "(", "name", "!=", "column_name", ")", ":", "raise", "ValueError", "(", "\"Column with name '\"", "+", "name", "+", "\"' already exists, pick a new column name\"", ")", "else", ":", "if", "stack_column_type", "==", "dict", ":", "new_column_name", "=", "[", "\"\"", ",", "\"\"", "]", "else", ":", "new_column_name", "=", "[", "\"\"", "]", "# infer column types", "head_row", "=", "SArray", "(", "self", "[", "column_name", "]", ".", "head", "(", "100", ")", ")", ".", "dropna", "(", ")", "if", "(", "len", "(", "head_row", ")", "==", "0", ")", ":", "raise", "ValueError", "(", "\"Cannot infer column type because there is not enough rows to infer value\"", ")", "if", "new_column_type", "is", "None", ":", "# we have to perform type inference", "if", "stack_column_type", "==", "dict", ":", "# infer key/value type", "keys", "=", "[", "]", "values", "=", "[", "]", "for", "row", "in", "head_row", ":", "for", "val", "in", "row", ":", "keys", ".", "append", "(", "val", ")", "if", "val", "is", "not", "None", ":", "values", ".", "append", "(", "row", "[", "val", "]", ")", "new_column_type", "=", "[", "infer_type_of_list", "(", "keys", ")", ",", "infer_type_of_list", "(", "values", ")", "]", "else", ":", "values", "=", "[", "v", "for", "v", "in", "itertools", ".", "chain", ".", "from_iterable", "(", "head_row", ")", "]", "new_column_type", "=", "[", "infer_type_of_list", "(", "values", ")", "]", "with", "cython_context", "(", ")", ":", "return", "SFrame", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "stack", "(", "column_name", ",", "new_column_name", ",", "new_column_type", ",", "drop_na", ")", ")" ]
Convert a "wide" column of an SFrame to one or two "tall" columns 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) and all columns other than the one that is stacked. Parameters -------------- column_name : str The column to stack. This column must be of dict/list/array type 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 newly stacked column(s) plus columns in original SFrame other than the stacked column. See Also -------- unstack Examples --------- Suppose 'sf' is an SFrame that contains a column of dict type: >>> sf = turicreate.SFrame({'topic':[1,2,3,4], ... 'words': [{'a':3, 'cat':2}, ... {'a':1, 'the':2}, ... {'the':1, 'dog':3}, ... {}] ... }) +-------+----------------------+ | topic | words | +-------+----------------------+ | 1 | {'a': 3, 'cat': 2} | | 2 | {'a': 1, 'the': 2} | | 3 | {'the': 1, 'dog': 3} | | 4 | {} | +-------+----------------------+ [4 rows x 2 columns] Stack would stack all keys in one column and all values in another column: >>> sf.stack('words', new_column_name=['word', 'count']) +-------+------+-------+ | topic | word | count | +-------+------+-------+ | 1 | a | 3 | | 1 | cat | 2 | | 2 | a | 1 | | 2 | the | 2 | | 3 | the | 1 | | 3 | dog | 3 | | 4 | None | None | +-------+------+-------+ [7 rows x 3 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. Suppose 'sf' is an SFrame that contains a user and his/her friends, where 'friends' columns is an array type. Stack on 'friends' column would create a user/friend list for each user/friend pair: >>> sf = turicreate.SFrame({'topic':[1,2,3], ... 'friends':[[2,3,4], [5,6], ... [4,5,10,None]] ... }) >>> sf +-------+------------------+ | topic | friends | +-------+------------------+ | 1 | [2, 3, 4] | | 2 | [5, 6] | | 3 | [4, 5, 10, None] | +----- -+------------------+ [3 rows x 2 columns] >>> sf.stack('friends', new_column_name='friend') +-------+--------+ | topic | friend | +-------+--------+ | 1 | 2 | | 1 | 3 | | 1 | 4 | | 2 | 5 | | 2 | 6 | | 3 | 4 | | 3 | 5 | | 3 | 10 | | 3 | None | +-------+--------+ [9 rows x 2 columns]
[ "Convert", "a", "wide", "column", "of", "an", "SFrame", "to", "one", "or", "two", "tall", "columns", "by", "stacking", "all", "values", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L5041-L5235
29,053
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.unstack
def unstack(self, column_names, new_column_name=None): """ Concatenate values from one or two columns into one column, grouping by all other columns. The resulting column could be of type list, array or dictionary. If ``column_names`` is a numeric column, the result will be of array.array type. If ``column_names`` is a non-numeric column, the new column will be of list type. If ``column_names`` is a list of two columns, the new column will be of dict type where the keys are taken from the first column in the list. Parameters ---------- column_names : str | [str, str] The column(s) that is(are) to be concatenated. If str, then collapsed column type is either array or list. If [str, str], then collapsed column type is dict new_column_name : str, optional New column name. If not given, a name is generated automatically. Returns ------- out : SFrame A new SFrame containing the grouped columns as well as the new column. See Also -------- stack : The inverse of unstack. groupby : ``unstack`` is a special version of ``groupby`` that uses the :mod:`~turicreate.aggregate.CONCAT` aggregator Notes ----- - There is no guarantee the resulting SFrame maintains the same order as the original SFrame. - Missing values are maintained during unstack. - When unstacking into a dictionary, if there is more than one instance of a given key for a particular group, an arbitrary value is selected. Examples -------- >>> sf = turicreate.SFrame({'count':[4, 2, 1, 1, 2, None], ... 'topic':['cat', 'cat', 'dog', 'elephant', 'elephant', 'fish'], ... 'word':['a', 'c', 'c', 'a', 'b', None]}) >>> sf.unstack(column_names=['word', 'count'], new_column_name='words') +----------+------------------+ | topic | words | +----------+------------------+ | elephant | {'a': 1, 'b': 2} | | dog | {'c': 1} | | cat | {'a': 4, 'c': 2} | | fish | None | +----------+------------------+ [4 rows x 2 columns] >>> sf = turicreate.SFrame({'friend': [2, 3, 4, 5, 6, 4, 5, 2, 3], ... 'user': [1, 1, 1, 2, 2, 2, 3, 4, 4]}) >>> sf.unstack('friend', new_column_name='new name') +------+-----------+ | user | new name | +------+-----------+ | 3 | [5] | | 1 | [2, 3, 4] | | 2 | [6, 4, 5] | | 4 | [2, 3] | +------+-----------+ [4 rows x 2 columns] """ if (type(column_names) != str and len(column_names) != 2): raise TypeError("'column_names' parameter has to be either a string or a list of two strings.") with cython_context(): if type(column_names) == str: key_columns = [i for i in self.column_names() if i != column_names] if new_column_name is not None: return self.groupby(key_columns, {new_column_name : aggregate.CONCAT(column_names)}) else: return self.groupby(key_columns, aggregate.CONCAT(column_names)) elif len(column_names) == 2: key_columns = [i for i in self.column_names() if i not in column_names] if new_column_name is not None: return self.groupby(key_columns, {new_column_name: aggregate.CONCAT(column_names[0], column_names[1])}) else: return self.groupby(key_columns, aggregate.CONCAT(column_names[0], column_names[1]))
python
def unstack(self, column_names, new_column_name=None): """ Concatenate values from one or two columns into one column, grouping by all other columns. The resulting column could be of type list, array or dictionary. If ``column_names`` is a numeric column, the result will be of array.array type. If ``column_names`` is a non-numeric column, the new column will be of list type. If ``column_names`` is a list of two columns, the new column will be of dict type where the keys are taken from the first column in the list. Parameters ---------- column_names : str | [str, str] The column(s) that is(are) to be concatenated. If str, then collapsed column type is either array or list. If [str, str], then collapsed column type is dict new_column_name : str, optional New column name. If not given, a name is generated automatically. Returns ------- out : SFrame A new SFrame containing the grouped columns as well as the new column. See Also -------- stack : The inverse of unstack. groupby : ``unstack`` is a special version of ``groupby`` that uses the :mod:`~turicreate.aggregate.CONCAT` aggregator Notes ----- - There is no guarantee the resulting SFrame maintains the same order as the original SFrame. - Missing values are maintained during unstack. - When unstacking into a dictionary, if there is more than one instance of a given key for a particular group, an arbitrary value is selected. Examples -------- >>> sf = turicreate.SFrame({'count':[4, 2, 1, 1, 2, None], ... 'topic':['cat', 'cat', 'dog', 'elephant', 'elephant', 'fish'], ... 'word':['a', 'c', 'c', 'a', 'b', None]}) >>> sf.unstack(column_names=['word', 'count'], new_column_name='words') +----------+------------------+ | topic | words | +----------+------------------+ | elephant | {'a': 1, 'b': 2} | | dog | {'c': 1} | | cat | {'a': 4, 'c': 2} | | fish | None | +----------+------------------+ [4 rows x 2 columns] >>> sf = turicreate.SFrame({'friend': [2, 3, 4, 5, 6, 4, 5, 2, 3], ... 'user': [1, 1, 1, 2, 2, 2, 3, 4, 4]}) >>> sf.unstack('friend', new_column_name='new name') +------+-----------+ | user | new name | +------+-----------+ | 3 | [5] | | 1 | [2, 3, 4] | | 2 | [6, 4, 5] | | 4 | [2, 3] | +------+-----------+ [4 rows x 2 columns] """ if (type(column_names) != str and len(column_names) != 2): raise TypeError("'column_names' parameter has to be either a string or a list of two strings.") with cython_context(): if type(column_names) == str: key_columns = [i for i in self.column_names() if i != column_names] if new_column_name is not None: return self.groupby(key_columns, {new_column_name : aggregate.CONCAT(column_names)}) else: return self.groupby(key_columns, aggregate.CONCAT(column_names)) elif len(column_names) == 2: key_columns = [i for i in self.column_names() if i not in column_names] if new_column_name is not None: return self.groupby(key_columns, {new_column_name: aggregate.CONCAT(column_names[0], column_names[1])}) else: return self.groupby(key_columns, aggregate.CONCAT(column_names[0], column_names[1]))
[ "def", "unstack", "(", "self", ",", "column_names", ",", "new_column_name", "=", "None", ")", ":", "if", "(", "type", "(", "column_names", ")", "!=", "str", "and", "len", "(", "column_names", ")", "!=", "2", ")", ":", "raise", "TypeError", "(", "\"'column_names' parameter has to be either a string or a list of two strings.\"", ")", "with", "cython_context", "(", ")", ":", "if", "type", "(", "column_names", ")", "==", "str", ":", "key_columns", "=", "[", "i", "for", "i", "in", "self", ".", "column_names", "(", ")", "if", "i", "!=", "column_names", "]", "if", "new_column_name", "is", "not", "None", ":", "return", "self", ".", "groupby", "(", "key_columns", ",", "{", "new_column_name", ":", "aggregate", ".", "CONCAT", "(", "column_names", ")", "}", ")", "else", ":", "return", "self", ".", "groupby", "(", "key_columns", ",", "aggregate", ".", "CONCAT", "(", "column_names", ")", ")", "elif", "len", "(", "column_names", ")", "==", "2", ":", "key_columns", "=", "[", "i", "for", "i", "in", "self", ".", "column_names", "(", ")", "if", "i", "not", "in", "column_names", "]", "if", "new_column_name", "is", "not", "None", ":", "return", "self", ".", "groupby", "(", "key_columns", ",", "{", "new_column_name", ":", "aggregate", ".", "CONCAT", "(", "column_names", "[", "0", "]", ",", "column_names", "[", "1", "]", ")", "}", ")", "else", ":", "return", "self", ".", "groupby", "(", "key_columns", ",", "aggregate", ".", "CONCAT", "(", "column_names", "[", "0", "]", ",", "column_names", "[", "1", "]", ")", ")" ]
Concatenate values from one or two columns into one column, grouping by all other columns. The resulting column could be of type list, array or dictionary. If ``column_names`` is a numeric column, the result will be of array.array type. If ``column_names`` is a non-numeric column, the new column will be of list type. If ``column_names`` is a list of two columns, the new column will be of dict type where the keys are taken from the first column in the list. Parameters ---------- column_names : str | [str, str] The column(s) that is(are) to be concatenated. If str, then collapsed column type is either array or list. If [str, str], then collapsed column type is dict new_column_name : str, optional New column name. If not given, a name is generated automatically. Returns ------- out : SFrame A new SFrame containing the grouped columns as well as the new column. See Also -------- stack : The inverse of unstack. groupby : ``unstack`` is a special version of ``groupby`` that uses the :mod:`~turicreate.aggregate.CONCAT` aggregator Notes ----- - There is no guarantee the resulting SFrame maintains the same order as the original SFrame. - Missing values are maintained during unstack. - When unstacking into a dictionary, if there is more than one instance of a given key for a particular group, an arbitrary value is selected. Examples -------- >>> sf = turicreate.SFrame({'count':[4, 2, 1, 1, 2, None], ... 'topic':['cat', 'cat', 'dog', 'elephant', 'elephant', 'fish'], ... 'word':['a', 'c', 'c', 'a', 'b', None]}) >>> sf.unstack(column_names=['word', 'count'], new_column_name='words') +----------+------------------+ | topic | words | +----------+------------------+ | elephant | {'a': 1, 'b': 2} | | dog | {'c': 1} | | cat | {'a': 4, 'c': 2} | | fish | None | +----------+------------------+ [4 rows x 2 columns] >>> sf = turicreate.SFrame({'friend': [2, 3, 4, 5, 6, 4, 5, 2, 3], ... 'user': [1, 1, 1, 2, 2, 2, 3, 4, 4]}) >>> sf.unstack('friend', new_column_name='new name') +------+-----------+ | user | new name | +------+-----------+ | 3 | [5] | | 1 | [2, 3, 4] | | 2 | [6, 4, 5] | | 4 | [2, 3] | +------+-----------+ [4 rows x 2 columns]
[ "Concatenate", "values", "from", "one", "or", "two", "columns", "into", "one", "column", "grouping", "by", "all", "other", "columns", ".", "The", "resulting", "column", "could", "be", "of", "type", "list", "array", "or", "dictionary", ".", "If", "column_names", "is", "a", "numeric", "column", "the", "result", "will", "be", "of", "array", ".", "array", "type", ".", "If", "column_names", "is", "a", "non", "-", "numeric", "column", "the", "new", "column", "will", "be", "of", "list", "type", ".", "If", "column_names", "is", "a", "list", "of", "two", "columns", "the", "new", "column", "will", "be", "of", "dict", "type", "where", "the", "keys", "are", "taken", "from", "the", "first", "column", "in", "the", "list", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L5237-L5324
29,054
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.sort
def sort(self, key_column_names, ascending=True): """ Sort current SFrame by the given columns, using the given sort order. Only columns that are type of str, int and float can be sorted. Parameters ---------- key_column_names : str | list of str | list of (str, bool) pairs Names of columns to be sorted. The result will be sorted first by first column, followed by second column, and so on. All columns will be sorted in the same order as governed by the `ascending` parameter. To control the sort ordering for each column individually, `key_column_names` must be a list of (str, bool) pairs. Given this case, the first value is the column name and the second value is a boolean indicating whether the sort order is ascending. ascending : bool, optional Sort all columns in the given order. Returns ------- out : SFrame A new SFrame that is sorted according to given sort criteria See Also -------- topk Examples -------- Suppose 'sf' is an sframe that has three columns 'a', 'b', 'c'. To sort by column 'a', ascending >>> sf = turicreate.SFrame({'a':[1,3,2,1], ... 'b':['a','c','b','b'], ... 'c':['x','y','z','y']}) >>> sf +---+---+---+ | a | b | c | +---+---+---+ | 1 | a | x | | 3 | c | y | | 2 | b | z | | 1 | b | y | +---+---+---+ [4 rows x 3 columns] >>> sf.sort('a') +---+---+---+ | a | b | c | +---+---+---+ | 1 | a | x | | 1 | b | y | | 2 | b | z | | 3 | c | y | +---+---+---+ [4 rows x 3 columns] To sort by column 'a', descending >>> sf.sort('a', ascending = False) +---+---+---+ | a | b | c | +---+---+---+ | 3 | c | y | | 2 | b | z | | 1 | a | x | | 1 | b | y | +---+---+---+ [4 rows x 3 columns] To sort by column 'a' and 'b', all ascending >>> sf.sort(['a', 'b']) +---+---+---+ | a | b | c | +---+---+---+ | 1 | a | x | | 1 | b | y | | 2 | b | z | | 3 | c | y | +---+---+---+ [4 rows x 3 columns] To sort by column 'a' ascending, and then by column 'c' descending >>> sf.sort([('a', True), ('c', False)]) +---+---+---+ | a | b | c | +---+---+---+ | 1 | b | y | | 1 | a | x | | 2 | b | z | | 3 | c | y | +---+---+---+ [4 rows x 3 columns] """ sort_column_names = [] sort_column_orders = [] # validate key_column_names if (type(key_column_names) == str): sort_column_names = [key_column_names] elif (type(key_column_names) == list): if (len(key_column_names) == 0): raise ValueError("Please provide at least one column to sort") first_param_types = set([type(i) for i in key_column_names]) if (len(first_param_types) != 1): raise ValueError("key_column_names element are not of the same type") first_param_type = first_param_types.pop() if (first_param_type == tuple): sort_column_names = [i[0] for i in key_column_names] sort_column_orders = [i[1] for i in key_column_names] elif(first_param_type == str): sort_column_names = key_column_names else: raise TypeError("key_column_names type is not supported") else: raise TypeError("key_column_names type is not correct. Supported types are str, list of str or list of (str,bool) pair.") # use the second parameter if the sort order is not given if (len(sort_column_orders) == 0): sort_column_orders = [ascending for i in sort_column_names] # make sure all column exists my_column_names = set(self.column_names()) for column in sort_column_names: if (type(column) != str): raise TypeError("Only string parameter can be passed in as column names") if (column not in my_column_names): raise ValueError("SFrame has no column named: '" + str(column) + "'") if (self[column].dtype not in (str, int, float,datetime.datetime)): raise TypeError("Only columns of type (str, int, float) can be sorted") with cython_context(): return SFrame(_proxy=self.__proxy__.sort(sort_column_names, sort_column_orders))
python
def sort(self, key_column_names, ascending=True): """ Sort current SFrame by the given columns, using the given sort order. Only columns that are type of str, int and float can be sorted. Parameters ---------- key_column_names : str | list of str | list of (str, bool) pairs Names of columns to be sorted. The result will be sorted first by first column, followed by second column, and so on. All columns will be sorted in the same order as governed by the `ascending` parameter. To control the sort ordering for each column individually, `key_column_names` must be a list of (str, bool) pairs. Given this case, the first value is the column name and the second value is a boolean indicating whether the sort order is ascending. ascending : bool, optional Sort all columns in the given order. Returns ------- out : SFrame A new SFrame that is sorted according to given sort criteria See Also -------- topk Examples -------- Suppose 'sf' is an sframe that has three columns 'a', 'b', 'c'. To sort by column 'a', ascending >>> sf = turicreate.SFrame({'a':[1,3,2,1], ... 'b':['a','c','b','b'], ... 'c':['x','y','z','y']}) >>> sf +---+---+---+ | a | b | c | +---+---+---+ | 1 | a | x | | 3 | c | y | | 2 | b | z | | 1 | b | y | +---+---+---+ [4 rows x 3 columns] >>> sf.sort('a') +---+---+---+ | a | b | c | +---+---+---+ | 1 | a | x | | 1 | b | y | | 2 | b | z | | 3 | c | y | +---+---+---+ [4 rows x 3 columns] To sort by column 'a', descending >>> sf.sort('a', ascending = False) +---+---+---+ | a | b | c | +---+---+---+ | 3 | c | y | | 2 | b | z | | 1 | a | x | | 1 | b | y | +---+---+---+ [4 rows x 3 columns] To sort by column 'a' and 'b', all ascending >>> sf.sort(['a', 'b']) +---+---+---+ | a | b | c | +---+---+---+ | 1 | a | x | | 1 | b | y | | 2 | b | z | | 3 | c | y | +---+---+---+ [4 rows x 3 columns] To sort by column 'a' ascending, and then by column 'c' descending >>> sf.sort([('a', True), ('c', False)]) +---+---+---+ | a | b | c | +---+---+---+ | 1 | b | y | | 1 | a | x | | 2 | b | z | | 3 | c | y | +---+---+---+ [4 rows x 3 columns] """ sort_column_names = [] sort_column_orders = [] # validate key_column_names if (type(key_column_names) == str): sort_column_names = [key_column_names] elif (type(key_column_names) == list): if (len(key_column_names) == 0): raise ValueError("Please provide at least one column to sort") first_param_types = set([type(i) for i in key_column_names]) if (len(first_param_types) != 1): raise ValueError("key_column_names element are not of the same type") first_param_type = first_param_types.pop() if (first_param_type == tuple): sort_column_names = [i[0] for i in key_column_names] sort_column_orders = [i[1] for i in key_column_names] elif(first_param_type == str): sort_column_names = key_column_names else: raise TypeError("key_column_names type is not supported") else: raise TypeError("key_column_names type is not correct. Supported types are str, list of str or list of (str,bool) pair.") # use the second parameter if the sort order is not given if (len(sort_column_orders) == 0): sort_column_orders = [ascending for i in sort_column_names] # make sure all column exists my_column_names = set(self.column_names()) for column in sort_column_names: if (type(column) != str): raise TypeError("Only string parameter can be passed in as column names") if (column not in my_column_names): raise ValueError("SFrame has no column named: '" + str(column) + "'") if (self[column].dtype not in (str, int, float,datetime.datetime)): raise TypeError("Only columns of type (str, int, float) can be sorted") with cython_context(): return SFrame(_proxy=self.__proxy__.sort(sort_column_names, sort_column_orders))
[ "def", "sort", "(", "self", ",", "key_column_names", ",", "ascending", "=", "True", ")", ":", "sort_column_names", "=", "[", "]", "sort_column_orders", "=", "[", "]", "# validate key_column_names", "if", "(", "type", "(", "key_column_names", ")", "==", "str", ")", ":", "sort_column_names", "=", "[", "key_column_names", "]", "elif", "(", "type", "(", "key_column_names", ")", "==", "list", ")", ":", "if", "(", "len", "(", "key_column_names", ")", "==", "0", ")", ":", "raise", "ValueError", "(", "\"Please provide at least one column to sort\"", ")", "first_param_types", "=", "set", "(", "[", "type", "(", "i", ")", "for", "i", "in", "key_column_names", "]", ")", "if", "(", "len", "(", "first_param_types", ")", "!=", "1", ")", ":", "raise", "ValueError", "(", "\"key_column_names element are not of the same type\"", ")", "first_param_type", "=", "first_param_types", ".", "pop", "(", ")", "if", "(", "first_param_type", "==", "tuple", ")", ":", "sort_column_names", "=", "[", "i", "[", "0", "]", "for", "i", "in", "key_column_names", "]", "sort_column_orders", "=", "[", "i", "[", "1", "]", "for", "i", "in", "key_column_names", "]", "elif", "(", "first_param_type", "==", "str", ")", ":", "sort_column_names", "=", "key_column_names", "else", ":", "raise", "TypeError", "(", "\"key_column_names type is not supported\"", ")", "else", ":", "raise", "TypeError", "(", "\"key_column_names type is not correct. Supported types are str, list of str or list of (str,bool) pair.\"", ")", "# use the second parameter if the sort order is not given", "if", "(", "len", "(", "sort_column_orders", ")", "==", "0", ")", ":", "sort_column_orders", "=", "[", "ascending", "for", "i", "in", "sort_column_names", "]", "# make sure all column exists", "my_column_names", "=", "set", "(", "self", ".", "column_names", "(", ")", ")", "for", "column", "in", "sort_column_names", ":", "if", "(", "type", "(", "column", ")", "!=", "str", ")", ":", "raise", "TypeError", "(", "\"Only string parameter can be passed in as column names\"", ")", "if", "(", "column", "not", "in", "my_column_names", ")", ":", "raise", "ValueError", "(", "\"SFrame has no column named: '\"", "+", "str", "(", "column", ")", "+", "\"'\"", ")", "if", "(", "self", "[", "column", "]", ".", "dtype", "not", "in", "(", "str", ",", "int", ",", "float", ",", "datetime", ".", "datetime", ")", ")", ":", "raise", "TypeError", "(", "\"Only columns of type (str, int, float) can be sorted\"", ")", "with", "cython_context", "(", ")", ":", "return", "SFrame", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "sort", "(", "sort_column_names", ",", "sort_column_orders", ")", ")" ]
Sort current SFrame by the given columns, using the given sort order. Only columns that are type of str, int and float can be sorted. Parameters ---------- key_column_names : str | list of str | list of (str, bool) pairs Names of columns to be sorted. The result will be sorted first by first column, followed by second column, and so on. All columns will be sorted in the same order as governed by the `ascending` parameter. To control the sort ordering for each column individually, `key_column_names` must be a list of (str, bool) pairs. Given this case, the first value is the column name and the second value is a boolean indicating whether the sort order is ascending. ascending : bool, optional Sort all columns in the given order. Returns ------- out : SFrame A new SFrame that is sorted according to given sort criteria See Also -------- topk Examples -------- Suppose 'sf' is an sframe that has three columns 'a', 'b', 'c'. To sort by column 'a', ascending >>> sf = turicreate.SFrame({'a':[1,3,2,1], ... 'b':['a','c','b','b'], ... 'c':['x','y','z','y']}) >>> sf +---+---+---+ | a | b | c | +---+---+---+ | 1 | a | x | | 3 | c | y | | 2 | b | z | | 1 | b | y | +---+---+---+ [4 rows x 3 columns] >>> sf.sort('a') +---+---+---+ | a | b | c | +---+---+---+ | 1 | a | x | | 1 | b | y | | 2 | b | z | | 3 | c | y | +---+---+---+ [4 rows x 3 columns] To sort by column 'a', descending >>> sf.sort('a', ascending = False) +---+---+---+ | a | b | c | +---+---+---+ | 3 | c | y | | 2 | b | z | | 1 | a | x | | 1 | b | y | +---+---+---+ [4 rows x 3 columns] To sort by column 'a' and 'b', all ascending >>> sf.sort(['a', 'b']) +---+---+---+ | a | b | c | +---+---+---+ | 1 | a | x | | 1 | b | y | | 2 | b | z | | 3 | c | y | +---+---+---+ [4 rows x 3 columns] To sort by column 'a' ascending, and then by column 'c' descending >>> sf.sort([('a', True), ('c', False)]) +---+---+---+ | a | b | c | +---+---+---+ | 1 | b | y | | 1 | a | x | | 2 | b | z | | 3 | c | y | +---+---+---+ [4 rows x 3 columns]
[ "Sort", "current", "SFrame", "by", "the", "given", "columns", "using", "the", "given", "sort", "order", ".", "Only", "columns", "that", "are", "type", "of", "str", "int", "and", "float", "can", "be", "sorted", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L5373-L5511
29,055
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.dropna
def dropna(self, columns=None, how='any'): """ Remove missing values from an SFrame. A missing value is either ``None`` or ``NaN``. If ``how`` is 'any', a row will be removed if any of the columns in the ``columns`` parameter contains at least one missing value. If ``how`` is 'all', a row will be removed if all of the columns in the ``columns`` parameter are missing values. If the ``columns`` parameter is not specified, the default is to consider all columns when searching for missing values. Parameters ---------- columns : list or str, optional The columns to use when looking for missing values. By default, all columns are used. how : {'any', 'all'}, optional Specifies whether a row should be dropped if at least one column has missing values, or if all columns have missing values. 'any' is default. Returns ------- out : SFrame SFrame with missing values removed (according to the given rules). See Also -------- dropna_split : Drops missing rows from the SFrame and returns them. Examples -------- Drop all missing values. >>> sf = turicreate.SFrame({'a': [1, None, None], 'b': ['a', 'b', None]}) >>> sf.dropna() +---+---+ | a | b | +---+---+ | 1 | a | +---+---+ [1 rows x 2 columns] Drop rows where every value is missing. >>> sf.dropna(any="all") +------+---+ | a | b | +------+---+ | 1 | a | | None | b | +------+---+ [2 rows x 2 columns] Drop rows where column 'a' has a missing value. >>> sf.dropna('a', any="all") +---+---+ | a | b | +---+---+ | 1 | a | +---+---+ [1 rows x 2 columns] """ # If the user gives me an empty list (the indicator to use all columns) # NA values being dropped would not be the expected behavior. This # is a NOOP, so let's not bother the server if type(columns) is list and len(columns) == 0: return SFrame(_proxy=self.__proxy__) (columns, all_behavior) = self.__dropna_errchk(columns, how) with cython_context(): return SFrame(_proxy=self.__proxy__.drop_missing_values(columns, all_behavior, False))
python
def dropna(self, columns=None, how='any'): """ Remove missing values from an SFrame. A missing value is either ``None`` or ``NaN``. If ``how`` is 'any', a row will be removed if any of the columns in the ``columns`` parameter contains at least one missing value. If ``how`` is 'all', a row will be removed if all of the columns in the ``columns`` parameter are missing values. If the ``columns`` parameter is not specified, the default is to consider all columns when searching for missing values. Parameters ---------- columns : list or str, optional The columns to use when looking for missing values. By default, all columns are used. how : {'any', 'all'}, optional Specifies whether a row should be dropped if at least one column has missing values, or if all columns have missing values. 'any' is default. Returns ------- out : SFrame SFrame with missing values removed (according to the given rules). See Also -------- dropna_split : Drops missing rows from the SFrame and returns them. Examples -------- Drop all missing values. >>> sf = turicreate.SFrame({'a': [1, None, None], 'b': ['a', 'b', None]}) >>> sf.dropna() +---+---+ | a | b | +---+---+ | 1 | a | +---+---+ [1 rows x 2 columns] Drop rows where every value is missing. >>> sf.dropna(any="all") +------+---+ | a | b | +------+---+ | 1 | a | | None | b | +------+---+ [2 rows x 2 columns] Drop rows where column 'a' has a missing value. >>> sf.dropna('a', any="all") +---+---+ | a | b | +---+---+ | 1 | a | +---+---+ [1 rows x 2 columns] """ # If the user gives me an empty list (the indicator to use all columns) # NA values being dropped would not be the expected behavior. This # is a NOOP, so let's not bother the server if type(columns) is list and len(columns) == 0: return SFrame(_proxy=self.__proxy__) (columns, all_behavior) = self.__dropna_errchk(columns, how) with cython_context(): return SFrame(_proxy=self.__proxy__.drop_missing_values(columns, all_behavior, False))
[ "def", "dropna", "(", "self", ",", "columns", "=", "None", ",", "how", "=", "'any'", ")", ":", "# If the user gives me an empty list (the indicator to use all columns)", "# NA values being dropped would not be the expected behavior. This", "# is a NOOP, so let's not bother the server", "if", "type", "(", "columns", ")", "is", "list", "and", "len", "(", "columns", ")", "==", "0", ":", "return", "SFrame", "(", "_proxy", "=", "self", ".", "__proxy__", ")", "(", "columns", ",", "all_behavior", ")", "=", "self", ".", "__dropna_errchk", "(", "columns", ",", "how", ")", "with", "cython_context", "(", ")", ":", "return", "SFrame", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "drop_missing_values", "(", "columns", ",", "all_behavior", ",", "False", ")", ")" ]
Remove missing values from an SFrame. A missing value is either ``None`` or ``NaN``. If ``how`` is 'any', a row will be removed if any of the columns in the ``columns`` parameter contains at least one missing value. If ``how`` is 'all', a row will be removed if all of the columns in the ``columns`` parameter are missing values. If the ``columns`` parameter is not specified, the default is to consider all columns when searching for missing values. Parameters ---------- columns : list or str, optional The columns to use when looking for missing values. By default, all columns are used. how : {'any', 'all'}, optional Specifies whether a row should be dropped if at least one column has missing values, or if all columns have missing values. 'any' is default. Returns ------- out : SFrame SFrame with missing values removed (according to the given rules). See Also -------- dropna_split : Drops missing rows from the SFrame and returns them. Examples -------- Drop all missing values. >>> sf = turicreate.SFrame({'a': [1, None, None], 'b': ['a', 'b', None]}) >>> sf.dropna() +---+---+ | a | b | +---+---+ | 1 | a | +---+---+ [1 rows x 2 columns] Drop rows where every value is missing. >>> sf.dropna(any="all") +------+---+ | a | b | +------+---+ | 1 | a | | None | b | +------+---+ [2 rows x 2 columns] Drop rows where column 'a' has a missing value. >>> sf.dropna('a', any="all") +---+---+ | a | b | +---+---+ | 1 | a | +---+---+ [1 rows x 2 columns]
[ "Remove", "missing", "values", "from", "an", "SFrame", ".", "A", "missing", "value", "is", "either", "None", "or", "NaN", ".", "If", "how", "is", "any", "a", "row", "will", "be", "removed", "if", "any", "of", "the", "columns", "in", "the", "columns", "parameter", "contains", "at", "least", "one", "missing", "value", ".", "If", "how", "is", "all", "a", "row", "will", "be", "removed", "if", "all", "of", "the", "columns", "in", "the", "columns", "parameter", "are", "missing", "values", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L5513-L5588
29,056
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.fillna
def fillna(self, column_name, value): """ Fill all missing values with a given value in a given column. If the ``value`` is not the same type as the values in ``column_name``, this method attempts to convert the value to the original column's type. If this fails, an error is raised. Parameters ---------- column_name : str The name of the column to modify. value : type convertible to SArray's type The value used to replace all missing values. Returns ------- out : SFrame A new SFrame with the specified value in place of missing values. See Also -------- dropna Examples -------- >>> sf = turicreate.SFrame({'a':[1, None, None], ... 'b':['13.1', '17.2', None]}) >>> sf = sf.fillna('a', 0) >>> sf +---+------+ | a | b | +---+------+ | 1 | 13.1 | | 0 | 17.2 | | 0 | None | +---+------+ [3 rows x 2 columns] """ # Normal error checking if type(column_name) is not str: raise TypeError("column_name must be a str") ret = self[self.column_names()] ret[column_name] = ret[column_name].fillna(value) return ret
python
def fillna(self, column_name, value): """ Fill all missing values with a given value in a given column. If the ``value`` is not the same type as the values in ``column_name``, this method attempts to convert the value to the original column's type. If this fails, an error is raised. Parameters ---------- column_name : str The name of the column to modify. value : type convertible to SArray's type The value used to replace all missing values. Returns ------- out : SFrame A new SFrame with the specified value in place of missing values. See Also -------- dropna Examples -------- >>> sf = turicreate.SFrame({'a':[1, None, None], ... 'b':['13.1', '17.2', None]}) >>> sf = sf.fillna('a', 0) >>> sf +---+------+ | a | b | +---+------+ | 1 | 13.1 | | 0 | 17.2 | | 0 | None | +---+------+ [3 rows x 2 columns] """ # Normal error checking if type(column_name) is not str: raise TypeError("column_name must be a str") ret = self[self.column_names()] ret[column_name] = ret[column_name].fillna(value) return ret
[ "def", "fillna", "(", "self", ",", "column_name", ",", "value", ")", ":", "# Normal error checking", "if", "type", "(", "column_name", ")", "is", "not", "str", ":", "raise", "TypeError", "(", "\"column_name must be a str\"", ")", "ret", "=", "self", "[", "self", ".", "column_names", "(", ")", "]", "ret", "[", "column_name", "]", "=", "ret", "[", "column_name", "]", ".", "fillna", "(", "value", ")", "return", "ret" ]
Fill all missing values with a given value in a given column. If the ``value`` is not the same type as the values in ``column_name``, this method attempts to convert the value to the original column's type. If this fails, an error is raised. Parameters ---------- column_name : str The name of the column to modify. value : type convertible to SArray's type The value used to replace all missing values. Returns ------- out : SFrame A new SFrame with the specified value in place of missing values. See Also -------- dropna Examples -------- >>> sf = turicreate.SFrame({'a':[1, None, None], ... 'b':['13.1', '17.2', None]}) >>> sf = sf.fillna('a', 0) >>> sf +---+------+ | a | b | +---+------+ | 1 | 13.1 | | 0 | 17.2 | | 0 | None | +---+------+ [3 rows x 2 columns]
[ "Fill", "all", "missing", "values", "with", "a", "given", "value", "in", "a", "given", "column", ".", "If", "the", "value", "is", "not", "the", "same", "type", "as", "the", "values", "in", "column_name", "this", "method", "attempts", "to", "convert", "the", "value", "to", "the", "original", "column", "s", "type", ".", "If", "this", "fails", "an", "error", "is", "raised", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L5684-L5728
29,057
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.add_row_number
def add_row_number(self, column_name='id', start=0, inplace=False): """ Returns an SFrame with a new column that numbers each row sequentially. By default the count starts at 0, but this can be changed to a positive or negative number. The new column will be named with the given column name. An error will be raised if the given column name already exists in the SFrame. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- column_name : str, optional The name of the new column that will hold the row numbers. start : int, optional The number used to start the row number count. inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The new SFrame with a column name Notes ----- The range of numbers is constrained by a signed 64-bit integer, so beware of overflow if you think the results in the row number column will be greater than 9 quintillion. Examples -------- >>> sf = turicreate.SFrame({'a': [1, None, None], 'b': ['a', 'b', None]}) >>> sf.add_row_number() +----+------+------+ | id | a | b | +----+------+------+ | 0 | 1 | a | | 1 | None | b | | 2 | None | None | +----+------+------+ [3 rows x 3 columns] """ if type(column_name) is not str: raise TypeError("Must give column_name as strs") if type(start) is not int: raise TypeError("Must give start as int") if column_name in self.column_names(): raise RuntimeError("Column '" + column_name + "' already exists in the current SFrame") the_col = _create_sequential_sarray(self.num_rows(), start) # Make sure the row number column is the first column new_sf = SFrame() new_sf.add_column(the_col, column_name, inplace=True) new_sf.add_columns(self, inplace=True) if inplace: self.__proxy__ = new_sf.__proxy__ return self else: return new_sf
python
def add_row_number(self, column_name='id', start=0, inplace=False): """ Returns an SFrame with a new column that numbers each row sequentially. By default the count starts at 0, but this can be changed to a positive or negative number. The new column will be named with the given column name. An error will be raised if the given column name already exists in the SFrame. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- column_name : str, optional The name of the new column that will hold the row numbers. start : int, optional The number used to start the row number count. inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The new SFrame with a column name Notes ----- The range of numbers is constrained by a signed 64-bit integer, so beware of overflow if you think the results in the row number column will be greater than 9 quintillion. Examples -------- >>> sf = turicreate.SFrame({'a': [1, None, None], 'b': ['a', 'b', None]}) >>> sf.add_row_number() +----+------+------+ | id | a | b | +----+------+------+ | 0 | 1 | a | | 1 | None | b | | 2 | None | None | +----+------+------+ [3 rows x 3 columns] """ if type(column_name) is not str: raise TypeError("Must give column_name as strs") if type(start) is not int: raise TypeError("Must give start as int") if column_name in self.column_names(): raise RuntimeError("Column '" + column_name + "' already exists in the current SFrame") the_col = _create_sequential_sarray(self.num_rows(), start) # Make sure the row number column is the first column new_sf = SFrame() new_sf.add_column(the_col, column_name, inplace=True) new_sf.add_columns(self, inplace=True) if inplace: self.__proxy__ = new_sf.__proxy__ return self else: return new_sf
[ "def", "add_row_number", "(", "self", ",", "column_name", "=", "'id'", ",", "start", "=", "0", ",", "inplace", "=", "False", ")", ":", "if", "type", "(", "column_name", ")", "is", "not", "str", ":", "raise", "TypeError", "(", "\"Must give column_name as strs\"", ")", "if", "type", "(", "start", ")", "is", "not", "int", ":", "raise", "TypeError", "(", "\"Must give start as int\"", ")", "if", "column_name", "in", "self", ".", "column_names", "(", ")", ":", "raise", "RuntimeError", "(", "\"Column '\"", "+", "column_name", "+", "\"' already exists in the current SFrame\"", ")", "the_col", "=", "_create_sequential_sarray", "(", "self", ".", "num_rows", "(", ")", ",", "start", ")", "# Make sure the row number column is the first column", "new_sf", "=", "SFrame", "(", ")", "new_sf", ".", "add_column", "(", "the_col", ",", "column_name", ",", "inplace", "=", "True", ")", "new_sf", ".", "add_columns", "(", "self", ",", "inplace", "=", "True", ")", "if", "inplace", ":", "self", ".", "__proxy__", "=", "new_sf", ".", "__proxy__", "return", "self", "else", ":", "return", "new_sf" ]
Returns an SFrame with a new column that numbers each row sequentially. By default the count starts at 0, but this can be changed to a positive or negative number. The new column will be named with the given column name. An error will be raised if the given column name already exists in the SFrame. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- column_name : str, optional The name of the new column that will hold the row numbers. start : int, optional The number used to start the row number count. inplace : bool, optional. Defaults to False. Whether the SFrame is modified in place. Returns ------- out : SFrame The new SFrame with a column name Notes ----- The range of numbers is constrained by a signed 64-bit integer, so beware of overflow if you think the results in the row number column will be greater than 9 quintillion. Examples -------- >>> sf = turicreate.SFrame({'a': [1, None, None], 'b': ['a', 'b', None]}) >>> sf.add_row_number() +----+------+------+ | id | a | b | +----+------+------+ | 0 | 1 | a | | 1 | None | b | | 2 | None | None | +----+------+------+ [3 rows x 3 columns]
[ "Returns", "an", "SFrame", "with", "a", "new", "column", "that", "numbers", "each", "row", "sequentially", ".", "By", "default", "the", "count", "starts", "at", "0", "but", "this", "can", "be", "changed", "to", "a", "positive", "or", "negative", "number", ".", "The", "new", "column", "will", "be", "named", "with", "the", "given", "column", "name", ".", "An", "error", "will", "be", "raised", "if", "the", "given", "column", "name", "already", "exists", "in", "the", "SFrame", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L5730-L5801
29,058
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool.AddSerializedFile
def AddSerializedFile(self, serialized_file_desc_proto): """Adds the FileDescriptorProto and its types to this pool. Args: serialized_file_desc_proto: A bytes string, serialization of the FileDescriptorProto to add. """ # pylint: disable=g-import-not-at-top from google.protobuf import descriptor_pb2 file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString( serialized_file_desc_proto) self.Add(file_desc_proto)
python
def AddSerializedFile(self, serialized_file_desc_proto): """Adds the FileDescriptorProto and its types to this pool. Args: serialized_file_desc_proto: A bytes string, serialization of the FileDescriptorProto to add. """ # pylint: disable=g-import-not-at-top from google.protobuf import descriptor_pb2 file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString( serialized_file_desc_proto) self.Add(file_desc_proto)
[ "def", "AddSerializedFile", "(", "self", ",", "serialized_file_desc_proto", ")", ":", "# pylint: disable=g-import-not-at-top", "from", "google", ".", "protobuf", "import", "descriptor_pb2", "file_desc_proto", "=", "descriptor_pb2", ".", "FileDescriptorProto", ".", "FromString", "(", "serialized_file_desc_proto", ")", "self", ".", "Add", "(", "file_desc_proto", ")" ]
Adds the FileDescriptorProto and its types to this pool. Args: serialized_file_desc_proto: A bytes string, serialization of the FileDescriptorProto to add.
[ "Adds", "the", "FileDescriptorProto", "and", "its", "types", "to", "this", "pool", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L148-L160
29,059
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool.AddDescriptor
def AddDescriptor(self, desc): """Adds a Descriptor to the pool, non-recursively. If the Descriptor contains nested messages or enums, the caller must explicitly register them. This method also registers the FileDescriptor associated with the message. Args: desc: A Descriptor. """ if not isinstance(desc, descriptor.Descriptor): raise TypeError('Expected instance of descriptor.Descriptor.') self._descriptors[desc.full_name] = desc self._AddFileDescriptor(desc.file)
python
def AddDescriptor(self, desc): """Adds a Descriptor to the pool, non-recursively. If the Descriptor contains nested messages or enums, the caller must explicitly register them. This method also registers the FileDescriptor associated with the message. Args: desc: A Descriptor. """ if not isinstance(desc, descriptor.Descriptor): raise TypeError('Expected instance of descriptor.Descriptor.') self._descriptors[desc.full_name] = desc self._AddFileDescriptor(desc.file)
[ "def", "AddDescriptor", "(", "self", ",", "desc", ")", ":", "if", "not", "isinstance", "(", "desc", ",", "descriptor", ".", "Descriptor", ")", ":", "raise", "TypeError", "(", "'Expected instance of descriptor.Descriptor.'", ")", "self", ".", "_descriptors", "[", "desc", ".", "full_name", "]", "=", "desc", "self", ".", "_AddFileDescriptor", "(", "desc", ".", "file", ")" ]
Adds a Descriptor to the pool, non-recursively. If the Descriptor contains nested messages or enums, the caller must explicitly register them. This method also registers the FileDescriptor associated with the message. Args: desc: A Descriptor.
[ "Adds", "a", "Descriptor", "to", "the", "pool", "non", "-", "recursively", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L162-L176
29,060
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool.AddServiceDescriptor
def AddServiceDescriptor(self, service_desc): """Adds a ServiceDescriptor to the pool. Args: service_desc: A ServiceDescriptor. """ if not isinstance(service_desc, descriptor.ServiceDescriptor): raise TypeError('Expected instance of descriptor.ServiceDescriptor.') self._service_descriptors[service_desc.full_name] = service_desc
python
def AddServiceDescriptor(self, service_desc): """Adds a ServiceDescriptor to the pool. Args: service_desc: A ServiceDescriptor. """ if not isinstance(service_desc, descriptor.ServiceDescriptor): raise TypeError('Expected instance of descriptor.ServiceDescriptor.') self._service_descriptors[service_desc.full_name] = service_desc
[ "def", "AddServiceDescriptor", "(", "self", ",", "service_desc", ")", ":", "if", "not", "isinstance", "(", "service_desc", ",", "descriptor", ".", "ServiceDescriptor", ")", ":", "raise", "TypeError", "(", "'Expected instance of descriptor.ServiceDescriptor.'", ")", "self", ".", "_service_descriptors", "[", "service_desc", ".", "full_name", "]", "=", "service_desc" ]
Adds a ServiceDescriptor to the pool. Args: service_desc: A ServiceDescriptor.
[ "Adds", "a", "ServiceDescriptor", "to", "the", "pool", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L193-L203
29,061
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool.AddExtensionDescriptor
def AddExtensionDescriptor(self, extension): """Adds a FieldDescriptor describing an extension to the pool. Args: extension: A FieldDescriptor. Raises: AssertionError: when another extension with the same number extends the same message. TypeError: when the specified extension is not a descriptor.FieldDescriptor. """ if not (isinstance(extension, descriptor.FieldDescriptor) and extension.is_extension): raise TypeError('Expected an extension descriptor.') if extension.extension_scope is None: self._toplevel_extensions[extension.full_name] = extension try: existing_desc = self._extensions_by_number[ extension.containing_type][extension.number] except KeyError: pass else: if extension is not existing_desc: raise AssertionError( 'Extensions "%s" and "%s" both try to extend message type "%s" ' 'with field number %d.' % (extension.full_name, existing_desc.full_name, extension.containing_type.full_name, extension.number)) self._extensions_by_number[extension.containing_type][ extension.number] = extension self._extensions_by_name[extension.containing_type][ extension.full_name] = extension # Also register MessageSet extensions with the type name. if _IsMessageSetExtension(extension): self._extensions_by_name[extension.containing_type][ extension.message_type.full_name] = extension
python
def AddExtensionDescriptor(self, extension): """Adds a FieldDescriptor describing an extension to the pool. Args: extension: A FieldDescriptor. Raises: AssertionError: when another extension with the same number extends the same message. TypeError: when the specified extension is not a descriptor.FieldDescriptor. """ if not (isinstance(extension, descriptor.FieldDescriptor) and extension.is_extension): raise TypeError('Expected an extension descriptor.') if extension.extension_scope is None: self._toplevel_extensions[extension.full_name] = extension try: existing_desc = self._extensions_by_number[ extension.containing_type][extension.number] except KeyError: pass else: if extension is not existing_desc: raise AssertionError( 'Extensions "%s" and "%s" both try to extend message type "%s" ' 'with field number %d.' % (extension.full_name, existing_desc.full_name, extension.containing_type.full_name, extension.number)) self._extensions_by_number[extension.containing_type][ extension.number] = extension self._extensions_by_name[extension.containing_type][ extension.full_name] = extension # Also register MessageSet extensions with the type name. if _IsMessageSetExtension(extension): self._extensions_by_name[extension.containing_type][ extension.message_type.full_name] = extension
[ "def", "AddExtensionDescriptor", "(", "self", ",", "extension", ")", ":", "if", "not", "(", "isinstance", "(", "extension", ",", "descriptor", ".", "FieldDescriptor", ")", "and", "extension", ".", "is_extension", ")", ":", "raise", "TypeError", "(", "'Expected an extension descriptor.'", ")", "if", "extension", ".", "extension_scope", "is", "None", ":", "self", ".", "_toplevel_extensions", "[", "extension", ".", "full_name", "]", "=", "extension", "try", ":", "existing_desc", "=", "self", ".", "_extensions_by_number", "[", "extension", ".", "containing_type", "]", "[", "extension", ".", "number", "]", "except", "KeyError", ":", "pass", "else", ":", "if", "extension", "is", "not", "existing_desc", ":", "raise", "AssertionError", "(", "'Extensions \"%s\" and \"%s\" both try to extend message type \"%s\" '", "'with field number %d.'", "%", "(", "extension", ".", "full_name", ",", "existing_desc", ".", "full_name", ",", "extension", ".", "containing_type", ".", "full_name", ",", "extension", ".", "number", ")", ")", "self", ".", "_extensions_by_number", "[", "extension", ".", "containing_type", "]", "[", "extension", ".", "number", "]", "=", "extension", "self", ".", "_extensions_by_name", "[", "extension", ".", "containing_type", "]", "[", "extension", ".", "full_name", "]", "=", "extension", "# Also register MessageSet extensions with the type name.", "if", "_IsMessageSetExtension", "(", "extension", ")", ":", "self", ".", "_extensions_by_name", "[", "extension", ".", "containing_type", "]", "[", "extension", ".", "message_type", ".", "full_name", "]", "=", "extension" ]
Adds a FieldDescriptor describing an extension to the pool. Args: extension: A FieldDescriptor. Raises: AssertionError: when another extension with the same number extends the same message. TypeError: when the specified extension is not a descriptor.FieldDescriptor.
[ "Adds", "a", "FieldDescriptor", "describing", "an", "extension", "to", "the", "pool", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L205-L245
29,062
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool.FindFileByName
def FindFileByName(self, file_name): """Gets a FileDescriptor by file name. Args: file_name: The path to the file to get a descriptor for. Returns: A FileDescriptor for the named file. Raises: KeyError: if the file cannot be found in the pool. """ try: return self._file_descriptors[file_name] except KeyError: pass try: file_proto = self._internal_db.FindFileByName(file_name) except KeyError as error: if self._descriptor_db: file_proto = self._descriptor_db.FindFileByName(file_name) else: raise error if not file_proto: raise KeyError('Cannot find a file named %s' % file_name) return self._ConvertFileProtoToFileDescriptor(file_proto)
python
def FindFileByName(self, file_name): """Gets a FileDescriptor by file name. Args: file_name: The path to the file to get a descriptor for. Returns: A FileDescriptor for the named file. Raises: KeyError: if the file cannot be found in the pool. """ try: return self._file_descriptors[file_name] except KeyError: pass try: file_proto = self._internal_db.FindFileByName(file_name) except KeyError as error: if self._descriptor_db: file_proto = self._descriptor_db.FindFileByName(file_name) else: raise error if not file_proto: raise KeyError('Cannot find a file named %s' % file_name) return self._ConvertFileProtoToFileDescriptor(file_proto)
[ "def", "FindFileByName", "(", "self", ",", "file_name", ")", ":", "try", ":", "return", "self", ".", "_file_descriptors", "[", "file_name", "]", "except", "KeyError", ":", "pass", "try", ":", "file_proto", "=", "self", ".", "_internal_db", ".", "FindFileByName", "(", "file_name", ")", "except", "KeyError", "as", "error", ":", "if", "self", ".", "_descriptor_db", ":", "file_proto", "=", "self", ".", "_descriptor_db", ".", "FindFileByName", "(", "file_name", ")", "else", ":", "raise", "error", "if", "not", "file_proto", ":", "raise", "KeyError", "(", "'Cannot find a file named %s'", "%", "file_name", ")", "return", "self", ".", "_ConvertFileProtoToFileDescriptor", "(", "file_proto", ")" ]
Gets a FileDescriptor by file name. Args: file_name: The path to the file to get a descriptor for. Returns: A FileDescriptor for the named file. Raises: KeyError: if the file cannot be found in the pool.
[ "Gets", "a", "FileDescriptor", "by", "file", "name", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L278-L305
29,063
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool.FindFileContainingSymbol
def FindFileContainingSymbol(self, symbol): """Gets the FileDescriptor for the file containing the specified symbol. Args: symbol: The name of the symbol to search for. Returns: A FileDescriptor that contains the specified symbol. Raises: KeyError: if the file cannot be found in the pool. """ symbol = _NormalizeFullyQualifiedName(symbol) try: return self._descriptors[symbol].file except KeyError: pass try: return self._enum_descriptors[symbol].file except KeyError: pass try: return self._FindFileContainingSymbolInDb(symbol) except KeyError: pass try: return self._file_desc_by_toplevel_extension[symbol] except KeyError: pass # Try nested extensions inside a message. message_name, _, extension_name = symbol.rpartition('.') try: message = self.FindMessageTypeByName(message_name) assert message.extensions_by_name[extension_name] return message.file except KeyError: raise KeyError('Cannot find a file containing %s' % symbol)
python
def FindFileContainingSymbol(self, symbol): """Gets the FileDescriptor for the file containing the specified symbol. Args: symbol: The name of the symbol to search for. Returns: A FileDescriptor that contains the specified symbol. Raises: KeyError: if the file cannot be found in the pool. """ symbol = _NormalizeFullyQualifiedName(symbol) try: return self._descriptors[symbol].file except KeyError: pass try: return self._enum_descriptors[symbol].file except KeyError: pass try: return self._FindFileContainingSymbolInDb(symbol) except KeyError: pass try: return self._file_desc_by_toplevel_extension[symbol] except KeyError: pass # Try nested extensions inside a message. message_name, _, extension_name = symbol.rpartition('.') try: message = self.FindMessageTypeByName(message_name) assert message.extensions_by_name[extension_name] return message.file except KeyError: raise KeyError('Cannot find a file containing %s' % symbol)
[ "def", "FindFileContainingSymbol", "(", "self", ",", "symbol", ")", ":", "symbol", "=", "_NormalizeFullyQualifiedName", "(", "symbol", ")", "try", ":", "return", "self", ".", "_descriptors", "[", "symbol", "]", ".", "file", "except", "KeyError", ":", "pass", "try", ":", "return", "self", ".", "_enum_descriptors", "[", "symbol", "]", ".", "file", "except", "KeyError", ":", "pass", "try", ":", "return", "self", ".", "_FindFileContainingSymbolInDb", "(", "symbol", ")", "except", "KeyError", ":", "pass", "try", ":", "return", "self", ".", "_file_desc_by_toplevel_extension", "[", "symbol", "]", "except", "KeyError", ":", "pass", "# Try nested extensions inside a message.", "message_name", ",", "_", ",", "extension_name", "=", "symbol", ".", "rpartition", "(", "'.'", ")", "try", ":", "message", "=", "self", ".", "FindMessageTypeByName", "(", "message_name", ")", "assert", "message", ".", "extensions_by_name", "[", "extension_name", "]", "return", "message", ".", "file", "except", "KeyError", ":", "raise", "KeyError", "(", "'Cannot find a file containing %s'", "%", "symbol", ")" ]
Gets the FileDescriptor for the file containing the specified symbol. Args: symbol: The name of the symbol to search for. Returns: A FileDescriptor that contains the specified symbol. Raises: KeyError: if the file cannot be found in the pool.
[ "Gets", "the", "FileDescriptor", "for", "the", "file", "containing", "the", "specified", "symbol", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L307-L349
29,064
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool.FindMessageTypeByName
def FindMessageTypeByName(self, full_name): """Loads the named descriptor from the pool. Args: full_name: The full name of the descriptor to load. Returns: The descriptor for the named type. Raises: KeyError: if the message cannot be found in the pool. """ full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._descriptors: self._FindFileContainingSymbolInDb(full_name) return self._descriptors[full_name]
python
def FindMessageTypeByName(self, full_name): """Loads the named descriptor from the pool. Args: full_name: The full name of the descriptor to load. Returns: The descriptor for the named type. Raises: KeyError: if the message cannot be found in the pool. """ full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._descriptors: self._FindFileContainingSymbolInDb(full_name) return self._descriptors[full_name]
[ "def", "FindMessageTypeByName", "(", "self", ",", "full_name", ")", ":", "full_name", "=", "_NormalizeFullyQualifiedName", "(", "full_name", ")", "if", "full_name", "not", "in", "self", ".", "_descriptors", ":", "self", ".", "_FindFileContainingSymbolInDb", "(", "full_name", ")", "return", "self", ".", "_descriptors", "[", "full_name", "]" ]
Loads the named descriptor from the pool. Args: full_name: The full name of the descriptor to load. Returns: The descriptor for the named type. Raises: KeyError: if the message cannot be found in the pool.
[ "Loads", "the", "named", "descriptor", "from", "the", "pool", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L351-L367
29,065
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool.FindEnumTypeByName
def FindEnumTypeByName(self, full_name): """Loads the named enum descriptor from the pool. Args: full_name: The full name of the enum descriptor to load. Returns: The enum descriptor for the named type. Raises: KeyError: if the enum cannot be found in the pool. """ full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._enum_descriptors: self._FindFileContainingSymbolInDb(full_name) return self._enum_descriptors[full_name]
python
def FindEnumTypeByName(self, full_name): """Loads the named enum descriptor from the pool. Args: full_name: The full name of the enum descriptor to load. Returns: The enum descriptor for the named type. Raises: KeyError: if the enum cannot be found in the pool. """ full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._enum_descriptors: self._FindFileContainingSymbolInDb(full_name) return self._enum_descriptors[full_name]
[ "def", "FindEnumTypeByName", "(", "self", ",", "full_name", ")", ":", "full_name", "=", "_NormalizeFullyQualifiedName", "(", "full_name", ")", "if", "full_name", "not", "in", "self", ".", "_enum_descriptors", ":", "self", ".", "_FindFileContainingSymbolInDb", "(", "full_name", ")", "return", "self", ".", "_enum_descriptors", "[", "full_name", "]" ]
Loads the named enum descriptor from the pool. Args: full_name: The full name of the enum descriptor to load. Returns: The enum descriptor for the named type. Raises: KeyError: if the enum cannot be found in the pool.
[ "Loads", "the", "named", "enum", "descriptor", "from", "the", "pool", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L369-L385
29,066
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool.FindFieldByName
def FindFieldByName(self, full_name): """Loads the named field descriptor from the pool. Args: full_name: The full name of the field descriptor to load. Returns: The field descriptor for the named field. Raises: KeyError: if the field cannot be found in the pool. """ full_name = _NormalizeFullyQualifiedName(full_name) message_name, _, field_name = full_name.rpartition('.') message_descriptor = self.FindMessageTypeByName(message_name) return message_descriptor.fields_by_name[field_name]
python
def FindFieldByName(self, full_name): """Loads the named field descriptor from the pool. Args: full_name: The full name of the field descriptor to load. Returns: The field descriptor for the named field. Raises: KeyError: if the field cannot be found in the pool. """ full_name = _NormalizeFullyQualifiedName(full_name) message_name, _, field_name = full_name.rpartition('.') message_descriptor = self.FindMessageTypeByName(message_name) return message_descriptor.fields_by_name[field_name]
[ "def", "FindFieldByName", "(", "self", ",", "full_name", ")", ":", "full_name", "=", "_NormalizeFullyQualifiedName", "(", "full_name", ")", "message_name", ",", "_", ",", "field_name", "=", "full_name", ".", "rpartition", "(", "'.'", ")", "message_descriptor", "=", "self", ".", "FindMessageTypeByName", "(", "message_name", ")", "return", "message_descriptor", ".", "fields_by_name", "[", "field_name", "]" ]
Loads the named field descriptor from the pool. Args: full_name: The full name of the field descriptor to load. Returns: The field descriptor for the named field. Raises: KeyError: if the field cannot be found in the pool.
[ "Loads", "the", "named", "field", "descriptor", "from", "the", "pool", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L387-L402
29,067
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool.FindServiceByName
def FindServiceByName(self, full_name): """Loads the named service descriptor from the pool. Args: full_name: The full name of the service descriptor to load. Returns: The service descriptor for the named service. Raises: KeyError: if the service cannot be found in the pool. """ full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._service_descriptors: self._FindFileContainingSymbolInDb(full_name) return self._service_descriptors[full_name]
python
def FindServiceByName(self, full_name): """Loads the named service descriptor from the pool. Args: full_name: The full name of the service descriptor to load. Returns: The service descriptor for the named service. Raises: KeyError: if the service cannot be found in the pool. """ full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._service_descriptors: self._FindFileContainingSymbolInDb(full_name) return self._service_descriptors[full_name]
[ "def", "FindServiceByName", "(", "self", ",", "full_name", ")", ":", "full_name", "=", "_NormalizeFullyQualifiedName", "(", "full_name", ")", "if", "full_name", "not", "in", "self", ".", "_service_descriptors", ":", "self", ".", "_FindFileContainingSymbolInDb", "(", "full_name", ")", "return", "self", ".", "_service_descriptors", "[", "full_name", "]" ]
Loads the named service descriptor from the pool. Args: full_name: The full name of the service descriptor to load. Returns: The service descriptor for the named service. Raises: KeyError: if the service cannot be found in the pool.
[ "Loads", "the", "named", "service", "descriptor", "from", "the", "pool", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L467-L482
29,068
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool._FindFileContainingSymbolInDb
def _FindFileContainingSymbolInDb(self, symbol): """Finds the file in descriptor DB containing the specified symbol. Args: symbol: The name of the symbol to search for. Returns: A FileDescriptor that contains the specified symbol. Raises: KeyError: if the file cannot be found in the descriptor database. """ try: file_proto = self._internal_db.FindFileContainingSymbol(symbol) except KeyError as error: if self._descriptor_db: file_proto = self._descriptor_db.FindFileContainingSymbol(symbol) else: raise error if not file_proto: raise KeyError('Cannot find a file containing %s' % symbol) return self._ConvertFileProtoToFileDescriptor(file_proto)
python
def _FindFileContainingSymbolInDb(self, symbol): """Finds the file in descriptor DB containing the specified symbol. Args: symbol: The name of the symbol to search for. Returns: A FileDescriptor that contains the specified symbol. Raises: KeyError: if the file cannot be found in the descriptor database. """ try: file_proto = self._internal_db.FindFileContainingSymbol(symbol) except KeyError as error: if self._descriptor_db: file_proto = self._descriptor_db.FindFileContainingSymbol(symbol) else: raise error if not file_proto: raise KeyError('Cannot find a file containing %s' % symbol) return self._ConvertFileProtoToFileDescriptor(file_proto)
[ "def", "_FindFileContainingSymbolInDb", "(", "self", ",", "symbol", ")", ":", "try", ":", "file_proto", "=", "self", ".", "_internal_db", ".", "FindFileContainingSymbol", "(", "symbol", ")", "except", "KeyError", "as", "error", ":", "if", "self", ".", "_descriptor_db", ":", "file_proto", "=", "self", ".", "_descriptor_db", ".", "FindFileContainingSymbol", "(", "symbol", ")", "else", ":", "raise", "error", "if", "not", "file_proto", ":", "raise", "KeyError", "(", "'Cannot find a file containing %s'", "%", "symbol", ")", "return", "self", ".", "_ConvertFileProtoToFileDescriptor", "(", "file_proto", ")" ]
Finds the file in descriptor DB containing the specified symbol. Args: symbol: The name of the symbol to search for. Returns: A FileDescriptor that contains the specified symbol. Raises: KeyError: if the file cannot be found in the descriptor database.
[ "Finds", "the", "file", "in", "descriptor", "DB", "containing", "the", "specified", "symbol", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L484-L505
29,069
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool._ConvertFileProtoToFileDescriptor
def _ConvertFileProtoToFileDescriptor(self, file_proto): """Creates a FileDescriptor from a proto or returns a cached copy. This method also has the side effect of loading all the symbols found in the file into the appropriate dictionaries in the pool. Args: file_proto: The proto to convert. Returns: A FileDescriptor matching the passed in proto. """ if file_proto.name not in self._file_descriptors: built_deps = list(self._GetDeps(file_proto.dependency)) direct_deps = [self.FindFileByName(n) for n in file_proto.dependency] public_deps = [direct_deps[i] for i in file_proto.public_dependency] file_descriptor = descriptor.FileDescriptor( pool=self, name=file_proto.name, package=file_proto.package, syntax=file_proto.syntax, options=_OptionsOrNone(file_proto), serialized_pb=file_proto.SerializeToString(), dependencies=direct_deps, public_dependencies=public_deps) scope = {} # This loop extracts all the message and enum types from all the # dependencies of the file_proto. This is necessary to create the # scope of available message types when defining the passed in # file proto. for dependency in built_deps: scope.update(self._ExtractSymbols( dependency.message_types_by_name.values())) scope.update((_PrefixWithDot(enum.full_name), enum) for enum in dependency.enum_types_by_name.values()) for message_type in file_proto.message_type: message_desc = self._ConvertMessageDescriptor( message_type, file_proto.package, file_descriptor, scope, file_proto.syntax) file_descriptor.message_types_by_name[message_desc.name] = ( message_desc) for enum_type in file_proto.enum_type: file_descriptor.enum_types_by_name[enum_type.name] = ( self._ConvertEnumDescriptor(enum_type, file_proto.package, file_descriptor, None, scope)) for index, extension_proto in enumerate(file_proto.extension): extension_desc = self._MakeFieldDescriptor( extension_proto, file_proto.package, index, is_extension=True) extension_desc.containing_type = self._GetTypeFromScope( file_descriptor.package, extension_proto.extendee, scope) self._SetFieldType(extension_proto, extension_desc, file_descriptor.package, scope) file_descriptor.extensions_by_name[extension_desc.name] = ( extension_desc) for desc_proto in file_proto.message_type: self._SetAllFieldTypes(file_proto.package, desc_proto, scope) if file_proto.package: desc_proto_prefix = _PrefixWithDot(file_proto.package) else: desc_proto_prefix = '' for desc_proto in file_proto.message_type: desc = self._GetTypeFromScope( desc_proto_prefix, desc_proto.name, scope) file_descriptor.message_types_by_name[desc_proto.name] = desc for index, service_proto in enumerate(file_proto.service): file_descriptor.services_by_name[service_proto.name] = ( self._MakeServiceDescriptor(service_proto, index, scope, file_proto.package, file_descriptor)) self.Add(file_proto) self._file_descriptors[file_proto.name] = file_descriptor return self._file_descriptors[file_proto.name]
python
def _ConvertFileProtoToFileDescriptor(self, file_proto): """Creates a FileDescriptor from a proto or returns a cached copy. This method also has the side effect of loading all the symbols found in the file into the appropriate dictionaries in the pool. Args: file_proto: The proto to convert. Returns: A FileDescriptor matching the passed in proto. """ if file_proto.name not in self._file_descriptors: built_deps = list(self._GetDeps(file_proto.dependency)) direct_deps = [self.FindFileByName(n) for n in file_proto.dependency] public_deps = [direct_deps[i] for i in file_proto.public_dependency] file_descriptor = descriptor.FileDescriptor( pool=self, name=file_proto.name, package=file_proto.package, syntax=file_proto.syntax, options=_OptionsOrNone(file_proto), serialized_pb=file_proto.SerializeToString(), dependencies=direct_deps, public_dependencies=public_deps) scope = {} # This loop extracts all the message and enum types from all the # dependencies of the file_proto. This is necessary to create the # scope of available message types when defining the passed in # file proto. for dependency in built_deps: scope.update(self._ExtractSymbols( dependency.message_types_by_name.values())) scope.update((_PrefixWithDot(enum.full_name), enum) for enum in dependency.enum_types_by_name.values()) for message_type in file_proto.message_type: message_desc = self._ConvertMessageDescriptor( message_type, file_proto.package, file_descriptor, scope, file_proto.syntax) file_descriptor.message_types_by_name[message_desc.name] = ( message_desc) for enum_type in file_proto.enum_type: file_descriptor.enum_types_by_name[enum_type.name] = ( self._ConvertEnumDescriptor(enum_type, file_proto.package, file_descriptor, None, scope)) for index, extension_proto in enumerate(file_proto.extension): extension_desc = self._MakeFieldDescriptor( extension_proto, file_proto.package, index, is_extension=True) extension_desc.containing_type = self._GetTypeFromScope( file_descriptor.package, extension_proto.extendee, scope) self._SetFieldType(extension_proto, extension_desc, file_descriptor.package, scope) file_descriptor.extensions_by_name[extension_desc.name] = ( extension_desc) for desc_proto in file_proto.message_type: self._SetAllFieldTypes(file_proto.package, desc_proto, scope) if file_proto.package: desc_proto_prefix = _PrefixWithDot(file_proto.package) else: desc_proto_prefix = '' for desc_proto in file_proto.message_type: desc = self._GetTypeFromScope( desc_proto_prefix, desc_proto.name, scope) file_descriptor.message_types_by_name[desc_proto.name] = desc for index, service_proto in enumerate(file_proto.service): file_descriptor.services_by_name[service_proto.name] = ( self._MakeServiceDescriptor(service_proto, index, scope, file_proto.package, file_descriptor)) self.Add(file_proto) self._file_descriptors[file_proto.name] = file_descriptor return self._file_descriptors[file_proto.name]
[ "def", "_ConvertFileProtoToFileDescriptor", "(", "self", ",", "file_proto", ")", ":", "if", "file_proto", ".", "name", "not", "in", "self", ".", "_file_descriptors", ":", "built_deps", "=", "list", "(", "self", ".", "_GetDeps", "(", "file_proto", ".", "dependency", ")", ")", "direct_deps", "=", "[", "self", ".", "FindFileByName", "(", "n", ")", "for", "n", "in", "file_proto", ".", "dependency", "]", "public_deps", "=", "[", "direct_deps", "[", "i", "]", "for", "i", "in", "file_proto", ".", "public_dependency", "]", "file_descriptor", "=", "descriptor", ".", "FileDescriptor", "(", "pool", "=", "self", ",", "name", "=", "file_proto", ".", "name", ",", "package", "=", "file_proto", ".", "package", ",", "syntax", "=", "file_proto", ".", "syntax", ",", "options", "=", "_OptionsOrNone", "(", "file_proto", ")", ",", "serialized_pb", "=", "file_proto", ".", "SerializeToString", "(", ")", ",", "dependencies", "=", "direct_deps", ",", "public_dependencies", "=", "public_deps", ")", "scope", "=", "{", "}", "# This loop extracts all the message and enum types from all the", "# dependencies of the file_proto. This is necessary to create the", "# scope of available message types when defining the passed in", "# file proto.", "for", "dependency", "in", "built_deps", ":", "scope", ".", "update", "(", "self", ".", "_ExtractSymbols", "(", "dependency", ".", "message_types_by_name", ".", "values", "(", ")", ")", ")", "scope", ".", "update", "(", "(", "_PrefixWithDot", "(", "enum", ".", "full_name", ")", ",", "enum", ")", "for", "enum", "in", "dependency", ".", "enum_types_by_name", ".", "values", "(", ")", ")", "for", "message_type", "in", "file_proto", ".", "message_type", ":", "message_desc", "=", "self", ".", "_ConvertMessageDescriptor", "(", "message_type", ",", "file_proto", ".", "package", ",", "file_descriptor", ",", "scope", ",", "file_proto", ".", "syntax", ")", "file_descriptor", ".", "message_types_by_name", "[", "message_desc", ".", "name", "]", "=", "(", "message_desc", ")", "for", "enum_type", "in", "file_proto", ".", "enum_type", ":", "file_descriptor", ".", "enum_types_by_name", "[", "enum_type", ".", "name", "]", "=", "(", "self", ".", "_ConvertEnumDescriptor", "(", "enum_type", ",", "file_proto", ".", "package", ",", "file_descriptor", ",", "None", ",", "scope", ")", ")", "for", "index", ",", "extension_proto", "in", "enumerate", "(", "file_proto", ".", "extension", ")", ":", "extension_desc", "=", "self", ".", "_MakeFieldDescriptor", "(", "extension_proto", ",", "file_proto", ".", "package", ",", "index", ",", "is_extension", "=", "True", ")", "extension_desc", ".", "containing_type", "=", "self", ".", "_GetTypeFromScope", "(", "file_descriptor", ".", "package", ",", "extension_proto", ".", "extendee", ",", "scope", ")", "self", ".", "_SetFieldType", "(", "extension_proto", ",", "extension_desc", ",", "file_descriptor", ".", "package", ",", "scope", ")", "file_descriptor", ".", "extensions_by_name", "[", "extension_desc", ".", "name", "]", "=", "(", "extension_desc", ")", "for", "desc_proto", "in", "file_proto", ".", "message_type", ":", "self", ".", "_SetAllFieldTypes", "(", "file_proto", ".", "package", ",", "desc_proto", ",", "scope", ")", "if", "file_proto", ".", "package", ":", "desc_proto_prefix", "=", "_PrefixWithDot", "(", "file_proto", ".", "package", ")", "else", ":", "desc_proto_prefix", "=", "''", "for", "desc_proto", "in", "file_proto", ".", "message_type", ":", "desc", "=", "self", ".", "_GetTypeFromScope", "(", "desc_proto_prefix", ",", "desc_proto", ".", "name", ",", "scope", ")", "file_descriptor", ".", "message_types_by_name", "[", "desc_proto", ".", "name", "]", "=", "desc", "for", "index", ",", "service_proto", "in", "enumerate", "(", "file_proto", ".", "service", ")", ":", "file_descriptor", ".", "services_by_name", "[", "service_proto", ".", "name", "]", "=", "(", "self", ".", "_MakeServiceDescriptor", "(", "service_proto", ",", "index", ",", "scope", ",", "file_proto", ".", "package", ",", "file_descriptor", ")", ")", "self", ".", "Add", "(", "file_proto", ")", "self", ".", "_file_descriptors", "[", "file_proto", ".", "name", "]", "=", "file_descriptor", "return", "self", ".", "_file_descriptors", "[", "file_proto", ".", "name", "]" ]
Creates a FileDescriptor from a proto or returns a cached copy. This method also has the side effect of loading all the symbols found in the file into the appropriate dictionaries in the pool. Args: file_proto: The proto to convert. Returns: A FileDescriptor matching the passed in proto.
[ "Creates", "a", "FileDescriptor", "from", "a", "proto", "or", "returns", "a", "cached", "copy", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L507-L589
29,070
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool._ConvertMessageDescriptor
def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None, scope=None, syntax=None): """Adds the proto to the pool in the specified package. Args: desc_proto: The descriptor_pb2.DescriptorProto protobuf message. package: The package the proto should be located in. file_desc: The file containing this message. scope: Dict mapping short and full symbols to message and enum types. syntax: string indicating syntax of the file ("proto2" or "proto3") Returns: The added descriptor. """ if package: desc_name = '.'.join((package, desc_proto.name)) else: desc_name = desc_proto.name if file_desc is None: file_name = None else: file_name = file_desc.name if scope is None: scope = {} nested = [ self._ConvertMessageDescriptor( nested, desc_name, file_desc, scope, syntax) for nested in desc_proto.nested_type] enums = [ self._ConvertEnumDescriptor(enum, desc_name, file_desc, None, scope) for enum in desc_proto.enum_type] fields = [self._MakeFieldDescriptor(field, desc_name, index) for index, field in enumerate(desc_proto.field)] extensions = [ self._MakeFieldDescriptor(extension, desc_name, index, is_extension=True) for index, extension in enumerate(desc_proto.extension)] oneofs = [ descriptor.OneofDescriptor(desc.name, '.'.join((desc_name, desc.name)), index, None, [], desc.options) for index, desc in enumerate(desc_proto.oneof_decl)] extension_ranges = [(r.start, r.end) for r in desc_proto.extension_range] if extension_ranges: is_extendable = True else: is_extendable = False desc = descriptor.Descriptor( name=desc_proto.name, full_name=desc_name, filename=file_name, containing_type=None, fields=fields, oneofs=oneofs, nested_types=nested, enum_types=enums, extensions=extensions, options=_OptionsOrNone(desc_proto), is_extendable=is_extendable, extension_ranges=extension_ranges, file=file_desc, serialized_start=None, serialized_end=None, syntax=syntax) for nested in desc.nested_types: nested.containing_type = desc for enum in desc.enum_types: enum.containing_type = desc for field_index, field_desc in enumerate(desc_proto.field): if field_desc.HasField('oneof_index'): oneof_index = field_desc.oneof_index oneofs[oneof_index].fields.append(fields[field_index]) fields[field_index].containing_oneof = oneofs[oneof_index] scope[_PrefixWithDot(desc_name)] = desc self._descriptors[desc_name] = desc return desc
python
def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None, scope=None, syntax=None): """Adds the proto to the pool in the specified package. Args: desc_proto: The descriptor_pb2.DescriptorProto protobuf message. package: The package the proto should be located in. file_desc: The file containing this message. scope: Dict mapping short and full symbols to message and enum types. syntax: string indicating syntax of the file ("proto2" or "proto3") Returns: The added descriptor. """ if package: desc_name = '.'.join((package, desc_proto.name)) else: desc_name = desc_proto.name if file_desc is None: file_name = None else: file_name = file_desc.name if scope is None: scope = {} nested = [ self._ConvertMessageDescriptor( nested, desc_name, file_desc, scope, syntax) for nested in desc_proto.nested_type] enums = [ self._ConvertEnumDescriptor(enum, desc_name, file_desc, None, scope) for enum in desc_proto.enum_type] fields = [self._MakeFieldDescriptor(field, desc_name, index) for index, field in enumerate(desc_proto.field)] extensions = [ self._MakeFieldDescriptor(extension, desc_name, index, is_extension=True) for index, extension in enumerate(desc_proto.extension)] oneofs = [ descriptor.OneofDescriptor(desc.name, '.'.join((desc_name, desc.name)), index, None, [], desc.options) for index, desc in enumerate(desc_proto.oneof_decl)] extension_ranges = [(r.start, r.end) for r in desc_proto.extension_range] if extension_ranges: is_extendable = True else: is_extendable = False desc = descriptor.Descriptor( name=desc_proto.name, full_name=desc_name, filename=file_name, containing_type=None, fields=fields, oneofs=oneofs, nested_types=nested, enum_types=enums, extensions=extensions, options=_OptionsOrNone(desc_proto), is_extendable=is_extendable, extension_ranges=extension_ranges, file=file_desc, serialized_start=None, serialized_end=None, syntax=syntax) for nested in desc.nested_types: nested.containing_type = desc for enum in desc.enum_types: enum.containing_type = desc for field_index, field_desc in enumerate(desc_proto.field): if field_desc.HasField('oneof_index'): oneof_index = field_desc.oneof_index oneofs[oneof_index].fields.append(fields[field_index]) fields[field_index].containing_oneof = oneofs[oneof_index] scope[_PrefixWithDot(desc_name)] = desc self._descriptors[desc_name] = desc return desc
[ "def", "_ConvertMessageDescriptor", "(", "self", ",", "desc_proto", ",", "package", "=", "None", ",", "file_desc", "=", "None", ",", "scope", "=", "None", ",", "syntax", "=", "None", ")", ":", "if", "package", ":", "desc_name", "=", "'.'", ".", "join", "(", "(", "package", ",", "desc_proto", ".", "name", ")", ")", "else", ":", "desc_name", "=", "desc_proto", ".", "name", "if", "file_desc", "is", "None", ":", "file_name", "=", "None", "else", ":", "file_name", "=", "file_desc", ".", "name", "if", "scope", "is", "None", ":", "scope", "=", "{", "}", "nested", "=", "[", "self", ".", "_ConvertMessageDescriptor", "(", "nested", ",", "desc_name", ",", "file_desc", ",", "scope", ",", "syntax", ")", "for", "nested", "in", "desc_proto", ".", "nested_type", "]", "enums", "=", "[", "self", ".", "_ConvertEnumDescriptor", "(", "enum", ",", "desc_name", ",", "file_desc", ",", "None", ",", "scope", ")", "for", "enum", "in", "desc_proto", ".", "enum_type", "]", "fields", "=", "[", "self", ".", "_MakeFieldDescriptor", "(", "field", ",", "desc_name", ",", "index", ")", "for", "index", ",", "field", "in", "enumerate", "(", "desc_proto", ".", "field", ")", "]", "extensions", "=", "[", "self", ".", "_MakeFieldDescriptor", "(", "extension", ",", "desc_name", ",", "index", ",", "is_extension", "=", "True", ")", "for", "index", ",", "extension", "in", "enumerate", "(", "desc_proto", ".", "extension", ")", "]", "oneofs", "=", "[", "descriptor", ".", "OneofDescriptor", "(", "desc", ".", "name", ",", "'.'", ".", "join", "(", "(", "desc_name", ",", "desc", ".", "name", ")", ")", ",", "index", ",", "None", ",", "[", "]", ",", "desc", ".", "options", ")", "for", "index", ",", "desc", "in", "enumerate", "(", "desc_proto", ".", "oneof_decl", ")", "]", "extension_ranges", "=", "[", "(", "r", ".", "start", ",", "r", ".", "end", ")", "for", "r", "in", "desc_proto", ".", "extension_range", "]", "if", "extension_ranges", ":", "is_extendable", "=", "True", "else", ":", "is_extendable", "=", "False", "desc", "=", "descriptor", ".", "Descriptor", "(", "name", "=", "desc_proto", ".", "name", ",", "full_name", "=", "desc_name", ",", "filename", "=", "file_name", ",", "containing_type", "=", "None", ",", "fields", "=", "fields", ",", "oneofs", "=", "oneofs", ",", "nested_types", "=", "nested", ",", "enum_types", "=", "enums", ",", "extensions", "=", "extensions", ",", "options", "=", "_OptionsOrNone", "(", "desc_proto", ")", ",", "is_extendable", "=", "is_extendable", ",", "extension_ranges", "=", "extension_ranges", ",", "file", "=", "file_desc", ",", "serialized_start", "=", "None", ",", "serialized_end", "=", "None", ",", "syntax", "=", "syntax", ")", "for", "nested", "in", "desc", ".", "nested_types", ":", "nested", ".", "containing_type", "=", "desc", "for", "enum", "in", "desc", ".", "enum_types", ":", "enum", ".", "containing_type", "=", "desc", "for", "field_index", ",", "field_desc", "in", "enumerate", "(", "desc_proto", ".", "field", ")", ":", "if", "field_desc", ".", "HasField", "(", "'oneof_index'", ")", ":", "oneof_index", "=", "field_desc", ".", "oneof_index", "oneofs", "[", "oneof_index", "]", ".", "fields", ".", "append", "(", "fields", "[", "field_index", "]", ")", "fields", "[", "field_index", "]", ".", "containing_oneof", "=", "oneofs", "[", "oneof_index", "]", "scope", "[", "_PrefixWithDot", "(", "desc_name", ")", "]", "=", "desc", "self", ".", "_descriptors", "[", "desc_name", "]", "=", "desc", "return", "desc" ]
Adds the proto to the pool in the specified package. Args: desc_proto: The descriptor_pb2.DescriptorProto protobuf message. package: The package the proto should be located in. file_desc: The file containing this message. scope: Dict mapping short and full symbols to message and enum types. syntax: string indicating syntax of the file ("proto2" or "proto3") Returns: The added descriptor.
[ "Adds", "the", "proto", "to", "the", "pool", "in", "the", "specified", "package", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L591-L670
29,071
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool._SetAllFieldTypes
def _SetAllFieldTypes(self, package, desc_proto, scope): """Sets all the descriptor's fields's types. This method also sets the containing types on any extensions. Args: package: The current package of desc_proto. desc_proto: The message descriptor to update. scope: Enclosing scope of available types. """ package = _PrefixWithDot(package) main_desc = self._GetTypeFromScope(package, desc_proto.name, scope) if package == '.': nested_package = _PrefixWithDot(desc_proto.name) else: nested_package = '.'.join([package, desc_proto.name]) for field_proto, field_desc in zip(desc_proto.field, main_desc.fields): self._SetFieldType(field_proto, field_desc, nested_package, scope) for extension_proto, extension_desc in ( zip(desc_proto.extension, main_desc.extensions)): extension_desc.containing_type = self._GetTypeFromScope( nested_package, extension_proto.extendee, scope) self._SetFieldType(extension_proto, extension_desc, nested_package, scope) for nested_type in desc_proto.nested_type: self._SetAllFieldTypes(nested_package, nested_type, scope)
python
def _SetAllFieldTypes(self, package, desc_proto, scope): """Sets all the descriptor's fields's types. This method also sets the containing types on any extensions. Args: package: The current package of desc_proto. desc_proto: The message descriptor to update. scope: Enclosing scope of available types. """ package = _PrefixWithDot(package) main_desc = self._GetTypeFromScope(package, desc_proto.name, scope) if package == '.': nested_package = _PrefixWithDot(desc_proto.name) else: nested_package = '.'.join([package, desc_proto.name]) for field_proto, field_desc in zip(desc_proto.field, main_desc.fields): self._SetFieldType(field_proto, field_desc, nested_package, scope) for extension_proto, extension_desc in ( zip(desc_proto.extension, main_desc.extensions)): extension_desc.containing_type = self._GetTypeFromScope( nested_package, extension_proto.extendee, scope) self._SetFieldType(extension_proto, extension_desc, nested_package, scope) for nested_type in desc_proto.nested_type: self._SetAllFieldTypes(nested_package, nested_type, scope)
[ "def", "_SetAllFieldTypes", "(", "self", ",", "package", ",", "desc_proto", ",", "scope", ")", ":", "package", "=", "_PrefixWithDot", "(", "package", ")", "main_desc", "=", "self", ".", "_GetTypeFromScope", "(", "package", ",", "desc_proto", ".", "name", ",", "scope", ")", "if", "package", "==", "'.'", ":", "nested_package", "=", "_PrefixWithDot", "(", "desc_proto", ".", "name", ")", "else", ":", "nested_package", "=", "'.'", ".", "join", "(", "[", "package", ",", "desc_proto", ".", "name", "]", ")", "for", "field_proto", ",", "field_desc", "in", "zip", "(", "desc_proto", ".", "field", ",", "main_desc", ".", "fields", ")", ":", "self", ".", "_SetFieldType", "(", "field_proto", ",", "field_desc", ",", "nested_package", ",", "scope", ")", "for", "extension_proto", ",", "extension_desc", "in", "(", "zip", "(", "desc_proto", ".", "extension", ",", "main_desc", ".", "extensions", ")", ")", ":", "extension_desc", ".", "containing_type", "=", "self", ".", "_GetTypeFromScope", "(", "nested_package", ",", "extension_proto", ".", "extendee", ",", "scope", ")", "self", ".", "_SetFieldType", "(", "extension_proto", ",", "extension_desc", ",", "nested_package", ",", "scope", ")", "for", "nested_type", "in", "desc_proto", ".", "nested_type", ":", "self", ".", "_SetAllFieldTypes", "(", "nested_package", ",", "nested_type", ",", "scope", ")" ]
Sets all the descriptor's fields's types. This method also sets the containing types on any extensions. Args: package: The current package of desc_proto. desc_proto: The message descriptor to update. scope: Enclosing scope of available types.
[ "Sets", "all", "the", "descriptor", "s", "fields", "s", "types", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L752-L782
29,072
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool._SetFieldType
def _SetFieldType(self, field_proto, field_desc, package, scope): """Sets the field's type, cpp_type, message_type and enum_type. Args: field_proto: Data about the field in proto format. field_desc: The descriptor to modiy. package: The package the field's container is in. scope: Enclosing scope of available types. """ if field_proto.type_name: desc = self._GetTypeFromScope(package, field_proto.type_name, scope) else: desc = None if not field_proto.HasField('type'): if isinstance(desc, descriptor.Descriptor): field_proto.type = descriptor.FieldDescriptor.TYPE_MESSAGE else: field_proto.type = descriptor.FieldDescriptor.TYPE_ENUM field_desc.cpp_type = descriptor.FieldDescriptor.ProtoTypeToCppProtoType( field_proto.type) if (field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE or field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP): field_desc.message_type = desc if field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM: field_desc.enum_type = desc if field_proto.label == descriptor.FieldDescriptor.LABEL_REPEATED: field_desc.has_default_value = False field_desc.default_value = [] elif field_proto.HasField('default_value'): field_desc.has_default_value = True if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT): field_desc.default_value = float(field_proto.default_value) elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING: field_desc.default_value = field_proto.default_value elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL: field_desc.default_value = field_proto.default_value.lower() == 'true' elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM: field_desc.default_value = field_desc.enum_type.values_by_name[ field_proto.default_value].number elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES: field_desc.default_value = text_encoding.CUnescape( field_proto.default_value) else: # All other types are of the "int" type. field_desc.default_value = int(field_proto.default_value) else: field_desc.has_default_value = False if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT): field_desc.default_value = 0.0 elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING: field_desc.default_value = u'' elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL: field_desc.default_value = False elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM: field_desc.default_value = field_desc.enum_type.values[0].number elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES: field_desc.default_value = b'' else: # All other types are of the "int" type. field_desc.default_value = 0 field_desc.type = field_proto.type
python
def _SetFieldType(self, field_proto, field_desc, package, scope): """Sets the field's type, cpp_type, message_type and enum_type. Args: field_proto: Data about the field in proto format. field_desc: The descriptor to modiy. package: The package the field's container is in. scope: Enclosing scope of available types. """ if field_proto.type_name: desc = self._GetTypeFromScope(package, field_proto.type_name, scope) else: desc = None if not field_proto.HasField('type'): if isinstance(desc, descriptor.Descriptor): field_proto.type = descriptor.FieldDescriptor.TYPE_MESSAGE else: field_proto.type = descriptor.FieldDescriptor.TYPE_ENUM field_desc.cpp_type = descriptor.FieldDescriptor.ProtoTypeToCppProtoType( field_proto.type) if (field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE or field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP): field_desc.message_type = desc if field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM: field_desc.enum_type = desc if field_proto.label == descriptor.FieldDescriptor.LABEL_REPEATED: field_desc.has_default_value = False field_desc.default_value = [] elif field_proto.HasField('default_value'): field_desc.has_default_value = True if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT): field_desc.default_value = float(field_proto.default_value) elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING: field_desc.default_value = field_proto.default_value elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL: field_desc.default_value = field_proto.default_value.lower() == 'true' elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM: field_desc.default_value = field_desc.enum_type.values_by_name[ field_proto.default_value].number elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES: field_desc.default_value = text_encoding.CUnescape( field_proto.default_value) else: # All other types are of the "int" type. field_desc.default_value = int(field_proto.default_value) else: field_desc.has_default_value = False if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT): field_desc.default_value = 0.0 elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING: field_desc.default_value = u'' elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL: field_desc.default_value = False elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM: field_desc.default_value = field_desc.enum_type.values[0].number elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES: field_desc.default_value = b'' else: # All other types are of the "int" type. field_desc.default_value = 0 field_desc.type = field_proto.type
[ "def", "_SetFieldType", "(", "self", ",", "field_proto", ",", "field_desc", ",", "package", ",", "scope", ")", ":", "if", "field_proto", ".", "type_name", ":", "desc", "=", "self", ".", "_GetTypeFromScope", "(", "package", ",", "field_proto", ".", "type_name", ",", "scope", ")", "else", ":", "desc", "=", "None", "if", "not", "field_proto", ".", "HasField", "(", "'type'", ")", ":", "if", "isinstance", "(", "desc", ",", "descriptor", ".", "Descriptor", ")", ":", "field_proto", ".", "type", "=", "descriptor", ".", "FieldDescriptor", ".", "TYPE_MESSAGE", "else", ":", "field_proto", ".", "type", "=", "descriptor", ".", "FieldDescriptor", ".", "TYPE_ENUM", "field_desc", ".", "cpp_type", "=", "descriptor", ".", "FieldDescriptor", ".", "ProtoTypeToCppProtoType", "(", "field_proto", ".", "type", ")", "if", "(", "field_proto", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_MESSAGE", "or", "field_proto", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_GROUP", ")", ":", "field_desc", ".", "message_type", "=", "desc", "if", "field_proto", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_ENUM", ":", "field_desc", ".", "enum_type", "=", "desc", "if", "field_proto", ".", "label", "==", "descriptor", ".", "FieldDescriptor", ".", "LABEL_REPEATED", ":", "field_desc", ".", "has_default_value", "=", "False", "field_desc", ".", "default_value", "=", "[", "]", "elif", "field_proto", ".", "HasField", "(", "'default_value'", ")", ":", "field_desc", ".", "has_default_value", "=", "True", "if", "(", "field_proto", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_DOUBLE", "or", "field_proto", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_FLOAT", ")", ":", "field_desc", ".", "default_value", "=", "float", "(", "field_proto", ".", "default_value", ")", "elif", "field_proto", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_STRING", ":", "field_desc", ".", "default_value", "=", "field_proto", ".", "default_value", "elif", "field_proto", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_BOOL", ":", "field_desc", ".", "default_value", "=", "field_proto", ".", "default_value", ".", "lower", "(", ")", "==", "'true'", "elif", "field_proto", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_ENUM", ":", "field_desc", ".", "default_value", "=", "field_desc", ".", "enum_type", ".", "values_by_name", "[", "field_proto", ".", "default_value", "]", ".", "number", "elif", "field_proto", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_BYTES", ":", "field_desc", ".", "default_value", "=", "text_encoding", ".", "CUnescape", "(", "field_proto", ".", "default_value", ")", "else", ":", "# All other types are of the \"int\" type.", "field_desc", ".", "default_value", "=", "int", "(", "field_proto", ".", "default_value", ")", "else", ":", "field_desc", ".", "has_default_value", "=", "False", "if", "(", "field_proto", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_DOUBLE", "or", "field_proto", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_FLOAT", ")", ":", "field_desc", ".", "default_value", "=", "0.0", "elif", "field_proto", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_STRING", ":", "field_desc", ".", "default_value", "=", "u''", "elif", "field_proto", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_BOOL", ":", "field_desc", ".", "default_value", "=", "False", "elif", "field_proto", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_ENUM", ":", "field_desc", ".", "default_value", "=", "field_desc", ".", "enum_type", ".", "values", "[", "0", "]", ".", "number", "elif", "field_proto", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_BYTES", ":", "field_desc", ".", "default_value", "=", "b''", "else", ":", "# All other types are of the \"int\" type.", "field_desc", ".", "default_value", "=", "0", "field_desc", ".", "type", "=", "field_proto", ".", "type" ]
Sets the field's type, cpp_type, message_type and enum_type. Args: field_proto: Data about the field in proto format. field_desc: The descriptor to modiy. package: The package the field's container is in. scope: Enclosing scope of available types.
[ "Sets", "the", "field", "s", "type", "cpp_type", "message_type", "and", "enum_type", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L784-L852
29,073
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool._MakeEnumValueDescriptor
def _MakeEnumValueDescriptor(self, value_proto, index): """Creates a enum value descriptor object from a enum value proto. Args: value_proto: The proto describing the enum value. index: The index of the enum value. Returns: An initialized EnumValueDescriptor object. """ return descriptor.EnumValueDescriptor( name=value_proto.name, index=index, number=value_proto.number, options=_OptionsOrNone(value_proto), type=None)
python
def _MakeEnumValueDescriptor(self, value_proto, index): """Creates a enum value descriptor object from a enum value proto. Args: value_proto: The proto describing the enum value. index: The index of the enum value. Returns: An initialized EnumValueDescriptor object. """ return descriptor.EnumValueDescriptor( name=value_proto.name, index=index, number=value_proto.number, options=_OptionsOrNone(value_proto), type=None)
[ "def", "_MakeEnumValueDescriptor", "(", "self", ",", "value_proto", ",", "index", ")", ":", "return", "descriptor", ".", "EnumValueDescriptor", "(", "name", "=", "value_proto", ".", "name", ",", "index", "=", "index", ",", "number", "=", "value_proto", ".", "number", ",", "options", "=", "_OptionsOrNone", "(", "value_proto", ")", ",", "type", "=", "None", ")" ]
Creates a enum value descriptor object from a enum value proto. Args: value_proto: The proto describing the enum value. index: The index of the enum value. Returns: An initialized EnumValueDescriptor object.
[ "Creates", "a", "enum", "value", "descriptor", "object", "from", "a", "enum", "value", "proto", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L854-L870
29,074
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool._MakeServiceDescriptor
def _MakeServiceDescriptor(self, service_proto, service_index, scope, package, file_desc): """Make a protobuf ServiceDescriptor given a ServiceDescriptorProto. Args: service_proto: The descriptor_pb2.ServiceDescriptorProto protobuf message. service_index: The index of the service in the File. scope: Dict mapping short and full symbols to message and enum types. package: Optional package name for the new message EnumDescriptor. file_desc: The file containing the service descriptor. Returns: The added descriptor. """ if package: service_name = '.'.join((package, service_proto.name)) else: service_name = service_proto.name methods = [self._MakeMethodDescriptor(method_proto, service_name, package, scope, index) for index, method_proto in enumerate(service_proto.method)] desc = descriptor.ServiceDescriptor(name=service_proto.name, full_name=service_name, index=service_index, methods=methods, options=_OptionsOrNone(service_proto), file=file_desc) self._service_descriptors[service_name] = desc return desc
python
def _MakeServiceDescriptor(self, service_proto, service_index, scope, package, file_desc): """Make a protobuf ServiceDescriptor given a ServiceDescriptorProto. Args: service_proto: The descriptor_pb2.ServiceDescriptorProto protobuf message. service_index: The index of the service in the File. scope: Dict mapping short and full symbols to message and enum types. package: Optional package name for the new message EnumDescriptor. file_desc: The file containing the service descriptor. Returns: The added descriptor. """ if package: service_name = '.'.join((package, service_proto.name)) else: service_name = service_proto.name methods = [self._MakeMethodDescriptor(method_proto, service_name, package, scope, index) for index, method_proto in enumerate(service_proto.method)] desc = descriptor.ServiceDescriptor(name=service_proto.name, full_name=service_name, index=service_index, methods=methods, options=_OptionsOrNone(service_proto), file=file_desc) self._service_descriptors[service_name] = desc return desc
[ "def", "_MakeServiceDescriptor", "(", "self", ",", "service_proto", ",", "service_index", ",", "scope", ",", "package", ",", "file_desc", ")", ":", "if", "package", ":", "service_name", "=", "'.'", ".", "join", "(", "(", "package", ",", "service_proto", ".", "name", ")", ")", "else", ":", "service_name", "=", "service_proto", ".", "name", "methods", "=", "[", "self", ".", "_MakeMethodDescriptor", "(", "method_proto", ",", "service_name", ",", "package", ",", "scope", ",", "index", ")", "for", "index", ",", "method_proto", "in", "enumerate", "(", "service_proto", ".", "method", ")", "]", "desc", "=", "descriptor", ".", "ServiceDescriptor", "(", "name", "=", "service_proto", ".", "name", ",", "full_name", "=", "service_name", ",", "index", "=", "service_index", ",", "methods", "=", "methods", ",", "options", "=", "_OptionsOrNone", "(", "service_proto", ")", ",", "file", "=", "file_desc", ")", "self", ".", "_service_descriptors", "[", "service_name", "]", "=", "desc", "return", "desc" ]
Make a protobuf ServiceDescriptor given a ServiceDescriptorProto. Args: service_proto: The descriptor_pb2.ServiceDescriptorProto protobuf message. service_index: The index of the service in the File. scope: Dict mapping short and full symbols to message and enum types. package: Optional package name for the new message EnumDescriptor. file_desc: The file containing the service descriptor. Returns: The added descriptor.
[ "Make", "a", "protobuf", "ServiceDescriptor", "given", "a", "ServiceDescriptorProto", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L872-L902
29,075
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool._MakeMethodDescriptor
def _MakeMethodDescriptor(self, method_proto, service_name, package, scope, index): """Creates a method descriptor from a MethodDescriptorProto. Args: method_proto: The proto describing the method. service_name: The name of the containing service. package: Optional package name to look up for types. scope: Scope containing available types. index: Index of the method in the service. Returns: An initialized MethodDescriptor object. """ full_name = '.'.join((service_name, method_proto.name)) input_type = self._GetTypeFromScope( package, method_proto.input_type, scope) output_type = self._GetTypeFromScope( package, method_proto.output_type, scope) return descriptor.MethodDescriptor(name=method_proto.name, full_name=full_name, index=index, containing_service=None, input_type=input_type, output_type=output_type, options=_OptionsOrNone(method_proto))
python
def _MakeMethodDescriptor(self, method_proto, service_name, package, scope, index): """Creates a method descriptor from a MethodDescriptorProto. Args: method_proto: The proto describing the method. service_name: The name of the containing service. package: Optional package name to look up for types. scope: Scope containing available types. index: Index of the method in the service. Returns: An initialized MethodDescriptor object. """ full_name = '.'.join((service_name, method_proto.name)) input_type = self._GetTypeFromScope( package, method_proto.input_type, scope) output_type = self._GetTypeFromScope( package, method_proto.output_type, scope) return descriptor.MethodDescriptor(name=method_proto.name, full_name=full_name, index=index, containing_service=None, input_type=input_type, output_type=output_type, options=_OptionsOrNone(method_proto))
[ "def", "_MakeMethodDescriptor", "(", "self", ",", "method_proto", ",", "service_name", ",", "package", ",", "scope", ",", "index", ")", ":", "full_name", "=", "'.'", ".", "join", "(", "(", "service_name", ",", "method_proto", ".", "name", ")", ")", "input_type", "=", "self", ".", "_GetTypeFromScope", "(", "package", ",", "method_proto", ".", "input_type", ",", "scope", ")", "output_type", "=", "self", ".", "_GetTypeFromScope", "(", "package", ",", "method_proto", ".", "output_type", ",", "scope", ")", "return", "descriptor", ".", "MethodDescriptor", "(", "name", "=", "method_proto", ".", "name", ",", "full_name", "=", "full_name", ",", "index", "=", "index", ",", "containing_service", "=", "None", ",", "input_type", "=", "input_type", ",", "output_type", "=", "output_type", ",", "options", "=", "_OptionsOrNone", "(", "method_proto", ")", ")" ]
Creates a method descriptor from a MethodDescriptorProto. Args: method_proto: The proto describing the method. service_name: The name of the containing service. package: Optional package name to look up for types. scope: Scope containing available types. index: Index of the method in the service. Returns: An initialized MethodDescriptor object.
[ "Creates", "a", "method", "descriptor", "from", "a", "MethodDescriptorProto", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L904-L929
29,076
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool._ExtractSymbols
def _ExtractSymbols(self, descriptors): """Pulls out all the symbols from descriptor protos. Args: descriptors: The messages to extract descriptors from. Yields: A two element tuple of the type name and descriptor object. """ for desc in descriptors: yield (_PrefixWithDot(desc.full_name), desc) for symbol in self._ExtractSymbols(desc.nested_types): yield symbol for enum in desc.enum_types: yield (_PrefixWithDot(enum.full_name), enum)
python
def _ExtractSymbols(self, descriptors): """Pulls out all the symbols from descriptor protos. Args: descriptors: The messages to extract descriptors from. Yields: A two element tuple of the type name and descriptor object. """ for desc in descriptors: yield (_PrefixWithDot(desc.full_name), desc) for symbol in self._ExtractSymbols(desc.nested_types): yield symbol for enum in desc.enum_types: yield (_PrefixWithDot(enum.full_name), enum)
[ "def", "_ExtractSymbols", "(", "self", ",", "descriptors", ")", ":", "for", "desc", "in", "descriptors", ":", "yield", "(", "_PrefixWithDot", "(", "desc", ".", "full_name", ")", ",", "desc", ")", "for", "symbol", "in", "self", ".", "_ExtractSymbols", "(", "desc", ".", "nested_types", ")", ":", "yield", "symbol", "for", "enum", "in", "desc", ".", "enum_types", ":", "yield", "(", "_PrefixWithDot", "(", "enum", ".", "full_name", ")", ",", "enum", ")" ]
Pulls out all the symbols from descriptor protos. Args: descriptors: The messages to extract descriptors from. Yields: A two element tuple of the type name and descriptor object.
[ "Pulls", "out", "all", "the", "symbols", "from", "descriptor", "protos", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L931-L945
29,077
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool._GetDeps
def _GetDeps(self, dependencies): """Recursively finds dependencies for file protos. Args: dependencies: The names of the files being depended on. Yields: Each direct and indirect dependency. """ for dependency in dependencies: dep_desc = self.FindFileByName(dependency) yield dep_desc for parent_dep in dep_desc.dependencies: yield parent_dep
python
def _GetDeps(self, dependencies): """Recursively finds dependencies for file protos. Args: dependencies: The names of the files being depended on. Yields: Each direct and indirect dependency. """ for dependency in dependencies: dep_desc = self.FindFileByName(dependency) yield dep_desc for parent_dep in dep_desc.dependencies: yield parent_dep
[ "def", "_GetDeps", "(", "self", ",", "dependencies", ")", ":", "for", "dependency", "in", "dependencies", ":", "dep_desc", "=", "self", ".", "FindFileByName", "(", "dependency", ")", "yield", "dep_desc", "for", "parent_dep", "in", "dep_desc", ".", "dependencies", ":", "yield", "parent_dep" ]
Recursively finds dependencies for file protos. Args: dependencies: The names of the files being depended on. Yields: Each direct and indirect dependency.
[ "Recursively", "finds", "dependencies", "for", "file", "protos", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L947-L961
29,078
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
DescriptorPool._GetTypeFromScope
def _GetTypeFromScope(self, package, type_name, scope): """Finds a given type name in the current scope. Args: package: The package the proto should be located in. type_name: The name of the type to be found in the scope. scope: Dict mapping short and full symbols to message and enum types. Returns: The descriptor for the requested type. """ if type_name not in scope: components = _PrefixWithDot(package).split('.') while components: possible_match = '.'.join(components + [type_name]) if possible_match in scope: type_name = possible_match break else: components.pop(-1) return scope[type_name]
python
def _GetTypeFromScope(self, package, type_name, scope): """Finds a given type name in the current scope. Args: package: The package the proto should be located in. type_name: The name of the type to be found in the scope. scope: Dict mapping short and full symbols to message and enum types. Returns: The descriptor for the requested type. """ if type_name not in scope: components = _PrefixWithDot(package).split('.') while components: possible_match = '.'.join(components + [type_name]) if possible_match in scope: type_name = possible_match break else: components.pop(-1) return scope[type_name]
[ "def", "_GetTypeFromScope", "(", "self", ",", "package", ",", "type_name", ",", "scope", ")", ":", "if", "type_name", "not", "in", "scope", ":", "components", "=", "_PrefixWithDot", "(", "package", ")", ".", "split", "(", "'.'", ")", "while", "components", ":", "possible_match", "=", "'.'", ".", "join", "(", "components", "+", "[", "type_name", "]", ")", "if", "possible_match", "in", "scope", ":", "type_name", "=", "possible_match", "break", "else", ":", "components", ".", "pop", "(", "-", "1", ")", "return", "scope", "[", "type_name", "]" ]
Finds a given type name in the current scope. Args: package: The package the proto should be located in. type_name: The name of the type to be found in the scope. scope: Dict mapping short and full symbols to message and enum types. Returns: The descriptor for the requested type.
[ "Finds", "a", "given", "type", "name", "in", "the", "current", "scope", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L963-L983
29,079
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/util/sequence.py
max_element
def max_element (elements, ordered = None): """ Returns the maximum number in 'elements'. Uses 'ordered' for comparisons, or '<' is none is provided. """ assert is_iterable(elements) assert callable(ordered) or ordered is None if not ordered: ordered = operator.lt max = elements [0] for e in elements [1:]: if ordered (max, e): max = e return max
python
def max_element (elements, ordered = None): """ Returns the maximum number in 'elements'. Uses 'ordered' for comparisons, or '<' is none is provided. """ assert is_iterable(elements) assert callable(ordered) or ordered is None if not ordered: ordered = operator.lt max = elements [0] for e in elements [1:]: if ordered (max, e): max = e return max
[ "def", "max_element", "(", "elements", ",", "ordered", "=", "None", ")", ":", "assert", "is_iterable", "(", "elements", ")", "assert", "callable", "(", "ordered", ")", "or", "ordered", "is", "None", "if", "not", "ordered", ":", "ordered", "=", "operator", ".", "lt", "max", "=", "elements", "[", "0", "]", "for", "e", "in", "elements", "[", "1", ":", "]", ":", "if", "ordered", "(", "max", ",", "e", ")", ":", "max", "=", "e", "return", "max" ]
Returns the maximum number in 'elements'. Uses 'ordered' for comparisons, or '<' is none is provided.
[ "Returns", "the", "maximum", "number", "in", "elements", ".", "Uses", "ordered", "for", "comparisons", "or", "<", "is", "none", "is", "provided", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/sequence.py#L24-L37
29,080
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/util/sequence.py
select_highest_ranked
def select_highest_ranked (elements, ranks): """ Returns all of 'elements' for which corresponding element in parallel list 'rank' is equal to the maximum value in 'rank'. """ assert is_iterable(elements) assert is_iterable(ranks) if not elements: return [] max_rank = max_element (ranks) result = [] while elements: if ranks [0] == max_rank: result.append (elements [0]) elements = elements [1:] ranks = ranks [1:] return result
python
def select_highest_ranked (elements, ranks): """ Returns all of 'elements' for which corresponding element in parallel list 'rank' is equal to the maximum value in 'rank'. """ assert is_iterable(elements) assert is_iterable(ranks) if not elements: return [] max_rank = max_element (ranks) result = [] while elements: if ranks [0] == max_rank: result.append (elements [0]) elements = elements [1:] ranks = ranks [1:] return result
[ "def", "select_highest_ranked", "(", "elements", ",", "ranks", ")", ":", "assert", "is_iterable", "(", "elements", ")", "assert", "is_iterable", "(", "ranks", ")", "if", "not", "elements", ":", "return", "[", "]", "max_rank", "=", "max_element", "(", "ranks", ")", "result", "=", "[", "]", "while", "elements", ":", "if", "ranks", "[", "0", "]", "==", "max_rank", ":", "result", ".", "append", "(", "elements", "[", "0", "]", ")", "elements", "=", "elements", "[", "1", ":", "]", "ranks", "=", "ranks", "[", "1", ":", "]", "return", "result" ]
Returns all of 'elements' for which corresponding element in parallel list 'rank' is equal to the maximum value in 'rank'.
[ "Returns", "all", "of", "elements", "for", "which", "corresponding", "element", "in", "parallel", "list", "rank", "is", "equal", "to", "the", "maximum", "value", "in", "rank", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/sequence.py#L39-L58
29,081
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/message.py
Message.CopyFrom
def CopyFrom(self, other_msg): """Copies the content of the specified message into the current message. The method clears the current message and then merges the specified message using MergeFrom. Args: other_msg: Message to copy into the current one. """ if self is other_msg: return self.Clear() self.MergeFrom(other_msg)
python
def CopyFrom(self, other_msg): """Copies the content of the specified message into the current message. The method clears the current message and then merges the specified message using MergeFrom. Args: other_msg: Message to copy into the current one. """ if self is other_msg: return self.Clear() self.MergeFrom(other_msg)
[ "def", "CopyFrom", "(", "self", ",", "other_msg", ")", ":", "if", "self", "is", "other_msg", ":", "return", "self", ".", "Clear", "(", ")", "self", ".", "MergeFrom", "(", "other_msg", ")" ]
Copies the content of the specified message into the current message. The method clears the current message and then merges the specified message using MergeFrom. Args: other_msg: Message to copy into the current one.
[ "Copies", "the", "content", "of", "the", "specified", "message", "into", "the", "current", "message", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/message.py#L106-L118
29,082
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/xgboost/_tree_ensemble.py
convert_tree_ensemble
def convert_tree_ensemble(model, feature_names, target, force_32bit_float): """Convert a generic tree model to the protobuf spec. This currently supports: * Decision tree regression Parameters ---------- model: str | Booster Path on disk where the XGboost JSON representation of the model is or a handle to the XGboost model. feature_names : list of strings or None Names of each of the features. When set to None, the feature names are extracted from the model. target: str, Name of the output column. force_32bit_float: bool If True, then the resulting CoreML model will use 32 bit floats internally. Returns ------- model_spec: An object of type Model_pb. Protobuf representation of the model """ if not(_HAS_XGBOOST): raise RuntimeError('xgboost not found. xgboost conversion API is disabled.') import json import os feature_map = None if isinstance(model, (_xgboost.core.Booster, _xgboost.XGBRegressor)): # Testing a few corner cases that we don't support if isinstance(model, _xgboost.XGBRegressor): try: objective = model.get_xgb_params()["objective"] except: objective = None if objective in ["reg:gamma", "reg:tweedie"]: raise ValueError("Regression objective '%s' not supported for export." % objective) # Now use the booster API. if isinstance(model, _xgboost.XGBRegressor): # Name change in 0.7 if hasattr(model, 'get_booster'): model = model.get_booster() else: model = model.booster() # Xgboost sometimes has feature names in there. Sometimes does not. if (feature_names is None) and (model.feature_names is None): raise ValueError("Feature names not present in the model. Must be provided during conversion.") feature_names = model.feature_names if feature_names is None: feature_names = model.feature_names xgb_model_str = model.get_dump(with_stats=True, dump_format = 'json') if model.feature_names: feature_map = {f:i for i,f in enumerate(model.feature_names)} # Path on the file system where the XGboost model exists. elif isinstance(model, str): if not os.path.exists(model): raise TypeError("Invalid path %s." % model) with open(model) as f: xgb_model_str = json.load(f) feature_map = {f:i for i,f in enumerate(feature_names)} else: raise TypeError("Unexpected type. Expecting XGBoost model.") mlkit_tree = _TreeEnsembleRegressor(feature_names, target) mlkit_tree.set_default_prediction_value(0.5) for xgb_tree_id, xgb_tree_str in enumerate(xgb_model_str): xgb_tree_json = json.loads(xgb_tree_str) recurse_json(mlkit_tree, xgb_tree_json, xgb_tree_id, node_id = 0, feature_map = feature_map, force_32bit_float = force_32bit_float) return mlkit_tree.spec
python
def convert_tree_ensemble(model, feature_names, target, force_32bit_float): """Convert a generic tree model to the protobuf spec. This currently supports: * Decision tree regression Parameters ---------- model: str | Booster Path on disk where the XGboost JSON representation of the model is or a handle to the XGboost model. feature_names : list of strings or None Names of each of the features. When set to None, the feature names are extracted from the model. target: str, Name of the output column. force_32bit_float: bool If True, then the resulting CoreML model will use 32 bit floats internally. Returns ------- model_spec: An object of type Model_pb. Protobuf representation of the model """ if not(_HAS_XGBOOST): raise RuntimeError('xgboost not found. xgboost conversion API is disabled.') import json import os feature_map = None if isinstance(model, (_xgboost.core.Booster, _xgboost.XGBRegressor)): # Testing a few corner cases that we don't support if isinstance(model, _xgboost.XGBRegressor): try: objective = model.get_xgb_params()["objective"] except: objective = None if objective in ["reg:gamma", "reg:tweedie"]: raise ValueError("Regression objective '%s' not supported for export." % objective) # Now use the booster API. if isinstance(model, _xgboost.XGBRegressor): # Name change in 0.7 if hasattr(model, 'get_booster'): model = model.get_booster() else: model = model.booster() # Xgboost sometimes has feature names in there. Sometimes does not. if (feature_names is None) and (model.feature_names is None): raise ValueError("Feature names not present in the model. Must be provided during conversion.") feature_names = model.feature_names if feature_names is None: feature_names = model.feature_names xgb_model_str = model.get_dump(with_stats=True, dump_format = 'json') if model.feature_names: feature_map = {f:i for i,f in enumerate(model.feature_names)} # Path on the file system where the XGboost model exists. elif isinstance(model, str): if not os.path.exists(model): raise TypeError("Invalid path %s." % model) with open(model) as f: xgb_model_str = json.load(f) feature_map = {f:i for i,f in enumerate(feature_names)} else: raise TypeError("Unexpected type. Expecting XGBoost model.") mlkit_tree = _TreeEnsembleRegressor(feature_names, target) mlkit_tree.set_default_prediction_value(0.5) for xgb_tree_id, xgb_tree_str in enumerate(xgb_model_str): xgb_tree_json = json.loads(xgb_tree_str) recurse_json(mlkit_tree, xgb_tree_json, xgb_tree_id, node_id = 0, feature_map = feature_map, force_32bit_float = force_32bit_float) return mlkit_tree.spec
[ "def", "convert_tree_ensemble", "(", "model", ",", "feature_names", ",", "target", ",", "force_32bit_float", ")", ":", "if", "not", "(", "_HAS_XGBOOST", ")", ":", "raise", "RuntimeError", "(", "'xgboost not found. xgboost conversion API is disabled.'", ")", "import", "json", "import", "os", "feature_map", "=", "None", "if", "isinstance", "(", "model", ",", "(", "_xgboost", ".", "core", ".", "Booster", ",", "_xgboost", ".", "XGBRegressor", ")", ")", ":", "# Testing a few corner cases that we don't support", "if", "isinstance", "(", "model", ",", "_xgboost", ".", "XGBRegressor", ")", ":", "try", ":", "objective", "=", "model", ".", "get_xgb_params", "(", ")", "[", "\"objective\"", "]", "except", ":", "objective", "=", "None", "if", "objective", "in", "[", "\"reg:gamma\"", ",", "\"reg:tweedie\"", "]", ":", "raise", "ValueError", "(", "\"Regression objective '%s' not supported for export.\"", "%", "objective", ")", "# Now use the booster API.", "if", "isinstance", "(", "model", ",", "_xgboost", ".", "XGBRegressor", ")", ":", "# Name change in 0.7", "if", "hasattr", "(", "model", ",", "'get_booster'", ")", ":", "model", "=", "model", ".", "get_booster", "(", ")", "else", ":", "model", "=", "model", ".", "booster", "(", ")", "# Xgboost sometimes has feature names in there. Sometimes does not.", "if", "(", "feature_names", "is", "None", ")", "and", "(", "model", ".", "feature_names", "is", "None", ")", ":", "raise", "ValueError", "(", "\"Feature names not present in the model. Must be provided during conversion.\"", ")", "feature_names", "=", "model", ".", "feature_names", "if", "feature_names", "is", "None", ":", "feature_names", "=", "model", ".", "feature_names", "xgb_model_str", "=", "model", ".", "get_dump", "(", "with_stats", "=", "True", ",", "dump_format", "=", "'json'", ")", "if", "model", ".", "feature_names", ":", "feature_map", "=", "{", "f", ":", "i", "for", "i", ",", "f", "in", "enumerate", "(", "model", ".", "feature_names", ")", "}", "# Path on the file system where the XGboost model exists.", "elif", "isinstance", "(", "model", ",", "str", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "model", ")", ":", "raise", "TypeError", "(", "\"Invalid path %s.\"", "%", "model", ")", "with", "open", "(", "model", ")", "as", "f", ":", "xgb_model_str", "=", "json", ".", "load", "(", "f", ")", "feature_map", "=", "{", "f", ":", "i", "for", "i", ",", "f", "in", "enumerate", "(", "feature_names", ")", "}", "else", ":", "raise", "TypeError", "(", "\"Unexpected type. Expecting XGBoost model.\"", ")", "mlkit_tree", "=", "_TreeEnsembleRegressor", "(", "feature_names", ",", "target", ")", "mlkit_tree", ".", "set_default_prediction_value", "(", "0.5", ")", "for", "xgb_tree_id", ",", "xgb_tree_str", "in", "enumerate", "(", "xgb_model_str", ")", ":", "xgb_tree_json", "=", "json", ".", "loads", "(", "xgb_tree_str", ")", "recurse_json", "(", "mlkit_tree", ",", "xgb_tree_json", ",", "xgb_tree_id", ",", "node_id", "=", "0", ",", "feature_map", "=", "feature_map", ",", "force_32bit_float", "=", "force_32bit_float", ")", "return", "mlkit_tree", ".", "spec" ]
Convert a generic tree model to the protobuf spec. This currently supports: * Decision tree regression Parameters ---------- model: str | Booster Path on disk where the XGboost JSON representation of the model is or a handle to the XGboost model. feature_names : list of strings or None Names of each of the features. When set to None, the feature names are extracted from the model. target: str, Name of the output column. force_32bit_float: bool If True, then the resulting CoreML model will use 32 bit floats internally. Returns ------- model_spec: An object of type Model_pb. Protobuf representation of the model
[ "Convert", "a", "generic", "tree", "model", "to", "the", "protobuf", "spec", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/xgboost/_tree_ensemble.py#L75-L156
29,083
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_one_hot_encoder.py
update_dimension
def update_dimension(model, input_dimension): """ Given a model that takes an array of dimension input_dimension, returns the output dimension. """ if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') _sklearn_util.check_fitted(model, lambda m: hasattr(m, 'active_features_')) _sklearn_util.check_fitted(model, lambda m: hasattr(m, 'n_values_')) if model.categorical_features == 'all': return len(model.active_features_) else: out_dimension = (len(model.active_features_) + (input_dimension - len(model.n_values_))) return out_dimension
python
def update_dimension(model, input_dimension): """ Given a model that takes an array of dimension input_dimension, returns the output dimension. """ if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') _sklearn_util.check_fitted(model, lambda m: hasattr(m, 'active_features_')) _sklearn_util.check_fitted(model, lambda m: hasattr(m, 'n_values_')) if model.categorical_features == 'all': return len(model.active_features_) else: out_dimension = (len(model.active_features_) + (input_dimension - len(model.n_values_))) return out_dimension
[ "def", "update_dimension", "(", "model", ",", "input_dimension", ")", ":", "if", "not", "(", "_HAS_SKLEARN", ")", ":", "raise", "RuntimeError", "(", "'scikit-learn not found. scikit-learn conversion API is disabled.'", ")", "_sklearn_util", ".", "check_fitted", "(", "model", ",", "lambda", "m", ":", "hasattr", "(", "m", ",", "'active_features_'", ")", ")", "_sklearn_util", ".", "check_fitted", "(", "model", ",", "lambda", "m", ":", "hasattr", "(", "m", ",", "'n_values_'", ")", ")", "if", "model", ".", "categorical_features", "==", "'all'", ":", "return", "len", "(", "model", ".", "active_features_", ")", "else", ":", "out_dimension", "=", "(", "len", "(", "model", ".", "active_features_", ")", "+", "(", "input_dimension", "-", "len", "(", "model", ".", "n_values_", ")", ")", ")", "return", "out_dimension" ]
Given a model that takes an array of dimension input_dimension, returns the output dimension.
[ "Given", "a", "model", "that", "takes", "an", "array", "of", "dimension", "input_dimension", "returns", "the", "output", "dimension", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_one_hot_encoder.py#L192-L209
29,084
apple/turicreate
src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py
convert_elementwise_mul_scalar
def convert_elementwise_mul_scalar(net, node, module, builder): """Convert a scalar multiplication from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ import numpy input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) mult = literal_eval(param['scalar']) builder.add_scale(name=name, W=numpy.array([mult]), b=0, has_bias=False, input_name=input_name, output_name=output_name)
python
def convert_elementwise_mul_scalar(net, node, module, builder): """Convert a scalar multiplication from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ import numpy input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) mult = literal_eval(param['scalar']) builder.add_scale(name=name, W=numpy.array([mult]), b=0, has_bias=False, input_name=input_name, output_name=output_name)
[ "def", "convert_elementwise_mul_scalar", "(", "net", ",", "node", ",", "module", ",", "builder", ")", ":", "import", "numpy", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'name'", "]", "param", "=", "_get_attr", "(", "node", ")", "mult", "=", "literal_eval", "(", "param", "[", "'scalar'", "]", ")", "builder", ".", "add_scale", "(", "name", "=", "name", ",", "W", "=", "numpy", ".", "array", "(", "[", "mult", "]", ")", ",", "b", "=", "0", ",", "has_bias", "=", "False", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ")" ]
Convert a scalar multiplication from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "a", "scalar", "multiplication", "from", "mxnet", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L224-L252
29,085
apple/turicreate
src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py
convert_dense
def convert_dense(net, node, module, builder): """Convert a dense layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) has_bias = True name = node['name'] inputs = node['inputs'] args, _ = module.get_params() W = args[_get_node_name(net, inputs[1][0])].asnumpy() if has_bias: Wb = args[_get_node_name(net, inputs[2][0])].asnumpy() else: Wb = None nC, nB = W.shape builder.add_inner_product( name=name, W=W, b=Wb, input_channels=nB, output_channels=nC, has_bias=has_bias, input_name=input_name, output_name=output_name )
python
def convert_dense(net, node, module, builder): """Convert a dense layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) has_bias = True name = node['name'] inputs = node['inputs'] args, _ = module.get_params() W = args[_get_node_name(net, inputs[1][0])].asnumpy() if has_bias: Wb = args[_get_node_name(net, inputs[2][0])].asnumpy() else: Wb = None nC, nB = W.shape builder.add_inner_product( name=name, W=W, b=Wb, input_channels=nB, output_channels=nC, has_bias=has_bias, input_name=input_name, output_name=output_name )
[ "def", "convert_dense", "(", "net", ",", "node", ",", "module", ",", "builder", ")", ":", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "has_bias", "=", "True", "name", "=", "node", "[", "'name'", "]", "inputs", "=", "node", "[", "'inputs'", "]", "args", ",", "_", "=", "module", ".", "get_params", "(", ")", "W", "=", "args", "[", "_get_node_name", "(", "net", ",", "inputs", "[", "1", "]", "[", "0", "]", ")", "]", ".", "asnumpy", "(", ")", "if", "has_bias", ":", "Wb", "=", "args", "[", "_get_node_name", "(", "net", ",", "inputs", "[", "2", "]", "[", "0", "]", ")", "]", ".", "asnumpy", "(", ")", "else", ":", "Wb", "=", "None", "nC", ",", "nB", "=", "W", ".", "shape", "builder", ".", "add_inner_product", "(", "name", "=", "name", ",", "W", "=", "W", ",", "b", "=", "Wb", ",", "input_channels", "=", "nB", ",", "output_channels", "=", "nC", ",", "has_bias", "=", "has_bias", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ")" ]
Convert a dense layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "a", "dense", "layer", "from", "mxnet", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L286-L325
29,086
apple/turicreate
src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py
convert_padding
def convert_padding(net, node, module, builder): """Convert a padding layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) pad = literal_eval(param['pad_width']) pad_left = pad[4] pad_top = pad[5] pad_right = pad[6] pad_bottom = pad[7] if param['mode'] == 'reflect': builder.add_padding( name=name, top=pad_top, bottom=pad_bottom, left=pad_left, right=pad_right, padding_type='reflection', input_name=input_name, output_name=output_name ) else: raise TypeError("Padding type %s not supported" % param['mode'])
python
def convert_padding(net, node, module, builder): """Convert a padding layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) pad = literal_eval(param['pad_width']) pad_left = pad[4] pad_top = pad[5] pad_right = pad[6] pad_bottom = pad[7] if param['mode'] == 'reflect': builder.add_padding( name=name, top=pad_top, bottom=pad_bottom, left=pad_left, right=pad_right, padding_type='reflection', input_name=input_name, output_name=output_name ) else: raise TypeError("Padding type %s not supported" % param['mode'])
[ "def", "convert_padding", "(", "net", ",", "node", ",", "module", ",", "builder", ")", ":", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'name'", "]", "param", "=", "_get_attr", "(", "node", ")", "pad", "=", "literal_eval", "(", "param", "[", "'pad_width'", "]", ")", "pad_left", "=", "pad", "[", "4", "]", "pad_top", "=", "pad", "[", "5", "]", "pad_right", "=", "pad", "[", "6", "]", "pad_bottom", "=", "pad", "[", "7", "]", "if", "param", "[", "'mode'", "]", "==", "'reflect'", ":", "builder", ".", "add_padding", "(", "name", "=", "name", ",", "top", "=", "pad_top", ",", "bottom", "=", "pad_bottom", ",", "left", "=", "pad_left", ",", "right", "=", "pad_right", ",", "padding_type", "=", "'reflection'", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ")", "else", ":", "raise", "TypeError", "(", "\"Padding type %s not supported\"", "%", "param", "[", "'mode'", "]", ")" ]
Convert a padding layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "a", "padding", "layer", "from", "mxnet", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L421-L462
29,087
apple/turicreate
src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py
convert_upsample
def convert_upsample(net, node, module, builder): """Convert a UpSampling layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) inputs = node['inputs'] args, _ = module.get_params() scale = literal_eval(param['scale']) #method if 'sample_type' in param.keys(): method = param['sample_type'] if method == 'nearest': mode = 'NN' elif method == '': mode = 'BILINEAR' builder.add_upsample(name, scaling_factor_h=scale, scaling_factor_w=scale, input_name=input_name, output_name=output_name, mode=mode)
python
def convert_upsample(net, node, module, builder): """Convert a UpSampling layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) inputs = node['inputs'] args, _ = module.get_params() scale = literal_eval(param['scale']) #method if 'sample_type' in param.keys(): method = param['sample_type'] if method == 'nearest': mode = 'NN' elif method == '': mode = 'BILINEAR' builder.add_upsample(name, scaling_factor_h=scale, scaling_factor_w=scale, input_name=input_name, output_name=output_name, mode=mode)
[ "def", "convert_upsample", "(", "net", ",", "node", ",", "module", ",", "builder", ")", ":", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'name'", "]", "param", "=", "_get_attr", "(", "node", ")", "inputs", "=", "node", "[", "'inputs'", "]", "args", ",", "_", "=", "module", ".", "get_params", "(", ")", "scale", "=", "literal_eval", "(", "param", "[", "'scale'", "]", ")", "#method", "if", "'sample_type'", "in", "param", ".", "keys", "(", ")", ":", "method", "=", "param", "[", "'sample_type'", "]", "if", "method", "==", "'nearest'", ":", "mode", "=", "'NN'", "elif", "method", "==", "''", ":", "mode", "=", "'BILINEAR'", "builder", ".", "add_upsample", "(", "name", ",", "scaling_factor_h", "=", "scale", ",", "scaling_factor_w", "=", "scale", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ",", "mode", "=", "mode", ")" ]
Convert a UpSampling layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "a", "UpSampling", "layer", "from", "mxnet", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L704-L738
29,088
apple/turicreate
src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py
convert_custom
def convert_custom(net, node, module, builder): """Convert highly specific ops""" input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) if param['op_type'] == 'special-darknet-maxpool': _add_pooling.add_pooling_with_padding_types( builder=builder, name=name, height=2, width=2, stride_height=1, stride_width=1, layer_type='MAX', padding_type='SAME', is_global=False, same_padding_asymmetry_mode='BOTTOM_RIGHT_HEAVY', input_name=input_name, output_name=output_name ) else: raise TypeError("MXNet layer of type Custom is not supported.")
python
def convert_custom(net, node, module, builder): """Convert highly specific ops""" input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) if param['op_type'] == 'special-darknet-maxpool': _add_pooling.add_pooling_with_padding_types( builder=builder, name=name, height=2, width=2, stride_height=1, stride_width=1, layer_type='MAX', padding_type='SAME', is_global=False, same_padding_asymmetry_mode='BOTTOM_RIGHT_HEAVY', input_name=input_name, output_name=output_name ) else: raise TypeError("MXNet layer of type Custom is not supported.")
[ "def", "convert_custom", "(", "net", ",", "node", ",", "module", ",", "builder", ")", ":", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'name'", "]", "param", "=", "_get_attr", "(", "node", ")", "if", "param", "[", "'op_type'", "]", "==", "'special-darknet-maxpool'", ":", "_add_pooling", ".", "add_pooling_with_padding_types", "(", "builder", "=", "builder", ",", "name", "=", "name", ",", "height", "=", "2", ",", "width", "=", "2", ",", "stride_height", "=", "1", ",", "stride_width", "=", "1", ",", "layer_type", "=", "'MAX'", ",", "padding_type", "=", "'SAME'", ",", "is_global", "=", "False", ",", "same_padding_asymmetry_mode", "=", "'BOTTOM_RIGHT_HEAVY'", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ")", "else", ":", "raise", "TypeError", "(", "\"MXNet layer of type Custom is not supported.\"", ")" ]
Convert highly specific ops
[ "Convert", "highly", "specific", "ops" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L808-L829
29,089
apple/turicreate
src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py
convert_embedding
def convert_embedding(net, node, model, builder): """Convert an embedding layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. model: model An model for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] inputs = node['inputs'] outputs = node['outputs'] arg_params, aux_params = model.get_params() W = arg_params[_get_node_name(net, inputs[1][0])].asnumpy() if not ONE_HOT_ENCODE_HACK: nC, nB = W.shape W = W.T builder.add_embedding(name = name, W = W, b = None, input_dim = nC, output_channels = nB, has_bias = False, input_name = input_name, output_name = output_name) else: W = W.T nC, nB = W.shape builder.add_inner_product(name = name, W = W, b = None, input_channels = nB, output_channels = nC, has_bias = False, input_name = input_name, output_name = output_name)
python
def convert_embedding(net, node, model, builder): """Convert an embedding layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. model: model An model for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] inputs = node['inputs'] outputs = node['outputs'] arg_params, aux_params = model.get_params() W = arg_params[_get_node_name(net, inputs[1][0])].asnumpy() if not ONE_HOT_ENCODE_HACK: nC, nB = W.shape W = W.T builder.add_embedding(name = name, W = W, b = None, input_dim = nC, output_channels = nB, has_bias = False, input_name = input_name, output_name = output_name) else: W = W.T nC, nB = W.shape builder.add_inner_product(name = name, W = W, b = None, input_channels = nB, output_channels = nC, has_bias = False, input_name = input_name, output_name = output_name)
[ "def", "convert_embedding", "(", "net", ",", "node", ",", "model", ",", "builder", ")", ":", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'name'", "]", "inputs", "=", "node", "[", "'inputs'", "]", "outputs", "=", "node", "[", "'outputs'", "]", "arg_params", ",", "aux_params", "=", "model", ".", "get_params", "(", ")", "W", "=", "arg_params", "[", "_get_node_name", "(", "net", ",", "inputs", "[", "1", "]", "[", "0", "]", ")", "]", ".", "asnumpy", "(", ")", "if", "not", "ONE_HOT_ENCODE_HACK", ":", "nC", ",", "nB", "=", "W", ".", "shape", "W", "=", "W", ".", "T", "builder", ".", "add_embedding", "(", "name", "=", "name", ",", "W", "=", "W", ",", "b", "=", "None", ",", "input_dim", "=", "nC", ",", "output_channels", "=", "nB", ",", "has_bias", "=", "False", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ")", "else", ":", "W", "=", "W", ".", "T", "nC", ",", "nB", "=", "W", ".", "shape", "builder", ".", "add_inner_product", "(", "name", "=", "name", ",", "W", "=", "W", ",", "b", "=", "None", ",", "input_channels", "=", "nB", ",", "output_channels", "=", "nC", ",", "has_bias", "=", "False", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ")" ]
Convert an embedding layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. model: model An model for MXNet builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "an", "embedding", "layer", "from", "mxnet", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L831-L875
29,090
apple/turicreate
src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py
convert_scalar_add
def convert_scalar_add(net, node, model, builder): """Convert a scalar add layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. model: model An model for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ import numpy as _np input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) mode = 'ADD' alpha = _np.array([float(param['scalar'])]) builder.add_scale(name = name, input_name = input_name, output_name = output_name, W = _np.array([1.0]), b = alpha, has_bias=True)
python
def convert_scalar_add(net, node, model, builder): """Convert a scalar add layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. model: model An model for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ import numpy as _np input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) mode = 'ADD' alpha = _np.array([float(param['scalar'])]) builder.add_scale(name = name, input_name = input_name, output_name = output_name, W = _np.array([1.0]), b = alpha, has_bias=True)
[ "def", "convert_scalar_add", "(", "net", ",", "node", ",", "model", ",", "builder", ")", ":", "import", "numpy", "as", "_np", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'name'", "]", "param", "=", "_get_attr", "(", "node", ")", "mode", "=", "'ADD'", "alpha", "=", "_np", ".", "array", "(", "[", "float", "(", "param", "[", "'scalar'", "]", ")", "]", ")", "builder", ".", "add_scale", "(", "name", "=", "name", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ",", "W", "=", "_np", ".", "array", "(", "[", "1.0", "]", ")", ",", "b", "=", "alpha", ",", "has_bias", "=", "True", ")" ]
Convert a scalar add layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. model: model An model for MXNet builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "a", "scalar", "add", "layer", "from", "mxnet", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L899-L923
29,091
apple/turicreate
src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py
convert_scalar_multiply
def convert_scalar_multiply(net, node, model, builder): """Convert a scalar multiply layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. model: model An model for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ import numpy as _np input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) alpha = _np.array([float(param['scalar'])]) builder.add_scale(name = name, input_name = input_name, output_name = output_name, W = alpha, has_bias=False, b=None)
python
def convert_scalar_multiply(net, node, model, builder): """Convert a scalar multiply layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. model: model An model for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ import numpy as _np input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) alpha = _np.array([float(param['scalar'])]) builder.add_scale(name = name, input_name = input_name, output_name = output_name, W = alpha, has_bias=False, b=None)
[ "def", "convert_scalar_multiply", "(", "net", ",", "node", ",", "model", ",", "builder", ")", ":", "import", "numpy", "as", "_np", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'name'", "]", "param", "=", "_get_attr", "(", "node", ")", "alpha", "=", "_np", ".", "array", "(", "[", "float", "(", "param", "[", "'scalar'", "]", ")", "]", ")", "builder", ".", "add_scale", "(", "name", "=", "name", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ",", "W", "=", "alpha", ",", "has_bias", "=", "False", ",", "b", "=", "None", ")" ]
Convert a scalar multiply layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. model: model An model for MXNet builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "a", "scalar", "multiply", "layer", "from", "mxnet", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L926-L949
29,092
apple/turicreate
src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py
convert_instancenorm
def convert_instancenorm(net, node, model, builder): """Convert an instance norm layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. model: model An model for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ import numpy as _np input_name, output_name = _get_input_output_name(net, node) name = node['name'] inputs = node['inputs'] outputs = node['outputs'] data_blob_name = _get_node_name(net, inputs[0][0]) gamma_blob_name = _get_node_name(net, inputs[1][0]) beta_blob_name = _get_node_name(net, inputs[2][0]) channels = _get_node_channels(net, inputs[0][0]) bn_output_name = output_name + '_bn_' builder.add_batchnorm( name = name + '_normalize', channels = channels, gamma = _np.ones((channels, )), beta = _np.zeros((channels, )), mean = None, variance = None, input_name = input_name, output_name = bn_output_name, compute_mean_var = True, instance_normalization = True) gamma_input_names = [bn_output_name, gamma_blob_name] gamma_output_name = output_name + '_mult_gamma' builder.add_elementwise(name=name+'_mult_gamma', input_names=gamma_input_names, output_name = gamma_output_name, mode='MULTIPLY', alpha = None) beta_input_names = [gamma_output_name, beta_blob_name] builder.add_elementwise(name=name+'_add_beta', input_names=beta_input_names, output_name = output_name, mode='ADD', alpha=None)
python
def convert_instancenorm(net, node, model, builder): """Convert an instance norm layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. model: model An model for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ import numpy as _np input_name, output_name = _get_input_output_name(net, node) name = node['name'] inputs = node['inputs'] outputs = node['outputs'] data_blob_name = _get_node_name(net, inputs[0][0]) gamma_blob_name = _get_node_name(net, inputs[1][0]) beta_blob_name = _get_node_name(net, inputs[2][0]) channels = _get_node_channels(net, inputs[0][0]) bn_output_name = output_name + '_bn_' builder.add_batchnorm( name = name + '_normalize', channels = channels, gamma = _np.ones((channels, )), beta = _np.zeros((channels, )), mean = None, variance = None, input_name = input_name, output_name = bn_output_name, compute_mean_var = True, instance_normalization = True) gamma_input_names = [bn_output_name, gamma_blob_name] gamma_output_name = output_name + '_mult_gamma' builder.add_elementwise(name=name+'_mult_gamma', input_names=gamma_input_names, output_name = gamma_output_name, mode='MULTIPLY', alpha = None) beta_input_names = [gamma_output_name, beta_blob_name] builder.add_elementwise(name=name+'_add_beta', input_names=beta_input_names, output_name = output_name, mode='ADD', alpha=None)
[ "def", "convert_instancenorm", "(", "net", ",", "node", ",", "model", ",", "builder", ")", ":", "import", "numpy", "as", "_np", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'name'", "]", "inputs", "=", "node", "[", "'inputs'", "]", "outputs", "=", "node", "[", "'outputs'", "]", "data_blob_name", "=", "_get_node_name", "(", "net", ",", "inputs", "[", "0", "]", "[", "0", "]", ")", "gamma_blob_name", "=", "_get_node_name", "(", "net", ",", "inputs", "[", "1", "]", "[", "0", "]", ")", "beta_blob_name", "=", "_get_node_name", "(", "net", ",", "inputs", "[", "2", "]", "[", "0", "]", ")", "channels", "=", "_get_node_channels", "(", "net", ",", "inputs", "[", "0", "]", "[", "0", "]", ")", "bn_output_name", "=", "output_name", "+", "'_bn_'", "builder", ".", "add_batchnorm", "(", "name", "=", "name", "+", "'_normalize'", ",", "channels", "=", "channels", ",", "gamma", "=", "_np", ".", "ones", "(", "(", "channels", ",", ")", ")", ",", "beta", "=", "_np", ".", "zeros", "(", "(", "channels", ",", ")", ")", ",", "mean", "=", "None", ",", "variance", "=", "None", ",", "input_name", "=", "input_name", ",", "output_name", "=", "bn_output_name", ",", "compute_mean_var", "=", "True", ",", "instance_normalization", "=", "True", ")", "gamma_input_names", "=", "[", "bn_output_name", ",", "gamma_blob_name", "]", "gamma_output_name", "=", "output_name", "+", "'_mult_gamma'", "builder", ".", "add_elementwise", "(", "name", "=", "name", "+", "'_mult_gamma'", ",", "input_names", "=", "gamma_input_names", ",", "output_name", "=", "gamma_output_name", ",", "mode", "=", "'MULTIPLY'", ",", "alpha", "=", "None", ")", "beta_input_names", "=", "[", "gamma_output_name", ",", "beta_blob_name", "]", "builder", ".", "add_elementwise", "(", "name", "=", "name", "+", "'_add_beta'", ",", "input_names", "=", "beta_input_names", ",", "output_name", "=", "output_name", ",", "mode", "=", "'ADD'", ",", "alpha", "=", "None", ")" ]
Convert an instance norm layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. model: model An model for MXNet builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "an", "instance", "norm", "layer", "from", "mxnet", "to", "coreml", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L976-L1026
29,093
apple/turicreate
src/unity/python/turicreate/util/__init__.py
_get_aws_credentials
def _get_aws_credentials(): """ Returns the values stored in the AWS credential environment variables. Returns the value stored in the AWS_ACCESS_KEY_ID environment variable and the value stored in the AWS_SECRET_ACCESS_KEY environment variable. Returns ------- out : tuple [string] The first string of the tuple is the value of the AWS_ACCESS_KEY_ID environment variable. The second string of the tuple is the value of the AWS_SECRET_ACCESS_KEY environment variable. Examples -------- >>> turicreate.aws.get_credentials() ('RBZH792CTQPP7T435BGQ', '7x2hMqplWsLpU/qQCN6xAPKcmWo46TlPJXYTvKcv') """ if (not 'AWS_ACCESS_KEY_ID' in _os.environ): raise KeyError('No access key found. Please set the environment variable AWS_ACCESS_KEY_ID.') if (not 'AWS_SECRET_ACCESS_KEY' in _os.environ): raise KeyError('No secret key found. Please set the environment variable AWS_SECRET_ACCESS_KEY.') return (_os.environ['AWS_ACCESS_KEY_ID'], _os.environ['AWS_SECRET_ACCESS_KEY'])
python
def _get_aws_credentials(): """ Returns the values stored in the AWS credential environment variables. Returns the value stored in the AWS_ACCESS_KEY_ID environment variable and the value stored in the AWS_SECRET_ACCESS_KEY environment variable. Returns ------- out : tuple [string] The first string of the tuple is the value of the AWS_ACCESS_KEY_ID environment variable. The second string of the tuple is the value of the AWS_SECRET_ACCESS_KEY environment variable. Examples -------- >>> turicreate.aws.get_credentials() ('RBZH792CTQPP7T435BGQ', '7x2hMqplWsLpU/qQCN6xAPKcmWo46TlPJXYTvKcv') """ if (not 'AWS_ACCESS_KEY_ID' in _os.environ): raise KeyError('No access key found. Please set the environment variable AWS_ACCESS_KEY_ID.') if (not 'AWS_SECRET_ACCESS_KEY' in _os.environ): raise KeyError('No secret key found. Please set the environment variable AWS_SECRET_ACCESS_KEY.') return (_os.environ['AWS_ACCESS_KEY_ID'], _os.environ['AWS_SECRET_ACCESS_KEY'])
[ "def", "_get_aws_credentials", "(", ")", ":", "if", "(", "not", "'AWS_ACCESS_KEY_ID'", "in", "_os", ".", "environ", ")", ":", "raise", "KeyError", "(", "'No access key found. Please set the environment variable AWS_ACCESS_KEY_ID.'", ")", "if", "(", "not", "'AWS_SECRET_ACCESS_KEY'", "in", "_os", ".", "environ", ")", ":", "raise", "KeyError", "(", "'No secret key found. Please set the environment variable AWS_SECRET_ACCESS_KEY.'", ")", "return", "(", "_os", ".", "environ", "[", "'AWS_ACCESS_KEY_ID'", "]", ",", "_os", ".", "environ", "[", "'AWS_SECRET_ACCESS_KEY'", "]", ")" ]
Returns the values stored in the AWS credential environment variables. Returns the value stored in the AWS_ACCESS_KEY_ID environment variable and the value stored in the AWS_SECRET_ACCESS_KEY environment variable. Returns ------- out : tuple [string] The first string of the tuple is the value of the AWS_ACCESS_KEY_ID environment variable. The second string of the tuple is the value of the AWS_SECRET_ACCESS_KEY environment variable. Examples -------- >>> turicreate.aws.get_credentials() ('RBZH792CTQPP7T435BGQ', '7x2hMqplWsLpU/qQCN6xAPKcmWo46TlPJXYTvKcv')
[ "Returns", "the", "values", "stored", "in", "the", "AWS", "credential", "environment", "variables", ".", "Returns", "the", "value", "stored", "in", "the", "AWS_ACCESS_KEY_ID", "environment", "variable", "and", "the", "value", "stored", "in", "the", "AWS_SECRET_ACCESS_KEY", "environment", "variable", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L47-L70
29,094
apple/turicreate
src/unity/python/turicreate/util/__init__.py
is_directory_archive
def is_directory_archive(path): """ Utility function that returns True if the path provided is a directory that has an SFrame or SGraph in it. SFrames are written to disk as a directory archive, this function identifies if a given directory is an archive for an SFrame. Parameters ---------- path : string Directory to evaluate. Returns ------- True if path provided is an archive location, False otherwise """ if path is None: return False if not _os.path.isdir(path): return False ini_path = '/'.join([_convert_slashes(path), 'dir_archive.ini']) if not _os.path.exists(ini_path): return False if _os.path.isfile(ini_path): return True return False
python
def is_directory_archive(path): """ Utility function that returns True if the path provided is a directory that has an SFrame or SGraph in it. SFrames are written to disk as a directory archive, this function identifies if a given directory is an archive for an SFrame. Parameters ---------- path : string Directory to evaluate. Returns ------- True if path provided is an archive location, False otherwise """ if path is None: return False if not _os.path.isdir(path): return False ini_path = '/'.join([_convert_slashes(path), 'dir_archive.ini']) if not _os.path.exists(ini_path): return False if _os.path.isfile(ini_path): return True return False
[ "def", "is_directory_archive", "(", "path", ")", ":", "if", "path", "is", "None", ":", "return", "False", "if", "not", "_os", ".", "path", ".", "isdir", "(", "path", ")", ":", "return", "False", "ini_path", "=", "'/'", ".", "join", "(", "[", "_convert_slashes", "(", "path", ")", ",", "'dir_archive.ini'", "]", ")", "if", "not", "_os", ".", "path", ".", "exists", "(", "ini_path", ")", ":", "return", "False", "if", "_os", ".", "path", ".", "isfile", "(", "ini_path", ")", ":", "return", "True", "return", "False" ]
Utility function that returns True if the path provided is a directory that has an SFrame or SGraph in it. SFrames are written to disk as a directory archive, this function identifies if a given directory is an archive for an SFrame. Parameters ---------- path : string Directory to evaluate. Returns ------- True if path provided is an archive location, False otherwise
[ "Utility", "function", "that", "returns", "True", "if", "the", "path", "provided", "is", "a", "directory", "that", "has", "an", "SFrame", "or", "SGraph", "in", "it", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L152-L181
29,095
apple/turicreate
src/unity/python/turicreate/util/__init__.py
get_archive_type
def get_archive_type(path): """ Returns the contents type for the provided archive path. Parameters ---------- path : string Directory to evaluate. Returns ------- Returns a string of: sframe, sgraph, raises TypeError for anything else """ if not is_directory_archive(path): raise TypeError('Unable to determine the type of archive at path: %s' % path) try: ini_path = '/'.join([_convert_slashes(path), 'dir_archive.ini']) parser = _ConfigParser.SafeConfigParser() parser.read(ini_path) contents = parser.get('metadata', 'contents') return contents except Exception as e: raise TypeError('Unable to determine type of archive for path: %s' % path, e)
python
def get_archive_type(path): """ Returns the contents type for the provided archive path. Parameters ---------- path : string Directory to evaluate. Returns ------- Returns a string of: sframe, sgraph, raises TypeError for anything else """ if not is_directory_archive(path): raise TypeError('Unable to determine the type of archive at path: %s' % path) try: ini_path = '/'.join([_convert_slashes(path), 'dir_archive.ini']) parser = _ConfigParser.SafeConfigParser() parser.read(ini_path) contents = parser.get('metadata', 'contents') return contents except Exception as e: raise TypeError('Unable to determine type of archive for path: %s' % path, e)
[ "def", "get_archive_type", "(", "path", ")", ":", "if", "not", "is_directory_archive", "(", "path", ")", ":", "raise", "TypeError", "(", "'Unable to determine the type of archive at path: %s'", "%", "path", ")", "try", ":", "ini_path", "=", "'/'", ".", "join", "(", "[", "_convert_slashes", "(", "path", ")", ",", "'dir_archive.ini'", "]", ")", "parser", "=", "_ConfigParser", ".", "SafeConfigParser", "(", ")", "parser", ".", "read", "(", "ini_path", ")", "contents", "=", "parser", ".", "get", "(", "'metadata'", ",", "'contents'", ")", "return", "contents", "except", "Exception", "as", "e", ":", "raise", "TypeError", "(", "'Unable to determine type of archive for path: %s'", "%", "path", ",", "e", ")" ]
Returns the contents type for the provided archive path. Parameters ---------- path : string Directory to evaluate. Returns ------- Returns a string of: sframe, sgraph, raises TypeError for anything else
[ "Returns", "the", "contents", "type", "for", "the", "provided", "archive", "path", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L183-L207
29,096
apple/turicreate
src/unity/python/turicreate/util/__init__.py
crossproduct
def crossproduct(d): """ Create an SFrame containing the crossproduct of all provided options. Parameters ---------- d : dict Each key is the name of an option, and each value is a list of the possible values for that option. Returns ------- out : SFrame There will be a column for each key in the provided dictionary, and a row for each unique combination of all values. Example ------- settings = {'argument_1':[0, 1], 'argument_2':['a', 'b', 'c']} print crossproduct(settings) +------------+------------+ | argument_2 | argument_1 | +------------+------------+ | a | 0 | | a | 1 | | b | 0 | | b | 1 | | c | 0 | | c | 1 | +------------+------------+ [6 rows x 2 columns] """ from .. import SArray d = [list(zip(list(d.keys()), x)) for x in _itertools.product(*list(d.values()))] sa = [{k:v for (k,v) in x} for x in d] return SArray(sa).unpack(column_name_prefix='')
python
def crossproduct(d): """ Create an SFrame containing the crossproduct of all provided options. Parameters ---------- d : dict Each key is the name of an option, and each value is a list of the possible values for that option. Returns ------- out : SFrame There will be a column for each key in the provided dictionary, and a row for each unique combination of all values. Example ------- settings = {'argument_1':[0, 1], 'argument_2':['a', 'b', 'c']} print crossproduct(settings) +------------+------------+ | argument_2 | argument_1 | +------------+------------+ | a | 0 | | a | 1 | | b | 0 | | b | 1 | | c | 0 | | c | 1 | +------------+------------+ [6 rows x 2 columns] """ from .. import SArray d = [list(zip(list(d.keys()), x)) for x in _itertools.product(*list(d.values()))] sa = [{k:v for (k,v) in x} for x in d] return SArray(sa).unpack(column_name_prefix='')
[ "def", "crossproduct", "(", "d", ")", ":", "from", ".", ".", "import", "SArray", "d", "=", "[", "list", "(", "zip", "(", "list", "(", "d", ".", "keys", "(", ")", ")", ",", "x", ")", ")", "for", "x", "in", "_itertools", ".", "product", "(", "*", "list", "(", "d", ".", "values", "(", ")", ")", ")", "]", "sa", "=", "[", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "x", "}", "for", "x", "in", "d", "]", "return", "SArray", "(", "sa", ")", ".", "unpack", "(", "column_name_prefix", "=", "''", ")" ]
Create an SFrame containing the crossproduct of all provided options. Parameters ---------- d : dict Each key is the name of an option, and each value is a list of the possible values for that option. Returns ------- out : SFrame There will be a column for each key in the provided dictionary, and a row for each unique combination of all values. Example ------- settings = {'argument_1':[0, 1], 'argument_2':['a', 'b', 'c']} print crossproduct(settings) +------------+------------+ | argument_2 | argument_1 | +------------+------------+ | a | 0 | | a | 1 | | b | 0 | | b | 1 | | c | 0 | | c | 1 | +------------+------------+ [6 rows x 2 columns]
[ "Create", "an", "SFrame", "containing", "the", "crossproduct", "of", "all", "provided", "options", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L209-L246
29,097
apple/turicreate
src/unity/python/turicreate/util/__init__.py
_assert_sframe_equal
def _assert_sframe_equal(sf1, sf2, check_column_names=True, check_column_order=True, check_row_order=True, float_column_delta=None): """ Assert the two SFrames are equal. The default behavior of this function uses the strictest possible definition of equality, where all columns must be in the same order, with the same names and have the same data in the same order. Each of these stipulations can be relaxed individually and in concert with another, with the exception of `check_column_order` and `check_column_names`, we must use one of these to determine which columns to compare with one another. Parameters ---------- sf1 : SFrame sf2 : SFrame check_column_names : bool If true, assert if the data values in two columns are the same, but they have different names. If False, column order is used to determine which columns to compare. check_column_order : bool If true, assert if the data values in two columns are the same, but are not in the same column position (one is the i-th column and the other is the j-th column, i != j). If False, column names are used to determine which columns to compare. check_row_order : bool If true, assert if all rows in the first SFrame exist in the second SFrame, but they are not in the same order. float_column_delta : float The acceptable delta that two float values can be and still be considered "equal". When this is None, only exact equality is accepted. This is the default behavior since columns of all Nones are often of float type. Applies to all float columns. """ from .. import SFrame as _SFrame if (type(sf1) is not _SFrame) or (type(sf2) is not _SFrame): raise TypeError("Cannot function on types other than SFrames.") if not check_column_order and not check_column_names: raise ValueError("Cannot ignore both column order and column names.") sf1.__materialize__() sf2.__materialize__() if sf1.num_columns() != sf2.num_columns(): raise AssertionError("Number of columns mismatched: " + str(sf1.num_columns()) + " != " + str(sf2.num_columns())) s1_names = sf1.column_names() s2_names = sf2.column_names() sorted_s1_names = sorted(s1_names) sorted_s2_names = sorted(s2_names) if check_column_names: if (check_column_order and (s1_names != s2_names)) or (sorted_s1_names != sorted_s2_names): raise AssertionError("SFrame does not have same column names: " + str(sf1.column_names()) + " != " + str(sf2.column_names())) if sf1.num_rows() != sf2.num_rows(): raise AssertionError("Number of rows mismatched: " + str(sf1.num_rows()) + " != " + str(sf2.num_rows())) if not check_row_order and (sf1.num_rows() > 1): sf1 = sf1.sort(s1_names) sf2 = sf2.sort(s2_names) names_to_check = None if check_column_names: names_to_check = list(zip(sorted_s1_names, sorted_s2_names)) else: names_to_check = list(zip(s1_names, s2_names)) for i in names_to_check: col1 = sf1[i[0]] col2 = sf2[i[1]] if col1.dtype != col2.dtype: raise AssertionError("Columns " + str(i) + " types mismatched.") compare_ary = None if col1.dtype == float and float_column_delta is not None: dt = float_column_delta compare_ary = ((col1 > col2-dt) & (col1 < col2+dt)) else: compare_ary = (sf1[i[0]] == sf2[i[1]]) if not compare_ary.all(): count = 0 for j in compare_ary: if not j: first_row = count break count += 1 raise AssertionError("Columns " + str(i) + " are not equal! First differing element is at row " + str(first_row) + ": " + str((col1[first_row],col2[first_row])))
python
def _assert_sframe_equal(sf1, sf2, check_column_names=True, check_column_order=True, check_row_order=True, float_column_delta=None): """ Assert the two SFrames are equal. The default behavior of this function uses the strictest possible definition of equality, where all columns must be in the same order, with the same names and have the same data in the same order. Each of these stipulations can be relaxed individually and in concert with another, with the exception of `check_column_order` and `check_column_names`, we must use one of these to determine which columns to compare with one another. Parameters ---------- sf1 : SFrame sf2 : SFrame check_column_names : bool If true, assert if the data values in two columns are the same, but they have different names. If False, column order is used to determine which columns to compare. check_column_order : bool If true, assert if the data values in two columns are the same, but are not in the same column position (one is the i-th column and the other is the j-th column, i != j). If False, column names are used to determine which columns to compare. check_row_order : bool If true, assert if all rows in the first SFrame exist in the second SFrame, but they are not in the same order. float_column_delta : float The acceptable delta that two float values can be and still be considered "equal". When this is None, only exact equality is accepted. This is the default behavior since columns of all Nones are often of float type. Applies to all float columns. """ from .. import SFrame as _SFrame if (type(sf1) is not _SFrame) or (type(sf2) is not _SFrame): raise TypeError("Cannot function on types other than SFrames.") if not check_column_order and not check_column_names: raise ValueError("Cannot ignore both column order and column names.") sf1.__materialize__() sf2.__materialize__() if sf1.num_columns() != sf2.num_columns(): raise AssertionError("Number of columns mismatched: " + str(sf1.num_columns()) + " != " + str(sf2.num_columns())) s1_names = sf1.column_names() s2_names = sf2.column_names() sorted_s1_names = sorted(s1_names) sorted_s2_names = sorted(s2_names) if check_column_names: if (check_column_order and (s1_names != s2_names)) or (sorted_s1_names != sorted_s2_names): raise AssertionError("SFrame does not have same column names: " + str(sf1.column_names()) + " != " + str(sf2.column_names())) if sf1.num_rows() != sf2.num_rows(): raise AssertionError("Number of rows mismatched: " + str(sf1.num_rows()) + " != " + str(sf2.num_rows())) if not check_row_order and (sf1.num_rows() > 1): sf1 = sf1.sort(s1_names) sf2 = sf2.sort(s2_names) names_to_check = None if check_column_names: names_to_check = list(zip(sorted_s1_names, sorted_s2_names)) else: names_to_check = list(zip(s1_names, s2_names)) for i in names_to_check: col1 = sf1[i[0]] col2 = sf2[i[1]] if col1.dtype != col2.dtype: raise AssertionError("Columns " + str(i) + " types mismatched.") compare_ary = None if col1.dtype == float and float_column_delta is not None: dt = float_column_delta compare_ary = ((col1 > col2-dt) & (col1 < col2+dt)) else: compare_ary = (sf1[i[0]] == sf2[i[1]]) if not compare_ary.all(): count = 0 for j in compare_ary: if not j: first_row = count break count += 1 raise AssertionError("Columns " + str(i) + " are not equal! First differing element is at row " + str(first_row) + ": " + str((col1[first_row],col2[first_row])))
[ "def", "_assert_sframe_equal", "(", "sf1", ",", "sf2", ",", "check_column_names", "=", "True", ",", "check_column_order", "=", "True", ",", "check_row_order", "=", "True", ",", "float_column_delta", "=", "None", ")", ":", "from", ".", ".", "import", "SFrame", "as", "_SFrame", "if", "(", "type", "(", "sf1", ")", "is", "not", "_SFrame", ")", "or", "(", "type", "(", "sf2", ")", "is", "not", "_SFrame", ")", ":", "raise", "TypeError", "(", "\"Cannot function on types other than SFrames.\"", ")", "if", "not", "check_column_order", "and", "not", "check_column_names", ":", "raise", "ValueError", "(", "\"Cannot ignore both column order and column names.\"", ")", "sf1", ".", "__materialize__", "(", ")", "sf2", ".", "__materialize__", "(", ")", "if", "sf1", ".", "num_columns", "(", ")", "!=", "sf2", ".", "num_columns", "(", ")", ":", "raise", "AssertionError", "(", "\"Number of columns mismatched: \"", "+", "str", "(", "sf1", ".", "num_columns", "(", ")", ")", "+", "\" != \"", "+", "str", "(", "sf2", ".", "num_columns", "(", ")", ")", ")", "s1_names", "=", "sf1", ".", "column_names", "(", ")", "s2_names", "=", "sf2", ".", "column_names", "(", ")", "sorted_s1_names", "=", "sorted", "(", "s1_names", ")", "sorted_s2_names", "=", "sorted", "(", "s2_names", ")", "if", "check_column_names", ":", "if", "(", "check_column_order", "and", "(", "s1_names", "!=", "s2_names", ")", ")", "or", "(", "sorted_s1_names", "!=", "sorted_s2_names", ")", ":", "raise", "AssertionError", "(", "\"SFrame does not have same column names: \"", "+", "str", "(", "sf1", ".", "column_names", "(", ")", ")", "+", "\" != \"", "+", "str", "(", "sf2", ".", "column_names", "(", ")", ")", ")", "if", "sf1", ".", "num_rows", "(", ")", "!=", "sf2", ".", "num_rows", "(", ")", ":", "raise", "AssertionError", "(", "\"Number of rows mismatched: \"", "+", "str", "(", "sf1", ".", "num_rows", "(", ")", ")", "+", "\" != \"", "+", "str", "(", "sf2", ".", "num_rows", "(", ")", ")", ")", "if", "not", "check_row_order", "and", "(", "sf1", ".", "num_rows", "(", ")", ">", "1", ")", ":", "sf1", "=", "sf1", ".", "sort", "(", "s1_names", ")", "sf2", "=", "sf2", ".", "sort", "(", "s2_names", ")", "names_to_check", "=", "None", "if", "check_column_names", ":", "names_to_check", "=", "list", "(", "zip", "(", "sorted_s1_names", ",", "sorted_s2_names", ")", ")", "else", ":", "names_to_check", "=", "list", "(", "zip", "(", "s1_names", ",", "s2_names", ")", ")", "for", "i", "in", "names_to_check", ":", "col1", "=", "sf1", "[", "i", "[", "0", "]", "]", "col2", "=", "sf2", "[", "i", "[", "1", "]", "]", "if", "col1", ".", "dtype", "!=", "col2", ".", "dtype", ":", "raise", "AssertionError", "(", "\"Columns \"", "+", "str", "(", "i", ")", "+", "\" types mismatched.\"", ")", "compare_ary", "=", "None", "if", "col1", ".", "dtype", "==", "float", "and", "float_column_delta", "is", "not", "None", ":", "dt", "=", "float_column_delta", "compare_ary", "=", "(", "(", "col1", ">", "col2", "-", "dt", ")", "&", "(", "col1", "<", "col2", "+", "dt", ")", ")", "else", ":", "compare_ary", "=", "(", "sf1", "[", "i", "[", "0", "]", "]", "==", "sf2", "[", "i", "[", "1", "]", "]", ")", "if", "not", "compare_ary", ".", "all", "(", ")", ":", "count", "=", "0", "for", "j", "in", "compare_ary", ":", "if", "not", "j", ":", "first_row", "=", "count", "break", "count", "+=", "1", "raise", "AssertionError", "(", "\"Columns \"", "+", "str", "(", "i", ")", "+", "\" are not equal! First differing element is at row \"", "+", "str", "(", "first_row", ")", "+", "\": \"", "+", "str", "(", "(", "col1", "[", "first_row", "]", ",", "col2", "[", "first_row", "]", ")", ")", ")" ]
Assert the two SFrames are equal. The default behavior of this function uses the strictest possible definition of equality, where all columns must be in the same order, with the same names and have the same data in the same order. Each of these stipulations can be relaxed individually and in concert with another, with the exception of `check_column_order` and `check_column_names`, we must use one of these to determine which columns to compare with one another. Parameters ---------- sf1 : SFrame sf2 : SFrame check_column_names : bool If true, assert if the data values in two columns are the same, but they have different names. If False, column order is used to determine which columns to compare. check_column_order : bool If true, assert if the data values in two columns are the same, but are not in the same column position (one is the i-th column and the other is the j-th column, i != j). If False, column names are used to determine which columns to compare. check_row_order : bool If true, assert if all rows in the first SFrame exist in the second SFrame, but they are not in the same order. float_column_delta : float The acceptable delta that two float values can be and still be considered "equal". When this is None, only exact equality is accepted. This is the default behavior since columns of all Nones are often of float type. Applies to all float columns.
[ "Assert", "the", "two", "SFrames", "are", "equal", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L263-L365
29,098
apple/turicreate
src/unity/python/turicreate/util/__init__.py
_make_temp_directory
def _make_temp_directory(prefix): ''' Generate a temporary directory that would not live beyond the lifetime of unity_server. Caller is expected to clean up the temp file as soon as the directory is no longer needed. But the directory will be cleaned as unity_server restarts ''' temp_dir = _make_temp_filename(prefix=str(prefix)) _os.makedirs(temp_dir) return temp_dir
python
def _make_temp_directory(prefix): ''' Generate a temporary directory that would not live beyond the lifetime of unity_server. Caller is expected to clean up the temp file as soon as the directory is no longer needed. But the directory will be cleaned as unity_server restarts ''' temp_dir = _make_temp_filename(prefix=str(prefix)) _os.makedirs(temp_dir) return temp_dir
[ "def", "_make_temp_directory", "(", "prefix", ")", ":", "temp_dir", "=", "_make_temp_filename", "(", "prefix", "=", "str", "(", "prefix", ")", ")", "_os", ".", "makedirs", "(", "temp_dir", ")", "return", "temp_dir" ]
Generate a temporary directory that would not live beyond the lifetime of unity_server. Caller is expected to clean up the temp file as soon as the directory is no longer needed. But the directory will be cleaned as unity_server restarts
[ "Generate", "a", "temporary", "directory", "that", "would", "not", "live", "beyond", "the", "lifetime", "of", "unity_server", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L382-L392
29,099
apple/turicreate
src/unity/python/turicreate/util/__init__.py
_make_temp_filename
def _make_temp_filename(prefix): ''' Generate a temporary file that would not live beyond the lifetime of unity_server. Caller is expected to clean up the temp file as soon as the file is no longer needed. But temp files created using this method will be cleaned up when unity_server restarts ''' temp_location = _get_temp_file_location() temp_file_name = '/'.join([temp_location, str(prefix)+str(_uuid.uuid4())]) return temp_file_name
python
def _make_temp_filename(prefix): ''' Generate a temporary file that would not live beyond the lifetime of unity_server. Caller is expected to clean up the temp file as soon as the file is no longer needed. But temp files created using this method will be cleaned up when unity_server restarts ''' temp_location = _get_temp_file_location() temp_file_name = '/'.join([temp_location, str(prefix)+str(_uuid.uuid4())]) return temp_file_name
[ "def", "_make_temp_filename", "(", "prefix", ")", ":", "temp_location", "=", "_get_temp_file_location", "(", ")", "temp_file_name", "=", "'/'", ".", "join", "(", "[", "temp_location", ",", "str", "(", "prefix", ")", "+", "str", "(", "_uuid", ".", "uuid4", "(", ")", ")", "]", ")", "return", "temp_file_name" ]
Generate a temporary file that would not live beyond the lifetime of unity_server. Caller is expected to clean up the temp file as soon as the file is no longer needed. But temp files created using this method will be cleaned up when unity_server restarts
[ "Generate", "a", "temporary", "file", "that", "would", "not", "live", "beyond", "the", "lifetime", "of", "unity_server", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L394-L405