def get_batch(self, batch_size, next_states=False):

        if batch_size > len(self.observations):
            raise TensorForceError(
                "Requested batch size is larger than observations in memory: increase config.first_update.")

        states = {name: np.zeros((batch_size,) + tuple(state['shape']), dtype=util.np_dtype(
            state['type'])) for name, state in self.states_spec.items()}
        internals = [np.zeros((batch_size,) + shape, dtype)
                     for shape, dtype in self.internals_spec]
        actions = {name: np.zeros((batch_size,) + tuple(action['shape']), dtype=util.np_dtype(action['type'])) for name, action in self.actions_spec.items()}
        terminal = np.zeros((batch_size,), dtype=util.np_dtype('bool'))
        reward = np.zeros((batch_size,), dtype=util.np_dtype('float'))
        if next_states:
            next_states = {name: np.zeros((batch_size,) + tuple(state['shape']), dtype=util.np_dtype(
                state['type'])) for name, state in self.states_spec.items()}
            next_internals = [np.zeros((batch_size,) + shape, dtype)
                              for shape, dtype in self.internals_spec]

        unseen_indices = list(xrange(
            self.none_priority_index + self.observations._capacity - 1,
            len(self.observations) + self.observations._capacity - 1)
        )
        self.batch_indices = unseen_indices[:batch_size]

        remaining = batch_size - len(self.batch_indices)
        if remaining:
            samples = self.observations.sample_minibatch(remaining)
            sample_indices = [i for i, o in samples]
            self.batch_indices += sample_indices

        np.random.shuffle(self.batch_indices)

        for n, index in enumerate(self.batch_indices):
            observation, _ = self.observations._memory[index]

            for name, state in states.items():
                state[n] = observation[0][name]
            for k, internal in enumerate(internals):
                internal[n] = observation[1][k]
            for name, action in actions.items():
                action[n] = observation[2][name]
            terminal[n] = observation[3]
            reward[n] = observation[4]
            if next_states:
                for name, next_state in next_states.items():
                    next_state[n] = observation[5][name]
                for k, next_internal in enumerate(next_internals):
                    next_internal[n] = observation[6][k]

        if next_states:
            return dict(
                states=states,
                internals=internals,
                actions=actions,
                terminal=terminal,
                reward=reward,
                next_states=next_states,
                next_internals=next_internals
            )
        else:
            return dict(
                states=states,
                internals=internals,
                actions=actions,
                terminal=terminal,
                reward=reward
            )

Samples a batch of the specified size according to priority.

Args:
batch_size: The batch size
next_states: A boolean flag indicating whether 'next_states' values should be included

Returns: A dict containing states, actions, rewards, terminals, internal states (and next states)


def map_to_pdf(map_source, zoom, x, y, width, height):
    map_source = app.config['mapsources'][map_source]
    pdf_file = print_map(map_source, x=float(x), y=float(y), zoom=int(zoom), width=float(width), height=float(height), format='pdf')
    return send_file(pdf_file, attachment_filename='map.pdf', as_attachment=True)

Generate a PDF at the given position.

Args:
map_source (str): id of the map source to print.
zoom (int): zoom-level to print
x (float): Center of the Map in mercator projection (EPSG:4326), x-coordinate
y (float): Center of the Map in mercator projection (EPSG:4326), y-coordinate
width (float): width of the pdf in mm
height (float): height of the pdf in mm

Returns:


def _Open(self, path_spec=None, mode='rb'):

    if not path_spec:
      raise ValueError('Missing path specification.')

    if not path_spec.HasParent():
      raise errors.PathSpecError(
          'Unsupported path specification without parent.')

    self._file_system = resolver.Resolver.OpenFileSystem(
        path_spec, resolver_context=self._resolver_context)
    tsk_volume = self._file_system.GetTSKVolume()
    tsk_vs, _ = tsk_partition.GetTSKVsPartByPathSpec(tsk_volume, path_spec)

    if tsk_vs is None:
      raise errors.PathSpecError(
          'Unable to retrieve TSK volume system part from path '
          'specification.')

    range_offset = tsk_partition.TSKVsPartGetStartSector(tsk_vs)
    range_size = tsk_partition.TSKVsPartGetNumberOfSectors(tsk_vs)

    if range_offset is None or range_size is None:
      raise errors.PathSpecError(
          'Unable to retrieve TSK volume system part data range from path '
          'specification.')

    bytes_per_sector = tsk_partition.TSKVolumeGetBytesPerSector(tsk_volume)
    range_offset *= bytes_per_sector
    range_size *= bytes_per_sector

    self.SetRange(range_offset, range_size)
    self._file_object = resolver.Resolver.OpenFileObject(
        path_spec.parent, resolver_context=self._resolver_context)
    self._file_object_set_in_init = True

    super(TSKPartitionFile, self)._Open(path_spec=path_spec, mode=mode)

Opens the file-like object defined by path specification.

Args:
path_spec (PathSpec): path specification.
mode (Optional[str]): file access mode.

Raises:
AccessError: if the access to open the file was denied.
IOError: if the file-like object could not be opened.
OSError: if the file-like object could not be opened.
PathSpecError: if the path specification is incorrect.
ValueError: if the path specification is invalid.


def retryable(a_func, retry_options, **kwargs):

    delay_mult = retry_options.backoff_settings.retry_delay_multiplier
    max_delay_millis = retry_options.backoff_settings.max_retry_delay_millis
    has_timeout_settings = _has_timeout_settings(retry_options.backoff_settings)

    if has_timeout_settings:
        timeout_mult = retry_options.backoff_settings.rpc_timeout_multiplier
        max_timeout = (retry_options.backoff_settings.max_rpc_timeout_millis /
                       _MILLIS_PER_SECOND)
        total_timeout = (retry_options.backoff_settings.total_timeout_millis /
                         _MILLIS_PER_SECOND)

    def inner(*args):

        delay = retry_options.backoff_settings.initial_retry_delay_millis
        exc = errors.RetryError('Retry total timeout exceeded before any'
                                'response was received')
        if has_timeout_settings:
            timeout = (
                retry_options.backoff_settings.initial_rpc_timeout_millis /
                _MILLIS_PER_SECOND)

            now = time.time()
            deadline = now + total_timeout
        else:
            timeout = None
            deadline = None

        while deadline is None or now < deadline:
            try:
                to_call = add_timeout_arg(a_func, timeout, **kwargs)
                return to_call(*args)
            except Exception as exception:
                code = config.exc_to_code(exception)
                if code not in retry_options.retry_codes:
                    raise errors.RetryError(
                        'Exception occurred in retry method that was not'
                        ' classified as transient', exception)

                exc = errors.RetryError(
                    'Retry total timeout exceeded with exception', exception)

                to_sleep = random.uniform(0, delay * 2)
                time.sleep(to_sleep / _MILLIS_PER_SECOND)
                delay = min(delay * delay_mult, max_delay_millis)

                if has_timeout_settings:
                    now = time.time()
                    timeout = min(
                        timeout * timeout_mult, max_timeout, deadline - now)

        raise exc

    return inner

Creates a function equivalent to a_func, but that retries on certain
exceptions.

Args:
a_func (callable): A callable.
retry_options (RetryOptions): Configures the exceptions upon which the
callable should retry, and the parameters to the exponential backoff
retry algorithm.
kwargs: Addtional arguments passed through to the callable.

Returns:
Callable: A function that will retry on exception.


def json_dumps(self, data):

        return json.dumps(
            data,
            separators=(',', ':'),
            sort_keys=True,
            cls=self.json_encoder,
            ensure_ascii=False
        ).encode('utf8')

Standardized json.dumps function with separators and sorted keys set

Args:
data (dict or list): data to be dumped

Returns:
string: json


def get_specification(version: str) -> Mapping[str, Any]:

    spec_dir = config["bel"]["lang"]["specifications"]
    spec_dict = {}

    bel_versions = get_bel_versions()
    if version not in bel_versions:
        log.error("Cannot get unknown version BEL specification")
        return {"error": "unknown version of BEL"}

    version_underscored = version.replace(".", "_")

    json_fn = f"{spec_dir}/bel_v{version_underscored}.json"

    with open(json_fn, "r") as f:
        spec_dict = json.load(f)

    return spec_dict

Get BEL Specification

The json file this depends on is generated by belspec_yaml2json as
part of the update_specifications function

Args:
version: e.g. 2.0.0 where the filename


def inet_to_str(inet):

    try:
        return socket.inet_ntop(socket.AF_INET, inet)
    except ValueError:
        return socket.inet_ntop(socket.AF_INET6, inet)

Convert inet object to a string

Args:
inet (inet struct): inet network address
Returns:
str: Printable/readable IP address


def serialize(self, datas):
    self._metas = OrderedDict({'references': self.get_meta_references(datas)})
    return self.get_enabled_references(datas, self._metas['references'])

Serialize datas to manifest structure with metas and references.

Only references are returned, metas are assigned to attribute
``ManifestSerializer._metas``.

Arguments:
datas (dict): Data where to search for reference declarations. This
is commonly the fully parsed manifest.

Returns:
collections.OrderedDict: Serialized enabled references datas.


def GenerateId(self, entity_id=None):

    self._idnum += 1
    if entity_id:
      return '%s_merged_%d' % (entity_id, self._idnum)
    else:
      return 'merged_%d' % self._idnum

Generate a unique id based on the given id.

This is done by appending a counter which is then incremented. The
counter is initialised at the maximum number used as an ending for
any id in the old and new schedules.

Args:
entity_id: The base id string. This is allowed to be None.

Returns:
The generated id.


def unix_time(self, dt):

        epoch = datetime.utcfromtimestamp(0)
        delta = dt - epoch
        return int(delta.total_seconds())

Returns the number of seconds since the UNIX epoch for the given
datetime (dt).

PARAMETERS:
dt -- datetime


async def inspect(self, service_id: str) -> Mapping[(str, Any)]:
    response = (await self.docker._query_json('services/{service_id}'.format(service_id=service_id), method='GET'))
    return response

Inspect a service

Args:
service_id: ID or name of the service

Returns:
a dict with info about a service


def SerializeAst(ast, src_path=None, metadata=None) -> SerializableAst:
    if ast.name.endswith('.__init__'):
        ast = ast.Visit(visitors.RenameModuleVisitor(ast.name, ast.name.rsplit('.__init__', 1)[0]))
    ast = ast.Visit(UndoModuleAliasesVisitor())
    deps = visitors.CollectDependencies()
    ast.Visit(deps)
    dependencies = deps.dependencies
    late_dependencies = deps.late_dependencies
    ast.Visit(visitors.ClearClassPointers())
    ast = ast.Visit(visitors.CanonicalOrderingVisitor())
    ast.Visit(ClearLookupCache())
    metadata = metadata or []
    return SerializableAst(ast, sorted(dependencies.items()), sorted(late_dependencies.items()), src_path=src_path, metadata=metadata)

Prepares an AST for serialization.

Args:
ast: The pytd.TypeDeclUnit to save to disk.
src_path: Optionally, the filepath of the original source file.
metadata: A list of arbitrary string-encoded metadata.

Returns:
The SerializableAst derived from `ast`.


