uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9f5522a4f4b57f527bac1739 | train | function | def create_federated_value(
value: building_blocks.ComputationBuildingBlock,
placement: placement_literals.PlacementLiteral) -> building_blocks.Call:
r"""Creates a called federated value.
Call
/ \
Intrinsic Comp
Args:
value: A `building_blocks.ComputationBuildingBlock`... | def create_federated_value(
value: building_blocks.ComputationBuildingBlock,
placement: placement_literals.PlacementLiteral) -> building_blocks.Call:
| r"""Creates a called federated value.
Call
/ \
Intrinsic Comp
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
placement: A `placement_literals.PlacementLiteral` to use as the placement.
Returns:
A `building_blocks.Call`.
Raises:
... | )
elements.append((name, intrinsic))
result = building_blocks.Struct(elements,
value.type_signature.member.python_container)
symbols = ((value_ref.name, value),)
return building_blocks.Block(symbols, result)
def create_federated_value(
value: building_blocks.ComputationBu... | 77 | 77 | 259 | 31 | 46 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_value | create_federated_value | 1,127 | 1,158 | 1,127 | 1,129 | 37c7d1791ac5293ab7719d24fe0f244d89815d71 | bigcode/the-stack | train |
f2dff1312fd0a7440870b589 | train | function | def _create_flat_federated_zip(value):
r"""Private function to create a called federated zip for a non-nested type.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp]
This function returns a federated tuple given a `value` with a tuple of
federated values ... | def _create_flat_federated_zip(value):
| r"""Private function to create a called federated zip for a non-nested type.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp]
This function returns a federated tuple given a `value` with a tuple of
federated values type signature.
Args:
value: A `... |
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
placement: A `placement_literals.PlacementLiteral` to use as the placement.
Returns:
A `building_blocks.Call`.
Raises:
TypeError: If any of the types do not match.
"""
py_typecheck.check_type(value, building_blo... | 216 | 216 | 723 | 10 | 206 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | _create_flat_federated_zip | _create_flat_federated_zip | 1,161 | 1,235 | 1,161 | 1,161 | 2b81c65adc810959e8be95534bab0a5b2dc1b082 | bigcode/the-stack | train |
d6d4f2602970d5f4098bd509 | train | function | def create_tensorflow_binary_operator(
operand_type: computation_types.Type,
operator: Callable[[Any, Any], Any]) -> building_blocks.CompiledComputation:
"""Creates a TensorFlow computation for the binary `operator`.
For `T` the `operand_type`, the type signature of the constructed operator
will be `(<T,... | def create_tensorflow_binary_operator(
operand_type: computation_types.Type,
operator: Callable[[Any, Any], Any]) -> building_blocks.CompiledComputation:
| """Creates a TensorFlow computation for the binary `operator`.
For `T` the `operand_type`, the type signature of the constructed operator
will be `(<T,T> -> U)`, where `U` is the result of applying `operator` to
a tuple of type `<T,T>`.
Notice that we have quite serious restrictions on `operand_type` here; ... | tensor of this same dtype and shape `new_shape`, with the same
value in each entry as its scalar argument.
Raises:
TypeError: If the types of the arguments do not match the declared arg
types.
ValueError: If `new_shape` is not fully defined.
"""
proto = tensorflow_computation_factory.create_broa... | 129 | 129 | 430 | 34 | 95 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_tensorflow_binary_operator | create_tensorflow_binary_operator | 300 | 339 | 300 | 302 | d76ec576212b3007be3616423fc3c15df9632268 | bigcode/the-stack | train |
80c014c4dc8f88dcb6ac3e17 | train | function | def create_federated_zip(
value: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
r"""Creates a called federated zip.
This function accepts a value whose type signature is a (potentially) nested
tuple structure of federated values all with the same placement, and uses
one of the federated... | def create_federated_zip(
value: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
| r"""Creates a called federated zip.
This function accepts a value whose type signature is a (potentially) nested
tuple structure of federated values all with the same placement, and uses
one of the federated_zip intrinsics (at client or at server) to promote the
placement to the highest level. E.g., A value ... | 1]]
else:
# Recursive case for three or more elements
split_point = int((start_index + end_index) / 2)
left_tree, left_paths = _build_tree_of_zips_and_paths_to_elements(
args, start_index, split_point)
right_tree, right_paths = _build_tree_of_zips_and_paths_to_elements(
args, split_poi... | 256 | 256 | 964 | 22 | 233 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_zip | create_federated_zip | 1,299 | 1,397 | 1,299 | 1,300 | c7b6142fb7cca36aa1b36ea9fe91255b91ed61fe | bigcode/the-stack | train |
36843af44cc695f82a5a9954 | train | function | def create_tensorflow_binary_operator_with_upcast(
type_signature: computation_types.Type,
operator: Callable[[Any, Any], Any]) -> building_blocks.CompiledComputation:
"""Creates TF computation upcasting its argument and applying `operator`.
The concept of upcasting is explained further in the docstring fo... | def create_tensorflow_binary_operator_with_upcast(
type_signature: computation_types.Type,
operator: Callable[[Any, Any], Any]) -> building_blocks.CompiledComputation:
| """Creates TF computation upcasting its argument and applying `operator`.
The concept of upcasting is explained further in the docstring for
`apply_binary_operator_with_upcast`.
Args:
type_signature: Value convertible to `computation_types.StructType`,
with two elements, both of the same type or the... | the same dtype as the leaves of the '
'first. See `type_analysis.is_binary_op_with_upcast_compatible_pair` for '
'more details.'.format(type_spec))
def create_tensorflow_binary_operator_with_upcast(
type_signature: computation_types.Type,
operator: Callable[[Any, Any], Any]) -> building_blocks.... | 75 | 75 | 253 | 37 | 38 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_tensorflow_binary_operator_with_upcast | create_tensorflow_binary_operator_with_upcast | 1,835 | 1,861 | 1,835 | 1,837 | 54f3b3c17681b7340b3083349423272189fd4840 | bigcode/the-stack | train |
6940d60d849c4454a10e16a2 | train | function | def create_zip_two_values(
value: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
r"""Creates a called federated zip with two values.
Call
/ \
Intrinsic Tuple
|
[Comp1, Comp2]
Notice that this function will drop any names as... | def create_zip_two_values(
value: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
| r"""Creates a called federated zip with two values.
Call
/ \
Intrinsic Tuple
|
[Comp1, Comp2]
Notice that this function will drop any names associated to the two-tuple it
is processing. This is necessary due to the type signature of the
underl... | ATED_VALUE_AT_SERVER.uri, placement_fn_type)
return building_blocks.Call(placement_function, unplaced_zero)
elif type_spec.is_struct():
elements = []
for k in range(len(type_spec)):
elements.append(create_generic_constant(type_spec[k], scalar_value))
names = [name for name, _ in anonymous_tuple.... | 162 | 162 | 542 | 21 | 141 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_zip_two_values | create_zip_two_values | 1,467 | 1,524 | 1,467 | 1,468 | dc8afa0db9d8971afbbedc7043243abe00677598 | bigcode/the-stack | train |
e7bc5d26ed66d69adb33b445 | train | function | def create_federated_setattr_call(
federated_comp: building_blocks.ComputationBuildingBlock, name: str,
value_comp: building_blocks.ComputationBuildingBlock
) -> building_blocks.Call:
"""Returns building block for `setattr(name, value_comp)` on `federated_comp`.
Creates an appropriate communication intrins... | def create_federated_setattr_call(
federated_comp: building_blocks.ComputationBuildingBlock, name: str,
value_comp: building_blocks.ComputationBuildingBlock
) -> building_blocks.Call:
| """Returns building block for `setattr(name, value_comp)` on `federated_comp`.
Creates an appropriate communication intrinsic (either `federated_map` or
`federated_apply`) as well as a `building_blocks.Lambda`
representing setting the `name` attribute of `federated_comp`'s `member` to
`value_comp`, and stitc... | ,
as defined by `name`.
"""
py_typecheck.check_type(arg, building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(name, str)
py_typecheck.check_type(arg.type_signature, computation_types.FederatedType)
py_typecheck.check_type(arg.type_signature.member,
computation_types.... | 141 | 141 | 472 | 42 | 99 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_setattr_call | create_federated_setattr_call | 397 | 437 | 397 | 400 | 405ecfa3a58e81308bddc5442383975a38d0cd36 | bigcode/the-stack | train |
253d4118e7ba04fe4b960a19 | train | function | def construct_tensorflow_selecting_and_packing_outputs(
parameter_type: computation_types.StructType,
output_structure: anonymous_tuple.AnonymousTuple
) -> building_blocks.CompiledComputation:
"""Constructs TensorFlow selecting and packing elements from its input.
The result of this function can be called ... | def construct_tensorflow_selecting_and_packing_outputs(
parameter_type: computation_types.StructType,
output_structure: anonymous_tuple.AnonymousTuple
) -> building_blocks.CompiledComputation:
| """Constructs TensorFlow selecting and packing elements from its input.
The result of this function can be called on a deduplicated
`building_blocks.Struct` containing called graphs, thus preventing us from
embedding the same TensorFlow computation in the generated graphs, and
reducing the amount of work dup... | """
def __init__(self, tuple_index: int, selection_sequence: Sequence[int]):
self._tuple_index = tuple_index
self._selection_sequence = selection_sequence
@property
def tuple_index(self):
return self._tuple_index
@property
def selection_sequence(self):
return self._selection_sequence
de... | 228 | 228 | 763 | 39 | 188 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | construct_tensorflow_selecting_and_packing_outputs | construct_tensorflow_selecting_and_packing_outputs | 141 | 215 | 141 | 144 | a8b2ca6f46cceaca6be1a4e273d0c4aede9a728c | bigcode/the-stack | train |
8d9b9de18949b79a14181e1e | train | function | def create_federated_apply(
fn: building_blocks.ComputationBuildingBlock,
arg: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
r"""Creates a called federated apply.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp]
Args:
fn: A... | def create_federated_apply(
fn: building_blocks.ComputationBuildingBlock,
arg: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
| r"""Creates a called federated apply.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp]
Args:
fn: A `building_blocks.ComputationBuildingBlock` to use as the function.
arg: A `building_blocks.ComputationBuildingBlock` to use as the argument.
Retur... | .FEDERATED_AGGREGATE.uri,
intrinsic_type)
values = building_blocks.Struct((value, zero, accumulate, merge, report))
return building_blocks.Call(intrinsic, values)
def create_federated_apply(
fn: building_blocks.ComputationBuildingBlock,
arg: building_blocks.Computatio... | 74 | 74 | 248 | 32 | 42 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_apply | create_federated_apply | 694 | 724 | 694 | 696 | 838321c6df12e8e8dd59597f4bcb0a26696715e9 | bigcode/the-stack | train |
e87ca30943f5bb80edfd7e02 | train | class | class SelectionSpec(object):
"""Data class representing map from input tuple to selection of result.
Attributes:
tuple_index: The index of the source of the selection sequence in the
desired result of the generated TensorFlow. If this `SelectionSpec`
appears at index i of a list of `SelectionSpec`s... | class SelectionSpec(object):
| """Data class representing map from input tuple to selection of result.
Attributes:
tuple_index: The index of the source of the selection sequence in the
desired result of the generated TensorFlow. If this `SelectionSpec`
appears at index i of a list of `SelectionSpec`s, index j is the source
... | _blocks.CompiledComputation`
representing the identity function taking an argument of type
`type_signature` and returning the same value.
Raises:
TypeError: If `type_signature` contains any types which cannot appear in
TensorFlow bindings.
"""
proto = tensorflow_computation_factory.create_ident... | 84 | 84 | 280 | 5 | 79 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | SelectionSpec | SelectionSpec | 96 | 127 | 96 | 96 | 4465d238294cb7aa538c3a2d283038d91ba306e6 | bigcode/the-stack | train |
171ef22aa981f482a5a16c35 | train | function | def _extract_selections(parameter_value, output_spec):
results = []
for selection_spec in output_spec:
result_element = parameter_value[selection_spec.tuple_index]
for selection in selection_spec.selection_sequence:
py_typecheck.check_type(selection, int)
result_element = result_element[selectio... | def _extract_selections(parameter_value, output_spec):
| results = []
for selection_spec in output_spec:
result_element = parameter_value[selection_spec.tuple_index]
for selection in selection_spec.selection_sequence:
py_typecheck.check_type(selection, int)
result_element = result_element[selection]
results.append(result_element)
return results
| (self):
return self._selection_sequence
def __str__(self):
return 'SelectionSequence(tuple_index={},selection_sequence={}'.format(
self._tuple_index, self._selection_sequence)
def __repr__(self):
return str(self)
def _extract_selections(parameter_value, output_spec):
| 64 | 64 | 74 | 11 | 53 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | _extract_selections | _extract_selections | 130 | 138 | 130 | 130 | 45ccb3546610d30292245371da8c1ebbc02d65f5 | bigcode/the-stack | train |
c90761345c9969553e50f123 | train | function | def create_federated_collect(
value: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
r"""Creates a called federated collect.
Call
/ \
Intrinsic Comp
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
Returns:
A `buildin... | def create_federated_collect(
value: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
| r"""Creates a called federated collect.
Call
/ \
Intrinsic Comp
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
Returns:
A `building_blocks.Call`.
Raises:
TypeError: If any of the types do not match.
"""
py_typecheck.check_type(... | _signature,
result_type)
intrinsic = building_blocks.Intrinsic(intrinsic_defs.FEDERATED_BROADCAST.uri,
intrinsic_type)
return building_blocks.Call(intrinsic, value)
def create_federated_collect(
value: building_blocks.Comp... | 64 | 64 | 200 | 22 | 42 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_collect | create_federated_collect | 754 | 779 | 754 | 755 | 65f9eb8f2ead58dc8cfaa8834b0c8e7845e58a0a | bigcode/the-stack | train |
d700f665555377aa4896f778 | train | function | def create_federated_eval(
fn: building_blocks.ComputationBuildingBlock,
placement: placement_literals.PlacementLiteral,
) -> building_blocks.Call:
r"""Creates a called federated eval.
Call
/ \
Intrinsic Comp
Args:
fn: A `building_blocks.ComputationBuildingBlock` to us... | def create_federated_eval(
fn: building_blocks.ComputationBuildingBlock,
placement: placement_literals.PlacementLiteral,
) -> building_blocks.Call:
| r"""Creates a called federated eval.
Call
/ \
Intrinsic Comp
Args:
fn: A `building_blocks.ComputationBuildingBlock` to use as the function.
placement: A `placement_literals.PlacementLiteral` to use as the placement.
Returns:
A `building_blocks.Call`.
Raises:
... | _types.FunctionType(
type_conversions.type_to_non_all_equal(value.type_signature), result_type)
intrinsic = building_blocks.Intrinsic(intrinsic_defs.FEDERATED_COLLECT.uri,
intrinsic_type)
return building_blocks.Call(intrinsic, value)
def create_federated_eval(
fn: b... | 87 | 87 | 292 | 32 | 55 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_eval | create_federated_eval | 782 | 817 | 782 | 785 | 0377fa6028acc11558f59262bf93dc303f43d97a | bigcode/the-stack | train |
e4540b3e621ffbefdd8ade4b | train | function | def _build_tree_of_zips_and_paths_to_elements(
args: building_blocks.Reference,
start_index: int,
end_index: int,
) -> Tuple[building_blocks.ComputationBuildingBlock, List[List[int]]]:
"""Builds a binary tree of federated_zips and a list of paths to each element.
Args:
args: A reference to the valu... | def _build_tree_of_zips_and_paths_to_elements(
args: building_blocks.Reference,
start_index: int,
end_index: int,
) -> Tuple[building_blocks.ComputationBuildingBlock, List[List[int]]]:
| """Builds a binary tree of federated_zips and a list of paths to each element.
Args:
args: A reference to the values to be zipped.
start_index: The index of the first element of `args` to zip.
end_index: The index of the last element of `args` to zip.
Returns:
A tuple containing the tree of zips... | ipped_tree_ref, path) for path in paths])
flatten_fn = building_blocks.Lambda(zipped_tree_ref.name,
zipped_tree_ref.type_signature,
flattened_tree)
unnamed_zip = map_fn(flatten_fn, zipped_block)
return create_named_federated_tuple... | 145 | 145 | 485 | 47 | 98 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | _build_tree_of_zips_and_paths_to_elements | _build_tree_of_zips_and_paths_to_elements | 1,243 | 1,287 | 1,243 | 1,247 | 0888d1d2ccf90ae2436d10cf5fdae9c2ee0db638 | bigcode/the-stack | train |
6844dae0a231126d06b30543 | train | function | def _create_naming_function(tuple_type_to_name, names_to_add, container_type):
"""Private function to construct lambda naming a given tuple type.
Args:
tuple_type_to_name: Instance of `computation_types.StructType`, the type
of the argument which we wish to name.
names_to_add: Python `list` or `tuple... | def _create_naming_function(tuple_type_to_name, names_to_add, container_type):
| """Private function to construct lambda naming a given tuple type.
Args:
tuple_type_to_name: Instance of `computation_types.StructType`, the type
of the argument which we wish to name.
names_to_add: Python `list` or `tuple`, the names we wish to give to
`tuple_type_to_name`.
container_type:... | the value.
Returns:
A `building_blocks.Call`.
Raises:
TypeError: If any of the types do not match.
"""
py_typecheck.check_type(value, building_blocks.ComputationBuildingBlock)
intrinsic_type = computation_types.FunctionType(value.type_signature,
val... | 114 | 114 | 381 | 18 | 96 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | _create_naming_function | _create_naming_function | 1,622 | 1,659 | 1,622 | 1,622 | 66575157076914f11eece888ea8e8d8ba80c60a9 | bigcode/the-stack | train |
269526e4e903a6d13d98ccbf | train | function | def create_federated_broadcast(
value: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
r"""Creates a called federated broadcast.
Call
/ \
Intrinsic Comp
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
Returns:
A `bui... | def create_federated_broadcast(
value: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
| r"""Creates a called federated broadcast.
Call
/ \
Intrinsic Comp
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
Returns:
A `building_blocks.Call`.
Raises:
TypeError: If any of the types do not match.
"""
py_typecheck.check_typ... | .Intrinsic(intrinsic_defs.FEDERATED_APPLY.uri,
intrinsic_type)
values = building_blocks.Struct((fn, arg))
return building_blocks.Call(intrinsic, values)
def create_federated_broadcast(
value: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
| 64 | 64 | 188 | 23 | 41 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_broadcast | create_federated_broadcast | 727 | 751 | 727 | 728 | dd14ed8e011e027ce625e574d7a59933b9e292b8 | bigcode/the-stack | train |
b68078e505e325a3cb367c1d | train | function | def create_named_tuple(
comp: building_blocks.ComputationBuildingBlock,
names: Sequence[str],
container_type=None,
) -> building_blocks.ComputationBuildingBlock:
"""Creates a computation that applies `names` to `comp`.
Args:
comp: A `building_blocks.ComputationBuildingBlock` with a `type_signature`... | def create_named_tuple(
comp: building_blocks.ComputationBuildingBlock,
names: Sequence[str],
container_type=None,
) -> building_blocks.ComputationBuildingBlock:
| """Creates a computation that applies `names` to `comp`.
Args:
comp: A `building_blocks.ComputationBuildingBlock` with a `type_signature`
of type `computation_types.StructType`.
names: Python `tuple` or `list` containing instances of type `str` or
`None`, the names to apply to `comp`.
conta... | already correct, so no work is necessary
return tuple_to_name
naming_fn = _create_naming_function(tuple_to_name.type_signature.member,
names_to_add, container_type)
return create_federated_map_or_apply(naming_fn, tuple_to_name)
def create_named_tuple(
comp: building_b... | 91 | 91 | 305 | 35 | 56 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_named_tuple | create_named_tuple | 1,718 | 1,748 | 1,718 | 1,722 | 59a29cd1c60bcb8a9462d1b4c3f8fc245bf76775 | bigcode/the-stack | train |
f598d1cf501602c053c4480a | train | function | def create_federated_getattr_comp(
comp: building_blocks.ComputationBuildingBlock,
name: str) -> building_blocks.Lambda:
"""Function to construct computation for `federated_apply` of `__getattr__`.
Creates a `building_blocks.ComputationBuildingBlock`
which selects `name` from its argument, of type `comp.... | def create_federated_getattr_comp(
comp: building_blocks.ComputationBuildingBlock,
name: str) -> building_blocks.Lambda:
| """Function to construct computation for `federated_apply` of `__getattr__`.
Creates a `building_blocks.ComputationBuildingBlock`
which selects `name` from its argument, of type `comp.type_signature.member`,
an instance of `computation_types.StructType`.
Args:
comp: Instance of `building_blocks.Computat... | ((key, building_blocks.Selection(lambda_arg, index=idx)))
return_tuple = building_blocks.Struct(elements,
named_tuple_signature.python_container)
lambda_to_return = building_blocks.Lambda(lambda_arg.name,
named_tuple_signature, retu... | 105 | 105 | 350 | 30 | 75 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_getattr_comp | create_federated_getattr_comp | 504 | 539 | 504 | 506 | 0ff6839fc67edccb24fc07007af5d45981caa4e8 | bigcode/the-stack | train |
a52838f2a0a8586810f75697 | train | function | def create_compiled_empty_tuple() -> building_blocks.Call:
"""Returns called graph representing the empty tuple.
Returns:
An instance of `building_blocks.Call`, calling a noarg function
which returns an empty tuple. This function is an instance of
`building_blocks.CompiledComputation`.
"""
proto = ... | def create_compiled_empty_tuple() -> building_blocks.Call:
| """Returns called graph representing the empty tuple.
Returns:
An instance of `building_blocks.Call`, calling a noarg function
which returns an empty tuple. This function is an instance of
`building_blocks.CompiledComputation`.
"""
proto = tensorflow_computation_factory.create_empty_tuple()
compi... | string.ascii_lowercase
prefix = '_{}'.format(''.join(random.choice(characters) for _ in range(3)))
index = 1
while True:
yield '{}{}'.format(prefix, index)
index += 1
def create_compiled_empty_tuple() -> building_blocks.Call:
| 64 | 64 | 97 | 12 | 51 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_compiled_empty_tuple | create_compiled_empty_tuple | 61 | 71 | 61 | 61 | 94b77beea2fdec115dd6c0d0d90af55ed0a1ffd2 | bigcode/the-stack | train |
016fa6716849645bd12b6544 | train | function | def create_federated_secure_sum(
value: building_blocks.ComputationBuildingBlock,
bitwidth: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
r"""Creates a called secure sum.
Call
/ \
Intrinsic [Comp, Comp]
Args:
value: A `building_blocks.ComputationBu... | def create_federated_secure_sum(
value: building_blocks.ComputationBuildingBlock,
bitwidth: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
| r"""Creates a called secure sum.
Call
/ \
Intrinsic [Comp, Comp]
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
bitwidth: A `building_blocks.ComputationBuildingBlock` to use as the
bitwidth value.
Returns:
A `building_blocks.Cal... | .Intrinsic(intrinsic_defs.FEDERATED_REDUCE.uri,
intrinsic_type)
values = building_blocks.Struct((value, zero, op))
return building_blocks.Call(intrinsic, values)
def create_federated_secure_sum(
value: building_blocks.ComputationBuildingBlock,
bitwidth: building_block... | 78 | 78 | 263 | 34 | 44 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_secure_sum | create_federated_secure_sum | 1,013 | 1,044 | 1,013 | 1,015 | bbe863878160092046e91f38a24bdc0254227ca4 | bigcode/the-stack | train |
75f32c25fa0e8c9dad5ae100 | train | function | def create_federated_unzip(
value: building_blocks.ComputationBuildingBlock) -> building_blocks.Block:
r"""Creates a tuple of called federated maps or applies.
Block
/ \
[value=Comp] Tuple
|
[Call, Call... | def create_federated_unzip(
value: building_blocks.ComputationBuildingBlock) -> building_blocks.Block:
| r"""Creates a tuple of called federated maps or applies.
Block
/ \
[value=Comp] Tuple
|
[Call, Call, ...]
/ \ / \
Intrinsic Tuple ... | TypeError: If any of the types do not match.
"""
py_typecheck.check_type(value, building_blocks.ComputationBuildingBlock)
result_type = computation_types.FederatedType(value.type_signature.member,
placement_literals.SERVER)
intrinsic_type = computation_types.Func... | 131 | 131 | 438 | 23 | 108 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_unzip | create_federated_unzip | 1,074 | 1,124 | 1,074 | 1,075 | 4f9a2708213b9a26fba4c4282827cceac1634894 | bigcode/the-stack | train |
26d2d2d0d95d6d0725f90d28 | train | function | def create_sequence_map(
fn: building_blocks.ComputationBuildingBlock,
arg: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
r"""Creates a called sequence map.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp]
Args:
fn: A `buil... | def create_sequence_map(
fn: building_blocks.ComputationBuildingBlock,
arg: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
| r"""Creates a called sequence map.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp]
Args:
fn: A `building_blocks.ComputationBuildingBlock` to use as the function.
arg: A `building_blocks.ComputationBuildingBlock` to use as the argument.
Returns:... | _equal)
intrinsic_type = computation_types.FunctionType(parameter_type, result_type)
intrinsic = building_blocks.Intrinsic(uri, intrinsic_type)
return building_blocks.Call(intrinsic, value)
def create_sequence_map(
fn: building_blocks.ComputationBuildingBlock,
arg: building_blocks.ComputationBuildingBlock... | 70 | 70 | 235 | 30 | 40 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_sequence_map | create_sequence_map | 1,527 | 1,556 | 1,527 | 1,529 | f83a1b559939fcb4f12e59293d7142c9a0dfe797 | bigcode/the-stack | train |
1187b2c8d11b7da2418e5d9f | train | function | def create_compiled_identity(
type_signature: computation_types.Type,
name: Optional[str] = None) -> building_blocks.CompiledComputation:
"""Creates CompiledComputation representing identity function.
Args:
type_signature: A `computation_types.Type`.
name: An optional string name to use as the name... | def create_compiled_identity(
type_signature: computation_types.Type,
name: Optional[str] = None) -> building_blocks.CompiledComputation:
| """Creates CompiledComputation representing identity function.
Args:
type_signature: A `computation_types.Type`.
name: An optional string name to use as the name of the computation.
Returns:
An instance of `building_blocks.CompiledComputation`
representing the identity function taking an argumen... | """
proto = tensorflow_computation_factory.create_empty_tuple()
compiled = building_blocks.CompiledComputation(proto)
return building_blocks.Call(compiled, None)
def create_compiled_identity(
type_signature: computation_types.Type,
name: Optional[str] = None) -> building_blocks.CompiledComputation:
| 64 | 64 | 160 | 31 | 33 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_compiled_identity | create_compiled_identity | 74 | 93 | 74 | 76 | 458be40d9be5084a1edfa39f34a776f5c6b1676e | bigcode/the-stack | train |
0a123260d14789d9ee1a5733 | train | function | def create_computation_appending(
comp1: building_blocks.ComputationBuildingBlock,
comp2: building_blocks.ComputationBuildingBlock):
r"""Returns a block appending `comp2` to `comp1`.
Block
/ \
[comps=Tuple] Tuple
| |
[Comp, Comp] [Sel(0)... | def create_computation_appending(
comp1: building_blocks.ComputationBuildingBlock,
comp2: building_blocks.ComputationBuildingBlock):
| r"""Returns a block appending `comp2` to `comp1`.
Block
/ \
[comps=Tuple] Tuple
| |
[Comp, Comp] [Sel(0), ..., Sel(0), Sel(1)]
\ \ \
Sel(0) Sel(n) Ref(co... | int):
selected = building_blocks.Selection(apply_input, index=key)
else:
elems = anonymous_tuple.to_elements(comp.type_signature.member)
index_range = range(*key.indices(len(elems)))
elem_list = []
for k in index_range:
elem_list.append(
(elems[k][0], building_blocks.Selection(app... | 140 | 140 | 469 | 29 | 110 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_computation_appending | create_computation_appending | 584 | 634 | 584 | 586 | d745326b8630df4bab8eb58da027af69cbc67248 | bigcode/the-stack | train |
cc02f4a1a4c73e493e91e29a | train | function | def _check_generic_operator_type(type_spec):
"""Checks that `type_spec` can be the signature of args to a generic op."""
if not type_analysis.contains_only(
type_spec, lambda t: t.is_federated() or t.is_struct() or t.is_tensor()):
raise TypeError(
'Generic operators are only implemented for argume... | def _check_generic_operator_type(type_spec):
| """Checks that `type_spec` can be the signature of args to a generic op."""
if not type_analysis.contains_only(
type_spec, lambda t: t.is_federated() or t.is_struct() or t.is_tensor()):
raise TypeError(
'Generic operators are only implemented for arguments both containing '
'only federated... | .Selection(ref, index=row)
sel_column = building_blocks.Selection(sel_row, index=column)
columns.append(sel_column)
tup = building_blocks.Struct(columns)
rows.append(tup)
tup = building_blocks.Struct(rows)
if not comp.is_reference():
return building_blocks.Block(((ref.name, comp),), tup)
e... | 85 | 85 | 285 | 9 | 75 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | _check_generic_operator_type | _check_generic_operator_type | 1,812 | 1,832 | 1,812 | 1,812 | 68378eabfa3d7c8d70327986bc9265488985afab | bigcode/the-stack | train |
cd07c77c849a0bae71c81220 | train | function | def create_named_tuple_setattr_lambda(
named_tuple_signature: computation_types.StructType, name: str,
value_comp: building_blocks.ComputationBuildingBlock
) -> building_blocks.Lambda:
"""Creates a building block for replacing one attribute in a named tuple.
Returns an instance of `building_blocks.Lambda` ... | def create_named_tuple_setattr_lambda(
named_tuple_signature: computation_types.StructType, name: str,
value_comp: building_blocks.ComputationBuildingBlock
) -> building_blocks.Lambda:
| """Creates a building block for replacing one attribute in a named tuple.
Returns an instance of `building_blocks.Lambda` which takes an
argument of type `computation_types.StructType` and returns a
`building_blocks.Struct` which contains all the same elements as
the argument, except the attribute `name` now... | ederated_comp` with its `member`'s `name` attribute set to
`value`.
"""
py_typecheck.check_type(federated_comp,
building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(name, str)
py_typecheck.check_type(value_comp, building_blocks.ComputationBuildingBlock)
py_typecheck.... | 201 | 201 | 671 | 40 | 161 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_named_tuple_setattr_lambda | create_named_tuple_setattr_lambda | 440 | 501 | 440 | 443 | e48b0646b524b5358b17b0bae22fb4cbffc5cb64 | bigcode/the-stack | train |
81ae1d612df859b82774a00d | train | function | def create_federated_getattr_call(arg: building_blocks.ComputationBuildingBlock,
name: str) -> building_blocks.Call:
"""Creates computation building block passing getattr to federated value.
Args:
arg: Instance of `building_blocks.ComputationBuildingBlock` of
`computatio... | def create_federated_getattr_call(arg: building_blocks.ComputationBuildingBlock,
name: str) -> building_blocks.Call:
| """Creates computation building block passing getattr to federated value.
Args:
arg: Instance of `building_blocks.ComputationBuildingBlock` of
`computation_types.FederatedType` with member of type
`computation_types.StructType` from which we wish to pick out item
`name`.
name: String name... | atedType)
py_typecheck.check_type(arg.type_signature.member,
computation_types.StructType)
getitem_comp = create_federated_getitem_comp(arg, idx)
return create_federated_map_or_apply(getitem_comp, arg)
def create_federated_getattr_call(arg: building_blocks.ComputationBuildingBlock,
... | 78 | 78 | 261 | 27 | 51 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_getattr_call | create_federated_getattr_call | 370 | 394 | 370 | 371 | bcc39c489d5075c9f8110376449c720974c6a2ca | bigcode/the-stack | train |
32291318d872421b6b000cb1 | train | function | def create_named_federated_tuple(
tuple_to_name: building_blocks.ComputationBuildingBlock,
names_to_add: Sequence[str],
container_type=None,
) -> building_blocks.ComputationBuildingBlock:
"""Name tuple elements with names in `names_to_add`.
Certain intrinsics, e.g. `federated_zip`, only accept unnamed ... | def create_named_federated_tuple(
tuple_to_name: building_blocks.ComputationBuildingBlock,
names_to_add: Sequence[str],
container_type=None,
) -> building_blocks.ComputationBuildingBlock:
| """Name tuple elements with names in `names_to_add`.
Certain intrinsics, e.g. `federated_zip`, only accept unnamed tuples as
arguments, and can only produce unnamed tuples as their outputs. This is not
necessarily desirable behavior, as it necessitates dropping any names that
exist before the zip. This funct... | tuple_type_to_name`; here, `names_to_add` has '
'{} elements and `tuple_type_to_name` has {}.'.format(
len(names_to_add), len(tuple_type_to_name)))
naming_lambda_arg = building_blocks.Reference('x', tuple_type_to_name)
def _create_struct_element(i):
return (names_to_add[i],
buil... | 175 | 175 | 585 | 42 | 133 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_named_federated_tuple | create_named_federated_tuple | 1,662 | 1,715 | 1,662 | 1,666 | ac333ffb8bcc465c5d58ec121ae7c3a02d7f358f | bigcode/the-stack | train |
b13cf2accafd6dfa485e8824 | train | function | def _prepend_to_paths(paths: List[List[int]], element: int):
for path in paths:
path.insert(0, element)
| def _prepend_to_paths(paths: List[List[int]], element: int):
| for path in paths:
path.insert(0, element)
| ipped_tree_ref.name,
zipped_tree_ref.type_signature,
flattened_tree)
unnamed_zip = map_fn(flatten_fn, zipped_block)
return create_named_federated_tuple(unnamed_zip, names_to_add, container_type)
def _prepend_to_paths(paths: List[List[... | 64 | 64 | 29 | 15 | 49 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | _prepend_to_paths | _prepend_to_paths | 1,238 | 1,240 | 1,238 | 1,238 | 2ec3b9f96ba0075df262cc408ff429f0cd7a3815 | bigcode/the-stack | train |
0fc952b111a1d2a845428548 | train | function | def create_sequence_reduce(
value: building_blocks.ComputationBuildingBlock,
zero: building_blocks.ComputationBuildingBlock,
op: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
r"""Creates a called sequence reduce.
Call
/ \
Intrinsic Tuple
... | def create_sequence_reduce(
value: building_blocks.ComputationBuildingBlock,
zero: building_blocks.ComputationBuildingBlock,
op: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
| r"""Creates a called sequence reduce.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp, Comp]
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
zero: A `building_blocks.ComputationBuildingBlock` to use as the initial
... | _type)
intrinsic = building_blocks.Intrinsic(intrinsic_defs.SEQUENCE_MAP.uri,
intrinsic_type)
values = building_blocks.Struct((fn, arg))
return building_blocks.Call(intrinsic, values)
def create_sequence_reduce(
value: building_blocks.ComputationBuildingBlock,
zero:... | 85 | 85 | 286 | 40 | 45 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_sequence_reduce | create_sequence_reduce | 1,559 | 1,594 | 1,559 | 1,562 | d3990867848b0a376cc61feef41e5ffe378b5d31 | bigcode/the-stack | train |
92d201aea59da38cf5cf70a2 | train | function | def create_federated_getitem_call(
arg: building_blocks.ComputationBuildingBlock,
idx: Union[int, slice]) -> building_blocks.Call:
"""Creates computation building block passing getitem to federated value.
Args:
arg: Instance of `building_blocks.ComputationBuildingBlock` of
`computation_types.Fede... | def create_federated_getitem_call(
arg: building_blocks.ComputationBuildingBlock,
idx: Union[int, slice]) -> building_blocks.Call:
| """Creates computation building block passing getitem to federated value.
Args:
arg: Instance of `building_blocks.ComputationBuildingBlock` of
`computation_types.FederatedType` with member of type
`computation_types.StructType` from which we wish to pick out item
`idx`.
idx: Index, instan... | by
`type_analysis.is_generic_op_compatible_type`, or `operator` is not
callable.
"""
proto = tensorflow_computation_factory.create_binary_operator(
operator, operand_type)
return building_blocks.CompiledComputation(proto)
def create_federated_getitem_call(
arg: building_blocks.ComputationBuildi... | 84 | 84 | 283 | 32 | 52 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_getitem_call | create_federated_getitem_call | 342 | 367 | 342 | 344 | 2b299448b2bddd0f83b8802426a5495c9d6cfedb | bigcode/the-stack | train |
bbd099edeb782236ab74cf1e | train | function | def unique_name_generator(comp: building_blocks.ComputationBuildingBlock,
prefix: str = '_var') -> Iterator[str]:
"""Yields a new unique name that does not exist in `comp`.
Args:
comp: The compuation building block to use as a reference.
prefix: The prefix to use when generating u... | def unique_name_generator(comp: building_blocks.ComputationBuildingBlock,
prefix: str = '_var') -> Iterator[str]:
| """Yields a new unique name that does not exist in `comp`.
Args:
comp: The compuation building block to use as a reference.
prefix: The prefix to use when generating unique names. If `prefix` is
`None` or if `comp` contains any name with this prefix, then a unique
prefix will be generated from ... | _federated.python.core.impl.types import type_conversions
from tensorflow_federated.python.core.impl.types import type_serialization
from tensorflow_federated.python.core.impl.utils import tensorflow_utils
def unique_name_generator(comp: building_blocks.ComputationBuildingBlock,
prefix: str = ... | 64 | 64 | 205 | 25 | 38 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | unique_name_generator | unique_name_generator | 38 | 58 | 38 | 39 | 1c35779b9dae5e199b018b1de8b560ecf7442c18 | bigcode/the-stack | train |
1431d7cb1062d5e0b280e0e7 | train | function | def create_federated_mean(
value: building_blocks.ComputationBuildingBlock,
weight: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
r"""Creates a called federated mean.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp]
Args:
v... | def create_federated_mean(
value: building_blocks.ComputationBuildingBlock,
weight: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
| r"""Creates a called federated mean.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp]
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
weight: A `building_blocks.ComputationBuildingBlock` to use as the weight or
... | _equal:
return create_federated_map_all_equal(fn, arg)
else:
return create_federated_map(fn, arg)
elif arg.type_signature.placement is placement_literals.SERVER:
return create_federated_apply(fn, arg)
else:
raise TypeError('Unsupported placement {}.'.format(
arg.type_signature.placem... | 105 | 105 | 350 | 32 | 73 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_mean | create_federated_mean | 928 | 970 | 928 | 930 | 0480774733dfc07b446d1b65335f48107bfebf04 | bigcode/the-stack | train |
7fae8ffe02bc6a29d65211b4 | train | function | def create_sequence_sum(
value: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
r"""Creates a called sequence sum.
Call
/ \
Intrinsic Comp
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
Returns:
A `building_blocks.C... | def create_sequence_sum(
value: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
| r"""Creates a called sequence sum.
Call
/ \
Intrinsic Comp
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
Returns:
A `building_blocks.Call`.
Raises:
TypeError: If any of the types do not match.
"""
py_typecheck.check_type(value... | building_blocks.Intrinsic(intrinsic_defs.SEQUENCE_REDUCE.uri,
intrinsic_type)
values = building_blocks.Struct((value, zero, op))
return building_blocks.Call(intrinsic, values)
def create_sequence_sum(
value: building_blocks.ComputationBuildingBlock) -> building_blocks.Ca... | 64 | 64 | 156 | 20 | 44 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_sequence_sum | create_sequence_sum | 1,597 | 1,619 | 1,597 | 1,598 | 75ae5d04f1f595805622d2813da6db2d24af5329 | bigcode/the-stack | train |
a1c6ea60189292d262abb088 | train | function | def create_zip(
comp: building_blocks.ComputationBuildingBlock) -> building_blocks.Block:
r"""Returns a computation which zips `comp`.
Returns the following computation where `x` is `comp` unless `comp` is a
Reference, in which case the Reference is inlined and the Tuple is returned.
Block
... | def create_zip(
comp: building_blocks.ComputationBuildingBlock) -> building_blocks.Block:
| r"""Returns a computation which zips `comp`.
Returns the following computation where `x` is `comp` unless `comp` is a
Reference, in which case the Reference is inlined and the Tuple is returned.
Block
/ \
[comp=x] Tuple
|
[Tuple, ... | names` attached to
the `type_signature` of those elements.
Raises:
TypeError: If the types do not match.
"""
py_typecheck.check_type(names, (list, tuple))
if not all(isinstance(x, (str, type(None))) for x in names):
raise TypeError('Expected `names` containing only instances of `str` or '
... | 165 | 165 | 550 | 19 | 146 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_zip | create_zip | 1,751 | 1,809 | 1,751 | 1,752 | 196149bc844287febaeb3a21a656fd8eea088bee | bigcode/the-stack | train |
6898e3441ad68884c3ee017d | train | function | def create_federated_reduce(
value: building_blocks.ComputationBuildingBlock,
zero: building_blocks.ComputationBuildingBlock,
op: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
r"""Creates a called federated reduce.
Call
/ \
Intrinsic Tuple
... | def create_federated_reduce(
value: building_blocks.ComputationBuildingBlock,
zero: building_blocks.ComputationBuildingBlock,
op: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
| r"""Creates a called federated reduce.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp, Comp]
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
zero: A `building_blocks.ComputationBuildingBlock` to use as the initial
... | (
type_conversions.type_to_non_all_equal(value.type_signature),
result_type)
intrinsic = building_blocks.Intrinsic(intrinsic_defs.FEDERATED_MEAN.uri,
intrinsic_type)
return building_blocks.Call(intrinsic, value)
def create_federated_reduce(
value: bu... | 95 | 95 | 317 | 42 | 53 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_reduce | create_federated_reduce | 973 | 1,010 | 973 | 976 | 26271a8413afd754c4df57d275782bd3db15905f | bigcode/the-stack | train |
9ceb362e591809091df33ef1 | train | function | def create_tensorflow_constant(type_spec: computation_types.Type,
scalar_value: Union[int, float, str],
name=None) -> building_blocks.Call:
"""Creates called graph returning constant `scalar_value` of type `type_spec`.
`scalar_value` must be a scalar, a... | def create_tensorflow_constant(type_spec: computation_types.Type,
scalar_value: Union[int, float, str],
name=None) -> building_blocks.Call:
| """Creates called graph returning constant `scalar_value` of type `type_spec`.
`scalar_value` must be a scalar, and cannot be a float if any of the tensor
leaves of `type_spec` contain an integer data type. `type_spec` must contain
only named tuples and tensor types, but these can be arbitrarily nested.
Arg... | .Computation(
type=serialized_function_type,
tensorflow=pb.TensorFlow(
graph_def=serialization_utils.pack_graph_def(graph.as_graph_def()),
parameter=parameter_binding,
result=result_binding))
return building_blocks.CompiledComputation(proto)
def create_tensorflow_constant(typ... | 84 | 84 | 283 | 32 | 52 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_tensorflow_constant | create_tensorflow_constant | 218 | 245 | 218 | 220 | e18687096ca6ffb158cdb558e911b2a06b13fef5 | bigcode/the-stack | train |
43d30f875f15072d3822f37a | train | function | def create_generic_constant(
type_spec: Optional[computation_types.Type],
scalar_value: Union[int,
float]) -> building_blocks.ComputationBuildingBlock:
"""Creates constant for a combination of federated, tuple and tensor types.
Args:
type_spec: A `computation_types.Type` contain... | def create_generic_constant(
type_spec: Optional[computation_types.Type],
scalar_value: Union[int,
float]) -> building_blocks.ComputationBuildingBlock:
| """Creates constant for a combination of federated, tuple and tensor types.
Args:
type_spec: A `computation_types.Type` containing only federated, tuple or
tensor types, or `None` to use to construct a generic constant.
scalar_value: The scalar value we wish this constant to have.
Returns:
Ins... | ))
return building_blocks.Struct(return_tuple,
type_signature.python_container), index
else:
# This shouldn't be possible since the structure was already traversed
# above.
raise TypeError('Only type signatures consisting of structures of '
... | 203 | 203 | 678 | 34 | 169 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_generic_constant | create_generic_constant | 1,400 | 1,464 | 1,400 | 1,403 | 36587885d5868cc553dcf02d061b52c7c3fea58e | bigcode/the-stack | train |
853aa799e7e4ae950a2f5e26 | train | function | def create_federated_getitem_comp(
comp: building_blocks.ComputationBuildingBlock,
key: Union[int, slice]) -> building_blocks.Lambda:
"""Function to construct computation for `federated_apply` of `__getitem__`.
Creates a `building_blocks.ComputationBuildingBlock`
which selects `key` from its argument, of... | def create_federated_getitem_comp(
comp: building_blocks.ComputationBuildingBlock,
key: Union[int, slice]) -> building_blocks.Lambda:
| """Function to construct computation for `federated_apply` of `__getitem__`.
Creates a `building_blocks.ComputationBuildingBlock`
which selects `key` from its argument, of type `comp.type_signature.member`,
of type `computation_types.StructType`.
Args:
comp: Instance of `building_blocks.ComputationBuild... | in element_names:
raise ValueError(
'The federated value has no element of name `{}`. Value: {}'.format(
name, comp.formatted_representation()))
apply_input = building_blocks.Reference('x', comp.type_signature.member)
selected = building_blocks.Selection(apply_input, name=name)
apply_lamb... | 122 | 122 | 408 | 33 | 88 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_getitem_comp | create_federated_getitem_comp | 542 | 581 | 542 | 544 | 6b27f53b6777d8e805e7e90a4aef60c638fca11c | bigcode/the-stack | train |
16f875ea6c3c18d56db46db1 | train | function | def create_federated_map(
fn: building_blocks.ComputationBuildingBlock,
arg: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
r"""Creates a called federated map.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp]
Args:
fn: A `bu... | def create_federated_map(
fn: building_blocks.ComputationBuildingBlock,
arg: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
| r"""Creates a called federated map.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp]
Args:
fn: A `building_blocks.ComputationBuildingBlock` to use as the function.
arg: A `building_blocks.ComputationBuildingBlock` to use as the argument.
Returns... | placement, all_equal=all_equal)
intrinsic_type = computation_types.FunctionType(fn.type_signature,
result_type)
intrinsic = building_blocks.Intrinsic(uri, intrinsic_type)
return building_blocks.Call(intrinsic, fn)
def create_federated_map(
fn: building_blocks... | 80 | 80 | 268 | 32 | 48 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_map | create_federated_map | 820 | 852 | 820 | 822 | 49ee9b49d2fd65d62792cea4c5e57807d8e63b54 | bigcode/the-stack | train |
92b27cdf0655e1546debc8f5 | train | function | def apply_binary_operator_with_upcast(
arg: building_blocks.ComputationBuildingBlock,
operator: Callable[[Any, Any], Any]) -> building_blocks.Call:
"""Constructs result of applying `operator` to `arg` upcasting if appropriate.
Notice `arg` here must be of federated type, with a named tuple member of
leng... | def apply_binary_operator_with_upcast(
arg: building_blocks.ComputationBuildingBlock,
operator: Callable[[Any, Any], Any]) -> building_blocks.Call:
| """Constructs result of applying `operator` to `arg` upcasting if appropriate.
Notice `arg` here must be of federated type, with a named tuple member of
length 2, or a named tuple type of length 2. If the named tuple type of `arg`
satisfies certain conditions (that is, there is only a single tensor dtype in
... | first, as explained in `apply_binary_operator_with_upcast`, and
both containing only tuples and tensors in their type tree.
operator: Callable defining the operator.
Returns:
A `building_blocks.CompiledComputation` encapsulating a function which
upcasts the second element of its argument and appli... | 173 | 173 | 578 | 34 | 138 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | apply_binary_operator_with_upcast | apply_binary_operator_with_upcast | 1,864 | 1,917 | 1,864 | 1,866 | 78ce1b5c9d17f7f229c9c34df32650c5dde8abd4 | bigcode/the-stack | train |
91f0e302df27cecf8ebda4a6 | train | function | def create_compiled_input_replication(
type_signature: computation_types.Type,
n_replicas: int) -> building_blocks.CompiledComputation:
"""Creates a compiled computation which replicates its argument.
Args:
type_signature: A `computation_types.Type`, the type of the parameter of the
constructed c... | def create_compiled_input_replication(
type_signature: computation_types.Type,
n_replicas: int) -> building_blocks.CompiledComputation:
| """Creates a compiled computation which replicates its argument.
Args:
type_signature: A `computation_types.Type`, the type of the parameter of the
constructed computation.
n_replicas: Integer, the number of times the argument is intended to be
replicated.
Returns:
An instance of `buildi... | _constant(
scalar_value, type_spec)
compiled = building_blocks.CompiledComputation(proto, name)
return building_blocks.Call(compiled, None)
def create_compiled_input_replication(
type_signature: computation_types.Type,
n_replicas: int) -> building_blocks.CompiledComputation:
| 64 | 64 | 210 | 32 | 32 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_compiled_input_replication | create_compiled_input_replication | 248 | 270 | 248 | 250 | e862aae312e7ed412648fcd1165f78651ab0be31 | bigcode/the-stack | train |
f12a178f649372cb6df6ee69 | train | function | def _selection_from_path(
selected: building_blocks.ComputationBuildingBlock,
path: List[int],
) -> building_blocks.ComputationBuildingBlock:
for path_element in path:
selected = building_blocks.Selection(selected, index=path_element)
return selected
| def _selection_from_path(
selected: building_blocks.ComputationBuildingBlock,
path: List[int],
) -> building_blocks.ComputationBuildingBlock:
| for path_element in path:
selected = building_blocks.Selection(selected, index=path_element)
return selected
| _type(tree, building_blocks.ComputationBuildingBlock)
assert len(paths) == (end_index - start_index + 1)
return (tree, paths)
def _selection_from_path(
selected: building_blocks.ComputationBuildingBlock,
path: List[int],
) -> building_blocks.ComputationBuildingBlock:
| 64 | 64 | 55 | 31 | 33 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | _selection_from_path | _selection_from_path | 1,290 | 1,296 | 1,290 | 1,293 | b0245d813b7ad7c18550e7c823e83a2031098084 | bigcode/the-stack | train |
4a04c8c40a6a83241d242e13 | train | function | def create_federated_aggregate(
value: building_blocks.ComputationBuildingBlock,
zero: building_blocks.ComputationBuildingBlock,
accumulate: building_blocks.ComputationBuildingBlock,
merge: building_blocks.ComputationBuildingBlock,
report: building_blocks.ComputationBuildingBlock) -> building_blocks... | def create_federated_aggregate(
value: building_blocks.ComputationBuildingBlock,
zero: building_blocks.ComputationBuildingBlock,
accumulate: building_blocks.ComputationBuildingBlock,
merge: building_blocks.ComputationBuildingBlock,
report: building_blocks.ComputationBuildingBlock) -> building_blocks... | r"""Creates a called federated aggregate.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp, Comp, Comp, Comp]
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
zero: A `building_blocks.ComputationBuildingBlock` to use as... | .type_signature)
for index, (name, _) in enumerate(named_type_signatures):
sel = building_blocks.Selection(sel_0, index=index)
elements.append((name, sel))
sel_1 = building_blocks.Selection(ref, index=1)
elements.append((name2, sel_1))
result = building_blocks.Struct(elements)
symbols = ((ref.name, co... | 155 | 155 | 517 | 63 | 92 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_aggregate | create_federated_aggregate | 637 | 691 | 637 | 642 | 91e1d3036e01f3dcbf211ddbbccd97689cb9362c | bigcode/the-stack | train |
a4187fd5ec2b3702b473457a | train | function | def create_federated_sum(
value: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
r"""Creates a called federated sum.
Call
/ \
Intrinsic Comp
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
Returns:
A `building_blocks... | def create_federated_sum(
value: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
| r"""Creates a called federated sum.
Call
/ \
Intrinsic Comp
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
Returns:
A `building_blocks.Call`.
Raises:
TypeError: If any of the types do not match.
"""
py_typecheck.check_type(valu... | trinsic(intrinsic_defs.FEDERATED_SECURE_SUM.uri,
intrinsic_type)
values = building_blocks.Struct([value, bitwidth])
return building_blocks.Call(intrinsic, values)
def create_federated_sum(
value: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
| 64 | 64 | 188 | 22 | 42 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_sum | create_federated_sum | 1,047 | 1,071 | 1,047 | 1,048 | 07d83b20dc5e54361df05eb6afff3e8204b903dc | bigcode/the-stack | train |
9661bc748b1e8a67e207a494 | train | function | def create_federated_map_or_apply(
fn: building_blocks.ComputationBuildingBlock,
arg: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
r"""Creates a called federated map or apply depending on `arg`s placement.
Call
/ \
Intrinsic Tuple
|
... | def create_federated_map_or_apply(
fn: building_blocks.ComputationBuildingBlock,
arg: building_blocks.ComputationBuildingBlock) -> building_blocks.Call:
| r"""Creates a called federated map or apply depending on `arg`s placement.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp]
Args:
fn: A `building_blocks.ComputationBuildingBlock` to use as the function.
arg: A `building_blocks.ComputationBuildingBl... | = building_blocks.Intrinsic(
intrinsic_defs.FEDERATED_MAP_ALL_EQUAL.uri, intrinsic_type)
values = building_blocks.Struct((fn, arg))
return building_blocks.Call(intrinsic, values)
def create_federated_map_or_apply(
fn: building_blocks.ComputationBuildingBlock,
arg: building_blocks.ComputationBuildingB... | 78 | 78 | 262 | 34 | 44 | OpenMined/federated | tensorflow_federated/python/core/impl/compiler/building_block_factory.py | Python | create_federated_map_or_apply | create_federated_map_or_apply | 893 | 925 | 893 | 895 | 6c0d539bd76ec69b05dca6b237ef413781de1f92 | bigcode/the-stack | train |
06eae0375d42da6a403021eb | train | function | def test_fourtoonemultiplexer():
mp = FourToOneMultiplexer()
_str = mp.__str__()
in1 = Power()
in2 = Power()
in3 = Power()
in4 = Power()
sig1 = Power()
sig2 = Power()
in1.connect(mp.input_a)
in2.connect(mp.input_b)
in3.connect(mp.input_c)
in4.connect(mp.input_d)
s... | def test_fourtoonemultiplexer():
| mp = FourToOneMultiplexer()
_str = mp.__str__()
in1 = Power()
in2 = Power()
in3 = Power()
in4 = Power()
sig1 = Power()
sig2 = Power()
in1.connect(mp.input_a)
in2.connect(mp.input_b)
in3.connect(mp.input_c)
in4.connect(mp.input_d)
sig1.connect(mp.signal_a)
sig2... |
in2.on()
assert mp.output.value
sig.off()
assert mp.output.value
in1.off()
assert not mp.output.value
sig.on()
assert mp.output.value
in2.off()
assert not mp.output.value
def test_fourtoonemultiplexer():
| 64 | 64 | 208 | 8 | 55 | martinohanlon/PhilbinSS | philbinss/test_multiplexers.py | Python | test_fourtoonemultiplexer | test_fourtoonemultiplexer | 38 | 82 | 38 | 38 | f2b5d29875b221b045bf54107db419d647007ee0 | bigcode/the-stack | train |
cccd51a262df9bfb9b71cb9b | train | function | def run_tests():
test_twotoonemultiplexer()
test_fourtoonemultiplexer()
test_twotofourdecoder()
| def run_tests():
| test_twotoonemultiplexer()
test_fourtoonemultiplexer()
test_twotofourdecoder()
| .output_b.value
assert dc.output_c.value
assert not dc.output_d.value
in1.on()
in2.on()
assert not dc.output_a.value
assert not dc.output_b.value
assert not dc.output_c.value
assert dc.output_d.value
def run_tests():
| 64 | 64 | 29 | 4 | 59 | martinohanlon/PhilbinSS | philbinss/test_multiplexers.py | Python | run_tests | run_tests | 118 | 121 | 118 | 118 | 0318283d2a12685005a515b221f15a54269a4f56 | bigcode/the-stack | train |
9620aa2f91eb3cc08dd7313e | train | function | def test_twotoonemultiplexer():
mp = TwoToOneMultiplexer()
_str = mp.__str__()
in1 = Power()
in2 = Power()
sig = Power()
in1.connect(mp.input_a)
in2.connect(mp.input_b)
sig.connect(mp.signal)
#when the signal is off, output is a, when signal is on output is b
assert not m... | def test_twotoonemultiplexer():
| mp = TwoToOneMultiplexer()
_str = mp.__str__()
in1 = Power()
in2 = Power()
sig = Power()
in1.connect(mp.input_a)
in2.connect(mp.input_b)
sig.connect(mp.signal)
#when the signal is off, output is a, when signal is on output is b
assert not mp.output.value
in1.on()
... | from components import Power
from multiplexers import TwoToOneMultiplexer, FourToOneMultiplexer, TwoToFourDecoder
def test_twotoonemultiplexer():
| 35 | 64 | 169 | 9 | 25 | martinohanlon/PhilbinSS | philbinss/test_multiplexers.py | Python | test_twotoonemultiplexer | test_twotoonemultiplexer | 4 | 36 | 4 | 4 | 3b913737bcf12b515f77e6b738b29f664f36cef2 | bigcode/the-stack | train |
b1e9338cc6d5a32c10677e88 | train | function | def test_twotofourdecoder():
dc = TwoToFourDecoder()
_str = dc.__str__()
in1 = Power()
in2 = Power()
in1.connect(dc.input_a)
in2.connect(dc.input_b)
assert dc.output_a.value
assert not dc.output_b.value
assert not dc.output_c.value
assert not dc.output_d.value
in1.on()
... | def test_twotofourdecoder():
| dc = TwoToFourDecoder()
_str = dc.__str__()
in1 = Power()
in2 = Power()
in1.connect(dc.input_a)
in2.connect(dc.input_b)
assert dc.output_a.value
assert not dc.output_b.value
assert not dc.output_c.value
assert not dc.output_d.value
in1.on()
assert not dc.output_a.value... | 2.on()
assert not mp.output.value
in4.on()
assert mp.output.value
sig1.off()
assert not mp.output.value
in3.on()
assert mp.output.value
in3.off()
assert not mp.output.value
def test_twotofourdecoder():
| 64 | 64 | 201 | 8 | 55 | martinohanlon/PhilbinSS | philbinss/test_multiplexers.py | Python | test_twotofourdecoder | test_twotofourdecoder | 84 | 116 | 84 | 84 | 89b794a381de2773aae3df8cb0adcd4be7964ecb | bigcode/the-stack | train |
3faadef9cd3fa97265cf7002 | train | class | class PublisherCommandTests(TestCase):
"""
Tests for the publish command
"""
def test_command_line_should_raise_without_superuser(self):
raised = False
try:
com = publisher_publish.Command()
com.handle_noargs()
except CommandError:
raised = Tr... | class PublisherCommandTests(TestCase):
| """
Tests for the publish command
"""
def test_command_line_should_raise_without_superuser(self):
raised = False
try:
com = publisher_publish.Command()
com.handle_noargs()
except CommandError:
raised = True
self.assertTrue(raised)
... | # -*- coding: utf-8 -*-
from __future__ import with_statement
from djangocms_text_ckeditor.models import Text
from django.core.cache import cache
from django.core.management.base import CommandError
from django.core.urlresolvers import reverse
from cms.api import create_page, add_plugin, create_title
from cms.constan... | 204 | 256 | 1,246 | 7 | 196 | jrief/django-cms | cms/tests/publisher.py | Python | PublisherCommandTests | PublisherCommandTests | 23 | 162 | 23 | 23 | a5ea678e7d889e3111844fe1291c7058835092bf | bigcode/the-stack | train |
1feb71bfaee53b775a542401 | train | class | class PublishingTests(TestCase):
def create_page(self, title=None, **kwargs):
return create_page(title or self._testMethodName,
"nav_playground.html", "en", **kwargs)
def test_publish_home(self):
name = self._testMethodName
page = self.create_page(name, publis... | class PublishingTests(TestCase):
| def create_page(self, title=None, **kwargs):
return create_page(title or self._testMethodName,
"nav_playground.html", "en", **kwargs)
def test_publish_home(self):
name = self._testMethodName
page = self.create_page(name, published=False)
self.assertFal... | Now we don't expect it to raise, but we need to redirect IO
com = publisher_publish.Command()
com.handle_noargs()
lines = buffer.getvalue().split('\n') #NB: readlines() doesn't work
for line in lines:
if 'Total' in line:
pages_from_output = int(l... | 256 | 256 | 6,791 | 6 | 250 | jrief/django-cms | cms/tests/publisher.py | Python | PublishingTests | PublishingTests | 165 | 818 | 165 | 165 | 87d7506746be1b79552dac1529f0164fba401175 | bigcode/the-stack | train |
2741d46f26e20e14f5546011 | train | function | def makedirs(dirname):
if not os.path.exists(dirname):
os.makedirs(dirname)
| def makedirs(dirname):
| if not os.path.exists(dirname):
os.makedirs(dirname)
| = t # [:args.data_size] # (T)
batch_y = true_y # .reshape([1] + list(true_y.shape)) # (T, M, D)
return batch_y0.to(device), batch_t.to(device), batch_y.to(device)
def makedirs(dirname):
| 64 | 64 | 19 | 6 | 58 | zhaofeng-shu33/torchdiffeq | examples/ode_system_identify.py | Python | makedirs | makedirs | 51 | 53 | 51 | 51 | 87d2754c90c9abd07bcd5e8b827619a9a9cd9b03 | bigcode/the-stack | train |
fc6098395418fefff91e147d | train | function | def visualize(true_y, pred_y, odefunc, itr):
if args.viz:
ax_traj.cla()
ax_traj.set_title('Trajectories')
ax_traj.set_xlabel('t')
ax_traj.set_ylabel('x,y')
ax_traj.plot(t.cpu().numpy(), true_y.cpu().numpy()[:, 0, 0], t.cpu().numpy(), true_y.cpu().numpy()[:, 0, 1], 'g-')
... | def visualize(true_y, pred_y, odefunc, itr):
| if args.viz:
ax_traj.cla()
ax_traj.set_title('Trajectories')
ax_traj.set_xlabel('t')
ax_traj.set_ylabel('x,y')
ax_traj.plot(t.cpu().numpy(), true_y.cpu().numpy()[:, 0, 0], t.cpu().numpy(), true_y.cpu().numpy()[:, 0, 1], 'g-')
ax_traj.plot(t.cpu().numpy(), pred_y.cpu(... | batch_y = true_y # .reshape([1] + list(true_y.shape)) # (T, M, D)
return batch_y0.to(device), batch_t.to(device), batch_y.to(device)
def makedirs(dirname):
if not os.path.exists(dirname):
os.makedirs(dirname)
if args.viz:
makedirs('png')
import matplotlib.pyplot as plt
fig = plt.fig... | 164 | 164 | 547 | 14 | 150 | zhaofeng-shu33/torchdiffeq | examples/ode_system_identify.py | Python | visualize | visualize | 66 | 107 | 66 | 67 | f6d7f1bee0684b00f91d2cf6a9c99693126a53e8 | bigcode/the-stack | train |
6afdf32286e807755e526d84 | train | function | def get_batch():
# s = torch.from_numpy(np.random.choice(np.arange(args.data_size - args.batch_time, dtype=np.int64), args.batch_size, replace=False))
batch_y0 = true_y[0] # (M, D)
batch_t = t # [:args.data_size] # (T)
batch_y = true_y # .reshape([1] + list(true_y.shape)) # (T, M, D)
return batch... | def get_batch():
# s = torch.from_numpy(np.random.choice(np.arange(args.data_size - args.batch_time, dtype=np.int64), args.batch_size, replace=False))
| batch_y0 = true_y[0] # (M, D)
batch_t = t # [:args.data_size] # (T)
batch_y = true_y # .reshape([1] + list(true_y.shape)) # (T, M, D)
return batch_y0.to(device), batch_t.to(device), batch_y.to(device)
| * t * torch.sin(t))).T
# true_y = true_y.reshape([args.data_size, 1, 2])
def get_batch():
# s = torch.from_numpy(np.random.choice(np.arange(args.data_size - args.batch_time, dtype=np.int64), args.batch_size, replace=False))
| 64 | 64 | 114 | 36 | 28 | zhaofeng-shu33/torchdiffeq | examples/ode_system_identify.py | Python | get_batch | get_batch | 43 | 48 | 43 | 44 | 06424e5d1f2677e095e14b3638dc69612cae9f17 | bigcode/the-stack | train |
59b722e0fba22fdaa0443f5b | train | class | class ODEFunc(nn.Module):
def __init__(self):
super(ODEFunc, self).__init__()
self.variable = nn.Parameter((torch.randn(())))
def forward(self, t, y):
return torch.matmul(y, true_A) + self.variable * torch.stack((torch.cos(t), torch.sin(t)))
| class ODEFunc(nn.Module):
| def __init__(self):
super(ODEFunc, self).__init__()
self.variable = nn.Parameter((torch.randn(())))
def forward(self, t, y):
return torch.matmul(y, true_A) + self.variable * torch.stack((torch.cos(t), torch.sin(t)))
| black")
ax_vecfield.set_xlim(-2, 2)
ax_vecfield.set_ylim(-2, 2)
fig.tight_layout()
plt.savefig('png/{:03d}'.format(itr))
plt.draw()
plt.pause(0.001)
class ODEFunc(nn.Module):
| 64 | 64 | 68 | 7 | 57 | zhaofeng-shu33/torchdiffeq | examples/ode_system_identify.py | Python | ODEFunc | ODEFunc | 110 | 116 | 110 | 111 | 82980c741554008a39b7ec00e63f37f03f93c0ae | bigcode/the-stack | train |
46520235f26737221ac2b2fc | train | class | class RunningAverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self, momentum=0.99):
self.momentum = momentum
self.reset()
def reset(self):
self.val = None
self.avg = 0
def update(self, val):
if self.val is None:
... | class RunningAverageMeter(object):
| """Computes and stores the average and current value"""
def __init__(self, momentum=0.99):
self.momentum = momentum
self.reset()
def reset(self):
self.val = None
self.avg = 0
def update(self, val):
if self.val is None:
self.avg = val
else:
... | .Parameter((torch.randn(())))
def forward(self, t, y):
return torch.matmul(y, true_A) + self.variable * torch.stack((torch.cos(t), torch.sin(t)))
# def odefunc(t, y):
# t: place holder, y tensor
class RunningAverageMeter(object):
| 64 | 64 | 109 | 6 | 57 | zhaofeng-shu33/torchdiffeq | examples/ode_system_identify.py | Python | RunningAverageMeter | RunningAverageMeter | 122 | 138 | 122 | 122 | 291c9bc2cbf6100d311cf12a504d05d500e021d0 | bigcode/the-stack | train |
96b978dfa40091487cb49c36 | train | class | class CPointer(Type):
"""
Type class for pointers to other types.
"""
mutable = True
def __init__(self, dtype):
self.dtype = dtype
name = "%s*" % dtype
super(CPointer, self).__init__(name)
@property
def key(self):
return self.dtype
| class CPointer(Type):
| """
Type class for pointers to other types.
"""
mutable = True
def __init__(self, dtype):
self.dtype = dtype
name = "%s*" % dtype
super(CPointer, self).__init__(name)
@property
def key(self):
return self.dtype
| mutable = True
def __init__(self, dtype):
self.dtype = dtype
name = "memory-managed *%s" % dtype
super(MemInfoPointer, self).__init__(name)
@property
def key(self):
return self.dtype
class CPointer(Type):
| 64 | 64 | 72 | 5 | 58 | eric-erki/numba | numba/types/misc.py | Python | CPointer | CPointer | 131 | 144 | 131 | 131 | d1c1124b55a8374498669d6802dc702baf862a76 | bigcode/the-stack | train |
639a46691d4eaf433dc145e8 | train | class | class Const(Dummy):
"""
A compile-time constant, for (internal) use when a type is needed for
lookup.
"""
def __init__(self, value):
self.value = value
# We want to support constants of non-hashable values, therefore
# fall back on the value's id() if necessary.
try:... | class Const(Dummy):
| """
A compile-time constant, for (internal) use when a type is needed for
lookup.
"""
def __init__(self, value):
self.value = value
# We want to support constants of non-hashable values, therefore
# fall back on the value's id() if necessary.
try:
hash(va... | . This is used as a temporaray placeholder
during type inference in the hope that the type can be later refined.
"""
def is_precise(self):
return False
class RawPointer(Opaque):
"""
A raw pointer without any specific meaning.
"""
class Const(Dummy):
| 63 | 64 | 140 | 5 | 58 | eric-erki/numba | numba/types/misc.py | Python | Const | Const | 40 | 60 | 40 | 40 | 036837bfdd1486e19800c8a6cdf74af52c39558d | bigcode/the-stack | train |
4a98ef6f89ac8dc48b458324 | train | class | class EllipsisType(Opaque):
"""
The type for the Ellipsis singleton.
"""
| class EllipsisType(Opaque):
| """
The type for the Ellipsis singleton.
"""
| NoneType(Opaque):
"""
The type for None.
"""
def unify(self, typingctx, other):
"""
Turn anything to a Optional type;
"""
if isinstance(other, (Optional, NoneType)):
return other
return Optional(other)
class EllipsisType(Opaque):
| 64 | 64 | 20 | 7 | 57 | eric-erki/numba | numba/types/misc.py | Python | EllipsisType | EllipsisType | 246 | 249 | 246 | 246 | ea93df397fb70598a75672a268c24072fcdce0a7 | bigcode/the-stack | train |
922e74e184069ddea3ff4f4b | train | class | class VarArg(Type):
"""
Special type representing a variable number of arguments at the
end of a function's signature. Only used for signature matching,
not for actual values.
"""
def __init__(self, dtype):
self.dtype = dtype
super(VarArg, self).__init__("*%s" % dtype)
@pr... | class VarArg(Type):
| """
Special type representing a variable number of arguments at the
end of a function's signature. Only used for signature matching,
not for actual values.
"""
def __init__(self, dtype):
self.dtype = dtype
super(VarArg, self).__init__("*%s" % dtype)
@property
def key(s... | default value.
"""
def __init__(self, value):
self.value = value
super(Omitted, self).__init__("omitted(default=%r)" % (value,))
@property
def key(self):
return type(self.value), id(self.value)
class VarArg(Type):
| 64 | 64 | 88 | 5 | 59 | eric-erki/numba | numba/types/misc.py | Python | VarArg | VarArg | 77 | 90 | 77 | 77 | e46b7f18d27a6411a85beef663fcc661645cbc47 | bigcode/the-stack | train |
db02a0f86e13a1c61c7d5a74 | train | class | class ContextManager(Phantom):
"""
An overly-simple ContextManager type that cannot be materialized.
"""
def __init__(self, cm):
self.cm = cm
super(ContextManager, self).__init__("ContextManager({})".format(cm))
| class ContextManager(Phantom):
| """
An overly-simple ContextManager type that cannot be materialized.
"""
def __init__(self, cm):
self.cm = cm
super(ContextManager, self).__init__("ContextManager({})".format(cm))
| all the data fields of the class instance.
"""
def __init__(self, classtyp):
self.class_type = classtyp
name = "data.{0}".format(self.class_type.name)
super(ClassDataType, self).__init__(name)
class ContextManager(Phantom):
| 64 | 64 | 56 | 7 | 57 | eric-erki/numba | numba/types/misc.py | Python | ContextManager | ContextManager | 423 | 429 | 423 | 423 | b719dd2891f0c246dbf46b64e8f65e579413c78e | bigcode/the-stack | train |
43afcedcced0e27d8e68ffff | train | class | class ClassDataType(Type):
"""
Internal only.
Represents the data of the instance. The representation of
ClassInstanceType contains a pointer to a ClassDataType which represents
a C structure that contains all the data fields of the class instance.
"""
def __init__(self, classtyp):
... | class ClassDataType(Type):
| """
Internal only.
Represents the data of the instance. The representation of
ClassInstanceType contains a pointer to a ClassDataType which represents
a C structure that contains all the data fields of the class instance.
"""
def __init__(self, classtyp):
self.class_type = classtyp
... | if not isinstance(typ, Type):
raise TypeError("arg is not a Type; got: {0}".format(type(typ)))
self._define = typ
def unify(self, typingctx, other):
return typingctx.unify_pairs(self.get(), other)
class ClassDataType(Type):
| 64 | 64 | 103 | 6 | 58 | eric-erki/numba | numba/types/misc.py | Python | ClassDataType | ClassDataType | 410 | 420 | 410 | 410 | 9511f658266e04d4ea6a8819a19c191a3df65744 | bigcode/the-stack | train |
795e13861ae85f9c9e28f21a | train | class | class DeferredType(Type):
"""
Represents a type that will be defined later. It must be defined
before it is materialized (used in the compiler). Once defined, it
behaves exactly as the type it is defining.
"""
def __init__(self):
self._define = None
name = "{0}#{1}".format(type... | class DeferredType(Type):
| """
Represents a type that will be defined later. It must be defined
before it is materialized (used in the compiler). Once defined, it
behaves exactly as the type it is defining.
"""
def __init__(self):
self._define = None
name = "{0}#{1}".format(type(self).__name__, id(self))... | context, args, kws):
return self.ctor_template(context).apply(args, kws)
def get_call_signatures(self):
return (), True
def _specialize_template(self, basecls):
return type(basecls.__name__, (basecls,), dict(key=self))
class DeferredType(Type):
| 64 | 64 | 213 | 5 | 59 | eric-erki/numba | numba/types/misc.py | Python | DeferredType | DeferredType | 383 | 407 | 383 | 383 | 1df42ed8963f1aa36add57e3fe5d181abc1c14ad | bigcode/the-stack | train |
57582ee85b5f6dea7172402a | train | class | class ClassInstanceType(Type):
"""
The type of a jitted class *instance*. It will be the return-type
of the constructor of the class.
"""
mutable = True
name_prefix = "instance"
def __init__(self, class_type):
self.class_type = class_type
name = "{0}.{1}".format(self.name_p... | class ClassInstanceType(Type):
| """
The type of a jitted class *instance*. It will be the return-type
of the constructor of the class.
"""
mutable = True
name_prefix = "instance"
def __init__(self, class_type):
self.class_type = class_type
name = "{0}.{1}".format(self.name_prefix, self.class_type.name)
... | def __init__(self, name, members):
assert members in (2, 3)
self.members = members
self.has_step = members >= 3
super(SliceType, self).__init__(name)
@property
def key(self):
return self.members
class ClassInstanceType(Type):
| 68 | 68 | 227 | 6 | 61 | eric-erki/numba | numba/types/misc.py | Python | ClassInstanceType | ClassInstanceType | 306 | 347 | 306 | 306 | a628fc1c1046059f31b274a1ee2c0c740dacb517 | bigcode/the-stack | train |
8b6829511ac472f369d43cb8 | train | class | class ExceptionInstance(Phantom):
"""
The type of exception instances. *exc_class* should be the
exception class.
"""
def __init__(self, exc_class):
assert issubclass(exc_class, BaseException)
name = "%s(...)" % (exc_class.__name__,)
self.exc_class = exc_class
super... | class ExceptionInstance(Phantom):
| """
The type of exception instances. *exc_class* should be the
exception class.
"""
def __init__(self, exc_class):
assert issubclass(exc_class, BaseException)
name = "%s(...)" % (exc_class.__name__,)
self.exc_class = exc_class
super(ExceptionInstance, self).__init__... | _call_signatures()[0][0]
def get_call_signatures(self):
from .. import typing
return_type = ExceptionInstance(self.exc_class)
return [typing.signature(return_type)], False
@property
def key(self):
return self.exc_class
class ExceptionInstance(Phantom):
| 64 | 64 | 101 | 7 | 56 | eric-erki/numba | numba/types/misc.py | Python | ExceptionInstance | ExceptionInstance | 276 | 290 | 276 | 276 | 3f4d079f835a83751c5b8765d3d845dde38801f5 | bigcode/the-stack | train |
a5404a0e11d1f6546ba62841 | train | class | class MemInfoPointer(Type):
"""
Pointer to a Numba "meminfo" (i.e. the information for a managed
piece of memory).
"""
mutable = True
def __init__(self, dtype):
self.dtype = dtype
name = "memory-managed *%s" % dtype
super(MemInfoPointer, self).__init__(name)
@proper... | class MemInfoPointer(Type):
| """
Pointer to a Numba "meminfo" (i.e. the information for a managed
piece of memory).
"""
mutable = True
def __init__(self, dtype):
self.dtype = dtype
name = "memory-managed *%s" % dtype
super(MemInfoPointer, self).__init__(name)
@property
def key(self):
... | ):
def __init__(self, template):
self.template = template
cls = type(self)
super(Macro, self).__init__("%s(%s)" % (cls.__name__, template))
@property
def key(self):
return self.template
class MemInfoPointer(Type):
| 64 | 64 | 95 | 6 | 57 | eric-erki/numba | numba/types/misc.py | Python | MemInfoPointer | MemInfoPointer | 114 | 128 | 114 | 114 | 9fe6c7af44dddde317bad74ad0b7253fccf75217 | bigcode/the-stack | train |
1824a7729c993e91e4c64e08 | train | class | class PyObject(Dummy):
"""
A generic CPython object.
"""
def is_precise(self):
return False
| class PyObject(Dummy):
| """
A generic CPython object.
"""
def is_precise(self):
return False
| from __future__ import print_function, division, absolute_import
from .abstract import *
from .common import *
from ..typeconv import Conversion
class PyObject(Dummy):
| 36 | 64 | 28 | 6 | 29 | eric-erki/numba | numba/types/misc.py | Python | PyObject | PyObject | 8 | 14 | 8 | 8 | 4d1efb67fc25bd1eb7714d875933b9866dfd2695 | bigcode/the-stack | train |
8a8c85dcde2305099511b8de | train | class | class ClassType(Callable, Opaque):
"""
The type of the jitted class (not instance). When the type of a class
is called, its constructor is invoked.
"""
mutable = True
name_prefix = "jitclass"
instance_type_class = ClassInstanceType
def __init__(self, class_def, ctor_template_cls, struc... | class ClassType(Callable, Opaque):
| """
The type of the jitted class (not instance). When the type of a class
is called, its constructor is invoked.
"""
mutable = True
name_prefix = "jitclass"
instance_type_class = ClassInstanceType
def __init__(self, class_def, ctor_template_cls, struct, jitmethods,
jit... | (self):
return self.class_type.class_def.__name__
@property
def jitprops(self):
return self.class_type.jitprops
@property
def jitmethods(self):
return self.class_type.jitmethods
@property
def struct(self):
return self.class_type.struct
@property
def me... | 91 | 91 | 305 | 9 | 81 | eric-erki/numba | numba/types/misc.py | Python | ClassType | ClassType | 350 | 380 | 350 | 350 | 310fe053e22155a70bd5945c35cb952446ff1284 | bigcode/the-stack | train |
b9331607ad67d0d1af62de76 | train | class | class Omitted(Opaque):
"""
An omitted function argument with a default value.
"""
def __init__(self, value):
self.value = value
super(Omitted, self).__init__("omitted(default=%r)" % (value,))
@property
def key(self):
return type(self.value), id(self.value)
| class Omitted(Opaque):
| """
An omitted function argument with a default value.
"""
def __init__(self, value):
self.value = value
super(Omitted, self).__init__("omitted(default=%r)" % (value,))
@property
def key(self):
return type(self.value), id(self.value)
| except TypeError:
self._key = id(value)
else:
self._key = value
super(Const, self).__init__("const(%r)" % (value,))
@property
def key(self):
return type(self.value), self._key
class Omitted(Opaque):
| 64 | 64 | 74 | 6 | 57 | eric-erki/numba | numba/types/misc.py | Python | Omitted | Omitted | 63 | 74 | 63 | 63 | 1e3b2c64248d769475a0aa9cf220c896d25d074f | bigcode/the-stack | train |
be00ba4f645f0851dabb4e02 | train | class | class EphemeralPointer(CPointer):
"""
Type class for pointers which aren't guaranteed to last long - e.g.
stack-allocated slots. The data model serializes such pointers
by copying the data pointed to.
"""
| class EphemeralPointer(CPointer):
| """
Type class for pointers which aren't guaranteed to last long - e.g.
stack-allocated slots. The data model serializes such pointers
by copying the data pointed to.
"""
| .
"""
mutable = True
def __init__(self, dtype):
self.dtype = dtype
name = "%s*" % dtype
super(CPointer, self).__init__(name)
@property
def key(self):
return self.dtype
class EphemeralPointer(CPointer):
| 64 | 64 | 49 | 7 | 56 | eric-erki/numba | numba/types/misc.py | Python | EphemeralPointer | EphemeralPointer | 147 | 152 | 147 | 147 | bb7ebcb73c825edd5f789965549be2ad37376a55 | bigcode/the-stack | train |
7911a8436cdb9c79b007177e | train | class | class RawPointer(Opaque):
"""
A raw pointer without any specific meaning.
"""
| class RawPointer(Opaque):
| """
A raw pointer without any specific meaning.
"""
| """
class Undefined(Dummy):
"""
A type that is left imprecise. This is used as a temporaray placeholder
during type inference in the hope that the type can be later refined.
"""
def is_precise(self):
return False
class RawPointer(Opaque):
| 64 | 64 | 19 | 6 | 57 | eric-erki/numba | numba/types/misc.py | Python | RawPointer | RawPointer | 34 | 37 | 34 | 34 | f2a26b2cc7c0399c02e0dd314da172b2d471dcae | bigcode/the-stack | train |
a33e60be18b395f41ee25613 | train | class | class Phantom(Dummy):
"""
A type that cannot be materialized. A Phantom cannot be used as
argument or return type.
"""
| class Phantom(Dummy):
| """
A type that cannot be materialized. A Phantom cannot be used as
argument or return type.
"""
| from __future__ import print_function, division, absolute_import
from .abstract import *
from .common import *
from ..typeconv import Conversion
class PyObject(Dummy):
"""
A generic CPython object.
"""
def is_precise(self):
return False
class Phantom(Dummy):
| 63 | 64 | 32 | 5 | 57 | eric-erki/numba | numba/types/misc.py | Python | Phantom | Phantom | 17 | 21 | 17 | 17 | 594c0f8db47fb56053d5daafb69c52439c529268 | bigcode/the-stack | train |
3ea93881b49336952ab49068 | train | class | class ExceptionClass(Callable, Phantom):
"""
The type of exception classes (not instances).
"""
def __init__(self, exc_class):
assert issubclass(exc_class, BaseException)
name = "%s" % (exc_class.__name__)
self.exc_class = exc_class
super(ExceptionClass, self).__init__(n... | class ExceptionClass(Callable, Phantom):
| """
The type of exception classes (not instances).
"""
def __init__(self, exc_class):
assert issubclass(exc_class, BaseException)
name = "%s" % (exc_class.__name__)
self.exc_class = exc_class
super(ExceptionClass, self).__init__(name)
def get_call_type(self, context... | , other):
"""
Turn anything to a Optional type;
"""
if isinstance(other, (Optional, NoneType)):
return other
return Optional(other)
class EllipsisType(Opaque):
"""
The type for the Ellipsis singleton.
"""
class ExceptionClass(Callable, Phantom):
| 63 | 64 | 149 | 8 | 55 | eric-erki/numba | numba/types/misc.py | Python | ExceptionClass | ExceptionClass | 252 | 273 | 252 | 252 | 1587fc2b460f45d820746965bd3bb1956daab73d | bigcode/the-stack | train |
b92922fe10c2bd4222c2fa1c | train | class | class SliceType(Type):
def __init__(self, name, members):
assert members in (2, 3)
self.members = members
self.has_step = members >= 3
super(SliceType, self).__init__(name)
@property
def key(self):
return self.members
| class SliceType(Type):
| def __init__(self, name, members):
assert members in (2, 3)
self.members = members
self.has_step = members >= 3
super(SliceType, self).__init__(name)
@property
def key(self):
return self.members
| assert issubclass(exc_class, BaseException)
name = "%s(...)" % (exc_class.__name__,)
self.exc_class = exc_class
super(ExceptionInstance, self).__init__(name)
@property
def key(self):
return self.exc_class
class SliceType(Type):
| 64 | 64 | 68 | 5 | 58 | eric-erki/numba | numba/types/misc.py | Python | SliceType | SliceType | 293 | 303 | 293 | 294 | 67dceb3631d5a6c462322f8cd578eb7b479fb7dd | bigcode/the-stack | train |
8380740f12a55e18b5cf0a6d | train | class | class Object(Type):
# XXX unused?
mutable = True
def __init__(self, clsobj):
self.cls = clsobj
name = "Object(%s)" % clsobj.__name__
super(Object, self).__init__(name)
@property
def key(self):
return self.cls
| class Object(Type):
# XXX unused?
| mutable = True
def __init__(self, clsobj):
self.cls = clsobj
name = "Object(%s)" % clsobj.__name__
super(Object, self).__init__(name)
@property
def key(self):
return self.cls
| = dtype
self.count = count
name = "*%s[%d]" % (dtype, count)
super(EphemeralArray, self).__init__(name)
@property
def key(self):
return self.dtype, self.count
class Object(Type):
# XXX unused?
| 64 | 64 | 69 | 9 | 54 | eric-erki/numba | numba/types/misc.py | Python | Object | Object | 172 | 183 | 172 | 173 | f8057cb19066e072c1ccecb6e345106042c33928 | bigcode/the-stack | train |
03598c92649ed9168aeca0f8 | train | class | class Macro(Type):
def __init__(self, template):
self.template = template
cls = type(self)
super(Macro, self).__init__("%s(%s)" % (cls.__name__, template))
@property
def key(self):
return self.template
| class Macro(Type):
| def __init__(self, template):
self.template = template
cls = type(self)
super(Macro, self).__init__("%s(%s)" % (cls.__name__, template))
@property
def key(self):
return self.template
| return self.dtype
class Module(Dummy):
def __init__(self, pymod):
self.pymod = pymod
super(Module, self).__init__("Module(%s)" % pymod)
@property
def key(self):
return self.pymod
class Macro(Type):
| 64 | 64 | 61 | 4 | 59 | eric-erki/numba | numba/types/misc.py | Python | Macro | Macro | 103 | 111 | 103 | 103 | caf9cdbbb615f50a7f8d345f2ff200572162df6e | bigcode/the-stack | train |
2780e631a451f8066dc4aaa8 | train | class | class Undefined(Dummy):
"""
A type that is left imprecise. This is used as a temporaray placeholder
during type inference in the hope that the type can be later refined.
"""
def is_precise(self):
return False
| class Undefined(Dummy):
| """
A type that is left imprecise. This is used as a temporaray placeholder
during type inference in the hope that the type can be later refined.
"""
def is_precise(self):
return False
| Object(Dummy):
"""
A generic CPython object.
"""
def is_precise(self):
return False
class Phantom(Dummy):
"""
A type that cannot be materialized. A Phantom cannot be used as
argument or return type.
"""
class Undefined(Dummy):
| 63 | 64 | 55 | 5 | 58 | eric-erki/numba | numba/types/misc.py | Python | Undefined | Undefined | 24 | 31 | 24 | 24 | 7ec1bddd632398d702b3fe8f9f9a511846293296 | bigcode/the-stack | train |
25a243f30ec8d14c66bf0a47 | train | class | class NoneType(Opaque):
"""
The type for None.
"""
def unify(self, typingctx, other):
"""
Turn anything to a Optional type;
"""
if isinstance(other, (Optional, NoneType)):
return other
return Optional(other)
| class NoneType(Opaque):
| """
The type for None.
"""
def unify(self, typingctx, other):
"""
Turn anything to a Optional type;
"""
if isinstance(other, (Optional, NoneType)):
return other
return Optional(other)
| unified = typingctx.unify_pairs(self.type, other.type)
else:
unified = typingctx.unify_pairs(self.type, other)
if unified is not None:
if isinstance(unified, Optional):
return unified
else:
return Optional(unified)
class No... | 64 | 64 | 58 | 6 | 58 | eric-erki/numba | numba/types/misc.py | Python | NoneType | NoneType | 232 | 243 | 232 | 232 | 11d927431374ad60491427bf8dc21daef09251d3 | bigcode/the-stack | train |
d3bf54d929c30fd44f6d4868 | train | class | class Optional(Type):
"""
Type class for optional types, i.e. union { some type, None }
"""
def __init__(self, typ):
assert not isinstance(typ, (Optional, NoneType))
self.type = typ
name = "?%s" % typ
super(Optional, self).__init__(name)
@property
def key(self):... | class Optional(Type):
| """
Type class for optional types, i.e. union { some type, None }
"""
def __init__(self, typ):
assert not isinstance(typ, (Optional, NoneType))
self.type = typ
name = "?%s" % typ
super(Optional, self).__init__(name)
@property
def key(self):
return self.t... | @property
def key(self):
return self.dtype, self.count
class Object(Type):
# XXX unused?
mutable = True
def __init__(self, clsobj):
self.cls = clsobj
name = "Object(%s)" % clsobj.__name__
super(Object, self).__init__(name)
@property
def key(self):
ret... | 89 | 89 | 299 | 4 | 84 | eric-erki/numba | numba/types/misc.py | Python | Optional | Optional | 186 | 229 | 186 | 186 | 825a551366e588f497dd8a0e4171075c8ed19028 | bigcode/the-stack | train |
469dc87fa820d9bb35e7bc0c | train | class | class EphemeralArray(Type):
"""
Similar to EphemeralPointer, but pointing to an array of elements,
rather than a single one. The array size must be known at compile-time.
"""
def __init__(self, dtype, count):
self.dtype = dtype
self.count = count
name = "*%s[%d]" % (dtype, ... | class EphemeralArray(Type):
| """
Similar to EphemeralPointer, but pointing to an array of elements,
rather than a single one. The array size must be known at compile-time.
"""
def __init__(self, dtype, count):
self.dtype = dtype
self.count = count
name = "*%s[%d]" % (dtype, count)
super(Ephemer... | key(self):
return self.dtype
class EphemeralPointer(CPointer):
"""
Type class for pointers which aren't guaranteed to last long - e.g.
stack-allocated slots. The data model serializes such pointers
by copying the data pointed to.
"""
class EphemeralArray(Type):
| 63 | 64 | 112 | 6 | 57 | eric-erki/numba | numba/types/misc.py | Python | EphemeralArray | EphemeralArray | 155 | 169 | 155 | 155 | d49b1b0d2250acff7006730896217c3cc9e82b2d | bigcode/the-stack | train |
ce6a42bd6f62aedea67cda8e | train | class | class Module(Dummy):
def __init__(self, pymod):
self.pymod = pymod
super(Module, self).__init__("Module(%s)" % pymod)
@property
def key(self):
return self.pymod
| class Module(Dummy):
| def __init__(self, pymod):
self.pymod = pymod
super(Module, self).__init__("Module(%s)" % pymod)
@property
def key(self):
return self.pymod
| used for signature matching,
not for actual values.
"""
def __init__(self, dtype):
self.dtype = dtype
super(VarArg, self).__init__("*%s" % dtype)
@property
def key(self):
return self.dtype
class Module(Dummy):
| 64 | 64 | 56 | 5 | 58 | eric-erki/numba | numba/types/misc.py | Python | Module | Module | 93 | 100 | 93 | 93 | 31d271146de4c81cf46cfb1540b700a4faa23cc5 | bigcode/the-stack | train |
be50ec07e4ba4fbf8bd929ed | train | class | class Accessory(object):
"""Implementation of the 'Accessory' model.
TODO: type model description here.
Attributes:
asin (string): TODO: type description here.
title (string): TODO: type description here.
"""
# Create a mapping from Model property names to API property names
... | class Accessory(object):
| """Implementation of the 'Accessory' model.
TODO: type model description here.
Attributes:
asin (string): TODO: type description here.
title (string): TODO: type description here.
"""
# Create a mapping from Model property names to API property names
_names = {
"asin"... | # -*- coding: utf-8 -*-
"""
awsecommerceservice
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class Accessory(object):
| 45 | 79 | 265 | 5 | 40 | nidaizamir/Test-PY | awsecommerceservice/models/accessory.py | Python | Accessory | Accessory | 10 | 61 | 10 | 11 | 305bbbe2660c3b40b59350c743ff9b0ba5ab93b2 | bigcode/the-stack | train |
32be733e3ac3913b6b9bf010 | train | class | class Internet(BaseProvider):
"""Class for generating data related to the internet."""
_MAX_IPV4: Final[int] = (2 ** 32) - 1
_MAX_IPV6: Final[int] = (2 ** 128) - 1
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Initialize attributes.
:param args: Arguments.
:param k... | class Internet(BaseProvider):
| """Class for generating data related to the internet."""
_MAX_IPV4: Final[int] = (2 ** 32) - 1
_MAX_IPV6: Final[int] = (2 ** 128) - 1
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Initialize attributes.
:param args: Arguments.
:param kwargs: Keyword arguments.
... | """Provides data related to internet."""
import urllib.error
import urllib.parse
import urllib.request
from ipaddress import IPv4Address, IPv6Address
from typing import Any, Dict, Final, List, Optional, Set, Union
from mimesis.data import (
EMOJI,
HTTP_METHODS,
HTTP_STATUS_CODES,
HTTP_STATUS_MSGS,
... | 177 | 256 | 2,612 | 5 | 172 | ngnpope/mimesis | mimesis/providers/internet.py | Python | Internet | Internet | 29 | 402 | 29 | 29 | 709d73df7ceffebb6b0cfaa3ddd9ee3c42b34c15 | bigcode/the-stack | train |
78961ebe254db1e16bd66cad | train | class | class ForemanAttributeInteger(ForemanAttributeRegex):
protobuf = jobs_pb2.ForemanAttributeInteger
| class ForemanAttributeInteger(ForemanAttributeRegex):
| protobuf = jobs_pb2.ForemanAttributeInteger
| .RDFProtoStruct):
protobuf = jobs_pb2.ForemanAttributeRegex
def Validate(self):
if not self.attribute_name:
raise ValueError("ForemanAttributeRegex rule invalid - "
"not attribute set.")
self.attribute_name.Validate()
class ForemanAttributeInteger(ForemanAttributeRegex):
| 64 | 64 | 22 | 11 | 53 | pchaigno/grr | lib/rdfvalues/foreman.py | Python | ForemanAttributeInteger | ForemanAttributeInteger | 25 | 26 | 25 | 25 | f8253490ba0a37fe8466c33dd025a652c06d2404 | bigcode/the-stack | train |
ca69cb407798628ee4c8da5d | train | class | class ForemanRule(rdf_structs.RDFProtoStruct):
"""A Foreman rule RDF value."""
protobuf = jobs_pb2.ForemanRule
def Validate(self):
for rule in self.regex_rules:
rule.Validate()
for rule in self.integer_rules:
rule.Validate()
@property
def hunt_id(self):
"""Returns hunt id of this ru... | class ForemanRule(rdf_structs.RDFProtoStruct):
| """A Foreman rule RDF value."""
protobuf = jobs_pb2.ForemanRule
def Validate(self):
for rule in self.regex_rules:
rule.Validate()
for rule in self.integer_rules:
rule.Validate()
@property
def hunt_id(self):
"""Returns hunt id of this rule's actions or None if there's none."""
fo... | self.attribute_name:
raise ValueError("ForemanAttributeRegex rule invalid - "
"not attribute set.")
self.attribute_name.Validate()
class ForemanAttributeInteger(ForemanAttributeRegex):
protobuf = jobs_pb2.ForemanAttributeInteger
class ForemanRule(rdf_structs.RDFProtoStruct):
| 64 | 64 | 113 | 13 | 50 | pchaigno/grr | lib/rdfvalues/foreman.py | Python | ForemanRule | ForemanRule | 29 | 45 | 29 | 29 | 5b5c280f6dc08edd10d5f0e37b2bd4a29c4de137 | bigcode/the-stack | train |
9e609ce39135eaaaf8836a7a | train | class | class ForemanRuleAction(rdf_structs.RDFProtoStruct):
protobuf = jobs_pb2.ForemanRuleAction
| class ForemanRuleAction(rdf_structs.RDFProtoStruct):
| protobuf = jobs_pb2.ForemanRuleAction
| """RDFValue instances related to the foreman implementation."""
from grr.lib.rdfvalues import protodict as rdf_protodict
from grr.lib.rdfvalues import structs as rdf_structs
from grr.proto import jobs_pb2
class ForemanRuleAction(rdf_structs.RDFProtoStruct):
| 64 | 64 | 25 | 14 | 49 | pchaigno/grr | lib/rdfvalues/foreman.py | Python | ForemanRuleAction | ForemanRuleAction | 10 | 11 | 10 | 10 | 9d0af1b9b7f2c75a9ef2fa59e98fd460b91b69d3 | bigcode/the-stack | train |
c3b793f2b421a6181ae2960f | train | class | class ForemanRules(rdf_protodict.RDFValueArray):
"""A list of rules that the foreman will apply."""
rdf_type = ForemanRule
| class ForemanRules(rdf_protodict.RDFValueArray):
| """A list of rules that the foreman will apply."""
rdf_type = ForemanRule
| property
def hunt_id(self):
"""Returns hunt id of this rule's actions or None if there's none."""
for action in self.actions or []:
if action.hunt_id is not None:
return action.hunt_id
class ForemanRules(rdf_protodict.RDFValueArray):
| 64 | 64 | 35 | 14 | 49 | pchaigno/grr | lib/rdfvalues/foreman.py | Python | ForemanRules | ForemanRules | 48 | 50 | 48 | 48 | d8c3d62f4c799c621d9fdeb9f6cd09a558796317 | bigcode/the-stack | train |
1879c0592d2638bc821a3f65 | train | class | class ForemanAttributeRegex(rdf_structs.RDFProtoStruct):
protobuf = jobs_pb2.ForemanAttributeRegex
def Validate(self):
if not self.attribute_name:
raise ValueError("ForemanAttributeRegex rule invalid - "
"not attribute set.")
self.attribute_name.Validate()
| class ForemanAttributeRegex(rdf_structs.RDFProtoStruct):
| protobuf = jobs_pb2.ForemanAttributeRegex
def Validate(self):
if not self.attribute_name:
raise ValueError("ForemanAttributeRegex rule invalid - "
"not attribute set.")
self.attribute_name.Validate()
| todict
from grr.lib.rdfvalues import structs as rdf_structs
from grr.proto import jobs_pb2
class ForemanRuleAction(rdf_structs.RDFProtoStruct):
protobuf = jobs_pb2.ForemanRuleAction
class ForemanAttributeRegex(rdf_structs.RDFProtoStruct):
| 64 | 64 | 62 | 14 | 49 | pchaigno/grr | lib/rdfvalues/foreman.py | Python | ForemanAttributeRegex | ForemanAttributeRegex | 14 | 22 | 14 | 14 | 712b30a440d8c781e9886b46192950c608415c26 | bigcode/the-stack | train |
de4dd38f5750be27ea583d24 | train | function | def setup(url, league_id):
is_season_data = 'standings' in url
soup = run_selenium(url, is_season_data, league_id)
if soup is None:
abort(500)
sys.exit('BeautifulSoup object is None.')
app.logger.info('%s - Scraping list of weeks', league_id)
weeks = None
if not is_season_data:
... | def setup(url, league_id):
| is_season_data = 'standings' in url
soup = run_selenium(url, is_season_data, league_id)
if soup is None:
abort(500)
sys.exit('BeautifulSoup object is None.')
app.logger.info('%s - Scraping list of weeks', league_id)
weeks = None
if not is_season_data:
weeks = soup.find("... | &view"
"mScoreboard&view=mSettings&view=mTeam&view=modular&view=mNav").format(app.config.get("SEASON"), league_id)
try:
r = requests.get(url)
except requests.exceptions.RequestException as ex:
app.logger.error('%s - Could not make ESPN API call', league_id, ex)
abort(500)
... | 108 | 108 | 360 | 7 | 100 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | setup | setup | 186 | 222 | 186 | 186 | eab64e64375ada6673bf7ffcccd103f7daa61924 | bigcode/the-stack | train |
ba2b5376a2104df76042bf76 | train | function | @app.route('/', methods=['GET'])
def index():
return render_template('index.html')
| @app.route('/', methods=['GET'])
def index():
| return render_template('index.html')
| Wait
import config
# Create the Flask application.
app = Flask(__name__)
app.logger.setLevel(logging.INFO)
app.config.from_object(config.ProductionConfig)
@app.errorhandler(500)
def abort_error():
return render_template('error.html'), 500
@app.route('/', methods=['GET'])
def index():
| 64 | 64 | 18 | 10 | 53 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | index | index | 29 | 31 | 29 | 30 | b4e5bcaace3e77bcc6877356e74fcffb39d8ee95 | bigcode/the-stack | train |
174ad50cd2986d7a604b50bf | train | function | def append_team_names(soup, is_season_data, teams, league_id):
app.logger.info('%s - Appending team names', league_id)
if is_season_data:
table_body_class = 'Table Table--align-right Table--fixed Table--fixed-left'
table_body = soup.find_all('table', class_=table_body_class)[0]
team_name... | def append_team_names(soup, is_season_data, teams, league_id):
| app.logger.info('%s - Appending team names', league_id)
if is_season_data:
table_body_class = 'Table Table--align-right Table--fixed Table--fixed-left'
table_body = soup.find_all('table', class_=table_body_class)[0]
team_names = table_body.find_all('span', class_='teamName truncate')
... | else:
columns = table_rows[row].findAll('td')[1:len(categories) + 1]
team_row = [c.getText() for c in columns]
teams.append(team_row)
return teams
def append_team_names(soup, is_season_data, teams, league_id):
| 64 | 64 | 172 | 17 | 46 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | append_team_names | append_team_names | 290 | 303 | 290 | 290 | 3074f9308e09e37c8d597c7ded0ce1f87abdae4b | bigcode/the-stack | train |
74a10412e1543ffb0f6bddb8 | train | function | def update_player_rank_sums(player_rank_sums, team_names, ranks):
for player in team_names:
if player in player_rank_sums:
player_rank_sums[player] += ranks[player]
# if player doesn't have opponent rank values, store to dict
else:
player_rank_sums[player] = ranks[pla... | def update_player_rank_sums(player_rank_sums, team_names, ranks):
| for player in team_names:
if player in player_rank_sums:
player_rank_sums[player] += ranks[player]
# if player doesn't have opponent rank values, store to dict
else:
player_rank_sums[player] = ranks[player]
return
| ]]
# if player doesn't have opponent rank values, store to dict
else:
player_opp_rank_sums[player] = ranks[matchups[player]]
return
# update player dictionary with current week player rank info
def update_player_rank_sums(player_rank_sums, team_names, ranks):
| 64 | 64 | 74 | 16 | 47 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | update_player_rank_sums | update_player_rank_sums | 532 | 539 | 532 | 532 | 85fd93a4513ba78c39c0e732d6631a5484270f5c | bigcode/the-stack | train |
e1d57935c6ab04c24c986450 | train | function | @app.route('/season_analysis', methods=['GET', 'POST'])
def season_analysis():
season_values = endpoints_setup(True)
league_id = season_values[0]
if season_values[1] == 'private':
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('season_analys... | @app.route('/season_analysis', methods=['GET', 'POST'])
def season_analysis():
| season_values = endpoints_setup(True)
league_id = season_values[0]
if season_values[1] == 'private':
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('season_analysis.html', league_id=league_id, current_week=season_values[1],
... | private_league=True)
return render_template('season_matchups.html', league_id=league_id, current_week=season_values[1],
weeks=season_values[2], matchups=season_values[3][1])
@app.route('/season_analysis', methods=['GET', 'POST'])
def season_analysis():
| 64 | 64 | 104 | 17 | 47 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | season_analysis | season_analysis | 108 | 115 | 108 | 109 | 3c5a2aff06ea507343155d56e68e9e757697848a | bigcode/the-stack | train |
b5a45319c57c4fe616266a4e | train | function | @app.route('/tools', methods=['GET', 'POST'])
def tools():
if request.method == 'POST':
url = request.form['url']
app.logger.info('URL: %s', url)
try:
parsed_url = urlparse.urlparse(url)
league_id = int((urlparse.parse_qs(parsed_url.query, strict_parsing=True)['league... | @app.route('/tools', methods=['GET', 'POST'])
def tools():
| if request.method == 'POST':
url = request.form['url']
app.logger.info('URL: %s', url)
try:
parsed_url = urlparse.urlparse(url)
league_id = int((urlparse.parse_qs(parsed_url.query, strict_parsing=True)['leagueId'])[0])
except ValueError as ex:
app.... | Create the Flask application.
app = Flask(__name__)
app.logger.setLevel(logging.INFO)
app.config.from_object(config.ProductionConfig)
@app.errorhandler(500)
def abort_error():
return render_template('error.html'), 500
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
@app.r... | 81 | 81 | 271 | 15 | 66 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | tools | tools | 34 | 56 | 34 | 35 | d07b0c2bc3eaab8cf8dd7eff6dfa622540beef6c | bigcode/the-stack | train |
0760e04d1ff9500d6e8bc6b0 | train | function | @app.route('/overall_perf', methods=['GET', 'POST'])
def overall_perf():
season_values = get_overall_perf()
league_id = season_values[0]
if season_values[1] == 'private':
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('overall_perf.html', le... | @app.route('/overall_perf', methods=['GET', 'POST'])
def overall_perf():
| season_values = get_overall_perf()
league_id = season_values[0]
if season_values[1] == 'private':
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('overall_perf.html', league_id=league_id, current_week=season_values[1],
... | ('index.html', league_id=league_id, private_league=True)
return render_template('season_sos.html', league_id=league_id, current_week=season_values[1],
rankings=season_values[2])
@app.route('/overall_perf', methods=['GET', 'POST'])
def overall_perf():
| 64 | 64 | 96 | 17 | 47 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | overall_perf | overall_perf | 128 | 135 | 128 | 129 | 5cb1b5ce5e8dd02f8cbf267489820f32cbec0138 | bigcode/the-stack | train |
46ac6dae53b5bc7c0568dc48 | train | function | def update_player_opp_rank_sums(player_opp_rank_sums, team_names, matchups, ranks):
for player in team_names:
if player in player_opp_rank_sums:
player_opp_rank_sums[player] += ranks[matchups[player]]
# if player doesn't have opponent rank values, store to dict
else:
... | def update_player_opp_rank_sums(player_opp_rank_sums, team_names, matchups, ranks):
| for player in team_names:
if player in player_opp_rank_sums:
player_opp_rank_sums[player] += ranks[matchups[player]]
# if player doesn't have opponent rank values, store to dict
else:
player_opp_rank_sums[player] = ranks[matchups[player]]
return
| team in sorted_avg_rank:
rankings.append([rank, team[0], team[1]])
rank += 1
return rankings
# update player dictionary with current week opponent rank info
def update_player_opp_rank_sums(player_opp_rank_sums, team_names, matchups, ranks):
| 64 | 64 | 93 | 23 | 40 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | update_player_opp_rank_sums | update_player_opp_rank_sums | 521 | 528 | 521 | 521 | 41d354c2ad2214c69578ff159fb183574bc5f589 | bigcode/the-stack | train |
ce0a2254177030e372e19e12 | train | function | def get_table_rows_and_cats(soup, is_season_data, league_id):
app.logger.info('%s - Starting scraping table_rows and categories', league_id)
# Scrape objects depending on whether the user asked for season or weekly data.
if is_season_data:
categories_list = soup.find_all('thead', class_='Table__head... | def get_table_rows_and_cats(soup, is_season_data, league_id):
| app.logger.info('%s - Starting scraping table_rows and categories', league_id)
# Scrape objects depending on whether the user asked for season or weekly data.
if is_season_data:
categories_list = soup.find_all('thead', class_='Table__header-group Table__THEAD')[1]
table_body = soup.find_all(... | Got BeautifulSoup object', league_id)
except Exception as ex:
app.logger.error('%s - Could not get page source.', league_id, ex)
soup = None
finally:
driver.quit()
return soup
def get_table_rows_and_cats(soup, is_season_data, league_id):
| 66 | 66 | 222 | 18 | 47 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | get_table_rows_and_cats | get_table_rows_and_cats | 258 | 272 | 258 | 258 | 4b00ef972ce0639180db212660a0a1484a53f288 | bigcode/the-stack | train |
84838fbc5c5aab334499b9d0 | train | function | def format_team(team_raw, team_dict):
team = []
team.append(team_dict[team_raw['teamId']])
scores = team_raw['cumulativeScore']['scoreByStat']
# FG%
team.append(key_check(scores, '19'))
# FT%
team.append(key_check(scores, '20'))
# 3PM
team.append(key_check(scores, '17'))
# REB
... | def format_team(team_raw, team_dict):
| team = []
team.append(team_dict[team_raw['teamId']])
scores = team_raw['cumulativeScore']['scoreByStat']
# FG%
team.append(key_check(scores, '19'))
# FT%
team.append(key_check(scores, '20'))
# 3PM
team.append(key_check(scores, '17'))
# REB
team.append(key_check(scores, '6'))
... | # check if val exists, otherwise return 0
def key_check(stats, key):
try:
return stats[key]['score']
except KeyError:
pass
return 0
# format espn api call info into 9-cat team info
def format_team(team_raw, team_dict):
| 64 | 64 | 175 | 9 | 54 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | format_team | format_team | 589 | 611 | 589 | 589 | 2a8b06803906e407ce550db41c380a0507bdf755 | bigcode/the-stack | train |
ebe6b84acb3b326911bf1805 | train | function | @app.errorhandler(500)
def abort_error():
return render_template('error.html'), 500
| @app.errorhandler(500)
def abort_error():
| return render_template('error.html'), 500
| DesiredCapabilities
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import config
# Create the Flask application.
app = Flask(__name__)
app.logger.setLevel(logging.INFO)
app.config.from_object(config.ProductionConfig)
@app.errorhandler(500)
d... | 64 | 64 | 21 | 10 | 54 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | abort_error | abort_error | 24 | 26 | 24 | 25 | b2adb7221a6f878664ece4ae2d1fcf408eac79f1 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.