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 execute_partitioned_dml(self, dml, params=None, param_types=None): """Execute a partitionable DML statement. :type dml: str :param dml: DML statement :type p...
if params is not None: if param_types is None: raise ValueError("Specify 'param_types' when passing 'params'.") params_pb = Struct( fields={key: _make_value_pb(value) for key, value in params.items()} ) else: params_pb = No...
<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_in_transaction(self, func, *args, **kw): """Perform a unit of work in a transaction, retrying on abort. :type func: callable :param func: takes a require...
# Sanity check: Is there a transaction already running? # If there is, then raise a red flag. Otherwise, mark that this one # is running. if getattr(self._local, "transaction_running", False): raise RuntimeError("Spanner does not support nested transactions.") 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 from_dict(cls, database, mapping): """Reconstruct an instance from a mapping. :type database: :class:`~google.cloud.spanner.database.Database` :param databas...
instance = cls(database) session = instance._session = database.session() session._session_id = mapping["session_id"] snapshot = instance._snapshot = session.snapshot() snapshot._transaction_id = mapping["transaction_id"] return instance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self): """Return state as a dictionary. Result can be used to serialize the instance and reconstitute it later using :meth:`from_dict`. :rtype: dict ...
session = self._get_session() snapshot = self._get_snapshot() return { "session_id": session._session_id, "transaction_id": snapshot._transaction_id, }
<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_session(self): """Create session as needed. .. note:: Caller is responsible for cleaning up the session after all partitions have been processed. """
if self._session is None: session = self._session = self._database.session() session.create() return self._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 _get_snapshot(self): """Create snapshot if needed."""
if self._snapshot is None: self._snapshot = self._get_session().snapshot( read_timestamp=self._read_timestamp, exact_staleness=self._exact_staleness, multi_use=True, ) self._snapshot.begin() return self._snapshot
<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_read_batches( self, table, columns, keyset, index="", partition_size_bytes=None, max_partitions=None, ): """Start a partitioned batch read operation...
partitions = self._get_snapshot().partition_read( table=table, columns=columns, keyset=keyset, index=index, partition_size_bytes=partition_size_bytes, max_partitions=max_partitions, ) read_info = { "table": tab...
<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_read_batch(self, batch): """Process a single, partitioned read. :type batch: mapping :param batch: one of the mappings returned from an earlier call ...
kwargs = copy.deepcopy(batch["read"]) keyset_dict = kwargs.pop("keyset") kwargs["keyset"] = KeySet._from_dict(keyset_dict) return self._get_snapshot().read(partition=batch["partition"], **kwargs)
<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_query_batches( self, sql, params=None, param_types=None, partition_size_bytes=None, max_partitions=None, ): """Start a partitioned query operation. ...
partitions = self._get_snapshot().partition_query( sql=sql, params=params, param_types=param_types, partition_size_bytes=partition_size_bytes, max_partitions=max_partitions, ) query_info = {"sql": sql} if params: q...
<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(self, batch): """Process a single, partitioned query or read. :type batch: mapping :param batch: one of the mappings returned from an earlier call to...
if "query" in batch: return self.process_query_batch(batch) if "read" in batch: return self.process_read_batch(batch) raise ValueError("Invalid batch")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def location_path(cls, project, location): """Return a fully-qualified location string."""
return google.api_core.path_template.expand( "projects/{project}/locations/{location}", project=project, location=location, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def model_path(cls, project, location, model): """Return a fully-qualified model string."""
return google.api_core.path_template.expand( "projects/{project}/locations/{location}/models/{model}", project=project, location=location, model=model, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def model_evaluation_path(cls, project, location, model, model_evaluation): """Return a fully-qualified model_evaluation string."""
return google.api_core.path_template.expand( "projects/{project}/locations/{location}/models/{model}/modelEvaluations/{model_evaluation}", project=project, location=location, model=model, model_evaluation=model_evaluation, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def annotation_spec_path(cls, project, location, dataset, annotation_spec): """Return a fully-qualified annotation_spec string."""
return google.api_core.path_template.expand( "projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}", project=project, location=location, dataset=dataset, annotation_spec=annotation_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 table_spec_path(cls, project, location, dataset, table_spec): """Return a fully-qualified table_spec string."""
return google.api_core.path_template.expand( "projects/{project}/locations/{location}/datasets/{dataset}/tableSpecs/{table_spec}", project=project, location=location, dataset=dataset, table_spec=table_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 column_spec_path(cls, project, location, dataset, table_spec, column_spec): """Return a fully-qualified column_spec string."""
return google.api_core.path_template.expand( "projects/{project}/locations/{location}/datasets/{dataset}/tableSpecs/{table_spec}/columnSpecs/{column_spec}", project=project, location=location, dataset=dataset, table_spec=table_spec, column...
<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_dataset( self, parent, dataset, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ ...
# Wrap the transport method to add retry and timeout logic. if "create_dataset" not in self._inner_api_calls: self._inner_api_calls[ "create_dataset" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_dataset, 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 delete_dataset( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes a d...
# Wrap the transport method to add retry and timeout logic. if "delete_dataset" not in self._inner_api_calls: self._inner_api_calls[ "delete_dataset" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_dataset, 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 exponential_sleep_generator(initial, maximum, multiplier=_DEFAULT_DELAY_MULTIPLIER): """Generates sleep intervals based on the exponential back-off algorithm...
delay = initial while True: # Introduce jitter by yielding a delay that is uniformly distributed # to average out to the delay time. yield min(random.uniform(0.0, delay * 2.0), maximum) delay = delay * multiplier
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retry_target(target, predicate, sleep_generator, deadline, on_error=None): """Call a function and retry if it fails. This is the lowest-level retry helper. G...
if deadline is not None: deadline_datetime = datetime_helpers.utcnow() + datetime.timedelta( seconds=deadline ) else: deadline_datetime = None last_exc = None for sleep in sleep_generator: try: return target() # pylint: disable=broad-ex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self): """Opens the stream."""
if self.is_active: raise ValueError("Can not open an already open stream.") request_generator = _RequestQueueGenerator( self._request_queue, initial_request=self._initial_request ) call = self._start_rpc(iter(request_generator), metadata=self._rpc_metadata) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self, request): """Queue a message to be sent on the stream. Send is non-blocking. If the underlying RPC has been closed, this will raise. Args: request...
if self.call is None: raise ValueError("Can not send() on an RPC that has never been open()ed.") # Don't use self.is_active(), as ResumableBidiRpc will overload it # to mean something semantically different. if self.call.is_active(): self._request_queue.put(requ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _recoverable(self, method, *args, **kwargs): """Wraps a method to recover the stream and retry on error. If a retryable error occurs while making the call, t...
while True: try: return method(*args, **kwargs) except Exception as exc: with self._operational_lock: _LOGGER.debug("Call to retryable %r caused %s.", method, exc) if not self._should_recover(exc): ...
<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(self): """Start the background thread and begin consuming the thread."""
with self._operational_lock: ready = threading.Event() thread = threading.Thread( name=_BIDIRECTIONAL_CONSUMER_NAME, target=self._thread_main, args=(ready,) ) thread.daemon = True thread.start() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self): """Stop consuming the stream and shutdown the background thread."""
with self._operational_lock: self._bidi_rpc.close() if self._thread is not None: # Resume the thread to wake it up in case it is sleeping. self.resume() self._thread.join() self._thread = 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 resume(self): """Resumes the response stream."""
with self._wake: self._paused = False self._wake.notifyAll()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def project_path(cls, user, project): """Return a fully-qualified project string."""
return google.api_core.path_template.expand( "users/{user}/projects/{project}", user=user, project=project )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fingerprint_path(cls, user, fingerprint): """Return a fully-qualified fingerprint string."""
return google.api_core.path_template.expand( "users/{user}/sshPublicKeys/{fingerprint}", user=user, fingerprint=fingerprint, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_posix_account( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Delet...
# Wrap the transport method to add retry and timeout logic. if "delete_posix_account" not in self._inner_api_calls: self._inner_api_calls[ "delete_posix_account" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_posix_account,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_ssh_public_key( self, parent, ssh_public_key, project_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.D...
# Wrap the transport method to add retry and timeout logic. if "import_ssh_public_key" not in self._inner_api_calls: self._inner_api_calls[ "import_ssh_public_key" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.import_ssh_public_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 update_ssh_public_key( self, name, ssh_public_key, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DE...
# Wrap the transport method to add retry and timeout logic. if "update_ssh_public_key" not in self._inner_api_calls: self._inner_api_calls[ "update_ssh_public_key" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_ssh_public_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 _gc_rule_from_pb(gc_rule_pb): """Convert a protobuf GC rule to a native object. :type gc_rule_pb: :class:`.table_v2_pb2.GcRule` :param gc_rule_pb: The GC rul...
rule_name = gc_rule_pb.WhichOneof("rule") if rule_name is None: return None if rule_name == "max_num_versions": return MaxVersionsGCRule(gc_rule_pb.max_num_versions) elif rule_name == "max_age": max_age = _helpers._duration_pb_to_timedelta(gc_rule_pb.max_age) return Max...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_pb(self): """Converts the garbage collection rule to a protobuf. :rtype: :class:`.table_v2_pb2.GcRule` :returns: The converted current object. """
max_age = _helpers._timedelta_to_duration_pb(self.max_age) return table_v2_pb2.GcRule(max_age=max_age)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_pb(self): """Converts the union into a single GC rule as a protobuf. :rtype: :class:`.table_v2_pb2.GcRule` :returns: The converted current object. """
union = table_v2_pb2.GcRule.Union(rules=[rule.to_pb() for rule in self.rules]) return table_v2_pb2.GcRule(union=union)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_pb(self): """Converts the intersection into a single GC rule as a protobuf. :rtype: :class:`.table_v2_pb2.GcRule` :returns: The converted current object. ...
intersection = table_v2_pb2.GcRule.Intersection( rules=[rule.to_pb() for rule in self.rules] ) return table_v2_pb2.GcRule(intersection=intersection)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_pb(self): """Converts the column family to a protobuf. :rtype: :class:`.table_v2_pb2.ColumnFamily` :returns: The converted current object. """
if self.gc_rule is None: return table_v2_pb2.ColumnFamily() else: return table_v2_pb2.ColumnFamily(gc_rule=self.gc_rule.to_pb())
<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(self): """Create this column family. For example: .. literalinclude:: snippets_table.py :start-after: [START bigtable_create_column_family] :end-befor...
column_family = self.to_pb() modification = table_admin_v2_pb2.ModifyColumnFamiliesRequest.Modification( id=self.column_family_id, create=column_family ) client = self._table._instance._client # data it contains are the GC rule and the column family ID already ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self): """Delete this column family. For example: .. literalinclude:: snippets_table.py :start-after: [START bigtable_delete_column_family] :end-befor...
modification = table_admin_v2_pb2.ModifyColumnFamiliesRequest.Modification( id=self.column_family_id, drop=True ) client = self._table._instance._client # data it contains are the GC rule and the column family ID already # stored on this instance. client.tab...
<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_wrap_exception(exception): """Wraps a gRPC exception class, if needed."""
if isinstance(exception, grpc.RpcError): return exceptions.from_grpc_error(exception) return exception
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _on_rpc_done(self, future): """Triggered whenever the underlying RPC terminates without recovery. This is typically triggered from one of two threads: the ba...
_LOGGER.info("RPC termination has signaled manager shutdown.") future = _maybe_wrap_exception(future) thread = threading.Thread( name=_RPC_ERROR_THREAD_NAME, target=self.close, kwargs={"reason": future} ) thread.daemon = True thread.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def for_document( cls, document_ref, snapshot_callback, snapshot_class_instance, reference_class_instance, ): """ Creates a watch snapshot listener for a documen...
return cls( document_ref, document_ref._client, { "documents": {"documents": [document_ref._document_path]}, "target_id": WATCH_TARGET_ID, }, document_watch_comparator, snapshot_callback, snapsho...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_snapshot(self, proto): """ Called everytime there is a response from listen. Collect changes and 'push' the changes in a batch to the customer when we rec...
TargetChange = firestore_pb2.TargetChange target_changetype_dispatch = { TargetChange.NO_CHANGE: self._on_snapshot_target_change_no_change, TargetChange.ADD: self._on_snapshot_target_change_add, TargetChange.REMOVE: self._on_snapshot_target_change_remove, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def push(self, read_time, next_resume_token): """ Assembles a new snapshot from the current set of changes and invokes the user's callback. Clears the current ch...
deletes, adds, updates = Watch._extract_changes( self.doc_map, self.change_map, read_time ) updated_tree, updated_map, appliedChanges = self._compute_snapshot( self.doc_tree, self.doc_map, deletes, adds, updates ) if not self.has_pushed or len(appliedCh...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _current_size(self): """ Returns the current count of all documents, including the changes from the current changeMap. """
deletes, adds, _ = Watch._extract_changes(self.doc_map, self.change_map, None) return len(self.doc_map) + len(adds) - len(deletes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reset_docs(self): """ Helper to clear the docs on RESET or filter mismatch. """
_LOGGER.debug("resetting documents") self.change_map.clear() self.resume_token = None # Mark each document as deleted. If documents are not deleted # they will be sent again by the server. for snapshot in self.doc_tree.keys(): name = snapshot.reference._docu...
<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_request( self, method, url, data=None, content_type=None, headers=None, target_object=None, ): """A low level method to send a request to the API. Typi...
headers = headers or {} headers.update(self._EXTRA_HEADERS) headers["Accept-Encoding"] = "gzip" if content_type: headers["Content-Type"] = content_type headers["User-Agent"] = self.USER_AGENT return self._do_request(method, url, headers, data, target_objec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def api_request( self, method, path, query_params=None, data=None, content_type=None, headers=None, api_base_url=None, api_version=None, expect_json=True, _target...
url = self.build_api_url( path=path, query_params=query_params, api_base_url=api_base_url, api_version=api_version, ) # Making the executive decision that any dictionary # data will be sent properly as JSON. if data and isinstance...
<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_label_filter(category, *args, **kwargs): """Construct a filter string to filter on metric or resource labels."""
terms = list(args) for key, value in six.iteritems(kwargs): if value is None: continue suffix = None if key.endswith( ("_prefix", "_suffix", "_greater", "_greaterequal", "_less", "_lessequal") ): key, suffix = key.rsplit("_", 1) if c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_interval(self, end_time, start_time=None): """Copy the query and set the query time interval. Example:: import datetime now = datetime.datetime.utcnow...
new_query = copy.deepcopy(self) new_query._end_time = end_time new_query._start_time = start_time return new_query
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_group(self, group_id): """Copy the query and add filtering by group. Example:: query = query.select_group('1234567') :type group_id: str :param group_...
new_query = copy.deepcopy(self) new_query._filter.group_id = group_id return new_query
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_projects(self, *args): """Copy the query and add filtering by monitored projects. This is only useful if the target project represents a Stackdriver a...
new_query = copy.deepcopy(self) new_query._filter.projects = args return new_query
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_resources(self, *args, **kwargs): """Copy the query and add filtering by resource labels. Examples:: query = query.select_resources(zone='us-central1-...
new_query = copy.deepcopy(self) new_query._filter.select_resources(*args, **kwargs) return new_query
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_metrics(self, *args, **kwargs): """Copy the query and add filtering by metric labels. Examples:: query = query.select_metrics(instance_name='myinstanc...
new_query = copy.deepcopy(self) new_query._filter.select_metrics(*args, **kwargs) return new_query
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def align(self, per_series_aligner, seconds=0, minutes=0, hours=0): """Copy the query and add temporal alignment. If ``per_series_aligner`` is not :data:`Aligner...
new_query = copy.deepcopy(self) new_query._per_series_aligner = per_series_aligner new_query._alignment_period_seconds = seconds + 60 * (minutes + 60 * hours) return new_query
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reduce(self, cross_series_reducer, *group_by_fields): """Copy the query and add cross-series reduction. Cross-series reduction combines time series by aggreg...
new_query = copy.deepcopy(self) new_query._cross_series_reducer = cross_series_reducer new_query._group_by_fields = group_by_fields return new_query
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter(self, headers_only=False, page_size=None): """Yield all time series objects selected by the query. The generator returned iterates over :class:`~google....
if self._end_time is None: raise ValueError("Query time interval not specified.") params = self._build_query_params(headers_only, page_size) for ts in self._client.list_time_series(**params): yield ts
<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_query_params(self, headers_only=False, page_size=None): """Return key-value pairs for the list_time_series API call. :type headers_only: bool :param h...
params = {"name": self._project_path, "filter_": self.filter} params["interval"] = types.TimeInterval() params["interval"].end_time.FromDatetime(self._end_time) if self._start_time: params["interval"].start_time.FromDatetime(self._start_time) if ( 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_properties_from_api_repr(self, resource): """Update specific properties from its API representation."""
self.name = resource.get("name") self.number = resource["projectNumber"] self.labels = resource.get("labels", {}) self.status = resource["lifecycleState"] if "parent" in resource: self.parent = resource["parent"]
<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_meaning(value_pb, is_list=False): """Get the meaning from a protobuf value. :type value_pb: :class:`.entity_pb2.Value` :param value_pb: The protobuf val...
meaning = None if is_list: # An empty list will have no values, hence no shared meaning # set among them. if len(value_pb.array_value.values) == 0: return None # We check among all the meanings, some of which may be None, # the rest which may be enum/int val...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def entity_from_protobuf(pb): """Factory method for creating an entity based on a protobuf. The protobuf should be one returned from the Cloud Datastore Protobuf...
key = None if pb.HasField("key"): # Message field (Key) key = key_from_protobuf(pb.key) entity_props = {} entity_meanings = {} exclude_from_indexes = [] for prop_name, value_pb in _property_tuples(pb): value = _get_value_from_value_pb(value_pb) entity_props[prop_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 entity_to_protobuf(entity): """Converts an entity into a protobuf. :type entity: :class:`google.cloud.datastore.entity.Entity` :param entity: The entity to b...
entity_pb = entity_pb2.Entity() if entity.key is not None: key_pb = entity.key.to_protobuf() entity_pb.key.CopyFrom(key_pb) for name, value in entity.items(): value_is_list = isinstance(value, list) value_pb = _new_value_pb(entity_pb, name) # Set the appropriate va...
<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_read_options(eventual, transaction_id): """Validate rules for read options, and assign to the request. Helper method for ``lookup()`` and ``run_query``. ...
if transaction_id is None: if eventual: return datastore_pb2.ReadOptions( read_consistency=datastore_pb2.ReadOptions.EVENTUAL ) else: return datastore_pb2.ReadOptions() else: if eventual: raise ValueError("eventual must be ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def key_from_protobuf(pb): """Factory method for creating a key based on a protobuf. The protobuf should be one returned from the Cloud Datastore Protobuf API. :...
path_args = [] for element in pb.path: path_args.append(element.kind) if element.id: # Simple field (int64) path_args.append(element.id) # This is safe: we expect proto objects returned will only have # one of `name` or `id` set. if element.name: # Simple f...
<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_attr_value(val): """Given a value, return the protobuf attribute name and proper value. The Protobuf API uses different attribute names based on value ty...
if isinstance(val, datetime.datetime): name = "timestamp" value = _datetime_to_pb_timestamp(val) elif isinstance(val, Key): name, value = "key", val.to_protobuf() elif isinstance(val, bool): name, value = "boolean", val elif isinstance(val, float): name, value =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_value_from_value_pb(value_pb): """Given a protobuf for a Value, get the correct value. The Cloud Datastore Protobuf API returns a Property Protobuf whic...
value_type = value_pb.WhichOneof("value_type") if value_type == "timestamp_value": result = _pb_timestamp_to_datetime(value_pb.timestamp_value) elif value_type == "key_value": result = key_from_protobuf(value_pb.key_value) elif value_type == "boolean_value": result = value_pb...
<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_protobuf_value(value_pb, val): """Assign 'val' to the correct subfield of 'value_pb'. The Protobuf API uses different attribute names based on value typ...
attr, val = _pb_attr_value(val) if attr == "key_value": value_pb.key_value.CopyFrom(val) elif attr == "timestamp_value": value_pb.timestamp_value.CopyFrom(val) elif attr == "entity_value": entity_pb = entity_to_protobuf(val) value_pb.entity_value.CopyFrom(entity_pb) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def TimeFromTicks(ticks, tz=None): """Construct a DB-API time value from the given ticks value. :type ticks: float :param ticks: a number of seconds since the ep...
dt = datetime.datetime.fromtimestamp(ticks, tz=tz) return dt.timetz()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def registry_path(cls, project, location, registry): """Return a fully-qualified registry string."""
return google.api_core.path_template.expand( "projects/{project}/locations/{location}/registries/{registry}", project=project, location=location, registry=registry, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def device_path(cls, project, location, registry, device): """Return a fully-qualified device string."""
return google.api_core.path_template.expand( "projects/{project}/locations/{location}/registries/{registry}/devices/{device}", project=project, location=location, registry=registry, device=device, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_device( self, parent, device, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Cr...
# Wrap the transport method to add retry and timeout logic. if "create_device" not in self._inner_api_calls: self._inner_api_calls[ "create_device" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_device, defa...
<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_iam_policy( self, resource, policy, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """...
# Wrap the transport method to add retry and timeout logic. if "set_iam_policy" not in self._inner_api_calls: self._inner_api_calls[ "set_iam_policy" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.set_iam_policy, 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 bind_device_to_gateway( self, parent, gateway_id, device_id, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, m...
# Wrap the transport method to add retry and timeout logic. if "bind_device_to_gateway" not in self._inner_api_calls: self._inner_api_calls[ "bind_device_to_gateway" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.bind_device_to_ga...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def queue_path(cls, project, location, queue): """Return a fully-qualified queue string."""
return google.api_core.path_template.expand( "projects/{project}/locations/{location}/queues/{queue}", project=project, location=location, queue=queue, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def task_path(cls, project, location, queue, task): """Return a fully-qualified task string."""
return google.api_core.path_template.expand( "projects/{project}/locations/{location}/queues/{queue}/tasks/{task}", project=project, location=location, queue=queue, task=task, )
<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_queue( self, parent, queue, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Crea...
# Wrap the transport method to add retry and timeout logic. if "create_queue" not in self._inner_api_calls: self._inner_api_calls[ "create_queue" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_queue, default...
<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_task( self, parent, task, response_view=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=...
# Wrap the transport method to add retry and timeout logic. if "create_task" not in self._inner_api_calls: self._inner_api_calls[ "create_task" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_task, default_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 _exponential_timeout_generator(initial, maximum, multiplier, deadline): """A generator that yields exponential timeout values. Args: initial (float): The in...
if deadline is not None: deadline_datetime = datetime_helpers.utcnow() + datetime.timedelta( seconds=deadline ) else: deadline_datetime = datetime.datetime.max timeout = initial while True: now = datetime_helpers.utcnow() yield min( # 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 _format_operation(operation, parameters=None): """Formats parameters in operation in way BigQuery expects. :type: str :param operation: A Google BigQuery que...
if parameters is None: return operation if isinstance(parameters, collections_abc.Mapping): return _format_operation_dict(operation, parameters) return _format_operation_list(operation, parameters)
<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_description(self, schema): """Set description from schema. :type schema: Sequence[google.cloud.bigquery.schema.SchemaField] :param schema: A description...
if schema is None: self.description = None return self.description = tuple( [ Column( name=field.name, type_code=field.field_type, display_size=None, internal_size=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 _set_rowcount(self, query_results): """Set the rowcount from query results. Normally, this sets rowcount to the number of rows returned by the query, but if ...
total_rows = 0 num_dml_affected_rows = query_results.num_dml_affected_rows if query_results.total_rows is not None and query_results.total_rows > 0: total_rows = query_results.total_rows if num_dml_affected_rows is not None and num_dml_affected_rows > 0: total_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 execute(self, operation, parameters=None, job_id=None): """Prepare and execute a database operation. .. note:: When setting query parameters, values which ar...
self._query_data = None self._query_job = None client = self.connection._client # The DB-API uses the pyformat formatting, since the way BigQuery does # query parameters was not one of the standard options. Convert both # the query and the parameters to the format expec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _try_fetch(self, size=None): """Try to start fetching data, if not yet started. Mutates self to indicate that iteration has started. """
if self._query_job is None: raise exceptions.InterfaceError( "No query results: execute() must be called before fetch." ) is_dml = ( self._query_job.statement_type and self._query_job.statement_type.upper() != "SELECT" ) 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 _update_from_api_repr(self, resource): """Helper for API methods returning sink resources."""
self.destination = resource["destination"] self.filter_ = resource.get("filter") self._writer_identity = resource.get("writerIdentity")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _merge_by_type(lhs, rhs, type_): """Helper for '_merge_chunk'."""
merger = _MERGE_BY_TYPE[type_.code] return merger(lhs, rhs, 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 _merge_chunk(self, value): """Merge pending chunk with next value. :type value: :class:`~google.protobuf.struct_pb2.Value` :param value: continuation of chun...
current_column = len(self._current_row) field = self.fields[current_column] merged = _merge_by_type(self._pending_chunk, value, field.type) self._pending_chunk = None return merged
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _merge_values(self, values): """Merge values into rows. :type values: list of :class:`~google.protobuf.struct_pb2.Value` :param values: non-chunked values fr...
width = len(self.fields) for value in values: index = len(self._current_row) field = self.fields[index] self._current_row.append(_parse_value_pb(value, field.type)) if len(self._current_row) == width: self._rows.append(self._current_row) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _consume_next(self): """Consume the next partial result set from the stream. Parse the result set into new/existing rows in :attr:`_rows` """
response = six.next(self._response_iterator) self._counter += 1 if self._metadata is None: # first response metadata = self._metadata = response.metadata source = self._source if source is not None and source._transaction_id is None: source...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def one_or_none(self): """Return exactly one result, or None if there are no results. :raises: :exc:`ValueError`: If there are multiple results. :raises: :exc:`R...
# Sanity check: Has consumption of this query already started? # If it has, then this is an exception. if self._metadata is not None: raise RuntimeError( "Can not call `.one` or `.one_or_none` after " "stream consumption has already started." ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def product_set_path(cls, project, location, product_set): """Return a fully-qualified product_set string."""
return google.api_core.path_template.expand( "projects/{project}/locations/{location}/productSets/{product_set}", project=project, location=location, product_set=product_set, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def product_path(cls, project, location, product): """Return a fully-qualified product string."""
return google.api_core.path_template.expand( "projects/{project}/locations/{location}/products/{product}", project=project, location=location, product=product, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reference_image_path(cls, project, location, product, reference_image): """Return a fully-qualified reference_image string."""
return google.api_core.path_template.expand( "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}", project=project, location=location, product=product, reference_image=reference_image, )
<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_product_set( self, parent, product_set, product_set_id, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT,...
# Wrap the transport method to add retry and timeout logic. if "create_product_set" not in self._inner_api_calls: self._inner_api_calls[ "create_product_set" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_product_set, ...
<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_reference_image( self, parent, reference_image, reference_image_id, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.met...
# Wrap the transport method to add retry and timeout logic. if "create_reference_image" not in self._inner_api_calls: self._inner_api_calls[ "create_reference_image" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_reference_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_product_sets( self, parent, input_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None...
# Wrap the transport method to add retry and timeout logic. if "import_product_sets" not in self._inner_api_calls: self._inner_api_calls[ "import_product_sets" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.import_product_sets, ...
<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_log_entry(entry_pb): """Special helper to parse ``LogEntry`` protobuf into a dictionary. The ``proto_payload`` field in ``LogEntry`` is of type ``Any`...
try: return MessageToDict(entry_pb) except TypeError: if entry_pb.HasField("proto_payload"): proto_payload = entry_pb.proto_payload entry_pb.ClearField("proto_payload") entry_mapping = MessageToDict(entry_pb) entry_mapping["protoPayload"] = 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 _item_to_entry(iterator, entry_pb, loggers): """Convert a log entry protobuf to the native object. .. note:: This method does not have the correct signature ...
resource = _parse_log_entry(entry_pb) return entry_from_resource(resource, iterator.client, loggers)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _item_to_sink(iterator, log_sink_pb): """Convert a sink protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :para...
# NOTE: LogSink message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. resource = MessageToDict(log_sink_pb) return Sink.from_api_repr(resource, iterator.client)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _item_to_metric(iterator, log_metric_pb): """Convert a metric protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator`...
# NOTE: LogMetric message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. resource = MessageToDict(log_metric_pb) return Metric.from_api_repr(resource, iterator.client)
<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_logging_api(client): """Create an instance of the Logging API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The cli...
generated = LoggingServiceV2Client( credentials=client._credentials, client_info=_CLIENT_INFO ) return _LoggingAPI(generated, client)
<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_metrics_api(client): """Create an instance of the Metrics API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The cli...
generated = MetricsServiceV2Client( credentials=client._credentials, client_info=_CLIENT_INFO ) return _MetricsAPI(generated, client)