class Multimodal2VisionEncoder(nn.Module):

    def __init__(self, config):
        super().__init__()
        self.config = config
        self.layers = nn.ModuleList([Multimodal2VisionEncoderLayer(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, causal_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 idx, encoder_layer in enumerate(self.layers):
            if output_hidden_states:
                encoder_states = encoder_states + (hidden_states,)
            if self.gradient_checkpointing and self.training:
                layer_outputs = self._gradient_checkpointing_func(encoder_layer.__call__, hidden_states, attention_mask, causal_attention_mask, output_attentions)
            else:
                layer_outputs = encoder_layer(hidden_states, attention_mask, causal_attention_mask, output_attentions=output_attentions)
            hidden_states = layer_outputs[0]
            if output_attentions:
                all_attentions = all_attentions + (layer_outputs[1],)
        if output_hidden_states:
            encoder_states = encoder_states + (hidden_states,)
        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
[`Multimodal2VisionEncoderLayer`].

Args:
config: Multimodal2VisionConfig


def claim(self, file_readers):

        unclaimed_readers = []
        vcf_readers = []
        for file_reader in file_readers:
            if self._is_mutect_vcf(file_reader):
                vcf_reader = vcf.VcfReader(file_reader)
                vcf_readers.append(_MutectVcfReader(vcf_reader))
            else:
                unclaimed_readers.append(file_reader)
        return (unclaimed_readers, vcf_readers)

Recognizes and claims MuTect VCFs form the set of all input VCFs.

Each defined caller has a chance to evaluate and claim all the incoming
files as something that it can process.

Args:
file_readers: the collection of currently unclaimed files

Returns:
A tuple of unclaimed readers and MuTectVcfReaders.


def add_graph(self, y, x_label=None, y_label='', title='', x_run=None, y_run=None, svg_size_px=None, key_position='bottom right'):
    if (x_run is None):
        x_run = self.default_x_run
    if (y_run is None):
        y_run = self.default_y_run
    if (svg_size_px is None):
        svg_size_px = self.default_svg_size_px
    for panel in self.panels:
        x_run = self._load_x_run(x_run)
        y_run = self._load_y_run(y_run)
        svg_size_px = self._load_svg_size_px(svg_size_px)
        panel.add_graph(y=y, x_run=x_run, y_run=y_run, svg_size_px=svg_size_px, y_label=y_label, x_label=(x_label if (x_label is not None) else self.default_x_label), title=title, key_position=key_position)

Add a new graph to the overlap report.

Args:
y (str): Value plotted on y-axis.
x_label (str): Label on x-axis.
y_label (str): Label on y-axis.
title (str): Title of the plot.
x_run ((float,float)): x-range.
y_run ((int,int)): y-rang.
svg_size_px ((int,int): Size of SVG image in pixels.
key_position (str): GnuPlot position of the legend.


def get_nltk_builder(languages):
    all_stemmers = []
    all_stopwords_filters = []
    all_word_characters = set()
    for language in languages:
        if (language == 'en'):
            all_stemmers.append(lunr.stemmer.stemmer)
            all_stopwords_filters.append(stop_word_filter)
            all_word_characters.update({'\\w'})
        else:
            (stopwords, word_characters) = _get_stopwords_and_word_characters(language)
            all_stemmers.append(Pipeline.registered_functions['stemmer-{}'.format(language)])
            all_stopwords_filters.append(generate_stop_word_filter(stopwords, language=language))
            all_word_characters.update(word_characters)
    builder = Builder()
    multi_trimmer = generate_trimmer(''.join(sorted(all_word_characters)))
    Pipeline.register_function(multi_trimmer, 'lunr-multi-trimmer-{}'.format('-'.join(languages)))
    builder.pipeline.reset()
    for fn in chain([multi_trimmer], all_stopwords_filters, all_stemmers):
        builder.pipeline.add(fn)
    for fn in all_stemmers:
        builder.search_pipeline.add(fn)
    return builder

Returns a builder with stemmers for all languages added to it.

Args:
languages (list): A list of supported languages.


def get_structures(self, chemsys_formula_id, final=True):

        prop = "final_structure" if final else "initial_structure"
        data = self.get_data(chemsys_formula_id, prop=prop)
        return [d[prop] for d in data]

Get a list of Structures corresponding to a chemical system, formula,
or materials_id.

Args:
chemsys_formula_id (str): A chemical system (e.g., Li-Fe-O),
or formula (e.g., Fe2O3) or materials_id (e.g., mp-1234).
final (bool): Whether to get the final structure, or the initial
(pre-relaxation) structure. Defaults to True.

Returns:
List of Structure objects.


class JetMoeMoE(nn.Module):

    def __init__(self, config: JetMoeConfig):
        super(JetMoeMoE, self).__init__()
        self.input_size = config.hidden_size
        self.hidden_size = config.intermediate_size
        self.activation = ACT2FN[config.activation_function]
        self.bias = torch.nn.Parameter(torch.empty(self.input_size))
        self.input_linear = JetMoeParallelExperts(config.num_local_experts, self.input_size, self.hidden_size * 2)
        self.output_linear = JetMoeParallelExperts(config.num_local_experts, self.hidden_size, self.input_size)
        self.router = JetMoeTopKGating(input_size=self.input_size, num_experts=config.num_local_experts, top_k=config.num_experts_per_tok)

    def forward(self, layer_input):

        bsz, length, emb_size = layer_input.size()
        layer_input = layer_input.reshape(-1, emb_size)
        _, batch_index, batch_gates, expert_size, router_logits = self.router(layer_input)
        expert_inputs = layer_input[batch_index]
        hidden_states = self.input_linear(expert_inputs, expert_size)
        chunked_hidden_states = hidden_states.chunk(2, dim=-1)
        hidden_states = self.activation(chunked_hidden_states[0]) * chunked_hidden_states[1]
        expert_outputs = self.output_linear(hidden_states, expert_size)
        expert_outputs = expert_outputs * batch_gates[:, None]
        zeros = torch.zeros((bsz * length, self.input_size), dtype=expert_outputs.dtype, device=expert_outputs.device)
        layer_output = zeros.index_add(0, batch_index, expert_outputs)
        layer_output = layer_output.view(bsz, length, self.input_size)
        layer_output = layer_output + self.bias
        return (layer_output, router_logits)

A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.

Args:
config:
Configuration object with model hyperparameters.


def get_outputs_filtered(self, owner, spent=None):
    outputs = self.fastquery.get_outputs_by_public_key(owner)
    if (spent is None):
        return outputs
    elif (spent is True):
        return self.fastquery.filter_unspent_outputs(outputs)
    elif (spent is False):
        return self.fastquery.filter_spent_outputs(outputs)

Get a list of output links filtered on some criteria

Args:
owner (str): base58 encoded public_key.
spent (bool): If ``True`` return only the spent outputs. If
``False`` return only unspent outputs. If spent is
not specified (``None``) return all outputs.

Returns:
:obj:`list` of TransactionLink: list of ``txid`` s and ``output`` s
pointing to another transaction's condition


def _ensure_proper_types(struct, encoding, force_types):
    if (force_types is None):
        return struct
    res = None
    if isinstance(struct, (dict, collections.OrderedDict)):
        res = type(struct)()
        for (k, v) in struct.items():
            res[_ensure_proper_types(k, encoding, force_types)] = _ensure_proper_types(v, encoding, force_types)
    elif isinstance(struct, list):
        res = []
        for i in struct:
            res.append(_ensure_proper_types(i, encoding, force_types))
    elif isinstance(struct, six.binary_type):
        res = struct.decode(encoding)
    elif isinstance(struct, (six.text_type, type(None), type(True), six.integer_types, float)):
        res = struct
    elif isinstance(struct, datetime.datetime):
        res = struct
    else:
        raise AnyMarkupError('internal error - unexpected type {0} in parsed markup'.format(type(struct)))
    if (force_types and isinstance(res, six.text_type)):
        res = _recognize_basic_types(res)
    elif (not (force_types or isinstance(res, (dict, collections.OrderedDict, list, six.text_type)))):
        res = six.text_type(res)
    return res

A convenience function that recursively makes sure the given structure
contains proper types according to value of `force_types`.

Args:
struct: a structure to check and fix
encoding: encoding to use on found bytestrings
force_types:
if `True`, integers, floats, booleans and none/null
are recognized and returned as proper types instead of strings;
if `False`, everything is converted to strings
if `None`, unmodified `struct` is returned
Returns:
a fully decoded copy of given structure


def combine_samples(self, md5_list, filename, type_tag):

        total_bytes = ""
        for md5 in md5_list:
            total_bytes += self.get_sample(md5)['sample']['raw_bytes']
            self.remove_sample(md5)

        return self.store_sample(total_bytes, filename, type_tag)

Combine samples together. This may have various use cases the most significant
involving a bunch of sample 'chunks' got uploaded and now we combine them together

Args:
md5_list: The list of md5s to combine, order matters!
filename: name of the file (used purely as meta data not for lookup)
type_tag: ('exe','pcap','pdf','json','swf', or ...)
Returns:
the computed md5 of the combined samples


def pprint_value_string(self, value):

        unit = '' if self.unit is None else ' ' + bytes_to_unicode(self.unit)
        value = self.pprint_value(value)
        return title_format.format(name=bytes_to_unicode(self.label), val=value, unit=unit)

Pretty print the dimension value and unit.

Args:
value: Dimension value to format

Returns:
Formatted dimension value string with unit


def layer_preprocess(layer_input, hparams, layer_collection=None):
    assert ('a' not in hparams.layer_preprocess_sequence), 'No residual connections allowed in hparams.layer_preprocess_sequence'
    assert ('z' not in hparams.layer_preprocess_sequence), 'No residual connections allowed in hparams.layer_preprocess_sequence'
    return layer_prepostprocess(None, layer_input, sequence=hparams.layer_preprocess_sequence, dropout_rate=hparams.layer_prepostprocess_dropout, norm_type=hparams.norm_type, depth=None, epsilon=hparams.norm_epsilon, dropout_broadcast_dims=comma_separated_string_to_integer_list(getattr(hparams, 'layer_prepostprocess_dropout_broadcast_dims', '')), default_name='layer_prepostprocess', layer_collection=layer_collection)

Apply layer preprocessing.

See layer_prepostprocess() for details.

A hyperparameters object is passed for convenience.  The hyperparameters
that may be used are:

layer_preprocess_sequence
layer_prepostprocess_dropout
norm_type
hidden_size
norm_epsilon

Args:
layer_input: a Tensor
hparams: a hyperparameters object.
layer_collection: A tensorflow_kfac.LayerCollection. Only used by the
KFAC optimizer. Default is None.

Returns:
a Tensor


def os_volumes(self):
    if (not self.__os_volumes):
        self.__os_volumes = OsVolumes(self.__connection)
    return self.__os_volumes

Gets the OS Volumes API client.

Returns:
OsVolumes:


def _finish_parsing(self, instrumentation_block):
    formatter = _InstrumentationBlockFormatter(instrumentation_block)
    return formatter.has_completed_result_block_format(self.DEFAULT_INSTRUMENTATION_ERROR_MESSAGE)

Finishes parsing the instrumentation result block for the final
instrumentation run status.

Args:
instrumentation_block: _InstrumentationBlock, the instrumentation
result block for the instrumenation run. Potentially, thisi
could actually be method block if the instrumentation outputi
is malformed.

Returns:
A boolean indicating whether the instrumentation run completed
with all the tests passing.

Raises:
signals.TestError: Error raised if the instrumentation failed to
complete with either a pass or fail status.


def delete_container_instance_group(access_token, subscription_id, resource_group,
                                    container_group_name):

    endpoint = ''.join([get_rm_endpoint(),
                        '/subscriptions/', subscription_id,
                        '/resourcegroups/', resource_group,
                        '/providers/Microsoft.ContainerInstance/ContainerGroups/',
                        container_group_name,
                        '?api-version=', CONTAINER_API])
    return do_delete(endpoint, access_token)

Delete a container group from a resource group.

Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
container_group_name (str): Name of container instance group.

Returns:
HTTP response.


def _GetSignatureMatchParserNames(self, file_object):

    parser_names = []
    scan_state = pysigscan.scan_state()
    self._file_scanner.scan_file_object(scan_state, file_object)

    for scan_result in iter(scan_state.scan_results):
      format_specification = (
          self._formats_with_signatures.GetSpecificationBySignature(
              scan_result.identifier))

      if format_specification.identifier not in parser_names:
        parser_names.append(format_specification.identifier)

    return parser_names

Determines if a file-like object matches one of the known signatures.

Args:
file_object (file): file-like object whose contents will be checked
for known signatures.

Returns:
list[str]: parser names for which the contents of the file-like object
matches their known signatures.


def _call_api(self, method, params=None):
    url = self.url.format(method=method)
    if (not params):
        params = {'token': self.token}
    else:
        params['token'] = self.token
    logger.debug('Send request to %s', url)
    response = requests.get(url, params=params).json()
    if self.verify:
        if (not response['ok']):
            msg = 'For {url} API returned this bad response {response}'
            raise Exception(msg.format(url=url, response=response))
    return response

Low-level method to call the Slack API.

Args:
method: {str} method name to call
params: {dict} GET parameters
The token will always be added


def GetUnicodeString(value):

  if isinstance(value, list):
    value = [GetUnicodeString(item) for item in value]
    return ''.join(value)

  if isinstance(value, py2to3.INTEGER_TYPES):
    value = '{0:d}'.format(value)

  if not isinstance(value, py2to3.UNICODE_TYPE):
    return codecs.decode(value, 'utf8', 'ignore')
  return value

Attempts to convert the argument to a Unicode string.

Args:
value (list|int|bytes|str): value to convert.

Returns:
str: string representation of the argument.


def create_alias(alias_name, alias_command):

    alias_name, alias_command = alias_name.strip(), alias_command.strip()
    alias_table = get_alias_table()
    if alias_name not in alias_table.sections():
        alias_table.add_section(alias_name)

    alias_table.set(alias_name, 'command', alias_command)
    _commit_change(alias_table)

Create an alias.

Args:
alias_name: The name of the alias.
alias_command: The command that the alias points to.


def lint_fileset(*dirnames, **kwargs):
    try:
        rc_filename = kwargs['rc_filename']
        description = kwargs['description']
        if (len(kwargs) != 2):
            raise KeyError
    except KeyError:
        raise KeyError(_LINT_FILESET_MSG)
    pylint_shell_command = ['pylint', '--rcfile', rc_filename]
    pylint_shell_command.extend(dirnames)
    status_code = subprocess.call(pylint_shell_command)
    if (status_code != 0):
        error_message = _ERROR_TEMPLATE.format(description, status_code)
        print(error_message, file=sys.stderr)
        sys.exit(status_code)

Lints a group of files using a given rcfile.

Keyword arguments are

* ``rc_filename`` (``str``): The name of the Pylint config RC file.
* ``description`` (``str``): A description of the files and configuration
currently being run.

Args:
dirnames (tuple): Directories to run Pylint in.
kwargs: The keyword arguments. The only keyword arguments
are ``rc_filename`` and ``description`` and both
are required.

Raises:
KeyError: If the wrong keyword arguments are used.


def get_plugin(cls, name: str) -> Type[ConnectionPlugin]:

        if name not in cls.available:
            raise ConnectionPluginNotRegistered(
                f"Connection {name!r} is not registered"
            )
        return cls.available[name]

Fetches the connection plugin by name if already registered

Args:
name: name of the connection plugin

Raises:
:obj:`nornir.core.exceptions.ConnectionPluginNotRegistered`


def descriptors(package):

    from os import path
    dpath = _descriptor_path(package)
    if path.isfile(dpath):
        import json
        with open(dpath) as f:
            jdb = json.load(f)
        return jdb
    else:
        return None

Returns a dictionary of descriptors deserialized from JSON for the
specified package.

Args:
package (str): name of the python package to get settings for.


def import_demonstrations(self, demonstrations):
    if isinstance(demonstrations, dict):
        if self.unique_state:
            demonstrations['states'] = dict(state=demonstrations['states'])
        if self.unique_action:
            demonstrations['actions'] = dict(action=demonstrations['actions'])
        self.model.import_demo_experience(**demonstrations)
    else:
        if self.unique_state:
            states = dict(state=list())
        else:
            states = {name: list() for name in demonstrations[0]['states']}
        internals = {name: list() for name in demonstrations[0]['internals']}
        if self.unique_action:
            actions = dict(action=list())
        else:
            actions = {name: list() for name in demonstrations[0]['actions']}
        terminal = list()
        reward = list()
        for demonstration in demonstrations:
            if self.unique_state:
                states['state'].append(demonstration['states'])
            else:
                for (name, state) in states.items():
                    state.append(demonstration['states'][name])
            for (name, internal) in internals.items():
                internal.append(demonstration['internals'][name])
            if self.unique_action:
                actions['action'].append(demonstration['actions'])
            else:
                for (name, action) in actions.items():
                    action.append(demonstration['actions'][name])
            terminal.append(demonstration['terminal'])
            reward.append(demonstration['reward'])
        self.model.import_demo_experience(states=states, internals=internals, actions=actions, terminal=terminal, reward=reward)

Imports demonstrations, i.e. expert observations. Note that for large numbers of observations,
set_demonstrations is more appropriate, which directly sets memory contents to an array an expects
a different layout.

Args:
demonstrations: List of observation dicts


def _build_endpoint(self, endpoint_name):

        endpoint_relative = settings.get('asmaster_endpoints', endpoint_name)
        return '%s%s' % (self.host, endpoint_relative)

Generate an enpoint url from a setting name.

Args:
endpoint_name(str): setting name for the enpoint to build

Returns:
(str) url enpoint


def ExpandWindowsUserEnvironmentVariables(data_string, knowledge_base, sid=None, username=None):
    win_environ_regex = re.compile('%([^%]+?)%')
    components = []
    offset = 0
    for match in win_environ_regex.finditer(data_string):
        components.append(data_string[offset:match.start()])
        kb_user = knowledge_base.GetUser(sid=sid, username=username)
        kb_value = None
        if kb_user:
            kb_value = getattr(kb_user, match.group(1).lower(), None)
        if (isinstance(kb_value, string_types) and kb_value):
            components.append(kb_value)
        else:
            components.append(('%%%s%%' % match.group(1)))
        offset = match.end()
    components.append(data_string[offset:])
    return ''.join(components)

r"""Take a string and expand windows user environment variables based.

Args:
data_string: A string, e.g. "%TEMP%\\LogFiles"
knowledge_base: A knowledgebase object.
sid: A Windows SID for a user to expand for.
username: A Windows user name to expand for.

Returns:
A string with available environment variables expanded.


def set_element_dt(self, el_name, dt, tz=None, el_idx=0):
    dt = d1_common.date_time.cast_naive_datetime_to_tz(dt, tz)
    self.get_element_by_name(el_name, el_idx).text = dt.isoformat()

Set the text of the selected element to an ISO8601 formatted datetime.

Args:
el_name : str
Name of element to update.

dt : datetime.datetime
Date and time to set

tz : datetime.tzinfo
Timezone to set

- Without a timezone, other contextual information is required in order to
determine the exact represented time.
- If dt has timezone: The ``tz`` parameter is ignored.
- If dt is naive (without timezone): The timezone is set to ``tz``.
- ``tz=None``: Prevent naive dt from being set to a timezone. Without a
timezone, other contextual information is required in order to determine
the exact represented time.
- ``tz=d1_common.date_time.UTC()``: Set naive dt to UTC.

el_idx : int
Index of element to use in the event that there are multiple sibling
elements with the same name.


def traverse_ancestors(self, include_self=True):

        if not isinstance(include_self, bool):
            raise TypeError("include_self must be a bool")
        if include_self:
            c = self
        else:
            c = self.parent
        while c is not None:
            yield c; c = c.parent

Traverse over the ancestors of this ``Node``

Args:
``include_self`` (``bool``): ``True`` to include self in the traversal, otherwise ``False``


def get_json(filename):
    check_if_this_file_exist(filename)
    filename = os.path.abspath(filename)
    s = command_line(['exiftool', '-G', '-j', '-sort', filename])
    if s:
        s = s.decode('utf-8').rstrip('\r\n')
        return json.loads(s)
    else:
        return s

Return a json value of the exif

Get a filename and return a JSON object

Arguments:
filename {string} -- your filename

Returns:
[JSON] -- Return a JSON object


def AnalyzeClient(self, client):

    keywords = set(["."])

    def TryAppend(prefix, keyword):
      precondition.AssertType(prefix, Text)
      precondition.AssertType(keyword, Text)
      if keyword:
        keyword_string = self._NormalizeKeyword(keyword)
        keywords.add(keyword_string)
        if prefix:
          keywords.add(prefix + ":" + keyword_string)

    def TryAppendPrefixes(prefix, keyword, delimiter):
      TryAppend(prefix, keyword)
      segments = keyword.split(delimiter)
      for i in range(1, len(segments)):
        TryAppend(prefix, delimiter.join(segments[0:i]))
      return len(segments)

    def TryAppendIP(ip):
      TryAppend("ip", ip)

      if TryAppendPrefixes("ip", Text(ip), ".") == 4:
        return

      TryAppendPrefixes("ip", Text(ip), ":")

    def TryAppendMac(mac):
      TryAppend("mac", mac)
      if len(mac) == 12:

        TryAppend("mac", ":".join([mac[i:i + 2] for i in range(0, 12, 2)]))

    TryAppend("host", client.knowledge_base.fqdn)
    host = client.knowledge_base.fqdn.split(".", 1)[0]
    TryAppendPrefixes("host", host, "-")
    TryAppendPrefixes("host", client.knowledge_base.fqdn, ".")
    TryAppend("", client.knowledge_base.os)
    TryAppend("", client.Uname())
    TryAppend("", client.os_release)
    TryAppend("", client.os_version)
    TryAppend("", client.kernel)
    TryAppend("", client.arch)

    kb = client.knowledge_base
    if kb:
      for user in kb.users:
        TryAppend("user", user.username)
        TryAppend("", user.full_name)
        if user.full_name:
          for name in user.full_name.split():

            TryAppend("", name.strip("\"'()"))

    for ip in client.GetIPAddresses():
      TryAppendIP(ip)
    for mac in client.GetMacAddresses():
      TryAppendMac(mac)

    client_info = client.startup_info.client_info
    if client_info:
      TryAppend("client", client_info.client_name)
      TryAppend("client", Text(client_info.client_version))
      if client_info.labels:
        for label in client_info.labels:
          TryAppend("label", label)

    return keywords

Finds the client_id and keywords for a client.

Args:
client: A Client object record to find keywords for.

Returns:
A list of keywords related to client.


def batch_norm_relu(inputs, is_training, relu=True, init_zero=False, data_format='channels_first'):
    if init_zero:
        gamma_initializer = tf.zeros_initializer()
    else:
        gamma_initializer = tf.ones_initializer()
    if (data_format == 'channels_first'):
        axis = 1
    else:
        axis = 3
    inputs = layers().BatchNormalization(axis=axis, momentum=BATCH_NORM_DECAY, epsilon=BATCH_NORM_EPSILON, center=True, scale=True, fused=True, gamma_initializer=gamma_initializer)(inputs, training=is_training)
    if relu:
        inputs = tf.nn.relu(inputs)
    return inputs

Performs a batch normalization followed by a ReLU.

Args:
inputs: `Tensor` of shape `[batch, channels, ...]`.
is_training: `bool` for whether the model is training.
relu: `bool` if False, omits the ReLU operation.
init_zero: `bool` if True, initializes scale parameter of batch
normalization with 0 instead of 1 (default).
data_format: `str` either "channels_first" for `[batch, channels, height,
width]` or "channels_last for `[batch, height, width, channels]`.

Returns:
A normalized `Tensor` with the same `data_format`.


def qn_to_qubo(expr):

    try:
        import sympy
    except ImportError:
        raise ImportError("This function requires sympy. Please install it.")
    assert type(expr) == sympy.Add
    to_i = lambda s: int(str(s)[1:])
    max_i = max(map(to_i, expr.free_symbols)) + 1
    qubo = [[0.] * max_i for _ in range(max_i)]
    for arg in expr.args:
        syms = arg.free_symbols
        assert len(syms) <= 2
        if len(syms) == 2:
            assert type(arg) == sympy.Mul
            i, j = list(map(to_i, syms))
            if i > j:
                i, j = j, i
            if i == j:
                if len(arg.args) == 2:
                    qubo[i][i] = float(arg.args[0])
                elif len(arg.args) == 1:
                    qubo[i][i] = 1.0
                else:
                    raise ValueError(f"Too many args! arg.args = {arg.args}")
                continue
            if len(arg.args) == 3:
                qubo[i][j] = float(arg.args[0])
            elif len(arg.args) == 2:
                qubo[i][j]
        if len(syms) == 1:
            if len(arg.args) == 2:
                assert type(arg) == sympy.Mul
                i = to_i(next(iter(syms)))
                qubo[i][i] = float(arg.args[0])
            elif len(arg.args) == 1:
                qubo[i][i] = 1.0
            else:
                raise ValueError(f"Too many args! arg.args = {arg.args}")
    return qubo

Convert Sympy's expr to QUBO.

Args:
expr: Sympy's quadratic expression with variable `q0`, `q1`, ...
Returns:
[[float]]: Returns QUBO matrix.


def _SparseReorderGrad(op: ops.Operation, unused_output_indices_grad, output_values_grad):
    input_indices = op.inputs[0]
    input_shape = op.inputs[2]
    num_entries = array_ops.shape(input_indices)[0]
    entry_indices = math_ops.range(num_entries)
    sp_unordered = sparse_tensor.SparseTensor(input_indices, entry_indices, input_shape)
    sp_ordered = sparse_ops.sparse_reorder(sp_unordered)
    inverted_permutation = array_ops.invert_permutation(sp_ordered.values)
    return (None, array_ops.gather(output_values_grad, inverted_permutation), None)

Gradients for the SparseReorder op.

Args:
op: the SparseReorder op
unused_output_indices_grad: the incoming gradients of the output indices
output_values_grad: the incoming gradients of the output values

Returns:
Gradient for each of the 3 input tensors:
(input_indices, input_values, input_shape)
The gradients for input_indices and input_shape is None.


def PmfProbLess(pmf1, pmf2):
    total = 0.0
    for (v1, p1) in pmf1.Items():
        for (v2, p2) in pmf2.Items():
            if (v1 < v2):
                total += (p1 * p2)
    return total

Probability that a value from pmf1 is less than a value from pmf2.

Args:
pmf1: Pmf object
pmf2: Pmf object

Returns:
float probability


def minimum(x1, x2, output_shape=None, name=None):

  output_shape = convert_to_shape(output_shape)
  with tf.name_scope(name, default_name="minimum"):
    x1, x2 = binary_arguments_to_tensors(x1, x2)
    return MinMaxOperation(
        tf.minimum, x1, x2, output_shape=_infer_binary_broadcast_shape(
            x1.shape, x2.shape, output_shape)).outputs[0]

Binary minimum with broadcsting.

Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor


def _create_moving_sequence(image, pad_lefts, total_padding):

  with tf.name_scope("moving_sequence"):
    def get_padded_image(args):
      pad_left, = args
      pad_right = total_padding - pad_left
      padding = tf.stack([pad_left, pad_right], axis=-1)
      z = tf.zeros((1, 2), dtype=pad_left.dtype)
      padding = tf.concat([padding, z], axis=0)
      return tf.pad(image, padding)

    padded_images = tf.map_fn(
        get_padded_image, [pad_lefts], dtype=tf.uint8, infer_shape=False,
        back_prop=False)

  return padded_images

Create a moving image sequence from the given image a left padding values.

Args:
image: [in_h, in_w, n_channels] uint8 array
pad_lefts: [sequence_length, 2] int32 array of left padding values
total_padding: tensor of padding values, (pad_h, pad_w)

Returns:
[sequence_length, out_h, out_w, n_channels] uint8 image sequence, where
out_h = in_h + pad_h, out_w = in_w + out_w


def sparse_categorical_crossentropy(target, output, from_logits=False, axis=-1):
    if axis != -1 and axis != len(output.shape) - 1:
        raise ValueError(f'Only axis=-1 is currently supported. Received: axis={axis}')
    output, from_logits = _get_logits(output, from_logits, 'Softmax', 'sparse_categorical_crossentropy')
    target = tf.convert_to_tensor(target)
    target = tf.cast(target, dtype='int64')
    output = tf.convert_to_tensor(output)
    if len(target.shape) == len(output.shape) and target.shape[-1] == 1:
        target = tf.squeeze(target, axis=-1)
    if len(output.shape) < 1:
        raise ValueError(f'Argument `output` must be at least rank 1. Received: output.shape={output.shape}')
    if len(target.shape) != len(output.shape[:-1]):
        raise ValueError(f'Argument `output` must have rank (ndim) `target.ndim - 1`. Received: target.shape={target.shape}, output.shape={output.shape}')
    for e1, e2 in zip(target.shape, output.shape[:-1]):
        if e1 is not None and e2 is not None and (e1 != e2):
            raise ValueError(f'Arguments `target` and `output` must have the same shape up until the last dimension: target.shape={target.shape}, output.shape={output.shape}')
    if not from_logits:
        output = tf.clip_by_value(output, backend.epsilon(), 1 - backend.epsilon())
        output = tf.math.log(output)
    result = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=target, logits=output)
    return result

Categorical crossentropy with integer targets.

Args:
target: An integer tensor.
output: A tensor resulting from a softmax
(unless `from_logits` is True, in which
case `output` is expected to be the logits).
from_logits: Boolean, whether `output` is the
result of a softmax, or is a tensor of logits.
axis: Int specifying the channels axis. `axis=-1` corresponds to data
format `channels_last`, and `axis=1` corresponds to data format
`channels_first`.

Returns:
Output tensor.


def WriteSourceFile(self, source_file):
    debug_event = debug_event_pb2.DebugEvent(source_file=source_file)
    self._EnsureTimestampAdded(debug_event)
    _pywrap_debug_events_writer.WriteSourceFile(self._dump_root, debug_event)

Write a SourceFile proto with the writer.

Args:
source_file: A SourceFile proto, describing the content of a source file
involved in the execution of the debugged TensorFlow program.


def DeleteSnapshots(self, request, global_params=None):
    config = self.GetMethodConfig('DeleteSnapshots')
    return self._RunMethod(config, request, global_params=global_params)

Deletes a snapshot.

Args:
request: (DataflowProjectsDeleteSnapshotsRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(DeleteSnapshotResponse) The response message.


def Getattr(self, path, fh=None):

    del fh

    if not path:
      raise fuse.FuseOSError(errno.ENOENT)

    if path != self.root:
      full_path = self.root.Add(path)
    else:
      full_path = path

    fd = aff4.FACTORY.Open(full_path, token=self.token)

    if full_path == "/":
      return self.MakePartialStat(fd)

    fd = aff4.FACTORY.Open(full_path, token=self.token)

    aff4_stat = fd.Get(fd.Schema.STAT)

    if aff4_stat:
      return aff4_stat.AsDict()

    elif fd.Get(fd.Schema.LAST) is None:

      raise fuse.FuseOSError(errno.ENOENT)
    else:

      pass

    return self.MakePartialStat(fd)

Performs a stat on a file or directory.

Args:
path: The path to stat.
fh: A file handler. Not used.

Returns:
A dictionary mapping st_ names to their values.

Raises:
FuseOSError: When a path is supplied that grr doesn't know about, ie an
invalid file path.
ValueError: If an empty path is passed. (The empty string, when passed to
self.root.Add, returns a path for aff4:/, the root directory, which is not
the behaviour we want.)


def stddev(self, name='stddev'):
    with self._name_scope(name):
        try:
            return self._stddev()
        except NotImplementedError as original_exception:
            try:
                return math_ops.sqrt(self._variance())
            except NotImplementedError:
                raise original_exception

Standard deviation.

Standard deviation is defined as,

```none
stddev = E[(X - E[X])**2]**0.5
```

where `X` is the random variable associated with this distribution, `E`
denotes expectation, and `stddev.shape = batch_shape + event_shape`.

Args:
name: Python `str` prepended to names of ops created by this function.

Returns:
stddev: Floating-point `Tensor` with shape identical to
`batch_shape + event_shape`, i.e., the same shape as `self.mean()`.


def _check_validity(cls, text):
    if ((not text[0].lstrip().startswith('1 ')) or (not text[1].lstrip().startswith('2 '))):
        raise ValueError('Line number check failed')
    for line in text:
        line = line.strip()
        if (str(cls._checksum(line)) != line[(- 1)]):
            raise ValueError('Checksum validation failed')

Check the validity of a TLE

Args:
text (tuple of str)
Raise:
ValueError


def remove_plugin(self, name, force=False):
    url = self._url('/plugins/{0}', name)
    res = self._delete(url, params={'force': force})
    self._raise_for_status(res)
    return True

Remove an installed plugin.

Args:
name (string): Name of the plugin to remove. The ``:latest``
tag is optional, and is the default if omitted.
force (bool): Disable the plugin before removing. This may
result in issues if the plugin is in use by a container.

Returns:
``True`` if successful


def create_xml_dom_element(doc, name, value):
    s = str_or_unicode(value)
    if (six.PY2 and (not isinstance(s, unicode))):
        s = s.decode('utf-8', 'ignore')
    if isinstance(value, bool):
        s = s.lower()
    s = _ILLEGAL_XML_CHARS_REGEX.sub(u'', s)
    e = doc.createElement(name)
    e.appendChild(doc.createTextNode(s))
    return e

Returns an XML DOM element with name and text value.

Args:
doc: minidom.Document, the DOM document it should create nodes from.
name: str, the tag of XML element.
value: object, whose string representation will be used
as the value of the XML element. Illegal or highly discouraged xml 1.0
characters are stripped.

Returns:
An instance of minidom.Element.


def _create_dag_op(self, name, params, qargs):

        if name == "u0":
            op_class = U0Gate
        elif name == "u1":
            op_class = U1Gate
        elif name == "u2":
            op_class = U2Gate
        elif name == "u3":
            op_class = U3Gate
        elif name == "x":
            op_class = XGate
        elif name == "y":
            op_class = YGate
        elif name == "z":
            op_class = ZGate
        elif name == "t":
            op_class = TGate
        elif name == "tdg":
            op_class = TdgGate
        elif name == "s":
            op_class = SGate
        elif name == "sdg":
            op_class = SdgGate
        elif name == "swap":
            op_class = SwapGate
        elif name == "rx":
            op_class = RXGate
        elif name == "ry":
            op_class = RYGate
        elif name == "rz":
            op_class = RZGate
        elif name == "rzz":
            op_class = RZZGate
        elif name == "id":
            op_class = IdGate
        elif name == "h":
            op_class = HGate
        elif name == "cx":
            op_class = CnotGate
        elif name == "cy":
            op_class = CyGate
        elif name == "cz":
            op_class = CzGate
        elif name == "ch":
            op_class = CHGate
        elif name == "crz":
            op_class = CrzGate
        elif name == "cu1":
            op_class = Cu1Gate
        elif name == "cu3":
            op_class = Cu3Gate
        elif name == "ccx":
            op_class = ToffoliGate
        elif name == "cswap":
            op_class = FredkinGate
        else:
            raise QiskitError("unknown operation for ast node name %s" % name)

        op = op_class(*params)

        self.dag.apply_operation_back(op, qargs, [], condition=self.condition)

Create a DAG node out of a parsed AST op node.

Args:
name (str): operation name to apply to the dag.
params (list): op parameters
qargs (list(QuantumRegister, int)): qubits to attach to

Raises:
QiskitError: if encountering a non-basis opaque gate


async def send_script(self, conn_id, data):

        self._ensure_connection(conn_id, True)
        connection_string = self._get_property(conn_id, "connection_string")

        msg = dict(connection_string=connection_string, fragment_count=1, fragment_index=0,
                   script=base64.b64encode(data))
        await self._send_command(OPERATIONS.SEND_SCRIPT, msg, COMMANDS.SendScriptResponse)

Send a a script to this IOTile device

Args:
conn_id (int): A unique identifier that will refer to this connection
data (bytes): the script to send to the device


def broadcast(tensor):
    _check_device(tensor)
    with ops.device(tensor.device):
        return gen_nccl_ops.nccl_broadcast(input=tensor, shape=tensor.shape)

Returns a tensor that can be efficiently transferred to other devices.

Args:
tensor: The tensor to send; must be assigned to a GPU device.

Returns:
A tensor with the value of `src_tensor`, which can be used as input to
ops on other GPU devices.


def create_variable(self, feature_column, name, shape, dtype=None, trainable=True, use_resource=True, initializer=None):
    if name in self._cols_to_vars_map[feature_column]:
        raise ValueError('Variable already exists.')
    with trackable.no_manual_dependency_tracking_scope(self._layer):
        var = self._layer.add_weight(name=name, shape=shape, dtype=dtype, initializer=initializer, trainable=self._trainable and trainable, use_resource=use_resource, getter=variable_scope.get_variable)
    if isinstance(var, variables.PartitionedVariable):
        for v in var:
            part_name = name + '/' + str(v._get_save_slice_info().var_offset[0])
            self._layer._track_trackable(v, feature_column.name + '/' + part_name)
    elif isinstance(var, trackable.Trackable):
        self._layer._track_trackable(var, feature_column.name + '/' + name)
    self._cols_to_vars_map[feature_column][name] = var
    return var

Creates a new variable.

Args:
feature_column: A `FeatureColumn` object this variable corresponds to.
name: variable name.
shape: variable shape.
dtype: The type of the variable. Defaults to `self.dtype` or `float32`.
trainable: Whether this variable is trainable or not.
use_resource: If true, we use resource variables. Otherwise we use
RefVariable.
initializer: initializer instance (callable).

Returns:
The created variable.


def _rpc(self, method, *args):
    with self._lock:
        apiid = next(self._counter)
        data = {'id': apiid, 'method': method, 'params': args}
        request = json.dumps(data)
        self._client_send(request)
        response = self._client_receive()
    if (not response):
        raise ProtocolError(self._ad, ProtocolError.NO_RESPONSE_FROM_SERVER)
    result = json.loads(str(response, encoding='utf8'))
    if result['error']:
        raise ApiError(self._ad, result['error'])
    if (result['id'] != apiid):
        raise ProtocolError(self._ad, ProtocolError.MISMATCHED_API_ID)
    if (result.get('callback') is not None):
        if (self._event_client is None):
            self._event_client = self._start_event_client()
        return callback_handler.CallbackHandler(callback_id=result['callback'], event_client=self._event_client, ret_value=result['result'], method_name=method, ad=self._ad)
    return result['result']

Sends an rpc to the app.

Args:
method: str, The name of the method to execute.
args: any, The args of the method.

Returns:
The result of the rpc.

Raises:
ProtocolError: Something went wrong with the protocol.
ApiError: The rpc went through, however executed with errors.


def _get_user_command_string(self):
    sdk_int = int(self._ad.build_info['build_version_sdk'])
    if sdk_int < 24:
        return ''
    return f'--user {self.user_id}'

Gets the appropriate command argument for specifying user IDs.

By default, `SnippetClient` operates within the current user.

We don't add the `--user {ID}` arg when Android's SDK is below 24,
where multi-user support is not well implemented.

Returns:
String, the command param section to be formatted into the adb
commands.


def verify_fileobj(fileobj, writable=False):
    try:
        data = fileobj.read(0)
    except Exception:
        if (not hasattr(fileobj, 'read')):
            raise ValueError(('%r not a valid file object' % fileobj))
        raise ValueError(("Can't read from file object %r" % fileobj))
    if (not isinstance(data, bytes)):
        raise ValueError(('file object %r not opened in binary mode' % fileobj))
    if writable:
        try:
            fileobj.write(b'')
        except Exception:
            if (not hasattr(fileobj, 'write')):
                raise ValueError(('%r not a valid file object' % fileobj))
            raise ValueError(("Can't write to file object %r" % fileobj))

Verifies that the passed fileobj is a file like object which
we can use.

Args:
writable (bool): verify that the file object is writable as well

Raises:
ValueError: In case the object is not a file object that is readable
(or writable if required) or is not opened in bytes mode.


def match_bitap(self, text, pattern, loc):
    s = self.match_alphabet(pattern)

    def match_bitapScore(e, x):
        'Compute and return the score for a match with e errors and x location.\n      Accesses loc and pattern through being a closure.\n\n      Args:\n        e: Number of errors in match.\n        x: Location of match.\n\n      Returns:\n        Overall score for match (0.0 = good, 1.0 = bad).\n      '
        accuracy = (float(e) / len(pattern))
        proximity = abs((loc - x))
        if (not self.Match_Distance):
            return ((proximity and 1.0) or accuracy)
        return (accuracy + (proximity / float(self.Match_Distance)))
    score_threshold = self.Match_Threshold
    best_loc = text.find(pattern, loc)
    if (best_loc != (- 1)):
        score_threshold = min(match_bitapScore(0, best_loc), score_threshold)
        best_loc = text.rfind(pattern, (loc + len(pattern)))
        if (best_loc != (- 1)):
            score_threshold = min(match_bitapScore(0, best_loc), score_threshold)
    matchmask = (1 << (len(pattern) - 1))
    best_loc = (- 1)
    bin_max = (len(pattern) + len(text))
    last_rd = None
    for d in range(len(pattern)):
        bin_min = 0
        bin_mid = bin_max
        while (bin_min < bin_mid):
            if (match_bitapScore(d, (loc + bin_mid)) <= score_threshold):
                bin_min = bin_mid
            else:
                bin_max = bin_mid
            bin_mid = (((bin_max - bin_min)
        bin_max = bin_mid
        start = max(1, ((loc - bin_mid) + 1))
        finish = (min((loc + bin_mid), len(text)) + len(pattern))
        rd = ([0] * (finish + 2))
        rd[(finish + 1)] = ((1 << d) - 1)
        for j in range(finish, (start - 1), (- 1)):
            if (len(text) <= (j - 1)):
                charMatch = 0
            else:
                charMatch = s.get(text[(j - 1)], 0)
            if (d == 0):
                rd[j] = (((rd[(j + 1)] << 1) | 1) & charMatch)
            else:
                rd[j] = (((((rd[(j + 1)] << 1) | 1) & charMatch) | (((last_rd[(j + 1)] | last_rd[j]) << 1) | 1)) | last_rd[(j + 1)])
            if (rd[j] & matchmask):
                score = match_bitapScore(d, (j - 1))
                if (score <= score_threshold):
                    score_threshold = score
                    best_loc = (j - 1)
                    if (best_loc > loc):
                        start = max(1, ((2 * loc) - best_loc))
                    else:
                        break
        if (match_bitapScore((d + 1), loc) > score_threshold):
            break
        last_rd = rd
    return best_loc

Locate the best instance of 'pattern' in 'text' near 'loc' using the
Bitap algorithm.

Args:
text: The text to search.
pattern: The pattern to search for.
loc: The location to search around.

Returns:
Best match index or -1.


def do_operation_update(self, info, an_op):

        self.update_op_func(self.metric_name, info, an_op)

Updates an operation using the assigned update_op_func

Args:
info: (:class:`endpoints_management.control.report_request.Info`): the
info instance to update
an_op: (:class:`endpoints_management.control.report_request.Info`):
the info instance to update

Return:
`True` if desc is supported, otherwise `False`


def _IsValidUrl(self, url):
    parsed_url = urlparse.urlparse(url)
    return (parsed_url.scheme in self._SUPPORTED_URL_SCHEMES)

Checks if an URL is considered valid.

Returns:
bool: True if the URL is valid.


def find_copy_constructor(type_):
    copy_ = type_.constructors((lambda x: is_copy_constructor(x)), recursive=False, allow_empty=True)
    if copy_:
        return copy_[0]
    return None

Returns reference to copy constructor.

Args:
type_ (declarations.class_t): the class to be searched.

Returns:
declarations.constructor_t: the copy constructor


def splitdrive(self, path):
    path = make_string_path(path)
    if self.is_windows_fs:
        if (len(path) >= 2):
            path = self.normcase(path)
            sep = self._path_separator(path)
            if (sys.version_info >= (2, 7, 8)):
                if ((path[0:2] == (sep * 2)) and (path[2:3] != sep)):
                    sep_index = path.find(sep, 2)
                    if (sep_index == (- 1)):
                        return (path[:0], path)
                    sep_index2 = path.find(sep, (sep_index + 1))
                    if (sep_index2 == (sep_index + 1)):
                        return (path[:0], path)
                    if (sep_index2 == (- 1)):
                        sep_index2 = len(path)
                    return (path[:sep_index2], path[sep_index2:])
            if (path[1:2] == self._matching_string(path, ':')):
                return (path[:2], path[2:])
    return (path[:0], path)

Splits the path into the drive part and the rest of the path.

Taken from Windows specific implementation in Python 3.5
and slightly adapted.

Args:
path: the full path to be splitpath.

Returns:
A tuple of the drive part and the rest of the path, or of
an empty string and the full path if drive letters are
not supported or no drive is present.


def get_plot(self, xlim=None, ylim=None, units="thz"):

        u = freq_units(units)

        ncolors = max(3, len(self._doses))
        ncolors = min(9, ncolors)

        import palettable

        colors = palettable.colorbrewer.qualitative.Set1_9.mpl_colors

        y = None
        alldensities = []
        allfrequencies = []
        plt = pretty_plot(12, 8)

        for key, dos in self._doses.items():
            frequencies = dos['frequencies'] * u.factor
            densities = dos['densities']
            if y is None:
                y = np.zeros(frequencies.shape)
            if self.stack:
                y += densities
                newdens = y.copy()
            else:
                newdens = densities
            allfrequencies.append(frequencies)
            alldensities.append(newdens)

        keys = list(self._doses.keys())
        keys.reverse()
        alldensities.reverse()
        allfrequencies.reverse()
        allpts = []
        for i, (key, frequencies, densities) in enumerate(zip(keys, allfrequencies, alldensities)):
            allpts.extend(list(zip(frequencies, densities)))
            if self.stack:
                plt.fill(frequencies, densities, color=colors[i % ncolors],
                         label=str(key))
            else:
                plt.plot(frequencies, densities, color=colors[i % ncolors],
                         label=str(key), linewidth=3)

        if xlim:
            plt.xlim(xlim)
        if ylim:
            plt.ylim(ylim)
        else:
            xlim = plt.xlim()
            relevanty = [p[1] for p in allpts
                         if xlim[0] < p[0] < xlim[1]]
            plt.ylim((min(relevanty), max(relevanty)))

        ylim = plt.ylim()
        plt.plot([0, 0], ylim, 'k--', linewidth=2)

        plt.xlabel(r'$\mathrm{{Frequencies\ ({})}}$'.format(u.label))
        plt.ylabel(r'$\mathrm{Density\ of\ states}$')

        plt.legend()
        leg = plt.gca().get_legend()
        ltext = leg.get_texts()
        plt.setp(ltext, fontsize=30)
        plt.tight_layout()
        return plt

Get a matplotlib plot showing the DOS.

Args:
xlim: Specifies the x-axis limits. Set to None for automatic
determination.
ylim: Specifies the y-axis limits.
units: units for the frequencies. Accepted values thz, ev, mev, ha, cm-1, cm^-1.


def UninstallDriver(bundle_name):
    km = objc.KextManager()
    cf_bundle_name = km.PyStringToCFString(bundle_name)
    status = km.iokit.KextManagerUnloadKextWithIdentifier(cf_bundle_name)
    km.dll.CFRelease(cf_bundle_name)
    return status

Calls into the IOKit to unload a kext by its name.

Args:
bundle_name: The bundle identifier of the kernel extension as defined in
Info.plist field CFBundleIdentifier.
Returns:
The error code from the library call. objc.OS_SUCCESS if successfull.


def case_report_content(store, institute_obj, case_obj):

    variant_types = {
        'causatives_detailed': 'causatives',
        'suspects_detailed': 'suspects',
        'classified_detailed': 'acmg_classification',
        'tagged_detailed': 'manual_rank',
        'dismissed_detailed': 'dismiss_variant',
        'commented_detailed': 'is_commented',
    }
    data = case_obj

    for individual in data['individuals']:
        try:
            sex = int(individual.get('sex', 0))
        except ValueError as err:
            sex = 0
        individual['sex_human'] = SEX_MAP[sex]
        individual['phenotype_human'] = PHENOTYPE_MAP.get(individual['phenotype'])

    data['comments'] = store.events(institute_obj, case=case_obj, comments=True)

    data['manual_rank_options'] = MANUAL_RANK_OPTIONS
    data['dismissed_options'] = DISMISS_VARIANT_OPTIONS
    data['genetic_models'] = dict(GENETIC_MODELS)
    data['report_created_at'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")

    evaluated_variants = {}
    for vt in variant_types:
        evaluated_variants[vt] = []

    for var_type in ['causatives', 'suspects']:

        vt = '_'.join([var_type, 'detailed'])
        for var_id in case_obj.get(var_type,[]):
            variant_obj = store.variant(var_id)
            if not variant_obj:
                continue

            evaluated_variants[vt].append(variant_obj)

    for var_obj in store.evaluated_variants(case_id=case_obj['_id']):

        for vt in variant_types:
            keyword = variant_types[vt]

            if keyword in var_obj:
                evaluated_variants[vt].append(var_obj)

    for var_type in evaluated_variants:
        decorated_variants = []
        for var_obj in evaluated_variants[var_type]:

            if var_obj['category'] == 'snv':
                decorated_info = variant_decorator(
                        store=store,
                        institute_obj=institute_obj,
                        case_obj=case_obj,
                        variant_id=None,
                        variant_obj=var_obj,
                        add_case=False,
                        add_other=False,
                        get_overlapping=False
                    )
            else:
                decorated_info = sv_variant(
                    store=store,
                    institute_id=institute_obj['_id'],
                    case_name=case_obj['display_name'],
                    variant_obj=var_obj,
                    add_case=False,
                    get_overlapping=False
                    )
            decorated_variants.append(decorated_info['variant'])

        data[var_type] = decorated_variants

    return data

Gather contents to be visualized in a case report

Args:
store(adapter.MongoAdapter)
institute_obj(models.Institute)
case_obj(models.Case)

Returns:
data(dict)


def convert_to_tensor(x, dtype=None, sparse=None, ragged=None):
    if any_symbolic_tensors((x,)):
        return ConvertToTensor(dtype=dtype, sparse=sparse, ragged=ragged)(x)
    return backend.core.convert_to_tensor(x, dtype=dtype, sparse=sparse, ragged=ragged)

Convert a NumPy array or Python array to a tensor.

Native tensors for the current backend or left unchanged unless the `dtype`,
`sparse` or `ragged` arguments are set.

Args:
x: A NumPy array, Python array (can be nested) or a backend tensor.
dtype: The target type. If `None`, the type of `x` is used.
sparse: Whether to keep sparse tensors. `False` will cause sparse
tensors to be densified. The default value of `None` means that
sparse tensors are kept only if the backend supports them.
ragged: Whether to keep ragged tensors. `False` will cause ragged
tensors to be densified. The default value of `None` means that
ragged tensors are kept only if the backend supports them.

Returns:
A backend tensor of the specified `dtype` and sparseness.

Example:

>>> x = np.array([1, 2, 3])
>>> y = keras.ops.convert_to_tensor(x)


def _calculate_scores(self, query, key):
    scores = math_ops.matmul(query, key, transpose_b=True)
    if self.scale is not None:
        scores *= self.scale
    return scores

Calculates attention scores as a query-key dot product.

Args:
query: Query tensor of shape `[batch_size, Tq, dim]`.
key: Key tensor of shape `[batch_size, Tv, dim]`.
Returns:
Tensor of shape `[batch_size, Tq, Tv]`.


def get_scan_stats(self):
    time_spent = time.time()
    return (self._scan_event_count, self._v1_scan_count, self._v1_scan_response_count, self._v2_scan_count, self._device_scan_counts.copy(), (time_spent - self._last_reset_time))

Return the scan event statistics for this adapter

Returns:
int : total scan events
int : total v1 scan count
int : total v1 scan response count
int : total v2 scan count
dict : device-specific scan counts
float : seconds since last reset


def assert_is_compatible_with(self, other):
    if not self.is_compatible_with(other):
        raise ValueError('Shapes %s and %s are incompatible' % (self, other))

Raises exception if `self` and `other` do not represent the same shape.

This method can be used to assert that there exists a shape that both
`self` and `other` represent.

Args:
other: Another TensorShape.

Raises:
ValueError: If `self` and `other` do not represent the same shape.


def eye(size, dtype=None, name=None):
    if dtype is None:
        dtype = floatx()
    tf_dtype = dtypes_module.as_dtype(dtype)
    return variable(linalg_ops.eye(size, dtype=tf_dtype), dtype, name)

Instantiate an identity matrix and returns it.

Args:
size: Integer, number of rows/columns.
dtype: String, data type of returned Keras variable.
name: String, name of returned Keras variable.

Returns:
A Keras variable, an identity matrix.

Example:

>>> kvar = tf.keras.backend.eye(3)
>>> tf.keras.backend.eval(kvar)
array([[1.,  0.,  0.],
[0.,  1.,  0.],
[0.,  0.,  1.]], dtype=float32)


def compare_python_to_reference_murmur3_32(data: Any, seed: int=0) -> None:
    assert mmh3, 'Need mmh3 module'
    c_data = to_str(data)
    c_signed = mmh3.hash(c_data, seed=seed)
    py_data = to_bytes(c_data)
    py_unsigned = murmur3_x86_32(py_data, seed=seed)
    py_signed = twos_comp_to_signed(py_unsigned, n_bits=32)
    preamble = 'Hashing {data} with MurmurHash3/32-bit/seed={seed}'.format(data=repr(data), seed=seed)
    if (c_signed == py_signed):
        print((preamble + ' -> {result}: OK'.format(result=c_signed)))
    else:
        raise AssertionError((preamble + '; mmh3 says {c_data} -> {c_signed}, Python version says {py_data} -> {py_unsigned} = {py_signed}'.format(c_data=repr(c_data), c_signed=c_signed, py_data=repr(py_data), py_unsigned=py_unsigned, py_signed=py_signed)))

Checks the pure Python implementation of 32-bit murmur3 against the
``mmh3`` C-based module.

Args:
data: data to hash
seed: seed

Raises:
AssertionError: if the two calculations don't match


def context(self, name):
    data = self._context(name)
    context = data.get('context')
    if context:
        return context
    assert self.load_path
    context_path = os.path.join(self.load_path, 'contexts', ('%s.rxt' % name))
    context = ResolvedContext.load(context_path)
    data['context'] = context
    data['loaded'] = True
    return context

Get a context.

Args:
name (str): Name to store the context under.

Returns:
`ResolvedContext` object.


def __mul__(self, other):
    try:
        other = as_dimension(other)
    except (TypeError, ValueError):
        return NotImplemented
    if self._value is None or other.value is None:
        return Dimension(None)
    else:
        return Dimension(self._value * other.value)

Returns the product of `self` and `other`.

Dimensions are summed as follows:

```python
tf.compat.v1.Dimension(m)    * tf.compat.v1.Dimension(n)     ==
tf.compat.v1.Dimension(m * n)
tf.compat.v1.Dimension(m)    * tf.compat.v1.Dimension(None)  # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) * tf.compat.v1.Dimension(n)     # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) * tf.compat.v1.Dimension(None)  # equiv. to
tf.compat.v1.Dimension(None)
```

Args:
other: Another Dimension, or a value accepted by `as_dimension`.

Returns:
A Dimension whose value is the product of `self` and `other`.


def valid(self, value, level=[]):

		self.validation_failures = []

		if value is None and self._optional:
			return True

		for i in range(len(self._nodes)):

			if self._nodes[i].valid(value):

				return True

		self.validation_failures.append(('.'.join(level), 'no valid option'))
		return False

Valid

Checks if a value is valid based on the instance's values

Arguments:
value {mixed} -- The value to validate

Returns:
bool


def complement(self, alphabet):

        states = sorted(self.states, key=attrgetter('initial'), reverse=True)
        for state in states:
            if state.final:
                state.final = False
            else:
                state.final = True

Returns the complement of DFA
Args:
alphabet (list): The input alphabet
Returns:
None


def close(self, channel_identifier: ChannelID, partner: Address, balance_hash: BalanceHash, nonce: Nonce, additional_hash: AdditionalHash, signature: Signature, given_block_identifier: BlockSpecification):
    log_details = {'token_network': pex(self.address), 'node': pex(self.node_address), 'partner': pex(partner), 'nonce': nonce, 'balance_hash': encode_hex(balance_hash), 'additional_hash': encode_hex(additional_hash), 'signature': encode_hex(signature)}
    log.debug('closeChannel called', **log_details)
    checking_block = self.client.get_checking_block()
    try:
        self._close_preconditions(channel_identifier, partner=partner, block_identifier=given_block_identifier)
    except NoStateForBlockIdentifier:
        pass
    error_prefix = 'closeChannel call will fail'
    with self.channel_operations_lock[partner]:
        gas_limit = self.proxy.estimate_gas(checking_block, 'closeChannel', channel_identifier=channel_identifier, partner=partner, balance_hash=balance_hash, nonce=nonce, additional_hash=additional_hash, signature=signature)
        if gas_limit:
            error_prefix = 'closeChannel call failed'
            transaction_hash = self.proxy.transact('closeChannel', safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_CLOSE_CHANNEL), channel_identifier=channel_identifier, partner=partner, balance_hash=balance_hash, nonce=nonce, additional_hash=additional_hash, signature=signature)
            self.client.poll(transaction_hash)
            receipt_or_none = check_transaction_threw(self.client, transaction_hash)
        transaction_executed = (gas_limit is not None)
        if ((not transaction_executed) or receipt_or_none):
            if transaction_executed:
                block = receipt_or_none['blockNumber']
            else:
                block = checking_block
            self.proxy.jsonrpc_client.check_for_insufficient_eth(transaction_name='closeChannel', transaction_executed=transaction_executed, required_gas=GAS_REQUIRED_FOR_CLOSE_CHANNEL, block_identifier=block)
            (error_type, msg) = self._check_channel_state_for_close(participant1=self.node_address, participant2=partner, block_identifier=block, channel_identifier=channel_identifier)
            if (not error_type):
                error_type = RaidenUnrecoverableError
            error_msg = f'{error_prefix}. {msg}'
            if (error_type == RaidenRecoverableError):
                log.warning(error_msg, **log_details)
            else:
                log.critical(error_msg, **log_details)
            raise error_type(error_msg)
    log.info('closeChannel successful', **log_details)

Close the channel using the provided balance proof.

Note:
This method must *not* be called without updating the application
state, otherwise the node may accept new transfers which cannot be
used, because the closer is not allowed to update the balance proof
submitted on chain after closing

Raises:
RaidenRecoverableError: If the channel is already closed.
RaidenUnrecoverableError: If the channel does not exist or is settled.


def _handle_error_response(response_body):

    try:
        error_data = json.loads(response_body)
        error_details = '{}: {}'.format(
            error_data['error'],
            error_data.get('error_description'))

    except (KeyError, ValueError):
        error_details = response_body

    raise exceptions.RefreshError(
        error_details, response_body)

Translates an error response into an exception.

Args:
response_body (str): The decoded response data.

Raises:
google.auth.exceptions.RefreshError


async def read_reply(self):
    code = 500
    messages = []
    go_on = True
    while go_on:
        try:
            line = (await self.readline())
        except ValueError as e:
            code = 500
            go_on = False
        else:
            try:
                code = int(line[:3])
            except ValueError as e:
                raise ConnectionResetError('Connection lost.') from e
            else:
                go_on = (line[3:4] == b'-')
        message = line[4:].strip(b' \t\r\n').decode('ascii')
        messages.append(message)
    full_message = '\n'.join(messages)
    return (code, full_message)

Reads a reply from the server.

Raises:
ConnectionResetError: If the connection with the server is lost
(we can't read any response anymore). Or if the server
replies without a proper return code.

Returns:
(int, str): A (code, full_message) 2-tuple consisting of:

- server response code ;
- server response string corresponding to response code
(multiline responses are returned in a single string).


def _generate_assignments(splittable_dimensions, mesh_dimension_to_size):

  assignments = []
  for assignment_size in six.moves.xrange(
      1 + min(len(splittable_dimensions), len(mesh_dimension_to_size))):
    for s_dims_chosen in itertools.combinations(splittable_dimensions,
                                                assignment_size):
      for m_dims_chosen in itertools.permutations(mesh_dimension_to_size,
                                                  assignment_size):
        assignments.append(dict(zip(s_dims_chosen, m_dims_chosen)))
  return assignments

Generates all ways to map splittable dimensions to mesh dimensions.

Args:
splittable_dimensions: a frozenset of the names of splittable dimensions.
mesh_dimension_to_size: a dictionary from mesh dimension name to size.

Returns:
A list of the valid assignments. Each assignment is a dict keyed by every
splittable dimension, whose value is either a mesh dimension or None.


def check_call(state, callstr, argstr=None, expand_msg=None):
    state.assert_is(['function_defs', 'lambda_functions'], 'check_call', ['check_function_def', 'check_lambda_function'])
    if (expand_msg is None):
        expand_msg = 'To verify it, we reran {{argstr}}. '
    (stu_part, _argstr) = build_call(callstr, state.student_parts['node'])
    (sol_part, _) = build_call(callstr, state.solution_parts['node'])
    append_message = {'msg': expand_msg, 'kwargs': {'argstr': (argstr or _argstr)}}
    child = part_to_child(stu_part, sol_part, append_message, state)
    return child

When checking a function definition of lambda function,
prepare has_equal_x for checking the call of a user-defined function.

Args:
callstr (str): call string that specifies how the function should be called, e.g. `f(1, a = 2)`.
``check_call()`` will replace ``f`` with the function/lambda you're targeting.
argstr (str): If specified, this overrides the way the function call is refered to in the expand message.
expand_msg (str): If specified, this overrides any messages that are prepended by previous SCT chains.
state (State): state object that is chained from.

:Example:

Student and solution code::

def my_power(x):
print("calculating sqrt...")
return(x * x)

SCT::

Ex().check_function_def('my_power').multi(
check_call("f(3)").has_equal_value()
check_call("f(3)").has_equal_output()
)


def get_by(self, field, value):

        firmwares = self.get_all()
        matches = []
        for item in firmwares:
            if item.get(field) == value:
                matches.append(item)
        return matches

Gets the list of firmware baseline resources managed by the appliance. Optional parameters can be used to
filter the list of resources returned.

The search is case-insensitive.

Args:
field: Field name to filter.
value: Value to filter.

Returns:
list: List of firmware baseline resources.


def fit(self, mol1, mol2):

        return self.get_rmsd(mol1, mol2) < self._tolerance

Fit two molecules.

Args:
mol1: First molecule. OpenBabel OBMol or pymatgen Molecule object
mol2: Second molecule. OpenBabel OBMol or pymatgen Molecule object

Returns:
A boolean value indicates whether two molecules are the same.


def write_profile(name, repo, token):
    make_sure_folder_exists(CONFIG_FOLDER)
    config = configparser.ConfigParser()
    config.read(CONFIG_FILE)
    profile = {'repo': repo, 'token': token}
    config[name] = profile
    with open(CONFIG_FILE, 'w') as configfile:
        config.write(configfile)
    return profile

Save a profile to the CONFIG_FILE.

After you use this method to save a profile, you can load it anytime
later with the ``read_profile()`` function defined above.

Args:

name
The name of the profile to save.

repo
The Github repo you want to connect to. For instance,
this repo is ``jtpaasch/simplygithub``.

token
A personal access token to connect to the repo. It is
a hash that looks something like ``ff20ae42dc...``

Returns:
A dictionary with the profile's ``repo`` and ``token`` values.


def OpenFile(client_path, max_timestamp=None):
    path_info = data_store.REL_DB.ReadLatestPathInfosWithHashBlobReferences([client_path], max_timestamp=max_timestamp)[client_path]
    if (path_info is None):
        raise FileHasNoContentError(client_path)
    hash_id = rdf_objects.SHA256HashID.FromBytes(path_info.hash_entry.sha256.AsBytes())
    blob_references = data_store.REL_DB.ReadHashBlobReferences([hash_id])[hash_id]
    if (blob_references is None):
        raise MissingBlobReferencesError(('File hash was expected to have corresponding blob references, but they were not found: %r' % hash_id))
    return BlobStream(client_path, blob_references, hash_id)

Opens latest content of a given file for reading.

Args:
client_path: A db.ClientPath object describing path to a file.
max_timestamp: If specified, will open the last collected version with a
timestamp equal or lower than max_timestamp. If not specified, will simply
open the latest version.

Returns:
A file like object with random access support.

Raises:
FileHasNoContentError: if the file was never collected.
MissingBlobReferencesError: if one of the blobs was not found.


def get_text_features(self, input_ids: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, position_ids: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None) -> torch.FloatTensor:
    output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
    output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict
    text_outputs = self.text_model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
    pooled_output = text_outputs[1] if return_dict is not None else text_outputs.pooler_output
    text_features = self.text_projection(pooled_output)
    text_features = F.normalize(text_features, dim=-1)
    return text_features

Returns:
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
applying the projection layer to the pooled output of [`ClapTextModel`].

Examples:

```python
>>> from transformers import AutoTokenizer, ClapModel

>>> model = ClapModel.from_pretrained("laion/clap-htsat-unfused")
>>> tokenizer = AutoTokenizer.from_pretrained("laion/clap-htsat-unfused")

>>> inputs = tokenizer(["the sound of a cat", "the sound of a dog"], padding=True, return_tensors="pt")
>>> text_features = model.get_text_features(**inputs)
```


def read(self, size=None):

    if not self._is_open:
      raise IOError('Not opened.')

    return self._vslvm_logical_volume.read(size)

Reads a byte string from the file-like object at the current offset.

The function will read a byte string of the specified size or
all of the remaining data if no size was specified.

Args:
size (Optional[int]): number of bytes to read, where None is all
remaining data.

Returns:
bytes: data read.

Raises:
IOError: if the read failed.
OSError: if the read failed.


def FindProxies():
    proxies = []
    for i in range(0, 100):
        try:
            sid = winreg.EnumKey(winreg.HKEY_USERS, i)
        except OSError:
            break
        try:
            subkey = (sid + '\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings')
            internet_settings = winreg.OpenKey(winreg.HKEY_USERS, subkey)
            proxy_enable = winreg.QueryValueEx(internet_settings, 'ProxyEnable')[0]
            if proxy_enable:
                proxy_server = str(winreg.QueryValueEx(internet_settings, 'ProxyServer')[0])
                if ('=' in proxy_server):
                    for p in proxy_server.split(';'):
                        (protocol, address) = p.split('=', 1)
                        if (not re.match('^([^/:]+):
                            address = ('%s:
                        proxies.append(address)
                elif (proxy_server[:5] == 'http:'):
                    proxies.append(proxy_server)
                else:
                    proxies.append(('http:
            internet_settings.Close()
        except (OSError, ValueError, TypeError):
            continue
    logging.debug('Found proxy servers: %s', proxies)
    return proxies

Tries to find proxies by interrogating all the user's settings.

This function is a modified urillib.getproxies_registry() from the
standard library. We just store the proxy value in the environment
for urllib to find it.

TODO(user): Iterate through all the possible values if one proxy
fails, in case more than one proxy is specified in different users
profiles.

Returns:
A list of proxies.


def GetTARInfoByPathSpec(self, path_spec):
    location = getattr(path_spec, 'location', None)
    if (location is None):
        raise errors.PathSpecError('Path specification missing location.')
    if (not location.startswith(self.LOCATION_ROOT)):
        raise errors.PathSpecError('Invalid location in path specification.')
    if (len(location) == 1):
        return None
    try:
        return self._tar_file.getmember(location[1:])
    except KeyError:
        pass

Retrieves the TAR info for a path specification.

Args:
path_spec (PathSpec): a path specification.

Returns:
tarfile.TARInfo: TAR info or None if it does not exist.

Raises:
PathSpecError: if the path specification is incorrect.


def import_args_from_dict(value, args, config):
    if isinstance(value, six.string_types):
        for match in TOKEN_REGEX.finditer(str(value)):
            token = match.group(1)
            if (token in args):
                actual_param = args[token]
                if isinstance(actual_param, six.string_types):
                    value = value.replace(('@' + token), args[token])
                else:
                    value = actual_param
    elif isinstance(value, list):
        return [import_args_from_dict(item, args, config) for item in value]
    elif isinstance(value, dict):
        return {key: import_args_from_dict(val, args, config) for (key, val) in value.items()}
    elif isinstance(value, tuple):
        return tuple((import_args_from_dict(val, args, config) for val in value))
    return value

Replaces some arguments by those specified by a key-value dictionary.

This function will be recursively called on a dictionary looking for any
value containing a "$" variable. If found, the value will be replaced
by the attribute in "args" of the same name.

It is used to load arguments from the CLI and any extra configuration
parameters passed in recipes.

Args:
value: The value of a {key: value} dictionary. This is passed recursively
and may change in nature: string, list, or dict. The top-level variable
should be the dictionary that is supposed to be recursively traversed.
args: A {key: value} dictionary used to do replacements.
config: A dftimewolf.Config class containing configuration information

Returns:
The first caller of the function will receive a dictionary in which strings
starting with "@" are replaced by the parameters in args.


def _create_grad_indexed_slices_init(grad_output_slices, forward_input):
    assert isinstance(grad_output_slices, indexed_slices.IndexedSlices)
    assert isinstance(forward_input, tensor.Tensor)
    values_out = grad_output_slices.values
    indices_out = grad_output_slices.indices
    if values_out.shape.is_fully_defined():
        values_shape = tensor_shape.TensorShape([0] + values_out.shape.as_list()[1:])
        values = array_ops.zeros(values_shape, dtype=values_out.dtype, name='values_init')
    else:
        if forward_input.dtype == dtypes.resource:
            forward_shape = gen_resource_variable_ops.variable_shape(forward_input)
        else:
            forward_shape = array_ops.shape(forward_input)
        values_shape = array_ops.concat([[0], forward_shape[1:]], 0)
        values = array_ops.zeros(values_shape, dtype=values_out.dtype, name='values_init')
    indices = constant_op.constant([], indices_out.dtype, name='indices_init')
    if forward_input.dtype == dtypes.resource:
        shape = gen_resource_variable_ops.variable_shape(forward_input, name='shape_init')
    else:
        shape = array_ops.shape(forward_input, name='shape_init')
    return indexed_slices.IndexedSlices(values=values, indices=indices, dense_shape=shape)

Creates an IndexedSlices to pass as input to the while grad function.

Args:
grad_output_slices: IndexedSlices. The corresponding while grad function
output.
forward_input: Tensor. The corresponding input to the forward while op.

Returns:
Zeros IndexedSlices, created in current Graph.


def translations(self, **kwargs):

        path = self._get_id_path('translations')

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

Get the translations for a specific movie id.

Args:
append_to_response: (optional) Comma separated, any movie method.

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


def _numpy_section(line_info):
    next_line_is_hyphens = _line_is_hyphens(line_info.next.stripped)
    if next_line_is_hyphens:
        possible_title = line_info.remaining
        return _section_from_possible_title(possible_title)
    else:
        return None

Checks whether the current line is the start of a new numpy-style section.

Numpy style sections are followed by a full line of hyphens, for example:

Section Name
------------
Section body goes here.

Args:
line_info: Information about the current line.
Returns:
A Section type if one matches, or None if no section type matches.


def get_metrics_result(self):
    return_metrics = {}
    for metric in self.metrics:
        result = metric.result()
        if isinstance(result, dict):
            return_metrics.update(result)
        else:
            return_metrics[metric.name] = result
    return python_utils.pythonify_logs(return_metrics)

Returns the model's metrics values as a dict.

If any of the metric result is a dict (containing multiple metrics),
each of them gets added to the top level returned dict of this method.

Returns:
A `dict` containing values of the metrics listed in `self.metrics`.
Example: `{'loss': 0.2, 'accuracy': 0.7}`.


def contrast(x, severity=1):

  c = [0.4, .3, .2, .1, .05][severity - 1]

  x = np.array(x) / 255.
  means = np.mean(x, axis=(0, 1), keepdims=True)
  x_clip = np.clip((x - means) * c + means, 0, 1) * 255
  return around_and_astype(x_clip)

Change contrast of images.

Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.

Returns:
numpy array, image with uint8 pixels in [0,255]. Changed contrast.


def get(self, report_id):

        return Report(
            self._app,
            self._swimlane.request('get', "reports/{0}".format(report_id)).json()
        )

Retrieve report by ID

Args:
report_id (str): Full report ID

Returns:
Report: Corresponding Report instance


def state(self):
    if not self.has_job:
        return PipelineState.DONE
    self._update_job()
    return self._get_job_state()

Return the current state of the remote job.

Returns:
A PipelineState object.


def _ParseValueData(self, knowledge_base, value_data):

    if not isinstance(value_data, py2to3.UNICODE_TYPE):
      raise errors.PreProcessFail(
          'Unsupported Windows Registry value type: {0:s} for '
          'artifact: {1:s}.'.format(
              type(value_data), self.ARTIFACT_DEFINITION_NAME))

    environment_variable = artifacts.EnvironmentVariableArtifact(
        case_sensitive=False, name=self._NAME, value=value_data)

    try:
      logger.debug('setting environment variable: {0:s} to: "{1:s}"'.format(
          self._NAME, value_data))
      knowledge_base.AddEnvironmentVariable(environment_variable)
    except KeyError:

      pass

Parses Windows Registry value data for a preprocessing attribute.

Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
value_data (object): Windows Registry value data.

Raises:
errors.PreProcessFail: if the preprocessing fails.


def write_file(self, filename, file_format='xyz'):
    mol = pb.Molecule(self._obmol)
    return mol.write(file_format, filename, overwrite=True)

Uses OpenBabel to output all supported formats.

Args:
filename: Filename of file to output
file_format: String specifying any OpenBabel supported formats.


def stitch_map(tiles, width, height, bbox, dpi):

    size = (int(width * dpi_to_dpmm(dpi)), int(height * dpi_to_dpmm(dpi)))
    background = Image.new('RGBA', size, (255, 255, 255))
    for layer in tiles:
        layer_img = Image.new("RGBA", size)
        for (x, y), tile_path in layer.items():
            tile = Image.open(tile_path)
            layer_img.paste(tile, ((x - bbox.min.x) * TILE_SIZE, (y - bbox.min.y) * TILE_SIZE))
        background = Image.alpha_composite(background, layer_img)
    add_scales_bar(background, bbox)
    return background.convert("RGB")

Merge tiles together into one image.

Args:
tiles (list of dict of file): tiles for each layer
width (float): page width in mm
height (height): page height in mm
dpi (dpi): resolution in dots per inch

Returns:
PIL.Image: merged map.


def _InitializeURL(self, upload_url, current_content_length):

    if current_content_length != 0:
      return upload_url

    headers = {
        'Content-Type': 'application/xml',
        'Content-Length': 0,
        'x-goog-resumable': 'start'
    }

    req = urllib2.Request(upload_url, data={}, headers=headers)
    resp = self._url_opener.open(req)

    return resp.headers['location']

Ensures that the URL used to upload operations is properly initialized.

Args:
upload_url: a string url.
current_content_length: an integer identifying the current content length
of data uploaded to the Batch Job.

Returns:
An initialized string URL, or the provided string URL if the URL has
already been initialized.


def set_colour(self, r, g, b):
    if (not (0 <= r <= 255)):
        raise ValueError('The value for red needs to be between 0 and 255.')
    if (not (0 <= g <= 255)):
        raise ValueError('The value for green needs to be between 0 and 255.')
    if (not (0 <= b <= 255)):
        raise ValueError('The value for blue needs to be between 0 and 255.')
    hexvalue = BulbDevice._rgb_to_hexvalue(r, g, b)
    payload = self.generate_payload(SET, {self.DPS_INDEX_MODE: self.DPS_MODE_COLOUR, self.DPS_INDEX_COLOUR: hexvalue})
    data = self._send_receive(payload)
    return data

Set colour of an rgb bulb.

Args:
r(int): Value for the colour red as int from 0-255.
g(int): Value for the colour green as int from 0-255.
b(int): Value for the colour blue as int from 0-255.


async def upload_image(self, image_file, filename=None, *, return_uploaded_image=False):
    image_filename = (filename or os.path.basename(image_file.name))
    image_data = image_file.read()
    res = (await self._base_request(IMAGE_UPLOAD_URL, 'application/x-www-form-urlencoded;charset=UTF-8', 'json', json.dumps({'protocolVersion': '0.8', 'createSessionRequest': {'fields': [{'external': {'name': 'file', 'filename': image_filename, 'put': {}, 'size': len(image_data)}}]}})))
    try:
        upload_url = self._get_upload_session_status(res)['externalFieldTransfers'][0]['putInfo']['url']
    except KeyError:
        raise exceptions.NetworkError('image upload failed: can not acquire an upload url')
    res = (await self._base_request(upload_url, 'application/octet-stream', 'json', image_data))
    try:
        raw_info = self._get_upload_session_status(res)['additionalInfo']['uploader_service.GoogleRupioAdditionalInfo']['completionInfo']['customerSpecificInfo']
        image_id = raw_info['photoid']
        url = raw_info['url']
    except KeyError:
        raise exceptions.NetworkError('image upload failed: can not fetch upload info')
    result = UploadedImage(image_id=image_id, url=url)
    return (result if return_uploaded_image else result.image_id)

Upload an image that can be later attached to a chat message.

Args:
image_file: A file-like object containing an image.
filename (str): (optional) Custom name for the uploaded file.
return_uploaded_image (bool): (optional) If True, return
:class:`.UploadedImage` instead of image ID. Defaults to False.

Raises:
hangups.NetworkError: If the upload request failed.

Returns:
:class:`.UploadedImage` instance, or ID of the uploaded image.


def compute_advantages(rollout, last_r, gamma=0.9, lambda_=1.0, use_gae=True):
    traj = {}
    trajsize = len(rollout[SampleBatch.ACTIONS])
    for key in rollout:
        traj[key] = np.stack(rollout[key])
    if use_gae:
        assert (SampleBatch.VF_PREDS in rollout), 'Values not found!'
        vpred_t = np.concatenate([rollout[SampleBatch.VF_PREDS], np.array([last_r])])
        delta_t = ((traj[SampleBatch.REWARDS] + (gamma * vpred_t[1:])) - vpred_t[:(- 1)])
        traj[Postprocessing.ADVANTAGES] = discount(delta_t, (gamma * lambda_))
        traj[Postprocessing.VALUE_TARGETS] = (traj[Postprocessing.ADVANTAGES] + traj[SampleBatch.VF_PREDS]).copy().astype(np.float32)
    else:
        rewards_plus_v = np.concatenate([rollout[SampleBatch.REWARDS], np.array([last_r])])
        traj[Postprocessing.ADVANTAGES] = discount(rewards_plus_v, gamma)[:(- 1)]
        traj[Postprocessing.VALUE_TARGETS] = np.zeros_like(traj[Postprocessing.ADVANTAGES])
    traj[Postprocessing.ADVANTAGES] = traj[Postprocessing.ADVANTAGES].copy().astype(np.float32)
    assert all(((val.shape[0] == trajsize) for val in traj.values())), 'Rollout stacked incorrectly!'
    return SampleBatch(traj)

Given a rollout, compute its value targets and the advantage.

Args:
rollout (SampleBatch): SampleBatch of a single trajectory
last_r (float): Value estimation for last observation
gamma (float): Discount factor.
lambda_ (float): Parameter for GAE
use_gae (bool): Using Generalized Advantage Estamation

Returns:
SampleBatch (SampleBatch): Object with experience from rollout and
processed rewards.


def plot_spectra_pages_pdf(ss, pdf_filename='pages.pdf', setup=_default_setup):

    logger = a99.get_python_logger()
    xmin, xmax, ymin_, ymax, xspan, yspan = calc_max_min(ss)
    ymin = ymin_ if setup.ymin is None else setup.ymin
    num_pages = len(ss)
    a99.format_BLB()
    pdf = matplotlib.backends.backend_pdf.PdfPages(pdf_filename)
    for i, s in enumerate(ss):
        title = s.title
        fig = plt.figure()
        plt.plot(s.x, s.y, c=_FAV_COLOR)
        if setup.flag_xlabel and setup.fmt_xlabel:
            _set_plot(plt.xlabel, setup.fmt_xlabel, s)
        if setup.flag_ylabel and setup.fmt_ylabel:
            _set_plot(plt.ylabel, setup.fmt_ylabel, s)
        _set_plot(plt.title, setup.fmt_title, s)
        plt.xlim([xmin-xspan*_T, xmax+xspan*_T])
        plt.ylim([ymin-yspan*_T, ymax+yspan*_T])
        plt.tight_layout()
        plt.subplots_adjust(top=0.94)
        logger.info("Printing page {0:d}/{1:d} ('{2!s}')".format(i+1, num_pages, title))
        pdf.savefig(fig)
        plt.close()
    pdf.close()
    logger.info("File {0!s} successfully created.".format(pdf_filename))

Plots spectra into a PDF file, one spectrum per page.

Splits into several pieces of width

Args:
ss: list of Spectrum objects
pdf_filename: name of output file


def address(self, ip, owner=None, **kwargs):

        return Address(self.tcex, ip, owner=owner, **kwargs)

Create the Address TI object.

Args:
owner:
ip:
**kwargs:

Return:


def __set_proxy(self, config):

        if "proxy" in config and config["proxy"]:
            proxy = config["proxy"]
            splitted = proxy.split(':')
            if len(splitted) != 2:
                raise ValueError(ONEVIEW_CLIENT_INVALID_PROXY)

            proxy_host = splitted[0]
            proxy_port = int(splitted[1])
            self.__connection.set_proxy(proxy_host, proxy_port)

Set proxy if needed
Args:
config: Config dict


def get_static_batch_size(layer):
    batch_input_shape, _ = get_input_shape_and_dtype(layer)
    if batch_input_shape is not None:
        return tensor_shape.Dimension(batch_input_shape[0]).value
    return None

Gets the static batch size of a Layer.

Args:
layer: a `Layer` instance.

Returns:
The static batch size of a Layer.


def FindUnspentCoinsByAsset(self, asset_id, from_addr=None, use_standard=False, watch_only_val=0):
    coins = self.FindUnspentCoins(from_addr=from_addr, use_standard=use_standard, watch_only_val=watch_only_val)
    return [coin for coin in coins if (coin.Output.AssetId == asset_id)]

Finds unspent coin objects in the wallet limited to those of a certain asset type.

Args:
asset_id (UInt256): a bytearray (len 32) representing an asset on the blockchain.
from_addr (UInt160): a bytearray (len 20) representing an address.
use_standard (bool): whether or not to only include standard contracts ( i.e not a smart contract addr ).
watch_only_val (int): a flag ( 0 or 64 ) indicating whether or not to find coins that are in 'watch only' addresses.

Returns:
list: a list of ``neo.Wallet.Coin`` in the wallet that are not spent


def run(self, samples=1000, chains=1, **kwargs):

        self.fit = self.stan_model.sampling(data=self.X, iter=samples,
                                            chains=chains, **kwargs)
        return self._convert_to_results()

Run the Stan sampler.
Args:
samples (int): Number of samples to obtain (in each chain).
chains (int): Number of chains to use.
kwargs (dict): Optional keyword arguments passed onto the PyStan
StanModel.sampling() call.
Returns: A PyMC3ModelResults instance.


def pad_image(self, image: np.ndarray, pad_size: Optional[Dict[str, int]]=None, constant_values: Union[float, Iterable[float]]=0, pad_mode: PaddingMode=PaddingMode.CONSTANT, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, **kwargs):
    height, width = get_image_size(image, channel_dim=input_data_format)
    max_height = pad_size.get('height', height)
    max_width = pad_size.get('width', width)
    pad_right, pad_bottom = (max_width - width, max_height - height)
    if pad_right < 0 or pad_bottom < 0:
        raise ValueError('The padding size must be greater than image size')
    padding = ((0, pad_bottom), (0, pad_right))
    padded_image = pad(image, padding, mode=pad_mode, constant_values=constant_values, data_format=data_format, input_data_format=input_data_format)
    return padded_image

Pad an image with zeros to the given size.

Args:
image (`np.ndarray`):
Image to pad.
pad_size (`Dict[str, int]`)
Size of the output image with pad.
constant_values (`Union[float, Iterable[float]]`)
The fill value to use when padding the image.
pad_mode (`PaddingMode`)
The pad mode, default to PaddingMode.CONSTANT
data_format (`ChannelDimension` or `str`, *optional*)
The channel dimension format of the image. If not provided, it will be the same as the input image.
input_data_format (`ChannelDimension` or `str`, *optional*):
The channel dimension format of the input image. If not provided, it will be inferred.


def _linop_inverse(self) -> 'LinearOperatorBlockLowerTriangular':
    if len(self.operators) == 1:
        return LinearOperatorBlockLowerTriangular([[self.operators[0][0].inverse()]], is_non_singular=self.is_non_singular, is_self_adjoint=self.is_self_adjoint, is_positive_definite=self.is_positive_definite, is_square=True)
    blockwise_dim = len(self.operators)
    upper_left_inverse = LinearOperatorBlockLowerTriangular(self.operators[:-1]).inverse()
    bottom_row = self.operators[-1]
    bottom_right_inverse = bottom_row[-1].inverse()
    inverse_bottom_row = []
    for i in range(blockwise_dim - 1):
        blocks = []
        for j in range(i, blockwise_dim - 1):
            result = bottom_row[j].matmul(upper_left_inverse.operators[j][i])
            if not any((isinstance(result, op_type) for op_type in linear_operator_addition.SUPPORTED_OPERATORS)):
                result = linear_operator_full_matrix.LinearOperatorFullMatrix(result.to_dense())
            blocks.append(result)
        summed_blocks = linear_operator_addition.add_operators(blocks)
        assert len(summed_blocks) == 1
        block = summed_blocks[0]
        block = bottom_right_inverse.matmul(block)
        block = linear_operator_identity.LinearOperatorScaledIdentity(num_rows=bottom_right_inverse.domain_dimension_tensor(), multiplier=math_ops.cast(-1, dtype=block.dtype)).matmul(block)
        inverse_bottom_row.append(block)
    inverse_bottom_row.append(bottom_right_inverse)
    return LinearOperatorBlockLowerTriangular(upper_left_inverse.operators + [inverse_bottom_row], is_non_singular=self.is_non_singular, is_self_adjoint=self.is_self_adjoint, is_positive_definite=self.is_positive_definite, is_square=True)

Inverse of LinearOperatorBlockLowerTriangular.

We recursively apply the identity:

```none
|A 0|'  =  |    A'  0|
|B C|      |-C'BA' C'|
```

where `A` is n-by-n, `B` is m-by-n,
`C` is m-by-m, and `'` denotes inverse.

This identity can be verified through multiplication:

```none
|A 0||    A'  0|
|B C||-C'BA' C'|

= |       AA'   0|
|BA'-CC'BA' CC'|

= |I 0|
|0 I|
```
Returns:
A 'LinearOperatorBlockLowerTriangular'.


def run(inputs, program, outputs):

  root = tempfile.mkdtemp()
  try:
    cwd = os.getcwd()
    for fake, real in inputs:
      parent = os.path.join(root, os.path.dirname(fake))
      if not os.path.exists(parent):
        os.makedirs(parent)

      if hasattr(os, 'symlink') and not os.name == 'nt':
        os.symlink(os.path.join(cwd, real), os.path.join(root, fake))
      else:
        shutil.copyfile(os.path.join(cwd, real), os.path.join(root, fake))
    if subprocess.call(program + [root]) != 0:
      return 1
    for fake, real in outputs:
      shutil.copyfile(os.path.join(root, fake), real)
    return 0
  finally:
    try:
      shutil.rmtree(root)
    except EnvironmentError:

      pass

Creates temp symlink tree, runs program, and copies back outputs.

Args:
inputs: List of fake paths to real paths, which are used for symlink tree.
program: List containing real path of program and its arguments. The
execroot directory will be appended as the last argument.
outputs: List of fake outputted paths to copy back to real paths.
Returns:
0 if succeeded or nonzero if failed.


def play_from_queue(self, index, start=True):

        if not self.speaker_info:
            self.get_speaker_info()

        uri = 'x-rincon-queue:{0}
        self.avTransport.SetAVTransportURI([
            ('InstanceID', 0),
            ('CurrentURI', uri),
            ('CurrentURIMetaData', '')
        ])

        self.avTransport.Seek([
            ('InstanceID', 0),
            ('Unit', 'TRACK_NR'),
            ('Target', index + 1)
        ])

        if start:
            self.play()

Play a track from the queue by index.

The index number is required as an argument, where the first index
is 0.

Args:
index (int): 0-based index of the track to play
start (bool): If the item that has been set should start playing


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

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

Adds a data center resource based upon the attributes specified.

Args:
information: Data center information
timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.

Returns:
dict: Added data center.


def _make_gh_link_node(app, rawtext, role, kind, api_type, id, options=None):

    url = "%s/%s/%s" % (_BOKEH_GH, api_type, id)
    options = options or {}
    set_classes(options)
    node = nodes.reference(
        rawtext, kind + utils.unescape(id), refuri=url, **options)
    return node

Return a link to a Bokeh Github resource.

Args:
app (Sphinx app) : current app
rawtext (str) : text being replaced with link node.
role (str) : role name
kind (str) : resource type (issue, pull, etc.)
api_type (str) : type for api link
id : (str) : id of the resource to link to
options (dict) : options dictionary passed to role function


def __gt__(self, other):
    other = as_dimension(other)
    if self._value is None or other.value is None:
        return None
    else:
        return self._value > other.value

Returns True if `self` is known to be greater than `other`.

Dimensions are compared as follows:

```python
(tf.compat.v1.Dimension(m)    > tf.compat.v1.Dimension(n))    == (m > n)
(tf.compat.v1.Dimension(m)    > tf.compat.v1.Dimension(None)) == None
(tf.compat.v1.Dimension(None) > tf.compat.v1.Dimension(n))    == None
(tf.compat.v1.Dimension(None) > tf.compat.v1.Dimension(None)) == None
```

Args:
other: Another Dimension.

Returns:
The value of `self.value > other.value` if both are known, otherwise
None.