def recipe_dv360_targeter(config, auth_dv, auth_sheet, auth_bigquery, recipe_name, recipe_slug, command, first_and_third):
    dataset(config, {'__comment__': 'Ensure dataset exists.', 'auth': auth_bigquery, 'dataset': recipe_slug})
    drive(config, {'__comment__': 'Copy the default template to sheet with the recipe name', 'auth': auth_sheet, 'copy': {'source': 'https:
    dv_targeter(config, {'__comment': 'Depending on users choice, execute a different part of the solution.', 'auth_dv': auth_dv, 'auth_sheets': auth_sheet, 'auth_bigquery': auth_bigquery, 'sheet': recipe_name, 'dataset': recipe_slug, 'command': command, 'first_and_third': first_and_third})

Allows bulk targeting DV360 through Sheets and BigQuery.

Args:
auth_dv (authentication) - Credentials used for dv.
auth_sheet (authentication) - Credentials used for sheet.
auth_bigquery (authentication) - Credentials used for bigquery.
recipe_name (string) - Name of Google Sheet to create.
recipe_slug (string) - Name of Google BigQuery dataset to create.
command (choice) - Action to take.
first_and_third (boolean) - Load first and third party data (may be slow). If not selected, enter audience identifiers into sheet manually.


def update_config_proto(self, config_proto):
    return self._extended._update_config_proto(config_proto)

Returns a copy of `config_proto` modified for use with this strategy.

DEPRECATED: This method is not available in TF 2.x.

The updated config has something needed to run a strategy, e.g.
configuration to run collective ops, or device filters to improve
distributed training performance.

Args:
config_proto: a `tf.ConfigProto` object.

Returns:
The updated copy of the `config_proto`.


def dicts_to_mrc(code, dicts):

    def _dict_to_mrc(code, d):
        i1 = d.get("i1", d.get("ind1"))
        i2 = d.get("i2", d.get("ind2"))

        one_chars = [k for k in d.keys() if len(k) == 1]
        out = "%s%s%s L " % (code, i1, i2)
        for key in resorted(one_chars):
            for item in d[key]:
                out += "$$%s%s" % (key, item)

        return out

    return [
        _dict_to_mrc(code, d)
        for d in dicts
    ]

Convert `dicts` under `code` to MRC. This is used to compose some of the
data from user's input to MRC template, which is then converted to
MARC XML / Dublin core.

Args:
code (str): Code of the aleph field, whic hshould be used.
dicts (dict): Dict with aleph fields (i1/i2, a..z, 0..9) and
informations in this fields.

Returns:
list: List of lines with MRC data.


def check_unique_named_object_has_class(root, name, class_name):

    assert class_name == get_unique_named_object(root, name).__class__.__name__

checks the type (type name) of an unique named object (no fully qualified
name)

Args:
root: start of search
name: name of object
class_name: the name of the type to be checked

Returns:
nothing (if not unique, raises an error)


Raises error if invalid SAM format detected

Args:
entries (list): A list of SamEntry instances

line (int): Line number of first entry

Raises:
FormatError: Error when SAM format incorrect with descriptive message


def embedding_feature(self):
    return HardwareFeature._embedding_feature_proto_to_string(self.tpu_hardware_feature_proto.embedding_feature)

TPU embedding feature.

Returns:
An EmbeddingFeature enum.


def update(self, information, timeout=-1):

        return self._client.update(information, timeout=timeout)

Edit an IPv4 Range.

Args:
information (dict): Information to update.
timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.

Returns:
dict: Updated IPv4 range.


def is_jpeg(contents, name=None):
    with ops.name_scope(name, 'is_jpeg'):
        substr = string_ops.substr(contents, 0, 3)
        return math_ops.equal(substr, b'\xff\xd8\xff', name=name)

Convenience function to check if the 'contents' encodes a JPEG image.

Args:
contents: 0-D `string`. The encoded image bytes.
name: A name for the operation (optional)

Returns:
A scalar boolean tensor indicating if 'contents' may be a JPEG image.
is_jpeg is susceptible to false positives.


def evaluate_test(self, stage, root=False):

    args_adjusted = []
    for arg in stage.args:
      if isinstance(arg, PipelineFuture):
        arg = arg.default
      if isinstance(arg, Slot):
        value = arg.value
        arg._touched = True
      else:
        value = arg
      args_adjusted.append(value)

    kwargs_adjusted = {}
    for name, arg in stage.kwargs.iteritems():
      if isinstance(arg, PipelineFuture):
        arg = arg.default
      if isinstance(arg, Slot):
        value = arg.value
        arg._touched = True
      else:
        value = arg
      kwargs_adjusted[name] = value

    stage.args, stage.kwargs = args_adjusted, kwargs_adjusted
    pipeline_generator = mr_util.is_generator_function(stage.run)
    logging.debug('Running %s(*%s, **%s)', stage._class_path,
                  _short_repr(stage.args), _short_repr(stage.kwargs))

    if stage.async:
      stage.run_test(*stage.args, **stage.kwargs)
    elif pipeline_generator:
      all_output_slots = set()
      try:
        pipeline_iter = stage.run_test(*stage.args, **stage.kwargs)
      except NotImplementedError:
        pipeline_iter = stage.run(*stage.args, **stage.kwargs)

      all_substages = set()
      next_value = None
      last_sub_stage = None
      while True:
        try:
          yielded = pipeline_iter.send(next_value)
        except StopIteration:
          break

        if isinstance(yielded, Pipeline):
          if yielded in all_substages:
            raise UnexpectedPipelineError(
                'Already yielded pipeline object %r' % yielded)
          else:
            all_substages.add(yielded)

          last_sub_stage = yielded
          next_value = yielded.outputs
          all_output_slots.update(next_value._output_dict.itervalues())
        else:
          raise UnexpectedPipelineError(
              'Yielded a disallowed value: %r' % yielded)

      if last_sub_stage:

        for slot_name, slot in last_sub_stage.outputs._output_dict.iteritems():
          stage.outputs._output_dict[slot_name] = slot

          all_output_slots.remove(slot)
      else:

        stage.outputs.default._set_value_test(stage._pipeline_key, None)
    else:
      try:
        result = stage.run_test(*stage.args, **stage.kwargs)
      except NotImplementedError:
        result = stage.run(*stage.args, **stage.kwargs)
      stage.outputs.default._set_value_test(stage._pipeline_key, result)

    if root:
      found_outputs = set()
      for slot in stage.outputs._output_dict.itervalues():
        if slot.filled:
          found_outputs.add(slot.name)
        if slot.name == 'default':
          continue
        if slot.name not in stage.output_names:
          raise SlotNotDeclaredError(
              'Undeclared output from root pipeline "%s"' % slot.name)

      missing_outputs = set(stage.output_names) - found_outputs
      if missing_outputs:
        raise SlotNotFilledError(
            'Outputs %r were never filled.' % missing_outputs)

    logging.debug('Finalizing %s(*%s, **%s)', stage._class_path,
                  _short_repr(stage.args), _short_repr(stage.kwargs))
    ran = False
    try:
      stage.finalized_test()
      ran = True
    except NotImplementedError:
      pass
    if not ran:
      try:
        stage.finalized()
      except NotImplementedError:
        pass

Recursively evaluates the given pipeline in test mode.

Args:
stage: The Pipeline instance to run at this stage in the flow.
root: True if the supplied stage is the root of the pipeline.


def add_index_argument(cls, group):
    prefix = cls.argument_prefix
    group.add_argument(('--%s-index' % prefix), action='store', dest=('%s_index' % prefix), help=('Name of the %s root markdown file, can be None' % cls.extension_name))

Subclasses may call this to add an index argument.

Args:
group: arparse.ArgumentGroup, the extension argument group
prefix: str, arguments have to be namespaced


def reformat_css(input_file, output_file):
    line_count = get_line_count(input_file)
    f = open(input_file, 'r+')
    output = open(output_file, 'w')
    for line in range(line_count):
        string = f.readline().strip()
        string = re.sub('\\{', '{\n', string)
        string = re.sub('; ', ';', string)
        string = re.sub(';', ';\n', string)
        string = re.sub('} ', '*/\n', string)
        output.write(string)
    output.close()
    f.close()
    indent_css(output_file, output_file)
    add_whitespace_before('{', output_file, output_file)

Reformats poorly written css. This function does not validate or fix errors in the code.
It only gives code the proper indentation.

Args:
input_file: string, path to the input file.

output_file: string, path to where the reformatted css should be saved. If the target file
doesn't exist, a new file is created.

Returns:
None.


def AddComment(self, comment):
    if (not comment):
        return
    if (not self.comment):
        self.comment = comment
    else:
        self.comment = ''.join([self.comment, comment])

Adds a comment to the event tag.

Args:
comment (str): comment.


def __add__(self, other):

        if not all(np.equal(self.energies, other.energies)):
            raise ValueError("Energies of both DOS are not compatible!")
        densities = {spin: self.densities[spin] + other.densities[spin]
                     for spin in self.densities.keys()}
        return Dos(self.efermi, self.energies, densities)

Adds two DOS together. Checks that energy scales are the same.
Otherwise, a ValueError is thrown.

Args:
other: Another DOS object.

Returns:
Sum of the two DOSs.


def ParseFileObject(self, parser_mediator, file_object):

    data = file_object.read(self._HEADER_READ_SIZE)
    if not data.startswith(b'<?xml'):
      raise errors.UnableToParseFile(
          'Not an Opera typed history file [not a XML]')

    _, _, data = data.partition(b'\n')
    if not data.startswith(b'<typed_history'):
      raise errors.UnableToParseFile(
          'Not an Opera typed history file [wrong XML root key]')

    file_object.seek(0, os.SEEK_SET)

    xml = ElementTree.parse(file_object)

    for history_item in xml.iterfind('typed_history_item'):
      event_data = OperaTypedHistoryEventData()
      event_data.entry_type = history_item.get('type', None)
      event_data.url = history_item.get('content', None)

      if event_data.entry_type == 'selected':
        event_data.entry_selection = 'Filled from autocomplete.'
      elif event_data.entry_type == 'text':
        event_data.entry_selection = 'Manually typed.'

      last_typed_time = history_item.get('last_typed', None)
      if last_typed_time is None:
        parser_mediator.ProduceExtractionWarning('missing last typed time.')
        continue

      date_time = dfdatetime_time_elements.TimeElements()

      try:
        date_time.CopyFromStringISO8601(last_typed_time)
      except ValueError as exception:
        parser_mediator.ProduceExtractionWarning(
            'unsupported last typed time: {0:s} with error: {1!s}.'.format(
                last_typed_time, exception))
        continue

      event = time_events.DateTimeValuesEvent(
          date_time, definitions.TIME_DESCRIPTION_LAST_VISITED)
      parser_mediator.ProduceEventWithEventData(event, event_data)

Parses an Opera typed history file-like object.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): file-like object.

Raises:
UnableToParseFile: when the file cannot be parsed.


def get_np_module(array: Array, *, strict: bool=True):
    return lazy.get_xnp(array, strict=strict)

Returns the numpy module associated with the given array.

Args:
array: Either tf, jax or numpy array.
strict: If `False`, default to `np.array` if the array can't be infered (
to support array-like: list, tuple,...)

Returns:
The numpy module.


def index(self, entries):

        if not self.is_empty():
            raise ValueError("Cannot call index again on a non-empty index")
        if not isinstance(entries, list):
            queue = deque([])
            for key, minhash, size in entries:
                if size <= 0:
                    raise ValueError("Set size must be positive")
                queue.append((key, minhash, size))
            entries = list(queue)
        if len(entries) == 0:
            raise ValueError("entries is empty")

        sizes, counts = np.array(sorted(
            Counter(e[2] for e in entries).most_common())).T
        partitions = optimal_partitions(sizes, counts, len(self.indexes))
        for i, (lower, upper) in enumerate(partitions):
            self.lowers[i], self.uppers[i] = lower, upper

        entries.sort(key=lambda e : e[2])
        curr_part = 0
        for key, minhash, size in entries:
            if size > self.uppers[curr_part]:
                curr_part += 1
            for r in self.indexes[curr_part]:
                self.indexes[curr_part][r].insert(key, minhash)

Index all sets given their keys, MinHashes, and sizes.
It can be called only once after the index is created.

Args:
entries (`iterable` of `tuple`): An iterable of tuples, each must be
in the form of `(key, minhash, size)`, where `key` is the unique
identifier of a set, `minhash` is the MinHash of the set,
and `size` is the size or number of unique items in the set.

Note:
`size` must be positive.


def _standardize_args(inputs, initial_state, constants, num_constants):
    if isinstance(inputs, list):
        assert initial_state is None and constants is None
        if num_constants:
            constants = inputs[-num_constants:]
            inputs = inputs[:-num_constants]
        if len(inputs) > 1:
            initial_state = inputs[1:]
            inputs = inputs[:1]
        if len(inputs) > 1:
            inputs = tuple(inputs)
        else:
            inputs = inputs[0]

    def to_list_or_none(x):
        if x is None or isinstance(x, list):
            return x
        if isinstance(x, tuple):
            return list(x)
        return [x]
    initial_state = to_list_or_none(initial_state)
    constants = to_list_or_none(constants)
    return (inputs, initial_state, constants)

Standardizes `__call__` to a single list of tensor inputs.

When running a model loaded from a file, the input tensors
`initial_state` and `constants` can be passed to `RNN.__call__()` as part
of `inputs` instead of by the dedicated keyword arguments. This method
makes sure the arguments are separated and that `initial_state` and
`constants` are lists of tensors (or None).

Args:
inputs: Tensor or list/tuple of tensors. which may include constants
and initial states. In that case `num_constant` must be specified.
initial_state: Tensor or list of tensors or None, initial states.
constants: Tensor or list of tensors or None, constant tensors.
num_constants: Expected number of constants (if constants are passed as
part of the `inputs` list.

Returns:
inputs: Single tensor or tuple of tensors.
initial_state: List of tensors or None.
constants: List of tensors or None.


def execute_log(args, root_dir):

    if args.get('keys'):
        config_dir = os.path.join(root_dir, '.config/pueue')
        queue_path = os.path.join(config_dir, 'queue')
        if os.path.exists(queue_path):
            queue_file = open(queue_path, 'rb')
            try:
                queue = pickle.load(queue_file)
            except Exception:
                print('Queue log file seems to be corrupted. Aborting.')
                return
            queue_file.close()
        else:
            print('There is no queue log file. Aborting.')
            return

        for key in args.get('keys'):

            if queue.get(key) and queue[key]['status'] in ['failed', 'done']:
                entry = queue[key]
                print('Log of entry: {}'.format(key))
                print('Returncode: {}'.format(entry['returncode']))
                print('Command: {}'.format(entry['command']))
                print('Path: {}'.format(entry['path']))
                print('Start: {}, End: {} \n'.format(entry['start'], entry['end']))

                if len(entry['stderr']) > 0:
                    print(Color('{autored}Stderr output: {/autored}\n    ') + entry['stderr'])

                if len(entry['stdout']) > 0:
                    print(Color('{autogreen}Stdout output: {/autogreen}\n    ') + entry['stdout'])
            else:
                print('No finished process with key {}.'.format(key))

    else:
        log_path = os.path.join(root_dir, '.local/share/pueue/queue.log')
        log_file = open(log_path, 'r')
        print(log_file.read())

Print the current log file.

Args:
args['keys'] (int): If given, we only look at the specified processes.
root_dir (string): The path to the root directory the daemon is running in.


def parse_str(value: Any) -> str:
    return str(value)

Convert the provided value into a string value.

Args:
* value: of Any type

Returns:
* string value


def GetSortedEvents(self, time_range=None):

    if not self._is_open:
      raise IOError('Unable to read from closed storage writer.')

    event_heap = event_heaps.EventHeap()

    for event in self._events:
      if (time_range and (
          event.timestamp < time_range.start_timestamp or
          event.timestamp > time_range.end_timestamp)):
        continue

      event = copy.deepcopy(event)

      self._ReadEventDataIntoEvent(event)

      event_heap.PushEvent(event)

    return iter(event_heap.PopEvents())

Retrieves the events in increasing chronological order.

Args:
time_range (Optional[TimeRange]): time range used to filter events
that fall in a specific period.

Returns:
generator(EventObject): event generator.

Raises:
IOError: when the storage writer is closed.
OSError: when the storage writer is closed.


def breakpoint_info(self, handle=0, index=(- 1)):
    if ((index < 0) and (handle == 0)):
        raise ValueError('Handle must be provided if index is not set.')
    bp = structs.JLinkBreakpointInfo()
    bp.Handle = int(handle)
    res = self._dll.JLINKARM_GetBPInfoEx(index, ctypes.byref(bp))
    if (res < 0):
        raise errors.JLinkException('Failed to get breakpoint info.')
    return bp

Returns the information about a set breakpoint.

Note:
Either ``handle`` or ``index`` can be specified.  If the ``index``
is not provided, the ``handle`` must be set, and vice-versa.  If
both ``index`` and ``handle`` are provided, the ``index`` overrides
the provided ``handle``.

Args:
self (JLink): the ``JLink`` instance
handle (int): option handle of a valid breakpoint
index (int): optional index of the breakpoint.

Returns:
An instance of ``JLinkBreakpointInfo`` specifying information about
the breakpoint.

Raises:
JLinkException: on error.
ValueError: if both the handle and index are invalid.


def _ParameterDecorator(naming_type, testcases):

  def _Apply(obj):
    if isinstance(obj, type):
      _ModifyClass(
          obj,
          list(testcases) if not isinstance(testcases, collections.Sequence)
          else testcases,
          naming_type)
      return obj
    else:
      return _ParameterizedTestIter(obj, testcases, naming_type)

  if _IsSingletonList(testcases):
    assert _NonStringIterable(testcases[0]), (
        'Single parameter argument must be a non-string iterable')
    testcases = testcases[0]

  return _Apply

Implementation of the parameterization decorators.

Args:
naming_type: The naming type.
testcases: Testcase parameters.

Returns:
A function for modifying the decorated object.


def plot_timestream(array, kidid, xtick='time', scantypes=None, ax=None, **kwargs):

    if ax is None:
        ax = plt.gca()

    index = np.where(array.kidid == kidid)[0]
    if len(index) == 0:
        raise KeyError('Such a kidid does not exist.')
    index = int(index)

    if scantypes is None:
        if xtick == 'time':
            ax.plot(array.time, array[:, index], label='ALL', **kwargs)
        elif xtick == 'index':
            ax.plot(np.ogrid[:len(array.time)], array[:, index], label='ALL', **kwargs)
    else:
        for scantype in scantypes:
            if xtick == 'time':
                ax.plot(array.time[array.scantype == scantype],
                        array[:, index][array.scantype == scantype], label=scantype, **kwargs)
            elif xtick == 'index':
                ax.plot(np.ogrid[:len(array.time[array.scantype == scantype])],
                        array[:, index][array.scantype == scantype], label=scantype, **kwargs)
    ax.set_xlabel('{}'.format(xtick))
    ax.set_ylabel(str(array.datatype.values))
    ax.legend()

    kidtpdict = {0: 'wideband', 1: 'filter', 2: 'blind'}
    try:
        kidtp = kidtpdict[int(array.kidtp[index])]
    except KeyError:
        kidtp = 'filter'
    ax.set_title('ch

    logger.info('timestream data (ch={}) has been plotted.'.format(kidid))

Plot timestream data.

Args:
array (xarray.DataArray): Array which the timestream data are included.
kidid (int): Kidid.
xtick (str): Type of x axis.
'time': Time.
'index': Time index.
scantypes (list): Scantypes. If None, all scantypes are used.
ax (matplotlib.axes): Axis you want to plot on.
kwargs (optional): Plot options passed to ax.plot().


def ConsumeBool(self):
    try:
        result = ParseBool(self.token)
    except ValueError as e:
        raise self._ParseError(str(e))
    self.NextToken()
    return result

Consumes a boolean value.

Returns:
The bool parsed.

Raises:
ParseError: If a boolean value couldn't be consumed.


def get_dc_keywords(index_page):

    keyword_lists = (
        keyword_list.split()
        for keyword_list in parse_meta(index_page, "dc.keywords", "DC")
    )

    return [
        SourceString(keyword, source="DC")
        for keyword in sum(keyword_lists, [])
    ]

Return list of `keywords` parsed from Dublin core.

Args:
index_page (str): Content of the page as UTF-8 string

Returns:
list: List of :class:`.SourceString` objects.


def get_score(self, error=None):

        if error is not None:
            self.error = error
        if self.error >= 0:
            return 1 / (self.error + 1)
        else:
            return 1 + abs(self.error)

Calculate bee's fitness score given a value returned by the fitness
function

Args:
error (float): value returned by the fitness function

Returns:
float: derived fitness score


def _CopyField(field, number=None):

  positional_args, kwargs = _GetFieldAttributes(field)
  number = number or field.number
  positional_args.append(number)
  return field.__class__(*positional_args, **kwargs)

Copies a (potentially) owned ProtoRPC field instance into a new copy.

Args:
field: A ProtoRPC message field to be copied.
number: An integer for the field to override the number of the field.
Defaults to None.

Raises:
TypeError: If the field is not an instance of messages.Field.

Returns:
A copy of the ProtoRPC message field.


def tile_images(data, padsize=1, padval=0):

    assert(data.ndim == 4)
    data = data.transpose(0, 2, 3, 1)

    n = int(np.ceil(np.sqrt(data.shape[0])))
    padding = (
        (0, n ** 2 - data.shape[0]),
        (0, padsize),
        (0, padsize)
    ) + ((0, 0),) * (data.ndim - 3)
    data = np.pad(
        data, padding, mode='constant', constant_values=(padval, padval))
    data = data.reshape(
        (n, n)
        + data.shape[1:]
    ).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
    data = data.reshape(
        (n * data.shape[1], n * data.shape[3]) + data.shape[4:])
    if data.shape[2] == 1:

        return data.reshape(data.shape[:2])
    return data

Convert an array with shape of (B, C, H, W) into a tiled image.

Args:
data (~numpy.ndarray): An array with shape of (B, C, H, W).
padsize (int): Each tile has padding with this size.
padval (float): Padding pixels are filled with this value.

Returns:
tile_image (~numpy.ndarray): A tile image.


def AddNewSignature(self, pattern, offset=None):

    self.signatures.append(Signature(pattern, offset=offset))

Adds a signature.

Args:
pattern (bytes): pattern of the signature.
offset (int): offset of the signature. None is used to indicate
the signature has no offset. A positive offset is relative from
the start of the data a negative offset is relative from the end
of the data.


def parse_hausdorff(ml_log, log=None, print_output=False):
    hausdorff_distance = {'min_distance': 0.0, 'max_distance': 0.0, 'mean_distance': 0.0, 'rms_distance': 0.0, 'number_points': 0}
    with open(ml_log) as fread:
        result = fread.readlines()
        data = ''
        for (idx, line) in enumerate(result):
            m = re.match('\\s*Sampled (\\d+) pts.*', line)
            if (m is not None):
                hausdorff_distance['number_points'] = int(m.group(1))
            if ('Hausdorff Distance computed' in line):
                data = result[(idx + 2)]
        m = re.match('\\D+(\\d+\\.*\\d*)\\D+(\\d+\\.*\\d*)\\D+(\\d+\\.*\\d*)\\D+(\\d+\\.*\\d*)', data)
        hausdorff_distance['min_distance'] = float(m.group(1))
        hausdorff_distance['max_distance'] = float(m.group(2))
        hausdorff_distance['mean_distance'] = float(m.group(3))
        hausdorff_distance['rms_distance'] = float(m.group(4))
        for (key, value) in hausdorff_distance.items():
            if (log is not None):
                log_file = open(log, 'a')
                log_file.write('{:16} = {}\n'.format(key, value))
                log_file.close()
            elif print_output:
                print('{:16} = {}'.format(key, value))
        return hausdorff_distance

Parse the ml_log file generated by the hausdorff_distance function.

Args:
ml_log (str): MeshLab log file to parse
log (str): filename to log output

Returns:
dict: dictionary with the following keys:
number_points (int): number of points in mesh
min_distance (float): minimum hausdorff distance
max_distance (float): maximum hausdorff distance
mean_distance (float): mean hausdorff distance
rms_distance (float): root mean square distance


def _next_func(string_handle):
    with ops.device(self._source_device_string):
        iterator = iterator_ops.Iterator.from_string_handle(string_handle, dataset_ops.get_legacy_output_types(self), dataset_ops.get_legacy_output_shapes(self), dataset_ops.get_legacy_output_classes(self))
    return structure.to_tensor_list(self.element_spec, iterator.get_next())

Calls get_next for created iterator.

Args:
string_handle: An iterator string handle created by _init_func
Returns:
The elements generated from `input_dataset`


def UploadImage(client, filepath):
    media_service = client.GetService('MediaService', 'v201809')
    with open(filepath, 'rb') as image_handle:
        image_data = image_handle.read().decode('utf-8')
    image = [{'xsi_type': 'Image', 'data': image_data, 'type': 'IMAGE'}]
    image = media_service.upload(image)[0]
    return image

Uploads a .jpg image with the given filepath via the AdWords MediaService.

Args:
client: an AdWordsClient instance.
filepath: a str filepath to the .jpg file to be uploaded.

Returns:
The created Image as a sudsobject.


def __init__(self, xid=None, role=ControllerRole.OFPCR_ROLE_NOCHANGE,
                 generation_id=UBINT64_MAX_VALUE):

        super().__init__(xid, role, generation_id)
        self.header.message_type = Type.OFPT_ROLE_REPLY

Create a RoleReply with the optional parameters below.

Args:
xid (int): OpenFlow xid to the header.
role (:class:`~.controller2switch.common.ControllerRole`):
Is the new role that the controller wants to assume.
generation_id (int): Master Election Generation Id. The default
value is -1. For this field, it's UBINT64_MAX_VALUE.


def from_json_keyfile_dict(cls, keyfile_dict, scopes='', token_uri=None, revoke_uri=None):
    return cls._from_parsed_json_keyfile(keyfile_dict, scopes, token_uri=token_uri, revoke_uri=revoke_uri)

Factory constructor from parsed JSON keyfile.

Args:
keyfile_dict: dict-like object, The parsed dictionary-like object
containing the contents of the JSON keyfile.
scopes: List or string, (Optional) Scopes to use when acquiring an
access token.
token_uri: string, URI for OAuth 2.0 provider token endpoint.
If unset and not present in keyfile_dict, defaults
to Google's endpoints.
revoke_uri: string, URI for OAuth 2.0 provider revoke endpoint.
If unset and not present in keyfile_dict, defaults
to Google's endpoints.

Returns:
ServiceAccountCredentials, a credentials object created from
the keyfile.

Raises:
ValueError, if the credential type is not :data:`SERVICE_ACCOUNT`.
KeyError, if one of the expected keys is not present in
the keyfile.


def _cauchy_equation(wavelength, coefficients):

        n = 0.
        for i, c in enumerate(coefficients):
            exponent  = 2*i
            n += c / wavelength**exponent
        return n

Helpful function to evaluate Cauchy equations.

Args:
wavelength (float, list, None): The wavelength(s) the
Cauchy equation will be evaluated at.
coefficients (list): A list of the coefficients of
the Cauchy equation.

Returns:
float, list: The refractive index at the target wavelength(s).


def __init__(self, columns: list[str], num_buckets: int, *, epsilon: Optional[float]=None, elementwise: bool=False, name: Optional[str]=None):
    super().__init__(columns)
    self.num_buckets = num_buckets
    self.epsilon = epsilon
    self.elementwise = elementwise
    self.name = name

This function applies a bucketizing transformation on the given columns
of incoming data. The transformation splits the input data range into
a set of consecutive bins/buckets, and converts the input values to
bucket IDs (integers) where each ID corresponds to a particular bin.

Args:
columns: List of column names to apply the transformation.
num_buckets: Number of buckets to be created.
epsilon: (Optional) A float number that specifies the error tolerance
when computing quantiles, so that we guarantee that any value x will
have a quantile q such that x is in the interval
[q - epsilon, q + epsilon] (or the symmetric interval for even
num_buckets). Must be greater than 0.0.
elementwise: (Optional) A boolean that specifies whether the quantiles
should be computed on an element-wise basis. If False, the quantiles
are computed globally.
name: (Optional) A string that specifies the name of the operation.


def get_metric_name(metric, weighted=False):
    if tf2.enabled():
        if isinstance(metric, str):
            return metric
        metric = metrics_module.get(metric)
        return metric.name if hasattr(metric, 'name') else metric.__name__
    else:
        metric_name_prefix = 'weighted_' if weighted else ''
        if metric in ('accuracy', 'acc', 'crossentropy', 'ce'):
            if metric in ('accuracy', 'acc'):
                suffix = 'acc'
            elif metric in ('crossentropy', 'ce'):
                suffix = 'ce'
        else:
            metric_fn = metrics_module.get(metric)
            if hasattr(metric_fn, 'name'):
                suffix = metric_fn.name
            else:
                suffix = metric_fn.__name__
        metric_name = metric_name_prefix + suffix
        return metric_name

Returns the name corresponding to the given metric input.

Args:
metric: Metric function name or reference.
weighted: Boolean indicating if the given metric is weighted.

Returns:
The metric name.


def from_string(string):

        lines = list(clean_lines(string.splitlines()))
        params = {}
        for line in lines:
            for sline in line.split(';'):
                m = re.match(r'(\w+)\s*=\s*(.*)', sline.strip())
                if m:
                    key = m.group(1).strip()
                    val = m.group(2).strip()
                    val = Incar.proc_val(key, val)
                    params[key] = val
        return Incar(params)

Reads an Incar object from a string.

Args:
string (str): Incar string

Returns:
Incar object


def _unpack_oxm_field(self):
    field_int = (self.oxm_field_and_mask >> 1)
    if (self.oxm_class == OxmClass.OFPXMC_OPENFLOW_BASIC):
        return OxmOfbMatchField(field_int)
    return field_int

Unpack oxm_field from oxm_field_and_mask.

Returns:
:class:`OxmOfbMatchField`, int: oxm_field from oxm_field_and_mask.

Raises:
ValueError: If oxm_class is OFPXMC_OPENFLOW_BASIC but
:class:`OxmOfbMatchField` has no such integer value.


def save(self, projects):

        base_path = os.path.expanduser(self.path)

        if not os.path.isdir(base_path):
            return

        logger.debug("Save projects config to %s", base_path)

        for name, data in list(projects.items()):
            project_file_path = self.get_project_config_path(name)
            with open(project_file_path, "w") as f:
                yaml.dump(data, stream = f, default_flow_style = False)
                logger.debug("Project '%s' config has been writed to '%s'", name, project_file_path)

Save the projects configs to local path

Args:
projects (dict): project_name -> project_data


def __init__(self, name, key_path='', registry=None):

    super(VirtualWinRegistryKey, self).__init__(key_path=key_path)
    self._name = name
    self._registry = registry
    self._registry_key = None
    self._subkeys = collections.OrderedDict()

Initializes a Windows Registry key.

Args:
name (str): name of the Windows Registry key.
key_path (Optional[str]): Windows Registry key path.
registry (Optional[WinRegistry]): Windows Registry.


def _as_arg_name_and_type(text):
    tokens = text.split()
    if len(tokens) < 2:
        return None
    if _is_arg_name(tokens[0]):
        type_token = ' '.join(tokens[1:])
        type_token = type_token.lstrip('{([').rstrip('])}')
        return (tokens[0], type_token)
    else:
        return None

Returns text as a name and type, if text looks like an arg name and type.

Example:
_as_arg_name_and_type("foo (int)") == "foo", "int"

Args:
text: The text, which may or may not be an arg name and type.
Returns:
The arg name and type, if text looks like an arg name and type.
None otherwise.


def get_experiment_in_group(self, group, bucketing_id):

    experiment_id = self.bucketer.find_bucket(bucketing_id, group.id, group.trafficAllocation)
    if experiment_id:
      experiment = self.config.get_experiment_from_id(experiment_id)
      if experiment:
        self.logger.info('User with bucketing ID "%s" is in experiment %s of group %s.' % (
          bucketing_id,
          experiment.key,
          group.id
        ))
        return experiment

    self.logger.info('User with bucketing ID "%s" is not in any experiments of group %s.' % (
      bucketing_id,
      group.id
    ))

    return None

Determine which experiment in the group the user is bucketed into.

Args:
group: The group to bucket the user into.
bucketing_id: ID to be used for bucketing the user.

Returns:
Experiment if the user is bucketed into an experiment in the specified group. None otherwise.


def set_stderrthreshold(s):
    if (s in converter.ABSL_LEVELS):
        FLAGS.stderrthreshold = converter.ABSL_LEVELS[s]
    elif (isinstance(s, str) and (s.upper() in converter.ABSL_NAMES)):
        FLAGS.stderrthreshold = s
    else:
        raise ValueError('set_stderrthreshold only accepts integer absl logging level from -3 to 1, or case-insensitive string values \'debug\', \'info\', \'warning\', \'error\', and \'fatal\'. But found "{}" ({}).'.format(s, type(s)))

Sets the stderr threshold to the value passed in.

Args:
s: str|int, valid strings values are case-insensitive 'debug',
'info', 'warning', 'error', and 'fatal'; valid integer values are
logging.DEBUG|INFO|WARNING|ERROR|FATAL.

Raises:
ValueError: Raised when s is an invalid value.


def create_branch_and_checkout(self, branch_name: str):
    self.create_branch(branch_name)
    self.checkout(branch_name)

Creates a new branch if it doesn't exist

Args:
branch_name: branch name


def run(self, config, data_store, signal_server, workflow_id):
    self._workflow_id = workflow_id
    self._celery_app = create_app(config)
    args = self._parameters.consolidate(self._provided_arguments)
    for (key, value) in args.items():
        data_store.get(self._workflow_id).set(key, value)
    for (name, dag) in self._dags_blueprint.items():
        if dag.autostart:
            self._queue_dag(name)
    while self._dags_running:
        if (config.workflow_polling_time > 0.0):
            sleep(config.workflow_polling_time)
        for i in range(MAX_SIGNAL_REQUESTS):
            request = signal_server.receive()
            if (request is None):
                break
            try:
                response = self._handle_request(request)
                if (response is not None):
                    signal_server.send(response)
                else:
                    signal_server.restore(request)
            except (RequestActionUnknown, RequestFailed):
                signal_server.send(Response(success=False, uid=request.uid))
        for (name, dag) in list(self._dags_running.items()):
            if dag.ready():
                if (self._celery_app.conf.result_expires == 0):
                    dag.forget()
                del self._dags_running[name]
            elif dag.failed():
                self._stop_workflow = True
    signal_server.clear()
    if self._clear_data_store:
        data_store.remove(self._workflow_id)

Run all autostart dags in the workflow.

Only the dags that are flagged as autostart are started.

Args:
config (Config): Reference to the configuration object from which the
settings for the workflow are retrieved.
data_store (DataStore): A DataStore object that is fully initialised and
connected to the persistent data storage.
signal_server (Server): A signal Server object that receives requests
from dags and tasks.
workflow_id (str): A unique workflow id that represents this workflow run


def _ReadCharacterDataTypeDefinition(
      self, definitions_registry, definition_values, definition_name,
      is_member=False):

    return self._ReadFixedSizeDataTypeDefinition(
        definitions_registry, definition_values,
        data_types.CharacterDefinition, definition_name,
        self._SUPPORTED_ATTRIBUTES_FIXED_SIZE_DATA_TYPE,
        is_member=is_member, supported_size_values=(1, 2, 4))

Reads a character data type definition.

Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, object]): definition values.
definition_name (str): name of the definition.
is_member (Optional[bool]): True if the data type definition is a member
data type definition.

Returns:
CharacterDataTypeDefinition: character data type definition.


def cast_to_model_input_dtypes(x, model):
    input_dtypes = nest.map_structure(lambda t: t.dtype, model.inputs)
    return nest.map_structure(math_ops.cast, x, input_dtypes)

Casts the given data tensors to the dtypes of the model inputs.

Args:
x: tensor or list/tuple of tensors.
model: The model.

Returns:
Converted input. Each tensor is casted to the corresponding input in
`model.inputs`.


def _VerifyGeneratedGradients(grads, op: ops.Operation):
    if op.type == 'While' or op.type == 'StatelessWhile':
        return
    if len(grads) != len(op.inputs):
        raise ValueError(f'Num gradients {len(grads)} generated for op {op.node_def} do not match num inputs {len(op.inputs)}')

Verify that gradients are valid in number and type.

Args:
grads: List of generated gradients.
op: Operation for which the gradients where generated.

Raises:
ValueError: if sizes of gradients and inputs don't match.
TypeError: if type of any gradient is not valid for its input.


def transform_function(self, fn, user_context):
    future_features = inspect_utils.getfutureimports(fn)
    node, source = parser.parse_entity(fn, future_features=future_features)
    logging.log(3, 'Source code of %s:\n\n%s\n', fn, source)
    origin_info.resolve_entity(node, source, fn)
    namespace = inspect_utils.getnamespace(fn)
    namer = naming.Namer(namespace)
    new_name = namer.new_symbol(self.get_transformed_name(node), ())
    entity_info = transformer.EntityInfo(name=new_name, source_code=source, source_file='<fragment>', future_features=future_features, namespace=namespace)
    context = transformer.Context(entity_info, namer, user_context)
    node = self._erase_arg_defaults(node)
    result = self.transform_ast(node, context)
    return (result, context)

Transforms a function.

Subclasses may override this method. The return value is opaque.

The method receives the original AST. The result is passed as-is to the
output of `transform`.

Args:
fn: A function or lambda.
user_context: An opaque object (may be None) that is forwarded to
transform_ast, through the ctx.user attribute.
Returns:
Tuple[Any, Any]. By default it returns the output of transform_ast,
together with a `transformer.Context` containing information about the
transformation process.


def GetPointWithDistanceTraveled(self, shape_dist_traveled):
    if (not self.distance):
        return None
    if (shape_dist_traveled <= self.distance[0]):
        return self.points[0]
    if (shape_dist_traveled >= self.distance[(- 1)]):
        return self.points[(- 1)]
    index = bisect.bisect(self.distance, shape_dist_traveled)
    (lat0, lng0, dist0) = self.points[(index - 1)]
    (lat1, lng1, dist1) = self.points[index]
    ca = (shape_dist_traveled - dist0)
    bc = (dist1 - shape_dist_traveled)
    ba = (bc + ca)
    if (ba == 0):
        return None
    lat = (((lat1 * ca) + (lat0 * bc)) / ba)
    lng = (((lng1 * ca) + (lng0 * bc)) / ba)
    return (lat, lng, shape_dist_traveled)

Returns a point on the shape polyline with the input shape_dist_traveled.

Args:
shape_dist_traveled: The input shape_dist_traveled.

Returns:
The shape point as a tuple (lat, lng, shape_dist_traveled), where lat and
lng is the location of the shape point, and shape_dist_traveled is an
increasing metric representing the distance traveled along the shape.
Returns None if there is data error in shape.


def compute_cyclomatic_complexity(function):

    E = compute_number_edges(function)
    N = len(function.nodes)
    P = len(compute_strongly_connected_components(function))
    return E - N + 2 * P

Compute the cyclomatic complexity of a function
Args:
function (core.declarations.function.Function)
Returns:
int


def write_chunks(self, data, start, step, count) -> None:
    self.mglo.write_chunks(data, start, step, count)

Split data to count equal parts.

Write the chunks using offsets calculated from start, step and stop.

Args:
data (bytes): The data.
start (int): First offset.
step (int): Offset increment.
count (int): The number of offsets.


def weighted_average(input_tensor: torch.Tensor, weights: Optional[torch.Tensor]=None, dim=None) -> torch.Tensor:
    if weights is not None:
        weighted_tensor = torch.where(weights != 0, input_tensor * weights, torch.zeros_like(input_tensor))
        sum_weights = torch.clamp(weights.sum(dim=dim) if dim else weights.sum(), min=1.0)
        return (weighted_tensor.sum(dim=dim) if dim else weighted_tensor.sum()) / sum_weights
    else:
        return input_tensor.mean(dim=dim)

Computes the weighted average of a given tensor across a given `dim`, masking values associated with weight zero,
meaning instead of `nan * 0 = nan` you will get `0 * 0 = 0`.

Args:
input_tensor (`torch.FloatTensor`):
Input tensor, of which the average must be computed.
weights (`torch.FloatTensor`, *optional*):
Weights tensor, of the same shape as `input_tensor`.
dim (`int`, *optional*):
The dim along which to average `input_tensor`.

Returns:
`torch.FloatTensor`: The tensor with values averaged along the specified `dim`.


def get_child(self, name: YangIdentifier, ns: YangIdentifier=None) -> Optional[SchemaNode]:
    ns = (ns if ns else self.ns)
    todo = []
    for child in self.children:
        if (child.name is None):
            todo.append(child)
        elif ((child.name == name) and (child.ns == ns)):
            return child
    for c in todo:
        grandchild = c.get_child(name, ns)
        if (grandchild is not None):
            return grandchild

Return receiver's schema child.

Args:
name: Child's name.
ns: Child's namespace (= `self.ns` if absent).


async def gen(self, name):

        if self.ctor is None:
            raise s_exc.NoSuchCtor(name=name, mesg='BaseRef.gen() requires ctor')

        base = self.base_by_name.get(name)

        if base is None:
            base = await self.ctor(name)
            self.put(name, base)
        else:
            base.incref()

        return base

Atomically get/gen a Base and incref.
(requires ctor during BaseRef init)

Args:
name (str): The name/iden of the Base instance.


def __init__(self, minimum, maximum, decimals=2, singleStep=0.1, parent=None):

        super(CustomDoubleSpinboxDelegate, self).__init__(parent)

        self.minimum = minimum
        self.maximum = maximum
        self.decimals = decimals
        self.singleStep = singleStep

construct a new instance of a CustomDoubleSpinboxDelegate.

Args:
maximum (float): minimum allowed number in QDoubleSpinBox.
minimum (float): maximum allowed number in QDoubleSpinBox.
singleStep (int, optional): amount of steps to stepUp QDoubleSpinBox. defaults to 0.1.
decimals (int, optional): decimals to use.  defaults to 2.


class CLIPSegEncoder(nn.Module):

    def __init__(self, config: CLIPSegConfig):
        super().__init__()
        self.config = config
        self.layers = nn.ModuleList([CLIPSegEncoderLayer(config) for _ in range(config.num_hidden_layers)])
        self.gradient_checkpointing = False

    def forward(self, inputs_embeds, attention_mask: Optional[torch.Tensor]=None, causal_attention_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None) -> Union[Tuple, BaseModelOutput]:

        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
        output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict
        encoder_states = () if output_hidden_states else None
        all_attentions = () if output_attentions else None
        hidden_states = inputs_embeds
        for idx, encoder_layer in enumerate(self.layers):
            if output_hidden_states:
                encoder_states = encoder_states + (hidden_states,)
            if self.gradient_checkpointing and self.training:
                layer_outputs = self._gradient_checkpointing_func(encoder_layer.__call__, hidden_states, attention_mask, causal_attention_mask, output_attentions)
            else:
                layer_outputs = encoder_layer(hidden_states, attention_mask, causal_attention_mask, output_attentions=output_attentions)
            hidden_states = layer_outputs[0]
            if output_attentions:
                all_attentions = all_attentions + (layer_outputs[1],)
        if output_hidden_states:
            encoder_states = encoder_states + (hidden_states,)
        if not return_dict:
            return tuple((v for v in [hidden_states, encoder_states, all_attentions] if v is not None))
        return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions)

Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
[`CLIPSegEncoderLayer`].

