Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def list_instances( self, parent, page_token=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry ...
[ "\n Lists information about instances in a project.\n\n Example:\n >>> from google.cloud import bigtable_admin_v2\n >>>\n >>> client = bigtable_admin_v2.BigtableInstanceAdminClient()\n >>>\n >>> parent = client.project_path('[PROJECT]')\n ...
Please provide a description of the function:def update_instance( self, name, display_name, type_, labels, state=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): ...
[ "\n Updates an instance within a project.\n\n Example:\n >>> from google.cloud import bigtable_admin_v2\n >>> from google.cloud.bigtable_admin_v2 import enums\n >>>\n >>> client = bigtable_admin_v2.BigtableInstanceAdminClient()\n >>>\n ...
Please provide a description of the function:def partial_update_instance( self, instance, update_mask, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add...
[ "\n Partially updates an instance within a project.\n\n Example:\n >>> from google.cloud import bigtable_admin_v2\n >>>\n >>> client = bigtable_admin_v2.BigtableInstanceAdminClient()\n >>>\n >>> # TODO: Initialize `instance`:\n >>> inst...
Please provide a description of the function:def create_cluster( self, parent, cluster_id, cluster, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method t...
[ "\n Creates a cluster within an instance.\n\n Example:\n >>> from google.cloud import bigtable_admin_v2\n >>>\n >>> client = bigtable_admin_v2.BigtableInstanceAdminClient()\n >>>\n >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]')\n ...
Please provide a description of the function:def update_cluster( self, name, serve_nodes, location=None, state=None, default_storage_type=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata...
[ "\n Updates a cluster within an instance.\n\n Example:\n >>> from google.cloud import bigtable_admin_v2\n >>>\n >>> client = bigtable_admin_v2.BigtableInstanceAdminClient()\n >>>\n >>> name = client.cluster_path('[PROJECT]', '[INSTANCE]', '[CLUSTE...
Please provide a description of the function:def create_app_profile( self, parent, app_profile_id, app_profile, ignore_warnings=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): ...
[ "\n Creates an app profile within an instance.\n\n Example:\n >>> from google.cloud import bigtable_admin_v2\n >>>\n >>> client = bigtable_admin_v2.BigtableInstanceAdminClient()\n >>>\n >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]')\...
Please provide a description of the function:def update_app_profile( self, app_profile, update_mask, ignore_warnings=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap...
[ "\n Updates an app profile within an instance.\n\n Example:\n >>> from google.cloud import bigtable_admin_v2\n >>>\n >>> client = bigtable_admin_v2.BigtableInstanceAdminClient()\n >>>\n >>> # TODO: Initialize `app_profile`:\n >>> app_pr...
Please provide a description of the function:def annotation_spec_set_path(cls, project, annotation_spec_set): return google.api_core.path_template.expand( "projects/{project}/annotationSpecSets/{annotation_spec_set}", project=project, annotation_spec_set=annotation_s...
[ "Return a fully-qualified annotation_spec_set string." ]
Please provide a description of the function:def dataset_path(cls, project, dataset): return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}", project=project, dataset=dataset )
[ "Return a fully-qualified dataset string." ]
Please provide a description of the function:def annotated_dataset_path(cls, project, dataset, annotated_dataset): return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}", project=project, dataset=dat...
[ "Return a fully-qualified annotated_dataset string." ]
Please provide a description of the function:def example_path(cls, project, dataset, annotated_dataset, example): return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}/examples/{example}", project=project, ...
[ "Return a fully-qualified example string." ]
Please provide a description of the function:def data_item_path(cls, project, dataset, data_item): return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}/dataItems/{data_item}", project=project, dataset=dataset, data_item=data...
[ "Return a fully-qualified data_item string." ]
Please provide a description of the function:def instruction_path(cls, project, instruction): return google.api_core.path_template.expand( "projects/{project}/instructions/{instruction}", project=project, instruction=instruction, )
[ "Return a fully-qualified instruction string." ]
Please provide a description of the function:def export_data( self, name, annotated_dataset, output_config, filter_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): ...
[ "\n Exports data and annotations from dataset.\n\n Example:\n >>> from google.cloud import datalabeling_v1beta1\n >>>\n >>> client = datalabeling_v1beta1.DataLabelingServiceClient()\n >>>\n >>> name = client.dataset_path('[PROJECT]', '[DATASET]')\...
Please provide a description of the function:def label_image( self, parent, basic_config, feature, image_classification_config=None, bounding_poly_config=None, polyline_config=None, segmentation_config=None, retry=google.api_core.gapic_v1.method.DE...
[ "\n Starts a labeling task for image. The type of image labeling task is\n configured by feature in the request.\n\n Example:\n >>> from google.cloud import datalabeling_v1beta1\n >>> from google.cloud.datalabeling_v1beta1 import enums\n >>>\n >>> cli...
Please provide a description of the function:def label_video( self, parent, basic_config, feature, video_classification_config=None, object_detection_config=None, object_tracking_config=None, event_config=None, retry=google.api_core.gapic_v1.method...
[ "\n Starts a labeling task for video. The type of video labeling task is\n configured by feature in the request.\n\n Example:\n >>> from google.cloud import datalabeling_v1beta1\n >>> from google.cloud.datalabeling_v1beta1 import enums\n >>>\n >>> cli...
Please provide a description of the function:def label_text( self, parent, basic_config, feature, text_classification_config=None, text_entity_extraction_config=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DE...
[ "\n Starts a labeling task for text. The type of text labeling task is\n configured by feature in the request.\n\n Example:\n >>> from google.cloud import datalabeling_v1beta1\n >>> from google.cloud.datalabeling_v1beta1 import enums\n >>>\n >>> clien...
Please provide a description of the function:def create_instruction( self, parent, instruction, 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 ...
[ "\n Creates an instruction for how data should be labeled.\n\n Example:\n >>> from google.cloud import datalabeling_v1beta1\n >>>\n >>> client = datalabeling_v1beta1.DataLabelingServiceClient()\n >>>\n >>> parent = client.project_path('[PROJECT]')...
Please provide a description of the function:def from_api_repr(cls, resource, config): name = variable_name_from_full_name(resource.get("name")) variable = cls(name=name, config=config) variable._set_properties(resource=resource) return variable
[ "Factory: construct a Variable given its API representation\n\n :type resource: dict\n :param resource: change set representation returned from the API.\n\n :type config: :class:`google.cloud.runtimeconfig.config.Config`\n :param config: The config to which this variable belongs.\n\n ...
Please provide a description of the function:def full_name(self): if not self.name: raise ValueError("Missing variable name.") return "%s/variables/%s" % (self.config.full_name, self.name)
[ "Fully-qualified name of this variable.\n\n Example:\n ``projects/my-project/configs/my-config/variables/my-var``\n\n :rtype: str\n :returns: The full name based on config and variable names.\n\n :raises: :class:`ValueError` if the variable is missing a name.\n " ]
Please provide a description of the function:def value(self): value = self._properties.get("value") if value is not None: value = base64.b64decode(value) return value
[ "Value of the variable, as bytes.\n\n See\n https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables\n\n :rtype: bytes or ``NoneType``\n :returns: The value of the variable or ``None`` if the property\n is not set...
Please provide a description of the function:def update_time(self): value = self._properties.get("updateTime") if value is not None: try: value = datetime.datetime.strptime( value, datetime_helpers._RFC3339_MICROS ) exc...
[ "Retrieve the timestamp at which the variable was updated.\n\n See\n https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables\n\n Returns:\n :class:`~api_core.datetime_helpers.DatetimeWithNanoseconds`,\n :class:`dat...
Please provide a description of the function:def _set_properties(self, resource): self._properties.clear() cleaned = resource.copy() if "name" in cleaned: self.name = variable_name_from_full_name(cleaned.pop("name")) self._properties.update(cleaned)
[ "Update properties from resource in body of ``api_response``\n\n :type resource: dict\n :param resource: variable representation returned from the API.\n " ]
Please provide a description of the function:def from_any_pb(pb_type, any_pb): msg = pb_type() # Unwrap proto-plus wrapped messages. if callable(getattr(pb_type, "pb", None)): msg_pb = pb_type.pb(msg) else: msg_pb = msg # Unpack the Any object and populate the protobuf message...
[ "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.\...
Please provide a description of the function:def get_messages(module): answer = collections.OrderedDict() for name in dir(module): candidate = getattr(module, name) if inspect.isclass(candidate) and issubclass(candidate, message.Message): answer[name] = candidate return answ...
[ "Discovers all protobuf Message classes in a given import module.\n\n Args:\n module (module): A Python module; :func:`dir` will be run against this\n module to find Message subclasses.\n\n Returns:\n dict[str, google.protobuf.message.Message]: A dictionary with the\n Messa...
Please provide a description of the function:def _resolve_subkeys(key, separator="."): parts = key.split(separator, 1) if len(parts) > 1: return parts else: return parts[0], None
[ "Resolve a potentially nested key.\n\n If the key contains the ``separator`` (e.g. ``.``) then the key will be\n split on the first instance of the subkey::\n\n >>> _resolve_subkeys('a.b.c')\n ('a', 'b.c')\n >>> _resolve_subkeys('d|e|f', separator='|')\n ('d', 'e|f')\n\n If not, the...
Please provide a description of the function:def get(msg_or_dict, key, default=_SENTINEL): # We may need to get a nested key. Resolve this. key, subkey = _resolve_subkeys(key) # Attempt to get the value from the two types of objects we know about. # If we get something else, complain. if isins...
[ "Retrieve a key's value from a protobuf Message or dictionary.\n\n Args:\n mdg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the\n object.\n key (str): The key to retrieve from the object.\n default (Any): If the key is not present on the object, and a default\n ...
Please provide a description of the function:def _set_field_on_message(msg, key, value): # Attempt to set the value on the types of objects we know how to deal # with. if isinstance(value, (collections_abc.MutableSequence, tuple)): # Clear the existing repeated protobuf message of any elements ...
[ "Set helper for protobuf Messages." ]
Please provide a description of the function:def set(msg_or_dict, key, value): # Sanity check: Is our target object valid? if not isinstance(msg_or_dict, (collections_abc.MutableMapping, message.Message)): raise TypeError( "set() expected a dict or protobuf message, got {!r}.".format( ...
[ "Set a key's value on a protobuf Message or dictionary.\n\n Args:\n msg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the\n object.\n key (str): The key to set.\n value (Any): The value to set.\n\n Raises:\n TypeError: If ``msg_or_dict`` is not a Message or...
Please provide a description of the function:def setdefault(msg_or_dict, key, value): if not get(msg_or_dict, key, default=None): set(msg_or_dict, key, value)
[ "Set the key on a protobuf Message or dictionary to a given value if the\n current value is falsy.\n\n Because protobuf Messages do not distinguish between unset values and\n falsy ones particularly well (by design), this method treats any falsy\n value (e.g. 0, empty list) as a target to be overwritten...
Please provide a description of the function:def field_mask(original, modified): if original is None and modified is None: return field_mask_pb2.FieldMask() if original is None and modified is not None: original = copy.deepcopy(modified) original.Clear() if modified is None an...
[ "Create a field mask by comparing two messages.\n\n Args:\n original (~google.protobuf.message.Message): the original message.\n If set to None, this field will be interpretted as an empty\n message.\n modified (~google.protobuf.message.Message): the modified message.\n ...
Please provide a description of the function:def topic_path(cls, project, topic): return google.api_core.path_template.expand( "projects/{project}/topics/{topic}", project=project, topic=topic )
[ "Return a fully-qualified topic string." ]
Please provide a description of the function:def snapshot_path(cls, project, snapshot): return google.api_core.path_template.expand( "projects/{project}/snapshots/{snapshot}", project=project, snapshot=snapshot, )
[ "Return a fully-qualified snapshot string." ]
Please provide a description of the function:def create_subscription( self, name, topic, push_config=None, ack_deadline_seconds=None, retain_acked_messages=None, message_retention_duration=None, labels=None, enable_message_ordering=None, ex...
[ "\n Creates a subscription to a given topic. See the resource name rules. If\n the subscription already exists, returns ``ALREADY_EXISTS``. If the\n corresponding topic doesn't exist, returns ``NOT_FOUND``.\n\n If the name is not provided in the request, the server will assign a\n ...
Please provide a description of the function:def seek( self, subscription, time=None, snapshot=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method ...
[ "\n Seeks an existing subscription to a point in time or to a given snapshot,\n whichever is provided in the request. Snapshots are used in\n <a href=\"https://cloud.google.com/pubsub/docs/replay-overview\">Seek</a>\n operations, which allow\n you to manage message acknowledgments...
Please provide a description of the function:def complete_query( self, name, query, page_size, language_codes=None, company_name=None, scope=None, type_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.m...
[ "\n Completes the specified prefix with keyword suggestions.\n Intended for use by a job search auto-complete search box.\n\n Example:\n >>> from google.cloud import talent_v4beta1\n >>>\n >>> client = talent_v4beta1.CompletionClient()\n >>>\n ...
Please provide a description of the function:def _new_session(self): if self.labels: return self._database.session(labels=self.labels) return self._database.session()
[ "Helper for concrete methods creating session instances.\n\n :rtype: :class:`~google.cloud.spanner_v1.session.Session`\n :returns: new session instance.\n " ]
Please provide a description of the function:def bind(self, database): self._database = database while not self._sessions.full(): session = self._new_session() session.create() self._sessions.put(session)
[ "Associate the pool with a database.\n\n :type database: :class:`~google.cloud.spanner_v1.database.Database`\n :param database: database used by the pool: used to create sessions\n when needed.\n " ]
Please provide a description of the function:def get(self, timeout=None): # pylint: disable=arguments-differ if timeout is None: timeout = self.default_timeout session = self._sessions.get(block=True, timeout=timeout) if not session.exists(): session = self._d...
[ "Check a session out from the pool.\n\n :type timeout: int\n :param timeout: seconds to block waiting for an available session\n\n :rtype: :class:`~google.cloud.spanner_v1.session.Session`\n :returns: an existing session from the pool, or a newly-created\n session.\n ...
Please provide a description of the function:def clear(self): while True: try: session = self._sessions.get(block=False) except queue.Empty: break else: session.delete()
[ "Delete all sessions in the pool." ]
Please provide a description of the function:def get(self): try: session = self._sessions.get_nowait() except queue.Empty: session = self._new_session() session.create() else: if not session.exists(): session = self._new_se...
[ "Check a session out from the pool.\n\n :rtype: :class:`~google.cloud.spanner_v1.session.Session`\n :returns: an existing session from the pool, or a newly-created\n session.\n " ]
Please provide a description of the function:def put(self, session): try: self._sessions.put_nowait(session) except queue.Full: try: session.delete() except NotFound: pass
[ "Return a session to the pool.\n\n Never blocks: if the pool is full, the returned session is\n discarded.\n\n :type session: :class:`~google.cloud.spanner_v1.session.Session`\n :param session: the session being returned.\n " ]
Please provide a description of the function:def bind(self, database): self._database = database for _ in xrange(self.size): session = self._new_session() session.create() self.put(session)
[ "Associate the pool with a database.\n\n :type database: :class:`~google.cloud.spanner_v1.database.Database`\n :param database: database used by the pool: used to create sessions\n when needed.\n " ]
Please provide a description of the function:def get(self, timeout=None): # pylint: disable=arguments-differ if timeout is None: timeout = self.default_timeout ping_after, session = self._sessions.get(block=True, timeout=timeout) if _NOW() > ping_after: if not...
[ "Check a session out from the pool.\n\n :type timeout: int\n :param timeout: seconds to block waiting for an available session\n\n :rtype: :class:`~google.cloud.spanner_v1.session.Session`\n :returns: an existing session from the pool, or a newly-created\n session.\n ...
Please provide a description of the function:def put(self, session): self._sessions.put_nowait((_NOW() + self._delta, session))
[ "Return a session to the pool.\n\n Never blocks: if the pool is full, raises.\n\n :type session: :class:`~google.cloud.spanner_v1.session.Session`\n :param session: the session being returned.\n\n :raises: :exc:`six.moves.queue.Full` if the queue is full.\n " ]
Please provide a description of the function:def ping(self): while True: try: ping_after, session = self._sessions.get(block=False) except queue.Empty: # all sessions in use break if ping_after > _NOW(): # oldest session is fresh ...
[ "Refresh maybe-expired sessions in the pool.\n\n This method is designed to be called from a background thread,\n or during the \"idle\" phase of an event loop.\n " ]
Please provide a description of the function:def bind(self, database): super(TransactionPingingPool, self).bind(database) self.begin_pending_transactions()
[ "Associate the pool with a database.\n\n :type database: :class:`~google.cloud.spanner_v1.database.Database`\n :param database: database used by the pool: used to create sessions\n when needed.\n " ]
Please provide a description of the function:def put(self, session): if self._sessions.full(): raise queue.Full txn = session._transaction if txn is None or txn.committed() or txn._rolled_back: session.transaction() self._pending_sessions.put(session...
[ "Return a session to the pool.\n\n Never blocks: if the pool is full, raises.\n\n :type session: :class:`~google.cloud.spanner_v1.session.Session`\n :param session: the session being returned.\n\n :raises: :exc:`six.moves.queue.Full` if the queue is full.\n " ]
Please provide a description of the function:def begin_pending_transactions(self): while not self._pending_sessions.empty(): session = self._pending_sessions.get() session._transaction.begin() super(TransactionPingingPool, self).put(session)
[ "Begin all transactions for sessions added to the pool." ]
Please provide a description of the function:def setup_logging( handler, excluded_loggers=EXCLUDED_LOGGER_DEFAULTS, log_level=logging.INFO ): all_excluded_loggers = set(excluded_loggers + EXCLUDED_LOGGER_DEFAULTS) logger = logging.getLogger() logger.setLevel(log_level) logger.addHandler(handler...
[ "Attach a logging handler to the Python root logger\n\n Excludes loggers that this library itself uses to avoid\n infinite recursion.\n\n :type handler: :class:`logging.handler`\n :param handler: the handler to attach to the global handler\n\n :type excluded_loggers: tuple\n :param excluded_logger...
Please provide a description of the function:def emit(self, record): message = super(CloudLoggingHandler, self).format(record) self.transport.send(record, message, resource=self.resource, labels=self.labels)
[ "Actually log the specified logging record.\n\n Overrides the default emit behavior of ``StreamHandler``.\n\n See https://docs.python.org/2/library/logging.html#handler-objects\n\n :type record: :class:`logging.LogRecord`\n :param record: The record to be logged.\n " ]
Please provide a description of the function:def _query_param_from_api_repr(resource): qp_type = resource["parameterType"] if "arrayType" in qp_type: klass = ArrayQueryParameter elif "structTypes" in qp_type: klass = StructQueryParameter else: klass = ScalarQueryParameter ...
[ "Helper: construct concrete query parameter from JSON resource." ]
Please provide a description of the function:def from_api_repr(cls, resource): name = resource.get("name") type_ = resource["parameterType"]["type"] value = resource["parameterValue"]["value"] converted = _QUERY_PARAMS_FROM_JSON[type_](value, None) return cls(name, type_...
[ "Factory: construct parameter from JSON resource.\n\n :type resource: dict\n :param resource: JSON mapping of parameter\n\n :rtype: :class:`~google.cloud.bigquery.query.ScalarQueryParameter`\n :returns: instance\n " ]
Please provide a description of the function:def to_api_repr(self): value = self.value converter = _SCALAR_VALUE_TO_JSON_PARAM.get(self.type_) if converter is not None: value = converter(value) resource = { "parameterType": {"type": self.type_}, ...
[ "Construct JSON API representation for the parameter.\n\n :rtype: dict\n :returns: JSON mapping\n " ]
Please provide a description of the function:def from_api_repr(cls, resource): array_type = resource["parameterType"]["arrayType"]["type"] if array_type == "STRUCT": return cls._from_api_repr_struct(resource) return cls._from_api_repr_scalar(resource)
[ "Factory: construct parameter from JSON resource.\n\n :type resource: dict\n :param resource: JSON mapping of parameter\n\n :rtype: :class:`~google.cloud.bigquery.query.ArrayQueryParameter`\n :returns: instance\n " ]
Please provide a description of the function:def to_api_repr(self): values = self.values if self.array_type == "RECORD" or self.array_type == "STRUCT": reprs = [value.to_api_repr() for value in values] a_type = reprs[0]["parameterType"] a_values = [repr_["par...
[ "Construct JSON API representation for the parameter.\n\n :rtype: dict\n :returns: JSON mapping\n " ]
Please provide a description of the function:def from_api_repr(cls, resource): name = resource.get("name") instance = cls(name) type_resources = {} types = instance.struct_types for item in resource["parameterType"]["structTypes"]: types[item["name"]] = item[...
[ "Factory: construct parameter from JSON resource.\n\n :type resource: dict\n :param resource: JSON mapping of parameter\n\n :rtype: :class:`~google.cloud.bigquery.query.StructQueryParameter`\n :returns: instance\n " ]
Please provide a description of the function:def to_api_repr(self): s_types = {} values = {} for name, value in self.struct_values.items(): type_ = self.struct_types[name] if type_ in ("STRUCT", "ARRAY"): repr_ = value.to_api_repr() ...
[ "Construct JSON API representation for the parameter.\n\n :rtype: dict\n :returns: JSON mapping\n " ]
Please provide a description of the function:def _set_properties(self, api_response): job_id_present = ( "jobReference" in api_response and "jobId" in api_response["jobReference"] and "projectId" in api_response["jobReference"] ) if not job_id_present...
[ "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 format(self, record): message = super(ContainerEngineHandler, self).format(record) return format_stackdriver_json(record, message)
[ "Format the message into JSON expected by fluentd.\n\n :type record: :class:`~logging.LogRecord`\n :param record: the log record\n\n :rtype: str\n :returns: A JSON string formatted for GKE fluentd.\n " ]
Please provide a description of the function:def analyze_sentiment( self, document, encoding_type=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to ad...
[ "\n Analyzes the sentiment of the provided text.\n\n Example:\n >>> from google.cloud import language_v1\n >>>\n >>> client = language_v1.LanguageServiceClient()\n >>>\n >>> # TODO: Initialize `document`:\n >>> document = {}\n ...
Please provide a description of the function:def _commit_with_retry(client, write_pbs, transaction_id): current_sleep = _INITIAL_SLEEP while True: try: return client._firestore_api.commit( client._database_string, write_pbs, transaction=tr...
[ "Call ``Commit`` on the GAPIC client with retry / sleep.\n\n Retries the ``Commit`` RPC on Unavailable. Usually this RPC-level\n retry is handled by the underlying GAPICd client, but in this case it\n doesn't because ``Commit`` is not always idempotent. But here we know it\n is \"idempotent\"-like becau...
Please provide a description of the function:def _sleep(current_sleep, max_sleep=_MAX_SLEEP, multiplier=_MULTIPLIER): actual_sleep = random.uniform(0.0, current_sleep) time.sleep(actual_sleep) return min(multiplier * current_sleep, max_sleep)
[ "Sleep and produce a new sleep time.\n\n .. _Exponential Backoff And Jitter: https://www.awsarchitectureblog.com/\\\n 2015/03/backoff.html\n\n Select a duration between zero and ``current_sleep``. It might seem\n counterintuitive to have so much jitter, but\n `Expo...
Please provide a description of the function:def _add_write_pbs(self, write_pbs): if self._read_only: raise ValueError(_WRITE_READ_ONLY) super(Transaction, self)._add_write_pbs(write_pbs)
[ "Add `Write`` protobufs to this transaction.\n\n Args:\n write_pbs (List[google.cloud.proto.firestore.v1beta1.\\\n write_pb2.Write]): A list of write protobufs to be added.\n\n Raises:\n ValueError: If this transaction is read-only.\n " ]
Please provide a description of the function:def _options_protobuf(self, retry_id): if retry_id is not None: if self._read_only: raise ValueError(_CANT_RETRY_READ_ONLY) return types.TransactionOptions( read_write=types.TransactionOptions.ReadWrit...
[ "Convert the current object to protobuf.\n\n The ``retry_id`` value is used when retrying a transaction that\n failed (e.g. due to contention). It is intended to be the \"first\"\n transaction that failed (i.e. if multiple retries are needed).\n\n Args:\n retry_id (Union[bytes...
Please provide a description of the function:def _begin(self, retry_id=None): if self.in_progress: msg = _CANT_BEGIN.format(self._id) raise ValueError(msg) transaction_response = self._client._firestore_api.begin_transaction( self._client._database_string, ...
[ "Begin the transaction.\n\n Args:\n retry_id (Optional[bytes]): Transaction ID of a transaction to be\n retried.\n\n Raises:\n ValueError: If the current transaction has already begun.\n " ]
Please provide a description of the function:def _rollback(self): if not self.in_progress: raise ValueError(_CANT_ROLLBACK) try: # NOTE: The response is just ``google.protobuf.Empty``. self._client._firestore_api.rollback( self._client._datab...
[ "Roll back the transaction.\n\n Raises:\n ValueError: If no transaction is in progress.\n " ]
Please provide a description of the function:def _commit(self): if not self.in_progress: raise ValueError(_CANT_COMMIT) commit_response = _commit_with_retry(self._client, self._write_pbs, self._id) self._clean_up() return list(commit_response.write_results)
[ "Transactionally commit the changes accumulated.\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 t...
Please provide a description of the function:def _pre_commit(self, transaction, *args, **kwargs): # Force the ``transaction`` to be not "in progress". transaction._clean_up() transaction._begin(retry_id=self.retry_id) # Update the stored transaction IDs. self.current_id...
[ "Begin transaction and call the wrapped callable.\n\n If the callable raises an exception, the transaction will be rolled\n back. If not, the transaction will be \"ready\" for ``Commit`` (i.e.\n it will have staged writes).\n\n Args:\n transaction (~.firestore_v1beta1.transact...
Please provide a description of the function:def _maybe_commit(self, transaction): try: transaction._commit() return True except exceptions.GoogleAPICallError as exc: if transaction._read_only: raise if isinstance(exc, exceptions....
[ "Try to commit the transaction.\n\n If the transaction is read-write and the ``Commit`` fails with the\n ``ABORTED`` status code, it will be retried. Any other failure will\n not be caught.\n\n Args:\n transaction (~.firestore_v1beta1.transaction.Transaction): The\n ...
Please provide a description of the function:def profile_path(cls, project, tenant, profile): return google.api_core.path_template.expand( "projects/{project}/tenants/{tenant}/profiles/{profile}", project=project, tenant=tenant, profile=profile, )
[ "Return a fully-qualified profile string." ]
Please provide a description of the function:def create_profile( self, parent, profile, 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 time...
[ "\n Creates and returns a new profile.\n\n Example:\n >>> from google.cloud import talent_v4beta1\n >>>\n >>> client = talent_v4beta1.ProfileServiceClient()\n >>>\n >>> parent = client.tenant_path('[PROJECT]', '[TENANT]')\n >>>\n ...
Please provide a description of the function:def get_profile( self, 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. if ...
[ "\n Gets the specified profile.\n\n Example:\n >>> from google.cloud import talent_v4beta1\n >>>\n >>> client = talent_v4beta1.ProfileServiceClient()\n >>>\n >>> name = client.profile_path('[PROJECT]', '[TENANT]', '[PROFILE]')\n >>>\n ...
Please provide a description of the function:def update_profile( self, profile, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retr...
[ "\n Updates the specified profile and returns the updated result.\n\n Example:\n >>> from google.cloud import talent_v4beta1\n >>>\n >>> client = talent_v4beta1.ProfileServiceClient()\n >>>\n >>> # TODO: Initialize `profile`:\n >>> prof...
Please provide a description of the function:def search_profiles( self, parent, request_metadata, profile_query=None, page_size=None, offset=None, disable_spell_check=None, order_by=None, case_sensitive_sort=None, histogram_queries=None, ...
[ "\n Searches for profiles within a tenant.\n\n For example, search by raw queries \"software engineer in Mountain View\"\n or search by structured filters (location filter, education filter,\n etc.).\n\n See ``SearchProfilesRequest`` for more information.\n\n Example:\n ...
Please provide a description of the function:def predict( self, name, payload, params=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add re...
[ "\n Perform an online prediction. The prediction result will be directly\n returned in the response. Available for following ML problems, and their\n expected request payloads:\n\n - Image Classification - Image in .JPEG, .GIF or .PNG format,\n image\\_bytes up to 30MB.\n ...
Please provide a description of the function:def batch_predict( self, name, input_config, output_config, params=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # W...
[ "\n Perform a batch prediction. Unlike the online ``Predict``, batch\n prediction result won't be immediately available in the response.\n Instead, a long running operation object is returned. User can poll the\n operation result via ``GetOperation`` method. Once the operation is\n ...
Please provide a description of the function:def from_service_account_json(cls, json_credentials_path, *args, **kwargs): if "credentials" in kwargs: raise TypeError("credentials must not be in keyword arguments") with io.open(json_credentials_path, "r", encoding="utf-8") as json_fi:...
[ "Factory to retrieve JSON credentials while creating client.\n\n :type json_credentials_path: str\n :param json_credentials_path: The path to a private key file (this file\n was given to you when you created the\n service accoun...
Please provide a description of the function:def _http(self): if self._http_internal is None: self._http_internal = google.auth.transport.requests.AuthorizedSession( self._credentials ) return self._http_internal
[ "Getter for object used for HTTP transport.\n\n :rtype: :class:`~requests.Session`\n :returns: An HTTP object.\n " ]
Please provide a description of the function:def alert_policy_path(cls, project, alert_policy): return google.api_core.path_template.expand( "projects/{project}/alertPolicies/{alert_policy}", project=project, alert_policy=alert_policy, )
[ "Return a fully-qualified alert_policy string." ]
Please provide a description of the function:def alert_policy_condition_path(cls, project, alert_policy, condition): return google.api_core.path_template.expand( "projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}", project=project, alert_policy=a...
[ "Return a fully-qualified alert_policy_condition string." ]
Please provide a description of the function:def _get_many(queue_, max_items=None, max_latency=0): start = time.time() # Always return at least one item. items = [queue_.get()] while max_items is None or len(items) < max_items: try: elapsed = time.time() - start time...
[ "Get multiple items from a Queue.\n\n Gets at least one (blocking) and at most ``max_items`` items\n (non-blocking) from a given Queue. Does not mark the items as done.\n\n Args:\n queue_ (~queue.Queue`): The Queue to get items from.\n max_items (int): The maximum number of items to get. If `...
Please provide a description of the function:def _error_result_to_exception(error_result): reason = error_result.get("reason") status_code = _ERROR_REASON_TO_EXCEPTION.get( reason, http_client.INTERNAL_SERVER_ERROR ) return exceptions.from_http_status( status_code, error_result.get(...
[ "Maps BigQuery error reasons to an exception.\n\n The reasons and their matching HTTP status codes are documented on\n the `troubleshooting errors`_ page.\n\n .. _troubleshooting errors: https://cloud.google.com/bigquery\\\n /troubleshooting-errors\n\n :type error_result: Mapping[str, str]\n :...
Please provide a description of the function:def _from_api_repr(cls, resource): job_id = resource.get("jobId") project = resource.get("projectId") location = resource.get("location") job_ref = cls(job_id, project, location) return job_ref
[ "Returns a job reference for an API resource representation." ]
Please provide a description of the function:def created(self): statistics = self._properties.get("statistics") if statistics is not None: millis = statistics.get("creationTime") if millis is not None: return _helpers._datetime_from_microseconds(millis * ...
[ "Datetime at which the job was created.\n\n :rtype: ``datetime.datetime``, or ``NoneType``\n :returns: the creation time (None until set from the server).\n " ]
Please provide a description of the function:def started(self): statistics = self._properties.get("statistics") if statistics is not None: millis = statistics.get("startTime") if millis is not None: return _helpers._datetime_from_microseconds(millis * 100...
[ "Datetime at which the job was started.\n\n :rtype: ``datetime.datetime``, or ``NoneType``\n :returns: the start time (None until set from the server).\n " ]
Please provide a description of the function:def ended(self): statistics = self._properties.get("statistics") if statistics is not None: millis = statistics.get("endTime") if millis is not None: return _helpers._datetime_from_microseconds(millis * 1000.0)
[ "Datetime at which the job finished.\n\n :rtype: ``datetime.datetime``, or ``NoneType``\n :returns: the end time (None until set from the server).\n " ]
Please provide a description of the function:def _job_statistics(self): statistics = self._properties.get("statistics", {}) return statistics.get(self._JOB_TYPE, {})
[ "Helper for job-type specific statistics-based properties." ]
Please provide a description of the function:def _set_properties(self, api_response): cleaned = api_response.copy() self._scrub_local_properties(cleaned) statistics = cleaned.get("statistics", {}) if "creationTime" in statistics: statistics["creationTime"] = float(s...
[ "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 _get_resource_config(cls, resource): if "jobReference" not in resource or "jobId" not in resource["jobReference"]: raise KeyError( "Resource lacks required identity information: " '["jobReference"]["jobId"]' ...
[ "Helper for :meth:`from_api_repr`\n\n :type resource: dict\n :param resource: resource for the job\n\n :rtype: dict\n :returns: tuple (string, dict), where the first element is the\n job ID and the second contains job-specific configuration.\n :raises: :class:`Key...
Please provide a description of the function:def _begin(self, client=None, retry=DEFAULT_RETRY): if self.state is not None: raise ValueError("Job already begun.") client = self._require_client(client) path = "/projects/%s/jobs" % (self.project,) # jobs.insert is id...
[ "API call: begin the job via a POST request\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/insert\n\n :type client: :class:`~google.cloud.bigquery.client.Client` or\n ``NoneType``\n :param client: the client to use. If not passed, falls bac...
Please provide a description of the function:def exists(self, client=None, retry=DEFAULT_RETRY): client = self._require_client(client) extra_params = {"fields": "id"} if self.location: extra_params["location"] = self.location try: client._call_api( ...
[ "API call: test for the existence of the job via a GET request\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/get\n\n :type client: :class:`~google.cloud.bigquery.client.Client` or\n ``NoneType``\n :param client: the client to use. If not p...
Please provide a description of the function:def reload(self, client=None, retry=DEFAULT_RETRY): client = self._require_client(client) extra_params = {} if self.location: extra_params["location"] = self.location api_response = client._call_api( retry, m...
[ "API call: refresh job properties via a GET request.\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/get\n\n :type client: :class:`~google.cloud.bigquery.client.Client` or\n ``NoneType``\n :param client: the client to use. If not passed, fal...
Please provide a description of the function:def cancel(self, client=None): client = self._require_client(client) extra_params = {} if self.location: extra_params["location"] = self.location api_response = client._connection.api_request( method="POST", ...
[ "API call: cancel job via a POST request\n\n See\n https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/cancel\n\n :type client: :class:`~google.cloud.bigquery.client.Client` or\n ``NoneType``\n :param client: the client to use. If not passed, falls back t...
Please provide a description of the function:def _set_future_result(self): # This must be done in a lock to prevent the polling thread # and main thread from both executing the completion logic # at the same time. with self._completion_lock: # If the operation isn't ...
[ "Set the result or exception from the job if it is complete." ]
Please provide a description of the function:def done(self, retry=DEFAULT_RETRY): # Do not refresh is the state is already done, as the job will not # change once complete. if self.state != _DONE_STATE: self.reload(retry=retry) return self.state == _DONE_STATE
[ "Refresh the job and checks if it is complete.\n\n :type retry: :class:`google.api_core.retry.Retry`\n :param retry: (Optional) How to retry the RPC.\n\n :rtype: bool\n :returns: True if the job is complete, False otherwise.\n " ]
Please provide a description of the function:def result(self, timeout=None, retry=DEFAULT_RETRY): if self.state is None: self._begin(retry=retry) # TODO: modify PollingFuture so it can pass a retry argument to done(). return super(_AsyncJob, self).result(timeout=timeout)
[ "Start the job and wait for it to complete and get the result.\n\n :type timeout: float\n :param timeout:\n How long (in seconds) to wait for job to complete before raising\n a :class:`concurrent.futures.TimeoutError`.\n\n :type retry: :class:`google.api_core.retry.Retry`\...
Please provide a description of the function:def _get_sub_prop(self, key, default=None): return _helpers._get_sub_prop( self._properties, [self._job_type, key], default=default )
[ "Get a value in the ``self._properties[self._job_type]`` dictionary.\n\n Most job properties are inside the dictionary related to the job type\n (e.g. 'copy', 'extract', 'load', 'query'). Use this method to access\n those properties::\n\n self._get_sub_prop('destinationTable')\n\n ...
Please provide a description of the function:def _set_sub_prop(self, key, value): _helpers._set_sub_prop(self._properties, [self._job_type, key], value)
[ "Set a value in the ``self._properties[self._job_type]`` dictionary.\n\n Most job properties are inside the dictionary related to the job type\n (e.g. 'copy', 'extract', 'load', 'query'). Use this method to set\n those properties::\n\n self._set_sub_prop('useLegacySql', False)\n\n ...
Please provide a description of the function:def _del_sub_prop(self, key): _helpers._del_sub_prop(self._properties, [self._job_type, key])
[ "Remove ``key`` from the ``self._properties[self._job_type]`` dict.\n\n Most job properties are inside the dictionary related to the job type\n (e.g. 'copy', 'extract', 'load', 'query'). Use this method to clear\n those properties::\n\n self._del_sub_prop('useLegacySql')\n\n T...