def __init__(self, feature_set='spe+'):

        filename = filenames[feature_set]
        self.segments, self.seg_dict, self.names = self._read_table(filename)
        self.seg_seq = {seg[0]: i for (i, seg) in enumerate(self.segments)}
        self.weights = self._read_weights()
        self.seg_regex = self._build_seg_regex()
        self.longest_seg = max([len(x) for x in self.seg_dict.keys()])
        self.xsampa = xsampa.XSampa()

Construct a FeatureTable object

Args:
feature_set (str): the feature set that the FeatureTable will use;
currently, there is only one of these ("spe+")


def is_finite_number(value):
    if (not isinstance(value, (numbers.Integral, float))):
        return False
    if isinstance(value, bool):
        return False
    if isinstance(value, float):
        if (math.isnan(value) or math.isinf(value)):
            return False
    if (abs(value) > (2 ** 53)):
        return False
    return True

Validates if the given value is a number, enforces
absolute limit of 2^53 and restricts NAN, INF, -INF.

Args:
value: Value to be validated.

Returns:
Boolean: True if value is a number and not NAN, INF, -INF or
greater than absolute limit of 2^53 else False.


def FindServiceByName(self, full_name):

    full_name = _NormalizeFullyQualifiedName(full_name)
    if full_name not in self._service_descriptors:
      self._FindFileContainingSymbolInDb(full_name)
    return self._service_descriptors[full_name]

Loads the named service descriptor from the pool.

Args:
full_name: The full name of the service descriptor to load.

Returns:
The service descriptor for the named service.

Raises:
KeyError: if the service cannot be found in the pool.


def exists(self, uri):

        try:
            urllib.request.urlopen(uri)
            return True
        except urllib.error.HTTPError:
            return False

Method returns true is the entity exists in the Repository,
false, otherwise

Args:
uri(str): Entity URI

Returns:
bool


def stripped_op_list_for_graph(graph_def):
    used_ops = ops_used_by_graph_def(graph_def)
    op_defs = []
    for op in sorted(used_ops):
        op_def = op_def_registry.get(op)
        if op_def is not None:
            op_defs.append(op_def)
    return op_def_pb2.OpList(op=op_defs)

Collect the stripped OpDefs for ops used by a graph.

This function computes the `stripped_op_list` field of `MetaGraphDef` and
similar protos.  The result can be communicated from the producer to the
consumer, which can then use the C++ function
`RemoveNewDefaultAttrsFromGraphDef` to improve forwards compatibility.

Args:
graph_def: A `GraphDef` proto, as from `graph.as_graph_def()`.

Returns:
An `OpList` of ops used by the graph.


def _add_sample_measure(self, measure_params, num_samples):

        measured_qubits = list({qubit for qubit, cmembit in measure_params})
        num_measured = len(measured_qubits)

        axis = list(range(self._number_of_qubits))
        for qubit in reversed(measured_qubits):

            axis.remove(self._number_of_qubits - 1 - qubit)
        probabilities = np.reshape(np.sum(np.abs(self._statevector) ** 2,
                                          axis=tuple(axis)),
                                   2 ** num_measured)

        samples = self._local_random.choice(range(2 ** num_measured),
                                            num_samples, p=probabilities)

        memory = []
        for sample in samples:
            classical_memory = self._classical_memory
            for count, (qubit, cmembit) in enumerate(sorted(measure_params)):
                qubit_outcome = int((sample & (1 << count)) >> count)
                membit = 1 << cmembit
                classical_memory = (classical_memory & (~membit)) | (qubit_outcome << cmembit)
            value = bin(classical_memory)[2:]
            memory.append(hex(int(value, 2)))
        return memory

Generate memory samples from current statevector.

Args:
measure_params (list): List of (qubit, cmembit) values for
measure instructions to sample.
num_samples (int): The number of memory samples to generate.

Returns:
list: A list of memory values in hex format.


def _PrintAnalysisStatusUpdateWindow(self, processing_status):
    if self._stdout_output_writer:
        self._ClearScreen()
    output_text = 'plaso - {0:s} version {1:s}\n\n'.format(self._tool_name, plaso.__version__)
    self._output_writer.Write(output_text)
    self._PrintAnalysisStatusHeader(processing_status)
    table_view = views.CLITabularTableView(column_names=['Identifier', 'PID', 'Status', 'Memory', 'Events', 'Tags', 'Reports'], column_sizes=[23, 7, 15, 15, 15, 15, 0])
    self._AddsAnalysisProcessStatusTableRow(processing_status.foreman_status, table_view)
    for worker_status in processing_status.workers_status:
        self._AddsAnalysisProcessStatusTableRow(worker_status, table_view)
    table_view.Write(self._output_writer)
    self._output_writer.Write('\n')
    if processing_status.aborted:
        self._output_writer.Write('Processing aborted - waiting for clean up.\n\n')
    if self._stdout_output_writer:
        sys.stdout.flush()

Prints an analysis status update in window mode.

Args:
processing_status (ProcessingStatus): processing status.


def bel_edges(self, nanopub: Mapping[(str, Any)], namespace_targets: Mapping[(str, List[str])]={}, rules: List[str]=[], orthologize_target: str=None) -> List[Mapping[(str, Any)]]:
    edges = bel.edge.edges.create_edges(nanopub, self.endpoint, namespace_targets=namespace_targets, rules=rules, orthologize_target=orthologize_target)
    return edges

Create BEL Edges from BEL nanopub

Args:
nanopub (Mapping[str, Any]): bel nanopub
namespace_targets (Mapping[str, List[str]]): what namespaces to canonicalize
rules (List[str]): which computed edge rules to process, default is all,
look at BEL Specification yaml file for computed edge signature keys,
e.g. degradation, if any rule in list is 'skip', then skip computing edges
just return primary_edge
orthologize_target (str): species to convert BEL into, e.g. TAX:10090 for mouse, default option does not orthologize

Returns:
List[Mapping[str, Any]]: edge list with edge attributes (e.g. context)


def GetRootKey(self):
    root_registry_key = virtual.VirtualWinRegistryKey('')
    for mapped_key in self._MAPPED_KEYS:
        key_path_segments = key_paths.SplitKeyPath(mapped_key)
        if (not key_path_segments):
            continue
        registry_key = root_registry_key
        for name in key_path_segments[:(- 1)]:
            sub_registry_key = registry_key.GetSubkeyByName(name)
            if (not sub_registry_key):
                sub_registry_key = virtual.VirtualWinRegistryKey(name)
                registry_key.AddSubkey(sub_registry_key)
            registry_key = sub_registry_key
        sub_registry_key = registry_key.GetSubkeyByName(key_path_segments[(- 1)])
        if ((not sub_registry_key) and isinstance(registry_key, virtual.VirtualWinRegistryKey)):
            sub_registry_key = virtual.VirtualWinRegistryKey(key_path_segments[(- 1)], registry=self)
            registry_key.AddSubkey(sub_registry_key)
    return root_registry_key

Retrieves the Windows Registry root key.

Returns:
WinRegistryKey: Windows Registry root key.

Raises:
RuntimeError: if there are multiple matching mappings and
the correct mapping cannot be resolved.


def update(self, force=False):
    if (self.is_404 and (not force)):
        return 0
    if self._last_modified:
        headers = {'If-Modified-Since': self._last_modified}
    else:
        headers = None
    try:
        res = self._board._requests_session.get(self._api_url, headers=headers)
    except:
        return 0
    if (res.status_code == 304):
        return 0
    elif (res.status_code == 404):
        self.is_404 = True
        self._board._thread_cache.pop(self.id, None)
        return 0
    elif (res.status_code == 200):
        if self.is_404:
            self.is_404 = False
            self._board._thread_cache[self.id] = self
        self.want_update = False
        self.omitted_images = 0
        self.omitted_posts = 0
        self._last_modified = res.headers['Last-Modified']
        posts = res.json()['posts']
        original_post_count = len(self.replies)
        self.topic = Post(self, posts[0])
        if (self.last_reply_id and (not force)):
            self.replies.extend((Post(self, p) for p in posts if (p['no'] > self.last_reply_id)))
        else:
            self.replies[:] = [Post(self, p) for p in posts[1:]]
        new_post_count = len(self.replies)
        post_count_delta = (new_post_count - original_post_count)
        if (not post_count_delta):
            return 0
        self.last_reply_id = self.replies[(- 1)].post_number
        return post_count_delta
    else:
        res.raise_for_status()

Fetch new posts from the server.

Arguments:
force (bool): Force a thread update, even if thread has 404'd.

Returns:
int: How many new posts have been fetched.


def unwrap_aliases(data_type):

    unwrapped_alias = False
    while is_alias(data_type):
        unwrapped_alias = True
        data_type = data_type.data_type
    return data_type, unwrapped_alias

Convenience method to unwrap all Alias(es) from around a DataType.

Args:
data_type (DataType): The target to unwrap.

Return:
Tuple[DataType, bool]: The underlying data type and a bool indicating
whether the input type had at least one alias layer.


def Matches(self, file_entry):
    if (not self._filters):
        return True
    results = []
    for file_entry_filter in self._filters:
        result = file_entry_filter.Matches(file_entry)
        results.append(result)
    return ((True in results) or (False not in results))

Compares the file entry against the filter collection.

Args:
file_entry (dfvfs.FileEntry): file entry to compare.

Returns:
bool: True if the file entry matches one of the filters. If no filters
are provided or applicable the result will be True.


def GetFileObjectByPathSpec(self, path_spec):
    file_entry = self.GetFileEntryByPathSpec(path_spec)
    if (not file_entry):
        return None
    return file_entry.GetFileObject()

Retrieves a file-like object for a path specification.

Args:
path_spec (PathSpec): a path specification.

Returns:
FileIO: a file-like object or None if not available.


def resolve_variables(variables, context, provider):

    for variable in variables:
        variable.resolve(context, provider)

Given a list of variables, resolve all of them.

Args:
variables (list of :class:`stacker.variables.Variable`): list of
variables
context (:class:`stacker.context.Context`): stacker context
provider (:class:`stacker.provider.base.BaseProvider`): subclass of the
base provider


def write(self, symbol, data):
    cursor = self._collection.find()
    for res in cursor:
        library = self._arctic_lib.arctic[res['library_name']]
        dslice = self._slice(data, to_dt(res['start'], mktz('UTC')), to_dt(res['end'], mktz('UTC')))
        if (len(dslice) != 0):
            library.write(symbol, dslice)

Split the tick data to the underlying collections and write the data to each low
level library.

Args:
symbol (str): the symbol for the timeseries data
data (list of dicts or pandas dataframe): Tick data to write
if a list of dicts is given the list must be in time order and the time must be stored in
an element named 'index' the value of which must be a timezone aware datetime.
For a pandas dataframe the index must be a datetime


def to_utc_datetime(self, has_tz: bool=False) -> datetime.datetime:
    epoch = self._epoch_datetime_utc()
    if not has_tz:
        epoch = epoch.replace(tzinfo=None)
    return epoch + datetime.timedelta(microseconds=self.micros)

Returns a ``datetime.datetime`` object of UTC for this Timestamp.

Note that this method returns a ``datetime.datetime`` object without a
timezone info by default, as builtin `datetime.datetime.utcnow` method. If
this is used as part of the processed data, one should set has_tz=True to
avoid offset due to default timezone mismatch.

Args:
has_tz: whether the timezone info is attached, default to False.

