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 delete_record_set(self, record_set):
"""Append a record set to the 'deletions' for the change set. :type record_set: :class:`google.cloud.dns.resource_record... |
if not isinstance(record_set, ResourceRecordSet):
raise ValueError("Pass a ResourceRecordSet")
self._deletions += (record_set,) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_resource(self):
"""Generate a resource for ``create``.""" |
additions = [
{
"name": added.name,
"type": added.record_type,
"ttl": str(added.ttl),
"rrdatas": added.rrdatas,
}
for added in self.additions
]
deletions = [
{
"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 sinks_api(self):
"""Helper for log sink-related API calls. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks """ |
if self._sinks_api is None:
if self._use_grpc:
self._sinks_api = _gapic.make_sinks_api(self)
else:
self._sinks_api = JSONSinksAPI(self)
return self._sinks_api |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def metrics_api(self):
"""Helper for log metric-related API calls. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics """ |
if self._metrics_api is None:
if self._use_grpc:
self._metrics_api = _gapic.make_metrics_api(self)
else:
self._metrics_api = JSONMetricsAPI(self)
return self._metrics_api |
<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(self, name, filter_=None, destination=None):
"""Creates a sink bound to the current client. :type name: str :param name: the name of the sink to be cons... |
return Sink(name, filter_, destination, client=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 metric(self, name, filter_=None, description=""):
"""Creates a metric bound to the current client. :type name: str :param name: the name of the metric to be ... |
return Metric(name, filter_, client=self, description=description) |
<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_default_handler(self, **kw):
"""Return the default logging handler based on the local environment. :type kw: dict :param kw: keyword args passed to handl... |
gke_cluster_name = retrieve_metadata_server(_GKE_CLUSTER_NAME)
if (
_APPENGINE_FLEXIBLE_ENV_VM in os.environ
or _APPENGINE_INSTANCE_ID in os.environ
):
return AppEngineHandler(self, **kw)
elif gke_cluster_name is not None:
return Containe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_logging( self, log_level=logging.INFO, excluded_loggers=EXCLUDED_LOGGER_DEFAULTS, **kw ):
"""Attach default Stackdriver logging handler to the root log... |
handler = self.get_default_handler(**kw)
setup_logging(handler, log_level=log_level, excluded_loggers=excluded_loggers) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def key_ring_path(cls, project, location, key_ring):
"""Return a fully-qualified key_ring string.""" |
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/keyRings/{key_ring}",
project=project,
location=location,
key_ring=key_ring,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def crypto_key_path_path(cls, project, location, key_ring, crypto_key_path):
"""Return a fully-qualified crypto_key_path string.""" |
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key_path=**}",
project=project,
location=location,
key_ring=key_ring,
crypto_key_path=crypto_key_path,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def crypto_key_version_path( cls, project, location, key_ring, crypto_key, crypto_key_version ):
"""Return a fully-qualified crypto_key_version string.""" |
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}",
project=project,
location=location,
key_ring=key_ring,
crypto_key=crypto_key,
... |
<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_key_ring( self, parent, key_ring_id, key_ring, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata... |
# Wrap the transport method to add retry and timeout logic.
if "create_key_ring" not in self._inner_api_calls:
self._inner_api_calls[
"create_key_ring"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_key_ring,
... |
<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_crypto_key( self, parent, crypto_key_id, crypto_key, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, me... |
# Wrap the transport method to add retry and timeout logic.
if "create_crypto_key" not in self._inner_api_calls:
self._inner_api_calls[
"create_crypto_key"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_crypto_key,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def span_path(cls, project, trace, span):
"""Return a fully-qualified span string.""" |
return google.api_core.path_template.expand(
"projects/{project}/traces/{trace}/spans/{span}",
project=project,
trace=trace,
span=span,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def batch_write_spans( self, name, spans, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ):
""" S... |
# Wrap the transport method to add retry and timeout logic.
if "batch_write_spans" not in self._inner_api_calls:
self._inner_api_calls[
"batch_write_spans"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.batch_write_spans,
... |
<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_span( self, name, span_id, display_name, start_time, end_time, parent_span_id=None, attributes=None, stack_trace=None, time_events=None, links=None, st... |
# Wrap the transport method to add retry and timeout logic.
if "create_span" not in self._inner_api_calls:
self._inner_api_calls[
"create_span"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_span,
default_re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _wrap_callback_errors(callback, message):
"""Wraps a user callback so that if an exception occurs the message is nacked. Args: callback (Callable[None, Messa... |
try:
callback(message)
except Exception:
# Note: the likelihood of this failing is extremely low. This just adds
# a message to a queue, so if this doesn't work the world is in an
# unrecoverable state and this thread should just bail.
_LOGGER.exception(
"Top... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ack_deadline(self):
"""Return the current ack deadline based on historical time-to-ack. This method is "sticky". It will only perform the computations to che... |
target = min([self._last_histogram_size * 2, self._last_histogram_size + 100])
if len(self.ack_histogram) > target:
self._ack_deadline = self.ack_histogram.percentile(percent=99)
return self._ack_deadline |
<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(self):
"""Return the current load. The load is represented as a float, where 1.0 represents having hit one of the flow control limits, and values betwee... |
if self._leaser is None:
return 0
return max(
[
self._leaser.message_count / self._flow_control.max_messages,
self._leaser.bytes / self._flow_control.max_bytes,
]
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maybe_pause_consumer(self):
"""Check the current load and pause the consumer if needed.""" |
if self.load >= 1.0:
if self._consumer is not None and not self._consumer.is_paused:
_LOGGER.debug("Message backlog over load at %.2f, pausing.", self.load)
self._consumer.pause() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maybe_resume_consumer(self):
"""Check the current load and resume the consumer if needed.""" |
# If we have been paused by flow control, check and see if we are
# back within our limits.
#
# In order to not thrash too much, require us to have passed below
# the resume threshold (80% by default) of each flow control setting
# before restarting.
if self._con... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _send_unary_request(self, request):
"""Send a request using a separate unary request instead of over the stream. Args: request (types.StreamingPullRequest):
... |
if request.ack_ids:
self._client.acknowledge(
subscription=self._subscription, ack_ids=list(request.ack_ids)
)
if request.modify_deadline_ack_ids:
# Send ack_ids with the same deadline seconds together.
deadline_to_ack_ids = collections.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 send(self, request):
"""Queue a request to be sent to the RPC.""" |
if self._UNARY_REQUESTS:
try:
self._send_unary_request(request)
except exceptions.GoogleAPICallError:
_LOGGER.debug(
"Exception while sending unary RPC. This is typically "
"non-fatal as stream requests are best-eff... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def heartbeat(self):
"""Sends an empty request over the streaming pull RPC. This always sends over the stream, regardless of if ``self._UNARY_REQUESTS`` is set o... |
if self._rpc is not None and self._rpc.is_active:
self._rpc.send(types.StreamingPullRequest()) |
<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_initial_request(self):
"""Return the initial request for the RPC. This defines the initial request that must always be sent to Pub/Sub immediately upon ... |
# Any ack IDs that are under lease management need to have their
# deadline extended immediately.
if self._leaser is not None:
# Explicitly copy the list, as it could be modified by another
# thread.
lease_ids = list(self._leaser.ack_ids)
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _should_recover(self, exception):
"""Determine if an error on the RPC stream should be recovered. If the exception is one of the retryable exceptions, this w... |
exception = _maybe_wrap_exception(exception)
# If this is in the list of idempotent exceptions, then we want to
# recover.
if isinstance(exception, _RETRYABLE_STREAM_ERRORS):
_LOGGER.info("Observed recoverable stream error %s", exception)
return True
_LOG... |
<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(self, reference, document_data):
"""Add a "change" to this batch to create a document. If the document given by ``reference`` already exists, then thi... |
write_pbs = _helpers.pbs_for_create(reference._document_path, document_data)
self._add_write_pbs(write_pbs) |
<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(self, reference, document_data, merge=False):
"""Add a "change" to replace a document. See :meth:`~.firestore_v1beta1.document.DocumentReference.set` for... |
if merge is not False:
write_pbs = _helpers.pbs_for_set_with_merge(
reference._document_path, document_data, merge
)
else:
write_pbs = _helpers.pbs_for_set_no_merge(
reference._document_path, document_data
)
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 update(self, reference, field_updates, option=None):
"""Add a "change" to update a document. See :meth:`~.firestore_v1beta1.document.DocumentReference.update... |
if option.__class__.__name__ == "ExistsOption":
raise ValueError("you must not pass an explicit write option to " "update.")
write_pbs = _helpers.pbs_for_update(
reference._document_path, field_updates, option
)
self._add_write_pbs(write_pbs) |
<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, reference, option=None):
"""Add a "change" to delete a document. See :meth:`~.firestore_v1beta1.document.DocumentReference.delete` for more info... |
write_pb = _helpers.pb_for_delete(reference._document_path, option)
self._add_write_pbs([write_pb]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commit(self):
"""Commit the changes accumulated in this batch. Returns: List[google.cloud.proto.firestore.v1beta1.\ to the changes committed, returned in the... |
commit_response = self._client._firestore_api.commit(
self._client._database_string,
self._write_pbs,
transaction=None,
metadata=self._client._rpc_metadata,
)
self._write_pbs = []
self.write_results = results = list(commit_response.write_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ensure_tuple_or_list(arg_name, tuple_or_list):
"""Ensures an input is a tuple or list. This effectively reduces the iterable types allowed to a very short w... |
if not isinstance(tuple_or_list, (tuple, list)):
raise TypeError(
"Expected %s to be a tuple or list. "
"Received %r" % (arg_name, tuple_or_list)
)
return list(tuple_or_list) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _microseconds_from_datetime(value):
"""Convert non-none datetime to microseconds. :type value: :class:`datetime.datetime` :param value: The timestamp to conv... |
if not value.tzinfo:
value = value.replace(tzinfo=UTC)
# Regardless of what timezone is on the value, convert it to UTC.
value = value.astimezone(UTC)
# Convert the datetime to a microsecond timestamp.
return int(calendar.timegm(value.timetuple()) * 1e6) + value.microsecond |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _time_from_iso8601_time_naive(value):
"""Convert a zoneless ISO8601 time string to naive datetime time :type value: str :param value: The time string to conv... |
if len(value) == 8: # HH:MM:SS
fmt = _TIMEONLY_NO_FRACTION
elif len(value) == 15: # HH:MM:SS.micros
fmt = _TIMEONLY_W_MICROS
else:
raise ValueError("Unknown time format: {}".format(value))
return datetime.datetime.strptime(value, fmt).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 _rfc3339_to_datetime(dt_str):
"""Convert a microsecond-precision timestamp to a native datetime. :type dt_str: str :param dt_str: The string to convert. :rty... |
return datetime.datetime.strptime(dt_str, _RFC3339_MICROS).replace(tzinfo=UTC) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _datetime_to_rfc3339(value, ignore_zone=True):
"""Convert a timestamp to a string. :type value: :class:`datetime.datetime` :param value: The datetime object ... |
if not ignore_zone and value.tzinfo is not None:
# Convert to UTC and remove the time zone info.
value = value.replace(tzinfo=None) - value.utcoffset()
return value.strftime(_RFC3339_MICROS) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _bytes_to_unicode(value):
"""Converts bytes to a unicode value, if necessary. :type value: bytes :param value: bytes value to attempt string conversion on. :... |
result = value.decode("utf-8") if isinstance(value, six.binary_type) else value
if isinstance(result, six.text_type):
return result
else:
raise ValueError("%r could not be converted to unicode" % (value,)) |
<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_any_pb(pb_type, any_pb):
"""Converts an Any protobuf to the specified message type Args: pb_type (type):
the type of the message that any_pb stores an... |
msg = pb_type()
if not any_pb.Unpack(msg):
raise TypeError(
"Could not convert {} to {}".format(
any_pb.__class__.__name__, pb_type.__name__
)
)
return msg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pb_timestamp_to_datetime(timestamp_pb):
"""Convert a Timestamp protobuf to a datetime object. :type timestamp_pb: :class:`google.protobuf.timestamp_pb2.Time... |
return _EPOCH + datetime.timedelta(
seconds=timestamp_pb.seconds, microseconds=(timestamp_pb.nanos / 1000.0)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _datetime_to_pb_timestamp(when):
"""Convert a datetime object to a Timestamp protobuf. :type when: :class:`datetime.datetime` :param when: the datetime to co... |
ms_value = _microseconds_from_datetime(when)
seconds, micros = divmod(ms_value, 10 ** 6)
nanos = micros * 10 ** 3
return timestamp_pb2.Timestamp(seconds=seconds, nanos=nanos) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _duration_pb_to_timedelta(duration_pb):
"""Convert a duration protobuf to a Python timedelta object. .. note:: The Python timedelta has a granularity of micr... |
return datetime.timedelta(
seconds=duration_pb.seconds, microseconds=(duration_pb.nanos / 1000.0)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _name_from_project_path(path, project, template):
"""Validate a URI path and get the leaf object's name. :type path: str :param path: URI path containing the... |
if isinstance(template, str):
template = re.compile(template)
match = template.match(path)
if not match:
raise ValueError(
'path "%s" did not match expected pattern "%s"' % (path, template.pattern)
)
if project is not None:
found_project = match.group("pro... |
<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_secure_channel(credentials, user_agent, host, extra_options=()):
"""Makes a secure channel for an RPC service. Uses / depends on gRPC. :type credentials... |
target = "%s:%d" % (host, http_client.HTTPS_PORT)
http_request = google.auth.transport.requests.Request()
user_agent_option = ("grpc.primary_user_agent", user_agent)
options = (user_agent_option,) + extra_options
return google.auth.transport.grpc.secure_authorized_channel(
credentials, htt... |
<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_secure_stub(credentials, user_agent, stub_class, host, extra_options=()):
"""Makes a secure stub for an RPC service. Uses / depends on gRPC. :type crede... |
channel = make_secure_channel(
credentials, user_agent, host, extra_options=extra_options
)
return stub_class(channel) |
<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_insecure_stub(stub_class, host, port=None):
"""Makes an insecure stub for an RPC service. Uses / depends on gRPC. :type stub_class: type :param stub_cla... |
if port is None:
target = host
else:
# NOTE: This assumes port != http_client.HTTPS_PORT:
target = "%s:%d" % (host, port)
channel = grpc.insecure_channel(target)
return stub_class(channel) |
<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_single_feature_method(feature):
"""Return a function that will detect a single feature. Args: feature (enum):
A specific feature defined as a member... |
# Define the function properties.
fx_name = feature.name.lower()
if "detection" in fx_name:
fx_doc = "Perform {0}.".format(fx_name.replace("_", " "))
else:
fx_doc = "Return {desc} information.".format(desc=fx_name.replace("_", " "))
# Provide a complete docstring with argument and ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule(self, callback, *args, **kwargs):
"""Schedule the callback to be called asynchronously in a thread pool. Args: callback (Callable):
The function to... |
self._executor.submit(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 shutdown(self):
"""Shuts down the scheduler and immediately end all pending callbacks. """ |
# Drop all pending item from the executor. Without this, the executor
# will block until all pending items are complete, which is
# undesirable.
try:
while True:
self._executor._work_queue.get(block=False)
except queue.Empty:
pass
... |
<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_events( self, project_name, group_id, service_filter=None, time_range=None, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google... |
# Wrap the transport method to add retry and timeout logic.
if "list_events" not in self._inner_api_calls:
self._inner_api_calls[
"list_events"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.list_events,
default_re... |
<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_events( self, project_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ):
""" Dele... |
# Wrap the transport method to add retry and timeout logic.
if "delete_events" not in self._inner_api_calls:
self._inner_api_calls[
"delete_events"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.delete_events,
defa... |
<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_document_ref(iterator, item):
"""Convert Document resource to document ref. Args: iterator (google.api_core.page_iterator.GRPCIterator):
iterator r... |
document_id = item.name.split(_helpers.DOCUMENT_PATH_DELIMITER)[-1]
return iterator.collection.document(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 parent(self):
"""Document that owns the current collection. Returns: Optional[~.firestore_v1beta1.document.DocumentReference]: The parent document, if the cu... |
if len(self._path) == 1:
return None
else:
parent_path = self._path[:-1]
return self._client.document(*parent_path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def document(self, document_id=None):
"""Create a sub-document underneath the current collection. Args: document_id (Optional[str]):
The document identifier wit... |
if document_id is None:
document_id = _auto_id()
child_path = self._path + (document_id,)
return self._client.document(*child_path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parent_info(self):
"""Get fully-qualified parent path and prefix for this collection. Returns: Tuple[str, str]: Pair of * the fully-qualified (with database... |
parent_doc = self.parent
if parent_doc is None:
parent_path = _helpers.DOCUMENT_PATH_DELIMITER.join(
(self._client._database_string, "documents")
)
else:
parent_path = parent_doc._document_path
expected_prefix = _helpers.DOCUMENT_PATH... |
<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(self, document_data, document_id=None):
"""Create a document in the Firestore database with the provided data. Args: document_data (dict):
Property name... |
if document_id is None:
parent_path, expected_prefix = self._parent_info()
document_pb = document_pb2.Document()
created_document_pb = self._client._firestore_api.create_document(
parent_path,
collection_id=self.id,
document_... |
<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_documents(self, page_size=None):
"""List all subdocuments of the current collection. Args: page_size (Optional[int]]):
The maximum number of documents ... |
parent, _ = self._parent_info()
iterator = self._client._firestore_api.list_documents(
parent,
self.id,
page_size=page_size,
show_missing=True,
metadata=self._client._rpc_metadata,
)
iterator.collection = self
iterator... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select(self, field_paths):
"""Create a "select" query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.select` for more information... |
query = query_mod.Query(self)
return query.select(field_paths) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def where(self, field_path, op_string, value):
"""Create a "where" query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.where` for mo... |
query = query_mod.Query(self)
return query.where(field_path, op_string, 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 order_by(self, field_path, **kwargs):
"""Create an "order by" query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.order_by` for ... |
query = query_mod.Query(self)
return query.order_by(field_path, **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 limit(self, count):
"""Create a limited query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.limit` for more information on this ... |
query = query_mod.Query(self)
return query.limit(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 offset(self, num_to_skip):
"""Skip to an offset in a query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.offset` for more inform... |
query = query_mod.Query(self)
return query.offset(num_to_skip) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start_at(self, document_fields):
"""Start query at a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.start_at` for more inf... |
query = query_mod.Query(self)
return query.start_at(document_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 start_after(self, document_fields):
"""Start query after a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.start_after` for... |
query = query_mod.Query(self)
return query.start_after(document_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 end_before(self, document_fields):
"""End query before a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.end_before` for mo... |
query = query_mod.Query(self)
return query.end_before(document_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 end_at(self, document_fields):
"""End query at a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.end_at` for more informati... |
query = query_mod.Query(self)
return query.end_at(document_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 stream(self, transaction=None):
"""Read the documents in this collection. This sends a ``RunQuery`` RPC and then returns an iterator which consumes each docu... |
query = query_mod.Query(self)
return query.stream(transaction=transaction) |
<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_languages(self, target_language=None):
"""Get list of supported languages for translation. Response See https://cloud.google.com/translate/docs/discoveri... |
query_params = {}
if target_language is None:
target_language = self.target_language
if target_language is not None:
query_params["target"] = target_language
response = self._connection.api_request(
method="GET", path="/languages", query_params=query_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detect_language(self, values):
"""Detect the language of a string or list of strings. See https://cloud.google.com/translate/docs/detecting-language :type va... |
single_value = False
if isinstance(values, six.string_types):
single_value = True
values = [values]
data = {"q": values}
response = self._connection.api_request(
method="POST", path="/detect", data=data
)
detections = response.get("... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def translate( self, values, target_language=None, format_=None, source_language=None, customization_ids=(), model=None, ):
"""Translate a string or list of stri... |
single_value = False
if isinstance(values, six.string_types):
single_value = True
values = [values]
if target_language is None:
target_language = self.target_language
if isinstance(customization_ids, six.string_types):
customization_ids =... |
<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(self, items):
"""Add messages to be managed by the leaser.""" |
for item in items:
# Add the ack ID to the set of managed ack IDs, and increment
# the size counter.
if item.ack_id not in self._leased_messages:
self._leased_messages[item.ack_id] = _LeasedMessage(
added_time=time.time(), size=item.byte_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 remove(self, items):
"""Remove messages from lease management.""" |
# Remove the ack ID from lease management, and decrement the
# byte counter.
for item in items:
if self._leased_messages.pop(item.ack_id, None) is not None:
self._bytes -= item.byte_size
else:
_LOGGER.debug("Item %s was not managed.", item... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maintain_leases(self):
"""Maintain all of the leases being managed. This method modifies the ack deadline for all of the managed ack IDs, then waits for most... |
while self._manager.is_active and not self._stop_event.is_set():
# Determine the appropriate duration for the lease. This is
# based off of how long previous messages have taken to ack, with
# a sensible default and within the ranges allowed by Pub/Sub.
p99 = sel... |
<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_report_error_api(client):
"""Create an instance of the gapic Logging API. :type client::class:`google.cloud.error_reporting.Client` :param client: Error... |
gax_client = report_errors_service_client.ReportErrorsServiceClient(
credentials=client._credentials, client_info=_CLIENT_INFO
)
return _ErrorReportingGapicApi(gax_client, client.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 report_error_event(self, error_report):
"""Uses the gapic client to report the error. :type error_report: dict :param error_report: payload of the error repo... |
project_name = self._gapic_api.project_path(self._project)
error_report_payload = report_errors_service_pb2.ReportedErrorEvent()
ParseDict(error_report, error_report_payload)
self._gapic_api.report_error_event(project_name, error_report_payload) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def table_path(cls, project, instance, table):
"""Return a fully-qualified table string.""" |
return google.api_core.path_template.expand(
"projects/{project}/instances/{instance}/tables/{table}",
project=project,
instance=instance,
table=table,
) |
<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_rows( self, table_name, app_profile_id=None, rows=None, filter_=None, rows_limit=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_... |
# Wrap the transport method to add retry and timeout logic.
if "read_rows" not in self._inner_api_calls:
self._inner_api_calls[
"read_rows"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.read_rows,
default_retry=se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mutate_rows( self, table_name, entries, app_profile_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, m... |
# Wrap the transport method to add retry and timeout logic.
if "mutate_rows" not in self._inner_api_calls:
self._inner_api_calls[
"mutate_rows"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.mutate_rows,
default_re... |
<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_and_mutate_row( self, table_name, row_key, app_profile_id=None, predicate_filter=None, true_mutations=None, false_mutations=None, retry=google.api_core.... |
# Wrap the transport method to add retry and timeout logic.
if "check_and_mutate_row" not in self._inner_api_calls:
self._inner_api_calls[
"check_and_mutate_row"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.check_and_mutate_row,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def name(self):
"""Instance name used in requests. .. note:: This property will not change if ``instance_id`` does not, but the return value is not cached. For e... |
return self._client.instance_admin_client.instance_path(
project=self._client.project, instance=self.instance_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 exists(self):
"""Check whether the instance already exists. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_check_instance_exists]... |
try:
self._client.instance_admin_client.get_instance(name=self.name)
return True
# NOTE: There could be other exceptions that are returned to the user.
except NotFound:
return False |
<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_iam_policy(self):
"""Gets the access control policy for an instance resource. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_... |
instance_admin_client = self._client.instance_admin_client
resp = instance_admin_client.get_iam_policy(resource=self.name)
return Policy.from_pb(resp) |
<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_iam_policy(self, policy):
"""Sets the access control policy on an instance resource. Replaces any existing policy. For more information about policy, ple... |
instance_admin_client = self._client.instance_admin_client
resp = instance_admin_client.set_iam_policy(
resource=self.name, policy=policy.to_pb()
)
return Policy.from_pb(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cluster( self, cluster_id, location_id=None, serve_nodes=None, default_storage_type=None ):
"""Factory to create a cluster associated with this instance. For... |
return Cluster(
cluster_id,
self,
location_id=location_id,
serve_nodes=serve_nodes,
default_storage_type=default_storage_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 list_clusters(self):
"""List the clusters in this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_clusters_on_insta... |
resp = self._client.instance_admin_client.list_clusters(self.name)
clusters = [Cluster.from_pb(cluster, self) for cluster in resp.clusters]
return clusters, resp.failed_locations |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def table(self, table_id, mutation_timeout=None, app_profile_id=None):
"""Factory to create a table associated with this instance. For example: .. literalinclude... |
return Table(
table_id,
self,
app_profile_id=app_profile_id,
mutation_timeout=mutation_timeout,
) |
<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_tables(self):
"""List the tables in this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_tables] :end-before: ... |
table_list_pb = self._client.table_admin_client.list_tables(self.name)
result = []
for table_pb in table_list_pb:
table_prefix = self.name + "/tables/"
if not table_pb.name.startswith(table_prefix):
raise ValueError(
"Table name {} no... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def app_profile( self, app_profile_id, routing_policy_type=None, description=None, cluster_id=None, allow_transactional_writes=None, ):
"""Factory to create AppP... |
return AppProfile(
app_profile_id,
self,
routing_policy_type=routing_policy_type,
description=description,
cluster_id=cluster_id,
allow_transactional_writes=allow_transactional_writes,
) |
<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_app_profiles(self):
"""Lists information about AppProfiles in an instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_li... |
resp = self._client.instance_admin_client.list_app_profiles(self.name)
return [AppProfile.from_pb(app_profile, self) for app_profile in resp] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _row_from_mapping(mapping, schema):
"""Convert a mapping to a row tuple using the schema. Args: mapping (Dict[str, object]) Mapping of row data: must contain... |
if len(schema) == 0:
raise ValueError(_TABLE_HAS_NO_SCHEMA)
row = []
for field in schema:
if field.mode == "REQUIRED":
row.append(mapping[field.name])
elif field.mode == "REPEATED":
row.append(mapping.get(field.name, ()))
elif field.mode == "NULLABLE... |
<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_row(iterator, resource):
"""Convert a JSON row to the native object. .. note:: This assumes that the ``schema`` attribute has been added to the iter... |
return Row(
_helpers._row_tuple_from_json(resource, iterator.schema),
iterator._field_to_index,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _table_arg_to_table_ref(value, default_project=None):
"""Helper to convert a string or Table to TableReference. This function keeps TableReference and other ... |
if isinstance(value, six.string_types):
value = TableReference.from_string(value, default_project=default_project)
if isinstance(value, (Table, TableListItem)):
value = value.reference
return 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 _table_arg_to_table(value, default_project=None):
"""Helper to convert a string or TableReference to a Table. This function keeps Table and other kinds of ob... |
if isinstance(value, six.string_types):
value = TableReference.from_string(value, default_project=default_project)
if isinstance(value, TableReference):
value = Table(value)
if isinstance(value, TableListItem):
newvalue = Table(value.reference)
newvalue._properties = 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 from_string(cls, table_id, default_project=None):
"""Construct a table reference from table ID string. Args: table_id (str):
A table ID in standard SQL form... |
from google.cloud.bigquery.dataset import DatasetReference
(
output_project_id,
output_dataset_id,
output_table_id,
) = _helpers._parse_3_part_id(
table_id, default_project=default_project, property_name="table_id"
)
return cls(
... |
<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_bqstorage(self):
"""Construct a BigQuery Storage API representation of this table. Install the ``google-cloud-bigquery-storage`` package to use this featu... |
if bigquery_storage_v1beta1 is None:
raise ValueError(_NO_BQSTORAGE_ERROR)
table_ref = bigquery_storage_v1beta1.types.TableReference()
table_ref.project_id = self._project
table_ref.dataset_id = self._dataset_id
table_id = self._table_id
if "@" in table_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(self, key, default=None):
"""Return a value for key, with a default value if it does not exist. Args: key (str):
The key of the column to access default... |
index = self._xxx_field_to_index.get(key)
if index is None:
return default
return self._xxx_values[index] |
<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_progress_bar(self, progress_bar_type):
"""Construct a tqdm progress bar object, if tqdm is installed.""" |
if tqdm is None:
if progress_bar_type is not None:
warnings.warn(_NO_TQDM_ERROR, UserWarning, stacklevel=3)
return None
description = "Downloading"
unit = "rows"
try:
if progress_bar_type == "tqdm":
return tqdm.tqdm(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 to_dataframe(self, bqstorage_client=None, dtypes=None, progress_bar_type=None):
"""Create a pandas DataFrame by loading all pages of a query. Args: bqstorage... |
if pandas is None:
raise ValueError(_NO_PANDAS_ERROR)
if dtypes is None:
dtypes = {}
progress_bar = self._get_progress_bar(progress_bar_type)
if bqstorage_client is not None:
try:
return self._to_dataframe_bqstorage(
... |
<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_dataframe(self, bqstorage_client=None, dtypes=None, progress_bar_type=None):
"""Create an empty dataframe. Args: bqstorage_client (Any):
Ignored. Added f... |
if pandas is None:
raise ValueError(_NO_PANDAS_ERROR)
return pandas.DataFrame() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prepare_batch_request(self):
"""Prepares headers and body for a batch request. :rtype: tuple (dict, str) :returns: The pair of headers and body of the batch... |
if len(self._requests) == 0:
raise ValueError("No deferred requests")
multi = MIMEMultipart()
for method, uri, headers, body in self._requests:
subrequest = MIMEApplicationHTTP(method, uri, headers, body)
multi.attach(subrequest)
# The `email` pack... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _finish_futures(self, responses):
"""Apply all the batch responses to the futures created. :type responses: list of (headers, payload) tuples. :param respons... |
# If a bad status occurs, we track it, but don't raise an exception
# until all futures have been populated.
exception_args = None
if len(self._target_objects) != len(responses):
raise ValueError("Expected a response for every request.")
for target_object, subrespo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.