Args:
config: CLIPSegConfig


def expects_none(options):
    if any(((options.get(key) is not None) for key in ['count', 'maximum', 'minimum', 'between'])):
        return matches_count(0, options)
    else:
        return False

Returns whether the given query options expect a possible count of zero.

Args:
options (Dict[str, int | Iterable[int]]): A dictionary of query options.

Returns:
bool: Whether a possible count of zero is expected.


def create_list(self, **kwargs):

        path = self._get_path('create_list')
        kwargs.update({'session_id': self.session_id})

        payload = {
            'name': kwargs.pop('name', None),
            'description': kwargs.pop('description', None),
        }
        if 'language' in kwargs:
            payload['language'] = kwargs['language']

        response = self._POST(path, kwargs, payload)
        self._set_attrs_to_values(response)
        return response

Create a new list.

A valid session id is required.

Args:
name: Name of the list.
description: Description of the list.
language: (optional) ISO 639-1 code.

Returns:
A dict respresentation of the JSON returned from the API.


def create_identity_with_grad_check_fn(expected_gradient, expected_dtype=None):

    @custom_gradient.custom_gradient
    def _identity_with_grad_check(x):

        x = array_ops.identity(x)

        def grad(dx):

            if expected_dtype:
                assert dx.dtype == expected_dtype, 'dx.dtype should be %s but is: %s' % (expected_dtype, dx.dtype)
            expected_tensor = tensor_conversion.convert_to_tensor_v2_with_dispatch(expected_gradient, dtype=dx.dtype, name='expected_gradient')
            with ops.control_dependencies([x]):
                assert_op = check_ops.assert_equal(dx, expected_tensor)
            with ops.control_dependencies([assert_op]):
                dx = array_ops.identity(dx)
            return dx
        return (x, grad)

    def identity_with_grad_check(x):
        return _identity_with_grad_check(x)
    return identity_with_grad_check