Returns:
a ``datetime.datetime`` object of UTC for this Timestamp.


def SetKeyPathPrefix(self, key_path_prefix):
    self._key_path_prefix = key_path_prefix
    self._key_path_prefix_length = len(key_path_prefix)
    self._key_path_prefix_upper = key_path_prefix.upper()

Sets the Window Registry key path prefix.

Args:
key_path_prefix (str): Windows Registry key path prefix.


class FlaxForceTokensLogitsProcessor(FlaxLogitsProcessor):

    def __init__(self, force_token_map):
        force_token_map = dict(force_token_map)
        force_token_array = jnp.ones(max(force_token_map.keys()) + 1, dtype=jnp.int32) * -1
        for index, token in force_token_map.items():
            if token is not None:
                force_token_array = force_token_array.at[index].set(token)
        self.force_token_array = jnp.int32(force_token_array)

    def __call__(self, input_ids: jnp.ndarray, scores: jnp.ndarray, cur_len: int) -> jnp.ndarray:

        def _force_token(generation_idx):
            batch_size = scores.shape[0]
            current_token = self.force_token_array[generation_idx]
            new_scores = jnp.ones_like(scores, dtype=scores.dtype) * -float('inf')
            updates = jnp.zeros((batch_size, 1), dtype=scores.dtype)
            new_scores = lax.dynamic_update_slice(new_scores, updates, (0, current_token))
            return new_scores
        scores = lax.cond(cur_len >= self.force_token_array.shape[0], lambda: scores, lambda: lax.cond(self.force_token_array[cur_len] >= 0, lambda: _force_token(cur_len), lambda: scores))
        return scores

[`FlaxLogitsProcessor`] that takes a list of pairs of integers which indicates a mapping from generation indices to
token indices that will be forced before sampling. The processor will set their log probs to 0 and all other tokens
to `-inf` so that they are sampled at their corresponding index.

Args:
force_token_map (`list`):
Map giving token ids and indices where they will be forced to be sampled.


def pad_image(self, image: np.ndarray, size: Dict[str, int], random_padding: bool=False, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None) -> np.ndarray:
    output_height, output_width = (size['height'], size['width'])
    input_height, input_width = get_image_size(image, channel_dim=input_data_format)
    delta_width = output_width - input_width
    delta_height = output_height - input_height
    if random_padding:
        pad_top = np.random.randint(low=0, high=delta_height + 1)
        pad_left = np.random.randint(low=0, high=delta_width + 1)
    else:
        pad_top = delta_height
        pad_left = delta_width
    pad_bottom = delta_height - pad_top
    pad_right = delta_width - pad_left
    padding = ((pad_top, pad_bottom), (pad_left, pad_right))
    return pad(image, padding, data_format=data_format, input_data_format=input_data_format)

Pad the image to the specified size.

Args:
image (`np.ndarray`):
The image to be padded.
size (`Dict[str, int]`):
The size `{"height": h, "width": w}` to pad the image to.
random_padding (`bool`, *optional*, defaults to `False`):
Whether to use random padding or not.
data_format (`str` or `ChannelDimension`, *optional*):
The data format of the output image. If unset, the same format as the input image is used.
input_data_format (`ChannelDimension` or `str`, *optional*):
The channel dimension format of the input image. If not provided, it will be inferred.


def mcast_ip_mask(ip_addr_and_mask, return_tuple=True):

    regex_mcast_ip_and_mask = __re.compile("^(((2[2-3][4-9])|(23[0-3]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))/((3[0-2])|([1-2][0-9])|[3-9]))$")
    if return_tuple:
        while not regex_mcast_ip_and_mask.match(ip_addr_and_mask):
            print("Not a good multicast IP and CIDR mask combo.")
            print("Please try again.")
            ip_addr_and_mask = input("Please enter a multicast IP address and mask in the follwing format x.x.x.x/x: ")
        ip_cidr_split = ip_addr_and_mask.split("/")
        ip_addr = ip_cidr_split[0]
        cidr = ip_cidr_split[1]
        return ip_addr, cidr
    elif not return_tuple:
        if not regex_mcast_ip_and_mask.match(ip_addr_and_mask):
            return False
        else:
            return True

Function to check if a address is multicast and that the CIDR mask is good
Args:
ip_addr_and_mask: Multicast IP address and mask in the following format 239.1.1.1/24
return_tuple: Set to True it returns a IP and mask in a tuple, set to False returns True or False

Returns: see return_tuple for return options


def _ParseBooleanValue(self, byte_stream):
    if (byte_stream == b'\x00'):
        return False
    if (byte_stream == b'\x01'):
        return True
    raise errors.ParseError('Unsupported boolean value.')

Parses a boolean value.

Args:
byte_stream (bytes): byte stream.

Returns:
bool: boolean value.

Raises:
ParseError: when the boolean value cannot be parsed.


def threat(self, name, owner=None, **kwargs):

        return Threat(self.tcex, name, owner=owner, **kwargs)

Create the Threat TI object.

Args:
owner:
name:
**kwargs:

Return:


def sspro_results(self):
    return ssbio.protein.sequence.utils.fasta.load_fasta_file_as_dict_of_seqs(self.out_sspro)

Parse the SSpro output file and return a dict of secondary structure compositions.

Returns:
dict: Keys are sequence IDs, values are the lists of secondary structure predictions.
H: helix
E: strand
C: the rest


def put_path(self, url, path):
    cache_path = self._url_to_path(url)
    try:
        dir = os.path.dirname(cache_path)
        os.makedirs(dir)
    except OSError as e:
        if (e.errno != errno.EEXIST):
            raise Error(('Failed to create cache directories for ' % cache_path))
    try:
        os.unlink(cache_path)
    except OSError:
        pass
    try:
        os.link(path, cache_path)
    except OSError:
        try:
            shutil.copyfile(path, cache_path)
        except IOError:
            raise Error(('Failed to cache %s as %s for %s' % (path, cache_path, url)))

Puts a resource already on disk into the disk cache.

Args:
url: The original url of the resource
path: The resource already available on disk

Raises:
CacheError: If the file cannot be put in cache


def is_apk_installed(device: AndroidDevice, package_name: str) -> bool:
    try:
        out = device.adb.shell(['pm', 'list', 'package'])
        return bool(utils.grep('^package:%s$' % package_name, out))
    except adb.AdbError as error:
        raise errors.DeviceError(device, error)

Check if the given apk is already installed.

Args:
device: AndroidDevice, Mobly's Android controller object.
package_name: str, name of the package.

Returns:
True if package is installed. False otherwise.


def run_inference(self, batch: Sequence[pandas.DataFrame], model: BaseEstimator, inference_args: Optional[dict[str, Any]]=None) -> Iterable[PredictionResult]:
    for dataframe in iter(batch):
        if dataframe.shape[0] != 1:
            raise ValueError('Only dataframes with single rows are supported.')
    predictions, splits = self._model_inference_fn(model, batch, inference_args)
    return utils._convert_to_result(splits, predictions, model_id=self._model_uri)

Runs inferences on a batch of pandas dataframes.

Args:
batch: A sequence of examples as numpy arrays. They should
be single examples.
model: A dataframe model or pipeline. Must implement predict(X).
Where the parameter X is a pandas dataframe.
inference_args: Any additional arguments for an inference.

Returns:
An Iterable of type PredictionResult.


def config_cmd_handler(conf, config='config'):
    if (conf[config].create or conf[config].update):
        conf.create_config_(update=conf[config].update)
    if conf[config].create_local:
        conf.create_config_(index=(- 1), update=conf[config].update)
    if conf[config].edit:
        if (not conf.config_files_[0].is_file()):
            conf.create_config_(update=conf[config].update)
        subprocess.call(shlex.split('{} {}'.format(conf[config].editor, conf.config_files_[0])))

Implement the behavior of a subcmd using config_conf_section

Args:
conf (:class:`~loam.manager.ConfigurationManager`): it should contain a
section created with :func:`config_conf_section` function.
config (str): name of the configuration section created with
:func:`config_conf_section` function.


def AddArguments(cls, argument_group):

    shared_4n6time_output.Shared4n6TimeOutputArgumentsHelper.AddArguments(
        argument_group)
    MySQL4n6TimeDatabaseArgumentsHelper.AddArguments(argument_group)

Adds command line arguments the helper supports to an argument group.

This function takes an argument parser or an argument group object and adds
to it all the command line arguments this helper supports.

Args:
argument_group (argparse._ArgumentGroup|argparse.ArgumentParser):
argparse group.


def get_kwdefaults(func, parse_source=False):
    r

    argspec = inspect.getargspec(func)
    kwdefaults = {}
    if argspec.args is None or argspec.defaults is None:
        pass
    else:
        args = argspec.args
        defaults = argspec.defaults

        kwpos = len(args) - len(defaults)
        kwdefaults = OrderedDict(zip(args[kwpos:], defaults))
    if parse_source and argspec.keywords:

        keyword_defaults = parse_func_kwarg_keys(func, with_vals=True)
        for key, val in keyword_defaults:
            assert key not in kwdefaults, 'parsing error'
            kwdefaults[key] = val
    return kwdefaults

