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
4f59a5aa427ecaffeab90234
train
function
@typemap def tanh(x, name=''): ''' Computes the element-wise tanh of ``x``: The output tensor has the same shape as ``x``. Example: >>> C.tanh([[1,2],[3,4]]).eval() array([[ 0.761594, 0.964028], [ 0.995055, 0.999329]], dtype=float32) Args: x: numpy array o...
@typemap def tanh(x, name=''):
''' Computes the element-wise tanh of ``x``: The output tensor has the same shape as ``x``. Example: >>> C.tanh([[1,2],[3,4]]).eval() array([[ 0.761594, 0.964028], [ 0.995055, 0.999329]], dtype=float32) Args: x: numpy array or any :class:`~cntk.ops.functio...
): the name of the Function instance in the network Returns: :class:`~cntk.ops.functions.Function` ''' from cntk.cntk_py import sigmoid x = sanitize_input(x) return sigmoid(x, name) @typemap def tanh(x, name=''):
64
64
178
12
52
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
tanh
tanh
1,638
1,658
1,638
1,639
4087cb79848bbb12be58a2e05f7a519ee9758bcf
bigcode/the-stack
train
e805a2680c092bffa40610db
train
function
@typemap def depth_to_space(operand, block_size, name=''): ''' Rearranges elements in the input tensor from the depth dimension into spatial blocks. This operation is useful for implementing sub-pixel convolution that is part of models for image super-resolution (see [1]). It rearranges elements of a...
@typemap def depth_to_space(operand, block_size, name=''):
''' Rearranges elements in the input tensor from the depth dimension into spatial blocks. This operation is useful for implementing sub-pixel convolution that is part of models for image super-resolution (see [1]). It rearranges elements of an input tensor of shape (Cxbxb, H, W) to a tensor of s...
node_input ancestor_referent (optional): class:`~cntk.ops.functions.Function` that outputs ancestor of node_referent name (str, optional): the name of the Function instance in the network Returns: :class:`~cntk.ops.functions.Function` ''' from cntk.cntk_py import crop arg_node_i...
193
193
644
17
176
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
depth_to_space
depth_to_space
3,985
4,026
3,985
3,986
919bf418b209842502df9fd05fd76deebdef8470
bigcode/the-stack
train
3d23fdc8199c42a3d1d52792
train
function
@typemap def param_relu(alpha, x, name=''): ''' Parametric rectified linear operation. Computes the element-wise parameteric rectified linear of ``x``: ``max(x, 0)`` for ``x >= 0`` and ``x``: ``alpha*x`` otherwise. The output tensor has the same shape as ``x``. Example: >>> alpha = C.const...
@typemap def param_relu(alpha, x, name=''):
''' Parametric rectified linear operation. Computes the element-wise parameteric rectified linear of ``x``: ``max(x, 0)`` for ``x >= 0`` and ``x``: ``alpha*x`` otherwise. The output tensor has the same shape as ``x``. Example: >>> alpha = C.constant(value=[[0.5, 0.5, 0.5, 0.5, 0.5]]) ...
(`str`, default to ''): the name of the Function instance in the network Returns: cntk.ops.functions.Function: An instance of :class:`~cntk.ops.functions.Function` ''' from cntk.cntk_py import leaky_re_lu x = sanitize_input(x) return leaky_re_lu(x, alpha, name) @typemap def param_r...
92
92
307
14
78
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
param_relu
param_relu
1,505
1,529
1,505
1,506
de7e6174f84ec2de17adc5d3e85611675ce0ea60
bigcode/the-stack
train
de0f1ee40fcd0d80764113c1
train
function
@typemap def elu(x, alpha=1.0, name=''): ''' Exponential linear unit operation. Computes the element-wise exponential linear of ``x``: ``max(x, 0)`` for ``x >= 0`` and ``x``: ``alpha * (exp(x)-1)`` otherwise. The output tensor has the same shape as ``x``. Example: >>> C.elu([[-1, -0.5, 0, ...
@typemap def elu(x, alpha=1.0, name=''):
''' Exponential linear unit operation. Computes the element-wise exponential linear of ``x``: ``max(x, 0)`` for ``x >= 0`` and ``x``: ``alpha * (exp(x)-1)`` otherwise. The output tensor has the same shape as ``x``. Example: >>> C.elu([[-1, -0.5, 0, 1, 2]]).eval() array([[-0.632121,...
(str, optional): the name of the Function instance in the network Returns: :class:`~cntk.ops.functions.Function` ''' from cntk.cntk_py import re_lu x = sanitize_input(x) return re_lu(x, name) @typemap def elu(x, alpha=1.0, name=''):
77
77
259
17
60
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
elu
elu
1,431
1,453
1,431
1,432
61868e84edf0cf8072b4f3331e7696d5c4d0e5e9
bigcode/the-stack
train
86475a5be0da950463f7beeb
train
function
@typemap def constant(value=None, shape=None, dtype=None, device=None, name=''): ''' It creates a constant tensor initialized from a numpy array. Example: >>> constant_data = C.constant([[1., 2.], [3., 4.], [5., 6.]]) >>> constant_data.value array([[ 1., 2.], [ 3., ...
@typemap def constant(value=None, shape=None, dtype=None, device=None, name=''):
''' It creates a constant tensor initialized from a numpy array. Example: >>> constant_data = C.constant([[1., 2.], [3., 4.], [5., 6.]]) >>> constant_data.value array([[ 1., 2.], [ 3., 4.], [ 5., 6.]], dtype=float32) Args: value (scalar ...
device (:class:`~cntk.device.DeviceDescriptor`): instance of DeviceDescriptor name (str, optional): the name of the Parameter instance in the network Returns: :class:`~cntk.variables.Parameter` ''' from ..variables import Parameter return Parameter(shape, init, dtype, device, n...
91
91
304
21
70
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
constant
constant
3,774
3,800
3,774
3,775
7e2c82335383ea87e6ad6ddf4cfd73224a8c6c1d
bigcode/the-stack
train
8b825ea4045e386d04fe4d7a
train
function
@typemap def less(left, right, name=''): ''' Elementwise 'less' comparison of two tensors. Result is 1 if left < right else 0. Example: >>> C.less([41., 42., 43.], [42., 42., 42.]).eval() array([ 1., 0., 0.], dtype=float32) >>> C.less([-1,0,1], [0]).eval() array([ 1., 0., 0...
@typemap def less(left, right, name=''):
''' Elementwise 'less' comparison of two tensors. Result is 1 if left < right else 0. Example: >>> C.less([41., 42., 43.], [42., 42., 42.]).eval() array([ 1., 0., 0.], dtype=float32) >>> C.less([-1,0,1], [0]).eval() array([ 1., 0., 0.], dtype=float32) Args: lef...
''' from cntk.cntk_py import local_response_normalization operand = sanitize_input(operand) return local_response_normalization(operand, depth_radius, bias, alpha, beta, name) ########################################################################## # comparison ops ###################################...
65
65
219
13
52
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
less
less
689
712
689
690
4740473382dedfc85b95671dead707e264d27dc9
bigcode/the-stack
train
e38095457ddeaaab6d706ead
train
function
@typemap def pad(x, pattern, mode=CONSTANT_PAD, constant_value = 0, name=''): ''' Pads a tensor according to the specified patterns. Three padding modes are supported: CONSTANT / REFLECT / SYMMETRIC. Example: >>> data = np.arange(6, dtype=np.float32).reshape((2,3)) >>> x = C.constant(va...
@typemap def pad(x, pattern, mode=CONSTANT_PAD, constant_value = 0, name=''):
''' Pads a tensor according to the specified patterns. Three padding modes are supported: CONSTANT / REFLECT / SYMMETRIC. Example: >>> data = np.arange(6, dtype=np.float32).reshape((2,3)) >>> x = C.constant(value=data) >>> C.pad(x, pattern=[(1,1),(2,2)], mode=C.ops.CONSTANT_PAD,...
[[0,1],[2,3],[4,5]]], 1, 2).eval() array([[[ 0., 2., 4.], [ 1., 3., 5.]]], dtype=float32) Args: x: tensor to be transposed axis1 (int or :class:`~cntk.axis.Axis`): the axis to swap with ``axis2`` axis2 (int or :class:`~cntk.axis.Axis`): the axis to swap with ``ax...
230
230
767
25
205
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
pad
pad
2,614
2,654
2,614
2,615
66e39dc687ca856d29ee148eed55a733005b416b
bigcode/the-stack
train
9dee5bbe9624537b6ae2e126
train
function
@typemap def argmax(x, axis=None, name=''): ''' Computes the argmax of the input tensor's elements across the specified axis. If no axis is specified, it will return the flatten index of the largest element in tensor x. Example: >>> # create 3x2 matrix in a sequence of length 1 in a batch o...
@typemap def argmax(x, axis=None, name=''):
''' Computes the argmax of the input tensor's elements across the specified axis. If no axis is specified, it will return the flatten index of the largest element in tensor x. Example: >>> # create 3x2 matrix in a sequence of length 1 in a batch of one sample >>> data = [[10, 20],[3...
): Scalar channel factor. bias (numpy array): Bias values for each channel. Returns: cntk.ops.functions.Function: An instance of :class:`~cntk.ops.functions.Function` ''' from cntk.cntk_py import image_scaler x = sanitize_input(x) return image_scaler(x, scalar, biases, name)...
91
91
304
15
76
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
argmax
argmax
3,331
3,362
3,331
3,332
079f6e7c83e5277429d36832be137273da1fcb85
bigcode/the-stack
train
e267b15e2b67769ada6f4dc5
train
function
@typemap def cos(x, name=''): ''' Computes the element-wise cosine of ``x``: The output tensor has the same shape as ``x``. Example: >>> np.round(C.cos(np.arccos([[1,0.5],[-0.25,-0.75]])).eval(),5) array([[ 1. , 0.5 ], [-0.25, -0.75]], dtype=float32) Args: ...
@typemap def cos(x, name=''):
''' Computes the element-wise cosine of ``x``: The output tensor has the same shape as ``x``. Example: >>> np.round(C.cos(np.arccos([[1,0.5],[-0.25,-0.75]])).eval(),5) array([[ 1. , 0.5 ], [-0.25, -0.75]], dtype=float32) Args: x: numpy array or any :class:...
optional): the name of the Function instance in the network Returns: :class:`~cntk.ops.functions.Function` ''' from cntk.cntk_py import sin x = sanitize_input(x) return sin(x, name) @typemap def cos(x, name=''):
64
64
182
11
53
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
cos
cos
1,704
1,724
1,704
1,705
b04d03bdd3aa8887b25bb944d94ee783a154f5a8
bigcode/the-stack
train
0eed73ee28e50fd3df7894a9
train
function
@typemap def forward_backward(graph, features, blankTokenId, delayConstraint=-1, name=''): ''' Criterion node for training methods that rely on forward-backward Viterbi-like passes, e.g. Connectionist Temporal Classification (CTC) training The node takes as the input the graph of labels, produced by the...
@typemap def forward_backward(graph, features, blankTokenId, delayConstraint=-1, name=''):
''' Criterion node for training methods that rely on forward-backward Viterbi-like passes, e.g. Connectionist Temporal Classification (CTC) training The node takes as the input the graph of labels, produced by the labels_to_graph operation that determines the exact forward/backward procedure. E...
reconciled to. name (str, optional): the name of the reconcile_dynamic_axes Function in the network Returns: :class:`~cntk.ops.functions.Function` ''' from cntk.cntk_py import reconcile_dynamic_axes x = sanitize_input(x) dynamic_axes_as = sanitize_input(dynamic_axes_as) return ...
256
256
1,071
23
233
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
forward_backward
forward_backward
263
350
263
264
b2d448e2403566e1c694b3131b324b2dc27ea58f
bigcode/the-stack
train
c7ac6f88a0d2878334b20d57
train
function
@typemap def times_transpose(left, right, name=''): ''' The output of this operation is the product of the first (``left``) argument with the second (``right``) argument transposed. The second (``right``) argument must have a rank of 1 or 2. This operation is conceptually computing ``np.dot(left, right....
@typemap def times_transpose(left, right, name=''):
''' The output of this operation is the product of the first (``left``) argument with the second (``right``) argument transposed. The second (``right``) argument must have a rank of 1 or 2. This operation is conceptually computing ``np.dot(left, right.T)`` except when ``right`` is a vector in which ...
]]], <BLANKLINE> <BLANKLINE> [[[ 20., 29.], [ 38., 47.]], <BLANKLINE> [[ 28., 41.], [ 54., 67.]]]]) Args: left: left side matrix or tensor right: right side matrix or tensor output_rank (int): in ca...
256
256
890
15
241
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
times_transpose
times_transpose
1,177
1,273
1,177
1,178
644b003e439f8652943834831847b209273d0793
bigcode/the-stack
train
958c632216cd7cd120aa76f3
train
function
@typemap def acos(x, name=''): ''' Computes the element-wise arccos (inverse cosine) of ``x``: The output tensor has the same shape as ``x``. Example: >>> np.round(C.acos([[1,0.5],[-0.25,-0.75]]).eval(),5) array([[ 0. , 1.0472 ], [ 1.82348, 2.41886]], dtype=float32...
@typemap def acos(x, name=''):
''' Computes the element-wise arccos (inverse cosine) of ``x``: The output tensor has the same shape as ``x``. Example: >>> np.round(C.acos([[1,0.5],[-0.25,-0.75]]).eval(),5) array([[ 0. , 1.0472 ], [ 1.82348, 2.41886]], dtype=float32) Args: x: numpy a...
optional): the name of the Function instance in the network Returns: :class:`~cntk.ops.functions.Function` ''' from cntk.cntk_py import tan x = sanitize_input(x) return tan(x, name) @typemap def acos(x, name=''):
64
64
190
11
53
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
acos
acos
1,747
1,767
1,747
1,748
4f37b461a833fb015a48dc6fb201624b38f9a30b
bigcode/the-stack
train
b9047915528e5911502f5b00
train
function
@typemap def unpack_batch(x, name=''): ''' Concatenate the input tensor's last dynamic axis to static axis. Only tensors with batch axis are supported now. Example: >>> data = np.arange(12).reshape((3,2,2)) >>> x = C.input((2,2)) >>> C.unpack_batch(x).eval({x:data}) arra...
@typemap def unpack_batch(x, name=''):
''' Concatenate the input tensor's last dynamic axis to static axis. Only tensors with batch axis are supported now. Example: >>> data = np.arange(12).reshape((3,2,2)) >>> x = C.input((2,2)) >>> C.unpack_batch(x).eval({x:data}) array([[[ 0., 1.], [ 2....
]]) # (but make it into a Function) from cntk.cntk_py import splice inputs = [sanitize_input(x) for x in inputs] axis = sanitize_axis(axis) return splice(inputs, axis, name) # C++ projection expects inputs as a list @typemap def unpack_batch(x, name=''):
72
72
241
12
59
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
unpack_batch
unpack_batch
2,793
2,821
2,793
2,794
daae5167f1f0a70d9f95232f12fdf58f83806926
bigcode/the-stack
train
0bb3a1948dc928c718ace96f
train
function
@typemap def stop_gradient(input, name=''): ''' Outputs its input as it is and prevents any gradient contribution from its output to its input. Args: input: class:`~cntk.ops.functions.Function` that outputs a tensor name (str, optional): the name of the Function instance in the network ...
@typemap def stop_gradient(input, name=''):
''' Outputs its input as it is and prevents any gradient contribution from its output to its input. Args: input: class:`~cntk.ops.functions.Function` that outputs a tensor name (str, optional): the name of the Function instance in the network Returns: :class:`~cntk.ops.functions...
ize mean = sanitize_input(mean, get_data_type(mean)) inv_stddev = sanitize_input(inv_stddev, get_data_type(inv_stddev)) return per_dim_mean_variance_normalize(operand, mean, inv_stddev, name) @typemap def stop_gradient(input, name=''):
64
64
123
12
52
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
stop_gradient
stop_gradient
3,827
3,841
3,827
3,828
2bd7b5f65a0d67b31bcfa5a27f7013b029ab5fa2
bigcode/the-stack
train
3162cc71e0b1d08dd05d869d
train
function
@typemap def parameter(shape=None, init=None, dtype=None, device=None, name=''): ''' It creates a parameter tensor. Example: >>> init_parameter = C.parameter(shape=(3,4), init=2) >>> np.asarray(init_parameter) # doctest: +SKIP array([[ 2., 2., 2., 2.], [ 2., 2., ...
@typemap def parameter(shape=None, init=None, dtype=None, device=None, name=''):
''' It creates a parameter tensor. Example: >>> init_parameter = C.parameter(shape=(3,4), init=2) >>> np.asarray(init_parameter) # doctest: +SKIP array([[ 2., 2., 2., 2.], [ 2., 2., 2., 2.], [ 2., 2., 2., 2.]], dtype=float32) Args: ...
k.variables.Variable` ''' from cntk.cntk_py import placeholder_variable, NDShape, Axis if shape is None: shape = NDShape.unknown().dimensions() else: shape = sanitize_shape(shape) if dynamic_axes is None: dynamic_axes = Axis.unknown_dynamic_axes() dynamic_axes = saniti...
108
108
360
21
87
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
parameter
parameter
3,740
3,771
3,740
3,741
64fd097a9429799add5f446a583996e8f9dc22e2
bigcode/the-stack
train
f0e314d9d351f040b04e3785
train
function
@typemap def input(shape, dtype=default_override_or(np.float32), needs_gradient=False, is_sparse=False, dynamic_axes=[Axis.default_batch_axis()], name=''): ''' DEPRECATED. It creates an input in the network: a place where data, such as features and labels, should be provided. Args: ...
@typemap def input(shape, dtype=default_override_or(np.float32), needs_gradient=False, is_sparse=False, dynamic_axes=[Axis.default_batch_axis()], name=''):
''' DEPRECATED. It creates an input in the network: a place where data, such as features and labels, should be provided. Args: shape (tuple or int): the shape of the input tensor dtype (np.float32 or np.float64 or np.float16): data type. Default is np.float32. needs_gradien...
We need _input_spec because input is python built-in and because of typemap, must remain in sync with input. TODO: Investigate to remove it. ''' pass @typemap def input(shape, dtype=default_override_or(np.float32), needs_gradient=False, is_sparse=False, dynamic_axes=[Axis.default_batch_axis()...
77
77
258
37
39
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
input
input
3,622
3,646
3,622
3,624
1692bddebd3254683ce465f8941e3384d97640a9
bigcode/the-stack
train
e9031da2a1c7cc3e2f4b7f2b
train
function
@typemap def optimized_rnnstack(operand, weights, hidden_size, num_layers, bidirectional=False, recurrent_op='lstm', name=''): ''' An RNN implementation that uses the primitives in cuDNN. If cuDNN is not available it fails. You can use :class:`~cntk.misc.optimized_rnnstack_converter.c...
@typemap def optimized_rnnstack(operand, weights, hidden_size, num_layers, bidirectional=False, recurrent_op='lstm', name=''):
''' An RNN implementation that uses the primitives in cuDNN. If cuDNN is not available it fails. You can use :class:`~cntk.misc.optimized_rnnstack_converter.convert_optimized_rnnstack` to convert a model to GEMM-based implementation when no cuDNN. Args: operand: input of the optimized RNN s...
10000], [ 2, 20, 200, 2000, 20000]).eval() array([ 1., 10., 200., 1000., 10000.], dtype=float32) Args: flag: condition tensor value_if_true: true branch tensor value_if_false: false branch tensor name (str, optional): the name of the Function instance in the ne...
214
214
716
34
180
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
optimized_rnnstack
optimized_rnnstack
2,378
2,427
2,378
2,380
7c833821ebd17db8ab569ccb51c3e57369c72268
bigcode/the-stack
train
f2cca67ebd1f62664a663a1c
train
function
@typemap def round(arg, name=''): ''' The output of this operation is the element wise value rounded to the nearest integer. In case of tie, where element can have exact fractional part of 0.5 this operation follows "round half-up" tie breaking strategy. This is different from the round operation of...
@typemap def round(arg, name=''):
''' The output of this operation is the element wise value rounded to the nearest integer. In case of tie, where element can have exact fractional part of 0.5 this operation follows "round half-up" tie breaking strategy. This is different from the round operation of numpy which follows round hal...
array([[ 1., 4.], [ 2., 6.]], dtype=float32) Args: arg: input tensor name (str, optional): the name of the Function instance in the network (optional) Returns: :class:`~cntk.ops.functions.Function` ''' from cntk.cntk_py import ceil arg = sanitize_inp...
110
110
367
11
99
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
round
round
1,336
1,368
1,336
1,337
e5c3f1f3dbf51c3c5507daaca5f9afd19f197ea6
bigcode/the-stack
train
21f4569ac9473a72b0fe9506
train
function
@typemap def tan(x, name=''): ''' Computes the element-wise tangent of ``x``: The output tensor has the same shape as ``x``. Example: >>> np.round(C.tan([-1, 0, 1]).eval(), 5) array([-1.55741, 0. , 1.55741], dtype=float32) Args: x: numpy array or any :class:`~cntk.op...
@typemap def tan(x, name=''):
''' Computes the element-wise tangent of ``x``: The output tensor has the same shape as ``x``. Example: >>> np.round(C.tan([-1, 0, 1]).eval(), 5) array([-1.55741, 0. , 1.55741], dtype=float32) Args: x: numpy array or any :class:`~cntk.ops.functions.Function` that out...
optional): the name of the Function instance in the network Returns: :class:`~cntk.ops.functions.Function` ''' from cntk.cntk_py import cos x = sanitize_input(x) return cos(x, name) @typemap def tan(x, name=''):
64
64
168
11
53
yuhonghong66/CNTK
bindings/python/cntk/ops/__init__.py
Python
tan
tan
1,726
1,745
1,726
1,727
edd8971fc17bc183afaadc96e62e402cdf52e2e8
bigcode/the-stack
train
b69212dacf33923e95acf5da
train
class
class Executed: def __init__(self, returncode: int, stdout: bytes, stderr: bytes) -> None: self.returncode = returncode self._stdout = stdout self._stderr = stderr @property def stdout(self) -> str: return self._stdout.decode() @property def stderr(self) -> str: return self._stderr.decode()
class Executed:
def __init__(self, returncode: int, stdout: bytes, stderr: bytes) -> None: self.returncode = returncode self._stdout = stdout self._stderr = stderr @property def stdout(self) -> str: return self._stdout.decode() @property def stderr(self) -> str: return self._stderr.decode()
: Path = Path(__file__).parent ROOT_DIR: str = f"{PREFIX}/.." EXTENSIONS: Generator[str, None, None] = ( f"cogs.{f[:-3]}" for f in os.listdir(f"{PREFIX}/cogs") if f.endswith(".py") ) class Executed:
64
64
82
4
60
null2264/speedrunbot-plusplus
src/bot.py
Python
Executed
Executed
22
34
22
22
939fd3d38dc2c4b8a87cb89ae6e40e49abb5d128
bigcode/the-stack
train
967c22f4819cfef41b76faed
train
class
class SRBpp(commands.Bot): def __init__(self) -> None: super().__init__( allowed_mentions=discord.AllowedMentions(everyone=False, users=False, roles=False), case_insensitive=True, command_prefix=get_prefix, intents=discord.Intents(messages=True, guilds=True), help_command=commands.MinimalHelpCommand(d...
class SRBpp(commands.Bot):
def __init__(self) -> None: super().__init__( allowed_mentions=discord.AllowedMentions(everyone=False, users=False, roles=False), case_insensitive=True, command_prefix=get_prefix, intents=discord.Intents(messages=True, guilds=True), help_command=commands.MinimalHelpCommand(dm_help=True), activity=d...
embed=discord.Embed( title=f"{title} Page: {line + 1}/{lines_length}", description="\n".join(lines[line]), ) ) except discord.Forbidden: await ctx.reply( "You have blocked the bot and the message is too long to be sent in this channel. Please unblock me and try again. " ) els...
132
132
441
7
125
null2264/speedrunbot-plusplus
src/bot.py
Python
SRBpp
SRBpp
120
183
120
120
73b7fa76ff9ed1199b72c85b750e77c985d45e57
bigcode/the-stack
train
6fde28438309d685349416c1
train
function
def divide_chunks(l: list[str], n: int) -> Generator[list[str], None, None]: """ Take a list of strings and return a generator which yields the same list of strings but in chunks of `n` strings. """ for i in range(0, len(l), n): yield l[i : i + n]
def divide_chunks(l: list[str], n: int) -> Generator[list[str], None, None]:
""" Take a list of strings and return a generator which yields the same list of strings but in chunks of `n` strings. """ for i in range(0, len(l), n): yield l[i : i + n]
stdout self._stderr = stderr @property def stdout(self) -> str: return self._stdout.decode() @property def stderr(self) -> str: return self._stderr.decode() def divide_chunks(l: list[str], n: int) -> Generator[list[str], None, None]:
64
64
74
21
43
null2264/speedrunbot-plusplus
src/bot.py
Python
divide_chunks
divide_chunks
37
43
37
37
235edfbe952390e98a7d788535eabbc18a9b0d18
bigcode/the-stack
train
f163b2ea1e272b6948408a7e
train
function
async def execv(prog: str, *argv: tuple[str, ...]) -> Executed: """ Run a program called PROG with the command line arguments ARGV. This returns a tuple containing the processes returncode, as well as the encoded stdout and stderr. """ # This is like `shlex.join()`, but it gets rid of any `None` values. args = " ...
async def execv(prog: str, *argv: tuple[str, ...]) -> Executed:
""" Run a program called PROG with the command line arguments ARGV. This returns a tuple containing the processes returncode, as well as the encoded stdout and stderr. """ # This is like `shlex.join()`, but it gets rid of any `None` values. args = " ".join(shlex.quote(arg) for arg in tuple(filter(lambda x: x, arg...
a generator which yields the same list of strings but in chunks of `n` strings. """ for i in range(0, len(l), n): yield l[i : i + n] async def execv(prog: str, *argv: tuple[str, ...]) -> Executed:
64
64
167
21
43
null2264/speedrunbot-plusplus
src/bot.py
Python
execv
execv
46
60
46
46
87077795f89bc2284611e6013dcc7ac599a3fdfd
bigcode/the-stack
train
c4067dd8abc4f3916d059649
train
function
def get_prefix(bot: SRBpp, message: Message) -> list[str]: """ Gets the list of prefixes that can be used to call the bot, including pinging the bot. """ PREFIXES: tuple[str, ...] = ("+", ";") return commands.when_mentioned_or(*PREFIXES)(bot, message)
def get_prefix(bot: SRBpp, message: Message) -> list[str]:
""" Gets the list of prefixes that can be used to call the bot, including pinging the bot. """ PREFIXES: tuple[str, ...] = ("+", ";") return commands.when_mentioned_or(*PREFIXES)(bot, message)
`&&` """ if message.author.bot: return commands = message.content.split(" && ") for command in commands: message.content = command await self.invoke(await self.get_context(message)) def get_prefix(bot: SRBpp, message: Message) -> list[str]:
64
64
70
17
47
null2264/speedrunbot-plusplus
src/bot.py
Python
get_prefix
get_prefix
186
191
186
186
6abba60a7cf4e186551f06d39aeaea18da73b7f5
bigcode/the-stack
train
5c4c293a4d3f52e098026f4a
train
function
async def run_and_output( ctx: Union[SlashContext, Context], prog: str, *argv: tuple[str, ...], title: Optional[str] = None, ) -> None: """ Run a program called `prog` with the command line arguments `argv` as a subprocess and return its output + exit code. If `title` is supplied, it will be used as the title of...
async def run_and_output( ctx: Union[SlashContext, Context], prog: str, *argv: tuple[str, ...], title: Optional[str] = None, ) -> None:
""" Run a program called `prog` with the command line arguments `argv` as a subprocess and return its output + exit code. If `title` is supplied, it will be used as the title of the embed that is sent to discord. If `title` is not supplied, then the first line of output from `prog` will be used. """ is_slash_cal...
.join()`, but it gets rid of any `None` values. args = " ".join(shlex.quote(arg) for arg in tuple(filter(lambda x: x, argv))) ret = await asyncio.create_subprocess_shell( f"{PREFIX}/{prog} {args}", stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stdout, stderr = await ret.communicate() ret...
139
139
466
41
98
null2264/speedrunbot-plusplus
src/bot.py
Python
run_and_output
run_and_output
63
117
63
68
39a57036c63ff0f172bb4e10b26e1c572ba0878a
bigcode/the-stack
train
3c5b097d5a607947c49ed7ef
train
class
class TimeStamps(models.Model): """docstring for TimeStamps.""" date_created = models.DateField(auto_now_add=True) date_updated = models.DateField(auto_now_add=True) class Meta: abstract = True
class TimeStamps(models.Model):
"""docstring for TimeStamps.""" date_created = models.DateField(auto_now_add=True) date_updated = models.DateField(auto_now_add=True) class Meta: abstract = True
from django.db import models class TimeStamps(models.Model):
13
64
49
7
5
BuildForSDGCohort2/Team-1053
api/utils/models.py
Python
TimeStamps
TimeStamps
4
10
4
4
a3a4a2b109aeaa9b2f81df0601036e0ffdd0fe83
bigcode/the-stack
train
a6467602b86eafeb07228028
train
class
class Migration(migrations.Migration): dependencies = [ ('Gallery', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='image', options={'ordering': ['date']}, ), ]
class Migration(migrations.Migration):
dependencies = [ ('Gallery', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='image', options={'ordering': ['date']}, ), ]
# Generated by Django 3.2.4 on 2021-07-04 22:46 from django.db import migrations class Migration(migrations.Migration):
36
64
50
7
28
Ammoh-Moringa/The-Gallery
Gallery/migrations/0002_alter_image_options.py
Python
Migration
Migration
6
17
6
7
fa968b9b4729842453023e570d52d9b45a56a979
bigcode/the-stack
train
6a7a5121b5d32db534b22614
train
class
class DeleteTransitRouterPeerAttachmentRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Cbn', '2017-09-12', 'DeleteTransitRouterPeerAttachment','cbn') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self,...
class DeleteTransitRouterPeerAttachmentRequest(RpcRequest):
def __init__(self): RpcRequest.__init__(self, 'Cbn', '2017-09-12', 'DeleteTransitRouterPeerAttachment','cbn') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", ...
may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Li...
124
124
415
11
112
leafcoder/aliyun-openapi-python-sdk
aliyun-python-sdk-cbn/aliyunsdkcbn/request/v20170912/DeleteTransitRouterPeerAttachmentRequest.py
Python
DeleteTransitRouterPeerAttachmentRequest
DeleteTransitRouterPeerAttachmentRequest
23
74
23
24
9fa868fe58d13fc08bbf70652567977ae9693c4a
bigcode/the-stack
train
7bc0c09d585b4deda12a52ef
train
function
def transform_source(source, callback_params=None, **kwargs): """This function is called by the import hook loader with the named keyword that we specified when we created the import hook. It gives us the option to compare the original source and the transformed one. This type of additional op...
def transform_source(source, callback_params=None, **kwargs):
"""This function is called by the import hook loader with the named keyword that we specified when we created the import hook. It gives us the option to compare the original source and the transformed one. This type of additional option can be useful when debugging a source transformer....
"""nobreak.py ------------- This module enables someone to use ``nobreak`` as a keyword equivalent to ``else`` in ``for`` and ``while`` loops. """ from ideas import import_hook, utils import token_utils def transform_source(source, callback_params=None, **kwargs):
64
64
165
12
51
aroberge/ideas
ideas/examples/nobreak.py
Python
transform_source
transform_source
12
30
12
12
3bc56c092e9be7e6b5a25ea601d920c4b7227457
bigcode/the-stack
train
001a9f3cd6d285855ed41a7c
train
function
def nobreak_as_a_keyword(source): """``nobreak`` is replaced by ``else`` only if it is the first non-space token on a line and if its indentation matches that of a ``for`` or ``while`` block. """ indentations = {} lines = token_utils.get_lines(source) new_tokens = [] for line in lines: ...
def nobreak_as_a_keyword(source):
"""``nobreak`` is replaced by ``else`` only if it is the first non-space token on a line and if its indentation matches that of a ``for`` or ``while`` block. """ indentations = {} lines = token_utils.get_lines(source) new_tokens = [] for line in lines: first = token_utils.get_fir...
our new transformation. """ if callback_params["show_original"]: utils.print_source(source, "Original") source = nobreak_as_a_keyword(source) if callback_params["show_transformed"]: utils.print_source(source, "Transformed") return source def nobreak_as_a_keyword(source):
64
64
173
8
55
aroberge/ideas
ideas/examples/nobreak.py
Python
nobreak_as_a_keyword
nobreak_as_a_keyword
33
53
33
33
7764f17592ff694ef7ca5d680652468131f10c7f
bigcode/the-stack
train
5c625a564c164552227bb98a
train
function
def add_hook(show_original=False, show_transformed=False, verbose_finder=False): """Creates and automatically adds the import hook in sys.meta_path""" callback_params = { "show_original": show_original, "show_transformed": show_transformed, } hook = import_hook.create_hook( trans...
def add_hook(show_original=False, show_transformed=False, verbose_finder=False):
"""Creates and automatically adds the import hook in sys.meta_path""" callback_params = { "show_original": show_original, "show_transformed": show_transformed, } hook = import_hook.create_hook( transform_source=transform_source, callback_params=callback_params, ho...
ations[first.start_col] in ["for", "while"]: first.string = "else" indentations[first.start_col] = first.string new_tokens.extend(line) return token_utils.untokenize(new_tokens) def add_hook(show_original=False, show_transformed=False, verbose_finder=False):
64
64
100
17
47
aroberge/ideas
ideas/examples/nobreak.py
Python
add_hook
add_hook
56
68
56
56
f90cc3c580a9abeee220f55d98aadebb3db3d105
bigcode/the-stack
train
91fb4879f99d3dca4fc2fcc8
train
class
class DefaultTeacher(WikiSQLTeacher): pass
class DefaultTeacher(WikiSQLTeacher):
pass
question = line["question"] table = table_data[id] context = table_into_context(table) sql = parse_into_sql(table, line["sql"]) yield (context + '\n' + question, [sql], None, None), new_episode class DefaultTeacher(WikiSQLTeacher):
64
64
11
8
55
novium258/cortx-1
doc/integrations/pytorch/parlai/tasks/wikisql/agents.py
Python
DefaultTeacher
DefaultTeacher
120
121
120
120
4d9ac945ba5941a99a7b098b1cad47d8683de273
bigcode/the-stack
train
b76a89d55e1ea32b82bbe004
train
function
def _datatype(opt): build(opt) dt = opt['datatype'].split(':')[0] if dt == 'train': suffix = 'train' # Using matched set as valid and mismatched set as test elif dt == 'valid': suffix = 'dev' elif dt == 'test': suffix = 'test' else: raise Runtim...
def _datatype(opt):
build(opt) dt = opt['datatype'].split(':')[0] if dt == 'train': suffix = 'train' # Using matched set as valid and mismatched set as test elif dt == 'valid': suffix = 'dev' elif dt == 'test': suffix = 'test' else: raise RuntimeError('Not valid dat...
in the # LICENSE file in the root directory of this source tree. # # Download and build the data if it does not exist. from parlai.core.teachers import DialogTeacher from parlai.utils.io import PathManager from .build import build import os import json def _datatype(opt):
64
64
91
5
58
novium258/cortx-1
doc/integrations/pytorch/parlai/tasks/wikisql/agents.py
Python
_datatype
_datatype
16
31
16
16
71ebc7bbf32aad1aa05c127fa0daa05610533b06
bigcode/the-stack
train
4390a484804961f253fcd7a3
train
class
class WikiSQLTeacher(DialogTeacher): def __init__(self, opt, shared=None): # store datatype self.dt = _datatype(opt) self.agg_ops = ['', 'MAX', 'MIN', 'COUNT', 'SUM', 'AVG'] self.cond_ops = ['=', '>', '<', 'OP'] self.syms = [ 'SELECT', 'WHERE...
class WikiSQLTeacher(DialogTeacher):
def __init__(self, opt, shared=None): # store datatype self.dt = _datatype(opt) self.agg_ops = ['', 'MAX', 'MIN', 'COUNT', 'SUM', 'AVG'] self.cond_ops = ['=', '>', '<', 'OP'] self.syms = [ 'SELECT', 'WHERE', 'AND', 'C...
python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # # Download and build the data if it does not exist. from parlai.core.teachers import DialogTeacher from parlai.utils.io imp...
184
184
616
7
176
novium258/cortx-1
doc/integrations/pytorch/parlai/tasks/wikisql/agents.py
Python
WikiSQLTeacher
WikiSQLTeacher
34
117
34
34
ae9987387cd8bd475f8b454384cc4bbd10b2f574
bigcode/the-stack
train
9bfcb7fd9c704ceb61decbc7
train
function
def copy_legacy_redirects(app, docname): # Sphinx expects two arguments # FILL in this dicts the necessary redirects redirect_files = { "creating_packages/package_dev_flow.html": "../developing_packages/package_dev_flow.html", "conan1.0.html": "faq/conan1.0.html", "mastering/python_requi...
def copy_legacy_redirects(app, docname): # Sphinx expects two arguments # FILL in this dicts the necessary redirects
redirect_files = { "creating_packages/package_dev_flow.html": "../developing_packages/package_dev_flow.html", "conan1.0.html": "faq/conan1.0.html", "mastering/python_requires.html": "../extending/python_requires.html", "mastering/version_ranges.html": "../versioning/version_ranges.ht...
default' # Fix unsupported image types using the Pillow. #epub_fix_images = False # Scale large images. #epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. #epub_show_urls = 'inline' # If false, no index is generated. #epub_use_index = True # A list of regular expressions that ...
217
217
724
30
186
conan-io/docs
conf.py
Python
copy_legacy_redirects
copy_legacy_redirects
406
469
406
407
00d72a18f7fef30d38301e6c2720aed172d8717d
bigcode/the-stack
train
0c437df0eda1172edb30d470
train
function
def setup(app): app.connect('build-finished', copy_legacy_redirects)
def setup(app):
app.connect('build-finished', copy_legacy_redirects)
target_path = app.outdir + '/' + html_src_path html = redirect_template % dst_path if not os.path.exists(os.path.dirname(target_path)): os.makedirs(os.path.dirname(target_path)) with open(target_path, "w") as f: f.write(html) def setup(app):
64
64
18
4
60
conan-io/docs
conf.py
Python
setup
setup
471
472
471
471
3be4b50f5db92f8088192104eb7b8e6bb83f739a
bigcode/the-stack
train
b01ba03aab38903c2cb03ac9
train
class
class TestAutoParallelMapper(unittest.TestCase): def test_mapper_dp_mp_pp(self): cluster_json_file = "" cluster_json_object = json.loads(cluster_json) with open("./auto_parallel_cluster.json", "w") as cluster_json_file: json.dump(cluster_json_object, cluster_json_file) cl...
class TestAutoParallelMapper(unittest.TestCase):
def test_mapper_dp_mp_pp(self): cluster_json_file = "" cluster_json_object = json.loads(cluster_json) with open("./auto_parallel_cluster.json", "w") as cluster_json_file: json.dump(cluster_json_object, cluster_json_file) cluster = Cluster() cluster.build_from_file...
(train_program, startup_program) dist_strategy = fleet.DistributedStrategy() # auto completion complete_train_program = auto.complete_annotation(train_program, dist_context) partitioner = Parti...
256
256
1,097
9
246
wanghuancoder/Paddle
python/paddle/fluid/tests/unittests/test_auto_parallel_mapper.py
Python
TestAutoParallelMapper
TestAutoParallelMapper
505
608
505
505
e5ffa8a6312f011290da71badba7cee167a551d7
bigcode/the-stack
train
0fcdc894762609913d505512
train
function
def is_in_machine(device_local_id, machine): for device in machine.devices.values(): if device_local_id == device.local_id: return True return False
def is_in_machine(device_local_id, machine):
for device in machine.devices.values(): if device_local_id == device.local_id: return True return False
_ops = partitioner.apply_optimize(optimizer, dist_params_grads, dist_train_program, dist_startup_prog) reshard(dist_train_program, dist_startup_prog, rank_id, dist_context) return dist_train_program, dist_startup_prog def is_in_machine(device_local_id, machine):
64
64
36
10
53
wanghuancoder/Paddle
python/paddle/fluid/tests/unittests/test_auto_parallel_mapper.py
Python
is_in_machine
is_in_machine
491
495
491
491
3f2697272da665aa39e12165c718588422339eb5
bigcode/the-stack
train
d8fb564e8021e82dbf8ffe5d
train
function
def mlp_forward(train_program, start_program): with static.program_guard(train_program,start_program), \ utils.unique_name.guard(): batch_size = 4 hidden_size = 64 input = static.data( name="input", shape=[batch_size, hidden_size], dtype='float32') label = static....
def mlp_forward(train_program, start_program):
with static.program_guard(train_program,start_program), \ utils.unique_name.guard(): batch_size = 4 hidden_size = 64 input = static.data( name="input", shape=[batch_size, hidden_size], dtype='float32') label = static.data( name="label", shape=[batch_si...
.linear0(out) out = F.gelu(out, approximate=True) out = self.linear1(out) out = self.linear2(out) out = F.gelu(out, approximate=True) out = self.linear3(out) return out def mlp_forward(train_program, start_program):
64
64
211
10
53
wanghuancoder/Paddle
python/paddle/fluid/tests/unittests/test_auto_parallel_mapper.py
Python
mlp_forward
mlp_forward
441
465
441
441
9836869db64f5e21847b8508a5472558ae379062
bigcode/the-stack
train
aef8a142f0803fed84ab0c5e
train
function
def get_dist_prog(train_program, startup_program, dist_context, rank_id): loss, train_program, startup_program = mlp_forward(train_program, startup_program) dist_strategy = fleet.DistributedStrategy() # auto completion complete_train_program = aut...
def get_dist_prog(train_program, startup_program, dist_context, rank_id):
loss, train_program, startup_program = mlp_forward(train_program, startup_program) dist_strategy = fleet.DistributedStrategy() # auto completion complete_train_program = auto.complete_annotation(train_program, ...
initializer_range=0.02) predict = mlp(input) error_cost = paddle.nn.functional.square_error_cost(predict, label) loss = paddle.mean(error_cost) return loss, train_program, start_program def get_dist_prog(train_program, startup_program, dist_context, rank_id):
64
64
205
16
47
wanghuancoder/Paddle
python/paddle/fluid/tests/unittests/test_auto_parallel_mapper.py
Python
get_dist_prog
get_dist_prog
468
488
468
468
c1e9dbf8a5422dd3201178da93b839c8840c8ca2
bigcode/the-stack
train
80454333a4c052f7ebc7c69d
train
function
def get_device_local_ids(machine): local_ids = [] for device in machine.devices.values(): local_ids.append[device.local_id] return local_ids
def get_device_local_ids(machine):
local_ids = [] for device in machine.devices.values(): local_ids.append[device.local_id] return local_ids
_startup_prog, rank_id, dist_context) return dist_train_program, dist_startup_prog def is_in_machine(device_local_id, machine): for device in machine.devices.values(): if device_local_id == device.local_id: return True return False def get_device_local_ids(machine):
64
64
34
7
56
wanghuancoder/Paddle
python/paddle/fluid/tests/unittests/test_auto_parallel_mapper.py
Python
get_device_local_ids
get_device_local_ids
498
502
498
498
3d8a16dcbadda240ee897f03053304f158665094
bigcode/the-stack
train
2ef74c000533b57396d88342
train
class
class MLPLayer(nn.Layer): def __init__(self, hidden_size=64, intermediate_size=4 * 64, initializer_range=0.02): super(MLPLayer, self).__init__() d_model = hidden_size dim_feedforward = intermediate_size np.random.seed(2021) a...
class MLPLayer(nn.Layer):
def __init__(self, hidden_size=64, intermediate_size=4 * 64, initializer_range=0.02): super(MLPLayer, self).__init__() d_model = hidden_size dim_feedforward = intermediate_size np.random.seed(2021) arr0 = np.random.normal(0, ...
type": "NVL", "bandwidth": 42 }, { "source_global_id": 8, "target_global_id": 6, "type": "NVL", "bandwidth": 42 }, { "source_global_id": 8, "target_global_id": 7, "type": "NVL", "bandwidth": 42 ...
183
183
610
7
176
wanghuancoder/Paddle
python/paddle/fluid/tests/unittests/test_auto_parallel_mapper.py
Python
MLPLayer
MLPLayer
375
438
375
375
a12a34e5ea524e037c81c91f04bba9ca2c42b765
bigcode/the-stack
train
54785f0293646aa6c456a6d2
train
function
def get_graphql_property_type_inputs( property_types: Sequence[PropertyTypeFragment], properties_dict: Dict[str, PropertyValue], ) -> List[PropertyTypeInput]: """This function gets existing property types and dictionary, where key - are type names, and keys - new values formats data, validates existence...
def get_graphql_property_type_inputs( property_types: Sequence[PropertyTypeFragment], properties_dict: Dict[str, PropertyValue], ) -> List[PropertyTypeInput]:
"""This function gets existing property types and dictionary, where key - are type names, and keys - new values formats data, validates existence of keys from `properties_dict` in `property_types` and returns list of PropertyTypeInput Args: property_types (List[ `pyinventory.graphql.propert...
_field_name[0]: gps_value[0], formated_type.graphql_field_name[1]: gps_value[1], } else: assert isinstance( value, formated_type.data_type ), f"property {property_type_name} is not of type {type_key}" return {formated_type.graphql_field_name[0]: cast(PropertyValu...
117
118
396
36
81
englishthomas/magma-1
symphony/cli/pyinventory/_utils.py
Python
get_graphql_property_type_inputs
get_graphql_property_type_inputs
73
122
73
76
b1154aeedeb217aed0789e0413c05cb36ac3382b
bigcode/the-stack
train
bbbea648fc25d260c3f5ecba
train
function
def get_port_definition_input( port_definition: EquipmentPortDefinitionFragment, is_new: bool = True ) -> EquipmentPortInput: return EquipmentPortInput( name=port_definition.name, id=port_definition.id if not is_new else None, index=port_definition.index, visibleLabel=port_defini...
def get_port_definition_input( port_definition: EquipmentPortDefinitionFragment, is_new: bool = True ) -> EquipmentPortInput:
return EquipmentPortInput( name=port_definition.name, id=port_definition.id if not is_new else None, index=port_definition.index, visibleLabel=port_definition.visibleLabel, )
=position_definition.name, id=position_definition.id if not is_new else None, index=position_definition.index, visibleLabel=position_definition.visibleLabel, ) def get_port_definition_input( port_definition: EquipmentPortDefinitionFragment, is_new: bool = True ) -> EquipmentPortInput:
64
64
72
28
36
englishthomas/magma-1
symphony/cli/pyinventory/_utils.py
Python
get_port_definition_input
get_port_definition_input
277
285
277
279
f5098000c25c074afc890ea1c750a3eefe738578
bigcode/the-stack
train
1b63fa607c16f8e79c402036
train
function
def format_property_definitions( properties: List[PropertyDefinition] ) -> List[PropertyTypeInput]: property_types = [ from_dict( data_class=PropertyTypeInput, data={ "name": prop.property_name, "type": PropertyKind(prop.property_kind), ...
def format_property_definitions( properties: List[PropertyDefinition] ) -> List[PropertyTypeInput]:
property_types = [ from_dict( data_class=PropertyTypeInput, data={ "name": prop.property_name, "type": PropertyKind(prop.property_kind), "index": i, "externalId": prop.external_id, "isMandatory": prop.is_...
EquipmentPortInput( name=port_definition.name, id=port_definition.id if not is_new else None, index=port_definition.index, visibleLabel=port_definition.visibleLabel, ) def format_property_definitions( properties: List[PropertyDefinition] ) -> List[PropertyTypeInput]:
64
64
148
22
42
englishthomas/magma-1
symphony/cli/pyinventory/_utils.py
Python
format_property_definitions
format_property_definitions
288
309
288
290
5880c9c6968d07af8c81c2abc55d23c99439e183
bigcode/the-stack
train
48e668131bf249a84e70f373
train
function
def deprecated( deprecated_in: str, deprecated_by: str ) -> Callable[[Callable[..., ReturnType]], Callable[..., ReturnType]]: def wrapped(func: Callable[..., ReturnType]) -> Callable[..., ReturnType]: def wrapper(*args: str, **kwargs: int) -> Callable[..., ReturnType]: func_name = func.__nam...
def deprecated( deprecated_in: str, deprecated_by: str ) -> Callable[[Callable[..., ReturnType]], Callable[..., ReturnType]]:
def wrapped(func: Callable[..., ReturnType]) -> Callable[..., ReturnType]: def wrapper(*args: str, **kwargs: int) -> Callable[..., ReturnType]: func_name = func.__name__ message = f"{func_name} is deprecated in {deprecated_in}. Use the {deprecated_by} function instead." w...
isInstanceProperty": not prop.is_fixed, }, config=Config(strict=True), ) for i, prop in enumerate(properties) ] return property_types def deprecated( deprecated_in: str, deprecated_by: str ) -> Callable[[Callable[..., ReturnType]], Callable[..., ReturnType]]:
64
64
141
28
35
englishthomas/magma-1
symphony/cli/pyinventory/_utils.py
Python
deprecated
deprecated
312
324
312
314
6850d03fca81e84d351b918da34d320ee40b44e3
bigcode/the-stack
train
9d01fd14ef8419ced9d2bb5e
train
function
def get_property_type_input( property_type: PropertyTypeFragment, is_new: bool = True ) -> PropertyTypeInput: return PropertyTypeInput( name=property_type.name, type=property_type.type, id=property_type.id if not is_new else None, externalId=property_type.externalId if not is_new...
def get_property_type_input( property_type: PropertyTypeFragment, is_new: bool = True ) -> PropertyTypeInput:
return PropertyTypeInput( name=property_type.name, type=property_type.type, id=property_type.id if not is_new else None, externalId=property_type.externalId if not is_new else None, index=property_type.index, category=property_type.category, stringValue=proper...
[str, str, Optional[PropertyValue], Optional[bool]]] ) -> List[PropertyTypeInput]: property_types = _make_property_types(properties) return property_types def get_property_type_input( property_type: PropertyTypeFragment, is_new: bool = True ) -> PropertyTypeInput:
64
64
205
27
36
englishthomas/magma-1
symphony/cli/pyinventory/_utils.py
Python
get_property_type_input
get_property_type_input
241
263
241
243
48a027fc8a570109e7217d2166ac29a7a39d5f07
bigcode/the-stack
train
5cfdd7bb681b5d21589bca5d
train
function
def _get_property_default_value( name: str, type: str, value: Optional[PropertyValue] ) -> Dict[str, PropertyValue]: if value is None: return {} # pyre-fixme[6]: Expected `Union[Tuple[float, float], bool, datetime.date, # float, int, str]` for 3rd param but got `Union[None, Tuple[float, float],...
def _get_property_default_value( name: str, type: str, value: Optional[PropertyValue] ) -> Dict[str, PropertyValue]:
if value is None: return {} # pyre-fixme[6]: Expected `Union[Tuple[float, float], bool, datetime.date, # float, int, str]` for 3rd param but got `Union[None, Tuple[float, float], bool, # datetime.date, float, int, str]`. return get_graphql_input_field(property_type_name=name, type_key=type...
_data), "%Y-%m-%d").date()) else: values.append(property.__dict__[str_field]) return tuple(value for value in values) def _get_property_default_value( name: str, type: str, value: Optional[PropertyValue] ) -> Dict[str, PropertyValue]:
64
64
128
31
33
englishthomas/magma-1
symphony/cli/pyinventory/_utils.py
Python
_get_property_default_value
_get_property_default_value
195
203
195
197
de1a6b6754b1ccc27d89d7f3f8ee85fe28d8bba7
bigcode/the-stack
train
b95919b4d3307aa3870448d8
train
function
def format_properties( properties: Sequence[Tuple[str, str, Optional[PropertyValue], Optional[bool]]] ) -> List[PropertyTypeInput]: property_types = _make_property_types(properties) return property_types
def format_properties( properties: Sequence[Tuple[str, str, Optional[PropertyValue], Optional[bool]]] ) -> List[PropertyTypeInput]:
property_types = _make_property_types(properties) return property_types
]: return value if key != "type" else PropertyKind(value) # TODO(T63055378): remove and change usage to format_property_definitions def format_properties( properties: Sequence[Tuple[str, str, Optional[PropertyValue], Optional[bool]]] ) -> List[PropertyTypeInput]:
64
64
47
32
31
englishthomas/magma-1
symphony/cli/pyinventory/_utils.py
Python
format_properties
format_properties
234
238
234
236
2e33f98d5b29be30045dc322d6573069ef16cd24
bigcode/the-stack
train
6c50ef7569466a32791cf24d
train
function
def get_position_definition_input( position_definition: EquipmentPositionDefinitionFragment, is_new: bool = True ) -> EquipmentPositionInput: return EquipmentPositionInput( name=position_definition.name, id=position_definition.id if not is_new else None, index=position_definition.index, ...
def get_position_definition_input( position_definition: EquipmentPositionDefinitionFragment, is_new: bool = True ) -> EquipmentPositionInput:
return EquipmentPositionInput( name=position_definition.name, id=position_definition.id if not is_new else None, index=position_definition.index, visibleLabel=position_definition.visibleLabel, )
property_type.isEditable, isInstanceProperty=property_type.isInstanceProperty, isMandatory=property_type.isMandatory, isDeleted=property_type.isDeleted, ) def get_position_definition_input( position_definition: EquipmentPositionDefinitionFragment, is_new: bool = True ) -> EquipmentPositi...
64
64
72
28
36
englishthomas/magma-1
symphony/cli/pyinventory/_utils.py
Python
get_position_definition_input
get_position_definition_input
266
274
266
268
eb1e614556bceedac9f793c773cd46528759e980
bigcode/the-stack
train
3287a7fbec88d78b757d432e
train
function
def format_to_type_and_field_name(type_key: str) -> Optional[DataTypeName]: formated = TYPE_AND_FIELD_NAME.get(type_key, None) return formated
def format_to_type_and_field_name(type_key: str) -> Optional[DataTypeName]:
formated = TYPE_AND_FIELD_NAME.get(type_key, None) return formated
import PropertyFragment from .graphql.property_input import PropertyInput from .graphql.property_kind_enum import PropertyKind from .graphql.property_type_fragment import PropertyTypeFragment from .graphql.property_type_input import PropertyTypeInput def format_to_type_and_field_name(type_key: str) -> Optional[DataTyp...
64
64
38
19
44
englishthomas/magma-1
symphony/cli/pyinventory/_utils.py
Python
format_to_type_and_field_name
format_to_type_and_field_name
34
36
34
34
d5f201fd9df9033b93dd705d7485fba215d65048
bigcode/the-stack
train
c1bd7a3940e9ee3577a19738
train
function
def get_graphql_property_inputs( property_types: Sequence[PropertyTypeFragment], properties_dict: Mapping[str, PropertyValue], ) -> List[PropertyInput]: """This function gets existing property types and dictionary, where key - are type names, and keys - new values formats data, validates existence of ke...
def get_graphql_property_inputs( property_types: Sequence[PropertyTypeFragment], properties_dict: Mapping[str, PropertyValue], ) -> List[PropertyInput]:
"""This function gets existing property types and dictionary, where key - are type names, and keys - new values formats data, validates existence of keys from `properties_dict` in `property_types` and returns list of PropertyInput Args: property_types (Sequence[ `pyinventory.graphql.propert...
"type": PropertyKind(property_type_names[name].type), } result.update( get_graphql_input_field( property_type_name=name, type_key=property_type_names[name].type.value, value=value, ) ) properties.append( ...
119
119
398
34
84
englishthomas/magma-1
symphony/cli/pyinventory/_utils.py
Python
get_graphql_property_inputs
get_graphql_property_inputs
125
174
125
128
4d91b57aaf2b08479e8800316a028222c55162a5
bigcode/the-stack
train
666aaf313078a0e1500f9eb3
train
function
def _make_property_types( properties: Sequence[Tuple[str, str, Optional[PropertyValue], Optional[bool]]] ) -> List[PropertyTypeInput]: property_types = [ from_dict( data_class=PropertyTypeInput, data={ "name": arg[0], "type": PropertyKind(arg[1]), ...
def _make_property_types( properties: Sequence[Tuple[str, str, Optional[PropertyValue], Optional[bool]]] ) -> List[PropertyTypeInput]:
property_types = [ from_dict( data_class=PropertyTypeInput, data={ "name": arg[0], "type": PropertyKind(arg[1]), "index": i, **_get_property_default_value(arg[0], arg[1], arg[2]), "isInstanceProperty": ar...
datetime.date, float, int, str]`. return get_graphql_input_field(property_type_name=name, type_key=type, value=value) def _make_property_types( properties: Sequence[Tuple[str, str, Optional[PropertyValue], Optional[bool]]] ) -> List[PropertyTypeInput]:
64
64
134
34
30
englishthomas/magma-1
symphony/cli/pyinventory/_utils.py
Python
_make_property_types
_make_property_types
206
223
206
208
7d6d9d9ecdcb21d57c6cfc4f7ab207a876d1ffb3
bigcode/the-stack
train
c90515c1535ac19f68b8ec12
train
function
def _get_property_value( property_type: str, property: PropertyFragment ) -> Tuple[PropertyValue, ...]: formated_name = format_to_type_and_field_name(property_type) if formated_name is None: raise AssertionError(f"Unknown property type - {property_type}") str_fields = formated_name.graphql_fiel...
def _get_property_value( property_type: str, property: PropertyFragment ) -> Tuple[PropertyValue, ...]:
formated_name = format_to_type_and_field_name(property_type) if formated_name is None: raise AssertionError(f"Unknown property type - {property_type}") str_fields = formated_name.graphql_field_name values = [] for str_field in str_fields: if property_type == "date": date...
.value, value=value, ) ) properties.append( from_dict(data_class=PropertyInput, data=result, config=Config(strict=True)) ) return properties def _get_property_value( property_type: str, property: PropertyFragment ) -> Tuple[PropertyValue, ...]:
64
64
148
26
37
englishthomas/magma-1
symphony/cli/pyinventory/_utils.py
Python
_get_property_value
_get_property_value
177
192
177
179
4412a656e2655564c9b8c4fd39cd0606122a1294
bigcode/the-stack
train
79dbef55d98738784b693b5b
train
function
def property_type_to_kind( key: str, value: PropertyValue ) -> Union[PropertyValue, PropertyKind]: return value if key != "type" else PropertyKind(value)
def property_type_to_kind( key: str, value: PropertyValue ) -> Union[PropertyValue, PropertyKind]:
return value if key != "type" else PropertyKind(value)
3], }, config=Config(strict=True), ) for i, arg in enumerate(properties) ] return property_types # TODO(T63055378): remove def property_type_to_kind( key: str, value: PropertyValue ) -> Union[PropertyValue, PropertyKind]:
64
64
40
26
37
englishthomas/magma-1
symphony/cli/pyinventory/_utils.py
Python
property_type_to_kind
property_type_to_kind
227
230
227
229
39f3b6716d69db042a70533777657151a055039d
bigcode/the-stack
train
e6b11bf037bc708ce929d83f
train
function
def get_graphql_input_field( property_type_name: str, type_key: str, value: PropertyValue ) -> Dict[str, PropertyValue]: formated_type = format_to_type_and_field_name(type_key) if formated_type is None: raise Exception( f"property type {property_type_name} has not supported type {type_ke...
def get_graphql_input_field( property_type_name: str, type_key: str, value: PropertyValue ) -> Dict[str, PropertyValue]:
formated_type = format_to_type_and_field_name(type_key) if formated_type is None: raise Exception( f"property type {property_type_name} has not supported type {type_key}" ) if type_key == "string": assert isinstance(value, str) or isinstance( value, bytes ...
.graphql.property_type_fragment import PropertyTypeFragment from .graphql.property_type_input import PropertyTypeInput def format_to_type_and_field_name(type_key: str) -> Optional[DataTypeName]: formated = TYPE_AND_FIELD_NAME.get(type_key, None) return formated def get_graphql_input_field( property_type_...
91
91
305
32
58
englishthomas/magma-1
symphony/cli/pyinventory/_utils.py
Python
get_graphql_input_field
get_graphql_input_field
39
70
39
41
46013f0bd7c35e75b96203646b89ff8aa9b74d8c
bigcode/the-stack
train
7726a65ae173e3325d5b0200
train
class
@pd.api.extensions.register_dataframe_accessor('dqc') # type: ignore class QualityChecker(object): """Monkeypatch pandas dataframe to provide quality checks.""" def __init__(self, pandas_obj: pd.DataFrame) -> None: """Dataframe to work on. Args: pandas_obj (pd.DataFrame): Datafram...
@pd.api.extensions.register_dataframe_accessor('dqc') # type: ignore class QualityChecker(object):
"""Monkeypatch pandas dataframe to provide quality checks.""" def __init__(self, pandas_obj: pd.DataFrame) -> None: """Dataframe to work on. Args: pandas_obj (pd.DataFrame): Dataframe to apply the checks on """ self._validate(pandas_obj) self._obj = pandas_o...
from lark import Lark, Tree, Token from pkg_resources import resource_string from typing import Tuple, List, Any from genie_pkg import GenieException import numpy as np from dateutil.parser import parse import pandas as pd import typing @pd.api.extensions.register_dataframe_accessor('dqc') # type: ignore class QualityC...
75
256
2,316
21
53
mkeshav/data-genie
genie_pkg/dqc.py
Python
QualityChecker
QualityChecker
10
245
10
12
77e11ca6d2b9a5b23da720a98bbacfe015e7cf26
bigcode/the-stack
train
61862eaea0e4a09e0c63a3aa
train
class
class Migration(migrations.Migration): dependencies = [ ('web', '0004_post_category'), ] operations = [ migrations.AddField( model_name='post', name='createdAt', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), ...
class Migration(migrations.Migration):
dependencies = [ ('web', '0004_post_category'), ] operations = [ migrations.AddField( model_name='post', name='createdAt', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), ...
# Generated by Django 2.0.2 on 2018-03-05 00:53 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration):
44
64
72
7
36
michaelhelvey/vault.io
web/migrations/0005_post_createdat.py
Python
Migration
Migration
7
20
7
8
b66d3be19cb9822f0b8c5e6d284af85d5a9b0145
bigcode/the-stack
train
368e6430fcc4a9e8f4cf4841
train
function
def call_prepare_scriptable_func_impl(obj, memo): if not isinstance(obj, torch.nn.Module): return obj obj_id = id(obj) # If obj_id is in memo, obj has already been prepared or is being # prepared in another call up the stack. if obj_id in memo: return memo[id(obj)] obj = obj._...
def call_prepare_scriptable_func_impl(obj, memo):
if not isinstance(obj, torch.nn.Module): return obj obj_id = id(obj) # If obj_id is in memo, obj has already been prepared or is being # prepared in another call up the stack. if obj_id in memo: return memo[id(obj)] obj = obj.__prepare_scriptable__() if hasattr(obj, '__prepare...
super().__init__() class ScriptModule(torch.nn.Module): # type: ignore[no-redef] def __init__(self, arg=None): super().__init__() class RecursiveScriptModule(ScriptModule): # type: ignore[no-redef] def __init__(self, arg=None): super().__init__() def call_prepare_scr...
82
82
275
11
72
rkindi/pytorch
torch/jit/_script.py
Python
call_prepare_scriptable_func_impl
call_prepare_scriptable_func_impl
942
973
942
942
425a85990e2f4c7a1f82b7d54e03818b976e4f8b
bigcode/the-stack
train
4b04d90c0e9e10bb97f933d2
train
class
class OrderedDictWrapper(object): def __init__(self, _c): self._c = _c def keys(self): return [k for k, v in self.items()] def values(self): return [v for k, v in self.items()] def __len__(self): return len(self.values()) def __delitem__(self, k): raise Ru...
class OrderedDictWrapper(object):
def __init__(self, _c): self._c = _c def keys(self): return [k for k, v in self.items()] def values(self): return [v for k, v in self.items()] def __len__(self): return len(self.values()) def __delitem__(self, k): raise RuntimeError("cannot delete methods ...
in C++. # Each OrderedDict needs to support: # x not in view # x in view # view[name] = ... # view.values() # del view[name] # view.items() # view.keys() # len(view) class OrderedDictWrapper(object):
64
64
216
6
58
rkindi/pytorch
torch/jit/_script.py
Python
OrderedDictWrapper
OrderedDictWrapper
152
185
152
152
eef94033eaddf1dec5e86d87884ea654891eacee
bigcode/the-stack
train
30a5afdd1d9f83aad5a35915
train
class
class _CachedForward(object): def __get__(self, obj, cls): return self.__getattr__("forward") # type: ignore[attr-defined]
class _CachedForward(object):
def __get__(self, obj, cls): return self.__getattr__("forward") # type: ignore[attr-defined]
(self, name) for name in ("_parameters", "_buffers", "_modules"): delattr(self, name) cls.__init__ = init_then_script # type: ignore[misc] super(ScriptMeta, cls).__init__(name, bases, attrs) class _CachedForward(object):
64
64
34
6
58
rkindi/pytorch
torch/jit/_script.py
Python
_CachedForward
_CachedForward
296
298
296
296
289769a9973674b568b985a240bafe2c8d9d4312
bigcode/the-stack
train
97db50859b99384796bd7e17
train
function
def script(obj, optimize=None, _frames_up=0, _rcb=None, example_inputs: Union[List[Tuple], Dict[Callable, List[Tuple]], None] = None): r""" Scripting a function or ``nn.Module`` will inspect the source code, compile it as TorchScript code using the TorchScript compiler, and return a :class:`Scrip...
def script(obj, optimize=None, _frames_up=0, _rcb=None, example_inputs: Union[List[Tuple], Dict[Callable, List[Tuple]], None] = None):
r""" Scripting a function or ``nn.Module`` will inspect the source code, compile it as TorchScript code using the TorchScript compiler, and return a :class:`ScriptModule` or :class:`ScriptFunction`. TorchScript itself is a subset of the Python language, so not all features in Python work, but we pro...
``obj``. Args: obj (dict): The Python dictionary that is used to initialize the ``ScriptDict`` returned by this function. Returns: An instance of ``torch._C.ScriptDict`` that has the same data as ``obj`` and can be passed between Python and TorchScript with referen...
256
256
2,645
40
216
rkindi/pytorch
torch/jit/_script.py
Python
script
script
1,010
1,318
1,010
1,011
e2181f3d5f54df33a5e907efbb24b606d382c366
bigcode/the-stack
train
721d836a15c703ae1051bfb6
train
function
def create_script_dict(obj): """ Create a ``torch._C.ScriptDict`` instance with the data from ``obj``. Args: obj (dict): The Python dictionary that is used to initialize the ``ScriptDict`` returned by this function. Returns: An instance of ``torch._C.ScriptDict`` th...
def create_script_dict(obj):
""" Create a ``torch._C.ScriptDict`` instance with the data from ``obj``. Args: obj (dict): The Python dictionary that is used to initialize the ``ScriptDict`` returned by this function. Returns: An instance of ``torch._C.ScriptDict`` that has the same data as ``obj...
for k, v in new_obj_dict.items(): obj.__dict__[name] = v return obj def call_prepare_scriptable_func(obj): memo: Dict[int, torch.nn.Module] = {} return call_prepare_scriptable_func_impl(obj, memo) def create_script_dict(obj):
64
64
117
6
58
rkindi/pytorch
torch/jit/_script.py
Python
create_script_dict
create_script_dict
980
993
980
980
4d77aab4a0ebde900f391ec0ee6293bca34e54fd
bigcode/the-stack
train
9d144eb0dc3d235113b41e7c
train
function
def _unwrap_optional(x): assert x is not None, "Unwrapping null optional" return x
def _unwrap_optional(x):
assert x is not None, "Unwrapping null optional" return x
.add_row(line, stat.duration_ns()) table = _ScriptProfileTable([lineno, hits, time_ns, line_contents], list(source_range)) outputs.append(table.dump_string()) return '\n\n'.join(outputs) def dump(self): print(self.dump_string()) def _unwrap_optional(x):
64
64
24
6
58
rkindi/pytorch
torch/jit/_script.py
Python
_unwrap_optional
_unwrap_optional
1,543
1,545
1,543
1,543
b1fa88923138f2411d0de9634cf1dbcc757569c5
bigcode/the-stack
train
92871ec9359d7df95c873c1e
train
function
def _check_directly_compile_overloaded(obj): qual_name = _qualified_name(obj) if _jit_internal._get_fn_overloads(qual_name) or _try_get_jit_cached_overloads(obj): raise RuntimeError( "Function {} cannot be directly compiled because it" " is overloaded. It must be used in a contex...
def _check_directly_compile_overloaded(obj):
qual_name = _qualified_name(obj) if _jit_internal._get_fn_overloads(qual_name) or _try_get_jit_cached_overloads(obj): raise RuntimeError( "Function {} cannot be directly compiled because it" " is overloaded. It must be used in a context of a function" " where its inpu...
_compiled_fns + compiled_fns # cache compilation, remove information stored to do compilation _set_jit_overload_cache(obj, compiled_fns) _jit_internal._clear_fn_overloads(qual_name) return compiled_fns def _check_directly_compile_overloaded(obj):
64
64
95
10
53
rkindi/pytorch
torch/jit/_script.py
Python
_check_directly_compile_overloaded
_check_directly_compile_overloaded
1,386
1,393
1,386
1,386
8148587c32e077ffd3db1433deaa87e3348c42af
bigcode/the-stack
train
3935df4f8b2ce69db2a6faf0
train
function
def script_method(fn): if not _enabled: return fn # NOTE: we need to traverse two frames here because the meta-class frame # for ScriptModule will be present, as opposed to invoking @script on a # a function or invoking define() on a CompilationUnit. # The stack will look like: # # 0...
def script_method(fn):
if not _enabled: return fn # NOTE: we need to traverse two frames here because the meta-class frame # for ScriptModule will be present, as opposed to invoking @script on a # a function or invoking define() on a CompilationUnit. # The stack will look like: # # 0. createResolutionCallb...
super(ScriptMeta, cls).__init__(name, bases, attrs) class _CachedForward(object): def __get__(self, obj, cls): return self.__getattr__("forward") # type: ignore[attr-defined] class ScriptWarning(Warning): pass def script_method(fn):
64
64
200
5
58
rkindi/pytorch
torch/jit/_script.py
Python
script_method
script_method
305
322
305
305
22c321e9be3d5571b13c440e3318c1c93195acd8
bigcode/the-stack
train
98fa980fcf78bd522535e1e0
train
function
def _compile_function_with_overload(overload_fn, qual_name, impl_fn): overload_decl = get_jit_def(overload_fn, overload_fn.__name__).decl() overload_signature = torch.jit.annotations.get_signature( overload_fn, None, None, inspect.ismethod(overload_fn) ) impl_ast = get_jit_def(impl_fn, impl_fn._...
def _compile_function_with_overload(overload_fn, qual_name, impl_fn):
overload_decl = get_jit_def(overload_fn, overload_fn.__name__).decl() overload_signature = torch.jit.annotations.get_signature( overload_fn, None, None, inspect.ismethod(overload_fn) ) impl_ast = get_jit_def(impl_fn, impl_fn.__name__) overload_defaults = get_default_args(overload_fn) imp...
( loc, "Default parameters on overloads do not affect the runtime so they " "must equal to the default parameter on the implementation function. Found on " "parameter {name}".format(name=name), ) def _compile_function_with_overload(overload_fn,...
64
64
185
17
47
rkindi/pytorch
torch/jit/_script.py
Python
_compile_function_with_overload
_compile_function_with_overload
1,336
1,356
1,336
1,336
6ee71351066d8d73d6bb3b8242b33a615a5764be
bigcode/the-stack
train
a7bfc5418e1a362a7af0b185
train
class
class OrderedModuleDict(OrderedDictWrapper): def __init__(self, module, python_dict): super(OrderedModuleDict, self).__init__(torch._C.ModuleDict(module)) # contains _both_ script modules and non-script python-only modules # because script modules are subclassed in python and the # ...
class OrderedModuleDict(OrderedDictWrapper):
def __init__(self, module, python_dict): super(OrderedModuleDict, self).__init__(torch._C.ModuleDict(module)) # contains _both_ script modules and non-script python-only modules # because script modules are subclassed in python and the # C++ Module class will not hold references to ...
self._c.items() def __setitem__(self, k, v): if k not in self: raise RuntimeError( "Can't add a new parameter after ScriptModule construction." " Tried to add '{}".format(k) ) self._c.setattr(k, v) def __contains__(self, k): retu...
120
120
403
9
111
rkindi/pytorch
torch/jit/_script.py
Python
OrderedModuleDict
OrderedModuleDict
188
226
188
188
5f0ca8cc72abc7cee755dda9ab8d78227f0f3e03
bigcode/the-stack
train
5d71c043eebcc0875efa3502
train
function
def _is_new_style_class(cls): if hasattr(cls, "__class__"): return "__dict__" in dir(cls) or hasattr(cls, "__slots__")
def _is_new_style_class(cls):
if hasattr(cls, "__class__"): return "__dict__" in dir(cls) or hasattr(cls, "__slots__")
_db # Gets a function from the name of a method on a type def _get_function_from_type(cls, name): return getattr(cls, name, None) # ScriptClasses must be new-style classes because we construct them using their # __new__ method. def _is_new_style_class(cls):
64
64
35
8
56
rkindi/pytorch
torch/jit/_script.py
Python
_is_new_style_class
_is_new_style_class
132
134
132
132
54a60bf41ae59999dc46f01db3ae8e17ebc82d04
bigcode/the-stack
train
d0adc301083a88b16d342d2d
train
function
def _check_overload_defaults(impl_defaults, overload_defaults, loc): for name, overload_value in overload_defaults.items(): if name not in impl_defaults or impl_defaults[name] != overload_value: raise torch.jit.frontend.FrontendError( loc, "Default parameters on o...
def _check_overload_defaults(impl_defaults, overload_defaults, loc):
for name, overload_value in overload_defaults.items(): if name not in impl_defaults or impl_defaults[name] != overload_value: raise torch.jit.frontend.FrontendError( loc, "Default parameters on overloads do not affect the runtime so they " "must eq...
fn else: return torch.jit._recursive.create_script_class(obj) # overloads are registered in _jit_internal and compiled here so that _overload # can be used in nn/functional.py without an import cycle def _check_overload_defaults(impl_defaults, overload_defaults, loc):
64
64
100
15
48
rkindi/pytorch
torch/jit/_script.py
Python
_check_overload_defaults
_check_overload_defaults
1,325
1,333
1,325
1,325
778518ae1629197adf3ede22abe61d4dec96921e
bigcode/the-stack
train
af8cb22fbaee045c0064aca2
train
function
def call_prepare_scriptable_func(obj): memo: Dict[int, torch.nn.Module] = {} return call_prepare_scriptable_func_impl(obj, memo)
def call_prepare_scriptable_func(obj):
memo: Dict[int, torch.nn.Module] = {} return call_prepare_scriptable_func_impl(obj, memo)
new_obj_dict[name] = call_prepare_scriptable_func_impl(sub_module, memo) else: new_obj_dict[name] = sub_module for k, v in new_obj_dict.items(): obj.__dict__[name] = v return obj def call_prepare_scriptable_func(obj):
64
64
32
8
55
rkindi/pytorch
torch/jit/_script.py
Python
call_prepare_scriptable_func
call_prepare_scriptable_func
976
978
976
976
f7dd334736497ff96c9fef24c0d107171e3604c7
bigcode/the-stack
train
825b6c29e5502c4d18e33798
train
class
class ConstMap: def __init__(self, const_mapping): self.const_mapping = const_mapping def __getattr__(self, attr): return self.const_mapping[attr]
class ConstMap:
def __init__(self, const_mapping): self.const_mapping = const_mapping def __getattr__(self, attr): return self.const_mapping[attr]
2 gets us to the proper surrounding scope. _rcb = _jit_internal.createResolutionCallbackFromFrame(frames_up=2) ast = get_jit_def(fn, fn.__name__, self_name="ScriptModule") return ScriptMethodStub(_rcb, ast, fn) class ConstMap:
64
64
39
4
60
rkindi/pytorch
torch/jit/_script.py
Python
ConstMap
ConstMap
325
330
325
325
ae40518f2a5a266392a4dd9b8aa879fd867bf31e
bigcode/the-stack
train
9cd3a3f28df7bef34cd6314a
train
function
def _get_type_trace_db(): # This is a private API. Use of this for external purposes is discouraged. return type_trace_db
def _get_type_trace_db(): # This is a private API. Use of this for external purposes is discouraged.
return type_trace_db
del AttributeModule del m Args: value: An initial value to be assigned to attribute. type: A Python type Returns: Returns `value` """ def _get_type_trace_db(): # This is a private API. Use of this for external purposes is discouraged.
64
64
30
24
40
rkindi/pytorch
torch/jit/_script.py
Python
_get_type_trace_db
_get_type_trace_db
121
123
121
122
0938518f33d394df91a2016c6055cc2946f3f969
bigcode/the-stack
train
815b52d9fa1ca83f0fcb9937
train
function
def create_script_list(obj, type_hint=None): """ Create a ``torch._C.ScriptList`` instance with the data from ``obj``. Args: obj (dict): The Python list that is used to initialize the ``ScriptList`` returned by this function. Returns: An instance of ``torch._C.ScriptL...
def create_script_list(obj, type_hint=None):
""" Create a ``torch._C.ScriptList`` instance with the data from ``obj``. Args: obj (dict): The Python list that is used to initialize the ``ScriptList`` returned by this function. Returns: An instance of ``torch._C.ScriptList`` that has the same data as ``obj`` ...
._C.ScriptDict`` that has the same data as ``obj`` and can be passed between Python and TorchScript with reference semantics and zero copy overhead. """ return torch._C.ScriptDict(obj) # type: ignore[attr-defined] def create_script_list(obj, type_hint=None):
64
64
122
10
54
rkindi/pytorch
torch/jit/_script.py
Python
create_script_list
create_script_list
996
1,007
996
996
87fe3f79dcf5af13c0b01e6300d1886964c37be9
bigcode/the-stack
train
365f67793bafd67ab86beb53
train
class
class ScriptWarning(Warning): pass
class ScriptWarning(Warning):
pass
# type: ignore[misc] super(ScriptMeta, cls).__init__(name, bases, attrs) class _CachedForward(object): def __get__(self, obj, cls): return self.__getattr__("forward") # type: ignore[attr-defined] class ScriptWarning(Warning):
64
64
9
6
58
rkindi/pytorch
torch/jit/_script.py
Python
ScriptWarning
ScriptWarning
301
302
301
301
9fe84fcc17ff05c513038c1b9538725c988ac101
bigcode/the-stack
train
ed979552767aa1f3c0203fe6
train
class
class _ScriptProfile: def __init__(self): self.profile = classes.profiling._ScriptProfile() def enable(self): self.profile.enable() def disable(self): self.profile.disable() def dump_string(self) -> str: outputs: List[str] = [] for source_stats in self.profile....
class _ScriptProfile:
def __init__(self): self.profile = classes.profiling._ScriptProfile() def enable(self): self.profile.enable() def disable(self): self.profile.disable() def dump_string(self) -> str: outputs: List[str] = [] for source_stats in self.profile._dump_stats(): ...
cells.append((header, dict(rows))) outputs.append(header_buffer) outputs.append(pad('', len(header_buffer), 0, '=')) for line in self.source_range: row_buffer = '' for header, rows in cells: cell = rows.get(line) if cell is Non...
101
101
337
5
96
rkindi/pytorch
torch/jit/_script.py
Python
_ScriptProfile
_ScriptProfile
1,501
1,540
1,501
1,501
4c498d3c529edebeedb7bde66fd065640ae09e80
bigcode/the-stack
train
3e49c6876c612913acb0b225
train
function
def _get_overloads(obj): # check for cached compiled fns existing_compiled_fns = _try_get_jit_cached_overloads(obj) qual_name = _qualified_name(obj) uncompiled_overloads = _jit_internal._get_fn_overloads(qual_name) if uncompiled_overloads is None: return existing_compiled_fns if obj in ...
def _get_overloads(obj): # check for cached compiled fns
existing_compiled_fns = _try_get_jit_cached_overloads(obj) qual_name = _qualified_name(obj) uncompiled_overloads = _jit_internal._get_fn_overloads(qual_name) if uncompiled_overloads is None: return existing_compiled_fns if obj in uncompiled_overloads: raise RuntimeError(_jit_interna...
.range() ) fn = torch._C._jit_script_compile_overload( qual_name, overload_decl, impl_ast, _rcb, implementation_defaults, overload_signature, ) return fn def _get_overloads(obj): # check for cached compiled fns
64
64
216
16
47
rkindi/pytorch
torch/jit/_script.py
Python
_get_overloads
_get_overloads
1,359
1,383
1,359
1,360
526a36a1e87a37451050c38c607db51985c5689f
bigcode/the-stack
train
b826b890646a3a91885f37d6
train
function
def _recursive_compile_class(obj, loc): _qual_name = _qualified_name(obj) # We're starting a new compilation, so update the error call stack in # case it fails error_stack = torch._C.CallStack(_qual_name, loc) rcb = _jit_internal.createResolutionCallbackForClassMethods(obj) return _compile_and_r...
def _recursive_compile_class(obj, loc):
_qual_name = _qualified_name(obj) # We're starting a new compilation, so update the error call stack in # case it fails error_stack = torch._C.CallStack(_qual_name, loc) rcb = _jit_internal.createResolutionCallbackForClassMethods(obj) return _compile_and_register_class(obj, rcb, _qual_name)
_class_def(obj, obj.__name__) mangled_classname = torch._C._jit_script_interface_compile( qualified_name, ast, rcb, is_module_interface ) obj.__torch_script_interface__ = mangled_classname return obj def _recursive_compile_class(obj, loc):
64
64
87
9
54
rkindi/pytorch
torch/jit/_script.py
Python
_recursive_compile_class
_recursive_compile_class
1,427
1,433
1,427
1,427
fff94ac4e128da44e9cac597fbf07962f20d07be
bigcode/the-stack
train
91f35d85eb35dad25e6ed93d
train
function
def pad(s: str, padding: int, offset: int = 0, char: str = ' '): if padding >= len(s): padding -= len(s) return ''.join([char for _ in range(padding + offset)]) + s
def pad(s: str, padding: int, offset: int = 0, char: str = ' '):
if padding >= len(s): padding -= len(s) return ''.join([char for _ in range(padding + offset)]) + s
Methods(obj) return _compile_and_register_class(obj, rcb, _qual_name) CompilationUnit = torch._C.CompilationUnit set_module(CompilationUnit, "torch.jit") def pad(s: str, padding: int, offset: int = 0, char: str = ' '):
64
64
55
24
40
rkindi/pytorch
torch/jit/_script.py
Python
pad
pad
1,439
1,442
1,439
1,439
692c35ea11a5266daf2e368ae9cbc640f4d58560
bigcode/the-stack
train
3b1cd4ebbed17642a8134aeb
train
function
def unpackage_script_module(importer: PackageImporter, script_module_id: str) -> torch.nn.Module: """ Called by ``torch.package.PackageImporter``'s Pickler's ``persistent_load`` function. Performs work of loading and returning a ScriptModule from a ``torch.package`` archive. """ if not isinstance(im...
def unpackage_script_module(importer: PackageImporter, script_module_id: str) -> torch.nn.Module:
""" Called by ``torch.package.PackageImporter``'s Pickler's ``persistent_load`` function. Performs work of loading and returning a ScriptModule from a ``torch.package`` archive. """ if not isinstance(importer.zip_reader, torch._C.PyTorchFileReader): raise RuntimeError( "Loading S...
, fn) class ConstMap: def __init__(self, const_mapping): self.const_mapping = const_mapping def __getattr__(self, attr): return self.const_mapping[attr] def unpackage_script_module(importer: PackageImporter, script_module_id: str) -> torch.nn.Module:
64
64
179
22
42
rkindi/pytorch
torch/jit/_script.py
Python
unpackage_script_module
unpackage_script_module
333
351
333
333
1e3b552c9b94e157520f826085ed711973961689
bigcode/the-stack
train
e45b3eeb6d57c450f02863d3
train
class
class _ScriptProfileTable: def __init__(self, cols: List[_ScriptProfileColumn], source_range: List[int]): self.cols = cols self.source_range = source_range def dump_string(self): outputs: List[str] = [] cells: List[Tuple[str, Dict[int, str]]] = [] header_buffer = '' ...
class _ScriptProfileTable:
def __init__(self, cols: List[_ScriptProfileColumn], source_range: List[int]): self.cols = cols self.source_range = source_range def dump_string(self): outputs: List[str] = [] cells: List[Tuple[str, Dict[int, str]]] = [] header_buffer = '' for col in self.cols: ...
_length + self.alignment padding -= padding % self.alignment else: padding = 0 rows = [(key, pad(cell, padding, self.offset)) for key, cell in rows] return pad(self.header, padding, self.offset), rows class _ScriptProfileTable:
64
64
193
6
57
rkindi/pytorch
torch/jit/_script.py
Python
_ScriptProfileTable
_ScriptProfileTable
1,473
1,498
1,473
1,473
b2c8c1a734e64cf47f447013462beb92dd263ba9
bigcode/the-stack
train
7beb572bb05759528db6dc91
train
class
class ScriptMeta(type): def __init__(cls, name, bases, attrs): # noqa: B902 # Aggregate all the ScriptMethods and constants from superclasses cls._methods: Dict[str, Any] = {} cls._constants_set = set(getattr(cls, "__constants__", ())) for base in reversed(bases): for k,...
class ScriptMeta(type):
def __init__(cls, name, bases, attrs): # noqa: B902 # Aggregate all the ScriptMethods and constants from superclasses cls._methods: Dict[str, Any] = {} cls._constants_set = set(getattr(cls, "__constants__", ())) for base in reversed(bases): for k, v in getattr(base, "_me...
to replace existing module '{}': {}".format(k, v) ) def __getitem__(self, k): return self._python_modules[k] # For each user-defined class that subclasses ScriptModule, this meta-class: # (1) finds all the methods annotated with @script_method in a ScriptModule and # removes them from th...
163
163
546
5
158
rkindi/pytorch
torch/jit/_script.py
Python
ScriptMeta
ScriptMeta
237
293
237
237
bcbc6f292b8b644eee96b56db300430e9a587a76
bigcode/the-stack
train
bbef5c8dfd6a85f9c348b716
train
class
class _ScriptProfileColumn: def __init__(self, header: str, alignment: int = 4, offset: int = 0): self.header = header self.alignment = alignment self.offset = offset self.rows: Dict[int, Any] = {} def add_row(self, lineno: int, value: Any): self.rows[lineno] = value ...
class _ScriptProfileColumn:
def __init__(self, header: str, alignment: int = 4, offset: int = 0): self.header = header self.alignment = alignment self.offset = offset self.rows: Dict[int, Any] = {} def add_row(self, lineno: int, value: Any): self.rows[lineno] = value def materialize(self): ...
"torch.jit") def pad(s: str, padding: int, offset: int = 0, char: str = ' '): if padding >= len(s): padding -= len(s) return ''.join([char for _ in range(padding + offset)]) + s class _ScriptProfileColumn:
66
66
220
6
59
rkindi/pytorch
torch/jit/_script.py
Python
_ScriptProfileColumn
_ScriptProfileColumn
1,445
1,470
1,445
1,445
44906247ed7e28daeccdc6ffb56c966e4969bf43
bigcode/the-stack
train
a98da4fd0f357a3470aa43f7
train
function
def _get_function_from_type(cls, name): return getattr(cls, name, None)
def _get_function_from_type(cls, name):
return getattr(cls, name, None)
Returns: Returns `value` """ def _get_type_trace_db(): # This is a private API. Use of this for external purposes is discouraged. return type_trace_db # Gets a function from the name of a method on a type def _get_function_from_type(cls, name):
64
64
19
10
53
rkindi/pytorch
torch/jit/_script.py
Python
_get_function_from_type
_get_function_from_type
126
127
126
126
609f3e033bc1e6ce911a86cacebce3ebd764bda1
bigcode/the-stack
train
f1fcafae79ede7d1154df49b
train
function
def interface(obj): if not inspect.isclass(obj): raise RuntimeError("interface must be applied to a class") if not _is_new_style_class(obj): raise RuntimeError("TorchScript interfaces must inherit from 'object'") # Expected MRO is: # User module # torch.nn.modules.module.Module ...
def interface(obj):
if not inspect.isclass(obj): raise RuntimeError("interface must be applied to a class") if not _is_new_style_class(obj): raise RuntimeError("TorchScript interfaces must inherit from 'object'") # Expected MRO is: # User module # torch.nn.modules.module.Module # object i...
_qualified_name(obj) if _jit_internal._get_fn_overloads(qual_name) or _try_get_jit_cached_overloads(obj): raise RuntimeError( "Function {} cannot be directly compiled because it" " is overloaded. It must be used in a context of a function" " where its inputs can determin...
85
85
284
4
81
rkindi/pytorch
torch/jit/_script.py
Python
interface
interface
1,396
1,424
1,396
1,396
0413e10a90e35618391fe0067bd6e0f1a8f229ba
bigcode/the-stack
train
824ea38edf64f735a37dd8f3
train
class
@skipIf(NO_MOCK, NO_MOCK_REASON) @skipIf(six.PY3, 'Running tests with Python 3. These tests need to be rewritten to support Py3.') @skipIf(HAS_BOTO is False, 'The boto module must be installed.') @skipIf(HAS_MOTO is False, 'The moto module must be installed.') class BotoElbTestCase(TestCase, LoaderModuleMockMixin): ...
@skipIf(NO_MOCK, NO_MOCK_REASON) @skipIf(six.PY3, 'Running tests with Python 3. These tests need to be rewritten to support Py3.') @skipIf(HAS_BOTO is False, 'The boto module must be installed.') @skipIf(HAS_MOTO is False, 'The moto module must be installed.') class BotoElbTestCase(TestCase, LoaderModuleMockMixin):
''' TestCase for salt.modules.boto_elb module ''' def setup_loader_modules(self): opts = salt.config.DEFAULT_MASTER_OPTS utils = salt.loader.utils(opts, whitelist=['boto']) funcs = salt.loader.minion_mods(opts, utils=utils) return { boto_elb: { ...
s from tests.support.mixins import LoaderModuleMockMixin from tests.support.unit import skipIf, TestCase from tests.support.mock import NO_MOCK, NO_MOCK_REASON log = logging.getLogger(__name__) region = 'us-east-1' access_key = 'GKTADJGHEIQSXMKKRBJ08H' secret_key = 'askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs' conn_par...
255
256
1,525
91
164
l2ol33rt/salt
tests/unit/modules/test_boto_elb.py
Python
BotoElbTestCase
BotoElbTestCase
69
211
69
73
2cdfdd7fb21c46543a241659745eb55a731a784a
bigcode/the-stack
train
965161edb13110654506a211
train
function
def __populate_resources(collection): # Iterate over categories for category in collection.categories: usage = dict() # Extract callbacks for callback in collection.callbacks(category): for parameter in (p for i, p in enumerate(callback.declaration.points.parameters) ...
def __populate_resources(collection): # Iterate over categories
for category in collection.categories: usage = dict() # Extract callbacks for callback in collection.callbacks(category): for parameter in (p for i, p in enumerate(callback.declaration.points.parameters) if isinstance(p, Declaration) and ...
interfaces present in the collection after this function termination. :param collection: InterfaceCategoriesSpecification object. :param conf: Configuration property dictionary of InterfaceCategoriesSpecification object. :return: None """ # Add resources if get_conf_property(collection.conf, ...
95
95
318
12
82
mutilin/klever
core/core/vtg/emg/processGenerator/linuxModule/interface/categories.py
Python
__populate_resources
__populate_resources
46
82
46
47
a27fd8f4f732626ae44894cc8c47fb0b562e8d71
bigcode/the-stack
train
8eb1b998d54bf668c0cd893e
train
function
def __complement_interfaces(collection): def __match_interface_for_container(signature, category, id_match): candidates = collection.resolve_interface_weakly(signature, category, use_cache=False) if len(candidates) == 1: return candidates[0] elif len(candidates) == 0: ...
def __complement_interfaces(collection):
def __match_interface_for_container(signature, category, id_match): candidates = collection.resolve_interface_weakly(signature, category, use_cache=False) if len(candidates) == 1: return candidates[0] elif len(candidates) == 0: return None else: st...
category, False) if len(p_interface) == 0: p_interface = collection.resolve_interface_weakly(declaration.parameters[index], category, False) if len(p_interface) == 1: p_interface = p_interface[0] elif len(p_interface) == 0: p_interface...
168
168
563
7
160
mutilin/klever
core/core/vtg/emg/processGenerator/linuxModule/interface/categories.py
Python
__complement_interfaces
__complement_interfaces
165
229
165
165
aba445120a4cc638f6a85fa0300e345a271903cf
bigcode/the-stack
train
0976c94e9553c4eae53d4589
train
function
def fulfill_function_interfaces(collection, interface, category=None): """ Check an interface declaration (function or function pointer) and try to match its return value type and parameters arguments types with existing interfaces. The algorythm should be the following: * Match explicitly stated inter...
def fulfill_function_interfaces(collection, interface, category=None):
""" Check an interface declaration (function or function pointer) and try to match its return value type and parameters arguments types with existing interfaces. The algorythm should be the following: * Match explicitly stated interface References (only if they meet given category). * Match rest pa...
# Try to resolve interface intfs = collection.resolve_interface_weakly(parameter, category=callback.category, use_cache=False) if len(intfs) == 0: # Only unmatched resources should be introduced usage[parameter.identifier] = { ...
226
226
754
11
214
mutilin/klever
core/core/vtg/emg/processGenerator/linuxModule/interface/categories.py
Python
fulfill_function_interfaces
fulfill_function_interfaces
85
162
85
85
2060ce98024c29d3507cc5279142b5575dc24ed7
bigcode/the-stack
train
7f4828b7f1ecf39ffc01e9d9
train
function
def yield_categories(collection): """ Analyze all new types found by SA component and yield final set of interface categories built from manually prepared interface specifications and global variables. All new categories and interfaces are added directly to the InterfaceCategoriesSpecification object. A...
def yield_categories(collection):
""" Analyze all new types found by SA component and yield final set of interface categories built from manually prepared interface specifications and global variables. All new categories and interfaces are added directly to the InterfaceCategoriesSpecification object. Also all types declarations are upd...
. # from core.vtg.emg.common import get_conf_property from core.vtg.emg.common.c.types import Declaration, Function, Array, Pointer, Primitive from core.vtg.emg.processGenerator.linuxModule.interface import Resource, Callback, StructureContainer, \ FunctionInterface def yield_categories(collection):
64
64
156
5
58
mutilin/klever
core/core/vtg/emg/processGenerator/linuxModule/interface/categories.py
Python
yield_categories
yield_categories
24
43
24
24
3b6a06c724b3883c98b150cafb4a642782c8a058
bigcode/the-stack
train
fb27c727f7aef1d5cf0e1000
train
function
def fib(n: int) -> int: """Calculate n-th Fibonacci number recursively, short version.""" assert n >= 0 return 1 if n in [0, 1] else fib(n - 1) + fib(n - 2)
def fib(n: int) -> int:
"""Calculate n-th Fibonacci number recursively, short version.""" assert n >= 0 return 1 if n in [0, 1] else fib(n - 1) + fib(n - 2)
def fib(n: int) -> int:
9
64
55
9
0
deeplook/tenliners
pyteen/snippets/algorithms/fibonacci_rec_short.py
Python
fib
fib
1
4
1
1
7cb0252508ab68a5244621e0b1f58ad5dcfb918f
bigcode/the-stack
train
be29d976ad34334fc475bfce
train
function
def test_lasertiming_dmov_fail(): logger.debug('test_lasertiming_dmov_fail') FakeLaserTiming = make_fake_device(LaserTiming) lxt = FakeLaserTiming('FAKE:VIT', name='fstiming') # The move should timeout if the DMOV signal is never put to with pytest.raises(StatusTimeoutError): lxt.mv(1e-6, wa...
def test_lasertiming_dmov_fail():
logger.debug('test_lasertiming_dmov_fail') FakeLaserTiming = make_fake_device(LaserTiming) lxt = FakeLaserTiming('FAKE:VIT', name='fstiming') # The move should timeout if the DMOV signal is never put to with pytest.raises(StatusTimeoutError): lxt.mv(1e-6, wait=True, timeout=1)
test_lasertiming_dmov_pass(lxt): logger.debug('test_lasertiming_dmov') # Ensure the wrapper and pv_positioner done checking are working lxt.mv(1e-6, wait=True, timeout=1) def test_lasertiming_dmov_fail():
64
64
95
10
54
dlzhu/pcdsdevices
tests/test_lxe.py
Python
test_lasertiming_dmov_fail
test_lasertiming_dmov_fail
105
111
105
105
afa8716dca8ed41c7f2db2119c08a213e2735be5
bigcode/the-stack
train
dd59ddb3568bce00ac1d00d5
train
function
def test_laser_timing_offset(lxt): logger.debug('test_laser_timing_offset') print('Dial position is', lxt.position) # lxt.limits = (1e-10, 1e-3) initial_limits = lxt.limits for pos in [1.0e-6, 2.0e-6, 8.0e-4]: print('Setting the current position to', pos) print('Limits were', lxt.lim...
def test_laser_timing_offset(lxt):
logger.debug('test_laser_timing_offset') print('Dial position is', lxt.position) # lxt.limits = (1e-10, 1e-3) initial_limits = lxt.limits for pos in [1.0e-6, 2.0e-6, 8.0e-4]: print('Setting the current position to', pos) print('Limits were', lxt.limits) lxt.set_current_positi...
9, 10e-9) with pytest.raises(ValueError): lxt.mv(-1.1e-9) with pytest.raises(ValueError): lxt.mv(11e-9) lxt.mv(1e-9) def test_laser_timing_offset(lxt):
64
64
194
10
54
dlzhu/pcdsdevices
tests/test_lxe.py
Python
test_laser_timing_offset
test_laser_timing_offset
195
212
195
195
af8149416b1bd68524288e19cc8ca61224853a28
bigcode/the-stack
train
e1f88998c65003a8488bfbfd
train
function
def test_laser_timing_motion(lxt): logger.debug('test_laser_timing_motion') # A basic dependency sanity check... np.testing.assert_allclose(convert_unit(1, 's', 'ns'), 1e9) for pos in range(1, 3): pos *= 1e-6 lxt.move(pos).wait(1) np.testing.assert_allclose(lxt.position, pos) ...
def test_laser_timing_motion(lxt):
logger.debug('test_laser_timing_motion') # A basic dependency sanity check... np.testing.assert_allclose(convert_unit(1, 's', 'ns'), 1e9) for pos in range(1, 3): pos *= 1e-6 lxt.move(pos).wait(1) np.testing.assert_allclose(lxt.position, pos) np.testing.assert_allclose(-l...
=True, timeout=1) def test_lasertiming_dmov_fail(): logger.debug('test_lasertiming_dmov_fail') FakeLaserTiming = make_fake_device(LaserTiming) lxt = FakeLaserTiming('FAKE:VIT', name='fstiming') # The move should timeout if the DMOV signal is never put to with pytest.raises(StatusTimeoutError): ...
111
111
373
10
101
dlzhu/pcdsdevices
tests/test_lxe.py
Python
test_laser_timing_motion
test_laser_timing_motion
114
153
114
114
77dc63b52cc86100990fb57835043b8818429329
bigcode/the-stack
train
4b40ac78b4d244e382bd7076
train
function
def test_lasertiming_dmov_pass(lxt): logger.debug('test_lasertiming_dmov') # Ensure the wrapper and pv_positioner done checking are working lxt.mv(1e-6, wait=True, timeout=1)
def test_lasertiming_dmov_pass(lxt):
logger.debug('test_lasertiming_dmov') # Ensure the wrapper and pv_positioner done checking are working lxt.mv(1e-6, wait=True, timeout=1)
='lxt') lxt._fs_tgt_time.sim_set_limits(lxt.limits) lxt._fs_tgt_time.sim_put(0) wrap_pv_positioner_move(monkeypatch, lxt) return lxt def test_lasertiming_dmov_pass(lxt):
64
64
55
12
51
dlzhu/pcdsdevices
tests/test_lxe.py
Python
test_lasertiming_dmov_pass
test_lasertiming_dmov_pass
99
102
99
99
49d625e84c05e7a2bd1a028e6fe2a0ba8fde7f0a
bigcode/the-stack
train
193b784487de0692dc1075e3
train
function
@pytest.mark.timeout(5) def test_lxe_disconnected(lxe_calibration_file): logger.debug('test_lxe_disconnected') LaserTiming('TST', name='tst') LaserEnergyPositioner('TST2', name='tst2', calibration_file=lxe_calibration_file) LaserTimingCompensation('TST3', delay_prefix='TST3:DEL...
@pytest.mark.timeout(5) def test_lxe_disconnected(lxe_calibration_file):
logger.debug('test_lxe_disconnected') LaserTiming('TST', name='tst') LaserEnergyPositioner('TST2', name='tst2', calibration_file=lxe_calibration_file) LaserTimingCompensation('TST3', delay_prefix='TST3:DELAY', laser_prefix='TST3:LASER', name='tst3')
) np.testing.assert_allclose( [lxt_ttc.delay.inverse(i * 1e5).delay for i in range(len(mm_to_seconds_values))], mm_to_seconds_values, ) @pytest.mark.timeout(5) def test_lxe_disconnected(lxe_calibration_file):
64
64
102
18
46
dlzhu/pcdsdevices
tests/test_lxe.py
Python
test_lxe_disconnected
test_lxe_disconnected
300
307
300
301
5456ab7c51f843d6aaca00412a9f491fd0032950
bigcode/the-stack
train
cd4d5d50c4eba1447acf4cd3
train
function
def wrap_pv_positioner_move(monkeypatch, pv_positioner): """Monkeypatch move method on PV positioner to allow testing.""" if getattr(pv_positioner.move, '_wrapped', False): return def move_replacement(position, wait=False, **kwargs): st = original_move(position, wait=False, **kwargs) ...
def wrap_pv_positioner_move(monkeypatch, pv_positioner):
"""Monkeypatch move method on PV positioner to allow testing.""" if getattr(pv_positioner.move, '_wrapped', False): return def move_replacement(position, wait=False, **kwargs): st = original_move(position, wait=False, **kwargs) # if pv_positioner.done is not None: # pv_p...
= True lxe.move(20) lxe.enable_plotting = False lxe.move(30) with pytest.raises(ValueError): # Out-of-range value lxe.move(1e9) def wrap_pv_positioner_move(monkeypatch, pv_positioner):
64
64
176
15
49
dlzhu/pcdsdevices
tests/test_lxe.py
Python
wrap_pv_positioner_move
wrap_pv_positioner_move
49
66
49
49
2e9bf47ff576d166e3daa52080073eb23024107e
bigcode/the-stack
train
ac70f2eb873e2cbf368d3ea7
train
function
def test_laser_energy_positioner(monkeypatch, lxe_calibration_file): logger.debug('test_laser_energy_positioner') class MyLaserEnergyPositioner(LaserEnergyPositioner): motor = Cpt(SoftPositioner) def no_op(*args, **kwargs): ... monkeypatch.setattr(LaserEnergyPlotContext, 'plot', no_op...
def test_laser_energy_positioner(monkeypatch, lxe_calibration_file):
logger.debug('test_laser_energy_positioner') class MyLaserEnergyPositioner(LaserEnergyPositioner): motor = Cpt(SoftPositioner) def no_op(*args, **kwargs): ... monkeypatch.setattr(LaserEnergyPlotContext, 'plot', no_op) monkeypatch.setattr(LaserEnergyPlotContext, 'add_line', no_op) ...
ensation) from pcdsdevices.utils import convert_unit logger = logging.getLogger(__name__) @pytest.fixture def lxe_calibration_file(): return MODULE_PATH / 'xcslt8717_wpcalib_opa' def test_laser_energy_positioner(monkeypatch, lxe_calibration_file):
64
64
184
17
47
dlzhu/pcdsdevices
tests/test_lxe.py
Python
test_laser_energy_positioner
test_laser_energy_positioner
24
46
24
24
2288ec4da39ca31826c176649551447a159196fb
bigcode/the-stack
train
eead8d1ef1cfbe592e142a5f
train
function
def test_laser_timing_compensation(lxt_ttc): logger.debug('test_laser_timing_compensation') pos = 1.0e-6 lxt_ttc.move(pos).wait(timeout=2) assert lxt_ttc.position[0] == pos assert lxt_ttc.delay.position[0] == pos np.testing.assert_allclose(lxt_ttc.laser.position, pos) milliseconds_to_mm_v...
def test_laser_timing_compensation(lxt_ttc):
logger.debug('test_laser_timing_compensation') pos = 1.0e-6 lxt_ttc.move(pos).wait(timeout=2) assert lxt_ttc.position[0] == pos assert lxt_ttc.delay.position[0] == pos np.testing.assert_allclose(lxt_ttc.laser.position, pos) milliseconds_to_mm_values = [ # Delay motor is inverted: ...
lxt_ttc.delay.motor.user_setpoint.sim_set_limits((-1e12, 1e12)) lxt_ttc.delay.motor.motor_spg.sim_put('Go') wrap_pv_positioner_move(monkeypatch, lxt_ttc.laser) wrap_motor_move(monkeypatch, lxt_ttc.delay.motor) return lxt_ttc def test_laser_timing_compensation(lxt_ttc):
90
90
303
13
76
dlzhu/pcdsdevices
tests/test_lxe.py
Python
test_laser_timing_compensation
test_laser_timing_compensation
260
297
260
260
b0ad5d773fdef3f1aa11239144391219418e297e
bigcode/the-stack
train
304cb950441c0b0a2e94dd25
train
function
@pytest.fixture def lxt_ttc(monkeypatch): """LaserTimingCompensation pseudopositioner device instance for testing.""" lxt_ttc = make_fake_device(LaserTimingCompensation)( '', delay_prefix='DELAY:', laser_prefix='LASER:', name='lxt_ttc') lxt_ttc.laser._fs_tgt_time.sim_set_lim...
@pytest.fixture def lxt_ttc(monkeypatch):
"""LaserTimingCompensation pseudopositioner device instance for testing.""" lxt_ttc = make_fake_device(LaserTimingCompensation)( '', delay_prefix='DELAY:', laser_prefix='LASER:', name='lxt_ttc') lxt_ttc.laser._fs_tgt_time.sim_set_limits((0, 4e9)) lxt_ttc.laser._fs_tgt_ti...
.subscribe(complete_move, run=False) lxt.mv(5e-6) assert lxt.notepad_setpoint.get() == 5e-6 assert lxt.notepad_readback.get() == 5e-6 @pytest.fixture def lxt_ttc(monkeypatch):
64
64
214
12
51
dlzhu/pcdsdevices
tests/test_lxe.py
Python
lxt_ttc
lxt_ttc
240
257
240
241
89d42007590bacdcddc2acc8eb060fed55d14f78
bigcode/the-stack
train