text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(self, table, columns, keyset, index="", limit=0, partition=None):
"""Perform a ``StreamingRead`` API request for rows in a table. :type table: str :para... |
if self._read_request_count > 0:
if not self._multi_use:
raise ValueError("Cannot re-use single-use snapshot.")
if self._transaction_id is None:
raise ValueError("Transaction ID pending.")
database = self._session._database
api = database... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute_sql( self, sql, params=None, param_types=None, query_mode=None, partition=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core... |
if self._read_request_count > 0:
if not self._multi_use:
raise ValueError("Cannot re-use single-use snapshot.")
if self._transaction_id is None:
raise ValueError("Transaction ID pending.")
if params is not None:
if param_types is None... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def partition_read( self, table, columns, keyset, index="", partition_size_bytes=None, max_partitions=None, ):
"""Perform a ``ParitionRead`` API request for rows... |
if not self._multi_use:
raise ValueError("Cannot use single-use snapshot.")
if self._transaction_id is None:
raise ValueError("Transaction not started.")
database = self._session._database
api = database.spanner_api
metadata = _metadata_with_prefix(data... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def partition_query( self, sql, params=None, param_types=None, partition_size_bytes=None, max_partitions=None, ):
"""Perform a ``ParitionQuery`` API request. :ty... |
if not self._multi_use:
raise ValueError("Cannot use single-use snapshot.")
if self._transaction_id is None:
raise ValueError("Transaction not started.")
if params is not None:
if param_types is None:
raise ValueError("Specify 'param_types' ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def begin(self):
"""Begin a read-only transaction on the database. :rtype: bytes :returns: the ID for the newly-begun transaction. :raises ValueError: if the tra... |
if not self._multi_use:
raise ValueError("Cannot call 'begin' on single-use snapshots")
if self._transaction_id is not None:
raise ValueError("Read-only transaction already begun")
if self._read_request_count > 0:
raise ValueError("Read-only transaction alr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_user_agent(self):
"""Returns the user-agent string for this client info.""" |
# Note: the order here is important as the internal metrics system
# expects these items to be in specific locations.
ua = ""
if self.user_agent is not None:
ua += "{user_agent} "
ua += "gl-python/{python_version} "
if self.grpc_version is not None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_trace_api(client):
""" Create an instance of the gapic Trace API. Args: client (~google.cloud.trace.client.Client):
The client that holds configuration... |
generated = trace_service_client.TraceServiceClient(
credentials=client._credentials, client_info=_CLIENT_INFO
)
return _TraceAPI(generated, client) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _item_to_bucket(iterator, item):
"""Convert a JSON bucket to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param itera... |
name = item.get("name")
bucket = Bucket(iterator.client, name)
bucket._set_properties(item)
return bucket |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_service_account_email(self, project=None):
"""Get the email address of the project's GCS service account :type project: str :param project: (Optional) Pr... |
if project is None:
project = self.project
path = "/projects/%s/serviceAccount" % (project,)
api_response = self._base_connection.api_request(method="GET", path=path)
return api_response["email_address"] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bucket(self, bucket_name, user_project=None):
"""Factory constructor for bucket object. .. note:: This will not make an HTTP request; it simply instantiates ... |
return Bucket(client=self, name=bucket_name, user_project=user_project) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_bucket(self, bucket_name):
"""Get a bucket by name. If the bucket isn't found, this will raise a :class:`google.cloud.exceptions.NotFound`. For example: ... |
bucket = Bucket(self, name=bucket_name)
bucket.reload(client=self)
return bucket |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_buckets( self, max_results=None, page_token=None, prefix=None, projection="noAcl", fields=None, project=None, ):
"""Get all buckets in the project assoc... |
if project is None:
project = self.project
if project is None:
raise ValueError("Client project not set: pass an explicit project.")
extra_params = {"project": project}
if prefix is not None:
extra_params["prefix"] = prefix
extra_params["... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_job_id(job_id, prefix=None):
"""Construct an ID for a new job. :type job_id: str or ``NoneType`` :param job_id: the user-provided job ID :type prefix: ... |
if job_id is not None:
return job_id
elif prefix is not None:
return str(prefix) + str(uuid.uuid4())
else:
return str(uuid.uuid4()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_mode(stream):
"""Check that a stream was opened in read-binary mode. :type stream: IO[bytes] :param stream: A bytes IO object open for reading. :raise... |
mode = getattr(stream, "mode", None)
if isinstance(stream, gzip.GzipFile):
if mode != gzip.READ:
raise ValueError(
"Cannot upload gzip files opened in write mode: use "
"gzip.GzipFile(filename, mode='rb')"
)
else:
if mode is not None... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_service_account_email(self, project=None):
"""Get the email address of the project's BigQuery service account Note: This is the service account that BigQ... |
if project is None:
project = self.project
path = "/projects/%s/serviceAccount" % (project,)
api_response = self._connection.api_request(method="GET", path=path)
return api_response["email"] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_projects(self, max_results=None, page_token=None, retry=DEFAULT_RETRY):
"""List projects for the project associated with this client. See https://cloud.... |
return page_iterator.HTTPIterator(
client=self,
api_request=functools.partial(self._call_api, retry),
path="/projects",
item_to_value=_item_to_project,
items_key="projects",
page_token=page_token,
max_results=max_results,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_datasets( self, project=None, include_all=False, filter=None, max_results=None, page_token=None, retry=DEFAULT_RETRY, ):
"""List datasets for the projec... |
extra_params = {}
if project is None:
project = self.project
if include_all:
extra_params["all"] = True
if filter:
# TODO: consider supporting a dict of label -> value for filter,
# and converting it into a string here.
extra_p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dataset(self, dataset_id, project=None):
"""Construct a reference to a dataset. :type dataset_id: str :param dataset_id: ID of the dataset. :type project: st... |
if project is None:
project = self.project
return DatasetReference(project, dataset_id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_dataset(self, dataset_ref, retry=DEFAULT_RETRY):
"""Fetch the dataset referenced by ``dataset_ref`` Args: dataset_ref (Union[ \ :class:`~google.cloud.big... |
if isinstance(dataset_ref, str):
dataset_ref = DatasetReference.from_string(
dataset_ref, default_project=self.project
)
api_response = self._call_api(retry, method="GET", path=dataset_ref.path)
return Dataset.from_api_repr(api_response) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_table(self, table, retry=DEFAULT_RETRY):
"""Fetch the table referenced by ``table``. Args: table (Union[ \ :class:`~google.cloud.bigquery.table.Table`, \... |
table_ref = _table_arg_to_table_ref(table, default_project=self.project)
api_response = self._call_api(retry, method="GET", path=table_ref.path)
return Table.from_api_repr(api_response) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_dataset(self, dataset, fields, retry=DEFAULT_RETRY):
"""Change some fields of a dataset. Use ``fields`` to specify which fields to update. At least on... |
partial = dataset._build_resource(fields)
if dataset.etag is not None:
headers = {"If-Match": dataset.etag}
else:
headers = None
api_response = self._call_api(
retry, method="PATCH", path=dataset.path, data=partial, headers=headers
)
r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_table(self, table, fields, retry=DEFAULT_RETRY):
"""Change some fields of a table. Use ``fields`` to specify which fields to update. At least one fiel... |
partial = table._build_resource(fields)
if table.etag is not None:
headers = {"If-Match": table.etag}
else:
headers = None
api_response = self._call_api(
retry, method="PATCH", path=table.path, data=partial, headers=headers
)
return Ta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_query_results( self, job_id, retry, project=None, timeout_ms=None, location=None ):
"""Get the query results object for a query job. Arguments: job_id (... |
extra_params = {"maxResults": 0}
if project is None:
project = self.project
if timeout_ms is not None:
extra_params["timeoutMs"] = timeout_ms
if location is None:
location = self.location
if location is not None:
extra_params[... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def job_from_resource(self, resource):
"""Detect correct job type from resource and instantiate. :type resource: dict :param resource: one job resource from API ... |
config = resource.get("configuration", {})
if "load" in config:
return job.LoadJob.from_api_repr(resource, self)
elif "copy" in config:
return job.CopyJob.from_api_repr(resource, self)
elif "extract" in config:
return job.ExtractJob.from_api_repr(reso... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cancel_job(self, job_id, project=None, location=None, retry=DEFAULT_RETRY):
"""Attempt to cancel a job from a job ID. See https://cloud.google.com/bigquery/d... |
extra_params = {"projection": "full"}
if project is None:
project = self.project
if location is None:
location = self.location
if location is not None:
extra_params["location"] = location
path = "/projects/{}/jobs/{}/cancel".format(project... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_jobs( self, project=None, max_results=None, page_token=None, all_users=None, state_filter=None, retry=DEFAULT_RETRY, min_creation_time=None, max_creation... |
extra_params = {
"allUsers": all_users,
"stateFilter": state_filter,
"minCreationTime": _str_or_none(
google.cloud._helpers._millis_from_datetime(min_creation_time)
),
"maxCreationTime": _str_or_none(
google.cloud._help... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_table_from_uri( self, source_uris, destination, job_id=None, job_id_prefix=None, location=None, project=None, job_config=None, retry=DEFAULT_RETRY, ):
"... |
job_id = _make_job_id(job_id, job_id_prefix)
if project is None:
project = self.project
if location is None:
location = self.location
job_ref = job._JobReference(job_id, project=project, location=location)
if isinstance(source_uris, six.string_types):... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_table_from_file( self, file_obj, destination, rewind=False, size=None, num_retries=_DEFAULT_NUM_RETRIES, job_id=None, job_id_prefix=None, location=None, ... |
job_id = _make_job_id(job_id, job_id_prefix)
if project is None:
project = self.project
if location is None:
location = self.location
destination = _table_arg_to_table_ref(destination, default_project=self.project)
job_ref = job._JobReference(job_id, p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_table_from_dataframe( self, dataframe, destination, num_retries=_DEFAULT_NUM_RETRIES, job_id=None, job_id_prefix=None, location=None, project=None, job_c... |
job_id = _make_job_id(job_id, job_id_prefix)
if job_config is None:
job_config = job.LoadJobConfig()
job_config.source_format = job.SourceFormat.PARQUET
if location is None:
location = self.location
tmpfd, tmppath = tempfile.mkstemp(suffix="_job_{}.par... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy_table( self, sources, destination, job_id=None, job_id_prefix=None, location=None, project=None, job_config=None, retry=DEFAULT_RETRY, ):
"""Copy one or... |
job_id = _make_job_id(job_id, job_id_prefix)
if project is None:
project = self.project
if location is None:
location = self.location
job_ref = job._JobReference(job_id, project=project, location=location)
# sources can be one of many different input ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_table( self, source, destination_uris, job_id=None, job_id_prefix=None, location=None, project=None, job_config=None, retry=DEFAULT_RETRY, ):
"""Star... |
job_id = _make_job_id(job_id, job_id_prefix)
if project is None:
project = self.project
if location is None:
location = self.location
job_ref = job._JobReference(job_id, project=project, location=location)
source = _table_arg_to_table_ref(source, defau... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query( self, query, job_config=None, job_id=None, job_id_prefix=None, location=None, project=None, retry=DEFAULT_RETRY, ):
"""Run a SQL query. See https://cl... |
job_id = _make_job_id(job_id, job_id_prefix)
if project is None:
project = self.project
if location is None:
location = self.location
if self._default_query_job_config:
if job_config:
# anything that's not defined on the incoming
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert_rows(self, table, rows, selected_fields=None, **kwargs):
"""Insert rows into a table via the streaming API. See https://cloud.google.com/bigquery/docs... |
table = _table_arg_to_table(table, default_project=self.project)
if not isinstance(table, Table):
raise TypeError(_NEED_TABLE_ARGUMENT)
schema = table.schema
# selected_fields can override the table schema.
if selected_fields is not None:
schema = sele... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert_rows_json( self, table, json_rows, row_ids=None, skip_invalid_rows=None, ignore_unknown_values=None, template_suffix=None, retry=DEFAULT_RETRY, ):
"""... |
# Convert table to just a reference because unlike insert_rows,
# insert_rows_json doesn't need the table schema. It's not doing any
# type conversions.
table = _table_arg_to_table_ref(table, default_project=self.project)
rows_info = []
data = {"rows": rows_info}
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_partitions(self, table, retry=DEFAULT_RETRY):
"""List the partitions in a table. Arguments: table (Union[ \ :class:`~google.cloud.bigquery.table.Table`,... |
table = _table_arg_to_table_ref(table, default_project=self.project)
meta_table = self.get_table(
TableReference(
self.dataset(table.dataset_id, project=table.project),
"%s$__PARTITIONS_SUMMARY__" % table.table_id,
)
)
subset = [c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_rows( self, table, selected_fields=None, max_results=None, page_token=None, start_index=None, page_size=None, retry=DEFAULT_RETRY, ):
"""List the rows o... |
table = _table_arg_to_table(table, default_project=self.project)
if not isinstance(table, Table):
raise TypeError(_NEED_TABLE_ARGUMENT)
schema = table.schema
# selected_fields can override the table schema.
if selected_fields is not None:
schema = sele... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _schema_from_json_file_object(self, file_obj):
"""Helper function for schema_from_json that takes a file object that describes a table schema. Returns: List ... |
json_data = json.load(file_obj)
return [SchemaField.from_api_repr(field) for field in json_data] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _schema_to_json_file_object(self, schema_list, file_obj):
"""Helper function for schema_to_json that takes a schema list and file object and writes the schem... |
json.dump(schema_list, file_obj, indent=2, sort_keys=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schema_from_json(self, file_or_path):
"""Takes a file object or file path that contains json that describes a table schema. Returns: List of schema field obj... |
if isinstance(file_or_path, io.IOBase):
return self._schema_from_json_file_object(file_or_path)
with open(file_or_path) as file_obj:
return self._schema_from_json_file_object(file_obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schema_to_json(self, schema_list, destination):
"""Takes a list of schema field objects. Serializes the list of schema field objects as json to a file. Desti... |
json_schema_list = [f.to_api_repr() for f in schema_list]
if isinstance(destination, io.IOBase):
return self._schema_to_json_file_object(json_schema_list, destination)
with open(destination, mode="w") as file_obj:
return self._schema_to_json_file_object(json_schema_lis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_from_pb(self, instance_pb):
"""Refresh self from the server-provided protobuf. Helper for :meth:`from_pb` and :meth:`reload`. """ |
if not instance_pb.display_name: # Simple field (string)
raise ValueError("Instance protobuf does not contain display_name")
self.display_name = instance_pb.display_name
self.configuration_name = instance_pb.config
self.node_count = instance_pb.node_count |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_pb(cls, instance_pb, client):
"""Creates an instance from a protobuf. :type instance_pb: :class:`google.spanner.v2.spanner_instance_admin_pb2.Instance` ... |
match = _INSTANCE_NAME_RE.match(instance_pb.name)
if match is None:
raise ValueError(
"Instance protobuf name was not in the " "expected format.",
instance_pb.name,
)
if match.group("project") != client.project:
raise ValueErro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self):
"""Make a copy of this instance. Copies the local data stored as simple types and copies the client attached to this instance. :rtype: :class:`~g... |
new_client = self._client.copy()
return self.__class__(
self.instance_id,
new_client,
self.configuration_name,
node_count=self.node_count,
display_name=self.display_name,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exists(self):
"""Test whether this instance exists. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.... |
api = self._client.instance_admin_api
metadata = _metadata_with_prefix(self.name)
try:
api.get_instance(self.name, metadata=metadata)
except NotFound:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Update this instance. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.I... |
api = self._client.instance_admin_api
instance_pb = admin_v1_pb2.Instance(
name=self.name,
config=self.configuration_name,
display_name=self.display_name,
node_count=self.node_count,
)
field_mask = FieldMask(paths=["config", "display_name"... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
"""Mark an instance and all of its databases for permanent deletion. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.in... |
api = self._client.instance_admin_api
metadata = _metadata_with_prefix(self.name)
api.delete_instance(self.name, metadata=metadata) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def database(self, database_id, ddl_statements=(), pool=None):
"""Factory to create a database within this instance. :type database_id: str :param database_id: T... |
return Database(database_id, self, ddl_statements=ddl_statements, pool=pool) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_databases(self, page_size=None, page_token=None):
"""List databases for the instance. See https://cloud.google.com/spanner/reference/rpc/google.spanner.... |
metadata = _metadata_with_prefix(self.name)
page_iter = self._client.database_admin_api.list_databases(
self.name, page_size=page_size, metadata=metadata
)
page_iter.next_page_token = page_token
page_iter.item_to_value = self._item_to_database
return page_ite... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _item_to_database(self, iterator, database_pb):
"""Convert a database protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.I... |
return Database.from_pb(database_pb, self, pool=BurstyPool()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _blocking_poll(self, timeout=None):
"""Poll and wait for the Future to be resolved. Args: timeout (int):
How long (in seconds) to wait for the operation to ... |
if self._result_set:
return
retry_ = self._retry.with_deadline(timeout)
try:
retry_(self._done_or_raise)()
except exceptions.RetryError:
raise concurrent.futures.TimeoutError(
"Operation did not complete within the designated " "time... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def result(self, timeout=None):
"""Get the result of the operation, blocking if necessary. Args: timeout (int):
How long (in seconds) to wait for the operation ... |
self._blocking_poll(timeout=timeout)
if self._exception is not None:
# pylint: disable=raising-bad-type
# Pylint doesn't recognize that this is valid in this case.
raise self._exception
return self._result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_done_callback(self, fn):
"""Add a callback to be executed when the operation is complete. If the operation is not already complete, this will start a hel... |
if self._result_set:
_helpers.safe_invoke_callback(fn, self)
return
self._done_callbacks.append(fn)
if self._polling_thread is None:
# The polling thread will exit on its own as soon as the operation
# is done.
self._polling_thread =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _invoke_callbacks(self, *args, **kwargs):
"""Invoke all done callbacks.""" |
for callback in self._done_callbacks:
_helpers.safe_invoke_callback(callback, *args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_result(self, result):
"""Set the Future's result.""" |
self._result = result
self._result_set = True
self._invoke_callbacks(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_exception(self, exception):
"""Set the Future's exception.""" |
self._exception = exception
self._result_set = True
self._invoke_callbacks(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instantiate_client(_unused_client, _unused_to_delete):
"""Instantiate client.""" |
# [START client_create_default]
from google.cloud import logging
client = logging.Client()
# [END client_create_default]
credentials = object()
# [START client_create_explicit]
from google.cloud import logging
client = logging.Client(project="my-project", credentials=credentials) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def client_list_entries(client, to_delete):
# pylint: disable=unused-argument """List entries via client.""" |
# [START client_list_entries_default]
for entry in client.list_entries(): # API call(s)
do_something_with(entry)
# [END client_list_entries_default]
# [START client_list_entries_filter]
FILTER = "logName:log_name AND textPayload:simple"
for entry in client.list_entries(filter_=FILTER... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def client_list_entries_multi_project( client, to_delete ):
# pylint: disable=unused-argument """List entries via client across multiple projects.""" |
# [START client_list_entries_multi_project]
PROJECT_IDS = ["one-project", "another-project"]
for entry in client.list_entries(project_ids=PROJECT_IDS): # API call(s)
do_something_with(entry) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def logger_usage(client, to_delete):
"""Logger usage.""" |
LOG_NAME = "logger_usage_%d" % (_millis())
# [START logger_create]
logger = client.logger(LOG_NAME)
# [END logger_create]
to_delete.append(logger)
# [START logger_log_text]
logger.log_text("A simple entry") # API call
# [END logger_log_text]
# [START logger_log_struct]
logge... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def metric_crud(client, to_delete):
"""Metric CRUD.""" |
METRIC_NAME = "robots-%d" % (_millis(),)
DESCRIPTION = "Robots all up in your server"
FILTER = "logName:apache-access AND textPayload:robot"
UPDATED_FILTER = "textPayload:robot"
UPDATED_DESCRIPTION = "Danger, Will Robinson!"
# [START client_list_metrics]
for metric in client.list_metrics()... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sink_storage(client, to_delete):
"""Sink log entries to storage.""" |
bucket = _sink_storage_setup(client)
to_delete.append(bucket)
SINK_NAME = "robots-storage-%d" % (_millis(),)
FILTER = "textPayload:robot"
# [START sink_storage_create]
DESTINATION = "storage.googleapis.com/%s" % (bucket.name,)
sink = client.sink(SINK_NAME, filter_=FILTER, destination=DESTI... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sink_bigquery(client, to_delete):
"""Sink log entries to bigquery.""" |
dataset = _sink_bigquery_setup(client)
to_delete.append(dataset)
SINK_NAME = "robots-bigquery-%d" % (_millis(),)
FILTER = "textPayload:robot"
# [START sink_bigquery_create]
DESTINATION = "bigquery.googleapis.com%s" % (dataset.path,)
sink = client.sink(SINK_NAME, filter_=FILTER, destination... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sink_pubsub(client, to_delete):
"""Sink log entries to pubsub.""" |
topic = _sink_pubsub_setup(client)
to_delete.append(topic)
SINK_NAME = "robots-pubsub-%d" % (_millis(),)
FILTER = "logName:apache-access AND textPayload:robot"
UPDATED_FILTER = "textPayload:robot"
# [START sink_pubsub_create]
DESTINATION = "pubsub.googleapis.com/%s" % (topic.full_name,)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def complain(distribution_name):
"""Issue a warning if `distribution_name` is installed. In a future release, this method will be updated to raise ImportError ra... |
try:
pkg_resources.get_distribution(distribution_name)
warnings.warn(
"The {pkg} distribution is now obsolete. "
"Please `pip uninstall {pkg}`. "
"In the future, this warning will become an ImportError.".format(
pkg=distribution_name
)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_encryption_headers(key, source=False):
"""Builds customer encryption key headers :type key: bytes :param key: 32 byte key to build request key and hash.... |
if key is None:
return {}
key = _to_bytes(key)
key_hash = hashlib.sha256(key).digest()
key_hash = base64.b64encode(key_hash)
key = base64.b64encode(key)
if source:
prefix = "X-Goog-Copy-Source-Encryption-"
else:
prefix = "X-Goog-Encryption-"
return {
p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _raise_from_invalid_response(error):
"""Re-wrap and raise an ``InvalidResponse`` exception. :type error: :exc:`google.resumable_media.InvalidResponse` :param... |
response = error.response
error_message = str(error)
message = u"{method} {url}: {error}".format(
method=response.request.method, url=response.request.url, error=error_message
)
raise exceptions.from_http_status(response.status_code, message, response=response) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_query_parameters(base_url, name_value_pairs):
"""Add one query parameter to a base URL. :type base_url: string :param base_url: Base URL (may already co... |
if len(name_value_pairs) == 0:
return base_url
scheme, netloc, path, query, frag = urlsplit(base_url)
query = parse_qsl(query)
query.extend(name_value_pairs)
return urlunsplit((scheme, netloc, path, urlencode(query), frag)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chunk_size(self, value):
"""Set the blob's default chunk size. :type value: int :param value: (Optional) The current blob's chunk size, if it is set. :raises... |
if value is not None and value > 0 and value % self._CHUNK_SIZE_MULTIPLE != 0:
raise ValueError(
"Chunk size must be a multiple of %d." % (self._CHUNK_SIZE_MULTIPLE,)
)
self._chunk_size = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def path(self):
"""Getter property for the URL path to this Blob. :rtype: str :returns: The URL path to this Blob. """ |
if not self.name:
raise ValueError("Cannot determine path without a blob name.")
return self.path_helper(self.bucket.path, self.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _query_params(self):
"""Default query parameters.""" |
params = {}
if self.generation is not None:
params["generation"] = self.generation
if self.user_project is not None:
params["userProject"] = self.user_project
return params |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def public_url(self):
"""The public URL for this blob. Use :meth:`make_public` to enable anonymous access via the returned URL. :rtype: `string` :returns: The pu... |
return "{storage_base_url}/{bucket_name}/{quoted_name}".format(
storage_base_url=_API_ACCESS_ENDPOINT,
bucket_name=self.bucket.name,
quoted_name=quote(self.name.encode("utf-8")),
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_signed_url( self, expiration=None, api_access_endpoint=_API_ACCESS_ENDPOINT, method="GET", content_md5=None, content_type=None, response_disposition=... |
if version is None:
version = "v2"
elif version not in ("v2", "v4"):
raise ValueError("'version' must be either 'v2' or 'v4'")
resource = "/{bucket_name}/{quoted_name}".format(
bucket_name=self.bucket.name, quoted_name=quote(self.name.encode("utf-8"))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exists(self, client=None):
"""Determines whether or not this blob exists. If :attr:`user_project` is set on the bucket, bills the API request to that project... |
client = self._require_client(client)
# We only need the status code (200 or not) so we seek to
# minimize the returned payload.
query_params = self._query_params
query_params["fields"] = "name"
try:
# We intentionally pass `_target_object=None` since fields... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, client=None):
"""Deletes a blob from Cloud Storage. If :attr:`user_project` is set on the bucket, bills the API request to that project. :type c... |
return self.bucket.delete_blob(
self.name, client=client, generation=self.generation
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_download_url(self):
"""Get the download URL for the current blob. If the ``media_link`` has been loaded, it will be used, otherwise the URL will be cons... |
name_value_pairs = []
if self.media_link is None:
base_url = _DOWNLOAD_URL_TEMPLATE.format(path=self.path)
if self.generation is not None:
name_value_pairs.append(("generation", "{:d}".format(self.generation)))
else:
base_url = self.media_link... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_download( self, transport, file_obj, download_url, headers, start=None, end=None ):
"""Perform a download without any error handling. This is intended to... |
if self.chunk_size is None:
download = Download(
download_url, stream=file_obj, headers=headers, start=start, end=end
)
download.consume(transport)
else:
download = ChunkedDownload(
download_url,
self.chunk_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_to_file(self, file_obj, client=None, start=None, end=None):
"""Download the contents of this blob into a file-like object. .. note:: If the server-s... |
download_url = self._get_download_url()
headers = _get_encryption_headers(self._encryption_key)
headers["accept-encoding"] = "gzip"
transport = self._get_transport(client)
try:
self._do_download(transport, file_obj, download_url, headers, start, end)
except ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_to_filename(self, filename, client=None, start=None, end=None):
"""Download the contents of this blob into a named file. If :attr:`user_project` is ... |
try:
with open(filename, "wb") as file_obj:
self.download_to_file(file_obj, client=client, start=start, end=end)
except resumable_media.DataCorruption:
# Delete the corrupt downloaded file.
os.remove(filename)
raise
updated = self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_as_string(self, client=None, start=None, end=None):
"""Download the contents of this blob as a string. If :attr:`user_project` is set on the bucket,... |
string_buffer = BytesIO()
self.download_to_file(string_buffer, client=client, start=start, end=end)
return string_buffer.getvalue() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_content_type(self, content_type, filename=None):
"""Determine the content type from the current object. The return value will be determined in order of ... |
if content_type is None:
content_type = self.content_type
if content_type is None and filename is not None:
content_type, _ = mimetypes.guess_type(filename)
if content_type is None:
content_type = _DEFAULT_CONTENT_TYPE
return content_type |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_upload_arguments(self, content_type):
"""Get required arguments for performing an upload. The content type returned will be determined in order of prece... |
headers = _get_encryption_headers(self._encryption_key)
object_metadata = self._get_writable_metadata()
content_type = self._get_content_type(content_type)
return headers, object_metadata, content_type |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_upload( self, client, stream, content_type, size, num_retries, predefined_acl ):
"""Determine an upload strategy and then perform the upload. If the size... |
if size is not None and size <= _MAX_MULTIPART_SIZE:
response = self._do_multipart_upload(
client, stream, content_type, size, num_retries, predefined_acl
)
else:
response = self._do_resumable_upload(
client, stream, content_type, size... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_from_file( self, file_obj, rewind=False, size=None, content_type=None, num_retries=None, client=None, predefined_acl=None, ):
"""Upload the contents o... |
if num_retries is not None:
warnings.warn(_NUM_RETRIES_MESSAGE, DeprecationWarning, stacklevel=2)
_maybe_rewind(file_obj, rewind=rewind)
predefined_acl = ACL.validate_predefined(predefined_acl)
try:
created_json = self._do_upload(
client, file_o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_from_filename( self, filename, content_type=None, client=None, predefined_acl=None ):
"""Upload this blob's contents from the content of a named file.... |
content_type = self._get_content_type(content_type, filename=filename)
with open(filename, "rb") as file_obj:
total_bytes = os.fstat(file_obj.fileno()).st_size
self.upload_from_file(
file_obj,
content_type=content_type,
client=cli... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_from_string( self, data, content_type="text/plain", client=None, predefined_acl=None ):
"""Upload contents of this blob from the provided string. .. n... |
data = _to_bytes(data, encoding="utf-8")
string_buffer = BytesIO(data)
self.upload_from_file(
file_obj=string_buffer,
size=len(data),
content_type=content_type,
client=client,
predefined_acl=predefined_acl,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_resumable_upload_session( self, content_type=None, size=None, origin=None, client=None ):
"""Create a resumable upload session. Resumable upload sessi... |
extra_headers = {}
if origin is not None:
# This header is specifically for client-side uploads, it
# determines the origins allowed for CORS.
extra_headers["Origin"] = origin
try:
dummy_stream = BytesIO(b"")
# Send a fake the chunk s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_public(self, client=None):
"""Update blob's ACL, granting read access to anonymous users. :type client: :class:`~google.cloud.storage.client.Client` or ... |
self.acl.all().grant_read()
self.acl.save(client=client) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_private(self, client=None):
"""Update blob's ACL, revoking read access for anonymous users. :type client: :class:`~google.cloud.storage.client.Client` o... |
self.acl.all().revoke_read()
self.acl.save(client=client) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compose(self, sources, client=None):
"""Concatenate source blobs into this one. If :attr:`user_project` is set on the bucket, bills the API request to that p... |
client = self._require_client(client)
query_params = {}
if self.user_project is not None:
query_params["userProject"] = self.user_project
request = {
"sourceObjects": [{"name": source.name} for source in sources],
"destination": self._properties.cop... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rewrite(self, source, token=None, client=None):
"""Rewrite source blob into this one. If :attr:`user_project` is set on the bucket, bills the API request to ... |
client = self._require_client(client)
headers = _get_encryption_headers(self._encryption_key)
headers.update(_get_encryption_headers(source._encryption_key, source=True))
query_params = self._query_params
if "generation" in query_params:
del query_params["generation... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_storage_class(self, new_class, client=None):
"""Update blob's storage class via a rewrite-in-place. This helper will wait for the rewrite to complete ... |
if new_class not in self._STORAGE_CLASSES:
raise ValueError("Invalid storage class: %s" % (new_class,))
# Update current blob's storage class prior to rewrite
self._patch_property("storageClass", new_class)
# Execute consecutive rewrite operations until operation is done
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify_path(path, is_collection):
"""Verifies that a ``path`` has the correct form. Checks that all of the elements in ``path`` are strings. Args: document p... |
num_elements = len(path)
if num_elements == 0:
raise ValueError("Document or collection path cannot be empty")
if is_collection:
if num_elements % 2 == 0:
raise ValueError("A collection must have an odd number of path elements")
else:
if num_elements % 2 == 1:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode_value(value):
"""Converts a native Python value into a Firestore protobuf ``Value``. Args: value (Union[NoneType, bool, int, float, datetime.datetime,... |
if value is None:
return document_pb2.Value(null_value=struct_pb2.NULL_VALUE)
# Must come before six.integer_types since ``bool`` is an integer subtype.
if isinstance(value, bool):
return document_pb2.Value(boolean_value=value)
if isinstance(value, six.integer_types):
return d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode_dict(values_dict):
"""Encode a dictionary into protobuf ``Value``-s. Args: values_dict (dict):
The dictionary to encode as protobuf fields. Returns: ... |
return {key: encode_value(value) for key, value in six.iteritems(values_dict)} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reference_value_to_document(reference_value, client):
"""Convert a reference value string to a document. Args: reference_value (str):
A document reference v... |
# The first 5 parts are
# projects, {project}, databases, {database}, documents
parts = reference_value.split(DOCUMENT_PATH_DELIMITER, 5)
if len(parts) != 6:
msg = BAD_REFERENCE_ERROR.format(reference_value)
raise ValueError(msg)
# The sixth part is `a/b/c/d` (i.e. the document pat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_value(value, client):
"""Converts a Firestore protobuf ``Value`` to a native Python value. Args: value (google.cloud.firestore_v1beta1.types.Value):
... |
value_type = value.WhichOneof("value_type")
if value_type == "null_value":
return None
elif value_type == "boolean_value":
return value.boolean_value
elif value_type == "integer_value":
return value.integer_value
elif value_type == "double_value":
return value.doubl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_dict(value_fields, client):
"""Converts a protobuf map of Firestore ``Value``-s. Args: value_fields (google.protobuf.pyext._message.MessageMapContaine... |
return {
key: decode_value(value, client) for key, value in six.iteritems(value_fields)
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_doc_id(document_pb, expected_prefix):
"""Parse a document ID from a document protobuf. Args: document_pb (google.cloud.proto.firestore.v1beta1.\ document... |
prefix, document_id = document_pb.name.rsplit(DOCUMENT_PATH_DELIMITER, 1)
if prefix != expected_prefix:
raise ValueError(
"Unexpected document name",
document_pb.name,
"Expected to begin with",
expected_prefix,
)
return document_id |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_fields(document_data, prefix_path, expand_dots=False):
"""Do depth-first walk of tree, yielding field_path, value""" |
if not document_data:
yield prefix_path, _EmptyDict
else:
for key, value in sorted(six.iteritems(document_data)):
if expand_dots:
sub_key = FieldPath.from_string(key)
else:
sub_key = FieldPath(key)
field_path = FieldPath(*(pr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_field_value(document_data, field_path, value):
"""Set a value into a document for a field_path""" |
current = document_data
for element in field_path.parts[:-1]:
current = current.setdefault(element, {})
if value is _EmptyDict:
value = {}
current[field_path.parts[-1]] = value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.