r"""
Args:
func (func):

Returns:
dict:

CommandLine:
python -m utool.util_inspect get_kwdefaults

Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_inspect import *  # NOQA
>>> import utool as ut
>>> func = dummy_func
>>> parse_source = True
>>> kwdefaults = get_kwdefaults(func, parse_source)
>>> print('kwdefaults = %s' % (ut.repr4(kwdefaults),))


def write_config_files(self, host, hyperparameters, input_data_config):
    config_path = os.path.join(self.container_root, host, 'input', 'config')
    resource_config = {'current_host': host, 'hosts': self.hosts}
    json_input_data_config = {}
    for c in input_data_config:
        channel_name = c['ChannelName']
        json_input_data_config[channel_name] = {'TrainingInputMode': 'File'}
        if ('ContentType' in c):
            json_input_data_config[channel_name]['ContentType'] = c['ContentType']
    _write_json_file(os.path.join(config_path, 'hyperparameters.json'), hyperparameters)
    _write_json_file(os.path.join(config_path, 'resourceconfig.json'), resource_config)
    _write_json_file(os.path.join(config_path, 'inputdataconfig.json'), json_input_data_config)

Write the config files for the training containers.

This method writes the hyperparameters, resources and input data configuration files.

Args:
host (str): Host to write the configuration for
hyperparameters (dict): Hyperparameters for training.
input_data_config (dict): Training input channels to be used for training.

Returns: None


def get_vcf_entry(variant_obj, case_id=None):

    if variant_obj['category'] == 'snv':
        var_type = 'TYPE'
    else:
        var_type = 'SVTYPE'

    info_field = ';'.join(
            [
                'END='+str(variant_obj['end']),
                var_type+'='+variant_obj['sub_category'].upper()
            ]
        )

    variant_string = "{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}".format(
        variant_obj['chromosome'],
        variant_obj['position'],
        variant_obj['dbsnp_id'],
        variant_obj['reference'],
        variant_obj['alternative'],
        variant_obj['quality'],
        ';'.join(variant_obj['filters']),
        info_field
    )

    if case_id:
        variant_string += "\tGT"
        for sample in variant_obj['samples']:
            variant_string += "\t" + sample['genotype_call']

    return variant_string

Get vcf entry from variant object

Args:
variant_obj(dict)
Returns:
variant_string(str): string representing variant in vcf format


def _stringify_path(path_or_buffer):

    try:
        import pathlib
        _PATHLIB_INSTALLED = True
    except ImportError:
        _PATHLIB_INSTALLED = False

    if hasattr(path_or_buffer, '__fspath__'):
        return path_or_buffer.__fspath__()

    if _PATHLIB_INSTALLED and isinstance(path_or_buffer, pathlib.Path):
        return text_type(path_or_buffer)

    return path_or_buffer

Convert path like object to string

Args:
path_or_buffer: object to be converted

Returns:
string_path_or_buffer: maybe string version of path_or_buffer


def get_max_id(cls, session):
    id_base = None
    for c in ([cls] + list(cls.__bases__)):
        for base_class in c.__bases__:
            if (base_class.__name__ == 'Base'):
                if (id_base is None):
                    id_base = c
                else:
                    raise RuntimeError(('Multiple base object classes for class ' + cls.__name__))
    if (id_base is None):
        raise RuntimeError(('Error searching for base class of ' + cls.__name__))
    max_id = session.query(func.max(id_base.id)).scalar()
    if (max_id is None):
        max_id = 0
    return max_id

Get the current max value of the ``id`` column.

When creating and storing ORM objects in bulk, :mod:`sqlalchemy` does not automatically
generate an incrementing primary key ``id``. To do this manually, one needs to know the
current max ``id``. For ORM object classes that are derived from other ORM object classes,
the max ``id`` of the lowest base class is returned. This is designed to be used with
inheritance by joining, in which derived and base class objects have identical ``id`` values.

Args:
session: database session to operate in


def property_get(self, callself: 'cfg.Variable', is_class: bool=False) -> 'BaseValue':
    del callself, is_class
    return self

Bind this value to the given self or cls.

This function is similar to __get__ except at the abstract level. This does
not trigger any code execution inside the VM. See __get__ for more details.

Args:
callself: The Variable that should be passed as self or cls when the call
is made. We only need one of self or cls, so having them share a
parameter prevents accidentally passing in both.
is_class: Whether callself is self or cls. Should be cls only when we want
to directly pass in a class to bind a class method to, rather than
passing in an instance and calling get_class().

Returns:
Another abstract value that should be returned in place of this one. The
default implementation returns self, so this can always be called safely.


def gather(weights, indices, dim, output_shape=None):

  dim = convert_to_dimension(dim)
  output_shape = convert_to_shape(output_shape)
  if weights.dtype == tf.bool:
    return cast(gather(to_float(weights), indices, dim, output_shape), tf.bool)
  return einsum([one_hot(indices, dim, dtype=weights.dtype), weights],
                reduced_dims=[dim], output_shape=output_shape)

Shorthand for einsum([one_hot(indices, dim)], weights, reduced_dims=[dim]).

Args:
weights: a Tensor
indices: a Tensor with integer type
dim: a Dimension
output_shape: an optional mtf.Shape
Returns:
a Tensor


def __init__(self, enum_values=None, case_sensitive=True):

    super(EnumParser, self).__init__()
    self.enum_values = enum_values
    self.case_sensitive = case_sensitive

Initialize EnumParser.

Args:
enum_values: Array of values in the enum.
case_sensitive: Whether or not the enum is to be case-sensitive.


def GetBlockByHeight(self, height):

        hash = self.GetBlockHash(height)
        if hash is not None:
            return self.GetBlockByHash(hash)

Get a block by its height.
Args:
height(int): the height of the block to retrieve.

Returns:
neo.Core.Block: block instance.


def clear_executor_errors(self):
    if self._context_handle:
        pywrap_tfe.TFE_ContextClearExecutors(self._context_handle)
    else:
        raise ValueError('Context is not initialized.')

Clear errors in both local executors and remote workers.

After receiving errors from remote workers, additional requests on the fly
could further taint the status on the remote workers due to the async nature
of remote execution. Calling this method block on waiting for all pending
nodes in remote executors to finish and clear their error statuses.

Raises:
ValueError: if context is not initialized.


def mark_flags_as_required(flag_names, flag_values=_flagvalues.FLAGS):
    for flag_name in flag_names:
        mark_flag_as_required(flag_name, flag_values)

Ensures that flags are not None during program execution.

Recommended usage:

if __name__ == '__main__':
flags.mark_flags_as_required(['flag1', 'flag2', 'flag3'])
app.run()

Args:
flag_names: Sequence[str], names of the flags.
flag_values: flags.FlagValues, optional FlagValues instance where the flags
are defined.
Raises:
AttributeError: If any of flag name has not already been defined as a flag.


def load_model(itos_filename, classifier_filename, num_classes):
    itos = pickle.load(Path(itos_filename).open('rb'))
    stoi = collections.defaultdict((lambda : 0), {str(v): int(k) for (k, v) in enumerate(itos)})
    (bptt, em_sz, nh, nl) = (70, 400, 1150, 3)
    dps = (np.array([0.4, 0.5, 0.05, 0.3, 0.4]) * 0.5)
    vs = len(itos)
    model = get_rnn_classifer(bptt, (20 * 70), num_classes, vs, emb_sz=em_sz, n_hid=nh, n_layers=nl, pad_token=1, layers=[(em_sz * 3), 50, num_classes], drops=[dps[4], 0.1], dropouti=dps[0], wdrop=dps[1], dropoute=dps[2], dropouth=dps[3])
    model.load_state_dict(torch.load(classifier_filename, map_location=(lambda storage, loc: storage)))
    model.reset()
    model.eval()
    return (stoi, model)

Load the classifier and int to string mapping

Args:
itos_filename (str): The filename of the int to string mapping file (usually called itos.pkl)
classifier_filename (str): The filename of the trained classifier

Returns:
string to int mapping, trained classifer model


def get_rel_pos(self, q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
    max_rel_dist = int(2 * max(q_size, k_size) - 1)
    rel_pos_resized = F.interpolate(rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), size=max_rel_dist, mode='linear')
    rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
    q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
    k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
    relative_coords = q_coords - k_coords + (k_size - 1) * max(q_size / k_size, 1.0)
    return rel_pos_resized[relative_coords.long()]

Get relative positional embeddings according to the relative positions of
query and key sizes.

Args:
q_size (int):
size of the query.
k_size (int):
size of key k.
rel_pos (`torch.Tensor`):
relative position embeddings (L, channel).

Returns:
Extracted positional embeddings according to relative positions.


def get_transformation(self, struct1, struct2):
    if self._primitive_cell:
        raise ValueError('get_transformation cannot be used with the primitive cell option')
    (struct1, struct2) = self._process_species((struct1, struct2))
    (s1, s2, fu, s1_supercell) = self._preprocess(struct1, struct2, False)
    ratio = (fu if s1_supercell else (1 / fu))
    if (s1_supercell and (fu > 1)):
        raise ValueError('Struct1 must be the supercell, not the other way around')
    if ((len(s1) * ratio) >= len(s2)):
        match = self._strict_match(s1, s2, fu=fu, s1_supercell=False, use_rms=True, break_on_match=False)
        if (match is None):
            return None
        mapping = [(list(match[4]).index(i) if (i in match[4]) else None) for i in range(len(s1))]
        return (match[2], match[3], mapping)
    else:
        match = self._strict_match(s2, s1, fu=fu, s1_supercell=True, use_rms=True, break_on_match=False)
        if (match is None):
            return None
        not_included = list(range((len(s2) * fu)))
        for i in match[4]:
            not_included.remove(i)
        mapping = (list(match[4]) + not_included)
        return (match[2], (- match[3]), mapping)

Returns the supercell transformation, fractional translation vector,
and a mapping to transform struct2 to be similar to struct1.

Args:
struct1 (Structure): Reference structure
struct2 (Structure): Structure to transform.

Returns:
supercell (numpy.ndarray(3, 3)): supercell matrix
vector (numpy.ndarray(3)): fractional translation vector
mapping (list(int or None)):
The first len(struct1) items of the mapping vector are the
indices of struct1's corresponding sites in struct2 (or None
if there is no corresponding site), and the other items are
the remaining site indices of struct2.


def serialize_example(transformed_json_data, features, feature_indices, target_name):
    import six
    import tensorflow as tf
    from trainer import feature_transforms
    line = str(transformed_json_data[target_name][0])
    for (name, info) in feature_indices:
        if (features[name]['transform'] in [feature_transforms.IDENTITY_TRANSFORM, feature_transforms.SCALE_TRANSFORM]):
            line += (' %d:%s' % (info['index_start'], str(transformed_json_data[name][0])))
        elif (features[name]['transform'] in [feature_transforms.ONE_HOT_TRANSFORM, feature_transforms.MULTI_HOT_TRANSFORM]):
            for i in range(info['size']):
                if (i in transformed_json_data[name]):
                    line += (' %d:1' % (info['index_start'] + i))
        elif (features[name]['transform'] in [feature_transforms.IMAGE_TRANSFORM]):
            for i in range(info['size']):
                line += (' %d:%s' % ((info['index_start'] + i), str(transformed_json_data[name][i])))
    return line

Makes an instance of data in libsvm format.

Args:
transformed_json_data: dict of transformed data.
features: features config.
feature_indices: output of feature_transforms.get_transformed_feature_indices()

Returns:
The text line representation of an instance in libsvm format.


def make_input_feature_spec(include_label=True):
    result = {}
    if include_label:
        result['clicked'] = tf.io.FixedLenFeature(shape=[], dtype=tf.int64)
    for name in _INTEGER_COLUMN_NAMES:
        result[name] = tf.io.VarLenFeature(dtype=tf.int64)
    for name in _CATEGORICAL_COLUMN_NAMES:
        result[name] = tf.io.VarLenFeature(dtype=tf.string)
    return result

Input schema definition.

Args:
include_label: Indicates whether the label feature should be included.

Returns:
A `Schema` object.


def _add_step(self, step):
    self._closed()
    self.has_workflow_step = (self.has_workflow_step or step.is_workflow)
    self.wf_steps[step.name_in_workflow] = step

Add a step to the workflow.

Args:
step (Step): a step from the steps library.


def inspect_file(path):
    with open(path, 'rb') as f:
        (labels, count) = inspect((tx.decode(line) for line in f))
    return (labels, count)

Inspect SDFile structure

Returns:
tuple: (data label list, number of records)


def sign_hash(private_key, hash, hash_algo):

    hash_algo = _hash_algorithms[hash_algo]
    return get_privatekey(private_key).sign(
        hash,
        padding.PKCS1v15(),
        utils.Prehashed(hash_algo),
    )

Sign the given hash with the given private key.

Args:
private_key (str): PEM enoded private key
hash (byte str): hash to sign
hash_algo (str): name of hash algorithm used

Returns:
byte string representing the signature


def process_one_file(options):
    log.info('Process %s => %s', options.input, options.output)
    try:
        ret = check_or_generate_pyi(options)
    except utils.UsageError:
        logging.exception('')
        return 1
    if not options.check:
        if options.pickle_output:
            pyi_output = options.verify_pickle
        else:
            pyi_output = options.output
        if pyi_output:
            _write_pyi_output(options, ret.pyi, pyi_output)
        if options.pickle_output:
            log.info('write pickle %r => %r', options.input, options.output)
            write_pickle(ret.ast, options, ret.context.loader)
    if options.unused_imports_info_files:
        if options.use_rewrite:
            pass
        else:
            cwd = os.getcwd()
            unused_paths = sorted(ret.context.loader.get_unused_imports_map_paths())
            with options.open_function(options.unused_imports_info_files, 'wt', encoding='utf-8') as f:
                for unused_path in unused_paths:
                    f.write(f'{os.path.relpath(unused_path, cwd)}\n')
    exit_status = handle_errors(ret.context.errorlog, options)
    ret.context.program = None
    if options.touch and (not exit_status):
        with options.open_function(options.touch, 'a'):
            os.utime(options.touch, None)
    return exit_status

Check a .py file or generate a .pyi for it, according to options.

Args:
options: config.Options object.

Returns:
An error code (0 means no error).


def get_errors(self):
    errors = []
    errors.extend(self._get_signature_errors())
    errors.extend(self._get_additional_errors())
    errors.extend(self._get_entry_errors())
    return (errors if errors else None)

Verify that this MAR file is well formed.

Returns:
A list of strings describing errors in the MAR file
None if this MAR file appears well formed.


def from_dict(vpc_config, do_sanitize=False):
    if do_sanitize:
        vpc_config = sanitize(vpc_config)
    if (vpc_config is None):
        return (None, None)
    return (vpc_config[SUBNETS_KEY], vpc_config[SECURITY_GROUP_IDS_KEY])

Extracts subnets and security group ids as lists from a VpcConfig dict

Args:
vpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupIds'
do_sanitize (bool): whether to sanitize the VpcConfig dict before extracting values

Returns:
Tuple of lists as (subnets, security_group_ids)
If vpc_config parameter is None, returns (None, None)

Raises:
ValueError if sanitize enabled and vpc_config is invalid
KeyError if sanitize disabled and vpc_config is missing key(s)


def __call__(self,
            state: Sequence[tf.Tensor],
            timestep: tf.Tensor) -> Sequence[tf.Tensor]:

        raise NotImplementedError

Returns action fluents for the current `state` and `timestep`.

Args:
state (Sequence[tf.Tensor]): The current state fluents.
timestep (tf.Tensor): The current timestep.

Returns:
Sequence[tf.Tensor]: A tuple of action fluents.


def compute_output_shape(self, input_shape):

    input_shape = tf.TensorShape(input_shape).as_list()
    if self.data_format == 'channels_last':
      space = input_shape[1:-1]
      new_space = []
      for i in range(len(space)):
        new_dim = tf_layers_util.conv_output_length(
            space[i],
            self.kernel_size[i],
            padding=self.padding,
            stride=self.strides[i],
            dilation=self.dilation_rate[i])
        new_space.append(new_dim)
      return tf.TensorShape([input_shape[0]] + new_space + [self.filters])
    else:
      space = input_shape[2:]
      new_space = []
      for i in range(len(space)):
        new_dim = tf_layers_util.conv_output_length(
            space[i],
            self.kernel_size[i],
            padding=self.padding,
            stride=self.strides[i],
            dilation=self.dilation_rate[i])
        new_space.append(new_dim)
      return tf.TensorShape([input_shape[0], self.filters] + new_space)

Computes the output shape of the layer.

Args:
input_shape: Shape tuple (tuple of integers) or list of shape tuples
(one per output tensor of the layer). Shape tuples can include None for
free dimensions, instead of an integer.

Returns:
output_shape: A tuple representing the output shape.


def read_data_to_asp(file: str) -> List[str]:

    if file.endswith(".json"):
        with open(file) as f:
            data = json.load(f)
            return schema2asp(data2schema(data))
    elif file.endswith(".csv"):
        df = pd.read_csv(file)
        df = df.where((pd.notnull(df)), None)
        data = list(df.T.to_dict().values())
        schema = data2schema(data)
        asp = schema2asp(schema)
        return asp
    else:
        raise Exception("invalid file type")

Reads the given JSON file and generates the ASP definition.
Args:
file: the json data file
Returns:
the asp definition.


def orient_averaged_fixed(tm):

    S = np.zeros((2,2), dtype=complex)
    Z = np.zeros((4,4))
    ap = np.linspace(0, 360, tm.n_alpha+1)[:-1]
    aw = 1.0/tm.n_alpha

    for alpha in ap:
        for (beta, w) in zip(tm.beta_p, tm.beta_w):
            (S_ang, Z_ang) = tm.get_SZ_single(alpha=alpha, beta=beta)
            S += w * S_ang
            Z += w * Z_ang

    sw = tm.beta_w.sum()

    S *= aw/sw
    Z *= aw/sw

    return (S, Z)

Compute the T-matrix using variable orientation scatterers.

This method uses a fast Gaussian quadrature and is suitable
for most use. Uses the set particle orientation PDF, ignoring
the alpha and beta attributes.

Args:
tm: TMatrix (or descendant) instance.

Returns:
The amplitude (S) and phase (Z) matrices.


def __init__(self, options):

        self.queue = Queue(options)
        self.routing = Routing(options)
        self.__options = options
        self.__should_spawn_new_requests = False
        self.__should_stop = False
        self.__stopping = False
        self.__stopped = False
        self.__threads = {}
        self.__lock = threading.Lock()

        signal.signal(signal.SIGINT, self.__signal_handler)
        DebugHelper.setup(self.__options)

Constructs a Crawler instance.

Args:
options (:class:`nyawc.Options`): The options to use for the current crawling runtime.


def MultiHeadedAttentionQKV(
    feature_depth, num_heads=8, dropout=0.0, mode='train'):

  return combinators.Serial(
      combinators.Parallel(
          combinators.Parallel(
              core.Dense(feature_depth),
              core.Dense(feature_depth),
              core.Dense(feature_depth),
          ),
          combinators.Identity()
      ),
      PureMultiHeadedAttention(
          feature_depth=feature_depth, num_heads=num_heads,
          dropout=dropout, mode=mode),
      core.Dense(feature_depth),
  )

Transformer-style multi-headed attention.

Accepts inputs of the form (q, k, v), mask.

Args:
feature_depth: int:  depth of embedding
num_heads: int: number of attention heads
dropout: float: dropout rate
mode: str: 'train' or 'eval'

Returns:
Multi-headed self-attention layer.


def add_update_resource_views(self, resource_views):

        if not isinstance(resource_views, list):
            raise HDXError('ResourceViews should be a list!')
        for resource_view in resource_views:
            self.add_update_resource_view(resource_view)

Add new or update existing resource views in resource with new metadata.

Args:
resource_views (List[Union[ResourceView,Dict]]): A list of resource views metadata from ResourceView objects or dictionaries

Returns:
None


def FromEvent(cls, service_event):

    _, _, name = service_event.key_path.rpartition(
        WindowsService._REGISTRY_KEY_PATH_SEPARATOR)
    service_type = service_event.regvalue.get('Type', '')
    image_path = service_event.regvalue.get('ImagePath', '')
    start_type = service_event.regvalue.get('Start', '')
    service_dll = service_event.regvalue.get('ServiceDll', '')
    object_name = service_event.regvalue.get('ObjectName', '')

    if service_event.pathspec:
      source = (service_event.pathspec.location, service_event.key_path)
    else:
      source = ('Unknown', 'Unknown')
    return cls(
        name=name, service_type=service_type, image_path=image_path,
        start_type=start_type, object_name=object_name,
        source=source, service_dll=service_dll)

Creates a service object from an event.

Args:
service_event (EventObject): event to create a new service object from.

Returns:
WindowsService: service.


def fetch(version='bayestar2017'):
    doi = {'bayestar2015': '10.7910/DVN/40C44C', 'bayestar2017': '10.7910/DVN/LCYHJG'}
    try:
        doi = doi[version]
    except KeyError as err:
        raise ValueError('Version "{}" does not exist. Valid versions are: {}'.format(version, ', '.join(['"{}"'.format(k) for k in doi.keys()])))
    requirements = {'bayestar2015': {'contentType': 'application/x-hdf'}, 'bayestar2017': {'filename': 'bayestar2017.h5'}}[version]
    local_fname = os.path.join(data_dir(), 'bayestar', '{}.h5'.format(version))
    fetch_utils.dataverse_download_doi(doi, local_fname, file_requirements=requirements)

Downloads the specified version of the Bayestar dust map.

Args:
version (Optional[:obj:`str`]): The map version to download. Valid versions are
:obj:`'bayestar2017'` (Green, Schlafly, Finkbeiner et al. 2018) and
:obj:`'bayestar2015'` (Green, Schlafly, Finkbeiner et al. 2015). Defaults
to :obj:`'bayestar2017'`.

Raises:
:obj:`ValueError`: The requested version of the map does not exist.

:obj:`DownloadError`: Either no matching file was found under the given DOI, or
the MD5 sum of the file was not as expected.

:obj:`requests.exceptions.HTTPError`: The given DOI does not exist, or there
was a problem connecting to the Dataverse.


def _FetchServerCertificate(self):
    if self.server_certificate:
        return True
    response = self.http_manager.OpenServerEndpoint('server.pem', verify_cb=self.VerifyServerPEM)
    if response.Success():
        self.server_certificate = response.data
        return True
    self.timer.SlowPoll()
    return False

Attempts to fetch the server cert.

Returns:
True if we succeed.


def create_team(self, name):
    request = self._get_request()
    return request.post(self.TEAM_CREATE_URL, {'name': name})

Creates a new Team

Creates a new Team and makes you a member. You must not currently belong to a team to invoke.

Args:

name (str): The name of your team

Returns:
A Team object


def get_integer_index(miller_index: bool, round_dp: int=4, verbose: bool=True) -> Tuple[(int, int, int)]:
    miller_index = np.asarray(miller_index)
    miller_index /= min([m for m in miller_index if (m != 0)])
    miller_index /= np.max(np.abs(miller_index))
    md = [Fraction(n).limit_denominator(12).denominator for n in miller_index]
    miller_index *= reduce((lambda x, y: (x * y)), md)
    int_miller_index = np.int_(np.round(miller_index, 1))
    miller_index /= np.abs(reduce(gcd, int_miller_index))
    miller_index = np.array([round(h, round_dp) for h in miller_index])
    int_miller_index = np.int_(np.round(miller_index, 1))
    if (np.any((np.abs((miller_index - int_miller_index)) > 1e-06)) and verbose):
        warnings.warn('Non-integer encountered in Miller index')
    else:
        miller_index = int_miller_index
    miller_index += 0

    def n_minus(index):
        return len([h for h in index if (h < 0)])
    if (n_minus(miller_index) > n_minus((miller_index * (- 1)))):
        miller_index *= (- 1)
    if ((sum((miller_index != 0)) == 2) and (n_minus(miller_index) == 1) and (abs(min(miller_index)) > max(miller_index))):
        miller_index *= (- 1)
    return tuple(miller_index)

Attempt to convert a vector of floats to whole numbers.

Args:
miller_index (list of float): A list miller indexes.
round_dp (int, optional): The number of decimal places to round the
miller index to.
verbose (bool, optional): Whether to print warnings.

Returns:
(tuple): The Miller index.


def extract_distribution(monitoring_info_proto):
    if not is_distribution(monitoring_info_proto):
        raise ValueError('Unsupported type %s' % monitoring_info_proto.type)
    return _decode_distribution(coders.VarIntCoder(), monitoring_info_proto.payload)

Returns a tuple of (count, sum, min, max).

Args:
proto: The monitoring info for the distribution.


def export_default_instruments(target_folder, source_folder = None, raise_errors = False, verbose=True):

    print('export_def_instr called')
    instruments_to_load = get_classes_in_folder(source_folder, Instrument, verbose = True)
    print('instruments to load:')
    print(instruments_to_load)

    if verbose:
        print(('attempt to load {:d} instruments: '.format(len(instruments_to_load))))
    loaded_instruments, failed = Instrument.load_and_append(instruments_to_load, raise_errors = raise_errors)
    print('loaded instruments:')
    print(loaded_instruments, failed)

    for name, value in loaded_instruments.items():
        filename = os.path.join(target_folder, '{:s}.b26'.format(name))

        value.save_b26(filename)

    if verbose:
        print('\n================================================')
        print('================================================')
        print(('saved {:d} instruments, {:d} failed'.format(len(loaded_instruments), len(failed))))
        if failed != {}:
            for error_name, error in failed.items():
                print(('failed to create instruments: ', error_name, error))

tries to instantiate all the instruments that are imported in /instruments/__init__.py
and saves instruments that could be instantiate into a .b2 file in the folder path
Args:
target_folder: target path for .b26 files


def account_states(self, **kwargs):

        path = self._get_id_path('account_states')

        response = self._GET(path, kwargs)
        self._set_attrs_to_values(response)
        return response

This method lets users get the status of whether or not the movie has
been rated or added to their favourite or watch lists. A valid session
id is required.

Args:
session_id: see Authentication.

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


def load_pos_model(lang='en', version='2'):
    src_dir = 'pos{}'.format(version)
    p = locate_resource(src_dir, lang)
    fh = _open(p)
    return dict(np.load(fh))

Return a part of speech tagger parameters for `lang` and of version `version`

Args:
lang (string): language code.
version (string): version of the parameters to be used.


def _parse_service(service) -> tuple[str, str]:
    if not isinstance(service, str):
        raise ValueError(f'`service` must be a string, but `service` was of type {type(service)}. service={service}')
    if not service:
        raise ValueError('`service` must not be empty')
    parts = service.split(':
    if len(parts) == 2:
        protocol, address = parts
    elif len(parts) == 1:
        address = parts[0]
        protocol = _pywrap_utils_exp.TF_DATA_DefaultProtocol()
    else:
        raise ValueError(f"Malformed `service` string has multiple ':
    return (protocol, address)

Converts a tf.data service string into a (protocol, address) tuple.

Args:
service: A string in the format "protocol://address" or just "address". If
the string is only an address, the default protocol will be used.

Returns:
The (protocol, address) tuple


Pre-fetches all required items to be update into the cache.

This increases performance for update operations.

Args:
feed: List of feed items to retrieve


def output(self, _filename):

        for contract in self.slither.contracts_derived:
            txt = "\nContract %s"%contract.name
            table = PrettyTable(["Function",
                                 "require or assert"])
            for function in contract.functions:
                require = function.all_slithir_operations()
                require = [ir for ir in require if isinstance(ir, SolidityCall) and ir.function in require_or_assert]
                require = [ir.node for ir in require]
                table.add_row([function.name, self._convert([str(m.expression) for m in set(require)])])
            txt += "\n"+str(table)
            self.info(txt)

_filename is not used
Args:
_filename(string)


def find_elb(name='', env='', region=''):

    LOG.info('Find %s ELB in %s [%s].', name, env, region)

    url = '{0}/applications/{1}/loadBalancers'.format(API_URL, name)
    response = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)
    assert response.ok

    elb_dns = None
    accounts = response.json()
    for account in accounts:
        if account['account'] == env and account['region'] == region:
            elb_dns = account['dnsname']
            break
    else:
        raise SpinnakerElbNotFound('Elb for "{0}" in region {1} not found'.format(name, region))

    LOG.info('Found: %s', elb_dns)
    return elb_dns

Get an application's AWS elb dns name.

Args:
name (str): ELB name
env (str): Environment/account of ELB
region (str): AWS Region

Returns:
str: elb DNS record


def item(self, key):
    return _item.Item(self._name, key, context=self._context)

Retrieves an Item object for the specified key in this bucket.

The item need not exist.

Args:
key: the key of the item within the bucket.
Returns:
An Item instance representing the specified key.


def transform(self, target_type: Type[T], value: F, context: PipelineContext=None) -> T:
    pass

Transforms an object to a new type.

Args:
target_type: The type to be converted to.
value: The object to be transformed.
context: The context of the transformation (mutable).


def MultiDeleteAttributes(self, subjects, attributes, start=None, end=None, sync=True):
    for subject in subjects:
        self.DeleteAttributes(subject, attributes, start=start, end=end, sync=sync)

Remove all specified attributes from a list of subjects.

Args:
subjects: The list of subjects that will have these attributes removed.
attributes: A list of attributes.
start: A timestamp, attributes older than start will not be deleted.
end: A timestamp, attributes newer than end will not be deleted.
sync: If true we block until the operation completes.


def _ProcessFileEntry(self, mediator, file_entry):
    display_name = mediator.GetDisplayName()
    logger.debug('[ProcessFileEntry] processing file entry: {0:s}'.format(display_name))
    reference_count = mediator.resolver_context.GetFileObjectReferenceCount(file_entry.path_spec)
    try:
        if self._IsMetadataFile(file_entry):
            self._ProcessMetadataFile(mediator, file_entry)
        else:
            file_entry_processed = False
            for data_stream in file_entry.data_streams:
                if self._abort:
                    break
                if self._CanSkipDataStream(file_entry, data_stream):
                    logger.debug('[ProcessFileEntry] Skipping datastream {0:s} for {1:s}: {2:s}'.format(data_stream.name, file_entry.type_indicator, display_name))
                    continue
                self._ProcessFileEntryDataStream(mediator, file_entry, data_stream)
                file_entry_processed = True
            if (not file_entry_processed):
                self._ProcessFileEntryDataStream(mediator, file_entry, None)
    finally:
        new_reference_count = mediator.resolver_context.GetFileObjectReferenceCount(file_entry.path_spec)
        if (reference_count != new_reference_count):
            if mediator.resolver_context.ForceRemoveFileObject(file_entry.path_spec):
                logger.warning('File-object not explicitly closed for file: {0:s}'.format(display_name))
    logger.debug('[ProcessFileEntry] done processing file entry: {0:s}'.format(display_name))

Processes a file entry.

Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
file_entry (dfvfs.FileEntry): file entry.


def forward(self, spectrogram: torch.FloatTensor):
    batch_size, _, seq_length = spectrogram.shape
    hidden_states = self.input_conv(spectrogram)
    hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
    for resblock in self.resblocks:
        hidden_states = resblock(hidden_states)
    kernel_hidden_states = self.kernel_conv(hidden_states)
    bias_hidden_states = self.bias_conv(hidden_states)
    kernels = kernel_hidden_states.view(batch_size, self.conv_layers, self.conv_in_channels, self.conv_out_channels, self.conv_kernel_size, seq_length).contiguous()
    biases = bias_hidden_states.view(batch_size, self.conv_layers, self.conv_out_channels, seq_length).contiguous()
    return (kernels, biases)

Maps a conditioning log-mel spectrogram to a tensor of convolutional kernels and biases, for use in location
variable convolutional layers. Note that the input spectrogram should have shape (batch_size, input_channels,
seq_length).

Args:
spectrogram (`torch.FloatTensor` of shape `(batch_size, input_channels, seq_length)`):
Tensor containing the log-mel spectrograms.

Returns:
Tuple[`torch.FloatTensor, `torch.FloatTensor`]: tuple of tensors where the first element is the tensor of
location variable convolution kernels of shape `(batch_size, self.conv_layers, self.conv_in_channels,
self.conv_out_channels, self.conv_kernel_size, seq_length)` and the second element is the tensor of
location variable convolution biases of shape `(batch_size, self.conv_layers. self.conv_out_channels,
seq_length)`.


def find_matching_symlink(path, source):

    def to_abs(target):
        if os.path.isabs(target):
            return target
        else:
            return os.path.normpath(os.path.join(path, target))
    abs_source = to_abs(source)
    for name in os.listdir(path):
        linkpath = os.path.join(path, name)
        if os.path.islink:
            source_ = os.readlink(linkpath)
            if (to_abs(source_) == abs_source):
                return name
    return None

Find a symlink under `path` that points at `source`.

If source is relative, it is considered relative to `path`.

Returns:
str: Name of symlink found, or None.


def extract_storm_patches(label_grid, data, x_grid, y_grid, times, dx=1, dt=1, patch_radius=16):
    storm_objects = []
    if (len(label_grid.shape) == 3):
        ij_grid = np.indices(label_grid.shape[1:])
        for (t, time) in enumerate(times):
            storm_objects.append([])
            centers = list(center_of_mass(data[t], labels=label_grid[t], index=np.arange(1, (label_grid[t].max() + 1))))
            if (len(centers) > 0):
                for (o, center) in enumerate(centers):
                    int_center = np.round(center).astype(int)
                    obj_slice_buff = [slice((int_center[0] - patch_radius), (int_center[0] + patch_radius)), slice((int_center[1] - patch_radius), (int_center[1] + patch_radius))]
                    storm_objects[(- 1)].append(STObject(data[t][obj_slice_buff], np.where((label_grid[t][obj_slice_buff] == (o + 1)), 1, 0), x_grid[obj_slice_buff], y_grid[obj_slice_buff], ij_grid[0][obj_slice_buff], ij_grid[1][obj_slice_buff], time, time, dx=dx, step=dt))
                    if (t > 0):
                        dims = storm_objects[(- 1)][(- 1)].timesteps[0].shape
                        storm_objects[(- 1)][(- 1)].estimate_motion(time, data[(t - 1)], dims[1], dims[0])
    else:
        ij_grid = np.indices(label_grid.shape)
        storm_objects.append([])
        centers = list(center_of_mass(data, labels=label_grid, index=np.arange(1, (label_grid.max() + 1))))
        if (len(centers) > 0):
            for (o, center) in enumerate(centers):
                int_center = np.round(center).astype(int)
                obj_slice_buff = (slice((int_center[0] - patch_radius), (int_center[0] + patch_radius)), slice((int_center[1] - patch_radius), (int_center[1] + patch_radius)))
                storm_objects[(- 1)].append(STObject(data[obj_slice_buff], np.where((label_grid[obj_slice_buff] == (o + 1)), 1, 0), x_grid[obj_slice_buff], y_grid[obj_slice_buff], ij_grid[0][obj_slice_buff], ij_grid[1][obj_slice_buff], times[0], times[0], dx=dx, step=dt))
    return storm_objects

After storms are labeled, this method extracts boxes of equal size centered on each storm from the grid and places
them into STObjects. The STObjects contain intensity, location, and shape information about each storm
at each timestep.

Args:
label_grid: 2D or 3D array output by label_storm_objects.
data: 2D or 3D array used as input to label_storm_objects.
x_grid: 2D array of x-coordinate data, preferably on a uniform spatial grid with units of length.
y_grid: 2D array of y-coordinate data.
times: List or array of time values, preferably as integers
dx: grid spacing in same units as x_grid and y_grid.
dt: period elapsed between times
patch_radius: Number of grid points from center of mass to extract

Returns:
storm_objects: list of lists containing STObjects identified at each time.


def GetPresetsByOperatingSystem(self, operating_system):

    preset_definitions = []
    for preset_definition in self._definitions.values():
      for preset_operating_system in preset_definition.operating_systems:
        if preset_operating_system.IsEquivalent(operating_system):
          preset_definitions.append(preset_definition)

    return preset_definitions

Retrieves preset definitions for a specific operating system.

Args:
operating_system (OperatingSystemArtifact): an operating system artifact
attribute container.

Returns:
list[PresetDefinition]: preset definition that correspond with the
operating system.


def _create_hunt(self, name, args):

    runner_args = self.grr_api.types.CreateHuntRunnerArgs()
    runner_args.description = self.reason
    hunt = self.grr_api.CreateHunt(
        flow_name=name, flow_args=args, hunt_runner_args=runner_args)
    print('{0!s}: Hunt created'.format(hunt.hunt_id))
    self._check_approval_wrapper(hunt, hunt.Start)
    return hunt

Create specified hunt.

Args:
name: string containing hunt name.
args: proto (*FlowArgs) for type of hunt, as defined in GRR flow proto.

Returns:
The newly created GRR hunt object.

Raises:
ValueError: if approval is needed and approvers were not specified.


def _merge_nrows(nrows, static_nrows, value, dtype, validate):
    static_value_nrows = tensor_shape.dimension_at_index(value.shape, 0)
    if isinstance(value, tensor.Tensor):
        value_nrows = array_ops.shape(value, out_type=dtype)[0]
    else:
        value_nrows = value.nrows()
    if nrows is None:
        nrows = value_nrows
    elif static_value_nrows.value is not None and static_nrows.value is not None:
        if not static_value_nrows.is_compatible_with(static_nrows):
            raise ValueError('fields have incompatible nrows')
        nrows = value_nrows
    elif validate:
        nrows = control_flow_ops.with_dependencies([check_ops.assert_equal(nrows, value_nrows, message='fields have incompatible nrows')], nrows)
    return (nrows, static_nrows._merge_with(static_value_nrows))

Merges `nrows` with `nrows(value)`.

Checks that `value` has the expected number of rows (`nrows`), and returns
`nrows`.  If `validate` is true, then add validation ops that check that
the `nrows` values match.

Args:
nrows: scalar integer Tensor.
static_nrows: tf.Dimension: static value of nrows, if known.
value: Tensor or RaggedTensor or StructuredTensor
dtype: dtype for `nrows`.
validate: bool -- whether to add validation ops.

Returns:
A tuple `(nrows, static_nrows)`.


def _add_logger_by_name(self, name):
    data = dict(request.forms)
    loc = data.pop('loc', '')
    port = data.pop('port', None)
    conn_type = data.pop('conn_type', None)
    if ((not port) or (not conn_type)):
        e = 'Port and/or conn_type not set'
        raise ValueError(e)
    address = [loc, int(port)]
    if ('rotate_log' in data):
        data['rotate_log'] = (True if (data == 'true') else False)
    if ('rotate_log_delta' in data):
        data['rotate_log_delta'] = int(data['rotate_log_delta'])
    self._logger_manager.add_logger(name, address, conn_type, **data)

Handles POST requests for adding a new logger.

Expects logger configuration to be passed in the request's query string.
The logger name is included in the URL and the address components and
connection type should be included as well. The loc attribute is
defaulted to "localhost" when making the socket connection if not
defined.

loc = IP / interface
port = port / protocol
conn_type = udp or ethernet

Raises:
ValueError:
if the port or connection type are not supplied.


def removeMapIdentity(self, subject, vendorSpecific=None):

        response = self.removeMapIdentityResponse(subject, vendorSpecific)
        return self._read_boolean_response(response)

See Also: removeMapIdentityResponse()

Args:
subject:
vendorSpecific:

Returns:


def fill_list(self, list, input_list):

        for name in input_list:

            item = QtGui.QStandardItem(name)
            item.setSelectable(True)
            item.setEditable(False)

            list.model().appendRow(item)

fills a tree with nested parameters
Args:
tree: QtGui.QTreeView to fill
parameters: dictionary or Parameter object which contains the information to use to fill


class Phi4MultimodalVisionEncoder(nn.Module):

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

    @can_return_tuple
    def forward(self, inputs_embeds, attention_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None) -> 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
        encoder_states = () if output_hidden_states else None
        all_attentions = () if output_attentions else None
        hidden_states = inputs_embeds
        for encoder_layer in self.layers:
            if output_hidden_states:
                encoder_states = encoder_states + (hidden_states,)
            layer_outputs = encoder_layer(hidden_states, 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,)
        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
[`Phi4MultimodalVisionEncoderLayer`].

Args:
config: Phi4MultimodalVisionConfig


def need(self, folder, page=None, perpage=None):

        assert isinstance(page, int) or page is None
        assert isinstance(perpage, int) or perpage is None
        return self.get('need', params={'folder': folder,
                                 'page': page,
                                 'perpage': perpage})

Returns lists of files which are needed by this device in order
for it to become in sync.

Args:
folder (str):
page (int): If defined applies pagination accross the
collection of results.
perpage (int): If defined applies pagination across the
collection of results.

Returns:
dict


def l1_regularizer(weight=1.0, scope=None):

    def regularizer(tensor):
        with tf.name_scope(scope, 'L1Regularizer', [tensor]):
            l1_weight = tf.convert_to_tensor(weight, dtype=tensor.dtype.base_dtype, name='weight')
            return tf.multiply(l1_weight, tf.reduce_sum(tf.abs(tensor)), name='value')
    return regularizer

Define a L1 regularizer.

Args:
weight: scale the loss by this factor.
scope: Optional scope for name_scope.

Returns:
a regularizer function.


def size(self, path):
    try:
        return s3io.S3IO(options=self._options).size(path)
    except Exception as e:
        raise BeamIOError('size() operation failed', {path: e})

Get size of path on the FileSystem.

Args:
path: string path in question.

Returns: int size of path according to the FileSystem.

Raises:
``BeamIOError``: if path doesn't exist.


def issued_at(self):
    issued_at = self._issued_at
    if (issued_at is None):
        self._issued_at = int(time.time())
    return self._issued_at

Time when access token was requested, as seconds since epoch.

Note:
Accessing this property when there wasn't any request attempts
will return current time.

Returns:
int


def __init__(self, editor):

        self.editor = editor
        self.timer = QTimer(self.editor)
        self.timer.setSingleShot(True)
        self.timer.timeout.connect(self.do_autosave)
        self._enabled = False
        self._interval = self.DEFAULT_AUTOSAVE_INTERVAL

Constructor.

Autosave is disabled after construction and needs to be enabled
explicitly if required.

Args:
editor (Editor): editor plugin.


def set_learning_phase(value):
    warnings.warn('`tf.keras.backend.set_learning_phase` is deprecated and will be removed after 2020-10-11. To update it, simply pass a True/False value to the `training` argument of the `__call__` method of your layer or model.')
    deprecated_internal_set_learning_phase(value)

Sets the learning phase to a fixed value.

The backend learning phase affects any code that calls
`backend.learning_phase()`
In particular, all Keras built-in layers use the learning phase as the default
for the `training` arg to `Layer.__call__`.

User-written layers and models can achieve the same behavior with code that
looks like:

```python
def call(self, inputs, training=None):
if training is None:
training = backend.learning_phase()
```

Args:
value: Learning phase value, either 0 or 1 (integers).
0 = test, 1 = train

Raises:
ValueError: if `value` is neither `0` nor `1`.


def get_all_counters(obj, instance_list=None):
    (counters, instances_avail) = win32pdh.EnumObjectItems(None, None, obj, (- 1), 0)
    if (instance_list is None):
        instance_list = instances_avail
    if (not isinstance(instance_list, list)):
        instance_list = [instance_list]
    counter_list = []
    for counter in counters:
        for instance in instance_list:
            instance = ('*' if (instance.lower() == '_total') else instance)
            counter_list.append((obj, instance, counter))
        else:
            counter_list.append((obj, None, counter))
    return (get_counters(counter_list) if counter_list else {})

Get the values for all counters available to a Counter object

Args:

obj (str):
The name of the counter object. You can get a list of valid names
using the ``list_objects`` function

instance_list (list):
A list of instances to return. Use this to narrow down the counters
that are returned.

.. note::
``_Total`` is returned as ``*``


def from_yaml(cls, yaml_path, filename=None):

        if filename:

            yaml_path = os.path.join(os.path.dirname(yaml_path), filename)
        assert yaml_path.endswith(".yaml"), \
            "Expected a/path/to/<yamlname>.yaml, got %r" % yaml_path
        yamlname = os.path.basename(yaml_path)[:-5]
        log.debug("Parsing %s", yaml_path)
        with open(yaml_path) as f:
            text = f.read()

        ds = yaml.load(text, Loader=yaml.RoundTripLoader)
        docstring = None
        sections = []
        for d in ds:
            assert len(d) == 1, \
                "Expected section length 1, got %d" % len(d)
            lineno = d._yaml_line_col.line + 1
            name = list(d)[0]
            sections.append(cls(
                yaml_path, lineno, name, d[name]))
            if name == "builtin.defines.docstring":
                docstring = d[name]["value"]

        return sections, yamlname, docstring

Split a dictionary into parameters controllers parts blocks defines

Args:
yaml_path (str): File path to YAML file, or a file in the same dir
filename (str): If give, use this filename as the last element in
the yaml_path (so yaml_path can be __file__)

Returns:
tuple: (sections, yamlname, docstring) where sections is a
list of created sections


def chebyshev(coefs, time, domain):
    return (Chebyshev(coefs, domain=domain)(time) - (0.5 * coefs[0]))

Evaluate a Chebyshev Polynomial

Args:
coefs (list, np.array): Coefficients defining the polynomial
time (int, float): Time where to evaluate the polynomial
domain (list, tuple): Domain (or time interval) for which the polynomial is defined: [left, right]

Reference: Appendix A in the MSG Level 1.5 Image Data Format Description.


def get_num_bytes(self, batch: Sequence[torch.Tensor]) -> int:
    return sum((el.element_size() for tensor in batch for el in tensor.values()))

Returns:
The number of bytes of data for a batch of dict of Tensors.


def convert_coco_poly_to_mask(segmentations, height: int, width: int, device: torch.device) -> torch.Tensor:
    try:
        from pycocotools import mask as coco_mask
    except ImportError:
        raise ImportError('Pycocotools is not installed in your environment.')
    masks = []
    for polygons in segmentations:
        rles = coco_mask.frPyObjects(polygons, height, width)
        mask = coco_mask.decode(rles)
        if len(mask.shape) < 3:
            mask = mask[..., None]
        mask = torch.as_tensor(mask, dtype=torch.uint8, device=device)
        mask = torch.any(mask, axis=2)
        masks.append(mask)
    if masks:
        masks = torch.stack(masks, axis=0)
    else:
        masks = torch.zeros((0, height, width), dtype=torch.uint8, device=device)
    return masks

Convert a COCO polygon annotation to a mask.

Args:
segmentations (`List[List[float]]`):
List of polygons, each polygon represented by a list of x-y coordinates.
height (`int`):
Height of the mask.
width (`int`):
Width of the mask.


def __init__(self, path_map: Mapping[str, os.PathLike[str]], expected_input_key_map: Optional[Mapping[str, Collection[str]]]=None):
    self.path_map: Mapping[str, os.PathLike[str]] = path_map
    self.expected_input_key_map: Mapping[str, Collection[str]] = {}
    if expected_input_key_map is not None:
        if set(path_map.keys()) != set(expected_input_key_map.keys()):
            raise KeyError('The `path_map` and `expected_input_key_map` should have the same set of keys.')
        self.expected_input_key_map = expected_input_key_map

Initializes TFRecord represenatative dataset saver.

Args:
path_map: Signature def key -> path mapping. Each path is a TFRecord file
to which a `RepresentativeDataset` is saved. The signature def keys
should be a subset of the `SignatureDef` keys of the
`representative_dataset` argument of the `save()` call.
expected_input_key_map: Signature def key -> expected input keys. If set,
validate that the sample has same set of input keys before saving.

Raises:
KeyError: If path_map and expected_input_key_map have different keys.


def collections(self):
    iterator = self._firestore_api.list_collection_ids(self._database_string, metadata=self._rpc_metadata)
    iterator.client = self
    iterator.item_to_value = _item_to_collection_ref
    return iterator

List top-level collections of the client's database.

Returns:
Sequence[~.firestore_v1beta1.collection.CollectionReference]:
iterator of subcollections of the current document.


def add_sample_file(self, sample_path, source, reference, method='', file_format='raw', file_password='', sample_name='', campaign='', confidence='', description='', bucket_list=[]):
    if os.path.isfile(sample_path):
        data = {'api_key': self.api_key, 'username': self.username, 'source': source, 'reference': reference, 'method': method, 'filetype': file_format, 'upload_type': 'file', 'campaign': campaign, 'confidence': confidence, 'description': description, 'bucket_list': ','.join(bucket_list)}
        if (sample_name != ''):
            data['filename'] = sample_name
        with open(sample_path, 'rb') as fdata:
            if file_password:
                data['password'] = file_password
            r = requests.post('{0}/samples/'.format(self.url), data=data, files={'filedata': fdata}, verify=self.verify, proxies=self.proxies)
            if (r.status_code == 200):
                result_data = json.loads(r.text)
                return result_data
            else:
                log.error('Error with status code {0} and message {1}'.format(r.status_code, r.text))
        return None

Adds a file sample. For meta data only use add_sample_meta.

Args:
sample_path: The path on disk of the sample to upload
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
file_format: Must be raw, zip, or rar.
file_password: The password of a zip or rar archived sample
sample_name: Specify a filename for the sample rather than using
the name on disk
campaign: An associated campaign
confidence: The campaign confidence
description: A text description of the sample
bucket_list: A list of bucket list items to add
Returns:
A JSON sample object or None if there was an error.


def find_eq_stress(strains, stresses, tol=1e-10):
    stress_array = np.array(stresses)
    strain_array = np.array(strains)
    eq_stress = stress_array[np.all((abs(strain_array) < tol), axis=(1, 2))]
    if (eq_stress.size != 0):
        all_same = (abs((eq_stress - eq_stress[0])) < 1e-08).all()
        if ((len(eq_stress) > 1) and (not all_same)):
            raise ValueError('Multiple stresses found for equilibrium strain state, please specify equilibrium stress or   remove extraneous stresses.')
        eq_stress = eq_stress[0]
    else:
        warnings.warn('No eq state found, returning zero voigt stress')
        eq_stress = Stress(np.zeros((3, 3)))
    return eq_stress

Finds stress corresponding to zero strain state in stress-strain list

Args:
strains (Nx3x3 array-like): array corresponding to strains
stresses (Nx3x3 array-like): array corresponding to stresses
tol (float): tolerance to find zero strain state


def parse_env(config_schema, env):
    try:
        return {key: item_schema.parse(key, env.get(key)) for (key, item_schema) in config_schema.items()}
    except KeyError as error:
        raise MissingConfigError('Required config not set: {}'.format(error.args[0]))

Parse the values from a given environment against a given config schema

Args:
config_schema: A dict which maps the variable name to a Schema object
that describes the requested value.
env: A dict which represents the value of each variable in the
environment.


def PluginAssets(self, plugin_name):

    with self._accumulators_mutex:

      items = list(six.iteritems(self._accumulators))

    return {run: accum.PluginAssets(plugin_name) for run, accum in items}

Get index of runs and assets for a given plugin.

Args:
plugin_name: Name of the plugin we are checking for.

Returns:
A dictionary that maps from run_name to a list of plugin
assets for that run.


def verify_signature(amazon_cert: crypto.X509, signature: str, request_body: bytes) -> bool:

    signature = base64.b64decode(signature)

    try:
        crypto.verify(amazon_cert, signature, request_body, 'sha1')
        result = True
    except crypto.Error:
        result = False

    return result

Verifies Alexa request signature.

Args:
amazon_cert: Pycrypto X509 Amazon certificate.
signature: Base64 decoded Alexa request signature from Signature HTTP header.
request_body: full HTTPS request body
Returns:
result: True if verification was successful, False if not.


def trace_region_count(self):

        cmd = enums.JLinkTraceCommand.GET_NUM_REGIONS
        data = ctypes.c_uint32(0)
        res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data))
        if (res == 1):
            raise errors.JLinkException('Failed to get trace region count.')
        return data.value

Retrieves a count of the number of available trace regions.

Args:
self (JLink): the ``JLink`` instance.

Returns:
Count of the number of available trace regions.


def ProcessPathSpec(self, mediator, path_spec):

    self.last_activity_timestamp = time.time()
    self.processing_status = definitions.STATUS_INDICATOR_RUNNING

    file_entry = path_spec_resolver.Resolver.OpenFileEntry(
        path_spec, resolver_context=mediator.resolver_context)

    if file_entry is None:
      display_name = mediator.GetDisplayNameForPathSpec(path_spec)
      logger.warning(
          'Unable to open file entry with path spec: {0:s}'.format(
              display_name))
      self.processing_status = definitions.STATUS_INDICATOR_IDLE
      return

    mediator.SetFileEntry(file_entry)

    try:
      if file_entry.IsDirectory():
        self._ProcessDirectory(mediator, file_entry)
      self._ProcessFileEntry(mediator, file_entry)

    finally:
      mediator.ResetFileEntry()

      self.last_activity_timestamp = time.time()
      self.processing_status = definitions.STATUS_INDICATOR_IDLE

Processes a path specification.

Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
path_spec (dfvfs.PathSpec): path specification.


def Serialize(self, writer):

        super(Block, self).Serialize(writer)
        writer.WriteSerializableArray(self.Transactions)

Serialize full object.

Args:
writer (neo.IO.BinaryWriter):


def __init__(self, initialization_list=None):

    if initialization_list:

      self._trackers = {}
      for value_category_key, description_list in initialization_list.items():
        description = EventTrackerDescription._make(description_list)
        self._trackers[value_category_key] = _EventTracker(
            event_count=description.event_count,
            first_timestamp=description.first_timestamp,
            last_timestamp=description.last_timestamp)
    else:

      self._trackers = {
          constants.NAN_KEY: _EventTracker(),
          constants.NEG_INF_KEY: _EventTracker(),
          constants.POS_INF_KEY: _EventTracker(),
      }

Stores alert history for a single device, tensor pair.

Args:
initialization_list: (`list`) An optional list parsed from JSON read
from disk. That entity is used to initialize this NumericsAlertHistory.
Use the create_jsonable_object method of this class to create such an
object.


def is_remote_path(filepath):
    if re.match('^(/cns|/cfs|/gcs|/hdfs|/readahead|/placer|/tfhub|.*:
        return True
    return False

Determines if a given filepath indicates a remote location.

This function checks if the filepath represents a known remote pattern
such as GCS (`/gcs`), CNS (`/cns`), CFS (`/cfs`), HDFS (`/hdfs`), Placer
(`/placer`), TFHub (`/tfhub`), or a URL (`.*://`).

Args:
filepath (str): The path to be checked.

Returns:
bool: True if the filepath is a recognized remote path, otherwise False


def _set_median_session_metrics(session_group, aggregation_metric):
    measurements = sorted(_measurements(session_group, aggregation_metric), key=operator.attrgetter('metric_value.value'))
    median_session = measurements[((len(measurements) - 1)
    del session_group.metric_values[:]
    session_group.metric_values.MergeFrom(session_group.sessions[median_session].metric_values)

Sets the metrics for session_group to those of its "median session".

The median session is the session in session_group with the median value
of the metric given by 'aggregation_metric'. The median is taken over the
subset of sessions in the group whose 'aggregation_metric' was measured
at the largest training step among the sessions in the group.

Args:
session_group: A SessionGroup protobuffer.
aggregation_metric: A MetricName protobuffer.


def start_scan(self, active):

        try:
            self.bable.start_scan(self._on_device_found, active_scan=active, sync=True)
        except bable_interface.BaBLEException as err:

            if self._active_scan != active:
                raise err

        self._active_scan = active
        self.scanning = True

Start a scan. Will call self._on_device_found for each device scanned.
Args:
active (bool): Indicate if it is an active scan (probing for scan response) or not.


def register_type_spec_from_value_converter(type_object, converter_fn, allow_subclass=False):
    _, type_object = tf_decorator.unwrap(type_object)
    _TYPE_CONVERSION_FUNCTION_REGISTRY.append((type_object, converter_fn, allow_subclass))

Registers a function for converting values with a given type to TypeSpecs.

If multiple registered `type_object`s match a value, then the most recent
registration takes precedence.  Custom converters should not be defined for
`CompositeTensor`s; use `CompositeTensor._type_spec` instead.

Args:
type_object: A Python `type` object representing the type of values accepted
by `converter_fn`.
converter_fn: A function that takes one argument (an instance of the type
represented by `type_object`) and returns a `TypeSpec`.
allow_subclass: If true, then use `isinstance(value, type_object)` to check
for matches.  If false, then use `type(value) is type_object`.


def decode(self, probs, sizes=None):

        _, max_probs = torch.max(probs.transpose(0, 1), 2)
        strings = self.convert_to_strings(max_probs.view(max_probs.size(0), max_probs.size(1)), sizes)
        return self.process_strings(strings, remove_repetitions=True)

Returns the argmax decoding given the probability matrix. Removes
repeated elements in the sequence, as well as blanks.

Arguments:
probs: Tensor of character probabilities from the network. Expected shape of seq_length x batch x output_dim
sizes(optional): Size of each sequence in the mini-batch
Returns:
strings: sequences of the model's best guess for the transcription on inputs


def get_instance_status(self):
    status_url = self._get_url('status_path')
    res = self.rest_client.session.get(status_url)
    _handle_http_errors(res)
    return res.json()

Get the status the instance for this Streaming Analytics service.

Returns:
dict: JSON response for the instance status operation.


def hpo_diseases(username, password, hpo_ids, p_value_treshold=1):

    try:
        results = query_phenomizer.query(username, password, *hpo_ids)
        diseases = [result for result in results
                    if result['p_value'] <= p_value_treshold]
        return diseases
    except SystemExit:
        return None

Return the list of HGNC symbols that match annotated HPO terms.

Args:
username (str): username to use for phenomizer connection
password (str): password to use for phenomizer connection

Returns:
query_result: a generator of dictionaries on the form
{
'p_value': float,
'disease_source': str,
'disease_nr': int,
'gene_symbols': list(str),
'description': str,
'raw_line': str
}


def _build(self, x, prev_state):
    x.get_shape().with_rank(2)
    self._batch_size = x.get_shape().as_list()[0]
    self._dtype = x.dtype
    x_zeros = tf.concat([x, tf.zeros(shape=(self._batch_size, 1), dtype=self._dtype)], 1)
    x_ones = tf.concat([x, tf.ones(shape=(self._batch_size, 1), dtype=self._dtype)], 1)
    halting_linear = basic.Linear(name='halting_linear', output_size=1)
    body = functools.partial(self._body, halting_linear=halting_linear, x_ones=x_ones)
    cumul_halting_init = tf.zeros(shape=(self._batch_size, 1), dtype=self._dtype)
    iteration_init = tf.zeros(shape=(self._batch_size, 1), dtype=self._dtype)
    core_output_size = [x.value for x in self._core.output_size]
    out_init = tf.zeros(shape=((self._batch_size,) + tuple(core_output_size)), dtype=self._dtype)
    cumul_state_init = _nested_zeros_like(prev_state)
    remainder_init = tf.zeros(shape=(self._batch_size, 1), dtype=self._dtype)
    (unused_final_x, final_out, unused_final_state, final_cumul_state, unused_final_halting, final_iteration, final_remainder) = tf.while_loop(self._cond, body, [x_zeros, out_init, prev_state, cumul_state_init, cumul_halting_init, iteration_init, remainder_init])
    act_output = basic.Linear(name='act_output_linear', output_size=self._output_size)(final_out)
    return ((act_output, (final_iteration, final_remainder)), final_cumul_state)

Connects the core to the graph.

Args:
x: Input `Tensor` of shape `(batch_size, input_size)`.
prev_state: Previous state. This could be a `Tensor`, or a tuple of
`Tensor`s.

Returns:
The tuple `(output, state)` for this core.

Raises:
ValueError: if the `Tensor` `x` does not have rank 2.


def flowshow(flow, win_name='', wait_time=0):
    flow = flowread(flow)
    flow_img = flow2rgb(flow)
    imshow(rgb2bgr(flow_img), win_name, wait_time)

Show optical flow.

Args:
flow (ndarray or str): The optical flow to be displayed.
win_name (str): The window name.
wait_time (int): Value of waitKey param.


def recall_at_k(y_true: List[int], y_pred: List[List[np.ndarray]], k: int):
    num_examples = float(len(y_pred))
    predictions = np.array(y_pred)
    predictions = np.flip(np.argsort(predictions, (- 1)), (- 1))[(:, :k)]
    num_correct = 0
    for el in predictions:
        if (0 in el):
            num_correct += 1
    return (float(num_correct) / num_examples)

Calculates recall at k ranking metric.

Args:
y_true: Labels. Not used in the calculation of the metric.
y_predicted: Predictions.
Each prediction contains ranking score of all ranking candidates for the particular data sample.
It is supposed that the ranking score for the true candidate goes first in the prediction.

Returns:
Recall at k


def today(boo):
    tod = datetime.strptime(datetime.today().date().isoformat().replace('-', ' '), '%Y %m %d')
    if boo:
        return int(str(tod).replace('-', '')[:8])
    else:
        return str(tod)[:10]

Return today's date as either a String or a Number, as specified by the User.

Args:
boo: if true, function returns Number (20151230); if false, returns String ("2015-12-30")
Returns:
either a Number or a string, dependent upon the user's input


def builder(structdef_url: str, fhir_context: context.FhirPathContext) -> expressions.Builder:
    structdef = fhir_context.get_structure_definition(structdef_url)
    struct_type = _fhir_path_data_types.StructureDataType.from_proto(structdef)
    return expressions.Builder(_evaluation.RootMessageNode(fhir_context, struct_type), _PRIMITIVE_HANDLER)

Returns a FHIRPath expression builder.

This gives the caller tab suggestions and early error detection when
building FHIRPath expressions. See the documentation on the returned
expressions.Builder for more details.

Args:
structdef_url: the URL of the FHIR StructureDefinition to use.
fhir_context: a DefinitionLoader used to load FHIR structure definitions and
dependencies.
Returns: a builder object to creae FHIRPath expressions.


def python_executable(check=True, short=False):
    r
    if not check:
        python_exe = 'python'
    else:
        from os.path import isdir
        python_exe_long = unixpath(sys.executable)
        python_exe = python_exe_long
        if short:
            python_exe_short = basename(python_exe_long)
            found = search_env_paths(python_exe_short, key_list=['PATH'],
                                     verbose=False)
            found = [f for f in found if not isdir(f)]
            if len(found) > 0:
                if found[0] == python_exe_long:

                    python_exe = python_exe_short
    return python_exe

r"""
Args:
short (bool): (default = False)

