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 as_proto(self): """Returns this shape as a `TensorShapeProto`."""
if self._dims is None: return tensor_shape_pb2.TensorShapeProto(unknown_rank=True) else: return tensor_shape_pb2.TensorShapeProto( dim=[ tensor_shape_pb2.TensorShapeProto.Dim( size=-1 if d.value is None else d.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 convert_predict_response(pred, serving_bundle): """Converts a PredictResponse to ClassificationResponse or RegressionResponse. Args: pred: PredictResponse to...
output = pred.outputs[serving_bundle.predict_output_tensor] raw_output = output.float_val if serving_bundle.model_type == 'classification': values = [] for example_index in range(output.tensor_shape.dim[0].size): start = example_index * output.tensor_shape.dim[1].size values.append(raw_output...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_prediction_values(values, serving_bundle, model_spec=None): """Converts tensor values into ClassificationResponse or RegressionResponse. Args: values...
if serving_bundle.model_type == 'classification': response = classification_pb2.ClassificationResponse() for example_index in range(len(values)): classification = response.result.classifications.add() for class_index in range(len(values[example_index])): class_score = classification.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 _update_dicts(name_scope, model_layer, input_to_in_layer, model_name_to_output, prev_node_name): """Updates input_to_in_layer, model_name_to_output, and prev...
layer_config = model_layer.get('config') if not layer_config.get('layers'): raise ValueError('layer is not a model.') node_name = _scoped_name(name_scope, layer_config.get('name')) input_layers = layer_config.get('input_layers') output_layers = layer_config.get('output_layers') inbound_nodes = model_l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def keras_model_to_graph_def(keras_layer): """Returns a GraphDef representation of the Keras model in a dict form. Note that it only supports models that impleme...
input_to_layer = {} model_name_to_output = {} g = GraphDef() # Sequential model layers do not have a field "inbound_nodes" but # instead are defined implicitly via order of layers. prev_node_name = None for (name_scope, layer) in _walk_layers(keras_layer): if _is_model(layer): (input_to_layer...
<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): """Returns True if the hparams plugin is active. The hparams plugin is active iff there is a tag with the hparams plugin name as its plugin ...
if not self._context.multiplexer: return False scalars_plugin = self._get_scalars_plugin() if not scalars_plugin or not scalars_plugin.is_active(): return False return bool(self._context.multiplexer.PluginRunToTagToContent( metadata.PLUGIN_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 markdown_to_safe_html(markdown_string): """Convert Markdown to HTML that's safe to splice into the DOM. Arguments: markdown_string: A Unicode string or UTF-8...
warning = '' # Convert to utf-8 whenever we have a binary input. if isinstance(markdown_string, six.binary_type): markdown_string_decoded = markdown_string.decode('utf-8') # Remove null bytes and warn if there were any, since it probably means # we were given a bad encoding. markdown_string = 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 as_dtype(type_value): """Converts the given `type_value` to a `DType`. Args: type_value: A value that can be converted to a `tf.DType` object. This may curre...
if isinstance(type_value, DType): return type_value try: return _INTERN_TABLE[type_value] except KeyError: pass try: return _STRING_TO_TF[type_value] except KeyError: pass try: return _PYTHON_TO_TF[type_value] except KeyError: pass ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def real_dtype(self): """Returns the dtype correspond to this dtype's real part."""
base = self.base_dtype if base == complex64: return float32 elif base == complex128: return float64 else: 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 min(self): """Returns the minimum representable value in this data type. Raises: TypeError: if this is a non-numeric, unordered, or quantized type. """
if self.is_quantized or self.base_dtype in ( bool, string, complex64, complex128, ): raise TypeError("Cannot find minimum value of %s." % self) # there is no simple way to get the min value of a dtype, we have to check # float...
<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_compatible_with(self, other): """Returns True if the `other` DType will be converted to this DType. The conversion rules are as follows: ```python DType(T...
other = as_dtype(other) return self._type_enum in ( other.as_datatype_enum, other.base_dtype.as_datatype_enum, )
<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. This function also starts a debugger data server on separate thread if the plugin ha...
return { _ACK_ROUTE: self._serve_ack, _COMM_ROUTE: self._serve_comm, _DEBUGGER_GRPC_HOST_PORT_ROUTE: self._serve_debugger_grpc_host_port, _DEBUGGER_GRAPH_ROUTE: self._serve_debugger_graph, _GATED_GRPC_ROUTE: self._serve_gated_grpc, _TENSOR_DATA_ROUTE: self._serve_ten...
<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): """The audio plugin is active iff any run has at least one relevant tag."""
if not self._multiplexer: return False return bool(self._multiplexer.PluginRunToTagToContent(metadata.PLUGIN_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 _index_impl(self): """Return information about the tags in each run. Result is a dictionary of the form { "runName1": { "tagName1": { "displayName": "The fir...
runs = self._multiplexer.Runs() result = {run: {} for run in runs} mapping = self._multiplexer.PluginRunToTagToContent(metadata.PLUGIN_NAME) for (run, tag_to_content) in six.iteritems(mapping): for tag in tag_to_content: summary_metadata = self._multiplexer.SummaryMetadata(run, 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 _serve_audio_metadata(self, request): """Given a tag and list of runs, serve a list of metadata for audio. Note that the actual audio data are not sent; inst...
tag = request.args.get('tag') run = request.args.get('run') sample = int(request.args.get('sample', 0)) events = self._multiplexer.Tensors(run, tag) response = self._audio_response_for_run(events, 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 _audio_response_for_run(self, tensor_events, run, tag, sample): """Builds a JSON-serializable object with information about audio. Args: tensor_events: A lis...
response = [] index = 0 filtered_events = self._filter_by_sample(tensor_events, sample) content_type = self._get_mime_type(run, tag) for (index, tensor_event) in enumerate(filtered_events): data = tensor_util.make_ndarray(tensor_event.tensor_proto) label = data[sample, 1] response...
<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_for_individual_audio(self, run, tag, sample, index): """Builds a URL for accessing the specified audio. This should be kept in sync with _serve_audio_...
query_string = urllib.parse.urlencode({ 'run': run, 'tag': tag, 'sample': sample, 'index': index, }) return query_string
<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_audio(self, request): """Serve encoded audio data."""
tag = request.args.get('tag') run = request.args.get('run') index = int(request.args.get('index')) sample = int(request.args.get('sample', 0)) events = self._filter_by_sample(self._multiplexer.Tensors(run, tag), sample) data = tensor_util.make_ndarray(events[index].tensor_proto)[sample, 0] ...
<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, images, max_outputs=3, display_name=None, description=None, collections=None): """Create a legacy image summary op for use in a TensorFlow graph. Ar...
# 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), \ 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, images, max_outputs=3, display_name=None, description=None): """Create a legacy image summary protobuf. This behaves as if you were to create an `op...
# TODO(nickfelt): remove on-demand imports once dep situation is fixed. import tensorflow.compat.v1 as tf images = np.array(images).astype(np.uint8) if images.ndim != 4: raise ValueError('Shape %r must have rank 4' % (images.shape, )) limited_images = images[:max_outputs] encoded_images = [encoder.en...
<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_size_guidance_from_flags(flags): """Apply user per-summary size guidance overrides."""
tensor_size_guidance = dict(DEFAULT_TENSOR_SIZE_GUIDANCE) if not flags or not flags.samples_per_plugin: return tensor_size_guidance for token in flags.samples_per_plugin.split(','): k, v = token.strip().split('=') tensor_size_guidance[k] = int(v) return tensor_size_guidance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def standard_tensorboard_wsgi(flags, plugin_loaders, assets_zip_provider): """Construct a TensorBoardWSGIApp with standard plugins and multiplexer. Args: flags: ...
multiplexer = event_multiplexer.EventMultiplexer( size_guidance=DEFAULT_SIZE_GUIDANCE, tensor_size_guidance=tensor_size_guidance_from_flags(flags), purge_orphaned_data=flags.purge_orphaned_data, max_reload_threads=flags.max_reload_threads) loading_multiplexer = multiplexer reload_interval...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def TensorBoardWSGIApp(logdir, plugins, multiplexer, reload_interval, path_prefix='', reload_task='auto'): """Constructs the TensorBoard application. Args: logdi...
path_to_run = parse_event_files_spec(logdir) if reload_interval >= 0: # We either reload the multiplexer once when TensorBoard starts up, or we # continuously reload the multiplexer. start_reloading_multiplexer(multiplexer, path_to_run, reload_interval, reload_task) 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 parse_event_files_spec(logdir): """Parses `logdir` into a map from paths to run group names. The events files flag format is a comma-separated list of path s...
files = {} if logdir is None: return files # Make sure keeping consistent with ParseURI in core/lib/io/path.cc uri_pattern = re.compile('[a-zA-Z][0-9a-zA-Z.]*://.*') for specification in logdir.split(','): # Check if the spec contains group. A spec start with xyz:// is regarded as # URI path spec...
<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_reloading_multiplexer(multiplexer, path_to_run, load_interval, reload_task): """Starts automatically reloading the given multiplexer. If `load_interval...
if load_interval < 0: raise ValueError('load_interval is negative: %d' % load_interval) def _reload(): while True: start = time.time() logger.info('TensorBoard reload process beginning') for path, name in six.iteritems(path_to_run): multiplexer.AddRunsFromDirectory(path, 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 get_database_info(db_uri): """Returns TBContext fields relating to SQL database. Args: db_uri: A string URI expressing the DB file, e.g. "sqlite:~/tb.db". Re...
if not db_uri: return None, None scheme = urlparse.urlparse(db_uri).scheme if scheme == 'sqlite': return sqlite3, create_sqlite_connection_provider(db_uri) else: raise ValueError('Only sqlite DB URIs are supported now: ' + db_uri)
<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_sqlite_connection_provider(db_uri): """Returns function that returns SQLite Connection objects. Args: db_uri: A string URI expressing the DB file, e.g...
uri = urlparse.urlparse(db_uri) if uri.scheme != 'sqlite': raise ValueError('Scheme is not sqlite: ' + db_uri) if uri.netloc: raise ValueError('Can not connect to SQLite over network: ' + db_uri) if uri.path == ':memory:': raise ValueError('Memory mode SQLite not supported: ' + db_uri) path = os....
<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_plugins_listing(self, request): """Serves an object mapping plugin name to whether it is enabled. Args: request: The werkzeug.Request object. Returns:...
response = {} for plugin in self._plugins: start = time.time() response[plugin.plugin_name] = plugin.is_active() elapsed = time.time() - start logger.info( 'Plugin listing: is_active() for %s took %0.3f seconds', plugin.plugin_name, elapsed) return http_util.Resp...
<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_time_indices(s): """Parse a string as time indices. Args: s: A valid slicing string for time indices. E.g., '-1', '[:]', ':', '2:10' Returns: A slice o...
if not s.startswith('['): s = '[' + s + ']' parsed = command_parser._parse_slices(s) if len(parsed) != 1: raise ValueError( 'Invalid number of slicing objects in time indices (%d)' % len(parsed)) else: return parsed[0]
<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_buffers_for_display(s, limit=40): """Process a buffer for human-readable display. This function performs the following operation on each of the buffe...
if isinstance(s, (list, tuple)): return [process_buffers_for_display(elem, limit=limit) for elem in s] else: length = len(s) if length > limit: return (binascii.b2a_qp(s[:limit]) + b' (length-%d truncated at %d bytes)' % (length, limit)) else: return binascii.b2a_qp(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 array_view(array, slicing=None, mapping=None): """View a slice or the entirety of an ndarray. Args: array: The input array, as an numpy.ndarray. slicing: Opt...
dtype = translate_dtype(array.dtype) sliced_array = (array[command_parser._parse_slices(slicing)] if slicing else array) if np.isscalar(sliced_array) and str(dtype) == 'string': # When a string Tensor (for which dtype is 'object') is sliced down to only # one element, it becomes a str...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def array_to_base64_png(array): """Convert an array into base64-enoded PNG image. Args: array: A 2D np.ndarray or nested list of items. Returns: A base64-encoded...
# TODO(cais): Deal with 3D case. # TODO(cais): If there are None values in here, replace them with all NaNs. array = np.array(array, dtype=np.float32) if len(array.shape) != 2: raise ValueError( "Expected rank-2 array; received rank-%d array." % len(array.shape)) if not np.size(array): 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 _safe_copy_proto_list_values(dst_proto_list, src_proto_list, get_key): """Safely merge values from `src_proto_list` into `dst_proto_list`. Each element in `d...
def _assert_proto_container_unique_keys(proto_list, get_key): """Asserts proto_list to only contains unique keys. Args: proto_list: A `RepeatedCompositeContainer` or `RepeatedScalarContainer`. get_key: A function that takes an element of `proto_list` and returns a hashable key. Rai...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combine_graph_defs(to_proto, from_proto): """Combines two GraphDefs by adding nodes from from_proto into to_proto. All GraphDefs are expected to be of Tensor...
if from_proto.version != to_proto.version: raise ValueError('Cannot combine GraphDefs of different versions.') try: _safe_copy_proto_list_values( to_proto.node, from_proto.node, lambda n: n.name) except _ProtoListDuplicateKeyError as exc: raise ValueError('A GraphDef contains...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scalar(name, data, step=None, description=None): """Write a scalar summary. Arguments: name: A name for this summary. The summary tag used for TensorBoard wi...
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 scalar_pb(tag, data, description=None): """Create a scalar summary_pb2.Summary protobuf. Arguments: tag: String tag for the summary. data: A 0-dimensional `n...
arr = np.array(data) if arr.shape != (): raise ValueError('Expected scalar shape for tensor, got shape: %s.' % arr.shape) if arr.dtype.kind not in ('b', 'i', 'u', 'f'): # bool, int, uint, float raise ValueError('Cast %s to float is not supported' % arr.dtype.name) tensor_proto = 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 dump_data(logdir): """Dumps plugin data to the log directory."""
# Create a tfevents file in the logdir so it is detected as a run. write_empty_event_file(logdir) plugin_logdir = plugin_asset_util.PluginDirectory( logdir, profile_plugin.ProfilePlugin.plugin_name) _maybe_create_directory(plugin_logdir) for run in profile_demo_data.RUNS: run_dir = os.path.join(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 calc_health_pill(tensor): """Calculate health pill of a tensor. Args: tensor: An instance of `np.array` (for initialized tensors) or `tensorflow.python.debug...
health_pill = [0.0] * 14 # TODO(cais): Add unit test for this method that compares results with # DebugNumericSummary output. # Is tensor initialized. if not isinstance(tensor, np.ndarray): return health_pill health_pill[0] = 1.0 if not (np.issubdtype(tensor.dtype, np.float) or np.issu...
<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_config(self): '''Reads the config file from disk or creates a new one.''' filename = '{}/{}'.format(self.PLUGIN_LOGDIR, CONFIG_FILENAME) modified_time = os.path.getmtime(filename) if modified_time != self.config_last_modified_time: config = read_pickle(filename, default=self.previous_con...
<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_summary(self, session, frame): '''Writes the frame to disk as a tensor summary.''' summary = session.run(self.summary_op, feed_dict={ self.frame_placeholder: frame }) path = '{}/{}'.format(self.PLUGIN_LOGDIR, SUMMARY_FILENAME) write_file(summary, 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 _enough_time_has_passed(self, FPS): '''For limiting how often frames are computed.''' if FPS == 0: return False else: earliest_time = self.last_update_time + (1.0 / FPS) return time.time() >= earliest_time
<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_recording(self, frame, config): '''Adds a frame to the current video output.''' # pylint: disable=redefined-variable-type should_record = config['is_recording'] if should_record: if not self.is_recording: self.is_recording = True logger.info( 'Starting reco...
<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(self, session, arrays=None, frame=None): '''Creates a frame and writes it to disk. Args: arrays: a list of np arrays. Use the "custom" option in the client. frame: a 2D np array. This way the plugin can be used for video of any kind, not just the visualization that comes wit...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def gradient_helper(optimizer, loss, var_list=None): '''A helper to get the gradients out at each step. Args: optimizer: the optimizer op. loss: the op that computes your loss value. Returns: the gradient tensors and the train_step op. ''' if var_list is None: var_list = tf.compa...
<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_extractors(col_params): """Creates extractors to extract properties corresponding to 'col_params'. Args: col_params: List of ListSessionGroupsRequest...
result = [] for col_param in col_params: result.append(_create_extractor(col_param)) return result
<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_metric_extractor(metric_name): """Returns function that extracts a metric from a session group or a session. Args: metric_name: tensorboard.hparams.M...
def extractor_fn(session_or_group): metric_value = _find_metric_value(session_or_group, metric_name) return metric_value.value if metric_value else None return extractor_fn
<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_metric_value(session_or_group, metric_name): """Returns the metric_value for a given metric in a session or session group. Args: session_or_group: A Se...
# Note: We can speed this up by converting the metric_values field # to a dictionary on initialization, to avoid a linear search here. We'll # need to wrap the SessionGroup and Session protos in a python object for # that. for metric_value in session_or_group.metric_values: if (metric_value.name.tag == 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 _create_hparam_extractor(hparam_name): """Returns an extractor function that extracts an hparam from a session group. Args: hparam_name: str. Identies the hp...
def extractor_fn(session_group): if hparam_name in session_group.hparams: return _value_to_python(session_group.hparams[hparam_name]) return None return extractor_fn
<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_filters(col_params, extractors): """Creates filters for the given col_params. Args: col_params: List of ListSessionGroupsRequest.ColParam protobufs. ...
result = [] for col_param, extractor in zip(col_params, extractors): a_filter = _create_filter(col_param, extractor) if a_filter: result.append(a_filter) return result
<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_filter(col_param, extractor): """Creates a filter for the given col_param and extractor. Args: col_param: A tensorboard.hparams.ColParams object iden...
include_missing_values = not col_param.exclude_missing_values if col_param.HasField('filter_regexp'): value_filter_fn = _create_regexp_filter(col_param.filter_regexp) elif col_param.HasField('filter_interval'): value_filter_fn = _create_interval_filter(col_param.filter_interval) elif col_param.HasField...
<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_regexp_filter(regex): """Returns a boolean function that filters strings based on a regular exp. Args: regex: A string describing the regexp to use. ...
# Warning: Note that python's regex library allows inputs that take # exponential time. Time-limiting it is difficult. When we move to # a true multi-tenant tensorboard server, the regexp implementation here # would need to be replaced by something more secure. compiled_regex = re.compile(regex) def filter...
<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_interval_filter(interval): """Returns a function that checkes whether a number belongs to an interval. Args: interval: A tensorboard.hparams.Interval...
def filter_fn(value): if (not isinstance(value, six.integer_types) and not isinstance(value, float)): raise error.HParamsError( 'Cannot use an interval filter for a value of type: %s, Value: %s' % (type(value), value)) return interval.min_value <= value and value <= interval...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _value_to_python(value): """Converts a google.protobuf.Value to a native Python object."""
assert isinstance(value, struct_pb2.Value) field = value.WhichOneof('kind') if field == 'number_value': return value.number_value elif field == 'string_value': return value.string_value elif field == 'bool_value': return value.bool_value else: raise ValueError('Unknown struct_pb2.Value one...
<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_avg_session_metrics(session_group): """Sets the metrics for the group to be the average of its sessions. The resulting session group metrics consist of ...
assert session_group.sessions, 'SessionGroup cannot be empty.' # Algorithm: Iterate over all (session, metric) pairs and maintain a # dict from _MetricIdentifier to _MetricStats objects. # Then use the final dict state to compute the average for each metric. metric_stats = collections.defaultdict(_MetricStat...
<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_median_session_metrics(session_group, aggregation_metric): """Sets the metrics for session_group to those of its "median session". The median session is...
measurements = sorted(_measurements(session_group, aggregation_metric), key=operator.attrgetter('metric_value.value')) median_session = measurements[(len(measurements) - 1) // 2].session_index del session_group.metric_values[:] session_group.metric_values.MergeFrom( session_group....
<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_extremum_session_metrics(session_group, aggregation_metric, extremum_fn): """Sets the metrics for session_group to those of its "extremum session". The ...
measurements = _measurements(session_group, aggregation_metric) ext_session = extremum_fn( measurements, key=operator.attrgetter('metric_value.value')).session_index del session_group.metric_values[:] session_group.metric_values.MergeFrom( session_group.sessions[ext_session].metric_values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _measurements(session_group, metric_name): """A generator for the values of the metric across the sessions in the group. Args: session_group: A SessionGroup ...
for session_index, session in enumerate(session_group.sessions): metric_value = _find_metric_value(session, metric_name) if not metric_value: continue yield _Measurement(metric_value, session_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 _build_session_groups(self): """Returns a list of SessionGroups protobuffers from the summary data."""
# Algorithm: We keep a dict 'groups_by_name' mapping a SessionGroup name # (str) to a SessionGroup protobuffer. We traverse the runs associated with # the plugin--each representing a single session. We form a Session # protobuffer from each run and add it to the relevant SessionGroup object # in 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 _add_session(self, session, start_info, groups_by_name): """Adds a new Session protobuffer to the 'groups_by_name' dictionary. Called by _build_session_group...
# If the group_name is empty, this session's group contains only # this session. Use the session name for the group name since session # names are unique. group_name = start_info.group_name or session.name if group_name in groups_by_name: groups_by_name[group_name].sessions.extend([session]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_session(self, name, start_info, end_info): """Builds a session object."""
assert start_info is not None result = api_pb2.Session( name=name, start_time_secs=start_info.start_time_secs, model_uri=start_info.model_uri, metric_values=self._build_session_metric_values(name), monitor_url=start_info.monitor_url) if end_info is not None: 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 _build_session_metric_values(self, session_name): """Builds the session metric values."""
# result is a list of api_pb2.MetricValue instances. result = [] metric_infos = self._experiment.metric_infos for metric_info in metric_infos: metric_name = metric_info.name try: metric_eval = metrics.last_metric_eval( self._context.multiplexer, session_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 _aggregate_metrics(self, session_group): """Sets the metrics of the group based on aggregation_type."""
if (self._request.aggregation_type == api_pb2.AGGREGATION_AVG or self._request.aggregation_type == api_pb2.AGGREGATION_UNSET): _set_avg_session_metrics(session_group) elif self._request.aggregation_type == api_pb2.AGGREGATION_MEDIAN: _set_median_session_metrics(session_group, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sort(self, session_groups): """Sorts 'session_groups' in place according to _request.col_params."""
# Sort by session_group name so we have a deterministic order. session_groups.sort(key=operator.attrgetter('name')) # Sort by lexicographical order of the _request.col_params whose order # is not ORDER_UNSPECIFIED. The first such column is the primary sorting # key, the second is the secondary sor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def readAudioFile(path): ''' This function returns a numpy array that stores the audio samples of a specified WAV of AIFF file ''' extension = os.path.splitext(path)[1] try: #if extension.lower() == '.wav': #[Fs, x] = wavfile.read(path) if extension.lower() == '.aif' or ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def computePreRec(cm, class_names): ''' This function computes the precision, recall and f1 measures, given a confusion matrix ''' n_classes = cm.shape[0] if len(class_names) != n_classes: print("Error in computePreRec! Confusion matrix and class_names " "list must be of th...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def trainHMM_computeStatistics(features, labels): ''' This function computes the statistics used to train an HMM joint segmentation-classification model using a sequence of sequential features and respective labels ARGUMENTS: - features: a numpy matrix of feature vectors (numOfDimensions x n_wi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def levenshtein(str1, s2): ''' Distance between two strings ''' N1 = len(str1) N2 = len(s2) stringRange = [range(N1 + 1)] * (N2 + 1) for i in range(N2 + 1): stringRange[i] = range(i,i + N1 + 1) for i in range(0,N2): for j in range(0,N1): if str1[j] == s2[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 chordialDiagram(fileStr, SM, Threshold, names, namesCategories): ''' Generates a d3js chordial diagram that illustrates similarites ''' colors = text_list_to_colors_simple(namesCategories) SM2 = SM.copy() SM2 = (SM2 + SM2.T) / 2.0 for i in range(SM2.shape[0]): M = Threshold # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stZCR(frame): """Computes zero crossing rate of frame"""
count = len(frame) countZ = numpy.sum(numpy.abs(numpy.diff(numpy.sign(frame)))) / 2 return (numpy.float64(countZ) / numpy.float64(count-1.0))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stHarmonic(frame, fs): """ Computes harmonic ratio and pitch """
M = numpy.round(0.016 * fs) - 1 R = numpy.correlate(frame, frame, mode='full') g = R[len(frame)-1] R = R[len(frame):-1] # estimate m0 (as the first zero crossing of R) [a, ] = numpy.nonzero(numpy.diff(numpy.sign(R))) if len(a) == 0: m0 = len(R)-1 else: m0 = a[0] 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 stMFCC(X, fbank, n_mfcc_feats): """ Computes the MFCCs of a frame, given the fft mag ARGUMENTS: X: fft magnitude abs(FFT) fbank: filter bank (see mfccInitFil...
mspec = numpy.log10(numpy.dot(X, fbank.T)+eps) ceps = dct(mspec, type=2, norm='ortho', axis=-1)[:n_mfcc_feats] return ceps
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stChromaFeaturesInit(nfft, fs): """ This function initializes the chroma matrices used in the calculation of the chroma features """
freqs = numpy.array([((f + 1) * fs) / (2 * nfft) for f in range(nfft)]) Cp = 27.50 nChroma = numpy.round(12.0 * numpy.log2(freqs / Cp)).astype(int) nFreqsPerChroma = numpy.zeros((nChroma.shape[0], )) uChroma = numpy.unique(nChroma) for u in uChroma: idx = numpy.nonzero(nChroma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stFeatureExtraction(signal, fs, win, step): """ This function implements the shor-term windowing process. For each short-term window a set of features is ext...
win = int(win) step = int(step) # Signal normalization signal = numpy.double(signal) signal = signal / (2.0 ** 15) DC = signal.mean() MAX = (numpy.abs(signal)).max() signal = (signal - DC) / (MAX + 0.0000000001) N = len(signal) # total number of sa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mtFeatureExtraction(signal, fs, mt_win, mt_step, st_win, st_step): """ Mid-term feature extraction """
mt_win_ratio = int(round(mt_win / st_step)) mt_step_ratio = int(round(mt_step / st_step)) mt_features = [] st_features, f_names = stFeatureExtraction(signal, fs, st_win, st_step) n_feats = len(st_features) n_stats = 2 mt_features, mid_feature_names = [], [] #for i in range(n_stats *...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dirWavFeatureExtraction(dirName, mt_win, mt_step, st_win, st_step, compute_beat=False): """ This function extracts the mid-term features of the WAVE files of...
all_mt_feats = numpy.array([]) process_times = [] types = ('*.wav', '*.aif', '*.aiff', '*.mp3', '*.au', '*.ogg') wav_file_list = [] for files in types: wav_file_list.extend(glob.glob(os.path.join(dirName, files))) wav_file_list = sorted(wav_file_list) wav_file_list2, mt_feat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dirWavFeatureExtractionNoAveraging(dirName, mt_win, mt_step, st_win, st_step): """ This function extracts the mid-term features of the WAVE files of a partic...
all_mt_feats = numpy.array([]) signal_idx = numpy.array([]) process_times = [] types = ('*.wav', '*.aif', '*.aiff', '*.ogg') wav_file_list = [] for files in types: wav_file_list.extend(glob.glob(os.path.join(dirName, files))) wav_file_list = sorted(wav_file_list) for i, wav...
<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_bundle(data_bundle_path, locale): """ Sync Data Bundle """
import rqalpha.utils.bundle_helper rqalpha.utils.bundle_helper.update_bundle(data_bundle_path, locale)
<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(**kwargs): """ Start to run a strategy """
config_path = kwargs.get('config_path', None) if config_path is not None: config_path = os.path.abspath(config_path) kwargs.pop('config_path') if not kwargs.get('base__securities', None): kwargs.pop('base__securities', None) from rqalpha import main source_code = kwargs.get...
<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(directory): """ Generate example strategies to target folder """
source_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "examples") try: shutil.copytree(source_dir, os.path.join(directory, "examples")) except OSError as e: if e.errno == errno.EEXIST: six.print_("Folder examples is exists.")
<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_config(directory): """ Generate default config file """
default_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "config.yml") target_config_path = os.path.abspath(os.path.join(directory, 'config.yml')) shutil.copy(default_config, target_config_path) six.print_("Config file has been generated in", target_config_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 perform_request(self, method, url, headers=None, params=None, body=None): """ Perform the actual request. Retrieve a connection from the connection pool, pas...
if body is not None: body = self.serializer.dumps(body) # some clients or environments don't support sending GET with body if method in ('HEAD', 'GET') and self.send_get_body_as != 'GET': # send it as post instead if self.send_get_body_as == ...
<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_commits(head, name): """ Go through the git repository log and generate a document per commit containing all the metadata. """
for commit in head.traverse(): yield { '_id': commit.hexsha, 'repository': name, 'committed_date': datetime.fromtimestamp(commit.committed_date), 'committer': { 'name': commit.committer.name, 'email': commit.committer.email, ...
<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_repo(client, path=None, index='git'): """ Parse a git repository with all it's commits and load it into elasticsearch using `client`. If the index doesn...
path = dirname(dirname(abspath(__file__))) if path is None else path repo_name = basename(path) repo = git.Repo(path) create_git_index(client, index) # we let the streaming bulk continuously process the commits as they come # in - since the `parse_commits` function is a generator this will av...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parallel_bulk( client, actions, thread_count=4, chunk_size=500, max_chunk_bytes=100 * 1024 * 1024, queue_size=4, expand_action_callback=expand_action, *args, ...
# Avoid importing multiprocessing unless parallel_bulk is used # to avoid exceptions on restricted environments like App Engine from multiprocessing.pool import ThreadPool actions = map(expand_action_callback, actions) class BlockingPool(ThreadPool): def _setup_queues(self): 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 forcemerge(self, index=None, params=None): """ The force merge API allows to force merging of one or more indices through an API. The merge relates to the nu...
return self.transport.perform_request( "POST", _make_path(index, "_forcemerge"), params=params )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rollover(self, alias, new_index=None, body=None, params=None): """ The rollover index API rolls an alias over to a new index when the existing index is consi...
if alias in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'alias'.") return self.transport.perform_request( "POST", _make_path(alias, "_rollover", new_index), params=params, body=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 _escape(value): """ Escape a single value of a URL string or a query parameter. If it is a list or tuple, turn it into a comma-separated string first. """
# make sequences into comma-separated stings if isinstance(value, (list, tuple)): value = ",".join(value) # dates and datetimes into isoformat elif isinstance(value, (date, datetime)): value = value.isoformat() # make bools into true/false strings elif isinstance(value, bool)...
<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_path(*parts): """ Create a URL string from parts, omit all `None` values and empty strings. Convert lists and tuples to comma separated values. """
# TODO: maybe only allow some parts to be lists/tuples ? return "/" + "/".join( # preserve ',' and '*' in url for nicer URLs in logs quote_plus(_escape(p), b",*") for p in parts if p not in SKIP_IN_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 query_params(*es_query_params): """ Decorator that pops all accepted parameters from method's kwargs and puts them in the params argument. """
def _wrapper(func): @wraps(func) def _wrapped(*args, **kwargs): params = {} if "params" in kwargs: params = kwargs.pop("params").copy() for p in es_query_params + GLOBAL_PARAMS: if p in kwargs: v = kwargs.pop(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 print_hits(results): " Simple utility function to print results of a search query. " print_search_stats(results) for hit in results['hits']['hits']: # get created date for a repo and fallback to authored_date for a commit created_at = parse_date(hit['_source'].get('created_at', hit['_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 post(self): """Deal with incoming requests."""
body = tornado.escape.json_decode(self.request.body) try: self._bo.register( params=body["params"], target=body["target"], ) print("BO has registered: {} points.".format(len(self._bo.space)), end="\n\n") except KeyError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, params, target): """Expect observation with known target"""
self._space.register(params, target) self.dispatch(Events.OPTMIZATION_STEP)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def probe(self, params, lazy=True): """Probe target of x"""
if lazy: self._queue.add(params) else: self._space.probe(params) self.dispatch(Events.OPTMIZATION_STEP)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def suggest(self, utility_function): """Most promissing point to probe next"""
if len(self._space) == 0: return self._space.array_to_params(self._space.random_sample()) # Sklearn's GP throws a large number of warnings at times, but # we don't really need to see them here. with warnings.catch_warnings(): warnings.simplefilter("ignore") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prime_queue(self, init_points): """Make sure there's something in the queue at the very beginning."""
if self._queue.empty and self._space.empty: init_points = max(init_points, 1) for _ in range(init_points): self._queue.add(self._space.random_sample())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maximize(self, init_points=5, n_iter=25, acq='ucb', kappa=2.576, xi=0.0, **gp_params): """Mazimize your function"""
self._prime_subscriptions() self.dispatch(Events.OPTMIZATION_START) self._prime_queue(init_points) self.set_gp_params(**gp_params) util = UtilityFunction(kind=acq, kappa=kappa, xi=xi) iteration = 0 while not self._queue.empty or iteration < n_iter: 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 register(self, params, target): """ Append a point and its target value to the known data. Parameters x : ndarray a single point, with len(x) == self.dim y :...
x = self._as_array(params) if x in self: raise KeyError('Data point {} is not unique'.format(x)) # Insert data into unique dictionary self._cache[_hashable(x.ravel())] = target self._params = np.concatenate([self._params, x.reshape(1, -1)]) self._target = 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 probe(self, params): """ Evaulates a single point x, to obtain the value y and then records them as observations. Notes ----- If x has been previously seen r...
x = self._as_array(params) try: target = self._cache[_hashable(x)] except KeyError: params = dict(zip(self._keys, x)) target = self.target_func(**params) self.register(x, target) return target
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def random_sample(self): """ Creates random points within the bounds of the space. Returns data: ndarray [num x dim] array points with dimensions corresponding t...
# TODO: support integer, category, and basic scipy.optimize constraints data = np.empty((1, self.dim)) for col, (lower, upper) in enumerate(self._bounds): data.T[col] = self.random_state.uniform(lower, upper, size=1) return data.ravel()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max(self): """Get maximum target value found and corresponding parametes."""
try: res = { 'target': self.target.max(), 'params': dict( zip(self.keys, self.params[self.target.argmax()]) ) } except ValueError: res = {} return res