text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_reg(cls):
"""Return all of the registered classes. :return: an ``dict`` of task_family -> class """ |
# We have to do this on-demand in case task names have changed later
reg = dict()
for task_cls in cls._reg:
if not task_cls._visible_in_registry:
continue
name = task_cls.get_task_family()
if name in reg and \
(reg[name] =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_reg(cls, reg):
"""The writing complement of _get_reg """ |
cls._reg = [task_cls for task_cls in reg.values() if task_cls is not cls.AMBIGUOUS_CLASS] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_task_cls(cls, name):
""" Returns an unambiguous class or raises an exception. """ |
task_cls = cls._get_reg().get(name)
if not task_cls:
raise TaskClassNotFoundException(cls._missing_task_msg(name))
if task_cls == cls.AMBIGUOUS_CLASS:
raise TaskClassAmbigiousException('Task %r is ambiguous' % name)
return task_cls |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _editdistance(a, b):
""" Simple unweighted Levenshtein distance """ |
r0 = range(0, len(b) + 1)
r1 = [0] * (len(b) + 1)
for i in range(0, len(a)):
r1[0] = i + 1
for j in range(0, len(b)):
c = 0 if a[i] is b[j] else 1
r1[j + 1] = min(r1[j] + 1, r0[j + 1] + 1, r0[j] + c)
r0 = r1[:]
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_copy(self, connection):
""" Override to perform custom queries. Any code here will be formed in the same transaction as the main copy, just prior to cop... |
# TODO: remove this after sufficient time so most people using the
# clear_table attribtue will have noticed it doesn't work anymore
if hasattr(self, "clear_table"):
raise Exception("The clear_table attribute has been removed. Override init_copy instead!")
if self.enable_m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def common_params(task_instance, task_cls):
""" Grab all the values in task_instance that are found in task_cls. """ |
if not isinstance(task_cls, task.Register):
raise TypeError("task_cls must be an uninstantiated Task")
task_instance_param_names = dict(task_instance.get_params()).keys()
task_cls_params_dict = dict(task_cls.get_params())
task_cls_param_names = task_cls_params_dict.keys()
common_param_name... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def previous(task):
""" Return a previous Task of the same family. By default checks if this task family only has one non-global parameter and if it is a DatePar... |
params = task.get_params()
previous_params = {}
previous_date_params = {}
for param_name, param_obj in params:
param_value = getattr(task, param_name)
if isinstance(param_obj, parameter.DateParameter):
previous_date_params[param_name] = param_value - datetime.timedelta(day... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exists(self, path):
""" Use ``hadoop fs -stat`` to check file existence. """ |
cmd = load_hadoop_cmd() + ['fs', '-stat', path]
logger.debug('Running file existence check: %s', subprocess.list2cmdline(cmd))
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, universal_newlines=True)
stdout, stderr = p.communicate()
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mkdir(self, path, parents=True, raise_if_exists=False):
""" No explicit -p switch, this version of Hadoop always creates parent directories. """ |
try:
self.call_check(load_hadoop_cmd() + ['fs', '-mkdir', path])
except hdfs_error.HDFSCliError as ex:
if "File exists" in ex.stderr:
if raise_if_exists:
raise FileAlreadyExists(ex.stderr)
else:
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_hive(args, check_return_code=True):
""" Runs the `hive` from the command line, passing in the given args, and returning stdout. With the apache release o... |
cmd = load_hive_cmd() + args
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if check_return_code and p.returncode != 0:
raise HiveCommandError("Hive command: {0} failed with error code: {1}".format(" ".join(cmd), p.returncode),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_hive_script(script):
""" Runs the contents of the given script in hive and returns stdout. """ |
if not os.path.isfile(script):
raise RuntimeError("Hive script: {0} does not exist.".format(script))
return run_hive(['-f', script]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_outputs(self, job):
""" Called before job is started. If output is a `FileSystemTarget`, create parent directories so the hive command won't fail """ |
outputs = flatten(job.output())
for o in outputs:
if isinstance(o, FileSystemTarget):
parent_dir = os.path.dirname(o.path)
if parent_dir and not o.fs.exists(parent_dir):
logger.info("Creating parent directory %r", parent_dir)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def path(self):
""" Returns the path to this table in HDFS. """ |
location = self.client.table_location(self.table, self.database)
if not location:
raise Exception("Couldn't find location for table: {0}".format(str(self)))
return location |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def global_instance(cls, cmdline_args, allow_override=False):
""" Meant to be used as a context manager. """ |
orig_value = cls._instance
assert (orig_value is None) or allow_override
new_value = None
try:
new_value = CmdlineParser(cmdline_args)
cls._instance = new_value
yield new_value
finally:
assert cls._instance is new_value
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def relpath(self, current_file, rel_path):
""" Compute path given current file and relative path. """ |
script_dir = os.path.dirname(os.path.abspath(current_file))
rel_path = os.path.abspath(os.path.join(script_dir, rel_path))
return rel_path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def args(self):
""" Returns an array of args to pass to the job. """ |
arglist = []
for k, v in six.iteritems(self.requires_hadoop()):
arglist.append('--' + k)
arglist.extend([t.output().path for t in flatten(v)])
arglist.extend(['--output', self.output()])
arglist.extend(self.job_args())
return arglist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_event(self, event):
"""Adds an event to the event file. Args: event: An `Event` protocol buffer. """ |
if not isinstance(event, event_pb2.Event):
raise TypeError("Expected an event_pb2.Event proto, "
" but got %s" % type(event))
self._async_writer.write(event.SerializeToString()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def write(self, bytestring):
'''Enqueue the given bytes to be written asychronously'''
with self._lock:
if self._closed:
raise IOError('Writer is closed')
self._byte_queue.put(bytestring) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def flush(self):
'''Write all the enqueued bytestring before this flush call to disk.
Block until all the above bytestring are written.
'''
with self._lock:
if self._closed:
raise IOError('Writer is closed')
self._byte_queue.join()
self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def close(self):
'''Closes the underlying writer, flushing any pending writes first.'''
if not self._closed:
with self._lock:
if not self._closed:
self._closed = True
self._worker.stop()
self._writer.flush()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _extract_device_name_from_event(event):
"""Extract device name from a tf.Event proto carrying tensor value.""" |
plugin_data_content = json.loads(
tf.compat.as_str(event.summary.value[0].metadata.plugin_data.content))
return plugin_data_content['device'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_graph(self, run_key, device_name, graph_def, debug=False):
"""Add a GraphDef. Args: run_key: A key for the run, containing information about the feeds, f... |
graph_dict = (self._run_key_to_debug_graphs if debug else
self._run_key_to_original_graphs)
if not run_key in graph_dict:
graph_dict[run_key] = dict() # Mapping device_name to GraphDef.
graph_dict[run_key][tf.compat.as_str(device_name)] = (
debug_graphs_helper.DebugGraphWra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_graphs(self, run_key, debug=False):
"""Get the runtime GraphDef protos associated with a run key. Args: run_key: A Session.run kay. debug: Whether the de... |
graph_dict = (self._run_key_to_debug_graphs if debug else
self._run_key_to_original_graphs)
graph_wrappers = graph_dict.get(run_key, {})
graph_defs = dict()
for device_name, wrapper in graph_wrappers.items():
graph_defs[device_name] = wrapper.graph_def
return graph_defs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_graph(self, run_key, device_name, debug=False):
"""Get the runtime GraphDef proto associated with a run key and a device. Args: run_key: A Session.run ka... |
return self.get_graphs(run_key, debug=debug).get(device_name, None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_maybe_base_expanded_node_name(self, node_name, run_key, device_name):
"""Obtain possibly base-expanded node name. Base-expansion is the transformation of... |
device_name = tf.compat.as_str(device_name)
if run_key not in self._run_key_to_original_graphs:
raise ValueError('Unknown run_key: %s' % run_key)
if device_name not in self._run_key_to_original_graphs[run_key]:
raise ValueError(
'Unknown device for run key "%s": %s' % (run_key, device... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_core_metadata_event(self, event):
"""Implementation of the core metadata-carrying Event proto callback. Args: event: An Event proto that contains core met... |
core_metadata = json.loads(event.log_message.message)
input_names = ','.join(core_metadata['input_names'])
output_names = ','.join(core_metadata['output_names'])
target_nodes = ','.join(core_metadata['target_nodes'])
self._run_key = RunKey(input_names, output_names, target_nodes)
if not self._... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_graph_def(self, graph_def, device_name, wall_time):
"""Implementation of the GraphDef-carrying Event proto callback. Args: graph_def: A GraphDef proto. N.... |
# For now, we do nothing with the graph def. However, we must define this
# method to satisfy the handler's interface. Furthermore, we may use the
# graph in the future (for instance to provide a graph if there is no graph
# provided otherwise).
del wall_time
self._graph_defs[device_name] = gra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_debugged_source_file(self, debugged_source_file):
"""Add a DebuggedSourceFile proto.""" |
# TODO(cais): Should the key include a host name, for certain distributed
# cases?
key = debugged_source_file.file_path
self._source_file_host[key] = debugged_source_file.host
self._source_file_last_modified[key] = debugged_source_file.last_modified
self._source_file_bytes[key] = debugged_sou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_op_traceback(self, op_name):
"""Get the traceback of an op in the latest version of the TF graph. Args: op_name: Name of the op. Returns: Creation traceb... |
if not self._graph_traceback:
raise ValueError('No graph traceback has been received yet.')
for op_log_entry in self._graph_traceback.log_entries:
if op_log_entry.name == op_name:
return self._code_def_to_traceback_list(op_log_entry.code_def)
raise ValueError(
'No op named "%s" ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_file_tracebacks(self, file_path):
"""Get the lists of ops created at lines of a specified source file. Args: file_path: Path to the source file. Returns:... |
if file_path not in self._source_file_content:
raise ValueError(
'Source file of path "%s" has not been received by this instance of '
'SourceManager.' % file_path)
lineno_to_op_names_and_stack_position = dict()
for op_log_entry in self._graph_traceback.log_entries:
for sta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_tensor_store(self, watch_key, time_indices=None, slicing=None, mapping=None):
"""Query tensor store for a given debugged tensor value. Args: watch_key:... |
return self._tensor_store.query(watch_key,
time_indices=time_indices,
slicing=slicing,
mapping=mapping) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Respond(request, content, content_type, code=200, expires=0, content_encoding=None, encoding='utf-8'):
"""Construct a werkzeug Response. Responses are transm... |
mimetype = _EXTRACT_MIMETYPE_PATTERN.search(content_type).group(0)
charset_match = _EXTRACT_CHARSET_PATTERN.search(content_type)
charset = charset_match.group(1) if charset_match else encoding
textual = charset_match or mimetype in _TEXTUAL_MIMETYPES
if (mimetype in _JSON_MIMETYPES and
isinstance(cont... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_longest_parent_path(path_set, path):
"""Finds the longest "parent-path" of 'path' in 'path_set'. This function takes and returns "path-like" strings wh... |
# This could likely be more efficiently implemented with a trie
# data-structure, but we don't want to add an extra dependency for that.
while path not in path_set:
if not path:
return None
path = os.path.dirname(path)
return path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _protobuf_value_type(value):
"""Returns the type of the google.protobuf.Value message as an api.DataType. Returns None if the type of 'value' is not one of t... |
if value.HasField("number_value"):
return api_pb2.DATA_TYPE_FLOAT64
if value.HasField("string_value"):
return api_pb2.DATA_TYPE_STRING
if value.HasField("bool_value"):
return api_pb2.DATA_TYPE_BOOL
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _protobuf_value_to_string(value):
"""Returns a string representation of given google.protobuf.Value message. Args: value: google.protobuf.Value message. Assu... |
value_in_json = json_format.MessageToJson(value)
if value.HasField("string_value"):
# Remove the quotations.
return value_in_json[1:-1]
return value_in_json |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_experiment_tag(self):
"""Finds the experiment associcated with the metadata.EXPERIMENT_TAG tag. Caches the experiment if it was found. Returns: The exp... |
with self._experiment_from_tag_lock:
if self._experiment_from_tag is None:
mapping = self.multiplexer.PluginRunToTagToContent(
metadata.PLUGIN_NAME)
for tag_to_content in mapping.values():
if metadata.EXPERIMENT_TAG in tag_to_content:
self._experiment_from_ta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compute_experiment_from_runs(self):
"""Computes a minimal Experiment protocol buffer by scanning the runs.""" |
hparam_infos = self._compute_hparam_infos()
if not hparam_infos:
return None
metric_infos = self._compute_metric_infos()
return api_pb2.Experiment(hparam_infos=hparam_infos,
metric_infos=metric_infos) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compute_hparam_infos(self):
"""Computes a list of api_pb2.HParamInfo from the current run, tag info. Finds all the SessionStartInfo messages and collects th... |
run_to_tag_to_content = self.multiplexer.PluginRunToTagToContent(
metadata.PLUGIN_NAME)
# Construct a dict mapping an hparam name to its list of values.
hparams = collections.defaultdict(list)
for tag_to_content in run_to_tag_to_content.values():
if metadata.SESSION_START_INFO_TAG not in ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compute_hparam_info_from_values(self, name, values):
"""Builds an HParamInfo message from the hparam name and list of values. Args: name: string. The hparam... |
# Figure out the type from the values.
# Ignore values whose type is not listed in api_pb2.DataType
# If all values have the same type, then that is the type used.
# Otherwise, the returned type is DATA_TYPE_STRING.
result = api_pb2.HParamInfo(name=name, type=api_pb2.DATA_TYPE_UNSET)
distinct_v... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def experiment_pb( hparam_infos, metric_infos, user='', description='', time_created_secs=None):
"""Creates a summary that defines a hyperparameter-tuning experi... |
if time_created_secs is None:
time_created_secs = time.time()
experiment = api_pb2.Experiment(
description=description,
user=user,
time_created_secs=time_created_secs,
hparam_infos=hparam_infos,
metric_infos=metric_infos)
return _summary(metadata.EXPERIMENT_TAG,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def session_start_pb(hparams, model_uri='', monitor_url='', group_name='', start_time_secs=None):
"""Constructs a SessionStartInfo protobuffer. Creates a summary... |
if start_time_secs is None:
start_time_secs = time.time()
session_start_info = plugin_data_pb2.SessionStartInfo(
model_uri=model_uri,
monitor_url=monitor_url,
group_name=group_name,
start_time_secs=start_time_secs)
for (hp_name, hp_val) in six.iteritems(hparams):
if isinstance(hp_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def session_end_pb(status, end_time_secs=None):
"""Constructs a SessionEndInfo protobuffer. Creates a summary that contains status information for a completed tr... |
if end_time_secs is None:
end_time_secs = time.time()
session_end_info = plugin_data_pb2.SessionEndInfo(status=status,
end_time_secs=end_time_secs)
return _summary(metadata.SESSION_END_INFO_TAG,
plugin_data_pb2.HParamsPluginData(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _summary(tag, hparams_plugin_data):
"""Returns a summary holding the given HParamsPluginData message. Helper function. Args: tag: string. The tag to use. hpa... |
summary = tf.compat.v1.Summary()
summary.value.add(
tag=tag,
metadata=metadata.create_summary_metadata(hparams_plugin_data))
return summary |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ListPlugins(logdir):
"""List all the plugins that have registered assets in logdir. If the plugins_dir does not exist, it returns an empty list. This maintai... |
plugins_dir = os.path.join(logdir, _PLUGINS_DIR)
try:
entries = tf.io.gfile.listdir(plugins_dir)
except tf.errors.NotFoundError:
return []
# Strip trailing slashes, which listdir() includes for some filesystems
# for subdirectories, after using them to bypass IsDirectory().
return [x.rstrip('/') fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ListAssets(logdir, plugin_name):
"""List all the assets that are available for given plugin in a logdir. Args: logdir: A directory that was created by a Tens... |
plugin_dir = PluginDirectory(logdir, plugin_name)
try:
# Strip trailing slashes, which listdir() includes for some filesystems.
return [x.rstrip('/') for x in tf.io.gfile.listdir(plugin_dir)]
except tf.errors.NotFoundError:
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def RetrieveAsset(logdir, plugin_name, asset_name):
"""Retrieve a particular plugin asset from a logdir. Args: logdir: A directory that was created by a TensorFl... |
asset_path = os.path.join(PluginDirectory(logdir, plugin_name), asset_name)
try:
with tf.io.gfile.GFile(asset_path, "r") as f:
return f.read()
except tf.errors.NotFoundError:
raise KeyError("Asset path %s not found" % asset_path)
except tf.errors.OpError as e:
raise KeyError("Couldn't read a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def distributions_route(self, request):
"""Given a tag and single run, return an array of compressed histograms.""" |
tag = request.args.get('tag')
run = request.args.get('run')
try:
(body, mime_type) = self.distributions_impl(tag, run)
code = 200
except ValueError as e:
(body, mime_type) = (str(e), 'text/plain')
code = 400
return http_util.Respond(request, body, mime_type, code=code) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Load(self):
"""Loads new values. The watcher will load from one path at a time; as soon as that path stops yielding events, it will move on to the next path.... |
try:
for event in self._LoadInternal():
yield event
except tf.errors.OpError:
if not tf.io.gfile.exists(self._directory):
raise DirectoryDeletedError(
'Directory %s has been permanently deleted' % self._directory) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _SetPath(self, path):
"""Sets the current path to watch for new events. This also records the size of the old path, if any. If the size can't be found, an er... |
old_path = self._path
if old_path and not io_wrapper.IsCloudPath(old_path):
try:
# We're done with the path, so store its size.
size = tf.io.gfile.stat(old_path).length
logger.debug('Setting latest size of %s to %d', old_path, size)
self._finalized_sizes[old_path] = size
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetNextPath(self):
"""Gets the next path to load from. This function also does the checking for out-of-order writes as it iterates through the paths. Return... |
paths = sorted(path
for path in io_wrapper.ListDirectoryAbsolute(self._directory)
if self._path_filter(path))
if not paths:
return None
if self._path is None:
return paths[0]
# Don't bother checking if the paths are GCS (which we can't check) or if
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _HasOOOWrite(self, path):
"""Returns whether the path has had an out-of-order write.""" |
# Check the sizes of each path before the current one.
size = tf.io.gfile.stat(path).length
old_size = self._finalized_sizes.get(path, None)
if size != old_size:
if old_size is None:
logger.error('File %s created after file %s even though it\'s '
'lexicographicall... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def example_protos_from_path(path, num_examples=10, start_index=0, parse_examples=True, sampling_odds=1, example_class=tf.train.Example):
"""Returns a number of ... |
def append_examples_from_iterable(iterable, examples):
for value in iterable:
if sampling_odds >= 1 or random.random() < sampling_odds:
examples.append(
example_class.FromString(value) if parse_examples else value)
if len(examples) >= num_examples:
return
examples ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_servo(examples, serving_bundle):
"""Send an RPC request to the Servomatic prediction service. Args: examples: A list of examples that matches the model ... |
parsed_url = urlparse('http://' + serving_bundle.inference_address)
channel = implementations.insecure_channel(parsed_url.hostname,
parsed_url.port)
stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)
if serving_bundle.use_predict:
request... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def migrate_value(value):
"""Convert `value` to a new-style value, if necessary and possible. An "old-style" value is a value that uses any `value` field other t... |
handler = {
'histo': _migrate_histogram_value,
'image': _migrate_image_value,
'audio': _migrate_audio_value,
'simple_value': _migrate_scalar_value,
}.get(value.WhichOneof('value'))
return handler(value) if handler else value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_plugin_apps(self):
"""Obtains a mapping between routes and handlers. Stores the logdir. Returns: A mapping between routes and handlers (functions that re... |
return {
'/infer': self._infer,
'/update_example': self._update_example,
'/examples_from_path': self._examples_from_path_handler,
'/sprite': self._serve_sprite,
'/duplicate_example': self._duplicate_example,
'/delete_example': self._delete_example,
'/infer_mu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _examples_from_path_handler(self, request):
"""Returns JSON of the specified examples. Args: request: A request that should contain 'examples_path' and 'max_... |
examples_count = int(request.args.get('max_examples'))
examples_path = request.args.get('examples_path')
sampling_odds = float(request.args.get('sampling_odds'))
self.example_class = (tf.train.SequenceExample
if request.args.get('sequence_examples') == 'true'
else tf.train.Example)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_example(self, request):
"""Updates the specified example. Args: request: A request that should contain 'index' and 'example'. Returns: An empty respo... |
if request.method != 'POST':
return http_util.Respond(request, {'error': 'invalid non-POST request'},
'application/json', code=405)
example_json = request.form['example']
index = int(request.form['index'])
if index >= len(self.examples):
return http_util.Respo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _duplicate_example(self, request):
"""Duplicates the specified example. Args: request: A request that should contain 'index'. Returns: An empty response. """ |
index = int(request.args.get('index'))
if index >= len(self.examples):
return http_util.Respond(request, {'error': 'invalid index provided'},
'application/json', code=400)
new_example = self.example_class()
new_example.CopyFrom(self.examples[index])
self.example... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _delete_example(self, request):
"""Deletes the specified example. Args: request: A request that should contain 'index'. Returns: An empty response. """ |
index = int(request.args.get('index'))
if index >= len(self.examples):
return http_util.Respond(request, {'error': 'invalid index provided'},
'application/json', code=400)
del self.examples[index]
self.updated_example_indices = set([
i if i < index else i - ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_request_arguments(self, request):
"""Parses comma separated request arguments Args: request: A request that should contain 'inference_address', 'model... |
inference_addresses = request.args.get('inference_address').split(',')
model_names = request.args.get('model_name').split(',')
model_versions = request.args.get('model_version').split(',')
model_signatures = request.args.get('model_signature').split(',')
if len(model_names) != len(inference_address... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _eligible_features_from_example_handler(self, request):
"""Returns a list of JSON objects for each feature in the example. Args: request: A request for featu... |
features_list = inference_utils.get_eligible_features(
self.examples[0: NUM_EXAMPLES_TO_SCAN], NUM_MUTANTS)
return http_util.Respond(request, features_list, 'application/json') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _serve_asset(self, path, gzipped_asset_bytes, request):
"""Serves a pre-gzipped static asset from the zip file.""" |
mimetype = mimetypes.guess_type(path)[0] or 'application/octet-stream'
return http_util.Respond(
request, gzipped_asset_bytes, mimetype, content_encoding='gzip') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _serve_environment(self, request):
"""Serve a JSON object containing some base properties used by the frontend. * data_location is either a path to a directo... |
return http_util.Respond(
request,
{
'data_location': self._logdir or self._db_uri,
'mode': 'db' if self._db_uri else 'logdir',
'window_title': self._window_title,
},
'application/json') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _serve_runs(self, request):
"""Serve a JSON array of run names, ordered by run started time. Sort order is by started time (aka first event time) with empty ... |
if self._db_connection_provider:
db = self._db_connection_provider()
cursor = db.execute('''
SELECT
run_name,
started_time IS NULL as started_time_nulls_last,
started_time
FROM Runs
ORDER BY started_time_nulls_last, started_time, run_name
''')... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fix_flags(self, flags):
"""Fixes standard TensorBoard CLI flags to parser.""" |
FlagsError = base_plugin.FlagsError
if flags.version_tb:
pass
elif flags.inspect:
if flags.logdir and flags.event_file:
raise FlagsError(
'Must specify either --logdir or --event_file, but not both.')
if not (flags.logdir or flags.event_file):
raise FlagsError(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put(self, message):
"""Put a message into the outgoing message stack. Outgoing message will be stored indefinitely to support multi-users. """ |
with self._outgoing_lock:
self._outgoing.append(message)
self._outgoing_counter += 1
# Check to see if there are pending queues waiting for the item.
if self._outgoing_counter in self._outgoing_pending_queues:
for q in self._outgoing_pending_queues[self._outgoing_counter]:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run():
"""Run custom scalar demo and generate event files.""" |
step = tf.compat.v1.placeholder(tf.float32, shape=[])
with tf.name_scope('loss'):
# Specify 2 different loss values, each tagged differently.
summary_lib.scalar('foo', tf.pow(0.9, step))
summary_lib.scalar('bar', tf.pow(0.85, step + 2))
# Log metric baz as well as upper and lower bounds for a mar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visualize_embeddings(summary_writer, config):
"""Stores a config file used by the embedding projector. Args: summary_writer: The summary writer used for writ... |
logdir = summary_writer.get_logdir()
# Sanity checks.
if logdir is None:
raise ValueError('Summary writer must have a logdir')
# Saving the config file in the logdir.
config_pbtxt = _text_format.MessageToString(config)
path = os.path.join(logdir, _projector_plugin.PROJECTOR_FILENAME)
with tf.io.gfi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _wrap_define_function(original_function):
"""Wraps absl.flags's define functions so tf.flags accepts old names.""" |
def wrapper(*args, **kwargs):
"""Wrapper function that turns old keyword names to new ones."""
has_old_names = False
for old_name, new_name in _six.iteritems(_RENAMED_ARGUMENTS):
if old_name in kwargs:
has_old_names = True
value = kwargs.pop(old_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def last_metric_eval(multiplexer, session_name, metric_name):
"""Returns the last evaluations of the given metric at the given session. Args: multiplexer: The Ev... |
try:
run, tag = run_tag_from_session_and_metric(session_name, metric_name)
tensor_events = multiplexer.Tensors(run=run, tag=tag)
except KeyError as e:
raise KeyError(
'Can\'t find metric %s for session: %s. Underlying error message: %s'
% (metric_name, session_name, e))
last_event = t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_value(self, scalar_data_blob, dtype_enum):
"""Obtains value for scalar event given blob and dtype enum. Args: scalar_data_blob: The blob obtained from t... |
tensorflow_dtype = tf.DType(dtype_enum)
buf = np.frombuffer(scalar_data_blob, dtype=tensorflow_dtype.as_numpy_dtype)
return np.asscalar(buf) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scalars_route(self, request):
"""Given a tag and single run, return array of ScalarEvents.""" |
# TODO: return HTTP status code for malformed requests
tag = request.args.get('tag')
run = request.args.get('run')
experiment = request.args.get('experiment')
output_format = request.args.get('format')
(body, mime_type) = self.scalars_impl(tag, run, experiment, output_format)
return http_ut... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def AddRun(self, path, name=None):
"""Add a run to the multiplexer. If the name is not specified, it is the same as the path. If a run by that name exists, and w... |
name = name or path
accumulator = None
with self._accumulators_mutex:
if name not in self._accumulators or self._paths[name] != path:
if name in self._paths and self._paths[name] != path:
# TODO(@dandelionmane) - Make it impossible to overwrite an old path
# with a new pat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def PluginAssets(self, plugin_name):
"""Get index of runs and assets for a given plugin. Args: plugin_name: Name of the plugin we are checking for. Returns: A di... |
with self._accumulators_mutex:
# To avoid nested locks, we construct a copy of the run-accumulator map
items = list(six.iteritems(self._accumulators))
return {run: accum.PluginAssets(plugin_name) for run, accum in items} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def RetrievePluginAsset(self, run, plugin_name, asset_name):
"""Return the contents for a specific plugin asset from a run. Args: run: The string name of the run... |
accumulator = self.GetAccumulator(run)
return accumulator.RetrievePluginAsset(plugin_name, asset_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Scalars(self, run, tag):
"""Retrieve the scalar events associated with a run and tag. Args: run: A string name of the run for which values are retrieved. tag... |
accumulator = self.GetAccumulator(run)
return accumulator.Scalars(tag) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Audio(self, run, tag):
"""Retrieve the audio events associated with a run and tag. Args: run: A string name of the run for which values are retrieved. tag: A... |
accumulator = self.GetAccumulator(run)
return accumulator.Audio(tag) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Tensors(self, run, tag):
"""Retrieve the tensor events associated with a run and tag. Args: run: A string name of the run for which values are retrieved. tag... |
accumulator = self.GetAccumulator(run)
return accumulator.Tensors(tag) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def SummaryMetadata(self, run, tag):
"""Return the summary metadata for the given tag on the given run. Args: run: A string name of the run for which summary met... |
accumulator = self.GetAccumulator(run)
return accumulator.SummaryMetadata(tag) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Runs(self):
"""Return all the run names in the `EventMultiplexer`. Returns: ``` {runName: { scalarValues: [tagA, tagB, tagC], graph: true, meta_graph: true}}... |
with self._accumulators_mutex:
# To avoid nested locks, we construct a copy of the run-accumulator map
items = list(six.iteritems(self._accumulators))
return {run_name: accumulator.Tags() for run_name, accumulator in items} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def text(name, data, step=None, description=None):
"""Write a text summary. Arguments: name: A name for this summary. The summary tag used for TensorBoard will b... |
summary_metadata = metadata.create_summary_metadata(
display_name=None, description=description)
# TODO(https://github.com/tensorflow/tensorboard/issues/2109): remove fallback
summary_scope = (
getattr(tf.summary.experimental, 'summary_scope', None) or
tf.summary.summary_scope)
with summary_s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def text_pb(tag, data, description=None):
"""Create a text tf.Summary protobuf. Arguments: tag: String tag for the summary. data: A Python bytestring (of type by... |
try:
tensor = tensor_util.make_tensor_proto(data, dtype=np.object)
except TypeError as e:
raise TypeError('tensor must be of type string', e)
summary_metadata = metadata.create_summary_metadata(
display_name=None, description=description)
summary = summary_pb2.Summary()
summary.value.add(tag=ta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def op(name, audio, sample_rate, labels=None, max_outputs=3, encoding=None, display_name=None, description=None, collections=None):
"""Create a legacy audio summ... |
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow # for contrib
import tensorflow.compat.v1 as tf
if display_name is None:
display_name = name
if encoding is None:
encoding = 'wav'
if encoding == 'wav':
encoding = metadata.Encoding.Value('WAV')
enc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pb(name, audio, sample_rate, labels=None, max_outputs=3, encoding=None, display_name=None, description=None):
"""Create a legacy audio summary protobuf. This... |
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
audio = np.array(audio)
if audio.ndim != 3:
raise ValueError('Shape %r must have rank 3' % (audio.shape,))
if encoding is None:
encoding = 'wav'
if encoding == 'wav':
encoding = metadata.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def op( name, labels, predictions, num_thresholds=None, weights=None, display_name=None, description=None, collections=None):
"""Create a PR curve summary op for... |
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
if num_thresholds is None:
num_thresholds = _DEFAULT_NUM_THRESHOLDS
if weights is None:
weights = 1.0
dtype = predictions.dtype
with tf.name_scope(name, values=[labels, predictions, weights... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pb(name, labels, predictions, num_thresholds=None, weights=None, display_name=None, description=None):
"""Create a PR curves summary protobuf. Arguments: nam... |
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
if num_thresholds is None:
num_thresholds = _DEFAULT_NUM_THRESHOLDS
if weights is None:
weights = 1.0
# Compute bins of true positives and false positives.
bucket_indices = np.int32(np.floor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def streaming_op(name, labels, predictions, num_thresholds=None, weights=None, metrics_collections=None, updates_collections=None, display_name=None, description=... |
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
if num_thresholds is None:
num_thresholds = _DEFAULT_NUM_THRESHOLDS
thresholds = [i / float(num_thresholds - 1)
for i in range(num_thresholds)]
with tf.name_scope(name, values=[lab... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raw_data_op( name, true_positive_counts, false_positive_counts, true_negative_counts, false_negative_counts, precision, recall, num_thresholds=None, display_n... |
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
with tf.name_scope(name, values=[
true_positive_counts,
false_positive_counts,
true_negative_counts,
false_negative_counts,
precision,
recall,
]):
return _create_te... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raw_data_pb( name, true_positive_counts, false_positive_counts, true_negative_counts, false_negative_counts, precision, recall, num_thresholds=None, display_n... |
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
if display_name is None:
display_name = name
summary_metadata = metadata.create_summary_metadata(
display_name=display_name if display_name is not None else name,
description=description o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_tensor_summary( name, true_positive_counts, false_positive_counts, true_negative_counts, false_negative_counts, precision, recall, num_thresholds=None... |
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
# Store the number of thresholds within the summary metadata because
# that value is constant for all pr curve summaries with the same tag.
summary_metadata = metadata.create_summary_metadata(
dis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
"""Executes the request. Returns: An array of tuples representing the metric evaluations--each of the form (<wall time in secs>, <training step>, ... |
run, tag = metrics.run_tag_from_session_and_metric(
self._request.session_name, self._request.metric_name)
body, _ = self._scalars_plugin_instance.scalars_impl(
tag, run, None, scalars_plugin.OutputFormat.JSON)
return body |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def histograms_route(self, request):
"""Given a tag and single run, return array of histogram values.""" |
tag = request.args.get('tag')
run = request.args.get('run')
try:
(body, mime_type) = self.histograms_impl(
tag, run, downsample_to=self.SAMPLE_SIZE)
code = 200
except ValueError as e:
(body, mime_type) = (str(e), 'text/plain')
code = 400
return http_util.Respond(re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _lazily_initialize(self):
"""Initialize the graph and session, if this has not yet been done.""" |
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
with self._initialization_lock:
if self._session:
return
graph = tf.Graph()
with graph.as_default():
self.initialize_graph()
# Don't reserve GPU because libpng c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_scalars_plugin(self):
"""Tries to get the scalars plugin. Returns: The scalars plugin. Or None if it is not yet registered. """ |
if scalars_metadata.PLUGIN_NAME in self._plugin_name_to_instance:
# The plugin is registered.
return self._plugin_name_to_instance[scalars_metadata.PLUGIN_NAME]
# The plugin is not yet registered.
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_active(self):
"""This plugin is active if 2 conditions hold. 1. The scalars plugin is registered and active. 2. There is a custom layout for the dashboard... |
if not self._multiplexer:
return False
scalars_plugin_instance = self._get_scalars_plugin()
if not (scalars_plugin_instance and
scalars_plugin_instance.is_active()):
return False
# This plugin is active if any run has a layout.
return bool(self._multiplexer.PluginRunToTagT... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_data_impl(self, run, tag, response_format):
"""Provides a response for downloading scalars data for a data series. Args: run: The run. tag: The spec... |
scalars_plugin_instance = self._get_scalars_plugin()
if not scalars_plugin_instance:
raise ValueError(('Failed to respond to request for /download_data. '
'The scalars plugin is oddly not registered.'))
body, mime_type = scalars_plugin_instance.scalars_impl(
tag, run,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def layout_route(self, request):
r"""Fetches the custom layout specified by the config file in the logdir. If more than 1 run contains a layout, this method merg... |
body = self.layout_impl()
return http_util.Respond(request, body, 'application/json') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_table_row(contents, tag='td'):
"""Given an iterable of string contents, make a table row. Args: contents: An iterable yielding strings. tag: The tag to ... |
columns = ('<%s>%s</%s>\n' % (tag, s, tag) for s in contents)
return '<tr>\n' + ''.join(columns) + '</tr>\n' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_table(contents, headers=None):
"""Given a numpy ndarray of strings, concatenate them into a html table. Args: contents: A np.ndarray of strings. May be ... |
if not isinstance(contents, np.ndarray):
raise ValueError('make_table contents must be a numpy ndarray')
if contents.ndim not in [1, 2]:
raise ValueError('make_table requires a 1d or 2d numpy array, was %dd' %
contents.ndim)
if headers:
if isinstance(headers, (list, tuple)):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reduce_to_2d(arr):
"""Given a np.npdarray with nDims > 2, reduce it to 2d. It does this by selecting the zeroth coordinate for every dimension greater than t... |
if not isinstance(arr, np.ndarray):
raise ValueError('reduce_to_2d requires a numpy.ndarray')
ndims = len(arr.shape)
if ndims < 2:
raise ValueError('reduce_to_2d requires an array of dimensionality >=2')
# slice(None) is equivalent to `:`, so we take arr[0,0,...0,:,:]
slices = ([0] * (ndims - 2)) + ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.