Returns:
str:

Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_cplat import *  # NOQA
>>> short = False
>>> result = python_executable(short)
>>> print(result)


def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
    local_stream = utils.BytearrayStream()
    if self._unique_identifier:
        self._unique_identifier.write(local_stream, kmip_version=kmip_version)
    if self._usage_limits_count:
        self._usage_limits_count.write(local_stream, kmip_version=kmip_version)
    if self._cryptographic_usage_mask:
        self._cryptographic_usage_mask.write(local_stream, kmip_version=kmip_version)
    if self._lease_time:
        self._lease_time.write(local_stream, kmip_version=kmip_version)
    self.length = local_stream.length()
    super(CheckResponsePayload, self).write(output_stream, kmip_version=kmip_version)
    output_stream.write(local_stream.buffer)

Write the data encoding the Check response payload to a stream.

Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0.

Raises:
ValueError: Raised if the data attribute is not defined.


def set_role(self, name, value=None, default=False, disable=False):

        cmd = self.command_builder('username %s role' % name, value=value,
                                   default=default, disable=disable)
        return self.configure(cmd)

Configures the user role vale in EOS

Args:
name (str): The name of the user to create

value (str): The value to configure for the user role

default (bool): Configure the user role using the EOS CLI
default command

disable (bool): Negate the user role using the EOS CLI no command