Returns a function that asserts it's gradient has a certain value.

This serves as a hook to assert intermediate gradients have a certain value.
This returns an identity function. The identity's gradient function is also
the identity function, except it asserts that the gradient equals
`expected_gradient` and has dtype `expected_dtype`.

Args:
expected_gradient: The gradient function asserts that the gradient is this
value.
expected_dtype: The gradient function asserts the gradient has this dtype.

Returns:
An identity function whose gradient function asserts the gradient has a
certain value.


def check_concurrency(self) -> bool:
    if (not self.operation.concurrency):
        return True
    ops_count = self.operation.runs.filter(status__status__in=self.STATUSES.RUNNING_STATUS).count()
    return (ops_count < self.operation.concurrency)

Checks the concurrency of the operation run.

Checks the concurrency of the operation run
to validate if we can start a new operation run.

Returns:
boolean: Whether to start a new operation run or not.


def dequantize_flow(dx, dy, max_val=0.02, denorm=True):

    assert dx.shape == dy.shape
    assert dx.ndim == 2 or (dx.ndim == 3 and dx.shape[-1] == 1)

    dx, dy = [dequantize(d, -max_val, max_val, 255) for d in [dx, dy]]

    if denorm:
        dx *= dx.shape[1]
        dy *= dx.shape[0]
    flow = np.dstack((dx, dy))
    return flow

