docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Whether previous slice retry has ended according to Logs API.
Args:
shard_state: shard state.
Returns:
True if the request of previous slice retry has ended. False if it has
not or unknown. | def _has_old_request_ended(self, shard_state):
assert shard_state.slice_start_time is not None
assert shard_state.slice_request_id is not None
request_ids = [shard_state.slice_request_id]
logs = None
try:
logs = list(logservice.fetch(request_ids=request_ids))
except (apiproxy_errors.F... | 631,687 |
Time to wait until slice_start_time is secs ago from now.
Args:
shard_state: shard state.
secs: duration in seconds.
now: a func that gets now.
Returns:
0 if no wait. A positive int in seconds otherwise. Always around up. | def _wait_time(self, shard_state, secs, now=datetime.datetime.now):
assert shard_state.slice_start_time is not None
delta = now() - shard_state.slice_start_time
duration = datetime.timedelta(seconds=secs)
if delta < duration:
return util.total_seconds(duration - delta)
else:
return ... | 631,688 |
Makes sure shard life cycle interface are respected.
Args:
obj: the obj that may have implemented _ShardLifeCycle.
slice_id: current slice_id
last_slice: whether this is the last slice.
begin_slice: whether this is the beginning or the end of a slice.
shard_ctx: shard ctx for dependen... | def _maintain_LC(self, obj, slice_id, last_slice=False, begin_slice=True,
shard_ctx=None, slice_ctx=None):
if obj is None or not isinstance(obj, shard_life_cycle._ShardLifeCycle):
return
shard_context = shard_ctx or self.shard_context
slice_context = slice_ctx or self.slice_co... | 631,690 |
Process a single data piece.
Call mapper handler on the data.
Args:
data: a datum to process.
input_reader: input reader.
ctx: mapreduce context
transient_shard_state: transient shard state.
Returns:
True if scan should be continued, False if scan should be stopped. | def _process_datum(self, data, input_reader, ctx, transient_shard_state):
if data is not input_readers.ALLOW_CHECKPOINT:
self.slice_context.incr(context.COUNTER_MAPPER_CALLS)
handler = transient_shard_state.handler
if isinstance(handler, map_job.Mapper):
handler(self.slice_context, ... | 631,696 |
Save state and schedule task.
Save shard state to datastore.
Schedule next slice if needed.
Set HTTP response code.
No modification to any shard_state or tstate.
Args:
shard_state: model.ShardState for current shard.
tstate: model.TransientShardState for current shard.
task_direc... | def _save_state_and_schedule_next(self, shard_state, tstate, task_directive):
spec = tstate.mapreduce_spec
if task_directive == self._TASK_DIRECTIVE.DROP_TASK:
return
if task_directive in (self._TASK_DIRECTIVE.RETRY_SLICE,
self._TASK_DIRECTIVE.RETRY_TASK):
# Set H... | 631,698 |
Whether to retry shard.
This method may modify shard_state and tstate to prepare for retry or fail.
Args:
shard_state: model.ShardState for current shard.
tstate: model.TransientShardState for current shard.
Returns:
A _TASK_DIRECTIVE enum. RETRY_SHARD if shard should be retried.
FA... | def _attempt_shard_retry(self, shard_state, tstate):
shard_attempts = shard_state.retries + 1
if shard_attempts >= parameters.config.SHARD_MAX_ATTEMPTS:
logging.warning(
"Shard attempt %s exceeded %s max attempts.",
shard_attempts, parameters.config.SHARD_MAX_ATTEMPTS)
retu... | 631,700 |
Attempt to retry this slice.
This method may modify shard_state and tstate to prepare for retry or fail.
Args:
shard_state: model.ShardState for current shard.
tstate: model.TransientShardState for current shard.
Returns:
A _TASK_DIRECTIVE enum. RETRY_SLICE if slice should be retried.
... | def _attempt_slice_retry(self, shard_state, tstate):
if (shard_state.slice_retries + 1 <
parameters.config.TASK_MAX_DATA_PROCESSING_ATTEMPTS):
logging.warning(
"Slice %s %s failed for the %s of up to %s attempts "
"(%s of %s taskqueue execution attempts). "
"Will ret... | 631,701 |
Get countdown for next slice's task.
When user sets processing rate, we set countdown to delay task execution.
Args:
spec: model.MapreduceSpec
Returns:
countdown in int. | def _get_countdown_for_next_slice(self, spec):
countdown = 0
if self._processing_limit(spec) != -1:
countdown = max(
int(parameters.config._SLICE_DURATION_SEC -
(self._time() - self._start_time)), 0)
return countdown | 631,702 |
Schedule slice scanning by adding it to the task queue.
Args:
worker_task: a model.HugeTask task for slice. This is NOT a taskqueue
task.
mapreduce_spec: an instance of model.MapreduceSpec.
queue_name: Optional queue to run on; uses the current queue of
execution or the default qu... | def _add_task(cls,
worker_task,
mapreduce_spec,
queue_name):
if not _run_task_hook(mapreduce_spec.get_hooks(),
"enqueue_worker_task",
worker_task,
queue_name):
try:
# Not ... | 631,704 |
Get the limit on the number of map calls allowed by this slice.
Args:
spec: a Mapreduce spec.
Returns:
The limit as a positive int if specified by user. -1 otherwise. | def _processing_limit(self, spec):
processing_rate = float(spec.mapper.params.get("processing_rate", 0))
slice_processing_limit = -1
if processing_rate > 0:
slice_processing_limit = int(math.ceil(
parameters.config._SLICE_DURATION_SEC*processing_rate/
int(spec.mapper.shard_cou... | 631,705 |
Update mr state by examing shard states.
Args:
state: current mapreduce state as MapreduceState.
shard_states: an iterator over shard states.
control: model.MapreduceControl entity. | def _update_state_from_shard_states(self, state, shard_states, control):
# Initialize vars.
state.active_shards, state.aborted_shards, state.failed_shards = 0, 0, 0
total_shards = 0
processed_counts = []
processed_status = []
state.counters_map.clear()
# Tally across shard states once.... | 631,710 |
Finalize outputs.
Args:
mapreduce_spec: an instance of MapreduceSpec.
mapreduce_state: an instance of MapreduceState. | def _finalize_outputs(cls, mapreduce_spec, mapreduce_state):
# Only finalize the output writers if the job is successful.
if (mapreduce_spec.mapper.output_writer_class() and
mapreduce_state.result_status == model.MapreduceState.RESULT_SUCCESS):
mapreduce_spec.mapper.output_writer_class().fina... | 631,711 |
Finalize job execution.
Invokes done callback and save mapreduce state in a transaction,
and schedule necessary clean ups. This method is idempotent.
Args:
mapreduce_spec: an instance of MapreduceSpec
mapreduce_state: an instance of MapreduceState | def _finalize_job(cls, mapreduce_spec, mapreduce_state):
config = util.create_datastore_write_config(mapreduce_spec)
queue_name = util.get_queue_name(mapreduce_spec.params.get(
model.MapreduceSpec.PARAM_DONE_CALLBACK_QUEUE))
done_callback = mapreduce_spec.params.get(
model.MapreduceSpec... | 631,712 |
Schedule new update status callback task.
Args:
mapreduce_state: mapreduce state as model.MapreduceState
mapreduce_spec: mapreduce specification as MapreduceSpec.
serial_id: id of the invocation as int.
queue_name: The queue to schedule this task on. Will use the current
queue of ex... | def reschedule(cls,
mapreduce_state,
mapreduce_spec,
serial_id,
queue_name=None):
task_name = ControllerCallbackHandler.get_task_name(
mapreduce_spec, serial_id)
task_params = ControllerCallbackHandler.controller_parameters(
... | 631,713 |
Get input readers.
Args:
state: a MapreduceState model.
Returns:
A tuple: (a list of input readers, a model._HugeTaskPayload entity).
The payload entity contains the json serialized input readers.
(None, None) when input reader inplitting returned no data to process. | def _get_input_readers(self, state):
serialized_input_readers_key = (self._SERIALIZED_INPUT_READERS_KEY %
state.key().id_or_name())
serialized_input_readers = model._HugeTaskPayload.get_by_key_name(
serialized_input_readers_key, parent=state)
# Initialize in... | 631,716 |
Run transaction to save state.
Args:
state: a model.MapreduceState entity.
serialized_readers_entity: a model._HugeTaskPayload entity containing
json serialized input readers.
Returns:
False if a fatal error is encountered and this task should be dropped
immediately. True if tran... | def _save_states(self, state, serialized_readers_entity):
mr_id = state.key().id_or_name()
fresh_state = model.MapreduceState.get_by_job_id(mr_id)
if not self._check_mr_state(fresh_state, mr_id):
return False
if fresh_state.active_shards != 0:
logging.warning(
"Mapreduce %s al... | 631,718 |
Check MapreduceState.
Args:
state: an MapreduceState instance.
mr_id: mapreduce id.
Returns:
True if state is valid. False if not and this task should be dropped. | def _check_mr_state(cls, state, mr_id):
if state is None:
logging.warning(
"Mapreduce State for job %s is missing. Dropping Task.",
mr_id)
return False
if not state.active:
logging.warning(
"Mapreduce %s is not active. Looks like spurious task "
"ex... | 631,720 |
Retrieves additional user-supplied params for the job and validates them.
Args:
validator_parameter: name of the request parameter which supplies
validator for this parameter set.
name_prefix: common prefix for all parameter names in the request.
Raises:
Any exception raised by the '... | def _get_params(self, validator_parameter, name_prefix):
params_validator = self.request.get(validator_parameter)
user_params = {}
for key in self.request.arguments():
if key.startswith(name_prefix):
values = self.request.get_all(key)
adjusted_key = key[len(name_prefix):]
... | 631,722 |
Get a required request parameter.
Args:
param_name: name of request parameter to fetch.
Returns:
parameter value
Raises:
errors.NotEnoughArgumentsError: if parameter is not specified. | def _get_required_param(self, param_name):
value = self.request.get(param_name)
if not value:
raise errors.NotEnoughArgumentsError(param_name + " not specified")
return value | 631,723 |
Save mapreduce state to datastore.
Save state to datastore so that UI can see it immediately.
Args:
mapreduce_spec: model.MapreduceSpec,
_app: app id if specified. None otherwise.
Returns:
The saved Mapreduce state. | def _create_and_save_state(cls, mapreduce_spec, _app):
state = model.MapreduceState.create_new(mapreduce_spec.mapreduce_id)
state.mapreduce_spec = mapreduce_spec
state.active = True
state.active_shards = 0
if _app:
state.app_id = _app
config = util.create_datastore_write_config(mapred... | 631,725 |
Schedule finalize task.
Args:
mapreduce_spec: mapreduce specification as MapreduceSpec. | def schedule(cls, mapreduce_spec):
task_name = mapreduce_spec.mapreduce_id + "-finalize"
finalize_task = taskqueue.Task(
name=task_name,
url=(mapreduce_spec.params["base_path"] + "/finalizejob_callback/" +
mapreduce_spec.mapreduce_id),
params={"mapreduce_id": mapreduce_... | 631,728 |
Helper for _split_input_from_params.
If there are not enough Entities to make all of the given shards, the
returned list of KeyRanges will include Nones. The returned list will
contain KeyRanges ordered lexographically with any Nones appearing at the
end.
Args:
app: the app.
namespace:... | def _split_input_from_namespace(cls, app, namespace, entity_kind,
shard_count):
raw_entity_kind = cls._get_raw_entity_kind(entity_kind)
if shard_count == 1:
# With one shard we don't need to calculate any splitpoints at all.
return [key_range.KeyRange(namespac... | 631,745 |
Validates mapper spec and all mapper parameters.
Args:
mapper_spec: The MapperSpec for this InputReader.
Raises:
BadReaderParamsError: required parameters are missing or invalid. | def validate(cls, mapper_spec):
if mapper_spec.input_reader_class() != cls:
raise BadReaderParamsError("Input reader class mismatch")
params = _get_params(mapper_spec)
if cls.ENTITY_KIND_PARAM not in params:
raise BadReaderParamsError("Missing mapper parameter 'entity_kind'")
if cls.BAT... | 631,747 |
Create new DatastoreInputReader from the json, encoded by to_json.
Args:
json: json map representation of DatastoreInputReader.
Returns:
an instance of DatastoreInputReader with all data deserialized from json. | def from_json(cls, json):
if json[cls.KEY_RANGE_PARAM] is None:
# pylint: disable=redefined-outer-name
key_ranges = None
else:
key_ranges = []
for k in json[cls.KEY_RANGE_PARAM]:
if k:
key_ranges.append(key_range.KeyRange.from_json(k))
else:
key_r... | 631,750 |
Validates mapper spec and all mapper parameters.
Args:
mapper_spec: The MapperSpec for this InputReader.
Raises:
BadReaderParamsError: required parameters are missing or invalid. | def validate(cls, mapper_spec):
if mapper_spec.input_reader_class() != cls:
raise BadReaderParamsError("Mapper input reader class mismatch")
params = _get_params(mapper_spec)
if cls.BLOB_KEYS_PARAM not in params:
raise BadReaderParamsError("Must specify 'blob_keys' for mapper input")
bl... | 631,755 |
Returns a list of shard_count input_spec_shards for input_spec.
Args:
mapper_spec: The mapper specification to split from. Must contain
'blob_keys' parameter with one or more blob keys.
Returns:
A list of BlobstoreInputReaders corresponding to the specified shards. | def split_input(cls, mapper_spec):
params = _get_params(mapper_spec)
blob_keys = params[cls.BLOB_KEYS_PARAM]
if isinstance(blob_keys, basestring):
# This is a mechanism to allow multiple blob keys (which do not contain
# commas) in a single string. It may go away.
blob_keys = blob_key... | 631,756 |
Read entry content.
Args:
entry: zip file entry as zipfile.ZipInfo.
Returns:
Entry content as string. | def _read(self, entry):
start_time = time.time()
content = self._zip.read(entry.filename)
ctx = context.get()
if ctx:
operation.counters.Increment(COUNTER_IO_READ_BYTES, len(content))(ctx)
operation.counters.Increment(
COUNTER_IO_READ_MSEC, int((time.time() - start_time) * 10... | 631,759 |
Creates an instance of the InputReader for the given input shard state.
Args:
json: The InputReader state as a dict-like object.
Returns:
An instance of the InputReader configured using the values of json. | def from_json(cls, json):
return cls(json[cls.BLOB_KEY_PARAM],
json[cls.START_INDEX_PARAM],
json[cls.END_INDEX_PARAM]) | 631,760 |
Validates mapper spec and all mapper parameters.
Args:
mapper_spec: The MapperSpec for this InputReader.
Raises:
BadReaderParamsError: required parameters are missing or invalid. | def validate(cls, mapper_spec):
if mapper_spec.input_reader_class() != cls:
raise BadReaderParamsError("Mapper input reader class mismatch")
params = _get_params(mapper_spec)
if cls.BLOB_KEY_PARAM not in params:
raise BadReaderParamsError("Must specify 'blob_key' for mapper input")
blob... | 631,762 |
Returns a list of input shard states for the input spec.
Args:
mapper_spec: The MapperSpec for this InputReader. Must contain
'blob_key' parameter with one blob key.
_reader: a callable that returns a file-like object for reading blobs.
Used for dependency injection.
Returns:
... | def split_input(cls, mapper_spec, _reader=blobstore.BlobReader):
params = _get_params(mapper_spec)
blob_key = params[cls.BLOB_KEY_PARAM]
zip_input = zipfile.ZipFile(_reader(blob_key))
zfiles = zip_input.infolist()
total_size = sum(x.file_size for x in zfiles)
num_shards = min(mapper_spec.sh... | 631,763 |
Creates an instance of the InputReader for the given input shard state.
Args:
json: The InputReader state as a dict-like object.
_reader: For dependency injection.
Returns:
An instance of the InputReader configured using the values of json. | def from_json(cls, json, _reader=blobstore.BlobReader):
return cls(json[cls.BLOB_KEY_PARAM],
json[cls.START_FILE_INDEX_PARAM],
json[cls.END_FILE_INDEX_PARAM],
json[cls.OFFSET_PARAM],
_reader) | 631,769 |
Initialize input reader.
Args:
count: number of entries this shard should generate.
string_length: the length of generated random strings. | def __init__(self, count, string_length):
self._count = count
self._string_length = string_length | 631,771 |
Create new DatastoreInputReader from the json, encoded by to_json.
Args:
json: json map representation of DatastoreInputReader.
Returns:
an instance of DatastoreInputReader with all data deserialized from json. | def from_json(cls, json):
return cls(
namespace_range.NamespaceRange.from_json_object(
json[cls.NAMESPACE_RANGE_PARAM]),
json[cls.BATCH_SIZE_PARAM]) | 631,779 |
Validates mapper spec.
Args:
mapper_spec: The MapperSpec for this InputReader.
Raises:
BadReaderParamsError: required parameters are missing or invalid. | def validate(cls, mapper_spec):
if mapper_spec.input_reader_class() != cls:
raise BadReaderParamsError("Input reader class mismatch")
params = _get_params(mapper_spec)
if cls.BATCH_SIZE_PARAM in params:
try:
batch_size = int(params[cls.BATCH_SIZE_PARAM])
if batch_size < 1:
... | 631,780 |
Returns a list of input readers for the input spec.
Args:
mapper_spec: The MapperSpec for this InputReader.
Returns:
A list of InputReaders. | def split_input(cls, mapper_spec):
batch_size = int(_get_params(mapper_spec).get(
cls.BATCH_SIZE_PARAM, cls._BATCH_SIZE))
shard_count = mapper_spec.shard_count
namespace_ranges = namespace_range.NamespaceRange.split(shard_count,
contig... | 631,781 |
Creates an instance of the InputReader for the given input shard's state.
Args:
json: The InputReader state as a dict-like object.
Returns:
An instance of the InputReader configured using the given JSON parameters. | def from_json(cls, json):
# Strip out unrecognized parameters, as introduced by b/5960884.
params = dict((str(k), v) for k, v in json.iteritems()
if k in cls._PARAMS)
# This is not symmetric with to_json() wrt. PROTOTYPE_REQUEST_PARAM because
# the constructor parameters need to ... | 631,785 |
Returns a list of input readers for the given input specification.
Args:
mapper_spec: The MapperSpec for this InputReader.
Returns:
A list of InputReaders. | def split_input(cls, mapper_spec):
params = _get_params(mapper_spec)
shard_count = mapper_spec.shard_count
# Pick out the overall start and end times and time step per shard.
start_time = params[cls.START_TIME_PARAM]
end_time = params[cls.END_TIME_PARAM]
seconds_per_shard = (end_time - sta... | 631,787 |
Validates the mapper's specification and all necessary parameters.
Args:
mapper_spec: The MapperSpec to be used with this InputReader.
Raises:
BadReaderParamsError: If the user fails to specify both a starting time
and an ending time, or if the starting time is later than the ending
... | def validate(cls, mapper_spec):
if mapper_spec.input_reader_class() != cls:
raise errors.BadReaderParamsError("Input reader class mismatch")
params = _get_params(mapper_spec, allowed_keys=cls._PARAMS)
if (cls.VERSION_IDS_PARAM not in params and
cls.MODULE_VERSIONS_PARAM not in params):
... | 631,788 |
Initialize a GoogleCloudStorageInputReader instance.
Args:
filenames: A list of Google Cloud Storage filenames of the form
'/bucket/objectname'.
index: Index of the next filename to read.
buffer_size: The size of the read buffer, None to use default.
_account_id: Internal use only. ... | def __init__(self, filenames, index=0, buffer_size=None, _account_id=None,
delimiter=None):
self._filenames = filenames
self._index = index
self._buffer_size = buffer_size
self._account_id = _account_id
self._delimiter = delimiter
self._bucket = None
self._bucket_iter = N... | 631,790 |
Validate mapper specification.
Args:
mapper_spec: an instance of model.MapperSpec
Raises:
BadReaderParamsError: if the specification is invalid for any reason such
as missing the bucket name or providing an invalid bucket name. | def validate(cls, mapper_spec):
reader_spec = cls.get_params(mapper_spec, allow_old=False)
# Bucket Name is required
if cls.BUCKET_NAME_PARAM not in reader_spec:
raise errors.BadReaderParamsError(
"%s is required for Google Cloud Storage" %
cls.BUCKET_NAME_PARAM)
try:
... | 631,793 |
Returns a list of input readers.
An equal number of input files are assigned to each shard (+/- 1). If there
are fewer files than shards, fewer than the requested number of shards will
be used. Input files are currently never split (although for some formats
could be and may be split in a future implem... | def split_input(cls, mapper_spec):
reader_spec = cls.get_params(mapper_spec, allow_old=False)
bucket = reader_spec[cls.BUCKET_NAME_PARAM]
filenames = reader_spec[cls.OBJECT_NAMES_PARAM]
delimiter = reader_spec.get(cls.DELIMITER_PARAM)
account_id = reader_spec.get(cls._ACCOUNT_ID_PARAM)
buff... | 631,794 |
Creates an instance of the InputReader for the given input shard state.
Args:
json: The InputReader state as a dict-like object.
Returns:
An instance of the InputReader configured using the values of json. | def from_json(cls, json):
result = super(_ReducerReader, cls).from_json(json)
result.current_key = _ReducerReader.decode_data(json["current_key"])
result.current_values = _ReducerReader.decode_data(json["current_values"])
return result | 631,804 |
Init.
The signature of __init__ is subject to change.
Read only properties:
job_context: JobContext object.
id: str. of format job_id-shard_number.
number: int. shard number. 0 indexed.
attempt: int. The current attempt at executing this shard.
Starting at 1.
Args:
j... | def __init__(self, job_context, shard_state):
self.job_context = job_context
self.id = shard_state.shard_id
self.number = shard_state.shard_number
self.attempt = shard_state.retries + 1
self._state = shard_state | 631,805 |
Changes counter by delta.
Args:
counter_name: the name of the counter to change. str.
delta: int. | def incr(self, counter_name, delta=1):
self._state.counters_map.increment(counter_name, delta) | 631,806 |
Get the current counter value.
Args:
counter_name: name of the counter in string.
default: default value in int if one doesn't exist.
Returns:
Current value of the counter. | def counter(self, counter_name, default=0):
return self._state.counters_map.get(counter_name, default) | 631,807 |
Init.
The signature of __init__ is subject to change.
Read only properties:
job_context: JobContext object.
shard_context: ShardContext object.
number: int. slice number. 0 indexed.
attempt: int. The current attempt at executing this slice.
starting at 1.
Args:
shard... | def __init__(self, shard_context, shard_state, tstate):
self._tstate = tstate
self.job_context = shard_context.job_context
self.shard_context = shard_context
self.number = shard_state.slice_id
self.attempt = shard_state.slice_retries + 1 | 631,808 |
Emits a value to output writer.
Args:
value: a value of type expected by the output writer. | def emit(self, value):
if not self._tstate.output_writer:
logging.error("emit is called, but no output writer is set.")
return
self._tstate.output_writer.write(value) | 631,809 |
Initialize a GoogleCloudStorageInputReader instance.
Args:
filenames: A list of Google Cloud Storage filenames of the form
'/bucket/objectname'.
index: Index of the next filename to read.
buffer_size: The size of the read buffer, None to use default.
_account_id: Internal use only. ... | def __init__(self, filenames, index=0, buffer_size=None, _account_id=None,
delimiter=None, path_filter=None):
super(GCSInputReader, self).__init__()
self._filenames = filenames
self._index = index
self._buffer_size = buffer_size
self._account_id = _account_id
self._delimiter ... | 631,810 |
Validate mapper specification.
Args:
job_config: map_job.JobConfig.
Raises:
BadReaderParamsError: if the specification is invalid for any reason such
as missing the bucket name or providing an invalid bucket name. | def validate(cls, job_config):
reader_params = job_config.input_reader_params
# Bucket Name is required
if cls.BUCKET_NAME_PARAM not in reader_params:
raise errors.BadReaderParamsError(
"%s is required for Google Cloud Storage" %
cls.BUCKET_NAME_PARAM)
try:
cloudsto... | 631,811 |
Returns a list of input readers.
An equal number of input files are assigned to each shard (+/- 1). If there
are fewer files than shards, fewer than the requested number of shards will
be used. Input files are currently never split (although for some formats
could be and may be split in a future implem... | def split_input(cls, job_config):
reader_params = job_config.input_reader_params
bucket = reader_params[cls.BUCKET_NAME_PARAM]
filenames = reader_params[cls.OBJECT_NAMES_PARAM]
delimiter = reader_params.get(cls.DELIMITER_PARAM)
account_id = reader_params.get(cls._ACCOUNT_ID_PARAM)
buffer_si... | 631,812 |
Get a list of key_ranges.KeyRanges objects, one for each shard.
This method uses scatter index to split each namespace into pieces
and assign those pieces to shards.
Args:
app: app_id in str.
namespaces: a list of namespaces in str.
shard_count: number of shards to split.
query_spe... | def _to_key_ranges_by_shard(cls, app, namespaces, shard_count, query_spec):
key_ranges_by_ns = []
# Split each ns into n splits. If a ns doesn't have enough scatter to
# split into n, the last few splits are None.
for namespace in namespaces:
ranges = cls._split_ns_by_scatter(
shard... | 631,822 |
Converts a namespace string into an int representing its lexographic order.
>>> _namespace_to_ord('')
''
>>> _namespace_to_ord('_')
1
>>> _namespace_to_ord('__')
2
Args:
namespace: A namespace string.
Returns:
An int representing the lexographical order of the given namespace string. | def _namespace_to_ord(namespace):
n = 0
for i, c in enumerate(namespace):
n += (_LEX_DISTANCE[MAX_NAMESPACE_LENGTH - i- 1] *
NAMESPACE_CHARACTERS.index(c)
+ 1)
return n | 631,827 |
Return the __namespace__ key for a namespace.
Args:
namespace: The namespace whose key is requested.
app: The id of the application that the key belongs to.
Returns:
A db.Key representing the namespace. | def _key_for_namespace(namespace, app):
if namespace:
return db.Key.from_path(metadata.Namespace.KIND_NAME,
namespace,
_app=app)
else:
return db.Key.from_path(metadata.Namespace.KIND_NAME,
metadata.Namespace.EMPTY_NAMESPA... | 631,828 |
Returns a copy of this NamespaceName with a new namespace_start.
Args:
after_namespace: A namespace string.
Returns:
A NamespaceRange object whose namespace_start is the lexographically next
namespace after the given namespace string.
Raises:
ValueError: if the NamespaceRange incl... | def with_start_after(self, after_namespace):
namespace_start = _ord_to_namespace(_namespace_to_ord(after_namespace) + 1)
return NamespaceRange(namespace_start, self.namespace_end, _app=self.app) | 631,835 |
Returns a datastore.Query that generates all namespaces in the range.
Args:
cursor: start cursor for the query.
Returns:
A datastore.Query instance that generates db.Keys for each namespace in
the NamespaceRange. | def make_datastore_query(self, cursor=None):
filters = {}
filters['__key__ >= '] = _key_for_namespace(
self.namespace_start, self.app)
filters['__key__ <= '] = _key_for_namespace(
self.namespace_end, self.app)
return datastore.Query('__namespace__',
filte... | 631,836 |
Constructor.
Any classes that subclass this will need to implement the _write() function.
Args:
flush_size_chars: buffer flush threshold as int.
ctx: mapreduce context as context.Context.
exclusive: a boolean flag indicating if the pool has an exclusive
access to the file. If it is T... | def __init__(self,
flush_size_chars=_FILE_POOL_FLUSH_SIZE,
ctx=None,
exclusive=False):
self._flush_size = flush_size_chars
self._buffer = []
self._size = 0
self._ctx = ctx
self._exclusive = exclusive | 631,841 |
Flush pool contents.
Args:
force: Inserts additional padding to achieve the minimum block size
required for GCS. | def flush(self, force=False):
super(GCSRecordsPool, self).flush()
if force:
extra_padding = self._buf_size % self._GCS_BLOCK_SIZE
if extra_padding > 0:
self._write("\x00" * (self._GCS_BLOCK_SIZE - extra_padding))
self._filehandle.flush() | 631,846 |
Validate mapper specification.
Args:
mapper_spec: an instance of model.MapperSpec.
Raises:
BadWriterParamsError: if the specification is invalid for any reason such
as missing the bucket name or providing an invalid bucket name. | def validate(cls, mapper_spec):
writer_spec = cls.get_params(mapper_spec, allow_old=False)
# Bucket Name is required
if cls.BUCKET_NAME_PARAM not in writer_spec:
raise errors.BadWriterParamsError(
"%s is required for Google Cloud Storage" %
cls.BUCKET_NAME_PARAM)
try:
... | 631,850 |
Write data to the GoogleCloudStorage file.
Args:
data: string containing the data to be written. | def write(self, data):
start_time = time.time()
self._get_write_buffer().write(data)
ctx = context.get()
operation.counters.Increment(COUNTER_IO_WRITE_BYTES, len(data))(ctx)
operation.counters.Increment(
COUNTER_IO_WRITE_MSEC, int((time.time() - start_time) * 1000))(ctx) | 631,853 |
Initialize a GoogleCloudStorageOutputWriter instance.
Args:
streaming_buffer: an instance of writable buffer from cloudstorage_api.
writer_spec: the specification for the writer. | def __init__(self, streaming_buffer, writer_spec=None):
self._streaming_buffer = streaming_buffer
self._no_dup = False
if writer_spec:
self._no_dup = writer_spec.get(self._NO_DUPLICATE, False)
if self._no_dup:
# This is the index of the current seg, starting at 0.
# This number is... | 631,854 |
Tries to remove any files created by this shard that aren't needed.
Args:
writer_spec: writer_spec for the MR.
exclude_list: A list of filenames (strings) that should not be
removed. | def _try_to_clean_garbage(self, writer_spec, exclude_list=()):
# Try to remove garbage (if any). Note that listbucket is not strongly
# consistent so something might survive.
tmpl = string.Template(self._TMPFILE_PREFIX)
prefix = tmpl.substitute(
id=self.status.mapreduce_id, shard=self.statu... | 631,871 |
Get weights for each offset in str of certain max length.
Args:
max_length: max length of the strings.
Returns:
A list of ints as weights.
Example:
If max_length is 2 and alphabet is "ab", then we have order "", "a", "aa",
"ab", "b", "ba", "bb". So the weight for the first char is 3. | def _get_weights(max_length):
weights = [1]
for i in range(1, max_length):
weights.append(weights[i-1] * len(_ALPHABET) + 1)
weights.reverse()
return weights | 631,886 |
Converts a string to its lexicographical order.
Args:
content: the string to convert. Of type str.
weights: weights from _get_weights.
Returns:
an int or long that represents the order of this string. "" has order 0. | def _str_to_ord(content, weights):
ordinal = 0
for i, c in enumerate(content):
ordinal += weights[i] * _ALPHABET.index(c) + 1
return ordinal | 631,887 |
Init.
Args:
filters: user supplied filters. Each filter should be a list or tuple of
format (<property_name_as_str>, <query_operator_as_str>,
<value_of_certain_type>). Value type should satisfy the property's type.
model_class_path: full path to the model class in str. | def __init__(self,
filters,
model_class_path):
self.filters = filters
self.model_class_path = model_class_path
self.model_class = util.for_name(self.model_class_path)
self.prop, self.start, self.end = self._get_range_from_filters(
self.filters, self.model_class... | 631,889 |
Evenly split this range into contiguous, non overlapping subranges.
Args:
n: number of splits.
Returns:
a list of contiguous, non overlapping sub PropertyRanges. Maybe less than
n when not enough subranges. | def split(self, n):
new_range_filters = []
name = self.start[0]
prop_cls = self.prop.__class__
if prop_cls in _DISCRETE_PROPERTY_SPLIT_FUNCTIONS:
splitpoints = _DISCRETE_PROPERTY_SPLIT_FUNCTIONS[prop_cls](
self.start[2], self.end[2], n,
self.start[1] == ">=", self.end[1] =... | 631,891 |
Make a query of entities within this range.
Query options are not supported. They should be specified when the query
is run.
Args:
ns: namespace of this query.
Returns:
a db.Query or ndb.Query, depends on the model class's type. | def make_query(self, ns):
if issubclass(self.model_class, db.Model):
query = db.Query(self.model_class, namespace=ns)
for f in self.filters:
query.filter("%s %s" % (f[0], f[1]), f[2])
else:
query = self.model_class.query(namespace=ns)
for f in self.filters:
query = q... | 631,892 |
Validates relevant parameters.
This method can validate fields which it deems relevant.
Args:
job_config: an instance of map_job.JobConfig.
Raises:
errors.BadWriterParamsError: required parameters are missing or invalid. | def validate(cls, job_config):
if job_config.output_writer_cls != cls:
raise errors.BadWriterParamsError(
"Expect output writer class %r, got %r." %
(cls, job_config.output_writer_cls)) | 631,893 |
Saves output references when a shard finishes.
Inside end_shard(), an output writer can optionally use this method
to persist some references to the outputs from this shard
(e.g a list of filenames)
Args:
shard_ctx: map_job_context.ShardContext for this shard.
iterator: an iterator that yi... | def commit_output(cls, shard_ctx, iterator):
# We accept an iterator just in case output references get too big.
outs = tuple(iterator)
shard_ctx._state.writer_state["outs"] = outs | 631,894 |
Deserialize from json.
Args:
json: a dict of json compatible fields.
Returns:
a KeyRanges object.
Raises:
ValueError: if the json is invalid. | def from_json(cls, json):
if json["name"] in _KEYRANGES_CLASSES:
return _KEYRANGES_CLASSES[json["name"]].from_json(json)
raise ValueError("Invalid json %s", json) | 631,897 |
Initializes the error with a message.
Args:
message (str): Message passed to Exception
raises (bool): Whether this should be raised outside custodian | def __init__(self, message, raises=False):
super(CustodianError, self).__init__(message)
self.raises = raises
self.message = message | 631,928 |
Initializes the handler with the output file to check.
Args:
output_filename (str): This is the file where the stderr for vasp
is being redirected. The error messages that are checked are
present in the stderr. Defaults to "std_err.txt", which is the
... | def __init__(self, output_filename="std_err.txt"):
self.output_filename = output_filename
self.errors = set()
self.error_count = Counter() | 631,940 |
Initializes the handler with max drift
Args:
max_drift (float): This defines the max drift. Leaving this at the default of None gets the max_drift from EDFIFFG | def __init__(self, max_drift=None, to_average=3, enaug_multiply=2):
self.max_drift = max_drift
self.to_average = int(to_average)
self.enaug_multiply = enaug_multiply | 631,946 |
Initializes the handler with the output file to check.
Args:
output_filename (str): This is the OSZICAR file. Change
this only if it is different from the default (unlikely).
nionic_steps (int): The threshold number of ionic steps that
needs to hit the ma... | def __init__(self, output_filename="OSZICAR", nionic_steps=10):
self.output_filename = output_filename
self.nionic_steps = nionic_steps | 631,963 |
Initializes the handler with an interval.
Args:
interval (int): Interval at which to checkpoint in seconds.
Defaults to 3600 (1 hr). | def __init__(self, interval=3600):
self.interval = interval
self.start_time = datetime.datetime.now()
self.chk_counter = 0 | 631,969 |
Applies a list of actions to the FEFF Input Set and rewrites modified
files.
Args:
actions [dict]: A list of actions of the form {'file': filename,
'action': moddermodification} or {'dict': feffinput_key,
'action': moddermodification} | def apply_actions(self, actions):
modified = []
for a in actions:
if "dict" in a:
k = a["dict"]
modified.append(k)
self.feffinp[k] = self.modify_object(a["action"], self.feffinp[k])
elif "file" in a:
self.mo... | 631,976 |
Creates a file.
Args:
filename (str): Filename.
settings (dict): Must be {"content": actual_content} | def file_create(filename, settings):
if len(settings) != 1:
raise ValueError("Settings must only contain one item with key "
"'content'.")
for k, v in settings.items():
if k == "content":
with open(filename, 'w') as f:
... | 631,987 |
Moves a file. {'_file_move': {'dest': 'new_file_name'}}
Args:
filename (str): Filename.
settings (dict): Must be {"dest": path of new file} | def file_move(filename, settings):
if len(settings) != 1:
raise ValueError("Settings must only contain one item with key "
"'dest'.")
for k, v in settings.items():
if k == "dest":
shutil.move(filename, v) | 631,988 |
Deletes a file. {'_file_delete': {'mode': "actual"}}
Args:
filename (str): Filename.
settings (dict): Must be {"mode": actual/simulated}. Simulated
mode only prints the action without performing it. | def file_delete(filename, settings):
if len(settings) != 1:
raise ValueError("Settings must only contain one item with key "
"'mode'.")
for k, v in settings.items():
if k == "mode" and v == "actual":
try:
o... | 631,989 |
Copies a file. {'_file_copy': {'dest': 'new_file_name'}}
Args:
filename (str): Filename.
settings (dict): Must be {"dest": path of new file} | def file_copy(filename, settings):
for k, v in settings.items():
if k.startswith("dest"):
shutil.copyfile(filename, v) | 631,990 |
Modifies file access
Args:
filename (str): Filename.
settings (dict): Can be "mode" or "owners" | def file_modify(filename, settings):
for k, v in settings.items():
if k == "mode":
os.chmod(filename,v)
if k == "owners":
os.chown(filename,v) | 631,991 |
Modify an object that supports pymatgen's as_dict() and from_dict API.
Args:
modification (dict): Modification must be {action_keyword :
settings}. E.g., {'_set': {'Hello':'Universe', 'Bye': 'World'}}
obj (object): Object to modify | def modify_object(self, modification, obj):
d = obj.as_dict()
self.modify(modification, d)
return obj.from_dict(d) | 632,000 |
Applies a list of actions to the Vasp Input Set and rewrites modified
files.
Args:
actions [dict]: A list of actions of the form {'file': filename,
'action': moddermodification} or {'dict': vaspinput_key,
'action': moddermodification} | def apply_actions(self, actions):
modified = []
for a in actions:
if "dict" in a:
k = a["dict"]
modified.append(k)
self.vi[k] = self.modify_object(a["action"], self.vi[k])
elif "file" in a:
self.modify(a["ac... | 632,012 |
Initializes the error handler from a set of input and output files.
Args:
input_file (str): Name of the QChem input file.
output_file (str): Name of the QChem output file.
scf_max_cycles (int): The max iterations to set to fix SCF failure.
geom_max_cycles (int): ... | def __init__(self,
input_file="mol.qin",
output_file="mol.qout",
scf_max_cycles=200,
geom_max_cycles=200):
self.input_file = input_file
self.output_file = output_file
self.scf_max_cycles = scf_max_cycles
self.ge... | 632,013 |
Initializes the error handler from a set of input and output files.
Args:
input_file (str): Name of the QChem input file.
output_file (str): Name of the QChem output file.
rca_gdm_thresh (float): The threshold for the prior scf algorithm.
If last deltaE is la... | def __init__(self,
input_file="mol.qin",
output_file="mol.qout",
rca_gdm_thresh=1.0E-3,
scf_max_cycles=200):
self.input_file = input_file
self.output_file = output_file
self.scf_max_cycles = scf_max_cycles
self.... | 632,016 |
Backup files to a tar.gz file. Used, for example, in backing up the
files of an errored run before performing corrections.
Args:
filenames ([str]): List of files to backup. Supports wildcards, e.g.,
*.*.
prefix (str): prefix to the files. Defaults to error, which means a
... | def backup(filenames, prefix="error"):
num = max([0] + [int(f.split(".")[1])
for f in glob("{}.*.tar.gz".format(prefix))])
filename = "{}.{}.tar.gz".format(prefix, num + 1)
logging.info("Backing up run to {}.".format(filename))
with tarfile.open(filename, "w:gz") as tar:
... | 632,021 |
Generates a VASP input based on an existing directory. This is typically
used to modify the VASP input files before the next VaspJob.
Args:
input_set (str): Full path to the input set. E.g.,
"pymatgen.io.vasp.sets.MPNonSCFSet".
contcar_only (bool): If True (defau... | def __init__(self, input_set, contcar_only=True, **kwargs):
self.input_set = input_set
self.contcar_only = contcar_only
self.kwargs = kwargs | 632,041 |
Removes extra dimensions added by the add_dimensions() function.
Ignores dimension names that don't exist.
Args:
dimension_names (list): List of dimension names to remove. | def remove_dimensions(self, dimension_names):
with self._lock:
for dimension in dimension_names:
if dimension in self._extra_dimensions:
del self._extra_dimensions[dimension] | 632,807 |
Send the given metrics to SignalFx.
Args:
cumulative_counters (list): a list of dictionaries representing the
cumulative counters to report.
gauges (list): a list of dictionaries representing the gauges to
report.
counters (list): a list of di... | def send(self, cumulative_counters=None, gauges=None, counters=None):
if not gauges and not cumulative_counters and not counters:
return
data = {
'cumulative_counter': cumulative_counters,
'gauge': gauges,
'counter': counters,
}
_... | 632,808 |
Send an event to SignalFx.
Args:
event_type (string): the event type (name of the event time
series).
category (string): the category of the event.
dimensions (dict): a map of event dimensions.
properties (dict): a map of extra properties on that ... | def send_event(self, event_type, category=None, dimensions=None,
properties=None, timestamp=None):
if category and category not in SUPPORTED_EVENT_CATEGORIES:
raise ValueError('Event category is not one of the supported' +
'types: {' +
... | 632,809 |
generic function to get object (metadata, tag, ) by name from SignalFx.
Args:
object_endpoint (string): API endpoint suffix (e.g. 'v2/tag')
object_name (string): name of the object (e.g. 'jvm.cpu.load')
Returns:
dictionary of response | def _get_object_by_name(self, object_endpoint, object_name, timeout=None):
timeout = timeout or self._timeout
resp = self._get(self._u(object_endpoint, object_name),
session=self._session, timeout=timeout)
resp.raise_for_status()
return resp.json() | 632,844 |
get a metric by name
Args:
metric_name (string): name of metric
Returns:
dictionary of response | def get_metric_by_name(self, metric_name, **kwargs):
return self._get_object_by_name(self._METRIC_ENDPOINT_SUFFIX,
metric_name,
**kwargs) | 632,846 |
Create or update a metric object
Args:
metric_name (string): name of metric
type (string): metric type, must be one of 'gauge', 'counter',
'cumulative_counter'
description (optional[string]): a description
custom_properties (optional[d... | def update_metric_by_name(self, metric_name, metric_type, description=None,
custom_properties=None, tags=None, **kwargs):
data = {'type': metric_type.upper(),
'description': description or '',
'customProperties': custom_properties or {},
... | 632,847 |
get a dimension by key and value
Args:
key (string): key of the dimension
value (string): value of the dimension
Returns:
dictionary of response | def get_dimension(self, key, value, **kwargs):
return self._get_object_by_name(self._DIMENSION_ENDPOINT_SUFFIX,
'{0}/{1}'.format(key, value),
**kwargs) | 632,849 |
update a dimension
Args:
key (string): key of the dimension
value (string): value of the dimension
description (optional[string]): a description
custom_properties (optional[dict]): dictionary of custom properties
tags (optional[list of strings]): list ... | def update_dimension(self, key, value, description=None,
custom_properties=None, tags=None, **kwargs):
data = {'description': description or '',
'customProperties': custom_properties or {},
'tags': tags or [],
'key': key,
... | 632,850 |
get a tag by name
Args:
tag_name (string): name of tag to get
Returns:
dictionary of the response | def get_tag(self, tag_name, **kwargs):
return self._get_object_by_name(self._TAG_ENDPOINT_SUFFIX,
tag_name,
**kwargs) | 632,854 |
update a tag by name
Args:
tag_name (string): name of tag to update
description (optional[string]): a description
custom_properties (optional[dict]): dictionary of custom properties | def update_tag(self, tag_name, description=None,
custom_properties=None, **kwargs):
data = {'description': description or '',
'customProperties': custom_properties or {}}
resp = self._put(self._u(self._TAG_ENDPOINT_SUFFIX, tag_name),
d... | 632,855 |
delete a tag by name
Args:
tag_name (string): name of tag to delete | def delete_tag(self, tag_name, **kwargs):
resp = self._delete(self._u(self._TAG_ENDPOINT_SUFFIX, tag_name),
**kwargs)
resp.raise_for_status()
# successful delete returns 204, which has no associated json
return resp | 632,856 |
Validate a detector.
Validates the given detector; throws a 400 Bad Request HTTP error if
the detector is invalid; otherwise doesn't return or throw anything.
Args:
detector (object): the detector model object. Will be serialized as
JSON. | def validate_detector(self, detector):
resp = self._post(self._u(self._DETECTOR_ENDPOINT_SUFFIX, 'validate'),
data=detector)
resp.raise_for_status() | 632,862 |
Creates a new detector.
Args:
detector (object): the detector model object. Will be serialized as
JSON.
Returns:
dictionary of the response (created detector model). | def create_detector(self, detector):
resp = self._post(self._u(self._DETECTOR_ENDPOINT_SUFFIX),
data=detector)
resp.raise_for_status()
return resp.json() | 632,863 |
Update an existing detector.
Args:
detector_id (string): the ID of the detector.
detector (object): the detector model object. Will be serialized as
JSON.
Returns:
dictionary of the response (updated detector model). | def update_detector(self, detector_id, detector):
resp = self._put(self._u(self._DETECTOR_ENDPOINT_SUFFIX, detector_id),
data=detector)
resp.raise_for_status()
return resp.json() | 632,864 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.