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 run(self):
"""Run a single thread of the workload.""" |
i = 0
operation_count = int(self._parameters['operationcount'])
while i < operation_count:
i += 1
weight = random.uniform(0, self._total_weight)
for j in range(len(self._weights)):
if weight <= self._weights[j]:
do_operatio... |
<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_methods(source_class, blacklist=()):
"""Add wrapped versions of the `api` member's methods to the class. Any methods passed in `blacklist` are not added.... |
def wrap(wrapped_fx):
"""Wrap a GAPIC method; preserve its name and docstring."""
# If this is a static or class method, then we need to *not*
# send self as the first argument.
#
# Similarly, for instance methods, we need to send self.api rather
# than self, since ... |
<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( self, parent, product, product_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metada... |
# Wrap the transport method to add retry and timeout logic.
if "create_product" not in self._inner_api_calls:
self._inner_api_calls[
"create_product"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_product,
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 update_product( self, product, update_mask=None, 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 "update_product" not in self._inner_api_calls:
self._inner_api_calls[
"update_product"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.update_product,
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 _assign_entity_to_pb(entity_pb, entity):
"""Copy ``entity`` into ``entity_pb``. Helper method for ``Batch.put``. :type entity_pb: :class:`.entity_pb2.Entity`... |
bare_entity_pb = helpers.entity_to_protobuf(entity)
bare_entity_pb.key.CopyFrom(bare_entity_pb.key)
entity_pb.CopyFrom(bare_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 _parse_commit_response(commit_response_pb):
"""Extract response data from a commit response. :type commit_response_pb: :class:`.datastore_pb2.CommitResponse`... |
mut_results = commit_response_pb.mutation_results
index_updates = commit_response_pb.index_updates
completed_keys = [
mut_result.key for mut_result in mut_results if mut_result.HasField("key")
] # Message field (Key)
return index_updates, completed_keys |
<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_partial_key_entity_pb(self):
"""Adds a new mutation for an entity with a partial key. :rtype: :class:`.entity_pb2.Entity` :returns: The newly created en... |
new_mutation = _datastore_pb2.Mutation()
self._mutations.append(new_mutation)
return new_mutation.insert |
<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_complete_key_entity_pb(self):
"""Adds a new mutation for an entity with a completed key. :rtype: :class:`.entity_pb2.Entity` :returns: The newly created... |
# We use ``upsert`` for entities with completed keys, rather than
# ``insert`` or ``update``, in order not to create race conditions
# based on prior existence / removal of the entity.
new_mutation = _datastore_pb2.Mutation()
self._mutations.append(new_mutation)
return n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_delete_key_pb(self):
"""Adds a new mutation for a key to be deleted. :rtype: :class:`.entity_pb2.Key` :returns: The newly created key protobuf that will... |
new_mutation = _datastore_pb2.Mutation()
self._mutations.append(new_mutation)
return new_mutation.delete |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rollback(self):
"""Rolls back the current batch. Marks the batch as aborted (can't be used again). Overridden by :class:`google.cloud.datastore.transaction.T... |
if self._status != self._IN_PROGRESS:
raise ValueError("Batch must be in progress to rollback()")
self._status = self._ABORTED |
<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_table( self, parent, table_id, table, initial_splits=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAU... |
# Wrap the transport method to add retry and timeout logic.
if "create_table" not in self._inner_api_calls:
self._inner_api_calls[
"create_table"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_table,
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_table_from_snapshot( self, parent, table_id, source_snapshot, 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 "create_table_from_snapshot" not in self._inner_api_calls:
self._inner_api_calls[
"create_table_from_snapshot"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_ta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def snapshot_table( self, name, cluster, snapshot_id, description, ttl=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.metho... |
# Wrap the transport method to add retry and timeout logic.
if "snapshot_table" not in self._inner_api_calls:
self._inner_api_calls[
"snapshot_table"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.snapshot_table,
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 company_path(cls, project, company):
"""Return a fully-qualified company string.""" |
return google.api_core.path_template.expand(
"projects/{project}/companies/{company}", project=project, company=company
) |
<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_company( self, parent, company, 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_company" not in self._inner_api_calls:
self._inner_api_calls[
"create_company"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_company,
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 update_company( self, company, update_mask=None, 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 "update_company" not in self._inner_api_calls:
self._inner_api_calls[
"update_company"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.update_company,
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 quotas(self):
"""Return DNS quotas for the project associated with this client. See https://cloud.google.com/dns/api/v1/projects/get :rtype: mapping :returns... |
path = "/projects/%s" % (self.project,)
resp = self._connection.api_request(method="GET", path=path)
return {
key: int(value) for key, value in resp["quota"].items() if key != "kind"
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_zones(self, max_results=None, page_token=None):
"""List zones for the project associated with this client. See https://cloud.google.com/dns/api/v1/manag... |
path = "/projects/%s/managedZones" % (self.project,)
return page_iterator.HTTPIterator(
client=self,
api_request=self._connection.api_request,
path=path,
item_to_value=_item_to_zone,
items_key="managedZones",
page_token=page_token,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zone(self, name, dns_name=None, description=None):
"""Construct a zone bound to this client. :type name: str :param name: Name of the zone. :type dns_name: s... |
return ManagedZone(name, dns_name, client=self, description=description) |
<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_from_query(query):
"""Convert a Query instance to the corresponding protobuf. :type query: :class:`Query` :param query: The source query. :rtype: :class:... |
pb = query_pb2.Query()
for projection_name in query.projection:
pb.projection.add().property.name = projection_name
if query.kind:
pb.kind.add().name = query.kind
composite_filter = pb.filter.composite_filter
composite_filter.op = query_pb2.CompositeFilter.AND
if query.ances... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def namespace(self, value):
"""Update the query's namespace. :type value: str """ |
if not isinstance(value, str):
raise ValueError("Namespace must be a string")
self._namespace = 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 kind(self, value):
"""Update the Kind of the Query. :type value: str :param value: updated kind for the query. .. note:: The protobuf specification allows fo... |
if not isinstance(value, str):
raise TypeError("Kind must be a string")
self._kind = 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 ancestor(self, value):
"""Set the ancestor for the query :type value: :class:`~google.cloud.datastore.key.Key` :param value: the new ancestor key """ |
if not isinstance(value, Key):
raise TypeError("Ancestor must be a Key")
self._ancestor = 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 add_filter(self, property_name, operator, value):
"""Filter the query based on a property name, operator and a value. Expressions take the form of:: .add_fil... |
if self.OPERATORS.get(operator) is None:
error_message = 'Invalid expression: "%s"' % (operator,)
choices_message = "Please use one of: =, <, <=, >, >=."
raise ValueError(error_message, choices_message)
if property_name == "__key__" and not isinstance(value, Key):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def projection(self, projection):
"""Set the fields returned the query. :type projection: str or sequence of strings :param projection: Each value is a string gi... |
if isinstance(projection, str):
projection = [projection]
self._projection[:] = projection |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def order(self, value):
"""Set the fields used to sort query results. Sort fields will be applied in the order specified. :type value: str or sequence of strings... |
if isinstance(value, str):
value = [value]
self._order[:] = 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 distinct_on(self, value):
"""Set fields used to group query results. :type value: str or sequence of strings :param value: Each value is a string giving the ... |
if isinstance(value, str):
value = [value]
self._distinct_on[:] = 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 fetch( self, limit=None, offset=0, start_cursor=None, end_cursor=None, client=None, eventual=False, ):
"""Execute the Query; return an iterator for the match... |
if client is None:
client = self._client
return Iterator(
self,
client,
limit=limit,
offset=offset,
start_cursor=start_cursor,
end_cursor=end_cursor,
eventual=eventual,
) |
<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_protobuf(self):
"""Build a query protobuf. Relies on the current state of the iterator. :rtype: :class:`.query_pb2.Query` :returns: The query protobuf... |
pb = _pb_from_query(self._query)
start_cursor = self.next_page_token
if start_cursor is not None:
pb.start_cursor = base64.urlsafe_b64decode(start_cursor)
end_cursor = self._end_cursor
if end_cursor is not None:
pb.end_cursor = base64.urlsafe_b64decode(... |
<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_query_results(self, response_pb):
"""Process the response from a datastore query. :type response_pb: :class:`.datastore_pb2.RunQueryResponse` :param... |
self._skipped_results = response_pb.batch.skipped_results
if response_pb.batch.more_results == _NO_MORE_RESULTS:
self.next_page_token = None
else:
self.next_page_token = base64.urlsafe_b64encode(
response_pb.batch.end_cursor
)
self._e... |
<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, table, columns, values):
"""Update one or more existing table rows. :type table: str :param table: Name of the table to be modified. :type colum... |
self._mutations.append(Mutation(update=_make_write_pb(table, columns, 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 delete(self, table, keyset):
"""Delete one or more table rows. :type table: str :param table: Name of the table to be modified. :type keyset: :class:`~google... |
delete = Mutation.Delete(table=table, key_set=keyset._to_pb())
self._mutations.append(Mutation(delete=delete)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dataset_exists(client, dataset_reference):
"""Return if a dataset exists. Args: client (google.cloud.bigquery.client.Client):
A client to connect to the Big... |
from google.cloud.exceptions import NotFound
try:
client.get_dataset(dataset_reference)
return True
except NotFound:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def table_exists(client, table_reference):
"""Return if a table exists. Args: client (google.cloud.bigquery.client.Client):
A client to connect to the BigQuery ... |
from google.cloud.exceptions import NotFound
try:
client.get_table(table_reference)
return True
except NotFound:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_query( self, project_id, partition_id, read_options=None, query=None, gql_query=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_co... |
# Wrap the transport method to add retry and timeout logic.
if "run_query" not in self._inner_api_calls:
self._inner_api_calls[
"run_query"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.run_query,
default_retry=se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commit( self, project_id, mode, mutations, transaction=None, 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 "commit" not in self._inner_api_calls:
self._inner_api_calls[
"commit"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.commit,
default_retry=self._metho... |
<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_gae_resource(self):
"""Return the GAE resource using the environment variables. :rtype: :class:`~google.cloud.logging.resource.Resource` :returns: Monito... |
gae_resource = Resource(
type="gae_app",
labels={
"project_id": self.project_id,
"module_id": self.module_id,
"version_id": self.version_id,
},
)
return gae_resource |
<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_gae_labels(self):
"""Return the labels for GAE app. If the trace ID can be detected, it will be included as a label. Currently, no other labels are inclu... |
gae_labels = {}
trace_id = get_trace_id()
if trace_id is not None:
gae_labels[_TRACE_ID_LABEL] = trace_id
return gae_labels |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def service_account_path(cls, project, service_account):
"""Return a fully-qualified service_account string.""" |
return google.api_core.path_template.expand(
"projects/{project}/serviceAccounts/{service_account}",
project=project,
service_account=service_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 generate_access_token( self, name, scope, delegates=None, lifetime=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.metho... |
# Wrap the transport method to add retry and timeout logic.
if "generate_access_token" not in self._inner_api_calls:
self._inner_api_calls[
"generate_access_token"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.generate_access_tok... |
<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_id_token( self, name, audience, delegates=None, include_email=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.m... |
# Wrap the transport method to add retry and timeout logic.
if "generate_id_token" not in self._inner_api_calls:
self._inner_api_calls[
"generate_id_token"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.generate_id_token,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sign_blob( self, name, payload, delegates=None, 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 "sign_blob" not in self._inner_api_calls:
self._inner_api_calls[
"sign_blob"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.sign_blob,
default_retry=se... |
<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_identity_binding_access_token( self, name, scope, jwt, 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 "generate_identity_binding_access_token" not in self._inner_api_calls:
self._inner_api_calls[
"generate_identity_binding_access_token"
] = google.api_core.gapic_v1.method.wrap_method(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def entry_path(cls, project, location, entry_group, entry):
"""Return a fully-qualified entry string.""" |
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}",
project=project,
location=location,
entry_group=entry_group,
entry=entry,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lookup_entry( self, linked_resource=None, sql_resource=None, 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 "lookup_entry" not in self._inner_api_calls:
self._inner_api_calls[
"lookup_entry"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.lookup_entry,
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 _get_document_path(client, path):
"""Convert a path tuple into a full path string. Of the form: documents/{document_path}`` Args: client (~.firestore_v1beta1... |
parts = (client._database_string, "documents") + path
return _helpers.DOCUMENT_PATH_DELIMITER.join(parts) |
<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_single_get(response_iterator):
"""Consume a gRPC stream that should contain a single response. The stream will correspond to a ``BatchGetDocuments``... |
# Calling ``list()`` consumes the entire iterator.
all_responses = list(response_iterator)
if len(all_responses) != 1:
raise ValueError(
"Unexpected response from `BatchGetDocumentsResponse`",
all_responses,
"Expected only one result",
)
return all_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 _document_path(self):
"""Create and cache the full path for this document. Of the form: documents/{document_path}`` Returns: str: The full document path. Rai... |
if self._document_path_internal is None:
if self._client is None:
raise ValueError("A document reference requires a `client`.")
self._document_path_internal = _get_document_path(self._client, self._path)
return self._document_path_internal |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collection(self, collection_id):
"""Create a sub-collection underneath the current document. Args: collection_id (str):
The sub-collection identifier (somet... |
child_path = self._path + (collection_id,)
return self._client.collection(*child_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 create(self, document_data):
"""Create the current document in the Firestore database. Args: document_data (dict):
Property names and values to use for crea... |
batch = self._client.batch()
batch.create(self, document_data)
write_results = batch.commit()
return _first_write_result(write_results) |
<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(self, document_data, merge=False):
"""Replace the current document in the Firestore database. A write ``option`` can be specified to indicate preconditio... |
batch = self._client.batch()
batch.set(self, document_data, merge=merge)
write_results = batch.commit()
return _first_write_result(write_results) |
<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, field_updates, option=None):
"""Update an existing document in the Firestore database. By default, this method verifies that the document exists... |
batch = self._client.batch()
batch.update(self, field_updates, option=option)
write_results = batch.commit()
return _first_write_result(write_results) |
<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, option=None):
"""Delete the current document in the Firestore database. Args: option (Optional[~.firestore_v1beta1.client.WriteOption]):
A writ... |
write_pb = _helpers.pb_for_delete(self._document_path, option)
commit_response = self._client._firestore_api.commit(
self._client._database_string,
[write_pb],
transaction=None,
metadata=self._client._rpc_metadata,
)
return commit_respons... |
<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(self, field_paths=None, transaction=None):
"""Retrieve a snapshot of the current document. See :meth:`~.firestore_v1beta1.client.Client.field_path` for m... |
if isinstance(field_paths, six.string_types):
raise ValueError("'field_paths' must be a sequence of paths, not a string.")
if field_paths is not None:
mask = common_pb2.DocumentMask(field_paths=sorted(field_paths))
else:
mask = None
firestore_api = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collections(self, page_size=None):
"""List subcollections of the current document. Args: page_size (Optional[int]]):
The maximum number of collections in ea... |
iterator = self._client._firestore_api.list_collection_ids(
self._document_path,
page_size=page_size,
metadata=self._client._rpc_metadata,
)
iterator.document = self
iterator.item_to_value = _item_to_collection_ref
return iterator |
<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(self, field_path):
"""Get a value from the snapshot data. If the data is nested, for example: .. code-block:: python { 'top1': { 'middle2': { 'bottom3': ... |
if not self._exists:
return None
nested_data = field_path_module.get_nested_value(field_path, self._data)
return copy.deepcopy(nested_data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def database_path(cls, project, instance, database):
"""Return a fully-qualified database string.""" |
return google.api_core.path_template.expand(
"projects/{project}/instances/{instance}/databases/{database}",
project=project,
instance=instance,
database=database,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_instances(self):
"""List instances owned by the project. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_instances] :end... |
resp = self.instance_admin_client.list_instances(self.project_path)
instances = [Instance.from_pb(instance, self) for instance in resp.instances]
return instances, resp.failed_locations |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_clusters(self):
"""List the clusters in the project. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_clusters_in_project... |
resp = self.instance_admin_client.list_clusters(
self.instance_admin_client.instance_path(self.project, "-")
)
clusters = []
instances = {}
for cluster in resp.clusters:
match_cluster_name = _CLUSTER_NAME_RE.match(cluster.name)
instance_id = 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 list_clusters( self, project_id, zone, parent=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=N... |
# Wrap the transport method to add retry and timeout logic.
if "list_clusters" not in self._inner_api_calls:
self._inner_api_calls[
"list_clusters"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.list_clusters,
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 get_cluster( self, project_id, zone, cluster_id, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, me... |
# Wrap the transport method to add retry and timeout logic.
if "get_cluster" not in self._inner_api_calls:
self._inner_api_calls[
"get_cluster"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.get_cluster,
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 set_labels( self, project_id, zone, cluster_id, resource_labels, label_fingerprint, name=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.a... |
# Wrap the transport method to add retry and timeout logic.
if "set_labels" not in self._inner_api_calls:
self._inner_api_calls[
"set_labels"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.set_labels,
default_retry... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def metric_path(cls, project, metric):
"""Return a fully-qualified metric string.""" |
return google.api_core.path_template.expand(
"projects/{project}/metrics/{metric}", project=project, metric=metric
) |
<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_log_metric( self, metric_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ):
""" Gets... |
# Wrap the transport method to add retry and timeout logic.
if "get_log_metric" not in self._inner_api_calls:
self._inner_api_calls[
"get_log_metric"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.get_log_metric,
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 metric_descriptor_path(cls, project, metric_descriptor):
"""Return a fully-qualified metric_descriptor string.""" |
return google.api_core.path_template.expand(
"projects/{project}/metricDescriptors/{metric_descriptor=**}",
project=project,
metric_descriptor=metric_descriptor,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def monitored_resource_descriptor_path(cls, project, monitored_resource_descriptor):
"""Return a fully-qualified monitored_resource_descriptor string.""" |
return google.api_core.path_template.expand(
"projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}",
project=project,
monitored_resource_descriptor=monitored_resource_descriptor,
) |
<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):
"""Construct a KeyRange protobuf. :rtype: :class:`~google.cloud.spanner_v1.proto.keys_pb2.KeyRange` :returns: protobuf corresponding to this in... |
kwargs = {}
if self.start_open is not None:
kwargs["start_open"] = _make_list_value_pb(self.start_open)
if self.start_closed is not None:
kwargs["start_closed"] = _make_list_value_pb(self.start_closed)
if self.end_open is not None:
kwargs["end_open... |
<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 keyrange's state as a dict. :rtype: dict :returns: state of this instance. """ |
mapping = {}
if self.start_open:
mapping["start_open"] = self.start_open
if self.start_closed:
mapping["start_closed"] = self.start_closed
if self.end_open:
mapping["end_open"] = self.end_open
if self.end_closed:
mapping["end_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 _to_pb(self):
"""Construct a KeySet protobuf. :rtype: :class:`~google.cloud.spanner_v1.proto.keys_pb2.KeySet` :returns: protobuf corresponding to this instan... |
if self.all_:
return KeySetPB(all=True)
kwargs = {}
if self.keys:
kwargs["keys"] = _make_list_value_pbs(self.keys)
if self.ranges:
kwargs["ranges"] = [krange._to_pb() for krange in self.ranges]
return KeySetPB(**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 _to_dict(self):
"""Return keyset's state as a dict. The result can be used to serialize the instance and reconstitute it later using :meth:`_from_dict`. :rty... |
if self.all_:
return {"all": True}
return {
"keys": self.keys,
"ranges": [keyrange._to_dict() for keyrange in self.ranges],
} |
<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, mapping):
"""Create an instance from the corresponding state mapping. :type mapping: dict :param mapping: the instance state. """ |
if mapping.get("all"):
return cls(all_=True)
r_mappings = mapping.get("ranges", ())
ranges = [KeyRange(**r_mapping) for r_mapping in r_mappings]
return cls(keys=mapping.get("keys", ()), ranges=ranges) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _wrap_unary_errors(callable_):
"""Map errors for Unary-Unary and Stream-Unary gRPC callables.""" |
_patch_callable_name(callable_)
@six.wraps(callable_)
def error_remapped_callable(*args, **kwargs):
try:
return callable_(*args, **kwargs)
except grpc.RpcError as exc:
six.raise_from(exceptions.from_grpc_error(exc), exc)
return error_remapped_callable |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _wrap_stream_errors(callable_):
"""Wrap errors for Unary-Stream and Stream-Stream gRPC callables. The callables that return iterators require a bit more logi... |
_patch_callable_name(callable_)
@general_helpers.wraps(callable_)
def error_remapped_callable(*args, **kwargs):
try:
result = callable_(*args, **kwargs)
return _StreamingResponseIterator(result)
except grpc.RpcError as exc:
six.raise_from(exceptions.from... |
<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_channel( target, credentials=None, scopes=None, ssl_credentials=None, **kwargs ):
"""Create a secure channel with credentials. Args: target (str):
Th... |
if credentials is None:
credentials, _ = google.auth.default(scopes=scopes)
else:
credentials = google.auth.credentials.with_scopes_if_required(
credentials, scopes
)
request = google.auth.transport.requests.Request()
# Create the metadata plugin for inserting 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 next(self):
"""Get the next response from the stream. Returns: protobuf.Message: A single response from the stream. """ |
try:
return six.next(self._wrapped)
except grpc.RpcError as exc:
six.raise_from(exceptions.from_grpc_error(exc), 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 wraps(wrapped):
"""A functools.wraps helper that handles partial objects on Python 2.""" |
if isinstance(wrapped, functools.partial):
return six.wraps(wrapped, assigned=_PARTIAL_VALID_ASSIGNMENTS)
else:
return six.wraps(wrapped) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _determine_default_project(project=None):
"""Determine default project explicitly or implicitly as fall-back. In implicit case, supports four environments. I... |
if project is None:
project = _get_gcd_project()
if project is None:
project = _base_default_project(project=project)
return 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 _datastore_api(self):
"""Getter for a wrapped API object.""" |
if self._datastore_api_internal is None:
if self._use_grpc:
self._datastore_api_internal = make_datastore_api(self)
else:
self._datastore_api_internal = HTTPDatastoreAPI(self)
return self._datastore_api_internal |
<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_multi( self, keys, missing=None, deferred=None, transaction=None, eventual=False ):
"""Retrieve entities, along with their attributes. :type keys: list o... |
if not keys:
return []
ids = set(key.project for key in keys)
for current_id in ids:
if current_id != self.project:
raise ValueError("Keys do not match project")
if transaction is None:
transaction = self.current_transaction
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put_multi(self, entities):
"""Save entities in the Cloud Datastore. :type entities: list of :class:`google.cloud.datastore.entity.Entity` :param entities: Th... |
if isinstance(entities, Entity):
raise ValueError("Pass a sequence of entities")
if not entities:
return
current = self.current_batch
in_batch = current is not None
if not in_batch:
current = self.batch()
current.begin()
... |
<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_multi(self, keys):
"""Delete keys from the Cloud Datastore. :type keys: list of :class:`google.cloud.datastore.key.Key` :param keys: The keys to be de... |
if not keys:
return
# We allow partial keys to attempt a delete, the backend will fail.
current = self.current_batch
in_batch = current is not None
if not in_batch:
current = self.batch()
current.begin()
for key in keys:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def allocate_ids(self, incomplete_key, num_ids):
"""Allocate a list of IDs from a partial key. :type incomplete_key: :class:`google.cloud.datastore.key.Key` :par... |
if not incomplete_key.is_partial:
raise ValueError(("Key is not partial.", incomplete_key))
incomplete_key_pb = incomplete_key.to_protobuf()
incomplete_key_pbs = [incomplete_key_pb] * num_ids
response_pb = self._datastore_api.allocate_ids(
incomplete_key.projec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mutate(self, row):
""" Add a row to the batch. If the current batch meets one of the size limits, the batch is sent synchronously. For example: .. literalinc... |
mutation_count = len(row._get_mutations())
if mutation_count > MAX_MUTATIONS:
raise MaxMutationsError(
"The row key {} exceeds the number of mutations {}.".format(
row.row_key, mutation_count
)
)
if (self.total_mutatio... |
<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_topic_path(topic_path):
"""Verify that a topic path is in the correct format. .. _resource manager docs: https://cloud.google.com/resource-manager/\ r... |
match = _TOPIC_REF_RE.match(topic_path)
if match is None:
raise ValueError(_BAD_TOPIC.format(topic_path))
return match.group("name"), match.group("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 from_api_repr(cls, resource, bucket):
"""Construct an instance from the JSON repr returned by the server. See: https://cloud.google.com/storage/docs/json_api... |
topic_path = resource.get("topic")
if topic_path is None:
raise ValueError("Resource has no topic")
name, project = _parse_topic_path(topic_path)
instance = cls(bucket, name, topic_project=project)
instance._properties = resource
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 exists(self, client=None):
"""Test whether this notification exists. See: https://cloud.google.com/storage/docs/json_api/v1/notifications/get If :attr:`user_... |
if self.notification_id is None:
raise ValueError("Notification not intialized by server")
client = self._require_client(client)
query_params = {}
if self.bucket.user_project is not None:
query_params["userProject"] = self.bucket.user_project
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reload(self, client=None):
"""Update this notification from the server configuration. See: https://cloud.google.com/storage/docs/json_api/v1/notifications/ge... |
if self.notification_id is None:
raise ValueError("Notification not intialized by server")
client = self._require_client(client)
query_params = {}
if self.bucket.user_project is not None:
query_params["userProject"] = self.bucket.user_project
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 delete(self, client=None):
"""Delete this notification. See: https://cloud.google.com/storage/docs/json_api/v1/notifications/delete If :attr:`user_project` i... |
if self.notification_id is None:
raise ValueError("Notification not intialized by server")
client = self._require_client(client)
query_params = {}
if self.bucket.user_project is not None:
query_params["userProject"] = self.bucket.user_project
client._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 create_instance( self, parent, instance_id, instance, 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_instance" not in self._inner_api_calls:
self._inner_api_calls[
"create_instance"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_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 import_instance( self, name, 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_instance" not in self._inner_api_calls:
self._inner_api_calls[
"import_instance"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.import_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 notification_channel_path(cls, project, notification_channel):
"""Return a fully-qualified notification_channel string.""" |
return google.api_core.path_template.expand(
"projects/{project}/notificationChannels/{notification_channel}",
project=project,
notification_channel=notification_channel,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def notification_channel_descriptor_path(cls, project, channel_descriptor):
"""Return a fully-qualified notification_channel_descriptor string.""" |
return google.api_core.path_template.expand(
"projects/{project}/notificationChannelDescriptors/{channel_descriptor}",
project=project,
channel_descriptor=channel_descriptor,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def batch(self, client=None):
"""Return a batch to use as a context manager. :type client: :class:`~google.cloud.logging.client.Client` or ``NoneType`` :param cl... |
client = self._require_client(client)
return Batch(self, 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 commit(self, client=None):
"""Send saved log entries as a single API call. :type client: :class:`~google.cloud.logging.client.Client` or ``NoneType`` :param ... |
if client is None:
client = self.client
kwargs = {"logger_name": self.logger.full_name}
if self.resource is not None:
kwargs["resource"] = self.resource._to_dict()
if self.logger.labels is not None:
kwargs["labels"] = self.logger.labels
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 _bytes_from_json(value, field):
"""Base64-decode value""" |
if _not_null(value, field):
return base64.standard_b64decode(_to_bytes(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 _time_from_json(value, field):
"""Coerce 'value' to a datetime date, if set or not nullable""" |
if _not_null(value, field):
if len(value) == 8: # HH:MM:SS
fmt = _TIMEONLY_WO_MICROS
elif len(value) == 15: # HH:MM:SS.micros
fmt = _TIMEONLY_W_MICROS
else:
raise ValueError("Unknown time format: {}".format(value))
return datetime.datetime.strpt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _record_from_json(value, field):
"""Coerce 'value' to a mapping, if set or not nullable.""" |
if _not_null(value, field):
record = {}
record_iter = zip(field.fields, value["f"])
for subfield, cell in record_iter:
converter = _CELLDATA_FROM_JSON[subfield.field_type]
if subfield.mode == "REPEATED":
value = [converter(item["v"], subfield) for ite... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _row_tuple_from_json(row, schema):
"""Convert JSON row data to row with appropriate types. Note: ``row['f']`` and ``schema`` are presumed to be of the same l... |
row_data = []
for field, cell in zip(schema, row["f"]):
converter = _CELLDATA_FROM_JSON[field.field_type]
if field.mode == "REPEATED":
row_data.append([converter(item["v"], field) for item in cell["v"]])
else:
row_data.append(converter(cell["v"], field))
ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _rows_from_json(values, schema):
"""Convert JSON row data to rows with appropriate types.""" |
from google.cloud.bigquery import Row
field_to_index = _field_to_index_mapping(schema)
return [Row(_row_tuple_from_json(r, schema), field_to_index) for r in 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 _decimal_to_json(value):
"""Coerce 'value' to a JSON-compatible representation.""" |
if isinstance(value, decimal.Decimal):
value = str(value)
return value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.