Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def save_predefined(self, predefined, client=None): predefined = self.validate_predefined(predefined) self._save(None, predefined, client)
[ "Save this ACL for the current bucket using a predefined ACL.\n\n If :attr:`user_project` is set, bills the API request to that project.\n\n :type predefined: str\n :param predefined: An identifier for a predefined ACL. Must be one\n of the keys in :attr:`PREDEFINED_J...
Please provide a description of the function:def incident_path(cls, project, incident): return google.api_core.path_template.expand( "projects/{project}/incidents/{incident}", project=project, incident=incident, )
[ "Return a fully-qualified incident string." ]
Please provide a description of the function:def annotation_path(cls, project, incident, annotation): return google.api_core.path_template.expand( "projects/{project}/incidents/{incident}/annotations/{annotation}", project=project, incident=incident, anno...
[ "Return a fully-qualified annotation string." ]
Please provide a description of the function:def artifact_path(cls, project, incident, artifact): return google.api_core.path_template.expand( "projects/{project}/incidents/{incident}/artifacts/{artifact}", project=project, incident=incident, artifact=art...
[ "Return a fully-qualified artifact string." ]
Please provide a description of the function:def role_assignment_path(cls, project, incident, role_assignment): return google.api_core.path_template.expand( "projects/{project}/incidents/{incident}/roleAssignments/{role_assignment}", project=project, incident=inciden...
[ "Return a fully-qualified role_assignment string." ]
Please provide a description of the function:def subscription_path(cls, project, incident, subscription): return google.api_core.path_template.expand( "projects/{project}/incidents/{incident}/subscriptions/{subscription}", project=project, incident=incident, ...
[ "Return a fully-qualified subscription string." ]
Please provide a description of the function:def tag_path(cls, project, incident, tag): return google.api_core.path_template.expand( "projects/{project}/incidents/{incident}/tags/{tag}", project=project, incident=incident, tag=tag, )
[ "Return a fully-qualified tag string." ]
Please provide a description of the function:def signal_path(cls, project, signal): return google.api_core.path_template.expand( "projects/{project}/signals/{signal}", project=project, signal=signal )
[ "Return a fully-qualified signal string." ]
Please provide a description of the function:def create_annotation( self, parent, annotation, 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 an...
[ "\n Creates an annotation on an existing incident. Only 'text/plain' and\n 'text/markdown' annotations can be created via this method.\n\n Example:\n >>> from google.cloud import irm_v1alpha2\n >>>\n >>> client = irm_v1alpha2.IncidentServiceClient()\n ...
Please provide a description of the function:def escalate_incident( self, incident, update_mask=None, subscriptions=None, tags=None, roles=None, artifacts=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method....
[ "\n Escalates an incident.\n\n Example:\n >>> from google.cloud import irm_v1alpha2\n >>>\n >>> client = irm_v1alpha2.IncidentServiceClient()\n >>>\n >>> # TODO: Initialize `incident`:\n >>> incident = {}\n >>>\n >...
Please provide a description of the function:def send_shift_handoff( self, parent, recipients, subject, cc=None, notes_content_type=None, notes_content=None, incidents=None, preview_only=None, retry=google.api_core.gapic_v1.method.DEFAULT, ...
[ "\n Sends a summary of the shift for oncall handoff.\n\n Example:\n >>> from google.cloud import irm_v1alpha2\n >>>\n >>> client = irm_v1alpha2.IncidentServiceClient()\n >>>\n >>> parent = client.project_path('[PROJECT]')\n >>>\n ...
Please provide a description of the function:def bigtable_admins(self): result = set() for member in self._bindings.get(BIGTABLE_ADMIN_ROLE, ()): result.add(member) return frozenset(result)
[ "Access to bigtable.admin role memebers\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_admins_policy]\n :end-before: [END bigtable_admins_policy]\n " ]
Please provide a description of the function:def bigtable_readers(self): result = set() for member in self._bindings.get(BIGTABLE_READER_ROLE, ()): result.add(member) return frozenset(result)
[ "Access to bigtable.reader role memebers\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_readers_policy]\n :end-before: [END bigtable_readers_policy]\n " ]
Please provide a description of the function:def bigtable_users(self): result = set() for member in self._bindings.get(BIGTABLE_USER_ROLE, ()): result.add(member) return frozenset(result)
[ "Access to bigtable.user role memebers\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_users_policy]\n :end-before: [END bigtable_users_policy]\n " ]
Please provide a description of the function:def bigtable_viewers(self): result = set() for member in self._bindings.get(BIGTABLE_VIEWER_ROLE, ()): result.add(member) return frozenset(result)
[ "Access to bigtable.viewer role memebers\n\n For example:\n\n .. literalinclude:: snippets.py\n :start-after: [START bigtable_viewers_policy]\n :end-before: [END bigtable_viewers_policy]\n " ]
Please provide a description of the function:def from_pb(cls, policy_pb): policy = cls(policy_pb.etag, policy_pb.version) for binding in policy_pb.bindings: policy[binding.role] = sorted(binding.members) return policy
[ "Factory: create a policy from a protobuf message.\n\n Args:\n policy_pb (google.iam.policy_pb2.Policy): message returned by\n ``get_iam_policy`` gRPC API.\n\n Returns:\n :class:`Policy`: the parsed policy\n " ]
Please provide a description of the function:def to_pb(self): return policy_pb2.Policy( etag=self.etag, version=self.version or 0, bindings=[ policy_pb2.Binding(role=role, members=sorted(self[role])) for role in self ], ...
[ "Render a protobuf message.\n\n Returns:\n google.iam.policy_pb2.Policy: a message to be passed to the\n ``set_iam_policy`` gRPC API.\n " ]
Please provide a description of the function:def from_api_repr(cls, resource): etag = resource.get("etag") if etag is not None: resource = resource.copy() resource["etag"] = base64.b64decode(etag.encode("ascii")) return super(Policy, cls).from_api_repr(resource...
[ "Factory: create a policy from a JSON resource.\n\n Overrides the base class version to store :attr:`etag` as bytes.\n\n Args:\n resource (dict): JSON policy resource returned by the\n ``getIamPolicy`` REST API.\n\n Returns:\n :class:`Policy`: the parsed policy\...
Please provide a description of the function:def to_api_repr(self): resource = super(Policy, self).to_api_repr() if self.etag is not None: resource["etag"] = base64.b64encode(self.etag).decode("ascii") return resource
[ "Render a JSON policy resource.\n\n Overrides the base class version to convert :attr:`etag` from bytes\n to JSON-compatible base64-encoded text.\n\n Returns:\n dict: a JSON resource to be passed to the\n ``setIamPolicy`` REST API.\n " ]
Please provide a description of the function:def _check_ddl_statements(value): if not all(isinstance(line, six.string_types) for line in value): raise ValueError("Pass a list of strings") if any("create database" in line.lower() for line in value): raise ValueError("Do not pass a 'CREATE D...
[ "Validate DDL Statements used to define database schema.\n\n See\n https://cloud.google.com/spanner/docs/data-definition-language\n\n :type value: list of string\n :param value: DDL statements, excluding the 'CREATE DATABSE' statement\n\n :rtype: tuple\n :returns: tuple of validated DDL statement ...
Please provide a description of the function:def from_pb(cls, database_pb, instance, pool=None): match = _DATABASE_NAME_RE.match(database_pb.name) if match is None: raise ValueError( "Database protobuf name was not in the " "expected format.", databas...
[ "Creates an instance of this class from a protobuf.\n\n :type database_pb:\n :class:`google.spanner.v2.spanner_instance_admin_pb2.Instance`\n :param database_pb: A instance protobuf object.\n\n :type instance: :class:`~google.cloud.spanner_v1.instance.Instance`\n :param instan...
Please provide a description of the function:def spanner_api(self): if self._spanner_api is None: credentials = self._instance._client.credentials if isinstance(credentials, google.auth.credentials.Scoped): credentials = credentials.with_scopes((SPANNER_DATA_SCOP...
[ "Helper for session-related API calls." ]
Please provide a description of the function:def create(self): api = self._instance._client.database_admin_api metadata = _metadata_with_prefix(self.name) db_name = self.database_id if "-" in db_name: db_name = "`%s`" % (db_name,) future = api.create_databas...
[ "Create this database within its instance\n\n Inclues any configured schema assigned to :attr:`ddl_statements`.\n\n See\n https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.CreateDatabase\n\n :rtype: :class:`~goo...
Please provide a description of the function:def exists(self): api = self._instance._client.database_admin_api metadata = _metadata_with_prefix(self.name) try: api.get_database_ddl(self.name, metadata=metadata) except NotFound: return False retur...
[ "Test whether this database exists.\n\n See\n https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDDL\n\n :rtype: bool\n :returns: True if the database exists, else false.\n " ]
Please provide a description of the function:def reload(self): api = self._instance._client.database_admin_api metadata = _metadata_with_prefix(self.name) response = api.get_database_ddl(self.name, metadata=metadata) self._ddl_statements = tuple(response.statements)
[ "Reload this database.\n\n Refresh any configured schema into :attr:`ddl_statements`.\n\n See\n https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDDL\n\n :raises NotFound: if the database does not exi...
Please provide a description of the function:def update_ddl(self, ddl_statements, operation_id=""): client = self._instance._client api = client.database_admin_api metadata = _metadata_with_prefix(self.name) future = api.update_database_ddl( self.name, ddl_statement...
[ "Update DDL for this database.\n\n Apply any configured schema from :attr:`ddl_statements`.\n\n See\n https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabase\n\n :type ddl_statements: Sequence[str]\n ...
Please provide a description of the function:def drop(self): api = self._instance._client.database_admin_api metadata = _metadata_with_prefix(self.name) api.drop_database(self.name, metadata=metadata)
[ "Drop this database.\n\n See\n https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.DropDatabase\n " ]
Please provide a description of the function:def execute_partitioned_dml(self, dml, params=None, param_types=None): if params is not None: if param_types is None: raise ValueError("Specify 'param_types' when passing 'params'.") params_pb = Struct( ...
[ "Execute a partitionable DML statement.\n\n :type dml: str\n :param dml: DML statement\n\n :type params: dict, {str -> column value}\n :param params: values for parameter replacement. Keys must match\n the names used in ``dml``.\n\n :type param_types: dict[s...
Please provide a description of the function:def batch_snapshot(self, read_timestamp=None, exact_staleness=None): return BatchSnapshot( self, read_timestamp=read_timestamp, exact_staleness=exact_staleness )
[ "Return an object which wraps a batch read / query.\n\n :type read_timestamp: :class:`datetime.datetime`\n :param read_timestamp: Execute all reads at the given timestamp.\n\n :type exact_staleness: :class:`datetime.timedelta`\n :param exact_staleness: Execute all reads at a timestamp th...
Please provide a description of the function:def run_in_transaction(self, func, *args, **kw): # Sanity check: Is there a transaction already running? # If there is, then raise a red flag. Otherwise, mark that this one # is running. if getattr(self._local, "transaction_running", ...
[ "Perform a unit of work in a transaction, retrying on abort.\n\n :type func: callable\n :param func: takes a required positional argument, the transaction,\n and additional positional / keyword arguments as supplied\n by the caller.\n\n :type args: tuple\...
Please provide a description of the function:def from_dict(cls, database, mapping): instance = cls(database) session = instance._session = database.session() session._session_id = mapping["session_id"] snapshot = instance._snapshot = session.snapshot() snapshot._transact...
[ "Reconstruct an instance from a mapping.\n\n :type database: :class:`~google.cloud.spanner.database.Database`\n :param database: database to use\n\n :type mapping: mapping\n :param mapping: serialized state of the instance\n\n :rtype: :class:`BatchSnapshot`\n " ]
Please provide a description of the function:def to_dict(self): session = self._get_session() snapshot = self._get_snapshot() return { "session_id": session._session_id, "transaction_id": snapshot._transaction_id, }
[ "Return state as a dictionary.\n\n Result can be used to serialize the instance and reconstitute\n it later using :meth:`from_dict`.\n\n :rtype: dict\n " ]
Please provide a description of the function:def _get_session(self): if self._session is None: session = self._session = self._database.session() session.create() return self._session
[ "Create session as needed.\n\n .. note::\n\n Caller is responsible for cleaning up the session after\n all partitions have been processed.\n " ]
Please provide a description of the function:def _get_snapshot(self): if self._snapshot is None: self._snapshot = self._get_session().snapshot( read_timestamp=self._read_timestamp, exact_staleness=self._exact_staleness, multi_use=True, ...
[ "Create snapshot if needed." ]
Please provide a description of the function:def generate_read_batches( self, table, columns, keyset, index="", partition_size_bytes=None, max_partitions=None, ): partitions = self._get_snapshot().partition_read( table=table, ...
[ "Start a partitioned batch read operation.\n\n Uses the ``PartitionRead`` API request to initiate the partitioned\n read. Returns a list of batch information needed to perform the\n actual reads.\n\n :type table: str\n :param table: name of the table from which to fetch data\n\n ...
Please provide a description of the function:def process_read_batch(self, batch): kwargs = copy.deepcopy(batch["read"]) keyset_dict = kwargs.pop("keyset") kwargs["keyset"] = KeySet._from_dict(keyset_dict) return self._get_snapshot().read(partition=batch["partition"], **kwargs)
[ "Process a single, partitioned read.\n\n :type batch: mapping\n :param batch:\n one of the mappings returned from an earlier call to\n :meth:`generate_read_batches`.\n\n :rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`\n :returns: a result set in...
Please provide a description of the function:def generate_query_batches( self, sql, params=None, param_types=None, partition_size_bytes=None, max_partitions=None, ): partitions = self._get_snapshot().partition_query( sql=sql, p...
[ "Start a partitioned query operation.\n\n Uses the ``PartitionQuery`` API request to start a partitioned\n query operation. Returns a list of batch information needed to\n peform the actual queries.\n\n :type sql: str\n :param sql: SQL query statement\n\n :type params: dic...
Please provide a description of the function:def process(self, batch): if "query" in batch: return self.process_query_batch(batch) if "read" in batch: return self.process_read_batch(batch) raise ValueError("Invalid batch")
[ "Process a single, partitioned query or read.\n\n :type batch: mapping\n :param batch:\n one of the mappings returned from an earlier call to\n :meth:`generate_query_batches`.\n\n :rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`\n :returns: a res...
Please provide a description of the function:def location_path(cls, project, location): return google.api_core.path_template.expand( "projects/{project}/locations/{location}", project=project, location=location, )
[ "Return a fully-qualified location string." ]
Please provide a description of the function:def model_path(cls, project, location, model): return google.api_core.path_template.expand( "projects/{project}/locations/{location}/models/{model}", project=project, location=location, model=model, )
[ "Return a fully-qualified model string." ]
Please provide a description of the function:def model_evaluation_path(cls, project, location, model, model_evaluation): return google.api_core.path_template.expand( "projects/{project}/locations/{location}/models/{model}/modelEvaluations/{model_evaluation}", project=project, ...
[ "Return a fully-qualified model_evaluation string." ]
Please provide a description of the function:def annotation_spec_path(cls, project, location, dataset, annotation_spec): return google.api_core.path_template.expand( "projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}", project=project, ...
[ "Return a fully-qualified annotation_spec string." ]
Please provide a description of the function:def table_spec_path(cls, project, location, dataset, table_spec): return google.api_core.path_template.expand( "projects/{project}/locations/{location}/datasets/{dataset}/tableSpecs/{table_spec}", project=project, location...
[ "Return a fully-qualified table_spec string." ]
Please provide a description of the function:def column_spec_path(cls, project, location, dataset, table_spec, column_spec): return google.api_core.path_template.expand( "projects/{project}/locations/{location}/datasets/{dataset}/tableSpecs/{table_spec}/columnSpecs/{column_spec}", ...
[ "Return a fully-qualified column_spec string." ]
Please provide a description of the function:def create_dataset( self, parent, dataset, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and time...
[ "\n Creates a dataset.\n\n Example:\n >>> from google.cloud import automl_v1beta1\n >>>\n >>> client = automl_v1beta1.AutoMlClient()\n >>>\n >>> parent = client.location_path('[PROJECT]', '[LOCATION]')\n >>>\n >>> # TODO: Ini...
Please provide a description of the function:def delete_dataset( 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. ...
[ "\n Deletes a dataset and all of its contents. Returns empty response in the\n ``response`` field when it completes, and ``delete_details`` in the\n ``metadata`` field.\n\n Example:\n >>> from google.cloud import automl_v1beta1\n >>>\n >>> client = automl...
Please provide a description of the function:def create_model( self, parent, model, 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 ...
[ "\n Creates a model. Returns a Model in the ``response`` field when it\n completes. When you create a model, several model evaluations are\n created for it: a global evaluation, and one evaluation for each\n annotation spec.\n\n Example:\n >>> from google.cloud import a...
Please provide a description of the function:def exponential_sleep_generator(initial, maximum, multiplier=_DEFAULT_DELAY_MULTIPLIER): delay = initial while True: # Introduce jitter by yielding a delay that is uniformly distributed # to average out to the delay time. yield min(random...
[ "Generates sleep intervals based on the exponential back-off algorithm.\n\n This implements the `Truncated Exponential Back-off`_ algorithm.\n\n .. _Truncated Exponential Back-off:\n https://cloud.google.com/storage/docs/exponential-backoff\n\n Args:\n initial (float): The minimum about of ti...
Please provide a description of the function:def retry_target(target, predicate, sleep_generator, deadline, on_error=None): if deadline is not None: deadline_datetime = datetime_helpers.utcnow() + datetime.timedelta( seconds=deadline ) else: deadline_datetime = None ...
[ "Call a function and retry if it fails.\n\n This is the lowest-level retry helper. Generally, you'll use the\n higher-level retry helper :class:`Retry`.\n\n Args:\n target(Callable): The function to call and retry. This must be a\n nullary function - apply arguments with `functools.partia...
Please provide a description of the function:def open(self): if self.is_active: raise ValueError("Can not open an already open stream.") request_generator = _RequestQueueGenerator( self._request_queue, initial_request=self._initial_request ) call = self....
[ "Opens the stream." ]
Please provide a description of the function:def close(self): if self.call is None: return self._request_queue.put(None) self.call.cancel() self._request_generator = None
[ "Closes the stream." ]
Please provide a description of the function:def send(self, request): if self.call is None: raise ValueError("Can not send() on an RPC that has never been open()ed.") # Don't use self.is_active(), as ResumableBidiRpc will overload it # to mean something semantically differe...
[ "Queue a message to be sent on the stream.\n\n Send is non-blocking.\n\n If the underlying RPC has been closed, this will raise.\n\n Args:\n request (protobuf.Message): The request to send.\n " ]
Please provide a description of the function:def _recoverable(self, method, *args, **kwargs): while True: try: return method(*args, **kwargs) except Exception as exc: with self._operational_lock: _LOGGER.debug("Call to retryab...
[ "Wraps a method to recover the stream and retry on error.\n\n If a retryable error occurs while making the call, then the stream will\n be re-opened and the method will be retried. This happens indefinitely\n so long as the error is a retryable one. If an error occurs while\n re-opening ...
Please provide a description of the function:def start(self): with self._operational_lock: ready = threading.Event() thread = threading.Thread( name=_BIDIRECTIONAL_CONSUMER_NAME, target=self._thread_main, args=(ready,) ...
[ "Start the background thread and begin consuming the thread." ]
Please provide a description of the function:def stop(self): with self._operational_lock: self._bidi_rpc.close() if self._thread is not None: # Resume the thread to wake it up in case it is sleeping. self.resume() self._thread.joi...
[ "Stop consuming the stream and shutdown the background thread." ]
Please provide a description of the function:def resume(self): with self._wake: self._paused = False self._wake.notifyAll()
[ "Resumes the response stream." ]
Please provide a description of the function:def project_path(cls, user, project): return google.api_core.path_template.expand( "users/{user}/projects/{project}", user=user, project=project )
[ "Return a fully-qualified project string." ]
Please provide a description of the function:def fingerprint_path(cls, user, fingerprint): return google.api_core.path_template.expand( "users/{user}/sshPublicKeys/{fingerprint}", user=user, fingerprint=fingerprint, )
[ "Return a fully-qualified fingerprint string." ]
Please provide a description of the function:def delete_posix_account( 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. ...
[ "\n Deletes a POSIX account.\n\n Example:\n >>> from google.cloud import oslogin_v1\n >>>\n >>> client = oslogin_v1.OsLoginServiceClient()\n >>>\n >>> name = client.project_path('[USER]', '[PROJECT]')\n >>>\n >>> client.delet...
Please provide a description of the function:def import_ssh_public_key( self, parent, ssh_public_key, project_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the...
[ "\n Adds an SSH public key and returns the profile information. Default POSIX\n account information is set when no username and UID exist as part of the\n login profile.\n\n Example:\n >>> from google.cloud import oslogin_v1\n >>>\n >>> client = oslogin_v...
Please provide a description of the function:def update_ssh_public_key( self, name, ssh_public_key, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the ...
[ "\n Updates an SSH public key and returns the profile information. This method\n supports patch semantics.\n\n Example:\n >>> from google.cloud import oslogin_v1\n >>>\n >>> client = oslogin_v1.OsLoginServiceClient()\n >>>\n >>> name = clie...
Please provide a description of the function:def _gc_rule_from_pb(gc_rule_pb): rule_name = gc_rule_pb.WhichOneof("rule") if rule_name is None: return None if rule_name == "max_num_versions": return MaxVersionsGCRule(gc_rule_pb.max_num_versions) elif rule_name == "max_age": ...
[ "Convert a protobuf GC rule to a native object.\n\n :type gc_rule_pb: :class:`.table_v2_pb2.GcRule`\n :param gc_rule_pb: The GC rule to convert.\n\n :rtype: :class:`GarbageCollectionRule` or :data:`NoneType <types.NoneType>`\n :returns: An instance of one of the native rules defined\n in :m...
Please provide a description of the function:def to_pb(self): max_age = _helpers._timedelta_to_duration_pb(self.max_age) return table_v2_pb2.GcRule(max_age=max_age)
[ "Converts the garbage collection rule to a protobuf.\n\n :rtype: :class:`.table_v2_pb2.GcRule`\n :returns: The converted current object.\n " ]
Please provide a description of the function:def to_pb(self): union = table_v2_pb2.GcRule.Union(rules=[rule.to_pb() for rule in self.rules]) return table_v2_pb2.GcRule(union=union)
[ "Converts the union into a single GC rule as a protobuf.\n\n :rtype: :class:`.table_v2_pb2.GcRule`\n :returns: The converted current object.\n " ]
Please provide a description of the function:def to_pb(self): intersection = table_v2_pb2.GcRule.Intersection( rules=[rule.to_pb() for rule in self.rules] ) return table_v2_pb2.GcRule(intersection=intersection)
[ "Converts the intersection into a single GC rule as a protobuf.\n\n :rtype: :class:`.table_v2_pb2.GcRule`\n :returns: The converted current object.\n " ]
Please provide a description of the function:def to_pb(self): if self.gc_rule is None: return table_v2_pb2.ColumnFamily() else: return table_v2_pb2.ColumnFamily(gc_rule=self.gc_rule.to_pb())
[ "Converts the column family to a protobuf.\n\n :rtype: :class:`.table_v2_pb2.ColumnFamily`\n :returns: The converted current object.\n " ]
Please provide a description of the function:def create(self): column_family = self.to_pb() modification = table_admin_v2_pb2.ModifyColumnFamiliesRequest.Modification( id=self.column_family_id, create=column_family ) client = self._table._instance._client # ...
[ "Create this column family.\n\n For example:\n\n .. literalinclude:: snippets_table.py\n :start-after: [START bigtable_create_column_family]\n :end-before: [END bigtable_create_column_family]\n\n " ]
Please provide a description of the function:def delete(self): modification = table_admin_v2_pb2.ModifyColumnFamiliesRequest.Modification( id=self.column_family_id, drop=True ) client = self._table._instance._client # data it contains are the GC rule and the column ...
[ "Delete this column family.\n\n For example:\n\n .. literalinclude:: snippets_table.py\n :start-after: [START bigtable_delete_column_family]\n :end-before: [END bigtable_delete_column_family]\n\n " ]
Please provide a description of the function:def _maybe_wrap_exception(exception): if isinstance(exception, grpc.RpcError): return exceptions.from_grpc_error(exception) return exception
[ "Wraps a gRPC exception class, if needed." ]
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.\n " ]
Please provide a description of the function:def _on_rpc_done(self, future): _LOGGER.info("RPC termination has signaled manager shutdown.") future = _maybe_wrap_exception(future) thread = threading.Thread( name=_RPC_ERROR_THREAD_NAME, target=self.close, kwargs={"reason": fut...
[ "Triggered whenever the underlying RPC terminates without recovery.\n\n This is typically triggered from one of two threads: the background\n consumer thread (when calling ``recv()`` produces a non-recoverable\n error) or the grpc management thread (when cancelling the RPC).\n\n This met...
Please provide a description of the function:def for_document( cls, document_ref, snapshot_callback, snapshot_class_instance, reference_class_instance, ): return cls( document_ref, document_ref._client, { "d...
[ "\n Creates a watch snapshot listener for a document. snapshot_callback\n receives a DocumentChange object, but may also start to get\n targetChange and such soon\n\n Args:\n document_ref: Reference to Document\n snapshot_callback: callback to be called on snapshot\...
Please provide a description of the function:def on_snapshot(self, proto): TargetChange = firestore_pb2.TargetChange target_changetype_dispatch = { TargetChange.NO_CHANGE: self._on_snapshot_target_change_no_change, TargetChange.ADD: self._on_snapshot_target_change_add, ...
[ "\n Called everytime there is a response from listen. Collect changes\n and 'push' the changes in a batch to the customer when we receive\n 'current' from the listen response.\n\n Args:\n listen_response(`google.cloud.firestore_v1beta1.types.ListenResponse`):\n ...
Please provide a description of the function:def push(self, read_time, next_resume_token): deletes, adds, updates = Watch._extract_changes( self.doc_map, self.change_map, read_time ) updated_tree, updated_map, appliedChanges = self._compute_snapshot( self.doc_tr...
[ "\n Assembles a new snapshot from the current set of changes and invokes\n the user's callback. Clears the current changes on completion.\n " ]
Please provide a description of the function:def _current_size(self): deletes, adds, _ = Watch._extract_changes(self.doc_map, self.change_map, None) return len(self.doc_map) + len(adds) - len(deletes)
[ "\n Returns the current count of all documents, including the changes from\n the current changeMap.\n " ]
Please provide a description of the function:def _reset_docs(self): _LOGGER.debug("resetting documents") self.change_map.clear() self.resume_token = None # Mark each document as deleted. If documents are not deleted # they will be sent again by the server. for s...
[ "\n Helper to clear the docs on RESET or filter mismatch.\n " ]
Please provide a description of the function:def build_api_url( cls, path, query_params=None, api_base_url=None, api_version=None ): url = cls.API_URL_TEMPLATE.format( api_base_url=(api_base_url or cls.API_BASE_URL), api_version=(api_version or cls.API_VERSION), ...
[ "Construct an API url given a few components, some optional.\n\n Typically, you shouldn't need to use this method.\n\n :type path: str\n :param path: The path to the resource (ie, ``'/b/bucket-name'``).\n\n :type query_params: dict or list\n :param query_params: A dictionary of ke...
Please provide a description of the function:def _make_request( self, method, url, data=None, content_type=None, headers=None, target_object=None, ): headers = headers or {} headers.update(self._EXTRA_HEADERS) headers["Accept-E...
[ "A low level method to send a request to the API.\n\n Typically, you shouldn't need to use this method.\n\n :type method: str\n :param method: The HTTP method to use in the request.\n\n :type url: str\n :param url: The URL to send the request to.\n\n :type data: str\n ...
Please provide a description of the function:def _do_request( self, method, url, headers, data, target_object ): # pylint: disable=unused-argument return self.http.request(url=url, method=method, headers=headers, data=data)
[ "Low-level helper: perform the actual API request over HTTP.\n\n Allows batch context managers to override and defer a request.\n\n :type method: str\n :param method: The HTTP method to use in the request.\n\n :type url: str\n :param url: The URL to send the request to.\n\n ...
Please provide a description of the function:def api_request( self, method, path, query_params=None, data=None, content_type=None, headers=None, api_base_url=None, api_version=None, expect_json=True, _target_object=None, ): ...
[ "Make a request over the HTTP transport to the API.\n\n You shouldn't need to use this method, but if you plan to\n interact with the API using these primitives, this is the\n correct one to use.\n\n :type method: str\n :param method: The HTTP method name (ie, ``GET``, ``POST``, e...
Please provide a description of the function:def _build_label_filter(category, *args, **kwargs): terms = list(args) for key, value in six.iteritems(kwargs): if value is None: continue suffix = None if key.endswith( ("_prefix", "_suffix", "_greater", "_greate...
[ "Construct a filter string to filter on metric or resource labels." ]
Please provide a description of the function:def select_interval(self, end_time, start_time=None): new_query = copy.deepcopy(self) new_query._end_time = end_time new_query._start_time = start_time return new_query
[ "Copy the query and set the query time interval.\n\n Example::\n\n import datetime\n\n now = datetime.datetime.utcnow()\n query = query.select_interval(\n end_time=now,\n start_time=now - datetime.timedelta(minutes=5))\n\n As a convenience...
Please provide a description of the function:def select_group(self, group_id): new_query = copy.deepcopy(self) new_query._filter.group_id = group_id return new_query
[ "Copy the query and add filtering by group.\n\n Example::\n\n query = query.select_group('1234567')\n\n :type group_id: str\n :param group_id: The ID of a group to filter by.\n\n :rtype: :class:`Query`\n :returns: The new query object.\n " ]
Please provide a description of the function:def select_projects(self, *args): new_query = copy.deepcopy(self) new_query._filter.projects = args return new_query
[ "Copy the query and add filtering by monitored projects.\n\n This is only useful if the target project represents a Stackdriver\n account containing the specified monitored projects.\n\n Examples::\n\n query = query.select_projects('project-1')\n query = query.select_proje...
Please provide a description of the function:def select_resources(self, *args, **kwargs): new_query = copy.deepcopy(self) new_query._filter.select_resources(*args, **kwargs) return new_query
[ "Copy the query and add filtering by resource labels.\n\n Examples::\n\n query = query.select_resources(zone='us-central1-a')\n query = query.select_resources(zone_prefix='europe-')\n query = query.select_resources(resource_type='gce_instance')\n\n A keyword argument `...
Please provide a description of the function:def select_metrics(self, *args, **kwargs): new_query = copy.deepcopy(self) new_query._filter.select_metrics(*args, **kwargs) return new_query
[ "Copy the query and add filtering by metric labels.\n\n Examples::\n\n query = query.select_metrics(instance_name='myinstance')\n query = query.select_metrics(instance_name_prefix='mycluster-')\n\n A keyword argument ``<label>=<value>`` ordinarily generates a filter\n expr...
Please provide a description of the function:def align(self, per_series_aligner, seconds=0, minutes=0, hours=0): new_query = copy.deepcopy(self) new_query._per_series_aligner = per_series_aligner new_query._alignment_period_seconds = seconds + 60 * (minutes + 60 * hours) return ...
[ "Copy the query and add temporal alignment.\n\n If ``per_series_aligner`` is not :data:`Aligner.ALIGN_NONE`, each time\n series will contain data points only on the period boundaries.\n\n Example::\n\n from google.cloud.monitoring import enums\n query = query.align(\n ...
Please provide a description of the function:def reduce(self, cross_series_reducer, *group_by_fields): new_query = copy.deepcopy(self) new_query._cross_series_reducer = cross_series_reducer new_query._group_by_fields = group_by_fields return new_query
[ "Copy the query and add cross-series reduction.\n\n Cross-series reduction combines time series by aggregating their\n data points.\n\n For example, you could request an aggregated time series for each\n combination of project and zone as follows::\n\n from google.cloud.monito...
Please provide a description of the function:def iter(self, headers_only=False, page_size=None): if self._end_time is None: raise ValueError("Query time interval not specified.") params = self._build_query_params(headers_only, page_size) for ts in self._client.list_time_ser...
[ "Yield all time series objects selected by the query.\n\n The generator returned iterates over\n :class:`~google.cloud.monitoring_v3.types.TimeSeries` objects\n containing points ordered from oldest to newest.\n\n Note that the :class:`Query` object itself is an iterable, such that\n ...
Please provide a description of the function:def _build_query_params(self, headers_only=False, page_size=None): params = {"name": self._project_path, "filter_": self.filter} params["interval"] = types.TimeInterval() params["interval"].end_time.FromDatetime(self._end_time) if se...
[ "Return key-value pairs for the list_time_series API call.\n\n :type headers_only: bool\n :param headers_only:\n Whether to omit the point data from the\n :class:`~google.cloud.monitoring_v3.types.TimeSeries` objects.\n\n :type page_size: int\n :param page_size:\n...
Please provide a description of the function:def from_api_repr(cls, resource, client): project = cls(project_id=resource["projectId"], client=client) project.set_properties_from_api_repr(resource) return project
[ "Factory: construct a project given its API representation.\n\n :type resource: dict\n :param resource: project resource representation returned from the API\n\n :type client: :class:`google.cloud.resource_manager.client.Client`\n :param client: The Client used with this project.\n\n ...
Please provide a description of the function:def set_properties_from_api_repr(self, resource): self.name = resource.get("name") self.number = resource["projectNumber"] self.labels = resource.get("labels", {}) self.status = resource["lifecycleState"] if "parent" in resour...
[ "Update specific properties from its API representation." ]
Please provide a description of the function:def create(self, client=None): client = self._require_client(client) data = {"projectId": self.project_id, "name": self.name, "labels": self.labels} resp = client._connection.api_request( method="POST", path="/projects", data=dat...
[ "API call: create the project via a ``POST`` request.\n\n See\n https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/create\n\n :type client: :class:`google.cloud.resource_manager.client.Client` or\n :data:`NoneType <types.NoneType>`\n :param cl...
Please provide a description of the function:def update(self, client=None): client = self._require_client(client) data = {"name": self.name, "labels": self.labels, "parent": self.parent} resp = client._connection.api_request(method="PUT", path=self.path, data=data) self.set_pr...
[ "API call: update the project via a ``PUT`` request.\n\n See\n https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/update\n\n :type client: :class:`google.cloud.resource_manager.client.Client` or\n :data:`NoneType <types.NoneType>`\n :param cli...
Please provide a description of the function:def delete(self, client=None, reload_data=False): client = self._require_client(client) client._connection.api_request(method="DELETE", path=self.path) # If the reload flag is set, reload the project. if reload_data: self...
[ "API call: delete the project via a ``DELETE`` request.\n\n See\n https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/delete\n\n This actually changes the status (``lifecycleState``) from ``ACTIVE``\n to ``DELETE_REQUESTED``.\n Later (it's not specified when...
Please provide a description of the function:def _get_meaning(value_pb, is_list=False): meaning = None if is_list: # An empty list will have no values, hence no shared meaning # set among them. if len(value_pb.array_value.values) == 0: return None # We check amo...
[ "Get the meaning from a protobuf value.\n\n :type value_pb: :class:`.entity_pb2.Value`\n :param value_pb: The protobuf value to be checked for an\n associated meaning.\n\n :type is_list: bool\n :param is_list: Boolean indicating if the ``value_pb`` contains\n a lis...
Please provide a description of the function:def entity_from_protobuf(pb): key = None if pb.HasField("key"): # Message field (Key) key = key_from_protobuf(pb.key) entity_props = {} entity_meanings = {} exclude_from_indexes = [] for prop_name, value_pb in _property_tuples(pb): ...
[ "Factory method for creating an entity based on a protobuf.\n\n The protobuf should be one returned from the Cloud Datastore\n Protobuf API.\n\n :type pb: :class:`.entity_pb2.Entity`\n :param pb: The Protobuf representing the entity.\n\n :rtype: :class:`google.cloud.datastore.entity.Entity`\n :ret...
Please provide a description of the function:def _set_pb_meaning_from_entity(entity, name, value, value_pb, is_list=False): if name not in entity._meanings: return meaning, orig_value = entity._meanings[name] # Only add the meaning back to the protobuf if the value is # unchanged from when...
[ "Add meaning information (from an entity) to a protobuf.\n\n :type entity: :class:`google.cloud.datastore.entity.Entity`\n :param entity: The entity to be turned into a protobuf.\n\n :type name: str\n :param name: The name of the property.\n\n :type value: object\n :param value: The current value ...
Please provide a description of the function:def entity_to_protobuf(entity): entity_pb = entity_pb2.Entity() if entity.key is not None: key_pb = entity.key.to_protobuf() entity_pb.key.CopyFrom(key_pb) for name, value in entity.items(): value_is_list = isinstance(value, list) ...
[ "Converts an entity into a protobuf.\n\n :type entity: :class:`google.cloud.datastore.entity.Entity`\n :param entity: The entity to be turned into a protobuf.\n\n :rtype: :class:`.entity_pb2.Entity`\n :returns: The protobuf representing the entity.\n " ]
Please provide a description of the function:def get_read_options(eventual, transaction_id): if transaction_id is None: if eventual: return datastore_pb2.ReadOptions( read_consistency=datastore_pb2.ReadOptions.EVENTUAL ) else: return datastore...
[ "Validate rules for read options, and assign to the request.\n\n Helper method for ``lookup()`` and ``run_query``.\n\n :type eventual: bool\n :param eventual: Flag indicating if ``EVENTUAL`` or ``STRONG``\n consistency should be used.\n\n :type transaction_id: bytes\n :param trans...