Returns:
True if the operation was successful otherwise False


def set_forced_variation(self, experiment_key, user_id, variation_key):
    if (not self.is_valid):
        self.logger.error(enums.Errors.INVALID_DATAFILE.format('set_forced_variation'))
        return False
    if (not validator.is_non_empty_string(experiment_key)):
        self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('experiment_key'))
        return False
    if (not isinstance(user_id, string_types)):
        self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('user_id'))
        return False
    return self.config.set_forced_variation(experiment_key, user_id, variation_key)

Force a user into a variation for a given experiment.

Args:
experiment_key: A string key identifying the experiment.
user_id: The user ID.
variation_key: A string variation key that specifies the variation which the user.
will be forced into. If null, then clear the existing experiment-to-variation mapping.

Returns:
A boolean value that indicates if the set completed successfully.


def get_inter_op_parallelism_threads():
    return context.context().inter_op_parallelism_threads

Get number of threads used for parallelism between independent operations.

Determines the number of threads used by independent non-blocking operations.
0 means the system picks an appropriate number.

Returns:
Number of parallel threads


def read_data_event(self, whence, complete=False, can_flush=False):

        return Transition(None, _read_data_handler(whence, self, complete, can_flush))

Creates a transition to a co-routine for retrieving data as bytes.

Args:
whence (Coroutine): The co-routine to return to after the data is satisfied.
complete (Optional[bool]): True if STREAM_END should be emitted if no bytes are read or
available; False if INCOMPLETE should be emitted in that case.
can_flush (Optional[bool]): True if NEXT may be requested after INCOMPLETE is emitted as a result of this
data request.


