body_hash
stringlengths 64
64
| body
stringlengths 23
109k
| docstring
stringlengths 1
57k
| path
stringlengths 4
198
| name
stringlengths 1
115
| repository_name
stringlengths 7
111
| repository_stars
float64 0
191k
| lang
stringclasses 1
value | body_without_docstring
stringlengths 14
108k
| unified
stringlengths 45
133k
|
---|---|---|---|---|---|---|---|---|---|
c0f8f62ef290d770a0f3612b243341227fd0a5d5a9e0662a9d203426c2ec4374
|
def cconv2d(x, w, **kwargs):
' Performs convolution with complex inputs and weights\n\n Need to create the weights and feed to this function. If you want to have\n this done for you automatically, use :py:func:`complex_convolution`.\n\n Parameters\n ----------\n x : tf tensor\n input tensor\n w : tf tensor\n weights tensor\n kwargs : (key, val) pairs\n Same as tf.nn.conv2d\n\n Returns\n -------\n y : :py:class:`tf.Tensor`\n Result of applying convolution to x\n\n Notes\n -----\n Uses tf.nn.conv2d which I believe is actually cross-correlation.\n '
default_args = {'strides': [1, 1, 1, 1], 'padding': 'SAME', 'data_format': 'NHWC', 'name': None}
for (key, val) in kwargs.items():
if (key not in default_args.keys()):
raise KeyError('Unknown argument {} for function tf.nn.conv2d'.format(key))
else:
default_args[key] = val
x = tf.cast(x, tf.complex64)
w = tf.cast(w, tf.complex64)
x_r = tf.real(x)
x_i = tf.imag(x)
w_r = tf.real(w)
w_i = tf.imag(w)
conv = (lambda x, w: tf.nn.conv2d(x, w, **default_args))
y_r = (conv(x_r, w_r) - conv(x_i, w_i))
y_i = (conv(x_i, w_r) + conv(x_r, w_i))
return tf.complex(y_r, y_i)
|
Performs convolution with complex inputs and weights
Need to create the weights and feed to this function. If you want to have
this done for you automatically, use :py:func:`complex_convolution`.
Parameters
----------
x : tf tensor
input tensor
w : tf tensor
weights tensor
kwargs : (key, val) pairs
Same as tf.nn.conv2d
Returns
-------
y : :py:class:`tf.Tensor`
Result of applying convolution to x
Notes
-----
Uses tf.nn.conv2d which I believe is actually cross-correlation.
|
tf_ops/general.py
|
cconv2d
|
fbcotter/tf_ops
| 0 |
python
|
def cconv2d(x, w, **kwargs):
' Performs convolution with complex inputs and weights\n\n Need to create the weights and feed to this function. If you want to have\n this done for you automatically, use :py:func:`complex_convolution`.\n\n Parameters\n ----------\n x : tf tensor\n input tensor\n w : tf tensor\n weights tensor\n kwargs : (key, val) pairs\n Same as tf.nn.conv2d\n\n Returns\n -------\n y : :py:class:`tf.Tensor`\n Result of applying convolution to x\n\n Notes\n -----\n Uses tf.nn.conv2d which I believe is actually cross-correlation.\n '
default_args = {'strides': [1, 1, 1, 1], 'padding': 'SAME', 'data_format': 'NHWC', 'name': None}
for (key, val) in kwargs.items():
if (key not in default_args.keys()):
raise KeyError('Unknown argument {} for function tf.nn.conv2d'.format(key))
else:
default_args[key] = val
x = tf.cast(x, tf.complex64)
w = tf.cast(w, tf.complex64)
x_r = tf.real(x)
x_i = tf.imag(x)
w_r = tf.real(w)
w_i = tf.imag(w)
conv = (lambda x, w: tf.nn.conv2d(x, w, **default_args))
y_r = (conv(x_r, w_r) - conv(x_i, w_i))
y_i = (conv(x_i, w_r) + conv(x_r, w_i))
return tf.complex(y_r, y_i)
|
def cconv2d(x, w, **kwargs):
' Performs convolution with complex inputs and weights\n\n Need to create the weights and feed to this function. If you want to have\n this done for you automatically, use :py:func:`complex_convolution`.\n\n Parameters\n ----------\n x : tf tensor\n input tensor\n w : tf tensor\n weights tensor\n kwargs : (key, val) pairs\n Same as tf.nn.conv2d\n\n Returns\n -------\n y : :py:class:`tf.Tensor`\n Result of applying convolution to x\n\n Notes\n -----\n Uses tf.nn.conv2d which I believe is actually cross-correlation.\n '
default_args = {'strides': [1, 1, 1, 1], 'padding': 'SAME', 'data_format': 'NHWC', 'name': None}
for (key, val) in kwargs.items():
if (key not in default_args.keys()):
raise KeyError('Unknown argument {} for function tf.nn.conv2d'.format(key))
else:
default_args[key] = val
x = tf.cast(x, tf.complex64)
w = tf.cast(w, tf.complex64)
x_r = tf.real(x)
x_i = tf.imag(x)
w_r = tf.real(w)
w_i = tf.imag(w)
conv = (lambda x, w: tf.nn.conv2d(x, w, **default_args))
y_r = (conv(x_r, w_r) - conv(x_i, w_i))
y_i = (conv(x_i, w_r) + conv(x_r, w_i))
return tf.complex(y_r, y_i)<|docstring|>Performs convolution with complex inputs and weights
Need to create the weights and feed to this function. If you want to have
this done for you automatically, use :py:func:`complex_convolution`.
Parameters
----------
x : tf tensor
input tensor
w : tf tensor
weights tensor
kwargs : (key, val) pairs
Same as tf.nn.conv2d
Returns
-------
y : :py:class:`tf.Tensor`
Result of applying convolution to x
Notes
-----
Uses tf.nn.conv2d which I believe is actually cross-correlation.<|endoftext|>
|
e2c146a479e5b6329339212aa23fa19a4be1db3d54ce70b593655cbf759a7d3d
|
def cconv2d_transpose(y, w, output_shape, **kwargs):
' Performs transpose convolution with complex outputs and weights.\n\n Need to create the weights and feed to this function. If you want to have\n this done for you automatically, use\n :py:func:`complex_convolution_transpose`.\n\n Parameters\n ----------\n x : tf tensor\n input tensor\n w : tf tensor\n weights tensor\n kwargs : (key, val) pairs\n Same as tf.nn.conv2d_transpose\n\n Notes\n -----\n Takes the complex conjugate of w before doing convolution. Uses\n tf.nn.conv2d_transpose which I believe is actually convolution.\n\n Returns\n -------\n y : :py:class:`tf.Tensor`\n Result of applying convolution to x\n '
default_args = {'strides': [1, 1, 1, 1], 'padding': 'SAME', 'data_format': 'NHWC', 'name': None}
for (key, val) in kwargs.items():
if (key not in default_args.keys()):
raise KeyError(('Unknown argument {} for function '.format(key) + 'tf.nn.conv2d_transpose'))
else:
default_args[key] = val
y = tf.cast(y, tf.complex64)
w = tf.cast(w, tf.complex64)
y_r = tf.real(y)
y_i = tf.imag(y)
w_r = tf.real(w)
w_i = (- tf.imag(w))
conv = (lambda y, w: tf.nn.conv2d_transpose(y, w, output_shape, **default_args))
x_r = (conv(y_r, w_r) - conv(y_i, w_i))
x_i = (conv(y_i, w_r) + conv(y_r, w_i))
x_r = tf.reshape(x_r, output_shape)
x_i = tf.reshape(x_i, output_shape)
return tf.complex(x_r, x_i)
|
Performs transpose convolution with complex outputs and weights.
Need to create the weights and feed to this function. If you want to have
this done for you automatically, use
:py:func:`complex_convolution_transpose`.
Parameters
----------
x : tf tensor
input tensor
w : tf tensor
weights tensor
kwargs : (key, val) pairs
Same as tf.nn.conv2d_transpose
Notes
-----
Takes the complex conjugate of w before doing convolution. Uses
tf.nn.conv2d_transpose which I believe is actually convolution.
Returns
-------
y : :py:class:`tf.Tensor`
Result of applying convolution to x
|
tf_ops/general.py
|
cconv2d_transpose
|
fbcotter/tf_ops
| 0 |
python
|
def cconv2d_transpose(y, w, output_shape, **kwargs):
' Performs transpose convolution with complex outputs and weights.\n\n Need to create the weights and feed to this function. If you want to have\n this done for you automatically, use\n :py:func:`complex_convolution_transpose`.\n\n Parameters\n ----------\n x : tf tensor\n input tensor\n w : tf tensor\n weights tensor\n kwargs : (key, val) pairs\n Same as tf.nn.conv2d_transpose\n\n Notes\n -----\n Takes the complex conjugate of w before doing convolution. Uses\n tf.nn.conv2d_transpose which I believe is actually convolution.\n\n Returns\n -------\n y : :py:class:`tf.Tensor`\n Result of applying convolution to x\n '
default_args = {'strides': [1, 1, 1, 1], 'padding': 'SAME', 'data_format': 'NHWC', 'name': None}
for (key, val) in kwargs.items():
if (key not in default_args.keys()):
raise KeyError(('Unknown argument {} for function '.format(key) + 'tf.nn.conv2d_transpose'))
else:
default_args[key] = val
y = tf.cast(y, tf.complex64)
w = tf.cast(w, tf.complex64)
y_r = tf.real(y)
y_i = tf.imag(y)
w_r = tf.real(w)
w_i = (- tf.imag(w))
conv = (lambda y, w: tf.nn.conv2d_transpose(y, w, output_shape, **default_args))
x_r = (conv(y_r, w_r) - conv(y_i, w_i))
x_i = (conv(y_i, w_r) + conv(y_r, w_i))
x_r = tf.reshape(x_r, output_shape)
x_i = tf.reshape(x_i, output_shape)
return tf.complex(x_r, x_i)
|
def cconv2d_transpose(y, w, output_shape, **kwargs):
' Performs transpose convolution with complex outputs and weights.\n\n Need to create the weights and feed to this function. If you want to have\n this done for you automatically, use\n :py:func:`complex_convolution_transpose`.\n\n Parameters\n ----------\n x : tf tensor\n input tensor\n w : tf tensor\n weights tensor\n kwargs : (key, val) pairs\n Same as tf.nn.conv2d_transpose\n\n Notes\n -----\n Takes the complex conjugate of w before doing convolution. Uses\n tf.nn.conv2d_transpose which I believe is actually convolution.\n\n Returns\n -------\n y : :py:class:`tf.Tensor`\n Result of applying convolution to x\n '
default_args = {'strides': [1, 1, 1, 1], 'padding': 'SAME', 'data_format': 'NHWC', 'name': None}
for (key, val) in kwargs.items():
if (key not in default_args.keys()):
raise KeyError(('Unknown argument {} for function '.format(key) + 'tf.nn.conv2d_transpose'))
else:
default_args[key] = val
y = tf.cast(y, tf.complex64)
w = tf.cast(w, tf.complex64)
y_r = tf.real(y)
y_i = tf.imag(y)
w_r = tf.real(w)
w_i = (- tf.imag(w))
conv = (lambda y, w: tf.nn.conv2d_transpose(y, w, output_shape, **default_args))
x_r = (conv(y_r, w_r) - conv(y_i, w_i))
x_i = (conv(y_i, w_r) + conv(y_r, w_i))
x_r = tf.reshape(x_r, output_shape)
x_i = tf.reshape(x_i, output_shape)
return tf.complex(x_r, x_i)<|docstring|>Performs transpose convolution with complex outputs and weights.
Need to create the weights and feed to this function. If you want to have
this done for you automatically, use
:py:func:`complex_convolution_transpose`.
Parameters
----------
x : tf tensor
input tensor
w : tf tensor
weights tensor
kwargs : (key, val) pairs
Same as tf.nn.conv2d_transpose
Notes
-----
Takes the complex conjugate of w before doing convolution. Uses
tf.nn.conv2d_transpose which I believe is actually convolution.
Returns
-------
y : :py:class:`tf.Tensor`
Result of applying convolution to x<|endoftext|>
|
8fdb0d8a8df9b8152f3b3c1533834930aa7c47ed980d2790842befef8a084c14
|
def separable_conv_with_pad(x, h_row, h_col, stride=1):
' Function to do spatial separable convolution.\n\n The filter weights must already be defined. It will use symmetric extension\n before convolution.\n\n Parameters\n ----------\n x : :py:class:`tf.Tensor` of shape [Batch, height, width, c]\n The input variable. Should be of shape\n h_row : tf tensor of shape [1, l, c_in, c_out]\n The spatial row filter\n h_col : tf tensor of shape [l, 1, c_in, c_out]\n The column filter.\n stride : int\n What stride to use on the convolution.\n\n Returns\n -------\n y : :py:class:`tf.Tensor`\n Result of applying convolution to x\n '
if tf.is_numeric_tensor(h_row):
h_size = h_row.get_shape().as_list()
else:
h_size = h_row.shape
assert (h_size[0] == 1)
pad = (h_size[1] // 2)
if ((h_size[1] % 2) == 0):
y = tf.pad(x, [[0, 0], [0, 0], [(pad - 1), pad], [0, 0]], 'SYMMETRIC')
else:
y = tf.pad(x, [[0, 0], [0, 0], [pad, pad], [0, 0]], 'SYMMETRIC')
y = tf.nn.conv2d(y, h_row, strides=[1, stride, stride, 1], padding='VALID')
if tf.is_numeric_tensor(h_col):
h_size = h_col.get_shape().as_list()
else:
h_size = h_col.shape
assert (h_size[1] == 1)
pad = (h_size[0] // 2)
if ((h_size[0] % 2) == 0):
y = tf.pad(y, [[0, 0], [(pad - 1), pad], [0, 0], [0, 0]], 'SYMMETRIC')
else:
y = tf.pad(y, [[0, 0], [pad, pad], [0, 0], [0, 0]], 'SYMMETRIC')
y = tf.nn.conv2d(y, h_col, strides=[1, stride, stride, 1], padding='VALID')
assert (x.get_shape().as_list()[1:3] == y.get_shape().as_list()[1:3])
return y
|
Function to do spatial separable convolution.
The filter weights must already be defined. It will use symmetric extension
before convolution.
Parameters
----------
x : :py:class:`tf.Tensor` of shape [Batch, height, width, c]
The input variable. Should be of shape
h_row : tf tensor of shape [1, l, c_in, c_out]
The spatial row filter
h_col : tf tensor of shape [l, 1, c_in, c_out]
The column filter.
stride : int
What stride to use on the convolution.
Returns
-------
y : :py:class:`tf.Tensor`
Result of applying convolution to x
|
tf_ops/general.py
|
separable_conv_with_pad
|
fbcotter/tf_ops
| 0 |
python
|
def separable_conv_with_pad(x, h_row, h_col, stride=1):
' Function to do spatial separable convolution.\n\n The filter weights must already be defined. It will use symmetric extension\n before convolution.\n\n Parameters\n ----------\n x : :py:class:`tf.Tensor` of shape [Batch, height, width, c]\n The input variable. Should be of shape\n h_row : tf tensor of shape [1, l, c_in, c_out]\n The spatial row filter\n h_col : tf tensor of shape [l, 1, c_in, c_out]\n The column filter.\n stride : int\n What stride to use on the convolution.\n\n Returns\n -------\n y : :py:class:`tf.Tensor`\n Result of applying convolution to x\n '
if tf.is_numeric_tensor(h_row):
h_size = h_row.get_shape().as_list()
else:
h_size = h_row.shape
assert (h_size[0] == 1)
pad = (h_size[1] // 2)
if ((h_size[1] % 2) == 0):
y = tf.pad(x, [[0, 0], [0, 0], [(pad - 1), pad], [0, 0]], 'SYMMETRIC')
else:
y = tf.pad(x, [[0, 0], [0, 0], [pad, pad], [0, 0]], 'SYMMETRIC')
y = tf.nn.conv2d(y, h_row, strides=[1, stride, stride, 1], padding='VALID')
if tf.is_numeric_tensor(h_col):
h_size = h_col.get_shape().as_list()
else:
h_size = h_col.shape
assert (h_size[1] == 1)
pad = (h_size[0] // 2)
if ((h_size[0] % 2) == 0):
y = tf.pad(y, [[0, 0], [(pad - 1), pad], [0, 0], [0, 0]], 'SYMMETRIC')
else:
y = tf.pad(y, [[0, 0], [pad, pad], [0, 0], [0, 0]], 'SYMMETRIC')
y = tf.nn.conv2d(y, h_col, strides=[1, stride, stride, 1], padding='VALID')
assert (x.get_shape().as_list()[1:3] == y.get_shape().as_list()[1:3])
return y
|
def separable_conv_with_pad(x, h_row, h_col, stride=1):
' Function to do spatial separable convolution.\n\n The filter weights must already be defined. It will use symmetric extension\n before convolution.\n\n Parameters\n ----------\n x : :py:class:`tf.Tensor` of shape [Batch, height, width, c]\n The input variable. Should be of shape\n h_row : tf tensor of shape [1, l, c_in, c_out]\n The spatial row filter\n h_col : tf tensor of shape [l, 1, c_in, c_out]\n The column filter.\n stride : int\n What stride to use on the convolution.\n\n Returns\n -------\n y : :py:class:`tf.Tensor`\n Result of applying convolution to x\n '
if tf.is_numeric_tensor(h_row):
h_size = h_row.get_shape().as_list()
else:
h_size = h_row.shape
assert (h_size[0] == 1)
pad = (h_size[1] // 2)
if ((h_size[1] % 2) == 0):
y = tf.pad(x, [[0, 0], [0, 0], [(pad - 1), pad], [0, 0]], 'SYMMETRIC')
else:
y = tf.pad(x, [[0, 0], [0, 0], [pad, pad], [0, 0]], 'SYMMETRIC')
y = tf.nn.conv2d(y, h_row, strides=[1, stride, stride, 1], padding='VALID')
if tf.is_numeric_tensor(h_col):
h_size = h_col.get_shape().as_list()
else:
h_size = h_col.shape
assert (h_size[1] == 1)
pad = (h_size[0] // 2)
if ((h_size[0] % 2) == 0):
y = tf.pad(y, [[0, 0], [(pad - 1), pad], [0, 0], [0, 0]], 'SYMMETRIC')
else:
y = tf.pad(y, [[0, 0], [pad, pad], [0, 0], [0, 0]], 'SYMMETRIC')
y = tf.nn.conv2d(y, h_col, strides=[1, stride, stride, 1], padding='VALID')
assert (x.get_shape().as_list()[1:3] == y.get_shape().as_list()[1:3])
return y<|docstring|>Function to do spatial separable convolution.
The filter weights must already be defined. It will use symmetric extension
before convolution.
Parameters
----------
x : :py:class:`tf.Tensor` of shape [Batch, height, width, c]
The input variable. Should be of shape
h_row : tf tensor of shape [1, l, c_in, c_out]
The spatial row filter
h_col : tf tensor of shape [l, 1, c_in, c_out]
The column filter.
stride : int
What stride to use on the convolution.
Returns
-------
y : :py:class:`tf.Tensor`
Result of applying convolution to x<|endoftext|>
|
c0b459b94a69d4569a72039a956877ce99e1e7952e052744e36950471885e2ae
|
def _get_var_name(x):
' Find the name of the variable by stripping off the scopes\n\n Notes\n -----\n A typical name will be scope1/scope2/.../name/kernel:0.\n This function serves to split off the scopes and return kernel\n '
split_colon = x.name.split(':')[0]
slash_strs = split_colon.split('/')
last_one = slash_strs[(- 1)]
return last_one
|
Find the name of the variable by stripping off the scopes
Notes
-----
A typical name will be scope1/scope2/.../name/kernel:0.
This function serves to split off the scopes and return kernel
|
tf_ops/general.py
|
_get_var_name
|
fbcotter/tf_ops
| 0 |
python
|
def _get_var_name(x):
' Find the name of the variable by stripping off the scopes\n\n Notes\n -----\n A typical name will be scope1/scope2/.../name/kernel:0.\n This function serves to split off the scopes and return kernel\n '
split_colon = x.name.split(':')[0]
slash_strs = split_colon.split('/')
last_one = slash_strs[(- 1)]
return last_one
|
def _get_var_name(x):
' Find the name of the variable by stripping off the scopes\n\n Notes\n -----\n A typical name will be scope1/scope2/.../name/kernel:0.\n This function serves to split off the scopes and return kernel\n '
split_colon = x.name.split(':')[0]
slash_strs = split_colon.split('/')
last_one = slash_strs[(- 1)]
return last_one<|docstring|>Find the name of the variable by stripping off the scopes
Notes
-----
A typical name will be scope1/scope2/.../name/kernel:0.
This function serves to split off the scopes and return kernel<|endoftext|>
|
c34c5bd4aa383d5e5d5fc6b09df4758339f5b0d004a6844de49e5eb761fe2c63
|
def get_static_shape_dyn_batch(x):
'Returns a tensor representing the static shape of x but keeping the batch\n unkown'
batch = tf.shape(x)[0]
static = x.get_shape()
return tf.concat([[batch], static[1:]], axis=0)
|
Returns a tensor representing the static shape of x but keeping the batch
unkown
|
tf_ops/general.py
|
get_static_shape_dyn_batch
|
fbcotter/tf_ops
| 0 |
python
|
def get_static_shape_dyn_batch(x):
'Returns a tensor representing the static shape of x but keeping the batch\n unkown'
batch = tf.shape(x)[0]
static = x.get_shape()
return tf.concat([[batch], static[1:]], axis=0)
|
def get_static_shape_dyn_batch(x):
'Returns a tensor representing the static shape of x but keeping the batch\n unkown'
batch = tf.shape(x)[0]
static = x.get_shape()
return tf.concat([[batch], static[1:]], axis=0)<|docstring|>Returns a tensor representing the static shape of x but keeping the batch
unkown<|endoftext|>
|
3d0a16b63247a21f6c1914203a23b6b7f69405195d454c13816ecf22a92f22df
|
def get_xavier_stddev(shape, uniform=False, factor=1.0, mode='FAN_AVG'):
"Get the correct stddev for a set of weights\n\n When initializing a deep network, it is in principle advantageous to keep\n the scale of the input variance constant, so it does not explode or diminish\n by reaching the final layer. This initializer use the following formula:\n\n .. code:: python\n\n if mode='FAN_IN': # Count only number of input connections.\n n = fan_in\n elif mode='FAN_OUT': # Count only number of output connections.\n n = fan_out\n elif mode='FAN_AVG': # Average number of inputs and output connections.\n n = (fan_in + fan_out)/2.0\n truncated_normal(shape, 0.0, stddev=sqrt(factor/n))\n\n * To get `Delving Deep into Rectifiers`__, use::\n\n factor=2.0\n mode='FAN_IN'\n uniform=False\n\n __ http://arxiv.org/pdf/1502.01852v1.pdf\n\n * To get `Convolutional Architecture for Fast Feature Embedding`__ , use::\n\n factor=1.0\n mode='FAN_IN'\n uniform=True\n\n __ http://arxiv.org/abs/1408.5093\n\n * To get `Understanding the difficulty of training deep feedforward neural\n networks`__ use::\n\n factor=1.0\n mode='FAN_AVG'\n uniform=True\n\n __ http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf\n\n * To get `xavier_initializer` use either::\n\n factor=1.0\n mode='FAN_AVG'\n uniform=True\n\n or::\n\n factor=1.0\n mode='FAN_AVG'\n uniform=False\n\n Parameters\n ----------\n factor: float\n A multiplicative factor.\n mode : str\n 'FAN_IN', 'FAN_OUT', 'FAN_AVG'.\n uniform : bool\n Whether to use uniform or normal distributed random initialization.\n seed : int\n Used to create random seeds. See `tf.set_random_seed`__\n for behaviour.\n\n __ https://www.tensorflow.org/api_docs/python/tf/set_random_seed\n\n dtype : tf.dtype\n The data type. Only floating point types are supported.\n\n Returns\n -------\n out : float\n The stddev/limit to use that generates tensors with unit variance.\n\n Raises\n ------\n ValueError : if `dtype` is not a floating point type.\n TypeError : if `mode` is not in ['FAN_IN', 'FAN_OUT', 'FAN_AVG'].\n "
if shape:
fan_in = (float(shape[(- 2)]) if (len(shape) > 1) else float(shape[(- 1)]))
fan_out = float(shape[(- 1)])
else:
fan_in = 1.0
fan_out = 1.0
for dim in shape[:(- 2)]:
fan_in *= float(dim)
fan_out *= float(dim)
if (mode == 'FAN_IN'):
n = fan_in
elif (mode == 'FAN_OUT'):
n = fan_out
elif (mode == 'FAN_AVG'):
n = ((fan_in + fan_out) / 2.0)
if uniform:
limit = math.sqrt(((3.0 * factor) / n))
return limit
else:
trunc_stddev = math.sqrt(((1.3 * factor) / n))
return trunc_stddev
|
Get the correct stddev for a set of weights
When initializing a deep network, it is in principle advantageous to keep
the scale of the input variance constant, so it does not explode or diminish
by reaching the final layer. This initializer use the following formula:
.. code:: python
if mode='FAN_IN': # Count only number of input connections.
n = fan_in
elif mode='FAN_OUT': # Count only number of output connections.
n = fan_out
elif mode='FAN_AVG': # Average number of inputs and output connections.
n = (fan_in + fan_out)/2.0
truncated_normal(shape, 0.0, stddev=sqrt(factor/n))
* To get `Delving Deep into Rectifiers`__, use::
factor=2.0
mode='FAN_IN'
uniform=False
__ http://arxiv.org/pdf/1502.01852v1.pdf
* To get `Convolutional Architecture for Fast Feature Embedding`__ , use::
factor=1.0
mode='FAN_IN'
uniform=True
__ http://arxiv.org/abs/1408.5093
* To get `Understanding the difficulty of training deep feedforward neural
networks`__ use::
factor=1.0
mode='FAN_AVG'
uniform=True
__ http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf
* To get `xavier_initializer` use either::
factor=1.0
mode='FAN_AVG'
uniform=True
or::
factor=1.0
mode='FAN_AVG'
uniform=False
Parameters
----------
factor: float
A multiplicative factor.
mode : str
'FAN_IN', 'FAN_OUT', 'FAN_AVG'.
uniform : bool
Whether to use uniform or normal distributed random initialization.
seed : int
Used to create random seeds. See `tf.set_random_seed`__
for behaviour.
__ https://www.tensorflow.org/api_docs/python/tf/set_random_seed
dtype : tf.dtype
The data type. Only floating point types are supported.
Returns
-------
out : float
The stddev/limit to use that generates tensors with unit variance.
Raises
------
ValueError : if `dtype` is not a floating point type.
TypeError : if `mode` is not in ['FAN_IN', 'FAN_OUT', 'FAN_AVG'].
|
tf_ops/general.py
|
get_xavier_stddev
|
fbcotter/tf_ops
| 0 |
python
|
def get_xavier_stddev(shape, uniform=False, factor=1.0, mode='FAN_AVG'):
"Get the correct stddev for a set of weights\n\n When initializing a deep network, it is in principle advantageous to keep\n the scale of the input variance constant, so it does not explode or diminish\n by reaching the final layer. This initializer use the following formula:\n\n .. code:: python\n\n if mode='FAN_IN': # Count only number of input connections.\n n = fan_in\n elif mode='FAN_OUT': # Count only number of output connections.\n n = fan_out\n elif mode='FAN_AVG': # Average number of inputs and output connections.\n n = (fan_in + fan_out)/2.0\n truncated_normal(shape, 0.0, stddev=sqrt(factor/n))\n\n * To get `Delving Deep into Rectifiers`__, use::\n\n factor=2.0\n mode='FAN_IN'\n uniform=False\n\n __ http://arxiv.org/pdf/1502.01852v1.pdf\n\n * To get `Convolutional Architecture for Fast Feature Embedding`__ , use::\n\n factor=1.0\n mode='FAN_IN'\n uniform=True\n\n __ http://arxiv.org/abs/1408.5093\n\n * To get `Understanding the difficulty of training deep feedforward neural\n networks`__ use::\n\n factor=1.0\n mode='FAN_AVG'\n uniform=True\n\n __ http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf\n\n * To get `xavier_initializer` use either::\n\n factor=1.0\n mode='FAN_AVG'\n uniform=True\n\n or::\n\n factor=1.0\n mode='FAN_AVG'\n uniform=False\n\n Parameters\n ----------\n factor: float\n A multiplicative factor.\n mode : str\n 'FAN_IN', 'FAN_OUT', 'FAN_AVG'.\n uniform : bool\n Whether to use uniform or normal distributed random initialization.\n seed : int\n Used to create random seeds. See `tf.set_random_seed`__\n for behaviour.\n\n __ https://www.tensorflow.org/api_docs/python/tf/set_random_seed\n\n dtype : tf.dtype\n The data type. Only floating point types are supported.\n\n Returns\n -------\n out : float\n The stddev/limit to use that generates tensors with unit variance.\n\n Raises\n ------\n ValueError : if `dtype` is not a floating point type.\n TypeError : if `mode` is not in ['FAN_IN', 'FAN_OUT', 'FAN_AVG'].\n "
if shape:
fan_in = (float(shape[(- 2)]) if (len(shape) > 1) else float(shape[(- 1)]))
fan_out = float(shape[(- 1)])
else:
fan_in = 1.0
fan_out = 1.0
for dim in shape[:(- 2)]:
fan_in *= float(dim)
fan_out *= float(dim)
if (mode == 'FAN_IN'):
n = fan_in
elif (mode == 'FAN_OUT'):
n = fan_out
elif (mode == 'FAN_AVG'):
n = ((fan_in + fan_out) / 2.0)
if uniform:
limit = math.sqrt(((3.0 * factor) / n))
return limit
else:
trunc_stddev = math.sqrt(((1.3 * factor) / n))
return trunc_stddev
|
def get_xavier_stddev(shape, uniform=False, factor=1.0, mode='FAN_AVG'):
"Get the correct stddev for a set of weights\n\n When initializing a deep network, it is in principle advantageous to keep\n the scale of the input variance constant, so it does not explode or diminish\n by reaching the final layer. This initializer use the following formula:\n\n .. code:: python\n\n if mode='FAN_IN': # Count only number of input connections.\n n = fan_in\n elif mode='FAN_OUT': # Count only number of output connections.\n n = fan_out\n elif mode='FAN_AVG': # Average number of inputs and output connections.\n n = (fan_in + fan_out)/2.0\n truncated_normal(shape, 0.0, stddev=sqrt(factor/n))\n\n * To get `Delving Deep into Rectifiers`__, use::\n\n factor=2.0\n mode='FAN_IN'\n uniform=False\n\n __ http://arxiv.org/pdf/1502.01852v1.pdf\n\n * To get `Convolutional Architecture for Fast Feature Embedding`__ , use::\n\n factor=1.0\n mode='FAN_IN'\n uniform=True\n\n __ http://arxiv.org/abs/1408.5093\n\n * To get `Understanding the difficulty of training deep feedforward neural\n networks`__ use::\n\n factor=1.0\n mode='FAN_AVG'\n uniform=True\n\n __ http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf\n\n * To get `xavier_initializer` use either::\n\n factor=1.0\n mode='FAN_AVG'\n uniform=True\n\n or::\n\n factor=1.0\n mode='FAN_AVG'\n uniform=False\n\n Parameters\n ----------\n factor: float\n A multiplicative factor.\n mode : str\n 'FAN_IN', 'FAN_OUT', 'FAN_AVG'.\n uniform : bool\n Whether to use uniform or normal distributed random initialization.\n seed : int\n Used to create random seeds. See `tf.set_random_seed`__\n for behaviour.\n\n __ https://www.tensorflow.org/api_docs/python/tf/set_random_seed\n\n dtype : tf.dtype\n The data type. Only floating point types are supported.\n\n Returns\n -------\n out : float\n The stddev/limit to use that generates tensors with unit variance.\n\n Raises\n ------\n ValueError : if `dtype` is not a floating point type.\n TypeError : if `mode` is not in ['FAN_IN', 'FAN_OUT', 'FAN_AVG'].\n "
if shape:
fan_in = (float(shape[(- 2)]) if (len(shape) > 1) else float(shape[(- 1)]))
fan_out = float(shape[(- 1)])
else:
fan_in = 1.0
fan_out = 1.0
for dim in shape[:(- 2)]:
fan_in *= float(dim)
fan_out *= float(dim)
if (mode == 'FAN_IN'):
n = fan_in
elif (mode == 'FAN_OUT'):
n = fan_out
elif (mode == 'FAN_AVG'):
n = ((fan_in + fan_out) / 2.0)
if uniform:
limit = math.sqrt(((3.0 * factor) / n))
return limit
else:
trunc_stddev = math.sqrt(((1.3 * factor) / n))
return trunc_stddev<|docstring|>Get the correct stddev for a set of weights
When initializing a deep network, it is in principle advantageous to keep
the scale of the input variance constant, so it does not explode or diminish
by reaching the final layer. This initializer use the following formula:
.. code:: python
if mode='FAN_IN': # Count only number of input connections.
n = fan_in
elif mode='FAN_OUT': # Count only number of output connections.
n = fan_out
elif mode='FAN_AVG': # Average number of inputs and output connections.
n = (fan_in + fan_out)/2.0
truncated_normal(shape, 0.0, stddev=sqrt(factor/n))
* To get `Delving Deep into Rectifiers`__, use::
factor=2.0
mode='FAN_IN'
uniform=False
__ http://arxiv.org/pdf/1502.01852v1.pdf
* To get `Convolutional Architecture for Fast Feature Embedding`__ , use::
factor=1.0
mode='FAN_IN'
uniform=True
__ http://arxiv.org/abs/1408.5093
* To get `Understanding the difficulty of training deep feedforward neural
networks`__ use::
factor=1.0
mode='FAN_AVG'
uniform=True
__ http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf
* To get `xavier_initializer` use either::
factor=1.0
mode='FAN_AVG'
uniform=True
or::
factor=1.0
mode='FAN_AVG'
uniform=False
Parameters
----------
factor: float
A multiplicative factor.
mode : str
'FAN_IN', 'FAN_OUT', 'FAN_AVG'.
uniform : bool
Whether to use uniform or normal distributed random initialization.
seed : int
Used to create random seeds. See `tf.set_random_seed`__
for behaviour.
__ https://www.tensorflow.org/api_docs/python/tf/set_random_seed
dtype : tf.dtype
The data type. Only floating point types are supported.
Returns
-------
out : float
The stddev/limit to use that generates tensors with unit variance.
Raises
------
ValueError : if `dtype` is not a floating point type.
TypeError : if `mode` is not in ['FAN_IN', 'FAN_OUT', 'FAN_AVG'].<|endoftext|>
|
f09f2193a7cbae820ab7574ad1e81e136e966eaac4506d432745ca6cc5a7be6d
|
def real_reg(w, wd=0.01, norm=2):
' Apply regularization on real weights\n\n norm can be any positive float. Of course the most commonly used values\n would be 2 and 1 (for L2 and L1 regularization), but you can experiment by\n making it some value in between. A value of p returns:\n\n .. math::\n\n wd \\times \\sum_{i} ||w_{i}||_{p}^{p}\n\n Parameters\n ----------\n w : :py:class:`tf.Tensor`\n The weights to regularize\n wd : positive float, optional (default=0.01)\n Regularization parameter\n norm : positive float, optional (default=2)\n The norm to use for regularization. E.g. set norm=1 for the L1 norm.\n\n Returns\n -------\n reg_loss : :py:class:`tf.Tensor`\n The loss. This method does not add anything to the REGULARIZATION_LOSSES\n collection. The calling function needs to do that.\n\n Raises\n ------\n ValueError : If norm is less than 0\n '
if ((wd is None) or (wd == 0) or (norm is None)):
return
if (norm <= 0):
raise ValueError('Can only take positive norms, not {}'.format(norm))
if (norm == 2):
reg_loss = tf.nn.l2_loss(w)
elif (norm == 1):
mag = tf.abs(w)
reg_loss = tf.reduce_sum(mag)
else:
mag = tf.abs(w)
reg_loss = ((1 / norm) * tf.reduce_sum((mag ** norm)))
reg_loss = tf.multiply(reg_loss, wd, name='weight_loss')
return reg_loss
|
Apply regularization on real weights
norm can be any positive float. Of course the most commonly used values
would be 2 and 1 (for L2 and L1 regularization), but you can experiment by
making it some value in between. A value of p returns:
.. math::
wd \times \sum_{i} ||w_{i}||_{p}^{p}
Parameters
----------
w : :py:class:`tf.Tensor`
The weights to regularize
wd : positive float, optional (default=0.01)
Regularization parameter
norm : positive float, optional (default=2)
The norm to use for regularization. E.g. set norm=1 for the L1 norm.
Returns
-------
reg_loss : :py:class:`tf.Tensor`
The loss. This method does not add anything to the REGULARIZATION_LOSSES
collection. The calling function needs to do that.
Raises
------
ValueError : If norm is less than 0
|
tf_ops/general.py
|
real_reg
|
fbcotter/tf_ops
| 0 |
python
|
def real_reg(w, wd=0.01, norm=2):
' Apply regularization on real weights\n\n norm can be any positive float. Of course the most commonly used values\n would be 2 and 1 (for L2 and L1 regularization), but you can experiment by\n making it some value in between. A value of p returns:\n\n .. math::\n\n wd \\times \\sum_{i} ||w_{i}||_{p}^{p}\n\n Parameters\n ----------\n w : :py:class:`tf.Tensor`\n The weights to regularize\n wd : positive float, optional (default=0.01)\n Regularization parameter\n norm : positive float, optional (default=2)\n The norm to use for regularization. E.g. set norm=1 for the L1 norm.\n\n Returns\n -------\n reg_loss : :py:class:`tf.Tensor`\n The loss. This method does not add anything to the REGULARIZATION_LOSSES\n collection. The calling function needs to do that.\n\n Raises\n ------\n ValueError : If norm is less than 0\n '
if ((wd is None) or (wd == 0) or (norm is None)):
return
if (norm <= 0):
raise ValueError('Can only take positive norms, not {}'.format(norm))
if (norm == 2):
reg_loss = tf.nn.l2_loss(w)
elif (norm == 1):
mag = tf.abs(w)
reg_loss = tf.reduce_sum(mag)
else:
mag = tf.abs(w)
reg_loss = ((1 / norm) * tf.reduce_sum((mag ** norm)))
reg_loss = tf.multiply(reg_loss, wd, name='weight_loss')
return reg_loss
|
def real_reg(w, wd=0.01, norm=2):
' Apply regularization on real weights\n\n norm can be any positive float. Of course the most commonly used values\n would be 2 and 1 (for L2 and L1 regularization), but you can experiment by\n making it some value in between. A value of p returns:\n\n .. math::\n\n wd \\times \\sum_{i} ||w_{i}||_{p}^{p}\n\n Parameters\n ----------\n w : :py:class:`tf.Tensor`\n The weights to regularize\n wd : positive float, optional (default=0.01)\n Regularization parameter\n norm : positive float, optional (default=2)\n The norm to use for regularization. E.g. set norm=1 for the L1 norm.\n\n Returns\n -------\n reg_loss : :py:class:`tf.Tensor`\n The loss. This method does not add anything to the REGULARIZATION_LOSSES\n collection. The calling function needs to do that.\n\n Raises\n ------\n ValueError : If norm is less than 0\n '
if ((wd is None) or (wd == 0) or (norm is None)):
return
if (norm <= 0):
raise ValueError('Can only take positive norms, not {}'.format(norm))
if (norm == 2):
reg_loss = tf.nn.l2_loss(w)
elif (norm == 1):
mag = tf.abs(w)
reg_loss = tf.reduce_sum(mag)
else:
mag = tf.abs(w)
reg_loss = ((1 / norm) * tf.reduce_sum((mag ** norm)))
reg_loss = tf.multiply(reg_loss, wd, name='weight_loss')
return reg_loss<|docstring|>Apply regularization on real weights
norm can be any positive float. Of course the most commonly used values
would be 2 and 1 (for L2 and L1 regularization), but you can experiment by
making it some value in between. A value of p returns:
.. math::
wd \times \sum_{i} ||w_{i}||_{p}^{p}
Parameters
----------
w : :py:class:`tf.Tensor`
The weights to regularize
wd : positive float, optional (default=0.01)
Regularization parameter
norm : positive float, optional (default=2)
The norm to use for regularization. E.g. set norm=1 for the L1 norm.
Returns
-------
reg_loss : :py:class:`tf.Tensor`
The loss. This method does not add anything to the REGULARIZATION_LOSSES
collection. The calling function needs to do that.
Raises
------
ValueError : If norm is less than 0<|endoftext|>
|
a8f0e67d7e7a584ed68055acb84b608cfe2dc2a9166701803b9d4bd7743e4f09
|
def complex_reg(w, wd=0.01, norm=1):
' Apply regularization on complex weights.\n\n norm can be any positive float. Of course the most commonly used values\n would be 2 and 1 (for L2 and L1 regularization), but you can experiment by\n making it some value in between. A value of p returns:\n\n .. math::\n\n wd \\times \\sum_{i} ||w_{i}||_{p}^{p}\n\n\n Parameters\n ----------\n w : :py:class:`tf.Tensor` (dtype=complex)\n The weights to regularize\n wd : positive float, optional (default=0.01)\n Regularization parameter\n norm : positive float, optional (default=1)\n The norm to use for regularization. E.g. set norm=1 for the L1 norm.\n\n Returns\n -------\n reg_loss : :py:class:`tf.Tensor`\n The loss. This method does not add anything to the REGULARIZATION_LOSSES\n collection. The calling function needs to do that.\n\n Raises\n ------\n ValueError : If norm is less than 0\n\n Notes\n -----\n Can call this function with real weights too, making it perhaps a better\n de-facto function to call, as it able to handle both cases.\n '
if ((wd is None) or (wd == 0) or (norm is None)):
return
if (norm <= 0):
raise ValueError('Can only take positive norms, not {}'.format(norm))
if w.dtype.is_floating:
return real_reg(w, wd, norm)
if (norm == 2):
reg_loss = (tf.nn.l2_loss(tf.real(w)) + tf.nn.l2_loss(tf.imag(w)))
elif (norm == 1):
mag = tf.abs(w)
reg_loss = tf.reduce_sum(mag)
else:
mag = tf.abs(w)
reg_loss = ((1 / norm) * tf.reduce_sum((mag ** norm)))
reg_loss = tf.multiply(reg_loss, wd, name='weight_loss')
return reg_loss
|
Apply regularization on complex weights.
norm can be any positive float. Of course the most commonly used values
would be 2 and 1 (for L2 and L1 regularization), but you can experiment by
making it some value in between. A value of p returns:
.. math::
wd \times \sum_{i} ||w_{i}||_{p}^{p}
Parameters
----------
w : :py:class:`tf.Tensor` (dtype=complex)
The weights to regularize
wd : positive float, optional (default=0.01)
Regularization parameter
norm : positive float, optional (default=1)
The norm to use for regularization. E.g. set norm=1 for the L1 norm.
Returns
-------
reg_loss : :py:class:`tf.Tensor`
The loss. This method does not add anything to the REGULARIZATION_LOSSES
collection. The calling function needs to do that.
Raises
------
ValueError : If norm is less than 0
Notes
-----
Can call this function with real weights too, making it perhaps a better
de-facto function to call, as it able to handle both cases.
|
tf_ops/general.py
|
complex_reg
|
fbcotter/tf_ops
| 0 |
python
|
def complex_reg(w, wd=0.01, norm=1):
' Apply regularization on complex weights.\n\n norm can be any positive float. Of course the most commonly used values\n would be 2 and 1 (for L2 and L1 regularization), but you can experiment by\n making it some value in between. A value of p returns:\n\n .. math::\n\n wd \\times \\sum_{i} ||w_{i}||_{p}^{p}\n\n\n Parameters\n ----------\n w : :py:class:`tf.Tensor` (dtype=complex)\n The weights to regularize\n wd : positive float, optional (default=0.01)\n Regularization parameter\n norm : positive float, optional (default=1)\n The norm to use for regularization. E.g. set norm=1 for the L1 norm.\n\n Returns\n -------\n reg_loss : :py:class:`tf.Tensor`\n The loss. This method does not add anything to the REGULARIZATION_LOSSES\n collection. The calling function needs to do that.\n\n Raises\n ------\n ValueError : If norm is less than 0\n\n Notes\n -----\n Can call this function with real weights too, making it perhaps a better\n de-facto function to call, as it able to handle both cases.\n '
if ((wd is None) or (wd == 0) or (norm is None)):
return
if (norm <= 0):
raise ValueError('Can only take positive norms, not {}'.format(norm))
if w.dtype.is_floating:
return real_reg(w, wd, norm)
if (norm == 2):
reg_loss = (tf.nn.l2_loss(tf.real(w)) + tf.nn.l2_loss(tf.imag(w)))
elif (norm == 1):
mag = tf.abs(w)
reg_loss = tf.reduce_sum(mag)
else:
mag = tf.abs(w)
reg_loss = ((1 / norm) * tf.reduce_sum((mag ** norm)))
reg_loss = tf.multiply(reg_loss, wd, name='weight_loss')
return reg_loss
|
def complex_reg(w, wd=0.01, norm=1):
' Apply regularization on complex weights.\n\n norm can be any positive float. Of course the most commonly used values\n would be 2 and 1 (for L2 and L1 regularization), but you can experiment by\n making it some value in between. A value of p returns:\n\n .. math::\n\n wd \\times \\sum_{i} ||w_{i}||_{p}^{p}\n\n\n Parameters\n ----------\n w : :py:class:`tf.Tensor` (dtype=complex)\n The weights to regularize\n wd : positive float, optional (default=0.01)\n Regularization parameter\n norm : positive float, optional (default=1)\n The norm to use for regularization. E.g. set norm=1 for the L1 norm.\n\n Returns\n -------\n reg_loss : :py:class:`tf.Tensor`\n The loss. This method does not add anything to the REGULARIZATION_LOSSES\n collection. The calling function needs to do that.\n\n Raises\n ------\n ValueError : If norm is less than 0\n\n Notes\n -----\n Can call this function with real weights too, making it perhaps a better\n de-facto function to call, as it able to handle both cases.\n '
if ((wd is None) or (wd == 0) or (norm is None)):
return
if (norm <= 0):
raise ValueError('Can only take positive norms, not {}'.format(norm))
if w.dtype.is_floating:
return real_reg(w, wd, norm)
if (norm == 2):
reg_loss = (tf.nn.l2_loss(tf.real(w)) + tf.nn.l2_loss(tf.imag(w)))
elif (norm == 1):
mag = tf.abs(w)
reg_loss = tf.reduce_sum(mag)
else:
mag = tf.abs(w)
reg_loss = ((1 / norm) * tf.reduce_sum((mag ** norm)))
reg_loss = tf.multiply(reg_loss, wd, name='weight_loss')
return reg_loss<|docstring|>Apply regularization on complex weights.
norm can be any positive float. Of course the most commonly used values
would be 2 and 1 (for L2 and L1 regularization), but you can experiment by
making it some value in between. A value of p returns:
.. math::
wd \times \sum_{i} ||w_{i}||_{p}^{p}
Parameters
----------
w : :py:class:`tf.Tensor` (dtype=complex)
The weights to regularize
wd : positive float, optional (default=0.01)
Regularization parameter
norm : positive float, optional (default=1)
The norm to use for regularization. E.g. set norm=1 for the L1 norm.
Returns
-------
reg_loss : :py:class:`tf.Tensor`
The loss. This method does not add anything to the REGULARIZATION_LOSSES
collection. The calling function needs to do that.
Raises
------
ValueError : If norm is less than 0
Notes
-----
Can call this function with real weights too, making it perhaps a better
de-facto function to call, as it able to handle both cases.<|endoftext|>
|
e5aa3c837eb6559d5d55b198cc157e8f992bbb0eb40196cefe8fa6fc944dd007
|
def initialise(cosmo, data, command_line):
'\n Main call to prepare the information for the NeuralNest run.\n '
varying_param_names = data.get_mcmc_parameters(['varying'])
derived_param_names = data.get_mcmc_parameters(['derived'])
if (getattr(command_line, (NN_prefix + 'sampler'), '').lower() == 'nested'):
(is_flat, is_bound) = sampler.check_flat_bound_priors(data.mcmc_parameters, varying_param_names)
if (not is_flat):
raise io_mp.ConfigurationError(('Nested Sampling with NeuralNest is only possible with flat ' + 'priors. Sorry!'))
if (not is_bound):
raise io_mp.ConfigurationError((('Nested Sampling with NeuralNest is only possible for bound ' + 'parameters. Set reasonable bounds for them in the ".param"') + 'file.'))
NN_folder = os.path.join(command_line.folder, NN_subfolder)
if (not os.path.exists(NN_folder)):
os.makedirs(NN_folder)
run_num = (sum((os.path.isdir(os.path.join(NN_folder, i)) for i in os.listdir(NN_folder))) + 1)
data.NN_arguments['x_dim'] = len(varying_param_names)
data.NN_arguments['num_derived'] = len(derived_param_names)
data.NN_arguments['verbose'] = True
data.NN_arguments['log_dir'] = os.path.join(NN_folder, str(run_num))
data.NN_arguments['use_gpu'] = False
data.NN_arguments['flow'] = 'nvp'
data.NN_arguments['load_model'] = ''
data.NN_arguments['batch_size'] = 100
if getattr(command_line, (NN_prefix + 'fastslow')):
data.NN_arguments['num_slow'] = data.block_parameters[0]
else:
data.NN_arguments['num_slow'] = 0
for arg in NN_user_arguments:
value = getattr(command_line, (NN_prefix + arg))
data.NN_arguments[arg] = value
if (arg == 'switch'):
if (value >= 0):
data.NN_arguments['switch'] = value
elif (data.NN_arguments['num_slow'] > 0):
data.NN_arguments['switch'] = (1.0 / (5 * data.NN_arguments['num_slow']))
if (getattr(command_line, (NN_prefix + 'sampler'), '').lower() == 'mcmc'):
data.NN_arguments['mcmc_steps'] = getattr(command_line, 'N')
data.NN_param_names = varying_param_names
base_name = os.path.join(NN_folder, 'base')
if (run_num == 1):
with open((base_name + name_arguments), 'w') as afile:
for arg in data.NN_arguments:
afile.write(' = '.join([str(arg), str(data.NN_arguments[arg])]))
afile.write('\n')
with open((base_name + name_paramnames), 'w') as pfile:
pfile.write('\n'.join((data.NN_param_names + derived_param_names)))
|
Main call to prepare the information for the NeuralNest run.
|
montepython/NeuralNest.py
|
initialise
|
LBJ-Wade/montepython_public_NN
| 2 |
python
|
def initialise(cosmo, data, command_line):
'\n \n '
varying_param_names = data.get_mcmc_parameters(['varying'])
derived_param_names = data.get_mcmc_parameters(['derived'])
if (getattr(command_line, (NN_prefix + 'sampler'), ).lower() == 'nested'):
(is_flat, is_bound) = sampler.check_flat_bound_priors(data.mcmc_parameters, varying_param_names)
if (not is_flat):
raise io_mp.ConfigurationError(('Nested Sampling with NeuralNest is only possible with flat ' + 'priors. Sorry!'))
if (not is_bound):
raise io_mp.ConfigurationError((('Nested Sampling with NeuralNest is only possible for bound ' + 'parameters. Set reasonable bounds for them in the ".param"') + 'file.'))
NN_folder = os.path.join(command_line.folder, NN_subfolder)
if (not os.path.exists(NN_folder)):
os.makedirs(NN_folder)
run_num = (sum((os.path.isdir(os.path.join(NN_folder, i)) for i in os.listdir(NN_folder))) + 1)
data.NN_arguments['x_dim'] = len(varying_param_names)
data.NN_arguments['num_derived'] = len(derived_param_names)
data.NN_arguments['verbose'] = True
data.NN_arguments['log_dir'] = os.path.join(NN_folder, str(run_num))
data.NN_arguments['use_gpu'] = False
data.NN_arguments['flow'] = 'nvp'
data.NN_arguments['load_model'] =
data.NN_arguments['batch_size'] = 100
if getattr(command_line, (NN_prefix + 'fastslow')):
data.NN_arguments['num_slow'] = data.block_parameters[0]
else:
data.NN_arguments['num_slow'] = 0
for arg in NN_user_arguments:
value = getattr(command_line, (NN_prefix + arg))
data.NN_arguments[arg] = value
if (arg == 'switch'):
if (value >= 0):
data.NN_arguments['switch'] = value
elif (data.NN_arguments['num_slow'] > 0):
data.NN_arguments['switch'] = (1.0 / (5 * data.NN_arguments['num_slow']))
if (getattr(command_line, (NN_prefix + 'sampler'), ).lower() == 'mcmc'):
data.NN_arguments['mcmc_steps'] = getattr(command_line, 'N')
data.NN_param_names = varying_param_names
base_name = os.path.join(NN_folder, 'base')
if (run_num == 1):
with open((base_name + name_arguments), 'w') as afile:
for arg in data.NN_arguments:
afile.write(' = '.join([str(arg), str(data.NN_arguments[arg])]))
afile.write('\n')
with open((base_name + name_paramnames), 'w') as pfile:
pfile.write('\n'.join((data.NN_param_names + derived_param_names)))
|
def initialise(cosmo, data, command_line):
'\n \n '
varying_param_names = data.get_mcmc_parameters(['varying'])
derived_param_names = data.get_mcmc_parameters(['derived'])
if (getattr(command_line, (NN_prefix + 'sampler'), ).lower() == 'nested'):
(is_flat, is_bound) = sampler.check_flat_bound_priors(data.mcmc_parameters, varying_param_names)
if (not is_flat):
raise io_mp.ConfigurationError(('Nested Sampling with NeuralNest is only possible with flat ' + 'priors. Sorry!'))
if (not is_bound):
raise io_mp.ConfigurationError((('Nested Sampling with NeuralNest is only possible for bound ' + 'parameters. Set reasonable bounds for them in the ".param"') + 'file.'))
NN_folder = os.path.join(command_line.folder, NN_subfolder)
if (not os.path.exists(NN_folder)):
os.makedirs(NN_folder)
run_num = (sum((os.path.isdir(os.path.join(NN_folder, i)) for i in os.listdir(NN_folder))) + 1)
data.NN_arguments['x_dim'] = len(varying_param_names)
data.NN_arguments['num_derived'] = len(derived_param_names)
data.NN_arguments['verbose'] = True
data.NN_arguments['log_dir'] = os.path.join(NN_folder, str(run_num))
data.NN_arguments['use_gpu'] = False
data.NN_arguments['flow'] = 'nvp'
data.NN_arguments['load_model'] =
data.NN_arguments['batch_size'] = 100
if getattr(command_line, (NN_prefix + 'fastslow')):
data.NN_arguments['num_slow'] = data.block_parameters[0]
else:
data.NN_arguments['num_slow'] = 0
for arg in NN_user_arguments:
value = getattr(command_line, (NN_prefix + arg))
data.NN_arguments[arg] = value
if (arg == 'switch'):
if (value >= 0):
data.NN_arguments['switch'] = value
elif (data.NN_arguments['num_slow'] > 0):
data.NN_arguments['switch'] = (1.0 / (5 * data.NN_arguments['num_slow']))
if (getattr(command_line, (NN_prefix + 'sampler'), ).lower() == 'mcmc'):
data.NN_arguments['mcmc_steps'] = getattr(command_line, 'N')
data.NN_param_names = varying_param_names
base_name = os.path.join(NN_folder, 'base')
if (run_num == 1):
with open((base_name + name_arguments), 'w') as afile:
for arg in data.NN_arguments:
afile.write(' = '.join([str(arg), str(data.NN_arguments[arg])]))
afile.write('\n')
with open((base_name + name_paramnames), 'w') as pfile:
pfile.write('\n'.join((data.NN_param_names + derived_param_names)))<|docstring|>Main call to prepare the information for the NeuralNest run.<|endoftext|>
|
fc3bda68117645a768a7662835eb78e86c71e507ff2aa059a29f80d74931f36e
|
async def async_select_program(self, call) -> None:
' Service for selecting a program '
data = call.data
appliance = self.get_appliance_from_device_id(data['device_id'])
if appliance:
program_key = data['program_key']
options = data.get('options')
(await appliance.async_select_program(key=program_key, options=options))
|
Service for selecting a program
|
custom_components/home_connect_alt/services.py
|
async_select_program
|
code-echobase/home-connect-hass
| 0 |
python
|
async def async_select_program(self, call) -> None:
' '
data = call.data
appliance = self.get_appliance_from_device_id(data['device_id'])
if appliance:
program_key = data['program_key']
options = data.get('options')
(await appliance.async_select_program(key=program_key, options=options))
|
async def async_select_program(self, call) -> None:
' '
data = call.data
appliance = self.get_appliance_from_device_id(data['device_id'])
if appliance:
program_key = data['program_key']
options = data.get('options')
(await appliance.async_select_program(key=program_key, options=options))<|docstring|>Service for selecting a program<|endoftext|>
|
09dd5b6b35adbc044064d519c25d786c0edea92bc3b9cfb53eacedce7bebf5a6
|
async def async_start_program(self, call) -> None:
' Service for starting the currently selected program '
data = call.data
appliance = self.get_appliance_from_device_id(data['device_id'])
if appliance:
(await appliance.async_start_program())
|
Service for starting the currently selected program
|
custom_components/home_connect_alt/services.py
|
async_start_program
|
code-echobase/home-connect-hass
| 0 |
python
|
async def async_start_program(self, call) -> None:
' '
data = call.data
appliance = self.get_appliance_from_device_id(data['device_id'])
if appliance:
(await appliance.async_start_program())
|
async def async_start_program(self, call) -> None:
' '
data = call.data
appliance = self.get_appliance_from_device_id(data['device_id'])
if appliance:
(await appliance.async_start_program())<|docstring|>Service for starting the currently selected program<|endoftext|>
|
24a2f7abc9552d2251bd021d1713a0a6a6867d7399cf58f1e477c099596e5bfa
|
async def async_stop_program(self, call) -> None:
' Service for stopping the currently active program '
data = call.data
appliance = self.get_appliance_from_device_id(data['device_id'])
if appliance:
(await appliance.async_stop_active_program())
|
Service for stopping the currently active program
|
custom_components/home_connect_alt/services.py
|
async_stop_program
|
code-echobase/home-connect-hass
| 0 |
python
|
async def async_stop_program(self, call) -> None:
' '
data = call.data
appliance = self.get_appliance_from_device_id(data['device_id'])
if appliance:
(await appliance.async_stop_active_program())
|
async def async_stop_program(self, call) -> None:
' '
data = call.data
appliance = self.get_appliance_from_device_id(data['device_id'])
if appliance:
(await appliance.async_stop_active_program())<|docstring|>Service for stopping the currently active program<|endoftext|>
|
d9af549ff94fc7f249a16e80698f68817c448e74e4c6a608f6ab9336312e08ca
|
def get_appliance_from_device_id(self, device_id):
' Helper function to get an appliance from the Home Assistant device_id '
device = self.dr.devices[device_id]
haId = list(device.identifiers)[0][1]
for (key, appliance) in self.homeconnect.appliances.items():
if (key.lower().replace('-', '_') == haId):
return appliance
return None
|
Helper function to get an appliance from the Home Assistant device_id
|
custom_components/home_connect_alt/services.py
|
get_appliance_from_device_id
|
code-echobase/home-connect-hass
| 0 |
python
|
def get_appliance_from_device_id(self, device_id):
' '
device = self.dr.devices[device_id]
haId = list(device.identifiers)[0][1]
for (key, appliance) in self.homeconnect.appliances.items():
if (key.lower().replace('-', '_') == haId):
return appliance
return None
|
def get_appliance_from_device_id(self, device_id):
' '
device = self.dr.devices[device_id]
haId = list(device.identifiers)[0][1]
for (key, appliance) in self.homeconnect.appliances.items():
if (key.lower().replace('-', '_') == haId):
return appliance
return None<|docstring|>Helper function to get an appliance from the Home Assistant device_id<|endoftext|>
|
7539d215a85dd21936d94dbd5cede58af5ca5b50d73f9753413d43829b6f80bd
|
def app_info(self, **kwargs):
'重写此方法'
self.name = kwargs.get('name', 'desktop')
self.desc = kwargs.get('desc', 'ctpbee桌面端')
self.icon = kwargs.get('icon', ':/icon/icon/bee_temp_grey.png')
self.versions = kwargs.get('versions', {'1.0': 'https://github.com/ctpbee/ctpbee_desktop/archive/master.zip'})
self.install_version = kwargs.get('install_version', '1.0')
self.app_url = kwargs.get('app_url', 'https://github.com/ctpbee/ctpbee_desktop')
|
重写此方法
|
app/honey/applications/example.py
|
app_info
|
ctpbee/bee-box
| 2 |
python
|
def app_info(self, **kwargs):
self.name = kwargs.get('name', 'desktop')
self.desc = kwargs.get('desc', 'ctpbee桌面端')
self.icon = kwargs.get('icon', ':/icon/icon/bee_temp_grey.png')
self.versions = kwargs.get('versions', {'1.0': 'https://github.com/ctpbee/ctpbee_desktop/archive/master.zip'})
self.install_version = kwargs.get('install_version', '1.0')
self.app_url = kwargs.get('app_url', 'https://github.com/ctpbee/ctpbee_desktop')
|
def app_info(self, **kwargs):
self.name = kwargs.get('name', 'desktop')
self.desc = kwargs.get('desc', 'ctpbee桌面端')
self.icon = kwargs.get('icon', ':/icon/icon/bee_temp_grey.png')
self.versions = kwargs.get('versions', {'1.0': 'https://github.com/ctpbee/ctpbee_desktop/archive/master.zip'})
self.install_version = kwargs.get('install_version', '1.0')
self.app_url = kwargs.get('app_url', 'https://github.com/ctpbee/ctpbee_desktop')<|docstring|>重写此方法<|endoftext|>
|
e3960fcd78c21a117b73c9968ec94adc9b215b9552db1d786f20f6ba43fd1a74
|
def orthonormalise(self, n_lyap, delay):
'\n\t\tOrthonormalise separation functions (with Gram-Schmidt) and return their norms after orthogonalisation (but before normalisation).\n\t\t'
vectors = np.split(np.arange(self.n, dtype=int), (n_lyap + 1))[1:]
norms = []
for (i, vector) in enumerate(vectors):
for j in range(i):
sp = self.scalar_product(delay, vector, vectors[j])
self.subtract(vector, vectors[j], sp)
norm = self.norm(delay, vector)
if (norm > NORM_THRESHOLD):
self.scale(vector, (1.0 / norm))
norms.append(norm)
return np.array(norms)
|
Orthonormalise separation functions (with Gram-Schmidt) and return their norms after orthogonalisation (but before normalisation).
|
jitcdde/past.py
|
orthonormalise
|
neurophysik/jitcdde
| 49 |
python
|
def orthonormalise(self, n_lyap, delay):
'\n\t\t\n\t\t'
vectors = np.split(np.arange(self.n, dtype=int), (n_lyap + 1))[1:]
norms = []
for (i, vector) in enumerate(vectors):
for j in range(i):
sp = self.scalar_product(delay, vector, vectors[j])
self.subtract(vector, vectors[j], sp)
norm = self.norm(delay, vector)
if (norm > NORM_THRESHOLD):
self.scale(vector, (1.0 / norm))
norms.append(norm)
return np.array(norms)
|
def orthonormalise(self, n_lyap, delay):
'\n\t\t\n\t\t'
vectors = np.split(np.arange(self.n, dtype=int), (n_lyap + 1))[1:]
norms = []
for (i, vector) in enumerate(vectors):
for j in range(i):
sp = self.scalar_product(delay, vector, vectors[j])
self.subtract(vector, vectors[j], sp)
norm = self.norm(delay, vector)
if (norm > NORM_THRESHOLD):
self.scale(vector, (1.0 / norm))
norms.append(norm)
return np.array(norms)<|docstring|>Orthonormalise separation functions (with Gram-Schmidt) and return their norms after orthogonalisation (but before normalisation).<|endoftext|>
|
0f11de2211009e355dff01b3670705282405642abefed19d6506578aa047d4b7
|
def remove_projections(self, delay, vectors):
'\n\t\tRemove projections of separation function to vectors and return norm after normalisation.\n\t\t'
sep_func = np.arange(self.n_basic, (2 * self.n_basic), 1, dtype=int)
assert np.all((sep_func == np.split(np.arange(self.n, dtype=int), (2 + (2 * len(vectors))))[1]))
assert (self.n_basic == len(sep_func))
d = (len(vectors) * 2)
def get_dummy(index):
return np.arange(((index + 2) * self.n_basic), ((index + 3) * self.n_basic))
dummy_num = 0
len_dummies = 0
for anchor in self:
for vector in vectors:
dummy = get_dummy(dummy_num)
for other_anchor in self:
other_anchor.state[dummy] = np.zeros(self.n_basic)
other_anchor.diff[dummy] = np.zeros(self.n_basic)
anchor.state[dummy] = vector[0]
anchor.diff[dummy] = vector[1]
past_dummies = [get_dummy((((dummy_num - i) - 1) % d)) for i in range(len_dummies)]
for past_dummy in past_dummies:
sp = self.scalar_product(delay, dummy, past_dummy)
self.subtract(dummy, past_dummy, sp)
norm = self.norm(delay, dummy)
if (norm > NORM_THRESHOLD):
self.scale(dummy, (1.0 / norm))
sp = self.scalar_product(delay, sep_func, dummy)
self.subtract(sep_func, dummy, sp)
else:
self.scale(dummy, 0.0)
len_dummies += 1
dummy_num = ((dummy_num + 1) % d)
if (len_dummies > len(vectors)):
len_dummies -= len(vectors)
for anchor in self:
anchor.state[(2 * self.n_basic):] = 0.0
anchor.diff[(2 * self.n_basic):] = 0.0
norm = self.norm(delay, sep_func)
self.scale(sep_func, (1.0 / norm))
return norm
|
Remove projections of separation function to vectors and return norm after normalisation.
|
jitcdde/past.py
|
remove_projections
|
neurophysik/jitcdde
| 49 |
python
|
def remove_projections(self, delay, vectors):
'\n\t\t\n\t\t'
sep_func = np.arange(self.n_basic, (2 * self.n_basic), 1, dtype=int)
assert np.all((sep_func == np.split(np.arange(self.n, dtype=int), (2 + (2 * len(vectors))))[1]))
assert (self.n_basic == len(sep_func))
d = (len(vectors) * 2)
def get_dummy(index):
return np.arange(((index + 2) * self.n_basic), ((index + 3) * self.n_basic))
dummy_num = 0
len_dummies = 0
for anchor in self:
for vector in vectors:
dummy = get_dummy(dummy_num)
for other_anchor in self:
other_anchor.state[dummy] = np.zeros(self.n_basic)
other_anchor.diff[dummy] = np.zeros(self.n_basic)
anchor.state[dummy] = vector[0]
anchor.diff[dummy] = vector[1]
past_dummies = [get_dummy((((dummy_num - i) - 1) % d)) for i in range(len_dummies)]
for past_dummy in past_dummies:
sp = self.scalar_product(delay, dummy, past_dummy)
self.subtract(dummy, past_dummy, sp)
norm = self.norm(delay, dummy)
if (norm > NORM_THRESHOLD):
self.scale(dummy, (1.0 / norm))
sp = self.scalar_product(delay, sep_func, dummy)
self.subtract(sep_func, dummy, sp)
else:
self.scale(dummy, 0.0)
len_dummies += 1
dummy_num = ((dummy_num + 1) % d)
if (len_dummies > len(vectors)):
len_dummies -= len(vectors)
for anchor in self:
anchor.state[(2 * self.n_basic):] = 0.0
anchor.diff[(2 * self.n_basic):] = 0.0
norm = self.norm(delay, sep_func)
self.scale(sep_func, (1.0 / norm))
return norm
|
def remove_projections(self, delay, vectors):
'\n\t\t\n\t\t'
sep_func = np.arange(self.n_basic, (2 * self.n_basic), 1, dtype=int)
assert np.all((sep_func == np.split(np.arange(self.n, dtype=int), (2 + (2 * len(vectors))))[1]))
assert (self.n_basic == len(sep_func))
d = (len(vectors) * 2)
def get_dummy(index):
return np.arange(((index + 2) * self.n_basic), ((index + 3) * self.n_basic))
dummy_num = 0
len_dummies = 0
for anchor in self:
for vector in vectors:
dummy = get_dummy(dummy_num)
for other_anchor in self:
other_anchor.state[dummy] = np.zeros(self.n_basic)
other_anchor.diff[dummy] = np.zeros(self.n_basic)
anchor.state[dummy] = vector[0]
anchor.diff[dummy] = vector[1]
past_dummies = [get_dummy((((dummy_num - i) - 1) % d)) for i in range(len_dummies)]
for past_dummy in past_dummies:
sp = self.scalar_product(delay, dummy, past_dummy)
self.subtract(dummy, past_dummy, sp)
norm = self.norm(delay, dummy)
if (norm > NORM_THRESHOLD):
self.scale(dummy, (1.0 / norm))
sp = self.scalar_product(delay, sep_func, dummy)
self.subtract(sep_func, dummy, sp)
else:
self.scale(dummy, 0.0)
len_dummies += 1
dummy_num = ((dummy_num + 1) % d)
if (len_dummies > len(vectors)):
len_dummies -= len(vectors)
for anchor in self:
anchor.state[(2 * self.n_basic):] = 0.0
anchor.diff[(2 * self.n_basic):] = 0.0
norm = self.norm(delay, sep_func)
self.scale(sep_func, (1.0 / norm))
return norm<|docstring|>Remove projections of separation function to vectors and return norm after normalisation.<|endoftext|>
|
b5c2cd2ec3c08d2ee3be4106c0ed9193819714f9f8d7419b9e806f4319081589
|
def normalise_indices(self, delay):
'\n\t\tNormalise the separation function of the tangent indices and return the norm (before normalisation).\n\t\t'
norm = self.norm(delay, self.tangent_indices)
if (norm > NORM_THRESHOLD):
self.scale(self.tangent_indices, (1.0 / norm))
return norm
|
Normalise the separation function of the tangent indices and return the norm (before normalisation).
|
jitcdde/past.py
|
normalise_indices
|
neurophysik/jitcdde
| 49 |
python
|
def normalise_indices(self, delay):
'\n\t\t\n\t\t'
norm = self.norm(delay, self.tangent_indices)
if (norm > NORM_THRESHOLD):
self.scale(self.tangent_indices, (1.0 / norm))
return norm
|
def normalise_indices(self, delay):
'\n\t\t\n\t\t'
norm = self.norm(delay, self.tangent_indices)
if (norm > NORM_THRESHOLD):
self.scale(self.tangent_indices, (1.0 / norm))
return norm<|docstring|>Normalise the separation function of the tangent indices and return the norm (before normalisation).<|endoftext|>
|
38ed7f66c861906d2b3ac85a14ffeb42eddc3630c59bf23b73c4df0c6a9541e9
|
def test_obtain_read_lock_with_no_existing_locks(self):
' Test that a lock can be obtained when no locks exist '
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T1, x2)')
self.assertEquals(instruction.variable_identifier, 'x2')
variable = self.data_manager.variables['x2']
self.assertTrue(variable.readable)
self.assertFalse(('x2' in self.data_manager.locks))
value = self.data_manager.obtain_read_lock(transaction, instruction)
self.assertEquals(len(self.data_manager.locks), 1)
self.assertTrue(value)
|
Test that a lock can be obtained when no locks exist
|
tests/test_data_manager.py
|
test_obtain_read_lock_with_no_existing_locks
|
cfnyu/distributed_db
| 0 |
python
|
def test_obtain_read_lock_with_no_existing_locks(self):
' '
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T1, x2)')
self.assertEquals(instruction.variable_identifier, 'x2')
variable = self.data_manager.variables['x2']
self.assertTrue(variable.readable)
self.assertFalse(('x2' in self.data_manager.locks))
value = self.data_manager.obtain_read_lock(transaction, instruction)
self.assertEquals(len(self.data_manager.locks), 1)
self.assertTrue(value)
|
def test_obtain_read_lock_with_no_existing_locks(self):
' '
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T1, x2)')
self.assertEquals(instruction.variable_identifier, 'x2')
variable = self.data_manager.variables['x2']
self.assertTrue(variable.readable)
self.assertFalse(('x2' in self.data_manager.locks))
value = self.data_manager.obtain_read_lock(transaction, instruction)
self.assertEquals(len(self.data_manager.locks), 1)
self.assertTrue(value)<|docstring|>Test that a lock can be obtained when no locks exist<|endoftext|>
|
4d9853b808ad373c96ab8bf168b875956a6512681bed88a85aef0e75db72b0e5
|
def test_obtain_read_lock_with_existing_locks(self):
' Test that a lock can be obtained when other locks exist '
dummy_tran = Transaction('T3', TransactionType.READ_WRITE, 1)
dummy_var = Variable(1, 4)
dummy_var1 = Variable(1, 6)
self.data_manager.locks['x4'] = [Lock(LockType.READ, dummy_tran, dummy_var)]
self.data_manager.locks['x6'] = [Lock(LockType.WRITE, dummy_tran, dummy_var1)]
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T1, x2)')
variable = self.data_manager.variables['x2']
self.assertTrue(variable.readable)
self.assertFalse(('x2' in self.data_manager.locks))
value = self.data_manager.obtain_read_lock(transaction, instruction)
self.assertTrue(('x2' in self.data_manager.locks))
self.assertTrue(value)
|
Test that a lock can be obtained when other locks exist
|
tests/test_data_manager.py
|
test_obtain_read_lock_with_existing_locks
|
cfnyu/distributed_db
| 0 |
python
|
def test_obtain_read_lock_with_existing_locks(self):
' '
dummy_tran = Transaction('T3', TransactionType.READ_WRITE, 1)
dummy_var = Variable(1, 4)
dummy_var1 = Variable(1, 6)
self.data_manager.locks['x4'] = [Lock(LockType.READ, dummy_tran, dummy_var)]
self.data_manager.locks['x6'] = [Lock(LockType.WRITE, dummy_tran, dummy_var1)]
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T1, x2)')
variable = self.data_manager.variables['x2']
self.assertTrue(variable.readable)
self.assertFalse(('x2' in self.data_manager.locks))
value = self.data_manager.obtain_read_lock(transaction, instruction)
self.assertTrue(('x2' in self.data_manager.locks))
self.assertTrue(value)
|
def test_obtain_read_lock_with_existing_locks(self):
' '
dummy_tran = Transaction('T3', TransactionType.READ_WRITE, 1)
dummy_var = Variable(1, 4)
dummy_var1 = Variable(1, 6)
self.data_manager.locks['x4'] = [Lock(LockType.READ, dummy_tran, dummy_var)]
self.data_manager.locks['x6'] = [Lock(LockType.WRITE, dummy_tran, dummy_var1)]
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T1, x2)')
variable = self.data_manager.variables['x2']
self.assertTrue(variable.readable)
self.assertFalse(('x2' in self.data_manager.locks))
value = self.data_manager.obtain_read_lock(transaction, instruction)
self.assertTrue(('x2' in self.data_manager.locks))
self.assertTrue(value)<|docstring|>Test that a lock can be obtained when other locks exist<|endoftext|>
|
219c9d0634d66402f3404d26a81096a13fedb9be2e2f5f1a9dadb9f7205be7fa
|
def test_obtain_read_lock_when_variable_unreadable(self):
' Test that a lock cannot be obtained when the Variable Readable is set to False '
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T1, x2)')
variable = self.data_manager.variables['x2']
variable.readable = False
self.data_manager.variables['x2'] = variable
self.assertFalse(self.data_manager.variables['x2'].readable)
self.assertFalse(self.data_manager.obtain_read_lock(transaction, instruction))
|
Test that a lock cannot be obtained when the Variable Readable is set to False
|
tests/test_data_manager.py
|
test_obtain_read_lock_when_variable_unreadable
|
cfnyu/distributed_db
| 0 |
python
|
def test_obtain_read_lock_when_variable_unreadable(self):
' '
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T1, x2)')
variable = self.data_manager.variables['x2']
variable.readable = False
self.data_manager.variables['x2'] = variable
self.assertFalse(self.data_manager.variables['x2'].readable)
self.assertFalse(self.data_manager.obtain_read_lock(transaction, instruction))
|
def test_obtain_read_lock_when_variable_unreadable(self):
' '
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T1, x2)')
variable = self.data_manager.variables['x2']
variable.readable = False
self.data_manager.variables['x2'] = variable
self.assertFalse(self.data_manager.variables['x2'].readable)
self.assertFalse(self.data_manager.obtain_read_lock(transaction, instruction))<|docstring|>Test that a lock cannot be obtained when the Variable Readable is set to False<|endoftext|>
|
c2644c0a6d43237c2266537b2921d26b44e3d1117add4fdc6b927059cf78de9f
|
def test_obtain_read_lock_with_ro_transaction(self):
' Test that a lock can be obtained when the Transaction Is Read-Only '
transaction = Transaction('T1', TransactionType.READ_ONLY, 1)
instruction = Instruction('R(T1, x2)')
self.assertTrue((transaction.transaction_type == TransactionType.READ_ONLY))
self.assertTrue(self.data_manager.obtain_read_lock(transaction, instruction))
|
Test that a lock can be obtained when the Transaction Is Read-Only
|
tests/test_data_manager.py
|
test_obtain_read_lock_with_ro_transaction
|
cfnyu/distributed_db
| 0 |
python
|
def test_obtain_read_lock_with_ro_transaction(self):
' '
transaction = Transaction('T1', TransactionType.READ_ONLY, 1)
instruction = Instruction('R(T1, x2)')
self.assertTrue((transaction.transaction_type == TransactionType.READ_ONLY))
self.assertTrue(self.data_manager.obtain_read_lock(transaction, instruction))
|
def test_obtain_read_lock_with_ro_transaction(self):
' '
transaction = Transaction('T1', TransactionType.READ_ONLY, 1)
instruction = Instruction('R(T1, x2)')
self.assertTrue((transaction.transaction_type == TransactionType.READ_ONLY))
self.assertTrue(self.data_manager.obtain_read_lock(transaction, instruction))<|docstring|>Test that a lock can be obtained when the Transaction Is Read-Only<|endoftext|>
|
252f82fe740ad96e5adc102f011afbdcece183ac81aa911eba6562b68466a644
|
def test_obtain_read_lock_with_existing_read_lock(self):
' Test that a lock cannot be obtained when another Transaction has a lock '
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T1, x2)')
self.assertTrue(self.data_manager.obtain_read_lock(transaction, instruction))
new_lock = self.data_manager.locks['x2'][0]
self.assertTrue((new_lock.lock_type == LockType.READ))
self.assertEquals(new_lock.transaction.index, 1)
transaction = Transaction('T2', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T2, x2)')
self.assertTrue(('x2' in self.data_manager.locks))
self.assertTrue(self.data_manager.obtain_read_lock(transaction, instruction))
|
Test that a lock cannot be obtained when another Transaction has a lock
|
tests/test_data_manager.py
|
test_obtain_read_lock_with_existing_read_lock
|
cfnyu/distributed_db
| 0 |
python
|
def test_obtain_read_lock_with_existing_read_lock(self):
' '
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T1, x2)')
self.assertTrue(self.data_manager.obtain_read_lock(transaction, instruction))
new_lock = self.data_manager.locks['x2'][0]
self.assertTrue((new_lock.lock_type == LockType.READ))
self.assertEquals(new_lock.transaction.index, 1)
transaction = Transaction('T2', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T2, x2)')
self.assertTrue(('x2' in self.data_manager.locks))
self.assertTrue(self.data_manager.obtain_read_lock(transaction, instruction))
|
def test_obtain_read_lock_with_existing_read_lock(self):
' '
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T1, x2)')
self.assertTrue(self.data_manager.obtain_read_lock(transaction, instruction))
new_lock = self.data_manager.locks['x2'][0]
self.assertTrue((new_lock.lock_type == LockType.READ))
self.assertEquals(new_lock.transaction.index, 1)
transaction = Transaction('T2', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T2, x2)')
self.assertTrue(('x2' in self.data_manager.locks))
self.assertTrue(self.data_manager.obtain_read_lock(transaction, instruction))<|docstring|>Test that a lock cannot be obtained when another Transaction has a lock<|endoftext|>
|
6fd5612cd9a5bb6f6a7996c5992f8b7afdf9c421cb85268785468a611bbd80a6
|
def test_obtain_read_lock_with_existing_write_lock(self):
' Test that a lock cannot be obtained when another Transaction has a lock '
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('W(T1,x2, 103)')
self.data_manager.obtain_write_lock(instruction, transaction)
transaction = Transaction('T2', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T2, x2)')
self.assertTrue(('x2' in self.data_manager.locks))
self.assertFalse(self.data_manager.obtain_read_lock(transaction, instruction))
|
Test that a lock cannot be obtained when another Transaction has a lock
|
tests/test_data_manager.py
|
test_obtain_read_lock_with_existing_write_lock
|
cfnyu/distributed_db
| 0 |
python
|
def test_obtain_read_lock_with_existing_write_lock(self):
' '
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('W(T1,x2, 103)')
self.data_manager.obtain_write_lock(instruction, transaction)
transaction = Transaction('T2', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T2, x2)')
self.assertTrue(('x2' in self.data_manager.locks))
self.assertFalse(self.data_manager.obtain_read_lock(transaction, instruction))
|
def test_obtain_read_lock_with_existing_write_lock(self):
' '
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('W(T1,x2, 103)')
self.data_manager.obtain_write_lock(instruction, transaction)
transaction = Transaction('T2', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T2, x2)')
self.assertTrue(('x2' in self.data_manager.locks))
self.assertFalse(self.data_manager.obtain_read_lock(transaction, instruction))<|docstring|>Test that a lock cannot be obtained when another Transaction has a lock<|endoftext|>
|
db44160bf950dd3d3415671fcdee94afff7c5cfed2c59ed5c8e742b8f3249138
|
def test_obtain_read_lock_when_trans_has_exiting_lock(self):
' Test that a lock can be obtained when same Transaction requests the same lock '
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T2, x2)')
self.assertTrue(self.data_manager.obtain_read_lock(transaction, instruction))
self.assertTrue(('x2' in self.data_manager.locks))
self.assertTrue(self.data_manager.obtain_read_lock(transaction, instruction))
|
Test that a lock can be obtained when same Transaction requests the same lock
|
tests/test_data_manager.py
|
test_obtain_read_lock_when_trans_has_exiting_lock
|
cfnyu/distributed_db
| 0 |
python
|
def test_obtain_read_lock_when_trans_has_exiting_lock(self):
' '
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T2, x2)')
self.assertTrue(self.data_manager.obtain_read_lock(transaction, instruction))
self.assertTrue(('x2' in self.data_manager.locks))
self.assertTrue(self.data_manager.obtain_read_lock(transaction, instruction))
|
def test_obtain_read_lock_when_trans_has_exiting_lock(self):
' '
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T2, x2)')
self.assertTrue(self.data_manager.obtain_read_lock(transaction, instruction))
self.assertTrue(('x2' in self.data_manager.locks))
self.assertTrue(self.data_manager.obtain_read_lock(transaction, instruction))<|docstring|>Test that a lock can be obtained when same Transaction requests the same lock<|endoftext|>
|
c04f437d9c1065bbce8f7e87d49b5e917d6d6a1bfb355f52ec53cdfac9be0503
|
def test_read_with_no_locks(self):
' Test the read method, which should return the last committed value '
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T1, x2)')
self.assertEquals(self.data_manager.read(transaction, instruction), '20')
|
Test the read method, which should return the last committed value
|
tests/test_data_manager.py
|
test_read_with_no_locks
|
cfnyu/distributed_db
| 0 |
python
|
def test_read_with_no_locks(self):
' '
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T1, x2)')
self.assertEquals(self.data_manager.read(transaction, instruction), '20')
|
def test_read_with_no_locks(self):
' '
transaction = Transaction('T1', TransactionType.READ_WRITE, 1)
instruction = Instruction('R(T1, x2)')
self.assertEquals(self.data_manager.read(transaction, instruction), '20')<|docstring|>Test the read method, which should return the last committed value<|endoftext|>
|
344a6db131e9468fbf7b1ffcba2089d5b5fc86b1b926a0bb86733bce6337346c
|
def test_entries_maintains_values_per_transaction(self):
' Ensure that entities is keeping the log of committed values per transaction '
self.assertEquals(self.data_manager.variables['x6'].value, '60')
self.data_manager.write_new_data(2, 'x6', 999, 'T1')
self.assertEquals(self.data_manager.variables['x6'].value, '60')
self.assertEquals(self.data_manager.entries['T1']['x6'].written_values[1], '60')
self.assertEquals(self.data_manager.entries['T1']['x6'].written_values[2], '999')
|
Ensure that entities is keeping the log of committed values per transaction
|
tests/test_data_manager.py
|
test_entries_maintains_values_per_transaction
|
cfnyu/distributed_db
| 0 |
python
|
def test_entries_maintains_values_per_transaction(self):
' '
self.assertEquals(self.data_manager.variables['x6'].value, '60')
self.data_manager.write_new_data(2, 'x6', 999, 'T1')
self.assertEquals(self.data_manager.variables['x6'].value, '60')
self.assertEquals(self.data_manager.entries['T1']['x6'].written_values[1], '60')
self.assertEquals(self.data_manager.entries['T1']['x6'].written_values[2], '999')
|
def test_entries_maintains_values_per_transaction(self):
' '
self.assertEquals(self.data_manager.variables['x6'].value, '60')
self.data_manager.write_new_data(2, 'x6', 999, 'T1')
self.assertEquals(self.data_manager.variables['x6'].value, '60')
self.assertEquals(self.data_manager.entries['T1']['x6'].written_values[1], '60')
self.assertEquals(self.data_manager.entries['T1']['x6'].written_values[2], '999')<|docstring|>Ensure that entities is keeping the log of committed values per transaction<|endoftext|>
|
a947e01e27bf9a62eccfa9c189e1ecf18023a9bf10337c7c58c84ba5d220d5be
|
def _get_serdesmode(self):
'\n Getter method for serdesmode, mapped from YANG variable /sfm_state/serdesmode/serdesmode (uint32)\n\n YANG Description: SFM Serdes Mode\n '
return self.__serdesmode
|
Getter method for serdesmode, mapped from YANG variable /sfm_state/serdesmode/serdesmode (uint32)
YANG Description: SFM Serdes Mode
|
pybind/slxos/v16r_1_00b/sfm_state/serdesmode/__init__.py
|
_get_serdesmode
|
shivharis/pybind
| 0 |
python
|
def _get_serdesmode(self):
'\n Getter method for serdesmode, mapped from YANG variable /sfm_state/serdesmode/serdesmode (uint32)\n\n YANG Description: SFM Serdes Mode\n '
return self.__serdesmode
|
def _get_serdesmode(self):
'\n Getter method for serdesmode, mapped from YANG variable /sfm_state/serdesmode/serdesmode (uint32)\n\n YANG Description: SFM Serdes Mode\n '
return self.__serdesmode<|docstring|>Getter method for serdesmode, mapped from YANG variable /sfm_state/serdesmode/serdesmode (uint32)
YANG Description: SFM Serdes Mode<|endoftext|>
|
099e26b8f59c84f45a6eaba86b3ed5a672bc8afdc668fe0c626413af1481fcae
|
def _set_serdesmode(self, v, load=False):
'\n Setter method for serdesmode, mapped from YANG variable /sfm_state/serdesmode/serdesmode (uint32)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_serdesmode is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_serdesmode() directly.\n\n YANG Description: SFM Serdes Mode\n '
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name='serdesmode', rest_name='serdesmode', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-sysmgr-operational', defining_module='brocade-sysmgr-operational', yang_type='uint32', is_config=False)
except (TypeError, ValueError):
raise ValueError({'error-string': 'serdesmode must be of a type compatible with uint32', 'defined-type': 'uint32', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={\'range\': [\'0..4294967295\']}, int_size=32), is_leaf=True, yang_name="serdesmode", rest_name="serdesmode", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'urn:brocade.com:mgmt:brocade-sysmgr-operational\', defining_module=\'brocade-sysmgr-operational\', yang_type=\'uint32\', is_config=False)'})
self.__serdesmode = t
if hasattr(self, '_set'):
self._set()
|
Setter method for serdesmode, mapped from YANG variable /sfm_state/serdesmode/serdesmode (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_serdesmode is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_serdesmode() directly.
YANG Description: SFM Serdes Mode
|
pybind/slxos/v16r_1_00b/sfm_state/serdesmode/__init__.py
|
_set_serdesmode
|
shivharis/pybind
| 0 |
python
|
def _set_serdesmode(self, v, load=False):
'\n Setter method for serdesmode, mapped from YANG variable /sfm_state/serdesmode/serdesmode (uint32)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_serdesmode is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_serdesmode() directly.\n\n YANG Description: SFM Serdes Mode\n '
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name='serdesmode', rest_name='serdesmode', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-sysmgr-operational', defining_module='brocade-sysmgr-operational', yang_type='uint32', is_config=False)
except (TypeError, ValueError):
raise ValueError({'error-string': 'serdesmode must be of a type compatible with uint32', 'defined-type': 'uint32', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={\'range\': [\'0..4294967295\']}, int_size=32), is_leaf=True, yang_name="serdesmode", rest_name="serdesmode", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'urn:brocade.com:mgmt:brocade-sysmgr-operational\', defining_module=\'brocade-sysmgr-operational\', yang_type=\'uint32\', is_config=False)'})
self.__serdesmode = t
if hasattr(self, '_set'):
self._set()
|
def _set_serdesmode(self, v, load=False):
'\n Setter method for serdesmode, mapped from YANG variable /sfm_state/serdesmode/serdesmode (uint32)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_serdesmode is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_serdesmode() directly.\n\n YANG Description: SFM Serdes Mode\n '
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name='serdesmode', rest_name='serdesmode', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-sysmgr-operational', defining_module='brocade-sysmgr-operational', yang_type='uint32', is_config=False)
except (TypeError, ValueError):
raise ValueError({'error-string': 'serdesmode must be of a type compatible with uint32', 'defined-type': 'uint32', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={\'range\': [\'0..4294967295\']}, int_size=32), is_leaf=True, yang_name="serdesmode", rest_name="serdesmode", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'urn:brocade.com:mgmt:brocade-sysmgr-operational\', defining_module=\'brocade-sysmgr-operational\', yang_type=\'uint32\', is_config=False)'})
self.__serdesmode = t
if hasattr(self, '_set'):
self._set()<|docstring|>Setter method for serdesmode, mapped from YANG variable /sfm_state/serdesmode/serdesmode (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_serdesmode is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_serdesmode() directly.
YANG Description: SFM Serdes Mode<|endoftext|>
|
e0d872c4e11aedb913163dcfaab8f4914a605d6e0fd33d588f3fb659dcf033f1
|
def _get_serdesmode_sfmid(self):
'\n Getter method for serdesmode_sfmid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_sfmid (uint32)\n\n YANG Description: SFM Serdes Mode\n '
return self.__serdesmode_sfmid
|
Getter method for serdesmode_sfmid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_sfmid (uint32)
YANG Description: SFM Serdes Mode
|
pybind/slxos/v16r_1_00b/sfm_state/serdesmode/__init__.py
|
_get_serdesmode_sfmid
|
shivharis/pybind
| 0 |
python
|
def _get_serdesmode_sfmid(self):
'\n Getter method for serdesmode_sfmid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_sfmid (uint32)\n\n YANG Description: SFM Serdes Mode\n '
return self.__serdesmode_sfmid
|
def _get_serdesmode_sfmid(self):
'\n Getter method for serdesmode_sfmid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_sfmid (uint32)\n\n YANG Description: SFM Serdes Mode\n '
return self.__serdesmode_sfmid<|docstring|>Getter method for serdesmode_sfmid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_sfmid (uint32)
YANG Description: SFM Serdes Mode<|endoftext|>
|
45c1de1e0de9973aa45d415ea50639c49aa7cb683ded32675c8e5bbb0f20a7cc
|
def _set_serdesmode_sfmid(self, v, load=False):
'\n Setter method for serdesmode_sfmid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_sfmid (uint32)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_serdesmode_sfmid is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_serdesmode_sfmid() directly.\n\n YANG Description: SFM Serdes Mode\n '
parent = getattr(self, '_parent', None)
if ((parent is not None) and (load is False)):
raise AttributeError(('Cannot set keys directly when' + ' within an instantiated list'))
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name='serdesmode-sfmid', rest_name='serdesmode-sfmid', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-sysmgr-operational', defining_module='brocade-sysmgr-operational', yang_type='uint32', is_config=False)
except (TypeError, ValueError):
raise ValueError({'error-string': 'serdesmode_sfmid must be of a type compatible with uint32', 'defined-type': 'uint32', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={\'range\': [\'0..4294967295\']}, int_size=32), is_leaf=True, yang_name="serdesmode-sfmid", rest_name="serdesmode-sfmid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace=\'urn:brocade.com:mgmt:brocade-sysmgr-operational\', defining_module=\'brocade-sysmgr-operational\', yang_type=\'uint32\', is_config=False)'})
self.__serdesmode_sfmid = t
if hasattr(self, '_set'):
self._set()
|
Setter method for serdesmode_sfmid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_sfmid (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_serdesmode_sfmid is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_serdesmode_sfmid() directly.
YANG Description: SFM Serdes Mode
|
pybind/slxos/v16r_1_00b/sfm_state/serdesmode/__init__.py
|
_set_serdesmode_sfmid
|
shivharis/pybind
| 0 |
python
|
def _set_serdesmode_sfmid(self, v, load=False):
'\n Setter method for serdesmode_sfmid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_sfmid (uint32)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_serdesmode_sfmid is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_serdesmode_sfmid() directly.\n\n YANG Description: SFM Serdes Mode\n '
parent = getattr(self, '_parent', None)
if ((parent is not None) and (load is False)):
raise AttributeError(('Cannot set keys directly when' + ' within an instantiated list'))
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name='serdesmode-sfmid', rest_name='serdesmode-sfmid', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-sysmgr-operational', defining_module='brocade-sysmgr-operational', yang_type='uint32', is_config=False)
except (TypeError, ValueError):
raise ValueError({'error-string': 'serdesmode_sfmid must be of a type compatible with uint32', 'defined-type': 'uint32', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={\'range\': [\'0..4294967295\']}, int_size=32), is_leaf=True, yang_name="serdesmode-sfmid", rest_name="serdesmode-sfmid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace=\'urn:brocade.com:mgmt:brocade-sysmgr-operational\', defining_module=\'brocade-sysmgr-operational\', yang_type=\'uint32\', is_config=False)'})
self.__serdesmode_sfmid = t
if hasattr(self, '_set'):
self._set()
|
def _set_serdesmode_sfmid(self, v, load=False):
'\n Setter method for serdesmode_sfmid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_sfmid (uint32)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_serdesmode_sfmid is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_serdesmode_sfmid() directly.\n\n YANG Description: SFM Serdes Mode\n '
parent = getattr(self, '_parent', None)
if ((parent is not None) and (load is False)):
raise AttributeError(('Cannot set keys directly when' + ' within an instantiated list'))
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name='serdesmode-sfmid', rest_name='serdesmode-sfmid', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-sysmgr-operational', defining_module='brocade-sysmgr-operational', yang_type='uint32', is_config=False)
except (TypeError, ValueError):
raise ValueError({'error-string': 'serdesmode_sfmid must be of a type compatible with uint32', 'defined-type': 'uint32', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={\'range\': [\'0..4294967295\']}, int_size=32), is_leaf=True, yang_name="serdesmode-sfmid", rest_name="serdesmode-sfmid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace=\'urn:brocade.com:mgmt:brocade-sysmgr-operational\', defining_module=\'brocade-sysmgr-operational\', yang_type=\'uint32\', is_config=False)'})
self.__serdesmode_sfmid = t
if hasattr(self, '_set'):
self._set()<|docstring|>Setter method for serdesmode_sfmid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_sfmid (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_serdesmode_sfmid is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_serdesmode_sfmid() directly.
YANG Description: SFM Serdes Mode<|endoftext|>
|
973d585b61ab169ff9cb5198656127317b25e1f293824227acac73302b268e41
|
def _get_serdesmode_feid(self):
'\n Getter method for serdesmode_feid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_feid (uint32)\n\n YANG Description: SFM Serdes Mode\n '
return self.__serdesmode_feid
|
Getter method for serdesmode_feid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_feid (uint32)
YANG Description: SFM Serdes Mode
|
pybind/slxos/v16r_1_00b/sfm_state/serdesmode/__init__.py
|
_get_serdesmode_feid
|
shivharis/pybind
| 0 |
python
|
def _get_serdesmode_feid(self):
'\n Getter method for serdesmode_feid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_feid (uint32)\n\n YANG Description: SFM Serdes Mode\n '
return self.__serdesmode_feid
|
def _get_serdesmode_feid(self):
'\n Getter method for serdesmode_feid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_feid (uint32)\n\n YANG Description: SFM Serdes Mode\n '
return self.__serdesmode_feid<|docstring|>Getter method for serdesmode_feid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_feid (uint32)
YANG Description: SFM Serdes Mode<|endoftext|>
|
6a35a393b92b4f0cc5412735feca8f09d82eee2e57512f4251b25d579f36cdf5
|
def _set_serdesmode_feid(self, v, load=False):
'\n Setter method for serdesmode_feid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_feid (uint32)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_serdesmode_feid is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_serdesmode_feid() directly.\n\n YANG Description: SFM Serdes Mode\n '
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name='serdesmode-feid', rest_name='serdesmode-feid', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-sysmgr-operational', defining_module='brocade-sysmgr-operational', yang_type='uint32', is_config=False)
except (TypeError, ValueError):
raise ValueError({'error-string': 'serdesmode_feid must be of a type compatible with uint32', 'defined-type': 'uint32', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={\'range\': [\'0..4294967295\']}, int_size=32), is_leaf=True, yang_name="serdesmode-feid", rest_name="serdesmode-feid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'urn:brocade.com:mgmt:brocade-sysmgr-operational\', defining_module=\'brocade-sysmgr-operational\', yang_type=\'uint32\', is_config=False)'})
self.__serdesmode_feid = t
if hasattr(self, '_set'):
self._set()
|
Setter method for serdesmode_feid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_feid (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_serdesmode_feid is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_serdesmode_feid() directly.
YANG Description: SFM Serdes Mode
|
pybind/slxos/v16r_1_00b/sfm_state/serdesmode/__init__.py
|
_set_serdesmode_feid
|
shivharis/pybind
| 0 |
python
|
def _set_serdesmode_feid(self, v, load=False):
'\n Setter method for serdesmode_feid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_feid (uint32)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_serdesmode_feid is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_serdesmode_feid() directly.\n\n YANG Description: SFM Serdes Mode\n '
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name='serdesmode-feid', rest_name='serdesmode-feid', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-sysmgr-operational', defining_module='brocade-sysmgr-operational', yang_type='uint32', is_config=False)
except (TypeError, ValueError):
raise ValueError({'error-string': 'serdesmode_feid must be of a type compatible with uint32', 'defined-type': 'uint32', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={\'range\': [\'0..4294967295\']}, int_size=32), is_leaf=True, yang_name="serdesmode-feid", rest_name="serdesmode-feid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'urn:brocade.com:mgmt:brocade-sysmgr-operational\', defining_module=\'brocade-sysmgr-operational\', yang_type=\'uint32\', is_config=False)'})
self.__serdesmode_feid = t
if hasattr(self, '_set'):
self._set()
|
def _set_serdesmode_feid(self, v, load=False):
'\n Setter method for serdesmode_feid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_feid (uint32)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_serdesmode_feid is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_serdesmode_feid() directly.\n\n YANG Description: SFM Serdes Mode\n '
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name='serdesmode-feid', rest_name='serdesmode-feid', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-sysmgr-operational', defining_module='brocade-sysmgr-operational', yang_type='uint32', is_config=False)
except (TypeError, ValueError):
raise ValueError({'error-string': 'serdesmode_feid must be of a type compatible with uint32', 'defined-type': 'uint32', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={\'range\': [\'0..4294967295\']}, int_size=32), is_leaf=True, yang_name="serdesmode-feid", rest_name="serdesmode-feid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'urn:brocade.com:mgmt:brocade-sysmgr-operational\', defining_module=\'brocade-sysmgr-operational\', yang_type=\'uint32\', is_config=False)'})
self.__serdesmode_feid = t
if hasattr(self, '_set'):
self._set()<|docstring|>Setter method for serdesmode_feid, mapped from YANG variable /sfm_state/serdesmode/serdesmode_feid (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_serdesmode_feid is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_serdesmode_feid() directly.
YANG Description: SFM Serdes Mode<|endoftext|>
|
69722da69c2664f33919822bdb78ebdd7c819112935de527273321b937ea2ccd
|
def test_source_volume_missing_1(sevenmode):
'Test missing input params.'
with pytest.raises(NidhoggException):
' no source volume '
sevenmode.update_snapmirror('dst_volume', source_filer='host')
with pytest.raises(NidhoggException):
' no source filer '
sevenmode.update_snapmirror('dst_volume', source_volume='vol')
with pytest.raises(NidhoggException):
' no source filer '
sevenmode.update_snapmirror('dst_volume', source_qtree='qtree')
with pytest.raises(NidhoggException):
' no source filer '
sevenmode.update_snapmirror('dst_volume', source_volume='vol', source_qtree='qtree')
with pytest.raises(NidhoggException):
' no source volume '
sevenmode.update_snapmirror('dst_volume', source_filer='host', source_qtree='qtree')
with pytest.raises(NidhoggException):
' no src qtree '
sevenmode.update_snapmirror('dst_volume', 'dst_qtree', source_filer='host', source_volume='vol')
with pytest.raises(NidhoggException):
' no dst qtree '
sevenmode.update_snapmirror('dst_volume', source_filer='host', source_volume='vol', source_qtree='qtree')
|
Test missing input params.
|
tests/test_snapmirror_params.py
|
test_source_volume_missing_1
|
ifxit/nidho
| 11 |
python
|
def test_source_volume_missing_1(sevenmode):
with pytest.raises(NidhoggException):
' no source volume '
sevenmode.update_snapmirror('dst_volume', source_filer='host')
with pytest.raises(NidhoggException):
' no source filer '
sevenmode.update_snapmirror('dst_volume', source_volume='vol')
with pytest.raises(NidhoggException):
' no source filer '
sevenmode.update_snapmirror('dst_volume', source_qtree='qtree')
with pytest.raises(NidhoggException):
' no source filer '
sevenmode.update_snapmirror('dst_volume', source_volume='vol', source_qtree='qtree')
with pytest.raises(NidhoggException):
' no source volume '
sevenmode.update_snapmirror('dst_volume', source_filer='host', source_qtree='qtree')
with pytest.raises(NidhoggException):
' no src qtree '
sevenmode.update_snapmirror('dst_volume', 'dst_qtree', source_filer='host', source_volume='vol')
with pytest.raises(NidhoggException):
' no dst qtree '
sevenmode.update_snapmirror('dst_volume', source_filer='host', source_volume='vol', source_qtree='qtree')
|
def test_source_volume_missing_1(sevenmode):
with pytest.raises(NidhoggException):
' no source volume '
sevenmode.update_snapmirror('dst_volume', source_filer='host')
with pytest.raises(NidhoggException):
' no source filer '
sevenmode.update_snapmirror('dst_volume', source_volume='vol')
with pytest.raises(NidhoggException):
' no source filer '
sevenmode.update_snapmirror('dst_volume', source_qtree='qtree')
with pytest.raises(NidhoggException):
' no source filer '
sevenmode.update_snapmirror('dst_volume', source_volume='vol', source_qtree='qtree')
with pytest.raises(NidhoggException):
' no source volume '
sevenmode.update_snapmirror('dst_volume', source_filer='host', source_qtree='qtree')
with pytest.raises(NidhoggException):
' no src qtree '
sevenmode.update_snapmirror('dst_volume', 'dst_qtree', source_filer='host', source_volume='vol')
with pytest.raises(NidhoggException):
' no dst qtree '
sevenmode.update_snapmirror('dst_volume', source_filer='host', source_volume='vol', source_qtree='qtree')<|docstring|>Test missing input params.<|endoftext|>
|
bffe0bb063defd97022f67083e8424d29208a4a5488effa0220c5a1ce9553ba0
|
def test_source_volume_missing_2(sevenmode):
'Test missing input params.'
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', source_filer='host')
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', source_volume='vol')
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', source_qtree='qtree')
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', source_volume='vol', source_qtree='qtree')
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', source_filer='host', source_qtree='qtree')
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', 'dst_qtree', source_filer='host', source_volume='vol')
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', source_filer='host', source_volume='vol', source_qtree='qtree')
|
Test missing input params.
|
tests/test_snapmirror_params.py
|
test_source_volume_missing_2
|
ifxit/nidho
| 11 |
python
|
def test_source_volume_missing_2(sevenmode):
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', source_filer='host')
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', source_volume='vol')
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', source_qtree='qtree')
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', source_volume='vol', source_qtree='qtree')
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', source_filer='host', source_qtree='qtree')
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', 'dst_qtree', source_filer='host', source_volume='vol')
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', source_filer='host', source_volume='vol', source_qtree='qtree')
|
def test_source_volume_missing_2(sevenmode):
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', source_filer='host')
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', source_volume='vol')
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', source_qtree='qtree')
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', source_volume='vol', source_qtree='qtree')
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', source_filer='host', source_qtree='qtree')
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', 'dst_qtree', source_filer='host', source_volume='vol')
with pytest.raises(NidhoggException):
sevenmode.update_snapmirror_with_snapshot('name', 'dst_volume', source_filer='host', source_volume='vol', source_qtree='qtree')<|docstring|>Test missing input params.<|endoftext|>
|
fe3c41802a62d0765c70cad8bf38189387cc920afac5d12b80e8a83325b058f4
|
def main() -> None:
'Process command line execution.'
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'the_htvms.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError("Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?") from exc
if ((len(sys.argv) > 1) and (sys.argv[1] == 'run')):
SiteManager(sys.argv[1:]).run_server()
else:
execute_from_command_line(sys.argv)
|
Process command line execution.
|
dramatic-dragonflies/manage.py
|
main
|
lavirlifiliol/summer-code-jam-2020
| 0 |
python
|
def main() -> None:
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'the_htvms.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError("Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?") from exc
if ((len(sys.argv) > 1) and (sys.argv[1] == 'run')):
SiteManager(sys.argv[1:]).run_server()
else:
execute_from_command_line(sys.argv)
|
def main() -> None:
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'the_htvms.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError("Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?") from exc
if ((len(sys.argv) > 1) and (sys.argv[1] == 'run')):
SiteManager(sys.argv[1:]).run_server()
else:
execute_from_command_line(sys.argv)<|docstring|>Process command line execution.<|endoftext|>
|
42b542dccf1c7f2da240196224a1f046a9062a12d7b9ae81beade4eac4ea314d
|
def prepare_server(self) -> None:
'Perform preparation tasks before running the server.'
django.setup()
if self.migrate:
print('Applying migrations.')
call_command('migrate', verbosity=self.verbosity)
if self.collectstatic:
print('Collecting static files.')
call_command('collectstatic', interactive=False, clear=True, verbosity=self.verbosity)
|
Perform preparation tasks before running the server.
|
dramatic-dragonflies/manage.py
|
prepare_server
|
lavirlifiliol/summer-code-jam-2020
| 0 |
python
|
def prepare_server(self) -> None:
django.setup()
if self.migrate:
print('Applying migrations.')
call_command('migrate', verbosity=self.verbosity)
if self.collectstatic:
print('Collecting static files.')
call_command('collectstatic', interactive=False, clear=True, verbosity=self.verbosity)
|
def prepare_server(self) -> None:
django.setup()
if self.migrate:
print('Applying migrations.')
call_command('migrate', verbosity=self.verbosity)
if self.collectstatic:
print('Collecting static files.')
call_command('collectstatic', interactive=False, clear=True, verbosity=self.verbosity)<|docstring|>Perform preparation tasks before running the server.<|endoftext|>
|
d81d5d52b8fd998b1781e1e8c3c85bc83240ed248fa0671da3f5893515a76676
|
@staticmethod
def perform_security_check() -> None:
'Perform django security tests.'
print('Running security checks.')
call_command('check', '--deploy', '--fail-level', 'WARNING')
|
Perform django security tests.
|
dramatic-dragonflies/manage.py
|
perform_security_check
|
lavirlifiliol/summer-code-jam-2020
| 0 |
python
|
@staticmethod
def perform_security_check() -> None:
print('Running security checks.')
call_command('check', '--deploy', '--fail-level', 'WARNING')
|
@staticmethod
def perform_security_check() -> None:
print('Running security checks.')
call_command('check', '--deploy', '--fail-level', 'WARNING')<|docstring|>Perform django security tests.<|endoftext|>
|
3c5ca71a88d8c0cb0a404f3a22a3271f3ef0da8d2822404ee36c6ed307c39ff7
|
def run_server(self) -> None:
'Prepare and run the web server.'
in_reloader = (os.environ.get('RUN_MAIN') == 'true')
if in_reloader:
self.prepare_server()
if self.check:
self.perform_security_check()
print('Starting server.')
call_command('runserver', '0.0.0.0:5000')
return
|
Prepare and run the web server.
|
dramatic-dragonflies/manage.py
|
run_server
|
lavirlifiliol/summer-code-jam-2020
| 0 |
python
|
def run_server(self) -> None:
in_reloader = (os.environ.get('RUN_MAIN') == 'true')
if in_reloader:
self.prepare_server()
if self.check:
self.perform_security_check()
print('Starting server.')
call_command('runserver', '0.0.0.0:5000')
return
|
def run_server(self) -> None:
in_reloader = (os.environ.get('RUN_MAIN') == 'true')
if in_reloader:
self.prepare_server()
if self.check:
self.perform_security_check()
print('Starting server.')
call_command('runserver', '0.0.0.0:5000')
return<|docstring|>Prepare and run the web server.<|endoftext|>
|
ee5f03d7199a8420149201cabf99281ef1680660d34d1bfc6d8b653f08e71755
|
def get_distance_matrix(mmcif_file, chain_id):
'\n Given a protein structure in mmcif format and a chain id, extract the\n residue type, the coordinate of each residue, and the residue numbering.\n Compute all the pairwise euclidean distances among residues. Returns a\n dictionary containing all of these data.\n '
parser = PDB.MMCIFParser()
structure = parser.get_structure('_', mmcif_file)
out = {'residue': [], 'coordinates': [], 'resseq': [], 'icode': []}
matching_chains = 0
for model in structure:
if (model.id == 0):
print('Processing model:', model.id)
for chain in model:
if (chain.id != chain_id):
continue
matching_chains += 1
for residue in chain.get_residues():
het_field = residue.id[0]
if (het_field != ' '):
continue
out['residue'].append(residue.resname)
if (residue.resname == 'GLY'):
out['coordinates'].append(residue['CA'].get_coord())
else:
out['coordinates'].append(residue['CB'].get_coord())
out['resseq'].append(residue.id[1])
out['icode'].append(residue.id[2])
else:
print('Skipping model:', model.id)
assert (matching_chains == 1)
out['coordinates'] = np.array(out['coordinates'], dtype=float)
out['resseq'] = np.array(out['resseq'], dtype=int)
out['icode'] = np.array(out['icode'], dtype=str)
out['icode'] = np.where((out['icode'] == ' '), 'nan', out['icode'])
out['distance_matrix'] = spatial.distance_matrix(out['coordinates'], out['coordinates'], p=2)
out['sequence'] = ''.join([SeqUtils.IUPACData.protein_letters_3to1[r.capitalize()] for r in out['residue']])
out['pdb_id'] = mmcif_file.split('.')[0]
out['chain_id'] = chain_id
return out
|
Given a protein structure in mmcif format and a chain id, extract the
residue type, the coordinate of each residue, and the residue numbering.
Compute all the pairwise euclidean distances among residues. Returns a
dictionary containing all of these data.
|
python/pdb_to_distance_matrix.py
|
get_distance_matrix
|
saulpierotti/.bioscripts
| 0 |
python
|
def get_distance_matrix(mmcif_file, chain_id):
'\n Given a protein structure in mmcif format and a chain id, extract the\n residue type, the coordinate of each residue, and the residue numbering.\n Compute all the pairwise euclidean distances among residues. Returns a\n dictionary containing all of these data.\n '
parser = PDB.MMCIFParser()
structure = parser.get_structure('_', mmcif_file)
out = {'residue': [], 'coordinates': [], 'resseq': [], 'icode': []}
matching_chains = 0
for model in structure:
if (model.id == 0):
print('Processing model:', model.id)
for chain in model:
if (chain.id != chain_id):
continue
matching_chains += 1
for residue in chain.get_residues():
het_field = residue.id[0]
if (het_field != ' '):
continue
out['residue'].append(residue.resname)
if (residue.resname == 'GLY'):
out['coordinates'].append(residue['CA'].get_coord())
else:
out['coordinates'].append(residue['CB'].get_coord())
out['resseq'].append(residue.id[1])
out['icode'].append(residue.id[2])
else:
print('Skipping model:', model.id)
assert (matching_chains == 1)
out['coordinates'] = np.array(out['coordinates'], dtype=float)
out['resseq'] = np.array(out['resseq'], dtype=int)
out['icode'] = np.array(out['icode'], dtype=str)
out['icode'] = np.where((out['icode'] == ' '), 'nan', out['icode'])
out['distance_matrix'] = spatial.distance_matrix(out['coordinates'], out['coordinates'], p=2)
out['sequence'] = .join([SeqUtils.IUPACData.protein_letters_3to1[r.capitalize()] for r in out['residue']])
out['pdb_id'] = mmcif_file.split('.')[0]
out['chain_id'] = chain_id
return out
|
def get_distance_matrix(mmcif_file, chain_id):
'\n Given a protein structure in mmcif format and a chain id, extract the\n residue type, the coordinate of each residue, and the residue numbering.\n Compute all the pairwise euclidean distances among residues. Returns a\n dictionary containing all of these data.\n '
parser = PDB.MMCIFParser()
structure = parser.get_structure('_', mmcif_file)
out = {'residue': [], 'coordinates': [], 'resseq': [], 'icode': []}
matching_chains = 0
for model in structure:
if (model.id == 0):
print('Processing model:', model.id)
for chain in model:
if (chain.id != chain_id):
continue
matching_chains += 1
for residue in chain.get_residues():
het_field = residue.id[0]
if (het_field != ' '):
continue
out['residue'].append(residue.resname)
if (residue.resname == 'GLY'):
out['coordinates'].append(residue['CA'].get_coord())
else:
out['coordinates'].append(residue['CB'].get_coord())
out['resseq'].append(residue.id[1])
out['icode'].append(residue.id[2])
else:
print('Skipping model:', model.id)
assert (matching_chains == 1)
out['coordinates'] = np.array(out['coordinates'], dtype=float)
out['resseq'] = np.array(out['resseq'], dtype=int)
out['icode'] = np.array(out['icode'], dtype=str)
out['icode'] = np.where((out['icode'] == ' '), 'nan', out['icode'])
out['distance_matrix'] = spatial.distance_matrix(out['coordinates'], out['coordinates'], p=2)
out['sequence'] = .join([SeqUtils.IUPACData.protein_letters_3to1[r.capitalize()] for r in out['residue']])
out['pdb_id'] = mmcif_file.split('.')[0]
out['chain_id'] = chain_id
return out<|docstring|>Given a protein structure in mmcif format and a chain id, extract the
residue type, the coordinate of each residue, and the residue numbering.
Compute all the pairwise euclidean distances among residues. Returns a
dictionary containing all of these data.<|endoftext|>
|
8ce1b61a33713c05b463135ef7fc4b1ff6a26b280fb4f88e4d1ea9725efb57c4
|
def main(args):
'\n Main function\n '
assert os.path.isfile(args.i)
assert args.i.endswith('.cif')
assert (len(args.c) == 1)
assert args.o.endswith('.pdb_distance_matrix.joblib.xz')
assert (not os.path.isfile(args.o))
out_dict = get_distance_matrix(args.i, args.c)
joblib.dump(out_dict, args.o)
|
Main function
|
python/pdb_to_distance_matrix.py
|
main
|
saulpierotti/.bioscripts
| 0 |
python
|
def main(args):
'\n \n '
assert os.path.isfile(args.i)
assert args.i.endswith('.cif')
assert (len(args.c) == 1)
assert args.o.endswith('.pdb_distance_matrix.joblib.xz')
assert (not os.path.isfile(args.o))
out_dict = get_distance_matrix(args.i, args.c)
joblib.dump(out_dict, args.o)
|
def main(args):
'\n \n '
assert os.path.isfile(args.i)
assert args.i.endswith('.cif')
assert (len(args.c) == 1)
assert args.o.endswith('.pdb_distance_matrix.joblib.xz')
assert (not os.path.isfile(args.o))
out_dict = get_distance_matrix(args.i, args.c)
joblib.dump(out_dict, args.o)<|docstring|>Main function<|endoftext|>
|
82a5babcb11c543c7c0150b10a32046cb2ab34bd3576ac360043ce89fa76c585
|
def parse_arguments():
'\n Parse command line arguments.\n '
description = ' '.join(__doc__.splitlines()[4:])
epilog = ', '.join(__doc__.splitlines()[1:4])
parser = argparse.ArgumentParser(description=description, epilog=epilog)
parser.add_argument('-i', type=str, help='the mmcif file to be used', metavar='<file>', required=True)
parser.add_argument('-o', type=str, help='the file where to save the joblib dump of the distance matrix', metavar='<file>', required=True)
parser.add_argument('-c', type=str, help='the pdb chain id to be considered', metavar='<letter>', required=True)
args = parser.parse_args()
return args
|
Parse command line arguments.
|
python/pdb_to_distance_matrix.py
|
parse_arguments
|
saulpierotti/.bioscripts
| 0 |
python
|
def parse_arguments():
'\n \n '
description = ' '.join(__doc__.splitlines()[4:])
epilog = ', '.join(__doc__.splitlines()[1:4])
parser = argparse.ArgumentParser(description=description, epilog=epilog)
parser.add_argument('-i', type=str, help='the mmcif file to be used', metavar='<file>', required=True)
parser.add_argument('-o', type=str, help='the file where to save the joblib dump of the distance matrix', metavar='<file>', required=True)
parser.add_argument('-c', type=str, help='the pdb chain id to be considered', metavar='<letter>', required=True)
args = parser.parse_args()
return args
|
def parse_arguments():
'\n \n '
description = ' '.join(__doc__.splitlines()[4:])
epilog = ', '.join(__doc__.splitlines()[1:4])
parser = argparse.ArgumentParser(description=description, epilog=epilog)
parser.add_argument('-i', type=str, help='the mmcif file to be used', metavar='<file>', required=True)
parser.add_argument('-o', type=str, help='the file where to save the joblib dump of the distance matrix', metavar='<file>', required=True)
parser.add_argument('-c', type=str, help='the pdb chain id to be considered', metavar='<letter>', required=True)
args = parser.parse_args()
return args<|docstring|>Parse command line arguments.<|endoftext|>
|
75a53b7f92b132dd3548a84ab00f9b5f467325dba36ff06a8957e5f9bc1b8fc4
|
def __init__(self, *args, **kwargs):
"\n Method is used to initialize the User mapping module and it's base module.\n\n Args:\n *args:\n **kwargs:\n "
self.min_ver = None
self.max_ver = None
super(UserMappingModule, self).__init__(*args, **kwargs)
|
Method is used to initialize the User mapping module and it's base module.
Args:
*args:
**kwargs:
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
__init__
|
Anillab/One-Minute-Pitch
| 4 |
python
|
def __init__(self, *args, **kwargs):
"\n Method is used to initialize the User mapping module and it's base module.\n\n Args:\n *args:\n **kwargs:\n "
self.min_ver = None
self.max_ver = None
super(UserMappingModule, self).__init__(*args, **kwargs)
|
def __init__(self, *args, **kwargs):
"\n Method is used to initialize the User mapping module and it's base module.\n\n Args:\n *args:\n **kwargs:\n "
self.min_ver = None
self.max_ver = None
super(UserMappingModule, self).__init__(*args, **kwargs)<|docstring|>Method is used to initialize the User mapping module and it's base module.
Args:
*args:
**kwargs:<|endoftext|>
|
15d4251ae31bfe7b4a4a94bcf8f04a4c392633fd774dcb5978761f884176aab4
|
def get_nodes(self, gid, sid, did, fid, fsid):
'\n Method is used to generate the browser collection node\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: foreign data wrapper ID\n fsid: Foreign server ID\n '
(yield self.generate_browser_collection_node(fsid))
|
Method is used to generate the browser collection node
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: foreign data wrapper ID
fsid: Foreign server ID
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
get_nodes
|
Anillab/One-Minute-Pitch
| 4 |
python
|
def get_nodes(self, gid, sid, did, fid, fsid):
'\n Method is used to generate the browser collection node\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: foreign data wrapper ID\n fsid: Foreign server ID\n '
(yield self.generate_browser_collection_node(fsid))
|
def get_nodes(self, gid, sid, did, fid, fsid):
'\n Method is used to generate the browser collection node\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: foreign data wrapper ID\n fsid: Foreign server ID\n '
(yield self.generate_browser_collection_node(fsid))<|docstring|>Method is used to generate the browser collection node
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: foreign data wrapper ID
fsid: Foreign server ID<|endoftext|>
|
42908e6e8b56fe91d013a49570882d6b85b3ed05811aae63fed9ad0859fc4bcd
|
@property
def node_inode(self):
'\n node_inode\n\n Override this property to make the node as leaf node.\n '
return False
|
node_inode
Override this property to make the node as leaf node.
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
node_inode
|
Anillab/One-Minute-Pitch
| 4 |
python
|
@property
def node_inode(self):
'\n node_inode\n\n Override this property to make the node as leaf node.\n '
return False
|
@property
def node_inode(self):
'\n node_inode\n\n Override this property to make the node as leaf node.\n '
return False<|docstring|>node_inode
Override this property to make the node as leaf node.<|endoftext|>
|
cb8a64ff0dc5af05d33acee800489fd61e213248ee9930ef382f4f12f79fffb9
|
@property
def script_load(self):
'\n Load the module script for user mapping, when any of the foreign server node is initialized.\n\n Returns: node type of the server module.\n '
return servers.ServerModule.NODE_TYPE
|
Load the module script for user mapping, when any of the foreign server node is initialized.
Returns: node type of the server module.
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
script_load
|
Anillab/One-Minute-Pitch
| 4 |
python
|
@property
def script_load(self):
'\n Load the module script for user mapping, when any of the foreign server node is initialized.\n\n Returns: node type of the server module.\n '
return servers.ServerModule.NODE_TYPE
|
@property
def script_load(self):
'\n Load the module script for user mapping, when any of the foreign server node is initialized.\n\n Returns: node type of the server module.\n '
return servers.ServerModule.NODE_TYPE<|docstring|>Load the module script for user mapping, when any of the foreign server node is initialized.
Returns: node type of the server module.<|endoftext|>
|
9ca67c4c0fb2138137ace45583cef1c88b14b4d76fe6ec5b6523ff824df90910
|
@property
def module_use_template_javascript(self):
'\n Returns whether Jinja2 template is used for generating the javascript\n module.\n '
return False
|
Returns whether Jinja2 template is used for generating the javascript
module.
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
module_use_template_javascript
|
Anillab/One-Minute-Pitch
| 4 |
python
|
@property
def module_use_template_javascript(self):
'\n Returns whether Jinja2 template is used for generating the javascript\n module.\n '
return False
|
@property
def module_use_template_javascript(self):
'\n Returns whether Jinja2 template is used for generating the javascript\n module.\n '
return False<|docstring|>Returns whether Jinja2 template is used for generating the javascript
module.<|endoftext|>
|
33a8234c84cfcfa0d6e7e52761dc240a57c36e810ae6352c14bc2d3b1bc846f2
|
def module_js(self):
'\n This property defines (if javascript) exists for this node.\n Override this property for your own logic.\n '
return make_response(render_template('user_mappings/js/user_mappings.js', _=gettext), 200, {'Content-Type': 'application/x-javascript'})
|
This property defines (if javascript) exists for this node.
Override this property for your own logic.
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
module_js
|
Anillab/One-Minute-Pitch
| 4 |
python
|
def module_js(self):
'\n This property defines (if javascript) exists for this node.\n Override this property for your own logic.\n '
return make_response(render_template('user_mappings/js/user_mappings.js', _=gettext), 200, {'Content-Type': 'application/x-javascript'})
|
def module_js(self):
'\n This property defines (if javascript) exists for this node.\n Override this property for your own logic.\n '
return make_response(render_template('user_mappings/js/user_mappings.js', _=gettext), 200, {'Content-Type': 'application/x-javascript'})<|docstring|>This property defines (if javascript) exists for this node.
Override this property for your own logic.<|endoftext|>
|
92deb6e9f2d494eb3cedaf101eb2ae4d2d5a749121e03f84fd35049d359c27dd
|
def check_precondition(f):
'\n This function will behave as a decorator which will checks\n database connection before running view, it will also attaches\n manager,conn & template_path properties to self\n '
@wraps(f)
def wrap(*args, **kwargs):
self = args[0]
self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(kwargs['sid'])
self.conn = self.manager.connection(did=kwargs['did'])
self.template_path = 'user_mappings/sql/#{0}#'.format(self.manager.version)
return f(*args, **kwargs)
return wrap
|
This function will behave as a decorator which will checks
database connection before running view, it will also attaches
manager,conn & template_path properties to self
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
check_precondition
|
Anillab/One-Minute-Pitch
| 4 |
python
|
def check_precondition(f):
'\n This function will behave as a decorator which will checks\n database connection before running view, it will also attaches\n manager,conn & template_path properties to self\n '
@wraps(f)
def wrap(*args, **kwargs):
self = args[0]
self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(kwargs['sid'])
self.conn = self.manager.connection(did=kwargs['did'])
self.template_path = 'user_mappings/sql/#{0}#'.format(self.manager.version)
return f(*args, **kwargs)
return wrap
|
def check_precondition(f):
'\n This function will behave as a decorator which will checks\n database connection before running view, it will also attaches\n manager,conn & template_path properties to self\n '
@wraps(f)
def wrap(*args, **kwargs):
self = args[0]
self.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(kwargs['sid'])
self.conn = self.manager.connection(did=kwargs['did'])
self.template_path = 'user_mappings/sql/#{0}#'.format(self.manager.version)
return f(*args, **kwargs)
return wrap<|docstring|>This function will behave as a decorator which will checks
database connection before running view, it will also attaches
manager,conn & template_path properties to self<|endoftext|>
|
775bb1a2dcbf818bde3ca111ba02db4930e2199489f25c2fbe79b154402e4466
|
@check_precondition
def list(self, gid, sid, did, fid, fsid):
'\n This function is used to list all the user mapping nodes within that collection.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n '
sql = render_template('/'.join([self.template_path, 'properties.sql']), fsid=fsid, conn=self.conn)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
return ajax_response(response=res['rows'], status=200)
|
This function is used to list all the user mapping nodes within that collection.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: Foreign data wrapper ID
fsid: Foreign server ID
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
list
|
Anillab/One-Minute-Pitch
| 4 |
python
|
@check_precondition
def list(self, gid, sid, did, fid, fsid):
'\n This function is used to list all the user mapping nodes within that collection.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n '
sql = render_template('/'.join([self.template_path, 'properties.sql']), fsid=fsid, conn=self.conn)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
return ajax_response(response=res['rows'], status=200)
|
@check_precondition
def list(self, gid, sid, did, fid, fsid):
'\n This function is used to list all the user mapping nodes within that collection.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n '
sql = render_template('/'.join([self.template_path, 'properties.sql']), fsid=fsid, conn=self.conn)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
return ajax_response(response=res['rows'], status=200)<|docstring|>This function is used to list all the user mapping nodes within that collection.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: Foreign data wrapper ID
fsid: Foreign server ID<|endoftext|>
|
3f56abff5141d6096623496c67ef0312ba707f1f4fffce7a3bf403f71783a592
|
@check_precondition
def nodes(self, gid, sid, did, fid, fsid):
'\n This function will used to create all the child node within that collection.\n Here it will create all the user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n '
res = []
sql = render_template('/'.join([self.template_path, 'properties.sql']), fsid=fsid, conn=self.conn)
(status, r_set) = self.conn.execute_2darray(sql)
if (not status):
return internal_server_error(errormsg=r_set)
for row in r_set['rows']:
res.append(self.blueprint.generate_browser_node(row['um_oid'], fsid, row['name'], icon='icon-user_mapping'))
return make_json_response(data=res, status=200)
|
This function will used to create all the child node within that collection.
Here it will create all the user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: Foreign data wrapper ID
fsid: Foreign server ID
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
nodes
|
Anillab/One-Minute-Pitch
| 4 |
python
|
@check_precondition
def nodes(self, gid, sid, did, fid, fsid):
'\n This function will used to create all the child node within that collection.\n Here it will create all the user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n '
res = []
sql = render_template('/'.join([self.template_path, 'properties.sql']), fsid=fsid, conn=self.conn)
(status, r_set) = self.conn.execute_2darray(sql)
if (not status):
return internal_server_error(errormsg=r_set)
for row in r_set['rows']:
res.append(self.blueprint.generate_browser_node(row['um_oid'], fsid, row['name'], icon='icon-user_mapping'))
return make_json_response(data=res, status=200)
|
@check_precondition
def nodes(self, gid, sid, did, fid, fsid):
'\n This function will used to create all the child node within that collection.\n Here it will create all the user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n '
res = []
sql = render_template('/'.join([self.template_path, 'properties.sql']), fsid=fsid, conn=self.conn)
(status, r_set) = self.conn.execute_2darray(sql)
if (not status):
return internal_server_error(errormsg=r_set)
for row in r_set['rows']:
res.append(self.blueprint.generate_browser_node(row['um_oid'], fsid, row['name'], icon='icon-user_mapping'))
return make_json_response(data=res, status=200)<|docstring|>This function will used to create all the child node within that collection.
Here it will create all the user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: Foreign data wrapper ID
fsid: Foreign server ID<|endoftext|>
|
04fed26bc6f10ead5ce2931fd183581f817345f7171ad5699a81f8b3be06ca06
|
@check_precondition
def node(self, gid, sid, did, fid, fsid, umid):
'\n This function will fetch properties of user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n umid: User mapping ID\n '
sql = render_template('/'.join([self.template_path, 'properties.sql']), conn=self.conn, umid=umid)
(status, r_set) = self.conn.execute_2darray(sql)
if (not status):
return internal_server_error(errormsg=r_set)
for row in r_set['rows']:
return make_json_response(data=self.blueprint.generate_browser_node(row['um_oid'], fsid, row['name'], icon='icon-user_mapping'), status=200)
return gone(gettext('Could not find the specified user mapping.'))
|
This function will fetch properties of user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: Foreign data wrapper ID
fsid: Foreign server ID
umid: User mapping ID
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
node
|
Anillab/One-Minute-Pitch
| 4 |
python
|
@check_precondition
def node(self, gid, sid, did, fid, fsid, umid):
'\n This function will fetch properties of user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n umid: User mapping ID\n '
sql = render_template('/'.join([self.template_path, 'properties.sql']), conn=self.conn, umid=umid)
(status, r_set) = self.conn.execute_2darray(sql)
if (not status):
return internal_server_error(errormsg=r_set)
for row in r_set['rows']:
return make_json_response(data=self.blueprint.generate_browser_node(row['um_oid'], fsid, row['name'], icon='icon-user_mapping'), status=200)
return gone(gettext('Could not find the specified user mapping.'))
|
@check_precondition
def node(self, gid, sid, did, fid, fsid, umid):
'\n This function will fetch properties of user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n umid: User mapping ID\n '
sql = render_template('/'.join([self.template_path, 'properties.sql']), conn=self.conn, umid=umid)
(status, r_set) = self.conn.execute_2darray(sql)
if (not status):
return internal_server_error(errormsg=r_set)
for row in r_set['rows']:
return make_json_response(data=self.blueprint.generate_browser_node(row['um_oid'], fsid, row['name'], icon='icon-user_mapping'), status=200)
return gone(gettext('Could not find the specified user mapping.'))<|docstring|>This function will fetch properties of user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: Foreign data wrapper ID
fsid: Foreign server ID
umid: User mapping ID<|endoftext|>
|
c1b8b4e83a65c11548fae40ccd6986be41d7ad3419c8731760fbac007725b062
|
@check_precondition
def properties(self, gid, sid, did, fid, fsid, umid):
'\n This function will show the properties of the selected user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n umid: User mapping ID\n '
sql = render_template('/'.join([self.template_path, 'properties.sql']), umid=umid, conn=self.conn)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
if (len(res['rows']) == 0):
return gone(gettext('Could not find the user mapping information.'))
if (res['rows'][0]['umoptions'] is not None):
res['rows'][0]['umoptions'] = tokenize_options(res['rows'][0]['umoptions'], 'umoption', 'umvalue')
return ajax_response(response=res['rows'][0], status=200)
|
This function will show the properties of the selected user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: Foreign data wrapper ID
fsid: Foreign server ID
umid: User mapping ID
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
properties
|
Anillab/One-Minute-Pitch
| 4 |
python
|
@check_precondition
def properties(self, gid, sid, did, fid, fsid, umid):
'\n This function will show the properties of the selected user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n umid: User mapping ID\n '
sql = render_template('/'.join([self.template_path, 'properties.sql']), umid=umid, conn=self.conn)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
if (len(res['rows']) == 0):
return gone(gettext('Could not find the user mapping information.'))
if (res['rows'][0]['umoptions'] is not None):
res['rows'][0]['umoptions'] = tokenize_options(res['rows'][0]['umoptions'], 'umoption', 'umvalue')
return ajax_response(response=res['rows'][0], status=200)
|
@check_precondition
def properties(self, gid, sid, did, fid, fsid, umid):
'\n This function will show the properties of the selected user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n umid: User mapping ID\n '
sql = render_template('/'.join([self.template_path, 'properties.sql']), umid=umid, conn=self.conn)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
if (len(res['rows']) == 0):
return gone(gettext('Could not find the user mapping information.'))
if (res['rows'][0]['umoptions'] is not None):
res['rows'][0]['umoptions'] = tokenize_options(res['rows'][0]['umoptions'], 'umoption', 'umvalue')
return ajax_response(response=res['rows'][0], status=200)<|docstring|>This function will show the properties of the selected user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: Foreign data wrapper ID
fsid: Foreign server ID
umid: User mapping ID<|endoftext|>
|
4013d8645bd4b0e95738c464c55849f81df67ac5da306a66c005a121b5052de3
|
@check_precondition
def create(self, gid, sid, did, fid, fsid):
'\n This function will create the user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n '
required_args = ['name']
data = (request.form if request.form else json.loads(request.data, encoding='utf-8'))
for arg in required_args:
if (arg not in data):
return make_json_response(status=410, success=0, errormsg=gettext(('Could not find the required parameter (%s).' % arg)))
try:
sql = render_template('/'.join([self.template_path, 'properties.sql']), fserid=fsid, conn=self.conn)
(status, res1) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res1)
fdw_data = res1['rows'][0]
is_valid_options = False
if ('umoptions' in data):
(is_valid_options, data['umoptions']) = validate_options(data['umoptions'], 'umoption', 'umvalue')
sql = render_template('/'.join([self.template_path, 'create.sql']), data=data, fdwdata=fdw_data, is_valid_options=is_valid_options, conn=self.conn)
(status, res) = self.conn.execute_scalar(sql)
if (not status):
return internal_server_error(errormsg=res)
sql = render_template('/'.join([self.template_path, 'properties.sql']), fsid=fsid, data=data, conn=self.conn)
(status, r_set) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=r_set)
for row in r_set['rows']:
return jsonify(node=self.blueprint.generate_browser_node(row['um_oid'], fsid, row['name'], icon='icon-user_mapping'))
except Exception as e:
return internal_server_error(errormsg=str(e))
|
This function will create the user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: Foreign data wrapper ID
fsid: Foreign server ID
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
create
|
Anillab/One-Minute-Pitch
| 4 |
python
|
@check_precondition
def create(self, gid, sid, did, fid, fsid):
'\n This function will create the user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n '
required_args = ['name']
data = (request.form if request.form else json.loads(request.data, encoding='utf-8'))
for arg in required_args:
if (arg not in data):
return make_json_response(status=410, success=0, errormsg=gettext(('Could not find the required parameter (%s).' % arg)))
try:
sql = render_template('/'.join([self.template_path, 'properties.sql']), fserid=fsid, conn=self.conn)
(status, res1) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res1)
fdw_data = res1['rows'][0]
is_valid_options = False
if ('umoptions' in data):
(is_valid_options, data['umoptions']) = validate_options(data['umoptions'], 'umoption', 'umvalue')
sql = render_template('/'.join([self.template_path, 'create.sql']), data=data, fdwdata=fdw_data, is_valid_options=is_valid_options, conn=self.conn)
(status, res) = self.conn.execute_scalar(sql)
if (not status):
return internal_server_error(errormsg=res)
sql = render_template('/'.join([self.template_path, 'properties.sql']), fsid=fsid, data=data, conn=self.conn)
(status, r_set) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=r_set)
for row in r_set['rows']:
return jsonify(node=self.blueprint.generate_browser_node(row['um_oid'], fsid, row['name'], icon='icon-user_mapping'))
except Exception as e:
return internal_server_error(errormsg=str(e))
|
@check_precondition
def create(self, gid, sid, did, fid, fsid):
'\n This function will create the user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n '
required_args = ['name']
data = (request.form if request.form else json.loads(request.data, encoding='utf-8'))
for arg in required_args:
if (arg not in data):
return make_json_response(status=410, success=0, errormsg=gettext(('Could not find the required parameter (%s).' % arg)))
try:
sql = render_template('/'.join([self.template_path, 'properties.sql']), fserid=fsid, conn=self.conn)
(status, res1) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res1)
fdw_data = res1['rows'][0]
is_valid_options = False
if ('umoptions' in data):
(is_valid_options, data['umoptions']) = validate_options(data['umoptions'], 'umoption', 'umvalue')
sql = render_template('/'.join([self.template_path, 'create.sql']), data=data, fdwdata=fdw_data, is_valid_options=is_valid_options, conn=self.conn)
(status, res) = self.conn.execute_scalar(sql)
if (not status):
return internal_server_error(errormsg=res)
sql = render_template('/'.join([self.template_path, 'properties.sql']), fsid=fsid, data=data, conn=self.conn)
(status, r_set) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=r_set)
for row in r_set['rows']:
return jsonify(node=self.blueprint.generate_browser_node(row['um_oid'], fsid, row['name'], icon='icon-user_mapping'))
except Exception as e:
return internal_server_error(errormsg=str(e))<|docstring|>This function will create the user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: Foreign data wrapper ID
fsid: Foreign server ID<|endoftext|>
|
d5763374d34306ef1a760195fa391f34ce1490571f396fe43a7cfcfe8d417aed
|
@check_precondition
def update(self, gid, sid, did, fid, fsid, umid):
'\n This function will update the data for the selected user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n umid: User mapping ID\n '
data = (request.form if request.form else json.loads(request.data, encoding='utf-8'))
try:
(sql, name) = self.get_sql(gid, sid, data, did, fid, fsid, umid)
if (not isinstance(sql, (str, unicode))):
return sql
sql = sql.strip('\n').strip(' ')
(status, res) = self.conn.execute_scalar(sql)
if (not status):
return internal_server_error(errormsg=res)
return jsonify(node=self.blueprint.generate_browser_node(umid, fsid, name, icon=('icon-%s' % self.node_type)))
except Exception as e:
return internal_server_error(errormsg=str(e))
|
This function will update the data for the selected user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: Foreign data wrapper ID
fsid: Foreign server ID
umid: User mapping ID
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
update
|
Anillab/One-Minute-Pitch
| 4 |
python
|
@check_precondition
def update(self, gid, sid, did, fid, fsid, umid):
'\n This function will update the data for the selected user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n umid: User mapping ID\n '
data = (request.form if request.form else json.loads(request.data, encoding='utf-8'))
try:
(sql, name) = self.get_sql(gid, sid, data, did, fid, fsid, umid)
if (not isinstance(sql, (str, unicode))):
return sql
sql = sql.strip('\n').strip(' ')
(status, res) = self.conn.execute_scalar(sql)
if (not status):
return internal_server_error(errormsg=res)
return jsonify(node=self.blueprint.generate_browser_node(umid, fsid, name, icon=('icon-%s' % self.node_type)))
except Exception as e:
return internal_server_error(errormsg=str(e))
|
@check_precondition
def update(self, gid, sid, did, fid, fsid, umid):
'\n This function will update the data for the selected user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n umid: User mapping ID\n '
data = (request.form if request.form else json.loads(request.data, encoding='utf-8'))
try:
(sql, name) = self.get_sql(gid, sid, data, did, fid, fsid, umid)
if (not isinstance(sql, (str, unicode))):
return sql
sql = sql.strip('\n').strip(' ')
(status, res) = self.conn.execute_scalar(sql)
if (not status):
return internal_server_error(errormsg=res)
return jsonify(node=self.blueprint.generate_browser_node(umid, fsid, name, icon=('icon-%s' % self.node_type)))
except Exception as e:
return internal_server_error(errormsg=str(e))<|docstring|>This function will update the data for the selected user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: Foreign data wrapper ID
fsid: Foreign server ID
umid: User mapping ID<|endoftext|>
|
1ea67583b3e887e78bd01491bb50e537681ffe29d9daff0ff68387186fa457f8
|
@check_precondition
def delete(self, gid, sid, did, fid, fsid, umid):
'\n This function will delete the selected user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: foreign data wrapper ID\n fsid: foreign server ID\n umid: User mapping ID\n '
if (self.cmd == 'delete'):
cascade = True
else:
cascade = False
try:
sql = render_template('/'.join([self.template_path, 'delete.sql']), fsid=fsid, conn=self.conn)
(status, name) = self.conn.execute_scalar(sql)
if (not status):
return internal_server_error(errormsg=name)
if (name is None):
return make_json_response(status=410, success=0, errormsg=gettext('Error: Object not found.'), info=gettext('The specified foreign server could not be found.\n'))
sql = render_template('/'.join([self.template_path, 'properties.sql']), umid=umid, conn=self.conn)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
if (not res['rows']):
return make_json_response(status=410, success=0, errormsg=gettext('The specified user mapping could not be found.\n'))
data = res['rows'][0]
sql = render_template('/'.join([self.template_path, 'delete.sql']), data=data, name=name, cascade=cascade, conn=self.conn)
(status, res) = self.conn.execute_scalar(sql)
if (not status):
return internal_server_error(errormsg=res)
return make_json_response(success=1, info=gettext('User Mapping dropped'), data={'id': umid, 'fsid': fsid, 'fid': fid, 'did': did, 'sid': sid, 'gid': gid})
except Exception as e:
return internal_server_error(errormsg=str(e))
|
This function will delete the selected user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: foreign data wrapper ID
fsid: foreign server ID
umid: User mapping ID
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
delete
|
Anillab/One-Minute-Pitch
| 4 |
python
|
@check_precondition
def delete(self, gid, sid, did, fid, fsid, umid):
'\n This function will delete the selected user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: foreign data wrapper ID\n fsid: foreign server ID\n umid: User mapping ID\n '
if (self.cmd == 'delete'):
cascade = True
else:
cascade = False
try:
sql = render_template('/'.join([self.template_path, 'delete.sql']), fsid=fsid, conn=self.conn)
(status, name) = self.conn.execute_scalar(sql)
if (not status):
return internal_server_error(errormsg=name)
if (name is None):
return make_json_response(status=410, success=0, errormsg=gettext('Error: Object not found.'), info=gettext('The specified foreign server could not be found.\n'))
sql = render_template('/'.join([self.template_path, 'properties.sql']), umid=umid, conn=self.conn)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
if (not res['rows']):
return make_json_response(status=410, success=0, errormsg=gettext('The specified user mapping could not be found.\n'))
data = res['rows'][0]
sql = render_template('/'.join([self.template_path, 'delete.sql']), data=data, name=name, cascade=cascade, conn=self.conn)
(status, res) = self.conn.execute_scalar(sql)
if (not status):
return internal_server_error(errormsg=res)
return make_json_response(success=1, info=gettext('User Mapping dropped'), data={'id': umid, 'fsid': fsid, 'fid': fid, 'did': did, 'sid': sid, 'gid': gid})
except Exception as e:
return internal_server_error(errormsg=str(e))
|
@check_precondition
def delete(self, gid, sid, did, fid, fsid, umid):
'\n This function will delete the selected user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: foreign data wrapper ID\n fsid: foreign server ID\n umid: User mapping ID\n '
if (self.cmd == 'delete'):
cascade = True
else:
cascade = False
try:
sql = render_template('/'.join([self.template_path, 'delete.sql']), fsid=fsid, conn=self.conn)
(status, name) = self.conn.execute_scalar(sql)
if (not status):
return internal_server_error(errormsg=name)
if (name is None):
return make_json_response(status=410, success=0, errormsg=gettext('Error: Object not found.'), info=gettext('The specified foreign server could not be found.\n'))
sql = render_template('/'.join([self.template_path, 'properties.sql']), umid=umid, conn=self.conn)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
if (not res['rows']):
return make_json_response(status=410, success=0, errormsg=gettext('The specified user mapping could not be found.\n'))
data = res['rows'][0]
sql = render_template('/'.join([self.template_path, 'delete.sql']), data=data, name=name, cascade=cascade, conn=self.conn)
(status, res) = self.conn.execute_scalar(sql)
if (not status):
return internal_server_error(errormsg=res)
return make_json_response(success=1, info=gettext('User Mapping dropped'), data={'id': umid, 'fsid': fsid, 'fid': fid, 'did': did, 'sid': sid, 'gid': gid})
except Exception as e:
return internal_server_error(errormsg=str(e))<|docstring|>This function will delete the selected user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: foreign data wrapper ID
fsid: foreign server ID
umid: User mapping ID<|endoftext|>
|
75e47ec24d34c62970dbd0d61c858904e294290143e0a69046bc274015a3e456
|
@check_precondition
def msql(self, gid, sid, did, fid, fsid, umid=None):
'\n This function is used to return modified SQL for the selected user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: foreign data wrapper ID\n fsid: foreign server ID\n umid: User mapping ID\n '
data = {}
for (k, v) in request.args.items():
try:
data[k] = json.loads(v, encoding='utf-8')
except ValueError:
data[k] = v
try:
(sql, name) = self.get_sql(gid, sid, data, did, fid, fsid, umid)
if (not isinstance(sql, (str, unicode))):
return sql
if (sql == ''):
sql = '--modified SQL'
return make_json_response(data=sql, status=200)
except Exception as e:
return internal_server_error(errormsg=str(e))
|
This function is used to return modified SQL for the selected user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: foreign data wrapper ID
fsid: foreign server ID
umid: User mapping ID
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
msql
|
Anillab/One-Minute-Pitch
| 4 |
python
|
@check_precondition
def msql(self, gid, sid, did, fid, fsid, umid=None):
'\n This function is used to return modified SQL for the selected user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: foreign data wrapper ID\n fsid: foreign server ID\n umid: User mapping ID\n '
data = {}
for (k, v) in request.args.items():
try:
data[k] = json.loads(v, encoding='utf-8')
except ValueError:
data[k] = v
try:
(sql, name) = self.get_sql(gid, sid, data, did, fid, fsid, umid)
if (not isinstance(sql, (str, unicode))):
return sql
if (sql == ):
sql = '--modified SQL'
return make_json_response(data=sql, status=200)
except Exception as e:
return internal_server_error(errormsg=str(e))
|
@check_precondition
def msql(self, gid, sid, did, fid, fsid, umid=None):
'\n This function is used to return modified SQL for the selected user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: foreign data wrapper ID\n fsid: foreign server ID\n umid: User mapping ID\n '
data = {}
for (k, v) in request.args.items():
try:
data[k] = json.loads(v, encoding='utf-8')
except ValueError:
data[k] = v
try:
(sql, name) = self.get_sql(gid, sid, data, did, fid, fsid, umid)
if (not isinstance(sql, (str, unicode))):
return sql
if (sql == ):
sql = '--modified SQL'
return make_json_response(data=sql, status=200)
except Exception as e:
return internal_server_error(errormsg=str(e))<|docstring|>This function is used to return modified SQL for the selected user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: foreign data wrapper ID
fsid: foreign server ID
umid: User mapping ID<|endoftext|>
|
96d3f4070d348c337f3ad799d8b899dbc5204b685c3b55aef9b3c4382330b0f7
|
def get_sql(self, gid, sid, data, did, fid, fsid, umid=None):
'\n This function will generate sql from model data.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n data: Contains the data of the selected user mapping node\n fid: foreign data wrapper ID\n fsid: foreign server ID\n umid: User mapping ID\n '
required_args = ['name']
if (umid is not None):
sql = render_template('/'.join([self.template_path, 'properties.sql']), umid=umid, conn=self.conn)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
if (len(res['rows']) == 0):
return gone(gettext('Could not find the user mapping information.'))
if (res['rows'][0]['umoptions'] is not None):
res['rows'][0]['umoptions'] = tokenize_options(res['rows'][0]['umoptions'], 'umoption', 'umvalue')
old_data = res['rows'][0]
sql = render_template('/'.join([self.template_path, 'properties.sql']), fserid=fsid, conn=self.conn)
(status, res1) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res1)
fdw_data = res1['rows'][0]
for arg in required_args:
if (arg not in data):
data[arg] = old_data[arg]
is_valid_added_options = is_valid_changed_options = False
if (('umoptions' in data) and ('added' in data['umoptions'])):
(is_valid_added_options, data['umoptions']['added']) = validate_options(data['umoptions']['added'], 'umoption', 'umvalue')
if (('umoptions' in data) and ('changed' in data['umoptions'])):
(is_valid_changed_options, data['umoptions']['changed']) = validate_options(data['umoptions']['changed'], 'umoption', 'umvalue')
sql = render_template('/'.join([self.template_path, 'update.sql']), data=data, o_data=old_data, is_valid_added_options=is_valid_added_options, is_valid_changed_options=is_valid_changed_options, fdwdata=fdw_data, conn=self.conn)
return (sql, (data['name'] if ('name' in data) else old_data['name']))
else:
sql = render_template('/'.join([self.template_path, 'properties.sql']), fserid=fsid, conn=self.conn)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
fdw_data = res['rows'][0]
is_valid_options = False
if ('umoptions' in data):
(is_valid_options, data['umoptions']) = validate_options(data['umoptions'], 'umoption', 'umvalue')
sql = render_template('/'.join([self.template_path, 'create.sql']), data=data, fdwdata=fdw_data, is_valid_options=is_valid_options, conn=self.conn)
sql += '\n'
return (sql, data['name'])
|
This function will generate sql from model data.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
data: Contains the data of the selected user mapping node
fid: foreign data wrapper ID
fsid: foreign server ID
umid: User mapping ID
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
get_sql
|
Anillab/One-Minute-Pitch
| 4 |
python
|
def get_sql(self, gid, sid, data, did, fid, fsid, umid=None):
'\n This function will generate sql from model data.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n data: Contains the data of the selected user mapping node\n fid: foreign data wrapper ID\n fsid: foreign server ID\n umid: User mapping ID\n '
required_args = ['name']
if (umid is not None):
sql = render_template('/'.join([self.template_path, 'properties.sql']), umid=umid, conn=self.conn)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
if (len(res['rows']) == 0):
return gone(gettext('Could not find the user mapping information.'))
if (res['rows'][0]['umoptions'] is not None):
res['rows'][0]['umoptions'] = tokenize_options(res['rows'][0]['umoptions'], 'umoption', 'umvalue')
old_data = res['rows'][0]
sql = render_template('/'.join([self.template_path, 'properties.sql']), fserid=fsid, conn=self.conn)
(status, res1) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res1)
fdw_data = res1['rows'][0]
for arg in required_args:
if (arg not in data):
data[arg] = old_data[arg]
is_valid_added_options = is_valid_changed_options = False
if (('umoptions' in data) and ('added' in data['umoptions'])):
(is_valid_added_options, data['umoptions']['added']) = validate_options(data['umoptions']['added'], 'umoption', 'umvalue')
if (('umoptions' in data) and ('changed' in data['umoptions'])):
(is_valid_changed_options, data['umoptions']['changed']) = validate_options(data['umoptions']['changed'], 'umoption', 'umvalue')
sql = render_template('/'.join([self.template_path, 'update.sql']), data=data, o_data=old_data, is_valid_added_options=is_valid_added_options, is_valid_changed_options=is_valid_changed_options, fdwdata=fdw_data, conn=self.conn)
return (sql, (data['name'] if ('name' in data) else old_data['name']))
else:
sql = render_template('/'.join([self.template_path, 'properties.sql']), fserid=fsid, conn=self.conn)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
fdw_data = res['rows'][0]
is_valid_options = False
if ('umoptions' in data):
(is_valid_options, data['umoptions']) = validate_options(data['umoptions'], 'umoption', 'umvalue')
sql = render_template('/'.join([self.template_path, 'create.sql']), data=data, fdwdata=fdw_data, is_valid_options=is_valid_options, conn=self.conn)
sql += '\n'
return (sql, data['name'])
|
def get_sql(self, gid, sid, data, did, fid, fsid, umid=None):
'\n This function will generate sql from model data.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n data: Contains the data of the selected user mapping node\n fid: foreign data wrapper ID\n fsid: foreign server ID\n umid: User mapping ID\n '
required_args = ['name']
if (umid is not None):
sql = render_template('/'.join([self.template_path, 'properties.sql']), umid=umid, conn=self.conn)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
if (len(res['rows']) == 0):
return gone(gettext('Could not find the user mapping information.'))
if (res['rows'][0]['umoptions'] is not None):
res['rows'][0]['umoptions'] = tokenize_options(res['rows'][0]['umoptions'], 'umoption', 'umvalue')
old_data = res['rows'][0]
sql = render_template('/'.join([self.template_path, 'properties.sql']), fserid=fsid, conn=self.conn)
(status, res1) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res1)
fdw_data = res1['rows'][0]
for arg in required_args:
if (arg not in data):
data[arg] = old_data[arg]
is_valid_added_options = is_valid_changed_options = False
if (('umoptions' in data) and ('added' in data['umoptions'])):
(is_valid_added_options, data['umoptions']['added']) = validate_options(data['umoptions']['added'], 'umoption', 'umvalue')
if (('umoptions' in data) and ('changed' in data['umoptions'])):
(is_valid_changed_options, data['umoptions']['changed']) = validate_options(data['umoptions']['changed'], 'umoption', 'umvalue')
sql = render_template('/'.join([self.template_path, 'update.sql']), data=data, o_data=old_data, is_valid_added_options=is_valid_added_options, is_valid_changed_options=is_valid_changed_options, fdwdata=fdw_data, conn=self.conn)
return (sql, (data['name'] if ('name' in data) else old_data['name']))
else:
sql = render_template('/'.join([self.template_path, 'properties.sql']), fserid=fsid, conn=self.conn)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
fdw_data = res['rows'][0]
is_valid_options = False
if ('umoptions' in data):
(is_valid_options, data['umoptions']) = validate_options(data['umoptions'], 'umoption', 'umvalue')
sql = render_template('/'.join([self.template_path, 'create.sql']), data=data, fdwdata=fdw_data, is_valid_options=is_valid_options, conn=self.conn)
sql += '\n'
return (sql, data['name'])<|docstring|>This function will generate sql from model data.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
data: Contains the data of the selected user mapping node
fid: foreign data wrapper ID
fsid: foreign server ID
umid: User mapping ID<|endoftext|>
|
e50be2aca60a4e9e49e46f1d73bb3bc7b5db92ea6b4f5596e807bbee931cf363
|
@check_precondition
def sql(self, gid, sid, did, fid, fsid, umid):
'\n This function will generate sql to show it in sql pane for the selected user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n umid: User mapping ID\n '
sql = render_template('/'.join([self.template_path, 'properties.sql']), umid=umid, conn=self.conn)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
if (len(res['rows']) == 0):
return gone(gettext('Could not find the user mapping information.'))
is_valid_options = False
if (res['rows'][0]['umoptions'] is not None):
res['rows'][0]['umoptions'] = tokenize_options(res['rows'][0]['umoptions'], 'umoption', 'umvalue')
if (len(res['rows'][0]['umoptions']) > 0):
is_valid_options = True
sql = render_template('/'.join([self.template_path, 'properties.sql']), fserid=fsid, conn=self.conn)
(status, res1) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res1)
fdw_data = res1['rows'][0]
sql = ''
sql = render_template('/'.join([self.template_path, 'create.sql']), data=res['rows'][0], fdwdata=fdw_data, is_valid_options=is_valid_options, conn=self.conn)
sql += '\n'
sql_header = u'-- User Mapping : {0}\n\n-- DROP USER MAPPING FOR {0} SERVER {1}\n\n'.format(res['rows'][0]['name'], fdw_data['name'])
sql = (sql_header + sql)
return ajax_response(response=sql.strip('\n'))
|
This function will generate sql to show it in sql pane for the selected user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: Foreign data wrapper ID
fsid: Foreign server ID
umid: User mapping ID
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
sql
|
Anillab/One-Minute-Pitch
| 4 |
python
|
@check_precondition
def sql(self, gid, sid, did, fid, fsid, umid):
'\n This function will generate sql to show it in sql pane for the selected user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n umid: User mapping ID\n '
sql = render_template('/'.join([self.template_path, 'properties.sql']), umid=umid, conn=self.conn)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
if (len(res['rows']) == 0):
return gone(gettext('Could not find the user mapping information.'))
is_valid_options = False
if (res['rows'][0]['umoptions'] is not None):
res['rows'][0]['umoptions'] = tokenize_options(res['rows'][0]['umoptions'], 'umoption', 'umvalue')
if (len(res['rows'][0]['umoptions']) > 0):
is_valid_options = True
sql = render_template('/'.join([self.template_path, 'properties.sql']), fserid=fsid, conn=self.conn)
(status, res1) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res1)
fdw_data = res1['rows'][0]
sql =
sql = render_template('/'.join([self.template_path, 'create.sql']), data=res['rows'][0], fdwdata=fdw_data, is_valid_options=is_valid_options, conn=self.conn)
sql += '\n'
sql_header = u'-- User Mapping : {0}\n\n-- DROP USER MAPPING FOR {0} SERVER {1}\n\n'.format(res['rows'][0]['name'], fdw_data['name'])
sql = (sql_header + sql)
return ajax_response(response=sql.strip('\n'))
|
@check_precondition
def sql(self, gid, sid, did, fid, fsid, umid):
'\n This function will generate sql to show it in sql pane for the selected user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign data wrapper ID\n fsid: Foreign server ID\n umid: User mapping ID\n '
sql = render_template('/'.join([self.template_path, 'properties.sql']), umid=umid, conn=self.conn)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
if (len(res['rows']) == 0):
return gone(gettext('Could not find the user mapping information.'))
is_valid_options = False
if (res['rows'][0]['umoptions'] is not None):
res['rows'][0]['umoptions'] = tokenize_options(res['rows'][0]['umoptions'], 'umoption', 'umvalue')
if (len(res['rows'][0]['umoptions']) > 0):
is_valid_options = True
sql = render_template('/'.join([self.template_path, 'properties.sql']), fserid=fsid, conn=self.conn)
(status, res1) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res1)
fdw_data = res1['rows'][0]
sql =
sql = render_template('/'.join([self.template_path, 'create.sql']), data=res['rows'][0], fdwdata=fdw_data, is_valid_options=is_valid_options, conn=self.conn)
sql += '\n'
sql_header = u'-- User Mapping : {0}\n\n-- DROP USER MAPPING FOR {0} SERVER {1}\n\n'.format(res['rows'][0]['name'], fdw_data['name'])
sql = (sql_header + sql)
return ajax_response(response=sql.strip('\n'))<|docstring|>This function will generate sql to show it in sql pane for the selected user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: Foreign data wrapper ID
fsid: Foreign server ID
umid: User mapping ID<|endoftext|>
|
979b1fbe9c37405f761a2581af37b3ed32c918515a20f7af6a8eebf4a34918ba
|
@check_precondition
def dependents(self, gid, sid, did, fid, fsid, umid):
'\n This function get the dependents and return ajax response\n for the user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: foreign data wrapper ID\n fsid: Foreign server ID\n umid: user mapping ID\n '
dependents_result = self.get_dependents(self.conn, umid)
return ajax_response(response=dependents_result, status=200)
|
This function get the dependents and return ajax response
for the user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: foreign data wrapper ID
fsid: Foreign server ID
umid: user mapping ID
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
dependents
|
Anillab/One-Minute-Pitch
| 4 |
python
|
@check_precondition
def dependents(self, gid, sid, did, fid, fsid, umid):
'\n This function get the dependents and return ajax response\n for the user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: foreign data wrapper ID\n fsid: Foreign server ID\n umid: user mapping ID\n '
dependents_result = self.get_dependents(self.conn, umid)
return ajax_response(response=dependents_result, status=200)
|
@check_precondition
def dependents(self, gid, sid, did, fid, fsid, umid):
'\n This function get the dependents and return ajax response\n for the user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: foreign data wrapper ID\n fsid: Foreign server ID\n umid: user mapping ID\n '
dependents_result = self.get_dependents(self.conn, umid)
return ajax_response(response=dependents_result, status=200)<|docstring|>This function get the dependents and return ajax response
for the user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: foreign data wrapper ID
fsid: Foreign server ID
umid: user mapping ID<|endoftext|>
|
d15152dfef4b3bebc9ec66b9d0b32c22ff5078f29d37b6797bf9a79605d0e29d
|
@check_precondition
def dependencies(self, gid, sid, did, fid, fsid, umid):
'\n This function get the dependencies and return ajax response\n for the user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign Data Wrapper ID\n fsid: Foreign server ID\n umid: user mapping ID\n '
dependencies_result = self.get_dependencies(self.conn, umid)
return ajax_response(response=dependencies_result, status=200)
|
This function get the dependencies and return ajax response
for the user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: Foreign Data Wrapper ID
fsid: Foreign server ID
umid: user mapping ID
|
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/foreign_data_wrappers/foreign_servers/user_mapping/__init__.py
|
dependencies
|
Anillab/One-Minute-Pitch
| 4 |
python
|
@check_precondition
def dependencies(self, gid, sid, did, fid, fsid, umid):
'\n This function get the dependencies and return ajax response\n for the user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign Data Wrapper ID\n fsid: Foreign server ID\n umid: user mapping ID\n '
dependencies_result = self.get_dependencies(self.conn, umid)
return ajax_response(response=dependencies_result, status=200)
|
@check_precondition
def dependencies(self, gid, sid, did, fid, fsid, umid):
'\n This function get the dependencies and return ajax response\n for the user mapping node.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n fid: Foreign Data Wrapper ID\n fsid: Foreign server ID\n umid: user mapping ID\n '
dependencies_result = self.get_dependencies(self.conn, umid)
return ajax_response(response=dependencies_result, status=200)<|docstring|>This function get the dependencies and return ajax response
for the user mapping node.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
fid: Foreign Data Wrapper ID
fsid: Foreign server ID
umid: user mapping ID<|endoftext|>
|
23f8288e5c754ba1a0686438fd2a0c622d7a70feae380a98e21154f40b997ed2
|
def __add__(self, other):
'operator.add as: a = x + y or a = a + i\n Here __add__ will return a new object copy after operation. \n :param other: An iterable as dict, Xunitrpt, et.\n :return: A new object of result Xunitrpt type\n '
z = Xunitrpt()
z.case_dict = self.case_dict.copy()
z.extend(other)
return z
|
operator.add as: a = x + y or a = a + i
Here __add__ will return a new object copy after operation.
:param other: An iterable as dict, Xunitrpt, et.
:return: A new object of result Xunitrpt type
|
src/cistat/model/xunit_report.py
|
__add__
|
maxwu/cistat
| 1 |
python
|
def __add__(self, other):
'operator.add as: a = x + y or a = a + i\n Here __add__ will return a new object copy after operation. \n :param other: An iterable as dict, Xunitrpt, et.\n :return: A new object of result Xunitrpt type\n '
z = Xunitrpt()
z.case_dict = self.case_dict.copy()
z.extend(other)
return z
|
def __add__(self, other):
'operator.add as: a = x + y or a = a + i\n Here __add__ will return a new object copy after operation. \n :param other: An iterable as dict, Xunitrpt, et.\n :return: A new object of result Xunitrpt type\n '
z = Xunitrpt()
z.case_dict = self.case_dict.copy()
z.extend(other)
return z<|docstring|>operator.add as: a = x + y or a = a + i
Here __add__ will return a new object copy after operation.
:param other: An iterable as dict, Xunitrpt, et.
:return: A new object of result Xunitrpt type<|endoftext|>
|
5fede6cee1c86530117c586a52e6bece03865498db21fa070ea435b8d1fa5882
|
def __iadd__(self, other):
' operator.idd as: a += i\n :param other: An iterable as dict, Xunitrpt, et.\n :return: The original operand after updating with data from other.\n '
return self.extend(other)
|
operator.idd as: a += i
:param other: An iterable as dict, Xunitrpt, et.
:return: The original operand after updating with data from other.
|
src/cistat/model/xunit_report.py
|
__iadd__
|
maxwu/cistat
| 1 |
python
|
def __iadd__(self, other):
' operator.idd as: a += i\n :param other: An iterable as dict, Xunitrpt, et.\n :return: The original operand after updating with data from other.\n '
return self.extend(other)
|
def __iadd__(self, other):
' operator.idd as: a += i\n :param other: An iterable as dict, Xunitrpt, et.\n :return: The original operand after updating with data from other.\n '
return self.extend(other)<|docstring|>operator.idd as: a += i
:param other: An iterable as dict, Xunitrpt, et.
:return: The original operand after updating with data from other.<|endoftext|>
|
574496aab2db237b2b5c0528df60b3570595992e615f37c2c105475ab7ff8515
|
def accumulate_xunit_str(self, xunit=None):
' Update data in given XUnit str to current XUnitReport Object\n If supplied with malformed str or None, silently do nothing but return itself.\n :param xunit: XUnit in a string\n :return: XunitReport Object itself after the accumulation\n '
if ((not xunit) or (not Xunitrpt.is_xunit_report(xunit))):
return self
root = ET.fromstring(xunit)
for e in root.iter('testcase'):
tcname = ((e.get('classname', 'UnknownClass') + '.') + e.get('name', 'UnknownTest'))
if (tcname not in self.case_dict):
self[tcname] = Xunitrpt.DEFAULT_DICT.copy()
self[tcname]['sum'] += 1
self[tcname]['time'] += float(e.get('time', 0))
tags = [child.tag for child in e]
if (('failure' in tags) or ('error' in tags)):
self[tcname]['fail'] += 1
elif ('skipped' in tags):
self[tcname]['skip'] += 1
else:
self[tcname]['pass'] += 1
self.cal_rate(tcname)
return self
|
Update data in given XUnit str to current XUnitReport Object
If supplied with malformed str or None, silently do nothing but return itself.
:param xunit: XUnit in a string
:return: XunitReport Object itself after the accumulation
|
src/cistat/model/xunit_report.py
|
accumulate_xunit_str
|
maxwu/cistat
| 1 |
python
|
def accumulate_xunit_str(self, xunit=None):
' Update data in given XUnit str to current XUnitReport Object\n If supplied with malformed str or None, silently do nothing but return itself.\n :param xunit: XUnit in a string\n :return: XunitReport Object itself after the accumulation\n '
if ((not xunit) or (not Xunitrpt.is_xunit_report(xunit))):
return self
root = ET.fromstring(xunit)
for e in root.iter('testcase'):
tcname = ((e.get('classname', 'UnknownClass') + '.') + e.get('name', 'UnknownTest'))
if (tcname not in self.case_dict):
self[tcname] = Xunitrpt.DEFAULT_DICT.copy()
self[tcname]['sum'] += 1
self[tcname]['time'] += float(e.get('time', 0))
tags = [child.tag for child in e]
if (('failure' in tags) or ('error' in tags)):
self[tcname]['fail'] += 1
elif ('skipped' in tags):
self[tcname]['skip'] += 1
else:
self[tcname]['pass'] += 1
self.cal_rate(tcname)
return self
|
def accumulate_xunit_str(self, xunit=None):
' Update data in given XUnit str to current XUnitReport Object\n If supplied with malformed str or None, silently do nothing but return itself.\n :param xunit: XUnit in a string\n :return: XunitReport Object itself after the accumulation\n '
if ((not xunit) or (not Xunitrpt.is_xunit_report(xunit))):
return self
root = ET.fromstring(xunit)
for e in root.iter('testcase'):
tcname = ((e.get('classname', 'UnknownClass') + '.') + e.get('name', 'UnknownTest'))
if (tcname not in self.case_dict):
self[tcname] = Xunitrpt.DEFAULT_DICT.copy()
self[tcname]['sum'] += 1
self[tcname]['time'] += float(e.get('time', 0))
tags = [child.tag for child in e]
if (('failure' in tags) or ('error' in tags)):
self[tcname]['fail'] += 1
elif ('skipped' in tags):
self[tcname]['skip'] += 1
else:
self[tcname]['pass'] += 1
self.cal_rate(tcname)
return self<|docstring|>Update data in given XUnit str to current XUnitReport Object
If supplied with malformed str or None, silently do nothing but return itself.
:param xunit: XUnit in a string
:return: XunitReport Object itself after the accumulation<|endoftext|>
|
c3943e0d8dafdc8c1c074d3d57e87f08cc1cc0be273619834e4589c195954ec1
|
def get_scatter_roi(self, title='CIStat', sub_title='Test ROI'):
' Return chart object to present ROI of each test class\n Here it is called Test ROI, not class ROI. Because a new feature is under primary scoping to allow case \n statistics being aggregated at any given level. Which means folks can check which package or parent package\n is consuming the most or producing the most. Users can select the depth of aggregation.\n \n Currently the ROI is calculated by:\n Pass Rate: The height\n Case Number: The scatter symbol size\n - Symbol size represents the cost\n - In future, cost shall combine case number and test time.\n E.g. cost = a/(b/time + c/num)\n Label: Just distribute the labels evenly on X-axis\n '
names = self.keys()
chart = Echart(title, sub_title)
roi_ls = [[i, self[x]['rate'], self[x]['sum'], Xunitrpt.get_case_shortname(x), x] for (i, x) in enumerate(names)]
max_case_num = sorted(roi_ls, key=operator.itemgetter(2), reverse=True)[0][2]
logger.debug('max case num is {}'.format(max_case_num))
__MAX_RADIUS = 120
for x in roi_ls:
chart.use(Scatter(x[4], [x[:3]], symbolSize=((x[2] * __MAX_RADIUS) / max_case_num)))
chart.use(Axis('category', 'bottom', data=[x[3] for x in roi_ls]))
chart.use(Axis('value', 'left', data=[((i + 1) * 0.1) for i in range(12)]))
return chart
|
Return chart object to present ROI of each test class
Here it is called Test ROI, not class ROI. Because a new feature is under primary scoping to allow case
statistics being aggregated at any given level. Which means folks can check which package or parent package
is consuming the most or producing the most. Users can select the depth of aggregation.
Currently the ROI is calculated by:
Pass Rate: The height
Case Number: The scatter symbol size
- Symbol size represents the cost
- In future, cost shall combine case number and test time.
E.g. cost = a/(b/time + c/num)
Label: Just distribute the labels evenly on X-axis
|
src/cistat/model/xunit_report.py
|
get_scatter_roi
|
maxwu/cistat
| 1 |
python
|
def get_scatter_roi(self, title='CIStat', sub_title='Test ROI'):
' Return chart object to present ROI of each test class\n Here it is called Test ROI, not class ROI. Because a new feature is under primary scoping to allow case \n statistics being aggregated at any given level. Which means folks can check which package or parent package\n is consuming the most or producing the most. Users can select the depth of aggregation.\n \n Currently the ROI is calculated by:\n Pass Rate: The height\n Case Number: The scatter symbol size\n - Symbol size represents the cost\n - In future, cost shall combine case number and test time.\n E.g. cost = a/(b/time + c/num)\n Label: Just distribute the labels evenly on X-axis\n '
names = self.keys()
chart = Echart(title, sub_title)
roi_ls = [[i, self[x]['rate'], self[x]['sum'], Xunitrpt.get_case_shortname(x), x] for (i, x) in enumerate(names)]
max_case_num = sorted(roi_ls, key=operator.itemgetter(2), reverse=True)[0][2]
logger.debug('max case num is {}'.format(max_case_num))
__MAX_RADIUS = 120
for x in roi_ls:
chart.use(Scatter(x[4], [x[:3]], symbolSize=((x[2] * __MAX_RADIUS) / max_case_num)))
chart.use(Axis('category', 'bottom', data=[x[3] for x in roi_ls]))
chart.use(Axis('value', 'left', data=[((i + 1) * 0.1) for i in range(12)]))
return chart
|
def get_scatter_roi(self, title='CIStat', sub_title='Test ROI'):
' Return chart object to present ROI of each test class\n Here it is called Test ROI, not class ROI. Because a new feature is under primary scoping to allow case \n statistics being aggregated at any given level. Which means folks can check which package or parent package\n is consuming the most or producing the most. Users can select the depth of aggregation.\n \n Currently the ROI is calculated by:\n Pass Rate: The height\n Case Number: The scatter symbol size\n - Symbol size represents the cost\n - In future, cost shall combine case number and test time.\n E.g. cost = a/(b/time + c/num)\n Label: Just distribute the labels evenly on X-axis\n '
names = self.keys()
chart = Echart(title, sub_title)
roi_ls = [[i, self[x]['rate'], self[x]['sum'], Xunitrpt.get_case_shortname(x), x] for (i, x) in enumerate(names)]
max_case_num = sorted(roi_ls, key=operator.itemgetter(2), reverse=True)[0][2]
logger.debug('max case num is {}'.format(max_case_num))
__MAX_RADIUS = 120
for x in roi_ls:
chart.use(Scatter(x[4], [x[:3]], symbolSize=((x[2] * __MAX_RADIUS) / max_case_num)))
chart.use(Axis('category', 'bottom', data=[x[3] for x in roi_ls]))
chart.use(Axis('value', 'left', data=[((i + 1) * 0.1) for i in range(12)]))
return chart<|docstring|>Return chart object to present ROI of each test class
Here it is called Test ROI, not class ROI. Because a new feature is under primary scoping to allow case
statistics being aggregated at any given level. Which means folks can check which package or parent package
is consuming the most or producing the most. Users can select the depth of aggregation.
Currently the ROI is calculated by:
Pass Rate: The height
Case Number: The scatter symbol size
- Symbol size represents the cost
- In future, cost shall combine case number and test time.
E.g. cost = a/(b/time + c/num)
Label: Just distribute the labels evenly on X-axis<|endoftext|>
|
c931d4f9a53982302640777dbacd42a812bf4e58067a20a7d20164a627b2c8c4
|
def get_class_rpt(self):
' Generate Class level statistics in Xunitrpt type.\n :return: Xunitrpt object on classes\n '
clsrpt = Xunitrpt()
for (k, v) in self:
clsrpt += {Xunitrpt.get_class_name(k): v}.iteritems()
return clsrpt
|
Generate Class level statistics in Xunitrpt type.
:return: Xunitrpt object on classes
|
src/cistat/model/xunit_report.py
|
get_class_rpt
|
maxwu/cistat
| 1 |
python
|
def get_class_rpt(self):
' Generate Class level statistics in Xunitrpt type.\n :return: Xunitrpt object on classes\n '
clsrpt = Xunitrpt()
for (k, v) in self:
clsrpt += {Xunitrpt.get_class_name(k): v}.iteritems()
return clsrpt
|
def get_class_rpt(self):
' Generate Class level statistics in Xunitrpt type.\n :return: Xunitrpt object on classes\n '
clsrpt = Xunitrpt()
for (k, v) in self:
clsrpt += {Xunitrpt.get_class_name(k): v}.iteritems()
return clsrpt<|docstring|>Generate Class level statistics in Xunitrpt type.
:return: Xunitrpt object on classes<|endoftext|>
|
9d277fa3df71ee4abad95345c181c23e711de44ae52e31c14a95b283d21af182
|
def get_variable_parent_name(var):
'Get the name of the parent if it exists or return the variable name otherwise.'
if (hasattr(var, 'parent') and (var.parent is not None)):
return var.parent.name
else:
return var.name
|
Get the name of the parent if it exists or return the variable name otherwise.
|
src/empirical_fire_modelling/cache/hashing.py
|
get_variable_parent_name
|
akuhnregnier/empirical-fire-modelling
| 0 |
python
|
def get_variable_parent_name(var):
if (hasattr(var, 'parent') and (var.parent is not None)):
return var.parent.name
else:
return var.name
|
def get_variable_parent_name(var):
if (hasattr(var, 'parent') and (var.parent is not None)):
return var.parent.name
else:
return var.name<|docstring|>Get the name of the parent if it exists or return the variable name otherwise.<|endoftext|>
|
92ca9825c3a93373a7e4e23844c6a7da87b0f3ca04e97112398cc113e04a526b
|
def as_dict(self):
'Return the flat dictionary as a dictionary.\n\n :rtype: dict\n\n '
dict_out = {}
for key in self._values.keys():
value = self._values[key]
if isinstance(value, FlatDict):
if (value.former_type == list):
dict_out[key] = [v for (k, v) in sorted(value.items())]
pass
elif (value.former_type == tuple):
dict_out[key] = tuple((v for (k, v) in sorted(value.items())))
pass
elif (value.former_type == dict):
dict_out[key] = value.as_dict()
else:
dict_out[key] = value
return dict_out
|
Return the flat dictionary as a dictionary.
:rtype: dict
|
GhostXML.indigoPlugin/Contents/Server Plugin/flatdict.py
|
as_dict
|
IndigoDomotics/GhostXML
| 2 |
python
|
def as_dict(self):
'Return the flat dictionary as a dictionary.\n\n :rtype: dict\n\n '
dict_out = {}
for key in self._values.keys():
value = self._values[key]
if isinstance(value, FlatDict):
if (value.former_type == list):
dict_out[key] = [v for (k, v) in sorted(value.items())]
pass
elif (value.former_type == tuple):
dict_out[key] = tuple((v for (k, v) in sorted(value.items())))
pass
elif (value.former_type == dict):
dict_out[key] = value.as_dict()
else:
dict_out[key] = value
return dict_out
|
def as_dict(self):
'Return the flat dictionary as a dictionary.\n\n :rtype: dict\n\n '
dict_out = {}
for key in self._values.keys():
value = self._values[key]
if isinstance(value, FlatDict):
if (value.former_type == list):
dict_out[key] = [v for (k, v) in sorted(value.items())]
pass
elif (value.former_type == tuple):
dict_out[key] = tuple((v for (k, v) in sorted(value.items())))
pass
elif (value.former_type == dict):
dict_out[key] = value.as_dict()
else:
dict_out[key] = value
return dict_out<|docstring|>Return the flat dictionary as a dictionary.
:rtype: dict<|endoftext|>
|
3255ea2549d890651d5817dffc5b4f0e0bfe693cc5a71eb9614dd6ac284de5e3
|
def clear(self):
'Remove all items from the flat dictionary.'
self._values.clear()
|
Remove all items from the flat dictionary.
|
GhostXML.indigoPlugin/Contents/Server Plugin/flatdict.py
|
clear
|
IndigoDomotics/GhostXML
| 2 |
python
|
def clear(self):
self._values.clear()
|
def clear(self):
self._values.clear()<|docstring|>Remove all items from the flat dictionary.<|endoftext|>
|
4a503f103d1d16e527bdaf7856e39b245a1671ff048ff42d6881af29b5c9aabb
|
def copy(self):
'Return a shallow copy of the flat dictionary.\n\n :rtype: flatdict.FlatDict\n\n '
values = {}
for key in self.keys():
values[key] = self.__getitem__(key)
return values
|
Return a shallow copy of the flat dictionary.
:rtype: flatdict.FlatDict
|
GhostXML.indigoPlugin/Contents/Server Plugin/flatdict.py
|
copy
|
IndigoDomotics/GhostXML
| 2 |
python
|
def copy(self):
'Return a shallow copy of the flat dictionary.\n\n :rtype: flatdict.FlatDict\n\n '
values = {}
for key in self.keys():
values[key] = self.__getitem__(key)
return values
|
def copy(self):
'Return a shallow copy of the flat dictionary.\n\n :rtype: flatdict.FlatDict\n\n '
values = {}
for key in self.keys():
values[key] = self.__getitem__(key)
return values<|docstring|>Return a shallow copy of the flat dictionary.
:rtype: flatdict.FlatDict<|endoftext|>
|
a0b8ffac4d429595ce3f7af36f0b208f34ad82c20a4992dd47d177aa2d7be9bd
|
def get(self, key, d=None):
'Return the value for key if key is in the flat dictionary, else\n default. If default is not given, it defaults to ``None``, so that this\n method never raises a ``KeyError``.\n\n :param mixed key: The key to get\n :param mixed d: The default value\n :rtype: mixed\n\n '
if (key not in self.keys()):
return self._values.get(key, d)
return self.__getitem__(key)
|
Return the value for key if key is in the flat dictionary, else
default. If default is not given, it defaults to ``None``, so that this
method never raises a ``KeyError``.
:param mixed key: The key to get
:param mixed d: The default value
:rtype: mixed
|
GhostXML.indigoPlugin/Contents/Server Plugin/flatdict.py
|
get
|
IndigoDomotics/GhostXML
| 2 |
python
|
def get(self, key, d=None):
'Return the value for key if key is in the flat dictionary, else\n default. If default is not given, it defaults to ``None``, so that this\n method never raises a ``KeyError``.\n\n :param mixed key: The key to get\n :param mixed d: The default value\n :rtype: mixed\n\n '
if (key not in self.keys()):
return self._values.get(key, d)
return self.__getitem__(key)
|
def get(self, key, d=None):
'Return the value for key if key is in the flat dictionary, else\n default. If default is not given, it defaults to ``None``, so that this\n method never raises a ``KeyError``.\n\n :param mixed key: The key to get\n :param mixed d: The default value\n :rtype: mixed\n\n '
if (key not in self.keys()):
return self._values.get(key, d)
return self.__getitem__(key)<|docstring|>Return the value for key if key is in the flat dictionary, else
default. If default is not given, it defaults to ``None``, so that this
method never raises a ``KeyError``.
:param mixed key: The key to get
:param mixed d: The default value
:rtype: mixed<|endoftext|>
|
f5f716bcc4e5605b5947f0f09932e5ce3d86063a550c62649fc4a907fa157c2e
|
def has_key(self, key):
'Check to see if the flat dictionary has a specific key.\n\n :param mixed key: The key to check for\n :rtype: bool\n\n '
return (key in self.keys())
|
Check to see if the flat dictionary has a specific key.
:param mixed key: The key to check for
:rtype: bool
|
GhostXML.indigoPlugin/Contents/Server Plugin/flatdict.py
|
has_key
|
IndigoDomotics/GhostXML
| 2 |
python
|
def has_key(self, key):
'Check to see if the flat dictionary has a specific key.\n\n :param mixed key: The key to check for\n :rtype: bool\n\n '
return (key in self.keys())
|
def has_key(self, key):
'Check to see if the flat dictionary has a specific key.\n\n :param mixed key: The key to check for\n :rtype: bool\n\n '
return (key in self.keys())<|docstring|>Check to see if the flat dictionary has a specific key.
:param mixed key: The key to check for
:rtype: bool<|endoftext|>
|
33340a92503b54656aa16e7cc73da6d8f07aa529ecfc100ddbf1eb12180e6677
|
def items(self):
"Return a copy of the flat dictionary's list of ``(key, value)``\n pairs.\n\n .. note:: CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the flat dictionary's history of insertions and deletions.\n\n :rtype: list\n\n "
items = list()
for key in self.keys():
items.append((key, self.__getitem__(key)))
return items
|
Return a copy of the flat dictionary's list of ``(key, value)``
pairs.
.. note:: CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the flat dictionary's history of insertions and deletions.
:rtype: list
|
GhostXML.indigoPlugin/Contents/Server Plugin/flatdict.py
|
items
|
IndigoDomotics/GhostXML
| 2 |
python
|
def items(self):
"Return a copy of the flat dictionary's list of ``(key, value)``\n pairs.\n\n .. note:: CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the flat dictionary's history of insertions and deletions.\n\n :rtype: list\n\n "
items = list()
for key in self.keys():
items.append((key, self.__getitem__(key)))
return items
|
def items(self):
"Return a copy of the flat dictionary's list of ``(key, value)``\n pairs.\n\n .. note:: CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the flat dictionary's history of insertions and deletions.\n\n :rtype: list\n\n "
items = list()
for key in self.keys():
items.append((key, self.__getitem__(key)))
return items<|docstring|>Return a copy of the flat dictionary's list of ``(key, value)``
pairs.
.. note:: CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the flat dictionary's history of insertions and deletions.
:rtype: list<|endoftext|>
|
e352ece74cd6ceaf41702e43b8b82eb7246a023d25edff7b5a1f4da63914cd40
|
def iteritems(self):
"Return an iterator over the flat dictionary's (key, value) pairs.\n See the note for :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.\n\n Using ``iteritems()`` while adding or deleting entries in the flat\n dictionary may raise a ``RuntimeError`` or fail to iterate over all\n entries.\n\n :rtype: Iterator\n :raises: RuntimeError\n\n "
for item in self.items():
(yield item)
|
Return an iterator over the flat dictionary's (key, value) pairs.
See the note for :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.
Using ``iteritems()`` while adding or deleting entries in the flat
dictionary may raise a ``RuntimeError`` or fail to iterate over all
entries.
:rtype: Iterator
:raises: RuntimeError
|
GhostXML.indigoPlugin/Contents/Server Plugin/flatdict.py
|
iteritems
|
IndigoDomotics/GhostXML
| 2 |
python
|
def iteritems(self):
"Return an iterator over the flat dictionary's (key, value) pairs.\n See the note for :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.\n\n Using ``iteritems()`` while adding or deleting entries in the flat\n dictionary may raise a ``RuntimeError`` or fail to iterate over all\n entries.\n\n :rtype: Iterator\n :raises: RuntimeError\n\n "
for item in self.items():
(yield item)
|
def iteritems(self):
"Return an iterator over the flat dictionary's (key, value) pairs.\n See the note for :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.\n\n Using ``iteritems()`` while adding or deleting entries in the flat\n dictionary may raise a ``RuntimeError`` or fail to iterate over all\n entries.\n\n :rtype: Iterator\n :raises: RuntimeError\n\n "
for item in self.items():
(yield item)<|docstring|>Return an iterator over the flat dictionary's (key, value) pairs.
See the note for :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.
Using ``iteritems()`` while adding or deleting entries in the flat
dictionary may raise a ``RuntimeError`` or fail to iterate over all
entries.
:rtype: Iterator
:raises: RuntimeError<|endoftext|>
|
d4d3bdbfb65bfe239c3eaa2b646ed8d23ccc0cf17e09a56aca26525ff5f721de
|
def iterkeys(self):
"Return an iterator over the flat dictionary's keys. See the note for\n :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.\n\n Using ``iterkeys()`` while adding or deleting entries in the flat\n dictionary may raise a ``RuntimeError`` or fail to iterate over all\n entries.\n\n :rtype: Iterator\n :raises: RuntimeError\n\n "
for key in self.keys():
(yield key)
|
Return an iterator over the flat dictionary's keys. See the note for
:py:class:`FlatDict.items() <flatdict.FlatDict.items>`.
Using ``iterkeys()`` while adding or deleting entries in the flat
dictionary may raise a ``RuntimeError`` or fail to iterate over all
entries.
:rtype: Iterator
:raises: RuntimeError
|
GhostXML.indigoPlugin/Contents/Server Plugin/flatdict.py
|
iterkeys
|
IndigoDomotics/GhostXML
| 2 |
python
|
def iterkeys(self):
"Return an iterator over the flat dictionary's keys. See the note for\n :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.\n\n Using ``iterkeys()`` while adding or deleting entries in the flat\n dictionary may raise a ``RuntimeError`` or fail to iterate over all\n entries.\n\n :rtype: Iterator\n :raises: RuntimeError\n\n "
for key in self.keys():
(yield key)
|
def iterkeys(self):
"Return an iterator over the flat dictionary's keys. See the note for\n :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.\n\n Using ``iterkeys()`` while adding or deleting entries in the flat\n dictionary may raise a ``RuntimeError`` or fail to iterate over all\n entries.\n\n :rtype: Iterator\n :raises: RuntimeError\n\n "
for key in self.keys():
(yield key)<|docstring|>Return an iterator over the flat dictionary's keys. See the note for
:py:class:`FlatDict.items() <flatdict.FlatDict.items>`.
Using ``iterkeys()`` while adding or deleting entries in the flat
dictionary may raise a ``RuntimeError`` or fail to iterate over all
entries.
:rtype: Iterator
:raises: RuntimeError<|endoftext|>
|
9738be90baab68fc8ab4973ae7bb36907f35dc59921a4bf53c878797ae63da89
|
def itervalues(self):
"Return an iterator over the flat dictionary's values. See the note\n for :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.\n\n Using ``itervalues()`` while adding or deleting entries in the flat\n dictionary may raise a ``RuntimeError`` or fail to iterate over all\n entries.\n\n :rtype: Iterator\n :raises: RuntimeError\n\n "
for key in self.keys():
(yield self.__getitem__(key))
|
Return an iterator over the flat dictionary's values. See the note
for :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.
Using ``itervalues()`` while adding or deleting entries in the flat
dictionary may raise a ``RuntimeError`` or fail to iterate over all
entries.
:rtype: Iterator
:raises: RuntimeError
|
GhostXML.indigoPlugin/Contents/Server Plugin/flatdict.py
|
itervalues
|
IndigoDomotics/GhostXML
| 2 |
python
|
def itervalues(self):
"Return an iterator over the flat dictionary's values. See the note\n for :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.\n\n Using ``itervalues()`` while adding or deleting entries in the flat\n dictionary may raise a ``RuntimeError`` or fail to iterate over all\n entries.\n\n :rtype: Iterator\n :raises: RuntimeError\n\n "
for key in self.keys():
(yield self.__getitem__(key))
|
def itervalues(self):
"Return an iterator over the flat dictionary's values. See the note\n for :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.\n\n Using ``itervalues()`` while adding or deleting entries in the flat\n dictionary may raise a ``RuntimeError`` or fail to iterate over all\n entries.\n\n :rtype: Iterator\n :raises: RuntimeError\n\n "
for key in self.keys():
(yield self.__getitem__(key))<|docstring|>Return an iterator over the flat dictionary's values. See the note
for :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.
Using ``itervalues()`` while adding or deleting entries in the flat
dictionary may raise a ``RuntimeError`` or fail to iterate over all
entries.
:rtype: Iterator
:raises: RuntimeError<|endoftext|>
|
33ad4d414f696e8b244c202c8f5a856644a84827db166576ad0a2a1f579efedd
|
def keys(self):
"Return a copy of the flat dictionary's list of keys. See the note for\n :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.\n\n :rtype: list\n\n "
keys = list()
for key in self._values.keys():
if isinstance(self._values[key], FlatDict):
child_keys = self._values[key].keys()
for child in child_keys:
keys.append(self._key(key, child))
else:
keys.append(key)
return keys
|
Return a copy of the flat dictionary's list of keys. See the note for
:py:class:`FlatDict.items() <flatdict.FlatDict.items>`.
:rtype: list
|
GhostXML.indigoPlugin/Contents/Server Plugin/flatdict.py
|
keys
|
IndigoDomotics/GhostXML
| 2 |
python
|
def keys(self):
"Return a copy of the flat dictionary's list of keys. See the note for\n :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.\n\n :rtype: list\n\n "
keys = list()
for key in self._values.keys():
if isinstance(self._values[key], FlatDict):
child_keys = self._values[key].keys()
for child in child_keys:
keys.append(self._key(key, child))
else:
keys.append(key)
return keys
|
def keys(self):
"Return a copy of the flat dictionary's list of keys. See the note for\n :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.\n\n :rtype: list\n\n "
keys = list()
for key in self._values.keys():
if isinstance(self._values[key], FlatDict):
child_keys = self._values[key].keys()
for child in child_keys:
keys.append(self._key(key, child))
else:
keys.append(key)
return keys<|docstring|>Return a copy of the flat dictionary's list of keys. See the note for
:py:class:`FlatDict.items() <flatdict.FlatDict.items>`.
:rtype: list<|endoftext|>
|
cfe76dc382942c5375598c58d188a6d23a5db5034e5aeb617d57c8f7bc1f2992
|
def pop(self, key, default=None):
'If key is in the flat dictionary, remove it and return its value,\n else return default. If default is not given and key is not in the\n dictionary, a ``KeyError`` is raised.\n\n :param mixed key: The key name\n :param mixed default: The default value\n :rtype: mixed\n\n '
if ((key not in self.keys()) and (key not in self._values)):
return default
if (key in self._values):
return self._values.pop(key, default)
value = self.__getitem__(key)
self.__delitem__(key)
return value
|
If key is in the flat dictionary, remove it and return its value,
else return default. If default is not given and key is not in the
dictionary, a ``KeyError`` is raised.
:param mixed key: The key name
:param mixed default: The default value
:rtype: mixed
|
GhostXML.indigoPlugin/Contents/Server Plugin/flatdict.py
|
pop
|
IndigoDomotics/GhostXML
| 2 |
python
|
def pop(self, key, default=None):
'If key is in the flat dictionary, remove it and return its value,\n else return default. If default is not given and key is not in the\n dictionary, a ``KeyError`` is raised.\n\n :param mixed key: The key name\n :param mixed default: The default value\n :rtype: mixed\n\n '
if ((key not in self.keys()) and (key not in self._values)):
return default
if (key in self._values):
return self._values.pop(key, default)
value = self.__getitem__(key)
self.__delitem__(key)
return value
|
def pop(self, key, default=None):
'If key is in the flat dictionary, remove it and return its value,\n else return default. If default is not given and key is not in the\n dictionary, a ``KeyError`` is raised.\n\n :param mixed key: The key name\n :param mixed default: The default value\n :rtype: mixed\n\n '
if ((key not in self.keys()) and (key not in self._values)):
return default
if (key in self._values):
return self._values.pop(key, default)
value = self.__getitem__(key)
self.__delitem__(key)
return value<|docstring|>If key is in the flat dictionary, remove it and return its value,
else return default. If default is not given and key is not in the
dictionary, a ``KeyError`` is raised.
:param mixed key: The key name
:param mixed default: The default value
:rtype: mixed<|endoftext|>
|
8548802ca2b913d39b0e7bb38103b9de36fb26d4e74503de9a9659c302b59515
|
def setdefault(self, key, default=None):
' If key is in the flat dictionary, return its value. If not,\n insert key with a value of default and return default.\n default defaults to ``None``.\n\n :param mixed key: The key name\n :param mixed default: The default value\n :rtype: mixed\n\n '
if (key not in self):
self.__setitem__(key, default)
return self.__getitem__(key)
|
If key is in the flat dictionary, return its value. If not,
insert key with a value of default and return default.
default defaults to ``None``.
:param mixed key: The key name
:param mixed default: The default value
:rtype: mixed
|
GhostXML.indigoPlugin/Contents/Server Plugin/flatdict.py
|
setdefault
|
IndigoDomotics/GhostXML
| 2 |
python
|
def setdefault(self, key, default=None):
' If key is in the flat dictionary, return its value. If not,\n insert key with a value of default and return default.\n default defaults to ``None``.\n\n :param mixed key: The key name\n :param mixed default: The default value\n :rtype: mixed\n\n '
if (key not in self):
self.__setitem__(key, default)
return self.__getitem__(key)
|
def setdefault(self, key, default=None):
' If key is in the flat dictionary, return its value. If not,\n insert key with a value of default and return default.\n default defaults to ``None``.\n\n :param mixed key: The key name\n :param mixed default: The default value\n :rtype: mixed\n\n '
if (key not in self):
self.__setitem__(key, default)
return self.__getitem__(key)<|docstring|>If key is in the flat dictionary, return its value. If not,
insert key with a value of default and return default.
default defaults to ``None``.
:param mixed key: The key name
:param mixed default: The default value
:rtype: mixed<|endoftext|>
|
bfc6f220fb652f10a7bbdb947d2328f444f2edb5961d83ccc1b627301a3e61a9
|
def set_delimiter(self, delimiter):
'Override the default or passed in delimiter with a new value.\n\n :param str delimiter: The delimiter to use\n\n '
self._delimiter = delimiter
for key in self._values.keys():
if isinstance(self._values[key], FlatDict):
self._values[key].set_delimiter(delimiter)
|
Override the default or passed in delimiter with a new value.
:param str delimiter: The delimiter to use
|
GhostXML.indigoPlugin/Contents/Server Plugin/flatdict.py
|
set_delimiter
|
IndigoDomotics/GhostXML
| 2 |
python
|
def set_delimiter(self, delimiter):
'Override the default or passed in delimiter with a new value.\n\n :param str delimiter: The delimiter to use\n\n '
self._delimiter = delimiter
for key in self._values.keys():
if isinstance(self._values[key], FlatDict):
self._values[key].set_delimiter(delimiter)
|
def set_delimiter(self, delimiter):
'Override the default or passed in delimiter with a new value.\n\n :param str delimiter: The delimiter to use\n\n '
self._delimiter = delimiter
for key in self._values.keys():
if isinstance(self._values[key], FlatDict):
self._values[key].set_delimiter(delimiter)<|docstring|>Override the default or passed in delimiter with a new value.
:param str delimiter: The delimiter to use<|endoftext|>
|
85b2159f4dd9dfec4c029fd2edc5b80e26b1d047d70496d30ad8dd9f20adbd8f
|
def update(self, other=None, **kwargs):
'Update the flat dictionary with the key/value pairs from other,\n overwriting existing keys.\n\n ``update()`` accepts either another flat dictionary object or an\n iterable of key/value pairs (as tuples or other iterables of length\n two). If keyword arguments are specified, the flat dictionary is then\n updated with those key/value pairs: ``d.update(red=1, blue=2)``.\n\n :rtype: None\n\n '
values = (other or kwargs)
if values:
for key in values:
self.__setitem__(key, values[key])
|
Update the flat dictionary with the key/value pairs from other,
overwriting existing keys.
``update()`` accepts either another flat dictionary object or an
iterable of key/value pairs (as tuples or other iterables of length
two). If keyword arguments are specified, the flat dictionary is then
updated with those key/value pairs: ``d.update(red=1, blue=2)``.
:rtype: None
|
GhostXML.indigoPlugin/Contents/Server Plugin/flatdict.py
|
update
|
IndigoDomotics/GhostXML
| 2 |
python
|
def update(self, other=None, **kwargs):
'Update the flat dictionary with the key/value pairs from other,\n overwriting existing keys.\n\n ``update()`` accepts either another flat dictionary object or an\n iterable of key/value pairs (as tuples or other iterables of length\n two). If keyword arguments are specified, the flat dictionary is then\n updated with those key/value pairs: ``d.update(red=1, blue=2)``.\n\n :rtype: None\n\n '
values = (other or kwargs)
if values:
for key in values:
self.__setitem__(key, values[key])
|
def update(self, other=None, **kwargs):
'Update the flat dictionary with the key/value pairs from other,\n overwriting existing keys.\n\n ``update()`` accepts either another flat dictionary object or an\n iterable of key/value pairs (as tuples or other iterables of length\n two). If keyword arguments are specified, the flat dictionary is then\n updated with those key/value pairs: ``d.update(red=1, blue=2)``.\n\n :rtype: None\n\n '
values = (other or kwargs)
if values:
for key in values:
self.__setitem__(key, values[key])<|docstring|>Update the flat dictionary with the key/value pairs from other,
overwriting existing keys.
``update()`` accepts either another flat dictionary object or an
iterable of key/value pairs (as tuples or other iterables of length
two). If keyword arguments are specified, the flat dictionary is then
updated with those key/value pairs: ``d.update(red=1, blue=2)``.
:rtype: None<|endoftext|>
|
bef2a195e987e3bb5fc0f8341daa224b78c829185be62becf7660787714289f6
|
def values(self):
"Return a copy of the flat dictionary's list of values. See the note\n for :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.\n\n :rtype: list\n\n "
values = list()
for key in self.keys():
values.append(self.__getitem__(key))
return values
|
Return a copy of the flat dictionary's list of values. See the note
for :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.
:rtype: list
|
GhostXML.indigoPlugin/Contents/Server Plugin/flatdict.py
|
values
|
IndigoDomotics/GhostXML
| 2 |
python
|
def values(self):
"Return a copy of the flat dictionary's list of values. See the note\n for :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.\n\n :rtype: list\n\n "
values = list()
for key in self.keys():
values.append(self.__getitem__(key))
return values
|
def values(self):
"Return a copy of the flat dictionary's list of values. See the note\n for :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.\n\n :rtype: list\n\n "
values = list()
for key in self.keys():
values.append(self.__getitem__(key))
return values<|docstring|>Return a copy of the flat dictionary's list of values. See the note
for :py:class:`FlatDict.items() <flatdict.FlatDict.items>`.
:rtype: list<|endoftext|>
|
c02d15ee3af03ce6e3c85bd2c5a744dc56984f4946d8b28d1dfe9e749eb2c28c
|
@login_manager.request_loader
def authenticate_user(request):
'Require token for authentication to allow user to access resources'
token = request.headers.get('Authorization')
if token:
try:
data = auth_serializer.loads(token)
except SignatureExpired:
return None
except BadSignature:
return None
user = User.query.get(data[0])
if ((user.password == data[2]) and user.logged_in):
return user
return None
|
Require token for authentication to allow user to access resources
|
blst/api.py
|
authenticate_user
|
collinmutembei/II
| 0 |
python
|
@login_manager.request_loader
def authenticate_user(request):
token = request.headers.get('Authorization')
if token:
try:
data = auth_serializer.loads(token)
except SignatureExpired:
return None
except BadSignature:
return None
user = User.query.get(data[0])
if ((user.password == data[2]) and user.logged_in):
return user
return None
|
@login_manager.request_loader
def authenticate_user(request):
token = request.headers.get('Authorization')
if token:
try:
data = auth_serializer.loads(token)
except SignatureExpired:
return None
except BadSignature:
return None
user = User.query.get(data[0])
if ((user.password == data[2]) and user.logged_in):
return user
return None<|docstring|>Require token for authentication to allow user to access resources<|endoftext|>
|
f193fbbbdf6de30c1db1cc89af958a03713dc3025547d4634744a5dc2a1e2ccc
|
def int_tested(*j, **hint):
'\n Return all args as Python integers.\n\n In some cases a routine needs to work with integers\n but it is convenient to allow the user to pass a non-integer\n value or expression. In this case, the flag ``strict`` can be set\n to False. The default behavior is to raise an error if any argument\n cannot pass an int(arg) == arg test.\n\n Examples\n ========\n\n >>> from sympy.ntheory.residue_ntheory import int_tested\n >>> from sympy import sqrt\n >>> n = sqrt(10)\n >>> int_tested(n, strict=False)\n 3\n >>> int_tested(n)\n Traceback (most recent call last):\n ...\n ValueError: All arguments were not integers\n\n '
i = tuple([int(i) for i in j])
if hint.get('strict', True):
if (i != j):
raise ValueError('all arguments were not integers')
if (len(i) == 1):
return i[0]
return i
|
Return all args as Python integers.
In some cases a routine needs to work with integers
but it is convenient to allow the user to pass a non-integer
value or expression. In this case, the flag ``strict`` can be set
to False. The default behavior is to raise an error if any argument
cannot pass an int(arg) == arg test.
Examples
========
>>> from sympy.ntheory.residue_ntheory import int_tested
>>> from sympy import sqrt
>>> n = sqrt(10)
>>> int_tested(n, strict=False)
3
>>> int_tested(n)
Traceback (most recent call last):
...
ValueError: All arguments were not integers
|
sympy/ntheory/residue_ntheory.py
|
int_tested
|
goodok/sympy
| 2 |
python
|
def int_tested(*j, **hint):
'\n Return all args as Python integers.\n\n In some cases a routine needs to work with integers\n but it is convenient to allow the user to pass a non-integer\n value or expression. In this case, the flag ``strict`` can be set\n to False. The default behavior is to raise an error if any argument\n cannot pass an int(arg) == arg test.\n\n Examples\n ========\n\n >>> from sympy.ntheory.residue_ntheory import int_tested\n >>> from sympy import sqrt\n >>> n = sqrt(10)\n >>> int_tested(n, strict=False)\n 3\n >>> int_tested(n)\n Traceback (most recent call last):\n ...\n ValueError: All arguments were not integers\n\n '
i = tuple([int(i) for i in j])
if hint.get('strict', True):
if (i != j):
raise ValueError('all arguments were not integers')
if (len(i) == 1):
return i[0]
return i
|
def int_tested(*j, **hint):
'\n Return all args as Python integers.\n\n In some cases a routine needs to work with integers\n but it is convenient to allow the user to pass a non-integer\n value or expression. In this case, the flag ``strict`` can be set\n to False. The default behavior is to raise an error if any argument\n cannot pass an int(arg) == arg test.\n\n Examples\n ========\n\n >>> from sympy.ntheory.residue_ntheory import int_tested\n >>> from sympy import sqrt\n >>> n = sqrt(10)\n >>> int_tested(n, strict=False)\n 3\n >>> int_tested(n)\n Traceback (most recent call last):\n ...\n ValueError: All arguments were not integers\n\n '
i = tuple([int(i) for i in j])
if hint.get('strict', True):
if (i != j):
raise ValueError('all arguments were not integers')
if (len(i) == 1):
return i[0]
return i<|docstring|>Return all args as Python integers.
In some cases a routine needs to work with integers
but it is convenient to allow the user to pass a non-integer
value or expression. In this case, the flag ``strict`` can be set
to False. The default behavior is to raise an error if any argument
cannot pass an int(arg) == arg test.
Examples
========
>>> from sympy.ntheory.residue_ntheory import int_tested
>>> from sympy import sqrt
>>> n = sqrt(10)
>>> int_tested(n, strict=False)
3
>>> int_tested(n)
Traceback (most recent call last):
...
ValueError: All arguments were not integers<|endoftext|>
|
f091f82fbc863e4c04dc840b1545b1edbed6b1b77723edbf2e616b3c11f77ff8
|
def n_order(a, n):
'Returns the order of ``a`` modulo ``n``.\n\n The order of ``a`` modulo ``n`` is the smallest integer\n ``k`` such that ``a**k`` leaves a remainder of 1 with ``n``.\n\n Examples\n ========\n\n >>> from sympy.ntheory import n_order\n >>> n_order(3, 7)\n 6\n >>> n_order(4, 7)\n 3\n '
(a, n) = int_tested(a, n)
if (igcd(a, n) != 1):
raise ValueError('The two numbers should be relatively prime')
group_order = totient(n)
factors = factorint(group_order)
order = 1
if (a > n):
a = (a % n)
for (p, e) in factors.iteritems():
exponent = group_order
for f in xrange(0, (e + 1)):
if (((a ** exponent) % n) != 1):
order *= (p ** ((e - f) + 1))
break
exponent = (exponent // p)
return order
|
Returns the order of ``a`` modulo ``n``.
The order of ``a`` modulo ``n`` is the smallest integer
``k`` such that ``a**k`` leaves a remainder of 1 with ``n``.
Examples
========
>>> from sympy.ntheory import n_order
>>> n_order(3, 7)
6
>>> n_order(4, 7)
3
|
sympy/ntheory/residue_ntheory.py
|
n_order
|
goodok/sympy
| 2 |
python
|
def n_order(a, n):
'Returns the order of ``a`` modulo ``n``.\n\n The order of ``a`` modulo ``n`` is the smallest integer\n ``k`` such that ``a**k`` leaves a remainder of 1 with ``n``.\n\n Examples\n ========\n\n >>> from sympy.ntheory import n_order\n >>> n_order(3, 7)\n 6\n >>> n_order(4, 7)\n 3\n '
(a, n) = int_tested(a, n)
if (igcd(a, n) != 1):
raise ValueError('The two numbers should be relatively prime')
group_order = totient(n)
factors = factorint(group_order)
order = 1
if (a > n):
a = (a % n)
for (p, e) in factors.iteritems():
exponent = group_order
for f in xrange(0, (e + 1)):
if (((a ** exponent) % n) != 1):
order *= (p ** ((e - f) + 1))
break
exponent = (exponent // p)
return order
|
def n_order(a, n):
'Returns the order of ``a`` modulo ``n``.\n\n The order of ``a`` modulo ``n`` is the smallest integer\n ``k`` such that ``a**k`` leaves a remainder of 1 with ``n``.\n\n Examples\n ========\n\n >>> from sympy.ntheory import n_order\n >>> n_order(3, 7)\n 6\n >>> n_order(4, 7)\n 3\n '
(a, n) = int_tested(a, n)
if (igcd(a, n) != 1):
raise ValueError('The two numbers should be relatively prime')
group_order = totient(n)
factors = factorint(group_order)
order = 1
if (a > n):
a = (a % n)
for (p, e) in factors.iteritems():
exponent = group_order
for f in xrange(0, (e + 1)):
if (((a ** exponent) % n) != 1):
order *= (p ** ((e - f) + 1))
break
exponent = (exponent // p)
return order<|docstring|>Returns the order of ``a`` modulo ``n``.
The order of ``a`` modulo ``n`` is the smallest integer
``k`` such that ``a**k`` leaves a remainder of 1 with ``n``.
Examples
========
>>> from sympy.ntheory import n_order
>>> n_order(3, 7)
6
>>> n_order(4, 7)
3<|endoftext|>
|
9ed21e800a408b6ab4562196f041874bda9021f7e606fedc541fdb46cd42bf11
|
def is_primitive_root(a, p):
'\n Returns True if ``a`` is a primitive root of ``p``\n\n ``a`` is said to be the primitive root of ``p`` if gcd(a, p) == 1 and\n totient(p) is the smallest positive number s.t.\n\n a**totient(p) cong 1 mod(p)\n\n Examples\n ========\n\n >>> from sympy.ntheory import is_primitive_root, n_order, totient\n >>> is_primitive_root(3, 10)\n True\n >>> is_primitive_root(9, 10)\n False\n >>> n_order(3, 10) == totient(10)\n True\n >>> n_order(9, 10) == totient(10)\n False\n\n '
(a, p) = int_tested(a, p)
if (igcd(a, p) != 1):
raise ValueError('The two numbers should be relatively prime')
if (a > p):
a = (a % p)
if (n_order(a, p) == totient(p)):
return True
else:
return False
|
Returns True if ``a`` is a primitive root of ``p``
``a`` is said to be the primitive root of ``p`` if gcd(a, p) == 1 and
totient(p) is the smallest positive number s.t.
a**totient(p) cong 1 mod(p)
Examples
========
>>> from sympy.ntheory import is_primitive_root, n_order, totient
>>> is_primitive_root(3, 10)
True
>>> is_primitive_root(9, 10)
False
>>> n_order(3, 10) == totient(10)
True
>>> n_order(9, 10) == totient(10)
False
|
sympy/ntheory/residue_ntheory.py
|
is_primitive_root
|
goodok/sympy
| 2 |
python
|
def is_primitive_root(a, p):
'\n Returns True if ``a`` is a primitive root of ``p``\n\n ``a`` is said to be the primitive root of ``p`` if gcd(a, p) == 1 and\n totient(p) is the smallest positive number s.t.\n\n a**totient(p) cong 1 mod(p)\n\n Examples\n ========\n\n >>> from sympy.ntheory import is_primitive_root, n_order, totient\n >>> is_primitive_root(3, 10)\n True\n >>> is_primitive_root(9, 10)\n False\n >>> n_order(3, 10) == totient(10)\n True\n >>> n_order(9, 10) == totient(10)\n False\n\n '
(a, p) = int_tested(a, p)
if (igcd(a, p) != 1):
raise ValueError('The two numbers should be relatively prime')
if (a > p):
a = (a % p)
if (n_order(a, p) == totient(p)):
return True
else:
return False
|
def is_primitive_root(a, p):
'\n Returns True if ``a`` is a primitive root of ``p``\n\n ``a`` is said to be the primitive root of ``p`` if gcd(a, p) == 1 and\n totient(p) is the smallest positive number s.t.\n\n a**totient(p) cong 1 mod(p)\n\n Examples\n ========\n\n >>> from sympy.ntheory import is_primitive_root, n_order, totient\n >>> is_primitive_root(3, 10)\n True\n >>> is_primitive_root(9, 10)\n False\n >>> n_order(3, 10) == totient(10)\n True\n >>> n_order(9, 10) == totient(10)\n False\n\n '
(a, p) = int_tested(a, p)
if (igcd(a, p) != 1):
raise ValueError('The two numbers should be relatively prime')
if (a > p):
a = (a % p)
if (n_order(a, p) == totient(p)):
return True
else:
return False<|docstring|>Returns True if ``a`` is a primitive root of ``p``
``a`` is said to be the primitive root of ``p`` if gcd(a, p) == 1 and
totient(p) is the smallest positive number s.t.
a**totient(p) cong 1 mod(p)
Examples
========
>>> from sympy.ntheory import is_primitive_root, n_order, totient
>>> is_primitive_root(3, 10)
True
>>> is_primitive_root(9, 10)
False
>>> n_order(3, 10) == totient(10)
True
>>> n_order(9, 10) == totient(10)
False<|endoftext|>
|
006f1a18c7626b8e7f579f218bac5a67f6998d3570dcf68bdce9c2ed1ab1dd6e
|
def is_quad_residue(a, p):
'\n Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``,\n i.e a % p in set([i**2 % p for i in range(p)]). If ``p`` is an odd\n prime, an iterative method is used to make the determination:\n\n >>> from sympy.ntheory import is_quad_residue\n >>> list(set([i**2 % 7 for i in range(7)]))\n [0, 1, 2, 4]\n >>> [j for j in range(7) if is_quad_residue(j, 7)]\n [0, 1, 2, 4]\n\n See Also\n ========\n\n legendre_symbol, jacobi_symbol\n '
(a, p) = int_tested(a, p)
if (p < 1):
raise ValueError('p must be > 0')
if ((a >= p) or (a < 0)):
a = (a % p)
if ((a < 2) or (p < 3)):
return True
if (not isprime(p)):
if ((p % 2) and (jacobi_symbol(a, p) == (- 1))):
return False
for i in range(2, ((p // 2) + 1)):
if (((i ** 2) % p) == a):
return True
return False
def square_and_multiply(a, n, p):
if (n == 1):
return a
elif ((n % 2) == 1):
return (((square_and_multiply(a, (n // 2), p) ** 2) * a) % p)
else:
return ((square_and_multiply(a, (n // 2), p) ** 2) % p)
return ((square_and_multiply(a, ((p - 1) // 2), p) % p) == 1)
|
Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``,
i.e a % p in set([i**2 % p for i in range(p)]). If ``p`` is an odd
prime, an iterative method is used to make the determination:
>>> from sympy.ntheory import is_quad_residue
>>> list(set([i**2 % 7 for i in range(7)]))
[0, 1, 2, 4]
>>> [j for j in range(7) if is_quad_residue(j, 7)]
[0, 1, 2, 4]
See Also
========
legendre_symbol, jacobi_symbol
|
sympy/ntheory/residue_ntheory.py
|
is_quad_residue
|
goodok/sympy
| 2 |
python
|
def is_quad_residue(a, p):
'\n Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``,\n i.e a % p in set([i**2 % p for i in range(p)]). If ``p`` is an odd\n prime, an iterative method is used to make the determination:\n\n >>> from sympy.ntheory import is_quad_residue\n >>> list(set([i**2 % 7 for i in range(7)]))\n [0, 1, 2, 4]\n >>> [j for j in range(7) if is_quad_residue(j, 7)]\n [0, 1, 2, 4]\n\n See Also\n ========\n\n legendre_symbol, jacobi_symbol\n '
(a, p) = int_tested(a, p)
if (p < 1):
raise ValueError('p must be > 0')
if ((a >= p) or (a < 0)):
a = (a % p)
if ((a < 2) or (p < 3)):
return True
if (not isprime(p)):
if ((p % 2) and (jacobi_symbol(a, p) == (- 1))):
return False
for i in range(2, ((p // 2) + 1)):
if (((i ** 2) % p) == a):
return True
return False
def square_and_multiply(a, n, p):
if (n == 1):
return a
elif ((n % 2) == 1):
return (((square_and_multiply(a, (n // 2), p) ** 2) * a) % p)
else:
return ((square_and_multiply(a, (n // 2), p) ** 2) % p)
return ((square_and_multiply(a, ((p - 1) // 2), p) % p) == 1)
|
def is_quad_residue(a, p):
'\n Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``,\n i.e a % p in set([i**2 % p for i in range(p)]). If ``p`` is an odd\n prime, an iterative method is used to make the determination:\n\n >>> from sympy.ntheory import is_quad_residue\n >>> list(set([i**2 % 7 for i in range(7)]))\n [0, 1, 2, 4]\n >>> [j for j in range(7) if is_quad_residue(j, 7)]\n [0, 1, 2, 4]\n\n See Also\n ========\n\n legendre_symbol, jacobi_symbol\n '
(a, p) = int_tested(a, p)
if (p < 1):
raise ValueError('p must be > 0')
if ((a >= p) or (a < 0)):
a = (a % p)
if ((a < 2) or (p < 3)):
return True
if (not isprime(p)):
if ((p % 2) and (jacobi_symbol(a, p) == (- 1))):
return False
for i in range(2, ((p // 2) + 1)):
if (((i ** 2) % p) == a):
return True
return False
def square_and_multiply(a, n, p):
if (n == 1):
return a
elif ((n % 2) == 1):
return (((square_and_multiply(a, (n // 2), p) ** 2) * a) % p)
else:
return ((square_and_multiply(a, (n // 2), p) ** 2) % p)
return ((square_and_multiply(a, ((p - 1) // 2), p) % p) == 1)<|docstring|>Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``,
i.e a % p in set([i**2 % p for i in range(p)]). If ``p`` is an odd
prime, an iterative method is used to make the determination:
>>> from sympy.ntheory import is_quad_residue
>>> list(set([i**2 % 7 for i in range(7)]))
[0, 1, 2, 4]
>>> [j for j in range(7) if is_quad_residue(j, 7)]
[0, 1, 2, 4]
See Also
========
legendre_symbol, jacobi_symbol<|endoftext|>
|
e1fddf433a7e85f737b0c08db4a67a9e1fdff8b832addbc7bbb28e7d6e1df547
|
def legendre_symbol(a, p):
'\n Returns\n =======\n\n 1. 0 if a is multiple of p\n 2. 1 if a is a quadratic residue of p\n 3. -1 otherwise\n\n p should be an odd prime by definition\n\n Examples\n ========\n\n >>> from sympy.ntheory import legendre_symbol\n >>> [legendre_symbol(i, 7) for i in range(7)]\n [0, 1, 1, -1, 1, -1, -1]\n >>> list(set([i**2 % 7 for i in range(7)]))\n [0, 1, 2, 4]\n\n See Also\n ========\n\n is_quad_residue, jacobi_symbol\n\n '
(a, p) = int_tested(a, p)
if ((not isprime(p)) or (p == 2)):
raise ValueError('p should be an odd prime')
(_, a) = divmod(a, p)
if (not a):
return 0
if is_quad_residue(a, p):
return 1
else:
return (- 1)
|
Returns
=======
1. 0 if a is multiple of p
2. 1 if a is a quadratic residue of p
3. -1 otherwise
p should be an odd prime by definition
Examples
========
>>> from sympy.ntheory import legendre_symbol
>>> [legendre_symbol(i, 7) for i in range(7)]
[0, 1, 1, -1, 1, -1, -1]
>>> list(set([i**2 % 7 for i in range(7)]))
[0, 1, 2, 4]
See Also
========
is_quad_residue, jacobi_symbol
|
sympy/ntheory/residue_ntheory.py
|
legendre_symbol
|
goodok/sympy
| 2 |
python
|
def legendre_symbol(a, p):
'\n Returns\n =======\n\n 1. 0 if a is multiple of p\n 2. 1 if a is a quadratic residue of p\n 3. -1 otherwise\n\n p should be an odd prime by definition\n\n Examples\n ========\n\n >>> from sympy.ntheory import legendre_symbol\n >>> [legendre_symbol(i, 7) for i in range(7)]\n [0, 1, 1, -1, 1, -1, -1]\n >>> list(set([i**2 % 7 for i in range(7)]))\n [0, 1, 2, 4]\n\n See Also\n ========\n\n is_quad_residue, jacobi_symbol\n\n '
(a, p) = int_tested(a, p)
if ((not isprime(p)) or (p == 2)):
raise ValueError('p should be an odd prime')
(_, a) = divmod(a, p)
if (not a):
return 0
if is_quad_residue(a, p):
return 1
else:
return (- 1)
|
def legendre_symbol(a, p):
'\n Returns\n =======\n\n 1. 0 if a is multiple of p\n 2. 1 if a is a quadratic residue of p\n 3. -1 otherwise\n\n p should be an odd prime by definition\n\n Examples\n ========\n\n >>> from sympy.ntheory import legendre_symbol\n >>> [legendre_symbol(i, 7) for i in range(7)]\n [0, 1, 1, -1, 1, -1, -1]\n >>> list(set([i**2 % 7 for i in range(7)]))\n [0, 1, 2, 4]\n\n See Also\n ========\n\n is_quad_residue, jacobi_symbol\n\n '
(a, p) = int_tested(a, p)
if ((not isprime(p)) or (p == 2)):
raise ValueError('p should be an odd prime')
(_, a) = divmod(a, p)
if (not a):
return 0
if is_quad_residue(a, p):
return 1
else:
return (- 1)<|docstring|>Returns
=======
1. 0 if a is multiple of p
2. 1 if a is a quadratic residue of p
3. -1 otherwise
p should be an odd prime by definition
Examples
========
>>> from sympy.ntheory import legendre_symbol
>>> [legendre_symbol(i, 7) for i in range(7)]
[0, 1, 1, -1, 1, -1, -1]
>>> list(set([i**2 % 7 for i in range(7)]))
[0, 1, 2, 4]
See Also
========
is_quad_residue, jacobi_symbol<|endoftext|>
|
eeb5dba72a222b36f8d24eccbbfce745bcab4fc1cbc8bc09c94b44f481a21e7f
|
def jacobi_symbol(m, n):
'\n Returns the product of the legendre_symbol(m, p)\n for all the prime factors, p, of n.\n\n Returns\n =======\n\n 1. 0 if m cong 0 mod(n)\n 2. 1 if x**2 cong m mod(n) has a solution\n 3. -1 otherwise\n\n Examples\n ========\n\n >>> from sympy.ntheory import jacobi_symbol, legendre_symbol\n >>> from sympy import Mul, S\n >>> jacobi_symbol(45, 77)\n -1\n >>> jacobi_symbol(60, 121)\n 1\n\n The relationship between the jacobi_symbol and legendre_symbol can\n be demonstrated as follows:\n\n >>> L = legendre_symbol\n >>> S(45).factors()\n {3: 2, 5: 1}\n >>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1\n True\n\n See Also\n ========\n\n is_quad_residue, legendre_symbol\n '
(m, n) = int_tested(m, n)
if (not (n % 2)):
raise ValueError('n should be an odd integer')
if ((m < 0) or (m > n)):
m = (m % n)
if (not m):
return int((n == 1))
if ((n == 1) or (m == 1)):
return 1
if (igcd(m, n) != 1):
return 0
j = 1
s = trailing(m)
m = (m >> s)
if ((s % 2) and ((n % 8) in [3, 5])):
j *= (- 1)
while (m != 1):
if (((m % 4) == 3) and ((n % 4) == 3)):
j *= (- 1)
(m, n) = ((n % m), m)
s = trailing(m)
m = (m >> s)
if ((s % 2) and ((n % 8) in [3, 5])):
j *= (- 1)
return j
|
Returns the product of the legendre_symbol(m, p)
for all the prime factors, p, of n.
Returns
=======
1. 0 if m cong 0 mod(n)
2. 1 if x**2 cong m mod(n) has a solution
3. -1 otherwise
Examples
========
>>> from sympy.ntheory import jacobi_symbol, legendre_symbol
>>> from sympy import Mul, S
>>> jacobi_symbol(45, 77)
-1
>>> jacobi_symbol(60, 121)
1
The relationship between the jacobi_symbol and legendre_symbol can
be demonstrated as follows:
>>> L = legendre_symbol
>>> S(45).factors()
{3: 2, 5: 1}
>>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1
True
See Also
========
is_quad_residue, legendre_symbol
|
sympy/ntheory/residue_ntheory.py
|
jacobi_symbol
|
goodok/sympy
| 2 |
python
|
def jacobi_symbol(m, n):
'\n Returns the product of the legendre_symbol(m, p)\n for all the prime factors, p, of n.\n\n Returns\n =======\n\n 1. 0 if m cong 0 mod(n)\n 2. 1 if x**2 cong m mod(n) has a solution\n 3. -1 otherwise\n\n Examples\n ========\n\n >>> from sympy.ntheory import jacobi_symbol, legendre_symbol\n >>> from sympy import Mul, S\n >>> jacobi_symbol(45, 77)\n -1\n >>> jacobi_symbol(60, 121)\n 1\n\n The relationship between the jacobi_symbol and legendre_symbol can\n be demonstrated as follows:\n\n >>> L = legendre_symbol\n >>> S(45).factors()\n {3: 2, 5: 1}\n >>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1\n True\n\n See Also\n ========\n\n is_quad_residue, legendre_symbol\n '
(m, n) = int_tested(m, n)
if (not (n % 2)):
raise ValueError('n should be an odd integer')
if ((m < 0) or (m > n)):
m = (m % n)
if (not m):
return int((n == 1))
if ((n == 1) or (m == 1)):
return 1
if (igcd(m, n) != 1):
return 0
j = 1
s = trailing(m)
m = (m >> s)
if ((s % 2) and ((n % 8) in [3, 5])):
j *= (- 1)
while (m != 1):
if (((m % 4) == 3) and ((n % 4) == 3)):
j *= (- 1)
(m, n) = ((n % m), m)
s = trailing(m)
m = (m >> s)
if ((s % 2) and ((n % 8) in [3, 5])):
j *= (- 1)
return j
|
def jacobi_symbol(m, n):
'\n Returns the product of the legendre_symbol(m, p)\n for all the prime factors, p, of n.\n\n Returns\n =======\n\n 1. 0 if m cong 0 mod(n)\n 2. 1 if x**2 cong m mod(n) has a solution\n 3. -1 otherwise\n\n Examples\n ========\n\n >>> from sympy.ntheory import jacobi_symbol, legendre_symbol\n >>> from sympy import Mul, S\n >>> jacobi_symbol(45, 77)\n -1\n >>> jacobi_symbol(60, 121)\n 1\n\n The relationship between the jacobi_symbol and legendre_symbol can\n be demonstrated as follows:\n\n >>> L = legendre_symbol\n >>> S(45).factors()\n {3: 2, 5: 1}\n >>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1\n True\n\n See Also\n ========\n\n is_quad_residue, legendre_symbol\n '
(m, n) = int_tested(m, n)
if (not (n % 2)):
raise ValueError('n should be an odd integer')
if ((m < 0) or (m > n)):
m = (m % n)
if (not m):
return int((n == 1))
if ((n == 1) or (m == 1)):
return 1
if (igcd(m, n) != 1):
return 0
j = 1
s = trailing(m)
m = (m >> s)
if ((s % 2) and ((n % 8) in [3, 5])):
j *= (- 1)
while (m != 1):
if (((m % 4) == 3) and ((n % 4) == 3)):
j *= (- 1)
(m, n) = ((n % m), m)
s = trailing(m)
m = (m >> s)
if ((s % 2) and ((n % 8) in [3, 5])):
j *= (- 1)
return j<|docstring|>Returns the product of the legendre_symbol(m, p)
for all the prime factors, p, of n.
Returns
=======
1. 0 if m cong 0 mod(n)
2. 1 if x**2 cong m mod(n) has a solution
3. -1 otherwise
Examples
========
>>> from sympy.ntheory import jacobi_symbol, legendre_symbol
>>> from sympy import Mul, S
>>> jacobi_symbol(45, 77)
-1
>>> jacobi_symbol(60, 121)
1
The relationship between the jacobi_symbol and legendre_symbol can
be demonstrated as follows:
>>> L = legendre_symbol
>>> S(45).factors()
{3: 2, 5: 1}
>>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1
True
See Also
========
is_quad_residue, legendre_symbol<|endoftext|>
|
164f792b287ec73f26b02fc6fd62e51e88673507708335095e9b5bede8e0fac8
|
def get_membership_degree(self, value: float):
'\n for a given input value get the degrees of truth for each member available in the Membership object.\n\n :param value: float: value for which degrees of truth are of interest\n\n :return: returns memberships with an additional degree value\n '
if (value > self.max_value):
value = self.max_value
elif (value < self.min_value):
value = self.min_value
for (category, values) in self.memberships.items():
if ((value >= values['lower_end']) and (value <= values['upper_end'])):
values['degree'] = float(values['coordinates']['degree_func'](value))
else:
values['degree'] = 0
return self.memberships
|
for a given input value get the degrees of truth for each member available in the Membership object.
:param value: float: value for which degrees of truth are of interest
:return: returns memberships with an additional degree value
|
components/controller/membership.py
|
get_membership_degree
|
Perledition/fuzzy-controller
| 2 |
python
|
def get_membership_degree(self, value: float):
'\n for a given input value get the degrees of truth for each member available in the Membership object.\n\n :param value: float: value for which degrees of truth are of interest\n\n :return: returns memberships with an additional degree value\n '
if (value > self.max_value):
value = self.max_value
elif (value < self.min_value):
value = self.min_value
for (category, values) in self.memberships.items():
if ((value >= values['lower_end']) and (value <= values['upper_end'])):
values['degree'] = float(values['coordinates']['degree_func'](value))
else:
values['degree'] = 0
return self.memberships
|
def get_membership_degree(self, value: float):
'\n for a given input value get the degrees of truth for each member available in the Membership object.\n\n :param value: float: value for which degrees of truth are of interest\n\n :return: returns memberships with an additional degree value\n '
if (value > self.max_value):
value = self.max_value
elif (value < self.min_value):
value = self.min_value
for (category, values) in self.memberships.items():
if ((value >= values['lower_end']) and (value <= values['upper_end'])):
values['degree'] = float(values['coordinates']['degree_func'](value))
else:
values['degree'] = 0
return self.memberships<|docstring|>for a given input value get the degrees of truth for each member available in the Membership object.
:param value: float: value for which degrees of truth are of interest
:return: returns memberships with an additional degree value<|endoftext|>
|
d2f81b551a58a92f22e77b92bee6973fb8793a79223e0b5ae10320287877577d
|
def get_member(self, name: str):
'\n get a member of the Membership object by it\'s name e.g "slow" if existing\n\n :param name: str: name of the member\n\n :return: dict of member, default or error case empty dict\n\n '
try:
return self.memberships[name]
except KeyError:
print('name is not valid for this group')
return dict()
|
get a member of the Membership object by it's name e.g "slow" if existing
:param name: str: name of the member
:return: dict of member, default or error case empty dict
|
components/controller/membership.py
|
get_member
|
Perledition/fuzzy-controller
| 2 |
python
|
def get_member(self, name: str):
'\n get a member of the Membership object by it\'s name e.g "slow" if existing\n\n :param name: str: name of the member\n\n :return: dict of member, default or error case empty dict\n\n '
try:
return self.memberships[name]
except KeyError:
print('name is not valid for this group')
return dict()
|
def get_member(self, name: str):
'\n get a member of the Membership object by it\'s name e.g "slow" if existing\n\n :param name: str: name of the member\n\n :return: dict of member, default or error case empty dict\n\n '
try:
return self.memberships[name]
except KeyError:
print('name is not valid for this group')
return dict()<|docstring|>get a member of the Membership object by it's name e.g "slow" if existing
:param name: str: name of the member
:return: dict of member, default or error case empty dict<|endoftext|>
|
3f351955712ebf490cc1fcd63da82609a6d7ceb94a23aa2708f42ef2cf4aabb6
|
def _contribute_max_min(self, value: float):
'\n class internal function to find the x and y values of a Membership object over all members\n :param value: float: x coordinate value of a member\n\n :return: None\n '
if (value > self.max_value):
self.max_value = value
elif (value < self.min_value):
self.min_value = value
|
class internal function to find the x and y values of a Membership object over all members
:param value: float: x coordinate value of a member
:return: None
|
components/controller/membership.py
|
_contribute_max_min
|
Perledition/fuzzy-controller
| 2 |
python
|
def _contribute_max_min(self, value: float):
'\n class internal function to find the x and y values of a Membership object over all members\n :param value: float: x coordinate value of a member\n\n :return: None\n '
if (value > self.max_value):
self.max_value = value
elif (value < self.min_value):
self.min_value = value
|
def _contribute_max_min(self, value: float):
'\n class internal function to find the x and y values of a Membership object over all members\n :param value: float: x coordinate value of a member\n\n :return: None\n '
if (value > self.max_value):
self.max_value = value
elif (value < self.min_value):
self.min_value = value<|docstring|>class internal function to find the x and y values of a Membership object over all members
:param value: float: x coordinate value of a member
:return: None<|endoftext|>
|
09fb0460bec9b77ba7b182733b68d403fd0bee69bd4ad50bff611cdb2fd2f1d7
|
def fit(self, members: dict, name: str=''):
'\n make the initialization of the Memberships objects members.\n\n :param members: dict: holding all members and ist lower, center and upper values\n :param name: str: name of the Membership object. Empty string default\n\n :return: None\n '
self.memberships = members
self.name = name
for (category, values) in self.memberships.items():
for x in list(values.values()):
self._contribute_max_min(x)
x_values = list(values.values())
if (len(set(x_values[:2])) == 1):
y_values = [1, 1, 0]
elif (len(set(x_values[1:])) == 1):
y_values = [0, 1, 1]
else:
y_values = [0, 1, 0]
values['coordinates'] = {'x': x_values, 'y': y_values, 'degree_func': interp1d(x_values, y_values)}
|
make the initialization of the Memberships objects members.
:param members: dict: holding all members and ist lower, center and upper values
:param name: str: name of the Membership object. Empty string default
:return: None
|
components/controller/membership.py
|
fit
|
Perledition/fuzzy-controller
| 2 |
python
|
def fit(self, members: dict, name: str=):
'\n make the initialization of the Memberships objects members.\n\n :param members: dict: holding all members and ist lower, center and upper values\n :param name: str: name of the Membership object. Empty string default\n\n :return: None\n '
self.memberships = members
self.name = name
for (category, values) in self.memberships.items():
for x in list(values.values()):
self._contribute_max_min(x)
x_values = list(values.values())
if (len(set(x_values[:2])) == 1):
y_values = [1, 1, 0]
elif (len(set(x_values[1:])) == 1):
y_values = [0, 1, 1]
else:
y_values = [0, 1, 0]
values['coordinates'] = {'x': x_values, 'y': y_values, 'degree_func': interp1d(x_values, y_values)}
|
def fit(self, members: dict, name: str=):
'\n make the initialization of the Memberships objects members.\n\n :param members: dict: holding all members and ist lower, center and upper values\n :param name: str: name of the Membership object. Empty string default\n\n :return: None\n '
self.memberships = members
self.name = name
for (category, values) in self.memberships.items():
for x in list(values.values()):
self._contribute_max_min(x)
x_values = list(values.values())
if (len(set(x_values[:2])) == 1):
y_values = [1, 1, 0]
elif (len(set(x_values[1:])) == 1):
y_values = [0, 1, 1]
else:
y_values = [0, 1, 0]
values['coordinates'] = {'x': x_values, 'y': y_values, 'degree_func': interp1d(x_values, y_values)}<|docstring|>make the initialization of the Memberships objects members.
:param members: dict: holding all members and ist lower, center and upper values
:param name: str: name of the Membership object. Empty string default
:return: None<|endoftext|>
|
9983b758d4218d6eb30539a4ba61abe2daa61a847ca3923def651062d3f9fae6
|
def show(self):
'\n plots all class members.\n\n :return: None but displays graph\n '
for (category, values) in self.memberships.items():
plt.plot(values['coordinates']['x'], values['coordinates']['y'], label=category)
plt.title(self.name)
plt.xticks(self.measure)
plt.legend()
plt.show()
|
plots all class members.
:return: None but displays graph
|
components/controller/membership.py
|
show
|
Perledition/fuzzy-controller
| 2 |
python
|
def show(self):
'\n plots all class members.\n\n :return: None but displays graph\n '
for (category, values) in self.memberships.items():
plt.plot(values['coordinates']['x'], values['coordinates']['y'], label=category)
plt.title(self.name)
plt.xticks(self.measure)
plt.legend()
plt.show()
|
def show(self):
'\n plots all class members.\n\n :return: None but displays graph\n '
for (category, values) in self.memberships.items():
plt.plot(values['coordinates']['x'], values['coordinates']['y'], label=category)
plt.title(self.name)
plt.xticks(self.measure)
plt.legend()
plt.show()<|docstring|>plots all class members.
:return: None but displays graph<|endoftext|>
|
24056e58902033fccd97c1d83f8f5feb00abd86009db64ac54b058a601794f7d
|
def normalize_context_key(string):
'Normalize context keys\n Function will normalize the string (remove white spaces and tailings)\n Args:\n string (str):\n Returns:\n Normalized string\n '
tmp = (string[:1].upper() + string[1:])
return tmp.replace(' ', '')
|
Normalize context keys
Function will normalize the string (remove white spaces and tailings)
Args:
string (str):
Returns:
Normalized string
|
Packs/AzureSecurityCenter/Integrations/AzureSecurityCenter_v2/AzureSecurityCenter_v2.py
|
normalize_context_key
|
jon-athon/content
| 799 |
python
|
def normalize_context_key(string):
'Normalize context keys\n Function will normalize the string (remove white spaces and tailings)\n Args:\n string (str):\n Returns:\n Normalized string\n '
tmp = (string[:1].upper() + string[1:])
return tmp.replace(' ', )
|
def normalize_context_key(string):
'Normalize context keys\n Function will normalize the string (remove white spaces and tailings)\n Args:\n string (str):\n Returns:\n Normalized string\n '
tmp = (string[:1].upper() + string[1:])
return tmp.replace(' ', )<|docstring|>Normalize context keys
Function will normalize the string (remove white spaces and tailings)
Args:
string (str):
Returns:
Normalized string<|endoftext|>
|
61db247f85ff7a27cd8a7ccbe09791f397f4de69bdd962498ac5719eebd0759b
|
def get_alert_command(client: MsClient, args: dict):
'Getting specified alert from API\n Args\n args (dict): dictionary containing commands args\n '
resource_group_name = args.get('resource_group_name')
asc_location = args.get('asc_location')
alert_id = args.get('alert_id')
alert = client.get_alert(resource_group_name, asc_location, alert_id)
final_output = list()
properties = alert.get('properties')
if properties:
basic_table_output = [{'DisplayName': properties.get('alertDisplayName'), 'CompromisedEntity': properties.get('compromisedEntity'), 'Description': properties.get('description'), 'DetectedTime': properties.get('detectedTimeUtc'), 'ReportedTime': properties.get('reportedTimeUtc'), 'ReportedSeverity': properties.get('reportedSeverity'), 'ConfidenceScore': properties.get('confidenceScore', 'None'), 'State': properties.get('state'), 'ActionTaken': properties.get('actionTaken'), 'CanBeInvestigated': properties.get('canBeInvestigated'), 'RemediationSteps': properties.get('remediationSteps'), 'VendorName': properties.get('vendorName'), 'AssociatedResource': properties.get('associatedResource'), 'AlertName': properties.get('alertName'), 'InstanceID': properties.get('instanceId', 'None'), 'ID': alert.get('name'), 'ExtendedProperties': properties.get('extendedProperties'), 'Entities': properties.get('entities'), 'SubscriptionID': properties.get('subscriptionId')}]
md = tableToMarkdown('Azure Security Center - Get Alert - Basic Property', basic_table_output, ['DisplayName', 'CompromisedEntity', 'Description', 'DetectedTime', 'ReportedTime', 'ReportedSeverity', 'ConfidenceScore', 'State', 'ActionTaken', 'CanBeInvestigated', 'RemediationSteps', 'VendorName', 'AssociatedResource', 'AlertName', 'InstanceID', 'ID'], removeNull=True)
ec = {'AzureSecurityCenter.Alert(val.ID && val.ID === obj.ID)': basic_table_output}
basic_table_entry = {'Type': entryTypes['note'], 'Contents': alert, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': md, 'EntryContext': ec}
final_output.append(basic_table_entry)
if (alert.get('properties') and alert.get('properties') and alert.get('properties').get('extendedProperties')):
extended_properties = dict()
properties = alert.get('properties')
if isinstance(properties.get('extendedProperties'), dict):
for (key, value) in alert['properties']['extendedProperties'].items():
extended_properties[normalize_context_key(key)] = value
extended_table_entry = {'Type': entryTypes['note'], 'Contents': alert['properties']['extendedProperties'], 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown('Azure Security Center - Get Alert - Extended Property', extended_properties, removeNull=True)}
final_output.append(extended_table_entry)
entities = properties.get('entities')
if entities:
if isinstance(entities, dict):
entities_table_output = list()
for entity in entities:
entities_table_output.append({'Content': ast.literal_eval(str(entity)), 'Type': entity['type']})
md = tableToMarkdown('Azure Security Center - Get Alert - Entity', entities_table_output, removeNull=True)
entities_table_entry = {'Type': entryTypes['note'], 'Contents': alert.get('properties').get('entities'), 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': md}
final_output.append(entities_table_entry)
demisto.results(final_output)
|
Getting specified alert from API
Args
args (dict): dictionary containing commands args
|
Packs/AzureSecurityCenter/Integrations/AzureSecurityCenter_v2/AzureSecurityCenter_v2.py
|
get_alert_command
|
jon-athon/content
| 799 |
python
|
def get_alert_command(client: MsClient, args: dict):
'Getting specified alert from API\n Args\n args (dict): dictionary containing commands args\n '
resource_group_name = args.get('resource_group_name')
asc_location = args.get('asc_location')
alert_id = args.get('alert_id')
alert = client.get_alert(resource_group_name, asc_location, alert_id)
final_output = list()
properties = alert.get('properties')
if properties:
basic_table_output = [{'DisplayName': properties.get('alertDisplayName'), 'CompromisedEntity': properties.get('compromisedEntity'), 'Description': properties.get('description'), 'DetectedTime': properties.get('detectedTimeUtc'), 'ReportedTime': properties.get('reportedTimeUtc'), 'ReportedSeverity': properties.get('reportedSeverity'), 'ConfidenceScore': properties.get('confidenceScore', 'None'), 'State': properties.get('state'), 'ActionTaken': properties.get('actionTaken'), 'CanBeInvestigated': properties.get('canBeInvestigated'), 'RemediationSteps': properties.get('remediationSteps'), 'VendorName': properties.get('vendorName'), 'AssociatedResource': properties.get('associatedResource'), 'AlertName': properties.get('alertName'), 'InstanceID': properties.get('instanceId', 'None'), 'ID': alert.get('name'), 'ExtendedProperties': properties.get('extendedProperties'), 'Entities': properties.get('entities'), 'SubscriptionID': properties.get('subscriptionId')}]
md = tableToMarkdown('Azure Security Center - Get Alert - Basic Property', basic_table_output, ['DisplayName', 'CompromisedEntity', 'Description', 'DetectedTime', 'ReportedTime', 'ReportedSeverity', 'ConfidenceScore', 'State', 'ActionTaken', 'CanBeInvestigated', 'RemediationSteps', 'VendorName', 'AssociatedResource', 'AlertName', 'InstanceID', 'ID'], removeNull=True)
ec = {'AzureSecurityCenter.Alert(val.ID && val.ID === obj.ID)': basic_table_output}
basic_table_entry = {'Type': entryTypes['note'], 'Contents': alert, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': md, 'EntryContext': ec}
final_output.append(basic_table_entry)
if (alert.get('properties') and alert.get('properties') and alert.get('properties').get('extendedProperties')):
extended_properties = dict()
properties = alert.get('properties')
if isinstance(properties.get('extendedProperties'), dict):
for (key, value) in alert['properties']['extendedProperties'].items():
extended_properties[normalize_context_key(key)] = value
extended_table_entry = {'Type': entryTypes['note'], 'Contents': alert['properties']['extendedProperties'], 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown('Azure Security Center - Get Alert - Extended Property', extended_properties, removeNull=True)}
final_output.append(extended_table_entry)
entities = properties.get('entities')
if entities:
if isinstance(entities, dict):
entities_table_output = list()
for entity in entities:
entities_table_output.append({'Content': ast.literal_eval(str(entity)), 'Type': entity['type']})
md = tableToMarkdown('Azure Security Center - Get Alert - Entity', entities_table_output, removeNull=True)
entities_table_entry = {'Type': entryTypes['note'], 'Contents': alert.get('properties').get('entities'), 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': md}
final_output.append(entities_table_entry)
demisto.results(final_output)
|
def get_alert_command(client: MsClient, args: dict):
'Getting specified alert from API\n Args\n args (dict): dictionary containing commands args\n '
resource_group_name = args.get('resource_group_name')
asc_location = args.get('asc_location')
alert_id = args.get('alert_id')
alert = client.get_alert(resource_group_name, asc_location, alert_id)
final_output = list()
properties = alert.get('properties')
if properties:
basic_table_output = [{'DisplayName': properties.get('alertDisplayName'), 'CompromisedEntity': properties.get('compromisedEntity'), 'Description': properties.get('description'), 'DetectedTime': properties.get('detectedTimeUtc'), 'ReportedTime': properties.get('reportedTimeUtc'), 'ReportedSeverity': properties.get('reportedSeverity'), 'ConfidenceScore': properties.get('confidenceScore', 'None'), 'State': properties.get('state'), 'ActionTaken': properties.get('actionTaken'), 'CanBeInvestigated': properties.get('canBeInvestigated'), 'RemediationSteps': properties.get('remediationSteps'), 'VendorName': properties.get('vendorName'), 'AssociatedResource': properties.get('associatedResource'), 'AlertName': properties.get('alertName'), 'InstanceID': properties.get('instanceId', 'None'), 'ID': alert.get('name'), 'ExtendedProperties': properties.get('extendedProperties'), 'Entities': properties.get('entities'), 'SubscriptionID': properties.get('subscriptionId')}]
md = tableToMarkdown('Azure Security Center - Get Alert - Basic Property', basic_table_output, ['DisplayName', 'CompromisedEntity', 'Description', 'DetectedTime', 'ReportedTime', 'ReportedSeverity', 'ConfidenceScore', 'State', 'ActionTaken', 'CanBeInvestigated', 'RemediationSteps', 'VendorName', 'AssociatedResource', 'AlertName', 'InstanceID', 'ID'], removeNull=True)
ec = {'AzureSecurityCenter.Alert(val.ID && val.ID === obj.ID)': basic_table_output}
basic_table_entry = {'Type': entryTypes['note'], 'Contents': alert, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': md, 'EntryContext': ec}
final_output.append(basic_table_entry)
if (alert.get('properties') and alert.get('properties') and alert.get('properties').get('extendedProperties')):
extended_properties = dict()
properties = alert.get('properties')
if isinstance(properties.get('extendedProperties'), dict):
for (key, value) in alert['properties']['extendedProperties'].items():
extended_properties[normalize_context_key(key)] = value
extended_table_entry = {'Type': entryTypes['note'], 'Contents': alert['properties']['extendedProperties'], 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown('Azure Security Center - Get Alert - Extended Property', extended_properties, removeNull=True)}
final_output.append(extended_table_entry)
entities = properties.get('entities')
if entities:
if isinstance(entities, dict):
entities_table_output = list()
for entity in entities:
entities_table_output.append({'Content': ast.literal_eval(str(entity)), 'Type': entity['type']})
md = tableToMarkdown('Azure Security Center - Get Alert - Entity', entities_table_output, removeNull=True)
entities_table_entry = {'Type': entryTypes['note'], 'Contents': alert.get('properties').get('entities'), 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': md}
final_output.append(entities_table_entry)
demisto.results(final_output)<|docstring|>Getting specified alert from API
Args
args (dict): dictionary containing commands args<|endoftext|>
|
0f18b51afcd9f33a3896b7d2af23435df7dc130017197030725aaf7bc17bd02c
|
def list_alerts_command(client: MsClient, args: dict):
'Getting all alerts\n\n Args:\n client:\n args (dict): usually demisto.args()\n '
resource_group_name = args.get('resource_group_name')
asc_location = args.get('asc_location')
filter_query = args.get('filter')
select_query = args.get('select')
expand_query = args.get('expand')
alerts = client.list_alerts(resource_group_name, asc_location, filter_query, select_query, expand_query).get('value')
outputs = list()
for alert in alerts:
properties = alert.get('properties')
if properties:
outputs.append({'DisplayName': properties.get('alertDisplayName'), 'CompromisedEntity': properties.get('compromisedEntity'), 'DetectedTime': properties.get('detectedTimeUtc'), 'ReportedSeverity': properties.get('reportedSeverity'), 'State': properties.get('state'), 'ActionTaken': properties.get('actionTaken'), 'Description': properties.get('description'), 'ID': alert.get('name')})
md = tableToMarkdown('Azure Security Center - List Alerts', outputs, ['DisplayName', 'CompromisedEntity', 'DetectedTime', 'ReportedSeverity', 'State', 'ActionTaken', 'Description', 'ID'], removeNull=True)
ec = {'AzureSecurityCenter.Alert(val.ID && val.ID === obj.ID)': outputs}
return (md, ec, alerts)
|
Getting all alerts
Args:
client:
args (dict): usually demisto.args()
|
Packs/AzureSecurityCenter/Integrations/AzureSecurityCenter_v2/AzureSecurityCenter_v2.py
|
list_alerts_command
|
jon-athon/content
| 799 |
python
|
def list_alerts_command(client: MsClient, args: dict):
'Getting all alerts\n\n Args:\n client:\n args (dict): usually demisto.args()\n '
resource_group_name = args.get('resource_group_name')
asc_location = args.get('asc_location')
filter_query = args.get('filter')
select_query = args.get('select')
expand_query = args.get('expand')
alerts = client.list_alerts(resource_group_name, asc_location, filter_query, select_query, expand_query).get('value')
outputs = list()
for alert in alerts:
properties = alert.get('properties')
if properties:
outputs.append({'DisplayName': properties.get('alertDisplayName'), 'CompromisedEntity': properties.get('compromisedEntity'), 'DetectedTime': properties.get('detectedTimeUtc'), 'ReportedSeverity': properties.get('reportedSeverity'), 'State': properties.get('state'), 'ActionTaken': properties.get('actionTaken'), 'Description': properties.get('description'), 'ID': alert.get('name')})
md = tableToMarkdown('Azure Security Center - List Alerts', outputs, ['DisplayName', 'CompromisedEntity', 'DetectedTime', 'ReportedSeverity', 'State', 'ActionTaken', 'Description', 'ID'], removeNull=True)
ec = {'AzureSecurityCenter.Alert(val.ID && val.ID === obj.ID)': outputs}
return (md, ec, alerts)
|
def list_alerts_command(client: MsClient, args: dict):
'Getting all alerts\n\n Args:\n client:\n args (dict): usually demisto.args()\n '
resource_group_name = args.get('resource_group_name')
asc_location = args.get('asc_location')
filter_query = args.get('filter')
select_query = args.get('select')
expand_query = args.get('expand')
alerts = client.list_alerts(resource_group_name, asc_location, filter_query, select_query, expand_query).get('value')
outputs = list()
for alert in alerts:
properties = alert.get('properties')
if properties:
outputs.append({'DisplayName': properties.get('alertDisplayName'), 'CompromisedEntity': properties.get('compromisedEntity'), 'DetectedTime': properties.get('detectedTimeUtc'), 'ReportedSeverity': properties.get('reportedSeverity'), 'State': properties.get('state'), 'ActionTaken': properties.get('actionTaken'), 'Description': properties.get('description'), 'ID': alert.get('name')})
md = tableToMarkdown('Azure Security Center - List Alerts', outputs, ['DisplayName', 'CompromisedEntity', 'DetectedTime', 'ReportedSeverity', 'State', 'ActionTaken', 'Description', 'ID'], removeNull=True)
ec = {'AzureSecurityCenter.Alert(val.ID && val.ID === obj.ID)': outputs}
return (md, ec, alerts)<|docstring|>Getting all alerts
Args:
client:
args (dict): usually demisto.args()<|endoftext|>
|
79d6a7b04011934b5e2ad54149dd3849352d21b06b2c02173cad55fe6cab0dd3
|
def update_alert_command(client: MsClient, args: dict):
'Update given alert\n\n Args:\n client: MsClient\n args (dict): usually demisto.args()\n '
resource_group_name = args.get('resource_group_name')
asc_location = args.get('asc_location')
alert_id = args.get('alert_id')
alert_update_action_type = args.get('alert_update_action_type')
client.update_alert(resource_group_name, asc_location, alert_id, alert_update_action_type)
outputs = {'ID': alert_id, 'ActionTaken': alert_update_action_type}
ec = {'AzureSecurityCenter.Alert(val.ID && val.ID === obj.ID)': outputs}
return (f'Alert - {alert_id} has been set to {alert_update_action_type}.', ec, None)
|
Update given alert
Args:
client: MsClient
args (dict): usually demisto.args()
|
Packs/AzureSecurityCenter/Integrations/AzureSecurityCenter_v2/AzureSecurityCenter_v2.py
|
update_alert_command
|
jon-athon/content
| 799 |
python
|
def update_alert_command(client: MsClient, args: dict):
'Update given alert\n\n Args:\n client: MsClient\n args (dict): usually demisto.args()\n '
resource_group_name = args.get('resource_group_name')
asc_location = args.get('asc_location')
alert_id = args.get('alert_id')
alert_update_action_type = args.get('alert_update_action_type')
client.update_alert(resource_group_name, asc_location, alert_id, alert_update_action_type)
outputs = {'ID': alert_id, 'ActionTaken': alert_update_action_type}
ec = {'AzureSecurityCenter.Alert(val.ID && val.ID === obj.ID)': outputs}
return (f'Alert - {alert_id} has been set to {alert_update_action_type}.', ec, None)
|
def update_alert_command(client: MsClient, args: dict):
'Update given alert\n\n Args:\n client: MsClient\n args (dict): usually demisto.args()\n '
resource_group_name = args.get('resource_group_name')
asc_location = args.get('asc_location')
alert_id = args.get('alert_id')
alert_update_action_type = args.get('alert_update_action_type')
client.update_alert(resource_group_name, asc_location, alert_id, alert_update_action_type)
outputs = {'ID': alert_id, 'ActionTaken': alert_update_action_type}
ec = {'AzureSecurityCenter.Alert(val.ID && val.ID === obj.ID)': outputs}
return (f'Alert - {alert_id} has been set to {alert_update_action_type}.', ec, None)<|docstring|>Update given alert
Args:
client: MsClient
args (dict): usually demisto.args()<|endoftext|>
|
a24c292f46d9cc37e910b5ed9b6a9865ca3c514b06ec8161156f2dbbde69ba6f
|
def list_locations_command(client: MsClient):
'Getting all locations\n '
locations = client.list_locations().get('value')
outputs = list()
if locations:
for location in locations:
if (location.get('properties') and location.get('properties').get('homeRegionName')):
home_region_name = location.get('properties').get('homeRegionName')
else:
home_region_name = None
outputs.append({'HomeRegionName': home_region_name, 'Name': location.get('name'), 'ID': location.get('id')})
md = tableToMarkdown('Azure Security Center - List Locations', outputs, ['HomeRegionName', 'Name', 'ID'], removeNull=True)
ec = {'AzureSecurityCenter.Location(val.ID && val.ID === obj.ID)': outputs}
return (md, ec, locations)
else:
return ('No locations found', None, None)
|
Getting all locations
|
Packs/AzureSecurityCenter/Integrations/AzureSecurityCenter_v2/AzureSecurityCenter_v2.py
|
list_locations_command
|
jon-athon/content
| 799 |
python
|
def list_locations_command(client: MsClient):
'\n '
locations = client.list_locations().get('value')
outputs = list()
if locations:
for location in locations:
if (location.get('properties') and location.get('properties').get('homeRegionName')):
home_region_name = location.get('properties').get('homeRegionName')
else:
home_region_name = None
outputs.append({'HomeRegionName': home_region_name, 'Name': location.get('name'), 'ID': location.get('id')})
md = tableToMarkdown('Azure Security Center - List Locations', outputs, ['HomeRegionName', 'Name', 'ID'], removeNull=True)
ec = {'AzureSecurityCenter.Location(val.ID && val.ID === obj.ID)': outputs}
return (md, ec, locations)
else:
return ('No locations found', None, None)
|
def list_locations_command(client: MsClient):
'\n '
locations = client.list_locations().get('value')
outputs = list()
if locations:
for location in locations:
if (location.get('properties') and location.get('properties').get('homeRegionName')):
home_region_name = location.get('properties').get('homeRegionName')
else:
home_region_name = None
outputs.append({'HomeRegionName': home_region_name, 'Name': location.get('name'), 'ID': location.get('id')})
md = tableToMarkdown('Azure Security Center - List Locations', outputs, ['HomeRegionName', 'Name', 'ID'], removeNull=True)
ec = {'AzureSecurityCenter.Location(val.ID && val.ID === obj.ID)': outputs}
return (md, ec, locations)
else:
return ('No locations found', None, None)<|docstring|>Getting all locations<|endoftext|>
|
1404d27cda31f7d74ccb542f56045538bc2aad9595e64d10a761e95c6f697212
|
def update_atp_command(client: MsClient, args: dict):
'Updating given Advanced Threat Protection (enable/disable)\n\n Args:\n client:\n args (dict): usually demisto.args()\n '
resource_group_name = args.get('resource_group_name')
setting_name = args.get('setting_name')
is_enabled = args.get('is_enabled')
storage_account = args.get('storage_account')
response = client.update_atp(resource_group_name, storage_account, setting_name, is_enabled)
outputs = {'ID': response.get('id'), 'Name': response.get('name'), 'IsEnabled': response.get('properties').get('is_enabled')}
md = tableToMarkdown('Azure Security Center - Update Advanced Threat Detection Setting', outputs, ['ID', 'Name', 'IsEnabled'], removeNull=True)
ec = {'AzureSecurityCenter.AdvancedThreatProtection(val.ID && val.ID === obj.ID)': outputs}
return (md, ec, response)
|
Updating given Advanced Threat Protection (enable/disable)
Args:
client:
args (dict): usually demisto.args()
|
Packs/AzureSecurityCenter/Integrations/AzureSecurityCenter_v2/AzureSecurityCenter_v2.py
|
update_atp_command
|
jon-athon/content
| 799 |
python
|
def update_atp_command(client: MsClient, args: dict):
'Updating given Advanced Threat Protection (enable/disable)\n\n Args:\n client:\n args (dict): usually demisto.args()\n '
resource_group_name = args.get('resource_group_name')
setting_name = args.get('setting_name')
is_enabled = args.get('is_enabled')
storage_account = args.get('storage_account')
response = client.update_atp(resource_group_name, storage_account, setting_name, is_enabled)
outputs = {'ID': response.get('id'), 'Name': response.get('name'), 'IsEnabled': response.get('properties').get('is_enabled')}
md = tableToMarkdown('Azure Security Center - Update Advanced Threat Detection Setting', outputs, ['ID', 'Name', 'IsEnabled'], removeNull=True)
ec = {'AzureSecurityCenter.AdvancedThreatProtection(val.ID && val.ID === obj.ID)': outputs}
return (md, ec, response)
|
def update_atp_command(client: MsClient, args: dict):
'Updating given Advanced Threat Protection (enable/disable)\n\n Args:\n client:\n args (dict): usually demisto.args()\n '
resource_group_name = args.get('resource_group_name')
setting_name = args.get('setting_name')
is_enabled = args.get('is_enabled')
storage_account = args.get('storage_account')
response = client.update_atp(resource_group_name, storage_account, setting_name, is_enabled)
outputs = {'ID': response.get('id'), 'Name': response.get('name'), 'IsEnabled': response.get('properties').get('is_enabled')}
md = tableToMarkdown('Azure Security Center - Update Advanced Threat Detection Setting', outputs, ['ID', 'Name', 'IsEnabled'], removeNull=True)
ec = {'AzureSecurityCenter.AdvancedThreatProtection(val.ID && val.ID === obj.ID)': outputs}
return (md, ec, response)<|docstring|>Updating given Advanced Threat Protection (enable/disable)
Args:
client:
args (dict): usually demisto.args()<|endoftext|>
|
4c97fbe7b0b7d80b412623bd0aaa2a8f517bd0daad237f4f37cae7d99f262bcc
|
def get_atp_command(client: MsClient, args: dict):
'Get given Advanced Threat Protection settings\n\n Args:\n client:\n args (dict): usually demisto.args()\n '
resource_group_name = args.get('resource_group_name')
setting_name = args.get('setting_name')
storage_account = args.get('storage_account')
response = client.get_atp(resource_group_name, storage_account, setting_name)
outputs = {'ID': response.get('id'), 'Name': response.get('name'), 'IsEnabled': (response['properties']['isEnabled'] if (response.get('properties') and response.get('properties').get('isEnabled')) else None)}
md = tableToMarkdown('Azure Security Center - Get Advanced Threat Detection Setting', outputs, ['ID', 'Name', 'IsEnabled'], removeNull=True)
ec = {'AzureSecurityCenter.AdvancedThreatProtection(val.ID && val.ID === obj.ID)': outputs}
return (md, ec, response)
|
Get given Advanced Threat Protection settings
Args:
client:
args (dict): usually demisto.args()
|
Packs/AzureSecurityCenter/Integrations/AzureSecurityCenter_v2/AzureSecurityCenter_v2.py
|
get_atp_command
|
jon-athon/content
| 799 |
python
|
def get_atp_command(client: MsClient, args: dict):
'Get given Advanced Threat Protection settings\n\n Args:\n client:\n args (dict): usually demisto.args()\n '
resource_group_name = args.get('resource_group_name')
setting_name = args.get('setting_name')
storage_account = args.get('storage_account')
response = client.get_atp(resource_group_name, storage_account, setting_name)
outputs = {'ID': response.get('id'), 'Name': response.get('name'), 'IsEnabled': (response['properties']['isEnabled'] if (response.get('properties') and response.get('properties').get('isEnabled')) else None)}
md = tableToMarkdown('Azure Security Center - Get Advanced Threat Detection Setting', outputs, ['ID', 'Name', 'IsEnabled'], removeNull=True)
ec = {'AzureSecurityCenter.AdvancedThreatProtection(val.ID && val.ID === obj.ID)': outputs}
return (md, ec, response)
|
def get_atp_command(client: MsClient, args: dict):
'Get given Advanced Threat Protection settings\n\n Args:\n client:\n args (dict): usually demisto.args()\n '
resource_group_name = args.get('resource_group_name')
setting_name = args.get('setting_name')
storage_account = args.get('storage_account')
response = client.get_atp(resource_group_name, storage_account, setting_name)
outputs = {'ID': response.get('id'), 'Name': response.get('name'), 'IsEnabled': (response['properties']['isEnabled'] if (response.get('properties') and response.get('properties').get('isEnabled')) else None)}
md = tableToMarkdown('Azure Security Center - Get Advanced Threat Detection Setting', outputs, ['ID', 'Name', 'IsEnabled'], removeNull=True)
ec = {'AzureSecurityCenter.AdvancedThreatProtection(val.ID && val.ID === obj.ID)': outputs}
return (md, ec, response)<|docstring|>Get given Advanced Threat Protection settings
Args:
client:
args (dict): usually demisto.args()<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.