Search is not available for this dataset
text
stringlengths
75
104k
def delete(self, client=None): """API call: delete all entries in a logger via a DELETE request See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs/delete :type client: :class:`~google.cloud.logging.client.Client` or ``NoneType`` ...
def list_entries( self, projects=None, filter_=None, order_by=None, page_size=None, page_token=None, ): """Return a page of log entries. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list :type projects: list ...
def log_text(self, text, **kw): """Add a text entry to be logged during :meth:`commit`. :type text: str :param text: the text entry :type kw: dict :param kw: (optional) additional keyword arguments for the entry. See :class:`~google.cloud.logging.entries.LogE...
def log_struct(self, info, **kw): """Add a struct entry to be logged during :meth:`commit`. :type info: dict :param info: the struct entry :type kw: dict :param kw: (optional) additional keyword arguments for the entry. See :class:`~google.cloud.logging.entri...
def log_proto(self, message, **kw): """Add a protobuf entry to be logged during :meth:`commit`. :type message: protobuf message :param message: the protobuf entry :type kw: dict :param kw: (optional) additional keyword arguments for the entry. See :class:`~go...
def commit(self, client=None): """Send saved log entries as a single API call. :type client: :class:`~google.cloud.logging.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ``client`` stored on the cur...
def full_name(self): """Fully-qualified name of this variable. Example: ``projects/my-project/configs/my-config`` :rtype: str :returns: The full name based on project and config names. :raises: :class:`ValueError` if the config is missing a name. """ if...
def _set_properties(self, api_response): """Update properties from resource in body of ``api_response`` :type api_response: dict :param api_response: response returned from an API call """ self._properties.clear() cleaned = api_response.copy() if "name" in cleane...
def reload(self, client=None): """API call: reload the config via a ``GET`` request. This method will reload the newest data for the config. See https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs/get :type client: :class:`...
def get_variable(self, variable_name, client=None): """API call: get a variable via a ``GET`` request. This will return None if the variable doesn't exist:: >>> from google.cloud import runtimeconfig >>> client = runtimeconfig.Client() >>> config = client.config('my-conf...
def list_variables(self, page_size=None, page_token=None, client=None): """API call: list variables for this config. This only lists variable names, not the values. See https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables/l...
def _bytes_from_json(value, field): """Base64-decode value""" if _not_null(value, field): return base64.standard_b64decode(_to_bytes(value))
def _timestamp_query_param_from_json(value, field): """Coerce 'value' to a datetime, if set or not nullable. Args: value (str): The timestamp. field (.SchemaField): The field corresponding to the value. Returns: Optional[datetime.datetime]: The parsed datetime object from `...
def _datetime_from_json(value, field): """Coerce 'value' to a datetime, if set or not nullable. Args: value (str): The timestamp. field (.SchemaField): The field corresponding to the value. Returns: Optional[datetime.datetime]: The parsed datetime object from ``value`` if t...
def _time_from_json(value, field): """Coerce 'value' to a datetime date, if set or not nullable""" if _not_null(value, field): if len(value) == 8: # HH:MM:SS fmt = _TIMEONLY_WO_MICROS elif len(value) == 15: # HH:MM:SS.micros fmt = _TIMEONLY_W_MICROS else: ...
def _record_from_json(value, field): """Coerce 'value' to a mapping, if set or not nullable.""" if _not_null(value, field): record = {} record_iter = zip(field.fields, value["f"]) for subfield, cell in record_iter: converter = _CELLDATA_FROM_JSON[subfield.field_type] ...
def _row_tuple_from_json(row, schema): """Convert JSON row data to row with appropriate types. Note: ``row['f']`` and ``schema`` are presumed to be of the same length. :type row: dict :param row: A JSON response row to be converted. :type schema: tuple :param schema: A tuple of ...
def _rows_from_json(values, schema): """Convert JSON row data to rows with appropriate types.""" from google.cloud.bigquery import Row field_to_index = _field_to_index_mapping(schema) return [Row(_row_tuple_from_json(r, schema), field_to_index) for r in values]
def _decimal_to_json(value): """Coerce 'value' to a JSON-compatible representation.""" if isinstance(value, decimal.Decimal): value = str(value) return value
def _bytes_to_json(value): """Coerce 'value' to an JSON-compatible representation.""" if isinstance(value, bytes): value = base64.standard_b64encode(value).decode("ascii") return value
def _timestamp_to_json_parameter(value): """Coerce 'value' to an JSON-compatible representation. This version returns the string representation used in query parameters. """ if isinstance(value, datetime.datetime): if value.tzinfo not in (None, UTC): # Convert to UTC and remove the ...
def _timestamp_to_json_row(value): """Coerce 'value' to an JSON-compatible representation. This version returns floating-point seconds value used in row data. """ if isinstance(value, datetime.datetime): value = _microseconds_from_datetime(value) * 1e-6 return value
def _datetime_to_json(value): """Coerce 'value' to an JSON-compatible representation.""" if isinstance(value, datetime.datetime): value = value.strftime(_RFC3339_MICROS_NO_ZULU) return value
def _date_to_json(value): """Coerce 'value' to an JSON-compatible representation.""" if isinstance(value, datetime.date): value = value.isoformat() return value
def _time_to_json(value): """Coerce 'value' to an JSON-compatible representation.""" if isinstance(value, datetime.time): value = value.isoformat() return value
def _scalar_field_to_json(field, row_value): """Maps a field and value to a JSON-safe value. Args: field ( \ :class:`~google.cloud.bigquery.schema.SchemaField`, \ ): The SchemaField to use for type conversion and field name. row_value (any): Value to ...
def _repeated_field_to_json(field, row_value): """Convert a repeated/array field to its JSON representation. Args: field ( \ :class:`~google.cloud.bigquery.schema.SchemaField`, \ ): The SchemaField to use for type conversion and field name. The field mode mus...
def _record_field_to_json(fields, row_value): """Convert a record/struct field to its JSON representation. Args: fields ( \ Sequence[:class:`~google.cloud.bigquery.schema.SchemaField`], \ ): The :class:`~google.cloud.bigquery.schema.SchemaField`s of the recor...
def _field_to_json(field, row_value): """Convert a field into JSON-serializable values. Args: field ( \ :class:`~google.cloud.bigquery.schema.SchemaField`, \ ): The SchemaField to use for type conversion and field name. row_value (Union[ \ Sequence[l...
def _snake_to_camel_case(value): """Convert snake case string to camel case.""" words = value.split("_") return words[0] + "".join(map(str.capitalize, words[1:]))
def _get_sub_prop(container, keys, default=None): """Get a nested value from a dictionary. This method works like ``dict.get(key)``, but for nested values. Arguments: container (dict): A dictionary which may contain other dictionaries as values. keys (iterable): A s...
def _set_sub_prop(container, keys, value): """Set a nested value in a dictionary. Arguments: container (dict): A dictionary which may contain other dictionaries as values. keys (iterable): A sequence of keys to attempt to set the value for. Each item in the s...
def _del_sub_prop(container, keys): """Remove a nested key fro a dictionary. Arguments: container (dict): A dictionary which may contain other dictionaries as values. keys (iterable): A sequence of keys to attempt to clear the value for. Each item in the sequ...
def _build_resource_from_properties(obj, filter_fields): """Build a resource based on a ``_properties`` dictionary, filtered by ``filter_fields``, which follow the name of the Python object. """ partial = {} for filter_field in filter_fields: api_field = obj._PROPERTY_TO_API_FIELD.get(filter...
def get_model(client, model_id): """Sample ID: go/samples-tracker/1510""" # [START bigquery_get_model] from google.cloud import bigquery # TODO(developer): Construct a BigQuery client object. # client = bigquery.Client() # TODO(developer): Set model_id to the ID of the model to fetch. # m...
def _check_database_id(database_id): """Make sure a "Reference" database ID is empty. :type database_id: unicode :param database_id: The ``database_id`` field from a "Reference" protobuf. :raises: :exc:`ValueError` if the ``database_id`` is not empty. """ if database_id != u"": msg = _...
def _add_id_or_name(flat_path, element_pb, empty_allowed): """Add the ID or name from an element to a list. :type flat_path: list :param flat_path: List of accumulated path parts. :type element_pb: :class:`._app_engine_key_pb2.Path.Element` :param element_pb: The element containing ID or name. ...
def _get_flat_path(path_pb): """Convert a legacy "Path" protobuf to a flat path. For example Element { type: "parent" id: 59 } Element { type: "child" name: "naem" } would convert to ``('parent', 59, 'child', 'naem')``. :type pa...
def _to_legacy_path(dict_path): """Convert a tuple of ints and strings in a legacy "Path". .. note: This assumes, but does not verify, that each entry in ``dict_path`` is valid (i.e. doesn't have more than one key out of "name" / "id"). :type dict_path: lsit :param dict_path: ...
def _parse_path(path_args): """Parses positional arguments into key path with kinds and IDs. :type path_args: tuple :param path_args: A tuple from positional arguments. Should be alternating list of kinds (string) and ID/name parts (int or str...
def _combine_args(self): """Sets protected data by combining raw data set from the constructor. If a ``_parent`` is set, updates the ``_flat_path`` and sets the ``_namespace`` and ``_project`` if not already set. :rtype: :class:`list` of :class:`dict` :returns: A list of key pa...
def _clone(self): """Duplicates the Key. Most attributes are simple types, so don't require copying. Other attributes like ``parent`` are long-lived and so we re-use them. :rtype: :class:`google.cloud.datastore.key.Key` :returns: A new ``Key`` instance with the same data as the...
def completed_key(self, id_or_name): """Creates new key from existing partial key by adding final ID/name. :type id_or_name: str or integer :param id_or_name: ID or name to be added to the key. :rtype: :class:`google.cloud.datastore.key.Key` :returns: A new ``Key`` instance wit...
def to_protobuf(self): """Return a protobuf corresponding to the key. :rtype: :class:`.entity_pb2.Key` :returns: The protobuf representing the key. """ key = _entity_pb2.Key() key.partition_id.project_id = self.project if self.namespace: key.partitio...
def to_legacy_urlsafe(self, location_prefix=None): """Convert to a base64 encode urlsafe string for App Engine. This is intended to work with the "legacy" representation of a datastore "Key" used within Google App Engine (a so-called "Reference"). The returned string can be used as the ...
def from_legacy_urlsafe(cls, urlsafe): """Convert urlsafe string to :class:`~google.cloud.datastore.key.Key`. This is intended to work with the "legacy" representation of a datastore "Key" used within Google App Engine (a so-called "Reference"). This assumes that ``urlsafe`` was created...
def _make_parent(self): """Creates a parent key for the current path. Extracts all but the last element in the key path and creates a new key, while still matching the namespace and the project. :rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType` :returns: A ne...
def parent(self): """The parent of the current key. :rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType` :returns: A new ``Key`` instance, whose path consists of all but the last element of current path. If the current key has only one path el...
def from_api_repr(cls, resource, zone): """Factory: construct a record set given its API representation :type resource: dict :param resource: record sets representation returned from the API :type zone: :class:`google.cloud.dns.zone.ManagedZone` :param zone: A zone which holds...
def _thread_main(self): """The entry point for the worker thread. Pulls pending log entries off the queue and writes them in batches to the Cloud Logger. """ _LOGGER.debug("Background thread started.") quit_ = False while True: batch = self._cloud_lo...
def start(self): """Starts the background thread. Additionally, this registers a handler for process exit to attempt to send any pending log entries before shutdown. """ with self._operational_lock: if self.is_alive: return self._thread =...
def stop(self, grace_period=None): """Signals the background thread to stop. This does not terminate the background thread. It simply queues the stop signal. If the main process exits before the background thread processes the stop signal, it will be terminated without finishing ...
def _main_thread_terminated(self): """Callback that attempts to send pending logs before termination.""" if not self.is_alive: return if not self._queue.empty(): print( "Program shutting down, attempting to send %d queued log " "entries to...
def enqueue( self, record, message, resource=None, labels=None, trace=None, span_id=None ): """Queues a log entry to be written by the background thread. :type record: :class:`logging.LogRecord` :param record: Python log record that the handler was called with. :type messag...
def send( self, record, message, resource=None, labels=None, trace=None, span_id=None ): """Overrides Transport.send(). :type record: :class:`logging.LogRecord` :param record: Python log record that the handler was called with. :type message: str :param message: The...
def _tokenize_field_path(path): """Lex a field path into tokens (including dots). Args: path (str): field path to be lexed. Returns: List(str): tokens """ pos = 0 get_token = TOKENS_REGEX.match match = get_token(path) while match is not None: type_ = match.lastgr...
def split_field_path(path): """Split a field path into valid elements (without dots). Args: path (str): field path to be lexed. Returns: List(str): tokens Raises: ValueError: if the path does not match the elements-interspersed- with-dots pattern. """ ...
def parse_field_path(api_repr): """Parse a **field path** from into a list of nested field names. See :func:`field_path` for more on **field paths**. Args: api_repr (str): The unique Firestore api representation which consists of either simple or UTF-8 field names. It canno...
def render_field_path(field_names): """Create a **field path** from a list of nested field names. A **field path** is a ``.``-delimited concatenation of the field names. It is used to represent a nested field. For example, in the data .. code-block: python data = { 'aa': { ...
def get_nested_value(field_path, data): """Get a (potentially nested) value from a dictionary. If the data is nested, for example: .. code-block:: python >>> data { 'top1': { 'middle2': { 'bottom3': 20, 'bottom4': 22, ...
def from_api_repr(cls, api_repr): """Factory: create a FieldPath from the string formatted per the API. Args: api_repr (str): a string path, with non-identifier elements quoted It cannot exceed 1500 characters, and cannot be empty. Returns: (:class:`FieldPath...
def from_string(cls, path_string): """Factory: create a FieldPath from a unicode string representation. This method splits on the character `.` and disallows the characters `~*/[]`. To create a FieldPath whose components have those characters, call the constructor. Args: ...
def eq_or_parent(self, other): """Check whether ``other`` is an ancestor. Returns: (bool) True IFF ``other`` is an ancestor or equal to ``self``, else False. """ return self.parts[: len(other.parts)] == other.parts[: len(self.parts)]
def lineage(self): """Return field paths for all parents. Returns: Set[:class:`FieldPath`] """ indexes = six.moves.range(1, len(self.parts)) return {FieldPath(*self.parts[:index]) for index in indexes}
def get_operation( self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT ): """Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. Example: ...
def list_operations( self, name, filter_, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT, ): """ Lists operations that match the specified filter in the request. Example: >>> from google.api_core import operations_v1 ...
def cancel_operation( self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT ): """Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. Clients can use :meth:`get_oper...
def delete_operation( self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT ): """Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. Example: ...
def config_name_from_full_name(full_name): """Extract the config name from a full resource name. >>> config_name_from_full_name('projects/my-proj/configs/my-config') "my-config" :type full_name: str :param full_name: The full resource name of a config. The full resource name looks like...
def variable_name_from_full_name(full_name): """Extract the variable name from a full resource name. >>> variable_name_from_full_name( 'projects/my-proj/configs/my-config/variables/var-name') "var-name" >>> variable_name_from_full_name( 'projects/my-proj/configs/my-con...
def max(self): """Return the maximum value in this histogram. If there are no values in the histogram at all, return 600. Returns: int: The maximum value in the histogram. """ if len(self._data) == 0: return 600 return next(iter(reversed(sorted(s...
def min(self): """Return the minimum value in this histogram. If there are no values in the histogram at all, return 10. Returns: int: The minimum value in the histogram. """ if len(self._data) == 0: return 10 return next(iter(sorted(self._data.k...
def add(self, value): """Add the value to this histogram. Args: value (int): The value. Values outside of ``10 <= x <= 600`` will be raised to ``10`` or reduced to ``600``. """ # If the value is out of bounds, bring it in bounds. value = int(value) ...
def percentile(self, percent): """Return the value that is the Nth precentile in the histogram. Args: percent (Union[int, float]): The precentile being sought. The default consumer implementations use consistently use ``99``. Returns: int: The value corr...
def job_path(cls, project, location, job): """Return a fully-qualified job string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/jobs/{job}", project=project, location=location, job=job, )
def create_job( self, parent, job, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a job. Example: >>> from google.cloud import scheduler_v1beta1 ...
def reference(self): """A :class:`~google.cloud.bigquery.model.ModelReference` pointing to this model. Read-only. Returns: google.cloud.bigquery.model.ModelReference: pointer to this model. """ ref = ModelReference() ref._proto = self._proto.model_re...
def created(self): """Union[datetime.datetime, None]: Datetime at which the model was created (:data:`None` until set from the server). Read-only. """ value = self._proto.creation_time if value is not None and value != 0: # value will be in milliseconds. ...
def modified(self): """Union[datetime.datetime, None]: Datetime at which the model was last modified (:data:`None` until set from the server). Read-only. """ value = self._proto.last_modified_time if value is not None and value != 0: # value will be in millis...
def expires(self): """Union[datetime.datetime, None]: The datetime when this model expires. If not present, the model will persist indefinitely. Expired models will be deleted and their storage reclaimed. """ value = self._properties.get("expirationTime") if value is not ...
def from_api_repr(cls, resource): """Factory: construct a model resource given its API representation Args: resource (Dict[str, object]): Model resource representation from the API Returns: google.cloud.bigquery.model.Model: Model parsed from ``resource`...
def path(self): """str: URL path for the model's APIs.""" return "/projects/%s/datasets/%s/models/%s" % ( self._proto.project_id, self._proto.dataset_id, self._proto.model_id, )
def from_api_repr(cls, resource): """Factory: construct a model reference given its API representation Args: resource (Dict[str, object]): Model reference representation returned from the API Returns: google.cloud.bigquery.model.ModelReference: ...
def from_string(cls, model_id, default_project=None): """Construct a model reference from model ID string. Args: model_id (str): A model ID in standard SQL format. If ``default_project`` is not specified, this must included a project ID, dataset ...
def lease_tasks( self, parent, lease_duration, max_tasks=None, response_view=None, filter_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Leases tasks ...
def format_stackdriver_json(record, message): """Helper to format a LogRecord in in Stackdriver fluentd format. :rtype: str :returns: JSON str to be written to the log file. """ subsecond, second = math.modf(record.created) payload = { "message": message, "timestamp": {...
def get_trace_id_from_flask(): """Get trace_id from flask request headers. :rtype: str :returns: TraceID in HTTP request headers. """ if flask is None or not flask.request: return None header = flask.request.headers.get(_FLASK_TRACE_HEADER) if header is None: return None ...
def get_trace_id_from_webapp2(): """Get trace_id from webapp2 request headers. :rtype: str :returns: TraceID in HTTP request headers. """ if webapp2 is None: return None try: # get_request() succeeds if we're in the middle of a webapp2 # request, or raises an assertion ...
def get_trace_id_from_django(): """Get trace_id from django request headers. :rtype: str :returns: TraceID in HTTP request headers. """ request = _get_django_request() if request is None: return None header = request.META.get(_DJANGO_TRACE_HEADER) if header is None: re...
def get_trace_id(): """Helper to get trace_id from web application request header. :rtype: str :returns: TraceID in HTTP request headers. """ checkers = ( get_trace_id_from_django, get_trace_id_from_flask, get_trace_id_from_webapp2, ) for checker in checkers: ...
def group_path(cls, project, group): """Return a fully-qualified group string.""" return google.api_core.path_template.expand( "projects/{project}/groups/{group}", project=project, group=group )
def list_groups( self, name, children_of_group=None, ancestors_of_group=None, descendants_of_group=None, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): "...
def list_voices( self, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Returns a list of ``Voice`` supported for synthesis. Example: >>> from google....
def synthesize_speech( self, input_, voice, audio_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Synthesizes speech synchronously: receive results after all text inp...
def ensure_signed_credentials(credentials): """Raise AttributeError if the credentials are unsigned. :type credentials: :class:`google.auth.credentials.Signing` :param credentials: The credentials used to create a private key for signing text. :raises: :exc:`AttributeError` if ...
def get_signed_query_params_v2(credentials, expiration, string_to_sign): """Gets query parameters for creating a signed URL. :type credentials: :class:`google.auth.credentials.Signing` :param credentials: The credentials used to create a private key for signing text. :type expi...
def get_expiration_seconds_v2(expiration): """Convert 'expiration' to a number of seconds in the future. :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] :param expiration: Point in time when the signed URL should expire. :raises: :exc:`TypeError` when expiration is not a valid ...
def get_expiration_seconds_v4(expiration): """Convert 'expiration' to a number of seconds offset from the current time. :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] :param expiration: Point in time when the signed URL should expire. :raises: :exc:`TypeError` when expiration ...
def get_canonical_headers(headers): """Canonicalize headers for signing. See: https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers :type headers: Union[dict|List(Tuple(str,str))] :param headers: (Optional) Additional HTTP headers to be included...
def canonicalize(method, resource, query_parameters, headers): """Canonicalize method, resource :type method: str :param method: The HTTP verb that will be used when requesting the URL. Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the signature will additio...