Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
is_pointer
(type_)
returns True, if type represents C++ pointer type, False otherwise
returns True, if type represents C++ pointer type, False otherwise
def is_pointer(type_): """returns True, if type represents C++ pointer type, False otherwise""" return does_match_definition(type_, cpptypes.pointer_t, (cpptypes.const_t, cpptypes.volatile_t)) \ or does_match_definition(type_, cpptypes.pointer_t, (cpptypes.volatile_t, cpptypes.const_t))
[ "def", "is_pointer", "(", "type_", ")", ":", "return", "does_match_definition", "(", "type_", ",", "cpptypes", ".", "pointer_t", ",", "(", "cpptypes", ".", "const_t", ",", "cpptypes", ".", "volatile_t", ")", ")", "or", "does_match_definition", "(", "type_", ",", "cpptypes", ".", "pointer_t", ",", "(", "cpptypes", ".", "volatile_t", ",", "cpptypes", ".", "const_t", ")", ")" ]
[ 229, 0 ]
[ 236, 73 ]
python
en
['en', 'en', 'en']
True
is_calldef_pointer
(type_)
returns True, if type represents pointer to free/member function, False otherwise
returns True, if type represents pointer to free/member function, False otherwise
def is_calldef_pointer(type_): """returns True, if type represents pointer to free/member function, False otherwise""" if not is_pointer(type_): return False nake_type = remove_alias(type_) nake_type = remove_cv(nake_type) return isinstance(nake_type, cpptypes.compound_t) \ and isinstance(nake_type.base, cpptypes.calldef_type_t)
[ "def", "is_calldef_pointer", "(", "type_", ")", ":", "if", "not", "is_pointer", "(", "type_", ")", ":", "return", "False", "nake_type", "=", "remove_alias", "(", "type_", ")", "nake_type", "=", "remove_cv", "(", "nake_type", ")", "return", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "compound_t", ")", "and", "isinstance", "(", "nake_type", ".", "base", ",", "cpptypes", ".", "calldef_type_t", ")" ]
[ 239, 0 ]
[ 247, 63 ]
python
en
['en', 'en', 'en']
True
remove_pointer
(type_)
removes pointer from the type definition If type is not pointer type, it will be returned as is.
removes pointer from the type definition
def remove_pointer(type_): """removes pointer from the type definition If type is not pointer type, it will be returned as is. """ nake_type = remove_alias(type_) if not is_pointer(nake_type): return type_ elif isinstance(nake_type, cpptypes.volatile_t) and \ isinstance(nake_type.base, cpptypes.pointer_t): return cpptypes.volatile_t(nake_type.base.base) elif isinstance(nake_type, cpptypes.const_t) and \ isinstance(nake_type.base, cpptypes.pointer_t): return cpptypes.const_t(nake_type.base.base) elif isinstance(nake_type, cpptypes.volatile_t) \ and isinstance(nake_type.base, cpptypes.const_t) \ and isinstance(nake_type.base.base, cpptypes.pointer_t): return ( cpptypes.volatile_t(cpptypes.const_t(nake_type.base.base.base)) ) else: return nake_type.base
[ "def", "remove_pointer", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "if", "not", "is_pointer", "(", "nake_type", ")", ":", "return", "type_", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "volatile_t", ")", "and", "isinstance", "(", "nake_type", ".", "base", ",", "cpptypes", ".", "pointer_t", ")", ":", "return", "cpptypes", ".", "volatile_t", "(", "nake_type", ".", "base", ".", "base", ")", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "const_t", ")", "and", "isinstance", "(", "nake_type", ".", "base", ",", "cpptypes", ".", "pointer_t", ")", ":", "return", "cpptypes", ".", "const_t", "(", "nake_type", ".", "base", ".", "base", ")", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "volatile_t", ")", "and", "isinstance", "(", "nake_type", ".", "base", ",", "cpptypes", ".", "const_t", ")", "and", "isinstance", "(", "nake_type", ".", "base", ".", "base", ",", "cpptypes", ".", "pointer_t", ")", ":", "return", "(", "cpptypes", ".", "volatile_t", "(", "cpptypes", ".", "const_t", "(", "nake_type", ".", "base", ".", "base", ".", "base", ")", ")", ")", "else", ":", "return", "nake_type", ".", "base" ]
[ 250, 0 ]
[ 271, 29 ]
python
en
['en', 'en', 'en']
True
is_reference
(type_)
returns True, if type represents C++ reference type, False otherwise
returns True, if type represents C++ reference type, False otherwise
def is_reference(type_): """returns True, if type represents C++ reference type, False otherwise""" nake_type = remove_alias(type_) return isinstance(nake_type, cpptypes.reference_t)
[ "def", "is_reference", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "return", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "reference_t", ")" ]
[ 274, 0 ]
[ 277, 54 ]
python
en
['en', 'en', 'en']
True
is_array
(type_)
returns True, if type represents C++ array type, False otherwise
returns True, if type represents C++ array type, False otherwise
def is_array(type_): """returns True, if type represents C++ array type, False otherwise""" nake_type = remove_alias(type_) nake_type = remove_reference(nake_type) nake_type = remove_cv(nake_type) return isinstance(nake_type, cpptypes.array_t)
[ "def", "is_array", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "nake_type", "=", "remove_reference", "(", "nake_type", ")", "nake_type", "=", "remove_cv", "(", "nake_type", ")", "return", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "array_t", ")" ]
[ 280, 0 ]
[ 285, 50 ]
python
en
['en', 'en', 'en']
True
array_size
(type_)
returns array size
returns array size
def array_size(type_): """returns array size""" nake_type = remove_alias(type_) nake_type = remove_reference(nake_type) nake_type = remove_cv(nake_type) assert isinstance(nake_type, cpptypes.array_t) return nake_type.size
[ "def", "array_size", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "nake_type", "=", "remove_reference", "(", "nake_type", ")", "nake_type", "=", "remove_cv", "(", "nake_type", ")", "assert", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "array_t", ")", "return", "nake_type", ".", "size" ]
[ 288, 0 ]
[ 294, 25 ]
python
en
['en', 'hu', 'en']
True
array_item_type
(type_)
returns array item type
returns array item type
def array_item_type(type_): """returns array item type""" if is_array(type_): type_ = remove_alias(type_) type_ = remove_cv(type_) return type_.base elif is_pointer(type_): return remove_pointer(type_) else: raise RuntimeError( "array_item_type functions takes as argument array or pointer " + "types")
[ "def", "array_item_type", "(", "type_", ")", ":", "if", "is_array", "(", "type_", ")", ":", "type_", "=", "remove_alias", "(", "type_", ")", "type_", "=", "remove_cv", "(", "type_", ")", "return", "type_", ".", "base", "elif", "is_pointer", "(", "type_", ")", ":", "return", "remove_pointer", "(", "type_", ")", "else", ":", "raise", "RuntimeError", "(", "\"array_item_type functions takes as argument array or pointer \"", "+", "\"types\"", ")" ]
[ 297, 0 ]
[ 308, 20 ]
python
en
['en', 'sr', 'en']
True
remove_reference
(type_)
removes reference from the type definition If type is not reference type, it will be returned as is.
removes reference from the type definition
def remove_reference(type_): """removes reference from the type definition If type is not reference type, it will be returned as is. """ nake_type = remove_alias(type_) if not is_reference(nake_type): return type_ else: return nake_type.base
[ "def", "remove_reference", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "if", "not", "is_reference", "(", "nake_type", ")", ":", "return", "type_", "else", ":", "return", "nake_type", ".", "base" ]
[ 311, 0 ]
[ 320, 29 ]
python
en
['en', 'en', 'en']
True
is_const
(type_)
returns True, if type represents C++ const type, False otherwise
returns True, if type represents C++ const type, False otherwise
def is_const(type_): """returns True, if type represents C++ const type, False otherwise""" nake_type = remove_alias(type_) if isinstance(nake_type, cpptypes.const_t): return True elif isinstance(nake_type, cpptypes.volatile_t): return is_const(nake_type.base) elif isinstance(nake_type, cpptypes.array_t): return is_const(nake_type.base) return False
[ "def", "is_const", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "if", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "const_t", ")", ":", "return", "True", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "volatile_t", ")", ":", "return", "is_const", "(", "nake_type", ".", "base", ")", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "array_t", ")", ":", "return", "is_const", "(", "nake_type", ".", "base", ")", "return", "False" ]
[ 323, 0 ]
[ 332, 16 ]
python
en
['en', 'en', 'en']
True
remove_const
(type_)
removes const from the type definition If type is not const type, it will be returned as is
removes const from the type definition
def remove_const(type_): """removes const from the type definition If type is not const type, it will be returned as is """ nake_type = remove_alias(type_) if not is_const(nake_type): return type_ else: # Handling for const and volatile qualified types. There is a # difference in behavior between GCCXML and CastXML for cv-qual arrays. # GCCXML produces the following nesting of types: # -> volatile_t(const_t(array_t)) # while CastXML produces the following nesting: # -> array_t(volatile_t(const_t)) # For both cases, we must unwrap the types, remove const_t, and add # back the outer layers if isinstance(nake_type, cpptypes.array_t): is_v = is_volatile(nake_type) if is_v: result_type = nake_type.base.base.base else: result_type = nake_type.base.base if is_v: result_type = cpptypes.volatile_t(result_type) return cpptypes.array_t(result_type, nake_type.size) elif isinstance(nake_type, cpptypes.volatile_t): return cpptypes.volatile_t(nake_type.base.base) return nake_type.base
[ "def", "remove_const", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "if", "not", "is_const", "(", "nake_type", ")", ":", "return", "type_", "else", ":", "# Handling for const and volatile qualified types. There is a", "# difference in behavior between GCCXML and CastXML for cv-qual arrays.", "# GCCXML produces the following nesting of types:", "# -> volatile_t(const_t(array_t))", "# while CastXML produces the following nesting:", "# -> array_t(volatile_t(const_t))", "# For both cases, we must unwrap the types, remove const_t, and add", "# back the outer layers", "if", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "array_t", ")", ":", "is_v", "=", "is_volatile", "(", "nake_type", ")", "if", "is_v", ":", "result_type", "=", "nake_type", ".", "base", ".", "base", ".", "base", "else", ":", "result_type", "=", "nake_type", ".", "base", ".", "base", "if", "is_v", ":", "result_type", "=", "cpptypes", ".", "volatile_t", "(", "result_type", ")", "return", "cpptypes", ".", "array_t", "(", "result_type", ",", "nake_type", ".", "size", ")", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "volatile_t", ")", ":", "return", "cpptypes", ".", "volatile_t", "(", "nake_type", ".", "base", ".", "base", ")", "return", "nake_type", ".", "base" ]
[ 335, 0 ]
[ 366, 29 ]
python
en
['en', 'en', 'en']
True
remove_declarated
(type_)
removes type-declaration class-binder :class:`declarated_t` from the `type_` If `type_` is not :class:`declarated_t`, it will be returned as is
removes type-declaration class-binder :class:`declarated_t` from the `type_`
def remove_declarated(type_): """removes type-declaration class-binder :class:`declarated_t` from the `type_` If `type_` is not :class:`declarated_t`, it will be returned as is """ type_ = remove_alias(type_) if isinstance(type_, cpptypes.elaborated_t): type_ = type_.base if isinstance(type_, cpptypes.declarated_t): type_ = type_.declaration return type_
[ "def", "remove_declarated", "(", "type_", ")", ":", "type_", "=", "remove_alias", "(", "type_", ")", "if", "isinstance", "(", "type_", ",", "cpptypes", ".", "elaborated_t", ")", ":", "type_", "=", "type_", ".", "base", "if", "isinstance", "(", "type_", ",", "cpptypes", ".", "declarated_t", ")", ":", "type_", "=", "type_", ".", "declaration", "return", "type_" ]
[ 369, 0 ]
[ 380, 16 ]
python
en
['en', 'en', 'en']
True
is_same
(type1, type2)
returns True, if type1 and type2 are same types
returns True, if type1 and type2 are same types
def is_same(type1, type2): """returns True, if type1 and type2 are same types""" nake_type1 = remove_declarated(type1) nake_type2 = remove_declarated(type2) return nake_type1 == nake_type2
[ "def", "is_same", "(", "type1", ",", "type2", ")", ":", "nake_type1", "=", "remove_declarated", "(", "type1", ")", "nake_type2", "=", "remove_declarated", "(", "type2", ")", "return", "nake_type1", "==", "nake_type2" ]
[ 383, 0 ]
[ 387, 35 ]
python
en
['en', 'en', 'en']
True
is_elaborated
(type_)
returns True, if type represents C++ elaborated type, False otherwise
returns True, if type represents C++ elaborated type, False otherwise
def is_elaborated(type_): """returns True, if type represents C++ elaborated type, False otherwise""" nake_type = remove_alias(type_) if isinstance(nake_type, cpptypes.elaborated_t): return True elif isinstance(nake_type, cpptypes.reference_t): return is_elaborated(nake_type.base) elif isinstance(nake_type, cpptypes.pointer_t): return is_elaborated(nake_type.base) elif isinstance(nake_type, cpptypes.volatile_t): return is_elaborated(nake_type.base) elif isinstance(nake_type, cpptypes.const_t): return is_elaborated(nake_type.base) return False
[ "def", "is_elaborated", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "if", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "elaborated_t", ")", ":", "return", "True", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "reference_t", ")", ":", "return", "is_elaborated", "(", "nake_type", ".", "base", ")", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "pointer_t", ")", ":", "return", "is_elaborated", "(", "nake_type", ".", "base", ")", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "volatile_t", ")", ":", "return", "is_elaborated", "(", "nake_type", ".", "base", ")", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "const_t", ")", ":", "return", "is_elaborated", "(", "nake_type", ".", "base", ")", "return", "False" ]
[ 390, 0 ]
[ 403, 16 ]
python
en
['en', 'en', 'en']
True
remove_elaborated
(type_)
removes type-declaration class-binder :class:`elaborated_t` from the `type_` If `type_` is not :class:`elaborated_t`, it will be returned as is
removes type-declaration class-binder :class:`elaborated_t` from the `type_`
def remove_elaborated(type_): """removes type-declaration class-binder :class:`elaborated_t` from the `type_` If `type_` is not :class:`elaborated_t`, it will be returned as is """ nake_type = remove_alias(type_) if not is_elaborated(nake_type): return type_ else: if isinstance(type_, cpptypes.elaborated_t): type_ = type_.base return type_
[ "def", "remove_elaborated", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "if", "not", "is_elaborated", "(", "nake_type", ")", ":", "return", "type_", "else", ":", "if", "isinstance", "(", "type_", ",", "cpptypes", ".", "elaborated_t", ")", ":", "type_", "=", "type_", ".", "base", "return", "type_" ]
[ 406, 0 ]
[ 418, 16 ]
python
en
['en', 'en', 'en']
True
is_volatile
(type_)
returns True, if type represents C++ volatile type, False otherwise
returns True, if type represents C++ volatile type, False otherwise
def is_volatile(type_): """returns True, if type represents C++ volatile type, False otherwise""" nake_type = remove_alias(type_) if isinstance(nake_type, cpptypes.volatile_t): return True elif isinstance(nake_type, cpptypes.const_t): return is_volatile(nake_type.base) elif isinstance(nake_type, cpptypes.array_t): return is_volatile(nake_type.base) return False
[ "def", "is_volatile", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "if", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "volatile_t", ")", ":", "return", "True", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "const_t", ")", ":", "return", "is_volatile", "(", "nake_type", ".", "base", ")", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "array_t", ")", ":", "return", "is_volatile", "(", "nake_type", ".", "base", ")", "return", "False" ]
[ 421, 0 ]
[ 430, 16 ]
python
en
['en', 'sr', 'en']
True
remove_volatile
(type_)
removes volatile from the type definition If type is not volatile type, it will be returned as is
removes volatile from the type definition
def remove_volatile(type_): """removes volatile from the type definition If type is not volatile type, it will be returned as is """ nake_type = remove_alias(type_) if not is_volatile(nake_type): return type_ else: if isinstance(nake_type, cpptypes.array_t): is_c = is_const(nake_type) if is_c: base_type_ = nake_type.base.base.base else: base_type_ = nake_type.base.base result_type = base_type_ if is_c: result_type = cpptypes.const_t(result_type) return cpptypes.array_t(result_type, nake_type.size) return nake_type.base
[ "def", "remove_volatile", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "if", "not", "is_volatile", "(", "nake_type", ")", ":", "return", "type_", "else", ":", "if", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "array_t", ")", ":", "is_c", "=", "is_const", "(", "nake_type", ")", "if", "is_c", ":", "base_type_", "=", "nake_type", ".", "base", ".", "base", ".", "base", "else", ":", "base_type_", "=", "nake_type", ".", "base", ".", "base", "result_type", "=", "base_type_", "if", "is_c", ":", "result_type", "=", "cpptypes", ".", "const_t", "(", "result_type", ")", "return", "cpptypes", ".", "array_t", "(", "result_type", ",", "nake_type", ".", "size", ")", "return", "nake_type", ".", "base" ]
[ 433, 0 ]
[ 452, 29 ]
python
en
['en', 'en', 'en']
True
remove_cv
(type_)
removes const and volatile from the type definition
removes const and volatile from the type definition
def remove_cv(type_): """removes const and volatile from the type definition""" nake_type = remove_alias(type_) if not is_const(nake_type) and not is_volatile(nake_type): return type_ result = nake_type if is_const(result): result = remove_const(result) if is_volatile(result): result = remove_volatile(result) if is_const(result): result = remove_const(result) return result
[ "def", "remove_cv", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "if", "not", "is_const", "(", "nake_type", ")", "and", "not", "is_volatile", "(", "nake_type", ")", ":", "return", "type_", "result", "=", "nake_type", "if", "is_const", "(", "result", ")", ":", "result", "=", "remove_const", "(", "result", ")", "if", "is_volatile", "(", "result", ")", ":", "result", "=", "remove_volatile", "(", "result", ")", "if", "is_const", "(", "result", ")", ":", "result", "=", "remove_const", "(", "result", ")", "return", "result" ]
[ 455, 0 ]
[ 468, 17 ]
python
en
['en', 'en', 'en']
True
is_fundamental
(type_)
returns True, if type represents C++ fundamental type
returns True, if type represents C++ fundamental type
def is_fundamental(type_): """returns True, if type represents C++ fundamental type""" return does_match_definition( type_, cpptypes.fundamental_t, (cpptypes.const_t, cpptypes.volatile_t)) \ or does_match_definition( type_, cpptypes.fundamental_t, (cpptypes.volatile_t, cpptypes.const_t))
[ "def", "is_fundamental", "(", "type_", ")", ":", "return", "does_match_definition", "(", "type_", ",", "cpptypes", ".", "fundamental_t", ",", "(", "cpptypes", ".", "const_t", ",", "cpptypes", ".", "volatile_t", ")", ")", "or", "does_match_definition", "(", "type_", ",", "cpptypes", ".", "fundamental_t", ",", "(", "cpptypes", ".", "volatile_t", ",", "cpptypes", ".", "const_t", ")", ")" ]
[ 471, 0 ]
[ 480, 52 ]
python
en
['en', 'la', 'en']
True
is_std_string
(type_)
Returns True, if type represents C++ `std::string`, False otherwise.
Returns True, if type represents C++ `std::string`, False otherwise.
def is_std_string(type_): """ Returns True, if type represents C++ `std::string`, False otherwise. """ if utils.is_str(type_): return type_ in string_equivalences else: type_ = remove_alias(type_) type_ = remove_reference(type_) type_ = remove_cv(type_) return type_.decl_string in string_equivalences
[ "def", "is_std_string", "(", "type_", ")", ":", "if", "utils", ".", "is_str", "(", "type_", ")", ":", "return", "type_", "in", "string_equivalences", "else", ":", "type_", "=", "remove_alias", "(", "type_", ")", "type_", "=", "remove_reference", "(", "type_", ")", "type_", "=", "remove_cv", "(", "type_", ")", "return", "type_", ".", "decl_string", "in", "string_equivalences" ]
[ 512, 0 ]
[ 524, 55 ]
python
en
['en', 'error', 'th']
False
is_std_wstring
(type_)
Returns True, if type represents C++ `std::wstring`, False otherwise.
Returns True, if type represents C++ `std::wstring`, False otherwise.
def is_std_wstring(type_): """ Returns True, if type represents C++ `std::wstring`, False otherwise. """ if utils.is_str(type_): return type_ in wstring_equivalences else: type_ = remove_alias(type_) type_ = remove_reference(type_) type_ = remove_cv(type_) return type_.decl_string in wstring_equivalences
[ "def", "is_std_wstring", "(", "type_", ")", ":", "if", "utils", ".", "is_str", "(", "type_", ")", ":", "return", "type_", "in", "wstring_equivalences", "else", ":", "type_", "=", "remove_alias", "(", "type_", ")", "type_", "=", "remove_reference", "(", "type_", ")", "type_", "=", "remove_cv", "(", "type_", ")", "return", "type_", ".", "decl_string", "in", "wstring_equivalences" ]
[ 527, 0 ]
[ 539, 56 ]
python
en
['en', 'error', 'th']
False
is_std_ostream
(type_)
Returns True, if type represents C++ std::ostream, False otherwise.
Returns True, if type represents C++ std::ostream, False otherwise.
def is_std_ostream(type_): """ Returns True, if type represents C++ std::ostream, False otherwise. """ if utils.is_str(type_): return type_ in ostream_equivalences else: type_ = remove_alias(type_) type_ = remove_reference(type_) type_ = remove_cv(type_) return type_.decl_string in ostream_equivalences
[ "def", "is_std_ostream", "(", "type_", ")", ":", "if", "utils", ".", "is_str", "(", "type_", ")", ":", "return", "type_", "in", "ostream_equivalences", "else", ":", "type_", "=", "remove_alias", "(", "type_", ")", "type_", "=", "remove_reference", "(", "type_", ")", "type_", "=", "remove_cv", "(", "type_", ")", "return", "type_", ".", "decl_string", "in", "ostream_equivalences" ]
[ 542, 0 ]
[ 554, 56 ]
python
en
['en', 'error', 'th']
False
is_std_wostream
(type_)
Returns True, if type represents C++ std::wostream, False otherwise.
Returns True, if type represents C++ std::wostream, False otherwise.
def is_std_wostream(type_): """ Returns True, if type represents C++ std::wostream, False otherwise. """ if utils.is_str(type_): return type_ in wostream_equivalences else: type_ = remove_alias(type_) type_ = remove_reference(type_) type_ = remove_cv(type_) return type_.decl_string in wostream_equivalences
[ "def", "is_std_wostream", "(", "type_", ")", ":", "if", "utils", ".", "is_str", "(", "type_", ")", ":", "return", "type_", "in", "wostream_equivalences", "else", ":", "type_", "=", "remove_alias", "(", "type_", ")", "type_", "=", "remove_reference", "(", "type_", ")", "type_", "=", "remove_cv", "(", "type_", ")", "return", "type_", ".", "decl_string", "in", "wostream_equivalences" ]
[ 557, 0 ]
[ 569, 57 ]
python
en
['en', 'error', 'th']
False
FortranFixedLexer._lex_fortran
(self, match, ctx=None)
Lex a line just as free form fortran without line break.
Lex a line just as free form fortran without line break.
def _lex_fortran(self, match, ctx=None): """Lex a line just as free form fortran without line break.""" lexer = FortranLexer() text = match.group(0) + "\n" for index, token, value in lexer.get_tokens_unprocessed(text): value = value.replace('\n', '') if value != '': yield index, token, value
[ "def", "_lex_fortran", "(", "self", ",", "match", ",", "ctx", "=", "None", ")", ":", "lexer", "=", "FortranLexer", "(", ")", "text", "=", "match", ".", "group", "(", "0", ")", "+", "\"\\n\"", "for", "index", ",", "token", ",", "value", "in", "lexer", ".", "get_tokens_unprocessed", "(", "text", ")", ":", "value", "=", "value", ".", "replace", "(", "'\\n'", ",", "''", ")", "if", "value", "!=", "''", ":", "yield", "index", ",", "token", ",", "value" ]
[ 176, 4 ]
[ 183, 41 ]
python
en
['en', 'en', 'en']
True
registo
(request)
Apresenta o formulário de registo ao utilizador. Se o método for POST, cria o objeto Utilizador com os dados do formulário. Caso seja outro, devolve o formulário sem dados introduzidos.
Apresenta o formulário de registo ao utilizador. Se o método for POST, cria o objeto Utilizador com os dados do formulário. Caso seja outro, devolve o formulário sem dados introduzidos.
def registo(request): """ Apresenta o formulário de registo ao utilizador. Se o método for POST, cria o objeto Utilizador com os dados do formulário. Caso seja outro, devolve o formulário sem dados introduzidos. """ if request.method == 'POST': form = UtilizadorRegistoForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success( request, f'A sua conta foi criada com sucesso. Pode começar a utilizar o mySchool!') return redirect('app-login') else: form = UtilizadorRegistoForm() return render(request, 'utilizadores/registo.html', {'form': form})
[ "def", "registo", "(", "request", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "form", "=", "UtilizadorRegistoForm", "(", "request", ".", "POST", ")", "if", "form", ".", "is_valid", "(", ")", ":", "form", ".", "save", "(", ")", "username", "=", "form", ".", "cleaned_data", ".", "get", "(", "'username'", ")", "messages", ".", "success", "(", "request", ",", "f'A sua conta foi criada com sucesso. Pode começar a utilizar o mySchool!')", "\r", "return", "redirect", "(", "'app-login'", ")", "else", ":", "form", "=", "UtilizadorRegistoForm", "(", ")", "return", "render", "(", "request", ",", "'utilizadores/registo.html'", ",", "{", "'form'", ":", "form", "}", ")" ]
[ 10, 0 ]
[ 26, 71 ]
python
en
['en', 'ja', 'th']
False
perfil
(request)
Apresenta o perfil ao utilizador, dentro da aplicação. Se o método for POST, atualiza o objeto Perfil com os dados do formulário. Caso seja outro, devolve o formulário sem dados introduzidos.
Apresenta o perfil ao utilizador, dentro da aplicação. Se o método for POST, atualiza o objeto Perfil com os dados do formulário. Caso seja outro, devolve o formulário sem dados introduzidos.
def perfil(request): """ Apresenta o perfil ao utilizador, dentro da aplicação. Se o método for POST, atualiza o objeto Perfil com os dados do formulário. Caso seja outro, devolve o formulário sem dados introduzidos. """ if request.method == 'POST': u_form = UtilizadorUpdateForm(request.POST, instance=request.user) if u_form.is_valid(): u_form.save() messages.success( request, f'A sua conta foi atualizada!') return redirect('app-perfil') else: u_form = UtilizadorUpdateForm(instance=request.user) context = { 'u_form': u_form, } return render(request, 'utilizadores/perfil.html', context)
[ "def", "perfil", "(", "request", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "u_form", "=", "UtilizadorUpdateForm", "(", "request", ".", "POST", ",", "instance", "=", "request", ".", "user", ")", "if", "u_form", ".", "is_valid", "(", ")", ":", "u_form", ".", "save", "(", ")", "messages", ".", "success", "(", "request", ",", "f'A sua conta foi atualizada!'", ")", "return", "redirect", "(", "'app-perfil'", ")", "else", ":", "u_form", "=", "UtilizadorUpdateForm", "(", "instance", "=", "request", ".", "user", ")", "context", "=", "{", "'u_form'", ":", "u_form", ",", "}", "return", "render", "(", "request", ",", "'utilizadores/perfil.html'", ",", "context", ")" ]
[ 30, 0 ]
[ 50, 63 ]
python
en
['en', 'ja', 'th']
False
RexxLexer.analyse_text
(text)
Check for inital comment and patterns that distinguish Rexx from other C-like languages.
Check for inital comment and patterns that distinguish Rexx from other C-like languages.
def analyse_text(text): """ Check for inital comment and patterns that distinguish Rexx from other C-like languages. """ if re.search(r'/\*\**\s*rexx', text, re.IGNORECASE): # Header matches MVS Rexx requirements, this is certainly a Rexx # script. return 1.0 elif text.startswith('/*'): # Header matches general Rexx requirements; the source code might # still be any language using C comments such as C++, C# or Java. lowerText = text.lower() result = sum(weight for (pattern, weight) in RexxLexer.PATTERNS_AND_WEIGHTS if pattern.search(lowerText)) + 0.01 return min(result, 1.0)
[ "def", "analyse_text", "(", "text", ")", ":", "if", "re", ".", "search", "(", "r'/\\*\\**\\s*rexx'", ",", "text", ",", "re", ".", "IGNORECASE", ")", ":", "# Header matches MVS Rexx requirements, this is certainly a Rexx", "# script.", "return", "1.0", "elif", "text", ".", "startswith", "(", "'/*'", ")", ":", "# Header matches general Rexx requirements; the source code might", "# still be any language using C comments such as C++, C# or Java.", "lowerText", "=", "text", ".", "lower", "(", ")", "result", "=", "sum", "(", "weight", "for", "(", "pattern", ",", "weight", ")", "in", "RexxLexer", ".", "PATTERNS_AND_WEIGHTS", "if", "pattern", ".", "search", "(", "lowerText", ")", ")", "+", "0.01", "return", "min", "(", "result", ",", "1.0", ")" ]
[ 782, 4 ]
[ 798, 35 ]
python
en
['en', 'error', 'th']
False
EasytrieveLexer.analyse_text
(text)
Perform a structural analysis for basic Easytrieve constructs.
Perform a structural analysis for basic Easytrieve constructs.
def analyse_text(text): """ Perform a structural analysis for basic Easytrieve constructs. """ result = 0.0 lines = text.split('\n') hasEndProc = False hasHeaderComment = False hasFile = False hasJob = False hasProc = False hasParm = False hasReport = False def isCommentLine(line): return EasytrieveLexer._COMMENT_LINE_REGEX.match(lines[0]) is not None def isEmptyLine(line): return not bool(line.strip()) # Remove possible empty lines and header comments. while lines and (isEmptyLine(lines[0]) or isCommentLine(lines[0])): if not isEmptyLine(lines[0]): hasHeaderComment = True del lines[0] if EasytrieveLexer._MACRO_HEADER_REGEX.match(lines[0]): # Looks like an Easytrieve macro. result = 0.4 if hasHeaderComment: result += 0.4 else: # Scan the source for lines starting with indicators. for line in lines: words = line.split() if (len(words) >= 2): firstWord = words[0] if not hasReport: if not hasJob: if not hasFile: if not hasParm: if firstWord == 'PARM': hasParm = True if firstWord == 'FILE': hasFile = True if firstWord == 'JOB': hasJob = True elif firstWord == 'PROC': hasProc = True elif firstWord == 'END-PROC': hasEndProc = True elif firstWord == 'REPORT': hasReport = True # Weight the findings. if hasJob and (hasProc == hasEndProc): if hasHeaderComment: result += 0.1 if hasParm: if hasProc: # Found PARM, JOB and PROC/END-PROC: # pretty sure this is Easytrieve. result += 0.8 else: # Found PARAM and JOB: probably this is Easytrieve result += 0.5 else: # Found JOB and possibly other keywords: might be Easytrieve result += 0.11 if hasParm: # Note: PARAM is not a proper English word, so this is # regarded a much better indicator for Easytrieve than # the other words. result += 0.2 if hasFile: result += 0.01 if hasReport: result += 0.01 assert 0.0 <= result <= 1.0 return result
[ "def", "analyse_text", "(", "text", ")", ":", "result", "=", "0.0", "lines", "=", "text", ".", "split", "(", "'\\n'", ")", "hasEndProc", "=", "False", "hasHeaderComment", "=", "False", "hasFile", "=", "False", "hasJob", "=", "False", "hasProc", "=", "False", "hasParm", "=", "False", "hasReport", "=", "False", "def", "isCommentLine", "(", "line", ")", ":", "return", "EasytrieveLexer", ".", "_COMMENT_LINE_REGEX", ".", "match", "(", "lines", "[", "0", "]", ")", "is", "not", "None", "def", "isEmptyLine", "(", "line", ")", ":", "return", "not", "bool", "(", "line", ".", "strip", "(", ")", ")", "# Remove possible empty lines and header comments.", "while", "lines", "and", "(", "isEmptyLine", "(", "lines", "[", "0", "]", ")", "or", "isCommentLine", "(", "lines", "[", "0", "]", ")", ")", ":", "if", "not", "isEmptyLine", "(", "lines", "[", "0", "]", ")", ":", "hasHeaderComment", "=", "True", "del", "lines", "[", "0", "]", "if", "EasytrieveLexer", ".", "_MACRO_HEADER_REGEX", ".", "match", "(", "lines", "[", "0", "]", ")", ":", "# Looks like an Easytrieve macro.", "result", "=", "0.4", "if", "hasHeaderComment", ":", "result", "+=", "0.4", "else", ":", "# Scan the source for lines starting with indicators.", "for", "line", "in", "lines", ":", "words", "=", "line", ".", "split", "(", ")", "if", "(", "len", "(", "words", ")", ">=", "2", ")", ":", "firstWord", "=", "words", "[", "0", "]", "if", "not", "hasReport", ":", "if", "not", "hasJob", ":", "if", "not", "hasFile", ":", "if", "not", "hasParm", ":", "if", "firstWord", "==", "'PARM'", ":", "hasParm", "=", "True", "if", "firstWord", "==", "'FILE'", ":", "hasFile", "=", "True", "if", "firstWord", "==", "'JOB'", ":", "hasJob", "=", "True", "elif", "firstWord", "==", "'PROC'", ":", "hasProc", "=", "True", "elif", "firstWord", "==", "'END-PROC'", ":", "hasEndProc", "=", "True", "elif", "firstWord", "==", "'REPORT'", ":", "hasReport", "=", "True", "# Weight the findings.", "if", "hasJob", "and", "(", "hasProc", "==", "hasEndProc", ")", ":", "if", "hasHeaderComment", ":", "result", "+=", "0.1", "if", "hasParm", ":", "if", "hasProc", ":", "# Found PARM, JOB and PROC/END-PROC:", "# pretty sure this is Easytrieve.", "result", "+=", "0.8", "else", ":", "# Found PARAM and JOB: probably this is Easytrieve", "result", "+=", "0.5", "else", ":", "# Found JOB and possibly other keywords: might be Easytrieve", "result", "+=", "0.11", "if", "hasParm", ":", "# Note: PARAM is not a proper English word, so this is", "# regarded a much better indicator for Easytrieve than", "# the other words.", "result", "+=", "0.2", "if", "hasFile", ":", "result", "+=", "0.01", "if", "hasReport", ":", "result", "+=", "0.01", "assert", "0.0", "<=", "result", "<=", "1.0", "return", "result" ]
[ 1040, 4 ]
[ 1119, 21 ]
python
en
['en', 'error', 'th']
False
JclLexer.analyse_text
(text)
Recognize JCL job by header.
Recognize JCL job by header.
def analyse_text(text): """ Recognize JCL job by header. """ result = 0.0 lines = text.split('\n') if len(lines) > 0: if JclLexer._JOB_HEADER_PATTERN.match(lines[0]): result = 1.0 assert 0.0 <= result <= 1.0 return result
[ "def", "analyse_text", "(", "text", ")", ":", "result", "=", "0.0", "lines", "=", "text", ".", "split", "(", "'\\n'", ")", "if", "len", "(", "lines", ")", ">", "0", ":", "if", "JclLexer", ".", "_JOB_HEADER_PATTERN", ".", "match", "(", "lines", "[", "0", "]", ")", ":", "result", "=", "1.0", "assert", "0.0", "<=", "result", "<=", "1.0", "return", "result" ]
[ 1192, 4 ]
[ 1202, 21 ]
python
en
['en', 'error', 'th']
False
ColumnDistinctValues._get_evaluation_dependencies
( cls, metric: MetricConfiguration, configuration: Optional[ExpectationConfiguration] = None, execution_engine: Optional[ExecutionEngine] = None, runtime_configuration: Optional[Dict] = None, )
Returns a dictionary of given metric names and their corresponding configuration, specifying the metric types and their respective domains
Returns a dictionary of given metric names and their corresponding configuration, specifying the metric types and their respective domains
def _get_evaluation_dependencies( cls, metric: MetricConfiguration, configuration: Optional[ExpectationConfiguration] = None, execution_engine: Optional[ExecutionEngine] = None, runtime_configuration: Optional[Dict] = None, ): """Returns a dictionary of given metric names and their corresponding configuration, specifying the metric types and their respective domains""" dependencies: dict = super()._get_evaluation_dependencies( metric=metric, configuration=configuration, execution_engine=execution_engine, runtime_configuration=runtime_configuration, ) if isinstance( execution_engine, (SqlAlchemyExecutionEngine, SparkDFExecutionEngine) ): dependencies["column.value_counts"] = MetricConfiguration( metric_name="column.value_counts", metric_domain_kwargs=metric.metric_domain_kwargs, metric_value_kwargs={ "sort": "value", "collate": None, }, ) return dependencies
[ "def", "_get_evaluation_dependencies", "(", "cls", ",", "metric", ":", "MetricConfiguration", ",", "configuration", ":", "Optional", "[", "ExpectationConfiguration", "]", "=", "None", ",", "execution_engine", ":", "Optional", "[", "ExecutionEngine", "]", "=", "None", ",", "runtime_configuration", ":", "Optional", "[", "Dict", "]", "=", "None", ",", ")", ":", "dependencies", ":", "dict", "=", "super", "(", ")", ".", "_get_evaluation_dependencies", "(", "metric", "=", "metric", ",", "configuration", "=", "configuration", ",", "execution_engine", "=", "execution_engine", ",", "runtime_configuration", "=", "runtime_configuration", ",", ")", "if", "isinstance", "(", "execution_engine", ",", "(", "SqlAlchemyExecutionEngine", ",", "SparkDFExecutionEngine", ")", ")", ":", "dependencies", "[", "\"column.value_counts\"", "]", "=", "MetricConfiguration", "(", "metric_name", "=", "\"column.value_counts\"", ",", "metric_domain_kwargs", "=", "metric", ".", "metric_domain_kwargs", ",", "metric_value_kwargs", "=", "{", "\"sort\"", ":", "\"value\"", ",", "\"collate\"", ":", "None", ",", "}", ",", ")", "return", "dependencies" ]
[ 51, 4 ]
[ 79, 27 ]
python
en
['en', 'en', 'en']
True
ColumnDistinctValuesCount._get_evaluation_dependencies
( cls, metric: MetricConfiguration, configuration: Optional[ExpectationConfiguration] = None, execution_engine: Optional[ExecutionEngine] = None, runtime_configuration: Optional[Dict] = None, )
Returns a dictionary of given metric names and their corresponding configuration, specifying the metric types and their respective domains
Returns a dictionary of given metric names and their corresponding configuration, specifying the metric types and their respective domains
def _get_evaluation_dependencies( cls, metric: MetricConfiguration, configuration: Optional[ExpectationConfiguration] = None, execution_engine: Optional[ExecutionEngine] = None, runtime_configuration: Optional[Dict] = None, ): """Returns a dictionary of given metric names and their corresponding configuration, specifying the metric types and their respective domains""" dependencies: dict = super()._get_evaluation_dependencies( metric=metric, configuration=configuration, execution_engine=execution_engine, runtime_configuration=runtime_configuration, ) if isinstance( execution_engine, (SqlAlchemyExecutionEngine, SparkDFExecutionEngine) ): dependencies["column.value_counts"] = MetricConfiguration( metric_name="column.value_counts", metric_domain_kwargs=metric.metric_domain_kwargs, metric_value_kwargs={ "sort": "value", "collate": None, }, ) return dependencies
[ "def", "_get_evaluation_dependencies", "(", "cls", ",", "metric", ":", "MetricConfiguration", ",", "configuration", ":", "Optional", "[", "ExpectationConfiguration", "]", "=", "None", ",", "execution_engine", ":", "Optional", "[", "ExecutionEngine", "]", "=", "None", ",", "runtime_configuration", ":", "Optional", "[", "Dict", "]", "=", "None", ",", ")", ":", "dependencies", ":", "dict", "=", "super", "(", ")", ".", "_get_evaluation_dependencies", "(", "metric", "=", "metric", ",", "configuration", "=", "configuration", ",", "execution_engine", "=", "execution_engine", ",", "runtime_configuration", "=", "runtime_configuration", ",", ")", "if", "isinstance", "(", "execution_engine", ",", "(", "SqlAlchemyExecutionEngine", ",", "SparkDFExecutionEngine", ")", ")", ":", "dependencies", "[", "\"column.value_counts\"", "]", "=", "MetricConfiguration", "(", "metric_name", "=", "\"column.value_counts\"", ",", "metric_domain_kwargs", "=", "metric", ".", "metric_domain_kwargs", ",", "metric_value_kwargs", "=", "{", "\"sort\"", ":", "\"value\"", ",", "\"collate\"", ":", "None", ",", "}", ",", ")", "return", "dependencies" ]
[ 114, 4 ]
[ 142, 27 ]
python
en
['en', 'en', 'en']
True
ExpectColumnMedianToBeBetween.validate_configuration
(self, configuration: Optional[ExpectationConfiguration])
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that necessary configuration arguments have been provided for the validation of the expectation. Args: configuration (OPTIONAL[ExpectationConfiguration]): \ An optional Expectation Configuration entry that will be used to configure the expectation Returns: True if the configuration has been validated successfully. Otherwise, raises an exception
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that necessary configuration arguments have been provided for the validation of the expectation.
def validate_configuration(self, configuration: Optional[ExpectationConfiguration]): """ Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that necessary configuration arguments have been provided for the validation of the expectation. Args: configuration (OPTIONAL[ExpectationConfiguration]): \ An optional Expectation Configuration entry that will be used to configure the expectation Returns: True if the configuration has been validated successfully. Otherwise, raises an exception """ super().validate_configuration(configuration) self.validate_metric_value_between_configuration(configuration=configuration)
[ "def", "validate_configuration", "(", "self", ",", "configuration", ":", "Optional", "[", "ExpectationConfiguration", "]", ")", ":", "super", "(", ")", ".", "validate_configuration", "(", "configuration", ")", "self", ".", "validate_metric_value_between_configuration", "(", "configuration", "=", "configuration", ")" ]
[ 104, 4 ]
[ 116, 85 ]
python
en
['en', 'error', 'th']
False
_f
(x, with_defaults)
A small helper function.
A small helper function.
def _f(x, with_defaults): """ A small helper function. """ return x.build_decl_string(with_defaults)
[ "def", "_f", "(", "x", ",", "with_defaults", ")", ":", "return", "x", ".", "build_decl_string", "(", "with_defaults", ")" ]
[ 467, 0 ]
[ 473, 45 ]
python
en
['en', 'error', 'th']
False
type_t.clone
(self)
returns new instance of the type
returns new instance of the type
def clone(self): """returns new instance of the type""" answer = self._clone_impl() return answer
[ "def", "clone", "(", "self", ")", ":", "answer", "=", "self", ".", "_clone_impl", "(", ")", "return", "answer" ]
[ 61, 4 ]
[ 64, 21 ]
python
en
['en', 'en', 'en']
True
compound_t.base
(self)
reference to internal/base class
reference to internal/base class
def base(self): """reference to internal/base class""" return self._base
[ "def", "base", "(", "self", ")", ":", "return", "self", ".", "_base" ]
[ 488, 4 ]
[ 490, 25 ]
python
en
['en', 'en', 'en']
True
array_t.size
(self)
returns array size
returns array size
def size(self): """returns array size""" return self._size
[ "def", "size", "(", "self", ")", ":", "return", "self", ".", "_size" ]
[ 616, 4 ]
[ 618, 25 ]
python
en
['en', 'hu', 'en']
True
array_t.size
(self, size)
sometimes there is a need to update the size of the array
sometimes there is a need to update the size of the array
def size(self, size): """sometimes there is a need to update the size of the array""" self.cache.reset() self._size = size
[ "def", "size", "(", "self", ",", "size", ")", ":", "self", ".", "cache", ".", "reset", "(", ")", "self", ".", "_size", "=", "size" ]
[ 621, 4 ]
[ 624, 25 ]
python
en
['en', 'en', 'en']
True
calldef_type_t.return_type
(self)
reference to :class:`return type <type_t>`
reference to :class:`return type <type_t>`
def return_type(self): """reference to :class:`return type <type_t>`""" return self._return_type
[ "def", "return_type", "(", "self", ")", ":", "return", "self", ".", "_return_type" ]
[ 662, 4 ]
[ 664, 32 ]
python
en
['en', 'en', 'en']
True
calldef_type_t.arguments_types
(self)
list of argument :class:`types <type_t>`
list of argument :class:`types <type_t>`
def arguments_types(self): """list of argument :class:`types <type_t>`""" return self._arguments_types
[ "def", "arguments_types", "(", "self", ")", ":", "return", "self", ".", "_arguments_types" ]
[ 671, 4 ]
[ 673, 36 ]
python
en
['en', 'en', 'en']
True
free_function_type_t.create_decl_string
( return_type, arguments_types, with_defaults=True)
Returns free function type :param return_type: function return type :type return_type: :class:`type_t` :param arguments_types: list of argument :class:`type <type_t>` :rtype: :class:`free_function_type_t`
Returns free function type
def create_decl_string( return_type, arguments_types, with_defaults=True): """ Returns free function type :param return_type: function return type :type return_type: :class:`type_t` :param arguments_types: list of argument :class:`type <type_t>` :rtype: :class:`free_function_type_t` """ return free_function_type_t.NAME_TEMPLATE % { 'return_type': return_type.build_decl_string(with_defaults), 'arguments': ','.join( [_f(x, with_defaults) for x in arguments_types])}
[ "def", "create_decl_string", "(", "return_type", ",", "arguments_types", ",", "with_defaults", "=", "True", ")", ":", "return", "free_function_type_t", ".", "NAME_TEMPLATE", "%", "{", "'return_type'", ":", "return_type", ".", "build_decl_string", "(", "with_defaults", ")", ",", "'arguments'", ":", "','", ".", "join", "(", "[", "_f", "(", "x", ",", "with_defaults", ")", "for", "x", "in", "arguments_types", "]", ")", "}" ]
[ 697, 4 ]
[ 712, 65 ]
python
en
['en', 'error', 'th']
False
free_function_type_t.create_typedef
(self, typedef_name, unused=None, with_defaults=True)
returns string, that contains valid C++ code, that defines typedef to function type :param name: the desired name of typedef
returns string, that contains valid C++ code, that defines typedef to function type
def create_typedef(self, typedef_name, unused=None, with_defaults=True): """returns string, that contains valid C++ code, that defines typedef to function type :param name: the desired name of typedef """ return free_function_type_t.TYPEDEF_NAME_TEMPLATE % { 'typedef_name': typedef_name, 'return_type': self.return_type.build_decl_string(with_defaults), 'arguments': ','.join( [_f(x, with_defaults) for x in self.arguments_types])}
[ "def", "create_typedef", "(", "self", ",", "typedef_name", ",", "unused", "=", "None", ",", "with_defaults", "=", "True", ")", ":", "return", "free_function_type_t", ".", "TYPEDEF_NAME_TEMPLATE", "%", "{", "'typedef_name'", ":", "typedef_name", ",", "'return_type'", ":", "self", ".", "return_type", ".", "build_decl_string", "(", "with_defaults", ")", ",", "'arguments'", ":", "','", ".", "join", "(", "[", "_f", "(", "x", ",", "with_defaults", ")", "for", "x", "in", "self", ".", "arguments_types", "]", ")", "}" ]
[ 729, 4 ]
[ 740, 70 ]
python
en
['en', 'en', 'en']
True
member_function_type_t.has_const
(self)
describes, whether function has const modifier
describes, whether function has const modifier
def has_const(self): """describes, whether function has const modifier""" return self._has_const
[ "def", "has_const", "(", "self", ")", ":", "return", "self", ".", "_has_const" ]
[ 764, 4 ]
[ 766, 30 ]
python
en
['en', 'gl', 'en']
True
member_function_type_t.class_inst
(self)
reference to parent :class:`class <declaration_t>`
reference to parent :class:`class <declaration_t>`
def class_inst(self): """reference to parent :class:`class <declaration_t>`""" return self._class_inst
[ "def", "class_inst", "(", "self", ")", ":", "return", "self", ".", "_class_inst" ]
[ 773, 4 ]
[ 775, 31 ]
python
en
['en', 'en', 'en']
True
member_function_type_t.create_typedef
( self, typedef_name, class_alias=None, with_defaults=True)
creates typedef to the function type :param typedef_name: desired type name :rtype: string
creates typedef to the function type
def create_typedef( self, typedef_name, class_alias=None, with_defaults=True): """creates typedef to the function type :param typedef_name: desired type name :rtype: string """ has_const_str = '' if self.has_const: has_const_str = 'const' if None is class_alias: if with_defaults: class_alias = self.class_inst.decl_string else: class_alias = self.class_inst.partial_decl_string return member_function_type_t.TYPEDEF_NAME_TEMPLATE % { 'typedef_name': typedef_name, 'return_type': self.return_type.build_decl_string(with_defaults), 'class': class_alias, 'arguments': ','.join( [_f(x, with_defaults) for x in self.arguments_types]), 'has_const': has_const_str}
[ "def", "create_typedef", "(", "self", ",", "typedef_name", ",", "class_alias", "=", "None", ",", "with_defaults", "=", "True", ")", ":", "has_const_str", "=", "''", "if", "self", ".", "has_const", ":", "has_const_str", "=", "'const'", "if", "None", "is", "class_alias", ":", "if", "with_defaults", ":", "class_alias", "=", "self", ".", "class_inst", ".", "decl_string", "else", ":", "class_alias", "=", "self", ".", "class_inst", ".", "partial_decl_string", "return", "member_function_type_t", ".", "TYPEDEF_NAME_TEMPLATE", "%", "{", "'typedef_name'", ":", "typedef_name", ",", "'return_type'", ":", "self", ".", "return_type", ".", "build_decl_string", "(", "with_defaults", ")", ",", "'class'", ":", "class_alias", ",", "'arguments'", ":", "','", ".", "join", "(", "[", "_f", "(", "x", ",", "with_defaults", ")", "for", "x", "in", "self", ".", "arguments_types", "]", ")", ",", "'has_const'", ":", "has_const_str", "}" ]
[ 782, 4 ]
[ 807, 39 ]
python
en
['en', 'en', 'en']
True
member_variable_type_t.variable_type
(self)
describes member variable :class:`type <type_t>`
describes member variable :class:`type <type_t>`
def variable_type(self): """describes member variable :class:`type <type_t>`""" return self._mv_type
[ "def", "variable_type", "(", "self", ")", ":", "return", "self", ".", "_mv_type" ]
[ 859, 4 ]
[ 861, 28 ]
python
en
['de', 'en', 'en']
True
declarated_t.declaration
(self)
reference to :class:`declaration_t`
reference to :class:`declaration_t`
def declaration(self): """reference to :class:`declaration_t`""" return self._declaration
[ "def", "declaration", "(", "self", ")", ":", "return", "self", ".", "_declaration" ]
[ 894, 4 ]
[ 896, 32 ]
python
en
['en', 'en', 'en']
True
factorial
(n)
Return the factorial of n, an exact integer >= 0. If the result is small enough to fit in an int, return an int. Else return a long. >>> [factorial(n) for n in range(6)] [1, 1, 2, 6, 24, 120] >>> factorial(-1) Traceback (most recent call last): ... ValueError: n must be >= 0 Factorials of floats are OK, but the float must be an exact integer: >>> factorial(30.1) Traceback (most recent call last): ... ValueError: n must be exact integer It must also not be ridiculously large: >>> factorial(1e100) Traceback (most recent call last): ... OverflowError: n too large
Return the factorial of n, an exact integer >= 0.
def factorial(n): """Return the factorial of n, an exact integer >= 0. If the result is small enough to fit in an int, return an int. Else return a long. >>> [factorial(n) for n in range(6)] [1, 1, 2, 6, 24, 120] >>> factorial(-1) Traceback (most recent call last): ... ValueError: n must be >= 0 Factorials of floats are OK, but the float must be an exact integer: >>> factorial(30.1) Traceback (most recent call last): ... ValueError: n must be exact integer It must also not be ridiculously large: >>> factorial(1e100) Traceback (most recent call last): ... OverflowError: n too large """ import math if not n >= 0: raise ValueError("n must be >= 0") if math.floor(n) != n: raise ValueError("n must be exact integer") if n+1 == n: # catch a value like 1e300 raise OverflowError("n too large") result = 1 factor = 2 while factor <= n: result *= factor factor += 1 return result
[ "def", "factorial", "(", "n", ")", ":", "import", "math", "if", "not", "n", ">=", "0", ":", "raise", "ValueError", "(", "\"n must be >= 0\"", ")", "if", "math", ".", "floor", "(", "n", ")", "!=", "n", ":", "raise", "ValueError", "(", "\"n must be exact integer\"", ")", "if", "n", "+", "1", "==", "n", ":", "# catch a value like 1e300", "raise", "OverflowError", "(", "\"n too large\"", ")", "result", "=", "1", "factor", "=", "2", "while", "factor", "<=", "n", ":", "result", "*=", "factor", "factor", "+=", "1", "return", "result" ]
[ 5, 0 ]
[ 43, 17 ]
python
en
['en', 'lb', 'en']
True
Renderer._get_column_list_from_evrs
(cls, evrs)
Get list of column names. If expect_table_columns_to_match_ordered_list EVR is present, use it as the list, including the order. Otherwise, get the list of all columns mentioned in the expectations and order it alphabetically. :param evrs: :return: list of columns with best effort sorting
Get list of column names.
def _get_column_list_from_evrs(cls, evrs): """ Get list of column names. If expect_table_columns_to_match_ordered_list EVR is present, use it as the list, including the order. Otherwise, get the list of all columns mentioned in the expectations and order it alphabetically. :param evrs: :return: list of columns with best effort sorting """ evrs_ = evrs if isinstance(evrs, list) else evrs.results expect_table_columns_to_match_ordered_list_evr = cls._find_evr_by_type( evrs_, "expect_table_columns_to_match_ordered_list" ) # Group EVRs by column sorted_columns = sorted( list( { evr.expectation_config.kwargs["column"] for evr in evrs_ if "column" in evr.expectation_config.kwargs } ) ) if expect_table_columns_to_match_ordered_list_evr: ordered_columns = expect_table_columns_to_match_ordered_list_evr.result[ "observed_value" ] else: ordered_columns = [] # only return ordered columns from expect_table_columns_to_match_ordered_list evr if they match set of column # names from entire evr if set(sorted_columns) == set(ordered_columns): return ordered_columns else: return sorted_columns
[ "def", "_get_column_list_from_evrs", "(", "cls", ",", "evrs", ")", ":", "evrs_", "=", "evrs", "if", "isinstance", "(", "evrs", ",", "list", ")", "else", "evrs", ".", "results", "expect_table_columns_to_match_ordered_list_evr", "=", "cls", ".", "_find_evr_by_type", "(", "evrs_", ",", "\"expect_table_columns_to_match_ordered_list\"", ")", "# Group EVRs by column", "sorted_columns", "=", "sorted", "(", "list", "(", "{", "evr", ".", "expectation_config", ".", "kwargs", "[", "\"column\"", "]", "for", "evr", "in", "evrs_", "if", "\"column\"", "in", "evr", ".", "expectation_config", ".", "kwargs", "}", ")", ")", "if", "expect_table_columns_to_match_ordered_list_evr", ":", "ordered_columns", "=", "expect_table_columns_to_match_ordered_list_evr", ".", "result", "[", "\"observed_value\"", "]", "else", ":", "ordered_columns", "=", "[", "]", "# only return ordered columns from expect_table_columns_to_match_ordered_list evr if they match set of column", "# names from entire evr", "if", "set", "(", "sorted_columns", ")", "==", "set", "(", "ordered_columns", ")", ":", "return", "ordered_columns", "else", ":", "return", "sorted_columns" ]
[ 61, 4 ]
[ 100, 33 ]
python
en
['en', 'error', 'th']
False
Renderer._group_and_order_expectations_by_column
(cls, expectations)
Group expectations by column.
Group expectations by column.
def _group_and_order_expectations_by_column(cls, expectations): """Group expectations by column.""" expectations_by_column = {} ordered_columns = [] for expectation in expectations.expectations: if "column" in expectation.kwargs: column = expectation.kwargs["column"] else: column = "_nocolumn" if column not in expectations_by_column: expectations_by_column[column] = [] expectations_by_column[column].append(expectation) # if possible, get the order of columns from expect_table_columns_to_match_ordered_list if ( expectation.expectation_type == "expect_table_columns_to_match_ordered_list" ): exp_column_list = expectation.kwargs["column_list"] if exp_column_list and len(exp_column_list) > 0: ordered_columns = exp_column_list # Group items by column sorted_columns = sorted(list(expectations_by_column.keys())) # only return ordered columns from expect_table_columns_to_match_ordered_list evr if they match set of column # names from entire evr, else use alphabetic sort if set(sorted_columns) == set(ordered_columns): return expectations_by_column, ordered_columns else: return expectations_by_column, sorted_columns
[ "def", "_group_and_order_expectations_by_column", "(", "cls", ",", "expectations", ")", ":", "expectations_by_column", "=", "{", "}", "ordered_columns", "=", "[", "]", "for", "expectation", "in", "expectations", ".", "expectations", ":", "if", "\"column\"", "in", "expectation", ".", "kwargs", ":", "column", "=", "expectation", ".", "kwargs", "[", "\"column\"", "]", "else", ":", "column", "=", "\"_nocolumn\"", "if", "column", "not", "in", "expectations_by_column", ":", "expectations_by_column", "[", "column", "]", "=", "[", "]", "expectations_by_column", "[", "column", "]", ".", "append", "(", "expectation", ")", "# if possible, get the order of columns from expect_table_columns_to_match_ordered_list", "if", "(", "expectation", ".", "expectation_type", "==", "\"expect_table_columns_to_match_ordered_list\"", ")", ":", "exp_column_list", "=", "expectation", ".", "kwargs", "[", "\"column_list\"", "]", "if", "exp_column_list", "and", "len", "(", "exp_column_list", ")", ">", "0", ":", "ordered_columns", "=", "exp_column_list", "# Group items by column", "sorted_columns", "=", "sorted", "(", "list", "(", "expectations_by_column", ".", "keys", "(", ")", ")", ")", "# only return ordered columns from expect_table_columns_to_match_ordered_list evr if they match set of column", "# names from entire evr, else use alphabetic sort", "if", "set", "(", "sorted_columns", ")", "==", "set", "(", "ordered_columns", ")", ":", "return", "expectations_by_column", ",", "ordered_columns", "else", ":", "return", "expectations_by_column", ",", "sorted_columns" ]
[ 120, 4 ]
[ 151, 57 ]
python
en
['en', 'en', 'en']
True
CounterfactualValueEstimator.predict_best
(self)
Predict the best treatment group based on the highest counterfactual value for a treatment.
Predict the best treatment group based on the highest counterfactual value for a treatment.
def predict_best(self): ''' Predict the best treatment group based on the highest counterfactual value for a treatment. ''' self._get_counterfactuals() self._get_counterfactual_values() return self.best_treatment
[ "def", "predict_best", "(", "self", ")", ":", "self", ".", "_get_counterfactuals", "(", ")", "self", ".", "_get_counterfactual_values", "(", ")", "return", "self", ".", "best_treatment" ]
[ 58, 4 ]
[ 65, 34 ]
python
en
['en', 'error', 'th']
False
CounterfactualValueEstimator.predict_counterfactuals
(self)
Predict the counterfactual values for each treatment group.
Predict the counterfactual values for each treatment group.
def predict_counterfactuals(self): ''' Predict the counterfactual values for each treatment group. ''' self._get_counterfactuals() self._get_counterfactual_values() return self.expected_values
[ "def", "predict_counterfactuals", "(", "self", ")", ":", "self", ".", "_get_counterfactuals", "(", ")", "self", ".", "_get_counterfactual_values", "(", ")", "return", "self", ".", "expected_values" ]
[ 67, 4 ]
[ 73, 35 ]
python
en
['en', 'error', 'th']
False
CounterfactualValueEstimator._get_counterfactuals
(self)
Get an array of counterfactual outcomes based on control outcome and the array of conditional average treatment effects.
Get an array of counterfactual outcomes based on control outcome and the array of conditional average treatment effects.
def _get_counterfactuals(self): ''' Get an array of counterfactual outcomes based on control outcome and the array of conditional average treatment effects. ''' conditions = self.treatment_names.copy() conditions.insert(0, self.control_name) cates_with_control = np.c_[np.zeros(self.cate.shape[0]), self.cate] cates_flat = cates_with_control.flatten() cates_filt = [actual_group == poss_group for actual_group in self.treatment for poss_group in conditions] control_outcome = self.y_proba - cates_flat[cates_filt] self.counterfactuals = cates_with_control + control_outcome[:, None]
[ "def", "_get_counterfactuals", "(", "self", ")", ":", "conditions", "=", "self", ".", "treatment_names", ".", "copy", "(", ")", "conditions", ".", "insert", "(", "0", ",", "self", ".", "control_name", ")", "cates_with_control", "=", "np", ".", "c_", "[", "np", ".", "zeros", "(", "self", ".", "cate", ".", "shape", "[", "0", "]", ")", ",", "self", ".", "cate", "]", "cates_flat", "=", "cates_with_control", ".", "flatten", "(", ")", "cates_filt", "=", "[", "actual_group", "==", "poss_group", "for", "actual_group", "in", "self", ".", "treatment", "for", "poss_group", "in", "conditions", "]", "control_outcome", "=", "self", ".", "y_proba", "-", "cates_flat", "[", "cates_filt", "]", "self", ".", "counterfactuals", "=", "cates_with_control", "+", "control_outcome", "[", ":", ",", "None", "]" ]
[ 75, 4 ]
[ 90, 76 ]
python
en
['en', 'error', 'th']
False
CounterfactualValueEstimator._get_counterfactual_values
(self)
Calculate the expected value of assigning a unit to each of the treatment conditions given the value of conversion and the conversion and impression costs associated with the treatment.
Calculate the expected value of assigning a unit to each of the treatment conditions given the value of conversion and the conversion and impression costs associated with the treatment.
def _get_counterfactual_values(self): ''' Calculate the expected value of assigning a unit to each of the treatment conditions given the value of conversion and the conversion and impression costs associated with the treatment. ''' self.expected_values = ((self.value[:, None] - self.conversion_cost) * self.counterfactuals - self.impression_cost) self.best_treatment = np.argmax(self.expected_values, axis=1)
[ "def", "_get_counterfactual_values", "(", "self", ")", ":", "self", ".", "expected_values", "=", "(", "(", "self", ".", "value", "[", ":", ",", "None", "]", "-", "self", ".", "conversion_cost", ")", "*", "self", ".", "counterfactuals", "-", "self", ".", "impression_cost", ")", "self", ".", "best_treatment", "=", "np", ".", "argmax", "(", "self", ".", "expected_values", ",", "axis", "=", "1", ")" ]
[ 92, 4 ]
[ 102, 69 ]
python
en
['en', 'error', 'th']
False
decl_factory_t.__init__
(self)
creates declarations factory
creates declarations factory
def __init__(self): """creates declarations factory""" object.__init__(self)
[ "def", "__init__", "(", "self", ")", ":", "object", ".", "__init__", "(", "self", ")" ]
[ 30, 4 ]
[ 32, 29 ]
python
en
['fr', 'la', 'en']
False
decl_factory_t.create_member_function
(self, *arguments, **keywords)
creates instance of class that describes member function declaration
creates instance of class that describes member function declaration
def create_member_function(self, *arguments, **keywords): """creates instance of class that describes member function declaration""" return member_function_t(*arguments, **keywords)
[ "def", "create_member_function", "(", "self", ",", "*", "arguments", ",", "*", "*", "keywords", ")", ":", "return", "member_function_t", "(", "*", "arguments", ",", "*", "*", "keywords", ")" ]
[ 34, 4 ]
[ 37, 56 ]
python
en
['en', 'en', 'en']
True
decl_factory_t.create_constructor
(self, *arguments, **keywords)
creates instance of class that describes constructor declaration
creates instance of class that describes constructor declaration
def create_constructor(self, *arguments, **keywords): """creates instance of class that describes constructor declaration""" return constructor_t(*arguments, **keywords)
[ "def", "create_constructor", "(", "self", ",", "*", "arguments", ",", "*", "*", "keywords", ")", ":", "return", "constructor_t", "(", "*", "arguments", ",", "*", "*", "keywords", ")" ]
[ 39, 4 ]
[ 41, 52 ]
python
en
['en', 'en', 'en']
True
decl_factory_t.create_destructor
(self, *arguments, **keywords)
creates instance of class that describes destructor declaration
creates instance of class that describes destructor declaration
def create_destructor(self, *arguments, **keywords): """creates instance of class that describes destructor declaration""" return destructor_t(*arguments, **keywords)
[ "def", "create_destructor", "(", "self", ",", "*", "arguments", ",", "*", "*", "keywords", ")", ":", "return", "destructor_t", "(", "*", "arguments", ",", "*", "*", "keywords", ")" ]
[ 43, 4 ]
[ 45, 51 ]
python
en
['en', 'lb', 'en']
True
decl_factory_t.create_member_operator
(self, *arguments, **keywords)
creates instance of class that describes member operator declaration
creates instance of class that describes member operator declaration
def create_member_operator(self, *arguments, **keywords): """creates instance of class that describes member operator declaration""" return member_operator_t(*arguments, **keywords)
[ "def", "create_member_operator", "(", "self", ",", "*", "arguments", ",", "*", "*", "keywords", ")", ":", "return", "member_operator_t", "(", "*", "arguments", ",", "*", "*", "keywords", ")" ]
[ 47, 4 ]
[ 50, 56 ]
python
en
['en', 'en', 'en']
True
decl_factory_t.create_casting_operator
(self, *arguments, **keywords)
creates instance of class that describes casting operator declaration
creates instance of class that describes casting operator declaration
def create_casting_operator(self, *arguments, **keywords): """creates instance of class that describes casting operator declaration""" return casting_operator_t(*arguments, **keywords)
[ "def", "create_casting_operator", "(", "self", ",", "*", "arguments", ",", "*", "*", "keywords", ")", ":", "return", "casting_operator_t", "(", "*", "arguments", ",", "*", "*", "keywords", ")" ]
[ 52, 4 ]
[ 55, 57 ]
python
en
['en', 'en', 'en']
True
decl_factory_t.create_free_function
(self, *arguments, **keywords)
creates instance of class that describes free function declaration
creates instance of class that describes free function declaration
def create_free_function(self, *arguments, **keywords): """creates instance of class that describes free function declaration""" return free_function_t(*arguments, **keywords)
[ "def", "create_free_function", "(", "self", ",", "*", "arguments", ",", "*", "*", "keywords", ")", ":", "return", "free_function_t", "(", "*", "arguments", ",", "*", "*", "keywords", ")" ]
[ 57, 4 ]
[ 60, 54 ]
python
en
['en', 'en', 'en']
True
decl_factory_t.create_free_operator
(self, *arguments, **keywords)
creates instance of class that describes free operator declaration
creates instance of class that describes free operator declaration
def create_free_operator(self, *arguments, **keywords): """creates instance of class that describes free operator declaration""" return free_operator_t(*arguments, **keywords)
[ "def", "create_free_operator", "(", "self", ",", "*", "arguments", ",", "*", "*", "keywords", ")", ":", "return", "free_operator_t", "(", "*", "arguments", ",", "*", "*", "keywords", ")" ]
[ 62, 4 ]
[ 65, 54 ]
python
en
['en', 'en', 'en']
True
decl_factory_t.create_class_declaration
(self, *arguments, **keywords)
creates instance of class that describes class declaration
creates instance of class that describes class declaration
def create_class_declaration(self, *arguments, **keywords): """creates instance of class that describes class declaration""" return class_declaration_t(*arguments, **keywords)
[ "def", "create_class_declaration", "(", "self", ",", "*", "arguments", ",", "*", "*", "keywords", ")", ":", "return", "class_declaration_t", "(", "*", "arguments", ",", "*", "*", "keywords", ")" ]
[ 67, 4 ]
[ 69, 58 ]
python
en
['en', 'lb', 'en']
True
decl_factory_t.create_class
(self, *arguments, **keywords)
creates instance of class that describes class definition declaration
creates instance of class that describes class definition declaration
def create_class(self, *arguments, **keywords): """creates instance of class that describes class definition declaration""" return class_t(*arguments, **keywords)
[ "def", "create_class", "(", "self", ",", "*", "arguments", ",", "*", "*", "keywords", ")", ":", "return", "class_t", "(", "*", "arguments", ",", "*", "*", "keywords", ")" ]
[ 71, 4 ]
[ 74, 46 ]
python
en
['en', 'en', 'en']
True
decl_factory_t.create_enumeration
(self, *arguments, **keywords)
creates instance of class that describes enumeration declaration
creates instance of class that describes enumeration declaration
def create_enumeration(self, *arguments, **keywords): """creates instance of class that describes enumeration declaration""" return enumeration_t(*arguments, **keywords)
[ "def", "create_enumeration", "(", "self", ",", "*", "arguments", ",", "*", "*", "keywords", ")", ":", "return", "enumeration_t", "(", "*", "arguments", ",", "*", "*", "keywords", ")" ]
[ 76, 4 ]
[ 78, 52 ]
python
en
['en', 'en', 'en']
True
decl_factory_t.create_namespace
(self, *arguments, **keywords)
creates instance of class that describes namespace declaration
creates instance of class that describes namespace declaration
def create_namespace(self, *arguments, **keywords): """creates instance of class that describes namespace declaration""" return namespace_t(*arguments, **keywords)
[ "def", "create_namespace", "(", "self", ",", "*", "arguments", ",", "*", "*", "keywords", ")", ":", "return", "namespace_t", "(", "*", "arguments", ",", "*", "*", "keywords", ")" ]
[ 80, 4 ]
[ 82, 50 ]
python
en
['en', 'en', 'en']
True
decl_factory_t.create_typedef
(self, *arguments, **keywords)
creates instance of class that describes typedef declaration
creates instance of class that describes typedef declaration
def create_typedef(self, *arguments, **keywords): """creates instance of class that describes typedef declaration""" return typedef_t(*arguments, **keywords)
[ "def", "create_typedef", "(", "self", ",", "*", "arguments", ",", "*", "*", "keywords", ")", ":", "return", "typedef_t", "(", "*", "arguments", ",", "*", "*", "keywords", ")" ]
[ 84, 4 ]
[ 86, 48 ]
python
en
['en', 'nl', 'en']
True
decl_factory_t.create_variable
(self, *arguments, **keywords)
creates instance of class that describes variable declaration
creates instance of class that describes variable declaration
def create_variable(self, *arguments, **keywords): """creates instance of class that describes variable declaration""" return variable_t(*arguments, **keywords)
[ "def", "create_variable", "(", "self", ",", "*", "arguments", ",", "*", "*", "keywords", ")", ":", "return", "variable_t", "(", "*", "arguments", ",", "*", "*", "keywords", ")" ]
[ 88, 4 ]
[ 90, 49 ]
python
en
['en', 'en', 'en']
True
bobby_columnar_table_multi_batch
()
# TODO: <Alex>ALEX -- Add DocString</Alex>
# TODO: <Alex>ALEX -- Add DocString</Alex>
def bobby_columnar_table_multi_batch(): """ # TODO: <Alex>ALEX -- Add DocString</Alex> """ verbose_profiler_config_file_path: str = file_relative_path( __file__, "bobby_user_workflow_verbose_profiler_config.yml" ) verbose_profiler_config: str with open(verbose_profiler_config_file_path) as f: verbose_profiler_config = f.read() my_row_count_range_rule_expectation_configurations_oneshot_sampling_method: List[ ExpectationConfiguration ] = [ ExpectationConfiguration( **{ "kwargs": {"min_value": 7505, "max_value": 8495}, "expectation_type": "expect_table_row_count_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "table.row_count", "domain_kwargs": {}, }, "num_batches": 2, }, }, }, ), ] my_column_ranges_rule_expectation_configurations_oneshot_sampling_method: List[ ExpectationConfiguration ] = [ ExpectationConfiguration( **{ "expectation_type": "expect_column_min_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.min", "domain_kwargs": {"column": "VendorID"}, }, "num_batches": 2, } }, "kwargs": { "column": "VendorID", "min_value": 1, "max_value": 1, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_max_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.max", "domain_kwargs": {"column": "VendorID"}, }, "num_batches": 2, } }, "kwargs": { "column": "VendorID", "min_value": 4, "max_value": 4, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_min_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.min", "domain_kwargs": {"column": "passenger_count"}, }, "num_batches": 2, } }, "kwargs": { "column": "passenger_count", "min_value": 0, "max_value": 1, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_max_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.max", "domain_kwargs": {"column": "passenger_count"}, }, "num_batches": 2, } }, "kwargs": { "column": "passenger_count", "min_value": 6, "max_value": 6, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_min_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.min", "domain_kwargs": {"column": "trip_distance"}, }, "num_batches": 2, } }, "kwargs": { "column": "trip_distance", "min_value": 0.0, "max_value": 0.0, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_max_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.max", "domain_kwargs": {"column": "trip_distance"}, }, "num_batches": 2, } }, "kwargs": { "column": "trip_distance", "min_value": 37.62, "max_value": 57.85, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_min_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.min", "domain_kwargs": {"column": "RatecodeID"}, }, "num_batches": 2, } }, "kwargs": { "column": "RatecodeID", "min_value": 1, "max_value": 1, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_max_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.max", "domain_kwargs": {"column": "RatecodeID"}, }, "num_batches": 2, } }, "kwargs": { "column": "RatecodeID", "min_value": 5, "max_value": 6, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_min_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.min", "domain_kwargs": {"column": "PULocationID"}, }, "num_batches": 2, } }, "kwargs": { "column": "PULocationID", "min_value": 1, "max_value": 1, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_max_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.max", "domain_kwargs": {"column": "PULocationID"}, }, "num_batches": 2, } }, "kwargs": { "column": "PULocationID", "min_value": 265, "max_value": 265, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_min_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.min", "domain_kwargs": {"column": "DOLocationID"}, }, "num_batches": 2, } }, "kwargs": { "column": "DOLocationID", "min_value": 1, "max_value": 1, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_max_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.max", "domain_kwargs": {"column": "DOLocationID"}, }, "num_batches": 2, } }, "kwargs": { "column": "DOLocationID", "min_value": 265, "max_value": 265, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_min_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.min", "domain_kwargs": {"column": "payment_type"}, }, "num_batches": 2, } }, "kwargs": { "column": "payment_type", "min_value": 1, "max_value": 1, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_max_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.max", "domain_kwargs": {"column": "payment_type"}, }, "num_batches": 2, } }, "kwargs": { "column": "payment_type", "min_value": 4, "max_value": 4, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_min_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.min", "domain_kwargs": {"column": "fare_amount"}, }, "num_batches": 2, } }, "kwargs": { "column": "fare_amount", "min_value": -51.84, "max_value": -21.16, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_max_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.max", "domain_kwargs": {"column": "fare_amount"}, }, "num_batches": 2, } }, "kwargs": { "column": "fare_amount", "min_value": 228.94, "max_value": 2990.05, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_min_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.min", "domain_kwargs": {"column": "extra"}, }, "num_batches": 2, } }, "kwargs": { "column": "extra", "min_value": -36.53, "max_value": -1.18, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_max_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.max", "domain_kwargs": {"column": "extra"}, }, "num_batches": 2, } }, "kwargs": { "column": "extra", "min_value": 4.51, "max_value": 6.99, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_min_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.min", "domain_kwargs": {"column": "mta_tax"}, }, "num_batches": 2, } }, "kwargs": { "column": "mta_tax", "min_value": -0.5, "max_value": -0.5, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_max_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.max", "domain_kwargs": {"column": "mta_tax"}, }, "num_batches": 2, } }, "kwargs": { "column": "mta_tax", "min_value": 0.69, "max_value": 37.32, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_min_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.min", "domain_kwargs": {"column": "tip_amount"}, }, "num_batches": 2, } }, "kwargs": { "column": "tip_amount", "min_value": 0.0, "max_value": 0.0, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_max_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.max", "domain_kwargs": {"column": "tip_amount"}, }, "num_batches": 2, } }, "kwargs": { "column": "tip_amount", "min_value": 46.84, "max_value": 74.86, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_min_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.min", "domain_kwargs": {"column": "tolls_amount"}, }, "num_batches": 2, } }, "kwargs": { "column": "tolls_amount", "min_value": 0.0, "max_value": 0.0, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_max_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.max", "domain_kwargs": {"column": "tolls_amount"}, }, "num_batches": 2, } }, "kwargs": { "column": "tolls_amount", "min_value": 26.4, "max_value": 497.67, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_min_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.min", "domain_kwargs": {"column": "improvement_surcharge"}, }, "num_batches": 2, } }, "kwargs": { "column": "improvement_surcharge", "min_value": -0.3, "max_value": -0.3, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_max_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.max", "domain_kwargs": {"column": "improvement_surcharge"}, }, "num_batches": 2, } }, "kwargs": { "column": "improvement_surcharge", "min_value": 0.3, "max_value": 0.3, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_min_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.min", "domain_kwargs": {"column": "total_amount"}, }, "num_batches": 2, } }, "kwargs": { "column": "total_amount", "min_value": -52.66, "max_value": -24.44, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_max_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.max", "domain_kwargs": {"column": "total_amount"}, }, "num_batches": 2, } }, "kwargs": { "column": "total_amount", "min_value": 550.18, "max_value": 2992.47, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_min_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.min", "domain_kwargs": {"column": "congestion_surcharge"}, }, "num_batches": 2, } }, "kwargs": { "column": "congestion_surcharge", "min_value": -2.49, "max_value": -0.01, "mostly": 1.0, }, }, ), ExpectationConfiguration( **{ "expectation_type": "expect_column_max_to_be_between", "meta": { "profiler_details": { "metric_configuration": { "metric_name": "column.max", "domain_kwargs": {"column": "congestion_surcharge"}, }, "num_batches": 2, } }, "kwargs": { "column": "congestion_surcharge", "min_value": 0.01, "max_value": 2.49, "mostly": 1.0, }, }, ), ] expectation_configurations: List[ExpectationConfiguration] = [] expectation_configurations.extend( my_row_count_range_rule_expectation_configurations_oneshot_sampling_method ) expectation_configurations.extend( my_column_ranges_rule_expectation_configurations_oneshot_sampling_method ) expectation_suite_name_oneshot_sampling_method: str = ( "bobby_columnar_table_multi_batch_oneshot_sampling_method" ) expected_expectation_suite_oneshot_sampling_method: ExpectationSuite = ( ExpectationSuite( expectation_suite_name=expectation_suite_name_oneshot_sampling_method ) ) expectation_configuration: ExpectationConfiguration for expectation_configuration in expectation_configurations: expected_expectation_suite_oneshot_sampling_method.add_expectation( expectation_configuration ) yaml = YAML() profiler_config: dict = yaml.load(verbose_profiler_config) expected_expectation_suite_oneshot_sampling_method.add_citation( comment="Suite created by Rule-Based Profiler with the configuration included.", profiler_config=profiler_config, ) return { "profiler_config": verbose_profiler_config, "test_configuration_oneshot_sampling_method": { "expectation_suite_name": expectation_suite_name_oneshot_sampling_method, "expected_expectation_suite": expected_expectation_suite_oneshot_sampling_method, }, }
[ "def", "bobby_columnar_table_multi_batch", "(", ")", ":", "verbose_profiler_config_file_path", ":", "str", "=", "file_relative_path", "(", "__file__", ",", "\"bobby_user_workflow_verbose_profiler_config.yml\"", ")", "verbose_profiler_config", ":", "str", "with", "open", "(", "verbose_profiler_config_file_path", ")", "as", "f", ":", "verbose_profiler_config", "=", "f", ".", "read", "(", ")", "my_row_count_range_rule_expectation_configurations_oneshot_sampling_method", ":", "List", "[", "ExpectationConfiguration", "]", "=", "[", "ExpectationConfiguration", "(", "*", "*", "{", "\"kwargs\"", ":", "{", "\"min_value\"", ":", "7505", ",", "\"max_value\"", ":", "8495", "}", ",", "\"expectation_type\"", ":", "\"expect_table_row_count_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"table.row_count\"", ",", "\"domain_kwargs\"", ":", "{", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", ",", "}", ",", "}", ",", ")", ",", "]", "my_column_ranges_rule_expectation_configurations_oneshot_sampling_method", ":", "List", "[", "ExpectationConfiguration", "]", "=", "[", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_min_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.min\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"VendorID\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"VendorID\"", ",", "\"min_value\"", ":", "1", ",", "\"max_value\"", ":", "1", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_max_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.max\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"VendorID\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"VendorID\"", ",", "\"min_value\"", ":", "4", ",", "\"max_value\"", ":", "4", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_min_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.min\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"passenger_count\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"passenger_count\"", ",", "\"min_value\"", ":", "0", ",", "\"max_value\"", ":", "1", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_max_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.max\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"passenger_count\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"passenger_count\"", ",", "\"min_value\"", ":", "6", ",", "\"max_value\"", ":", "6", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_min_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.min\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"trip_distance\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"trip_distance\"", ",", "\"min_value\"", ":", "0.0", ",", "\"max_value\"", ":", "0.0", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_max_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.max\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"trip_distance\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"trip_distance\"", ",", "\"min_value\"", ":", "37.62", ",", "\"max_value\"", ":", "57.85", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_min_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.min\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"RatecodeID\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"RatecodeID\"", ",", "\"min_value\"", ":", "1", ",", "\"max_value\"", ":", "1", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_max_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.max\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"RatecodeID\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"RatecodeID\"", ",", "\"min_value\"", ":", "5", ",", "\"max_value\"", ":", "6", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_min_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.min\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"PULocationID\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"PULocationID\"", ",", "\"min_value\"", ":", "1", ",", "\"max_value\"", ":", "1", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_max_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.max\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"PULocationID\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"PULocationID\"", ",", "\"min_value\"", ":", "265", ",", "\"max_value\"", ":", "265", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_min_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.min\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"DOLocationID\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"DOLocationID\"", ",", "\"min_value\"", ":", "1", ",", "\"max_value\"", ":", "1", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_max_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.max\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"DOLocationID\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"DOLocationID\"", ",", "\"min_value\"", ":", "265", ",", "\"max_value\"", ":", "265", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_min_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.min\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"payment_type\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"payment_type\"", ",", "\"min_value\"", ":", "1", ",", "\"max_value\"", ":", "1", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_max_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.max\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"payment_type\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"payment_type\"", ",", "\"min_value\"", ":", "4", ",", "\"max_value\"", ":", "4", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_min_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.min\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"fare_amount\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"fare_amount\"", ",", "\"min_value\"", ":", "-", "51.84", ",", "\"max_value\"", ":", "-", "21.16", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_max_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.max\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"fare_amount\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"fare_amount\"", ",", "\"min_value\"", ":", "228.94", ",", "\"max_value\"", ":", "2990.05", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_min_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.min\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"extra\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"extra\"", ",", "\"min_value\"", ":", "-", "36.53", ",", "\"max_value\"", ":", "-", "1.18", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_max_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.max\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"extra\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"extra\"", ",", "\"min_value\"", ":", "4.51", ",", "\"max_value\"", ":", "6.99", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_min_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.min\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"mta_tax\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"mta_tax\"", ",", "\"min_value\"", ":", "-", "0.5", ",", "\"max_value\"", ":", "-", "0.5", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_max_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.max\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"mta_tax\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"mta_tax\"", ",", "\"min_value\"", ":", "0.69", ",", "\"max_value\"", ":", "37.32", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_min_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.min\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"tip_amount\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"tip_amount\"", ",", "\"min_value\"", ":", "0.0", ",", "\"max_value\"", ":", "0.0", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_max_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.max\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"tip_amount\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"tip_amount\"", ",", "\"min_value\"", ":", "46.84", ",", "\"max_value\"", ":", "74.86", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_min_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.min\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"tolls_amount\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"tolls_amount\"", ",", "\"min_value\"", ":", "0.0", ",", "\"max_value\"", ":", "0.0", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_max_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.max\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"tolls_amount\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"tolls_amount\"", ",", "\"min_value\"", ":", "26.4", ",", "\"max_value\"", ":", "497.67", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_min_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.min\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"improvement_surcharge\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"improvement_surcharge\"", ",", "\"min_value\"", ":", "-", "0.3", ",", "\"max_value\"", ":", "-", "0.3", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_max_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.max\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"improvement_surcharge\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"improvement_surcharge\"", ",", "\"min_value\"", ":", "0.3", ",", "\"max_value\"", ":", "0.3", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_min_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.min\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"total_amount\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"total_amount\"", ",", "\"min_value\"", ":", "-", "52.66", ",", "\"max_value\"", ":", "-", "24.44", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_max_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.max\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"total_amount\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"total_amount\"", ",", "\"min_value\"", ":", "550.18", ",", "\"max_value\"", ":", "2992.47", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_min_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.min\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"congestion_surcharge\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"congestion_surcharge\"", ",", "\"min_value\"", ":", "-", "2.49", ",", "\"max_value\"", ":", "-", "0.01", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "ExpectationConfiguration", "(", "*", "*", "{", "\"expectation_type\"", ":", "\"expect_column_max_to_be_between\"", ",", "\"meta\"", ":", "{", "\"profiler_details\"", ":", "{", "\"metric_configuration\"", ":", "{", "\"metric_name\"", ":", "\"column.max\"", ",", "\"domain_kwargs\"", ":", "{", "\"column\"", ":", "\"congestion_surcharge\"", "}", ",", "}", ",", "\"num_batches\"", ":", "2", ",", "}", "}", ",", "\"kwargs\"", ":", "{", "\"column\"", ":", "\"congestion_surcharge\"", ",", "\"min_value\"", ":", "0.01", ",", "\"max_value\"", ":", "2.49", ",", "\"mostly\"", ":", "1.0", ",", "}", ",", "}", ",", ")", ",", "]", "expectation_configurations", ":", "List", "[", "ExpectationConfiguration", "]", "=", "[", "]", "expectation_configurations", ".", "extend", "(", "my_row_count_range_rule_expectation_configurations_oneshot_sampling_method", ")", "expectation_configurations", ".", "extend", "(", "my_column_ranges_rule_expectation_configurations_oneshot_sampling_method", ")", "expectation_suite_name_oneshot_sampling_method", ":", "str", "=", "(", "\"bobby_columnar_table_multi_batch_oneshot_sampling_method\"", ")", "expected_expectation_suite_oneshot_sampling_method", ":", "ExpectationSuite", "=", "(", "ExpectationSuite", "(", "expectation_suite_name", "=", "expectation_suite_name_oneshot_sampling_method", ")", ")", "expectation_configuration", ":", "ExpectationConfiguration", "for", "expectation_configuration", "in", "expectation_configurations", ":", "expected_expectation_suite_oneshot_sampling_method", ".", "add_expectation", "(", "expectation_configuration", ")", "yaml", "=", "YAML", "(", ")", "profiler_config", ":", "dict", "=", "yaml", ".", "load", "(", "verbose_profiler_config", ")", "expected_expectation_suite_oneshot_sampling_method", ".", "add_citation", "(", "comment", "=", "\"Suite created by Rule-Based Profiler with the configuration included.\"", ",", "profiler_config", "=", "profiler_config", ",", ")", "return", "{", "\"profiler_config\"", ":", "verbose_profiler_config", ",", "\"test_configuration_oneshot_sampling_method\"", ":", "{", "\"expectation_suite_name\"", ":", "expectation_suite_name_oneshot_sampling_method", ",", "\"expected_expectation_suite\"", ":", "expected_expectation_suite_oneshot_sampling_method", ",", "}", ",", "}" ]
[ 14, 0 ]
[ 687, 5 ]
python
en
['en', 'error', 'th']
False
DragonNet.__init__
(self, neurons_per_layer=200, targeted_reg=True, ratio=1., val_split=0.2, batch_size=64, epochs=30, learning_rate=1e-3, reg_l2=0.01, loss_func=dragonnet_loss_binarycross, verbose=True)
Initializes a Dragonnet.
Initializes a Dragonnet.
def __init__(self, neurons_per_layer=200, targeted_reg=True, ratio=1., val_split=0.2, batch_size=64, epochs=30, learning_rate=1e-3, reg_l2=0.01, loss_func=dragonnet_loss_binarycross, verbose=True): """ Initializes a Dragonnet. """ self.neurons_per_layer = neurons_per_layer self.targeted_reg = targeted_reg self.ratio = ratio self.val_split = val_split self.batch_size = batch_size self.epochs = epochs self.learning_rate = learning_rate self.loss_func = loss_func self.reg_l2 = reg_l2 self.verbose = verbose
[ "def", "__init__", "(", "self", ",", "neurons_per_layer", "=", "200", ",", "targeted_reg", "=", "True", ",", "ratio", "=", "1.", ",", "val_split", "=", "0.2", ",", "batch_size", "=", "64", ",", "epochs", "=", "30", ",", "learning_rate", "=", "1e-3", ",", "reg_l2", "=", "0.01", ",", "loss_func", "=", "dragonnet_loss_binarycross", ",", "verbose", "=", "True", ")", ":", "self", ".", "neurons_per_layer", "=", "neurons_per_layer", "self", ".", "targeted_reg", "=", "targeted_reg", "self", ".", "ratio", "=", "ratio", "self", ".", "val_split", "=", "val_split", "self", ".", "batch_size", "=", "batch_size", "self", ".", "epochs", "=", "epochs", "self", ".", "learning_rate", "=", "learning_rate", "self", ".", "loss_func", "=", "loss_func", "self", ".", "reg_l2", "=", "reg_l2", "self", ".", "verbose", "=", "verbose" ]
[ 31, 4 ]
[ 46, 30 ]
python
en
['en', 'error', 'th']
False
DragonNet.make_dragonnet
(self, input_dim)
Neural net predictive model. The dragon has three heads. Args: input_dim (int): number of rows in input Returns: model (keras.models.Model): DragonNet model
Neural net predictive model. The dragon has three heads.
def make_dragonnet(self, input_dim): """ Neural net predictive model. The dragon has three heads. Args: input_dim (int): number of rows in input Returns: model (keras.models.Model): DragonNet model """ inputs = Input(shape=(input_dim,), name='input') # representation x = Dense(units=self.neurons_per_layer, activation='elu', kernel_initializer='RandomNormal')(inputs) x = Dense(units=self.neurons_per_layer, activation='elu', kernel_initializer='RandomNormal')(x) x = Dense(units=self.neurons_per_layer, activation='elu', kernel_initializer='RandomNormal')(x) t_predictions = Dense(units=1, activation='sigmoid')(x) # HYPOTHESIS y0_hidden = Dense(units=int(self.neurons_per_layer / 2), activation='elu', kernel_regularizer=l2(self.reg_l2))(x) y1_hidden = Dense(units=int(self.neurons_per_layer/2), activation='elu', kernel_regularizer=l2(self.reg_l2))(x) # second layer y0_hidden = Dense(units=int(self.neurons_per_layer/2), activation='elu', kernel_regularizer=l2(self.reg_l2))(y0_hidden) y1_hidden = Dense(units=int(self.neurons_per_layer / 2), activation='elu', kernel_regularizer=l2(self.reg_l2))(y1_hidden) # third y0_predictions = Dense(units=1, activation=None, kernel_regularizer=l2(self.reg_l2), name='y0_predictions')(y0_hidden) y1_predictions = Dense(units=1, activation=None, kernel_regularizer=l2(self.reg_l2), name='y1_predictions')(y1_hidden) dl = EpsilonLayer() epsilons = dl(t_predictions, name='epsilon') concat_pred = Concatenate(1)([y0_predictions, y1_predictions, t_predictions, epsilons]) model = Model(inputs=inputs, outputs=concat_pred) return model
[ "def", "make_dragonnet", "(", "self", ",", "input_dim", ")", ":", "inputs", "=", "Input", "(", "shape", "=", "(", "input_dim", ",", ")", ",", "name", "=", "'input'", ")", "# representation", "x", "=", "Dense", "(", "units", "=", "self", ".", "neurons_per_layer", ",", "activation", "=", "'elu'", ",", "kernel_initializer", "=", "'RandomNormal'", ")", "(", "inputs", ")", "x", "=", "Dense", "(", "units", "=", "self", ".", "neurons_per_layer", ",", "activation", "=", "'elu'", ",", "kernel_initializer", "=", "'RandomNormal'", ")", "(", "x", ")", "x", "=", "Dense", "(", "units", "=", "self", ".", "neurons_per_layer", ",", "activation", "=", "'elu'", ",", "kernel_initializer", "=", "'RandomNormal'", ")", "(", "x", ")", "t_predictions", "=", "Dense", "(", "units", "=", "1", ",", "activation", "=", "'sigmoid'", ")", "(", "x", ")", "# HYPOTHESIS", "y0_hidden", "=", "Dense", "(", "units", "=", "int", "(", "self", ".", "neurons_per_layer", "/", "2", ")", ",", "activation", "=", "'elu'", ",", "kernel_regularizer", "=", "l2", "(", "self", ".", "reg_l2", ")", ")", "(", "x", ")", "y1_hidden", "=", "Dense", "(", "units", "=", "int", "(", "self", ".", "neurons_per_layer", "/", "2", ")", ",", "activation", "=", "'elu'", ",", "kernel_regularizer", "=", "l2", "(", "self", ".", "reg_l2", ")", ")", "(", "x", ")", "# second layer", "y0_hidden", "=", "Dense", "(", "units", "=", "int", "(", "self", ".", "neurons_per_layer", "/", "2", ")", ",", "activation", "=", "'elu'", ",", "kernel_regularizer", "=", "l2", "(", "self", ".", "reg_l2", ")", ")", "(", "y0_hidden", ")", "y1_hidden", "=", "Dense", "(", "units", "=", "int", "(", "self", ".", "neurons_per_layer", "/", "2", ")", ",", "activation", "=", "'elu'", ",", "kernel_regularizer", "=", "l2", "(", "self", ".", "reg_l2", ")", ")", "(", "y1_hidden", ")", "# third", "y0_predictions", "=", "Dense", "(", "units", "=", "1", ",", "activation", "=", "None", ",", "kernel_regularizer", "=", "l2", "(", "self", ".", "reg_l2", ")", ",", "name", "=", "'y0_predictions'", ")", "(", "y0_hidden", ")", "y1_predictions", "=", "Dense", "(", "units", "=", "1", ",", "activation", "=", "None", ",", "kernel_regularizer", "=", "l2", "(", "self", ".", "reg_l2", ")", ",", "name", "=", "'y1_predictions'", ")", "(", "y1_hidden", ")", "dl", "=", "EpsilonLayer", "(", ")", "epsilons", "=", "dl", "(", "t_predictions", ",", "name", "=", "'epsilon'", ")", "concat_pred", "=", "Concatenate", "(", "1", ")", "(", "[", "y0_predictions", ",", "y1_predictions", ",", "t_predictions", ",", "epsilons", "]", ")", "model", "=", "Model", "(", "inputs", "=", "inputs", ",", "outputs", "=", "concat_pred", ")", "return", "model" ]
[ 48, 4 ]
[ 97, 20 ]
python
en
['en', 'error', 'th']
False
DragonNet.fit
(self, X, treatment, y, p=None)
Fits the DragonNet model. Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix treatment (np.array or pd.Series): a treatment vector y (np.array or pd.Series): an outcome vector
Fits the DragonNet model.
def fit(self, X, treatment, y, p=None): """ Fits the DragonNet model. Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix treatment (np.array or pd.Series): a treatment vector y (np.array or pd.Series): an outcome vector """ X, treatment, y = convert_pd_to_np(X, treatment, y) y = np.hstack((y.reshape(-1, 1), treatment.reshape(-1, 1))) self.dragonnet = self.make_dragonnet(X.shape[1]) metrics = [regression_loss, binary_classification_loss, treatment_accuracy, track_epsilon] if self.targeted_reg: loss = make_tarreg_loss(ratio=self.ratio, dragonnet_loss=self.loss_func) else: loss = self.loss_func self.dragonnet.compile( optimizer=Adam(lr=self.learning_rate), loss=loss, metrics=metrics) adam_callbacks = [ TerminateOnNaN(), EarlyStopping(monitor='val_loss', patience=2, min_delta=0.), ReduceLROnPlateau(monitor='loss', factor=0.5, patience=5, verbose=self.verbose, mode='auto', min_delta=1e-8, cooldown=0, min_lr=0) ] self.dragonnet.fit(X, y, callbacks=adam_callbacks, validation_split=self.val_split, epochs=self.epochs, batch_size=self.batch_size, verbose=self.verbose) sgd_callbacks = [ TerminateOnNaN(), EarlyStopping(monitor='val_loss', patience=40, min_delta=0.), ReduceLROnPlateau(monitor='loss', factor=0.5, patience=5, verbose=self.verbose, mode='auto', min_delta=0., cooldown=0, min_lr=0) ] sgd_lr = 1e-5 momentum = 0.9 self.dragonnet.compile(optimizer=SGD(lr=sgd_lr, momentum=momentum, nesterov=True), loss=loss, metrics=metrics) self.dragonnet.fit(X, y, callbacks=sgd_callbacks, validation_split=self.val_split, epochs=300, batch_size=self.batch_size, verbose=self.verbose)
[ "def", "fit", "(", "self", ",", "X", ",", "treatment", ",", "y", ",", "p", "=", "None", ")", ":", "X", ",", "treatment", ",", "y", "=", "convert_pd_to_np", "(", "X", ",", "treatment", ",", "y", ")", "y", "=", "np", ".", "hstack", "(", "(", "y", ".", "reshape", "(", "-", "1", ",", "1", ")", ",", "treatment", ".", "reshape", "(", "-", "1", ",", "1", ")", ")", ")", "self", ".", "dragonnet", "=", "self", ".", "make_dragonnet", "(", "X", ".", "shape", "[", "1", "]", ")", "metrics", "=", "[", "regression_loss", ",", "binary_classification_loss", ",", "treatment_accuracy", ",", "track_epsilon", "]", "if", "self", ".", "targeted_reg", ":", "loss", "=", "make_tarreg_loss", "(", "ratio", "=", "self", ".", "ratio", ",", "dragonnet_loss", "=", "self", ".", "loss_func", ")", "else", ":", "loss", "=", "self", ".", "loss_func", "self", ".", "dragonnet", ".", "compile", "(", "optimizer", "=", "Adam", "(", "lr", "=", "self", ".", "learning_rate", ")", ",", "loss", "=", "loss", ",", "metrics", "=", "metrics", ")", "adam_callbacks", "=", "[", "TerminateOnNaN", "(", ")", ",", "EarlyStopping", "(", "monitor", "=", "'val_loss'", ",", "patience", "=", "2", ",", "min_delta", "=", "0.", ")", ",", "ReduceLROnPlateau", "(", "monitor", "=", "'loss'", ",", "factor", "=", "0.5", ",", "patience", "=", "5", ",", "verbose", "=", "self", ".", "verbose", ",", "mode", "=", "'auto'", ",", "min_delta", "=", "1e-8", ",", "cooldown", "=", "0", ",", "min_lr", "=", "0", ")", "]", "self", ".", "dragonnet", ".", "fit", "(", "X", ",", "y", ",", "callbacks", "=", "adam_callbacks", ",", "validation_split", "=", "self", ".", "val_split", ",", "epochs", "=", "self", ".", "epochs", ",", "batch_size", "=", "self", ".", "batch_size", ",", "verbose", "=", "self", ".", "verbose", ")", "sgd_callbacks", "=", "[", "TerminateOnNaN", "(", ")", ",", "EarlyStopping", "(", "monitor", "=", "'val_loss'", ",", "patience", "=", "40", ",", "min_delta", "=", "0.", ")", ",", "ReduceLROnPlateau", "(", "monitor", "=", "'loss'", ",", "factor", "=", "0.5", ",", "patience", "=", "5", ",", "verbose", "=", "self", ".", "verbose", ",", "mode", "=", "'auto'", ",", "min_delta", "=", "0.", ",", "cooldown", "=", "0", ",", "min_lr", "=", "0", ")", "]", "sgd_lr", "=", "1e-5", "momentum", "=", "0.9", "self", ".", "dragonnet", ".", "compile", "(", "optimizer", "=", "SGD", "(", "lr", "=", "sgd_lr", ",", "momentum", "=", "momentum", ",", "nesterov", "=", "True", ")", ",", "loss", "=", "loss", ",", "metrics", "=", "metrics", ")", "self", ".", "dragonnet", ".", "fit", "(", "X", ",", "y", ",", "callbacks", "=", "sgd_callbacks", ",", "validation_split", "=", "self", ".", "val_split", ",", "epochs", "=", "300", ",", "batch_size", "=", "self", ".", "batch_size", ",", "verbose", "=", "self", ".", "verbose", ")" ]
[ 99, 4 ]
[ 155, 48 ]
python
en
['en', 'error', 'th']
False
DragonNet.predict
(self, X, treatment=None, y=None, p=None)
Calls predict on fitted DragonNet. Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix Returns: (np.array): a 2D array with shape (X.shape[0], 4), where each row takes the form of (outcome do(t=0), outcome do(t=1), propensity, epsilon)
Calls predict on fitted DragonNet.
def predict(self, X, treatment=None, y=None, p=None): """ Calls predict on fitted DragonNet. Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix Returns: (np.array): a 2D array with shape (X.shape[0], 4), where each row takes the form of (outcome do(t=0), outcome do(t=1), propensity, epsilon) """ return self.dragonnet.predict(X)
[ "def", "predict", "(", "self", ",", "X", ",", "treatment", "=", "None", ",", "y", "=", "None", ",", "p", "=", "None", ")", ":", "return", "self", ".", "dragonnet", ".", "predict", "(", "X", ")" ]
[ 157, 4 ]
[ 167, 40 ]
python
en
['en', 'error', 'th']
False
DragonNet.predict_propensity
(self, X)
Predicts the individual propensity scores. Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix Returns: (np.array): propensity score vector
Predicts the individual propensity scores.
def predict_propensity(self, X): """ Predicts the individual propensity scores. Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix Returns: (np.array): propensity score vector """ preds = self.predict(X) return preds[:, 2]
[ "def", "predict_propensity", "(", "self", ",", "X", ")", ":", "preds", "=", "self", ".", "predict", "(", "X", ")", "return", "preds", "[", ":", ",", "2", "]" ]
[ 169, 4 ]
[ 179, 26 ]
python
en
['en', 'error', 'th']
False
DragonNet.predict_tau
(self, X)
Predicts the individual treatment effect (tau / "ITE"). Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix Returns: (np.array): treatment effect vector
Predicts the individual treatment effect (tau / "ITE").
def predict_tau(self, X): """ Predicts the individual treatment effect (tau / "ITE"). Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix Returns: (np.array): treatment effect vector """ preds = self.predict(X) return (preds[:, 1] - preds[:, 0]).reshape(-1, 1)
[ "def", "predict_tau", "(", "self", ",", "X", ")", ":", "preds", "=", "self", ".", "predict", "(", "X", ")", "return", "(", "preds", "[", ":", ",", "1", "]", "-", "preds", "[", ":", ",", "0", "]", ")", ".", "reshape", "(", "-", "1", ",", "1", ")" ]
[ 181, 4 ]
[ 191, 57 ]
python
en
['en', 'error', 'th']
False
DragonNet.fit_predict
(self, X, treatment, y, p=None, return_components=False)
Fits the DragonNet model and then predicts. Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix treatment (np.array or pd.Series): a treatment vector y (np.array or pd.Series): an outcome vector return_components (bool, optional): whether to return Returns: (np.array): predictions based on return_components flag if return_components=False (default), each row is treatment effect if return_components=True, each row is (outcome do(t=0), outcome do(t=1), propensity, epsilon)
Fits the DragonNet model and then predicts.
def fit_predict(self, X, treatment, y, p=None, return_components=False): """ Fits the DragonNet model and then predicts. Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix treatment (np.array or pd.Series): a treatment vector y (np.array or pd.Series): an outcome vector return_components (bool, optional): whether to return Returns: (np.array): predictions based on return_components flag if return_components=False (default), each row is treatment effect if return_components=True, each row is (outcome do(t=0), outcome do(t=1), propensity, epsilon) """ self.fit(X, treatment, y) return self.predict_tau(X)
[ "def", "fit_predict", "(", "self", ",", "X", ",", "treatment", ",", "y", ",", "p", "=", "None", ",", "return_components", "=", "False", ")", ":", "self", ".", "fit", "(", "X", ",", "treatment", ",", "y", ")", "return", "self", ".", "predict_tau", "(", "X", ")" ]
[ 193, 4 ]
[ 208, 34 ]
python
en
['en', 'error', 'th']
False
ExceptionAppend
(e, msg)
Append a message to the given exception's message.
Append a message to the given exception's message.
def ExceptionAppend(e, msg): """Append a message to the given exception's message.""" if not e.args: e.args = (msg,) elif len(e.args) == 1: e.args = (str(e.args[0]) + ' ' + msg,) else: e.args = (str(e.args[0]) + ' ' + msg,) + e.args[1:]
[ "def", "ExceptionAppend", "(", "e", ",", "msg", ")", ":", "if", "not", "e", ".", "args", ":", "e", ".", "args", "=", "(", "msg", ",", ")", "elif", "len", "(", "e", ".", "args", ")", "==", "1", ":", "e", ".", "args", "=", "(", "str", "(", "e", ".", "args", "[", "0", "]", ")", "+", "' '", "+", "msg", ",", ")", "else", ":", "e", ".", "args", "=", "(", "str", "(", "e", ".", "args", "[", "0", "]", ")", "+", "' '", "+", "msg", ",", ")", "+", "e", ".", "args", "[", "1", ":", "]" ]
[ 37, 0 ]
[ 44, 55 ]
python
en
['en', 'en', 'en']
True
FindQualifiedTargets
(target, qualified_list)
Given a list of qualified targets, return the qualified targets for the specified |target|.
Given a list of qualified targets, return the qualified targets for the specified |target|.
def FindQualifiedTargets(target, qualified_list): """ Given a list of qualified targets, return the qualified targets for the specified |target|. """ return [t for t in qualified_list if ParseQualifiedTarget(t)[1] == target]
[ "def", "FindQualifiedTargets", "(", "target", ",", "qualified_list", ")", ":", "return", "[", "t", "for", "t", "in", "qualified_list", "if", "ParseQualifiedTarget", "(", "t", ")", "[", "1", "]", "==", "target", "]" ]
[ 47, 0 ]
[ 52, 76 ]
python
en
['en', 'error', 'th']
False
GetEnvironFallback
(var_list, default)
Look up a key in the environment, with fallback to secondary keys and finally falling back to a default value.
Look up a key in the environment, with fallback to secondary keys and finally falling back to a default value.
def GetEnvironFallback(var_list, default): """Look up a key in the environment, with fallback to secondary keys and finally falling back to a default value.""" for var in var_list: if var in os.environ: return os.environ[var] return default
[ "def", "GetEnvironFallback", "(", "var_list", ",", "default", ")", ":", "for", "var", "in", "var_list", ":", "if", "var", "in", "os", ".", "environ", ":", "return", "os", ".", "environ", "[", "var", "]", "return", "default" ]
[ 113, 0 ]
[ 119, 16 ]
python
en
['en', 'en', 'en']
True
InvertRelativePath
(path, toplevel_dir=None)
Given a path like foo/bar that is relative to toplevel_dir, return the inverse relative path back to the toplevel_dir. E.g. os.path.normpath(os.path.join(path, InvertRelativePath(path))) should always produce the empty string, unless the path contains symlinks.
Given a path like foo/bar that is relative to toplevel_dir, return the inverse relative path back to the toplevel_dir.
def InvertRelativePath(path, toplevel_dir=None): """Given a path like foo/bar that is relative to toplevel_dir, return the inverse relative path back to the toplevel_dir. E.g. os.path.normpath(os.path.join(path, InvertRelativePath(path))) should always produce the empty string, unless the path contains symlinks. """ if not path: return path toplevel_dir = '.' if toplevel_dir is None else toplevel_dir return RelativePath(toplevel_dir, os.path.join(toplevel_dir, path))
[ "def", "InvertRelativePath", "(", "path", ",", "toplevel_dir", "=", "None", ")", ":", "if", "not", "path", ":", "return", "path", "toplevel_dir", "=", "'.'", "if", "toplevel_dir", "is", "None", "else", "toplevel_dir", "return", "RelativePath", "(", "toplevel_dir", ",", "os", ".", "path", ".", "join", "(", "toplevel_dir", ",", "path", ")", ")" ]
[ 177, 0 ]
[ 187, 69 ]
python
en
['en', 'en', 'en']
True
EncodePOSIXShellArgument
(argument)
Encodes |argument| suitably for consumption by POSIX shells. argument may be quoted and escaped as necessary to ensure that POSIX shells treat the returned value as a literal representing the argument passed to this function. Parameter (variable) expansions beginning with $ are allowed to remain intact without escaping the $, to allow the argument to contain references to variables to be expanded by the shell.
Encodes |argument| suitably for consumption by POSIX shells.
def EncodePOSIXShellArgument(argument): """Encodes |argument| suitably for consumption by POSIX shells. argument may be quoted and escaped as necessary to ensure that POSIX shells treat the returned value as a literal representing the argument passed to this function. Parameter (variable) expansions beginning with $ are allowed to remain intact without escaping the $, to allow the argument to contain references to variables to be expanded by the shell. """ if not isinstance(argument, str): argument = str(argument) if _quote.search(argument): quote = '"' else: quote = '' encoded = quote + re.sub(_escape, r'\\\1', argument) + quote return encoded
[ "def", "EncodePOSIXShellArgument", "(", "argument", ")", ":", "if", "not", "isinstance", "(", "argument", ",", "str", ")", ":", "argument", "=", "str", "(", "argument", ")", "if", "_quote", ".", "search", "(", "argument", ")", ":", "quote", "=", "'\"'", "else", ":", "quote", "=", "''", "encoded", "=", "quote", "+", "re", ".", "sub", "(", "_escape", ",", "r'\\\\\\1'", ",", "argument", ")", "+", "quote", "return", "encoded" ]
[ 259, 0 ]
[ 279, 16 ]
python
en
['en', 'en', 'en']
True
EncodePOSIXShellList
(list)
Encodes |list| suitably for consumption by POSIX shells. Returns EncodePOSIXShellArgument for each item in list, and joins them together using the space character as an argument separator.
Encodes |list| suitably for consumption by POSIX shells.
def EncodePOSIXShellList(list): """Encodes |list| suitably for consumption by POSIX shells. Returns EncodePOSIXShellArgument for each item in list, and joins them together using the space character as an argument separator. """ encoded_arguments = [] for argument in list: encoded_arguments.append(EncodePOSIXShellArgument(argument)) return ' '.join(encoded_arguments)
[ "def", "EncodePOSIXShellList", "(", "list", ")", ":", "encoded_arguments", "=", "[", "]", "for", "argument", "in", "list", ":", "encoded_arguments", ".", "append", "(", "EncodePOSIXShellArgument", "(", "argument", ")", ")", "return", "' '", ".", "join", "(", "encoded_arguments", ")" ]
[ 282, 0 ]
[ 292, 36 ]
python
en
['en', 'en', 'en']
True
DeepDependencyTargets
(target_dicts, roots)
Returns the recursive list of target dependencies.
Returns the recursive list of target dependencies.
def DeepDependencyTargets(target_dicts, roots): """Returns the recursive list of target dependencies.""" dependencies = set() pending = set(roots) while pending: # Pluck out one. r = pending.pop() # Skip if visited already. if r in dependencies: continue # Add it. dependencies.add(r) # Add its children. spec = target_dicts[r] pending.update(set(spec.get('dependencies', []))) pending.update(set(spec.get('dependencies_original', []))) return list(dependencies - set(roots))
[ "def", "DeepDependencyTargets", "(", "target_dicts", ",", "roots", ")", ":", "dependencies", "=", "set", "(", ")", "pending", "=", "set", "(", "roots", ")", "while", "pending", ":", "# Pluck out one.", "r", "=", "pending", ".", "pop", "(", ")", "# Skip if visited already.", "if", "r", "in", "dependencies", ":", "continue", "# Add it.", "dependencies", ".", "add", "(", "r", ")", "# Add its children.", "spec", "=", "target_dicts", "[", "r", "]", "pending", ".", "update", "(", "set", "(", "spec", ".", "get", "(", "'dependencies'", ",", "[", "]", ")", ")", ")", "pending", ".", "update", "(", "set", "(", "spec", ".", "get", "(", "'dependencies_original'", ",", "[", "]", ")", ")", ")", "return", "list", "(", "dependencies", "-", "set", "(", "roots", ")", ")" ]
[ 295, 0 ]
[ 311, 40 ]
python
en
['en', 'nl', 'en']
True
BuildFileTargets
(target_list, build_file)
From a target_list, returns the subset from the specified build_file.
From a target_list, returns the subset from the specified build_file.
def BuildFileTargets(target_list, build_file): """From a target_list, returns the subset from the specified build_file. """ return [p for p in target_list if BuildFile(p) == build_file]
[ "def", "BuildFileTargets", "(", "target_list", ",", "build_file", ")", ":", "return", "[", "p", "for", "p", "in", "target_list", "if", "BuildFile", "(", "p", ")", "==", "build_file", "]" ]
[ 314, 0 ]
[ 317, 63 ]
python
en
['en', 'en', 'en']
True
AllTargets
(target_list, target_dicts, build_file)
Returns all targets (direct and dependencies) for the specified build_file.
Returns all targets (direct and dependencies) for the specified build_file.
def AllTargets(target_list, target_dicts, build_file): """Returns all targets (direct and dependencies) for the specified build_file. """ bftargets = BuildFileTargets(target_list, build_file) deptargets = DeepDependencyTargets(target_dicts, bftargets) return bftargets + deptargets
[ "def", "AllTargets", "(", "target_list", ",", "target_dicts", ",", "build_file", ")", ":", "bftargets", "=", "BuildFileTargets", "(", "target_list", ",", "build_file", ")", "deptargets", "=", "DeepDependencyTargets", "(", "target_dicts", ",", "bftargets", ")", "return", "bftargets", "+", "deptargets" ]
[ 320, 0 ]
[ 325, 31 ]
python
en
['en', 'en', 'en']
True
WriteOnDiff
(filename)
Write to a file only if the new contents differ. Arguments: filename: name of the file to potentially write to. Returns: A file like object which will write to temporary file and only overwrite the target if it differs (on close).
Write to a file only if the new contents differ.
def WriteOnDiff(filename): """Write to a file only if the new contents differ. Arguments: filename: name of the file to potentially write to. Returns: A file like object which will write to temporary file and only overwrite the target if it differs (on close). """ class Writer(object): """Wrapper around file which only covers the target if it differs.""" def __init__(self): # Pick temporary file. tmp_fd, self.tmp_path = tempfile.mkstemp( suffix='.tmp', prefix=os.path.split(filename)[1] + '.gyp.', dir=os.path.split(filename)[0]) try: self.tmp_file = os.fdopen(tmp_fd, 'wb') except Exception: # Don't leave turds behind. os.unlink(self.tmp_path) raise def __getattr__(self, attrname): # Delegate everything else to self.tmp_file return getattr(self.tmp_file, attrname) def close(self): try: # Close tmp file. self.tmp_file.close() # Determine if different. same = False try: same = filecmp.cmp(self.tmp_path, filename, False) except OSError, e: if e.errno != errno.ENOENT: raise if same: # The new file is identical to the old one, just get rid of the new # one. os.unlink(self.tmp_path) else: # The new file is different from the old one, or there is no old one. # Rename the new file to the permanent name. # # tempfile.mkstemp uses an overly restrictive mode, resulting in a # file that can only be read by the owner, regardless of the umask. # There's no reason to not respect the umask here, which means that # an extra hoop is required to fetch it and reset the new file's mode. # # No way to get the umask without setting a new one? Set a safe one # and then set it back to the old value. umask = os.umask(077) os.umask(umask) os.chmod(self.tmp_path, 0666 & ~umask) if sys.platform == 'win32' and os.path.exists(filename): # NOTE: on windows (but not cygwin) rename will not replace an # existing file, so it must be preceded with a remove. Sadly there # is no way to make the switch atomic. os.remove(filename) os.rename(self.tmp_path, filename) except Exception: # Don't leave turds behind. os.unlink(self.tmp_path) raise return Writer()
[ "def", "WriteOnDiff", "(", "filename", ")", ":", "class", "Writer", "(", "object", ")", ":", "\"\"\"Wrapper around file which only covers the target if it differs.\"\"\"", "def", "__init__", "(", "self", ")", ":", "# Pick temporary file.", "tmp_fd", ",", "self", ".", "tmp_path", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "'.tmp'", ",", "prefix", "=", "os", ".", "path", ".", "split", "(", "filename", ")", "[", "1", "]", "+", "'.gyp.'", ",", "dir", "=", "os", ".", "path", ".", "split", "(", "filename", ")", "[", "0", "]", ")", "try", ":", "self", ".", "tmp_file", "=", "os", ".", "fdopen", "(", "tmp_fd", ",", "'wb'", ")", "except", "Exception", ":", "# Don't leave turds behind.", "os", ".", "unlink", "(", "self", ".", "tmp_path", ")", "raise", "def", "__getattr__", "(", "self", ",", "attrname", ")", ":", "# Delegate everything else to self.tmp_file", "return", "getattr", "(", "self", ".", "tmp_file", ",", "attrname", ")", "def", "close", "(", "self", ")", ":", "try", ":", "# Close tmp file.", "self", ".", "tmp_file", ".", "close", "(", ")", "# Determine if different.", "same", "=", "False", "try", ":", "same", "=", "filecmp", ".", "cmp", "(", "self", ".", "tmp_path", ",", "filename", ",", "False", ")", "except", "OSError", ",", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "ENOENT", ":", "raise", "if", "same", ":", "# The new file is identical to the old one, just get rid of the new", "# one.", "os", ".", "unlink", "(", "self", ".", "tmp_path", ")", "else", ":", "# The new file is different from the old one, or there is no old one.", "# Rename the new file to the permanent name.", "#", "# tempfile.mkstemp uses an overly restrictive mode, resulting in a", "# file that can only be read by the owner, regardless of the umask.", "# There's no reason to not respect the umask here, which means that", "# an extra hoop is required to fetch it and reset the new file's mode.", "#", "# No way to get the umask without setting a new one? Set a safe one", "# and then set it back to the old value.", "umask", "=", "os", ".", "umask", "(", "077", ")", "os", ".", "umask", "(", "umask", ")", "os", ".", "chmod", "(", "self", ".", "tmp_path", ",", "0666", "&", "~", "umask", ")", "if", "sys", ".", "platform", "==", "'win32'", "and", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "# NOTE: on windows (but not cygwin) rename will not replace an", "# existing file, so it must be preceded with a remove. Sadly there", "# is no way to make the switch atomic.", "os", ".", "remove", "(", "filename", ")", "os", ".", "rename", "(", "self", ".", "tmp_path", ",", "filename", ")", "except", "Exception", ":", "# Don't leave turds behind.", "os", ".", "unlink", "(", "self", ".", "tmp_path", ")", "raise", "return", "Writer", "(", ")" ]
[ 328, 0 ]
[ 398, 17 ]
python
en
['en', 'en', 'en']
True
EnsureDirExists
(path)
Make sure the directory for |path| exists.
Make sure the directory for |path| exists.
def EnsureDirExists(path): """Make sure the directory for |path| exists.""" try: os.makedirs(os.path.dirname(path)) except OSError: pass
[ "def", "EnsureDirExists", "(", "path", ")", ":", "try", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ")", "except", "OSError", ":", "pass" ]
[ 401, 0 ]
[ 406, 8 ]
python
en
['en', 'en', 'en']
True
GetFlavor
(params)
Returns |params.flavor| if it's set, the system's default flavor else.
Returns |params.flavor| if it's set, the system's default flavor else.
def GetFlavor(params): """Returns |params.flavor| if it's set, the system's default flavor else.""" flavors = { 'cygwin': 'win', 'win32': 'win', 'darwin': 'mac', } if 'flavor' in params: return params['flavor'] if sys.platform in flavors: return flavors[sys.platform] if sys.platform.startswith('sunos'): return 'solaris' if sys.platform.startswith('freebsd'): return 'freebsd' if sys.platform.startswith('openbsd'): return 'openbsd' if sys.platform.startswith('netbsd'): return 'netbsd' if sys.platform.startswith('aix'): return 'aix' if sys.platform.startswith('zos'): return 'zos' if sys.platform.startswith('os390'): return 'zos' return 'linux'
[ "def", "GetFlavor", "(", "params", ")", ":", "flavors", "=", "{", "'cygwin'", ":", "'win'", ",", "'win32'", ":", "'win'", ",", "'darwin'", ":", "'mac'", ",", "}", "if", "'flavor'", "in", "params", ":", "return", "params", "[", "'flavor'", "]", "if", "sys", ".", "platform", "in", "flavors", ":", "return", "flavors", "[", "sys", ".", "platform", "]", "if", "sys", ".", "platform", ".", "startswith", "(", "'sunos'", ")", ":", "return", "'solaris'", "if", "sys", ".", "platform", ".", "startswith", "(", "'freebsd'", ")", ":", "return", "'freebsd'", "if", "sys", ".", "platform", ".", "startswith", "(", "'openbsd'", ")", ":", "return", "'openbsd'", "if", "sys", ".", "platform", ".", "startswith", "(", "'netbsd'", ")", ":", "return", "'netbsd'", "if", "sys", ".", "platform", ".", "startswith", "(", "'aix'", ")", ":", "return", "'aix'", "if", "sys", ".", "platform", ".", "startswith", "(", "'zos'", ")", ":", "return", "'zos'", "if", "sys", ".", "platform", ".", "startswith", "(", "'os390'", ")", ":", "return", "'zos'", "return", "'linux'" ]
[ 409, 0 ]
[ 436, 16 ]
python
en
['en', 'fr', 'en']
True
CopyTool
(flavor, out_path)
Finds (flock|mac|win)_tool.gyp in the gyp directory and copies it to |out_path|.
Finds (flock|mac|win)_tool.gyp in the gyp directory and copies it to |out_path|.
def CopyTool(flavor, out_path): """Finds (flock|mac|win)_tool.gyp in the gyp directory and copies it to |out_path|.""" # aix and solaris just need flock emulation. mac and win use more complicated # support scripts. prefix = { 'aix': 'flock', 'solaris': 'flock', 'mac': 'mac', 'win': 'win' }.get(flavor, None) if not prefix: return # Slurp input file. source_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), '%s_tool.py' % prefix) with open(source_path) as source_file: source = source_file.readlines() # Add header and write it out. tool_path = os.path.join(out_path, 'gyp-%s-tool' % prefix) with open(tool_path, 'w') as tool_file: tool_file.write( ''.join([source[0], '# Generated by gyp. Do not edit.\n'] + source[1:])) # Make file executable. os.chmod(tool_path, 0755)
[ "def", "CopyTool", "(", "flavor", ",", "out_path", ")", ":", "# aix and solaris just need flock emulation. mac and win use more complicated", "# support scripts.", "prefix", "=", "{", "'aix'", ":", "'flock'", ",", "'solaris'", ":", "'flock'", ",", "'mac'", ":", "'mac'", ",", "'win'", ":", "'win'", "}", ".", "get", "(", "flavor", ",", "None", ")", "if", "not", "prefix", ":", "return", "# Slurp input file.", "source_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", ",", "'%s_tool.py'", "%", "prefix", ")", "with", "open", "(", "source_path", ")", "as", "source_file", ":", "source", "=", "source_file", ".", "readlines", "(", ")", "# Add header and write it out.", "tool_path", "=", "os", ".", "path", ".", "join", "(", "out_path", ",", "'gyp-%s-tool'", "%", "prefix", ")", "with", "open", "(", "tool_path", ",", "'w'", ")", "as", "tool_file", ":", "tool_file", ".", "write", "(", "''", ".", "join", "(", "[", "source", "[", "0", "]", ",", "'# Generated by gyp. Do not edit.\\n'", "]", "+", "source", "[", "1", ":", "]", ")", ")", "# Make file executable.", "os", ".", "chmod", "(", "tool_path", ",", "0755", ")" ]
[ 439, 0 ]
[ 466, 27 ]
python
en
['en', 'en', 'en']
True
TopologicallySorted
(graph, get_edges)
r"""Topologically sort based on a user provided edge definition. Args: graph: A list of node names. get_edges: A function mapping from node name to a hashable collection of node names which this node has outgoing edges to. Returns: A list containing all of the node in graph in topological order. It is assumed that calling get_edges once for each node and caching is cheaper than repeatedly calling get_edges. Raises: CycleError in the event of a cycle. Example: graph = {'a': '$(b) $(c)', 'b': 'hi', 'c': '$(b)'} def GetEdges(node): return re.findall(r'\$\(([^))]\)', graph[node]) print TopologicallySorted(graph.keys(), GetEdges) ==> ['a', 'c', b']
r"""Topologically sort based on a user provided edge definition.
def TopologicallySorted(graph, get_edges): r"""Topologically sort based on a user provided edge definition. Args: graph: A list of node names. get_edges: A function mapping from node name to a hashable collection of node names which this node has outgoing edges to. Returns: A list containing all of the node in graph in topological order. It is assumed that calling get_edges once for each node and caching is cheaper than repeatedly calling get_edges. Raises: CycleError in the event of a cycle. Example: graph = {'a': '$(b) $(c)', 'b': 'hi', 'c': '$(b)'} def GetEdges(node): return re.findall(r'\$\(([^))]\)', graph[node]) print TopologicallySorted(graph.keys(), GetEdges) ==> ['a', 'c', b'] """ get_edges = memoize(get_edges) visited = set() visiting = set() ordered_nodes = [] def Visit(node): if node in visiting: raise CycleError(visiting) if node in visited: return visited.add(node) visiting.add(node) for neighbor in get_edges(node): Visit(neighbor) visiting.remove(node) ordered_nodes.insert(0, node) for node in sorted(graph): Visit(node) return ordered_nodes
[ "def", "TopologicallySorted", "(", "graph", ",", "get_edges", ")", ":", "get_edges", "=", "memoize", "(", "get_edges", ")", "visited", "=", "set", "(", ")", "visiting", "=", "set", "(", ")", "ordered_nodes", "=", "[", "]", "def", "Visit", "(", "node", ")", ":", "if", "node", "in", "visiting", ":", "raise", "CycleError", "(", "visiting", ")", "if", "node", "in", "visited", ":", "return", "visited", ".", "add", "(", "node", ")", "visiting", ".", "add", "(", "node", ")", "for", "neighbor", "in", "get_edges", "(", "node", ")", ":", "Visit", "(", "neighbor", ")", "visiting", ".", "remove", "(", "node", ")", "ordered_nodes", ".", "insert", "(", "0", ",", "node", ")", "for", "node", "in", "sorted", "(", "graph", ")", ":", "Visit", "(", "node", ")", "return", "ordered_nodes" ]
[ 562, 0 ]
[ 600, 22 ]
python
en
['en', 'en', 'en']
True
BaseNotebookRenderer.add_code_cell
(self, code: str, lint: bool = False)
Add the given code as a new code cell. Args: code: Code to render into the notebook cell lint: Whether to lint the code before adding it Returns: Nothing, adds a cell to the class instance notebook
Add the given code as a new code cell. Args: code: Code to render into the notebook cell lint: Whether to lint the code before adding it
def add_code_cell(self, code: str, lint: bool = False) -> None: """ Add the given code as a new code cell. Args: code: Code to render into the notebook cell lint: Whether to lint the code before adding it Returns: Nothing, adds a cell to the class instance notebook """ if lint: code: str = lint_code(code).rstrip("\n") cell = nbformat.v4.new_code_cell(code) self._notebook["cells"].append(cell)
[ "def", "add_code_cell", "(", "self", ",", "code", ":", "str", ",", "lint", ":", "bool", "=", "False", ")", "->", "None", ":", "if", "lint", ":", "code", ":", "str", "=", "lint_code", "(", "code", ")", ".", "rstrip", "(", "\"\\n\"", ")", "cell", "=", "nbformat", ".", "v4", ".", "new_code_cell", "(", "code", ")", "self", ".", "_notebook", "[", "\"cells\"", "]", ".", "append", "(", "cell", ")" ]
[ 21, 4 ]
[ 35, 44 ]
python
en
['en', 'error', 'th']
False
BaseNotebookRenderer.add_markdown_cell
(self, markdown: str)
Add the given markdown as a new markdown cell. Args: markdown: Code to render into the notebook cell Returns: Nothing, adds a cell to the class instance notebook
Add the given markdown as a new markdown cell. Args: markdown: Code to render into the notebook cell
def add_markdown_cell(self, markdown: str) -> None: """ Add the given markdown as a new markdown cell. Args: markdown: Code to render into the notebook cell Returns: Nothing, adds a cell to the class instance notebook """ cell = nbformat.v4.new_markdown_cell(markdown) self._notebook["cells"].append(cell)
[ "def", "add_markdown_cell", "(", "self", ",", "markdown", ":", "str", ")", "->", "None", ":", "cell", "=", "nbformat", ".", "v4", ".", "new_markdown_cell", "(", "markdown", ")", "self", ".", "_notebook", "[", "\"cells\"", "]", ".", "append", "(", "cell", ")" ]
[ 37, 4 ]
[ 47, 44 ]
python
en
['en', 'error', 'th']
False
BaseNotebookRenderer.write_notebook_to_disk
( cls, notebook: nbformat.NotebookNode, notebook_file_path: str )
Write a given Jupyter notebook to disk. Args: notebook: Jupyter notebook notebook_file_path: Location to write notebook
Write a given Jupyter notebook to disk. Args: notebook: Jupyter notebook notebook_file_path: Location to write notebook
def write_notebook_to_disk( cls, notebook: nbformat.NotebookNode, notebook_file_path: str ) -> None: """ Write a given Jupyter notebook to disk. Args: notebook: Jupyter notebook notebook_file_path: Location to write notebook """ with open(notebook_file_path, "w") as f: nbformat.write(notebook, f)
[ "def", "write_notebook_to_disk", "(", "cls", ",", "notebook", ":", "nbformat", ".", "NotebookNode", ",", "notebook_file_path", ":", "str", ")", "->", "None", ":", "with", "open", "(", "notebook_file_path", ",", "\"w\"", ")", "as", "f", ":", "nbformat", ".", "write", "(", "notebook", ",", "f", ")" ]
[ 50, 4 ]
[ 60, 39 ]
python
en
['en', 'error', 'th']
False
BaseNotebookRenderer.render
(self)
Render a notebook from parameters.
Render a notebook from parameters.
def render(self): """ Render a notebook from parameters. """ raise NotImplementedError
[ "def", "render", "(", "self", ")", ":", "raise", "NotImplementedError" ]
[ 62, 4 ]
[ 66, 33 ]
python
en
['en', 'error', 'th']
False
BaseNotebookRenderer.render_to_disk
( self, notebook_file_path: str, )
Render a notebook to disk from arguments
Render a notebook to disk from arguments
def render_to_disk( self, notebook_file_path: str, ) -> None: """ Render a notebook to disk from arguments """ raise NotImplementedError
[ "def", "render_to_disk", "(", "self", ",", "notebook_file_path", ":", "str", ",", ")", "->", "None", ":", "raise", "NotImplementedError" ]
[ 68, 4 ]
[ 75, 33 ]
python
en
['en', 'error', 'th']
False
nested_update
( d: Union[Iterable, dict], u: Union[Iterable, dict], dedup: bool = False )
update d with items from u, recursively and joining elements
update d with items from u, recursively and joining elements
def nested_update( d: Union[Iterable, dict], u: Union[Iterable, dict], dedup: bool = False ): """update d with items from u, recursively and joining elements""" for k, v in u.items(): if isinstance(v, Mapping): d[k] = nested_update(d.get(k, {}), v, dedup=dedup) elif isinstance(v, set) or (k in d and isinstance(d[k], set)): s1 = d.get(k, set()) s2 = v or set() d[k] = s1 | s2 elif isinstance(v, list) or (k in d and isinstance(d[k], list)): l1 = d.get(k, []) l2 = v or [] if dedup: d[k] = list(set(l1 + l2)) else: d[k] = l1 + l2 else: d[k] = v return d
[ "def", "nested_update", "(", "d", ":", "Union", "[", "Iterable", ",", "dict", "]", ",", "u", ":", "Union", "[", "Iterable", ",", "dict", "]", ",", "dedup", ":", "bool", "=", "False", ")", ":", "for", "k", ",", "v", "in", "u", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "Mapping", ")", ":", "d", "[", "k", "]", "=", "nested_update", "(", "d", ".", "get", "(", "k", ",", "{", "}", ")", ",", "v", ",", "dedup", "=", "dedup", ")", "elif", "isinstance", "(", "v", ",", "set", ")", "or", "(", "k", "in", "d", "and", "isinstance", "(", "d", "[", "k", "]", ",", "set", ")", ")", ":", "s1", "=", "d", ".", "get", "(", "k", ",", "set", "(", ")", ")", "s2", "=", "v", "or", "set", "(", ")", "d", "[", "k", "]", "=", "s1", "|", "s2", "elif", "isinstance", "(", "v", ",", "list", ")", "or", "(", "k", "in", "d", "and", "isinstance", "(", "d", "[", "k", "]", ",", "list", ")", ")", ":", "l1", "=", "d", ".", "get", "(", "k", ",", "[", "]", ")", "l2", "=", "v", "or", "[", "]", "if", "dedup", ":", "d", "[", "k", "]", "=", "list", "(", "set", "(", "l1", "+", "l2", ")", ")", "else", ":", "d", "[", "k", "]", "=", "l1", "+", "l2", "else", ":", "d", "[", "k", "]", "=", "v", "return", "d" ]
[ 69, 0 ]
[ 89, 12 ]
python
en
['en', 'en', 'en']
True
in_databricks
()
Tests whether we are in a Databricks environment. Returns: bool
Tests whether we are in a Databricks environment.
def in_databricks() -> bool: """ Tests whether we are in a Databricks environment. Returns: bool """ return "DATABRICKS_RUNTIME_VERSION" in os.environ
[ "def", "in_databricks", "(", ")", "->", "bool", ":", "return", "\"DATABRICKS_RUNTIME_VERSION\"", "in", "os", ".", "environ" ]
[ 105, 0 ]
[ 112, 53 ]
python
en
['en', 'error', 'th']
False
convert_to_json_serializable
(data)
Helper function to convert an object to one that is json serializable Args: data: an object to attempt to convert a corresponding json-serializable object Returns: (dict) A converted test_object Warning: test_obj may also be converted in place.
Helper function to convert an object to one that is json serializable Args: data: an object to attempt to convert a corresponding json-serializable object Returns: (dict) A converted test_object Warning: test_obj may also be converted in place.
def convert_to_json_serializable(data): """ Helper function to convert an object to one that is json serializable Args: data: an object to attempt to convert a corresponding json-serializable object Returns: (dict) A converted test_object Warning: test_obj may also be converted in place. """ # If it's one of our types, we use our own conversion; this can move to full schema # once nesting goes all the way down if isinstance(data, (SerializableDictDot, SerializableDotDict)): return data.to_json_dict() # Handling "float(nan)" separately is required by Python-3.6 and Pandas-0.23 versions. if isinstance(data, float) and np.isnan(data): return None if isinstance(data, (str, int, float, bool)): # No problem to encode json return data if isinstance(data, dict): new_dict = {} for key in data: # A pandas index can be numeric, and a dict key can be numeric, but a json key must be a string new_dict[str(key)] = convert_to_json_serializable(data[key]) return new_dict if isinstance(data, (list, tuple, set)): new_list = [] for val in data: new_list.append(convert_to_json_serializable(val)) return new_list if isinstance(data, (np.ndarray, pd.Index)): # test_obj[key] = test_obj[key].tolist() # If we have an array or index, convert it first to a list--causing coercion to float--and then round # to the number of digits for which the string representation will equal the float representation return [convert_to_json_serializable(x) for x in data.tolist()] if isinstance(data, (datetime.datetime, datetime.date)): return data.isoformat() if isinstance(data, uuid.UUID): return str(data) # Use built in base type from numpy, https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html # https://github.com/numpy/numpy/pull/9505 if np.issubdtype(type(data), np.bool_): return bool(data) if np.issubdtype(type(data), np.integer) or np.issubdtype(type(data), np.uint): return int(data) if np.issubdtype(type(data), np.floating): # Note: Use np.floating to avoid FutureWarning from numpy return float(round(data, sys.float_info.dig)) # Note: This clause has to come after checking for np.ndarray or we get: # `ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()` if data is None: # No problem to encode json return data try: if not isinstance(data, list) and pd.isna(data): # pd.isna is functionally vectorized, but we only want to apply this to single objects # Hence, why we test for `not isinstance(list))` return None except TypeError: pass except ValueError: pass if isinstance(data, pd.Series): # Converting a series is tricky since the index may not be a string, but all json # keys must be strings. So, we use a very ugly serialization strategy index_name = data.index.name or "index" value_name = data.name or "value" return [ { index_name: convert_to_json_serializable(idx), value_name: convert_to_json_serializable(val), } for idx, val in data.iteritems() ] if isinstance(data, pd.DataFrame): return convert_to_json_serializable(data.to_dict(orient="records")) if pyspark and isinstance(data, pyspark.sql.DataFrame): # using StackOverflow suggestion for converting pyspark df into dictionary # https://stackoverflow.com/questions/43679880/pyspark-dataframe-to-dictionary-columns-as-keys-and-list-of-column-values-ad-di return convert_to_json_serializable( dict(zip(data.schema.names, zip(*data.collect()))) ) if isinstance(data, decimal.Decimal): if requires_lossy_conversion(data): logger.warning( f"Using lossy conversion for decimal {data} to float object to support serialization." ) return float(data) if isinstance(data, RunIdentifier): return data.to_json_dict() else: raise TypeError( "%s is of type %s which cannot be serialized." % (str(data), type(data).__name__) )
[ "def", "convert_to_json_serializable", "(", "data", ")", ":", "# If it's one of our types, we use our own conversion; this can move to full schema", "# once nesting goes all the way down", "if", "isinstance", "(", "data", ",", "(", "SerializableDictDot", ",", "SerializableDotDict", ")", ")", ":", "return", "data", ".", "to_json_dict", "(", ")", "# Handling \"float(nan)\" separately is required by Python-3.6 and Pandas-0.23 versions.", "if", "isinstance", "(", "data", ",", "float", ")", "and", "np", ".", "isnan", "(", "data", ")", ":", "return", "None", "if", "isinstance", "(", "data", ",", "(", "str", ",", "int", ",", "float", ",", "bool", ")", ")", ":", "# No problem to encode json", "return", "data", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "new_dict", "=", "{", "}", "for", "key", "in", "data", ":", "# A pandas index can be numeric, and a dict key can be numeric, but a json key must be a string", "new_dict", "[", "str", "(", "key", ")", "]", "=", "convert_to_json_serializable", "(", "data", "[", "key", "]", ")", "return", "new_dict", "if", "isinstance", "(", "data", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", ":", "new_list", "=", "[", "]", "for", "val", "in", "data", ":", "new_list", ".", "append", "(", "convert_to_json_serializable", "(", "val", ")", ")", "return", "new_list", "if", "isinstance", "(", "data", ",", "(", "np", ".", "ndarray", ",", "pd", ".", "Index", ")", ")", ":", "# test_obj[key] = test_obj[key].tolist()", "# If we have an array or index, convert it first to a list--causing coercion to float--and then round", "# to the number of digits for which the string representation will equal the float representation", "return", "[", "convert_to_json_serializable", "(", "x", ")", "for", "x", "in", "data", ".", "tolist", "(", ")", "]", "if", "isinstance", "(", "data", ",", "(", "datetime", ".", "datetime", ",", "datetime", ".", "date", ")", ")", ":", "return", "data", ".", "isoformat", "(", ")", "if", "isinstance", "(", "data", ",", "uuid", ".", "UUID", ")", ":", "return", "str", "(", "data", ")", "# Use built in base type from numpy, https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html", "# https://github.com/numpy/numpy/pull/9505", "if", "np", ".", "issubdtype", "(", "type", "(", "data", ")", ",", "np", ".", "bool_", ")", ":", "return", "bool", "(", "data", ")", "if", "np", ".", "issubdtype", "(", "type", "(", "data", ")", ",", "np", ".", "integer", ")", "or", "np", ".", "issubdtype", "(", "type", "(", "data", ")", ",", "np", ".", "uint", ")", ":", "return", "int", "(", "data", ")", "if", "np", ".", "issubdtype", "(", "type", "(", "data", ")", ",", "np", ".", "floating", ")", ":", "# Note: Use np.floating to avoid FutureWarning from numpy", "return", "float", "(", "round", "(", "data", ",", "sys", ".", "float_info", ".", "dig", ")", ")", "# Note: This clause has to come after checking for np.ndarray or we get:", "# `ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()`", "if", "data", "is", "None", ":", "# No problem to encode json", "return", "data", "try", ":", "if", "not", "isinstance", "(", "data", ",", "list", ")", "and", "pd", ".", "isna", "(", "data", ")", ":", "# pd.isna is functionally vectorized, but we only want to apply this to single objects", "# Hence, why we test for `not isinstance(list))`", "return", "None", "except", "TypeError", ":", "pass", "except", "ValueError", ":", "pass", "if", "isinstance", "(", "data", ",", "pd", ".", "Series", ")", ":", "# Converting a series is tricky since the index may not be a string, but all json", "# keys must be strings. So, we use a very ugly serialization strategy", "index_name", "=", "data", ".", "index", ".", "name", "or", "\"index\"", "value_name", "=", "data", ".", "name", "or", "\"value\"", "return", "[", "{", "index_name", ":", "convert_to_json_serializable", "(", "idx", ")", ",", "value_name", ":", "convert_to_json_serializable", "(", "val", ")", ",", "}", "for", "idx", ",", "val", "in", "data", ".", "iteritems", "(", ")", "]", "if", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", ":", "return", "convert_to_json_serializable", "(", "data", ".", "to_dict", "(", "orient", "=", "\"records\"", ")", ")", "if", "pyspark", "and", "isinstance", "(", "data", ",", "pyspark", ".", "sql", ".", "DataFrame", ")", ":", "# using StackOverflow suggestion for converting pyspark df into dictionary", "# https://stackoverflow.com/questions/43679880/pyspark-dataframe-to-dictionary-columns-as-keys-and-list-of-column-values-ad-di", "return", "convert_to_json_serializable", "(", "dict", "(", "zip", "(", "data", ".", "schema", ".", "names", ",", "zip", "(", "*", "data", ".", "collect", "(", ")", ")", ")", ")", ")", "if", "isinstance", "(", "data", ",", "decimal", ".", "Decimal", ")", ":", "if", "requires_lossy_conversion", "(", "data", ")", ":", "logger", ".", "warning", "(", "f\"Using lossy conversion for decimal {data} to float object to support serialization.\"", ")", "return", "float", "(", "data", ")", "if", "isinstance", "(", "data", ",", "RunIdentifier", ")", ":", "return", "data", ".", "to_json_dict", "(", ")", "else", ":", "raise", "TypeError", "(", "\"%s is of type %s which cannot be serialized.\"", "%", "(", "str", "(", "data", ")", ",", "type", "(", "data", ")", ".", "__name__", ")", ")" ]
[ 115, 0 ]
[ 231, 9 ]
python
en
['en', 'error', 'th']
False
ensure_json_serializable
(data)
Helper function to convert an object to one that is json serializable Args: data: an object to attempt to convert a corresponding json-serializable object Returns: (dict) A converted test_object Warning: test_obj may also be converted in place.
Helper function to convert an object to one that is json serializable Args: data: an object to attempt to convert a corresponding json-serializable object Returns: (dict) A converted test_object Warning: test_obj may also be converted in place.
def ensure_json_serializable(data): """ Helper function to convert an object to one that is json serializable Args: data: an object to attempt to convert a corresponding json-serializable object Returns: (dict) A converted test_object Warning: test_obj may also be converted in place. """ if isinstance(data, (SerializableDictDot, SerializableDotDict)): return if isinstance(data, ((str,), (int,), float, bool)): # No problem to encode json return if isinstance(data, dict): for key in data: str(key) # key must be cast-able to string ensure_json_serializable(data[key]) return if isinstance(data, (list, tuple, set)): for val in data: ensure_json_serializable(val) return if isinstance(data, (np.ndarray, pd.Index)): # test_obj[key] = test_obj[key].tolist() # If we have an array or index, convert it first to a list--causing coercion to float--and then round # to the number of digits for which the string representation will equal the float representation _ = [ensure_json_serializable(x) for x in data.tolist()] return if isinstance(data, (datetime.datetime, datetime.date)): return # Use built in base type from numpy, https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html # https://github.com/numpy/numpy/pull/9505 if np.issubdtype(type(data), np.bool_): return if np.issubdtype(type(data), np.integer) or np.issubdtype(type(data), np.uint): return if np.issubdtype(type(data), np.floating): # Note: Use np.floating to avoid FutureWarning from numpy return # Note: This clause has to come after checking for np.ndarray or we get: # `ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()` if data is None: # No problem to encode json return try: if not isinstance(data, list) and pd.isna(data): # pd.isna is functionally vectorized, but we only want to apply this to single objects # Hence, why we test for `not isinstance(list))` return except TypeError: pass except ValueError: pass if isinstance(data, pd.Series): # Converting a series is tricky since the index may not be a string, but all json # keys must be strings. So, we use a very ugly serialization strategy index_name = data.index.name or "index" value_name = data.name or "value" _ = [ { index_name: ensure_json_serializable(idx), value_name: ensure_json_serializable(val), } for idx, val in data.iteritems() ] return if pyspark and isinstance(data, pyspark.sql.DataFrame): # using StackOverflow suggestion for converting pyspark df into dictionary # https://stackoverflow.com/questions/43679880/pyspark-dataframe-to-dictionary-columns-as-keys-and-list-of-column-values-ad-di return ensure_json_serializable( dict(zip(data.schema.names, zip(*data.collect()))) ) if isinstance(data, pd.DataFrame): return ensure_json_serializable(data.to_dict(orient="records")) if isinstance(data, decimal.Decimal): return if isinstance(data, RunIdentifier): return else: raise InvalidExpectationConfigurationError( "%s is of type %s which cannot be serialized to json" % (str(data), type(data).__name__) )
[ "def", "ensure_json_serializable", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "(", "SerializableDictDot", ",", "SerializableDotDict", ")", ")", ":", "return", "if", "isinstance", "(", "data", ",", "(", "(", "str", ",", ")", ",", "(", "int", ",", ")", ",", "float", ",", "bool", ")", ")", ":", "# No problem to encode json", "return", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "for", "key", "in", "data", ":", "str", "(", "key", ")", "# key must be cast-able to string", "ensure_json_serializable", "(", "data", "[", "key", "]", ")", "return", "if", "isinstance", "(", "data", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", ":", "for", "val", "in", "data", ":", "ensure_json_serializable", "(", "val", ")", "return", "if", "isinstance", "(", "data", ",", "(", "np", ".", "ndarray", ",", "pd", ".", "Index", ")", ")", ":", "# test_obj[key] = test_obj[key].tolist()", "# If we have an array or index, convert it first to a list--causing coercion to float--and then round", "# to the number of digits for which the string representation will equal the float representation", "_", "=", "[", "ensure_json_serializable", "(", "x", ")", "for", "x", "in", "data", ".", "tolist", "(", ")", "]", "return", "if", "isinstance", "(", "data", ",", "(", "datetime", ".", "datetime", ",", "datetime", ".", "date", ")", ")", ":", "return", "# Use built in base type from numpy, https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html", "# https://github.com/numpy/numpy/pull/9505", "if", "np", ".", "issubdtype", "(", "type", "(", "data", ")", ",", "np", ".", "bool_", ")", ":", "return", "if", "np", ".", "issubdtype", "(", "type", "(", "data", ")", ",", "np", ".", "integer", ")", "or", "np", ".", "issubdtype", "(", "type", "(", "data", ")", ",", "np", ".", "uint", ")", ":", "return", "if", "np", ".", "issubdtype", "(", "type", "(", "data", ")", ",", "np", ".", "floating", ")", ":", "# Note: Use np.floating to avoid FutureWarning from numpy", "return", "# Note: This clause has to come after checking for np.ndarray or we get:", "# `ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()`", "if", "data", "is", "None", ":", "# No problem to encode json", "return", "try", ":", "if", "not", "isinstance", "(", "data", ",", "list", ")", "and", "pd", ".", "isna", "(", "data", ")", ":", "# pd.isna is functionally vectorized, but we only want to apply this to single objects", "# Hence, why we test for `not isinstance(list))`", "return", "except", "TypeError", ":", "pass", "except", "ValueError", ":", "pass", "if", "isinstance", "(", "data", ",", "pd", ".", "Series", ")", ":", "# Converting a series is tricky since the index may not be a string, but all json", "# keys must be strings. So, we use a very ugly serialization strategy", "index_name", "=", "data", ".", "index", ".", "name", "or", "\"index\"", "value_name", "=", "data", ".", "name", "or", "\"value\"", "_", "=", "[", "{", "index_name", ":", "ensure_json_serializable", "(", "idx", ")", ",", "value_name", ":", "ensure_json_serializable", "(", "val", ")", ",", "}", "for", "idx", ",", "val", "in", "data", ".", "iteritems", "(", ")", "]", "return", "if", "pyspark", "and", "isinstance", "(", "data", ",", "pyspark", ".", "sql", ".", "DataFrame", ")", ":", "# using StackOverflow suggestion for converting pyspark df into dictionary", "# https://stackoverflow.com/questions/43679880/pyspark-dataframe-to-dictionary-columns-as-keys-and-list-of-column-values-ad-di", "return", "ensure_json_serializable", "(", "dict", "(", "zip", "(", "data", ".", "schema", ".", "names", ",", "zip", "(", "*", "data", ".", "collect", "(", ")", ")", ")", ")", ")", "if", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", ":", "return", "ensure_json_serializable", "(", "data", ".", "to_dict", "(", "orient", "=", "\"records\"", ")", ")", "if", "isinstance", "(", "data", ",", "decimal", ".", "Decimal", ")", ":", "return", "if", "isinstance", "(", "data", ",", "RunIdentifier", ")", ":", "return", "else", ":", "raise", "InvalidExpectationConfigurationError", "(", "\"%s is of type %s which cannot be serialized to json\"", "%", "(", "str", "(", "data", ")", ",", "type", "(", "data", ")", ".", "__name__", ")", ")" ]
[ 234, 0 ]
[ 336, 9 ]
python
en
['en', 'error', 'th']
False
substitute_all_strftime_format_strings
( data: Union[dict, list, str, Any], datetime_obj: Optional[datetime.datetime] = None )
This utility function will iterate over input data and for all strings, replace any strftime format elements using either the provided datetime_obj or the current datetime
This utility function will iterate over input data and for all strings, replace any strftime format elements using either the provided datetime_obj or the current datetime
def substitute_all_strftime_format_strings( data: Union[dict, list, str, Any], datetime_obj: Optional[datetime.datetime] = None ) -> Union[str, Any]: """ This utility function will iterate over input data and for all strings, replace any strftime format elements using either the provided datetime_obj or the current datetime """ datetime_obj: datetime.datetime = datetime_obj or datetime.datetime.now() if isinstance(data, dict) or isinstance(data, OrderedDict): return { k: substitute_all_strftime_format_strings(v, datetime_obj=datetime_obj) for k, v in data.items() } elif isinstance(data, list): return [ substitute_all_strftime_format_strings(el, datetime_obj=datetime_obj) for el in data ] elif isinstance(data, str): return get_datetime_string_from_strftime_format(data, datetime_obj=datetime_obj) else: return data
[ "def", "substitute_all_strftime_format_strings", "(", "data", ":", "Union", "[", "dict", ",", "list", ",", "str", ",", "Any", "]", ",", "datetime_obj", ":", "Optional", "[", "datetime", ".", "datetime", "]", "=", "None", ")", "->", "Union", "[", "str", ",", "Any", "]", ":", "datetime_obj", ":", "datetime", ".", "datetime", "=", "datetime_obj", "or", "datetime", ".", "datetime", ".", "now", "(", ")", "if", "isinstance", "(", "data", ",", "dict", ")", "or", "isinstance", "(", "data", ",", "OrderedDict", ")", ":", "return", "{", "k", ":", "substitute_all_strftime_format_strings", "(", "v", ",", "datetime_obj", "=", "datetime_obj", ")", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", "}", "elif", "isinstance", "(", "data", ",", "list", ")", ":", "return", "[", "substitute_all_strftime_format_strings", "(", "el", ",", "datetime_obj", "=", "datetime_obj", ")", "for", "el", "in", "data", "]", "elif", "isinstance", "(", "data", ",", "str", ")", ":", "return", "get_datetime_string_from_strftime_format", "(", "data", ",", "datetime_obj", "=", "datetime_obj", ")", "else", ":", "return", "data" ]
[ 343, 0 ]
[ 365, 19 ]
python
en
['en', 'error', 'th']
False
get_datetime_string_from_strftime_format
( format_str: str, datetime_obj: Optional[datetime.datetime] = None )
This utility function takes a string with strftime format elements and substitutes those elements using either the provided datetime_obj or current datetime
This utility function takes a string with strftime format elements and substitutes those elements using either the provided datetime_obj or current datetime
def get_datetime_string_from_strftime_format( format_str: str, datetime_obj: Optional[datetime.datetime] = None ) -> str: """ This utility function takes a string with strftime format elements and substitutes those elements using either the provided datetime_obj or current datetime """ datetime_obj: datetime.datetime = datetime_obj or datetime.datetime.now() return datetime_obj.strftime(format_str)
[ "def", "get_datetime_string_from_strftime_format", "(", "format_str", ":", "str", ",", "datetime_obj", ":", "Optional", "[", "datetime", ".", "datetime", "]", "=", "None", ")", "->", "str", ":", "datetime_obj", ":", "datetime", ".", "datetime", "=", "datetime_obj", "or", "datetime", ".", "datetime", ".", "now", "(", ")", "return", "datetime_obj", ".", "strftime", "(", "format_str", ")" ]
[ 368, 0 ]
[ 376, 44 ]
python
en
['en', 'error', 'th']
False
sniff_s3_compression
(s3_url: S3Url)
Attempts to get read_csv compression from s3_url
Attempts to get read_csv compression from s3_url
def sniff_s3_compression(s3_url: S3Url) -> str: """Attempts to get read_csv compression from s3_url""" return _SUFFIX_TO_PD_KWARG.get(s3_url.suffix)
[ "def", "sniff_s3_compression", "(", "s3_url", ":", "S3Url", ")", "->", "str", ":", "return", "_SUFFIX_TO_PD_KWARG", ".", "get", "(", "s3_url", ".", "suffix", ")" ]
[ 462, 0 ]
[ 464, 49 ]
python
en
['en', 'en', 'en']
True