def pairwise_alignment_stats(reference_seq_aln, other_seq_aln):

    if len(reference_seq_aln) != len(other_seq_aln):
        raise ValueError('Sequence lengths not equal - was an alignment run?')

    reference_seq_aln = ssbio.protein.sequence.utils.cast_to_str(reference_seq_aln)
    other_seq_aln = ssbio.protein.sequence.utils.cast_to_str(other_seq_aln)

    infodict = {}

    stats_percent_ident = get_percent_identity(a_aln_seq=reference_seq_aln, b_aln_seq=other_seq_aln)
    infodict['percent_identity'] = stats_percent_ident

    aln_df = get_alignment_df(a_aln_seq=reference_seq_aln, b_aln_seq=other_seq_aln)
    infodict['deletions'] = get_deletions(aln_df)
    infodict['insertions'] = get_insertions(aln_df)
    infodict['mutations'] = get_mutations(aln_df)
    infodict['unresolved'] = get_unresolved(aln_df)

    return infodict

Get a report of a pairwise alignment.

Args:
reference_seq_aln (str, Seq, SeqRecord): Reference sequence, alignment form
other_seq_aln (str, Seq, SeqRecord): Other sequence, alignment form

Returns:
dict: Dictionary of information on mutations, insertions, sequence identity, etc.


def d_step(self, true_frames, gen_frames):
    hparam_to_disc_loss = {'least_squares': gan_losses.least_squares_discriminator_loss, 'cross_entropy': gan_losses.modified_discriminator_loss, 'wasserstein': gan_losses.wasserstein_discriminator_loss}
    (_, batch_size, _, _, _) = common_layers.shape_list(true_frames)
    all_frames = tf.concat([true_frames, tf.stop_gradient(gen_frames)], axis=1)
    all_logits = self.discriminator(all_frames)
    (true_logits, fake_logits_stop) = (all_logits[:batch_size], all_logits[batch_size:])
    mean_true_logits = tf.reduce_mean(true_logits)
    tf.summary.scalar('mean_true_logits', mean_true_logits)
    mean_fake_logits_stop = tf.reduce_mean(fake_logits_stop)
    tf.summary.scalar('mean_fake_logits_stop', mean_fake_logits_stop)
    discriminator_loss_func = hparam_to_disc_loss[self.hparams.gan_loss]
    gan_d_loss = discriminator_loss_func(discriminator_real_outputs=true_logits, discriminator_gen_outputs=fake_logits_stop, add_summaries=True)
    return (gan_d_loss, true_logits, fake_logits_stop)

Performs the discriminator step in computing the GAN loss.

Applies stop-gradient to the generated frames while computing the
discriminator loss to make sure that the gradients are not back-propagated
to the generator. This makes sure that only the discriminator is updated.

Args:
true_frames: True outputs
gen_frames: Generated frames.
Returns:
d_loss: Loss component due to the discriminator.


def _generate_matrix(self, hash_bytes):

        half_columns = self.columns
        cells = self.rows * half_columns

        matrix = [[False] * self.columns for _ in range(self.rows)]

        for cell in range(cells):

            if self._get_bit(cell, hash_bytes[1:]):

                column = cell
                row = cell % self.rows

                matrix[row][column] = True
                matrix[row][self.columns - column - 1] = True

        return matrix

Generates matrix that describes which blocks should be coloured.

Arguments:
hash_bytes - List of hash byte values for which the identicon is being
generated. Each element of the list should be an integer from 0 to
255.

Returns:
List of rows, where each element in a row is boolean. True means the
foreground colour should be used, False means a background colour
should be used.


def push(self, x):
    raise NotImplementedError()

Push a new value to the tracker.

Args:
x: The value to be pushed.


def _broadcast(value, target):
    return tf.broadcast_to(tf.convert_to_tensor(value=value, dtype=target.dtype), distribution_util.prefer_static_shape(target)[:(- 1)])

Broadcast a value to match the batching dimensions of a target.

If necessary the value is converted into a tensor. Both value and target
should be of the same dtype.

Args:
value: A value to broadcast.
target: A `Tensor` of shape [b1, ..., bn, d].

Returns:
A `Tensor` of shape [b1, ..., bn] and same dtype as the target.


def __init__(self, request, scalars_plugin_instance):

    self._request = request
    self._scalars_plugin_instance = scalars_plugin_instance

Constructor.

Args:
request: A ListSessionGroupsRequest protobuf.
scalars_plugin_instance: A scalars_plugin.ScalarsPlugin.


def save_libsvm(X, y, path):

    dump_svmlight_file(X, y, path, zero_based=False)

Save data as a LibSVM file.

Args:
X (numpy or scipy sparse matrix): Data matrix
y (numpy array): Target vector.
path (str): Path to the CSV file to save data.


async def wasSet(self, node, oldv):

        for func in self.onsets:
            try:
                await s_coro.ornot(func, node, oldv)
            except asyncio.CancelledError:
                raise
            except Exception:
                logger.exception('onset() error for %s' % (self.full,))

Fire the onset() handlers for this property.

Args:
node (synapse.lib.node.Node): The node whose property was set.
oldv (obj): The previous value of the property.


def from_dict(self, dictionary):
    for (remote_name, remote_value) in dictionary.items():
        local_name = next((name for (name, attribute) in self._attributes.items() if (attribute.remote_name == remote_name)), None)
        if local_name:
            setattr(self, local_name, remote_value)
        else:
            pass

Sets all the exposed ReST attribues from the given dictionary

Args:
dictionary (dict): dictionnary containing the raw object attributes and their values.

Example:
>>> info = {"name": "my group", "private": False}
>>> group = NUGroup()
>>> group.from_dict(info)
>>> print "name: %s - private: %s" % (group.name, group.private)
"name: my group - private: False"


def sparse(self, rows: np.ndarray=None, cols: np.ndarray=None, layer: str=None) -> scipy.sparse.coo_matrix:
    if (layer is None):
        return self.layers[''].sparse(rows=rows, cols=cols)
    else:
        return self.layers[layer].sparse(rows=rows, cols=cols)

Return the main matrix or specified layer as a scipy.sparse.coo_matrix, without loading dense matrix in RAM

Args:
rows:		Rows to include, or None to include all
cols:		Columns to include, or None to include all
layer:		Layer to return, or None to return the default layer

Returns:
Sparse matrix (:class:`scipy.sparse.coo_matrix`)


def compile_from_config(self, config):
    has_overridden_compile = self.__class__.compile != Trainer.compile
    if has_overridden_compile:
        warnings.warn("`compile()` was not called as part of model loading because the model's `compile()` method is custom. All subclassed Models that have `compile()` overridden should also override `get_compile_config()` and `compile_from_config(config)`. Alternatively, you can call `compile()` manually after loading.", stacklevel=2)
        return
    config = serialization_lib.deserialize_keras_object(config)
    self.compile(**config)
    if hasattr(self, 'optimizer') and self.built:
        self.optimizer.build(self.trainable_variables)

Compiles the model with the information given in config.

This method uses the information in the config (optimizer, loss,
metrics, etc.) to compile the model.

Args:
config: Dict containing information for compiling the model.


def custom_returnvalue(self, printer, desc=None):

        self.return_info = ReturnInfo(None, printer, True, desc)

Use a custom function to print the return value.

Args:
printer (callable): A function that should take in the return
value and convert it to a string.
desc (str): An optional description of the return value.


def assert_existing_objects_matched(self):
    for node_id, node in enumerate(self._checkpoint.object_graph_proto.nodes):
        trackable = self._checkpoint.object_by_proto_id.get(node_id, None)
        if trackable is not None and trackable._update_uid < self._checkpoint.restore_uid:
            raise AssertionError(f'Object {node} not assigned a value from checkpoint.')
    for trackable_object in util.list_objects(self._object_graph_view, self._options.experimental_skip_slot_variables):
        if isinstance(trackable_object, data_structures.TrackableDataStructure) and (not trackable_object._trackable_children(save_type=base.SaveType.CHECKPOINT)):
            continue
        self._checkpoint.all_python_objects.add(trackable_object)
    unused_python_objects = object_identity.ObjectIdentitySet(_objects_with_attributes(self._checkpoint.all_python_objects)) - object_identity.ObjectIdentitySet(self._checkpoint.object_by_proto_id.values())
    if unused_python_objects:
        num_unused_python_objects = len(list(unused_python_objects))
        num_variables_to_show = min(10, num_unused_python_objects)
        raise AssertionError(f'Found {num_unused_python_objects} Python objects that were not bound to checkpointed values, likely due to changes in the Python program. Showing {num_variables_to_show} of {num_unused_python_objects} unmatched objects: {list(unused_python_objects)[:num_variables_to_show]}')
    return self

Asserts that trackable Python objects have been matched.

Note that this is a weaker assertion than `assert_consumed`. It will only
fail for existing Python objects which are (transitive) dependencies of the
root object and which do not have an entry in the checkpoint.

It will not fail, for example, if a `tf.keras.Layer` object has not yet been
built and so has not created any `tf.Variable` objects.

Returns:
`self` for chaining.

Raises:
AssertionError: If a Python object exists in the transitive dependencies
of the root object but does not have a value in the checkpoint.


def mtr_lm_dense(sz):

  n = 2 ** sz
  hparams = mtf_unitransformer_base()
  hparams.d_model = 1024
  hparams.max_length = 1024
  hparams.batch_size = 128

  hparams.num_hidden_layers = 6
  hparams.d_ff = 8192 * n
  hparams.d_kv = 256
  hparams.num_heads = 8 * n
  hparams.learning_rate_decay_steps = 65536
  hparams.layout = "batch:batch;vocab:model;d_ff:model;heads:model"
  hparams.mesh_shape = "batch:32"
  return hparams

Series of architectures for language modeling.

We assume infinite training data, so no dropout necessary.

You can use languagemodel_wiki_noref_v32k_l1k.
(1 epoch = ~46000 steps).
TODO(noam): find a large enough dataset for these experiments.

Args:
sz: an integer

Returns:
a hparams


def _fulfillment_from_details(data, _depth=0):

    if _depth == 100:
        raise ThresholdTooDeep()

    if data['type'] == 'ed25519-sha-256':
        public_key = base58.b58decode(data['public_key'])
        return Ed25519Sha256(public_key=public_key)

    if data['type'] == 'threshold-sha-256':
        threshold = ThresholdSha256(data['threshold'])
        for cond in data['subconditions']:
            cond = _fulfillment_from_details(cond, _depth+1)
            threshold.add_subfulfillment(cond)
        return threshold

    raise UnsupportedTypeError(data.get('type'))

Load a fulfillment for a signing spec dictionary

Args:
data: tx.output[].condition.details dictionary


def _randomInts(self, shape, low, high):
    val = np.random.randint(low=low, high=high, size=shape)
    return constant_op.constant(val, dtype=dtypes.int32)

Generate a tensor of random 32-bit integer values.

Note that we use numpy to generate random numbers and then feed the result
through a constant op to avoid the re-rolling of TensorFlow random ops on
each run in graph mode.

Args:
shape: The output shape.
low: Lower bound of random numbers generated, inclusive.
high: Upper bound of random numbers generated, exclusive.

Returns:
A random tensor