def _GetIdentifierFromPath(self, parser_mediator):

    file_entry = parser_mediator.GetFileEntry()
    path = file_entry.path_spec.location
    file_system = file_entry.GetFileSystem()
    path_segments = file_system.SplitPath(path)
    return path_segments[-2]

Extracts a container or a graph ID from a JSON file's path.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.

Returns:
str: container or graph identifier.


def if_sqlserver_disable_constraints_triggers(session: SqlASession, tablename: str) -> None:
    with if_sqlserver_disable_constraints(session, tablename):
        with if_sqlserver_disable_triggers(session, tablename):
            (yield)

If we're running under SQL Server, disable triggers AND constraints for the
specified table while the resource is held.

Args:
session: SQLAlchemy :class:`Session`
tablename: table name


def json(self, include_id=False, date_fmt=None, object_id_fmt=str):
    (has_slots, d) = _get_dict(self)
    _id = self._id
    if (not include_id):
        self._id = None
    object_ids = {k: v for (k, v) in d.items() if isinstance(v, bson.ObjectId)}
    for (k, v) in object_ids.items():
        if (object_id_fmt is None):
            setattr(self, k, None)
        else:
            setattr(self, k, object_id_fmt(v))
    datetimes = {k: v for (k, v) in d.items() if isinstance(v, datetime.datetime)}
    for (k, v) in datetimes.items():
        if (date_fmt is None):
            ts = (time.mktime(v.timetuple()) + (v.microsecond / 1000000.0))
            setattr(self, k, ts)
        else:
            setattr(self, k, v.strftime(date_fmt))
    j = marshal_dict(self, JSON_TYPES, 'json', include_id=include_id, date_fmt=date_fmt, object_id_fmt=object_id_fmt)
    self._id = _id
    for (k, v) in object_ids.items():
        setattr(self, k, v)
    for (k, v) in datetimes.items():
        setattr(self, k, v)
    return j

