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
3eb85a15d8d9ae65594c9d5a
train
function
@tf_contextlib.contextmanager def init_scope(): """A context manager that lifts ops out of control-flow scopes and function-building graphs. There is often a need to lift variable initialization ops out of control-flow scopes, function-building graphs, and gradient tapes. Entering an `init_scope` is a mechanis...
@tf_contextlib.contextmanager def init_scope():
"""A context manager that lifts ops out of control-flow scopes and function-building graphs. There is often a need to lift variable initialization ops out of control-flow scopes, function-building graphs, and gradient tapes. Entering an `init_scope` is a mechanism for satisfying these desiderata. In particular...
graph building when entered (assuming init_scope is called # in a graph building context). Instead, we push a context which first # enables eager execution and then re-enters the Graph. context.context().context_switches.push( default.building_function, functools.partial...
233
233
778
11
221
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
init_scope
init_scope
5,306
5,380
5,306
5,307
590cb03cb8e932b17a633f06b96c32e915a24ff9
bigcode/the-stack
train
bb5d4520dad1104e9b90e22c
train
function
def _create_c_op(graph, node_def, inputs, control_inputs): """Creates a TF_Operation. Args: graph: a `Graph`. node_def: `node_def_pb2.NodeDef` for the operation to create. inputs: A list of `Tensor`s (corresponding to scalar inputs) and lists of `Tensor`s (corresponding to sequence inputs, e.g. "...
def _create_c_op(graph, node_def, inputs, control_inputs):
"""Creates a TF_Operation. Args: graph: a `Graph`. node_def: `node_def_pb2.NodeDef` for the operation to create. inputs: A list of `Tensor`s (corresponding to scalar inputs) and lists of `Tensor`s (corresponding to sequence inputs, e.g. "int64 * N", "list(int64)"). The length of the list sh...
None: if callable(device): node_def.device = device(node_def) else: node_def.device = _device_string(device) return node_def # Copied from core/framework/node_def_util.cc # TODO(mrry,josh11b): Consolidate this validation in C++ code. _VALID_OP_NAME_REGEX = re.compile("^[A-Za-z0-9.][A-Za-z0-9_.\...
127
128
428
15
113
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_create_c_op
_create_c_op
1,553
1,597
1,553
1,553
9263cbf6a4f6e5ccd8e67bd9e0c4f83480cccf9f
bigcode/the-stack
train
5708b7e76dfc5fda1de66a4c
train
function
def _set_call_cpp_shape_fn(call_cpp_shape_fn): """Sets default shape fns from passed common_shapes.call_cpp_shape_fn.""" global _call_cpp_shape_fn, _call_cpp_shape_fn_and_require_op if _call_cpp_shape_fn: return # already registered def call_without_requiring(op): return call_cpp_shape_fn(op, require_...
def _set_call_cpp_shape_fn(call_cpp_shape_fn):
"""Sets default shape fns from passed common_shapes.call_cpp_shape_fn.""" global _call_cpp_shape_fn, _call_cpp_shape_fn_and_require_op if _call_cpp_shape_fn: return # already registered def call_without_requiring(op): return call_cpp_shape_fn(op, require_shape_fn=False) _call_cpp_shape_fn = call_wi...
set to common_shapes.call_cpp_shape_fn by op generated code # (generated by python_op_gen.cc). # It is set outside ops.py to avoid a circular dependency. _call_cpp_shape_fn = None _call_cpp_shape_fn_and_require_op = None def _set_call_cpp_shape_fn(call_cpp_shape_fn):
64
64
129
12
51
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_set_call_cpp_shape_fn
_set_call_cpp_shape_fn
2,509
2,523
2,509
2,509
4ae9b05224c3369be8ddf8115f4d151975872355
bigcode/the-stack
train
5b1fe31ab13f96b197559d44
train
function
@tf_export("add_to_collection") def add_to_collection(name, value): """Wrapper for `Graph.add_to_collection()` using the default graph. See @{tf.Graph.add_to_collection} for more details. Args: name: The key for the collection. For example, the `GraphKeys` class contains many standard names for coll...
@tf_export("add_to_collection") def add_to_collection(name, value):
"""Wrapper for `Graph.add_to_collection()` using the default graph. See @{tf.Graph.add_to_collection} for more details. Args: name: The key for the collection. For example, the `GraphKeys` class contains many standard names for collections. value: The value to add to the collection. @compatib...
ARN, "VARIABLES collection name is deprecated, please use " "GLOBAL_VARIABLES instead; VARIABLES will be removed " "after 2017-03-02.", 1) return cls.GLOBAL_VARIABLES @tf_export("add_to_collection") def add_to_collection(name, value):
64
64
125
16
47
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
add_to_collection
add_to_collection
5,813
5,829
5,813
5,814
0e6c01e8e0f5da54e7944d7d6cd0ab06becedd2a
bigcode/the-stack
train
6d2c90f85f0d1e4a45dfddbe
train
function
def internal_convert_to_tensor(value, dtype=None, name=None, as_ref=False, preferred_dtype=None, ctx=None): """Converts the given `value` to an `Tensor`. This f...
def internal_convert_to_tensor(value, dtype=None, name=None, as_ref=False, preferred_dtype=None, ctx=None):
"""Converts the given `value` to an `Tensor`. This function converts Python objects of various types to `Tensor` objects. It accepts `Tensor` objects, numpy arrays, Python lists, and Python scalars. For example: This function can be useful when composing a new operation in Python All standard Python op co...
whose type has a registered `Tensor` conversion function. dtype: Optional element type for the returned tensor. If missing, the type is inferred from the type of `value`. name: Optional name to use if a new `Tensor` is created. preferred_dtype: Optional element type for the returned tensor, use...
256
256
1,004
29
226
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
internal_convert_to_tensor
internal_convert_to_tensor
1,021
1,128
1,021
1,026
d4b927f40e6264c262f06044cc87079753ccbbb0
bigcode/the-stack
train
2fbbad475f924d9fcc15ddb9
train
function
@tf_export("device") def device(device_name_or_function): """Wrapper for `Graph.device()` using the default graph. See @{tf.Graph.device} for more details. Args: device_name_or_function: The device name or function to use in the context. Returns: A context manager that specifies the default...
@tf_export("device") def device(device_name_or_function):
"""Wrapper for `Graph.device()` using the default graph. See @{tf.Graph.device} for more details. Args: device_name_or_function: The device name or function to use in the context. Returns: A context manager that specifies the default device to use for newly created ops. Raises: R...
_local._control_dependencies_stack = control_dependencies else: self._graph_control_dependencies_stack = control_dependencies # TODO(agarwal): currently device directives in an outer eager scope will not # apply to inner graph mode code. Fix that. @tf_export("device") def device(device_name_or_function):
64
64
182
13
51
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
device
device
4,956
4,983
4,956
4,957
94e5eb020970a505fbb4376c3af72df74de3cc90
bigcode/the-stack
train
b7a0b27ac1c0871e9b8d67af
train
function
def get_collection_proto_type(collection_name): """Returns the proto_type for collection_name.""" try: return _proto_function_registry.lookup(collection_name)[0] except LookupError: return None
def get_collection_proto_type(collection_name):
"""Returns the proto_type for collection_name.""" try: return _proto_function_registry.lookup(collection_name)[0] except LookupError: return None
callable(to_proto): raise TypeError("to_proto must be callable.") if from_proto and not callable(from_proto): raise TypeError("from_proto must be callable.") _proto_function_registry.register((proto_type, to_proto, from_proto), collection_name) def get_collection_proto_...
64
64
42
8
56
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
get_collection_proto_type
get_collection_proto_type
6,113
6,118
6,113
6,113
4df109192371b951ab6610cf00e34e3dedb0687b
bigcode/the-stack
train
9f6df8bb6c94ec4a903261f7
train
function
def _assert_same_graph(original_item, item): """Fail if the 2 items are from different graphs. Args: original_item: Original item to check against. item: Item to check. Raises: ValueError: if graphs do not match. """ if original_item.graph is not item.graph: raise ValueError("%s must be from...
def _assert_same_graph(original_item, item):
"""Fail if the 2 items are from different graphs. Args: original_item: Original item to check against. item: Item to check. Raises: ValueError: if graphs do not match. """ if original_item.graph is not item.graph: raise ValueError("%s must be from the same graph as %s." % (item, ...
would print the string `scope1/scope2`. Returns: A string representing the current name scope. """ if context.executing_eagerly(): return context.context().scope_name.rstrip("/") return get_default_graph().get_name_scope() def _assert_same_graph(original_item, item):
64
64
92
10
54
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_assert_same_graph
_assert_same_graph
5,580
5,592
5,580
5,580
b40a4fbf6f77276406cbb65580be6a5fa87e31da
bigcode/the-stack
train
c3a14147a7de0b767d21a2f9
train
function
@tf_export("add_to_collections") def add_to_collections(names, value): """Wrapper for `Graph.add_to_collections()` using the default graph. See @{tf.Graph.add_to_collections} for more details. Args: names: The key for the collections. The `GraphKeys` class contains many standard names for collection...
@tf_export("add_to_collections") def add_to_collections(names, value):
"""Wrapper for `Graph.add_to_collections()` using the default graph. See @{tf.Graph.add_to_collections} for more details. Args: names: The key for the collections. The `GraphKeys` class contains many standard names for collections. value: The value to add to the collections. @compatibility(ea...
value to add to the collection. @compatibility(eager) Collections are not supported when eager execution is enabled. @end_compatibility """ get_default_graph().add_to_collection(name, value) @tf_export("add_to_collections") def add_to_collections(names, value):
64
64
127
18
46
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
add_to_collections
add_to_collections
5,831
5,847
5,831
5,832
ff1fd5be1b9396e27f7f0f24b2b127e03c7f510c
bigcode/the-stack
train
efee8bd2f7cf7535af6091cf
train
function
def _run_using_default_session(operation, feed_dict, graph, session=None): """Uses the default session to run "operation". Args: operation: The Operation to be run. feed_dict: A dictionary that maps Tensor objects (or tensor names) to lists, numpy ndarrays, TensorProtos, or strings. graph: The gr...
def _run_using_default_session(operation, feed_dict, graph, session=None):
"""Uses the default session to run "operation". Args: operation: The Operation to be run. feed_dict: A dictionary that maps Tensor objects (or tensor names) to lists, numpy ndarrays, TensorProtos, or strings. graph: The graph in which "operation" is defined. session: (Optional) A different se...
's graph is different from the session's " "graph. Pass an explicit session to " "`eval(session=sess)`.") else: if session.graph is not graph: raise ValueError("Cannot use the given session to evaluate tensor: " "the tensor's graph is diff...
96
96
322
16
80
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_run_using_default_session
_run_using_default_session
5,208
5,240
5,208
5,208
ca87493cd1dbe3e6d0989523bcc8af8833c4fbe1
bigcode/the-stack
train
544bdd55c40c1d92b89a6a17
train
function
def _colocate_with_for_gradient(op, gradient_uid, ignore_existing=False): if context.executing_eagerly(): if op is not None: return device(op.device) else: return _NullContextmanager() else: default_graph = get_default_graph() if isinstance(op, EagerTensor): if default_graph.buildi...
def _colocate_with_for_gradient(op, gradient_uid, ignore_existing=False):
if context.executing_eagerly(): if op is not None: return device(op.device) else: return _NullContextmanager() else: default_graph = get_default_graph() if isinstance(op, EagerTensor): if default_graph.building_function: return default_graph.device(op.device) else: ...
container_name: The container string to use in the context. Returns: A context manager that specifies the default container to use for newly created stateful ops. """ return get_default_graph().container(container_name) def _colocate_with_for_gradient(op, gradient_uid, ignore_existing=False):
64
64
140
16
48
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_colocate_with_for_gradient
_colocate_with_for_gradient
5,000
5,015
5,000
5,000
de17feb55e3f5068209bba6d4dda10662a7699a0
bigcode/the-stack
train
73cc817d06905877d489c07b
train
function
@tf_export("NoGradient", "NotDifferentiable") def NotDifferentiable(op_type): """Specifies that ops of type `op_type` is not differentiable. This function should *not* be used for operations that have a well-defined gradient that is not yet implemented. This function is only used when defining a new op type. ...
@tf_export("NoGradient", "NotDifferentiable") def NotDifferentiable(op_type):
"""Specifies that ops of type `op_type` is not differentiable. This function should *not* be used for operations that have a well-defined gradient that is not yet implemented. This function is only used when defining a new op type. It may be used for ops such as `tf.size()` that are not differentiable. For...
_type must be a string") self._op_type = op_type def __call__(self, f): """Registers the function `f` as gradient function for `op_type`.""" _gradient_registry.register(f, self._op_type) return f @tf_export("NoGradient", "NotDifferentiable") def NotDifferentiable(op_type):
78
78
260
21
56
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
NotDifferentiable
NotDifferentiable
2,450
2,481
2,450
2,451
02d7a56a998406743c9ab1fb8ca783f609364f23
bigcode/the-stack
train
8fcbf4258c776ac3fcc36302
train
function
@tf_export("convert_to_tensor") def convert_to_tensor(value, dtype=None, name=None, preferred_dtype=None): """Converts the given `value` to a `Tensor`. This function converts Python objects of various types to `Tensor` objects. It accepts `Tensor` objects, numpy arrays, Python lists, and Python scalars. For ex...
@tf_export("convert_to_tensor") def convert_to_tensor(value, dtype=None, name=None, preferred_dtype=None):
"""Converts the given `value` to a `Tensor`. This function converts Python objects of various types to `Tensor` objects. It accepts `Tensor` objects, numpy arrays, Python lists, and Python scalars. For example: ```python import numpy as np def my_func(arg): arg = tf.convert_to_tensor(arg, dtype=tf....
module. EagerTensor = c_api.TFE_Py_InitEagerTensor(_EagerTensorBase) def _TensorTensorConversionFunction(t, dtype=None, name=None, as_ref=False): _ = name, as_ref if dtype and not dtype.is_compatible_with(t.dtype): raise ValueError( "Tensor conversion requested dtype %s for Tensor with dtype %s: %r" ...
167
167
558
24
143
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
convert_to_tensor
convert_to_tensor
959
1,014
959
960
ad911b10795673bdf8b51d19c28e34db505abe2c
bigcode/the-stack
train
613a4547bae5fd7560f64edd
train
function
def _error_prefix(name): return "" if name is None else "%s: " % name
def _error_prefix(name):
return "" if name is None else "%s: " % name
If no conversion function is registered for `value`. RuntimeError: If a registered conversion function returns an invalid value. """ return internal_convert_to_tensor( value=value, dtype=dtype, name=name, preferred_dtype=preferred_dtype, as_ref=False) def _error_prefix(name):
64
64
21
6
58
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_error_prefix
_error_prefix
1,017
1,018
1,017
1,017
fc5b010231679d9f4a4bbce3e433bbe8b48a7bc5
bigcode/the-stack
train
0d68afe12362c81cc4392aae
train
class
@tf_export("GraphKeys") class GraphKeys(object): """Standard names to use for graph collections. The standard library uses various well-known names to collect and retrieve values associated with a graph. For example, the `tf.Optimizer` subclasses default to optimizing the variables collected under `tf.GraphK...
@tf_export("GraphKeys") class GraphKeys(object):
"""Standard names to use for graph collections. The standard library uses various well-known names to collect and retrieve values associated with a graph. For example, the `tf.Optimizer` subclasses default to optimizing the variables collected under `tf.GraphKeys.TRAINABLE_VARIABLES` if none is specified, ...
a more # informative error if a mismatch is found. original_graph_element = None for op_input in op_input_list: # Determine if this is a valid graph_element. # TODO(josh11b): Note that we exclude subclasses of Tensor. Need to clean this # up. graph_element = None if (isinstance(op_input, (...
256
256
1,360
12
244
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
GraphKeys
GraphKeys
5,664
5,810
5,664
5,665
8a2c919a2d29c630e313f756db3a2e0b0cea83da
bigcode/the-stack
train
98369d94363fbc19799bca12
train
function
@tf_export("container") def container(container_name): """Wrapper for `Graph.container()` using the default graph. Args: container_name: The container string to use in the context. Returns: A context manager that specifies the default container to use for newly created stateful ops. """ return g...
@tf_export("container") def container(container_name):
"""Wrapper for `Graph.container()` using the default graph. Args: container_name: The container string to use in the context. Returns: A context manager that specifies the default container to use for newly created stateful ops. """ return get_default_graph().container(container_name)
if callable(device_name_or_function): raise RuntimeError( "tf.device does not support functions when eager execution " "is enabled.") return context.device(device_name_or_function) else: return get_default_graph().device(device_name_or_function) @tf_export("container") def container...
64
64
75
11
53
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
container
container
4,986
4,997
4,986
4,987
a2585f5601e9884cb1b068c2becfe29f1e8d9ee4
bigcode/the-stack
train
e51f1f6aa75880c5616763e0
train
function
def get_from_proto_function(collection_name): """Returns the from_proto function for collection_name.""" try: return _proto_function_registry.lookup(collection_name)[2] except LookupError: return None
def get_from_proto_function(collection_name):
"""Returns the from_proto function for collection_name.""" try: return _proto_function_registry.lookup(collection_name)[2] except LookupError: return None
_name)[0] except LookupError: return None def get_to_proto_function(collection_name): """Returns the to_proto function for collection_name.""" try: return _proto_function_registry.lookup(collection_name)[1] except LookupError: return None def get_from_proto_function(collection_name):
64
64
43
8
55
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
get_from_proto_function
get_from_proto_function
6,129
6,134
6,129
6,129
d57af7036c23484ea9842f221598da54b07c5736
bigcode/the-stack
train
60b954151f981dfe09eecc14
train
function
def register_dense_tensor_like_type(tensor_type): """EXPERIMENTAL: Registers `tensor_type` as implementing the tensor interface. A "tensor-like type" can represent a single dense tensor, and implements the `name` and `dtype` properties. Args: tensor_type: A type implementing the tensor interface. Raise...
def register_dense_tensor_like_type(tensor_type):
"""EXPERIMENTAL: Registers `tensor_type` as implementing the tensor interface. A "tensor-like type" can represent a single dense tensor, and implements the `name` and `dtype` properties. Args: tensor_type: A type implementing the tensor interface. Raises: TypeError: If `tensor_type` does not implem...
Returns true if `t` implements the tensor interface. See `register_dense_tensor_like_type()` for the current definition of a "tensor-like type". Args: t: An object. Returns: True iff `t` is an instance of one of the registered "tensor-like" types. """ return isinstance(t, _TENSOR_LIKE_TYPES) def...
89
89
299
10
79
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
register_dense_tensor_like_type
register_dense_tensor_like_type
143
173
143
143
4f92e207c168f553571daf9ae8a008bb889c14ff
bigcode/the-stack
train
c4d22aeb091d15562d100544
train
function
def set_shape_and_handle_data_for_outputs(op): """Set the shapes and resource handle data for op's outputs. When _USE_C_API = True, this is lazily called when a tensor's shape is first requested. Usually this should work automatically, but some edge cases may require manually calling this first to make sure Te...
def set_shape_and_handle_data_for_outputs(op):
"""Set the shapes and resource handle data for op's outputs. When _USE_C_API = True, this is lazily called when a tensor's shape is first requested. Usually this should work automatically, but some edge cases may require manually calling this first to make sure Tensor._shape_val and Tensor._handle_data are s...
shape_val = output._c_api_shape() # Set the resource handle data for compatibility with the Python shape # inference code. serialized = c_api.GetResourceHandleShapeAndType(op._graph._c_graph, output._as_tf_output()) if serialized: output._handle...
130
130
436
10
119
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
set_shape_and_handle_data_for_outputs
set_shape_and_handle_data_for_outputs
2,580
2,626
2,580
2,580
f8af98e377dcd6f1a25ef44c6ebafbaa902e314a
bigcode/the-stack
train
4fc2309352c4167c6730b366
train
function
@tf_export("control_dependencies") def control_dependencies(control_inputs): """Wrapper for `Graph.control_dependencies()` using the default graph. See @{tf.Graph.control_dependencies} for more details. When eager execution is enabled, any callable object in the `control_inputs` list will be called. Args...
@tf_export("control_dependencies") def control_dependencies(control_inputs):
"""Wrapper for `Graph.control_dependencies()` using the default graph. See @{tf.Graph.control_dependencies} for more details. When eager execution is enabled, any callable object in the `control_inputs` list will be called. Args: control_inputs: A list of `Operation` or `Tensor` objects which m...
( op, gradient_uid=gradient_uid, ignore_existing=ignore_existing) @tf_export("colocate_with") def colocate_with(op, ignore_existing=False): return _colocate_with_for_gradient(op, None, ignore_existing=ignore_existing) @tf_export("control_dependencies") def control_dependencies(control_inputs):
65
65
218
13
52
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
control_dependencies
control_dependencies
5,023
5,052
5,023
5,024
5a95873ccf29a242f5d291f23897127630095ce4
bigcode/the-stack
train
f91e36e13c51215690b7e1c4
train
function
def get_to_proto_function(collection_name): """Returns the to_proto function for collection_name.""" try: return _proto_function_registry.lookup(collection_name)[1] except LookupError: return None
def get_to_proto_function(collection_name):
"""Returns the to_proto function for collection_name.""" try: return _proto_function_registry.lookup(collection_name)[1] except LookupError: return None
((proto_type, to_proto, from_proto), collection_name) def get_collection_proto_type(collection_name): """Returns the proto_type for collection_name.""" try: return _proto_function_registry.lookup(collection_name)[0] except LookupError: return None def get_to_proto_fun...
64
64
43
8
55
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
get_to_proto_function
get_to_proto_function
6,121
6,126
6,121
6,121
5be03c19ee35ce40cc417a3fd80d68febc215d3d
bigcode/the-stack
train
f8077416be93cb1d71f87fb0
train
class
class RegisterStatistics(object): """A decorator for registering the statistics function for an op type. This decorator can be defined for an op type so that it gives a report on the resources used by an instance of an operator, in the form of an OpStats object. Well-known types of statistics include these ...
class RegisterStatistics(object):
"""A decorator for registering the statistics function for an op type. This decorator can be defined for an op type so that it gives a report on the resources used by an instance of an operator, in the form of an OpStats object. Well-known types of statistics include these so far: - flops: When running a...
statistic_type(self): return self._statistic_type @statistic_type.setter def statistic_type(self, statistic_type): self._statistic_type = statistic_type @property def value(self): return self._value @value.setter def value(self, value): self._value = value def __iadd__(self, other): ...
176
176
588
5
171
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
RegisterStatistics
RegisterStatistics
2,679
2,739
2,679
2,679
4f74a5204f91cae814335e8af4ee22b4e273d38b
bigcode/the-stack
train
6698cb93f09ff8ea88f0014b
train
function
def _NodeDef(op_type, name, device=None, attrs=None): # pylint: disable=redefined-outer-name """Create a NodeDef proto. Args: op_type: Value for the "op" attribute of the NodeDef proto. name: Value for the "name" attribute of the NodeDef proto. device: string, device, or function from NodeDef to strin...
def _NodeDef(op_type, name, device=None, attrs=None): # pylint: disable=redefined-outer-name
"""Create a NodeDef proto. Args: op_type: Value for the "op" attribute of the NodeDef proto. name: Value for the "name" attribute of the NodeDef proto. device: string, device, or function from NodeDef to string. Value for the "device" attribute of the NodeDef proto. attrs: Optional dictionary...
"IndexedSlicesValue", ["values", "indices", "dense_shape"]) def _device_string(dev_spec): if isinstance(dev_spec, pydev.DeviceSpec): return dev_spec.to_string() else: return dev_spec def _NodeDef(op_type, name, device=None, attrs=None): # pylint: disable=redefined-outer-name
75
75
252
26
48
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_NodeDef
_NodeDef
1,518
1,544
1,518
1,518
8365a6c812aedd7be19757e843d071472263a23e
bigcode/the-stack
train
ec577a05e2e78ee699c311e1
train
function
def eager_run(main=None, argv=None): """Runs the program with an optional main function and argv list. The program will run with eager execution enabled. Example: ```python import tensorflow as tf # Import subject to future changes: from tensorflow.contrib.eager.python import tfe def main(_): u =...
def eager_run(main=None, argv=None):
"""Runs the program with an optional main function and argv list. The program will run with eager execution enabled. Example: ```python import tensorflow as tf # Import subject to future changes: from tensorflow.contrib.eager.python import tfe def main(_): u = tf.constant(6.0) v = tf.constant...
, execution_mode)) else: raise ValueError( "tf.enable_eager_execution must be called at program startup.") # Monkey patch to get rid of an unnecessary conditional since the context is # now initialized. context.context = context.context_safe def eager_run(main=None, argv=None):
64
64
150
9
54
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
eager_run
eager_run
5,494
5,519
5,494
5,494
8996f63b84e1a0a51d374ac56d69f75c3cc0b933
bigcode/the-stack
train
644b4a678bc82a847ce4013f
train
function
@tf_export("register_tensor_conversion_function") def register_tensor_conversion_function(base_type, conversion_func, priority=100): """Registers a function for converting objects of `base_type` to `Tensor`. The conversion function mus...
@tf_export("register_tensor_conversion_function") def register_tensor_conversion_function(base_type, conversion_func, priority=100):
"""Registers a function for converting objects of `base_type` to `Tensor`. The conversion function must have the following signature: ```python def conversion_func(value, dtype=None, name=None, as_ref=False): # ... ``` It must return a `Tensor` with the given `dtype` if specified. If the co...
(Optional.) The required `DType` of the returned `Tensor` `IndexedSlices`. name: (Optional.) A name prefix to used when a new `Tensor` is created, in which case element `i` will be given the name `name + '_' + i`. Returns: A list of `Tensor`, `IndexedSlices`, and/or `SparseTensor` objects....
196
196
654
26
170
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
register_tensor_conversion_function
register_tensor_conversion_function
1,345
1,419
1,345
1,348
ea1b2b7b90e882db3c7e615b0b0a4fdf0c9649ea
bigcode/the-stack
train
daefec05a083208aeaf221f9
train
class
class _DefaultGraphStack(_DefaultStack): # pylint: disable=protected-access """A thread-local stack of objects for providing an implicit default graph.""" def __init__(self): super(_DefaultGraphStack, self).__init__() self._global_default_graph = None def get_default(self): """Override that returns...
class _DefaultGraphStack(_DefaultStack): # pylint: disable=protected-access
"""A thread-local stack of objects for providing an implicit default graph.""" def __init__(self): super(_DefaultGraphStack, self).__init__() self._global_default_graph = None def get_default(self): """Override that returns a global default if the stack is empty.""" ret = super(_DefaultGraphStac...
" "`run(session=sess)`") if session.graph is not graph: raise ValueError("Cannot use the default session to execute operation: " "the operation's graph is different from the " "session's graph. Pass an explicit session to " ...
132
132
440
18
114
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_DefaultGraphStack
_DefaultGraphStack
5,243
5,292
5,243
5,243
a5e47c2e8764bb135d58f42e54af51fa926f54b9
bigcode/the-stack
train
d40ffee449df75091328bfec
train
class
@tf_export("Tensor") class Tensor(_TensorLike): """Represents one of the outputs of an `Operation`. A `Tensor` is a symbolic handle to one of the outputs of an `Operation`. It does not hold the values of that operation's output, but instead provides a means of computing those values in a TensorFlow @{tf.Sess...
@tf_export("Tensor") class Tensor(_TensorLike):
"""Represents one of the outputs of an `Operation`. A `Tensor` is a symbolic handle to one of the outputs of an `Operation`. It does not hold the values of that operation's output, but instead provides a means of computing those values in a TensorFlow @{tf.Session}. This class has two primary purposes: ...
does not define a `dtype` property" % tensor_type.__name__) # We expect this list to be small, so choose quadratic complexity # for registration, so that we have a tuple that can be used for # more efficient `isinstance` checks later. global _TENSOR_LIKE_TYPES _TENSOR_LIKE_TYPES = tuple(l...
256
256
4,099
12
243
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
Tensor
Tensor
198
710
198
199
f52b4e85c8408a8fc41e4969b08049f94137e308
bigcode/the-stack
train
ebc63a255334ab7a20617501
train
function
@tf_export("op_scope") @tf_contextlib.contextmanager def op_scope(values, name, default_name=None): """DEPRECATED. Same as name_scope above, just different argument order.""" logging.warn("tf.op_scope(values, name, default_name) is deprecated," " use tf.name_scope(name, default_name, values)") with...
@tf_export("op_scope") @tf_contextlib.contextmanager def op_scope(values, name, default_name=None):
"""DEPRECATED. Same as name_scope above, just different argument order.""" logging.warn("tf.op_scope(values, name, default_name) is deprecated," " use tf.name_scope(name, default_name, values)") with name_scope(name, default_name=default_name, values=values) as scope: yield scope
return it. logging.warning(e) return name else: return name # pylint: disable=g-doc-return-or-yield # pylint: disable=not-context-manager @tf_export("op_scope") @tf_contextlib.contextmanager def op_scope(values, name, default_name=None):
64
64
94
25
38
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
op_scope
op_scope
6,072
6,079
6,072
6,074
aa32247aeb777211759668ba3aa987a66e3bdbb0
bigcode/the-stack
train
ffcb1a6d63d3b017fa15db50
train
function
def convert_n_to_tensor_or_indexed_slices(values, dtype=None, name=None): """Converts `values` to a list of `Output` or `IndexedSlices` objects. Any `IndexedSlices` or `SparseTensor` objects in `values` are returned unmodified. Args: values: A list of `None`, `IndexedSlices`, `SparseTensor`, or objects th...
def convert_n_to_tensor_or_indexed_slices(values, dtype=None, name=None):
"""Converts `values` to a list of `Output` or `IndexedSlices` objects. Any `IndexedSlices` or `SparseTensor` objects in `values` are returned unmodified. Args: values: A list of `None`, `IndexedSlices`, `SparseTensor`, or objects that can be consumed by `convert_to_tensor()`. dtype: (Optional.) ...
else: n = None if name is None else "%s_%d" % (name, i) ret.append( internal_convert_to_tensor_or_indexed_slices( value, dtype=dtype, name=n, as_ref=as_ref)) return ret def convert_n_to_tensor_or_indexed_slices(values, dtype=None, name=None):
76
76
254
18
57
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
convert_n_to_tensor_or_indexed_slices
convert_n_to_tensor_or_indexed_slices
1,316
1,341
1,316
1,316
b27eb9c133eb89d222bc19c4e207cf7742cbe883
bigcode/the-stack
train
be09ae4e1a2a9f6123468348
train
function
def _as_graph_element(obj): """Convert `obj` to a graph element if possible, otherwise return `None`. Args: obj: Object to convert. Returns: The result of `obj._as_graph_element()` if that method is available; otherwise `None`. """ conv_fn = getattr(obj, "_as_graph_element", None) if conv_...
def _as_graph_element(obj):
"""Convert `obj` to a graph element if possible, otherwise return `None`. Args: obj: Object to convert. Returns: The result of `obj._as_graph_element()` if that method is available; otherwise `None`. """ conv_fn = getattr(obj, "_as_graph_element", None) if conv_fn and callable(conv_fn): ...
s cannot be overwritten again on class %s." % (operator, clazz_object)) if operator not in Tensor.OVERLOADABLE_OPERATORS: raise ValueError("Overriding %s is disallowed" % operator) setattr(clazz_object, operator, func) def _as_graph_element(obj):
64
64
94
7
57
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_as_graph_element
_as_graph_element
109
122
109
109
7b52a616f2eb093afa4b29cdaa9fa1bfae68eb88
bigcode/the-stack
train
ca58c498574a9ee9ef0bc322
train
class
class _TensorLike(object): """Internal cls for grouping Tensor, SparseTensor, ..., for is_instance.""" pass
class _TensorLike(object):
"""Internal cls for grouping Tensor, SparseTensor, ..., for is_instance.""" pass
.numpy()) else: text = "<unprintable>" if "\n" in text: text = "\n" + text return text # NOTE(ebrevdo): Do not subclass this. If you do, I will break you on purpose. class _TensorLike(object):
64
64
25
6
58
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_TensorLike
_TensorLike
193
195
193
193
bb6ae3d307afca285c06c1ac38ffe0c4373fea4f
bigcode/the-stack
train
3b432e4290664e8d83f35ede
train
class
class _NullContextmanager(object): def __enter__(self): pass def __exit__(self, type_arg, value_arg, traceback_arg): return False # False values do not suppress exceptions
class _NullContextmanager(object):
def __enter__(self): pass def __exit__(self, type_arg, value_arg, traceback_arg): return False # False values do not suppress exceptions
_USE_C_SHAPES = os.getenv("TF_C_API_GRAPH_CONSTRUCTION_SHAPES", "0") is not "0" def tensor_id(tensor): """Returns a unique identifier for this Tensor.""" return tensor._id # pylint: disable=protected-access class _NullContextmanager(object):
64
64
45
7
56
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_NullContextmanager
_NullContextmanager
76
82
76
77
35b4198ae22d88c5535f49bb1db558dc0a622330
bigcode/the-stack
train
95c8acf52a06698f7cc6e01f
train
function
def uid(): """A unique (within this program execution) integer.""" return c_api.TFE_Py_UID()
def uid():
"""A unique (within this program execution) integer.""" return c_api.TFE_Py_UID()
complexity # for registration, so that we have a tuple that can be used for # more efficient `isinstance` checks later. global _TENSOR_LIKE_TYPES _TENSOR_LIKE_TYPES = tuple(list(_TENSOR_LIKE_TYPES) + [tensor_type]) def uid():
64
64
25
3
61
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
uid
uid
176
178
176
176
55b3d03838f9ff6e9e331611d1aebc16cf19076e
bigcode/the-stack
train
4b5be497afe362204017bd88
train
function
def _device_string(dev_spec): if isinstance(dev_spec, pydev.DeviceSpec): return dev_spec.to_string() else: return dev_spec
def _device_string(dev_spec):
if isinstance(dev_spec, pydev.DeviceSpec): return dev_spec.to_string() else: return dev_spec
._dense_shape is not None else "") def __neg__(self): return IndexedSlices(-self.values, self.indices, self.dense_shape) IndexedSlicesValue = collections.namedtuple( "IndexedSlicesValue", ["values", "indices", "dense_shape"]) def _device_string(dev_spec):
63
64
33
7
56
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_device_string
_device_string
1,511
1,515
1,511
1,511
8cb2fcda5b66cc05b97852c65a69376d2c86191b
bigcode/the-stack
train
df0b1076b93c4fefa18b39ba
train
function
def internal_convert_n_to_tensor_or_indexed_slices(values, dtype=None, name=None, as_ref=False): """Converts `values` to a list of `Tensor` or `IndexedSlices` object...
def internal_convert_n_to_tensor_or_indexed_slices(values, dtype=None, name=None, as_ref=False):
"""Converts `values` to a list of `Tensor` or `IndexedSlices` objects. Any `IndexedSlices` or `SparseTensor` objects in `values` are returned unmodified. Args: values: A list of `None`, `IndexedSlices`, `SparseTensor`, or objects that can be consumed by `convert_to_tensor()`. dtype: (Optional.) ...
).is_compatible_with(value.dtype): raise ValueError( "Tensor conversion requested dtype %s for Tensor with dtype %s: %r" % (dtypes.as_dtype(dtype).name, value.dtype.name, str(value))) return value else: return internal_convert_to_tensor( value, dtype=dtype, name=name, as_ref=...
105
105
350
26
79
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
internal_convert_n_to_tensor_or_indexed_slices
internal_convert_n_to_tensor_or_indexed_slices
1,274
1,313
1,274
1,277
e7ee5cfcbd24ab6757127c097265a85381956d70
bigcode/the-stack
train
ec3b20ac60927bc23541301f
train
function
def _assert_collection_is_ok(collection_name): if context.executing_eagerly(): if collection_name in GraphKeys._VARIABLE_COLLECTIONS: # pylint: disable=protected-access raise ValueError( "variable collections are not supported when eager execution is enabled." )
def _assert_collection_is_ok(collection_name):
if context.executing_eagerly(): if collection_name in GraphKeys._VARIABLE_COLLECTIONS: # pylint: disable=protected-access raise ValueError( "variable collections are not supported when eager execution is enabled." )
)[1] except LookupError: return None def get_from_proto_function(collection_name): """Returns the from_proto function for collection_name.""" try: return _proto_function_registry.lookup(collection_name)[2] except LookupError: return None def _assert_collection_is_ok(collection_name):
64
64
59
9
54
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_assert_collection_is_ok
_assert_collection_is_ok
6,137
6,142
6,137
6,137
8661ed94d37f4dcd87ce6a781ddd6b0ff53139f0
bigcode/the-stack
train
9681ee887f55f2b2b02abd18
train
function
def get_name_scope(): """Returns the current name scope in the default_graph. For example: ```python with tf.name_scope('scope1'): with tf.name_scope('scope2'): print(tf.get_name_scope()) ``` would print the string `scope1/scope2`. Returns: A string representing the current name scope. ...
def get_name_scope():
"""Returns the current name scope in the default_graph. For example: ```python with tf.name_scope('scope1'): with tf.name_scope('scope2'): print(tf.get_name_scope()) ``` would print the string `scope1/scope2`. Returns: A string representing the current name scope. """ if context.execu...
wish to use the default graph in that thread, you must explicitly add a `with g.as_default():` in that thread's function. Returns: The default `Graph` being used in the current thread. """ return _default_graph_stack.get_default() def get_name_scope():
64
64
106
5
59
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
get_name_scope
get_name_scope
5,560
5,577
5,560
5,560
ac63ee0b297bdeade068356735f8c7b8cb167025
bigcode/the-stack
train
0f5b3c3b11344e94d81bd049
train
function
def _get_graph_from_inputs(op_input_list, graph=None): """Returns the appropriate graph to use for the given inputs. This library method provides a consistent algorithm for choosing the graph in which an Operation should be constructed: 1. If the default graph is being used to construct a function, we us...
def _get_graph_from_inputs(op_input_list, graph=None):
"""Returns the appropriate graph to use for the given inputs. This library method provides a consistent algorithm for choosing the graph in which an Operation should be constructed: 1. If the default graph is being used to construct a function, we use the default graph. 2. If the "graph" is specified e...
_scope(): """Returns the current name scope in the default_graph. For example: ```python with tf.name_scope('scope1'): with tf.name_scope('scope2'): print(tf.get_name_scope()) ``` would print the string `scope1/scope2`. Returns: A string representing the current name scope. """ if con...
208
208
694
13
195
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_get_graph_from_inputs
_get_graph_from_inputs
5,595
5,661
5,595
5,595
614604c2782ccda1987d316e515e936f91d10605
bigcode/the-stack
train
3c9c03cc82a5f161102d15df
train
function
def tensor_id(tensor): """Returns a unique identifier for this Tensor.""" return tensor._id # pylint: disable=protected-access
def tensor_id(tensor):
"""Returns a unique identifier for this Tensor.""" return tensor._id # pylint: disable=protected-access
and there's no performance penalty with it enabled. _USE_C_API = os.getenv("TF_C_API_GRAPH_CONSTRUCTION", "1") is not "0" _USE_C_SHAPES = os.getenv("TF_C_API_GRAPH_CONSTRUCTION_SHAPES", "0") is not "0" def tensor_id(tensor):
64
64
30
6
58
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
tensor_id
tensor_id
71
73
71
71
2261182f6ed03960ae2c0be7690836a06a4be355
bigcode/the-stack
train
bc2bf599936175ae32179c9d
train
class
class _EagerTensorBase(Tensor): """Base class for EagerTensor.""" @property def dtype(self): # Note: using the intern table directly here as this is # performance-sensitive in some models. return dtypes._INTERN_TABLE[self._datatype_enum()] # pylint: disable=protected-access def numpy(self): "...
class _EagerTensorBase(Tensor):
"""Base class for EagerTensor.""" @property def dtype(self): # Note: using the intern table directly here as this is # performance-sensitive in some models. return dtypes._INTERN_TABLE[self._datatype_enum()] # pylint: disable=protected-access def numpy(self): """Returns a numpy array or a sca...
t:` to test if a " "tensor is defined, and use TensorFlow ops such as " "tf.cond to execute subgraphs conditioned on the value of " "a tensor.") def eval(self, feed_dict=None, session=None): """Evaluates this tensor in a `Session`. Calling this me...
256
256
1,679
9
247
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_EagerTensorBase
_EagerTensorBase
714
934
714
714
3095faf543959459aacb2684814fa830508517c3
bigcode/the-stack
train
b9bafc2ab5ab7f947172738d
train
function
def internal_convert_to_tensor_or_indexed_slices(value, dtype=None, name=None, as_ref=False): """Converts the given object to an `Tensor` or an `IndexedSlices`. If `val...
def internal_convert_to_tensor_or_indexed_slices(value, dtype=None, name=None, as_ref=False):
"""Converts the given object to an `Tensor` or an `IndexedSlices`. If `value` is an `IndexedSlices` or `SparseTensor` it is returned unmodified. Otherwise, it is converted to a `Tensor` using `convert_to_tensor()`. Args: value: An `IndexedSlices`, `SparseTensor`, or an object that can be consumed ...
to use if a new `Tensor` is created. Returns: An `Tensor`, `IndexedSlices`, or `SparseTensor` based on `value`. Raises: ValueError: If `dtype` does not match the element type of `value`. """ return internal_convert_to_tensor_or_indexed_slices( value=value, dtype=dtype, name=name, as_ref=False) ...
108
108
360
25
83
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
internal_convert_to_tensor_or_indexed_slices
internal_convert_to_tensor_or_indexed_slices
1,236
1,271
1,236
1,239
000bb298f9558349c74f8830d88f5b0393b43705
bigcode/the-stack
train
fd3b361540dda329c1d05db5
train
class
@tf_export("name_scope", "keras.backend.name_scope") class name_scope(object): # pylint: disable=invalid-name """A context manager for use when defining a Python op. This context manager validates that the given `values` are from the same graph, makes that graph the default graph, and pushes a name scope in t...
@tf_export("name_scope", "keras.backend.name_scope") class name_scope(object): # pylint: disable=invalid-name
"""A context manager for use when defining a Python op. This context manager validates that the given `values` are from the same graph, makes that graph the default graph, and pushes a name scope in that graph (see @{tf.Graph.name_scope} for more details on that). For example, to define a new Python op ...
.) If supplied, the resulting list is filtered to include only items whose `name` attribute matches using `re.match`. Items without a `name` attribute are never returned if a scope is supplied and the choice or `re.match` means that a `scope` without special tokens filters by prefix. Returns:...
256
256
900
27
229
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
name_scope
name_scope
5,914
6,012
5,914
5,915
615a52baa303c4e8b7726b5f73524698adaa70ce
bigcode/the-stack
train
86a68b835f9fa531151a2e49
train
class
@tf_export("Graph") class Graph(object): """A TensorFlow computation, represented as a dataflow graph. A `Graph` contains a set of @{tf.Operation} objects, which represent units of computation; and @{tf.Tensor} objects, which represent the units of data that flow between operations. A default `Graph` is...
@tf_export("Graph") class Graph(object):
"""A TensorFlow computation, represented as a dataflow graph. A `Graph` contains a set of @{tf.Operation} objects, which represent units of computation; and @{tf.Tensor} objects, which represent the units of data that flow between operations. A default `Graph` is always registered, and accessible by cal...
's statistics function in the registry and calls it. This function takes a Graph object and a NodeDef from a GraphDef, and if there's an associated statistics method, calls it and returns a result. If no function has been registered for the particular node type, it returns an empty statistics object. Args: ...
256
256
18,832
10
245
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
Graph
Graph
2,778
4,949
2,778
2,779
554f34e4623c990cd5fbcfc6e9da1df816835078
bigcode/the-stack
train
8c4c0549a6716e8ccdb823c1
train
class
@tf_export("Operation") class Operation(object): """Represents a graph node that performs computation on tensors. An `Operation` is a node in a TensorFlow `Graph` that takes zero or more `Tensor` objects as input, and produces zero or more `Tensor` objects as output. Objects of type `Operation` are created by ...
@tf_export("Operation") class Operation(object):
"""Represents a graph node that performs computation on tensors. An `Operation` is a node in a TensorFlow `Graph` that takes zero or more `Tensor` objects as input, and produces zero or more `Tensor` objects as output. Objects of type `Operation` are created by calling a Python op constructor (such as @{tf...
), compat.as_str(node_def.name)) # Add inputs for op_input in inputs: if isinstance(op_input, (list, tuple)): c_api.TF_AddInputList(op_desc, [t._as_tf_output() for t in op_input]) else: c_api.TF_AddInput(op_desc, op_input._as_tf_output()) # Add control inputs...
256
256
6,717
10
245
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
Operation
Operation
1,600
2,402
1,600
1,601
c44b80adda2f9022a2dbf578d6f62326fddf350e
bigcode/the-stack
train
ff240c97b7bc71ae5945106a
train
function
@tf_export("get_collection") def get_collection(key, scope=None): """Wrapper for `Graph.get_collection()` using the default graph. See @{tf.Graph.get_collection} for more details. Args: key: The key for the collection. For example, the `GraphKeys` class contains many standard names for collections. ...
@tf_export("get_collection") def get_collection(key, scope=None):
"""Wrapper for `Graph.get_collection()` using the default graph. See @{tf.Graph.get_collection} for more details. Args: key: The key for the collection. For example, the `GraphKeys` class contains many standard names for collections. scope: (Optional.) If supplied, the resulting list is filtered...
collection list itself, which can be modified in place to change the collection. @compatibility(eager) Collections are not supported when eager execution is enabled. @end_compatibility """ return get_default_graph().get_collection_ref(key) @tf_export("get_collection") def get_collection(key, scope=None)...
70
70
235
15
55
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
get_collection
get_collection
5,874
5,900
5,874
5,875
389eac2f76690adad38737ca7f0a67ee00251c37
bigcode/the-stack
train
3a958115ec5770bfeb079b84
train
function
def _TensorTensorConversionFunction(t, dtype=None, name=None, as_ref=False): _ = name, as_ref if dtype and not dtype.is_compatible_with(t.dtype): raise ValueError( "Tensor conversion requested dtype %s for Tensor with dtype %s: %r" % (dtype.name, t.dtype.name, str(t))) return t
def _TensorTensorConversionFunction(t, dtype=None, name=None, as_ref=False):
_ = name, as_ref if dtype and not dtype.is_compatible_with(t.dtype): raise ValueError( "Tensor conversion requested dtype %s for Tensor with dtype %s: %r" % (dtype.name, t.dtype.name, str(t))) return t
an EagerTensor class, as a subclass of _EagerTensorBase, and # registers it with the current module. EagerTensor = c_api.TFE_Py_InitEagerTensor(_EagerTensorBase) def _TensorTensorConversionFunction(t, dtype=None, name=None, as_ref=False):
64
64
79
18
46
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_TensorTensorConversionFunction
_TensorTensorConversionFunction
942
948
942
942
97f17a10a068c77c89129dc4db76563a4b6221e6
bigcode/the-stack
train
9bfc80872283e7ab166aa3f5
train
function
@tf_export("convert_to_tensor_or_indexed_slices") def convert_to_tensor_or_indexed_slices(value, dtype=None, name=None): """Converts the given object to a `Tensor` or an `IndexedSlices`. If `value` is an `IndexedSlices` or `SparseTensor` it is returned unmodified. Otherwise, it is converted to a `Tensor` using ...
@tf_export("convert_to_tensor_or_indexed_slices") def convert_to_tensor_or_indexed_slices(value, dtype=None, name=None):
"""Converts the given object to a `Tensor` or an `IndexedSlices`. If `value` is an `IndexedSlices` or `SparseTensor` it is returned unmodified. Otherwise, it is converted to a `Tensor` using `convert_to_tensor()`. Args: value: An `IndexedSlices`, `SparseTensor`, or an object that can be consumed b...
invalid value. """ return internal_convert_n_to_tensor( values=values, dtype=dtype, name=name, preferred_dtype=preferred_dtype, as_ref=False) @tf_export("convert_to_tensor_or_indexed_slices") def convert_to_tensor_or_indexed_slices(value, dtype=None, name=None):
71
71
238
30
41
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
convert_to_tensor_or_indexed_slices
convert_to_tensor_or_indexed_slices
1,211
1,233
1,211
1,212
6a45b9881bda83b3c167c872c4160c0edf9f4cf8
bigcode/the-stack
train
c5ed75e80211309c084b6726
train
function
@tf_contextlib.contextmanager def _enter_context_and_graph(context_fn, graph_fn): """Combines two context managers.""" with context_fn(), graph_fn(): yield
@tf_contextlib.contextmanager def _enter_context_and_graph(context_fn, graph_fn):
"""Combines two context managers.""" with context_fn(), graph_fn(): yield
es.push(default.building_function, default.as_default) with super(_DefaultGraphStack, self).get_controller(default) as g: yield g finally: context.context().context_switches.pop() @tf_contextlib.contextmanager def _enter_context_and_graph(context_f...
64
64
38
19
45
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_enter_context_and_graph
_enter_context_and_graph
5,295
5,299
5,295
5,296
d414d4e5aec1295034209ee1f570adebcd3fc607
bigcode/the-stack
train
af155464353564eb74424432
train
function
@tf_export("colocate_with") def colocate_with(op, ignore_existing=False): return _colocate_with_for_gradient(op, None, ignore_existing=ignore_existing)
@tf_export("colocate_with") def colocate_with(op, ignore_existing=False):
return _colocate_with_for_gradient(op, None, ignore_existing=ignore_existing)
an Eager-defined Tensor during graph " "construction, but a function was not being built.") return default_graph._colocate_with_for_gradient( op, gradient_uid=gradient_uid, ignore_existing=ignore_existing) @tf_export("colocate_with") def colocate_with(op, ignore_existing=False):
64
64
36
18
46
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
colocate_with
colocate_with
5,018
5,020
5,018
5,019
3bf25b558ca662e9f4e8e60619d1914dcddfaacf
bigcode/the-stack
train
408bc8d7fd1e968595a9ed88
train
function
def _name_from_scope_name(name): """Returns the name of an op given the name of its scope. Args: name: the name of the scope. Returns: the name of the op (equal to scope name minus any trailing slash). """ return name[:-1] if (name and name[-1] == "/") else name
def _name_from_scope_name(name):
"""Returns the name of an op given the name of its scope. Args: name: the name of the scope. Returns: the name of the op (equal to scope name minus any trailing slash). """ return name[:-1] if (name and name[-1] == "/") else name
Stats object containing information about resource usage. """ try: stats_func = _stats_registry.lookup(node.op + "," + statistic_type) result = stats_func(graph, node) except LookupError: result = OpStats(statistic_type) return result def _name_from_scope_name(name):
64
64
76
8
55
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_name_from_scope_name
_name_from_scope_name
2,766
2,775
2,766
2,766
f5c7a5e979deea335aff130a0a97b8a8fd501c03
bigcode/the-stack
train
4dec1b72ccd80b6eec038cd8
train
class
class _DefaultStack(threading.local): """A thread-local stack of objects for providing implicit defaults.""" def __init__(self): super(_DefaultStack, self).__init__() self._enforce_nesting = True self.stack = [] def get_default(self): return self.stack[-1] if len(self.stack) >= 1 else None de...
class _DefaultStack(threading.local):
"""A thread-local stack of objects for providing implicit defaults.""" def __init__(self): super(_DefaultStack, self).__init__() self._enforce_nesting = True self.stack = [] def get_default(self): return self.stack[-1] if len(self.stack) >= 1 else None def reset(self): self.stack = [] ...
for all operations constructed within the context. """ if context.executing_eagerly(): if control_inputs: # Excute any pending callables. for control in control_inputs: if callable(control): control() return _NullContextmanager() else: return get_default_graph().contr...
79
79
265
8
71
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_DefaultStack
_DefaultStack
5,055
5,096
5,055
5,055
1af7670439accb5cd35d1739607d1bf745448685
bigcode/the-stack
train
6a53711558b3b5876e941d6d
train
function
def is_dense_tensor_like(t): """EXPERIMENTAL: Returns true if `t` implements the tensor interface. See `register_dense_tensor_like_type()` for the current definition of a "tensor-like type". Args: t: An object. Returns: True iff `t` is an instance of one of the registered "tensor-like" types. """...
def is_dense_tensor_like(t):
"""EXPERIMENTAL: Returns true if `t` implements the tensor interface. See `register_dense_tensor_like_type()` for the current definition of a "tensor-like type". Args: t: An object. Returns: True iff `t` is an instance of one of the registered "tensor-like" types. """ return isinstance(t, _TENS...
as_graph_element()` if that method is available; otherwise `None`. """ conv_fn = getattr(obj, "_as_graph_element", None) if conv_fn and callable(conv_fn): return conv_fn() return None _TENSOR_LIKE_TYPES = tuple() def is_dense_tensor_like(t):
64
64
93
7
57
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
is_dense_tensor_like
is_dense_tensor_like
128
140
128
128
539258c0e10a003368687bbd341dc8f033ebbe25
bigcode/the-stack
train
de7e0bf30862289d57c07953
train
function
def convert_n_to_tensor(values, dtype=None, name=None, preferred_dtype=None): """Converts `values` to a list of `Tensor` objects. Args: values: A list of objects that can be consumed by `tf.convert_to_tensor()`. dtype: (Optional.) The required `DType` of the returned `Tensor` objects. name: (Optional.)...
def convert_n_to_tensor(values, dtype=None, name=None, preferred_dtype=None):
"""Converts `values` to a list of `Tensor` objects. Args: values: A list of objects that can be consumed by `tf.convert_to_tensor()`. dtype: (Optional.) The required `DType` of the returned `Tensor` objects. name: (Optional.) A name prefix to used when a new `Tensor` is created, in which case ele...
enumerate(values): n = None if name is None else "%s_%d" % (name, i) ret.append( internal_convert_to_tensor( value, dtype=dtype, name=n, as_ref=as_ref, preferred_dtype=preferred_dtype, ctx=ctx)) return ret def convert_n_to_tensor...
85
85
284
17
67
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
convert_n_to_tensor
convert_n_to_tensor
1,179
1,208
1,179
1,179
9256990f7eba770b68cf680785d7b2479112f854
bigcode/the-stack
train
2049401a4927524905993f11
train
function
def strip_name_scope(name, export_scope): """Removes name scope from a name. Args: name: A `string` name. export_scope: Optional `string`. Name scope to remove. Returns: Name with name scope removed, or the original name if export_scope is None. """ if export_scope: if export_scope[-1] =...
def strip_name_scope(name, export_scope):
"""Removes name scope from a name. Args: name: A `string` name. export_scope: Optional `string`. Name scope to remove. Returns: Name with name scope removed, or the original name if export_scope is None. """ if export_scope: if export_scope[-1] == "/": export_scope = export_scope[:...
= self._old_name else: self._name_scope.__exit__(type_arg, value_arg, traceback_arg) self._g_manager.__exit__(type_arg, value_arg, traceback_arg) return False # False values do not suppress exceptions def strip_name_scope(name, export_scope):
64
64
207
9
54
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
strip_name_scope
strip_name_scope
6,015
6,040
6,015
6,015
0bd51acc34582395bff9240d785d1109fdad12a2
bigcode/the-stack
train
af0147321c36de0bda27bfd8
train
function
def _set_shape_and_handle_data_for_outputs_c_api(op): """Set shapes and resource handle data using info from the C API.""" assert not _USE_C_SHAPES for output in op.outputs: output._shape_val = output._c_api_shape() # Set the resource handle data for compatibility with the Python shape # inference cod...
def _set_shape_and_handle_data_for_outputs_c_api(op):
"""Set shapes and resource handle data using info from the C API.""" assert not _USE_C_SHAPES for output in op.outputs: output._shape_val = output._c_api_shape() # Set the resource handle data for compatibility with the Python shape # inference code. serialized = c_api.GetResourceHandleShapeAndTyp...
more of the standard op # libraries. pass else: _shape_registry.register(f, self._op_type) return f # TODO(b/74620627): remove when _USE_C_SHAPES is removed def _set_shape_and_handle_data_for_outputs_c_api(op):
64
64
149
13
50
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
_set_shape_and_handle_data_for_outputs_c_api
_set_shape_and_handle_data_for_outputs_c_api
2,562
2,576
2,562
2,562
0ed1ed4f62582fcf0192fac17d28dc933af03b7e
bigcode/the-stack
train
435200d57b00c44b2fa1c943
train
function
@tf_export("get_default_graph") def get_default_graph(): """Returns the default graph for the current thread. The returned graph will be the innermost graph on which a `Graph.as_default()` context has been entered, or a global default graph if none has been explicitly created. NOTE: The default graph is a p...
@tf_export("get_default_graph") def get_default_graph():
"""Returns the default graph for the current thread. The returned graph will be the innermost graph on which a `Graph.as_default()` context has been entered, or a global default graph if none has been explicitly created. NOTE: The default graph is a property of the current thread. If you create a new thre...
_cleared(): raise AssertionError("Do not use tf.reset_default_graph() to clear " "nested graphs. If you need a cleared graph, " "exit the nesting and create a new graph.") _default_graph_stack.reset() @tf_export("get_default_graph") def get_default_graph():
64
64
147
13
51
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
get_default_graph
get_default_graph
5,541
5,557
5,541
5,542
fad1f196c711a08e7ca8e4fcf145fe7f34e7bd32
bigcode/the-stack
train
b3efb33c709120445c578213
train
class
@tf_export("IndexedSlices") class IndexedSlices(_TensorLike): """A sparse representation of a set of tensor slices at given indices. This class is a simple wrapper for a pair of `Tensor` objects: * `values`: A `Tensor` of any dtype with shape `[D0, D1, ..., Dn]`. * `indices`: A 1-D integer `Tensor` with shape...
@tf_export("IndexedSlices") class IndexedSlices(_TensorLike):
"""A sparse representation of a set of tensor slices at given indices. This class is a simple wrapper for a pair of `Tensor` objects: * `values`: A `Tensor` of any dtype with shape `[D0, D1, ..., Dn]`. * `indices`: A 1-D integer `Tensor` with shape `[D0]`. An `IndexedSlices` is typically used to represent ...
from the main # function if the context._context is already created, and the # register_tensor_conversion_function calls happen when the module is # imported. if context._context is not None and context.executing_eagerly( ) and isinstance(base_type, six.integer_types + ( float, np.n...
197
198
662
14
183
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
IndexedSlices
IndexedSlices
1,422
1,504
1,422
1,423
b0633c18a25d083b9b84476a52190042acbf1cdd
bigcode/the-stack
train
20c9f32cf8320d308a895343
train
function
def prepend_name_scope(name, import_scope): """Prepends name scope to a name. Args: name: A `string` name. import_scope: Optional `string`. Name scope to add. Returns: Name with name scope added, or the original name if import_scope is None. """ if import_scope: if import_scope[-1] == "/...
def prepend_name_scope(name, import_scope):
"""Prepends name scope to a name. Args: name: A `string` name. import_scope: Optional `string`. Name scope to add. Returns: Name with name scope added, or the original name if import_scope is None. """ if import_scope: if import_scope[-1] == "/": import_scope = import_scope[:-1] ...
"\1\2", compat.as_str(name), count=1) except TypeError as e: # If the name is not of a type we can process, simply return it. logging.warning(e) return name else: return name def prepend_name_scope(name, import_scope):
64
64
180
9
54
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
prepend_name_scope
prepend_name_scope
6,043
6,067
6,043
6,043
f5dfa8b93331f191c3233a940d3ac557a028f12d
bigcode/the-stack
train
df6d8af72b544efd5060811c
train
class
class RegisterShape(object): """No longer used. Was: A decorator for registering a shape function. Shape functions must now be registered via the SetShapeFn on the original Op specification in C++. """ def __init__(self, op_type): """Saves the `op_type` as the `Operation` type.""" if not isinstanc...
class RegisterShape(object):
"""No longer used. Was: A decorator for registering a shape function. Shape functions must now be registered via the SetShapeFn on the original Op specification in C++. """ def __init__(self, op_type): """Saves the `op_type` as the `Operation` type.""" if not isinstance(op_type, six.string_types):...
# already registered def call_without_requiring(op): return call_cpp_shape_fn(op, require_shape_fn=False) _call_cpp_shape_fn = call_without_requiring def call_with_requiring(op): return call_cpp_shape_fn(op, require_shape_fn=True) _call_cpp_shape_fn_and_require_op = call_with_requiring class Regis...
79
79
265
5
73
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
RegisterShape
RegisterShape
2,526
2,558
2,526
2,526
ccad06746fada80bcfd31a19342798d432f6d019
bigcode/the-stack
train
47e77b5fdd6febf00700695f
train
function
@tf_export("reset_default_graph") def reset_default_graph(): """Clears the default graph stack and resets the global default graph. NOTE: The default graph is a property of the current thread. This function applies only to the current thread. Calling this function while a `tf.Session` or `tf.InteractiveSessio...
@tf_export("reset_default_graph") def reset_default_graph():
"""Clears the default graph stack and resets the global default graph. NOTE: The default graph is a property of the current thread. This function applies only to the current thread. Calling this function while a `tf.Session` or `tf.InteractiveSession` is active will result in undefined behavior. Using any p...
name__ == "__main__": tfe.run() ``` Args: main: the main function to run. argv: the arguments to pass to it. """ enable_eager_execution() app.run(main, argv) @tf_export("reset_default_graph") def reset_default_graph():
64
64
186
13
51
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
reset_default_graph
reset_default_graph
5,522
5,538
5,522
5,523
f7ec453c3ea91a50c2c79c2916f0d0afb32afbe7
bigcode/the-stack
train
24d6bd46cddf413be3aed0ba
train
function
def get_stats_for_node_def(graph, node, statistic_type): """Looks up the node's statistics function in the registry and calls it. This function takes a Graph object and a NodeDef from a GraphDef, and if there's an associated statistics method, calls it and returns a result. If no function has been registered f...
def get_stats_for_node_def(graph, node, statistic_type):
"""Looks up the node's statistics function in the registry and calls it. This function takes a Graph object and a NodeDef from a GraphDef, and if there's an associated statistics method, calls it and returns a result. If no function has been registered for the particular node type, it returns an empty statis...
_type def __call__(self, f): """Registers "f" as the statistics function for "op_type".""" _stats_registry.register(f, self._op_type + "," + self._statistic_type) return f def get_stats_for_node_def(graph, node, statistic_type):
64
64
189
13
50
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
get_stats_for_node_def
get_stats_for_node_def
2,742
2,763
2,742
2,742
c733e0d74d38017dd542072c4652446fbd31b5f3
bigcode/the-stack
train
337b6aa7a27b0bf526c97c3d
train
function
@tf_export("enable_eager_execution") def enable_eager_execution(config=None, device_policy=None, execution_mode=None): """Enables eager execution for the lifetime of this program. Eager execution provides an imperative interface to TensorFlow. With eager execution enabled, TensorFlow f...
@tf_export("enable_eager_execution") def enable_eager_execution(config=None, device_policy=None, execution_mode=None):
"""Enables eager execution for the lifetime of this program. Eager execution provides an imperative interface to TensorFlow. With eager execution enabled, TensorFlow functions execute operations immediately (as opposed to adding to a graph to be executed later in a @{tf.Session}) and return concrete values (...
.building_function: raise RuntimeError("The global graph is building a function.") outer_context = default_graph.as_default else: # Find a context that is not building a function. for stack_entry in reversed(context.context().context_switches.stack): if not stack_entry.is_building_...
256
256
1,168
26
229
P-Hidringer/tensorflow
tensorflow/python/framework/ops.py
Python
enable_eager_execution
enable_eager_execution
5,383
5,491
5,383
5,385
ec01726b74a42bfd9a405b661fcbfe775709dc93
bigcode/the-stack
train
eafc22c6fd3378099fd0867c
train
function
def bot_log_embed(ctx, bot_and_owner: Tuple[Union[discord.Member, int], Union[discord.Member, int]], *, reason: str=None): def escape_markdown(txt: str): return discord.utils.escape_markdown(str(txt)) bot, bot_owner=bot_and_owner bot_text=f"[{escape_markdown(str(bot))} ({bot.id})](...
def bot_log_embed(ctx, bot_and_owner: Tuple[Union[discord.Member, int], Union[discord.Member, int]], *, reason: str=None):
def escape_markdown(txt: str): return discord.utils.escape_markdown(str(txt)) bot, bot_owner=bot_and_owner bot_text=f"[{escape_markdown(str(bot))} ({bot.id})](https://blist.xyz/bot/{bot.id})" \ if isinstance(bot, discord.Member) else escape_markdown(str(bot)) bot_owner_text=f"[{escape_ma...
import datetime from textwrap import dedent as wrap from typing import Union, Tuple, Dict import discord import googletrans import asyncio import typing from discord.ext import commands, flags from utils import checks from utils.time import time_took def bot_log_embed(ctx, bot_and_owner: Tuple[Union[discord.Member, in...
88
147
492
33
54
KowlinMC/BlistBot
cogs/staff_site.py
Python
bot_log_embed
bot_log_embed
14
44
14
15
edb516e2a4429bea39d83379bbc4f91f7c00146b
bigcode/the-stack
train
f1fc8ba29f24fd1a6c1d1a70
train
function
def setup(bot): bot.add_cog(Staff(bot))
def setup(bot):
bot.add_cog(Staff(bot))
=[x for x in await ctx.channel.pins() if x.embeds and x.embeds[0].author] if not channel_pins_hold_embeds: return try: await channel_pins_hold_embeds[0].unpin() except: return def setup(bot):
64
64
13
4
59
KowlinMC/BlistBot
cogs/staff_site.py
Python
setup
setup
495
496
495
495
751842013d29daadf1625fb5fc90da83536f47f6
bigcode/the-stack
train
7c873af0fc66055b7e2539eb
train
class
class Staff(commands.Cog): def __init__(self, bot): self.bot=bot self.translator=googletrans.Translator() @commands.has_permissions(kick_members=True) @commands.group(invoke_without_command=True, aliases=["q"]) async def queue(self, ctx): bots=await self.bot.pool.fetch("SELECT *...
class Staff(commands.Cog):
def __init__(self, bot): self.bot=bot self.translator=googletrans.Translator() @commands.has_permissions(kick_members=True) @commands.group(invoke_without_command=True, aliases=["q"]) async def queue(self, ctx): bots=await self.bot.pool.fetch("SELECT * FROM main_site_bot WHERE a...
": ("Bot deleted", discord.Color.red(), f"**Bot:** {bot_text}\n**Owner:** {bot_owner_text}", f"**Author:** {command_author}", str(reason)), "approve": ("Bot approved", discord.Color.green(), f"**Bot:** {bot_text}\n**Owner:** {bot_owner_text}", f"**Reviewer:** {command_auth...
256
256
4,374
6
249
KowlinMC/BlistBot
cogs/staff_site.py
Python
Staff
Staff
47
492
47
47
97de5a909f531d77134307b165e05d7b1f0de92a
bigcode/the-stack
train
30a23166eee2a99d03258322
train
function
def wiki_setup_safe_interwiki(tc): wiki_setup(tc) tc.env.config.set('wiki', 'render_unsafe_content', 'false') tc.env.config.set('wiki', 'safe_schemes', 'file,ftp,git,irc,http,https,ssh,svn,tsvn')
def wiki_setup_safe_interwiki(tc):
wiki_setup(tc) tc.env.config.set('wiki', 'render_unsafe_content', 'false') tc.env.config.set('wiki', 'safe_schemes', 'file,ftp,git,irc,http,https,ssh,svn,tsvn')
tc.env.db_transaction("INSERT INTO ticket (id) VALUES ('123')") def wiki_teardown(tc): tc.env.reset_db() def wiki_setup_split(tc): tc.env.config.set('wiki', 'split_page_names', 'true') wiki_setup(tc) def wiki_setup_safe_interwiki(tc):
64
64
64
8
56
exocad/exotrac
trac/wiki/tests/wikisyntax.py
Python
wiki_setup_safe_interwiki
wiki_setup_safe_interwiki
766
770
766
766
745378274c98fb09b16e5301f41f946b04c99521
bigcode/the-stack
train
b73c6c9f357a0ff137a9e207
train
function
def wiki_setup(tc): tc.env.config.set('wiki', 'render_unsafe_content', True) # for #9712 now = datetime.now(utc) wiki0 = WikiPage(tc.env) wiki0.name = 'Main/Sub' wiki0.text = '--' wiki0.save('joe', 'subpage', '::1', now) wiki1 = WikiPage(tc.env) wiki1.name = 'TestPage' wiki1.text = ...
def wiki_setup(tc):
tc.env.config.set('wiki', 'render_unsafe_content', True) # for #9712 now = datetime.now(utc) wiki0 = WikiPage(tc.env) wiki0.name = 'Main/Sub' wiki0.text = '--' wiki0.save('joe', 'subpage', '::1', now) wiki1 = WikiPage(tc.env) wiki1.name = 'TestPage' wiki1.text = '--' wiki1.save(...
title="InterMapTxt in MeatBall..."><span class="icon"></span>MeatBall:InterMapTxt</a> wiki page. </p> <p> Checkout the <a class="ext-link" href="tsvn:http://svn.edgewall.com/repos/trac" title="http://svn.edgewall.com/repos/trac in tsvn"><span class="icon"></span>Trac Repository</a>. </p> <p> complex link <a class="ext...
182
183
611
5
177
exocad/exotrac
trac/wiki/tests/wikisyntax.py
Python
wiki_setup
wiki_setup
687
754
687
687
a850202445a3b9e20028f86a1b80c288d1846695
bigcode/the-stack
train
77646107f3bba99e4fd9ac1a
train
function
def wiki_setup_split(tc): tc.env.config.set('wiki', 'split_page_names', 'true') wiki_setup(tc)
def wiki_setup_split(tc):
tc.env.config.set('wiki', 'split_page_names', 'true') wiki_setup(tc)
OtherThirdLevel' w.text = '--' w.save('joe', 'other third level of hierarchy', '::1', now) tc.env.db_transaction("INSERT INTO ticket (id) VALUES ('123')") def wiki_teardown(tc): tc.env.reset_db() def wiki_setup_split(tc):
64
64
27
6
58
exocad/exotrac
trac/wiki/tests/wikisyntax.py
Python
wiki_setup_split
wiki_setup_split
761
763
761
761
9e74aa6a1952f5f91c7e89b250a20041c24b10af
bigcode/the-stack
train
7cf925dd968b26d98160f08b
train
function
def suite(): suite = unittest.TestSuite() suite.addTest(formatter.suite(TEST_CASES, wiki_setup, __file__, wiki_teardown)) suite.addTest(formatter.suite(RELATIVE_LINKS_TESTS, wiki_setup, __file__, wiki_teardown, ...
def suite():
suite = unittest.TestSuite() suite.addTest(formatter.suite(TEST_CASES, wiki_setup, __file__, wiki_teardown)) suite.addTest(formatter.suite(RELATIVE_LINKS_TESTS, wiki_setup, __file__, wiki_teardown, context=...
_safe_interwiki(tc): wiki_setup(tc) tc.env.config.set('wiki', 'render_unsafe_content', 'false') tc.env.config.set('wiki', 'safe_schemes', 'file,ftp,git,irc,http,https,ssh,svn,tsvn') def suite():
64
64
184
3
61
exocad/exotrac
trac/wiki/tests/wikisyntax.py
Python
suite
suite
773
790
773
773
8aaa8858ae554f74bf4cfc14f0fb90144f732f03
bigcode/the-stack
train
0935ce57b763f407cb9f543c
train
function
def wiki_teardown(tc): tc.env.reset_db()
def wiki_teardown(tc):
tc.env.reset_db()
) w.name = 'FirstLevel/SecondLevel/OtherThirdLevel' w.text = '--' w.save('joe', 'other third level of hierarchy', '::1', now) tc.env.db_transaction("INSERT INTO ticket (id) VALUES ('123')") def wiki_teardown(tc):
63
64
12
6
58
exocad/exotrac
trac/wiki/tests/wikisyntax.py
Python
wiki_teardown
wiki_teardown
757
758
757
757
f1ff93d6b3aa9df7e786ae20a0743d81aae3ecb8
bigcode/the-stack
train
8aec28518d09d181137fa0a6
train
function
def rastrigin1(x): return 10.*len(x) + np.sum(x**2 - 10.*np.cos(2.*np.pi*x))
def rastrigin1(x):
return 10.*len(x) + np.sum(x**2 - 10.*np.cos(2.*np.pi*x))
# Rastrigin function a=10, b=2*pi import numpy as np def rastrigin1(x):
26
64
34
7
18
mcuntz/partialwrap
docs/examples_userguide/rastrigin1.py
Python
rastrigin1
rastrigin1
3
4
3
3
2a6adce9a3f2682aabc659d2e42cc21a6a5cb619
bigcode/the-stack
train
6a67ac8dc2ddc43297a4ea25
train
function
def print_hi(name): # Use a breakpoint in the code line below to debug your script. print(f'Hello {name}') # Press Ctrl+F8 to toggle the breakpoint.
def print_hi(name): # Use a breakpoint in the code line below to debug your script.
print(f'Hello {name}') # Press Ctrl+F8 to toggle the breakpoint.
Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. print('Hello Friend') def print_hi(name): # Use a breakpoint in the code line below to debug your script.
64
64
40
20
44
FahadHameed89/Webdev-Notes-2022
python_test/main.py
Python
print_hi
print_hi
9
11
9
10
894465373b7f8e49fff72456d86394bb8693a05b
bigcode/the-stack
train
08a0cd1ed10899239fccc491
train
function
def calc_check_digit(number): """Calculate the check digit for the number. The passed number should not have the check digit included.""" number = number.replace('-', '') return str( sum((i + 1) * int(n) for i, n in enumerate(reversed(number))) % 10)
def calc_check_digit(number):
"""Calculate the check digit for the number. The passed number should not have the check digit included.""" number = number.replace('-', '') return str( sum((i + 1) * int(n) for i, n in enumerate(reversed(number))) % 10)
def compact(number): """Convert the number to the minimal representation.""" number = clean(number, ' ').strip() if '-' not in number: number = '-'.join((number[:-3], number[-3:-1], number[-1:])) return number def calc_check_digit(number):
64
64
66
6
57
Semicheche/foa_frappe_docker
frappe-bench/env/lib/python2.7/site-packages/stdnum/casrn.py
Python
calc_check_digit
calc_check_digit
49
54
49
49
b29c78ba0b3f5f2a2e3710aa4aab4df0ee187951
bigcode/the-stack
train
cc42998d44b3ff551add1a3e
train
function
def compact(number): """Convert the number to the minimal representation.""" number = clean(number, ' ').strip() if '-' not in number: number = '-'.join((number[:-3], number[-3:-1], number[-1:])) return number
def compact(number):
"""Convert the number to the minimal representation.""" number = clean(number, ' ').strip() if '-' not in number: number = '-'.join((number[:-3], number[-3:-1], number[-1:])) return number
/wiki/CAS_Registry_Number >>> validate('87-86-5') '87-86-5' >>> validate('87-86-6') Traceback (most recent call last): ... InvalidChecksum: ... """ from stdnum.exceptions import * from stdnum.util import clean def compact(number):
64
64
57
4
59
Semicheche/foa_frappe_docker
frappe-bench/env/lib/python2.7/site-packages/stdnum/casrn.py
Python
compact
compact
41
46
41
41
f4fb26b291e2936528f4170654d698dc020eda97
bigcode/the-stack
train
5044a4c0cf8384902866ee12
train
function
def is_valid(number): """Check if the number provided is a valid CAS RN.""" try: return bool(validate(number)) except ValidationError: return False
def is_valid(number):
"""Check if the number provided is a valid CAS RN.""" try: return bool(validate(number)) except ValidationError: return False
or not number[-4:-2].isdigit(): raise InvalidFormat() if number[-2] != '-' or number[-5] != '-': raise InvalidFormat() if number[-1] != calc_check_digit(number[:-1]): raise InvalidChecksum() return number def is_valid(number):
64
64
36
5
58
Semicheche/foa_frappe_docker
frappe-bench/env/lib/python2.7/site-packages/stdnum/casrn.py
Python
is_valid
is_valid
71
76
71
71
c810a7c34746f4111aab77f775762f6423623be1
bigcode/the-stack
train
a8dfa48b9234d164930abeb2
train
function
def validate(number): """Check if the number provided is a valid CAS RN.""" number = compact(number) if not 7 <= len(number) <= 12: raise InvalidLength() if not number[:-5].isdigit() or not number[-4:-2].isdigit(): raise InvalidFormat() if number[-2] != '-' or number[-5] != '-': ...
def validate(number):
"""Check if the number provided is a valid CAS RN.""" number = compact(number) if not 7 <= len(number) <= 12: raise InvalidLength() if not number[:-5].isdigit() or not number[-4:-2].isdigit(): raise InvalidFormat() if number[-2] != '-' or number[-5] != '-': raise InvalidForma...
"""Calculate the check digit for the number. The passed number should not have the check digit included.""" number = number.replace('-', '') return str( sum((i + 1) * int(n) for i, n in enumerate(reversed(number))) % 10) def validate(number):
64
64
109
4
60
Semicheche/foa_frappe_docker
frappe-bench/env/lib/python2.7/site-packages/stdnum/casrn.py
Python
validate
validate
57
68
57
57
2da1075560fc66ba3504aff530f0c349b38980fa
bigcode/the-stack
train
b397ca08337c25a9588ad58e
train
function
def read_web_headers_cookies(website, headers=False, cookies=False): config = get_config_data('web_headers.json') return_headers = None return_cookies = None if headers: return_headers = config[website]['headers'] if cookies: return_cookies = config[website]['cookies'] return ...
def read_web_headers_cookies(website, headers=False, cookies=False):
config = get_config_data('web_headers.json') return_headers = None return_cookies = None if headers: return_headers = config[website]['headers'] if cookies: return_cookies = config[website]['cookies'] return return_headers, return_cookies
'] == 0 else False if result: print('发送成功') return True else: print('发送失败') return False except Exception as e: print(e) print(res.text) def read_web_headers_cookies(website, headers=False, cookies=F...
64
64
77
15
49
hvnobug/stock
configure/util.py
Python
read_web_headers_cookies
read_web_headers_cookies
33
44
33
33
ebaaa563532a1e5609373362ffaa55c85bec0488
bigcode/the-stack
train
b898b715c9319feaf24e7eaf
train
function
def notify(title='', desp=''): url = f"https://sc.ftqq.com/{config['WECHAT_ID']}.send?text={title}&desp={desp}" try: res = requests.get(url, timeout=5) except Exception as e: print(e) return False else: try: js = res.json() result = True if js['er...
def notify(title='', desp=''):
url = f"https://sc.ftqq.com/{config['WECHAT_ID']}.send?text={title}&desp={desp}" try: res = requests.get(url, timeout=5) except Exception as e: print(e) return False else: try: js = res.json() result = True if js['errno'] == 0 else False ...
-*- coding: utf-8 -*- # @Time : 2020/11/16 11:37 # @File : util.py # @Author : Rocky C@www.30daydo.com import requests from .settings import config, get_config_data def notify(title='', desp=''):
64
64
134
7
56
hvnobug/stock
configure/util.py
Python
notify
notify
9
30
9
9
b5df354916461a73dc7eadd8f91737ac25ed0d4d
bigcode/the-stack
train
b8b43642feedffa542b0a6a6
train
class
class Encoder(tf.keras.layers.Layer): """Encoder for mixture weight calculation (Lou et al., 2018). Attributes: U: Fully connected layer that learns N vectors with length L with `relu` activation. V: Fully connected layer that learns N vectors with lenght L with `sigmoid` ...
class Encoder(tf.keras.layers.Layer):
"""Encoder for mixture weight calculation (Lou et al., 2018). Attributes: U: Fully connected layer that learns N vectors with length L with `relu` activation. V: Fully connected layer that learns N vectors with lenght L with `sigmoid` activation. gating: Elementwis...
import tensorflow as tf from tensorflow.keras.layers import LSTM, Bidirectional from .param import TasNetParam class Encoder(tf.keras.layers.Layer):
31
90
301
7
23
kaparoo/TasNet
tasnet/layer.py
Python
Encoder
Encoder
6
40
6
6
129937e8c2149f157e6958cf0db32b6616638bf4
bigcode/the-stack
train
6bfde9e75446a4a1b13c6190
train
class
class Decoder(tf.keras.layers.Layer): """Decoder for waveform reconstruction (Lou et al., 2018). Attributes: B: Fully connected layer that learns N basis signals of the input mixtures. * N: Number of basis signals of the TasNet. * L: Length of each segment in input mixtures of the TasN...
class Decoder(tf.keras.layers.Layer):
"""Decoder for waveform reconstruction (Lou et al., 2018). Attributes: B: Fully connected layer that learns N basis signals of the input mixtures. * N: Number of basis signals of the TasNet. * L: Length of each segment in input mixtures of the TasNet. """ def __init__(self, pa...
.Tensor of shape=(, K, L) Returns: mixture_weights: Calculated weights corresponding to the segments. tf.Tensor of shape=(, K, N) """ return self.gating([self.U(mixture_segments), self.V(mixture_segments)]) class Decoder(tf.keras.layers.Layer):
63
64
207
7
56
kaparoo/TasNet
tasnet/layer.py
Python
Decoder
Decoder
43
70
43
43
2794fe6f639261d38bdf9e4f6db6143847c87735
bigcode/the-stack
train
27d37f665b171b3849cee1a6
train
class
class Separator(tf.keras.layers.Layer): """Separation network of the TasNet (Luo et al., 2018) In Separation Newtork, deep LSTM network is used. The directionality (uni-/bi-) of each LSTM layer is depend on the `causality` of the TasNet. Starting from the second LSTM layer, an identity skip connection ...
class Separator(tf.keras.layers.Layer):
"""Separation network of the TasNet (Luo et al., 2018) In Separation Newtork, deep LSTM network is used. The directionality (uni-/bi-) of each LSTM layer is depend on the `causality` of the TasNet. Starting from the second LSTM layer, an identity skip connection is added between every two LSTEM lay...
: Calculated weights corresponding to the segments. tf.Tensor of shape=(, K, N) """ return self.gating([self.U(mixture_segments), self.V(mixture_segments)]) class Decoder(tf.keras.layers.Layer): """Decoder for waveform reconstruction (Lou et al., 2018). Attribu...
256
256
1,044
7
249
kaparoo/TasNet
tasnet/layer.py
Python
Separator
Separator
73
171
73
73
c7a439c75ee1e4e86a88d2320a1c2c392ff22e1f
bigcode/the-stack
train
5430cc604625c605acddf418
train
class
class Workflow(Configurable): """ A specification for processing a dataset. Parameters ---------- label : str The shorthand name of the workflow. This is used as a reference throughout Lobster. dataset : Dataset The specification of data to be proce...
class Workflow(Configurable):
""" A specification for processing a dataset. Parameters ---------- label : str The shorthand name of the workflow. This is used as a reference throughout Lobster. dataset : Dataset The specification of data to be processed. Can be any of the ...
self.name = name self.cores = cores self.runtime = runtime self.memory = memory self.disk = disk self.tasks_max = tasks_max self.tasks_min = tasks_min modes = { 'fixed': wq.WORK_QUEUE_ALLOCATION_MODE_FIXED, 'max': wq.WORK_QUEUE_ALLOCATION...
256
256
3,701
5
250
NDCMS/lobster
lobster/core/workflow.py
Python
Workflow
Workflow
125
540
125
126
d39d8c46d74e3a0c762d67a7704642deb11a9dd1
bigcode/the-stack
train
6c5294ba3a4516308fecbe9a
train
class
class Category(Configurable): """ Resource specification for one or more :class:`~lobster.core.workflow.Workflow`. This information will be passed on to `WorkQueue`, which will forcibly terminate tasks of :class:`.Workflow` in the group that exceed the specified resources. Attributs modif...
class Category(Configurable):
""" Resource specification for one or more :class:`~lobster.core.workflow.Workflow`. This information will be passed on to `WorkQueue`, which will forcibly terminate tasks of :class:`.Workflow` in the group that exceed the specified resources. Attributs modifiable at runtime: * `tasks...
# -*- coding: utf-8 -*- import imp import json import logging import os import re import shlex import shutil import subprocess import sys from lobster import fs, util from lobster.core.dataset import EmptyDataset, MultiGridpackDataset, ParentMultiGridpackDataset, MultiProductionDataset, ProductionDataset from lobster....
125
237
790
5
120
NDCMS/lobster
lobster/core/workflow.py
Python
Category
Category
22
122
22
23
958e624283e96402e09d414c44795c61294f735f
bigcode/the-stack
train
0a49ec28452df64dfc26dff7
train
function
def loadData(inputDataset): """ Load input dataset """ if inputDataset == 'brainCIDR': path = '../input/brainCIDR/' df = pd.read_csv(f"{path}brainTags.csv", index_col = 0).T truth = pd.read_pickle(f'{path}truth.pkl') if inputDataset == 'pancreaticIsletCIDR': path...
def loadData(inputDataset):
""" Load input dataset """ if inputDataset == 'brainCIDR': path = '../input/brainCIDR/' df = pd.read_csv(f"{path}brainTags.csv", index_col = 0).T truth = pd.read_pickle(f'{path}truth.pkl') if inputDataset == 'pancreaticIsletCIDR': path = '../input/pancreaticIslet...
, random_state=None, copy_x=True) classifier.fit(X) labels= classifier.predict(X) silhouette_score_values.append(metrics.silhouette_score(X,labels ,metric='euclidean', sample_size=None, random_state=None)) plt.plot(numberOfClusters, silhouette_score_values) plt.title("Silhouette score v...
122
123
411
6
116
lev1khachatryan/ASDS_ML-2
Lectures/Levon/SpectralClustering/util.py
Python
loadData
loadData
67
104
67
67
1b08e676074ce27a36b2294c79bdbb0674d7eaed
bigcode/the-stack
train
8e886c5ebecfcfd721f16d54
train
function
def silhouetteAnalyis (X, numberOfClusters): silhouette_score_values=[] for i in tqdm(numberOfClusters): classifier=KMeans(i,init='k-means++', n_init=10, max_iter=300, tol=0.0001, verbose=0, random_state=None, copy_x=True) classifier.fit(X) labels= classifier.predict(X) silhouett...
def silhouetteAnalyis (X, numberOfClusters):
silhouette_score_values=[] for i in tqdm(numberOfClusters): classifier=KMeans(i,init='k-means++', n_init=10, max_iter=300, tol=0.0001, verbose=0, random_state=None, copy_x=True) classifier.fit(X) labels= classifier.predict(X) silhouette_score_values.append(metrics.silhouette_scor...
Clusters, distortions, 'bx-') plt.xlabel('k') plt.ylabel('Distortion') plt.title('The Elbow Method showing the optimal k') plt.show() if printFunctionNames: print('silhouetteAnalyis') def silhouetteAnalyis (X, numberOfClusters):
64
64
175
11
53
lev1khachatryan/ASDS_ML-2
Lectures/Levon/SpectralClustering/util.py
Python
silhouetteAnalyis
silhouetteAnalyis
51
64
51
51
255aa3da8edd66cbdb54c4e8b9f1e5cceb0a2f96
bigcode/the-stack
train
263b87d97a2f8a722e6cad5e
train
function
def plotCorrelation(resultsDf, name = None): import seaborn as sns scoreColumns = [c for c in resultsDf.columns if c.startswith('_')] score = resultsDf[scoreColumns] score = score.astype(float) sns.set(font_scale=0.9) # fig, ax = plt.subplots(figsize=(10,10)) sns.heatmap(score.corr(), annot=...
def plotCorrelation(resultsDf, name = None):
import seaborn as sns scoreColumns = [c for c in resultsDf.columns if c.startswith('_')] score = resultsDf[scoreColumns] score = score.astype(float) sns.set(font_scale=0.9) # fig, ax = plt.subplots(figsize=(10,10)) sns.heatmap(score.corr(), annot=True); if name is not None: plt.t...
generally higher for convex clusters than other concepts of clusters, such as density based clusters like those obtained from DBSCAN. """ scores['_davies_bouldin_score'] = metrics.davies_bouldin_score(data,clusters) return scores def plotCorrelation(resultsDf, name = None):
64
64
103
10
53
lev1khachatryan/ASDS_ML-2
Lectures/Levon/SpectralClustering/util.py
Python
plotCorrelation
plotCorrelation
145
154
145
145
e07ac8523fb1e2275ec87c46b43d243952bdc60f
bigcode/the-stack
train
5e82415d5ba26b1af3275096
train
function
def externalValidation(truthClusters, predictedClusters): def purity_score(y_true, y_pred): # compute contingency matrix (also called confusion matrix) contingency_matrix = metrics.cluster.contingency_matrix(y_true, y_pred) # return purity return np.sum(np.amax(contingency_matrix, ax...
def externalValidation(truthClusters, predictedClusters):
def purity_score(y_true, y_pred): # compute contingency matrix (also called confusion matrix) contingency_matrix = metrics.cluster.contingency_matrix(y_true, y_pred) # return purity return np.sum(np.amax(contingency_matrix, axis=0)) / np.sum(contingency_matrix) scores = {} s...
(np.load(f"{path}{inputDataset}_cells.npy"), inplace=True) df.columns = np.load(f"{path}{inputDataset}_genes.npy") truth = pd.read_pickle(f'{path}{inputDataset}_truth.pkl') return df, truth def externalValidation(truthClusters, predictedClusters):
64
64
190
10
53
lev1khachatryan/ASDS_ML-2
Lectures/Levon/SpectralClustering/util.py
Python
externalValidation
externalValidation
108
120
108
108
979f08f3172120de30b9acecaa50e53c229d8717
bigcode/the-stack
train
c4916d2ad3bbabf27cc80632
train
function
def internalValidation(data, clusters): scores = {} """ The score is bounded between -1 for incorrect clustering and +1 for highly dense clustering. Scores around zero indicate overlapping clusters. The score is higher when clusters are dense and well separated, which relates to a standard concept ...
def internalValidation(data, clusters):
scores = {} """ The score is bounded between -1 for incorrect clustering and +1 for highly dense clustering. Scores around zero indicate overlapping clusters. The score is higher when clusters are dense and well separated, which relates to a standard concept of a cluster. """ scores['_silho...
Clusters, predictedClusters) scores['_adjusted_mutual_info_score'] = metrics.adjusted_mutual_info_score(truthClusters, predictedClusters) scores['_fowlkes_mallows_score'] = metrics.fowlkes_mallows_score(truthClusters, predictedClusters) return scores def internalValidation(data, clusters):
67
67
226
7
59
lev1khachatryan/ASDS_ML-2
Lectures/Levon/SpectralClustering/util.py
Python
internalValidation
internalValidation
123
142
123
123
370ca9ad319b2f0b09cc0a12c22fd28228fbdd26
bigcode/the-stack
train
13b083adff4a12bdc82ce52c
train
function
def elbowAnalysis(X, numberOfClusters): distortions = [] for k in tqdm(numberOfClusters): kmeanModel = KMeans(n_clusters=k) kmeanModel.fit(X) distortions.append(sum(np.min(cdist(X, kmeanModel.cluster_centers_, 'euclidean'), axis=1)) / X.shape[0]) plt.plot(numberOfClusters, distorti...
def elbowAnalysis(X, numberOfClusters):
distortions = [] for k in tqdm(numberOfClusters): kmeanModel = KMeans(n_clusters=k) kmeanModel.fit(X) distortions.append(sum(np.min(cdist(X, kmeanModel.cluster_centers_, 'euclidean'), axis=1)) / X.shape[0]) plt.plot(numberOfClusters, distortions, 'bx-') plt.xlabel('k') plt....
ig import louvain from sklearn.metrics.cluster import adjusted_rand_score import umap import os from scipy import sparse, io plt.ion() plt.show() printFunctionNames = True if printFunctionNames: print('elbowAnalysis') def elbowAnalysis(X, numberOfClusters):
64
64
117
9
55
lev1khachatryan/ASDS_ML-2
Lectures/Levon/SpectralClustering/util.py
Python
elbowAnalysis
elbowAnalysis
34
46
34
34
cb9cbd7b2beae3d5c42ba041e74a084dbd2827e7
bigcode/the-stack
train
075ab2e38e1e82952c804e78
train
function
def add_ingress_port_to_security_lists(**kwargs): """Checks if the given ingress port already is a security list, if not it gets added. Args: **kwargs: Optional parameters Keyword Args: security_lists (list): A list of security_lists. port (int): The port to check ...
def add_ingress_port_to_security_lists(**kwargs):
"""Checks if the given ingress port already is a security list, if not it gets added. Args: **kwargs: Optional parameters Keyword Args: security_lists (list): A list of security_lists. port (int): The port to check description (str): A description for the ingre...
it's subnet and the # corresponsing security lists if public_ip: subnet = virtual_network.get_subnet( vnic.subnet_id).data if subnet is None: raise Exception( ...
221
222
740
11
210
mike-lischke/mysql-shell-plugins
mds_plugin/compute.py
Python
add_ingress_port_to_security_lists
add_ingress_port_to_security_lists
473
573
473
473
360264e55b49e4b8e1c66aa448e183f52bd18347
bigcode/the-stack
train
1c1f25e0ce38308238cb24ca
train
function
@plugin_function('mds.get.computeInstanceId') def get_instance_id(instance_name=None, compartment_id=None, config=None, interactive=True): """Returns an instance OCID based on instance_name or instance_id Args: instance_name (str): The name of the instance compartment...
@plugin_function('mds.get.computeInstanceId') def get_instance_id(instance_name=None, compartment_id=None, config=None, interactive=True):
"""Returns an instance OCID based on instance_name or instance_id Args: instance_name (str): The name of the instance compartment_id (str): OCID of the compartment config (object): An OCI config object or None interactive (bool): Whether exceptions are raised Return...
.code}; Status: {e.status})') except Exception as e: if raise_exceptions: raise print(f'ERROR: {e}') @plugin_function('mds.get.computeInstanceId') def get_instance_id(instance_name=None, compartment_id=None, config=None, interactive=True):
63
64
156
30
33
mike-lischke/mysql-shell-plugins
mds_plugin/compute.py
Python
get_instance_id
get_instance_id
820
839
820
822
4f55a65607bfe0838f6df7d542d9e82cc588c1ea
bigcode/the-stack
train
23115efb68ff699588790670
train
function
@plugin_function('mds.execute.ssh') def execute_ssh_command(command=None, **kwargs): """Execute the given command on the instance If no name is given, it will prompt the user for the name. Args: command (str): The command to execute. **kwargs: Additional options Keyword Args...
@plugin_function('mds.execute.ssh') def execute_ssh_command(command=None, **kwargs):
"""Execute the given command on the instance If no name is given, it will prompt the user for the name. Args: command (str): The command to execute. **kwargs: Additional options Keyword Args: instance_name (str): The name of the instance. instance_id (str): T...
return_python_object=True) if new_name is None and interactive: new_name = mysqlsh.globals.shell.prompt( "Please enter a new name for the instance " f"[{instance.display_name}]: ", {'defaultValue': instance.display_name}).strip() if ...
250
251
838
21
229
mike-lischke/mysql-shell-plugins
mds_plugin/compute.py
Python
execute_ssh_command
execute_ssh_command
2,009
2,117
2,009
2,010
2f3fa2cd5905507e894261d2f4a972c98bba843d
bigcode/the-stack
train
fcfcb8399ad34c59ca3268ed
train
function
def get_instance_by_id(**kwargs): """Returns an instance object for the given id Args: **kwargs: Optional parameters Keyword Args: instance_id (str): OCID of the instance. config (dict): An OCI config object or None config_profile (str): The name of an OCI config p...
def get_instance_by_id(**kwargs):
"""Returns an instance object for the given id Args: **kwargs: Optional parameters Keyword Args: instance_id (str): OCID of the instance. config (dict): An OCI config object or None config_profile (str): The name of an OCI config profile interactive (bool):...
if not type(items) is list: items = [items] # return objects in READABLE text output out = "" id = 1 for i in items: out += (f"{id:>4} " + core.fixed_len(i.display_name, 48, ' ', True) + core.fixed_len(i.operating_system, 16, ' ', True) + ...
135
135
453
8
126
mike-lischke/mysql-shell-plugins
mds_plugin/compute.py
Python
get_instance_by_id
get_instance_by_id
310
369
310
310
b2eb7f799e26e9f84ad8577d40c1a42cee2699a7
bigcode/the-stack
train
13db0560f403f2017b8cb061
train
function
@plugin_function('mds.get.computeInstanceVncSecurityLists') def get_instance_vcn_security_lists(**kwargs): """Returns the vnc_security_lists of an instance If no name is given, it will prompt the user for the name. Args: **kwargs: Optional parameters Keyword Args: instance_n...
@plugin_function('mds.get.computeInstanceVncSecurityLists') def get_instance_vcn_security_lists(**kwargs):
"""Returns the vnc_security_lists of an instance If no name is given, it will prompt the user for the name. Args: **kwargs: Optional parameters Keyword Args: instance_name (str): The name of the instance. instance_id (str): The OCID of the instance compartmen...
# the global one try: config = configuration.get_current_config( config=config, config_profile=config_profile, interactive=interactive) current_instance_id = configuration.get_current_instance_id( config=config) import oci.exceptions ...
228
229
766
24
204
mike-lischke/mysql-shell-plugins
mds_plugin/compute.py
Python
get_instance_vcn_security_lists
get_instance_vcn_security_lists
372
470
372
373
055b24a5837a9d625bdc7cf3e09d093b4038e3fa
bigcode/the-stack
train
82f16c7523020e1e13609dd9
train
function
@plugin_function('mds.get.computeShapeName') def get_shape_name(**kwargs): """Gets a certain shape id specified by name for the given compartment and availability_domain Args: **kwargs: Additional options Keyword Args: shape_name (str): Name of the shape limit_shapes_...
@plugin_function('mds.get.computeShapeName') def get_shape_name(**kwargs):
"""Gets a certain shape id specified by name for the given compartment and availability_domain Args: **kwargs: Additional options Keyword Args: shape_name (str): Name of the shape limit_shapes_to (list): List of strings to limit the shape selection availability...
", item_name_property="shape", given_value=shape_name, print_list=True) return core.return_oci_object( oci_object=shape, return_formatted=return_formatted, return_python_object=return_python_object, format_function=format_shapes) ...
102
103
346
18
84
mike-lischke/mysql-shell-plugins
mds_plugin/compute.py
Python
get_shape_name
get_shape_name
1,114
1,155
1,114
1,115
9b902bd4efea90ef9e426e362e1c424ad1b55b79
bigcode/the-stack
train
2e226c51492bd6d56685208a
train
function
@plugin_function('mds.list.computeShapes', shell=True, cli=True, web=True) def list_shapes(**kwargs): """Returns a list of all available compute shapes This list is specific for the given compartment and availability_domain Args: **kwargs: Additional options Keyword Args: li...
@plugin_function('mds.list.computeShapes', shell=True, cli=True, web=True) def list_shapes(**kwargs):
"""Returns a list of all available compute shapes This list is specific for the given compartment and availability_domain Args: **kwargs: Additional options Keyword Args: limit_shapes_to (list): A list of shape names availability_domain (str): The name of the availabi...
nic in attached_vnics: vnic = virtual_network.get_vnic( attached_vnic.vnic_id).data instance_ip = vnic.public_ip if instance_ip: break if not instance_ip and private_ip_fallback: ...
220
221
739
25
195
mike-lischke/mysql-shell-plugins
mds_plugin/compute.py
Python
list_shapes
list_shapes
943
1,035
943
944
93aa9c069d22e80c11f6f9c00354dbc19b590415
bigcode/the-stack
train
182cc07a5db7748b05dbaa6e
train
function
@plugin_function('mds.get.computeShape') def get_shape(**kwargs): """Gets a certain shape specified by name The shape is specific for the given compartment and availability_domain Args: **kwargs: Additional options Keyword Args: shape_name (str): Name of the shape l...
@plugin_function('mds.get.computeShape') def get_shape(**kwargs):
"""Gets a certain shape specified by name The shape is specific for the given compartment and availability_domain Args: **kwargs: Additional options Keyword Args: shape_name (str): Name of the shape limit_shapes_to (list): List of strings to limit the shape selection ...
s.shape in l_s for l_s in limit_shapes_to)] return core.return_oci_object( oci_object=shapes, return_formatted=return_formatted, return_python_object=return_python_object, format_function=format_shapes) excep...
170
171
573
16
154
mike-lischke/mysql-shell-plugins
mds_plugin/compute.py
Python
get_shape
get_shape
1,038
1,111
1,038
1,039
c0daf3c4c57763ebec68468950671167812e20b3
bigcode/the-stack
train
13be744ea2ea8f582c57015a
train
function
def format_image_list_item(data, index): img = data[index] # Shorten to 16 chars max os = img.operating_system[:14] + '..' \ if len(img.operating_system) > 16 \ else img.operating_system # Shorten to 16 chars max os_version = img.operating_system_version[:20] + '..' \ ...
def format_image_list_item(data, index):
img = data[index] # Shorten to 16 chars max os = img.operating_system[:14] + '..' \ if len(img.operating_system) > 16 \ else img.operating_system # Shorten to 16 chars max os_version = img.operating_system_version[:20] + '..' \ if len(img.operating_system_version) > 22...
{c.shape[:22]:22} {c.fault_domain[:15]:15} " f"{public_ip if public_ip != '' else private_ip:15} " f"{c.lifecycle_state}\n") i += 1 return out def format_image_list_item(data, index):
64
64
140
9
54
mike-lischke/mysql-shell-plugins
mds_plugin/compute.py
Python
format_image_list_item
format_image_list_item
238
250
238
238
532296eff213094f4f9cca72a26635e10021a5b0
bigcode/the-stack
train
e47480d2ae0e0c340a10f7e7
train
function
def format_vnic_listing(vnics): """Returns a formated list of vnics. Args: vnics (list): A list of vnics objects. Returns: The formated list as string """ import re out = "" i = 1 for v in vnics: # Shorten to 24 chars max, remove linebreaks ...
def format_vnic_listing(vnics):
"""Returns a formated list of vnics. Args: vnics (list): A list of vnics objects. Returns: The formated list as string """ import re out = "" i = 1 for v in vnics: # Shorten to 24 chars max, remove linebreaks name = re.sub(r'[\n\r]', ' ', ...
operating_system=operating_system, operating_system_version=operating_system_version, image_caption=operating_system_version, shape=shape, compartment_id=compartment_id, config=config, interactive=interactive) return None if image is None else image.id def format_vnic_listing...
66
66
220
9
56
mike-lischke/mysql-shell-plugins
mds_plugin/compute.py
Python
format_vnic_listing
format_vnic_listing
1,380
1,407
1,380
1,380
e344b794879a409709877c750f00736fcaca18c4
bigcode/the-stack
train
678763b342a1afbd2d1adcda
train
function
@plugin_function('mds.create.computeInstance') def create_instance(**kwargs): """Creates a new compute instance This function will create a new compartment. Args: **kwargs: Additional options Keyword Args: instance_name (str): The name used for the new compartment. ...
@plugin_function('mds.create.computeInstance') def create_instance(**kwargs):
"""Creates a new compute instance This function will create a new compartment. Args: **kwargs: Additional options Keyword Args: instance_name (str): The name used for the new compartment. availability_domain (str): The name of the availability_domain to use s...
_id: raise ValueError("No instance_id given." "Cancelling operation") import oci.exceptions try: # Initialize the oci client compute = core.get_oci_compute_client(config=config) network = core.get_oci_virtual_network...
255
256
2,518
16
239
mike-lischke/mysql-shell-plugins
mds_plugin/compute.py
Python
create_instance
create_instance
1,498
1,806
1,498
1,499
7ad8c6758031189aebcda00bc10312d9d93f53fe
bigcode/the-stack
train