Recover from quantized flow.

Args:
dx (ndarray): Quantized dx.
dy (ndarray): Quantized dy.
max_val (float): Maximum value used when quantizing.
denorm (bool): Whether to multiply flow values with width/height.

Returns:
ndarray: Dequantized flow.


def _apply_conv(self, inputs, w):
    tiled_weights = tf.tile(w, [1, 1, self._input_channels, 1])
    outputs = tf.nn.depthwise_conv2d(inputs, tiled_weights, strides=self.stride, padding=self._conv_op_padding, data_format=self._data_format)
    return outputs

Apply a depthwise_conv2d operation on `inputs` using variable `w`.

Args:
inputs: A Tensor of shape `data_format` and of type `tf.float16`,
`tf.bfloat16` or `tf.float32`.
w: A weight matrix of the same type as `inputs`.

Returns:
outputs: The result of the convolution operation on `inputs`.


def __x_google_quota_definitions_descriptor(self, limit_definitions):
    if (not limit_definitions):
        return None
    definitions_list = [{'name': ld.metric_name, 'metric': ld.metric_name, 'unit': '1/min/{project}', 'values': {'STANDARD': ld.default_limit}, 'displayName': ld.display_name} for ld in limit_definitions]
    metrics = [{'name': ld.metric_name, 'valueType': 'INT64', 'metricKind': 'GAUGE'} for ld in limit_definitions]
    return {'quota': {'limits': definitions_list}, 'metrics': metrics}

