INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Calculates the distance of a given image to the original image. | def normalized_distance(self, image):
"""Calculates the distance of a given image to the
original image.
Parameters
----------
image : `numpy.ndarray`
The image that should be compared to the original image.
Returns
-------
:class:`Distance`
... |
Interface to criterion. is_adverarial that calls __new_adversarial if necessary. | def __is_adversarial(self, image, predictions, in_bounds):
"""Interface to criterion.is_adverarial that calls
__new_adversarial if necessary.
Parameters
----------
predictions : :class:`numpy.ndarray`
A vector with the pre-softmax predictions for some image.
... |
Interface to model. channel_axis for attacks. | def channel_axis(self, batch):
"""Interface to model.channel_axis for attacks.
Parameters
----------
batch : bool
Controls whether the index of the axis for a batch of images
(4 dimensions) or a single image (3 dimensions) should be returned.
"""
... |
Returns true if _backward and _forward_backward can be called by an attack False otherwise. | def has_gradient(self):
"""Returns true if _backward and _forward_backward can be called
by an attack, False otherwise.
"""
try:
self.__model.gradient
self.__model.predictions_and_gradient
except AttributeError:
return False
else:
... |
Interface to model. predictions for attacks. | def predictions(self, image, strict=True, return_details=False):
"""Interface to model.predictions for attacks.
Parameters
----------
image : `numpy.ndarray`
Single input with shape as expected by the model
(without the batch dimension).
strict : bool
... |
Interface to model. batch_predictions for attacks. | def batch_predictions(
self, images, greedy=False, strict=True, return_details=False):
"""Interface to model.batch_predictions for attacks.
Parameters
----------
images : `numpy.ndarray`
Batch of inputs with shape as expected by the model.
greedy : bool
... |
Interface to model. gradient for attacks. | def gradient(self, image=None, label=None, strict=True):
"""Interface to model.gradient for attacks.
Parameters
----------
image : `numpy.ndarray`
Single input with shape as expected by the model
(without the batch dimension).
Defaults to the original... |
Interface to model. predictions_and_gradient for attacks. | def predictions_and_gradient(
self, image=None, label=None, strict=True, return_details=False):
"""Interface to model.predictions_and_gradient for attacks.
Parameters
----------
image : `numpy.ndarray`
Single input with shape as expected by the model
... |
Interface to model. backward for attacks. | def backward(self, gradient, image=None, strict=True):
"""Interface to model.backward for attacks.
Parameters
----------
gradient : `numpy.ndarray`
Gradient of some loss w.r.t. the logits.
image : `numpy.ndarray`
Single input with shape as expected by the... |
Returns the loss and the gradient of the loss w. r. t. x assuming that logits = model ( x ). | def loss_function(cls, const, a, x, logits, reconstructed_original,
confidence, min_, max_):
"""Returns the loss and the gradient of the loss w.r.t. x,
assuming that logits = model(x)."""
targeted = a.target_class() is not None
if targeted:
c_minimize =... |
Returns the index of the largest logit ignoring the class that is passed as exclude. | def best_other_class(logits, exclude):
"""Returns the index of the largest logit, ignoring the class that
is passed as `exclude`."""
other_logits = logits - onehot_like(logits, exclude, value=np.inf)
return np.argmax(other_logits) |
Concatenates the names of the given criteria in alphabetical order. | def name(self):
"""Concatenates the names of the given criteria in alphabetical order.
If a sub-criterion is itself a combined criterion, its name is
first split into the individual names and the names of the
sub-sub criteria is used instead of the name of the sub-criterion.
Thi... |
Difference map of the image. Approximate derivatives of the function image [ c:: ] ( e. g. PyTorch ) or image [:: c ] ( e. g. Keras ). dfdx dfdy = difference_map ( image ) In: image: numpy. ndarray of shape C x h x w or h x w x C with C = 1 or C = 3 ( color channels ) h w > = 3 and [ type ] is Float or Double. Contains... | def _difference_map(image, color_axis):
"""Difference map of the image.
Approximate derivatives of the function image[c, :, :]
(e.g. PyTorch) or image[:, :, c] (e.g. Keras).
dfdx, dfdy = difference_map(image)
In:
image: numpy.ndarray
of shape C x h x w or h x w x C, with C = 1 or C = 3
... |
Calculate the composition of the function image with the vector field vec_field by interpolation. new_func = compose ( image vec_field ) In: image: numpy. ndarray of shape C x h x w with C = 3 or C = 1 ( color channels ) h w > = 2 and [ type ] = Float or Double. Contains the values of a function f: R ^ 2 - > R ^ C on t... | def _compose(image, vec_field, color_axis):
"""Calculate the composition of the function image with the vector
field vec_field by interpolation.
new_func = compose(image, vec_field)
In:
image: numpy.ndarray
of shape C x h x w with C = 3 or C = 1 (color channels),
h, w >= 2, and [type... |
Calculate the deformation vector field In: fval: float gradf: numpy. ndarray of shape C x h x w with C = 3 or C = 1 ( color channels ) h w > = 1. d1x: numpy. ndarray of shape C x h x w and [ type ] = Float or Double. d2x: numpy. ndarray of shape C x h x w and [ type ] = Float or Double. smooth: float Width of the Gauss... | def _create_vec_field(fval, gradf, d1x, d2x, color_axis, smooth=0):
"""Calculate the deformation vector field
In:
fval: float
gradf: numpy.ndarray
of shape C x h x w with C = 3 or C = 1
(color channels), h, w >= 1.
d1x: numpy.ndarray
of shape C x h x w and [type] = 'Float' or... |
Transforms predictions into probability values. | def softmax(logits):
"""Transforms predictions into probability values.
Parameters
----------
logits : array_like
The logits predicted by the model.
Returns
-------
`numpy.ndarray`
Probability values corresponding to the logits.
"""
assert logits.ndim == 1
# f... |
Calculates the cross - entropy. | def crossentropy(label, logits):
"""Calculates the cross-entropy.
Parameters
----------
logits : array_like
The logits predicted by the model.
label : int
The label describing the target distribution.
Returns
-------
float
The cross-entropy between softmax(logit... |
Calculates the cross - entropy for a batch of logits. | def batch_crossentropy(label, logits):
"""Calculates the cross-entropy for a batch of logits.
Parameters
----------
logits : array_like
The logits predicted by the model for a batch of inputs.
label : int
The label describing the target distribution.
Returns
-------
np.... |
Binarizes the values of x. | def binarize(x, values, threshold=None, included_in='upper'):
"""Binarizes the values of x.
Parameters
----------
values : tuple of two floats
The lower and upper value to which the inputs are mapped.
threshold : float
The threshold; defaults to (values[0] + values[1]) / 2 if None.
... |
Returns an example image and its imagenet class label. | def imagenet_example(shape=(224, 224), data_format='channels_last'):
""" Returns an example image and its imagenet class label.
Parameters
----------
shape : list of integers
The shape of the returned image.
data_format : str
"channels_first" or "channels_last"
Returns
----... |
Returns a batch of example images and the corresponding labels | def samples(dataset='imagenet', index=0, batchsize=1, shape=(224, 224),
data_format='channels_last'):
''' Returns a batch of example images and the corresponding labels
Parameters
----------
dataset : string
The data set to load (options: imagenet, mnist, cifar10,
cifar100, ... |
Creates an array like a with all values set to 0 except one. | def onehot_like(a, index, value=1):
"""Creates an array like a, with all values
set to 0 except one.
Parameters
----------
a : array_like
The returned one-hot array will have the same shape
and dtype as this array
index : int
The index that should be set to `value`
v... |
Looks up the precomputed adversarial image for a given image. | def _get_output(self, a, image):
""" Looks up the precomputed adversarial image for a given image.
"""
sd = np.square(self._input_images - image)
mses = np.mean(sd, axis=tuple(range(1, sd.ndim)))
index = np.argmin(mses)
# if we run into numerical problems with this appr... |
backward: callable callable that backpropagates the gradient of the model w. r. t to preprocessed input through the preprocessing to get the gradient of the model s output w. r. t. the input before preprocessing dmdp: gradient of model w. r. t. preprocessed input | def _process_gradient(self, backward, dmdp):
"""
backward: `callable`
callable that backpropagates the gradient of the model w.r.t to
preprocessed input through the preprocessing to get the gradient
of the model's output w.r.t. the input before preprocessing
d... |
Convenience method that calculates predictions for a single image. | def predictions(self, image):
"""Convenience method that calculates predictions for a single image.
Parameters
----------
image : `numpy.ndarray`
Single input with shape as expected by the model
(without the batch dimension).
Returns
-------
... |
Calculates the gradient of the cross - entropy loss w. r. t. the image. | def gradient(self, image, label):
"""Calculates the gradient of the cross-entropy loss w.r.t. the image.
The default implementation calls predictions_and_gradient.
Subclasses can provide more efficient implementations that
only calculate the gradient.
Parameters
-------... |
Clone a remote git repository to a local path. | def clone(git_uri):
"""
Clone a remote git repository to a local path.
:param git_uri: the URI to the git repository to be cloned
:return: the generated local path where the repository has been cloned to
"""
hash_digest = sha256_hash(git_uri)
local_path = home_directory_path(FOLDER, hash_di... |
: param command:: param parser:: param cl_args:: param unknown_args:: return: | def run(command, parser, cl_args, unknown_args):
'''
:param command:
:param parser:
:param cl_args:
:param unknown_args:
:return:
'''
Log.debug("Deactivate Args: %s", cl_args)
return cli_helper.run(command, cl_args, "deactivate topology") |
Modified version of poll () from asyncore module | def poll(self, timeout=0.0):
"""Modified version of poll() from asyncore module"""
if self.sock_map is None:
Log.warning("Socket map is not registered to Gateway Looper")
readable_lst = []
writable_lst = []
error_lst = []
if self.sock_map is not None:
for fd, obj in self.sock_map.it... |
configure logging | def configure(level, logfile=None):
""" configure logging """
log_format = "%(asctime)s-%(levelname)s: %(message)s"
date_format = '%a, %d %b %Y %H:%M:%S'
logging.basicConfig(format=log_format, datefmt=date_format)
Log.setLevel(level)
if logfile is not None:
fh = logging.FileHandler(logfile)
fh.set... |
Result may be a python dictionary array or a primitive type that can be converted to JSON for writing back the result. | def write_success_response(self, result):
"""
Result may be a python dictionary, array or a primitive type
that can be converted to JSON for writing back the result.
"""
response = self.make_success_response(result)
now = time.time()
spent = now - self.basehandler_starttime
response[cons... |
Writes the message as part of the response and sets 404 status. | def write_error_response(self, message):
"""
Writes the message as part of the response and sets 404 status.
"""
self.set_status(404)
response = self.make_error_response(str(message))
now = time.time()
spent = now - self.basehandler_starttime
response[constants.RESPONSE_KEY_EXECUTION_TIM... |
write back json response | def write_json_response(self, response):
""" write back json response """
self.write(tornado.escape.json_encode(response))
self.set_header("Content-Type", "application/json") |
Makes the base dict for the response. The status is the string value for the key status of the response. This should be success or failure. | def make_response(self, status):
"""
Makes the base dict for the response.
The status is the string value for
the key "status" of the response. This
should be "success" or "failure".
"""
response = {
constants.RESPONSE_KEY_STATUS: status,
constants.RESPONSE_KEY_VERSION: const... |
Makes the python dict corresponding to the JSON that needs to be sent for a successful response. Result is the actual payload that gets sent. | def make_success_response(self, result):
"""
Makes the python dict corresponding to the
JSON that needs to be sent for a successful
response. Result is the actual payload
that gets sent.
"""
response = self.make_response(constants.RESPONSE_STATUS_SUCCESS)
response[constants.RESPONSE_KEY_... |
Makes the python dict corresponding to the JSON that needs to be sent for a failed response. Message is the message that is sent as the reason for failure. | def make_error_response(self, message):
"""
Makes the python dict corresponding to the
JSON that needs to be sent for a failed
response. Message is the message that is
sent as the reason for failure.
"""
response = self.make_response(constants.RESPONSE_STATUS_FAILURE)
response[constants.... |
Helper function to get request argument. Raises exception if argument is missing. Returns the cluster argument. | def get_argument_cluster(self):
"""
Helper function to get request argument.
Raises exception if argument is missing.
Returns the cluster argument.
"""
try:
return self.get_argument(constants.PARAM_CLUSTER)
except tornado.web.MissingArgumentError as e:
raise Exception(e.log_messa... |
Helper function to get request argument. Raises exception if argument is missing. Returns the role argument. | def get_argument_role(self):
"""
Helper function to get request argument.
Raises exception if argument is missing.
Returns the role argument.
"""
try:
return self.get_argument(constants.PARAM_ROLE, default=None)
except tornado.web.MissingArgumentError as e:
raise Exception(e.log_... |
Helper function to get request argument. Raises exception if argument is missing. Returns the environ argument. | def get_argument_environ(self):
"""
Helper function to get request argument.
Raises exception if argument is missing.
Returns the environ argument.
"""
try:
return self.get_argument(constants.PARAM_ENVIRON)
except tornado.web.MissingArgumentError as e:
raise Exception(e.log_messa... |
Helper function to get topology argument. Raises exception if argument is missing. Returns the topology argument. | def get_argument_topology(self):
"""
Helper function to get topology argument.
Raises exception if argument is missing.
Returns the topology argument.
"""
try:
topology = self.get_argument(constants.PARAM_TOPOLOGY)
return topology
except tornado.web.MissingArgumentError as e:
... |
Helper function to get component argument. Raises exception if argument is missing. Returns the component argument. | def get_argument_component(self):
"""
Helper function to get component argument.
Raises exception if argument is missing.
Returns the component argument.
"""
try:
component = self.get_argument(constants.PARAM_COMPONENT)
return component
except tornado.web.MissingArgumentError as ... |
Helper function to get instance argument. Raises exception if argument is missing. Returns the instance argument. | def get_argument_instance(self):
"""
Helper function to get instance argument.
Raises exception if argument is missing.
Returns the instance argument.
"""
try:
instance = self.get_argument(constants.PARAM_INSTANCE)
return instance
except tornado.web.MissingArgumentError as e:
... |
Helper function to get starttime argument. Raises exception if argument is missing. Returns the starttime argument. | def get_argument_starttime(self):
"""
Helper function to get starttime argument.
Raises exception if argument is missing.
Returns the starttime argument.
"""
try:
starttime = self.get_argument(constants.PARAM_STARTTIME)
return starttime
except tornado.web.MissingArgumentError as ... |
Helper function to get endtime argument. Raises exception if argument is missing. Returns the endtime argument. | def get_argument_endtime(self):
"""
Helper function to get endtime argument.
Raises exception if argument is missing.
Returns the endtime argument.
"""
try:
endtime = self.get_argument(constants.PARAM_ENDTIME)
return endtime
except tornado.web.MissingArgumentError as e:
rai... |
Helper function to get query argument. Raises exception if argument is missing. Returns the query argument. | def get_argument_query(self):
"""
Helper function to get query argument.
Raises exception if argument is missing.
Returns the query argument.
"""
try:
query = self.get_argument(constants.PARAM_QUERY)
return query
except tornado.web.MissingArgumentError as e:
raise Exception... |
Helper function to get offset argument. Raises exception if argument is missing. Returns the offset argument. | def get_argument_offset(self):
"""
Helper function to get offset argument.
Raises exception if argument is missing.
Returns the offset argument.
"""
try:
offset = self.get_argument(constants.PARAM_OFFSET)
return offset
except tornado.web.MissingArgumentError as e:
raise Exc... |
Helper function to get length argument. Raises exception if argument is missing. Returns the length argument. | def get_argument_length(self):
"""
Helper function to get length argument.
Raises exception if argument is missing.
Returns the length argument.
"""
try:
length = self.get_argument(constants.PARAM_LENGTH)
return length
except tornado.web.MissingArgumentError as e:
raise Exc... |
Helper function to get metricname arguments. Notice that it is get_argument s variation which means that this can be repeated. Raises exception if argument is missing. Returns a list of metricname arguments | def get_required_arguments_metricnames(self):
"""
Helper function to get metricname arguments.
Notice that it is get_argument"s" variation, which means that this can be repeated.
Raises exception if argument is missing.
Returns a list of metricname arguments
"""
try:
metricnames = self... |
Helper function to validate interval. An interval is valid if starttime and endtime are integrals and starttime is less than the endtime. Raises exception if interval is not valid. | def validateInterval(self, startTime, endTime):
"""
Helper function to validate interval.
An interval is valid if starttime and endtime are integrals,
and starttime is less than the endtime.
Raises exception if interval is not valid.
"""
start = int(startTime)
end = int(endTime)
if s... |
Tries to connect to the Heron Server | def start_connect(self):
"""Tries to connect to the Heron Server
``loop()`` method needs to be called after this.
"""
Log.debug("In start_connect() of %s" % self._get_classname())
# TODO: specify buffer size, exception handling
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
# when ... |
Registers protobuf message builders that this client wants to receive | def register_on_message(self, msg_builder):
"""Registers protobuf message builders that this client wants to receive
:param msg_builder: callable to create a protobuf message that this client wants to receive
"""
message = msg_builder()
Log.debug("In register_on_message(): %s" % message.DESCRIPTOR.... |
Sends a request message ( REQID is non - zero ) | def send_request(self, request, context, response_type, timeout_sec):
"""Sends a request message (REQID is non-zero)"""
# generates a unique request id
reqid = REQID.generate()
Log.debug("%s: In send_request() with REQID: %s" % (self._get_classname(), str(reqid)))
# register response message type
... |
Sends a message ( REQID is zero ) | def send_message(self, message):
"""Sends a message (REQID is zero)"""
Log.debug("In send_message() of %s" % self._get_classname())
outgoing_pkt = OutgoingPacket.create_packet(REQID.generate_zero(), message)
self._send_packet(outgoing_pkt) |
Handles timeout | def handle_timeout(self, reqid):
"""Handles timeout"""
if reqid in self.context_map:
context = self.context_map.pop(reqid)
self.response_message_map.pop(reqid)
self.on_response(StatusCode.TIMEOUT_ERROR, context, None) |
Create a tar file with a given set of files | def create_tar(tar_filename, files, config_dir, config_files):
'''
Create a tar file with a given set of files
'''
with contextlib.closing(tarfile.open(tar_filename, 'w:gz', dereference=True)) as tar:
for filename in files:
if os.path.isfile(filename):
tar.add(filename, arcname=os.path.basenam... |
Retrieve the given subparser from parser | def get_subparser(parser, command):
'''
Retrieve the given subparser from parser
'''
# pylint: disable=protected-access
subparsers_actions = [action for action in parser._actions
if isinstance(action, argparse._SubParsersAction)]
# there will probably only be one subparser_action,
... |
This will extract heron directory from. pex file. | def get_heron_dir():
"""
This will extract heron directory from .pex file.
For example,
when __file__ is '/Users/heron-user/bin/heron/heron/tools/common/src/python/utils/config.pyc', and
its real path is '/Users/heron-user/.heron/bin/heron/tools/common/src/python/utils/config.pyc',
the internal variable ``... |
Get all the heron lib jars with the absolute paths | def get_heron_libs(local_jars):
"""Get all the heron lib jars with the absolute paths"""
heron_lib_dir = get_heron_lib_dir()
heron_libs = [os.path.join(heron_lib_dir, f) for f in local_jars]
return heron_libs |
Parse cluster/ [ role ]/ [ environ ] supply default if not provided not required | def parse_cluster_role_env(cluster_role_env, config_path):
"""Parse cluster/[role]/[environ], supply default, if not provided, not required"""
parts = cluster_role_env.split('/')[:3]
if not os.path.isdir(config_path):
Log.error("Config path cluster directory does not exist: %s" % config_path)
raise Except... |
Parse cluster/ [ role ]/ [ environ ] supply empty string if not provided | def get_cluster_role_env(cluster_role_env):
"""Parse cluster/[role]/[environ], supply empty string, if not provided"""
parts = cluster_role_env.split('/')[:3]
if len(parts) == 3:
return (parts[0], parts[1], parts[2])
if len(parts) == 2:
return (parts[0], parts[1], "")
if len(parts) == 1:
return ... |
Check cluster/ [ role ]/ [ environ ] if they are required | def direct_mode_cluster_role_env(cluster_role_env, config_path):
"""Check cluster/[role]/[environ], if they are required"""
# otherwise, get the client.yaml file
cli_conf_file = os.path.join(config_path, CLIENT_YAML)
# if client conf doesn't exist, use default value
if not os.path.isfile(cli_conf_file):
... |
Check cluster/ [ role ]/ [ environ ] if they are required | def server_mode_cluster_role_env(cluster_role_env, config_map):
"""Check cluster/[role]/[environ], if they are required"""
cmap = config_map[cluster_role_env[0]]
# if role is required but not provided, raise exception
role_present = True if len(cluster_role_env[1]) > 0 else False
if ROLE_KEY in cmap and cma... |
if role is not provided supply userid if environ is not provided supply default | def defaults_cluster_role_env(cluster_role_env):
"""
if role is not provided, supply userid
if environ is not provided, supply 'default'
"""
if len(cluster_role_env[1]) == 0 and len(cluster_role_env[2]) == 0:
return (cluster_role_env[0], getpass.getuser(), ENVIRON)
return (cluster_role_env[0], cluster_... |
Parse the command line for overriding the defaults and create an override file. | def parse_override_config_and_write_file(namespace):
"""
Parse the command line for overriding the defaults and
create an override file.
"""
overrides = parse_override_config(namespace)
try:
tmp_dir = tempfile.mkdtemp()
override_config_file = os.path.join(tmp_dir, OVERRIDE_YAML)
with open(overri... |
Parse the command line for overriding the defaults | def parse_override_config(namespace):
"""Parse the command line for overriding the defaults"""
overrides = dict()
for config in namespace:
kv = config.split("=")
if len(kv) != 2:
raise Exception("Invalid config property format (%s) expected key=value" % config)
if kv[1] in ['true', 'True', 'TRUE... |
Get the path of java executable | def get_java_path():
"""Get the path of java executable"""
java_home = os.environ.get("JAVA_HOME")
return os.path.join(java_home, BIN_DIR, "java") |
Check if the java home set | def check_java_home_set():
"""Check if the java home set"""
# check if environ variable is set
if "JAVA_HOME" not in os.environ:
Log.error("JAVA_HOME not set")
return False
# check if the value set is correct
java_path = get_java_path()
if os.path.isfile(java_path) and os.access(java_path, os.X_OK)... |
Check if the release. yaml file exists | def check_release_file_exists():
"""Check if the release.yaml file exists"""
release_file = get_heron_release_file()
# if the file does not exist and is not a file
if not os.path.isfile(release_file):
Log.error("Required file not found: %s" % release_file)
return False
return True |
Print build_info from release. yaml | def print_build_info(zipped_pex=False):
"""Print build_info from release.yaml
:param zipped_pex: True if the PEX file is built with flag `zip_safe=False'.
"""
if zipped_pex:
release_file = get_zipped_heron_release_file()
else:
release_file = get_heron_release_file()
with open(release_file) as rele... |
Print version from release. yaml | def get_version_number(zipped_pex=False):
"""Print version from release.yaml
:param zipped_pex: True if the PEX file is built with flag `zip_safe=False'.
"""
if zipped_pex:
release_file = get_zipped_heron_release_file()
else:
release_file = get_heron_release_file()
with open(release_file) as releas... |
: param param:: param command_args:: return: | def insert_bool(param, command_args):
'''
:param param:
:param command_args:
:return:
'''
index = 0
found = False
for lelem in command_args:
if lelem == '--' and not found:
break
if lelem == param:
found = True
break
index = index + 1
if found:
command_args.insert(in... |
run command | def run(command, parser, args, unknown_args):
""" run command """
# get the command for detailed help
command_help = args['help-command']
# if no command is provided, just print main help
if command_help == 'help':
parser.print_help()
return True
# get the subparser for the specific command
subp... |
get | def get(self):
""" get """
try:
cluster = self.get_argument_cluster()
environ = self.get_argument_environ()
role = self.get_argument_role()
topology_name = self.get_argument_topology()
component = self.get_argument_component()
topology = self.tracker.getTopologyByClusterRoleE... |
Get the summary of exceptions for component_name and list of instances. Empty instance list will fetch all exceptions. | def getComponentExceptionSummary(self, tmaster, component_name, instances=[], callback=None):
"""
Get the summary of exceptions for component_name and list of instances.
Empty instance list will fetch all exceptions.
"""
if not tmaster or not tmaster.host or not tmaster.stats_port:
return
... |
: param cluster:: param environ:: param topology:: return: | def get(self, cluster, environ, topology):
'''
:param cluster:
:param environ:
:param topology:
:return:
'''
# pylint: disable=no-member
options = dict(
cluster=cluster,
environ=environ,
topology=topology,
active="topologies",
function=common.class... |
: return: | def get(self):
'''
:return:
'''
clusters = yield access.get_clusters()
# pylint: disable=no-member
options = dict(
topologies=[], # no topologies
clusters=[str(cluster) for cluster in clusters],
active="topologies", # active icon the nav bar
function=common.cla... |
: param cluster:: param environ:: param topology:: return: | def get(self, cluster, environ, topology):
'''
:param cluster:
:param environ:
:param topology:
:return:
'''
# fetch the execution of the topology asynchronously
execution_state = yield access.get_execution_state(cluster, environ, topology)
# fetch scheduler location of the topolog... |
: param cluster:: param environ:: param topology:: param container:: return: | def get(self, cluster, environ, topology, container):
'''
:param cluster:
:param environ:
:param topology:
:param container:
:return:
'''
path = self.get_argument("path")
options = dict(
cluster=cluster,
environ=environ,
topology=topology,
container=c... |
: param cluster:: param environ:: param topology:: param container:: return: | def get(self, cluster, environ, topology, container):
'''
:param cluster:
:param environ:
:param topology:
:param container:
:return:
'''
offset = self.get_argument("offset")
length = self.get_argument("length")
path = self.get_argument("path")
data = yield access.get_contai... |
: param cluster:: param environ:: param topology:: param container:: return: | def get(self, cluster, environ, topology, container):
'''
:param cluster:
:param environ:
:param topology:
:param container:
:return:
'''
path = self.get_argument("path", default=".")
data = yield access.get_filestats(cluster, environ, topology, container, path)
options = dict(
... |
: param cluster:: param environ:: param topology:: param container:: return: | def get(self, cluster, environ, topology, container):
'''
:param cluster:
:param environ:
:param topology:
:param container:
:return:
'''
# If the file is large, we want to abandon downloading
# if user cancels the requests.
# pylint: disable=attribute-defined-outside-init
se... |
get method | def get(self, path):
''' get method '''
path = tornado.escape.url_unescape(path)
if not path:
path = "."
# User should not be able to access anything outside
# of the dir that heron-shell is running in. This ensures
# sandboxing. So we don't allow absolute paths and parent
# accessing... |
Returns the UUID with which the watch is registered. This UUID can be used to unregister the watch. Returns None if watch could not be registered. | def register_watch(self, callback):
"""
Returns the UUID with which the watch is
registered. This UUID can be used to unregister
the watch.
Returns None if watch could not be registered.
The argument 'callback' must be a function that takes
exactly one argument, the topology on which
th... |
Unregister the watch with the given UUID. | def unregister_watch(self, uid):
"""
Unregister the watch with the given UUID.
"""
# Do not raise an error if UUID is
# not present in the watches.
Log.info("Unregister a watch with uid: " + str(uid))
self.watches.pop(uid, None) |
Call all the callbacks. If any callback raises an Exception unregister the corresponding watch. | def trigger_watches(self):
"""
Call all the callbacks.
If any callback raises an Exception,
unregister the corresponding watch.
"""
to_remove = []
for uid, callback in self.watches.items():
try:
callback(self)
except Exception as e:
Log.error("Caught exception whi... |
set physical plan | def set_physical_plan(self, physical_plan):
""" set physical plan """
if not physical_plan:
self.physical_plan = None
self.id = None
else:
self.physical_plan = physical_plan
self.id = physical_plan.topology.id
self.trigger_watches() |
set packing plan | def set_packing_plan(self, packing_plan):
""" set packing plan """
if not packing_plan:
self.packing_plan = None
self.id = None
else:
self.packing_plan = packing_plan
self.id = packing_plan.id
self.trigger_watches() |
set exectuion state | def set_execution_state(self, execution_state):
""" set exectuion state """
if not execution_state:
self.execution_state = None
self.cluster = None
self.environ = None
else:
self.execution_state = execution_state
cluster, environ = self.get_execution_state_dc_environ(execution_... |
Number of spouts + bolts | def num_instances(self):
"""
Number of spouts + bolts
"""
num = 0
# Get all the components
components = self.spouts() + self.bolts()
# Get instances for each worker
for component in components:
config = component.comp.config
for kvs in config.kvs:
if kvs.key == api_... |
Get all the machines that this topology is running on. These are the hosts of all the stmgrs. | def get_machines(self):
"""
Get all the machines that this topology is running on.
These are the hosts of all the stmgrs.
"""
if self.physical_plan:
stmgrs = list(self.physical_plan.stmgrs)
return map(lambda s: s.host_name, stmgrs)
return [] |
Get the current state of this topology. The state values are from the topology. proto RUNNING = 1 PAUSED = 2 KILLED = 3 if the state is None Unknown is returned. | def get_status(self):
"""
Get the current state of this topology.
The state values are from the topology.proto
RUNNING = 1, PAUSED = 2, KILLED = 3
if the state is None "Unknown" is returned.
"""
status = None
if self.physical_plan and self.physical_plan.topology:
status = self.phys... |
converts pb kvs to dict | def convert_pb_kvs(kvs, include_non_primitives=True):
"""
converts pb kvs to dict
"""
config = {}
for kv in kvs:
if kv.value:
config[kv.key] = kv.value
elif kv.serialized_value:
# add serialized_value support for python values (fixme)
# is this a serialized java object
if topo... |
Sync the topologies with the statemgrs. | def synch_topologies(self):
"""
Sync the topologies with the statemgrs.
"""
self.state_managers = statemanagerfactory.get_all_state_managers(self.config.statemgr_config)
try:
for state_manager in self.state_managers:
state_manager.start()
except Exception as ex:
Log.error("Fo... |
Find and return the topology given its cluster environ topology name and an optional role. Raises exception if topology is not found or more than one are found. | def getTopologyByClusterRoleEnvironAndName(self, cluster, role, environ, topologyName):
"""
Find and return the topology given its cluster, environ, topology name, and
an optional role.
Raises exception if topology is not found, or more than one are found.
"""
topologies = list(filter(lambda t: ... |
Returns all the topologies for a given state manager. | def getTopologiesForStateLocation(self, name):
"""
Returns all the topologies for a given state manager.
"""
return filter(lambda t: t.state_manager_name == name, self.topologies) |
Adds a topology in the local cache and sets a watch on any changes on the topology. | def addNewTopology(self, state_manager, topologyName):
"""
Adds a topology in the local cache, and sets a watch
on any changes on the topology.
"""
topology = Topology(topologyName, state_manager.name)
Log.info("Adding new topology: %s, state_manager: %s",
topologyName, state_manage... |
Removes the topology from the local cache. | def removeTopology(self, topology_name, state_manager_name):
"""
Removes the topology from the local cache.
"""
topologies = []
for top in self.topologies:
if (top.name == topology_name and
top.state_manager_name == state_manager_name):
# Remove topologyInfo
if (topol... |
Returns the repesentation of execution state that will be returned from Tracker. | def extract_execution_state(self, topology):
"""
Returns the repesentation of execution state that will
be returned from Tracker.
"""
execution_state = topology.execution_state
executionState = {
"cluster": execution_state.cluster,
"environ": execution_state.environ,
"ro... |
Returns the representation of scheduler location that will be returned from Tracker. | def extract_scheduler_location(self, topology):
"""
Returns the representation of scheduler location that will
be returned from Tracker.
"""
schedulerLocation = {
"name": None,
"http_endpoint": None,
"job_page_link": None,
}
if topology.scheduler_location:
sche... |
Returns the representation of tmaster that will be returned from Tracker. | def extract_tmaster(self, topology):
"""
Returns the representation of tmaster that will
be returned from Tracker.
"""
tmasterLocation = {
"name": None,
"id": None,
"host": None,
"controller_port": None,
"master_port": None,
"stats_port": None,
}
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.