def generate_pyi(src, options=None, loader=None):
    options = options or config.Options.create()
    ret = generate_pyi_ast(src, options, loader)
    return (ret, _output_ast(ret.ast, options))

Run the inferencer on a string of source code, producing output.

Args:
src: The source code.
options: config.Options object.
loader: A load_pytd.Loader instance.

Returns:
A tuple, (analyze.Analysis, pyi ast as string).

Raises:
CompileError: If we couldn't parse the input file.
UsageError: If the input filepath is invalid.


def create_subtask(self, cor, name=None, stop_timeout=1.0):
    if self.stopped:
        raise InternalError('Cannot add a subtask to a parent that is already stopped')
    subtask = BackgroundTask(cor, name, loop=self._loop, stop_timeout=stop_timeout)
    self.add_subtask(subtask)
    return subtask

Create and add a subtask from a coroutine.

This function will create a BackgroundTask and then
call self.add_subtask() on it.

Args:
cor (coroutine): The coroutine that should be wrapped
in a background task.
name (str): An optional name for the task.
stop_timeout (float): The maximum time to wait for this
subtask to die after stopping it.

Returns:
Backgroundtask: The created subtask.


def _format_csv(content, delimiter):
    reader = csv_reader(StringIO(content), delimiter=builtin_str(delimiter))
    rows = [row for row in reader]
    max_widths = [max(map(len, column)) for column in zip(*rows)]
    lines = [' '.join(('{entry:{width}}'.format(entry=entry, width=(width + 2)) for (entry, width) in zip(row, max_widths))) for row in rows]
    return '\n'.join(lines)

Format delimited text to have same column width.

Args:
content (str): The content of a metric.
delimiter (str): Value separator

Returns:
str: Formatted content.

Example:

>>> content = (
"value_mse,deviation_mse,data_set\n"
"0.421601,0.173461,train\n"
"0.67528,0.289545,testing\n"
"0.671502,0.297848,validation\n"
)
>>> _format_csv(content, ",")

"value_mse  deviation_mse   data_set\n"
"0.421601   0.173461        train\n"
"0.67528    0.289545        testing\n"
"0.671502   0.297848        validation\n"


def make(self, path, metadata=None):
    if self.mode != 'w':
        raise ValueError('`make` is only allowed in write mode.')
    if not isinstance(metadata, (dict, type(None))):
        raise ValueError(f'`metadata` should be a dict or `None`. Received: {metadata}')
    self._h5_entry_path = path
    if metadata:
        self._create_h5_group(path, metadata=metadata)
    else:
        self._h5_entry_group = {}
        self._h5_entry_initialized = False
    return self

Make a new H5 entry group.

This method is only available in write mode. It defers the creation of
the H5 entry group until `__setitem__` is called, preventing the
creation of empty groups.

Args:
path: `str`. The variable path.
metadata: Optional `dict`. The metadata to save with the H5 entry
group. Defaults to `None`.


def limit_replace(self, accountID, orderID, **kwargs):

        return self.replace(
            accountID,
            orderID,
            order=LimitOrderRequest(**kwargs)
        )

Shortcut to replace a pending Limit Order in an Account

Args:
accountID : The ID of the Account
orderID : The ID of the Limit Order to replace
kwargs : The arguments to create a LimitOrderRequest

Returns:
v20.response.Response containing the results from submitting
the request


def sg_cast(tensor, opt):
    r
    assert opt.dtype is not None, 'dtype is mandatory.'
    return tf.cast(tensor, opt.dtype, name=opt.name)