Describes the quota limit definitions for an API.

Args:
limit_definitions: List of endpoints.LimitDefinition tuples

Returns:
A dict descriptor of the API's quota limit definitions.


def plot_zt_mu(self, temp=600, output='eig', relaxation_time=1e-14, xlim=None):
    import matplotlib.pyplot as plt
    plt.figure(figsize=(9, 7))
    zt = self._bz.get_zt(relaxation_time=relaxation_time, output=output, doping_levels=False)[temp]
    plt.plot(self._bz.mu_steps, zt, linewidth=3.0)
    self._plot_bg_limits()
    self._plot_doping(temp)
    if (output == 'eig'):
        plt.legend(['ZT$_1$', 'ZT$_2$', 'ZT$_3$'])
    if (xlim is None):
        plt.xlim((- 0.5), (self._bz.gap + 0.5))
    else:
        plt.xlim(xlim)
    plt.ylabel('ZT', fontsize=30.0)
    plt.xlabel('E-E$_f$ (eV)', fontsize=30.0)
    plt.xticks(fontsize=25)
    plt.yticks(fontsize=25)
    plt.tight_layout()
    return plt

Plot the ZT in function of Fermi level.

Args:
temp: the temperature
xlim: a list of min and max fermi energy by default (0, and band
gap)
tau: A relaxation time in s. By default none and the plot is by
units of relaxation time

Returns:
a matplotlib object


def _construct(self, context):

    with self.g.as_default():
      if self._pass_through:

        return self._pass_through._construct(context)
      current_value = context.get(self, None)
      assert current_value is not _unspecified, 'Circular dependency'
      if current_value is not None:
        return current_value
      context[self] = _unspecified
      method_args = self._replace_deferred(self._method_args, context)
      method_kwargs = self._replace_deferred(self._method_kwargs, context)
      result = self._method(*method_args, **method_kwargs)
      _strip_unnecessary_contents_from_stack(result, set())

      context[self] = result
      return result

Constructs this by calling the deferred method.

This assumes that all unbound_vars have been specified in context and if
this layer has already been computed in this context, then the previously
constructed value will be returned.

Args:
context: A dict of UnboundVariables/_DeferredLayers to their values.
Returns:
The result of calling the given method on this layer.


def list_documents(self, limit=None):

        limit_str = ''
        if limit:
            try:
                limit_str = 'LIMIT {}'.format(int(limit))
            except (TypeError, ValueError):
                pass

        query = ('SELECT identifier FROM identifier_index ' + limit_str)

        for row in self.backend.library.database.connection.execute(query).fetchall():
            yield row['identifier']

Generates vids of all indexed identifiers.

Args:
limit (int, optional): If not empty, the maximum number of results to return

Generates:
str: vid of the document.


def mount_share_at_path(share_path, mount_path):

    sh_url = CFURLCreateWithString(None, share_path, None)
    mo_url = CFURLCreateWithString(None, mount_path, None)

    open_options = {NetFS.kNAUIOptionKey: NetFS.kNAUIOptionNoUI}

    mount_options = {NetFS.kNetFSAllowSubMountsKey: True,
                     NetFS.kNetFSMountAtMountDirKey: True}

    result, output = NetFS.NetFSMountURLSync(sh_url, mo_url, None, None,
                                             open_options, mount_options, None)

    if result != 0:
        raise Exception('Error mounting url "%s" at path "%s": %s' %
                        (share_path, mount_path, output))

    return str(output[0])

Mounts a share at the specified path

Args:
share_path: String URL with all auth info to connect to file share.
mount_path: Path to mount share on.

Returns:
The mount point or raises an error


def get_lambda_arn(app, account, region):

    session = boto3.Session(profile_name=account, region_name=region)
    lambda_client = session.client('lambda')

    lambda_arn = None
    paginator = lambda_client.get_paginator('list_functions')

    for lambda_functions in paginator.paginate():
        for lambda_function in lambda_functions['Functions']:
            if lambda_function['FunctionName'] == app:
                lambda_arn = lambda_function['FunctionArn']
                LOG.debug("Lambda ARN for lambda function %s is %s.", app, lambda_arn)
                break
        if lambda_arn:
            break

    if not lambda_arn:
        LOG.fatal('Lambda function with name %s not found in %s %s', app, account, region)
        raise LambdaFunctionDoesNotExist(
            'Lambda function with name {0} not found in {1} {2}'.format(app, account, region))

    return lambda_arn

Get lambda ARN.

Args:
account (str): AWS account name.
region (str): Region name, e.g. us-east-1
app (str): Lambda function name

Returns:
str: ARN for requested lambda function


def EnsureGdbPosition(self, pid, tid, frame_depth):
    position = [pid, tid, frame_depth]
    if (not pid):
        return
    if (not self.IsAttached()):
        try:
            self.Attach(position)
        except gdb.error as exc:
            raise PositionUnavailableException(exc.message)
    if (gdb.selected_inferior().pid != pid):
        self.Detach()
        try:
            self.Attach(position)
        except gdb.error as exc:
            raise PositionUnavailableException(exc.message)
    if tid:
        tstate_head = GdbCache.INTERP_HEAD['tstate_head']
        for tstate in self._IterateChainedList(tstate_head, 'next'):
            if (tid == tstate['thread_id']):
                self.selected_tstate = tstate
                break
        else:
            raise PositionUnavailableException(('Thread %s does not exist.' % str(tid)))
        stack_head = self.selected_tstate['frame']
        if (frame_depth is not None):
            frames = list(self._IterateChainedList(stack_head, 'f_back'))
            frames.reverse()
            try:
                self.selected_frame = frames[frame_depth]
            except IndexError:
                raise PositionUnavailableException(('Stack is not %s frames deep' % str((frame_depth + 1))))

Make sure our position matches the request.

Args:
pid: The process ID of the target process
tid: The python thread ident of the target thread
frame_depth: The 'depth' of the requested frame in the frame stack
Raises:
PositionUnavailableException: If the requested process, thread or frame
can't be found or accessed.


def value(self):
    (counter_type, value) = win32pdh.GetFormattedCounterValue(self.handle, win32pdh.PDH_FMT_DOUBLE)
    self.type = counter_type
    return value

Return the counter value

Returns:
long: The counter value


def bbox_rotate(bbox, angle, rows, cols, interpolation):
    scale = (cols / float(rows))
    x = np.array([bbox[0], bbox[2], bbox[2], bbox[0]])
    y = np.array([bbox[1], bbox[1], bbox[3], bbox[3]])
    x = (x - 0.5)
    y = (y - 0.5)
    angle = np.deg2rad(angle)
    x_t = ((((np.cos(angle) * x) * scale) + (np.sin(angle) * y)) / scale)
    y_t = ((((- np.sin(angle)) * x) * scale) + (np.cos(angle) * y))
    x_t = (x_t + 0.5)
    y_t = (y_t + 0.5)
    return [min(x_t), min(y_t), max(x_t), max(y_t)]

Rotates a bounding box by angle degrees

Args:
bbox (tuple): A tuple (x_min, y_min, x_max, y_max).
angle (int): Angle of rotation in degrees
rows (int): Image rows.
cols (int): Image cols.
interpolation (int): interpolation method.

return a tuple (x_min, y_min, x_max, y_max)


def get_max_muO2(self, min_voltage=None, max_voltage=None):
    data = []
    for pair in self._select_in_voltage_range(min_voltage, max_voltage):
        if (pair.muO2_discharge is not None):
            data.extend([d['chempot'] for d in pair.muO2_discharge])
        if (pair.muO2_charge is not None):
            data.extend([d['chempot'] for d in pair.muO2_discharge])
    return (max(data) if (len(data) > 0) else None)

Maximum critical oxygen chemical potential along path.

Args:
min_voltage: The minimum allowable voltage.
max_voltage: The maximum allowable voltage.

Returns:
Maximum critical oxygen chemical of all compounds along the
insertion path (a subset of the path can be chosen by the optional
arguments).


def is_sparse(tensor):
    spec = getattr(tensor, '_type_spec', None)
    if spec is not None:
        return isinstance(spec, sparse_tensor.SparseTensorSpec)
    return isinstance(tensor, sparse_tensor.SparseTensor)

Returns whether a tensor is a sparse tensor.

Args:
tensor: A tensor instance.

Returns:
A boolean.

Example:

>>> a = tf.keras.backend.placeholder((2, 2), sparse=False)
>>> print(tf.keras.backend.is_sparse(a))
False
>>> b = tf.keras.backend.placeholder((2, 2), sparse=True)
>>> print(tf.keras.backend.is_sparse(b))
True


def apply_step(self, variables, deltas, loss_sampled):

        update_stats_op = self.compute_and_apply_stats(
            loss_sampled, var_list=var_list)
        grads = [(a, b) for a, b in zip(deltas, varlist)]
        kfacOptim, _ = self.apply_gradients_kfac(grads)
        return kfacOptim

Applies the given (and already calculated) step deltas to the variable values.

Args:
variables: List of variables.
deltas: List of deltas of same length.
loss_sampled : the sampled loss

Returns:
The step-applied operation. A tf.group of tf.assign_add ops.


def add_op(state, op_func, *args, **kwargs):

    frameinfo = get_caller_frameinfo()
    kwargs['frameinfo'] = frameinfo

    for host in state.inventory:
        op_func(state, host, *args, **kwargs)

Prepare & add an operation to ``pyinfra.state`` by executing it on all hosts.

Args:
state (``pyinfra.api.State`` obj): the deploy state to add the operation
to op_func (function): the operation function from one of the modules,
ie ``server.user``
args/kwargs: passed to the operation function


