Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def table_data_client(self):
if self._table_data_client is None:
self._table_data_client = _create_gapic_client(bigtable_v2.BigtableClient)(
self
)
return self._table_data_client | [
"Getter for the gRPC stub used for the Table Admin API.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_table_data_client]\n :end-before: [END bigtable_table_data_client]\n\n :rtype: :class:`.bigtable_v2.BigtableClient`\n :return... |
Please provide a description of the function:def table_admin_client(self):
if self._table_admin_client is None:
if not self._admin:
raise ValueError("Client is not an admin client.")
self._table_admin_client = _create_gapic_client(
bigtable_admin_... | [
"Getter for the gRPC stub used for the Table Admin API.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_table_admin_client]\n :end-before: [END bigtable_table_admin_client]\n\n :rtype: :class:`.bigtable_admin_pb2.BigtableTableAdmin`\n ... |
Please provide a description of the function:def instance_admin_client(self):
if self._instance_admin_client is None:
if not self._admin:
raise ValueError("Client is not an admin client.")
self._instance_admin_client = _create_gapic_client(
bigtab... | [
"Getter for the gRPC stub used for the Table Admin API.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_instance_admin_client]\n :end-before: [END bigtable_instance_admin_client]\n\n :rtype: :class:`.bigtable_admin_pb2.BigtableInstanceA... |
Please provide a description of the function:def instance(self, instance_id, display_name=None, instance_type=None, labels=None):
return Instance(
instance_id,
self,
display_name=display_name,
instance_type=instance_type,
labels=labels,
... | [
"Factory to create a instance associated with this client.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_create_prod_instance]\n :end-before: [END bigtable_create_prod_instance]\n\n :type instance_id: str\n :param instance_id: ... |
Please provide a description of the function:def list_instances(self):
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 | [
"List instances owned by the project.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_list_instances]\n :end-before: [END bigtable_list_instances]\n\n :rtype: tuple\n :returns:\n (instances, failed_locations), where 'i... |
Please provide a description of the function:def list_clusters(self):
resp = self.instance_admin_client.list_clusters(
self.instance_admin_client.instance_path(self.project, "-")
)
clusters = []
instances = {}
for cluster in resp.clusters:
match_c... | [
"List the clusters in the project.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_list_clusters_in_project]\n :end-before: [END bigtable_list_clusters_in_project]\n\n :rtype: tuple\n :returns:\n (clusters, failed_loca... |
Please provide a description of the function:def DeleteMetricDescriptor(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!") | [
"Deletes a metric descriptor. Only user-created\n [custom metrics](/monitoring/custom-metrics) can be deleted.\n "
] |
Please provide a description of the function: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=None,
):
# Wrap the transport method ... | [
"\n Lists all clusters owned by a project in either the specified zone or all\n zones.\n\n Example:\n >>> from google.cloud import container_v1\n >>>\n >>> client = container_v1.ClusterManagerClient()\n >>>\n >>> # TODO: Initialize `project... |
Please provide a description of the function: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,
metadata=None,
):
# Wrap the t... | [
"\n Gets the details of a specific cluster.\n\n Example:\n >>> from google.cloud import container_v1\n >>>\n >>> client = container_v1.ClusterManagerClient()\n >>>\n >>> # TODO: Initialize `project_id`:\n >>> project_id = ''\n ... |
Please provide a description of the function: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.api_core.gapic_v1.method.DEFAULT,
... | [
"\n Sets labels on a cluster.\n\n Example:\n >>> from google.cloud import container_v1\n >>>\n >>> client = container_v1.ClusterManagerClient()\n >>>\n >>> # TODO: Initialize `project_id`:\n >>> project_id = ''\n >>>\n ... |
Please provide a description of the function:def metric_path(cls, project, metric):
return google.api_core.path_template.expand(
"projects/{project}/metrics/{metric}", project=project, metric=metric
) | [
"Return a fully-qualified metric string."
] |
Please provide a description of the function: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,
):
# Wrap the transport method to add retry and timeout logic.
... | [
"\n Gets a logs-based metric.\n\n Example:\n >>> from google.cloud import logging_v2\n >>>\n >>> client = logging_v2.MetricsServiceV2Client()\n >>>\n >>> metric_name = client.metric_path('[PROJECT]', '[METRIC]')\n >>>\n >>> r... |
Please provide a description of the function:def metric_descriptor_path(cls, project, metric_descriptor):
return google.api_core.path_template.expand(
"projects/{project}/metricDescriptors/{metric_descriptor=**}",
project=project,
metric_descriptor=metric_descriptor,... | [
"Return a fully-qualified metric_descriptor string."
] |
Please provide a description of the function:def monitored_resource_descriptor_path(cls, project, monitored_resource_descriptor):
return google.api_core.path_template.expand(
"projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}",
project=project,
... | [
"Return a fully-qualified monitored_resource_descriptor string."
] |
Please provide a description of the function:def _to_pb(self):
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_clos... | [
"Construct a KeyRange protobuf.\n\n :rtype: :class:`~google.cloud.spanner_v1.proto.keys_pb2.KeyRange`\n :returns: protobuf corresponding to this instance.\n "
] |
Please provide a description of the function:def _to_dict(self):
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"... | [
"Return keyrange's state as a dict.\n\n :rtype: dict\n :returns: state of this instance.\n "
] |
Please provide a description of the function:def _to_pb(self):
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 ... | [
"Construct a KeySet protobuf.\n\n :rtype: :class:`~google.cloud.spanner_v1.proto.keys_pb2.KeySet`\n :returns: protobuf corresponding to this instance.\n "
] |
Please provide a description of the function:def _to_dict(self):
if self.all_:
return {"all": True}
return {
"keys": self.keys,
"ranges": [keyrange._to_dict() for keyrange in self.ranges],
} | [
"Return keyset's state as a dict.\n\n The result can be used to serialize the instance and reconstitute\n it later using :meth:`_from_dict`.\n\n :rtype: dict\n :returns: state of this instance.\n "
] |
Please provide a description of the function:def _from_dict(cls, mapping):
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", ()), rang... | [
"Create an instance from the corresponding state mapping.\n\n :type mapping: dict\n :param mapping: the instance state.\n "
] |
Please provide a description of the function:def _wrap_unary_errors(callable_):
_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... | [
"Map errors for Unary-Unary and Stream-Unary gRPC callables."
] |
Please provide a description of the function:def _wrap_stream_errors(callable_):
_patch_callable_name(callable_)
@general_helpers.wraps(callable_)
def error_remapped_callable(*args, **kwargs):
try:
result = callable_(*args, **kwargs)
return _StreamingResponseIterator(re... | [
"Wrap errors for Unary-Stream and Stream-Stream gRPC callables.\n\n The callables that return iterators require a bit more logic to re-map\n errors when iterating. This wraps both the initial invocation and the\n iterator of the return value to re-map errors.\n "
] |
Please provide a description of the function:def create_channel(
target, credentials=None, scopes=None, ssl_credentials=None, **kwargs
):
if credentials is None:
credentials, _ = google.auth.default(scopes=scopes)
else:
credentials = google.auth.credentials.with_scopes_if_required(
... | [
"Create a secure channel with credentials.\n\n Args:\n target (str): The target service address in the format 'hostname:port'.\n credentials (google.auth.credentials.Credentials): The credentials. If\n not specified, then this function will attempt to ascertain the\n credentia... |
Please provide a description of the function:def next(self):
try:
return six.next(self._wrapped)
except grpc.RpcError as exc:
six.raise_from(exceptions.from_grpc_error(exc), exc) | [
"Get the next response from the stream.\n\n Returns:\n protobuf.Message: A single response from the stream.\n "
] |
Please provide a description of the function:def wraps(wrapped):
if isinstance(wrapped, functools.partial):
return six.wraps(wrapped, assigned=_PARTIAL_VALID_ASSIGNMENTS)
else:
return six.wraps(wrapped) | [
"A functools.wraps helper that handles partial objects on Python 2."
] |
Please provide a description of the function:def _determine_default_project(project=None):
if project is None:
project = _get_gcd_project()
if project is None:
project = _base_default_project(project=project)
return project | [
"Determine default project explicitly or implicitly as fall-back.\n\n In implicit case, supports four environments. In order of precedence, the\n implicit environments are:\n\n * DATASTORE_DATASET environment variable (for ``gcd`` / emulator testing)\n * GOOGLE_CLOUD_PROJECT environment variable\n * ... |
Please provide a description of the function:def _extended_lookup(
datastore_api,
project,
key_pbs,
missing=None,
deferred=None,
eventual=False,
transaction_id=None,
):
if missing is not None and missing != []:
raise ValueError("missing must be None or an empty list")
i... | [
"Repeat lookup until all keys found (unless stop requested).\n\n Helper function for :meth:`Client.get_multi`.\n\n :type datastore_api:\n :class:`google.cloud.datastore._http.HTTPDatastoreAPI`\n or :class:`google.cloud.datastore_v1.gapic.DatastoreClient`\n :param datastore_api: The datastore ... |
Please provide a description of the function:def _datastore_api(self):
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)
... | [
"Getter for a wrapped API object."
] |
Please provide a description of the function:def get(self, key, missing=None, deferred=None, transaction=None, eventual=False):
entities = self.get_multi(
keys=[key],
missing=missing,
deferred=deferred,
transaction=transaction,
eventual=eventu... | [
"Retrieve an entity from a single key (if it exists).\n\n .. note::\n\n This is just a thin wrapper over :meth:`get_multi`.\n The backend API does not make a distinction between a single key or\n multiple keys in a lookup request.\n\n :type key: :class:`google.cloud.datas... |
Please provide a description of the function:def get_multi(
self, keys, missing=None, deferred=None, transaction=None, eventual=False
):
if not keys:
return []
ids = set(key.project for key in keys)
for current_id in ids:
if current_id != self.projec... | [
"Retrieve entities, along with their attributes.\n\n :type keys: list of :class:`google.cloud.datastore.key.Key`\n :param keys: The keys to be retrieved from the datastore.\n\n :type missing: list\n :param missing: (Optional) If a list is passed, the key-only entities\n ... |
Please provide a description of the function:def put_multi(self, entities):
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 ... | [
"Save entities in the Cloud Datastore.\n\n :type entities: list of :class:`google.cloud.datastore.entity.Entity`\n :param entities: The entities to be saved to the datastore.\n\n :raises: :class:`ValueError` if ``entities`` is a single entity.\n "
] |
Please provide a description of the function:def delete_multi(self, keys):
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:
curre... | [
"Delete keys from the Cloud Datastore.\n\n :type keys: list of :class:`google.cloud.datastore.key.Key`\n :param keys: The keys to be deleted from the Datastore.\n "
] |
Please provide a description of the function:def allocate_ids(self, incomplete_key, num_ids):
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... | [
"Allocate a list of IDs from a partial key.\n\n :type incomplete_key: :class:`google.cloud.datastore.key.Key`\n :param incomplete_key: Partial key to use as base for allocated IDs.\n\n :type num_ids: int\n :param num_ids: The number of IDs to allocate.\n\n :rtype: list of :class:`... |
Please provide a description of the function:def key(self, *path_args, **kwargs):
if "project" in kwargs:
raise TypeError("Cannot pass project")
kwargs["project"] = self.project
if "namespace" not in kwargs:
kwargs["namespace"] = self.namespace
return Key... | [
"Proxy to :class:`google.cloud.datastore.key.Key`.\n\n Passes our ``project``.\n "
] |
Please provide a description of the function:def query(self, **kwargs):
if "client" in kwargs:
raise TypeError("Cannot pass client")
if "project" in kwargs:
raise TypeError("Cannot pass project")
kwargs["project"] = self.project
if "namespace" not in kwar... | [
"Proxy to :class:`google.cloud.datastore.query.Query`.\n\n Passes our ``project``.\n\n Using query to search a datastore:\n\n .. testsetup:: query\n\n import os\n import uuid\n\n from google.cloud import datastore\n\n unique = os.getenv('CIRCLE_BUILD_... |
Please provide a description of the function:def mutate(self, row):
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, mu... | [
" Add a row to the batch. If the current batch meets one of the size\n limits, the batch is sent synchronously.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_batcher_mutate]\n :end-before: [END bigtable_batcher_mutate]\n\n :typ... |
Please provide a description of the function:def flush(self):
if len(self.rows) != 0:
self.table.mutate_rows(self.rows)
self.total_mutation_count = 0
self.total_size = 0
self.rows = [] | [
" Sends the current. batch to Cloud Bigtable.\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_batcher_flush]\n :end-before: [END bigtable_batcher_flush]\n\n "
] |
Please provide a description of the function:def _parse_topic_path(topic_path):
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") | [
"Verify that a topic path is in the correct format.\n\n .. _resource manager docs: https://cloud.google.com/resource-manager/\\\n reference/rest/v1beta1/projects#\\\n Project.FIELDS.project_id\n .. _topic spec: https://cloud.google.com/storage/docs/j... |
Please provide a description of the function:def from_api_repr(cls, resource, bucket):
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, topi... | [
"Construct an instance from the JSON repr returned by the server.\n\n See: https://cloud.google.com/storage/docs/json_api/v1/notifications\n\n :type resource: dict\n :param resource: JSON repr of the notification\n\n :type bucket: :class:`google.cloud.storage.bucket.Bucket`\n :par... |
Please provide a description of the function:def _set_properties(self, response):
self._properties.clear()
self._properties.update(response) | [
"Helper for :meth:`reload`.\n\n :type response: dict\n :param response: resource mapping from server\n "
] |
Please provide a description of the function:def create(self, client=None):
if self.notification_id is not None:
raise ValueError(
"Notification already exists w/ id: {}".format(self.notification_id)
)
client = self._require_client(client)
query... | [
"API wrapper: create the notification.\n\n See:\n https://cloud.google.com/storage/docs/json_api/v1/notifications/insert\n\n If :attr:`user_project` is set on the bucket, bills the API request\n to that project.\n\n :type client: :class:`~google.cloud.storage.client.Client`\n ... |
Please provide a description of the function:def exists(self, client=None):
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:
... | [
"Test whether this notification exists.\n\n See:\n https://cloud.google.com/storage/docs/json_api/v1/notifications/get\n\n If :attr:`user_project` is set on the bucket, bills the API request\n to that project.\n\n :type client: :class:`~google.cloud.storage.client.Client` or\n ... |
Please provide a description of the function:def reload(self, client=None):
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:
... | [
"Update this notification from the server configuration.\n\n See:\n https://cloud.google.com/storage/docs/json_api/v1/notifications/get\n\n If :attr:`user_project` is set on the bucket, bills the API request\n to that project.\n\n :type client: :class:`~google.cloud.storage.client... |
Please provide a description of the function:def delete(self, client=None):
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:
... | [
"Delete this notification.\n\n See:\n https://cloud.google.com/storage/docs/json_api/v1/notifications/delete\n\n If :attr:`user_project` is set on the bucket, bills the API request\n to that project.\n\n :type client: :class:`~google.cloud.storage.client.Client` or\n ... |
Please provide a description of the function: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=None,
):
# Wrap the transport metho... | [
"\n Creates a Redis instance based on the specified tier and memory size.\n\n By default, the instance is accessible from the project's `default\n network <https://cloud.google.com/compute/docs/networks-and-firewalls#networks>`__.\n\n The creation is executed asynchronously and callers m... |
Please provide a description of the function: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 ... | [
"\n Import a Redis RDB snapshot file from GCS into a Redis instance.\n\n Redis may stop serving during this operation. Instance state will be\n IMPORTING for entire operation. When complete, the instance will contain\n only data from the imported file.\n\n The returned operation i... |
Please provide a description of the function:def notification_channel_path(cls, project, notification_channel):
return google.api_core.path_template.expand(
"projects/{project}/notificationChannels/{notification_channel}",
project=project,
notification_channel=notifi... | [
"Return a fully-qualified notification_channel string."
] |
Please provide a description of the function:def notification_channel_descriptor_path(cls, project, channel_descriptor):
return google.api_core.path_template.expand(
"projects/{project}/notificationChannelDescriptors/{channel_descriptor}",
project=project,
channel_de... | [
"Return a fully-qualified notification_channel_descriptor string."
] |
Please provide a description of the function:def batch(self, client=None):
client = self._require_client(client)
return Batch(self, client) | [
"Return a batch to use as a context manager.\n\n :type client: :class:`~google.cloud.logging.client.Client` or\n ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current topic.\n\n :rtype: :c... |
Please provide a description of the function:def _do_log(self, client, _entry_class, payload=None, **kw):
client = self._require_client(client)
# Apply defaults
kw["log_name"] = kw.pop("log_name", self.full_name)
kw["labels"] = kw.pop("labels", self.labels)
kw["resource... | [
"Helper for :meth:`log_empty`, :meth:`log_text`, etc.\n "
] |
Please provide a description of the function:def log_text(self, text, client=None, **kw):
self._do_log(client, TextEntry, text, **kw) | [
"API call: log a text message via a POST request\n\n See\n https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write\n\n :type text: str\n :param text: the log message.\n\n :type client: :class:`~google.cloud.logging.client.Client` or\n ``NoneT... |
Please provide a description of the function:def log_struct(self, info, client=None, **kw):
self._do_log(client, StructEntry, info, **kw) | [
"API call: log a structured message via a POST request\n\n See\n https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write\n\n :type info: dict\n :param info: the log entry information\n\n :type client: :class:`~google.cloud.logging.client.Client` or\n ... |
Please provide a description of the function:def log_proto(self, message, client=None, **kw):
self._do_log(client, ProtobufEntry, message, **kw) | [
"API call: log a protobuf message via a POST request\n\n See\n https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list\n\n :type message: :class:`~google.protobuf.message.Message`\n :param message: The protobuf message to be logged.\n\n :type client: :class:`~goog... |
Please provide a description of the function:def delete(self, client=None):
client = self._require_client(client)
client.logging_api.logger_delete(self.project, self.name) | [
"API call: delete all entries in a logger via a DELETE request\n\n See\n https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs/delete\n\n :type client: :class:`~google.cloud.logging.client.Client` or\n ``NoneType``\n :param client: the client to u... |
Please provide a description of the function:def list_entries(
self,
projects=None,
filter_=None,
order_by=None,
page_size=None,
page_token=None,
):
log_filter = "logName=%s" % (self.full_name,)
if filter_ is not None:
filter_ = "%... | [
"Return a page of log entries.\n\n See\n https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list\n\n :type projects: list of strings\n :param projects: project IDs to include. If not passed,\n defaults to the project bound to the client.\n\n ... |
Please provide a description of the function:def log_text(self, text, **kw):
self.entries.append(TextEntry(payload=text, **kw)) | [
"Add a text entry to be logged during :meth:`commit`.\n\n :type text: str\n :param text: the text entry\n\n :type kw: dict\n :param kw: (optional) additional keyword arguments for the entry.\n See :class:`~google.cloud.logging.entries.LogEntry`.\n "
] |
Please provide a description of the function:def log_struct(self, info, **kw):
self.entries.append(StructEntry(payload=info, **kw)) | [
"Add a struct entry to be logged during :meth:`commit`.\n\n :type info: dict\n :param info: the struct entry\n\n :type kw: dict\n :param kw: (optional) additional keyword arguments for the entry.\n See :class:`~google.cloud.logging.entries.LogEntry`.\n "
] |
Please provide a description of the function:def log_proto(self, message, **kw):
self.entries.append(ProtobufEntry(payload=message, **kw)) | [
"Add a protobuf entry to be logged during :meth:`commit`.\n\n :type message: protobuf message\n :param message: the protobuf entry\n\n :type kw: dict\n :param kw: (optional) additional keyword arguments for the entry.\n See :class:`~google.cloud.logging.entries.LogEntry... |
Please provide a description of the function:def commit(self, client=None):
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.logg... | [
"Send saved log entries as a single API call.\n\n :type client: :class:`~google.cloud.logging.client.Client` or\n ``NoneType``\n :param client: the client to use. If not passed, falls back to the\n ``client`` stored on the current batch.\n "
] |
Please provide a description of the function:def full_name(self):
if not self.name:
raise ValueError("Missing config name.")
return "projects/%s/configs/%s" % (self._client.project, self.name) | [
"Fully-qualified name of this variable.\n\n Example:\n ``projects/my-project/configs/my-config``\n\n :rtype: str\n :returns: The full name based on project and config names.\n\n :raises: :class:`ValueError` if the config is missing a name.\n "
] |
Please provide a description of the function:def _set_properties(self, api_response):
self._properties.clear()
cleaned = api_response.copy()
if "name" in cleaned:
self.name = config_name_from_full_name(cleaned.pop("name"))
self._properties.update(cleaned) | [
"Update properties from resource in body of ``api_response``\n\n :type api_response: dict\n :param api_response: response returned from an API call\n "
] |
Please provide a description of the function:def reload(self, client=None):
client = self._require_client(client)
# We assume the config exists. If it doesn't it will raise a NotFound
# exception.
resp = client._connection.api_request(method="GET", path=self.path)
self.... | [
"API call: reload the config via a ``GET`` request.\n\n This method will reload the newest data for the config.\n\n See\n https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs/get\n\n :type client: :class:`google.cloud.runtimeconfig.cli... |
Please provide a description of the function:def get_variable(self, variable_name, client=None):
client = self._require_client(client)
variable = Variable(config=self, name=variable_name)
try:
variable.reload(client=client)
return variable
except NotFound... | [
"API call: get a variable via a ``GET`` request.\n\n This will return None if the variable doesn't exist::\n\n >>> from google.cloud import runtimeconfig\n >>> client = runtimeconfig.Client()\n >>> config = client.config('my-config')\n >>> print(config.get_variable('varia... |
Please provide a description of the function:def list_variables(self, page_size=None, page_token=None, client=None):
path = "%s/variables" % (self.path,)
client = self._require_client(client)
iterator = page_iterator.HTTPIterator(
client=client,
api_request=clien... | [
"API call: list variables for this config.\n\n This only lists variable names, not the values.\n\n See\n https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables/list\n\n :type page_size: int\n :param page_size:\n ... |
Please provide a description of the function:def _bytes_from_json(value, field):
if _not_null(value, field):
return base64.standard_b64decode(_to_bytes(value)) | [
"Base64-decode value"
] |
Please provide a description of the function:def _timestamp_query_param_from_json(value, field):
if _not_null(value, field):
# Canonical formats for timestamps in BigQuery are flexible. See:
# g.co/cloud/bigquery/docs/reference/standard-sql/data-types#timestamp-type
# The separator betw... | [
"Coerce 'value' to a datetime, if set or not nullable.\n\n Args:\n value (str): The timestamp.\n field (.SchemaField): The field corresponding to the value.\n\n Returns:\n Optional[datetime.datetime]: The parsed datetime object from\n ``value`` if the ``field`` is not null (otherwi... |
Please provide a description of the function:def _datetime_from_json(value, field):
if _not_null(value, field):
if "." in value:
# YYYY-MM-DDTHH:MM:SS.ffffff
return datetime.datetime.strptime(value, _RFC3339_MICROS_NO_ZULU)
else:
# YYYY-MM-DDTHH:MM:SS
... | [
"Coerce 'value' to a datetime, if set or not nullable.\n\n Args:\n value (str): The timestamp.\n field (.SchemaField): The field corresponding to the value.\n\n Returns:\n Optional[datetime.datetime]: The parsed datetime object from\n ``value`` if the ``field`` is not null (otherwi... |
Please provide a description of the function:def _time_from_json(value, field):
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 ValueE... | [
"Coerce 'value' to a datetime date, if set or not nullable"
] |
Please provide a description of the function:def _record_from_json(value, field):
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 subfie... | [
"Coerce 'value' to a mapping, if set or not nullable."
] |
Please provide a description of the function:def _row_tuple_from_json(row, schema):
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 cel... | [
"Convert JSON row data to row with appropriate types.\n\n Note: ``row['f']`` and ``schema`` are presumed to be of the same length.\n\n :type row: dict\n :param row: A JSON response row to be converted.\n\n :type schema: tuple\n :param schema: A tuple of\n :class:`~google.cloud.bigq... |
Please provide a description of the function:def _rows_from_json(values, schema):
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] | [
"Convert JSON row data to rows with appropriate types."
] |
Please provide a description of the function:def _decimal_to_json(value):
if isinstance(value, decimal.Decimal):
value = str(value)
return value | [
"Coerce 'value' to a JSON-compatible representation."
] |
Please provide a description of the function:def _bytes_to_json(value):
if isinstance(value, bytes):
value = base64.standard_b64encode(value).decode("ascii")
return value | [
"Coerce 'value' to an JSON-compatible representation."
] |
Please provide a description of the function:def _timestamp_to_json_parameter(value):
if isinstance(value, datetime.datetime):
if value.tzinfo not in (None, UTC):
# Convert to UTC and remove the time zone info.
value = value.replace(tzinfo=None) - value.utcoffset()
value... | [
"Coerce 'value' to an JSON-compatible representation.\n\n This version returns the string representation used in query parameters.\n "
] |
Please provide a description of the function:def _timestamp_to_json_row(value):
if isinstance(value, datetime.datetime):
value = _microseconds_from_datetime(value) * 1e-6
return value | [
"Coerce 'value' to an JSON-compatible representation.\n\n This version returns floating-point seconds value used in row data.\n "
] |
Please provide a description of the function:def _datetime_to_json(value):
if isinstance(value, datetime.datetime):
value = value.strftime(_RFC3339_MICROS_NO_ZULU)
return value | [
"Coerce 'value' to an JSON-compatible representation."
] |
Please provide a description of the function:def _date_to_json(value):
if isinstance(value, datetime.date):
value = value.isoformat()
return value | [
"Coerce 'value' to an JSON-compatible representation."
] |
Please provide a description of the function:def _time_to_json(value):
if isinstance(value, datetime.time):
value = value.isoformat()
return value | [
"Coerce 'value' to an JSON-compatible representation."
] |
Please provide a description of the function:def _scalar_field_to_json(field, row_value):
converter = _SCALAR_VALUE_TO_JSON_ROW.get(field.field_type)
if converter is None: # STRING doesn't need converting
return row_value
return converter(row_value) | [
"Maps a field and value to a JSON-safe value.\n\n Args:\n field ( \\\n :class:`~google.cloud.bigquery.schema.SchemaField`, \\\n ):\n The SchemaField to use for type conversion and field name.\n row_value (any):\n Value to be converted, based on the field's ty... |
Please provide a description of the function:def _repeated_field_to_json(field, row_value):
# Remove the REPEATED, but keep the other fields. This allows us to process
# each item as if it were a top-level field.
item_field = copy.deepcopy(field)
item_field._mode = "NULLABLE"
values = []
fo... | [
"Convert a repeated/array field to its JSON representation.\n\n Args:\n field ( \\\n :class:`~google.cloud.bigquery.schema.SchemaField`, \\\n ):\n The SchemaField to use for type conversion and field name. The\n field mode must equal ``REPEATED``.\n row_value... |
Please provide a description of the function:def _record_field_to_json(fields, row_value):
record = {}
isdict = isinstance(row_value, dict)
for subindex, subfield in enumerate(fields):
subname = subfield.name
if isdict:
subvalue = row_value.get(subname)
else:
... | [
"Convert a record/struct field to its JSON representation.\n\n Args:\n fields ( \\\n Sequence[:class:`~google.cloud.bigquery.schema.SchemaField`], \\\n ):\n The :class:`~google.cloud.bigquery.schema.SchemaField`s of the\n record's subfields to use for type conversio... |
Please provide a description of the function:def _field_to_json(field, row_value):
if row_value is None:
return None
if field.mode == "REPEATED":
return _repeated_field_to_json(field, row_value)
if field.field_type == "RECORD":
return _record_field_to_json(field.fields, row_va... | [
"Convert a field into JSON-serializable values.\n\n Args:\n field ( \\\n :class:`~google.cloud.bigquery.schema.SchemaField`, \\\n ):\n The SchemaField to use for type conversion and field name.\n\n row_value (Union[ \\\n Sequence[list], \\\n any, \... |
Please provide a description of the function:def _snake_to_camel_case(value):
words = value.split("_")
return words[0] + "".join(map(str.capitalize, words[1:])) | [
"Convert snake case string to camel case."
] |
Please provide a description of the function:def _get_sub_prop(container, keys, default=None):
sub_val = container
for key in keys:
if key not in sub_val:
return default
sub_val = sub_val[key]
return sub_val | [
"Get a nested value from a dictionary.\n\n This method works like ``dict.get(key)``, but for nested values.\n\n Arguments:\n container (dict):\n A dictionary which may contain other dictionaries as values.\n keys (iterable):\n A sequence of keys to attempt to get the value ... |
Please provide a description of the function:def _set_sub_prop(container, keys, value):
sub_val = container
for key in keys[:-1]:
if key not in sub_val:
sub_val[key] = {}
sub_val = sub_val[key]
sub_val[keys[-1]] = value | [
"Set a nested value in a dictionary.\n\n Arguments:\n container (dict):\n A dictionary which may contain other dictionaries as values.\n keys (iterable):\n A sequence of keys to attempt to set the value for. Each item in\n the sequence represents a deeper nesting. T... |
Please provide a description of the function:def _del_sub_prop(container, keys):
sub_val = container
for key in keys[:-1]:
if key not in sub_val:
sub_val[key] = {}
sub_val = sub_val[key]
if keys[-1] in sub_val:
del sub_val[keys[-1]] | [
"Remove a nested key fro a dictionary.\n\n Arguments:\n container (dict):\n A dictionary which may contain other dictionaries as values.\n keys (iterable):\n A sequence of keys to attempt to clear the value for. Each item in\n the sequence represents a deeper nestin... |
Please provide a description of the function:def _build_resource_from_properties(obj, filter_fields):
partial = {}
for filter_field in filter_fields:
api_field = obj._PROPERTY_TO_API_FIELD.get(filter_field)
if api_field is None and filter_field not in obj._properties:
raise Valu... | [
"Build a resource based on a ``_properties`` dictionary, filtered by\n ``filter_fields``, which follow the name of the Python object.\n "
] |
Please provide a description of the function:def get_model(client, model_id):
# [START bigquery_get_model]
from google.cloud import bigquery
# TODO(developer): Construct a BigQuery client object.
# client = bigquery.Client()
# TODO(developer): Set model_id to the ID of the model to fetch.
... | [
"Sample ID: go/samples-tracker/1510"
] |
Please provide a description of the function:def _check_database_id(database_id):
if database_id != u"":
msg = _DATABASE_ID_TEMPLATE.format(database_id)
raise ValueError(msg) | [
"Make sure a \"Reference\" database ID is empty.\n\n :type database_id: unicode\n :param database_id: The ``database_id`` field from a \"Reference\" protobuf.\n\n :raises: :exc:`ValueError` if the ``database_id`` is not empty.\n "
] |
Please provide a description of the function:def _add_id_or_name(flat_path, element_pb, empty_allowed):
id_ = element_pb.id
name = element_pb.name
# NOTE: Below 0 and the empty string are the "null" values for their
# respective types, indicating that the value is unset.
if id_ == 0:
... | [
"Add the ID or name from an element to a list.\n\n :type flat_path: list\n :param flat_path: List of accumulated path parts.\n\n :type element_pb: :class:`._app_engine_key_pb2.Path.Element`\n :param element_pb: The element containing ID or name.\n\n :type empty_allowed: bool\n :param empty_allowed... |
Please provide a description of the function:def _get_flat_path(path_pb):
num_elts = len(path_pb.element)
last_index = num_elts - 1
result = []
for index, element in enumerate(path_pb.element):
result.append(element.type)
_add_id_or_name(result, element, index == last_index)
r... | [
"Convert a legacy \"Path\" protobuf to a flat path.\n\n For example\n\n Element {\n type: \"parent\"\n id: 59\n }\n Element {\n type: \"child\"\n name: \"naem\"\n }\n\n would convert to ``('parent', 59, 'child', 'naem')``.\n\n :type path_pb: :... |
Please provide a description of the function:def _to_legacy_path(dict_path):
elements = []
for part in dict_path:
element_kwargs = {"type": part["kind"]}
if "id" in part:
element_kwargs["id"] = part["id"]
elif "name" in part:
element_kwargs["name"] = part["na... | [
"Convert a tuple of ints and strings in a legacy \"Path\".\n\n .. note:\n\n This assumes, but does not verify, that each entry in\n ``dict_path`` is valid (i.e. doesn't have more than one\n key out of \"name\" / \"id\").\n\n :type dict_path: lsit\n :param dict_path: The \"structured\" ... |
Please provide a description of the function:def _parse_path(path_args):
if len(path_args) == 0:
raise ValueError("Key path must not be empty.")
kind_list = path_args[::2]
id_or_name_list = path_args[1::2]
# Dummy sentinel value to pad incomplete key to even length ... | [
"Parses positional arguments into key path with kinds and IDs.\n\n :type path_args: tuple\n :param path_args: A tuple from positional arguments. Should be\n alternating list of kinds (string) and ID/name\n parts (int or string).\n\n :rtype: :cla... |
Please provide a description of the function:def _combine_args(self):
child_path = self._parse_path(self._flat_path)
if self._parent is not None:
if self._parent.is_partial:
raise ValueError("Parent key must be complete.")
# We know that _parent.path() ... | [
"Sets protected data by combining raw data set from the constructor.\n\n If a ``_parent`` is set, updates the ``_flat_path`` and sets the\n ``_namespace`` and ``_project`` if not already set.\n\n :rtype: :class:`list` of :class:`dict`\n :returns: A list of key parts with kind and ID or n... |
Please provide a description of the function:def _clone(self):
cloned_self = self.__class__(
*self.flat_path, project=self.project, namespace=self.namespace
)
# If the current parent has already been set, we re-use
# the same instance
cloned_self._parent = se... | [
"Duplicates the Key.\n\n Most attributes are simple types, so don't require copying. Other\n attributes like ``parent`` are long-lived and so we re-use them.\n\n :rtype: :class:`google.cloud.datastore.key.Key`\n :returns: A new ``Key`` instance with the same data as the current one.\n ... |
Please provide a description of the function:def completed_key(self, id_or_name):
if not self.is_partial:
raise ValueError("Only a partial key can be completed.")
if isinstance(id_or_name, six.string_types):
id_or_name_key = "name"
elif isinstance(id_or_name, si... | [
"Creates new key from existing partial key by adding final ID/name.\n\n :type id_or_name: str or integer\n :param id_or_name: ID or name to be added to the key.\n\n :rtype: :class:`google.cloud.datastore.key.Key`\n :returns: A new ``Key`` instance with the same data as the current one\n ... |
Please provide a description of the function:def to_protobuf(self):
key = _entity_pb2.Key()
key.partition_id.project_id = self.project
if self.namespace:
key.partition_id.namespace_id = self.namespace
for item in self.path:
element = key.path.add()
... | [
"Return a protobuf corresponding to the key.\n\n :rtype: :class:`.entity_pb2.Key`\n :returns: The protobuf representing the key.\n "
] |
Please provide a description of the function:def to_legacy_urlsafe(self, location_prefix=None):
if location_prefix is None:
project_id = self.project
else:
project_id = location_prefix + self.project
reference = _app_engine_key_pb2.Reference(
app=pro... | [
"Convert to a base64 encode urlsafe string for App Engine.\n\n This is intended to work with the \"legacy\" representation of a\n datastore \"Key\" used within Google App Engine (a so-called\n \"Reference\"). The returned string can be used as the ``urlsafe``\n argument to ``ndb.Key(urls... |
Please provide a description of the function:def from_legacy_urlsafe(cls, urlsafe):
urlsafe = _to_bytes(urlsafe, encoding="ascii")
padding = b"=" * (-len(urlsafe) % 4)
urlsafe += padding
raw_bytes = base64.urlsafe_b64decode(urlsafe)
reference = _app_engine_key_pb2.Refer... | [
"Convert urlsafe string to :class:`~google.cloud.datastore.key.Key`.\n\n This is intended to work with the \"legacy\" representation of a\n datastore \"Key\" used within Google App Engine (a so-called\n \"Reference\"). This assumes that ``urlsafe`` was created within an App\n Engine app ... |
Please provide a description of the function:def _make_parent(self):
if self.is_partial:
parent_args = self.flat_path[:-1]
else:
parent_args = self.flat_path[:-2]
if parent_args:
return self.__class__(
*parent_args, project=self.projec... | [
"Creates a parent key for the current path.\n\n Extracts all but the last element in the key path and creates a new\n key, while still matching the namespace and the project.\n\n :rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType`\n :returns: A new ``Key`` instance, whos... |
Please provide a description of the function:def parent(self):
if self._parent is None:
self._parent = self._make_parent()
return self._parent | [
"The parent of the current key.\n\n :rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType`\n :returns: A new ``Key`` instance, whose path consists of all but the\n last element of current path. If the current key has only\n one path element, returns ``No... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.