Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def get_default_handler(self, **kw):
gke_cluster_name = retrieve_metadata_server(_GKE_CLUSTER_NAME)
if (
_APPENGINE_FLEXIBLE_ENV_VM in os.environ
or _APPENGINE_INSTANCE_ID in os.environ
):
return AppEngine... | [
"Return the default logging handler based on the local environment.\n\n :type kw: dict\n :param kw: keyword args passed to handler constructor\n\n :rtype: :class:`logging.Handler`\n :returns: The default log handler based on the environment\n "
] |
Please provide a description of the function:def setup_logging(
self, log_level=logging.INFO, excluded_loggers=EXCLUDED_LOGGER_DEFAULTS, **kw
):
handler = self.get_default_handler(**kw)
setup_logging(handler, log_level=log_level, excluded_loggers=excluded_loggers) | [
"Attach default Stackdriver logging handler to the root logger.\n\n This method uses the default log handler, obtained by\n :meth:`~get_default_handler`, and attaches it to the root Python\n logger, so that a call such as ``logging.warn``, as well as all child\n loggers, will report to S... |
Please provide a description of the function:def key_ring_path(cls, project, location, key_ring):
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/keyRings/{key_ring}",
project=project,
location=location,
key_ring=key_... | [
"Return a fully-qualified key_ring string."
] |
Please provide a description of the function:def crypto_key_path_path(cls, project, location, key_ring, crypto_key_path):
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key_path=**}",
project=project,
... | [
"Return a fully-qualified crypto_key_path string."
] |
Please provide a description of the function:def crypto_key_version_path(
cls, project, location, key_ring, crypto_key, crypto_key_version
):
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoK... | [
"Return a fully-qualified crypto_key_version string."
] |
Please provide a description of the function:def create_key_ring(
self,
parent,
key_ring_id,
key_ring,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
# Wrap the transport metho... | [
"\n Create a new ``KeyRing`` in a given Project and Location.\n\n Example:\n >>> from google.cloud import kms_v1\n >>>\n >>> client = kms_v1.KeyManagementServiceClient()\n >>>\n >>> parent = client.location_path('[PROJECT]', '[LOCATION]')\n ... |
Please provide a description of the function:def create_crypto_key(
self,
parent,
crypto_key_id,
crypto_key,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
# Wrap the transport... | [
"\n Create a new ``CryptoKey`` within a ``KeyRing``.\n\n ``CryptoKey.purpose`` and ``CryptoKey.version_template.algorithm`` are\n required.\n\n Example:\n >>> from google.cloud import kms_v1\n >>> from google.cloud.kms_v1 import enums\n >>>\n >... |
Please provide a description of the function:def span_path(cls, project, trace, span):
return google.api_core.path_template.expand(
"projects/{project}/traces/{trace}/spans/{span}",
project=project,
trace=trace,
span=span,
) | [
"Return a fully-qualified span string."
] |
Please provide a description of the function:def batch_write_spans(
self,
name,
spans,
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 timeo... | [
"\n Sends new spans to new or existing traces. You cannot update\n existing spans.\n\n Example:\n >>> from google.cloud import trace_v2\n >>>\n >>> client = trace_v2.TraceServiceClient()\n >>>\n >>> name = client.project_path('[PROJECT]')\n... |
Please provide a description of the function:def create_span(
self,
name,
span_id,
display_name,
start_time,
end_time,
parent_span_id=None,
attributes=None,
stack_trace=None,
time_events=None,
links=None,
status=None,
... | [
"\n Creates a new span.\n\n Example:\n >>> from google.cloud import trace_v2\n >>>\n >>> client = trace_v2.TraceServiceClient()\n >>>\n >>> name = client.span_path('[PROJECT]', '[TRACE]', '[SPAN]')\n >>>\n >>> # TODO: Initial... |
Please provide a description of the function:def _wrap_callback_errors(callback, message):
try:
callback(message)
except Exception:
# Note: the likelihood of this failing is extremely low. This just adds
# a message to a queue, so if this doesn't work the world is in an
# un... | [
"Wraps a user callback so that if an exception occurs the message is\n nacked.\n\n Args:\n callback (Callable[None, Message]): The user callback.\n message (~Message): The Pub/Sub message.\n "
] |
Please provide a description of the function:def ack_deadline(self):
target = min([self._last_histogram_size * 2, self._last_histogram_size + 100])
if len(self.ack_histogram) > target:
self._ack_deadline = self.ack_histogram.percentile(percent=99)
return self._ack_deadline | [
"Return the current ack deadline based on historical time-to-ack.\n\n This method is \"sticky\". It will only perform the computations to\n check on the right ack deadline if the histogram has gained a\n significant amount of new information.\n\n Returns:\n int: The ack deadli... |
Please provide a description of the function:def load(self):
if self._leaser is None:
return 0
return max(
[
self._leaser.message_count / self._flow_control.max_messages,
self._leaser.bytes / self._flow_control.max_bytes,
]
... | [
"Return the current load.\n\n The load is represented as a float, where 1.0 represents having\n hit one of the flow control limits, and values between 0.0 and 1.0\n represent how close we are to them. (0.5 means we have exactly half\n of what the flow control setting allows, for example.... |
Please provide a description of the function:def maybe_pause_consumer(self):
if self.load >= 1.0:
if self._consumer is not None and not self._consumer.is_paused:
_LOGGER.debug("Message backlog over load at %.2f, pausing.", self.load)
self._consumer.pause() | [
"Check the current load and pause the consumer if needed."
] |
Please provide a description of the function:def maybe_resume_consumer(self):
# If we have been paused by flow control, check and see if we are
# back within our limits.
#
# In order to not thrash too much, require us to have passed below
# the resume threshold (80% by d... | [
"Check the current load and resume the consumer if needed."
] |
Please provide a description of the function:def _send_unary_request(self, request):
if request.ack_ids:
self._client.acknowledge(
subscription=self._subscription, ack_ids=list(request.ack_ids)
)
if request.modify_deadline_ack_ids:
# Send ack... | [
"Send a request using a separate unary request instead of over the\n stream.\n\n Args:\n request (types.StreamingPullRequest): The stream request to be\n mapped into unary requests.\n "
] |
Please provide a description of the function:def send(self, request):
if self._UNARY_REQUESTS:
try:
self._send_unary_request(request)
except exceptions.GoogleAPICallError:
_LOGGER.debug(
"Exception while sending unary RPC. This... | [
"Queue a request to be sent to the RPC."
] |
Please provide a description of the function:def heartbeat(self):
if self._rpc is not None and self._rpc.is_active:
self._rpc.send(types.StreamingPullRequest()) | [
"Sends an empty request over the streaming pull RPC.\n\n This always sends over the stream, regardless of if\n ``self._UNARY_REQUESTS`` is set or not.\n "
] |
Please provide a description of the function:def open(self, callback):
if self.is_active:
raise ValueError("This manager is already open.")
if self._closed:
raise ValueError("This manager has been closed and can not be re-used.")
self._callback = functools.part... | [
"Begin consuming messages.\n\n Args:\n callback (Callable[None, google.cloud.pubsub_v1.message.Messages]):\n A callback that will be called for each message received on the\n stream.\n "
] |
Please provide a description of the function:def close(self, reason=None):
with self._closing:
if self._closed:
return
# Stop consuming messages.
if self.is_active:
_LOGGER.debug("Stopping consumer.")
self._consumer.st... | [
"Stop consuming messages and shutdown all helper threads.\n\n This method is idempotent. Additional calls will have no effect.\n\n Args:\n reason (Any): The reason to close this. If None, this is considered\n an \"intentional\" shutdown. This is passed to the callbacks\n ... |
Please provide a description of the function:def _get_initial_request(self):
# Any ack IDs that are under lease management need to have their
# deadline extended immediately.
if self._leaser is not None:
# Explicitly copy the list, as it could be modified by another
... | [
"Return the initial request for the RPC.\n\n This defines the initial request that must always be sent to Pub/Sub\n immediately upon opening the subscription.\n\n Returns:\n google.cloud.pubsub_v1.types.StreamingPullRequest: A request\n suitable for being the first request... |
Please provide a description of the function:def _on_response(self, response):
_LOGGER.debug(
"Scheduling callbacks for %s messages.", len(response.received_messages)
)
# Immediately modack the messages we received, as this tells the server
# that we've received th... | [
"Process all received Pub/Sub messages.\n\n For each message, send a modified acknowledgment request to the\n server. This prevents expiration of the message due to buffering by\n gRPC or proxy/firewall. This makes the server and client expiration\n timer closer to each other thus preven... |
Please provide a description of the function:def _should_recover(self, exception):
exception = _maybe_wrap_exception(exception)
# If this is in the list of idempotent exceptions, then we want to
# recover.
if isinstance(exception, _RETRYABLE_STREAM_ERRORS):
_LOGGER.i... | [
"Determine if an error on the RPC stream should be recovered.\n\n If the exception is one of the retryable exceptions, this will signal\n to the consumer thread that it should \"recover\" from the failure.\n\n This will cause the stream to exit when it returns :data:`False`.\n\n Returns:... |
Please provide a description of the function:def create(self, reference, document_data):
write_pbs = _helpers.pbs_for_create(reference._document_path, document_data)
self._add_write_pbs(write_pbs) | [
"Add a \"change\" to this batch to create a document.\n\n If the document given by ``reference`` already exists, then this\n batch will fail when :meth:`commit`-ed.\n\n Args:\n reference (~.firestore_v1beta1.document.DocumentReference): A\n document reference to be cre... |
Please provide a description of the function:def set(self, reference, document_data, merge=False):
if merge is not False:
write_pbs = _helpers.pbs_for_set_with_merge(
reference._document_path, document_data, merge
)
else:
write_pbs = _helpers.... | [
"Add a \"change\" to replace a document.\n\n See\n :meth:`~.firestore_v1beta1.document.DocumentReference.set` for\n more information on how ``option`` determines how the change is\n applied.\n\n Args:\n reference (~.firestore_v1beta1.document.DocumentReference):\n ... |
Please provide a description of the function:def update(self, reference, field_updates, option=None):
if option.__class__.__name__ == "ExistsOption":
raise ValueError("you must not pass an explicit write option to " "update.")
write_pbs = _helpers.pbs_for_update(
referen... | [
"Add a \"change\" to update a document.\n\n See\n :meth:`~.firestore_v1beta1.document.DocumentReference.update` for\n more information on ``field_updates`` and ``option``.\n\n Args:\n reference (~.firestore_v1beta1.document.DocumentReference): A\n document refere... |
Please provide a description of the function:def delete(self, reference, option=None):
write_pb = _helpers.pb_for_delete(reference._document_path, option)
self._add_write_pbs([write_pb]) | [
"Add a \"change\" to delete a document.\n\n See\n :meth:`~.firestore_v1beta1.document.DocumentReference.delete` for\n more information on how ``option`` determines how the change is\n applied.\n\n Args:\n reference (~.firestore_v1beta1.document.DocumentReference): A\n ... |
Please provide a description of the function:def commit(self):
commit_response = self._client._firestore_api.commit(
self._client._database_string,
self._write_pbs,
transaction=None,
metadata=self._client._rpc_metadata,
)
self._write_pbs ... | [
"Commit the changes accumulated in this batch.\n\n Returns:\n List[google.cloud.proto.firestore.v1beta1.\\\n write_pb2.WriteResult, ...]: The write results corresponding\n to the changes committed, returned in the same order as the\n changes were applied to thi... |
Please provide a description of the function:def _ensure_tuple_or_list(arg_name, tuple_or_list):
if not isinstance(tuple_or_list, (tuple, list)):
raise TypeError(
"Expected %s to be a tuple or list. "
"Received %r" % (arg_name, tuple_or_list)
)
return list(tuple_or_l... | [
"Ensures an input is a tuple or list.\n\n This effectively reduces the iterable types allowed to a very short\n whitelist: list and tuple.\n\n :type arg_name: str\n :param arg_name: Name of argument to use in error message.\n\n :type tuple_or_list: sequence of str\n :param tuple_or_list: Sequence ... |
Please provide a description of the function:def _microseconds_from_datetime(value):
if not value.tzinfo:
value = value.replace(tzinfo=UTC)
# Regardless of what timezone is on the value, convert it to UTC.
value = value.astimezone(UTC)
# Convert the datetime to a microsecond timestamp.
... | [
"Convert non-none datetime to microseconds.\n\n :type value: :class:`datetime.datetime`\n :param value: The timestamp to convert.\n\n :rtype: int\n :returns: The timestamp, in microseconds.\n "
] |
Please provide a description of the function:def _time_from_iso8601_time_naive(value):
if len(value) == 8: # HH:MM:SS
fmt = _TIMEONLY_NO_FRACTION
elif len(value) == 15: # HH:MM:SS.micros
fmt = _TIMEONLY_W_MICROS
else:
raise ValueError("Unknown time format: {}".format(value))
... | [
"Convert a zoneless ISO8601 time string to naive datetime time\n\n :type value: str\n :param value: The time string to convert\n\n :rtype: :class:`datetime.time`\n :returns: A datetime time object created from the string\n :raises ValueError: if the value does not match a known format.\n "
] |
Please provide a description of the function:def _rfc3339_to_datetime(dt_str):
return datetime.datetime.strptime(dt_str, _RFC3339_MICROS).replace(tzinfo=UTC) | [
"Convert a microsecond-precision timestamp to a native datetime.\n\n :type dt_str: str\n :param dt_str: The string to convert.\n\n :rtype: :class:`datetime.datetime`\n :returns: The datetime object created from the string.\n "
] |
Please provide a description of the function:def _rfc3339_nanos_to_datetime(dt_str):
with_nanos = _RFC3339_NANOS.match(dt_str)
if with_nanos is None:
raise ValueError(
"Timestamp: %r, does not match pattern: %r"
% (dt_str, _RFC3339_NANOS.pattern)
)
bare_seconds =... | [
"Convert a nanosecond-precision timestamp to a native datetime.\n\n .. note::\n\n Python datetimes do not support nanosecond precision; this function\n therefore truncates such values to microseconds.\n\n :type dt_str: str\n :param dt_str: The string to convert.\n\n :rtype: :class:`datetime... |
Please provide a description of the function:def _datetime_to_rfc3339(value, ignore_zone=True):
if not ignore_zone and value.tzinfo is not None:
# Convert to UTC and remove the time zone info.
value = value.replace(tzinfo=None) - value.utcoffset()
return value.strftime(_RFC3339_MICROS) | [
"Convert a timestamp to a string.\n\n :type value: :class:`datetime.datetime`\n :param value: The datetime object to be converted to a string.\n\n :type ignore_zone: bool\n :param ignore_zone: If True, then the timezone (if any) of the datetime\n object is ignored.\n\n :rtype: ... |
Please provide a description of the function:def _to_bytes(value, encoding="ascii"):
result = value.encode(encoding) if isinstance(value, six.text_type) else value
if isinstance(result, six.binary_type):
return result
else:
raise TypeError("%r could not be converted to bytes" % (value,)... | [
"Converts a string value to bytes, if necessary.\n\n Unfortunately, ``six.b`` is insufficient for this task since in\n Python2 it does not modify ``unicode`` objects.\n\n :type value: str / bytes or unicode\n :param value: The string/bytes value to be converted.\n\n :type encoding: str\n :param en... |
Please provide a description of the function:def _bytes_to_unicode(value):
result = value.decode("utf-8") if isinstance(value, six.binary_type) else value
if isinstance(result, six.text_type):
return result
else:
raise ValueError("%r could not be converted to unicode" % (value,)) | [
"Converts bytes to a unicode value, if necessary.\n\n :type value: bytes\n :param value: bytes value to attempt string conversion on.\n\n :rtype: str\n :returns: The original value converted to unicode (if bytes) or as passed\n in if it started out as unicode.\n\n :raises ValueError: if ... |
Please provide a description of the function:def _from_any_pb(pb_type, any_pb):
msg = pb_type()
if not any_pb.Unpack(msg):
raise TypeError(
"Could not convert {} to {}".format(
any_pb.__class__.__name__, pb_type.__name__
)
)
return msg | [
"Converts an Any protobuf to the specified message type\n\n Args:\n pb_type (type): the type of the message that any_pb stores an instance\n of.\n any_pb (google.protobuf.any_pb2.Any): the object to be converted.\n\n Returns:\n pb_type: An instance of the pb_type message.\n\n ... |
Please provide a description of the function:def _pb_timestamp_to_datetime(timestamp_pb):
return _EPOCH + datetime.timedelta(
seconds=timestamp_pb.seconds, microseconds=(timestamp_pb.nanos / 1000.0)
) | [
"Convert a Timestamp protobuf to a datetime object.\n\n :type timestamp_pb: :class:`google.protobuf.timestamp_pb2.Timestamp`\n :param timestamp_pb: A Google returned timestamp protobuf.\n\n :rtype: :class:`datetime.datetime`\n :returns: A UTC datetime object converted from a protobuf timestamp.\n "
] |
Please provide a description of the function:def _datetime_to_pb_timestamp(when):
ms_value = _microseconds_from_datetime(when)
seconds, micros = divmod(ms_value, 10 ** 6)
nanos = micros * 10 ** 3
return timestamp_pb2.Timestamp(seconds=seconds, nanos=nanos) | [
"Convert a datetime object to a Timestamp protobuf.\n\n :type when: :class:`datetime.datetime`\n :param when: the datetime to convert\n\n :rtype: :class:`google.protobuf.timestamp_pb2.Timestamp`\n :returns: A timestamp protobuf corresponding to the object.\n "
] |
Please provide a description of the function:def _duration_pb_to_timedelta(duration_pb):
return datetime.timedelta(
seconds=duration_pb.seconds, microseconds=(duration_pb.nanos / 1000.0)
) | [
"Convert a duration protobuf to a Python timedelta object.\n\n .. note::\n\n The Python timedelta has a granularity of microseconds while\n the protobuf duration type has a duration of nanoseconds.\n\n :type duration_pb: :class:`google.protobuf.duration_pb2.Duration`\n :param duration_pb: A p... |
Please provide a description of the function:def _name_from_project_path(path, project, template):
if isinstance(template, str):
template = re.compile(template)
match = template.match(path)
if not match:
raise ValueError(
'path "%s" did not match expected pattern "%s"' % (... | [
"Validate a URI path and get the leaf object's name.\n\n :type path: str\n :param path: URI path containing the name.\n\n :type project: str\n :param project: (Optional) The project associated with the request. It is\n included for validation purposes. If passed as None,\n ... |
Please provide a description of the function:def make_secure_channel(credentials, user_agent, host, extra_options=()):
target = "%s:%d" % (host, http_client.HTTPS_PORT)
http_request = google.auth.transport.requests.Request()
user_agent_option = ("grpc.primary_user_agent", user_agent)
options = (us... | [
"Makes a secure channel for an RPC service.\n\n Uses / depends on gRPC.\n\n :type credentials: :class:`google.auth.credentials.Credentials`\n :param credentials: The OAuth2 Credentials to use for creating\n access tokens.\n\n :type user_agent: str\n :param user_agent: The user ... |
Please provide a description of the function:def make_secure_stub(credentials, user_agent, stub_class, host, extra_options=()):
channel = make_secure_channel(
credentials, user_agent, host, extra_options=extra_options
)
return stub_class(channel) | [
"Makes a secure stub for an RPC service.\n\n Uses / depends on gRPC.\n\n :type credentials: :class:`google.auth.credentials.Credentials`\n :param credentials: The OAuth2 Credentials to use for creating\n access tokens.\n\n :type user_agent: str\n :param user_agent: The user age... |
Please provide a description of the function:def make_insecure_stub(stub_class, host, port=None):
if port is None:
target = host
else:
# NOTE: This assumes port != http_client.HTTPS_PORT:
target = "%s:%d" % (host, port)
channel = grpc.insecure_channel(target)
return stub_cla... | [
"Makes an insecure stub for an RPC service.\n\n Uses / depends on gRPC.\n\n :type stub_class: type\n :param stub_class: A gRPC stub type for a given service.\n\n :type host: str\n :param host: The host for the service. May also include the port\n if ``port`` is unspecified.\n\n :ty... |
Please provide a description of the function:def fromutc(self, dt):
if dt.tzinfo is None:
return dt.replace(tzinfo=self)
return super(_UTC, self).fromutc(dt) | [
"Convert a timestamp from (naive) UTC to this timezone."
] |
Please provide a description of the function:def add_single_feature_methods(cls):
# Sanity check: This only makes sense if we are building the GAPIC
# subclass and have enums already attached.
if not hasattr(cls, "enums"):
return cls
# Add each single-feature method to the class.
for f... | [
"Custom decorator intended for :class:`~vision.helpers.VisionHelpers`.\n\n This metaclass adds a `{feature}` method for every feature\n defined on the Feature enum.\n "
] |
Please provide a description of the function:def _create_single_feature_method(feature):
# Define the function properties.
fx_name = feature.name.lower()
if "detection" in fx_name:
fx_doc = "Perform {0}.".format(fx_name.replace("_", " "))
else:
fx_doc = "Return {desc} information.".... | [
"Return a function that will detect a single feature.\n\n Args:\n feature (enum): A specific feature defined as a member of\n :class:`~enums.Feature.Type`.\n\n Returns:\n function: A helper function to detect just that feature.\n ",
"\n\n Args:\n image (:class:`~.{modul... |
Please provide a description of the function:def schedule(self, callback, *args, **kwargs):
self._executor.submit(callback, *args, **kwargs) | [
"Schedule the callback to be called asynchronously in a thread pool.\n\n Args:\n callback (Callable): The function to call.\n args: Positional arguments passed to the function.\n kwargs: Key-word arguments passed to the function.\n\n Returns:\n None\n ... |
Please provide a description of the function:def shutdown(self):
# Drop all pending item from the executor. Without this, the executor
# will block until all pending items are complete, which is
# undesirable.
try:
while True:
self._executor._work_que... | [
"Shuts down the scheduler and immediately end all pending callbacks.\n "
] |
Please provide a description of the function:def list_events(
self,
project_name,
group_id,
service_filter=None,
time_range=None,
page_size=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metada... | [
"\n Lists the specified events.\n\n Example:\n >>> from google.cloud import errorreporting_v1beta1\n >>>\n >>> client = errorreporting_v1beta1.ErrorStatsServiceClient()\n >>>\n >>> project_name = client.project_path('[PROJECT]')\n >>>\n... |
Please provide a description of the function:def delete_events(
self,
project_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 Deletes all error events of a given project.\n\n Example:\n >>> from google.cloud import errorreporting_v1beta1\n >>>\n >>> client = errorreporting_v1beta1.ErrorStatsServiceClient()\n >>>\n >>> project_name = client.project_path('[PROJECT]')\n... |
Please provide a description of the function:def _item_to_document_ref(iterator, item):
document_id = item.name.split(_helpers.DOCUMENT_PATH_DELIMITER)[-1]
return iterator.collection.document(document_id) | [
"Convert Document resource to document ref.\n\n Args:\n iterator (google.api_core.page_iterator.GRPCIterator):\n iterator response\n item (dict): document resource\n "
] |
Please provide a description of the function:def parent(self):
if len(self._path) == 1:
return None
else:
parent_path = self._path[:-1]
return self._client.document(*parent_path) | [
"Document that owns the current collection.\n\n Returns:\n Optional[~.firestore_v1beta1.document.DocumentReference]: The\n parent document, if the current collection is not a\n top-level collection.\n "
] |
Please provide a description of the function:def document(self, document_id=None):
if document_id is None:
document_id = _auto_id()
child_path = self._path + (document_id,)
return self._client.document(*child_path) | [
"Create a sub-document underneath the current collection.\n\n Args:\n document_id (Optional[str]): The document identifier\n within the current collection. If not provided, will default\n to a random 20 character string composed of digits,\n uppercase a... |
Please provide a description of the function:def _parent_info(self):
parent_doc = self.parent
if parent_doc is None:
parent_path = _helpers.DOCUMENT_PATH_DELIMITER.join(
(self._client._database_string, "documents")
)
else:
parent_path ... | [
"Get fully-qualified parent path and prefix for this collection.\n\n Returns:\n Tuple[str, str]: Pair of\n\n * the fully-qualified (with database and project) path to the\n parent of this collection (will either be the database path\n or a document path).\n ... |
Please provide a description of the function:def add(self, document_data, document_id=None):
if document_id is None:
parent_path, expected_prefix = self._parent_info()
document_pb = document_pb2.Document()
created_document_pb = self._client._firestore_api.create_do... | [
"Create a document in the Firestore database with the provided data.\n\n Args:\n document_data (dict): Property names and values to use for\n creating the document.\n document_id (Optional[str]): The document identifier within the\n current collection. If n... |
Please provide a description of the function:def list_documents(self, page_size=None):
parent, _ = self._parent_info()
iterator = self._client._firestore_api.list_documents(
parent,
self.id,
page_size=page_size,
show_missing=True,
met... | [
"List all subdocuments of the current collection.\n\n Args:\n page_size (Optional[int]]): The maximum number of documents\n in each page of results from this request. Non-positive values\n are ignored. Defaults to a sensible value set by the API.\n\n Returns:\n ... |
Please provide a description of the function:def select(self, field_paths):
query = query_mod.Query(self)
return query.select(field_paths) | [
"Create a \"select\" query with this collection as parent.\n\n See\n :meth:`~.firestore_v1beta1.query.Query.select` for\n more information on this method.\n\n Args:\n field_paths (Iterable[str, ...]): An iterable of field paths\n (``.``-delimited list of field n... |
Please provide a description of the function:def where(self, field_path, op_string, value):
query = query_mod.Query(self)
return query.where(field_path, op_string, value) | [
"Create a \"where\" query with this collection as parent.\n\n See\n :meth:`~.firestore_v1beta1.query.Query.where` for\n more information on this method.\n\n Args:\n field_path (str): A field path (``.``-delimited list of\n field names) for the field to filter on... |
Please provide a description of the function:def order_by(self, field_path, **kwargs):
query = query_mod.Query(self)
return query.order_by(field_path, **kwargs) | [
"Create an \"order by\" query with this collection as parent.\n\n See\n :meth:`~.firestore_v1beta1.query.Query.order_by` for\n more information on this method.\n\n Args:\n field_path (str): A field path (``.``-delimited list of\n field names) on which to order t... |
Please provide a description of the function:def limit(self, count):
query = query_mod.Query(self)
return query.limit(count) | [
"Create a limited query with this collection as parent.\n\n See\n :meth:`~.firestore_v1beta1.query.Query.limit` for\n more information on this method.\n\n Args:\n count (int): Maximum number of documents to return that match\n the query.\n\n Returns:\n ... |
Please provide a description of the function:def offset(self, num_to_skip):
query = query_mod.Query(self)
return query.offset(num_to_skip) | [
"Skip to an offset in a query with this collection as parent.\n\n See\n :meth:`~.firestore_v1beta1.query.Query.offset` for\n more information on this method.\n\n Args:\n num_to_skip (int): The number of results to skip at the beginning\n of query results. (Must ... |
Please provide a description of the function:def start_at(self, document_fields):
query = query_mod.Query(self)
return query.start_at(document_fields) | [
"Start query at a cursor with this collection as parent.\n\n See\n :meth:`~.firestore_v1beta1.query.Query.start_at` for\n more information on this method.\n\n Args:\n document_fields (Union[~.firestore_v1beta1.\\\n document.DocumentSnapshot, dict, list, tuple]):... |
Please provide a description of the function:def start_after(self, document_fields):
query = query_mod.Query(self)
return query.start_after(document_fields) | [
"Start query after a cursor with this collection as parent.\n\n See\n :meth:`~.firestore_v1beta1.query.Query.start_after` for\n more information on this method.\n\n Args:\n document_fields (Union[~.firestore_v1beta1.\\\n document.DocumentSnapshot, dict, list, tu... |
Please provide a description of the function:def end_before(self, document_fields):
query = query_mod.Query(self)
return query.end_before(document_fields) | [
"End query before a cursor with this collection as parent.\n\n See\n :meth:`~.firestore_v1beta1.query.Query.end_before` for\n more information on this method.\n\n Args:\n document_fields (Union[~.firestore_v1beta1.\\\n document.DocumentSnapshot, dict, list, tupl... |
Please provide a description of the function:def end_at(self, document_fields):
query = query_mod.Query(self)
return query.end_at(document_fields) | [
"End query at a cursor with this collection as parent.\n\n See\n :meth:`~.firestore_v1beta1.query.Query.end_at` for\n more information on this method.\n\n Args:\n document_fields (Union[~.firestore_v1beta1.\\\n document.DocumentSnapshot, dict, list, tuple]): a d... |
Please provide a description of the function:def stream(self, transaction=None):
query = query_mod.Query(self)
return query.stream(transaction=transaction) | [
"Read the documents in this collection.\n\n This sends a ``RunQuery`` RPC and then returns an iterator which\n consumes each document returned in the stream of ``RunQueryResponse``\n messages.\n\n .. note::\n\n The underlying stream of responses will time out after\n ... |
Please provide a description of the function:def get_languages(self, target_language=None):
query_params = {}
if target_language is None:
target_language = self.target_language
if target_language is not None:
query_params["target"] = target_language
respo... | [
"Get list of supported languages for translation.\n\n Response\n\n See\n https://cloud.google.com/translate/docs/discovering-supported-languages\n\n :type target_language: str\n :param target_language: (Optional) The language used to localize\n retur... |
Please provide a description of the function:def detect_language(self, values):
single_value = False
if isinstance(values, six.string_types):
single_value = True
values = [values]
data = {"q": values}
response = self._connection.api_request(
... | [
"Detect the language of a string or list of strings.\n\n See https://cloud.google.com/translate/docs/detecting-language\n\n :type values: str or list\n :param values: String or list of strings that will have\n language detected.\n\n :rtype: dict or list\n :re... |
Please provide a description of the function:def translate(
self,
values,
target_language=None,
format_=None,
source_language=None,
customization_ids=(),
model=None,
):
single_value = False
if isinstance(values, six.string_types):
... | [
"Translate a string or list of strings.\n\n See https://cloud.google.com/translate/docs/translating-text\n\n :type values: str or list\n :param values: String or list of strings to translate.\n\n :type target_language: str\n :param target_language: The language to translate result... |
Please provide a description of the function:def add(self, items):
for item in items:
# Add the ack ID to the set of managed ack IDs, and increment
# the size counter.
if item.ack_id not in self._leased_messages:
self._leased_messages[item.ack_id] = _... | [
"Add messages to be managed by the leaser."
] |
Please provide a description of the function:def remove(self, items):
# Remove the ack ID from lease management, and decrement the
# byte counter.
for item in items:
if self._leased_messages.pop(item.ack_id, None) is not None:
self._bytes -= item.byte_size
... | [
"Remove messages from lease management."
] |
Please provide a description of the function:def maintain_leases(self):
while self._manager.is_active and not self._stop_event.is_set():
# Determine the appropriate duration for the lease. This is
# based off of how long previous messages have taken to ack, with
# a ... | [
"Maintain all of the leases being managed.\n\n This method modifies the ack deadline for all of the managed\n ack IDs, then waits for most of that time (but with jitter), and\n repeats.\n "
] |
Please provide a description of the function:def make_report_error_api(client):
gax_client = report_errors_service_client.ReportErrorsServiceClient(
credentials=client._credentials, client_info=_CLIENT_INFO
)
return _ErrorReportingGapicApi(gax_client, client.project) | [
"Create an instance of the gapic Logging API.\n\n :type client::class:`google.cloud.error_reporting.Client`\n :param client: Error Reporting client.\n\n :rtype: :class:_ErrorReportingGapicApi\n :returns: An Error Reporting API instance.\n "
] |
Please provide a description of the function:def report_error_event(self, error_report):
project_name = self._gapic_api.project_path(self._project)
error_report_payload = report_errors_service_pb2.ReportedErrorEvent()
ParseDict(error_report, error_report_payload)
self._gapic_api... | [
"Uses the gapic client to report the error.\n\n :type error_report: dict\n :param error_report:\n payload of the error report formatted according to\n https://cloud.google.com/error-reporting/docs/formatting-error-messages\n This object should be built using\n ... |
Please provide a description of the function:def table_path(cls, project, instance, table):
return google.api_core.path_template.expand(
"projects/{project}/instances/{instance}/tables/{table}",
project=project,
instance=instance,
table=table,
) | [
"Return a fully-qualified table string."
] |
Please provide a description of the function:def read_rows(
self,
table_name,
app_profile_id=None,
rows=None,
filter_=None,
rows_limit=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=No... | [
"\n Streams back the contents of all requested rows in key order, optionally\n applying the same Reader filter to each. Depending on their size,\n rows and cells may be broken up across multiple responses, but\n atomicity of each row will still be preserved. See the\n ReadRowsResp... |
Please provide a description of the function:def mutate_rows(
self,
table_name,
entries,
app_profile_id=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
# Wrap the transpor... | [
"\n Mutates multiple rows in a batch. Each individual row is mutated\n atomically as in MutateRow, but the entire batch is not executed\n atomically.\n\n Example:\n >>> from google.cloud import bigtable_v2\n >>>\n >>> client = bigtable_v2.BigtableClient()... |
Please provide a description of the function:def check_and_mutate_row(
self,
table_name,
row_key,
app_profile_id=None,
predicate_filter=None,
true_mutations=None,
false_mutations=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.a... | [
"\n Mutates a row atomically based on the output of a predicate Reader filter.\n\n Example:\n >>> from google.cloud import bigtable_v2\n >>>\n >>> client = bigtable_v2.BigtableClient()\n >>>\n >>> table_name = client.table_path('[PROJECT]', '[INST... |
Please provide a description of the function:def _update_from_pb(self, instance_pb):
if not instance_pb.display_name: # Simple field (string)
raise ValueError("Instance protobuf does not contain display_name")
self.display_name = instance_pb.display_name
self.type_ = instan... | [
"Refresh self from the server-provided protobuf.\n Helper for :meth:`from_pb` and :meth:`reload`.\n "
] |
Please provide a description of the function:def name(self):
return self._client.instance_admin_client.instance_path(
project=self._client.project, instance=self.instance_id
) | [
"Instance name used in requests.\n\n .. note::\n This property will not change if ``instance_id`` does not,\n but the return value is not cached.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_instance_name]\n :end-be... |
Please provide a description of the function:def create(
self,
location_id=None,
serve_nodes=None,
default_storage_type=None,
clusters=None,
):
if clusters is None:
warnings.warn(
_INSTANCE_CREATE_WARNING.format(
... | [
"Create this instance.\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 .. note::\n\n Uses the ``project`` and ``instance_id`` on the current\n ... |
Please provide a description of the function:def exists(self):
try:
self._client.instance_admin_client.get_instance(name=self.name)
return True
# NOTE: There could be other exceptions that are returned to the user.
except NotFound:
return False | [
"Check whether the instance already exists.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_check_instance_exists]\n :end-before: [END bigtable_check_instance_exists]\n\n :rtype: bool\n :returns: True if the table exists, else Fa... |
Please provide a description of the function:def reload(self):
instance_pb = self._client.instance_admin_client.get_instance(self.name)
# NOTE: _update_from_pb does not check that the project and
# instance ID on the response match the request.
self._update_from_pb(instan... | [
"Reload the metadata for this instance.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_reload_instance]\n :end-before: [END bigtable_reload_instance]\n "
] |
Please provide a description of the function:def update(self):
update_mask_pb = field_mask_pb2.FieldMask()
if self.display_name is not None:
update_mask_pb.paths.append("display_name")
if self.type_ is not None:
update_mask_pb.paths.append("type")
if self... | [
"Updates an instance within a project.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_update_instance]\n :end-before: [END bigtable_update_instance]\n\n .. note::\n\n Updates any or all of the following values:\n ... |
Please provide a description of the function:def get_iam_policy(self):
instance_admin_client = self._client.instance_admin_client
resp = instance_admin_client.get_iam_policy(resource=self.name)
return Policy.from_pb(resp) | [
"Gets the access control policy for an instance resource.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_get_iam_policy]\n :end-before: [END bigtable_get_iam_policy]\n\n :rtype: :class:`google.cloud.bigtable.policy.Policy`\n :re... |
Please provide a description of the function:def set_iam_policy(self, policy):
instance_admin_client = self._client.instance_admin_client
resp = instance_admin_client.set_iam_policy(
resource=self.name, policy=policy.to_pb()
)
return Policy.from_pb(resp) | [
"Sets the access control policy on an instance resource. Replaces any\n existing policy.\n\n For more information about policy, please see documentation of\n class `google.cloud.bigtable.policy.Policy`\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after:... |
Please provide a description of the function:def cluster(
self, cluster_id, location_id=None, serve_nodes=None, default_storage_type=None
):
return Cluster(
cluster_id,
self,
location_id=location_id,
serve_nodes=serve_nodes,
defaul... | [
"Factory to create a cluster associated with this instance.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_create_cluster]\n :end-before: [END bigtable_create_cluster]\n\n :type cluster_id: str\n :param cluster_id: The ID of the... |
Please provide a description of the function:def list_clusters(self):
resp = self._client.instance_admin_client.list_clusters(self.name)
clusters = [Cluster.from_pb(cluster, self) for cluster in resp.clusters]
return clusters, resp.failed_locations | [
"List the clusters in this instance.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_list_clusters_on_instance]\n :end-before: [END bigtable_list_clusters_on_instance]\n\n :rtype: tuple\n :returns:\n (clusters, failed_... |
Please provide a description of the function:def table(self, table_id, mutation_timeout=None, app_profile_id=None):
return Table(
table_id,
self,
app_profile_id=app_profile_id,
mutation_timeout=mutation_timeout,
) | [
"Factory to create a table associated with this instance.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_create_table]\n :end-before: [END bigtable_create_table]\n\n :type table_id: str\n :param table_id: The ID of the table.\n\... |
Please provide a description of the function:def list_tables(self):
table_list_pb = self._client.table_admin_client.list_tables(self.name)
result = []
for table_pb in table_list_pb:
table_prefix = self.name + "/tables/"
if not table_pb.name.startswith(table_pref... | [
"List the tables in this instance.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_list_tables]\n :end-before: [END bigtable_list_tables]\n\n :rtype: list of :class:`Table <google.cloud.bigtable.table.Table>`\n :returns: The list... |
Please provide a description of the function:def app_profile(
self,
app_profile_id,
routing_policy_type=None,
description=None,
cluster_id=None,
allow_transactional_writes=None,
):
return AppProfile(
app_profile_id,
self,
... | [
"Factory to create AppProfile associated with this instance.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_create_app_profile]\n :end-before: [END bigtable_create_app_profile]\n\n :type app_profile_id: str\n :param app_profile_... |
Please provide a description of the function:def list_app_profiles(self):
resp = self._client.instance_admin_client.list_app_profiles(self.name)
return [AppProfile.from_pb(app_profile, self) for app_profile in resp] | [
"Lists information about AppProfiles in an instance.\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_list_app_profiles]\n :end-before: [END bigtable_list_app_profiles]\n\n :rtype: :list:[`~google.cloud.bigtable.app_profile.AppProfile`]\... |
Please provide a description of the function:def system(session):
system_test_path = os.path.join("tests", "system.py")
system_test_folder_path = os.path.join("tests", "system")
# Sanity check: Only run tests if the environment variable is set.
if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"... | [
"Run the system test suite."
] |
Please provide a description of the function:def _reference_getter(table):
from google.cloud.bigquery import dataset
dataset_ref = dataset.DatasetReference(table.project, table.dataset_id)
return TableReference(dataset_ref, table.table_id) | [
"A :class:`~google.cloud.bigquery.table.TableReference` pointing to\n this table.\n\n Returns:\n google.cloud.bigquery.table.TableReference: pointer to this table.\n "
] |
Please provide a description of the function:def _view_use_legacy_sql_getter(table):
view = table._properties.get("view")
if view is not None:
# The server-side default for useLegacySql is True.
return view.get("useLegacySql", True)
# In some cases, such as in a table list no view objec... | [
"bool: Specifies whether to execute the view with Legacy or Standard SQL.\n\n This boolean specifies whether to execute the view with Legacy SQL\n (:data:`True`) or Standard SQL (:data:`False`). The client side default is\n :data:`False`. The server-side default is :data:`True`. If this table is\n not a... |
Please provide a description of the function:def _row_from_mapping(mapping, schema):
if len(schema) == 0:
raise ValueError(_TABLE_HAS_NO_SCHEMA)
row = []
for field in schema:
if field.mode == "REQUIRED":
row.append(mapping[field.name])
elif field.mode == "REPEATED":... | [
"Convert a mapping to a row tuple using the schema.\n\n Args:\n mapping (Dict[str, object])\n Mapping of row data: must contain keys for all required fields in\n the schema. Keys which do not correspond to a field in the schema\n are ignored.\n schema (List[google.c... |
Please provide a description of the function:def _item_to_row(iterator, resource):
return Row(
_helpers._row_tuple_from_json(resource, iterator.schema),
iterator._field_to_index,
) | [
"Convert a JSON row to the native object.\n\n .. note::\n\n This assumes that the ``schema`` attribute has been\n added to the iterator after being created, which\n should be done by the caller.\n\n :type iterator: :class:`~google.api_core.page_iterator.Iterator`\n :param iterator: The... |
Please provide a description of the function:def _rows_page_start(iterator, page, response):
total_rows = response.get("totalRows")
if total_rows is not None:
total_rows = int(total_rows)
iterator._total_rows = total_rows | [
"Grab total rows when :class:`~google.cloud.iterator.Page` starts.\n\n :type iterator: :class:`~google.api_core.page_iterator.Iterator`\n :param iterator: The iterator that is currently in use.\n\n :type page: :class:`~google.api_core.page_iterator.Page`\n :param page: The page that was just created.\n\... |
Please provide a description of the function:def _table_arg_to_table_ref(value, default_project=None):
if isinstance(value, six.string_types):
value = TableReference.from_string(value, default_project=default_project)
if isinstance(value, (Table, TableListItem)):
value = value.reference
... | [
"Helper to convert a string or Table to TableReference.\n\n This function keeps TableReference and other kinds of objects unchanged.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.