Helper method to convert to MongoDB documents to JSON

This includes helpers to convert non-JSON compatible types
to valid JSON types.  HOWEVER, it cannot recurse into nested
classes.

Args:
include_id:    bool, True to cast _id to a str,
False to omit from the result
date_fmt:      str-or-None:  None to cast to UNIX timestamp,
str (strftime format) to convert to string,
for example: '%Y-%m-%d_%H:%M:%S'
object_id_fmt: type, Cast the bson.ObjectId's to this format,
or None to exclude.  This only applies to
ObjectId variables other than _id.
Returns:
dict


def get_minimum_indentation(text):
    lines = text.split('\n')
    indentations = [get_indentation(line_) for line_ in lines if (len(line_.strip()) > 0)]
    if (len(indentations) == 0):
        return 0
    return min(indentations)

r"""
returns the number of preceding spaces

Args:
text (str): unicode text

Returns:
int: indentation

CommandLine:
python -m utool.util_str --exec-get_minimum_indentation --show

Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import *  # NOQA
>>> import utool as ut
>>> text = '    foo\n   bar'
>>> result = get_minimum_indentation(text)
>>> print(result)
3


def parse(self, text, layers=None):

        params = {
            "text": text,
            "key": self.key,
        }

        if layers is not None:

            if isinstance(layers, six.string_types):
                params["layers"] = layers

            elif isinstance(layers, collections.Iterable):
                params["layers"] = ",".join(layers)

        req = requests.get(self.NLU_URL, params=params)
        return req.json()

Parsing passed text to json.

Args:
text: Text to parse.
layers (optional): Special fields. Only one string
or iterable object (e.g "Data", ("Data", "Fio")).
Only these fields will be returned.

Returns:
The parsed text into a json object.


def update_panel(self, panel_obj, version=None, date_obj=None):

        LOG.info("Updating panel %s", panel_obj['panel_name'])

        date = panel_obj['date']
        if version:
            LOG.info("Updating version from {0} to version {1}".format(
                panel_obj['version'], version))
            panel_obj['version'] = version

            if date_obj:
                date = date_obj
        else:
            date = date_obj or dt.datetime.now()
        panel_obj['date'] = date

        updated_panel = self.panel_collection.find_one_and_replace(
            {'_id': panel_obj['_id']},
            panel_obj,
            return_document=pymongo.ReturnDocument.AFTER
        )

        return updated_panel

Replace a existing gene panel with a new one

Keeps the object id

Args:
panel_obj(dict)
version(float)
date_obj(datetime.datetime)

Returns:
updated_panel(dict)