r"""Casts a tensor to a new type.

See `tf.cast()` in tensorflow.

Args:
tensor: A `Tensor` or `SparseTensor` (automatically given by chain).
opt:
dtype : The destination type.
name : If provided, it replaces current tensor's name

Returns:
A `Tensor` or `SparseTensor` with same shape as `tensor`.


def _read_tags(self):
    tags = self._config.get('tags', {})
    logging.info('Tags:')
    for tag_name in tags.keys():
        tag = {}
        tag['Key'] = tag_name
        tag['Value'] = tags[tag_name]
        self._tags.append(tag)
        logging.info('{} = {}'.format(tag_name, tags[tag_name]))
    logging.debug(json.dumps(self._tags, indent=2, sort_keys=True))
    return True

Fill in the _tags dict from the tags file.

Args:
None

Returns:
True

Todo:
Figure what could go wrong and at least acknowledge the
the fact that Murphy was an optimist.


def _create_hparam_extractor(hparam_name):

  def extractor_fn(session_group):
    if hparam_name in session_group.hparams:
      return _value_to_python(session_group.hparams[hparam_name])
    return None

  return extractor_fn

Returns an extractor function that extracts an hparam from a session group.

Args:
hparam_name: str. Identies the hparam to extract from the session group.
Returns:
A function that takes a tensorboard.hparams.SessionGroup protobuffer and
returns the value, as a native Python object, of the hparam identified by
'hparam_name'.


def _internal_kv_put(key, value, overwrite=False):
    worker = ray.worker.get_global_worker()
    if (worker.mode == ray.worker.LOCAL_MODE):
        exists = (key in _local)
        if ((not exists) or overwrite):
            _local[key] = value
        return exists
    if overwrite:
        updated = worker.redis_client.hset(key, 'value', value)
    else:
        updated = worker.redis_client.hsetnx(key, 'value', value)
    return (updated == 0)

Globally associates a value with a given binary key.

This only has an effect if the key does not already have a value.

Returns:
already_exists (bool): whether the value already exists.


def _compile_control_flow_expression(self, expr: Expression, scope: Dict[(str, TensorFluent)], batch_size: Optional[int]=None, noise: Optional[List[tf.Tensor]]=None) -> TensorFluent:
    etype = expr.etype
    args = expr.args
    if (etype[1] == 'if'):
        condition = self._compile_expression(args[0], scope, batch_size, noise)
        true_case = self._compile_expression(args[1], scope, batch_size, noise)
        false_case = self._compile_expression(args[2], scope, batch_size, noise)
        fluent = TensorFluent.if_then_else(condition, true_case, false_case)
    else:
        raise ValueError('Invalid control flow expression:\n{}'.format(expr))
    return fluent

Compile a control flow expression `expr` into a TensorFluent
in the given `scope` with optional batch size.

Args:
expr (:obj:`rddl2tf.expr.Expression`): A RDDL control flow expression.
scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope.
batch_size (Optional[size]): The batch size.

Returns:
:obj:`rddl2tf.fluent.TensorFluent`: The compiled expression as a TensorFluent.


def __init__(self, rom_path):

        rom = ROM(rom_path)

        if rom.prg_rom_size == 0:
            raise ValueError('ROM has no PRG-ROM banks.')

        if rom.has_trainer:
            raise ValueError('ROM has trainer. trainer is not supported.')

        _ = rom.prg_rom

        _ = rom.chr_rom

        if rom.is_pal:
            raise ValueError('ROM is PAL. PAL is not supported.')

        elif rom.mapper not in {0, 1, 2, 3}:
            msg = 'ROM has an unsupported mapper number {}.'
            raise ValueError(msg.format(rom.mapper))

        self.np_random = np.random.RandomState()

        self._rom_path = rom_path

        self._env = _LIB.Initialize(self._rom_path)

        self.viewer = None

        self._has_backup = False

        self.done = True

        self.controllers = [self._controller_buffer(port) for port in range(2)]
        self.screen = self._screen_buffer()
        self.ram = self._ram_buffer()

Create a new NES environment.

Args:
rom_path (str): the path to the ROM for the environment

Returns:
None


def ParseRecord(self, parser_mediator, key, structure):

    if key not in (
        'log_entry', 'log_entry_at_end', 'log_entry_offset',
        'log_entry_offset_at_end'):
      raise errors.ParseError(
          'Unable to parse record, unknown structure: {0:s}'.format(key))

    try:
      date_time_string = self._GetISO8601String(structure)
    except ValueError as exception:
      parser_mediator.ProduceExtractionWarning(
          'unable to determine date time string with error: {0!s}'.format(
              exception))

    fraction_of_second_length = len(structure.fraction_of_second)
    if fraction_of_second_length == 3:
      date_time = dfdatetime_time_elements.TimeElementsInMilliseconds()
    elif fraction_of_second_length in (6, 7):
      date_time = dfdatetime_time_elements.TimeElementsInMicroseconds()

    try:
      date_time.CopyFromStringISO8601(date_time_string)
    except ValueError as exception:
      parser_mediator.ProduceExtractionWarning(
          'unable to parse date time value: {0:s} with error: {1!s}'.format(
              date_time_string, exception))
      return

    event_data = SCCMLogEventData()
    event_data.component = structure.component

    event_data.offset = 0
    event_data.text = structure.text

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

Parse the record and return an SCCM log event object.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
key (str): name of the parsed structure.
structure (pyparsing.ParseResults): structure of tokens derived from
a line of a text file.

Raises:
ParseError: when the structure type is unknown.


def add_snippet_client(self, name, package):

        if name in self._snippet_clients:
            raise Error(
                self,
                'Name "%s" is already registered with package "%s", it cannot '
                'be used again.' %
                (name, self._snippet_clients[name].client.package))

        for snippet_name, client in self._snippet_clients.items():
            if package == client.package:
                raise Error(
                    self,
                    'Snippet package "%s" has already been loaded under name'
                    ' "%s".' % (package, snippet_name))
        client = snippet_client.SnippetClient(package=package, ad=self._device)
        client.start_app_and_connect()
        self._snippet_clients[name] = client

Adds a snippet client to the management.

Args:
name: string, the attribute name to which to attach the snippet
client. E.g. `name='maps'` attaches the snippet client to
`ad.maps`.
package: string, the package name of the snippet apk to connect to.

Raises:
Error, if a duplicated name or package is passed in.


def groups(self, group_type=None, filters=None, params=None):

        group = self._tcex.ti.group(group_type)
        for g in self.tc_requests.groups_from_tag(group, self.name, filters=filters, params=params):
            yield g

Gets all groups from a tag.

Args:
filters:
params:
group_type:


def load(cls, pkid_or_path=None):

        path = pkid_or_path
        if isinstance(path, (int, np.int32, np.int64)):
            raise NotImplementedError('Lookup via CMS not implemented.')
        elif not os.path.isfile(path):
            raise FileNotFoundError('File {} not found.'.format(path))
        kwargs = {}
        fields = defaultdict(dict)
        with pd.HDFStore(path) as store:
            for key in store.keys():
                if 'kwargs' in key:
                    kwargs.update(store.get_storer(key).attrs.metadata)
                elif "FIELD" in key:
                    name, dname = "_".join(key.split("_")[1:]).split("/")
                    dname = dname.replace('values', '')
                    fields[name][dname] = store[key]
                else:
                    name = str(key[1:])
                    kwargs[name] = store[key]
        for name, field_data in fields.items():
            fps = field_data.pop('data')
            kwargs[name] = Field(fps, field_values=[field_data[str(arr)] for arr in
                                                    sorted(map(int, field_data.keys()))])
        return cls(**kwargs)

Load a container object from a persistent location or file path.

Args:
pkid_or_path: Integer pkid corresponding to the container table or file path

Returns:
container: The saved container object


def export_as_package(self, package_path, cv_source):

        if os.path.exists(package_path):
            raise exceptions.UserError('{} already exists'.format(package_path))

        package_name = os.path.basename(os.path.normpath(package_path))

        os.makedirs(package_path)

        with open(os.path.join(package_path, '__init__.py'), 'wb') as f:
            f.write('from {}.builder import xcessiv_ensemble'.format(package_name).encode('utf8'))

        os.makedirs(os.path.join(package_path, 'baselearners'))
        open(os.path.join(package_path, 'baselearners', '__init__.py'), 'a').close()
        for idx, base_learner in enumerate(self.base_learners):
            base_learner.export_as_file(os.path.join(package_path,
                                                     'baselearners',
                                                     'baselearner' + str(idx)))

        self.base_learner_origin.export_as_file(
            os.path.join(package_path, 'metalearner'),
            self.secondary_learner_hyperparameters
        )

        with open(os.path.join(package_path, 'cv.py'), 'wb') as f:
            f.write(cv_source.encode('utf8'))

        ensemble_source = ''
        stacker_file_loc = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'stacker.py')
        with open(stacker_file_loc) as f:
            ensemble_source += f.read()

        ensemble_source += '\n\n' \
                           '    def {}(self, X):\n' \
                           '        return self._process_using_' \
                           'meta_feature_generator(X, "{}")\n\n'\
            .format(self.base_learner_origin.meta_feature_generator,
                    self.base_learner_origin.meta_feature_generator)

        with open(os.path.join(package_path, 'stacker.py'), 'wb') as f:
            f.write(ensemble_source.encode('utf8'))

        builder_source = ''

        for idx, base_learner in enumerate(self.base_learners):
            builder_source += 'from {}.baselearners import baselearner{}\n'.format(package_name, idx)

        builder_source += 'from {}.cv import return_splits_iterable\n'.format(package_name)

        builder_source += 'from {} import metalearner\n'.format(package_name)

        builder_source += 'from {}.stacker import XcessivStackedEnsemble\n'.format(package_name)

        builder_source += '\nbase_learners = [\n'
        for idx, base_learner in enumerate(self.base_learners):
            builder_source += '    baselearner{}.base_learner,\n'.format(idx)
        builder_source += ']\n'

        builder_source += '\nmeta_feature_generators = [\n'
        for idx, base_learner in enumerate(self.base_learners):
            builder_source += '    baselearner{}.meta_feature_generator,\n'.format(idx)
        builder_source += ']\n'

        builder_source += '\nxcessiv_ensemble = XcessivStackedEnsemble(base_learners=base_learners,' \
                          ' meta_feature_generators=meta_feature_generators,' \
                          ' secondary_learner=metalearner.base_learner,' \
                          ' cv_function=return_splits_iterable)\n'

        with open(os.path.join(package_path, 'builder.py'), 'wb') as f:
            f.write(builder_source.encode('utf8'))

Exports the ensemble as a Python package and saves it to `package_path`.

Args:
package_path (str, unicode): Absolute/local path of place to save package in

cv_source (str, unicode): String containing actual code for base learner
cross-validation used to generate secondary meta-features.

Raises:
exceptions.UserError: If os.path.join(path, name) already exists.


def get_variation_from_key(self, experiment_key, variation_key):

    variation_map = self.variation_key_map.get(experiment_key)

    if variation_map:
      variation = variation_map.get(variation_key)
      if variation:
        return variation
      else:
        self.logger.error('Variation key "%s" is not in datafile.' % variation_key)
        self.error_handler.handle_error(exceptions.InvalidVariationException(enums.Errors.INVALID_VARIATION_ERROR))
        return None

    self.logger.error('Experiment key "%s" is not in datafile.' % experiment_key)
    self.error_handler.handle_error(exceptions.InvalidExperimentException(enums.Errors.INVALID_EXPERIMENT_KEY_ERROR))
    return None

Get variation given experiment and variation key.

Args:
experiment: Key representing parent experiment of variation.
variation_key: Key representing the variation.

Returns
Object representing the variation.


def sanitize_git_path(self, uri, ref=None):
    if uri.endswith('.git'):
        dir_name = uri[:(- 4)]
    else:
        dir_name = uri
    dir_name = self.sanitize_uri_path(dir_name)
    if (ref is not None):
        dir_name += ('-%s' % ref)
    return dir_name

Take a git URI and ref and converts it to a directory safe path.

Args:
uri (string): git URI
(e.g. git@github.com:foo/bar.git)
ref (string): optional git ref to be appended to the path

Returns:
str: Directory name for the supplied uri


def decode_iter_request(data: dict) -> Optional[Union[(str, int)]]:
    if ('response_metadata' in data):
        return data['response_metadata'].get('next_cursor')
    elif ('paging' in data):
        current_page = int(data['paging'].get('page', 1))
        max_page = int(data['paging'].get('pages', 1))
        if (current_page < max_page):
            return (current_page + 1)
    elif (('has_more' in data) and data['has_more'] and ('latest' in data)):
        return data['messages'][(- 1)]['ts']
    return None

Decode incoming response from an iteration request

Args:
data: Response data

Returns:
Next itervalue


def _sideral(date, longitude=0., model='mean', eop_correction=True, terms=106):

    t = date.change_scale('UT1').julian_century

    theta = 67310.54841 + (876600 * 3600 + 8640184.812866) * t + 0.093104 * t ** 2\
        - 6.2e-6 * t ** 3

    theta /= 240.

    if model == 'apparent':
        theta += equinox(date, eop_correction, terms)

    theta += longitude

    theta %= 360.

    return theta

Get the sideral time at a defined date

Args:
date (Date):
longitude (float): Longitude of the observer (in degrees)
East positive/West negative.
model (str): 'mean' or 'apparent' for GMST and GAST respectively
Return:
float: Sideral time in degrees

GMST: Greenwich Mean Sideral Time
LST: Local Sideral Time (Mean)
GAST: Greenwich Apparent Sideral Time


def add_plugin(self, f):

        if f.endswith('.py'):

            plugin_name = os.path.splitext(os.path.basename(f))[0]

            if plugin_name in sys.modules:
                try:
                    handler = reload(sys.modules[plugin_name])
                    print'\t- %s %sRELOAD%s' % (plugin_name, color.Yellow, color.Normal)
                except ImportError, error:
                    print 'Failed to import plugin: %s (%s)' % (plugin_name, error)
                    return
            else:

                try:
                    handler = __import__(plugin_name, globals(), locals(), [], -1)
                except ImportError, error:
                    print 'Failed to import plugin: %s (%s)' % (plugin_name, error)
                    return

            plugin = self.validate(handler)
            print '\t- %s %sOK%s' % (plugin_name, color.Green, color.Normal)
            if plugin:

                plugin['name'] = plugin_name
                plugin['dependencies'] = plugin['class'].dependencies
                plugin['docstring'] = plugin['class'].__doc__
                plugin['mod_time'] = datetime.utcfromtimestamp(os.path.getmtime(f))

                try:
                    plugin['sample_set_input'] = getattr(plugin['class'], 'sample_set_input')
                except AttributeError:
                    plugin['sample_set_input'] = False

                self.plugin_callback(plugin)

Adding and verifying plugin.

Args:
f: the filepath for the plugin.


def get_domain_reports(self, domains):

        api_name = 'virustotal-domain-reports'

        (all_responses, domains) = self._bulk_cache_lookup(api_name, domains)
        responses = self._request_reports("domain", domains, 'domain/report')

        for domain, response in zip(domains, responses):
            if self._cache:
                self._cache.cache_value(api_name, domain, response)
            all_responses[domain] = response

        return all_responses

Retrieves the most recent VT info for a set of domains.

Args:
domains: list of string domains.
Returns:
A dict with the domain as key and the VT report as value.


def add_minute(self, minute):
    _moy = (self.moy + int(minute))
    return self.__class__.from_moy(_moy)

Create a new DateTime after the minutes are added.

Args:
minute: An integer value for minutes.


def state_view_for_block(block_wrapper, state_view_factory):

        state_root_hash = \
            block_wrapper.state_root_hash \
            if block_wrapper is not None else None

        return state_view_factory.create_view(state_root_hash)

Returns the state view for an arbitrary block.

Args:
block_wrapper (BlockWrapper): The block for which a state
view is to be returned
state_view_factory (StateViewFactory): The state view factory
used to create the StateView object

Returns:
StateView object associated with the block


def mkdir(self, path):

        self.__validate_storage_path(path, projects_allowed=False)
        parent_metadata = self.get_parent(path)
        self.api_client.create_folder(path.split('/')[-1], parent_metadata['uuid'])

Create a folder in the storage service pointed by the given path.

Args:
path (str): The path of the folder to be created

Returns:
None

Raises:
StorageArgumentException: Invalid arguments
StorageForbiddenException: Server response code 403
StorageNotFoundException: Server response code 404
StorageException: other 400-600 error codes


def _execute(self, connection, query, fetch=True):
    with connection.cursor() as cursor:
        cursor.execute(query)
        if fetch:
            return cursor.fetchall()
        else:
            cursor.execute('COMMIT;')

Executes given query and returns result.

Args:
connection: connection to postgres database who stores mpr data.
query (str): sql query
fetch (boolean, optional): if True, fetch query result and return it. If False, do not fetch.

Returns:
iterable with query result or None if fetch is False.


def get_bucket_files(glob_pattern, base_dir, force=False, pattern_slice=slice(None)):
    if (gcsfs is None):
        raise RuntimeError("Missing 'gcsfs' dependency for GCS download.")
    if (not os.path.isdir(base_dir)):
        raise OSError('Directory does not exist: {}'.format(base_dir))
    if isinstance(glob_pattern, str):
        glob_pattern = [glob_pattern]
    fs = gcsfs.GCSFileSystem(token='anon')
    filenames = []
    for gp in glob_pattern:
        if isinstance(gp, str):
            glob_results = list(fs.glob(gp))
        else:
            glob_results = [fn for pat in gp for fn in fs.glob(pat)]
        for fn in glob_results[pattern_slice]:
            ondisk_fn = os.path.basename(fn)
            ondisk_pathname = os.path.join(base_dir, ondisk_fn)
            filenames.append(ondisk_pathname)
            if (force and os.path.isfile(ondisk_pathname)):
                os.remove(ondisk_pathname)
            elif os.path.isfile(ondisk_pathname):
                LOG.info('Found existing: {}'.format(ondisk_pathname))
                continue
            LOG.info('Downloading: {}'.format(ondisk_pathname))
            fs.get(('gs:
    if (not filenames):
        raise OSError('No files could be found or downloaded.')
    return filenames

Helper function to download files from Google Cloud Storage.

Args:
glob_pattern (str or list): Glob pattern string or series of patterns
used to search for on Google Cloud Storage. The pattern should
include the "gs://" protocol prefix. If a list of lists, then the
results of each sublist pattern are concatenated and the result is
treated as one pattern result. This is important for things like
``pattern_slice`` and complicated glob patterns not supported by
GCP.
base_dir (str): Root directory to place downloaded files on the local
system.
force (bool): Force re-download of data regardless of its existence on
the local system. Warning: May delete non-demo files stored in
download directory.
pattern_slice (slice): Slice object to limit the number of files
returned by each glob pattern.


def OpenAndRead(relative_path='debugger-blacklist.yaml'):
    try:
        with open(os.path.join(sys.path[0], relative_path), 'r') as f:
            return Read(f)
    except IOError:
        return None

Attempts to find the yaml configuration file, then read it.

Args:
relative_path: Optional relative path override.

Returns:
A Config object if the open and read were successful, None if the file
does not exist (which is not considered an error).

Raises:
Error (some subclass): As thrown by the called Read() function.


def _PromptUserForVSSCurrentVolume(self):
    while True:
        self._output_writer.Write('Volume Shadow Snapshots (VSS) were selected also process current\nvolume? [yes, no]\n')
        process_current_volume = self._input_reader.Read()
        process_current_volume = process_current_volume.strip()
        process_current_volume = process_current_volume.lower()
        if ((not process_current_volume) or (process_current_volume in ('no', 'yes'))):
            break
        self._output_writer.Write('\nUnsupported option, please try again or abort with Ctrl^C.\n\n')
    self._output_writer.Write('\n')
    return ((not process_current_volume) or (process_current_volume == 'yes'))

Prompts the user if the current volume with VSS should be processed.

Returns:
bool: True if the current volume with VSS should be processed.


def look_source(self, sourcepath, library_paths=None):

        if sourcepath not in self._CHILDREN_MAP:
            with io.open(sourcepath, 'r', encoding='utf-8') as fp:
                finded_paths = self.parse(fp.read())

            children = self.resolve(sourcepath, finded_paths,
                                    library_paths=library_paths)

            self._CHILDREN_MAP[sourcepath] = children

            for p in children:
                self._PARENTS_MAP[p].add(sourcepath)

            for path in children:
                if path not in self._CHILDREN_MAP:
                    self.look_source(path, library_paths=library_paths)

        return

Open a SCSS file (sourcepath) and find all involved file through
imports.

This will fill internal buffers ``_CHILDREN_MAP`` and ``_PARENTS_MAP``.

Args:
sourcepath (str): Source file path to start searching for imports.

Keyword Arguments:
library_paths (list): List of directory paths for libraries to
resolve paths if resolving fails on the base source path.
Default to None.


def get_cartesian(self):

    def create_cartesian(positions, row):
        xyz_frame = pd.DataFrame(columns=['atom', 'x', 'y', 'z'], index=self.index[:row], dtype='f8')
        xyz_frame['atom'] = self.loc[(xyz_frame.index, 'atom')]
        xyz_frame.loc[(:, ['x', 'y', 'z'])] = positions[:row]
        from chemcoord.cartesian_coordinates.cartesian_class_main import Cartesian
        cartesian = Cartesian(xyz_frame, metadata=self.metadata)
        return cartesian
    c_table = self.loc[(:, ['b', 'a', 'd'])]
    c_table = c_table.replace(constants.int_label)
    c_table = c_table.replace({k: v for (v, k) in enumerate(c_table.index)})
    c_table = c_table.values.astype('i8').T
    C = self.loc[(:, ['bond', 'angle', 'dihedral'])].values.T
    C[([1, 2], :)] = np.radians(C[([1, 2], :)])
    (err, row, positions) = transformation.get_X(C, c_table)
    positions = positions.T
    if (err == ERR_CODE_InvalidReference):
        rename = dict(enumerate(self.index))
        i = rename[row]
        (b, a, d) = self.loc[(i, ['b', 'a', 'd'])]
        cartesian = create_cartesian(positions, row)
        raise InvalidReference(i=i, b=b, a=a, d=d, already_built_cartesian=cartesian)
    elif (err == ERR_CODE_OK):
        return create_cartesian(positions, (row + 1))

Return the molecule in cartesian coordinates.

Raises an :class:`~exceptions.InvalidReference` exception,
if the reference of the i-th atom is undefined.

Args:
None

Returns:
Cartesian: Reindexed version of the zmatrix.


def getfileversion(self):

        status, major_v, minor_v, release, info = _C.Hgetfileversion(self._id)
        _checkErr('getfileversion', status, "cannot get file version")
        return major_v, minor_v, release, info

Get file version info.

Args:
no argument
Returns:
4-element tuple with the following components:
-major version number (int)
-minor version number (int)
-complete library version number (int)
-additional information (string)

C library equivalent : Hgetlibversion


def delete_fork_relation(self, **kwargs):
    path = ('/projects/%s/fork' % self.get_id())
    self.manager.gitlab.http_delete(path, **kwargs)

Delete a forked relation between existing projects.

Args:
**kwargs: Extra options to send to the server (e.g. sudo)

Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server failed to perform the request


def ami_lookup(region='us-east-1', name='tomcat8'):
    if AMI_JSON_URL:
        ami_dict = _get_ami_dict(AMI_JSON_URL)
        ami_id = ami_dict[region][name]
    elif GITLAB_TOKEN:
        warn_user('Use AMI_JSON_URL feature instead.')
        ami_contents = _get_ami_file(region=region)
        ami_dict = json.loads(ami_contents)
        ami_id = ami_dict[name]
    else:
        ami_id = name
    LOG.info('Using AMI: %s', ami_id)
    return ami_id

Look up AMI ID.

Use _name_ to find AMI ID. If no ami_base_url or gitlab_token is provided,
_name_ is returned as the ami id.

Args:
region (str): AWS Region to find AMI ID.
name (str): Simple AMI base name to lookup.

Returns:
str: AMI ID for _name_ in _region_.


def get_msd_plot(self, plt=None, mode='specie'):
    from pymatgen.util.plotting import pretty_plot
    plt = pretty_plot(12, 8, plt=plt)
    if (np.max(self.dt) > 100000):
        plot_dt = (self.dt / 1000)
        unit = 'ps'
    else:
        plot_dt = self.dt
        unit = 'fs'
    if (mode == 'species'):
        for sp in sorted(self.structure.composition.keys()):
            indices = [i for (i, site) in enumerate(self.structure) if (site.specie == sp)]
            sd = np.average(self.sq_disp_ions[(indices, :)], axis=0)
            plt.plot(plot_dt, sd, label=sp.__str__())
        plt.legend(loc=2, prop={'size': 20})
    elif (mode == 'sites'):
        for (i, site) in enumerate(self.structure):
            sd = self.sq_disp_ions[(i, :)]
            plt.plot(plot_dt, sd, label=('%s - %d' % (site.specie.__str__(), i)))
        plt.legend(loc=2, prop={'size': 20})
    elif (mode == 'mscd'):
        plt.plot(plot_dt, self.mscd, 'r')
        plt.legend(['Overall'], loc=2, prop={'size': 20})
    else:
        plt.plot(plot_dt, self.msd, 'k')
        plt.plot(plot_dt, self.msd_components[(:, 0)], 'r')
        plt.plot(plot_dt, self.msd_components[(:, 1)], 'g')
        plt.plot(plot_dt, self.msd_components[(:, 2)], 'b')
        plt.legend(['Overall', 'a', 'b', 'c'], loc=2, prop={'size': 20})
    plt.xlabel('Timestep ({})'.format(unit))
    if (mode == 'mscd'):
        plt.ylabel('MSCD ($\\AA^2$)')
    else:
        plt.ylabel('MSD ($\\AA^2$)')
    plt.tight_layout()
    return plt

Get the plot of the smoothed msd vs time graph. Useful for
checking convergence. This can be written to an image file.

Args:
plt: A plot object. Defaults to None, which means one will be
generated.
mode (str): Determines type of msd plot. By "species", "sites",
or direction (default). If mode = "mscd", the smoothed mscd vs.
time will be plotted.


def verify(self, obj):

        if obj not in self.options:
            raise ValidationError("Object is not in list of enumerated options",
                                  reason='not in list of enumerated options', object=obj, options=self.options)

        return obj

Verify that the object conforms to this verifier's schema.

Args:
obj (object): A python object to verify

Raises:
ValidationError: If there is a problem verifying the object, a
ValidationError is thrown with at least the reason key set indicating
the reason for the lack of validation.


def times(*combined):
    assert combined
    if len(combined) == 1:
        return combined[0]
    first = combined[0]
    rest_combined = times(*combined[1:])
    combined_results = []
    for a in first:
        for b in rest_combined:
            if set(a.keys()).intersection(set(b.keys())):
                raise ValueError('Keys need to not overlap: {} vs {}'.format(a.keys(), b.keys()))
            combined_results.append(OrderedDict(list(a.items()) + list(b.items())))
    return combined_results

Generate a product of N sets of combinations.

times(combine(a=[1,2]), combine(b=[3,4])) == combine(a=[1,2], b=[3,4])

Args:
*combined: N lists of dictionaries that specify combinations.

Returns:
a list of dictionaries for each combination.

Raises:
ValueError: if some of the inputs have overlapping keys.


def get_developer_package(path, format=None):

    from rez.developer_package import DeveloperPackage
    return DeveloperPackage.from_path(path, format=format)

Create a developer package.

Args:
path (str): Path to dir containing package definition file.
format (str): Package definition file format, detected if None.

Returns:
`DeveloperPackage`.


def get_pending_enrollment_message(cls, pending_users, enrolled_in):

        pending_emails = [pending_user.user_email for pending_user in pending_users]
        return (
            'warning',
            _(
                "The following learners do not have an account on "
                "{platform_name}. They have not been enrolled in "
                "{enrolled_in}. When these learners create an account, they will "
                "be enrolled automatically: {pending_email_list}"
            ).format(
                platform_name=settings.PLATFORM_NAME,
                enrolled_in=enrolled_in,
                pending_email_list=', '.join(pending_emails),
            )
        )

Create message for the users who were enrolled in a course or program.

Args:
users: An iterable of PendingEnterpriseCustomerUsers who were successfully linked with a pending enrollment
enrolled_in (str): A string identifier for the course or program the pending users were linked to

Returns:
tuple: A 2-tuple containing a message type and message text


def _group_value_by_device(per_replica_values):
    destinations = per_replica_values[0]._devices
    grouped = [[] for _ in range(len(destinations))]
    for per_replica_value in per_replica_values:
        for i, v in enumerate(per_replica_value.values):
            assert per_replica_value._devices == destinations
            grouped[i].append((v, None))
    return grouped

Group values into sublists by their devices.

This grouping is needed to call the all-reduce library because it expects a
list of the following form:
[[(grad0_gpu0, v0_gpu0), (grad1_gpu0, v1_gpu0), (grad2_gpu0, v2_gpu0) ...],
[(grad0_gpu1, v0_gpu1), (grad1_gpu1, v1_gpu1), (grad2_gpu1, v2_gpu1) ...],
[(grad0_gpu2, v0_gpu2), (grad1_gpu0, v1_gpu2), (grad2_gpu0, v2_gpu2) ...],
...
]

Args:
per_replica_values: a list of PerReplica objects.

Returns:
a list of lists, each sublist has components for its corresponding device of
PerReplica objects, paired with a None.


def LoadData(self, data, custom_properties=None):

    self.__data = []
    self.AppendData(data, custom_properties)

Loads new rows to the data table, clearing existing rows.

May also set the custom_properties for the added rows. The given custom
properties dictionary specifies the dictionary that will be used for *all*
given rows.

Args:
data: The rows that the table will contain.
custom_properties: A dictionary of string to string to set as the custom
properties for all rows.


def url_is(white_list):

    def func(url):
        prefixes = white_list.get('PREFIXES', ())
        for prefix in prefixes:
            if url.startswith(prefix):
                return True
        constants = white_list.get('CONSTANTS', ())
        for exact_url in constants:
            if (url == exact_url):
                return True
        return False
    return func

Function generator.

Args:
white_list (dict): dict with PREFIXES and CONSTANTS keys (list values).

Returns:
func: a function to check if a URL is...


def _cached_by_domain(api_name):

    def wrapped(func):

        def decorated(self, domains):
            if (not self._cache):
                return func(self, domains)
            all_responses = self._cache.bulk_lookup(api_name, domains)
            domains = list((set(domains) - set(all_responses)))
            if domains:
                response = func(self, domains)
                if (not response):
                    raise ResponseError('No response for uncached domains')
                for domain in response:
                    self._cache.cache_value(api_name, domain, response[domain])
                    all_responses[domain] = response[domain]
            return all_responses
        return decorated
    return wrapped

A caching wrapper for functions that take a list of domains as
parameters.

Raises:
ResponseError - if the response received from the endpoint is
not valid.


def process_new_issues(self, volumes, existing_issues):
    new_issues = {}
    for (issue_id, volume) in volumes.items():
        state = EBSIssueState.DETECTED.value
        if (issue_id in existing_issues):
            issue = existing_issues[issue_id]
            data = {'state': state, 'notes': issue.notes, 'last_notice': issue.last_notice}
            if issue.update(data):
                new_issues.setdefault(issue.volume.account, []).append(issue)
                self.log.debug('Updated EBSVolumeAuditIssue {}'.format(issue_id))
        else:
            properties = {'volume_id': volume.id, 'account_id': volume.account_id, 'location': volume.location, 'state': state, 'last_change': datetime.now(), 'last_notice': None, 'notes': []}
            issue = EBSVolumeAuditIssue.create(issue_id, properties=properties)
            new_issues.setdefault(issue.volume.account, []).append(issue)
    return new_issues

Takes a dict of existing volumes missing tags and a dict of existing issues, and finds any new or updated
issues.

Args:
volumes (:obj:`dict` of `str`: `EBSVolume`): Dict of current volumes with issues
existing_issues (:obj:`dict` of `str`: `EBSVolumeAuditIssue`): Current list of issues

Returns:
:obj:`dict` of `str`: `EBSVolumeAuditIssue`


def convert_tokens_into_matrix(self, token_list):

        return np.array(self.vectorize(token_list)).astype(np.float32)

Create matrix of sentences.

Args:
token_list:     The list of tokens.

Returns:
2-D `np.ndarray` of sentences.
Each row means one hot vectors of one sentence.


def flatten_(structure):

  if isinstance(structure, dict):
    if structure:
      structure = zip(*sorted(structure.items(), key=lambda x: x[0]))[1]
    else:

      structure = ()
  if isinstance(structure, (tuple, list)):
    result = []
    for element in structure:
      result += flatten_(element)
    return tuple(result)
  return (structure,)

Combine all leaves of a nested structure into a tuple.

The nested structure can consist of any combination of tuples, lists, and
dicts. Dictionary keys will be discarded but values will ordered by the
sorting of the keys.

Args:
structure: Nested structure.

Returns:
Flat tuple.


def validate_read(self, address):

        if not any(address.startswith(ns) for ns in self._read_list):
            raise AuthorizationException(address=address)

Raises an exception if the address is not allowed to be read in
this context, based on txn inputs.

Args:
address (str): An address to be validated.

Returns:
None

Raises:
AuthorizationException


def process_answer(self, user, item, asked, answered, time, answer, response_time, guess, **kwargs):
    pass

This method is used during the answer streaming and is called after the
predictive model for each answer.

Args:
user (int):
identifier of ther user answering the question
asked (int):
identifier of the asked item
answered (int):
identifier of the answered item or None if the user answered
"I don't know"
response_time (int)
time the answer took in milliseconds
time (datetime.datetime)
time when the user answered the question
guess (float):
probability of correct response in case of random answer


def print_serial_number_info(self, serial_number, print_to_screen=True):

        r = self.select_serial_number_row(serial_number)
        if r.empty:
            warnings.warn("missing serial number")
            return

        txt1 = 80 * "="
        txt1 += "\n"
        txt1 += f"   serial number {serial_number}\n"
        txt1 = 80 * "-"
        txt1 += "\n"
        txt2 = ""
        for label, value in zip(r.columns, r.values[0]):
            if label in self.headers:
                txt1 += f"{label}:    \t {value}\n"
            else:
                txt2 += f"({label}:    \t {value})\n"
        if print_to_screen:
            print(txt1)
            print(80 * "-")
            print(txt2)
            print(80 * "=")
            return
        else:
            return txt1

Print information about the run.

Args:
serial_number: serial number.
print_to_screen: runs the print statement if True,
returns txt if not.

Returns:
txt if print_to_screen is False, else None.


def concat_pairs(tensor_tuple0: Tuple[torch.Tensor], tensor_tuple1: Tuple[torch.Tensor]) -> Tuple[torch.Tensor]:
    return tuple([torch.cat([tensor0, tensor1]) for tensor0, tensor1 in zip(tensor_tuple0, tensor_tuple1)])

Concatenate two tuples of tensors pairwise

Args:
tensor_tuple0 (`Tuple[torch.Tensor]`):
Tuple of tensors.
tensor_tuple1 (`Tuple[torch.Tensor]`):
Tuple of tensors.

Returns:
(`Tuple[torch.Tensor]`): Tuple of concatenated tensors.


def __init__(self, inputs=None,
                 outputs=None,
                 assettype=AssetType.GoverningToken,
                 assetname='',
                 amount=Fixed8(0),
                 precision=0,
                 owner=None,
                 admin=None):

        super(RegisterTransaction, self).__init__(inputs, outputs)
        self.Type = TransactionType.RegisterTransaction
        self.AssetType = assettype
        self.Name = assetname
        self.Amount = amount

        if inputs is not None:
            self.inputs = inputs
        else:
            self.inputs = []

        if outputs is not None:
            self.outputs = outputs
        else:
            self.outputs = []

        if owner is not None and type(owner) is not EllipticCurve.ECPoint:
            raise Exception("Invalid owner, must be ECPoint instance")

        self.Owner = owner
        self.Admin = admin
        self.Precision = precision

Create an instance.

Args:
inputs (list):
outputs (list):
assettype (neo.Core.AssetType):
assetname (str):
amount (Fixed8):
precision (int): number of decimals the asset has.
owner (EllipticCurve.ECPoint):
admin (UInt160):


def trigger(self, target: str, trigger: str, parameters: Dict[(str, Any)]={}):
    pass

Calls the specified Trigger of another Area with the optionally given parameters.

Args:
target: The name of the target Area.
trigger: The name of the Trigger.
parameters: The parameters of the function call.


def RegisterSourceType(cls, source_type_class):
    if (source_type_class.TYPE_INDICATOR in cls._source_type_classes):
        raise KeyError('Source type already set for type: {0:s}.'.format(source_type_class.TYPE_INDICATOR))
    cls._source_type_classes[source_type_class.TYPE_INDICATOR] = source_type_class

Registers a source type.

Source types are identified based on their type indicator.

Args:
source_type_class (type): source type.

Raises:
KeyError: if source types is already set for the corresponding
type indicator.


def create_additional_charge(self, *, subscription_id, description, plan_value, plan_tax, plan_tax_return_base, currency):
    payload = {'description': description, 'additionalValues': [{'name': 'ITEM_VALUE', 'value': plan_value, 'currency': currency}, {'name': 'ITEM_TAX', 'value': plan_tax, 'currency': currency}, {'name': 'ITEM_TAX_RETURN_BASE', 'value': plan_tax_return_base, 'currency': currency}]}
    fmt = 'subscriptions/{}/recurringBillItems'.format(subscription_id)
    return self.client._post((self.url + fmt), json=payload, headers=self.get_headers())

Adds extra charges to the respective invoice for the current period.

Args:
subscription_id: Identification of the subscription
description:
plan_value:
plan_tax:
plan_tax_return_base:
currency:

Returns:


def create_list(self, **kwargs):
    path = self._get_path('create_list')
    kwargs.update({'session_id': self.session_id})
    payload = {'name': kwargs.pop('name', None), 'description': kwargs.pop('description', None)}
    if ('language' in kwargs):
        payload['language'] = kwargs['language']
    response = self._POST(path, kwargs, payload)
    self._set_attrs_to_values(response)
    return response

Create a new list.

A valid session id is required.

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

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


def rotation(self):
    rotation = self._libinput.libinput_event_tablet_tool_get_rotation(self._handle)
    changed = self._libinput.libinput_event_tablet_tool_rotation_has_changed(self._handle)
    return (rotation, changed)

The current Z rotation of the tool in degrees, clockwise
from the tool's logical neutral position and whether it has changed
in this event.

For tools of type :attr:`~libinput.constant.TabletToolType.MOUSE`
and :attr:`~libinput.constant.TabletToolType.LENS` the logical
neutral position is pointing to the current logical north
of the tablet. For tools of type
:attr:`~libinput.constant.TabletToolType.BRUSH`, the logical
neutral position is with the buttons pointing up.

If this axis does not exist on the current tool, this property is
(0, :obj:`False`).

Returns:
(float, bool): The current value of the the axis and whether it has
changed.


def memcached_client(servers=config.memcached_uri, debug=config.debug_memcache):
    key = None
    try:
        (client, key) = scoped_instance_manager.acquire(servers, debug=debug)
        (yield client)
    finally:
        if key:
            scoped_instance_manager.release(key)

Get a shared memcached instance.

This function shares the same memcached instance across nested invocations.
This is done so that memcached connections can be kept to a minimum, but at
the same time unnecessary extra reconnections are avoided. Typically an
initial scope (using 'with' construct) is made around parts of code that hit
the cache server many times - such as a resolve, or executing a context. On
exit of the topmost scope, the memcached client is disconnected.

Returns:
`Client`: Memcached instance.


def get_initial_state_args(value_and_gradients_function, initial_position, grad_tolerance, control_inputs=None):
    if control_inputs:
        with tf.control_dependencies(control_inputs):
            (f0, df0) = value_and_gradients_function(initial_position)
    else:
        (f0, df0) = value_and_gradients_function(initial_position)
    converged = (norm(df0, dims=1) < grad_tolerance)
    return dict(converged=converged, failed=tf.zeros_like(converged), num_iterations=tf.convert_to_tensor(value=0), num_objective_evaluations=tf.convert_to_tensor(value=1), position=initial_position, objective_value=f0, objective_gradient=df0)

Returns a dictionary to populate the initial state of the search procedure.

Performs an initial convergence check and the first evaluation of the
objective function.

Args:
value_and_gradients_function: A Python callable that accepts a tensor and
returns a tuple of two tensors: the objective function value and its
derivative.
initial_position: The starting point of the search procedure.
grad_tolerance: The gradient tolerance for the procedure.
control_inputs: Optional ops used to assert the validity of inputs, these
are added as control dependencies to execute before the objective
function is evaluated for the first time.

Returns:
An dictionary with values for the following keys:
converged: True if the convergence check finds that the initial position
is already an argmin of the objective function.
failed: Initialized to False.
num_objective_evaluations: Initialized to 1.
position: Initialized to the initial position.
objective_value: Initialized to the value of the objective function at
the initial position.
objective_gradient: Initialized to the gradient of the objective
function at the initial position.


def label_count(self, label_list_ids=None):
    count = collections.defaultdict(int)
    for label_list in self.label_lists.values():
        if ((label_list_ids is None) or (label_list.idx in label_list_ids)):
            for (label_value, label_count) in label_list.label_count().items():
                count[label_value] += label_count
    return count

Return a dictionary containing the number of times,
every label-value in this utterance is occurring.

Args:
label_list_ids (list): If not None, only labels from label-lists
with an id contained in this list
are considered.

Returns:
dict: A dictionary containing the number of occurrences
with the label-value as key.


def show(self, view: View, request: Request):
    return view.render('welcome', {'app': request.app().make('Application')})

Show the welcome page.

Arguments:
view {masonite.view.View} -- The Masonite view class.
Application {config.application} -- The application config module.

Returns:
masonite.view.View -- The Masonite view class.


def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:
    if token_ids_1 is None:
        return self.prefix_tokens + token_ids_0 + self.suffix_tokens
    return self.prefix_tokens + token_ids_0 + token_ids_1 + self.suffix_tokens

Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. An PLBART sequence has the following format, where `X` represents the sequence:

- `input_ids` (for encoder) `X [eos, src_lang_code]`
- `decoder_input_ids`: (for decoder) `X [eos, tgt_lang_code]`

BOS is never used. Pairs of sequences are not the expected use case, but they will be handled without a
separator.

Args:
token_ids_0 (`List[int]`):
List of IDs to which the special tokens will be added.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.

Returns:
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.


def dynamic_import(modname, import_tuples, developing=True, ignore_froms=[], dump=False, ignore_startswith=[], ignore_endswith=[], ignore_list=[], check_not_imported=True, return_initstr=False, verbose=False):
    if verbose:
        print(('[UTIL_IMPORT] Running Dynamic Imports for modname=%r ' % modname))
    try:
        module = sys.modules[modname]
    except:
        module = __import__(modname)
    imports = [tup[0] for tup in import_tuples]
    __excecute_imports(module, modname, imports, verbose=verbose)
    if developing:
        from_imports = __execute_fromimport_star(module, modname, import_tuples, ignore_list=ignore_list, ignore_startswith=ignore_startswith, ignore_endswith=ignore_endswith, check_not_imported=check_not_imported, verbose=verbose)
    else:
        from_imports = __execute_fromimport(module, modname, import_tuples, verbose=verbose)
    inject_execstr = _inject_execstr(modname, import_tuples)
    dump_requested = (((('--dump-%s-init' % modname) in sys.argv) or (('--print-%s-init' % modname) in sys.argv)) or dump)
    overwrite_requested = (('--update-%s-init' % modname) in sys.argv)
    if verbose:
        print(('[UTIL_IMPORT] Finished Dynamic Imports for modname=%r ' % modname))
    if dump_requested:
        is_main_proc = (multiprocessing.current_process().name == 'MainProcess')
        if is_main_proc:
            from utool import util_str
            initstr = _initstr(modname, imports, from_imports, inject_execstr)
            print(util_str.indent(initstr))
    if overwrite_requested:
        '\n        SeeAlso:\n            util_inject.inject_python_code\n            util_str.replace_between_tags\n        '
        is_main_proc = (multiprocessing.current_process().name == 'MainProcess')
        if is_main_proc:
            from utool import util_str
            from os.path import join, exists
            initstr = _initstr(modname, imports, from_imports, inject_execstr, withheader=False)
            new_else = util_str.indent(initstr)
            init_fpath = join(module.__path__[0], '__init__.py')
            print(('attempting to update: %r' % init_fpath))
            assert exists(init_fpath)
            new_lines = []
            editing = False
            updated = False
            with open(init_fpath, 'r') as file_:
                lines = file_.readlines()
                for line in lines:
                    if (not editing):
                        new_lines.append(line)
                    if line.strip().startswith('
                        new_lines.append((('\n' + new_else) + '\n
                        editing = True
                        updated = True
                    if line.strip().startswith('
                        editing = False
            if updated:
                print(('writing updated file: %r' % init_fpath))
                new_text = ''.join(new_lines)
                with open(init_fpath, 'w') as file_:
                    file_.write(new_text)
            else:
                print(('no write hook for file: %r' % init_fpath))
    if return_initstr:
        initstr = _initstr(modname, imports, from_imports, '', withheader=False)
        return (inject_execstr, initstr)
    else:
        return inject_execstr

MAIN ENTRY POINT

Dynamically import listed util libraries and their attributes.
Create reload_subs function.

Using __import__ like this is typically not considered good style However,
it is better than import * and this will generate the good file text that
can be used when the module is 'frozen"

Returns:
str: init_inject_str - by default all imports are executed in this
function and only the remainig code needed to be executed is
returned to define the reload logic.

str, str: init_inject_str, init_str - if return_initstr is True then
also returns init_str defining the from imports.

Ignore:
ignore_startswith = []
ignore_endswith = []
check_not_imported = True
verbose = True


def GetLaunchedFlows(self, flow_type='outstanding'):
    result = None
    all_clients = set(self.ListAllClients())
    finished_clients = set(self.ListFinishedClients())
    outstanding_clients = (all_clients - finished_clients)
    if (flow_type == 'all'):
        result = all_clients
    elif (flow_type == 'finished'):
        result = finished_clients
    elif (flow_type == 'outstanding'):
        result = outstanding_clients
    flows = aff4.FACTORY.MultiListChildren([self.urn.Add(x.Basename()) for x in result])
    return [x[0] for (_, x) in flows]

Returns the session IDs of all the flows we launched.

Args:
flow_type: The type of flows to fetch. Can be "all", "outstanding" or
"finished".

Returns:
A list of flow URNs.


def check_models_are_auto_configured(module: types.ModuleType, all_auto_models: List[str]) -> List[str]:
    defined_models = get_models(module)
    failures = []
    for model_name, _ in defined_models:
        if model_name not in all_auto_models and (not ignore_unautoclassed(model_name)):
            failures.append(f'{model_name} is defined in {module.__name__} but is not present in any of the auto mapping. If that is intended behavior, add its name to `IGNORE_NON_AUTO_CONFIGURED` in the file `utils/check_repo.py`.')
    return failures

Check models defined in module are each in an auto class.

Args:
module (`types.ModuleType`):
The module in which we get the models.
all_auto_models (`List[str]`):
The list of all models in an auto class (as obtained with `get_all_auto_configured_models()`).

Returns:
`List[str]`: The list of error messages corresponding to models not tested.


def overlap(self, feature, stranded: bool=False):
    feature_strand = feature.strand
    strand = self.strand
    if (stranded and ((strand == '.') or ((strand == '+') and (feature_strand in ['-', '.'])) or ((strand == '-') and (feature_strand in ['+', '.'])))):
        return False
    iv_1 = set(range(feature.start, (feature.end + 1)))
    iv_2 = set(range(self.start, (self.end + 1)))
    if (len(iv_1.intersection(iv_2)) > 0):
        return True
    else:
        return False

Determine if a feature's position overlaps with the entry

Args:
feature (class): GFF3Entry object

stranded (bool): allow features to overlap on different strands
if True [default: False]

Returns:
bool: True if features overlap, else False


def _add_mgmt_to_domains(self, conf, mgmts):

        for dom_name, dom_spec in conf['domains'].iteritems():
            domain_mgmt = [
                nic['net'] for nic in dom_spec['nics'] if nic['net'] in mgmts
            ].pop()

            dom_spec['mgmt_net'] = domain_mgmt

Add management network key('mgmt_net') to each domain. Note this
assumes ``conf`` was validated.

Args:
conf(dict): spec
mgmts(list): list of management networks names


def prepare(self, variables):

        initializedsteps = []
        if variables is None:
            variables = dict()
        for step, params, _resources, _files in self.steps:
            new_params = _complete_parameters(params, variables)
            initializedsteps.append(step(new_params))
        return initializedsteps

Initialize all steps in this recipe using their parameters.

Args:
variables (dict): A dictionary of global variable definitions
that may be used to replace or augment the parameters given
to each step.

Returns:
list of RecipeActionObject like instances: The list of instantiated
steps that can be used to execute this recipe.


def _get_symmetry(self):
    d = spglib.get_symmetry(self._cell, symprec=self._symprec, angle_tolerance=self._angle_tol)
    trans = []
    for t in d['translations']:
        trans.append([float(Fraction.from_float(c).limit_denominator(1000)) for c in t])
    trans = np.array(trans)
    trans[(np.abs(trans) == 1)] = 0
    return (d['rotations'], trans)

Get the symmetry operations associated with the structure.

Returns:
Symmetry operations as a tuple of two equal length sequences.
(rotations, translations). "rotations" is the numpy integer array
of the rotation matrices for scaled positions
"translations" gives the numpy float64 array of the translation
vectors in scaled positions.


def encode(self, input_ids: jnp.ndarray, attention_mask: Optional[jnp.ndarray]=None, position_ids: Optional[jnp.ndarray]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, train: bool=False, params: Optional[dict]=None, dropout_rng: PRNGKey=None):
    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.return_dict
    if attention_mask is None:
        attention_mask = jnp.ones_like(input_ids)
    if position_ids is None:
        batch_size, sequence_length = input_ids.shape
        position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
    rngs = {}
    if dropout_rng is not None:
        rngs['dropout'] = dropout_rng

    def _encoder_forward(module, input_ids, attention_mask, position_ids, **kwargs):
        encode_module = module._get_encoder_module()
        return encode_module(input_ids, attention_mask, position_ids, **kwargs)
    return self.module.apply({'params': params or self.params}, input_ids=jnp.array(input_ids, dtype='i4'), attention_mask=jnp.array(attention_mask, dtype='i4'), position_ids=jnp.array(position_ids, dtype='i4'), output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, deterministic=not train, rngs=rngs, method=_encoder_forward)

Returns:

Example:

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

>>> model = FlaxPegasusForConditionalGeneration.from_pretrained("google/pegasus-large")
>>> tokenizer = AutoTokenizer.from_pretrained("google/pegasus-large")

>>> text = "My friends are cool but they eat too many carbs."
>>> inputs = tokenizer(text, max_length=1024, return_tensors="np")
>>> encoder_outputs = model.encode(**inputs)
```


def for_input_type(self, input_type):
    return self

Returns a specialized implementation of self, if it exists.

Otherwise, returns self.

Args:
input_type: the type of input elements.


def _add_def_paths(self, prop_dict):

    for prop_key, prop_value in prop_dict.iteritems():
      if prop_key == '$ref' and not 'prop_value'.startswith('
        prop_dict[prop_key] = '
      elif isinstance(prop_value, dict):
        self._add_def_paths(prop_value)

Recursive method to add relative paths for any $ref objects.

Args:
prop_dict: The property dict to alter.

Side Effects:
Alters prop_dict in-place.


def get_collection(self, id_or_uri, filter=''):

        if filter:
            filter = self.__make_query_filter(filter)
            filter = "?" + filter[1:]

        uri = "{uri}{filter}".format(uri=self.build_uri(id_or_uri), filter=filter)
        logger.debug('Get resource collection (uri = %s)' % uri)
        response = self._connection.get(uri)
        return self.__get_members(response)

Retrieves a collection of resources.

Use this function when the 'start' and 'count' parameters are not allowed in the GET call.
Otherwise, use get_all instead.

Optional filtering criteria may be specified.

Args:
id_or_uri: Can be either the resource ID or the resource URI.
filter (list or str): General filter/query string.

Returns:
Collection of the requested resource.


def _validate(self, value):
    _LOGGER.info('validate: Got type %s', type(value))
    if ((value is not None) and (not isinstance(value, client.Flow))):
        raise TypeError('Property {0} must be convertible to a flow instance; received: {1}.'.format(self._name, value))

Validates a value as a proper Flow object.

Args:
value: A value to be set on the property.

Raises:
TypeError if the value is not an instance of Flow.


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

Delete an association between a GCP project and a GitHub Enterprise server.

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


def ParseFileObject(self, parser_mediator, file_object):
    try:
        self._ParseFileHeader(file_object)
    except errors.ParseError as exception:
        raise errors.ParseError('Unable to parse index file header with error: {0!s}'.format(exception))
    file_object.seek(112, os.SEEK_CUR)
    self._ParseIndexTable(file_object)

Parses a file-like object.

Args:
parser_mediator (ParserMediator): a parser mediator.
file_object (dfvfs.FileIO): a file-like object to parse.

Raises:
ParseError: when the file cannot be parsed.


def create_project(self, collab_id):
    return self._authenticated_request.to_endpoint('project/').with_json_body(self._prep_params(locals())).return_body().post()

Create a new project.

Args:
collab_id (int): The id of the collab the project should be created in.

Returns:
A dictionary of details of the created project::

{
u'collab_id': 12998,
u'created_by': u'303447',
u'created_on': u'2017-03-21T14:06:32.293902Z',
u'description': u'',
u'entity_type': u'project',
u'modified_by': u'303447',
u'modified_on': u'2017-03-21T14:06:32.293967Z',
u'name': u'12998',
u'uuid': u'2516442e-1e26-4de1-8ed8-94523224cc40'
}

Raises:
StorageForbiddenException: Server response code 403
StorageNotFoundException: Server response code 404
StorageException: other 400-600 error codes


def _map_query_path_to_location_info(query_metadata_table):
    query_path_to_location_info = {}
    for (location, location_info) in query_metadata_table.registered_locations:
        if (not isinstance(location, Location)):
            continue
        if (location.query_path in query_path_to_location_info):
            equivalent_location_info = query_path_to_location_info[location.query_path]
            if (not _location_infos_equal(location_info, equivalent_location_info)):
                raise AssertionError(u'Differing LocationInfos at query_path {} between {} and {}. Expected parent_location.query_path, optional_scopes_depth, recursive_scopes_depth and types to be equal for LocationInfos sharing the same query path.'.format(location.query_path, location_info, equivalent_location_info))
        query_path_to_location_info[location.query_path] = location_info
    return query_path_to_location_info

Create a map from each query path to a LocationInfo at that path.

Args:
query_metadata_table: QueryMetadataTable, object containing all metadata collected during
query processing, including location metadata (e.g. which locations
are folded or optional).

Returns:
Dict[Tuple[str], LocationInfo], dictionary mapping query path to LocationInfo at that path.


def __init__(self, filename, sample_filename, probability_threshold=0.9):

        self.samples = pd.read_csv(sample_filename, sep=" ", skiprows=2,
                                   names=["fid", "iid", "missing", "father",
                                          "mother", "sex", "plink_geno"],
                                   dtype=dict(fid=str, iid=str))

        try:
            self.samples = self.samples.set_index("iid", verify_integrity=True)

        except ValueError:
            logging.info(
                "Setting the index as 'fid_iid' because the individual IDs "
                "are not unique."
            )

            self.samples["fid_iid"] = [
                "{fid}_{iid}".format(fid=fid, iid=iid)
                for fid, iid in zip(self.samples.fid, self.samples.iid)
            ]
            self.samples = self.samples.set_index(
                "fid_iid", verify_integrity=True,
            )

        self._impute2_file = get_open_func(filename)(filename, "r")

        self.has_index = path.isfile(filename + ".idx")
        self._impute2_index = None
        self._index_has_location = False
        if self.has_index:
            self._impute2_index = get_index(
                filename,
                cols=[0, 1, 2],
                names=["chrom", "name", "pos"],
                sep=" ",
            )

            try:
                self._impute2_index = self._impute2_index.set_index(
                    "name", verify_integrity=True,
                )
                self._has_duplicated = False

            except ValueError as e:
                self._has_duplicated = True

                duplicated = self._impute2_index.name.duplicated(keep=False)
                duplicated_markers = self._impute2_index.loc[
                    duplicated, "name"
                ]
                duplicated_marker_counts = duplicated_markers.value_counts()

                self._dup_markers = {
                    m: [] for m in duplicated_marker_counts.index
                }

                logging.found_duplicates(duplicated_marker_counts.iteritems())

                counter = Counter()
                for i, marker in duplicated_markers.iteritems():
                    counter[marker] += 1
                    new_name = "{}:dup{}".format(marker, counter[marker])
                    self._impute2_index.loc[i, "name"] = new_name

                    self._dup_markers[marker].append(new_name)

                self._impute2_index = self._impute2_index.set_index(
                    "name", verify_integrity=True,
                )

            self._index_has_location = (
                "chrom" in self._impute2_index.columns and
                "pos" in self._impute2_index.columns
            )
            if self._index_has_location:

                self._impute2_index["multiallelic"] = False
                self._impute2_index.loc[
                    self._impute2_index.duplicated(["chrom", "pos"],
                                                   keep=False),
                    "multiallelic"
                ] = True

        self.prob_t = probability_threshold

IMPUTE2 file reader.

Args:
filename (str): The name of the IMPUTE2 file.
sample_filename (str): The name of the SAMPLE file.
probability_threshold (float): The probability threshold.

Note
====
If the sample IDs are not unique, the index is changed to be the
sample family ID and individual ID (i.e. fid_iid).


def __parse_tostr(self, text, **kwargs):
    n = self.options.get('nbest', 1)
    if (self._KW_BOUNDARY in kwargs):
        patt = kwargs.get(self._KW_BOUNDARY, '.')
        tokens = list(self.__split_pattern(text, patt))
        text = ''.join([t[0] for t in tokens])
        btext = self.__str2bytes(text)
        self.__mecab.mecab_lattice_set_sentence(self.lattice, btext)
        bpos = 0
        self.__mecab.mecab_lattice_set_boundary_constraint(self.lattice, bpos, self.MECAB_TOKEN_BOUNDARY)
        for (token, match) in tokens:
            bpos += 1
            if match:
                mark = self.MECAB_INSIDE_TOKEN
            else:
                mark = self.MECAB_ANY_BOUNDARY
            for _ in range(1, len(self.__str2bytes(token))):
                self.__mecab.mecab_lattice_set_boundary_constraint(self.lattice, bpos, mark)
                bpos += 1
            self.__mecab.mecab_lattice_set_boundary_constraint(self.lattice, bpos, self.MECAB_TOKEN_BOUNDARY)
    elif (self._KW_FEATURE in kwargs):
        features = kwargs.get(self._KW_FEATURE, ())
        fd = {morph: self.__str2bytes(feat) for (morph, feat) in features}
        tokens = self.__split_features(text, [e[0] for e in features])
        text = ''.join([t[0] for t in tokens])
        btext = self.__str2bytes(text)
        self.__mecab.mecab_lattice_set_sentence(self.lattice, btext)
        bpos = 0
        for (chunk, match) in tokens:
            c = len(self.__str2bytes(chunk))
            if (match == True):
                self.__mecab.mecab_lattice_set_feature_constraint(self.lattice, bpos, (bpos + c), fd[chunk])
            bpos += c
    else:
        btext = self.__str2bytes(text)
        self.__mecab.mecab_lattice_set_sentence(self.lattice, btext)
    self.__mecab.mecab_parse_lattice(self.tagger, self.lattice)
    if (n > 1):
        res = self.__mecab.mecab_lattice_nbest_tostr(self.lattice, n)
    else:
        res = self.__mecab.mecab_lattice_tostr(self.lattice)
    if (res != self.__ffi.NULL):
        raw = self.__ffi.string(res)
        return self.__bytes2str(raw).strip()
    else:
        err = self.__mecab.mecab_lattice_strerror(self.lattice)
        logger.error(self.__bytes2str(self.__ffi.string(err)))
        raise MeCabError(self.__bytes2str(self.__ffi.string(err)))

Builds and returns the MeCab function for parsing Unicode text.

Args:
fn_name: MeCab function name that determines the function
behavior, either 'mecab_sparse_tostr' or
'mecab_nbest_sparse_tostr'.

Returns:
A function definition, tailored to parsing Unicode text and
returning the result as a string suitable for display on stdout,
using either the default or N-best behavior.


def set_agent(self, short_name, client_id):
    if (short_name not in self.services):
        raise ArgumentError('Unknown service name', short_name=short_name)
    self.agents[short_name] = client_id

Register a client id that handlers commands for a service.

Args:
short_name (str): The name of the service to set an agent
for.
client_id (str): A globally unique id for the client that
should receive commands for this service.


def new_panel(store, institute_id, panel_name, display_name, csv_lines):
    institute_obj = store.institute(institute_id)
    if (institute_obj is None):
        flash('{}: institute not found'.format(institute_id))
        return None
    panel_obj = store.gene_panel(panel_name)
    if panel_obj:
        flash('panel already exists: {} - {}'.format(panel_obj['panel_name'], panel_obj['display_name']))
        return None
    log.debug('parse genes from CSV input')
    try:
        new_genes = parse_genes(csv_lines)
    except SyntaxError as error:
        flash(error.args[0], 'danger')
        return None
    log.debug('build new gene panel')
    panel_id = None
    try:
        panel_data = build_panel(dict(panel_name=panel_name, institute=institute_obj['_id'], version=1.0, date=dt.datetime.now(), display_name=display_name, genes=new_genes), store)
        panel_id = store.add_gene_panel(panel_data)
    except Exception as err:
        log.error('An error occurred while adding the gene panel {}'.format(err))
    return panel_id

Create a new gene panel.

Args:
store(scout.adapter.MongoAdapter)
institute_id(str)
panel_name(str)
display_name(str)
csv_lines(iterable(str)): Stream with genes

Returns:
panel_id: the ID of the new panel document created or None


def __init__(self, args=None, varargs=None, varkw=None, defaults=None, kwonlyargs=None, kwonlydefaults=None, annotations=None):
    self.args = args or []
    self.varargs = varargs
    self.varkw = varkw
    self.defaults = defaults or ()
    self.kwonlyargs = kwonlyargs or []
    self.kwonlydefaults = kwonlydefaults or {}
    self.annotations = annotations or {}

Constructs a FullArgSpec with each provided attribute, or the default.

Args:
args: A list of the argument names accepted by the function.
varargs: The name of the *varargs argument or None if there isn't one.
varkw: The name of the **kwargs argument or None if there isn't one.
defaults: A tuple of the defaults for the arguments that accept defaults.
kwonlyargs: A list of argument names that must be passed with a keyword.
kwonlydefaults: A dictionary of keyword only arguments and their defaults.
annotations: A dictionary of arguments and their annotated types.


def clock(self, interval, basis):

        cache_name = self._classify_clock(interval, basis)
        cache_data = self.clock_cache.get(cache_name)

        if cache_data is None:
            parent_stream, trigger = self.parent.clock(interval, basis)

            if trigger.use_count is False:
                raise SensorGraphSemanticError("Unsupported clock trigger in GatedClockScope", trigger=trigger)
            elif interval % trigger.reference != 0:
                raise SensorGraphSemanticError("Unsupported trigger ratio in GatedClockScope", trigger=trigger, interval=interval)

            ratio = interval

            stream = self.allocator.allocate_stream(DataStream.CounterType)
            latch_stream = self.allocator.attach_stream(self.latch_stream)

            self.sensor_graph.add_node(u'({} always && {} {}) => {} using copy_latest_a'.format(parent_stream, latch_stream, self.latch_trigger, stream))
            self.clock_cache[cache_name] = (stream, ratio)
        else:
            stream, ratio = cache_data

        if interval % ratio != 0:
            raise SensorGraphSemanticError("Unsupported trigger ratio in GatedClockScope", ratio=ratio, interval=interval)

        count = interval

        clock_stream = self.allocator.attach_stream(stream)
        return clock_stream, InputTrigger(u'count', '>=', count)

Return a NodeInput tuple for triggering an event every interval.

We request each distinct type of clock at most once and combine it with our
latch stream each time it is requested.

Args:
interval (int): The interval (in seconds) at which this input should
trigger.


def floor(cls, x: 'TensorFluent') -> 'TensorFluent':
    return cls._unary_op(x, tf.floor, tf.float32)

Returns a TensorFluent for the floor function.

Args:
x: The input fluent.

Returns:
A TensorFluent wrapping the floor function.


def _get_grand_potential(self, composition):

        if self.use_hull_energy:
            grand_potential = self.pd_non_grand.get_hull_energy(composition)
        else:
            grand_potential = InterfacialReactivity._get_entry_energy(
                self.pd_non_grand, composition)
        grand_potential -= sum([composition[e] * mu
                                for e, mu in self.pd.chempots.items()])
        if self.norm:

            grand_potential /= sum([composition[el]
                                    for el in composition
                                    if el not in self.pd.chempots])
        return grand_potential

Computes the grand potential Phi at a given composition and
chemical potential(s).

Args:
composition (Composition): Composition object.

Returns:
Grand potential at a given composition at chemical potential(s).


def generate(arglist, git_tag_override=None):
    spec, head_symlink, _, dest_file = arglist
    data = json.load(open(spec))
    git_version = None
    if not data['git']:
        git_version = b'unknown'
    else:
        old_branch = data['branch']
        new_branch = parse_branch_ref(head_symlink)
        if new_branch != old_branch:
            raise RuntimeError("Run ./configure again, branch was '%s' but is now '%s'" % (old_branch, new_branch))
        git_version = get_git_version(data['path'], git_tag_override)
    write_version_info(dest_file, git_version)

Generate version_info.cc as given `destination_file`.

Args:
arglist: should be a sequence that contains
spec, head_symlink, ref_symlink, destination_file.

`destination_file` is the filename where version_info.cc will be written

`spec` is a filename where the file contains a JSON dictionary
'git' bool that is true if the source is in a git repo
'path' base path of the source code
'branch' the name of the ref specification of the current branch/tag

`head_symlink` is a filename to HEAD that is cross-referenced against
what is contained in the json branch designation.

`ref_symlink` is unused in this script but passed, because the build
system uses that file to detect when commits happen.

git_tag_override: Override the value for the git tag. This is useful for
releases where we want to build the release before the git tag is
created.

Raises:
RuntimeError: If ./configure needs to be run, RuntimeError will be raised.


def is_location(v) -> (bool, str):

    def convert2float(value):
        try:
            float_num = float(value)
            return float_num
        except ValueError:
            return False
    if (not isinstance(v, str)):
        return (False, v)
    split_lst = v.split(':')
    if (len(split_lst) != 5):
        return (False, v)
    if convert2float(split_lst[3]):
        longitude = abs(convert2float(split_lst[3]))
        if (longitude > 90):
            return (False, v)
    if convert2float(split_lst[4]):
        latitude = abs(convert2float(split_lst[3]))
        if (latitude > 180):
            return (False, v)
    return (True, v)

Boolean function for checking if v is a location format

Args:
v:
Returns: bool


def save_link(self, path_info):

        assert path_info["scheme"] == "local"
        path = path_info["path"]

        if not os.path.exists(path):
            return

        mtime, _ = get_mtime_and_size(path)
        inode = get_inode(path)
        relpath = os.path.relpath(path, self.root_dir)

        cmd = (
            "REPLACE INTO {}(path, inode, mtime) "
            'VALUES ("{}", {}, "{}")'.format(
                self.LINK_STATE_TABLE, relpath, self._to_sqlite(inode), mtime
            )
        )
        self._execute(cmd)

Adds the specified path to the list of links created by dvc. This
list is later used on `dvc checkout` to cleanup old links.

Args:
path_info (dict): path info to add to the list of links.


def __init__(self, label, names=(), path=None):

        self.label = label
        self.names = names
        self.path = path
        for name in names:
            setattr(self, name, self.__class__(name, path="{0}.{1}".format(path, label) if path else label))

Create a new enumeration.  The parent enum creates an instance for each item.

Args:
label (str): enum name
names (list): item labels
path (list): qualified parent name, for :func:`repr` output


def output(self, filename):

        if filename == '':
            filename = 'contracts.dot'
        if not filename.endswith('.dot'):
            filename += ".dot"
        info = 'Inheritance Graph: ' + filename
        self.info(info)
        with open(filename, 'w', encoding='utf8') as f:
            f.write('digraph "" {\n')
            for c in self.contracts:
                f.write(self._summary(c))
            f.write('}')

Output the graph in filename
Args:
filename(string)


def show(config, section, opt):

        if section not in config.keys():
            raise ConfigError("section '{}' doesn't exist".format(section))

        if opt not in config[section].keys():
            raise ConfigError(
                "option '{}.{}' doesn't exist".format(section, opt)
            )

        logger.info(config[section][opt])

Prints option value from the config.

Args:
config (configobj.ConfigObj): config to work on.
section (str): section name.
opt (str): option name.


def _generate_parser(name, path, required=False, notfoundmsg=None):
    output = ('def %s(dom):\n' % _get_parser_name(name))
    dom = True
    parser_table = {'find': (lambda path: _find_template(path.params, path.index, required, notfoundmsg)), 'wfind': (lambda path: _wfind_template(dom, path.params, path.index, required, notfoundmsg)), 'match': (lambda path: _match_template(path.params, path.index, required, notfoundmsg)), 'left_neighbour_tag': (lambda path: _neigh_template(path.params, path.index, True, required, notfoundmsg)), 'right_neighbour_tag': (lambda path: _neigh_template(path.params, path.index, False, required, notfoundmsg))}
    if isinstance(path, path_patterns.PathCall):
        output += parser_table[path.call_type](path)
    elif isinstance(path, path_patterns.Chained):
        for path in path.chain:
            output += parser_table[path.call_type](path)
            dom = False
    else:
        raise UserWarning(('Unknown type of path parameters! (%s)' % str(path)))
    output += (IND + 'return el\n')
    output += '\n\n'
    return output

Generate parser named `name` for given `path`.

Args:
name (str): Basename for the parsing function (see
:func:`_get_parser_name` for details).
path (obj): :class:`.PathCall` or :class:`.Chained` instance.
required (bool, default False): Use :func:`_required_idiom` to returned
data.
notfoundmsg (str, default None): Message which will be used for
:func:`_required_idiom` if the item is not found.

Returns:
str: Python code for parsing `path`.


def plot_iso(axis, step, var):
    (xmesh, ymesh, fld) = get_meshes_fld(step, var)
    if conf.field.shift:
        fld = np.roll(fld, conf.field.shift, axis=0)
    axis.contour(xmesh, ymesh, fld, linewidths=1)

Plot isocontours of scalar field.

Args:
axis (:class:`matplotlib.axes.Axes`): the axis handler of an
existing matplotlib figure where the isocontours should
be plotted.
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
var (str): the scalar field name.


def predict(self, text):

        pred = self.predict_proba(text)
        tags = self._get_tags(pred)

        return tags

Predict using the model.

Args:
text: string, the input text.

Returns:
tags: list, shape = (num_words,)
Returns predicted values.


Converts given quaternion (x, y, z, w) to matrix.

Args:
quaternion: vec4 float angles

Returns:
3x3 rotation matrix


def AddEnumDescriptor(self, enum_desc):

    if not isinstance(enum_desc, descriptor.EnumDescriptor):
      raise TypeError('Expected instance of descriptor.EnumDescriptor.')

    self._enum_descriptors[enum_desc.full_name] = enum_desc
    self.AddFileDescriptor(enum_desc.file)

Adds an EnumDescriptor to the pool.

This method also registers the FileDescriptor associated with the message.

Args:
enum_desc: An EnumDescriptor.


def multi_flags_validator(flag_names, message='Flag validation failed', flag_values=FLAGS):

    def decorate(function):
        register_multi_flags_validator(flag_names, function, message=message, flag_values=flag_values)
        return function
    return decorate

A function decorator for defining a multi-flag validator.

Registers the decorated function as a validator for flag_names, e.g.

@gflags.multi_flags_validator(['foo', 'bar'])
def _CheckFooBar(flags_dict):
...

See register_multi_flags_validator() for the specification of checker
function.

Args:
flag_names: [str], a list of the flag names to be checked.
message: error text to be shown to the user if checker returns False.
If checker raises ValidationError, message from the raised
error will be shown.
flag_values: An optional FlagValues instance to validate against.

Returns:
A function decorator that registers its function argument as a validator.

Raises:
AttributeError: If a flag is not registered as a valid flag name.


def BalanceFor(self, assetId):
    for (key, fixed8) in self.Balances.items():
        if (key == assetId):
            return fixed8
    return Fixed8(0)

Get the balance for a given asset id.

Args:
assetId (UInt256):

Returns:
Fixed8: balance value.


def _init_from_bool(self, z, x):
    if (z is None):
        raise QiskitError('z vector must not be None.')
    if (x is None):
        raise QiskitError('x vector must not be None.')
    if (len(z) != len(x)):
        raise QiskitError('length of z and x vectors must be the same. (z: {} vs x: {})'.format(len(z), len(x)))
    z = _make_np_bool(z)
    x = _make_np_bool(x)
    self._z = z
    self._x = x
    return self

Construct pauli from boolean array.

Args:
z (numpy.ndarray): boolean, z vector
x (numpy.ndarray): boolean, x vector

Returns:
Pauli: self

Raises:
QiskitError: if z or x are None or the length of z and x are different.


def remove_child(self, child):

        if child in self.children.values() and hasattr(child, 'identifier'):
            for k in self.children.keys():
                if hasattr(self.children[k], 'identifier'):
                    if self.children[k].identifier == child.identifier:
                        if k in self._render_children_list:
                            self._render_children_list.remove(k)
                        self.children.pop(k)

                        break

Removes a child instance from the Tag's children.

Args:
child (Tag): The child to be removed.