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 |
---|---|---|---|---|---|---|---|---|---|---|---|
convert_broadcast_greater | (node, **kwargs) | Map MXNet's broadcast_greater operator attributes to onnx's Greater operator
and return the created node.
| Map MXNet's broadcast_greater operator attributes to onnx's Greater operator
and return the created node.
| def convert_broadcast_greater(node, **kwargs):
"""Map MXNet's broadcast_greater operator attributes to onnx's Greater operator
and return the created node.
"""
return create_basic_op_node('Greater', node, kwargs) | [
"def",
"convert_broadcast_greater",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"create_basic_op_node",
"(",
"'Greater'",
",",
"node",
",",
"kwargs",
")"
] | [
2432,
0
] | [
2436,
56
] | python | en | ['en', 'en', 'en'] | True |
convert_broadcast_equal | (node, **kwargs) | Map MXNet's broadcast_equal operator attributes to onnx's Equal operator
and return the created node.
| Map MXNet's broadcast_equal operator attributes to onnx's Equal operator
and return the created node.
| def convert_broadcast_equal(node, **kwargs):
"""Map MXNet's broadcast_equal operator attributes to onnx's Equal operator
and return the created node.
"""
return create_basic_op_node('Equal', node, kwargs) | [
"def",
"convert_broadcast_equal",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"create_basic_op_node",
"(",
"'Equal'",
",",
"node",
",",
"kwargs",
")"
] | [
2439,
0
] | [
2443,
54
] | python | en | ['en', 'en', 'en'] | True |
convert_broadcast_logical_and | (node, **kwargs) | Map MXNet's broadcast logical and operator attributes to onnx's Add operator
and return the created node.
| Map MXNet's broadcast logical and operator attributes to onnx's Add operator
and return the created node.
| def convert_broadcast_logical_and(node, **kwargs):
"""Map MXNet's broadcast logical and operator attributes to onnx's Add operator
and return the created node.
"""
return create_basic_op_node('And', node, kwargs) | [
"def",
"convert_broadcast_logical_and",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"create_basic_op_node",
"(",
"'And'",
",",
"node",
",",
"kwargs",
")"
] | [
2447,
0
] | [
2451,
52
] | python | en | ['en', 'en', 'en'] | True |
convert_broadcast_logical_or | (node, **kwargs) | Map MXNet's broadcast logical or operator attributes to onnx's Or operator
and return the created node.
| Map MXNet's broadcast logical or operator attributes to onnx's Or operator
and return the created node.
| def convert_broadcast_logical_or(node, **kwargs):
"""Map MXNet's broadcast logical or operator attributes to onnx's Or operator
and return the created node.
"""
return create_basic_op_node('Or', node, kwargs) | [
"def",
"convert_broadcast_logical_or",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"create_basic_op_node",
"(",
"'Or'",
",",
"node",
",",
"kwargs",
")"
] | [
2455,
0
] | [
2459,
51
] | python | en | ['en', 'en', 'en'] | True |
convert_broadcast_logical_xor | (node, **kwargs) | Map MXNet's broadcast logical xor operator attributes to onnx's Xor operator
and return the created node.
| Map MXNet's broadcast logical xor operator attributes to onnx's Xor operator
and return the created node.
| def convert_broadcast_logical_xor(node, **kwargs):
"""Map MXNet's broadcast logical xor operator attributes to onnx's Xor operator
and return the created node.
"""
return create_basic_op_node('Xor', node, kwargs) | [
"def",
"convert_broadcast_logical_xor",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"create_basic_op_node",
"(",
"'Xor'",
",",
"node",
",",
"kwargs",
")"
] | [
2463,
0
] | [
2467,
52
] | python | en | ['en', 'en', 'en'] | True |
convert_logical_not | (node, **kwargs) | Map MXNet's logical not operator attributes to onnx's Not operator
and return the created node.
| Map MXNet's logical not operator attributes to onnx's Not operator
and return the created node.
| def convert_logical_not(node, **kwargs):
"""Map MXNet's logical not operator attributes to onnx's Not operator
and return the created node.
"""
return create_basic_op_node('Not', node, kwargs) | [
"def",
"convert_logical_not",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"create_basic_op_node",
"(",
"'Not'",
",",
"node",
",",
"kwargs",
")"
] | [
2471,
0
] | [
2475,
52
] | python | en | ['en', 'en', 'en'] | True |
convert_size | (node, **kwargs) | Map MXNet's size_array operator attributes to onnx's Size operator
and return the created node.
| Map MXNet's size_array operator attributes to onnx's Size operator
and return the created node.
| def convert_size(node, **kwargs):
"""Map MXNet's size_array operator attributes to onnx's Size operator
and return the created node.
"""
return create_basic_op_node('Size', node, kwargs) | [
"def",
"convert_size",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"create_basic_op_node",
"(",
"'Size'",
",",
"node",
",",
"kwargs",
")"
] | [
2479,
0
] | [
2483,
53
] | python | en | ['en', 'en', 'en'] | True |
convert_logsoftmax | (node, **kwargs) | Map MXNet's log_softmax operator attributes to onnx's LogSoftMax operator
and return the created node.
| Map MXNet's log_softmax operator attributes to onnx's LogSoftMax operator
and return the created node.
| def convert_logsoftmax(node, **kwargs):
"""Map MXNet's log_softmax operator attributes to onnx's LogSoftMax operator
and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
# Converting to int
axis = int(attrs.get("axis", -1))
temp = attrs.get("temperature", 'None')
if temp != 'None':
raise AttributeError("LogSoftMax: ONNX supports only temperature=None")
node = onnx.helper.make_node(
'LogSoftmax',
input_nodes,
[name],
axis=axis,
name=name
)
return [node] | [
"def",
"convert_logsoftmax",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"# Converting to int",
"axis",
"=",
"int",
"(",
"attrs",
".",
"get",
"(",
"\"axis\"",
",",
"-",
"1",
")",
")",
"temp",
"=",
"attrs",
".",
"get",
"(",
"\"temperature\"",
",",
"'None'",
")",
"if",
"temp",
"!=",
"'None'",
":",
"raise",
"AttributeError",
"(",
"\"LogSoftMax: ONNX supports only temperature=None\"",
")",
"node",
"=",
"onnx",
".",
"helper",
".",
"make_node",
"(",
"'LogSoftmax'",
",",
"input_nodes",
",",
"[",
"name",
"]",
",",
"axis",
"=",
"axis",
",",
"name",
"=",
"name",
")",
"return",
"[",
"node",
"]"
] | [
2487,
0
] | [
2506,
17
] | python | en | ['en', 'sn', 'en'] | True |
convert_norm | (node, **kwargs) | Map MXNet's norm operator attributes to onnx's ReduceL1 and ReduceL2 operators
and return the created node.
| Map MXNet's norm operator attributes to onnx's ReduceL1 and ReduceL2 operators
and return the created node.
| def convert_norm(node, **kwargs):
"""Map MXNet's norm operator attributes to onnx's ReduceL1 and ReduceL2 operators
and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
mx_axis = attrs.get("axis", None)
axes = convert_string_to_list(str(mx_axis)) if mx_axis else None
keepdims = get_boolean_attribute_value(attrs, "keepdims")
ord = int(attrs.get("ord", 2))
onnx_op_name = "ReduceL1" if ord == 1 else "ReduceL2"
if axes:
reduce_node = onnx.helper.make_node(
onnx_op_name,
input_nodes,
[name],
axes=axes,
keepdims=keepdims,
name=name
)
return [reduce_node]
else:
reduce_node = onnx.helper.make_node(
onnx_op_name,
input_nodes,
[name],
keepdims=keepdims,
name=name
)
return [reduce_node] | [
"def",
"convert_norm",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"mx_axis",
"=",
"attrs",
".",
"get",
"(",
"\"axis\"",
",",
"None",
")",
"axes",
"=",
"convert_string_to_list",
"(",
"str",
"(",
"mx_axis",
")",
")",
"if",
"mx_axis",
"else",
"None",
"keepdims",
"=",
"get_boolean_attribute_value",
"(",
"attrs",
",",
"\"keepdims\"",
")",
"ord",
"=",
"int",
"(",
"attrs",
".",
"get",
"(",
"\"ord\"",
",",
"2",
")",
")",
"onnx_op_name",
"=",
"\"ReduceL1\"",
"if",
"ord",
"==",
"1",
"else",
"\"ReduceL2\"",
"if",
"axes",
":",
"reduce_node",
"=",
"onnx",
".",
"helper",
".",
"make_node",
"(",
"onnx_op_name",
",",
"input_nodes",
",",
"[",
"name",
"]",
",",
"axes",
"=",
"axes",
",",
"keepdims",
"=",
"keepdims",
",",
"name",
"=",
"name",
")",
"return",
"[",
"reduce_node",
"]",
"else",
":",
"reduce_node",
"=",
"onnx",
".",
"helper",
".",
"make_node",
"(",
"onnx_op_name",
",",
"input_nodes",
",",
"[",
"name",
"]",
",",
"keepdims",
"=",
"keepdims",
",",
"name",
"=",
"name",
")",
"return",
"[",
"reduce_node",
"]"
] | [
2509,
0
] | [
2541,
28
] | python | en | ['en', 'en', 'en'] | True |
convert_multinomial | (node, **kwargs) | Map MXNet's multinomial operator attributes to onnx's
Multinomial operator and return the created node.
| Map MXNet's multinomial operator attributes to onnx's
Multinomial operator and return the created node.
| def convert_multinomial(node, **kwargs):
"""Map MXNet's multinomial operator attributes to onnx's
Multinomial operator and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
dtype = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(attrs.get("dtype", 'int32'))]
sample_size = convert_string_to_list(attrs.get("shape", '1'))
if len(sample_size) < 2:
sample_size = sample_size[-1]
else:
raise AttributeError("ONNX currently supports integer sample_size only")
node = onnx.helper.make_node(
"Multinomial",
input_nodes,
[name],
dtype=dtype,
sample_size=sample_size,
name=name,
)
return [node] | [
"def",
"convert_multinomial",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"dtype",
"=",
"onnx",
".",
"mapping",
".",
"NP_TYPE_TO_TENSOR_TYPE",
"[",
"np",
".",
"dtype",
"(",
"attrs",
".",
"get",
"(",
"\"dtype\"",
",",
"'int32'",
")",
")",
"]",
"sample_size",
"=",
"convert_string_to_list",
"(",
"attrs",
".",
"get",
"(",
"\"shape\"",
",",
"'1'",
")",
")",
"if",
"len",
"(",
"sample_size",
")",
"<",
"2",
":",
"sample_size",
"=",
"sample_size",
"[",
"-",
"1",
"]",
"else",
":",
"raise",
"AttributeError",
"(",
"\"ONNX currently supports integer sample_size only\"",
")",
"node",
"=",
"onnx",
".",
"helper",
".",
"make_node",
"(",
"\"Multinomial\"",
",",
"input_nodes",
",",
"[",
"name",
"]",
",",
"dtype",
"=",
"dtype",
",",
"sample_size",
"=",
"sample_size",
",",
"name",
"=",
"name",
",",
")",
"return",
"[",
"node",
"]"
] | [
2544,
0
] | [
2563,
17
] | python | en | ['en', 'en', 'en'] | True |
convert_random_uniform | (node, **kwargs) | Map MXNet's random_uniform operator attributes to onnx's RandomUniform
operator and return the created node.
| Map MXNet's random_uniform operator attributes to onnx's RandomUniform
operator and return the created node.
| def convert_random_uniform(node, **kwargs):
"""Map MXNet's random_uniform operator attributes to onnx's RandomUniform
operator and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
# Converting to float32
low = float(attrs.get("low", 0))
high = float(attrs.get("high", 1.0))
shape = convert_string_to_list(attrs.get('shape', '[]'))
dtype = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(attrs.get('dtype', 'float32'))]
node = onnx.helper.make_node(
'RandomUniform',
input_nodes,
[name],
low=low,
high=high,
dtype=dtype,
shape=shape,
name=name
)
return [node] | [
"def",
"convert_random_uniform",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"# Converting to float32",
"low",
"=",
"float",
"(",
"attrs",
".",
"get",
"(",
"\"low\"",
",",
"0",
")",
")",
"high",
"=",
"float",
"(",
"attrs",
".",
"get",
"(",
"\"high\"",
",",
"1.0",
")",
")",
"shape",
"=",
"convert_string_to_list",
"(",
"attrs",
".",
"get",
"(",
"'shape'",
",",
"'[]'",
")",
")",
"dtype",
"=",
"onnx",
".",
"mapping",
".",
"NP_TYPE_TO_TENSOR_TYPE",
"[",
"np",
".",
"dtype",
"(",
"attrs",
".",
"get",
"(",
"'dtype'",
",",
"'float32'",
")",
")",
"]",
"node",
"=",
"onnx",
".",
"helper",
".",
"make_node",
"(",
"'RandomUniform'",
",",
"input_nodes",
",",
"[",
"name",
"]",
",",
"low",
"=",
"low",
",",
"high",
"=",
"high",
",",
"dtype",
"=",
"dtype",
",",
"shape",
"=",
"shape",
",",
"name",
"=",
"name",
")",
"return",
"[",
"node",
"]"
] | [
2567,
0
] | [
2589,
17
] | python | en | ['en', 'sv', 'en'] | True |
convert_random_normal | (node, **kwargs) | Map MXNet's random_normal operator attributes to onnx's RandomNormal
operator and return the created node.
| Map MXNet's random_normal operator attributes to onnx's RandomNormal
operator and return the created node.
| def convert_random_normal(node, **kwargs):
"""Map MXNet's random_normal operator attributes to onnx's RandomNormal
operator and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
# Converting to float32
mean = float(attrs.get("loc", 0))
scale = float(attrs.get("scale", 1.0))
shape = convert_string_to_list(attrs.get('shape', '[]'))
dtype = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(attrs.get('dtype', 'float32'))]
node = onnx.helper.make_node(
'RandomNormal',
input_nodes,
[name],
mean=mean,
scale=scale,
dtype=dtype,
shape=shape,
name=name
)
return [node] | [
"def",
"convert_random_normal",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"# Converting to float32",
"mean",
"=",
"float",
"(",
"attrs",
".",
"get",
"(",
"\"loc\"",
",",
"0",
")",
")",
"scale",
"=",
"float",
"(",
"attrs",
".",
"get",
"(",
"\"scale\"",
",",
"1.0",
")",
")",
"shape",
"=",
"convert_string_to_list",
"(",
"attrs",
".",
"get",
"(",
"'shape'",
",",
"'[]'",
")",
")",
"dtype",
"=",
"onnx",
".",
"mapping",
".",
"NP_TYPE_TO_TENSOR_TYPE",
"[",
"np",
".",
"dtype",
"(",
"attrs",
".",
"get",
"(",
"'dtype'",
",",
"'float32'",
")",
")",
"]",
"node",
"=",
"onnx",
".",
"helper",
".",
"make_node",
"(",
"'RandomNormal'",
",",
"input_nodes",
",",
"[",
"name",
"]",
",",
"mean",
"=",
"mean",
",",
"scale",
"=",
"scale",
",",
"dtype",
"=",
"dtype",
",",
"shape",
"=",
"shape",
",",
"name",
"=",
"name",
")",
"return",
"[",
"node",
"]"
] | [
2593,
0
] | [
2615,
17
] | python | en | ['en', 'sv', 'en'] | True |
convert_roipooling | (node, **kwargs) | Map MXNet's ROIPooling operator attributes to onnx's MaxRoiPool
operator and return the created node.
| Map MXNet's ROIPooling operator attributes to onnx's MaxRoiPool
operator and return the created node.
| def convert_roipooling(node, **kwargs):
"""Map MXNet's ROIPooling operator attributes to onnx's MaxRoiPool
operator and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
pooled_shape = convert_string_to_list(attrs.get('pooled_size'))
scale = float(attrs.get("spatial_scale"))
node = onnx.helper.make_node(
'MaxRoiPool',
input_nodes,
[name],
pooled_shape=pooled_shape,
spatial_scale=scale,
name=name
)
return [node] | [
"def",
"convert_roipooling",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"pooled_shape",
"=",
"convert_string_to_list",
"(",
"attrs",
".",
"get",
"(",
"'pooled_size'",
")",
")",
"scale",
"=",
"float",
"(",
"attrs",
".",
"get",
"(",
"\"spatial_scale\"",
")",
")",
"node",
"=",
"onnx",
".",
"helper",
".",
"make_node",
"(",
"'MaxRoiPool'",
",",
"input_nodes",
",",
"[",
"name",
"]",
",",
"pooled_shape",
"=",
"pooled_shape",
",",
"spatial_scale",
"=",
"scale",
",",
"name",
"=",
"name",
")",
"return",
"[",
"node",
"]"
] | [
2619,
0
] | [
2636,
17
] | python | en | ['en', 'en', 'en'] | True |
convert_tile | (node, **kwargs) | Map MXNet's Tile operator attributes to onnx's Tile
operator and return the created node.
| Map MXNet's Tile operator attributes to onnx's Tile
operator and return the created node.
| def convert_tile(node, **kwargs):
"""Map MXNet's Tile operator attributes to onnx's Tile
operator and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
reps_list = convert_string_to_list(attrs["reps"])
initializer = kwargs["initializer"]
reps_shape_np = np.array(reps_list, dtype='int64')
data_type = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[reps_shape_np.dtype]
dims = np.shape(reps_shape_np)
output_shape_name = "reps_attr_tensor" + str(kwargs["idx"])
tensor_node = onnx.helper.make_tensor_value_info(output_shape_name, data_type, dims)
initializer.append(
onnx.helper.make_tensor(
name=output_shape_name,
data_type=data_type,
dims=dims,
vals=reps_list,
raw=False,
)
)
input_nodes.append(output_shape_name)
tile_node = onnx.helper.make_node(
"Tile",
input_nodes,
[name],
name=name
)
return [tensor_node, tile_node] | [
"def",
"convert_tile",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"reps_list",
"=",
"convert_string_to_list",
"(",
"attrs",
"[",
"\"reps\"",
"]",
")",
"initializer",
"=",
"kwargs",
"[",
"\"initializer\"",
"]",
"reps_shape_np",
"=",
"np",
".",
"array",
"(",
"reps_list",
",",
"dtype",
"=",
"'int64'",
")",
"data_type",
"=",
"onnx",
".",
"mapping",
".",
"NP_TYPE_TO_TENSOR_TYPE",
"[",
"reps_shape_np",
".",
"dtype",
"]",
"dims",
"=",
"np",
".",
"shape",
"(",
"reps_shape_np",
")",
"output_shape_name",
"=",
"\"reps_attr_tensor\"",
"+",
"str",
"(",
"kwargs",
"[",
"\"idx\"",
"]",
")",
"tensor_node",
"=",
"onnx",
".",
"helper",
".",
"make_tensor_value_info",
"(",
"output_shape_name",
",",
"data_type",
",",
"dims",
")",
"initializer",
".",
"append",
"(",
"onnx",
".",
"helper",
".",
"make_tensor",
"(",
"name",
"=",
"output_shape_name",
",",
"data_type",
"=",
"data_type",
",",
"dims",
"=",
"dims",
",",
"vals",
"=",
"reps_list",
",",
"raw",
"=",
"False",
",",
")",
")",
"input_nodes",
".",
"append",
"(",
"output_shape_name",
")",
"tile_node",
"=",
"onnx",
".",
"helper",
".",
"make_node",
"(",
"\"Tile\"",
",",
"input_nodes",
",",
"[",
"name",
"]",
",",
"name",
"=",
"name",
")",
"return",
"[",
"tensor_node",
",",
"tile_node",
"]"
] | [
2640,
0
] | [
2674,
35
] | python | en | ['en', 'en', 'nl'] | True |
convert_broadcast_to | (node, **kwargs) | Map MXNet's broadcast_to operator attributes to onnx's Expand
operator and return the created node.
| Map MXNet's broadcast_to operator attributes to onnx's Expand
operator and return the created node.
| def convert_broadcast_to(node, **kwargs):
"""Map MXNet's broadcast_to operator attributes to onnx's Expand
operator and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
shape_list = convert_string_to_list(attrs["shape"])
initializer = kwargs["initializer"]
output_shape_np = np.array(shape_list, dtype='int64')
data_type = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[output_shape_np.dtype]
dims = np.shape(output_shape_np)
output_shape_name = "expand_attr_tensor" + str(kwargs["idx"])
tensor_node = onnx.helper.make_tensor_value_info(output_shape_name, data_type, dims)
initializer.append(
onnx.helper.make_tensor(
name=output_shape_name,
data_type=data_type,
dims=dims,
vals=shape_list,
raw=False,
)
)
input_nodes.append(output_shape_name)
expand_node = onnx.helper.make_node(
"Expand",
input_nodes,
[name],
name=name
)
return [tensor_node, expand_node] | [
"def",
"convert_broadcast_to",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"shape_list",
"=",
"convert_string_to_list",
"(",
"attrs",
"[",
"\"shape\"",
"]",
")",
"initializer",
"=",
"kwargs",
"[",
"\"initializer\"",
"]",
"output_shape_np",
"=",
"np",
".",
"array",
"(",
"shape_list",
",",
"dtype",
"=",
"'int64'",
")",
"data_type",
"=",
"onnx",
".",
"mapping",
".",
"NP_TYPE_TO_TENSOR_TYPE",
"[",
"output_shape_np",
".",
"dtype",
"]",
"dims",
"=",
"np",
".",
"shape",
"(",
"output_shape_np",
")",
"output_shape_name",
"=",
"\"expand_attr_tensor\"",
"+",
"str",
"(",
"kwargs",
"[",
"\"idx\"",
"]",
")",
"tensor_node",
"=",
"onnx",
".",
"helper",
".",
"make_tensor_value_info",
"(",
"output_shape_name",
",",
"data_type",
",",
"dims",
")",
"initializer",
".",
"append",
"(",
"onnx",
".",
"helper",
".",
"make_tensor",
"(",
"name",
"=",
"output_shape_name",
",",
"data_type",
"=",
"data_type",
",",
"dims",
"=",
"dims",
",",
"vals",
"=",
"shape_list",
",",
"raw",
"=",
"False",
",",
")",
")",
"input_nodes",
".",
"append",
"(",
"output_shape_name",
")",
"expand_node",
"=",
"onnx",
".",
"helper",
".",
"make_node",
"(",
"\"Expand\"",
",",
"input_nodes",
",",
"[",
"name",
"]",
",",
"name",
"=",
"name",
")",
"return",
"[",
"tensor_node",
",",
"expand_node",
"]"
] | [
2678,
0
] | [
2712,
37
] | python | en | ['en', 'en', 'en'] | True |
convert_topk | (node, **kwargs) | Map MXNet's topk operator attributes to onnx's TopK operator
and return the created node.
| Map MXNet's topk operator attributes to onnx's TopK operator
and return the created node.
| def convert_topk(node, **kwargs):
"""Map MXNet's topk operator attributes to onnx's TopK operator
and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
axis = int(attrs.get('axis', '-1'))
k = int(attrs.get('k', '1'))
ret_type = attrs.get('ret_typ')
dtype = attrs.get('dtype')
outputs = [name + '_output0']
if ret_type and ret_type == 'both':
if dtype and dtype == 'int64':
outputs.append(name + '_output1')
else:
raise NotImplementedError("ONNX expects indices to be of type int64")
else:
raise NotImplementedError("ONNX expects both value and indices as output")
export_nodes = []
k = np.asarray([k], dtype=np.int)
k_node = create_helper_tensor_node(k, name + '__k', kwargs)
export_nodes.extend(k_node)
k_node = k_node[-1].name
input_node = input_nodes[0]
topk_node = onnx.helper.make_node(
"TopK",
[input_node, k_node],
outputs,
axis=axis,
name=name
)
export_nodes.extend([topk_node])
return [topk_node] | [
"def",
"convert_topk",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"axis",
"=",
"int",
"(",
"attrs",
".",
"get",
"(",
"'axis'",
",",
"'-1'",
")",
")",
"k",
"=",
"int",
"(",
"attrs",
".",
"get",
"(",
"'k'",
",",
"'1'",
")",
")",
"ret_type",
"=",
"attrs",
".",
"get",
"(",
"'ret_typ'",
")",
"dtype",
"=",
"attrs",
".",
"get",
"(",
"'dtype'",
")",
"outputs",
"=",
"[",
"name",
"+",
"'_output0'",
"]",
"if",
"ret_type",
"and",
"ret_type",
"==",
"'both'",
":",
"if",
"dtype",
"and",
"dtype",
"==",
"'int64'",
":",
"outputs",
".",
"append",
"(",
"name",
"+",
"'_output1'",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"\"ONNX expects indices to be of type int64\"",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"\"ONNX expects both value and indices as output\"",
")",
"export_nodes",
"=",
"[",
"]",
"k",
"=",
"np",
".",
"asarray",
"(",
"[",
"k",
"]",
",",
"dtype",
"=",
"np",
".",
"int",
")",
"k_node",
"=",
"create_helper_tensor_node",
"(",
"k",
",",
"name",
"+",
"'__k'",
",",
"kwargs",
")",
"export_nodes",
".",
"extend",
"(",
"k_node",
")",
"k_node",
"=",
"k_node",
"[",
"-",
"1",
"]",
".",
"name",
"input_node",
"=",
"input_nodes",
"[",
"0",
"]",
"topk_node",
"=",
"onnx",
".",
"helper",
".",
"make_node",
"(",
"\"TopK\"",
",",
"[",
"input_node",
",",
"k_node",
"]",
",",
"outputs",
",",
"axis",
"=",
"axis",
",",
"name",
"=",
"name",
")",
"export_nodes",
".",
"extend",
"(",
"[",
"topk_node",
"]",
")",
"return",
"[",
"topk_node",
"]"
] | [
2716,
0
] | [
2753,
22
] | python | en | ['en', 'zh', 'en'] | True |
convert_take | (node, **kwargs) | Map MXNet's Take operator attributes to onnx's Gather operator.
| Map MXNet's Take operator attributes to onnx's Gather operator.
| def convert_take(node, **kwargs):
"""Map MXNet's Take operator attributes to onnx's Gather operator.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
axis = int(attrs.get('axis', 0))
node = onnx.helper.make_node(
"Gather",
input_nodes,
[name],
axis=axis,
name=name,
)
return [node] | [
"def",
"convert_take",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"axis",
"=",
"int",
"(",
"attrs",
".",
"get",
"(",
"'axis'",
",",
"0",
")",
")",
"node",
"=",
"onnx",
".",
"helper",
".",
"make_node",
"(",
"\"Gather\"",
",",
"input_nodes",
",",
"[",
"name",
"]",
",",
"axis",
"=",
"axis",
",",
"name",
"=",
"name",
",",
")",
"return",
"[",
"node",
"]"
] | [
2757,
0
] | [
2771,
17
] | python | en | ['en', 'en', 'en'] | True |
choice_blocks | (layers_configs, stage_ops) |
Create list of layer candidates for NNI one-shot NAS.
Parameters
----------
layers_configs : list
the layer config: [input_channel, output_channel, stride, height]
stage_ops : dict
the pairs of op name and layer operator
Returns
-------
output: list
list of layer operators
|
Create list of layer candidates for NNI one-shot NAS. | def choice_blocks(layers_configs, stage_ops):
"""
Create list of layer candidates for NNI one-shot NAS.
Parameters
----------
layers_configs : list
the layer config: [input_channel, output_channel, stride, height]
stage_ops : dict
the pairs of op name and layer operator
Returns
-------
output: list
list of layer operators
"""
ops_names = [op for op in stage_ops]
fm = {"fm_size": layers_configs[3]}
op_list = [stage_ops[op](*layers_configs[0:3], **fm) for op in ops_names]
return op_list | [
"def",
"choice_blocks",
"(",
"layers_configs",
",",
"stage_ops",
")",
":",
"ops_names",
"=",
"[",
"op",
"for",
"op",
"in",
"stage_ops",
"]",
"fm",
"=",
"{",
"\"fm_size\"",
":",
"layers_configs",
"[",
"3",
"]",
"}",
"op_list",
"=",
"[",
"stage_ops",
"[",
"op",
"]",
"(",
"*",
"layers_configs",
"[",
"0",
":",
"3",
"]",
",",
"*",
"*",
"fm",
")",
"for",
"op",
"in",
"ops_names",
"]",
"return",
"op_list"
] | [
435,
0
] | [
455,
18
] | python | en | ['en', 'error', 'th'] | False |
SingleOperation.__init__ | (self, layers_configs, stage_ops, sampled_op="") |
Parameters
----------
layers_configs : list
the layer config: [input_channel, output_channel, stride, height]
stage_ops : dict
the pairs of op name and layer operator
sampled_op : str
the searched layer name
|
Parameters
----------
layers_configs : list
the layer config: [input_channel, output_channel, stride, height]
stage_ops : dict
the pairs of op name and layer operator
sampled_op : str
the searched layer name
| def __init__(self, layers_configs, stage_ops, sampled_op=""):
"""
Parameters
----------
layers_configs : list
the layer config: [input_channel, output_channel, stride, height]
stage_ops : dict
the pairs of op name and layer operator
sampled_op : str
the searched layer name
"""
super(SingleOperation, self).__init__()
fm = {"fm_size": layers_configs[3]}
ops_names = [op_name for op_name in stage_ops]
sampled_op = sampled_op if sampled_op else ops_names[0]
# define the single op
self.op = stage_ops[sampled_op](*layers_configs[0:3], **fm) | [
"def",
"__init__",
"(",
"self",
",",
"layers_configs",
",",
"stage_ops",
",",
"sampled_op",
"=",
"\"\"",
")",
":",
"super",
"(",
"SingleOperation",
",",
"self",
")",
".",
"__init__",
"(",
")",
"fm",
"=",
"{",
"\"fm_size\"",
":",
"layers_configs",
"[",
"3",
"]",
"}",
"ops_names",
"=",
"[",
"op_name",
"for",
"op_name",
"in",
"stage_ops",
"]",
"sampled_op",
"=",
"sampled_op",
"if",
"sampled_op",
"else",
"ops_names",
"[",
"0",
"]",
"# define the single op",
"self",
".",
"op",
"=",
"stage_ops",
"[",
"sampled_op",
"]",
"(",
"*",
"layers_configs",
"[",
"0",
":",
"3",
"]",
",",
"*",
"*",
"fm",
")"
] | [
412,
4
] | [
429,
67
] | python | en | ['en', 'error', 'th'] | False |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up the Fido sensor. | Set up the Fido sensor. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Fido sensor."""
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
httpsession = hass.helpers.aiohttp_client.async_get_clientsession()
fido_data = FidoData(username, password, httpsession)
ret = await fido_data.async_update()
if ret is False:
return
name = config.get(CONF_NAME)
sensors = []
for number in fido_data.client.get_phone_numbers():
for variable in config[CONF_MONITORED_VARIABLES]:
sensors.append(FidoSensor(fido_data, variable, name, number))
async_add_entities(sensors, True) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"username",
"=",
"config",
".",
"get",
"(",
"CONF_USERNAME",
")",
"password",
"=",
"config",
".",
"get",
"(",
"CONF_PASSWORD",
")",
"httpsession",
"=",
"hass",
".",
"helpers",
".",
"aiohttp_client",
".",
"async_get_clientsession",
"(",
")",
"fido_data",
"=",
"FidoData",
"(",
"username",
",",
"password",
",",
"httpsession",
")",
"ret",
"=",
"await",
"fido_data",
".",
"async_update",
"(",
")",
"if",
"ret",
"is",
"False",
":",
"return",
"name",
"=",
"config",
".",
"get",
"(",
"CONF_NAME",
")",
"sensors",
"=",
"[",
"]",
"for",
"number",
"in",
"fido_data",
".",
"client",
".",
"get_phone_numbers",
"(",
")",
":",
"for",
"variable",
"in",
"config",
"[",
"CONF_MONITORED_VARIABLES",
"]",
":",
"sensors",
".",
"append",
"(",
"FidoSensor",
"(",
"fido_data",
",",
"variable",
",",
"name",
",",
"number",
")",
")",
"async_add_entities",
"(",
"sensors",
",",
"True",
")"
] | [
71,
0
] | [
89,
37
] | python | en | ['en', 'pt', 'en'] | True |
FidoSensor.__init__ | (self, fido_data, sensor_type, name, number) | Initialize the sensor. | Initialize the sensor. | def __init__(self, fido_data, sensor_type, name, number):
"""Initialize the sensor."""
self.client_name = name
self._number = number
self.type = sensor_type
self._name = SENSOR_TYPES[sensor_type][0]
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self._icon = SENSOR_TYPES[sensor_type][2]
self.fido_data = fido_data
self._state = None | [
"def",
"__init__",
"(",
"self",
",",
"fido_data",
",",
"sensor_type",
",",
"name",
",",
"number",
")",
":",
"self",
".",
"client_name",
"=",
"name",
"self",
".",
"_number",
"=",
"number",
"self",
".",
"type",
"=",
"sensor_type",
"self",
".",
"_name",
"=",
"SENSOR_TYPES",
"[",
"sensor_type",
"]",
"[",
"0",
"]",
"self",
".",
"_unit_of_measurement",
"=",
"SENSOR_TYPES",
"[",
"sensor_type",
"]",
"[",
"1",
"]",
"self",
".",
"_icon",
"=",
"SENSOR_TYPES",
"[",
"sensor_type",
"]",
"[",
"2",
"]",
"self",
".",
"fido_data",
"=",
"fido_data",
"self",
".",
"_state",
"=",
"None"
] | [
95,
4
] | [
104,
26
] | python | en | ['en', 'en', 'en'] | True |
FidoSensor.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
return f"{self.client_name} {self._number} {self._name}" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"f\"{self.client_name} {self._number} {self._name}\""
] | [
107,
4
] | [
109,
64
] | python | en | ['en', 'mi', 'en'] | True |
FidoSensor.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self):
"""Return the state of the sensor."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
112,
4
] | [
114,
26
] | python | en | ['en', 'en', 'en'] | True |
FidoSensor.unit_of_measurement | (self) | Return the unit of measurement of this entity, if any. | Return the unit of measurement of this entity, if any. | def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unit_of_measurement"
] | [
117,
4
] | [
119,
40
] | python | en | ['en', 'en', 'en'] | True |
FidoSensor.icon | (self) | Icon to use in the frontend, if any. | Icon to use in the frontend, if any. | def icon(self):
"""Icon to use in the frontend, if any."""
return self._icon | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"self",
".",
"_icon"
] | [
122,
4
] | [
124,
25
] | python | en | ['en', 'en', 'en'] | True |
FidoSensor.device_state_attributes | (self) | Return the state attributes of the sensor. | Return the state attributes of the sensor. | def device_state_attributes(self):
"""Return the state attributes of the sensor."""
return {"number": self._number} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"{",
"\"number\"",
":",
"self",
".",
"_number",
"}"
] | [
127,
4
] | [
129,
39
] | python | en | ['en', 'en', 'en'] | True |
FidoSensor.async_update | (self) | Get the latest data from Fido and update the state. | Get the latest data from Fido and update the state. | async def async_update(self):
"""Get the latest data from Fido and update the state."""
await self.fido_data.async_update()
if self.type == "balance":
if self.fido_data.data.get(self.type) is not None:
self._state = round(self.fido_data.data[self.type], 2)
else:
if self.fido_data.data.get(self._number, {}).get(self.type) is not None:
self._state = self.fido_data.data[self._number][self.type]
self._state = round(self._state, 2) | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"await",
"self",
".",
"fido_data",
".",
"async_update",
"(",
")",
"if",
"self",
".",
"type",
"==",
"\"balance\"",
":",
"if",
"self",
".",
"fido_data",
".",
"data",
".",
"get",
"(",
"self",
".",
"type",
")",
"is",
"not",
"None",
":",
"self",
".",
"_state",
"=",
"round",
"(",
"self",
".",
"fido_data",
".",
"data",
"[",
"self",
".",
"type",
"]",
",",
"2",
")",
"else",
":",
"if",
"self",
".",
"fido_data",
".",
"data",
".",
"get",
"(",
"self",
".",
"_number",
",",
"{",
"}",
")",
".",
"get",
"(",
"self",
".",
"type",
")",
"is",
"not",
"None",
":",
"self",
".",
"_state",
"=",
"self",
".",
"fido_data",
".",
"data",
"[",
"self",
".",
"_number",
"]",
"[",
"self",
".",
"type",
"]",
"self",
".",
"_state",
"=",
"round",
"(",
"self",
".",
"_state",
",",
"2",
")"
] | [
131,
4
] | [
140,
51
] | python | en | ['en', 'en', 'en'] | True |
FidoData.__init__ | (self, username, password, httpsession) | Initialize the data object. | Initialize the data object. | def __init__(self, username, password, httpsession):
"""Initialize the data object."""
self.client = FidoClient(username, password, REQUESTS_TIMEOUT, httpsession)
self.data = {} | [
"def",
"__init__",
"(",
"self",
",",
"username",
",",
"password",
",",
"httpsession",
")",
":",
"self",
".",
"client",
"=",
"FidoClient",
"(",
"username",
",",
"password",
",",
"REQUESTS_TIMEOUT",
",",
"httpsession",
")",
"self",
".",
"data",
"=",
"{",
"}"
] | [
146,
4
] | [
150,
22
] | python | en | ['en', 'en', 'en'] | True |
FidoData.async_update | (self) | Get the latest data from Fido. | Get the latest data from Fido. | async def async_update(self):
"""Get the latest data from Fido."""
try:
await self.client.fetch_data()
except PyFidoError as exp:
_LOGGER.error("Error on receive last Fido data: %s", exp)
return False
# Update data
self.data = self.client.get_data()
return True | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"try",
":",
"await",
"self",
".",
"client",
".",
"fetch_data",
"(",
")",
"except",
"PyFidoError",
"as",
"exp",
":",
"_LOGGER",
".",
"error",
"(",
"\"Error on receive last Fido data: %s\"",
",",
"exp",
")",
"return",
"False",
"# Update data",
"self",
".",
"data",
"=",
"self",
".",
"client",
".",
"get_data",
"(",
")",
"return",
"True"
] | [
153,
4
] | [
163,
19
] | python | en | ['en', 'en', 'en'] | True |
Model.fork | (self) |
Create a new model which has same topology, names, and IDs to current one.
Can only be invoked on a frozen model.
The new model will be in `Mutating` state.
This API is used in mutator base class.
|
Create a new model which has same topology, names, and IDs to current one. | def fork(self) -> 'Model':
"""
Create a new model which has same topology, names, and IDs to current one.
Can only be invoked on a frozen model.
The new model will be in `Mutating` state.
This API is used in mutator base class.
"""
new_model = Model(_internal=True)
new_model._root_graph_name = self._root_graph_name
new_model.python_class = self.python_class
new_model.python_init_params = self.python_init_params
new_model.graphs = {name: graph._fork_to(new_model) for name, graph in self.graphs.items()}
new_model.evaluator = copy.deepcopy(self.evaluator) # TODO this may be a problem when evaluator is large
new_model.history = [*self.history]
# Note: the history is not updated. It will be updated when the model is changed, that is in mutator.
return new_model | [
"def",
"fork",
"(",
"self",
")",
"->",
"'Model'",
":",
"new_model",
"=",
"Model",
"(",
"_internal",
"=",
"True",
")",
"new_model",
".",
"_root_graph_name",
"=",
"self",
".",
"_root_graph_name",
"new_model",
".",
"python_class",
"=",
"self",
".",
"python_class",
"new_model",
".",
"python_init_params",
"=",
"self",
".",
"python_init_params",
"new_model",
".",
"graphs",
"=",
"{",
"name",
":",
"graph",
".",
"_fork_to",
"(",
"new_model",
")",
"for",
"name",
",",
"graph",
"in",
"self",
".",
"graphs",
".",
"items",
"(",
")",
"}",
"new_model",
".",
"evaluator",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"evaluator",
")",
"# TODO this may be a problem when evaluator is large",
"new_model",
".",
"history",
"=",
"[",
"*",
"self",
".",
"history",
"]",
"# Note: the history is not updated. It will be updated when the model is changed, that is in mutator.",
"return",
"new_model"
] | [
131,
4
] | [
148,
24
] | python | en | ['en', 'error', 'th'] | False |
Model.get_nodes | (self) |
Traverse through all the nodes.
|
Traverse through all the nodes.
| def get_nodes(self) -> Iterable['Node']:
"""
Traverse through all the nodes.
"""
for graph in self.graphs.values():
for node in graph.nodes:
yield node | [
"def",
"get_nodes",
"(",
"self",
")",
"->",
"Iterable",
"[",
"'Node'",
"]",
":",
"for",
"graph",
"in",
"self",
".",
"graphs",
".",
"values",
"(",
")",
":",
"for",
"node",
"in",
"graph",
".",
"nodes",
":",
"yield",
"node"
] | [
169,
4
] | [
175,
26
] | python | en | ['en', 'error', 'th'] | False |
Model.get_nodes_by_label | (self, label: str) |
Traverse all the nodes to find the matched node(s) with the given label.
There could be multiple nodes with the same label. Name space name can uniquely
identify a graph or node.
NOTE: the implementation does not support the class abstration
|
Traverse all the nodes to find the matched node(s) with the given label.
There could be multiple nodes with the same label. Name space name can uniquely
identify a graph or node. | def get_nodes_by_label(self, label: str) -> List['Node']:
"""
Traverse all the nodes to find the matched node(s) with the given label.
There could be multiple nodes with the same label. Name space name can uniquely
identify a graph or node.
NOTE: the implementation does not support the class abstration
"""
matched_nodes = []
for graph in self.graphs.values():
nodes = graph.get_nodes_by_label(label)
matched_nodes.extend(nodes)
return matched_nodes | [
"def",
"get_nodes_by_label",
"(",
"self",
",",
"label",
":",
"str",
")",
"->",
"List",
"[",
"'Node'",
"]",
":",
"matched_nodes",
"=",
"[",
"]",
"for",
"graph",
"in",
"self",
".",
"graphs",
".",
"values",
"(",
")",
":",
"nodes",
"=",
"graph",
".",
"get_nodes_by_label",
"(",
"label",
")",
"matched_nodes",
".",
"extend",
"(",
"nodes",
")",
"return",
"matched_nodes"
] | [
177,
4
] | [
189,
28
] | python | en | ['en', 'error', 'th'] | False |
Model.get_nodes_by_type | (self, type_name: str) |
Traverse all the nodes to find the matched node(s) with the given type.
|
Traverse all the nodes to find the matched node(s) with the given type.
| def get_nodes_by_type(self, type_name: str) -> List['Node']:
"""
Traverse all the nodes to find the matched node(s) with the given type.
"""
matched_nodes = []
for graph in self.graphs.values():
nodes = graph.get_nodes_by_type(type_name)
matched_nodes.extend(nodes)
return matched_nodes | [
"def",
"get_nodes_by_type",
"(",
"self",
",",
"type_name",
":",
"str",
")",
"->",
"List",
"[",
"'Node'",
"]",
":",
"matched_nodes",
"=",
"[",
"]",
"for",
"graph",
"in",
"self",
".",
"graphs",
".",
"values",
"(",
")",
":",
"nodes",
"=",
"graph",
".",
"get_nodes_by_type",
"(",
"type_name",
")",
"matched_nodes",
".",
"extend",
"(",
"nodes",
")",
"return",
"matched_nodes"
] | [
191,
4
] | [
199,
28
] | python | en | ['en', 'error', 'th'] | False |
Model.get_node_by_name | (self, node_name: str) |
Traverse all the nodes to find the matched node with the given name.
|
Traverse all the nodes to find the matched node with the given name.
| def get_node_by_name(self, node_name: str) -> 'Node':
"""
Traverse all the nodes to find the matched node with the given name.
"""
matched_nodes = []
for graph in self.graphs.values():
nodes = graph.get_nodes_by_name(node_name)
matched_nodes.extend(nodes)
assert len(matched_nodes) <= 1
if matched_nodes:
return matched_nodes[0]
else:
return None | [
"def",
"get_node_by_name",
"(",
"self",
",",
"node_name",
":",
"str",
")",
"->",
"'Node'",
":",
"matched_nodes",
"=",
"[",
"]",
"for",
"graph",
"in",
"self",
".",
"graphs",
".",
"values",
"(",
")",
":",
"nodes",
"=",
"graph",
".",
"get_nodes_by_name",
"(",
"node_name",
")",
"matched_nodes",
".",
"extend",
"(",
"nodes",
")",
"assert",
"len",
"(",
"matched_nodes",
")",
"<=",
"1",
"if",
"matched_nodes",
":",
"return",
"matched_nodes",
"[",
"0",
"]",
"else",
":",
"return",
"None"
] | [
201,
4
] | [
213,
23
] | python | en | ['en', 'error', 'th'] | False |
Graph.get_node_by_name | (self, name: str) |
Returns the node which has specified name; or returns `None` if no node has this name.
|
Returns the node which has specified name; or returns `None` if no node has this name.
| def get_node_by_name(self, name: str) -> Optional['Node']:
"""
Returns the node which has specified name; or returns `None` if no node has this name.
"""
found = [node for node in self.nodes if node.name == name]
return found[0] if found else None | [
"def",
"get_node_by_name",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"Optional",
"[",
"'Node'",
"]",
":",
"found",
"=",
"[",
"node",
"for",
"node",
"in",
"self",
".",
"nodes",
"if",
"node",
".",
"name",
"==",
"name",
"]",
"return",
"found",
"[",
"0",
"]",
"if",
"found",
"else",
"None"
] | [
344,
4
] | [
349,
42
] | python | en | ['en', 'error', 'th'] | False |
Graph.get_nodes_by_type | (self, operation_type: str) |
Returns nodes whose operation is specified typed.
|
Returns nodes whose operation is specified typed.
| def get_nodes_by_type(self, operation_type: str) -> List['Node']:
"""
Returns nodes whose operation is specified typed.
"""
return [node for node in self.hidden_nodes if node.operation.type == operation_type] | [
"def",
"get_nodes_by_type",
"(",
"self",
",",
"operation_type",
":",
"str",
")",
"->",
"List",
"[",
"'Node'",
"]",
":",
"return",
"[",
"node",
"for",
"node",
"in",
"self",
".",
"hidden_nodes",
"if",
"node",
".",
"operation",
".",
"type",
"==",
"operation_type",
"]"
] | [
351,
4
] | [
355,
92
] | python | en | ['en', 'error', 'th'] | False |
Graph.get_node_by_id | (self, node_id: int) |
Returns the node which has specified name; or returns `None` if no node has this name.
|
Returns the node which has specified name; or returns `None` if no node has this name.
| def get_node_by_id(self, node_id: int) -> Optional['Node']:
"""
Returns the node which has specified name; or returns `None` if no node has this name.
"""
found = [node for node in self.nodes if node.id == node_id]
return found[0] if found else None | [
"def",
"get_node_by_id",
"(",
"self",
",",
"node_id",
":",
"int",
")",
"->",
"Optional",
"[",
"'Node'",
"]",
":",
"found",
"=",
"[",
"node",
"for",
"node",
"in",
"self",
".",
"nodes",
"if",
"node",
".",
"id",
"==",
"node_id",
"]",
"return",
"found",
"[",
"0",
"]",
"if",
"found",
"else",
"None"
] | [
357,
4
] | [
362,
42
] | python | en | ['en', 'error', 'th'] | False |
Graph.fork | (self) |
Fork the model and returns corresponding graph in new model.
This shortcut might be helpful because many algorithms only cares about "stem" subgraph instead of whole model.
|
Fork the model and returns corresponding graph in new model.
This shortcut might be helpful because many algorithms only cares about "stem" subgraph instead of whole model.
| def fork(self) -> 'Graph':
"""
Fork the model and returns corresponding graph in new model.
This shortcut might be helpful because many algorithms only cares about "stem" subgraph instead of whole model.
"""
return self.model.fork().graphs[self.name] | [
"def",
"fork",
"(",
"self",
")",
"->",
"'Graph'",
":",
"return",
"self",
".",
"model",
".",
"fork",
"(",
")",
".",
"graphs",
"[",
"self",
".",
"name",
"]"
] | [
402,
4
] | [
407,
50
] | python | en | ['en', 'error', 'th'] | False |
Node.specialize_cell | (self) |
Only available if the operation is a cell.
Duplicate the cell template and let this node reference to newly created copy.
|
Only available if the operation is a cell.
Duplicate the cell template and let this node reference to newly created copy.
| def specialize_cell(self) -> Graph:
"""
Only available if the operation is a cell.
Duplicate the cell template and let this node reference to newly created copy.
"""
new_cell = self.cell._copy()._register()
self.operation = Cell(new_cell.name)
return new_cell | [
"def",
"specialize_cell",
"(",
"self",
")",
"->",
"Graph",
":",
"new_cell",
"=",
"self",
".",
"cell",
".",
"_copy",
"(",
")",
".",
"_register",
"(",
")",
"self",
".",
"operation",
"=",
"Cell",
"(",
"new_cell",
".",
"name",
")",
"return",
"new_cell"
] | [
579,
4
] | [
586,
23
] | python | en | ['en', 'error', 'th'] | False |
_retrieve_online_state | (data, detail) | Get the latest state of the sensor. | Get the latest state of the sensor. | def _retrieve_online_state(data, detail):
"""Get the latest state of the sensor."""
# The doorbell will go into standby mode when there is no motion
# for a short while. It will wake by itself when needed so we need
# to consider is available or we will not report motion or dings
return detail.is_online or detail.is_standby | [
"def",
"_retrieve_online_state",
"(",
"data",
",",
"detail",
")",
":",
"# The doorbell will go into standby mode when there is no motion",
"# for a short while. It will wake by itself when needed so we need",
"# to consider is available or we will not report motion or dings",
"return",
"detail",
".",
"is_online",
"or",
"detail",
".",
"is_standby"
] | [
27,
0
] | [
33,
48
] | python | en | ['en', 'en', 'en'] | True |
_activity_time_based_state | (data, device_id, activity_types) | Get the latest state of the sensor. | Get the latest state of the sensor. | def _activity_time_based_state(data, device_id, activity_types):
"""Get the latest state of the sensor."""
latest = data.activity_stream.get_latest_device_activity(device_id, activity_types)
if latest is not None:
start = latest.activity_start_time
end = latest.activity_end_time + TIME_TO_DECLARE_DETECTION
return start <= datetime.now() <= end
return None | [
"def",
"_activity_time_based_state",
"(",
"data",
",",
"device_id",
",",
"activity_types",
")",
":",
"latest",
"=",
"data",
".",
"activity_stream",
".",
"get_latest_device_activity",
"(",
"device_id",
",",
"activity_types",
")",
"if",
"latest",
"is",
"not",
"None",
":",
"start",
"=",
"latest",
".",
"activity_start_time",
"end",
"=",
"latest",
".",
"activity_end_time",
"+",
"TIME_TO_DECLARE_DETECTION",
"return",
"start",
"<=",
"datetime",
".",
"now",
"(",
")",
"<=",
"end",
"return",
"None"
] | [
52,
0
] | [
60,
15
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, config_entry, async_add_entities) | Set up the August binary sensors. | Set up the August binary sensors. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the August binary sensors."""
data = hass.data[DOMAIN][config_entry.entry_id][DATA_AUGUST]
devices = []
for door in data.locks:
detail = data.get_device_detail(door.device_id)
if not detail.doorsense:
_LOGGER.debug(
"Not adding sensor class door for lock %s because it does not have doorsense",
door.device_name,
)
continue
_LOGGER.debug("Adding sensor class door for %s", door.device_name)
devices.append(AugustDoorBinarySensor(data, "door_open", door))
for doorbell in data.doorbells:
for sensor_type in SENSOR_TYPES_DOORBELL:
_LOGGER.debug(
"Adding doorbell sensor class %s for %s",
SENSOR_TYPES_DOORBELL[sensor_type][SENSOR_DEVICE_CLASS],
doorbell.device_name,
)
devices.append(AugustDoorbellBinarySensor(data, sensor_type, doorbell))
async_add_entities(devices, True) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"data",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"config_entry",
".",
"entry_id",
"]",
"[",
"DATA_AUGUST",
"]",
"devices",
"=",
"[",
"]",
"for",
"door",
"in",
"data",
".",
"locks",
":",
"detail",
"=",
"data",
".",
"get_device_detail",
"(",
"door",
".",
"device_id",
")",
"if",
"not",
"detail",
".",
"doorsense",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Not adding sensor class door for lock %s because it does not have doorsense\"",
",",
"door",
".",
"device_name",
",",
")",
"continue",
"_LOGGER",
".",
"debug",
"(",
"\"Adding sensor class door for %s\"",
",",
"door",
".",
"device_name",
")",
"devices",
".",
"append",
"(",
"AugustDoorBinarySensor",
"(",
"data",
",",
"\"door_open\"",
",",
"door",
")",
")",
"for",
"doorbell",
"in",
"data",
".",
"doorbells",
":",
"for",
"sensor_type",
"in",
"SENSOR_TYPES_DOORBELL",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Adding doorbell sensor class %s for %s\"",
",",
"SENSOR_TYPES_DOORBELL",
"[",
"sensor_type",
"]",
"[",
"SENSOR_DEVICE_CLASS",
"]",
",",
"doorbell",
".",
"device_name",
",",
")",
"devices",
".",
"append",
"(",
"AugustDoorbellBinarySensor",
"(",
"data",
",",
"sensor_type",
",",
"doorbell",
")",
")",
"async_add_entities",
"(",
"devices",
",",
"True",
")"
] | [
81,
0
] | [
107,
37
] | python | en | ['en', 'en', 'en'] | True |
AugustDoorBinarySensor.__init__ | (self, data, sensor_type, device) | Initialize the sensor. | Initialize the sensor. | def __init__(self, data, sensor_type, device):
"""Initialize the sensor."""
super().__init__(data, device)
self._data = data
self._sensor_type = sensor_type
self._device = device
self._update_from_data() | [
"def",
"__init__",
"(",
"self",
",",
"data",
",",
"sensor_type",
",",
"device",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"data",
",",
"device",
")",
"self",
".",
"_data",
"=",
"data",
"self",
".",
"_sensor_type",
"=",
"sensor_type",
"self",
".",
"_device",
"=",
"device",
"self",
".",
"_update_from_data",
"(",
")"
] | [
113,
4
] | [
119,
32
] | python | en | ['en', 'en', 'en'] | True |
AugustDoorBinarySensor.available | (self) | Return the availability of this sensor. | Return the availability of this sensor. | def available(self):
"""Return the availability of this sensor."""
return self._detail.bridge_is_online | [
"def",
"available",
"(",
"self",
")",
":",
"return",
"self",
".",
"_detail",
".",
"bridge_is_online"
] | [
122,
4
] | [
124,
44
] | python | en | ['en', 'en', 'en'] | True |
AugustDoorBinarySensor.is_on | (self) | Return true if the binary sensor is on. | Return true if the binary sensor is on. | def is_on(self):
"""Return true if the binary sensor is on."""
return self._detail.door_state == LockDoorStatus.OPEN | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_detail",
".",
"door_state",
"==",
"LockDoorStatus",
".",
"OPEN"
] | [
127,
4
] | [
129,
61
] | python | en | ['en', 'fy', 'en'] | True |
AugustDoorBinarySensor.device_class | (self) | Return the class of this device. | Return the class of this device. | def device_class(self):
"""Return the class of this device."""
return DEVICE_CLASS_DOOR | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"DEVICE_CLASS_DOOR"
] | [
132,
4
] | [
134,
32
] | python | en | ['en', 'en', 'en'] | True |
AugustDoorBinarySensor.name | (self) | Return the name of the binary sensor. | Return the name of the binary sensor. | def name(self):
"""Return the name of the binary sensor."""
return f"{self._device.device_name} Open" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"f\"{self._device.device_name} Open\""
] | [
137,
4
] | [
139,
49
] | python | en | ['en', 'mi', 'en'] | True |
AugustDoorBinarySensor._update_from_data | (self) | Get the latest state of the sensor and update activity. | Get the latest state of the sensor and update activity. | def _update_from_data(self):
"""Get the latest state of the sensor and update activity."""
door_activity = self._data.activity_stream.get_latest_device_activity(
self._device_id, [ActivityType.DOOR_OPERATION]
)
if door_activity is not None:
update_lock_detail_from_activity(self._detail, door_activity) | [
"def",
"_update_from_data",
"(",
"self",
")",
":",
"door_activity",
"=",
"self",
".",
"_data",
".",
"activity_stream",
".",
"get_latest_device_activity",
"(",
"self",
".",
"_device_id",
",",
"[",
"ActivityType",
".",
"DOOR_OPERATION",
"]",
")",
"if",
"door_activity",
"is",
"not",
"None",
":",
"update_lock_detail_from_activity",
"(",
"self",
".",
"_detail",
",",
"door_activity",
")"
] | [
142,
4
] | [
149,
73
] | python | en | ['en', 'en', 'en'] | True |
AugustDoorBinarySensor.unique_id | (self) | Get the unique of the door open binary sensor. | Get the unique of the door open binary sensor. | def unique_id(self) -> str:
"""Get the unique of the door open binary sensor."""
return f"{self._device_id}_open" | [
"def",
"unique_id",
"(",
"self",
")",
"->",
"str",
":",
"return",
"f\"{self._device_id}_open\""
] | [
152,
4
] | [
154,
40
] | python | en | ['en', 'nl', 'en'] | True |
AugustDoorbellBinarySensor.__init__ | (self, data, sensor_type, device) | Initialize the sensor. | Initialize the sensor. | def __init__(self, data, sensor_type, device):
"""Initialize the sensor."""
super().__init__(data, device)
self._check_for_off_update_listener = None
self._data = data
self._sensor_type = sensor_type
self._device = device
self._state = None
self._available = False
self._update_from_data() | [
"def",
"__init__",
"(",
"self",
",",
"data",
",",
"sensor_type",
",",
"device",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"data",
",",
"device",
")",
"self",
".",
"_check_for_off_update_listener",
"=",
"None",
"self",
".",
"_data",
"=",
"data",
"self",
".",
"_sensor_type",
"=",
"sensor_type",
"self",
".",
"_device",
"=",
"device",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"_available",
"=",
"False",
"self",
".",
"_update_from_data",
"(",
")"
] | [
160,
4
] | [
169,
32
] | python | en | ['en', 'en', 'en'] | True |
AugustDoorbellBinarySensor.available | (self) | Return the availability of this sensor. | Return the availability of this sensor. | def available(self):
"""Return the availability of this sensor."""
return self._available | [
"def",
"available",
"(",
"self",
")",
":",
"return",
"self",
".",
"_available"
] | [
172,
4
] | [
174,
30
] | python | en | ['en', 'en', 'en'] | True |
AugustDoorbellBinarySensor.is_on | (self) | Return true if the binary sensor is on. | Return true if the binary sensor is on. | def is_on(self):
"""Return true if the binary sensor is on."""
return self._state | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
177,
4
] | [
179,
26
] | python | en | ['en', 'fy', 'en'] | True |
AugustDoorbellBinarySensor.device_class | (self) | Return the class of this device, from component DEVICE_CLASSES. | Return the class of this device, from component DEVICE_CLASSES. | def device_class(self):
"""Return the class of this device, from component DEVICE_CLASSES."""
return SENSOR_TYPES_DOORBELL[self._sensor_type][SENSOR_DEVICE_CLASS] | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"SENSOR_TYPES_DOORBELL",
"[",
"self",
".",
"_sensor_type",
"]",
"[",
"SENSOR_DEVICE_CLASS",
"]"
] | [
182,
4
] | [
184,
76
] | python | en | ['en', 'en', 'en'] | True |
AugustDoorbellBinarySensor.name | (self) | Return the name of the binary sensor. | Return the name of the binary sensor. | def name(self):
"""Return the name of the binary sensor."""
return f"{self._device.device_name} {SENSOR_TYPES_DOORBELL[self._sensor_type][SENSOR_NAME]}" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"f\"{self._device.device_name} {SENSOR_TYPES_DOORBELL[self._sensor_type][SENSOR_NAME]}\""
] | [
187,
4
] | [
189,
100
] | python | en | ['en', 'mi', 'en'] | True |
AugustDoorbellBinarySensor._state_provider | (self) | Return the state provider for the binary sensor. | Return the state provider for the binary sensor. | def _state_provider(self):
"""Return the state provider for the binary sensor."""
return SENSOR_TYPES_DOORBELL[self._sensor_type][SENSOR_STATE_PROVIDER] | [
"def",
"_state_provider",
"(",
"self",
")",
":",
"return",
"SENSOR_TYPES_DOORBELL",
"[",
"self",
".",
"_sensor_type",
"]",
"[",
"SENSOR_STATE_PROVIDER",
"]"
] | [
192,
4
] | [
194,
78
] | python | en | ['en', 'no', 'en'] | True |
AugustDoorbellBinarySensor._is_time_based | (self) | Return true of false if the sensor is time based. | Return true of false if the sensor is time based. | def _is_time_based(self):
"""Return true of false if the sensor is time based."""
return SENSOR_TYPES_DOORBELL[self._sensor_type][SENSOR_STATE_IS_TIME_BASED] | [
"def",
"_is_time_based",
"(",
"self",
")",
":",
"return",
"SENSOR_TYPES_DOORBELL",
"[",
"self",
".",
"_sensor_type",
"]",
"[",
"SENSOR_STATE_IS_TIME_BASED",
"]"
] | [
197,
4
] | [
199,
83
] | python | en | ['en', 'no', 'en'] | True |
AugustDoorbellBinarySensor._update_from_data | (self) | Get the latest state of the sensor. | Get the latest state of the sensor. | def _update_from_data(self):
"""Get the latest state of the sensor."""
self._cancel_any_pending_updates()
self._state = self._state_provider(self._data, self._detail)
if self._is_time_based:
self._available = _retrieve_online_state(self._data, self._detail)
self._schedule_update_to_recheck_turn_off_sensor()
else:
self._available = True | [
"def",
"_update_from_data",
"(",
"self",
")",
":",
"self",
".",
"_cancel_any_pending_updates",
"(",
")",
"self",
".",
"_state",
"=",
"self",
".",
"_state_provider",
"(",
"self",
".",
"_data",
",",
"self",
".",
"_detail",
")",
"if",
"self",
".",
"_is_time_based",
":",
"self",
".",
"_available",
"=",
"_retrieve_online_state",
"(",
"self",
".",
"_data",
",",
"self",
".",
"_detail",
")",
"self",
".",
"_schedule_update_to_recheck_turn_off_sensor",
"(",
")",
"else",
":",
"self",
".",
"_available",
"=",
"True"
] | [
202,
4
] | [
211,
34
] | python | en | ['en', 'en', 'en'] | True |
AugustDoorbellBinarySensor._schedule_update_to_recheck_turn_off_sensor | (self) | Schedule an update to recheck the sensor to see if it is ready to turn off. | Schedule an update to recheck the sensor to see if it is ready to turn off. | def _schedule_update_to_recheck_turn_off_sensor(self):
"""Schedule an update to recheck the sensor to see if it is ready to turn off."""
# If the sensor is already off there is nothing to do
if not self._state:
return
# self.hass is only available after setup is completed
# and we will recheck in async_added_to_hass
if not self.hass:
return
@callback
def _scheduled_update(now):
"""Timer callback for sensor update."""
self._check_for_off_update_listener = None
self._update_from_data()
self._check_for_off_update_listener = async_track_point_in_utc_time(
self.hass, _scheduled_update, utcnow() + TIME_TO_DECLARE_DETECTION
) | [
"def",
"_schedule_update_to_recheck_turn_off_sensor",
"(",
"self",
")",
":",
"# If the sensor is already off there is nothing to do",
"if",
"not",
"self",
".",
"_state",
":",
"return",
"# self.hass is only available after setup is completed",
"# and we will recheck in async_added_to_hass",
"if",
"not",
"self",
".",
"hass",
":",
"return",
"@",
"callback",
"def",
"_scheduled_update",
"(",
"now",
")",
":",
"\"\"\"Timer callback for sensor update.\"\"\"",
"self",
".",
"_check_for_off_update_listener",
"=",
"None",
"self",
".",
"_update_from_data",
"(",
")",
"self",
".",
"_check_for_off_update_listener",
"=",
"async_track_point_in_utc_time",
"(",
"self",
".",
"hass",
",",
"_scheduled_update",
",",
"utcnow",
"(",
")",
"+",
"TIME_TO_DECLARE_DETECTION",
")"
] | [
213,
4
] | [
233,
9
] | python | en | ['en', 'en', 'en'] | True |
AugustDoorbellBinarySensor._cancel_any_pending_updates | (self) | Cancel any updates to recheck a sensor to see if it is ready to turn off. | Cancel any updates to recheck a sensor to see if it is ready to turn off. | def _cancel_any_pending_updates(self):
"""Cancel any updates to recheck a sensor to see if it is ready to turn off."""
if self._check_for_off_update_listener:
_LOGGER.debug("%s: canceled pending update", self.entity_id)
self._check_for_off_update_listener()
self._check_for_off_update_listener = None | [
"def",
"_cancel_any_pending_updates",
"(",
"self",
")",
":",
"if",
"self",
".",
"_check_for_off_update_listener",
":",
"_LOGGER",
".",
"debug",
"(",
"\"%s: canceled pending update\"",
",",
"self",
".",
"entity_id",
")",
"self",
".",
"_check_for_off_update_listener",
"(",
")",
"self",
".",
"_check_for_off_update_listener",
"=",
"None"
] | [
235,
4
] | [
240,
54
] | python | en | ['en', 'en', 'en'] | True |
AugustDoorbellBinarySensor.async_added_to_hass | (self) | Call the mixin to subscribe and setup an async_track_point_in_utc_time to turn off the sensor if needed. | Call the mixin to subscribe and setup an async_track_point_in_utc_time to turn off the sensor if needed. | async def async_added_to_hass(self):
"""Call the mixin to subscribe and setup an async_track_point_in_utc_time to turn off the sensor if needed."""
self._schedule_update_to_recheck_turn_off_sensor()
await super().async_added_to_hass() | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"_schedule_update_to_recheck_turn_off_sensor",
"(",
")",
"await",
"super",
"(",
")",
".",
"async_added_to_hass",
"(",
")"
] | [
242,
4
] | [
245,
43
] | python | en | ['en', 'en', 'en'] | True |
AugustDoorbellBinarySensor.unique_id | (self) | Get the unique id of the doorbell sensor. | Get the unique id of the doorbell sensor. | def unique_id(self) -> str:
"""Get the unique id of the doorbell sensor."""
return (
f"{self._device_id}_"
f"{SENSOR_TYPES_DOORBELL[self._sensor_type][SENSOR_NAME].lower()}"
) | [
"def",
"unique_id",
"(",
"self",
")",
"->",
"str",
":",
"return",
"(",
"f\"{self._device_id}_\"",
"f\"{SENSOR_TYPES_DOORBELL[self._sensor_type][SENSOR_NAME].lower()}\"",
")"
] | [
248,
4
] | [
253,
9
] | python | en | ['en', 'nl', 'en'] | True |
_assert_tensors_equal | (a, b, atol=1e-12, prefix="") | If tensors not close, or a and b arent both tensors, raise a nice Assertion error. | If tensors not close, or a and b arent both tensors, raise a nice Assertion error. | def _assert_tensors_equal(a, b, atol=1e-12, prefix=""):
"""If tensors not close, or a and b arent both tensors, raise a nice Assertion error."""
if a is None and b is None:
return True
try:
if tf.debugging.assert_near(a, b, atol=atol):
return True
raise
except Exception:
msg = "{} != {}".format(a, b)
if prefix:
msg = prefix + ": " + msg
raise AssertionError(msg) | [
"def",
"_assert_tensors_equal",
"(",
"a",
",",
"b",
",",
"atol",
"=",
"1e-12",
",",
"prefix",
"=",
"\"\"",
")",
":",
"if",
"a",
"is",
"None",
"and",
"b",
"is",
"None",
":",
"return",
"True",
"try",
":",
"if",
"tf",
".",
"debugging",
".",
"assert_near",
"(",
"a",
",",
"b",
",",
"atol",
"=",
"atol",
")",
":",
"return",
"True",
"raise",
"except",
"Exception",
":",
"msg",
"=",
"\"{} != {}\"",
".",
"format",
"(",
"a",
",",
"b",
")",
"if",
"prefix",
":",
"msg",
"=",
"prefix",
"+",
"\": \"",
"+",
"msg",
"raise",
"AssertionError",
"(",
"msg",
")"
] | [
284,
0
] | [
296,
33
] | python | en | ['en', 'en', 'en'] | True |
mock_webhook_id | () | Mock webhook_id. | Mock webhook_id. | def mock_webhook_id():
"""Mock webhook_id."""
with patch(
"homeassistant.components.webhook.async_generate_id", return_value=WEBHOOK_ID
):
yield | [
"def",
"mock_webhook_id",
"(",
")",
":",
"with",
"patch",
"(",
"\"homeassistant.components.webhook.async_generate_id\"",
",",
"return_value",
"=",
"WEBHOOK_ID",
")",
":",
"yield"
] | [
24,
0
] | [
29,
13
] | python | en | ['en', 'xh', 'hi'] | False |
mock_secret | () | Mock secret. | Mock secret. | def mock_secret():
"""Mock secret."""
with patch("secrets.token_hex", return_value=SECRET):
yield | [
"def",
"mock_secret",
"(",
")",
":",
"with",
"patch",
"(",
"\"secrets.token_hex\"",
",",
"return_value",
"=",
"SECRET",
")",
":",
"yield"
] | [
33,
0
] | [
36,
13
] | python | en | ['en', 'fy', 'en'] | False |
mock_not_supports_encryption | () | Mock non successful nacl import. | Mock non successful nacl import. | def mock_not_supports_encryption():
"""Mock non successful nacl import."""
with patch(
"homeassistant.components.owntracks.config_flow.supports_encryption",
return_value=False,
):
yield | [
"def",
"mock_not_supports_encryption",
"(",
")",
":",
"with",
"patch",
"(",
"\"homeassistant.components.owntracks.config_flow.supports_encryption\"",
",",
"return_value",
"=",
"False",
",",
")",
":",
"yield"
] | [
40,
0
] | [
46,
13
] | python | de | ['de', 'it', 'en'] | False |
init_config_flow | (hass) | Init a configuration flow. | Init a configuration flow. | async def init_config_flow(hass):
"""Init a configuration flow."""
await async_process_ha_core_config(
hass,
{"external_url": BASE_URL},
)
flow = config_flow.OwnTracksFlow()
flow.hass = hass
return flow | [
"async",
"def",
"init_config_flow",
"(",
"hass",
")",
":",
"await",
"async_process_ha_core_config",
"(",
"hass",
",",
"{",
"\"external_url\"",
":",
"BASE_URL",
"}",
",",
")",
"flow",
"=",
"config_flow",
".",
"OwnTracksFlow",
"(",
")",
"flow",
".",
"hass",
"=",
"hass",
"return",
"flow"
] | [
49,
0
] | [
57,
15
] | python | en | ['es', 'fr', 'en'] | False |
test_user | (hass, webhook_id, secret) | Test user step. | Test user step. | async def test_user(hass, webhook_id, secret):
"""Test user step."""
flow = await init_config_flow(hass)
result = await flow.async_step_user()
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "user"
result = await flow.async_step_user({})
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "OwnTracks"
assert result["data"][CONF_WEBHOOK_ID] == WEBHOOK_ID
assert result["data"][CONF_SECRET] == SECRET
assert result["data"][CONF_CLOUDHOOK] == CLOUDHOOK
assert result["description_placeholders"][CONF_WEBHOOK_URL] == WEBHOOK_URL | [
"async",
"def",
"test_user",
"(",
"hass",
",",
"webhook_id",
",",
"secret",
")",
":",
"flow",
"=",
"await",
"init_config_flow",
"(",
"hass",
")",
"result",
"=",
"await",
"flow",
".",
"async_step_user",
"(",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\"",
"result",
"=",
"await",
"flow",
".",
"async_step_user",
"(",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"\"OwnTracks\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_WEBHOOK_ID",
"]",
"==",
"WEBHOOK_ID",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_SECRET",
"]",
"==",
"SECRET",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_CLOUDHOOK",
"]",
"==",
"CLOUDHOOK",
"assert",
"result",
"[",
"\"description_placeholders\"",
"]",
"[",
"CONF_WEBHOOK_URL",
"]",
"==",
"WEBHOOK_URL"
] | [
60,
0
] | [
74,
78
] | python | be | ['da', 'be', 'en'] | False |
test_import | (hass, webhook_id, secret) | Test import step. | Test import step. | async def test_import(hass, webhook_id, secret):
"""Test import step."""
flow = await init_config_flow(hass)
result = await flow.async_step_import({})
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "OwnTracks"
assert result["data"][CONF_WEBHOOK_ID] == WEBHOOK_ID
assert result["data"][CONF_SECRET] == SECRET
assert result["data"][CONF_CLOUDHOOK] == CLOUDHOOK
assert result["description_placeholders"] is None | [
"async",
"def",
"test_import",
"(",
"hass",
",",
"webhook_id",
",",
"secret",
")",
":",
"flow",
"=",
"await",
"init_config_flow",
"(",
"hass",
")",
"result",
"=",
"await",
"flow",
".",
"async_step_import",
"(",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"\"OwnTracks\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_WEBHOOK_ID",
"]",
"==",
"WEBHOOK_ID",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_SECRET",
"]",
"==",
"SECRET",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_CLOUDHOOK",
"]",
"==",
"CLOUDHOOK",
"assert",
"result",
"[",
"\"description_placeholders\"",
"]",
"is",
"None"
] | [
77,
0
] | [
87,
53
] | python | de | ['de', 'sd', 'en'] | False |
test_import_setup | (hass) | Test that we automatically create a config flow. | Test that we automatically create a config flow. | async def test_import_setup(hass):
"""Test that we automatically create a config flow."""
await async_process_ha_core_config(
hass,
{"external_url": "http://example.com"},
)
assert not hass.config_entries.async_entries(DOMAIN)
assert await async_setup_component(hass, DOMAIN, {"owntracks": {}})
await hass.async_block_till_done()
assert hass.config_entries.async_entries(DOMAIN) | [
"async",
"def",
"test_import_setup",
"(",
"hass",
")",
":",
"await",
"async_process_ha_core_config",
"(",
"hass",
",",
"{",
"\"external_url\"",
":",
"\"http://example.com\"",
"}",
",",
")",
"assert",
"not",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
"DOMAIN",
")",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"{",
"\"owntracks\"",
":",
"{",
"}",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
"DOMAIN",
")"
] | [
90,
0
] | [
100,
52
] | python | en | ['en', 'en', 'en'] | True |
test_abort_if_already_setup | (hass) | Test that we can't add more than one instance. | Test that we can't add more than one instance. | async def test_abort_if_already_setup(hass):
"""Test that we can't add more than one instance."""
flow = await init_config_flow(hass)
MockConfigEntry(domain=DOMAIN, data={}).add_to_hass(hass)
assert hass.config_entries.async_entries(DOMAIN)
# Should fail, already setup (import)
result = await flow.async_step_import({})
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "single_instance_allowed"
# Should fail, already setup (flow)
result = await flow.async_step_user({})
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "single_instance_allowed" | [
"async",
"def",
"test_abort_if_already_setup",
"(",
"hass",
")",
":",
"flow",
"=",
"await",
"init_config_flow",
"(",
"hass",
")",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"data",
"=",
"{",
"}",
")",
".",
"add_to_hass",
"(",
"hass",
")",
"assert",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
"DOMAIN",
")",
"# Should fail, already setup (import)",
"result",
"=",
"await",
"flow",
".",
"async_step_import",
"(",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"single_instance_allowed\"",
"# Should fail, already setup (flow)",
"result",
"=",
"await",
"flow",
".",
"async_step_user",
"(",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"single_instance_allowed\""
] | [
103,
0
] | [
118,
56
] | python | en | ['en', 'en', 'en'] | True |
test_user_not_supports_encryption | (hass, not_supports_encryption) | Test user step. | Test user step. | async def test_user_not_supports_encryption(hass, not_supports_encryption):
"""Test user step."""
flow = await init_config_flow(hass)
result = await flow.async_step_user({})
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert (
result["description_placeholders"]["secret"]
== "Encryption is not supported because nacl is not installed."
) | [
"async",
"def",
"test_user_not_supports_encryption",
"(",
"hass",
",",
"not_supports_encryption",
")",
":",
"flow",
"=",
"await",
"init_config_flow",
"(",
"hass",
")",
"result",
"=",
"await",
"flow",
".",
"async_step_user",
"(",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"(",
"result",
"[",
"\"description_placeholders\"",
"]",
"[",
"\"secret\"",
"]",
"==",
"\"Encryption is not supported because nacl is not installed.\"",
")"
] | [
121,
0
] | [
130,
5
] | python | be | ['da', 'be', 'en'] | False |
test_unload | (hass) | Test unloading a config flow. | Test unloading a config flow. | async def test_unload(hass):
"""Test unloading a config flow."""
await async_process_ha_core_config(
hass,
{"external_url": "http://example.com"},
)
with patch(
"homeassistant.config_entries.ConfigEntries.async_forward_entry_setup"
) as mock_forward:
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "import"}, data={}
)
assert len(mock_forward.mock_calls) == 1
entry = result["result"]
assert mock_forward.mock_calls[0][1][0] is entry
assert mock_forward.mock_calls[0][1][1] == "device_tracker"
assert entry.data["webhook_id"] in hass.data["webhook"]
with patch(
"homeassistant.config_entries.ConfigEntries.async_forward_entry_unload",
return_value=None,
) as mock_unload:
assert await hass.config_entries.async_unload(entry.entry_id)
assert len(mock_unload.mock_calls) == 1
assert mock_forward.mock_calls[0][1][0] is entry
assert mock_forward.mock_calls[0][1][1] == "device_tracker"
assert entry.data["webhook_id"] not in hass.data["webhook"] | [
"async",
"def",
"test_unload",
"(",
"hass",
")",
":",
"await",
"async_process_ha_core_config",
"(",
"hass",
",",
"{",
"\"external_url\"",
":",
"\"http://example.com\"",
"}",
",",
")",
"with",
"patch",
"(",
"\"homeassistant.config_entries.ConfigEntries.async_forward_entry_setup\"",
")",
"as",
"mock_forward",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"import\"",
"}",
",",
"data",
"=",
"{",
"}",
")",
"assert",
"len",
"(",
"mock_forward",
".",
"mock_calls",
")",
"==",
"1",
"entry",
"=",
"result",
"[",
"\"result\"",
"]",
"assert",
"mock_forward",
".",
"mock_calls",
"[",
"0",
"]",
"[",
"1",
"]",
"[",
"0",
"]",
"is",
"entry",
"assert",
"mock_forward",
".",
"mock_calls",
"[",
"0",
"]",
"[",
"1",
"]",
"[",
"1",
"]",
"==",
"\"device_tracker\"",
"assert",
"entry",
".",
"data",
"[",
"\"webhook_id\"",
"]",
"in",
"hass",
".",
"data",
"[",
"\"webhook\"",
"]",
"with",
"patch",
"(",
"\"homeassistant.config_entries.ConfigEntries.async_forward_entry_unload\"",
",",
"return_value",
"=",
"None",
",",
")",
"as",
"mock_unload",
":",
"assert",
"await",
"hass",
".",
"config_entries",
".",
"async_unload",
"(",
"entry",
".",
"entry_id",
")",
"assert",
"len",
"(",
"mock_unload",
".",
"mock_calls",
")",
"==",
"1",
"assert",
"mock_forward",
".",
"mock_calls",
"[",
"0",
"]",
"[",
"1",
"]",
"[",
"0",
"]",
"is",
"entry",
"assert",
"mock_forward",
".",
"mock_calls",
"[",
"0",
"]",
"[",
"1",
"]",
"[",
"1",
"]",
"==",
"\"device_tracker\"",
"assert",
"entry",
".",
"data",
"[",
"\"webhook_id\"",
"]",
"not",
"in",
"hass",
".",
"data",
"[",
"\"webhook\"",
"]"
] | [
133,
0
] | [
163,
63
] | python | en | ['en', 'fr', 'en'] | True |
test_with_cloud_sub | (hass) | Test creating a config flow while subscribed. | Test creating a config flow while subscribed. | async def test_with_cloud_sub(hass):
"""Test creating a config flow while subscribed."""
hass.config.components.add("cloud")
with patch(
"homeassistant.components.cloud.async_active_subscription", return_value=True
), patch(
"homeassistant.components.cloud.async_create_cloudhook",
return_value="https://hooks.nabu.casa/ABCD",
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}, data={}
)
entry = result["result"]
assert entry.data["cloudhook"]
assert (
result["description_placeholders"]["webhook_url"]
== "https://hooks.nabu.casa/ABCD"
) | [
"async",
"def",
"test_with_cloud_sub",
"(",
"hass",
")",
":",
"hass",
".",
"config",
".",
"components",
".",
"add",
"(",
"\"cloud\"",
")",
"with",
"patch",
"(",
"\"homeassistant.components.cloud.async_active_subscription\"",
",",
"return_value",
"=",
"True",
")",
",",
"patch",
"(",
"\"homeassistant.components.cloud.async_create_cloudhook\"",
",",
"return_value",
"=",
"\"https://hooks.nabu.casa/ABCD\"",
",",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
",",
"data",
"=",
"{",
"}",
")",
"entry",
"=",
"result",
"[",
"\"result\"",
"]",
"assert",
"entry",
".",
"data",
"[",
"\"cloudhook\"",
"]",
"assert",
"(",
"result",
"[",
"\"description_placeholders\"",
"]",
"[",
"\"webhook_url\"",
"]",
"==",
"\"https://hooks.nabu.casa/ABCD\"",
")"
] | [
166,
0
] | [
184,
5
] | python | en | ['en', 'en', 'en'] | True |
setup | (hass, config) | Set up the smarty environment. | Set up the smarty environment. | def setup(hass, config):
"""Set up the smarty environment."""
conf = config[DOMAIN]
host = conf[CONF_HOST]
name = conf[CONF_NAME]
_LOGGER.debug("Name: %s, host: %s", name, host)
smarty = Smarty(host=host)
hass.data[DOMAIN] = {"api": smarty, "name": name}
# Initial update
smarty.update()
# Load platforms
discovery.load_platform(hass, "fan", DOMAIN, {}, config)
discovery.load_platform(hass, "sensor", DOMAIN, {}, config)
discovery.load_platform(hass, "binary_sensor", DOMAIN, {}, config)
def poll_device_update(event_time):
"""Update Smarty device."""
_LOGGER.debug("Updating Smarty device...")
if smarty.update():
_LOGGER.debug("Update success...")
dispatcher_send(hass, SIGNAL_UPDATE_SMARTY)
else:
_LOGGER.debug("Update failed...")
track_time_interval(hass, poll_device_update, timedelta(seconds=30))
return True | [
"def",
"setup",
"(",
"hass",
",",
"config",
")",
":",
"conf",
"=",
"config",
"[",
"DOMAIN",
"]",
"host",
"=",
"conf",
"[",
"CONF_HOST",
"]",
"name",
"=",
"conf",
"[",
"CONF_NAME",
"]",
"_LOGGER",
".",
"debug",
"(",
"\"Name: %s, host: %s\"",
",",
"name",
",",
"host",
")",
"smarty",
"=",
"Smarty",
"(",
"host",
"=",
"host",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"{",
"\"api\"",
":",
"smarty",
",",
"\"name\"",
":",
"name",
"}",
"# Initial update",
"smarty",
".",
"update",
"(",
")",
"# Load platforms",
"discovery",
".",
"load_platform",
"(",
"hass",
",",
"\"fan\"",
",",
"DOMAIN",
",",
"{",
"}",
",",
"config",
")",
"discovery",
".",
"load_platform",
"(",
"hass",
",",
"\"sensor\"",
",",
"DOMAIN",
",",
"{",
"}",
",",
"config",
")",
"discovery",
".",
"load_platform",
"(",
"hass",
",",
"\"binary_sensor\"",
",",
"DOMAIN",
",",
"{",
"}",
",",
"config",
")",
"def",
"poll_device_update",
"(",
"event_time",
")",
":",
"\"\"\"Update Smarty device.\"\"\"",
"_LOGGER",
".",
"debug",
"(",
"\"Updating Smarty device...\"",
")",
"if",
"smarty",
".",
"update",
"(",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Update success...\"",
")",
"dispatcher_send",
"(",
"hass",
",",
"SIGNAL_UPDATE_SMARTY",
")",
"else",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Update failed...\"",
")",
"track_time_interval",
"(",
"hass",
",",
"poll_device_update",
",",
"timedelta",
"(",
"seconds",
"=",
"30",
")",
")",
"return",
"True"
] | [
37,
0
] | [
70,
15
] | python | en | ['en', 'en', 'en'] | True |
convert_tf_weight_name_to_pt_weight_name | (tf_name, start_prefix_to_remove="") |
Convert a TF 2.0 model variable name in a pytorch model weight name.
Conventions for TF2.0 scopes -> PyTorch attribute names conversions:
- '$1___$2' is replaced by $2 (can be used to duplicate or remove layers in TF2.0 vs PyTorch)
- '_._' is replaced by a new level separation (can be used to convert TF2.0 lists in PyTorch nn.ModulesList)
return tuple with:
- pytorch model weight name
- transpose: boolean indicating whether TF2.0 and PyTorch weights matrices are transposed with regards to each
other
|
Convert a TF 2.0 model variable name in a pytorch model weight name. | def convert_tf_weight_name_to_pt_weight_name(tf_name, start_prefix_to_remove=""):
"""
Convert a TF 2.0 model variable name in a pytorch model weight name.
Conventions for TF2.0 scopes -> PyTorch attribute names conversions:
- '$1___$2' is replaced by $2 (can be used to duplicate or remove layers in TF2.0 vs PyTorch)
- '_._' is replaced by a new level separation (can be used to convert TF2.0 lists in PyTorch nn.ModulesList)
return tuple with:
- pytorch model weight name
- transpose: boolean indicating whether TF2.0 and PyTorch weights matrices are transposed with regards to each
other
"""
tf_name = tf_name.replace(":0", "") # device ids
tf_name = re.sub(
r"/[^/]*___([^/]*)/", r"/\1/", tf_name
) # '$1___$2' is replaced by $2 (can be used to duplicate or remove layers in TF2.0 vs PyTorch)
tf_name = tf_name.replace(
"_._", "/"
) # '_._' is replaced by a level separation (can be used to convert TF2.0 lists in PyTorch nn.ModulesList)
tf_name = re.sub(r"//+", "/", tf_name) # Remove empty levels at the end
tf_name = tf_name.split("/") # Convert from TF2.0 '/' separators to PyTorch '.' separators
# Some weights have a single name withtout "/" such as final_logits_bias in BART
if len(tf_name) > 1:
tf_name = tf_name[1:] # Remove level zero
# When should we transpose the weights
transpose = bool(
tf_name[-1] in ["kernel", "pointwise_kernel", "depthwise_kernel"]
or "emb_projs" in tf_name
or "out_projs" in tf_name
)
# Convert standard TF2.0 names in PyTorch names
if tf_name[-1] == "kernel" or tf_name[-1] == "embeddings" or tf_name[-1] == "gamma":
tf_name[-1] = "weight"
if tf_name[-1] == "beta":
tf_name[-1] = "bias"
# The SeparableConv1D TF layer contains two weights that are translated to PyTorch Conv1D here
if tf_name[-1] == "pointwise_kernel" or tf_name[-1] == "depthwise_kernel":
tf_name[-1] = tf_name[-1].replace("_kernel", ".weight")
# Remove prefix if needed
tf_name = ".".join(tf_name)
if start_prefix_to_remove:
tf_name = tf_name.replace(start_prefix_to_remove, "", 1)
return tf_name, transpose | [
"def",
"convert_tf_weight_name_to_pt_weight_name",
"(",
"tf_name",
",",
"start_prefix_to_remove",
"=",
"\"\"",
")",
":",
"tf_name",
"=",
"tf_name",
".",
"replace",
"(",
"\":0\"",
",",
"\"\"",
")",
"# device ids",
"tf_name",
"=",
"re",
".",
"sub",
"(",
"r\"/[^/]*___([^/]*)/\"",
",",
"r\"/\\1/\"",
",",
"tf_name",
")",
"# '$1___$2' is replaced by $2 (can be used to duplicate or remove layers in TF2.0 vs PyTorch)",
"tf_name",
"=",
"tf_name",
".",
"replace",
"(",
"\"_._\"",
",",
"\"/\"",
")",
"# '_._' is replaced by a level separation (can be used to convert TF2.0 lists in PyTorch nn.ModulesList)",
"tf_name",
"=",
"re",
".",
"sub",
"(",
"r\"//+\"",
",",
"\"/\"",
",",
"tf_name",
")",
"# Remove empty levels at the end",
"tf_name",
"=",
"tf_name",
".",
"split",
"(",
"\"/\"",
")",
"# Convert from TF2.0 '/' separators to PyTorch '.' separators",
"# Some weights have a single name withtout \"/\" such as final_logits_bias in BART",
"if",
"len",
"(",
"tf_name",
")",
">",
"1",
":",
"tf_name",
"=",
"tf_name",
"[",
"1",
":",
"]",
"# Remove level zero",
"# When should we transpose the weights",
"transpose",
"=",
"bool",
"(",
"tf_name",
"[",
"-",
"1",
"]",
"in",
"[",
"\"kernel\"",
",",
"\"pointwise_kernel\"",
",",
"\"depthwise_kernel\"",
"]",
"or",
"\"emb_projs\"",
"in",
"tf_name",
"or",
"\"out_projs\"",
"in",
"tf_name",
")",
"# Convert standard TF2.0 names in PyTorch names",
"if",
"tf_name",
"[",
"-",
"1",
"]",
"==",
"\"kernel\"",
"or",
"tf_name",
"[",
"-",
"1",
"]",
"==",
"\"embeddings\"",
"or",
"tf_name",
"[",
"-",
"1",
"]",
"==",
"\"gamma\"",
":",
"tf_name",
"[",
"-",
"1",
"]",
"=",
"\"weight\"",
"if",
"tf_name",
"[",
"-",
"1",
"]",
"==",
"\"beta\"",
":",
"tf_name",
"[",
"-",
"1",
"]",
"=",
"\"bias\"",
"# The SeparableConv1D TF layer contains two weights that are translated to PyTorch Conv1D here",
"if",
"tf_name",
"[",
"-",
"1",
"]",
"==",
"\"pointwise_kernel\"",
"or",
"tf_name",
"[",
"-",
"1",
"]",
"==",
"\"depthwise_kernel\"",
":",
"tf_name",
"[",
"-",
"1",
"]",
"=",
"tf_name",
"[",
"-",
"1",
"]",
".",
"replace",
"(",
"\"_kernel\"",
",",
"\".weight\"",
")",
"# Remove prefix if needed",
"tf_name",
"=",
"\".\"",
".",
"join",
"(",
"tf_name",
")",
"if",
"start_prefix_to_remove",
":",
"tf_name",
"=",
"tf_name",
".",
"replace",
"(",
"start_prefix_to_remove",
",",
"\"\"",
",",
"1",
")",
"return",
"tf_name",
",",
"transpose"
] | [
29,
0
] | [
79,
29
] | python | en | ['en', 'error', 'th'] | False |
load_pytorch_checkpoint_in_tf2_model | (tf_model, pytorch_checkpoint_path, tf_inputs=None, allow_missing_keys=False) | Load pytorch checkpoints in a TF 2.0 model | Load pytorch checkpoints in a TF 2.0 model | def load_pytorch_checkpoint_in_tf2_model(tf_model, pytorch_checkpoint_path, tf_inputs=None, allow_missing_keys=False):
"""Load pytorch checkpoints in a TF 2.0 model"""
try:
import tensorflow as tf # noqa: F401
import torch # noqa: F401
except ImportError:
logger.error(
"Loading a PyTorch model in TensorFlow, requires both PyTorch and TensorFlow to be installed. Please see "
"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions."
)
raise
pt_path = os.path.abspath(pytorch_checkpoint_path)
logger.info("Loading PyTorch weights from {}".format(pt_path))
pt_state_dict = torch.load(pt_path, map_location="cpu")
logger.info("PyTorch checkpoint contains {:,} parameters".format(sum(t.numel() for t in pt_state_dict.values())))
return load_pytorch_weights_in_tf2_model(
tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys
) | [
"def",
"load_pytorch_checkpoint_in_tf2_model",
"(",
"tf_model",
",",
"pytorch_checkpoint_path",
",",
"tf_inputs",
"=",
"None",
",",
"allow_missing_keys",
"=",
"False",
")",
":",
"try",
":",
"import",
"tensorflow",
"as",
"tf",
"# noqa: F401",
"import",
"torch",
"# noqa: F401",
"except",
"ImportError",
":",
"logger",
".",
"error",
"(",
"\"Loading a PyTorch model in TensorFlow, requires both PyTorch and TensorFlow to be installed. Please see \"",
"\"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions.\"",
")",
"raise",
"pt_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"pytorch_checkpoint_path",
")",
"logger",
".",
"info",
"(",
"\"Loading PyTorch weights from {}\"",
".",
"format",
"(",
"pt_path",
")",
")",
"pt_state_dict",
"=",
"torch",
".",
"load",
"(",
"pt_path",
",",
"map_location",
"=",
"\"cpu\"",
")",
"logger",
".",
"info",
"(",
"\"PyTorch checkpoint contains {:,} parameters\"",
".",
"format",
"(",
"sum",
"(",
"t",
".",
"numel",
"(",
")",
"for",
"t",
"in",
"pt_state_dict",
".",
"values",
"(",
")",
")",
")",
")",
"return",
"load_pytorch_weights_in_tf2_model",
"(",
"tf_model",
",",
"pt_state_dict",
",",
"tf_inputs",
"=",
"tf_inputs",
",",
"allow_missing_keys",
"=",
"allow_missing_keys",
")"
] | [
87,
0
] | [
107,
5
] | python | en | ['en', 'en', 'en'] | True |
load_pytorch_model_in_tf2_model | (tf_model, pt_model, tf_inputs=None, allow_missing_keys=False) | Load pytorch checkpoints in a TF 2.0 model | Load pytorch checkpoints in a TF 2.0 model | def load_pytorch_model_in_tf2_model(tf_model, pt_model, tf_inputs=None, allow_missing_keys=False):
"""Load pytorch checkpoints in a TF 2.0 model"""
pt_state_dict = pt_model.state_dict()
return load_pytorch_weights_in_tf2_model(
tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys
) | [
"def",
"load_pytorch_model_in_tf2_model",
"(",
"tf_model",
",",
"pt_model",
",",
"tf_inputs",
"=",
"None",
",",
"allow_missing_keys",
"=",
"False",
")",
":",
"pt_state_dict",
"=",
"pt_model",
".",
"state_dict",
"(",
")",
"return",
"load_pytorch_weights_in_tf2_model",
"(",
"tf_model",
",",
"pt_state_dict",
",",
"tf_inputs",
"=",
"tf_inputs",
",",
"allow_missing_keys",
"=",
"allow_missing_keys",
")"
] | [
110,
0
] | [
116,
5
] | python | en | ['en', 'en', 'en'] | True |
load_pytorch_weights_in_tf2_model | (tf_model, pt_state_dict, tf_inputs=None, allow_missing_keys=False) | Load pytorch state_dict in a TF 2.0 model. | Load pytorch state_dict in a TF 2.0 model. | def load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None, allow_missing_keys=False):
"""Load pytorch state_dict in a TF 2.0 model."""
try:
import tensorflow as tf # noqa: F401
import torch # noqa: F401
from tensorflow.python.keras import backend as K
except ImportError:
logger.error(
"Loading a PyTorch model in TensorFlow, requires both PyTorch and TensorFlow to be installed. Please see "
"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions."
)
raise
if tf_inputs is None:
tf_inputs = tf_model.dummy_inputs
if tf_inputs is not None:
tf_model(tf_inputs, training=False) # Make sure model is built
# Adapt state dict - TODO remove this and update the AWS weights files instead
# Convert old format to new format if needed from a PyTorch state_dict
old_keys = []
new_keys = []
for key in pt_state_dict.keys():
new_key = None
if "gamma" in key:
new_key = key.replace("gamma", "weight")
if "beta" in key:
new_key = key.replace("beta", "bias")
if new_key:
old_keys.append(key)
new_keys.append(new_key)
for old_key, new_key in zip(old_keys, new_keys):
pt_state_dict[new_key] = pt_state_dict.pop(old_key)
# Make sure we are able to load PyTorch base models as well as derived models (with heads)
# TF models always have a prefix, some of PyTorch models (base ones) don't
start_prefix_to_remove = ""
if not any(s.startswith(tf_model.base_model_prefix) for s in pt_state_dict.keys()):
start_prefix_to_remove = tf_model.base_model_prefix + "."
symbolic_weights = tf_model.trainable_weights + tf_model.non_trainable_weights
tf_loaded_numel = 0
weight_value_tuples = []
all_pytorch_weights = set(list(pt_state_dict.keys()))
missing_keys = []
for symbolic_weight in symbolic_weights:
sw_name = symbolic_weight.name
name, transpose = convert_tf_weight_name_to_pt_weight_name(
sw_name, start_prefix_to_remove=start_prefix_to_remove
)
# Find associated numpy array in pytorch model state dict
if name not in pt_state_dict:
if allow_missing_keys:
missing_keys.append(name)
continue
elif tf_model._keys_to_ignore_on_load_missing is not None:
# authorized missing keys don't have to be loaded
if any(re.search(pat, name) is not None for pat in tf_model._keys_to_ignore_on_load_missing):
continue
raise AttributeError("{} not found in PyTorch model".format(name))
array = pt_state_dict[name].numpy()
if transpose:
array = numpy.transpose(array)
if len(symbolic_weight.shape) < len(array.shape):
array = numpy.squeeze(array)
elif len(symbolic_weight.shape) > len(array.shape):
array = numpy.expand_dims(array, axis=0)
if list(symbolic_weight.shape) != list(array.shape):
try:
array = numpy.reshape(array, symbolic_weight.shape)
except AssertionError as e:
e.args += (symbolic_weight.shape, array.shape)
raise e
try:
assert list(symbolic_weight.shape) == list(array.shape)
except AssertionError as e:
e.args += (symbolic_weight.shape, array.shape)
raise e
tf_loaded_numel += array.size
# logger.warning("Initialize TF weight {}".format(symbolic_weight.name))
weight_value_tuples.append((symbolic_weight, array))
all_pytorch_weights.discard(name)
K.batch_set_value(weight_value_tuples)
if tf_inputs is not None:
tf_model(tf_inputs, training=False) # Make sure restore ops are run
logger.info("Loaded {:,} parameters in the TF 2.0 model.".format(tf_loaded_numel))
unexpected_keys = list(all_pytorch_weights)
if tf_model._keys_to_ignore_on_load_missing is not None:
for pat in tf_model._keys_to_ignore_on_load_missing:
missing_keys = [k for k in missing_keys if re.search(pat, k) is None]
if tf_model._keys_to_ignore_on_load_unexpected is not None:
for pat in tf_model._keys_to_ignore_on_load_unexpected:
unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
if len(unexpected_keys) > 0:
logger.warning(
f"Some weights of the PyTorch model were not used when "
f"initializing the TF 2.0 model {tf_model.__class__.__name__}: {unexpected_keys}\n"
f"- This IS expected if you are initializing {tf_model.__class__.__name__} from a PyTorch model trained on another task "
f"or with another architecture (e.g. initializing a TFBertForSequenceClassification model from a BertForPreTraining model).\n"
f"- This IS NOT expected if you are initializing {tf_model.__class__.__name__} from a PyTorch model that you expect "
f"to be exactly identical (e.g. initializing a TFBertForSequenceClassification model from a BertForSequenceClassification model)."
)
else:
logger.warning(f"All PyTorch model weights were used when initializing {tf_model.__class__.__name__}.\n")
if len(missing_keys) > 0:
logger.warning(
f"Some weights or buffers of the TF 2.0 model {tf_model.__class__.__name__} were not initialized from the PyTorch model "
f"and are newly initialized: {missing_keys}\n"
f"You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference."
)
else:
logger.warning(
f"All the weights of {tf_model.__class__.__name__} were initialized from the PyTorch model.\n"
f"If your task is similar to the task the model of the checkpoint was trained on, "
f"you can already use {tf_model.__class__.__name__} for predictions without further training."
)
return tf_model | [
"def",
"load_pytorch_weights_in_tf2_model",
"(",
"tf_model",
",",
"pt_state_dict",
",",
"tf_inputs",
"=",
"None",
",",
"allow_missing_keys",
"=",
"False",
")",
":",
"try",
":",
"import",
"tensorflow",
"as",
"tf",
"# noqa: F401",
"import",
"torch",
"# noqa: F401",
"from",
"tensorflow",
".",
"python",
".",
"keras",
"import",
"backend",
"as",
"K",
"except",
"ImportError",
":",
"logger",
".",
"error",
"(",
"\"Loading a PyTorch model in TensorFlow, requires both PyTorch and TensorFlow to be installed. Please see \"",
"\"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions.\"",
")",
"raise",
"if",
"tf_inputs",
"is",
"None",
":",
"tf_inputs",
"=",
"tf_model",
".",
"dummy_inputs",
"if",
"tf_inputs",
"is",
"not",
"None",
":",
"tf_model",
"(",
"tf_inputs",
",",
"training",
"=",
"False",
")",
"# Make sure model is built",
"# Adapt state dict - TODO remove this and update the AWS weights files instead",
"# Convert old format to new format if needed from a PyTorch state_dict",
"old_keys",
"=",
"[",
"]",
"new_keys",
"=",
"[",
"]",
"for",
"key",
"in",
"pt_state_dict",
".",
"keys",
"(",
")",
":",
"new_key",
"=",
"None",
"if",
"\"gamma\"",
"in",
"key",
":",
"new_key",
"=",
"key",
".",
"replace",
"(",
"\"gamma\"",
",",
"\"weight\"",
")",
"if",
"\"beta\"",
"in",
"key",
":",
"new_key",
"=",
"key",
".",
"replace",
"(",
"\"beta\"",
",",
"\"bias\"",
")",
"if",
"new_key",
":",
"old_keys",
".",
"append",
"(",
"key",
")",
"new_keys",
".",
"append",
"(",
"new_key",
")",
"for",
"old_key",
",",
"new_key",
"in",
"zip",
"(",
"old_keys",
",",
"new_keys",
")",
":",
"pt_state_dict",
"[",
"new_key",
"]",
"=",
"pt_state_dict",
".",
"pop",
"(",
"old_key",
")",
"# Make sure we are able to load PyTorch base models as well as derived models (with heads)",
"# TF models always have a prefix, some of PyTorch models (base ones) don't",
"start_prefix_to_remove",
"=",
"\"\"",
"if",
"not",
"any",
"(",
"s",
".",
"startswith",
"(",
"tf_model",
".",
"base_model_prefix",
")",
"for",
"s",
"in",
"pt_state_dict",
".",
"keys",
"(",
")",
")",
":",
"start_prefix_to_remove",
"=",
"tf_model",
".",
"base_model_prefix",
"+",
"\".\"",
"symbolic_weights",
"=",
"tf_model",
".",
"trainable_weights",
"+",
"tf_model",
".",
"non_trainable_weights",
"tf_loaded_numel",
"=",
"0",
"weight_value_tuples",
"=",
"[",
"]",
"all_pytorch_weights",
"=",
"set",
"(",
"list",
"(",
"pt_state_dict",
".",
"keys",
"(",
")",
")",
")",
"missing_keys",
"=",
"[",
"]",
"for",
"symbolic_weight",
"in",
"symbolic_weights",
":",
"sw_name",
"=",
"symbolic_weight",
".",
"name",
"name",
",",
"transpose",
"=",
"convert_tf_weight_name_to_pt_weight_name",
"(",
"sw_name",
",",
"start_prefix_to_remove",
"=",
"start_prefix_to_remove",
")",
"# Find associated numpy array in pytorch model state dict",
"if",
"name",
"not",
"in",
"pt_state_dict",
":",
"if",
"allow_missing_keys",
":",
"missing_keys",
".",
"append",
"(",
"name",
")",
"continue",
"elif",
"tf_model",
".",
"_keys_to_ignore_on_load_missing",
"is",
"not",
"None",
":",
"# authorized missing keys don't have to be loaded",
"if",
"any",
"(",
"re",
".",
"search",
"(",
"pat",
",",
"name",
")",
"is",
"not",
"None",
"for",
"pat",
"in",
"tf_model",
".",
"_keys_to_ignore_on_load_missing",
")",
":",
"continue",
"raise",
"AttributeError",
"(",
"\"{} not found in PyTorch model\"",
".",
"format",
"(",
"name",
")",
")",
"array",
"=",
"pt_state_dict",
"[",
"name",
"]",
".",
"numpy",
"(",
")",
"if",
"transpose",
":",
"array",
"=",
"numpy",
".",
"transpose",
"(",
"array",
")",
"if",
"len",
"(",
"symbolic_weight",
".",
"shape",
")",
"<",
"len",
"(",
"array",
".",
"shape",
")",
":",
"array",
"=",
"numpy",
".",
"squeeze",
"(",
"array",
")",
"elif",
"len",
"(",
"symbolic_weight",
".",
"shape",
")",
">",
"len",
"(",
"array",
".",
"shape",
")",
":",
"array",
"=",
"numpy",
".",
"expand_dims",
"(",
"array",
",",
"axis",
"=",
"0",
")",
"if",
"list",
"(",
"symbolic_weight",
".",
"shape",
")",
"!=",
"list",
"(",
"array",
".",
"shape",
")",
":",
"try",
":",
"array",
"=",
"numpy",
".",
"reshape",
"(",
"array",
",",
"symbolic_weight",
".",
"shape",
")",
"except",
"AssertionError",
"as",
"e",
":",
"e",
".",
"args",
"+=",
"(",
"symbolic_weight",
".",
"shape",
",",
"array",
".",
"shape",
")",
"raise",
"e",
"try",
":",
"assert",
"list",
"(",
"symbolic_weight",
".",
"shape",
")",
"==",
"list",
"(",
"array",
".",
"shape",
")",
"except",
"AssertionError",
"as",
"e",
":",
"e",
".",
"args",
"+=",
"(",
"symbolic_weight",
".",
"shape",
",",
"array",
".",
"shape",
")",
"raise",
"e",
"tf_loaded_numel",
"+=",
"array",
".",
"size",
"# logger.warning(\"Initialize TF weight {}\".format(symbolic_weight.name))",
"weight_value_tuples",
".",
"append",
"(",
"(",
"symbolic_weight",
",",
"array",
")",
")",
"all_pytorch_weights",
".",
"discard",
"(",
"name",
")",
"K",
".",
"batch_set_value",
"(",
"weight_value_tuples",
")",
"if",
"tf_inputs",
"is",
"not",
"None",
":",
"tf_model",
"(",
"tf_inputs",
",",
"training",
"=",
"False",
")",
"# Make sure restore ops are run",
"logger",
".",
"info",
"(",
"\"Loaded {:,} parameters in the TF 2.0 model.\"",
".",
"format",
"(",
"tf_loaded_numel",
")",
")",
"unexpected_keys",
"=",
"list",
"(",
"all_pytorch_weights",
")",
"if",
"tf_model",
".",
"_keys_to_ignore_on_load_missing",
"is",
"not",
"None",
":",
"for",
"pat",
"in",
"tf_model",
".",
"_keys_to_ignore_on_load_missing",
":",
"missing_keys",
"=",
"[",
"k",
"for",
"k",
"in",
"missing_keys",
"if",
"re",
".",
"search",
"(",
"pat",
",",
"k",
")",
"is",
"None",
"]",
"if",
"tf_model",
".",
"_keys_to_ignore_on_load_unexpected",
"is",
"not",
"None",
":",
"for",
"pat",
"in",
"tf_model",
".",
"_keys_to_ignore_on_load_unexpected",
":",
"unexpected_keys",
"=",
"[",
"k",
"for",
"k",
"in",
"unexpected_keys",
"if",
"re",
".",
"search",
"(",
"pat",
",",
"k",
")",
"is",
"None",
"]",
"if",
"len",
"(",
"unexpected_keys",
")",
">",
"0",
":",
"logger",
".",
"warning",
"(",
"f\"Some weights of the PyTorch model were not used when \"",
"f\"initializing the TF 2.0 model {tf_model.__class__.__name__}: {unexpected_keys}\\n\"",
"f\"- This IS expected if you are initializing {tf_model.__class__.__name__} from a PyTorch model trained on another task \"",
"f\"or with another architecture (e.g. initializing a TFBertForSequenceClassification model from a BertForPreTraining model).\\n\"",
"f\"- This IS NOT expected if you are initializing {tf_model.__class__.__name__} from a PyTorch model that you expect \"",
"f\"to be exactly identical (e.g. initializing a TFBertForSequenceClassification model from a BertForSequenceClassification model).\"",
")",
"else",
":",
"logger",
".",
"warning",
"(",
"f\"All PyTorch model weights were used when initializing {tf_model.__class__.__name__}.\\n\"",
")",
"if",
"len",
"(",
"missing_keys",
")",
">",
"0",
":",
"logger",
".",
"warning",
"(",
"f\"Some weights or buffers of the TF 2.0 model {tf_model.__class__.__name__} were not initialized from the PyTorch model \"",
"f\"and are newly initialized: {missing_keys}\\n\"",
"f\"You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\"",
")",
"else",
":",
"logger",
".",
"warning",
"(",
"f\"All the weights of {tf_model.__class__.__name__} were initialized from the PyTorch model.\\n\"",
"f\"If your task is similar to the task the model of the checkpoint was trained on, \"",
"f\"you can already use {tf_model.__class__.__name__} for predictions without further training.\"",
")",
"return",
"tf_model"
] | [
119,
0
] | [
251,
19
] | python | en | ['en', 'en', 'en'] | True |
load_tf2_checkpoint_in_pytorch_model | (pt_model, tf_checkpoint_path, tf_inputs=None, allow_missing_keys=False) |
Load TF 2.0 HDF5 checkpoint in a PyTorch model We use HDF5 to easily do transfer learning (see
https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357).
|
Load TF 2.0 HDF5 checkpoint in a PyTorch model We use HDF5 to easily do transfer learning (see
https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357).
| def load_tf2_checkpoint_in_pytorch_model(pt_model, tf_checkpoint_path, tf_inputs=None, allow_missing_keys=False):
"""
Load TF 2.0 HDF5 checkpoint in a PyTorch model We use HDF5 to easily do transfer learning (see
https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357).
"""
try:
import tensorflow as tf # noqa: F401
import torch # noqa: F401
except ImportError:
logger.error(
"Loading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed. Please see "
"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions."
)
raise
import transformers
from .modeling_tf_utils import load_tf_weights
logger.info("Loading TensorFlow weights from {}".format(tf_checkpoint_path))
# Instantiate and load the associated TF 2.0 model
tf_model_class_name = "TF" + pt_model.__class__.__name__ # Add "TF" at the beginning
tf_model_class = getattr(transformers, tf_model_class_name)
tf_model = tf_model_class(pt_model.config)
if tf_inputs is None:
tf_inputs = tf_model.dummy_inputs
if tf_inputs is not None:
tf_model(tf_inputs, training=False) # Make sure model is built
load_tf_weights(tf_model, tf_checkpoint_path)
return load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=allow_missing_keys) | [
"def",
"load_tf2_checkpoint_in_pytorch_model",
"(",
"pt_model",
",",
"tf_checkpoint_path",
",",
"tf_inputs",
"=",
"None",
",",
"allow_missing_keys",
"=",
"False",
")",
":",
"try",
":",
"import",
"tensorflow",
"as",
"tf",
"# noqa: F401",
"import",
"torch",
"# noqa: F401",
"except",
"ImportError",
":",
"logger",
".",
"error",
"(",
"\"Loading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed. Please see \"",
"\"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions.\"",
")",
"raise",
"import",
"transformers",
"from",
".",
"modeling_tf_utils",
"import",
"load_tf_weights",
"logger",
".",
"info",
"(",
"\"Loading TensorFlow weights from {}\"",
".",
"format",
"(",
"tf_checkpoint_path",
")",
")",
"# Instantiate and load the associated TF 2.0 model",
"tf_model_class_name",
"=",
"\"TF\"",
"+",
"pt_model",
".",
"__class__",
".",
"__name__",
"# Add \"TF\" at the beginning",
"tf_model_class",
"=",
"getattr",
"(",
"transformers",
",",
"tf_model_class_name",
")",
"tf_model",
"=",
"tf_model_class",
"(",
"pt_model",
".",
"config",
")",
"if",
"tf_inputs",
"is",
"None",
":",
"tf_inputs",
"=",
"tf_model",
".",
"dummy_inputs",
"if",
"tf_inputs",
"is",
"not",
"None",
":",
"tf_model",
"(",
"tf_inputs",
",",
"training",
"=",
"False",
")",
"# Make sure model is built",
"load_tf_weights",
"(",
"tf_model",
",",
"tf_checkpoint_path",
")",
"return",
"load_tf2_model_in_pytorch_model",
"(",
"pt_model",
",",
"tf_model",
",",
"allow_missing_keys",
"=",
"allow_missing_keys",
")"
] | [
259,
0
] | [
293,
101
] | python | en | ['en', 'error', 'th'] | False |
load_tf2_model_in_pytorch_model | (pt_model, tf_model, allow_missing_keys=False) | Load TF 2.0 model in a pytorch model | Load TF 2.0 model in a pytorch model | def load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=False):
"""Load TF 2.0 model in a pytorch model"""
weights = tf_model.weights
return load_tf2_weights_in_pytorch_model(pt_model, weights, allow_missing_keys=allow_missing_keys) | [
"def",
"load_tf2_model_in_pytorch_model",
"(",
"pt_model",
",",
"tf_model",
",",
"allow_missing_keys",
"=",
"False",
")",
":",
"weights",
"=",
"tf_model",
".",
"weights",
"return",
"load_tf2_weights_in_pytorch_model",
"(",
"pt_model",
",",
"weights",
",",
"allow_missing_keys",
"=",
"allow_missing_keys",
")"
] | [
296,
0
] | [
300,
102
] | python | en | ['en', 'fy', 'it'] | False |
load_tf2_weights_in_pytorch_model | (pt_model, tf_weights, allow_missing_keys=False) | Load TF2.0 symbolic weights in a PyTorch model | Load TF2.0 symbolic weights in a PyTorch model | def load_tf2_weights_in_pytorch_model(pt_model, tf_weights, allow_missing_keys=False):
"""Load TF2.0 symbolic weights in a PyTorch model"""
try:
import tensorflow as tf # noqa: F401
import torch # noqa: F401
except ImportError:
logger.error(
"Loading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed. Please see "
"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions."
)
raise
new_pt_params_dict = {}
current_pt_params_dict = dict(pt_model.named_parameters())
# Make sure we are able to load PyTorch base models as well as derived models (with heads)
# TF models always have a prefix, some of PyTorch models (base ones) don't
start_prefix_to_remove = ""
if not any(s.startswith(pt_model.base_model_prefix) for s in current_pt_params_dict.keys()):
start_prefix_to_remove = pt_model.base_model_prefix + "."
# Build a map from potential PyTorch weight names to TF 2.0 Variables
tf_weights_map = {}
for tf_weight in tf_weights:
pt_name, transpose = convert_tf_weight_name_to_pt_weight_name(
tf_weight.name, start_prefix_to_remove=start_prefix_to_remove
)
tf_weights_map[pt_name] = (tf_weight.numpy(), transpose)
all_tf_weights = set(list(tf_weights_map.keys()))
loaded_pt_weights_data_ptr = {}
missing_keys_pt = []
for pt_weight_name, pt_weight in current_pt_params_dict.items():
# Handle PyTorch shared weight ()not duplicated in TF 2.0
if pt_weight.data_ptr() in loaded_pt_weights_data_ptr:
new_pt_params_dict[pt_weight_name] = loaded_pt_weights_data_ptr[pt_weight.data_ptr()]
continue
# Find associated numpy array in pytorch model state dict
if pt_weight_name not in tf_weights_map:
if allow_missing_keys:
missing_keys_pt.append(pt_weight_name)
continue
raise AttributeError("{} not found in TF 2.0 model".format(pt_weight_name))
array, transpose = tf_weights_map[pt_weight_name]
if transpose:
array = numpy.transpose(array)
if len(pt_weight.shape) < len(array.shape):
array = numpy.squeeze(array)
elif len(pt_weight.shape) > len(array.shape):
array = numpy.expand_dims(array, axis=0)
if list(pt_weight.shape) != list(array.shape):
try:
array = numpy.reshape(array, pt_weight.shape)
except AssertionError as e:
e.args += (pt_weight.shape, array.shape)
raise e
try:
assert list(pt_weight.shape) == list(array.shape)
except AssertionError as e:
e.args += (pt_weight.shape, array.shape)
raise e
# logger.warning("Initialize PyTorch weight {}".format(pt_weight_name))
new_pt_params_dict[pt_weight_name] = torch.from_numpy(array)
loaded_pt_weights_data_ptr[pt_weight.data_ptr()] = torch.from_numpy(array)
all_tf_weights.discard(pt_weight_name)
missing_keys, unexpected_keys = pt_model.load_state_dict(new_pt_params_dict, strict=False)
missing_keys += missing_keys_pt
if len(unexpected_keys) > 0:
logger.warning(
f"Some weights of the TF 2.0 model were not used when "
f"initializing the PyTorch model {pt_model.__class__.__name__}: {unexpected_keys}\n"
f"- This IS expected if you are initializing {pt_model.__class__.__name__} from a TF 2.0 model trained on another task "
f"or with another architecture (e.g. initializing a BertForSequenceClassification model from a TFBertForPreTraining model).\n"
f"- This IS NOT expected if you are initializing {pt_model.__class__.__name__} from a TF 2.0 model that you expect "
f"to be exactly identical (e.g. initializing a BertForSequenceClassification model from a TFBertForSequenceClassification model)."
)
else:
logger.warning(f"All TF 2.0 model weights were used when initializing {pt_model.__class__.__name__}.\n")
if len(missing_keys) > 0:
logger.warning(
f"Some weights of {pt_model.__class__.__name__} were not initialized from the TF 2.0 model "
f"and are newly initialized: {missing_keys}\n"
f"You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference."
)
else:
logger.warning(
f"All the weights of {pt_model.__class__.__name__} were initialized from the TF 2.0 model.\n"
f"If your task is similar to the task the model of the checkpoint was trained on, "
f"you can already use {pt_model.__class__.__name__} for predictions without further training."
)
logger.info("Weights or buffers not loaded from TF 2.0 model: {}".format(all_tf_weights))
return pt_model | [
"def",
"load_tf2_weights_in_pytorch_model",
"(",
"pt_model",
",",
"tf_weights",
",",
"allow_missing_keys",
"=",
"False",
")",
":",
"try",
":",
"import",
"tensorflow",
"as",
"tf",
"# noqa: F401",
"import",
"torch",
"# noqa: F401",
"except",
"ImportError",
":",
"logger",
".",
"error",
"(",
"\"Loading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed. Please see \"",
"\"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions.\"",
")",
"raise",
"new_pt_params_dict",
"=",
"{",
"}",
"current_pt_params_dict",
"=",
"dict",
"(",
"pt_model",
".",
"named_parameters",
"(",
")",
")",
"# Make sure we are able to load PyTorch base models as well as derived models (with heads)",
"# TF models always have a prefix, some of PyTorch models (base ones) don't",
"start_prefix_to_remove",
"=",
"\"\"",
"if",
"not",
"any",
"(",
"s",
".",
"startswith",
"(",
"pt_model",
".",
"base_model_prefix",
")",
"for",
"s",
"in",
"current_pt_params_dict",
".",
"keys",
"(",
")",
")",
":",
"start_prefix_to_remove",
"=",
"pt_model",
".",
"base_model_prefix",
"+",
"\".\"",
"# Build a map from potential PyTorch weight names to TF 2.0 Variables",
"tf_weights_map",
"=",
"{",
"}",
"for",
"tf_weight",
"in",
"tf_weights",
":",
"pt_name",
",",
"transpose",
"=",
"convert_tf_weight_name_to_pt_weight_name",
"(",
"tf_weight",
".",
"name",
",",
"start_prefix_to_remove",
"=",
"start_prefix_to_remove",
")",
"tf_weights_map",
"[",
"pt_name",
"]",
"=",
"(",
"tf_weight",
".",
"numpy",
"(",
")",
",",
"transpose",
")",
"all_tf_weights",
"=",
"set",
"(",
"list",
"(",
"tf_weights_map",
".",
"keys",
"(",
")",
")",
")",
"loaded_pt_weights_data_ptr",
"=",
"{",
"}",
"missing_keys_pt",
"=",
"[",
"]",
"for",
"pt_weight_name",
",",
"pt_weight",
"in",
"current_pt_params_dict",
".",
"items",
"(",
")",
":",
"# Handle PyTorch shared weight ()not duplicated in TF 2.0",
"if",
"pt_weight",
".",
"data_ptr",
"(",
")",
"in",
"loaded_pt_weights_data_ptr",
":",
"new_pt_params_dict",
"[",
"pt_weight_name",
"]",
"=",
"loaded_pt_weights_data_ptr",
"[",
"pt_weight",
".",
"data_ptr",
"(",
")",
"]",
"continue",
"# Find associated numpy array in pytorch model state dict",
"if",
"pt_weight_name",
"not",
"in",
"tf_weights_map",
":",
"if",
"allow_missing_keys",
":",
"missing_keys_pt",
".",
"append",
"(",
"pt_weight_name",
")",
"continue",
"raise",
"AttributeError",
"(",
"\"{} not found in TF 2.0 model\"",
".",
"format",
"(",
"pt_weight_name",
")",
")",
"array",
",",
"transpose",
"=",
"tf_weights_map",
"[",
"pt_weight_name",
"]",
"if",
"transpose",
":",
"array",
"=",
"numpy",
".",
"transpose",
"(",
"array",
")",
"if",
"len",
"(",
"pt_weight",
".",
"shape",
")",
"<",
"len",
"(",
"array",
".",
"shape",
")",
":",
"array",
"=",
"numpy",
".",
"squeeze",
"(",
"array",
")",
"elif",
"len",
"(",
"pt_weight",
".",
"shape",
")",
">",
"len",
"(",
"array",
".",
"shape",
")",
":",
"array",
"=",
"numpy",
".",
"expand_dims",
"(",
"array",
",",
"axis",
"=",
"0",
")",
"if",
"list",
"(",
"pt_weight",
".",
"shape",
")",
"!=",
"list",
"(",
"array",
".",
"shape",
")",
":",
"try",
":",
"array",
"=",
"numpy",
".",
"reshape",
"(",
"array",
",",
"pt_weight",
".",
"shape",
")",
"except",
"AssertionError",
"as",
"e",
":",
"e",
".",
"args",
"+=",
"(",
"pt_weight",
".",
"shape",
",",
"array",
".",
"shape",
")",
"raise",
"e",
"try",
":",
"assert",
"list",
"(",
"pt_weight",
".",
"shape",
")",
"==",
"list",
"(",
"array",
".",
"shape",
")",
"except",
"AssertionError",
"as",
"e",
":",
"e",
".",
"args",
"+=",
"(",
"pt_weight",
".",
"shape",
",",
"array",
".",
"shape",
")",
"raise",
"e",
"# logger.warning(\"Initialize PyTorch weight {}\".format(pt_weight_name))",
"new_pt_params_dict",
"[",
"pt_weight_name",
"]",
"=",
"torch",
".",
"from_numpy",
"(",
"array",
")",
"loaded_pt_weights_data_ptr",
"[",
"pt_weight",
".",
"data_ptr",
"(",
")",
"]",
"=",
"torch",
".",
"from_numpy",
"(",
"array",
")",
"all_tf_weights",
".",
"discard",
"(",
"pt_weight_name",
")",
"missing_keys",
",",
"unexpected_keys",
"=",
"pt_model",
".",
"load_state_dict",
"(",
"new_pt_params_dict",
",",
"strict",
"=",
"False",
")",
"missing_keys",
"+=",
"missing_keys_pt",
"if",
"len",
"(",
"unexpected_keys",
")",
">",
"0",
":",
"logger",
".",
"warning",
"(",
"f\"Some weights of the TF 2.0 model were not used when \"",
"f\"initializing the PyTorch model {pt_model.__class__.__name__}: {unexpected_keys}\\n\"",
"f\"- This IS expected if you are initializing {pt_model.__class__.__name__} from a TF 2.0 model trained on another task \"",
"f\"or with another architecture (e.g. initializing a BertForSequenceClassification model from a TFBertForPreTraining model).\\n\"",
"f\"- This IS NOT expected if you are initializing {pt_model.__class__.__name__} from a TF 2.0 model that you expect \"",
"f\"to be exactly identical (e.g. initializing a BertForSequenceClassification model from a TFBertForSequenceClassification model).\"",
")",
"else",
":",
"logger",
".",
"warning",
"(",
"f\"All TF 2.0 model weights were used when initializing {pt_model.__class__.__name__}.\\n\"",
")",
"if",
"len",
"(",
"missing_keys",
")",
">",
"0",
":",
"logger",
".",
"warning",
"(",
"f\"Some weights of {pt_model.__class__.__name__} were not initialized from the TF 2.0 model \"",
"f\"and are newly initialized: {missing_keys}\\n\"",
"f\"You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\"",
")",
"else",
":",
"logger",
".",
"warning",
"(",
"f\"All the weights of {pt_model.__class__.__name__} were initialized from the TF 2.0 model.\\n\"",
"f\"If your task is similar to the task the model of the checkpoint was trained on, \"",
"f\"you can already use {pt_model.__class__.__name__} for predictions without further training.\"",
")",
"logger",
".",
"info",
"(",
"\"Weights or buffers not loaded from TF 2.0 model: {}\"",
".",
"format",
"(",
"all_tf_weights",
")",
")",
"return",
"pt_model"
] | [
303,
0
] | [
408,
19
] | python | en | ['en', 'en', 'en'] | True |
lazyprop | (fun) |
Decorator which only evaluates the specified function when accessed.
|
Decorator which only evaluates the specified function when accessed.
| def lazyprop(fun):
"""
Decorator which only evaluates the specified function when accessed.
"""
name = '_lazy_' + fun.__name__
@property
def _lazy(self):
val = getattr(self, name, None)
if val is None:
val = fun(self)
setattr(self, name, val)
return val
return _lazy | [
"def",
"lazyprop",
"(",
"fun",
")",
":",
"name",
"=",
"'_lazy_'",
"+",
"fun",
".",
"__name__",
"@",
"property",
"def",
"_lazy",
"(",
"self",
")",
":",
"val",
"=",
"getattr",
"(",
"self",
",",
"name",
",",
"None",
")",
"if",
"val",
"is",
"None",
":",
"val",
"=",
"fun",
"(",
"self",
")",
"setattr",
"(",
"self",
",",
"name",
",",
"val",
")",
"return",
"val",
"return",
"_lazy"
] | [
35,
0
] | [
49,
16
] | python | en | ['en', 'error', 'th'] | False |
taskd_cmd | (cmd, *args, **kwargs) |
Invoke taskd with the specified command with the privileges of the 'taskd'
user and 'taskd' group.
If 'capture_stdout' is passed as a keyword argument with the value True,
the return value are the contents the command printed to stdout.
|
Invoke taskd with the specified command with the privileges of the 'taskd'
user and 'taskd' group. | def taskd_cmd(cmd, *args, **kwargs):
"""
Invoke taskd with the specified command with the privileges of the 'taskd'
user and 'taskd' group.
If 'capture_stdout' is passed as a keyword argument with the value True,
the return value are the contents the command printed to stdout.
"""
capture_stdout = kwargs.pop("capture_stdout", False)
fun = subprocess.check_output if capture_stdout else subprocess.check_call
return fun(
[TASKD_COMMAND, cmd, "--data", TASKD_DATA_DIR] + list(args),
preexec_fn=run_as_taskd_user,
**kwargs
) | [
"def",
"taskd_cmd",
"(",
"cmd",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"capture_stdout",
"=",
"kwargs",
".",
"pop",
"(",
"\"capture_stdout\"",
",",
"False",
")",
"fun",
"=",
"subprocess",
".",
"check_output",
"if",
"capture_stdout",
"else",
"subprocess",
".",
"check_call",
"return",
"fun",
"(",
"[",
"TASKD_COMMAND",
",",
"cmd",
",",
"\"--data\"",
",",
"TASKD_DATA_DIR",
"]",
"+",
"list",
"(",
"args",
")",
",",
"preexec_fn",
"=",
"run_as_taskd_user",
",",
"*",
"*",
"kwargs",
")"
] | [
63,
0
] | [
77,
5
] | python | en | ['en', 'error', 'th'] | False |
certtool_cmd | (*args, **kwargs) |
Invoke certtool from GNUTLS and return the output of the command.
The provided arguments are added to the certtool command and keyword
arguments are added to subprocess.check_output().
Note that this will suppress all output of certtool and it will only be
printed whenever there is an unsuccessful return code.
|
Invoke certtool from GNUTLS and return the output of the command. | def certtool_cmd(*args, **kwargs):
"""
Invoke certtool from GNUTLS and return the output of the command.
The provided arguments are added to the certtool command and keyword
arguments are added to subprocess.check_output().
Note that this will suppress all output of certtool and it will only be
printed whenever there is an unsuccessful return code.
"""
return subprocess.check_output(
[CERTTOOL_COMMAND] + list(args),
preexec_fn=lambda: os.umask(0077),
stderr=subprocess.STDOUT,
**kwargs
) | [
"def",
"certtool_cmd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"subprocess",
".",
"check_output",
"(",
"[",
"CERTTOOL_COMMAND",
"]",
"+",
"list",
"(",
"args",
")",
",",
"preexec_fn",
"=",
"lambda",
":",
"os",
".",
"umask",
"(",
"0077",
")",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
",",
"*",
"*",
"kwargs",
")"
] | [
80,
0
] | [
95,
5
] | python | en | ['en', 'error', 'th'] | False |
mark_imperative | (*path) |
Mark the specified path as being imperatively managed by creating an empty
file called ".imperative", so that it doesn't interfere with the
declarative configuration.
|
Mark the specified path as being imperatively managed by creating an empty
file called ".imperative", so that it doesn't interfere with the
declarative configuration.
| def mark_imperative(*path):
"""
Mark the specified path as being imperatively managed by creating an empty
file called ".imperative", so that it doesn't interfere with the
declarative configuration.
"""
open(os.path.join(mkpath(*path), ".imperative"), 'a').close() | [
"def",
"mark_imperative",
"(",
"*",
"path",
")",
":",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"mkpath",
"(",
"*",
"path",
")",
",",
"\".imperative\"",
")",
",",
"'a'",
")",
".",
"close",
"(",
")"
] | [
107,
0
] | [
113,
65
] | python | en | ['en', 'error', 'th'] | False |
is_imperative | (*path) |
Check whether the given path is marked as imperative, see mark_imperative()
for more information.
|
Check whether the given path is marked as imperative, see mark_imperative()
for more information.
| def is_imperative(*path):
"""
Check whether the given path is marked as imperative, see mark_imperative()
for more information.
"""
full_path = []
for component in path:
full_path.append(component)
if os.path.exists(os.path.join(mkpath(*full_path), ".imperative")):
return True
return False | [
"def",
"is_imperative",
"(",
"*",
"path",
")",
":",
"full_path",
"=",
"[",
"]",
"for",
"component",
"in",
"path",
":",
"full_path",
".",
"append",
"(",
"component",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"mkpath",
"(",
"*",
"full_path",
")",
",",
"\".imperative\"",
")",
")",
":",
"return",
"True",
"return",
"False"
] | [
116,
0
] | [
126,
16
] | python | en | ['en', 'error', 'th'] | False |
create_template | (contents) |
Generate a temporary file with the specified contents as a list of strings
and yield its path as the context.
|
Generate a temporary file with the specified contents as a list of strings
and yield its path as the context.
| def create_template(contents):
"""
Generate a temporary file with the specified contents as a list of strings
and yield its path as the context.
"""
template = NamedTemporaryFile(mode="w", prefix="certtool-template")
template.writelines(map(lambda l: l + "\n", contents))
template.flush()
yield template.name
template.close() | [
"def",
"create_template",
"(",
"contents",
")",
":",
"template",
"=",
"NamedTemporaryFile",
"(",
"mode",
"=",
"\"w\"",
",",
"prefix",
"=",
"\"certtool-template\"",
")",
"template",
".",
"writelines",
"(",
"map",
"(",
"lambda",
"l",
":",
"l",
"+",
"\"\\n\"",
",",
"contents",
")",
")",
"template",
".",
"flush",
"(",
")",
"yield",
"template",
".",
"name",
"template",
".",
"close",
"(",
")"
] | [
139,
0
] | [
148,
20
] | python | en | ['en', 'error', 'th'] | False |
cli | (ctx) |
Manage Taskserver users and certificates
|
Manage Taskserver users and certificates
| def cli(ctx):
"""
Manage Taskserver users and certificates
"""
if not IS_AUTO_CONFIG:
return
for path in (CA_KEY, CA_CERT, CRL_FILE):
if not os.path.exists(path):
msg = "CA setup not done or incomplete, missing file {}."
ctx.fail(msg.format(path)) | [
"def",
"cli",
"(",
"ctx",
")",
":",
"if",
"not",
"IS_AUTO_CONFIG",
":",
"return",
"for",
"path",
"in",
"(",
"CA_KEY",
",",
"CA_CERT",
",",
"CRL_FILE",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"msg",
"=",
"\"CA setup not done or incomplete, missing file {}.\"",
"ctx",
".",
"fail",
"(",
"msg",
".",
"format",
"(",
"path",
")",
")"
] | [
446,
0
] | [
455,
38
] | python | en | ['en', 'error', 'th'] | False |
org_cli | () |
Manage organisations
|
Manage organisations
| def org_cli():
"""
Manage organisations
"""
pass | [
"def",
"org_cli",
"(",
")",
":",
"pass"
] | [
459,
0
] | [
463,
8
] | python | en | ['en', 'error', 'th'] | False |
user_cli | () |
Manage users
|
Manage users
| def user_cli():
"""
Manage users
"""
pass | [
"def",
"user_cli",
"(",
")",
":",
"pass"
] | [
467,
0
] | [
471,
8
] | python | en | ['en', 'error', 'th'] | False |
group_cli | () |
Manage groups
|
Manage groups
| def group_cli():
"""
Manage groups
"""
pass | [
"def",
"group_cli",
"(",
")",
":",
"pass"
] | [
475,
0
] | [
479,
8
] | python | en | ['en', 'error', 'th'] | False |
list_users | (organisation) |
List all users belonging to the specified organisation.
|
List all users belonging to the specified organisation.
| def list_users(organisation):
"""
List all users belonging to the specified organisation.
"""
label("The following users exists for {}:".format(organisation.name))
for user in organisation.users.values():
sys.stdout.write(user.name + "\n") | [
"def",
"list_users",
"(",
"organisation",
")",
":",
"label",
"(",
"\"The following users exists for {}:\"",
".",
"format",
"(",
"organisation",
".",
"name",
")",
")",
"for",
"user",
"in",
"organisation",
".",
"users",
".",
"values",
"(",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"user",
".",
"name",
"+",
"\"\\n\"",
")"
] | [
484,
0
] | [
490,
42
] | python | en | ['en', 'error', 'th'] | False |
list_groups | (organisation) |
List all users belonging to the specified organisation.
|
List all users belonging to the specified organisation.
| def list_groups(organisation):
"""
List all users belonging to the specified organisation.
"""
label("The following users exists for {}:".format(organisation.name))
for group in organisation.groups.values():
sys.stdout.write(group.name + "\n") | [
"def",
"list_groups",
"(",
"organisation",
")",
":",
"label",
"(",
"\"The following users exists for {}:\"",
".",
"format",
"(",
"organisation",
".",
"name",
")",
")",
"for",
"group",
"in",
"organisation",
".",
"groups",
".",
"values",
"(",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"group",
".",
"name",
"+",
"\"\\n\"",
")"
] | [
495,
0
] | [
501,
43
] | python | en | ['en', 'error', 'th'] | False |
list_orgs | () |
List available organisations
|
List available organisations
| def list_orgs():
"""
List available organisations
"""
label("The following organisations exist:")
for org in Manager().orgs:
sys.stdout.write(org.name + "\n") | [
"def",
"list_orgs",
"(",
")",
":",
"label",
"(",
"\"The following organisations exist:\"",
")",
"for",
"org",
"in",
"Manager",
"(",
")",
".",
"orgs",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"org",
".",
"name",
"+",
"\"\\n\"",
")"
] | [
505,
0
] | [
511,
41
] | python | en | ['en', 'error', 'th'] | False |
get_uuid | (organisation, user) |
Get the UUID of the specified user belonging to the specified organisation.
|
Get the UUID of the specified user belonging to the specified organisation.
| def get_uuid(organisation, user):
"""
Get the UUID of the specified user belonging to the specified organisation.
"""
userobj = organisation.get_user(user)
if userobj is None:
msg = "User {} doesn't exist in organisation {}."
sys.exit(msg.format(userobj.name, organisation.name))
label("User {} has the following UUID:".format(userobj.name))
sys.stdout.write(user.key + "\n") | [
"def",
"get_uuid",
"(",
"organisation",
",",
"user",
")",
":",
"userobj",
"=",
"organisation",
".",
"get_user",
"(",
"user",
")",
"if",
"userobj",
"is",
"None",
":",
"msg",
"=",
"\"User {} doesn't exist in organisation {}.\"",
"sys",
".",
"exit",
"(",
"msg",
".",
"format",
"(",
"userobj",
".",
"name",
",",
"organisation",
".",
"name",
")",
")",
"label",
"(",
"\"User {} has the following UUID:\"",
".",
"format",
"(",
"userobj",
".",
"name",
")",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"user",
".",
"key",
"+",
"\"\\n\"",
")"
] | [
517,
0
] | [
527,
37
] | python | en | ['en', 'error', 'th'] | False |
export_user | (organisation, user) |
Export user of the specified organisation as a series of shell commands
that can be used on the client side to easily import the certificates.
Note that the private key will be exported as well, so use this with care!
|
Export user of the specified organisation as a series of shell commands
that can be used on the client side to easily import the certificates. | def export_user(organisation, user):
"""
Export user of the specified organisation as a series of shell commands
that can be used on the client side to easily import the certificates.
Note that the private key will be exported as well, so use this with care!
"""
userobj = organisation.get_user(user)
if userobj is None:
msg = "User {} doesn't exist in organisation {}."
sys.exit(msg.format(user, organisation.name))
sys.stdout.write(userobj.export()) | [
"def",
"export_user",
"(",
"organisation",
",",
"user",
")",
":",
"userobj",
"=",
"organisation",
".",
"get_user",
"(",
"user",
")",
"if",
"userobj",
"is",
"None",
":",
"msg",
"=",
"\"User {} doesn't exist in organisation {}.\"",
"sys",
".",
"exit",
"(",
"msg",
".",
"format",
"(",
"user",
",",
"organisation",
".",
"name",
")",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"userobj",
".",
"export",
"(",
")",
")"
] | [
533,
0
] | [
545,
38
] | python | en | ['en', 'error', 'th'] | False |
add_org | (name) |
Create an organisation with the specified name.
|
Create an organisation with the specified name.
| def add_org(name):
"""
Create an organisation with the specified name.
"""
if os.path.exists(mkpath(name)):
msg = "Organisation with name {} already exists."
sys.exit(msg.format(name))
taskd_cmd("add", "org", name)
mark_imperative(name) | [
"def",
"add_org",
"(",
"name",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"mkpath",
"(",
"name",
")",
")",
":",
"msg",
"=",
"\"Organisation with name {} already exists.\"",
"sys",
".",
"exit",
"(",
"msg",
".",
"format",
"(",
"name",
")",
")",
"taskd_cmd",
"(",
"\"add\"",
",",
"\"org\"",
",",
"name",
")",
"mark_imperative",
"(",
"name",
")"
] | [
550,
0
] | [
559,
25
] | python | en | ['en', 'error', 'th'] | False |
del_org | (name) |
Delete the organisation with the specified name.
All of the users and groups will be deleted as well and client certificates
will be revoked.
|
Delete the organisation with the specified name. | def del_org(name):
"""
Delete the organisation with the specified name.
All of the users and groups will be deleted as well and client certificates
will be revoked.
"""
Manager().del_org(name)
msg = ("Organisation {} deleted. Be sure to restart the Taskserver"
" using 'systemctl restart taskserver.service' in order for"
" the certificate revocation to apply.")
click.echo(msg.format(name), err=True) | [
"def",
"del_org",
"(",
"name",
")",
":",
"Manager",
"(",
")",
".",
"del_org",
"(",
"name",
")",
"msg",
"=",
"(",
"\"Organisation {} deleted. Be sure to restart the Taskserver\"",
"\" using 'systemctl restart taskserver.service' in order for\"",
"\" the certificate revocation to apply.\"",
")",
"click",
".",
"echo",
"(",
"msg",
".",
"format",
"(",
"name",
")",
",",
"err",
"=",
"True",
")"
] | [
564,
0
] | [
575,
42
] | python | en | ['en', 'error', 'th'] | False |
add_user | (organisation, user) |
Create a user for the given organisation along with a client certificate
and print the key of the new user.
The client certificate along with it's public key can be shown via the
'user export' subcommand.
|
Create a user for the given organisation along with a client certificate
and print the key of the new user. | def add_user(organisation, user):
"""
Create a user for the given organisation along with a client certificate
and print the key of the new user.
The client certificate along with it's public key can be shown via the
'user export' subcommand.
"""
userobj = organisation.add_user(user)
if userobj is None:
msg = "User {} already exists in organisation {}."
sys.exit(msg.format(user, organisation))
else:
mark_imperative(organisation.name, "users", userobj.key) | [
"def",
"add_user",
"(",
"organisation",
",",
"user",
")",
":",
"userobj",
"=",
"organisation",
".",
"add_user",
"(",
"user",
")",
"if",
"userobj",
"is",
"None",
":",
"msg",
"=",
"\"User {} already exists in organisation {}.\"",
"sys",
".",
"exit",
"(",
"msg",
".",
"format",
"(",
"user",
",",
"organisation",
")",
")",
"else",
":",
"mark_imperative",
"(",
"organisation",
".",
"name",
",",
"\"users\"",
",",
"userobj",
".",
"key",
")"
] | [
581,
0
] | [
594,
64
] | python | en | ['en', 'error', 'th'] | False |
del_user | (organisation, user) |
Delete a user from the given organisation.
This will also revoke the client certificate of the given user.
|
Delete a user from the given organisation. | def del_user(organisation, user):
"""
Delete a user from the given organisation.
This will also revoke the client certificate of the given user.
"""
organisation.del_user(user)
msg = ("User {} deleted. Be sure to restart the Taskserver using"
" 'systemctl restart taskserver.service' in order for the"
" certificate revocation to apply.")
click.echo(msg.format(user), err=True) | [
"def",
"del_user",
"(",
"organisation",
",",
"user",
")",
":",
"organisation",
".",
"del_user",
"(",
"user",
")",
"msg",
"=",
"(",
"\"User {} deleted. Be sure to restart the Taskserver using\"",
"\" 'systemctl restart taskserver.service' in order for the\"",
"\" certificate revocation to apply.\"",
")",
"click",
".",
"echo",
"(",
"msg",
".",
"format",
"(",
"user",
")",
",",
"err",
"=",
"True",
")"
] | [
600,
0
] | [
610,
42
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.