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 text_array_to_html(text_arr): """Take a numpy.ndarray containing strings, and convert it into html. If the ndarray contains a single scalar string, that stri...
if not text_arr.shape: # It is a scalar. No need to put it in a table, just apply markdown return plugin_util.markdown_to_safe_html(np.asscalar(text_arr)) warning = '' if len(text_arr.shape) > 2: warning = plugin_util.markdown_to_safe_html(WARNING_TEMPLATE ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_string_tensor_event(event): """Convert a TensorEvent into a JSON-compatible response."""
string_arr = tensor_util.make_ndarray(event.tensor_proto) html = text_array_to_html(string_arr) return { 'wall_time': event.wall_time, 'step': event.step, 'text': html, }
<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_summary_metadata(display_name, description, num_thresholds): """Create a `summary_pb2.SummaryMetadata` proto for pr_curves plugin data. Arguments: dis...
pr_curve_plugin_data = plugin_data_pb2.PrCurvePluginData( version=PROTO_VERSION, num_thresholds=num_thresholds) content = pr_curve_plugin_data.SerializeToString() return summary_pb2.SummaryMetadata( display_name=display_name, summary_description=description, plugin_data=summary_pb2.Summar...
<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_plugin_metadata(content): """Parse summary metadata to a Python object. Arguments: content: The `content` field of a `SummaryMetadata` proto correspond...
if not isinstance(content, bytes): raise TypeError('Content type must be bytes') result = plugin_data_pb2.PrCurvePluginData.FromString(content) if result.version == 0: return result else: logger.warn( 'Unknown metadata version: %s. The latest version known to ' 'this build of Tensor...
<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_field_to_observations_map(generator, query_for_tag=''): """Return a field to `Observations` dict for the event generator. Args: generator: A generator ov...
def increment(stat, event, tag=''): assert stat in TRACKED_FIELDS field_to_obs[stat].append(Observation(step=event.step, wall_time=event.wall_time, tag=tag)._asdict()) field_to_obs = dict([(t, []) for t in TRACKED_FIELDS]...
<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_unique_tags(field_to_obs): """Returns a dictionary of tags that a user could query over. Args: field_to_obs: Dict that maps string field to `Observation`...
return {field: sorted(set([x.get('tag', '') for x in observations])) for field, observations in field_to_obs.items() if field in TAG_FIELDS}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_dict(d, show_missing=True): """Prints a shallow dict to console. Args: d: Dict to print. show_missing: Whether to show keys with empty values. """
for k, v in sorted(d.items()): if (not v) and show_missing: # No instances of the key, so print missing symbol. print('{} -'.format(k)) elif isinstance(v, list): # Value is a list, so print each item of the list. print(k) for item in v: print(' {}'.format(item)) el...
<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_dict_to_print(field_to_obs): """Transform the field-to-obs mapping into a printable dictionary. Args: field_to_obs: Dict that maps string field to `Obser...
def compressed_steps(steps): return {'num_steps': len(set(steps)), 'min_step': min(steps), 'max_step': max(steps), 'last_step': steps[-1], 'first_step': steps[0], 'outoforder_steps': get_out_of_order(steps)} def full_steps(steps): return {'steps...
<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_out_of_order(list_of_numbers): """Returns elements that break the monotonically non-decreasing trend. This is used to find instances of global step value...
# TODO: Consider changing this to only check for out-of-order # steps within a particular tag. result = [] # pylint: disable=consider-using-enumerate for i in range(len(list_of_numbers)): if i == 0: continue if list_of_numbers[i] < list_of_numbers[i - 1]: result.append((list_of_numbers[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 generators_from_logdir(logdir): """Returns a list of event generators for subdirectories with event files. The number of generators returned should equal the...
subdirs = io_wrapper.GetLogdirSubdirectories(logdir) generators = [ itertools.chain(*[ generator_from_event_file(os.path.join(subdir, f)) for f in tf.io.gfile.listdir(subdir) if io_wrapper.IsTensorFlowEventsFile(os.path.join(subdir, f)) ]) for subdir in subdirs ] retur...
<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_inspection_units(logdir='', event_file='', tag=''): """Returns a list of InspectionUnit objects given either logdir or event_file. If logdir is given, th...
if logdir: subdirs = io_wrapper.GetLogdirSubdirectories(logdir) inspection_units = [] for subdir in subdirs: generator = itertools.chain(*[ generator_from_event_file(os.path.join(subdir, f)) for f in tf.io.gfile.listdir(subdir) if io_wrapper.IsTensorFlowEventsFile(os.p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inspect(logdir='', event_file='', tag=''): """Main function for inspector that prints out a digest of event files. Args: logdir: A log directory that contain...
print(PRINT_SEPARATOR + 'Processing event files... (this can take a few minutes)\n' + PRINT_SEPARATOR) inspection_units = get_inspection_units(logdir, event_file, tag) for unit in inspection_units: if tag: print('Event statistics for tag {} in {}:'.format(tag, unit.name)) else: ...
<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, context): """Returns the debugger plugin, if possible. Args: context: The TBContext flags including `add_arguments`. Returns: A DebuggerPlugin ins...
if not (context.flags.debugger_data_server_grpc_port > 0 or context.flags.debugger_port > 0): return None flags = context.flags try: # pylint: disable=g-import-not-at-top,unused-import import tensorflow except ImportError: raise ImportError( 'To use the deb...
<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_summary_metadata(hparams_plugin_data_pb): """Returns a summary metadata for the HParams plugin. Returns a summary_pb2.SummaryMetadata holding a copy o...
if not isinstance(hparams_plugin_data_pb, plugin_data_pb2.HParamsPluginData): raise TypeError('Needed an instance of plugin_data_pb2.HParamsPluginData.' ' Got: %s' % type(hparams_plugin_data_pb)) content = plugin_data_pb2.HParamsPluginData() content.CopyFrom(hparams_plugin_data_pb) 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 _parse_plugin_data_as(content, data_oneof_field): """Returns a data oneof's field from plugin_data.content. Raises HParamsError if the content doesn't have '...
plugin_data = plugin_data_pb2.HParamsPluginData.FromString(content) if plugin_data.version != PLUGIN_DATA_VERSION: raise error.HParamsError( 'Only supports plugin_data version: %s; found: %s in: %s' % (PLUGIN_DATA_VERSION, plugin_data.version, plugin_data)) if not plugin_data.HasField(data_on...
<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_event(self, event): """Writes an event proto to disk. This method is threadsafe with respect to invocations of itself. Args: event: The event proto. Ra...
self._lock.acquire() try: self._events_writer.WriteEvent(event) self._event_count += 1 if self._always_flush: # We flush on every event within the integration test. self._events_writer.Flush() if self._event_count == self._check_this_often: # Every so often, we ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dispose(self): """Disposes of this events writer manager, making it no longer usable. Call this method when this object is done being used in order to clean ...
self._lock.acquire() self._events_writer.Close() self._events_writer = None self._lock.release()
<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_events_writer(self, directory): """Creates a new events writer. Args: directory: The directory in which to write files containing events. Returns: A ...
total_size = 0 events_files = self._fetch_events_files_on_disk() for file_name in events_files: file_path = os.path.join(self._events_directory, file_name) total_size += tf.io.gfile.stat(file_path).length if total_size >= self.total_file_size_cap_bytes: # The total size written to di...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fetch_events_files_on_disk(self): """Obtains the names of debugger-related events files within the directory. Returns: The names of the debugger-related eve...
all_files = tf.io.gfile.listdir(self._events_directory) relevant_files = [ file_name for file_name in all_files if _DEBUGGER_EVENTS_FILE_NAME_REGEX.match(file_name) ] return sorted(relevant_files, key=self._obtain_file_index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reexport_tf_summary(): """Re-export all symbols from the original tf.summary. This function finds the original tf.summary V2 API and re-exports all the symbo...
import sys # pylint: disable=g-import-not-at-top # API packages to check for the original V2 summary API, in preference order # to avoid going "under the hood" to the _api packages unless necessary. packages = [ 'tensorflow', 'tensorflow.compat.v2', 'tensorflow._api.v2', 'tensorflow._...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bench(image, thread_count): """Encode `image` to PNG on `thread_count` threads in parallel. Returns: A `float` representing number of seconds that it takes a...
threads = [threading.Thread(target=lambda: encoder.encode_png(image)) for _ in xrange(thread_count)] start_time = datetime.datetime.now() for thread in threads: thread.start() for thread in threads: thread.join() end_time = datetime.datetime.now() delta = (end_time - start_time).total_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _image_of_size(image_size): """Generate a square RGB test image of the given side length."""
return np.random.uniform(0, 256, [image_size, image_size, 3]).astype(np.uint8)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _format_line(headers, fields): """Format a line of a table. Arguments: headers: A list of strings that are used as the table headers. fields: A list of the s...
assert len(fields) == len(headers), (fields, headers) fields = ["%2.4f" % field if isinstance(field, float) else str(field) for field in fields] return ' '.join(' ' * max(0, len(header) - len(field)) + field for (header, field) in zip(headers, fields))
<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_gated_grpc_tensors(self, matching_debug_op=None): """Extract all nodes with gated-gRPC debug ops attached. Uses cached values if available. This method i...
with self._grpc_gated_lock: matching_debug_op = matching_debug_op or 'DebugIdentity' if matching_debug_op not in self._grpc_gated_tensors: # First, construct a map from node name to op type. node_name_to_op_type = dict( (node.name, node.op) for node in self._graph_def.node) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maybe_base_expanded_node_name(self, node_name): """Expand the base name if there are node names nested under the node. For example, if there are two nodes in...
with self._node_name_lock: # Lazily populate the map from original node name to base-expanded ones. if self._maybe_base_expanded_node_names is None: self._maybe_base_expanded_node_names = dict() # Sort all the node names. sorted_names = sorted(node.name for node in self._graph_d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Reload(self): """Load events from every detected run."""
logger.info('Beginning DbImportMultiplexer.Reload()') # Defer event sink creation until needed; this ensures it will only exist in # the thread that calls Reload(), since DB connections must be thread-local. if not self._event_sink: self._event_sink = self._CreateEventSink() # Use collections...
<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_batches(self): """Returns a batched event iterator over the run directory event files."""
event_iterator = self._directory_watcher.Load() while True: events = [] event_bytes = 0 start = time.time() for event_proto in event_iterator: events.append(event_proto) event_bytes += len(event_proto) if len(events) >= self._BATCH_COUNT or event_bytes >= self._B...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_event(self, event, tagged_data): """Processes a single tf.Event and records it in tagged_data."""
event_type = event.WhichOneof('what') # Handle the most common case first. if event_type == 'summary': for value in event.summary.value: value = data_compat.migrate_value(value) tag, metadata, values = tagged_data.get(value.tag, (None, None, [])) values.append((event.step, eve...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _buckets(data, bucket_count=None): """Create a TensorFlow op to group data into histogram buckets. Arguments: data: A `Tensor` of any shape. Must be castable...
# TODO(nickfelt): remove on-demand imports once dep situation is fixed. import tensorflow.compat.v1 as tf if bucket_count is None: bucket_count = summary_v2.DEFAULT_BUCKET_COUNT with tf.name_scope('buckets', values=[data, bucket_count]), \ tf.control_dependencies([tf.assert_scalar(bucket_count), ...
<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, data, bucket_count=None, display_name=None, description=None, collections=None): """Create a legacy histogram summary op. Arguments: name: A unique ...
# 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, description=description) with tf.name_scope(name): tensor = _bu...
<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, data, bucket_count=None, display_name=None, description=None): """Create a legacy histogram summary protobuf. Arguments: name: A unique name for the...
# TODO(nickfelt): remove on-demand imports once dep situation is fixed. import tensorflow.compat.v1 as tf if bucket_count is None: bucket_count = summary_v2.DEFAULT_BUCKET_COUNT data = np.array(data).flatten().astype(float) if data.size == 0: buckets = np.array([]).reshape((0, 3)) else: min_ =...
<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(self, value): """Add a tensor the watch store."""
if self._disposed: raise ValueError( 'Cannot add value: this _WatchStore instance is already disposed') self._data.append(value) if hasattr(value, 'nbytes'): self._in_mem_bytes += value.nbytes self._ensure_bytes_limits()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def num_in_memory(self): """Get number of values in memory."""
n = len(self._data) - 1 while n >= 0: if isinstance(self._data[n], _TensorValueDiscarded): break n -= 1 return len(self._data) - 1 - 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 num_discarded(self): """Get the number of values discarded due to exceeding both limits."""
if not self._data: return 0 n = 0 while n < len(self._data): if not isinstance(self._data[n], _TensorValueDiscarded): break n += 1 return 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 query(self, time_indices): """Query the values at given time indices. Args: time_indices: 0-based time indices to query, as a `list` of `int`. Returns: Value...
if self._disposed: raise ValueError( 'Cannot query: this _WatchStore instance is already disposed') if not isinstance(time_indices, (tuple, list)): time_indices = [time_indices] output = [] for time_index in time_indices: if isinstance(self._data[time_index], _TensorValueDis...
<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(self, watch_key, tensor_value): """Add a tensor value. Args: watch_key: A string representing the debugger tensor watch, e.g., 'Dense_1/BiasAdd:0:DebugId...
if watch_key not in self._tensor_data: self._tensor_data[watch_key] = _WatchStore( watch_key, mem_bytes_limit=self._watch_mem_bytes_limit) self._tensor_data[watch_key].add(tensor_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 query(self, watch_key, time_indices=None, slicing=None, mapping=None): """Query tensor store for a given watch_key. Args: watch_key: The watch key to query. ...
if watch_key not in self._tensor_data: raise KeyError("watch_key not found: %s" % watch_key) if time_indices is None: time_indices = '-1' time_slicing = tensor_helper.parse_time_indices(time_indices) all_time_indices = list(range(self._tensor_data[watch_key].num_total())) sliced_time_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 _obtain_sampled_health_pills(self, run, node_names): """Obtains the health pills for a run sampled by the event multiplexer. This is much faster than the alt...
runs_to_tags_to_content = self._event_multiplexer.PluginRunToTagToContent( constants.DEBUGGER_PLUGIN_NAME) if run not in runs_to_tags_to_content: # The run lacks health pills. return {} # This is also a mapping between node name and plugin content because this # plugin tags by nod...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _tensor_proto_to_health_pill(self, tensor_event, node_name, device, output_slot): """Converts an event_accumulator.TensorEvent to a HealthPillEvent. Args: te...
return self._process_health_pill_value( wall_time=tensor_event.wall_time, step=tensor_event.step, device_name=device, output_slot=output_slot, node_name=node_name, tensor_proto=tensor_event.tensor_proto)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _obtain_health_pills_at_step(self, events_directory, node_names, step): """Reads disk to obtain the health pills for a run at a specific step. This could be ...
# Obtain all files with debugger-related events. pattern = os.path.join(events_directory, _DEBUGGER_EVENTS_GLOB_PATTERN) file_paths = glob.glob(pattern) if not file_paths: raise IOError( 'No events files found that matches the pattern %r.' % pattern) # Sort by name (and thus by ti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_health_pill_event(self, node_name_set, mapping, target_step, file_path): """Creates health pills out of data in an event. Creates health pills out o...
events_loader = event_file_loader.EventFileLoader(file_path) for event in events_loader.Load(): if not event.HasField('summary'): logger.warn( 'An event in a debugger events file lacks a summary.') continue if event.step < target_step: # This event is not of the...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_health_pill_value(self, wall_time, step, device_name, output_slot, node_name, tensor_proto, node_name_set=None): """Creates a HealthPillEvent contai...
if node_name_set and node_name not in node_name_set: # This event is not relevant. return None # Since we seek health pills for a specific step, this function # returns 1 health pill per node per step. The wall time is the # seconds since the epoch. elements = list(tensor_util.make_nda...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _info_to_string(info): """Convert a `TensorBoardInfo` to string form to be stored on disk. The format returned by this function is opaque and should only be ...
for key in _TENSORBOARD_INFO_FIELDS: field_type = _TENSORBOARD_INFO_FIELDS[key] if not isinstance(getattr(info, key), field_type.runtime_type): raise ValueError( "expected %r of type %s, but found: %r" % (key, field_type.runtime_type, getattr(info, key)) ) if info.version !=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _info_from_string(info_string): """Parse a `TensorBoardInfo` object from its string representation. Args: info_string: A string representation of a `TensorBo...
try: json_value = json.loads(info_string) except ValueError: raise ValueError("invalid JSON: %r" % (info_string,)) if not isinstance(json_value, dict): raise ValueError("not a JSON object: %r" % (json_value,)) if json_value.get("version") != version.VERSION: raise ValueError("incompatible vers...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_key(working_directory, arguments, configure_kwargs): """Compute a `TensorBoardInfo.cache_key` field. The format returned by this function is opaque. Cl...
if not isinstance(arguments, (list, tuple)): raise TypeError( "'arguments' should be a list of arguments, but found: %r " "(use `shlex.split` if given a string)" % (arguments,) ) datum = { "working_directory": working_directory, "arguments": arguments, "configure_k...
<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_info_dir(): """Get path to directory in which to store info files. The directory returned by this function is "owned" by this module. If the contents of...
path = os.path.join(tempfile.gettempdir(), ".tensorboard-info") try: os.makedirs(path) except OSError as e: if e.errno == errno.EEXIST and os.path.isdir(path): pass else: raise else: os.chmod(path, 0o777) 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 write_info_file(tensorboard_info): """Write TensorBoardInfo to the current process's info file. This should be called by `main` once the server is ready. Whe...
payload = "%s\n" % _info_to_string(tensorboard_info) with open(_get_info_file_path(), "w") as outfile: outfile.write(payload)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_info_file(): """Remove the current process's TensorBoardInfo file, if it exists. If the file does not exist, no action is taken and no error is raised...
try: os.unlink(_get_info_file_path()) except OSError as e: if e.errno == errno.ENOENT: # The user may have wiped their temporary directory or something. # Not a problem: we're already in the state that we want to be in. pass 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 get_all(): """Return TensorBoardInfo values for running TensorBoard processes. This function may not provide a perfect snapshot of the set of running process...
info_dir = _get_info_dir() results = [] for filename in os.listdir(info_dir): filepath = os.path.join(info_dir, filename) try: with open(filepath) as infile: contents = infile.read() except IOError as e: if e.errno == errno.EACCES: # May have been written by this module 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 start(arguments, timeout=datetime.timedelta(seconds=60)): """Start a new TensorBoard instance, or reuse a compatible one. If the cache key determined by the ...
match = _find_matching_instance( cache_key( working_directory=os.getcwd(), arguments=arguments, configure_kwargs={}, ), ) if match: return StartReused(info=match) (stdout_fd, stdout_path) = tempfile.mkstemp(prefix=".tensorboard-stdout-") (stderr_fd, stderr_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 _find_matching_instance(cache_key): """Find a running TensorBoard instance compatible with the cache key. Returns: A `TensorBoardInfo` object, or `None` if n...
infos = get_all() candidates = [info for info in infos if info.cache_key == cache_key] for candidate in sorted(candidates, key=lambda x: x.port): # TODO(@wchargin): Check here that the provided port is still live. return candidate 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 _maybe_read_file(filename): """Read the given file, if it exists. Args: filename: A path to a file. Returns: A string containing the file contents, or `None`...
try: with open(filename) as infile: return infile.read() except IOError as e: if e.errno == errno.ENOENT: 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 process_raw_trace(raw_trace): """Processes raw trace data and returns the UI data."""
trace = trace_events_pb2.Trace() trace.ParseFromString(raw_trace) return ''.join(trace_events_json.TraceEventsJsonStream(trace))
<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): """Whether this plugin is active and has any profile data to show. Detecting profile data is expensive, so this process runs asynchronously ...
# If we are already active, we remain active and don't recompute this. # Otherwise, try to acquire the lock without blocking; if we get it and # we're still not active, launch a thread to check if we're active and # release the lock once the computation is finished. Either way, this # thread 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 _run_dir(self, run): """Helper that maps a frontend run name to a profile "run" directory. The frontend run name consists of the TensorBoard run name (aka th...
run = run.rstrip('/') if '/' not in run: run = './' + run tb_run_name, _, profile_run_name = run.rpartition('/') tb_run_directory = self.multiplexer.RunPaths().get(tb_run_name) if tb_run_directory is None: # Check if logdir is a directory to handle case where it's actually a # mul...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_run_to_tools(self): """Generator for pairs of "run name" and a list of tools for that run. The "run name" here is a "frontend run name" - see _run_d...
self.start_grpc_stub_if_necessary() plugin_assets = self.multiplexer.PluginAssets(PLUGIN_NAME) tb_run_names_to_dirs = self.multiplexer.RunPaths() # Ensure that we also check the root logdir, even if it isn't a recognized # TensorBoard run (i.e. has no tfevents file directly under it), to remain ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def host_impl(self, run, tool): """Returns available hosts for the run and tool in the log directory. In the plugin log directory, each directory contains profil...
hosts = {} run_dir = self._run_dir(run) if not run_dir: logger.warn("Cannot find asset directory for: %s", run) return hosts tool_pattern = '*' + TOOLS[tool] try: files = tf.io.gfile.glob(os.path.join(run_dir, tool_pattern)) hosts = [os.path.basename(f).replace(TOOLS[tool], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data_impl(self, request): """Retrieves and processes the tool data for a run and a host. Args: request: XMLHttpRequest Returns: A string that can be served t...
run = request.args.get('run') tool = request.args.get('tag') host = request.args.get('host') run_dir = self._run_dir(run) # Profile plugin "run" is the last component of run dir. profile_run = os.path.basename(run_dir) if tool not in TOOLS: return None self.start_grpc_stub_if_ne...
<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(logdir, run_name, initial_temperature, ambient_temperature, heat_coefficient): """Run a temperature simulation. This will simulate an object at temperatu...
tf.compat.v1.reset_default_graph() tf.compat.v1.set_random_seed(0) with tf.name_scope('temperature'): # Create a mutable variable to hold the object's temperature, and # create a scalar summary to track its value over time. The name of # the summary will appear as "temperature/current" due to the ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Cleanse(obj, encoding='utf-8'): """Makes Python object appropriate for JSON serialization. - Replaces instances of Infinity/-Infinity/NaN with strings. - Tur...
if isinstance(obj, int): return obj elif isinstance(obj, float): if obj == _INFINITY: return 'Infinity' elif obj == _NEGATIVE_INFINITY: return '-Infinity' elif math.isnan(obj): return 'NaN' else: return obj elif isinstance(obj, bytes): return tf.compat.as_text(obj,...
<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, data, display_name=None, description=None, collections=None): """Create a legacy text summary op. Text data summarized via this plugin will be visib...
# 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, description=description) with tf.name_scope(name): with tf.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 pb(name, data, display_name=None, description=None): """Create a legacy text summary protobuf. Arguments: name: A name for the generated node. Will also serv...
# TODO(nickfelt): remove on-demand imports once dep situation is fixed. import tensorflow.compat.v1 as tf try: tensor = tf.make_tensor_proto(data, dtype=tf.string) except TypeError as e: raise ValueError(e) if display_name is None: display_name = name summary_metadata = metadata.create_summar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _GeneratorFromPath(path): """Create an event generator for file or directory at given path string."""
if not path: raise ValueError('path must be a valid string') if io_wrapper.IsTensorFlowEventsFile(path): return event_file_loader.EventFileLoader(path) else: return directory_watcher.DirectoryWatcher( path, event_file_loader.EventFileLoader, io_wrapper.IsTensorFlowEventsFile)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ParseFileVersion(file_version): """Convert the string file_version in event.proto into a float. Args: file_version: String file_version from event.proto Ret...
tokens = file_version.split('brain.Event:') try: return float(tokens[-1]) except ValueError: ## This should never happen according to the definition of file_version ## specified in event.proto. logger.warn( ('Invalid event.proto file_version. Defaulting to use of ' 'out-of-order ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Reload(self): """Loads all events added since the last call to `Reload`. If `Reload` was never called, loads all events in the file. Returns: The `EventAccum...
with self._generator_mutex: for event in self._generator.Load(): self._ProcessEvent(event) return 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 RetrievePluginAsset(self, plugin_name, asset_name): """Return the contents of a given plugin asset. Args: plugin_name: The string name of a plugin. asset_nam...
return plugin_asset_util.RetrieveAsset(self.path, 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 FirstEventTimestamp(self): """Returns the timestamp in seconds of the first event. If the first event has been loaded (either by this method or by `Reload`, ...
if self._first_event_timestamp is not None: return self._first_event_timestamp with self._generator_mutex: try: event = next(self._generator.Load()) self._ProcessEvent(event) return self._first_event_timestamp except StopIteration: raise ValueError('No 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 Graph(self): """Return the graph definition, if there is one. If the graph is stored directly, return that. If no graph is stored directly but a metagraph is...
graph = graph_pb2.GraphDef() if self._graph is not None: graph.ParseFromString(self._graph) return graph raise ValueError('There is no graph in this EventAccumulator')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def MetaGraph(self): """Return the metagraph definition, if there is one. Raises: ValueError: If there is no metagraph for this run. Returns: The `meta_graph_def...
if self._meta_graph is None: raise ValueError('There is no metagraph in this EventAccumulator') meta_graph = meta_graph_pb2.MetaGraphDef() meta_graph.ParseFromString(self._meta_graph) return meta_graph
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _CheckForRestartAndMaybePurge(self, event): """Check and discard expired events using SessionLog.START. Check for a SessionLog.START event and purge all prev...
if event.HasField( 'session_log') and event.session_log.status == event_pb2.SessionLog.START: self._Purge(event, by_tags=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ProcessHistogram(self, tag, wall_time, step, histo): """Processes a proto histogram by adding it to accumulated state."""
histo = self._ConvertHistogramProtoToTuple(histo) histo_ev = HistogramEvent(wall_time, step, histo) self.histograms.AddItem(tag, histo_ev) self.compressed_histograms.AddItem(tag, histo_ev, self._CompressHistogram)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _CompressHistogram(self, histo_ev): """Callback for _ProcessHistogram."""
return CompressedHistogramEvent( histo_ev.wall_time, histo_ev.step, compressor.compress_histogram_proto( histo_ev.histogram_value, self._compression_bps))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ProcessImage(self, tag, wall_time, step, image): """Processes an image by adding it to accumulated state."""
event = ImageEvent(wall_time=wall_time, step=step, encoded_image_string=image.encoded_image_string, width=image.width, height=image.height) self.images.AddItem(tag, event)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ProcessAudio(self, tag, wall_time, step, audio): """Processes a audio by adding it to accumulated state."""
event = AudioEvent(wall_time=wall_time, step=step, encoded_audio_string=audio.encoded_audio_string, content_type=audio.content_type, sample_rate=audio.sample_rate, length_frames=audio.length_frames) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ProcessScalar(self, tag, wall_time, step, scalar): """Processes a simple value by adding it to accumulated state."""
sv = ScalarEvent(wall_time=wall_time, step=step, value=scalar) self.scalars.AddItem(tag, sv)
<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 all new events from disk as raw serialized proto bytestrings. Calling Load multiple times in a row will not 'drop' events as long as the...
logger.debug('Loading events from %s', self._file_path) # GetNext() expects a status argument on TF <= 1.7. get_next_args = inspect.getargspec(self._reader.GetNext).args # pylint: disable=deprecated-method # First argument is self legacy_get_next = (len(get_next_args) > 1) while True: ...
<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 all new events from disk. Calling Load multiple times in a row will not 'drop' events as long as the return value is not iterated over. ...
for record in super(EventFileLoader, self).Load(): yield event_pb2.Event.FromString(record)
<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_session_run_index(self, event): """Parses the session_run_index value from the event proto. Args: event: The event with metadata that contains the ses...
metadata_string = event.log_message.message try: metadata = json.loads(metadata_string) except ValueError as e: logger.error( "Could not decode metadata string '%s' for step value: %s", metadata_string, e) return constants.SENTINEL_FOR_UNDETERMINED_STEP try: ...
<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_image_metadata(self, request): """Given a tag and list of runs, serve a list of metadata for images. Note that the images themselves are not sent; ins...
tag = request.args.get('tag') run = request.args.get('run') sample = int(request.args.get('sample', 0)) response = self._image_response_for_run(run, tag, sample) return http_util.Respond(request, response, '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_individual_image(self, request): """Serves an individual image."""
run = request.args.get('run') tag = request.args.get('tag') index = int(request.args.get('index')) sample = int(request.args.get('sample', 0)) data = self._get_individual_image(run, tag, index, sample) image_type = imghdr.what(None, data) content_type = _IMGHDR_TO_MIMETYPE.get(image_type, _...
<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_all(logdir, steps, thresholds, verbose=False): """Generate PR curve summaries. Arguments: logdir: The directory into which to store all the runs' data. s...
# First, we generate data for a PR curve that assigns even weights for # predictions of all classes. run_name = 'colors' if verbose: print('--- Running: %s' % run_name) start_runs( logdir=logdir, steps=steps, run_name=run_name, thresholds=thresholds) # Next, we generate data 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 image(name, data, step=None, max_outputs=3, description=None): """Write an image summary. Arguments: name: A name for this summary. The summary tag used for ...
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 set_examples(self, examples): """Sets the examples to be displayed in WIT. Args: examples: List of example protos. Returns: self, in order to enabled method ...
self.store('examples', examples) if len(examples) > 0: self.store('are_sequence_examples', isinstance(examples[0], tf.train.SequenceExample)) return 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 set_estimator_and_feature_spec(self, estimator, feature_spec): """Sets the model for inference as a TF Estimator. Instead of using TF Serving to host a model...
# If custom function is set, remove it before setting estimator self.delete('custom_predict_fn') self.store('estimator_and_spec', { 'estimator': estimator, 'feature_spec': feature_spec}) self.set_inference_address('estimator') # If no model name has been set, give a default if not self.h...
<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_compare_estimator_and_feature_spec(self, estimator, feature_spec): """Sets a second model for inference as a TF Estimator. If you wish to compare the res...
# If custom function is set, remove it before setting estimator self.delete('compare_custom_predict_fn') self.store('compare_estimator_and_spec', { 'estimator': estimator, 'feature_spec': feature_spec}) self.set_compare_inference_address('estimator') # If no model name has been set, give a d...
<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_custom_predict_fn(self, predict_fn): """Sets a custom function for inference. Instead of using TF Serving to host a model for WIT to query, WIT can direc...
# If estimator is set, remove it before setting predict_fn self.delete('estimator_and_spec') self.store('custom_predict_fn', predict_fn) self.set_inference_address('custom_predict_fn') # If no model name has been set, give a default if not self.has_model_name(): self.set_model_name('1') ...
<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_compare_custom_predict_fn(self, predict_fn): """Sets a second custom function for inference. If you wish to compare the results of two models in WIT, use...
# If estimator is set, remove it before setting predict_fn self.delete('compare_estimator_and_spec') self.store('compare_custom_predict_fn', predict_fn) self.set_compare_inference_address('custom_predict_fn') # If no model name has been set, give a default if not self.has_compare_model_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 _sections_to_variance_sections(self, sections_over_time): '''Computes the variance of corresponding sections over time. Returns: a list of np arrays. ''' variance_sections = [] for i in range(len(sections_over_time[0])): time_sections = [sections[i] for sections in sections_over_ti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _maybe_clear_deque(self): '''Clears the deque if certain parts of the config have changed.''' for config_item in ['values', 'mode', 'show_all']: if self.config[config_item] != self.old_config[config_item]: self.sections_over_time.clear() break self.old_config = self.config w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lazy_load(name): """Decorator to define a function that lazily loads the module 'name'. This can be used to defer importing troublesome dependencies - e.g. o...
def wrapper(load_fn): # Wrap load_fn to call it exactly once and update __dict__ afterwards to # make future lookups efficient (only failed lookups call __getattr__). @_memoize def load_once(self): if load_once.loading: raise ImportError("Circular import when resolving LazyModule %r" % ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _memoize(f): """Memoizing decorator for f, which must have exactly 1 hashable argument."""
nothing = object() # Unique "no value" sentinel object. cache = {} # Use a reentrant lock so that if f references the resulting wrapper we die # with recursion depth exceeded instead of deadlocking. lock = threading.RLock() @functools.wraps(f) def wrapper(arg): if cache.get(arg, nothing) is nothing:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tf(): """Provide the root module of a TF-like API for use within TensorBoard. By default this is equivalent to `import tensorflow as tf`, but it can be used ...
try: from tensorboard.compat import notf # pylint: disable=g-import-not-at-top except ImportError: try: import tensorflow # pylint: disable=g-import-not-at-top return tensorflow except ImportError: pass from tensorboard.compat import tensorflow_stub # pylint: disable=g-import-not...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tf2(): """Provide the root module of a TF-2.0 API for use within TensorBoard. Returns: The root module of a TF-2.0 API, if available. Raises: ImportError: if...
# Import the `tf` compat API from this file and check if it's already TF 2.0. if tf.__version__.startswith('2.'): return tf elif hasattr(tf, 'compat') and hasattr(tf.compat, 'v2'): # As a fallback, try `tensorflow.compat.v2` if it's defined. return tf.compat.v2 raise ImportError('cannot import tens...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pywrap_tensorflow(): """Provide pywrap_tensorflow access in TensorBoard. pywrap_tensorflow cannot be accessed from tf.python.pywrap_tensorflow and needs to ...
try: from tensorboard.compat import notf # pylint: disable=g-import-not-at-top except ImportError: try: from tensorflow.python import pywrap_tensorflow # pylint: disable=g-import-not-at-top return pywrap_tensorflow except ImportError: pass from tensorboard.compat.tensorflow_stub 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 create_experiment_summary(): """Returns a summary proto buffer holding this experiment."""
# Convert TEMPERATURE_LIST to google.protobuf.ListValue temperature_list = struct_pb2.ListValue() temperature_list.extend(TEMPERATURE_LIST) materials = struct_pb2.ListValue() materials.extend(HEAT_COEFFICIENTS.keys()) return summary.experiment_pb( hparam_infos=[ api_pb2.HParamInfo(name='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 run(logdir, session_id, hparams, group_name): """Runs a temperature simulation. This will simulate an object at temperature `initial_temperature` sitting at ...
tf.reset_default_graph() tf.set_random_seed(0) initial_temperature = hparams['initial_temperature'] ambient_temperature = hparams['ambient_temperature'] heat_coefficient = HEAT_COEFFICIENTS[hparams['material']] session_dir = os.path.join(logdir, session_id) writer = tf.summary.FileWriter(session_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 get_filesystem(filename): """Return the registered filesystem for the given file."""
filename = compat.as_str_any(filename) prefix = "" index = filename.find("://") if index >= 0: prefix = filename[:index] fs = _REGISTERED_FILESYSTEMS.get(prefix, None) if fs is None: raise ValueError("No recognized filesystem for prefix %s" % prefix) return fs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def walk(top, topdown=True, onerror=None): """Recursive directory tree generator for directories. Args: top: string, a Directory name topdown: bool, Traverse pre...
top = compat.as_str_any(top) fs = get_filesystem(top) try: listing = listdir(top) except errors.NotFoundError as err: if onerror: onerror(err) else: return files = [] subdirs = [] for item in listing: full_path = fs.join(top, compat.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 bucket_and_path(self, url): """Split an S3-prefixed URL into bucket and path."""
url = compat.as_str_any(url) if url.startswith("s3://"): url = url[len("s3://"):] idx = url.index("/") bucket = url[:idx] path = url[(idx + 1):] return bucket, 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 exists(self, filename): """Determines whether a path exists or not."""
client = boto3.client("s3") bucket, path = self.bucket_and_path(filename) r = client.list_objects(Bucket=bucket, Prefix=path, Delimiter="/") if r.get("Contents") or r.get("CommonPrefixes"): return True return False