def _TensorArraySplitGrad(op: ops.Operation, flow):
    handle = op.inputs[0]
    dtype = op.get_attr('T')
    grad_source = _GetGradSource(flow)
    flow_out = array_ops.identity(op.outputs[0], 'flow_out')
    with ops.control_dependencies([flow_out]):
        flow = array_ops.identity(flow, 'write_barrier')
    g = tensor_array_ops.TensorArray(dtype=dtype, handle=handle, flow=flow, colocate_with_first_write_call=False).grad(source=grad_source, flow=flow)
    grad = g.concat()
    return [None, grad, None, flow]

Gradient for TensorArraySplit.

Args:
op: Forward TensorArraySplit op.
flow: Gradient `Tensor` flow to TensorArraySplit.

Returns:
A grad `Tensor`, the gradient created in upstream ReadGrads or PackGrad.


def _update_annotations(discretized_pulse: Callable) -> Callable:
    undecorated_annotations = list(discretized_pulse.__annotations__.items())
    decorated_annotations = undecorated_annotations[1:]
    decorated_annotations.insert(0, ('duration', int))
    discretized_pulse.__annotations__ = dict(decorated_annotations)
    return discretized_pulse

Update annotations of discretized continuous pulse function with duration.

Args:
discretized_pulse: Discretized decorated continuous pulse.


def install(self, remote_name, local_name=None):
    privileges = self.client.api.plugin_privileges(remote_name)
    it = self.client.api.pull_plugin(remote_name, privileges, local_name)
    for data in it:
        pass
    return self.get((local_name or remote_name))

Pull and install a plugin.

Args:
remote_name (string): Remote reference for the plugin to
install. The ``:latest`` tag is optional, and is the
default if omitted.
local_name (string): Local name for the pulled plugin.
The ``:latest`` tag is optional, and is the default if
omitted. Optional.

Returns:
(:py:class:`Plugin`): The installed plugin
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.


def add_oxidation_state_by_element(self, oxidation_states):

        try:
            for site in self.sites:
                new_sp = {}
                for el, occu in site.species.items():
                    sym = el.symbol
                    new_sp[Specie(sym, oxidation_states[sym])] = occu
                site.species = new_sp
        except KeyError:
            raise ValueError("Oxidation state of all elements must be "
                             "specified in the dictionary.")

Add oxidation states.

Args:
oxidation_states (dict): Dict of oxidation states.
E.g., {"Li":1, "Fe":2, "P":5, "O":-2}


def _strip_padding(tensors, pad_len):
    if not tensors:
        raise ValueError('tensors cannot be empty')
    shape = tensors[0].shape
    if len(shape) > 1:
        raise ValueError('tensors must be 1D')
    prefix_len = int(shape[0] - pad_len)
    if prefix_len < 0:
        raise ValueError('pad_len longer than tensor')
    stripped = []
    for t in tensors:
        with ops.colocate_with(t):
            stripped.append(array_ops.slice(t, [0], [prefix_len]))
    return stripped

Strip the suffix padding added by _padded_split.

Args:
tensors: list of `tf.Tensor` of identical length 1D tensors.
pad_len: number of elements to be stripped from the end of each tensor.

Returns:
list of `tf.Tensor` which are the stripped inputs.

Raises:
ValueError: tensors must be a non-empty list of 1D tensors, and
each must be longer than pad_len.


def VerifyStructure(self, parser_mediator, lines):

    try:
      structure = self._GDS_LINE.parseString(lines)
    except pyparsing.ParseException as exception:
      logger.debug('Not a Google Drive Sync log file: {0!s}'.format(exception))
      return False

    date_time = dfdatetime_time_elements.TimeElementsInMilliseconds()

    try:
      datetime_iso8601 = self._GetISO8601String(structure.date_time)
      date_time.CopyFromStringISO8601(datetime_iso8601)
    except ValueError as exception:
      logger.debug((
          'Not a Google Drive Sync log file, invalid date/time: {0!s} '
          'with error: {1!s}').format(structure.date_time, exception))
      return False

    return True

Verify that this file is a Google Drive Sync log file.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
lines (str): one or more lines from the text file.

Returns:
bool: True if this is the correct parser, False otherwise.


def plot_histograms(self, freq=None, title=None, figsize=(10, 10), **kwargs):
    if (title is None):
        title = self._get_default_plot_title(freq, 'Return Histogram Matrix')
    plt.figure()
    ser = self._get_series(freq).to_returns().dropna()
    ser.hist(figsize=figsize, **kwargs)
    return plt.suptitle(title)

Wrapper around pandas' hist.

Args:
* freq (str): Data frequency used for display purposes.
Refer to pandas docs for valid freq strings.
* figsize ((x,y)): figure size
* title (str): Title if default not appropriate
* kwargs: passed to pandas' hist method


def getTextlength(text, fontname="helv", fontsize=11, encoding=0):

    fontname = fontname.lower()
    basename = Base14_fontdict.get(fontname, None)

    glyphs = None
    if basename == "Symbol":
        glyphs = symbol_glyphs
    if basename == "ZapfDingbats":
        glyphs = zapf_glyphs
    if glyphs is not None:
        w = sum([glyphs[ord(c)][1] if ord(c)<256 else glyphs[183][1] for c in text])
        return w * fontsize

    if fontname in Base14_fontdict.keys():
        return TOOLS.measure_string(text, Base14_fontdict[fontname], fontsize, encoding)

    if fontname in ["china-t", "china-s",
                    "china-ts", "china-ss",
                    "japan", "japan-s",
                    "korea", "korea-s"]:
        return len(text) * fontsize

    raise ValueError("Font '%s' is unsupported" % fontname)

Calculate length of a string for a given built-in font.

Args:
fontname: name of the font.
fontsize: size of font in points.
encoding: encoding to use (0=Latin, 1=Greek, 2=Cyrillic).
Returns:
(float) length of text.


def rollapply(data, window, fn):
    res = data.copy()
    res[:] = np.nan
    n = len(data)
    if (window > n):
        return res
    for i in range((window - 1), n):
        res.iloc[i] = fn(data.iloc[((i - window) + 1):(i + 1)])
    return res

Apply a function fn over a rolling window of size window.

Args:
* data (Series or DataFrame): Series or DataFrame
* window (int): Window size
* fn (function): Function to apply over the rolling window.
For a series, the return value is expected to be a single
number. For a DataFrame, it shuold return a new row.

Returns:
* Object of same dimensions as data


def dense_block(x, blocks, name):
    for i in range(blocks):
        x = conv_block(x, 32, name=name + '_block' + str(i + 1))
    return x

A dense block.

Args:
x: input tensor.
blocks: integer, the number of building blocks.
name: string, block label.

Returns:
Output tensor for the block.


def gaussian_overlapping_coefficient(means_0, stds_0, means_1, stds_1, lower=None, upper=None):
    if (lower is None):
        lower = (- np.inf)
    if (upper is None):
        upper = np.inf

    def point_iterator():
        for ind in range(means_0.shape[0]):
            (yield (np.squeeze(means_0[ind]), np.squeeze(stds_0[ind]), np.squeeze(means_1[ind]), np.squeeze(stds_1[ind])))
    return np.array(list(multiprocess_mapping(_ComputeGaussianOverlap(lower, upper), point_iterator())))

Compute the overlapping coefficient of two Gaussian continuous_distributions.

This computes the :math:`\int_{-\infty}^{\infty}{\min(f(x), g(x))\partial x}` where
:math:`f \sim \mathcal{N}(\mu_0, \sigma_0^{2})` and :math:`f \sim \mathcal{N}(\mu_1, \sigma_1^{2})` are normally
distributed variables.

This will compute the overlap for each element in the first dimension.

Args:
means_0 (ndarray): the set of means of the first distribution
stds_0 (ndarray): the set of stds of the fist distribution
means_1 (ndarray): the set of means of the second distribution
stds_1 (ndarray): the set of stds of the second distribution
lower (float): the lower limit of the integration. If not set we set it to -inf.
upper (float): the upper limit of the integration. If not set we set it to +inf.


def subcommand(self, *args):
    return Subcommand(*args, directory=self.directory, env_vars=self.env_vars)

Get subcommand acting on a service. Subcommand will run in service directory
and with the environment variables used to run the service itself.

Args:
*args: Arguments to run command (e.g. "redis-cli", "-n", "1")

Returns:
Subcommand object.


def pool_direct_single_axis(input, axis, window_size, pooling_type, padding, dilation_rate, stride):
    effective_window_size = (window_size - 1) * dilation_rate + 1
    input_size = input.shape[axis]
    if padding == 'SAME':
        output_size = int(math.ceil(input_size / stride))
        total_padding_amount = max(0, (output_size - 1) * stride + effective_window_size - input_size)
        before_padding = total_padding_amount
    elif padding == 'VALID':
        output_size = int(math.ceil((input_size - effective_window_size + 1) / stride))
        before_padding = 0
    else:
        raise ValueError('Unsupported padding type: %r' % (padding,))
    output_shape = input.shape[:axis] + (output_size,) + input.shape[axis + 1:]
    output = np.zeros(output_shape, input.dtype)
    initial_dim_selector = tuple((np.s_[:] for _ in range(axis)))
    if pooling_type == 'MAX':
        pooling_func = np.max
    elif pooling_type == 'AVG':
        pooling_func = np.mean
    else:
        raise ValueError('Unsupported pooling type: %r' % (pooling_type,))
    for output_pos in range(output_size):
        input_start_pos = output_pos * stride - before_padding
        input_end_pos = min(input_start_pos + effective_window_size, input_size)
        if input_start_pos < 0:
            input_start_pos += dilation_rate
        input_slice = np.s_[input_start_pos:input_end_pos:dilation_rate]
        output[initial_dim_selector + (output_pos,)] = pooling_func(input[initial_dim_selector + (input_slice,)], axis=axis)
    return output

Numpy implementation of pooling along a single axis.

This is intended for testing only, and therefore isn't particularly efficient.

See pool_direct below for the meaning of the arguments.

Args:
input: numpy array.
axis: axis along which to perform pooling.
window_size: int >= 1.  Size of pooling window within axis.
pooling_type: either "MAX" or "AVG".
padding: either "SAME" or "VALID".
dilation_rate: int >= 1.  Dilation factor for window, i.e. stride at which
to sample input.
stride: int >= 1.  Stride at which to generate output.

Returns:
pooling output array of rank N+2.

Raises:
ValueError: if arguments are invalid.


def set_notifier_path(self, notifier, path):
    assert ((self.notifier is Model.notifier) or (notifier is Model.notifier)), ('Already have a notifier %s path %s' % (self.notifier, self.path))
    self.notifier = notifier
    self.path = path
    for (name, ct) in self.call_types.items():
        if ct.is_mapping:
            child = getattr(self, name)
            if (child and issubclass(ct.typ[1], Model)):
                for (k, v) in child.items():
                    v.set_notifier_path(notifier, (self.path + [name, k]))
        elif issubclass(ct.typ, Model):
            assert (not ct.is_array), ("Can't deal with Arrays of Models %s" % ct)
            child = getattr(self, name)
            child.set_notifier_path(notifier, (self.path + [name]))

Sets the notifier, and the path from the path from block root

Args:
notifier (Notifier): The Notifier to tell when endpoint data changes
path (list): The absolute path to get to this object


def getToC(doc, simple = True):

    def recurse(olItem, liste, lvl):

        while olItem:
            if olItem.title:
                title = olItem.title
            else:
                title = " "

            if not olItem.isExternal:
                if olItem.uri:
                    page = olItem.page + 1
                else:
                    page = -1
            else:
                page = -1

            if not simple:
                link = getLinkDict(olItem)
                liste.append([lvl, title, page, link])
            else:
                liste.append([lvl, title, page])

            if olItem.down:
                liste = recurse(olItem.down, liste, lvl+1)
            olItem = olItem.next
        return liste

    if doc.isClosed:
        raise ValueError("illegal operation on closed document")

    olItem = doc.outline

    if not olItem: return []
    lvl = 1
    liste = []
    return recurse(olItem, liste, lvl)

Create a table of contents.

Args:
simple: a bool to control output. Returns a list, where each entry consists of outline level, title, page number and link destination (if simple = False). For details see PyMuPDF's documentation.


def data(self, rows=None):
    rows = (tf.range(self._capacity) if (rows is None) else rows)
    assert (rows.shape.ndims == 1)
    episode = tools.nested.map((lambda var: tf.gather(var, rows)), self._buffers)
    length = tf.gather(self._length, rows)
    return (episode, length)

Access a batch of episodes from the memory.

Padding elements after the length of each episode are unspecified and might
contain old data.

Args:
rows: Episodes to select, defaults to all.

Returns:
Tuple containing a tuple of transition quantities with batch and time
dimensions, and a batch of sequence lengths.


def reset(self, blocking=True):

    promise = self.call('reset')
    if blocking:
      return promise()
    else:
      return promise

Reset the environment.

Args:
blocking: Whether to wait for the result.

Returns:
New observation when blocking, otherwise callable that returns the new
observation.


def _all_number_groups_remain_grouped(numobj, normalized_candidate, formatted_number_groups):

    from_index = 0
    if numobj.country_code_source != CountryCodeSource.FROM_DEFAULT_COUNTRY:

        country_code = str(numobj.country_code)
        from_index = normalized_candidate.find(country_code) + len(country_code)

    for ii, formatted_number_group in enumerate(formatted_number_groups):

        from_index = normalized_candidate.find(formatted_number_group, from_index)
        if from_index < 0:
            return False

        from_index += len(formatted_number_group)
        if (ii == 0 and from_index < len(normalized_candidate)):

            region = region_code_for_country_code(numobj.country_code)
            if (ndd_prefix_for_region(region, True) is not None and
                normalized_candidate[from_index].isdigit()):

                nsn = national_significant_number(numobj)
                return normalized_candidate[(from_index - len(formatted_number_group)):].startswith(nsn)

    return (normalized_candidate[from_index:].find(numobj.extension or U_EMPTY_STRING) != -1)

Returns True if the groups of digits found in our candidate phone number match our
expectations.

Arguments:
numobj -- the original number we found when parsing
normalized_candidate -- the candidate number, normalized to only contain ASCII digits,
but with non-digits (spaces etc) retained
expected_number_groups -- the groups of digits that we would expect to see if we
formatted this number
Returns True if expectations matched.


def netmiko_file_transfer(
    task: Task, source_file: str, dest_file: str, **kwargs: Any
) -> Result:

    net_connect = task.host.get_connection("netmiko", task.nornir.config)
    kwargs.setdefault("direction", "put")
    scp_result = file_transfer(
        net_connect, source_file=source_file, dest_file=dest_file, **kwargs
    )
    if kwargs.get("disable_md5") is True:
        file_valid = scp_result["file_exists"]
    else:
        file_valid = scp_result["file_exists"] and scp_result["file_verified"]
    return Result(
        host=task.host, result=file_valid, changed=scp_result["file_transferred"]
    )

Execute Netmiko file_transfer method

Arguments:
source_file: Source file.
dest_file: Destination file.
kwargs: Additional arguments to pass to file_transfer

Returns:
Result object with the following attributes set:
* result (``bool``): file exists and MD5 is valid
* changed (``bool``): the destination file was changed


def hour(self, value=None):

        if value is not None:
            try:
                value = int(value)
            except ValueError:
                raise ValueError('value {} need to be of type int '
                                 'for field `hour`'.format(value))
            if value < 1:
                raise ValueError('value need to be greater or equal 1 '
                                 'for field `hour`')
            if value > 24:
                raise ValueError('value need to be smaller 24 '
                                 'for field `hour`')

        self._hour = value

Corresponds to IDD Field `hour`

Args:
value (int): value for IDD Field `hour`
value >= 1
value <= 24
if `value` is None it will not be checked against the
specification and is assumed to be a missing value

Raises:
ValueError: if `value` is not a valid value


def conv_to_float(indata, inf_str=''):

    if indata.strip() == inf_str:
        outdata = float('Inf')
    else:
        try:
            outdata = float(indata)
        except:
            raise ValueError('Unable to convert {} to float'.format(indata))

    return outdata

Try to convert an arbitrary string to a float. Specify what will be replaced with "Inf".

Args:
indata (str): String which contains a float
inf_str (str): If string contains something other than a float, and you want to replace it with float("Inf"),
specify that string here.

Returns:
float: Converted string representation


def output_timer_stream(self, instruction_id, transform_id, timer_family_id):
    raise NotImplementedError(type(self))

Returns an output stream written timers to transform_id.

Args:
instruction_id: which instruction this stream belongs to
transform_id: the transform_id of the returned stream
timer_family_id: the timer family of the written timer


def _call_rpc(self, address, rpc_id, payload):
    (status, response) = self.hw.stream.send_rpc(address, rpc_id, payload, timeout=1.1)
    return response

Call an RPC with the given information and return its response.

Must raise a hardware error of the appropriate kind if the RPC
can not be executed correctly.  Otherwise it should return the binary
response payload received from the RPC.

Args:
address (int): The address of the tile we want to call the RPC
on
rpc_id (int): The id of the RPC that we want to call
payload (bytes, bytearray): The data that we want to send as the payload


def __call__(self, shape, dtype=dtypes.float32, **kwargs):
    self._validate_kwargs(kwargs)
    dtype = _assert_float_dtype(dtype)
    scale = self.scale
    fan_in, fan_out = _compute_fans(shape)
    if _PARTITION_SHAPE in kwargs:
        shape = kwargs[_PARTITION_SHAPE]
    if self.mode == 'fan_in':
        scale /= max(1.0, fan_in)
    elif self.mode == 'fan_out':
        scale /= max(1.0, fan_out)
    else:
        scale /= max(1.0, (fan_in + fan_out) / 2.0)
    if self.distribution == 'truncated_normal':
        stddev = math.sqrt(scale) / 0.8796256610342398
        return self._random_generator.truncated_normal(shape, 0.0, stddev, dtype)
    elif self.distribution == 'untruncated_normal':
        stddev = math.sqrt(scale)
        return self._random_generator.random_normal(shape, 0.0, stddev, dtype)
    else:
        limit = math.sqrt(3.0 * scale)
        return self._random_generator.random_uniform(shape, -limit, limit, dtype)

Returns a tensor object initialized as specified by the initializer.

Args:
shape: Shape of the tensor.
dtype: Optional dtype of the tensor. Only floating point types are
supported.
**kwargs: Additional keyword arguments.

Raises:
ValueError: If the dtype is not floating point


def ParseFileObject(self, parser_mediator, file_object):

    filename = parser_mediator.GetFilename()
    if not self._CACHE_FILENAME_RE.match(filename):
      raise errors.UnableToParseFile('Not a Firefox cache2 file.')

    file_size = file_object.get_size()
    if file_size < 36:
      raise errors.UnableToParseFile(
          'File size too small for Firefox cache2 file.')

    file_offset = self._GetCacheFileMetadataHeaderOffset(file_object)
    file_metadata_header_map = self._GetDataTypeMap(
        'firefox_cache2_file_metadata_header')

    try:
      file_metadata_header, _ = self._ReadStructureFromFileObject(
          file_object, file_offset, file_metadata_header_map)
    except (ValueError, errors.ParseError) as exception:
      raise errors.UnableToParseFile((
          'Unable to parse Firefox cache2 file metadata header with error: '
          '{0!s}').format(exception))

    if not self._ValidateCacheFileMetadataHeader(file_metadata_header):
      raise errors.UnableToParseFile('Not a valid Firefox cache2 record.')

    url = file_object.read(file_metadata_header.key_size)

    header_data = file_object.read()

    display_name = parser_mediator.GetDisplayName()
    request_method, response_code = self._ParseHTTPHeaders(
        header_data[:-4], file_offset, display_name)

    event_data = FirefoxCacheEventData()
    event_data.fetch_count = file_metadata_header.fetch_count
    event_data.frequency = file_metadata_header.frequency
    event_data.request_method = request_method
    event_data.request_size = file_metadata_header.key_size
    event_data.response_code = response_code
    event_data.version = self._CACHE_VERSION
    event_data.url = url.decode('ascii', errors='replace')

    date_time = dfdatetime_posix_time.PosixTime(
        timestamp=file_metadata_header.last_fetched_time)
    event = time_events.DateTimeValuesEvent(
        date_time, definitions.TIME_DESCRIPTION_LAST_VISITED)
    parser_mediator.ProduceEventWithEventData(event, event_data)

    if file_metadata_header.last_modified_time:
      date_time = dfdatetime_posix_time.PosixTime(
          timestamp=file_metadata_header.last_modified_time)
      event = time_events.DateTimeValuesEvent(
          date_time, definitions.TIME_DESCRIPTION_WRITTEN)
      parser_mediator.ProduceEventWithEventData(event, event_data)

    if file_metadata_header.expiration_time:
      date_time = dfdatetime_posix_time.PosixTime(
          timestamp=file_metadata_header.expiration_time)
      event = time_events.DateTimeValuesEvent(
          date_time, definitions.TIME_DESCRIPTION_EXPIRATION)
      parser_mediator.ProduceEventWithEventData(event, event_data)

Parses a Firefox cache file-like object.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): a file-like object.

Raises:
UnableToParseFile: when the file cannot be parsed.


def parsing_token_generator(data_dir, tmp_dir, train, source_vocab_size,
                            target_vocab_size):

  del (data_dir, tmp_dir, train, source_vocab_size, target_vocab_size)
  assert False, "Vocabulary generation not implemented"

Generator for parsing as a sequence-to-sequence task that uses tokens.

This generator assumes the files parsing_{train,dev}.trees, which contain
trees in WSJ format.

Args:
data_dir: path to the data directory.
tmp_dir: path to temporary storage directory.
train: whether we're training or not.
source_vocab_size: source vocab size.
target_vocab_size: target vocab size.

Returns:
A generator to a dictionary of inputs and outputs.


def _read_proto_resolve(self, length, ptype):
    if (ptype == '0800'):
        return ipaddress.ip_address(self._read_fileng(4))
    elif (ptype == '86dd'):
        return ipaddress.ip_address(self._read_fileng(16))
    else:
        return self._read_fileng(length)

Resolve IP address according to protocol.

Positional arguments:
* length -- int, protocol address length
* ptype -- int, protocol type

Returns:
* str -- IP address


def summary_writer(self):
    return self._summary_writer

Return the SummaryWriter used by the chief supervisor.

Returns:
A SummaryWriter.


def set_fog_density(self, density):

        if density < 0 or density > 1:
            raise HolodeckException("Fog density should be between 0 and 1")

        self._should_write_to_command_buffer = True
        command_to_send = ChangeFogDensityCommand(density)
        self._commands.add_command(command_to_send)

Queue up a change fog density command. It will be applied when `tick` or `step` is called next.
By the next tick, the exponential height fog in the world will have the new density. If there is no fog in the
world, it will be automatically created with the given density.

Args:
density (float): The new density value, between 0 and 1. The command will not be sent if the given
density is invalid.


def AssertType(value, expected_type):
    if (not isinstance(value, expected_type)):
        message = 'Expected type `%r`, but got value `%r` of type `%s`'
        message %= (expected_type, value, type(value))
        raise TypeError(message)

Ensures that given value has certain type.

Args:
value: A value to assert the type for.
expected_type: An expected type for the given value.

Raises:
TypeError: If given value does not have the expected type.