INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Connects the module to some inputs.
Args:
inputs: Tensor, final dimension must be equal to embedding_dim. All other
leading dimensions will be flattened and treated as a large batch.
is_training: boolean, whether this connection is to training data.
Returns:
dict containing the follo... | def _build(self, inputs, is_training):
"""Connects the module to some inputs.
Args:
inputs: Tensor, final dimension must be equal to embedding_dim. All other
leading dimensions will be flattened and treated as a large batch.
is_training: boolean, whether this connection is to training data.... |
Connects the module to some inputs.
Args:
inputs: Tensor, final dimension must be equal to embedding_dim. All other
leading dimensions will be flattened and treated as a large batch.
is_training: boolean, whether this connection is to training data. When
this is set to False, the intern... | def _build(self, inputs, is_training):
"""Connects the module to some inputs.
Args:
inputs: Tensor, final dimension must be equal to embedding_dim. All other
leading dimensions will be flattened and treated as a large batch.
is_training: boolean, whether this connection is to training data.... |
Add two arbitrarily nested `Tensors`. | def _nested_add(nested_a, nested_b):
"""Add two arbitrarily nested `Tensors`."""
return nest.map(lambda a, b: a + b, nested_a, nested_b) |
Multiply `Tensors` in arbitrarily nested `Tensor` `nested_a` with `p`. | def _nested_unary_mul(nested_a, p):
"""Multiply `Tensors` in arbitrarily nested `Tensor` `nested_a` with `p`."""
def mul_with_broadcast(tensor):
ndims = tensor.shape.ndims
if ndims != 2:
p_reshaped = tf.reshape(p, [-1] + [1] * (ndims - 1))
return p_reshaped * tensor
else:
return p * te... |
The `cond` of the `tf.while_loop`. | def _cond(self, unused_x, unused_cumul_out, unused_prev_state,
unused_cumul_state, cumul_halting, unused_iteration,
unused_remainder):
"""The `cond` of the `tf.while_loop`."""
return tf.reduce_any(cumul_halting < 1) |
The `body` of `tf.while_loop`. | def _body(self, x, cumul_out, prev_state, cumul_state,
cumul_halting, iteration, remainder, halting_linear, x_ones):
"""The `body` of `tf.while_loop`."""
# Increase iteration count only for those elements that are still running.
all_ones = tf.constant(1, shape=(self._batch_size, 1), dtype=self._... |
Connects the core to the graph.
Args:
x: Input `Tensor` of shape `(batch_size, input_size)`.
prev_state: Previous state. This could be a `Tensor`, or a tuple of
`Tensor`s.
Returns:
The tuple `(output, state)` for this core.
Raises:
ValueError: if the `Tensor` `x` does no... | def _build(self, x, prev_state):
"""Connects the core to the graph.
Args:
x: Input `Tensor` of shape `(batch_size, input_size)`.
prev_state: Previous state. This could be a `Tensor`, or a tuple of
`Tensor`s.
Returns:
The tuple `(output, state)` for this core.
Raises:
... |
Custom getter to restore all variables with `snt.restore_initializer`.
Args:
filename: The filename of the checkpoint.
name_fn: A function which can map the name of the variable requested. This
allows restoring variables with values having different names in the
checkpoint.
collection: Only s... | def restore_initializer(filename, name_fn=None,
collection=tf.GraphKeys.GLOBAL_VARIABLES):
"""Custom getter to restore all variables with `snt.restore_initializer`.
Args:
filename: The filename of the checkpoint.
name_fn: A function which can map the name of the variable requested. ... |
Calculate a reasonable embedding size for a vocabulary.
Rule of thumb is 6 * 4th root of vocab_size.
Args:
vocab_size: Size of the input vocabulary.
Returns:
The embedding size to use.
Raises:
ValueError: if `vocab_size` is invalid. | def _embedding_dim(vocab_size):
"""Calculate a reasonable embedding size for a vocabulary.
Rule of thumb is 6 * 4th root of vocab_size.
Args:
vocab_size: Size of the input vocabulary.
Returns:
The embedding size to use.
Raises:
ValueError: if `vocab_size` is invalid.
"""
if not vocab_size or... |
Lookup embeddings.
Looks up an embedding vector for each value in `ids`. All ids must be within
[0, vocab_size), else an `InvalidArgumentError` is raised at runtime.
Args:
ids: Tensor of dtype int64.
Returns:
Tensor of tf.shape(ids) + [embedding_dim] and dtype float32. | def _build(self, ids):
"""Lookup embeddings.
Looks up an embedding vector for each value in `ids`. All ids must be within
[0, vocab_size), else an `InvalidArgumentError` is raised at runtime.
Args:
ids: Tensor of dtype int64.
Returns:
Tensor of tf.shape(ids) + [embedding_dim] and dtyp... |
Generates n-dimensional homogenous coordinates for a given grid definition.
`source_shape` and `output_shape` are used to define the size of the source
and output signal domains, as opposed to the shape of the respective
Tensors. For example, for an image of size `width=W` and `height=H`,
`{source,output}_shap... | def _create_affine_features(output_shape, source_shape):
"""Generates n-dimensional homogenous coordinates for a given grid definition.
`source_shape` and `output_shape` are used to define the size of the source
and output signal domains, as opposed to the shape of the respective
Tensors. For example, for an i... |
Creates all the matrices needed to compute the output warped grids. | def _create_features(self, constraints):
"""Creates all the matrices needed to compute the output warped grids."""
affine_warp_constraints = constraints
if not isinstance(affine_warp_constraints, AffineWarpConstraints):
affine_warp_constraints = AffineWarpConstraints(affine_warp_constraints)
mask ... |
Assembles the module network and adds it to the graph.
The internal computation graph is assembled according to the set of
constraints provided at construction time.
Args:
inputs: Tensor containing a batch of transformation parameters.
Returns:
A batch of warped grids.
Raises:
... | def _build(self, inputs):
"""Assembles the module network and adds it to the graph.
The internal computation graph is assembled according to the set of
constraints provided at construction time.
Args:
inputs: Tensor containing a batch of transformation parameters.
Returns:
A batch of ... |
Returns a `sonnet` module to compute inverse affine transforms.
The function first assembles a network that given the constraints of the
current AffineGridWarper and a set of input parameters, retrieves the
coefficients of the corresponding inverse affine transform, then feeds its
output into a... | def inverse(self, name=None):
"""Returns a `sonnet` module to compute inverse affine transforms.
The function first assembles a network that given the constraints of the
current AffineGridWarper and a set of input parameters, retrieves the
coefficients of the corresponding inverse affine transfor... |
Computes a boolean mask from the user defined constraints. | def _calc_mask(self):
"""Computes a boolean mask from the user defined constraints."""
mask = []
for row in self._constraints:
mask.append(tuple(x is None for x in row))
return tuple(mask) |
Combines two constraints, raising an error if they are not compatible. | def _combine(self, x, y):
"""Combines two constraints, raising an error if they are not compatible."""
if x is None or y is None:
return x or y
if x != y:
raise ValueError('Incompatible set of constraints provided.')
return x |
Combines two sets of constraints into a coherent single set. | def combine_with(self, additional_constraints):
"""Combines two sets of constraints into a coherent single set."""
x = additional_constraints
if not isinstance(additional_constraints, AffineWarpConstraints):
x = AffineWarpConstraints(additional_constraints)
new_constraints = []
for left, right... |
Build magic (and sparsely documented) shapes_and_slices spec string. | def _partition_spec(self, shape, partition_info):
"""Build magic (and sparsely documented) shapes_and_slices spec string."""
if partition_info is None:
return '' # Empty string indicates a non-partitioned tensor.
ssi = tf.Variable.SaveSliceInfo(
full_name=self._var_name,
full_shape=pa... |
Bake an ``ansible-playbook`` command so it's ready to execute and
returns ``None``.
:return: None | def bake(self):
"""
Bake an ``ansible-playbook`` command so it's ready to execute and
returns ``None``.
:return: None
"""
# Pass a directory as inventory to let Ansible merge the multiple
# inventory sources located under
self.add_cli_arg('inventory',
... |
Executes ``ansible-playbook`` and returns a string.
:return: str | def execute(self):
"""
Executes ``ansible-playbook`` and returns a string.
:return: str
"""
if self._ansible_command is None:
self.bake()
try:
self._config.driver.sanity_checks()
cmd = util.run_command(
self._ansible_c... |
Log in to one instance. | def login(ctx, host, scenario_name): # pragma: no cover
""" Log in to one instance. """
args = ctx.obj.get('args')
subcommand = base._get_subcommand(__name__)
command_args = {
'subcommand': subcommand,
'host': host,
}
s = scenarios.Scenarios(
base.get_configs(args, comm... |
Execute the actions necessary to perform a `molecule login` and
returns None.
:return: None | def execute(self):
"""
Execute the actions necessary to perform a `molecule login` and
returns None.
:return: None
"""
c = self._config
if ((not c.state.created) and c.driver.managed):
msg = 'Instances not created. Please create instances first.'
... |
Execute scenario sequences based on parsed command-line arguments.
This is useful for subcommands that run scenario sequences, which
excludes subcommands such as ``list``, ``login``, and ``matrix``.
``args`` and ``command_args`` are combined using :func:`get_configs`
to generate the scenario(s) config... | def execute_cmdline_scenarios(scenario_name, args, command_args):
"""
Execute scenario sequences based on parsed command-line arguments.
This is useful for subcommands that run scenario sequences, which
excludes subcommands such as ``list``, ``login``, and ``matrix``.
``args`` and ``command_args``... |
Execute each command in the given scenario's configured sequence.
:param scenario: The scenario to execute.
:returns: None | def execute_scenario(scenario):
"""
Execute each command in the given scenario's configured sequence.
:param scenario: The scenario to execute.
:returns: None
"""
for action in scenario.sequence:
execute_subcommand(scenario.config, action)
# pruning only if a 'destroy' step was i... |
Glob the current directory for Molecule config files, instantiate config
objects, and returns a list.
:param args: A dict of options, arguments and commands from the CLI.
:param command_args: A dict of options passed to the subcommand from
the CLI.
:param ansible_args: An optional tuple of argumen... | def get_configs(args, command_args, ansible_args=()):
"""
Glob the current directory for Molecule config files, instantiate config
objects, and returns a list.
:param args: A dict of options, arguments and commands from the CLI.
:param command_args: A dict of options passed to the subcommand from
... |
Verify a Molecule config was found and returns None.
:param configs: A list containing absolute paths to Molecule config files.
:return: None | def _verify_configs(configs):
"""
Verify a Molecule config was found and returns None.
:param configs: A list containing absolute paths to Molecule config files.
:return: None
"""
if configs:
scenario_names = [c.scenario.name for c in configs]
for scenario_name, n in collections... |
Bake a ``gilt`` command so it's ready to execute and returns None.
:return: None | def bake(self):
"""
Bake a ``gilt`` command so it's ready to execute and returns None.
:return: None
"""
self._sh_command = getattr(sh, self.command)
self._sh_command = self._sh_command.bake(
self.options,
'overlay',
_env=self.env,
... |
Execute the actions necessary to cleanup the instances and returns
None.
:return: None | def execute(self):
"""
Execute the actions necessary to cleanup the instances and returns
None.
:return: None
"""
self.print_info()
if not self._config.provisioner.playbooks.cleanup:
msg = 'Skipping, cleanup playbook not configured.'
LOG.... |
Bake an `ansible-lint` command so it's ready to execute and returns
None.
:return: None | def bake(self):
"""
Bake an `ansible-lint` command so it's ready to execute and returns
None.
:return: None
"""
options = self.options
default_exclude_list = options.pop('default_exclude')
options_exclude_list = options.pop('exclude')
excludes = d... |
Print ``Ansible`` and ``Molecule`` environment variables and returns None.
:param env: A dict containing the shell's environment as collected by
``os.environ``.
:return: None | def print_environment_vars(env):
"""
Print ``Ansible`` and ``Molecule`` environment variables and returns None.
:param env: A dict containing the shell's environment as collected by
``os.environ``.
:return: None
"""
ansible_env = {k: v for (k, v) in env.items() if 'ANSIBLE_' in k}
print... |
Execute the given command and returns None.
:param cmd: A ``sh.Command`` object to execute.
:param debug: An optional bool to toggle debug output.
:return: ``sh`` object | def run_command(cmd, debug=False):
"""
Execute the given command and returns None.
:param cmd: A ``sh.Command`` object to execute.
:param debug: An optional bool to toggle debug output.
:return: ``sh`` object
"""
if debug:
# WARN(retr0h): Uses an internal ``sh`` data structure to di... |
Writes a file with the given filename and content and returns None.
:param filename: A string containing the target filename.
:param content: A string containing the data to be written.
:return: None | def write_file(filename, content):
"""
Writes a file with the given filename and content and returns None.
:param filename: A string containing the target filename.
:param content: A string containing the data to be written.
:return: None
"""
with open_file(filename, 'w') as f:
f.wr... |
Prepend an informational header on files managed by Molecule and returns
None.
:param filename: A string containing the target filename.
:return: None | def file_prepender(filename):
"""
Prepend an informational header on files managed by Molecule and returns
None.
:param filename: A string containing the target filename.
:return: None
"""
with open_file(filename, 'r+') as f:
content = f.read()
f.seek(0, 0)
f.write(m... |
Dump the provided data to a YAML document and returns a string.
:param data: A string containing an absolute path to the file to parse.
:return: str | def safe_dump(data):
"""
Dump the provided data to a YAML document and returns a string.
:param data: A string containing an absolute path to the file to parse.
:return: str
"""
# TODO(retr0h): Do we need to encode?
# yaml.dump(data) produces the document as a str object in both python
... |
Parse the provided string returns a dict.
:param string: A string to be parsed.
:return: dict | def safe_load(string):
"""
Parse the provided string returns a dict.
:param string: A string to be parsed.
:return: dict
"""
try:
return yaml.safe_load(string) or {}
except yaml.scanner.ScannerError as e:
sysexit_with_message(str(e)) |
Merges the values of B into A and returns a mutated dict A.
::
dict a
b:
- c: 0
- c: 2
d:
e: "aaa"
f: 3
dict b
a: 1
b:
- c: 3
d:
e: "bbb"
Will give an object such as::
{'a': 1... | def merge_dicts(a, b):
"""
Merges the values of B into A and returns a mutated dict A.
::
dict a
b:
- c: 0
- c: 2
d:
e: "aaa"
f: 3
dict b
a: 1
b:
- c: 3
d:
e: "bbb"
Will give a... |
Ensure value uniqueness.
The rule's arguments are validated against this schema:
{'type': 'boolean'} | def _validate_unique(self, unique, field, value):
"""Ensure value uniqueness.
The rule's arguments are validated against this schema:
{'type': 'boolean'}
"""
if unique:
root_key = self.schema_path[0]
data = (doc[field] for doc in self.root_document[root_k... |
Readonly but with a custom error.
The rule's arguments are validated against this schema:
{'type': 'boolean'} | def _validate_disallowed(self, disallowed, field, value):
""" Readonly but with a custom error.
The rule's arguments are validated against this schema:
{'type': 'boolean'}
"""
if disallowed:
msg = 'disallowed user provided config option'
self._error(field... |
Readonly but with a custom error.
The rule's arguments are validated against this schema:
{'type': 'boolean'} | def _validate_molecule_env_var(self, molecule_env_var, field, value):
""" Readonly but with a custom error.
The rule's arguments are validated against this schema:
{'type': 'boolean'}
"""
# TODO(retr0h): This needs to be better handled.
pattern = r'^[{$]+MOLECULE[_a-z0-9... |
Execute the actions necessary to perform a `molecule idempotence` and
returns None.
:return: None | def execute(self):
"""
Execute the actions necessary to perform a `molecule idempotence` and
returns None.
:return: None
"""
self.print_info()
if not self._config.state.converged:
msg = 'Instances not converged. Please converge instances first.'
... |
Parses the output of the provisioning for changed and returns a bool.
:param output: A string containing the output of the ansible run.
:return: bool | def _is_idempotent(self, output):
"""
Parses the output of the provisioning for changed and returns a bool.
:param output: A string containing the output of the ansible run.
:return: bool
"""
# Remove blank lines to make regex matches easier
output = re.sub(r'\n... |
Parses the output to identify the non idempotent tasks.
:param (str) output: A string containing the output of the ansible run.
:return: A list containing the names of the non idempotent tasks. | def _non_idempotent_tasks(self, output):
"""
Parses the output to identify the non idempotent tasks.
:param (str) output: A string containing the output of the ansible run.
:return: A list containing the names of the non idempotent tasks.
"""
# Remove blank lines to make... |
Initialize a new scenario for use with Molecule. | def scenario(ctx, dependency_name, driver_name, lint_name, provisioner_name,
role_name, scenario_name, verifier_name): # pragma: no cover
""" Initialize a new scenario for use with Molecule. """
command_args = {
'dependency_name': dependency_name,
'driver_name': driver_name,
... |
Execute the actions necessary to perform a `molecule init scenario` and
returns None.
:return: None | def execute(self):
"""
Execute the actions necessary to perform a `molecule init scenario` and
returns None.
:return: None
"""
scenario_name = self._command_args['scenario_name']
role_name = os.getcwd().split(os.sep)[-1]
role_directory = util.abs_path(os.... |
Implement Docker driver sanity checks. | def sanity_checks(self):
"""Implement Docker driver sanity checks."""
if self._config.state.sanity_checked:
return
log.info("Sanity checks: '{}'".format(self._name))
HAS_DOCKER_PY = None
try:
from ansible.module_utils.docker_common import HAS_DOCKER_PY
... |
Bake a `flake8` command so it's ready to execute and returns None.
:return: None | def bake(self):
"""
Bake a `flake8` command so it's ready to execute and returns None.
:return: None
"""
self._flake8_command = sh.flake8.bake(
self.options,
self._tests,
_env=self.env,
_out=LOG.out,
_err=LOG.error) |
Prepare the system for using ``ansible-galaxy`` and returns None.
:return: None | def _setup(self):
"""
Prepare the system for using ``ansible-galaxy`` and returns None.
:return: None
"""
role_directory = os.path.join(self._config.scenario.directory,
self.options['roles-path'])
if not os.path.isdir(role_directory)... |
Use the provisioner to configure instances (dependency, create, prepare
converge). | def converge(ctx, scenario_name, ansible_args): # pragma: no cover
"""
Use the provisioner to configure instances (dependency, create, prepare
converge).
"""
args = ctx.obj.get('args')
subcommand = base._get_subcommand(__name__)
command_args = {
'subcommand': subcommand,
}
... |
Execute the actions necessary to perform a `molecule converge` and
returns None.
:return: None | def execute(self):
"""
Execute the actions necessary to perform a `molecule converge` and
returns None.
:return: None
"""
self.print_info()
self._config.provisioner.converge()
self._config.state.change_state('converged', True) |
Return a list containing all scenario objects.
:return: list | def all(self):
"""
Return a list containing all scenario objects.
:return: list
"""
if self._scenario_name:
scenarios = self._filter_for_scenario()
self._verify()
return scenarios
scenarios = [c.scenario for c in self._configs]
... |
Verify the specified scenario was found and returns None.
:return: None | def _verify(self):
"""
Verify the specified scenario was found and returns None.
:return: None
"""
scenario_names = [c.scenario.name for c in self._configs]
if self._scenario_name not in scenario_names:
msg = ("Scenario '{}' not found. "
'... |
Find the scenario matching the provided scenario name and returns a
list.
:return: list | def _filter_for_scenario(self):
"""
Find the scenario matching the provided scenario name and returns a
list.
:return: list
"""
return [
c.scenario for c in self._configs
if c.scenario.name == self._scenario_name
] |
Build a matrix of scenarios with sequence to include and returns a
dict.
{
scenario_1: {
'subcommand': [
'action-1',
'action-2',
],
},
scenario_2: {
'subcommand': [
... | def _get_matrix(self):
"""
Build a matrix of scenarios with sequence to include and returns a
dict.
{
scenario_1: {
'subcommand': [
'action-1',
'action-2',
],
},
scenario_2: {
... |
Build a logger with the given name and returns the logger.
:param name: The name for the logger. This is usually the module
name, ``__name__``.
:return: logger object | def get_logger(name=None):
"""
Build a logger with the given name and returns the logger.
:param name: The name for the logger. This is usually the module
name, ``__name__``.
:return: logger object
"""
logging.setLoggerClass(CustomLogger)
logger = logging.getLogger(name)
... |
Lint the role. | def lint(ctx, scenario_name): # pragma: no cover
""" Lint the role. """
args = ctx.obj.get('args')
subcommand = base._get_subcommand(__name__)
command_args = {
'subcommand': subcommand,
}
base.execute_cmdline_scenarios(scenario_name, args, command_args) |
Execute the actions necessary to perform a `molecule lint` and
returns None.
:return: None | def execute(self):
"""
Execute the actions necessary to perform a `molecule lint` and
returns None.
:return: None
"""
self.print_info()
linters = [
l for l in [
self._config.lint,
self._config.verifier.lint,
... |
Create an inventory structure and returns a dict.
.. code-block:: yaml
ungrouped:
vars:
foo: bar
hosts:
instance-1:
instance-2:
children:
$child_group_name:
hosts:
... | def inventory(self):
"""
Create an inventory structure and returns a dict.
.. code-block:: yaml
ungrouped:
vars:
foo: bar
hosts:
instance-1:
instance-2:
children:
$child_group_n... |
Executes `ansible-playbook` against the cleanup playbook and returns
None.
:return: None | def cleanup(self):
"""
Executes `ansible-playbook` against the cleanup playbook and returns
None.
:return: None
"""
pb = self._get_ansible_playbook(self.playbooks.cleanup)
pb.execute() |
Executes ``ansible-playbook`` against the converge playbook unless
specified otherwise and returns a string.
:param playbook: An optional string containing an absolute path to a
playbook.
:param kwargs: An optional keyword arguments.
:return: str | def converge(self, playbook=None, **kwargs):
"""
Executes ``ansible-playbook`` against the converge playbook unless
specified otherwise and returns a string.
:param playbook: An optional string containing an absolute path to a
playbook.
:param kwargs: An optional keywor... |
Executes ``ansible-playbook`` against the destroy playbook and returns
None.
:return: None | def destroy(self):
"""
Executes ``ansible-playbook`` against the destroy playbook and returns
None.
:return: None
"""
pb = self._get_ansible_playbook(self.playbooks.destroy)
pb.execute() |
Executes ``ansible-playbook`` against the side_effect playbook and
returns None.
:return: None | def side_effect(self):
"""
Executes ``ansible-playbook`` against the side_effect playbook and
returns None.
:return: None
"""
pb = self._get_ansible_playbook(self.playbooks.side_effect)
pb.execute() |
Executes ``ansible-playbook`` against the create playbook and returns
None.
:return: None | def create(self):
"""
Executes ``ansible-playbook`` against the create playbook and returns
None.
:return: None
"""
pb = self._get_ansible_playbook(self.playbooks.create)
pb.execute() |
Executes ``ansible-playbook`` against the prepare playbook and returns
None.
:return: None | def prepare(self):
"""
Executes ``ansible-playbook`` against the prepare playbook and returns
None.
:return: None
"""
pb = self._get_ansible_playbook(self.playbooks.prepare)
pb.execute() |
Executes ``ansible-playbook`` against the converge playbook with the
``-syntax-check`` flag and returns None.
:return: None | def syntax(self):
"""
Executes ``ansible-playbook`` against the converge playbook with the
``-syntax-check`` flag and returns None.
:return: None
"""
pb = self._get_ansible_playbook(self.playbooks.converge)
pb.add_cli_arg('syntax-check', True)
pb.execute(... |
Executes ``ansible-playbook`` against the verify playbook and returns
None.
:return: None | def verify(self):
"""
Executes ``ansible-playbook`` against the verify playbook and returns
None.
:return: None
"""
pb = self._get_ansible_playbook(self.playbooks.verify)
pb.execute() |
Writes the provisioner's config file to disk and returns None.
:return: None | def write_config(self):
"""
Writes the provisioner's config file to disk and returns None.
:return: None
"""
template = util.render_template(
self._get_config_template(), config_options=self.config_options)
util.write_file(self.config_file, template) |
Manages inventory for Ansible and returns None.
:returns: None | def manage_inventory(self):
"""
Manages inventory for Ansible and returns None.
:returns: None
"""
self._write_inventory()
self._remove_vars()
if not self.links:
self._add_or_update_vars()
else:
self._link_or_update_vars() |
Creates host and/or group vars and returns None.
:returns: None | def _add_or_update_vars(self):
"""
Creates host and/or group vars and returns None.
:returns: None
"""
# Create the hosts extra inventory source (only if not empty)
hosts_file = os.path.join(self.inventory_directory, 'hosts')
if self.hosts:
util.write... |
Writes the provisioner's inventory file to disk and returns None.
:return: None | def _write_inventory(self):
"""
Writes the provisioner's inventory file to disk and returns None.
:return: None
"""
self._verify_inventory()
util.write_file(self.inventory_file, util.safe_dump(self.inventory)) |
Remove hosts/host_vars/group_vars and returns None.
:returns: None | def _remove_vars(self):
"""
Remove hosts/host_vars/group_vars and returns None.
:returns: None
"""
for name in ("hosts", "group_vars", "host_vars"):
d = os.path.join(self.inventory_directory, name)
if os.path.islink(d) or os.path.isfile(d):
... |
Creates or updates the symlink to group_vars and returns None.
:returns: None | def _link_or_update_vars(self):
"""
Creates or updates the symlink to group_vars and returns None.
:returns: None
"""
for d, source in self.links.items():
target = os.path.join(self.inventory_directory, d)
source = os.path.join(self._config.scenario.direc... |
Get an instance of AnsiblePlaybook and returns it.
:param playbook: A string containing an absolute path to a
provisioner's playbook.
:param kwargs: An optional keyword arguments.
:return: object | def _get_ansible_playbook(self, playbook, **kwargs):
"""
Get an instance of AnsiblePlaybook and returns it.
:param playbook: A string containing an absolute path to a
provisioner's playbook.
:param kwargs: An optional keyword arguments.
:return: object
"""
... |
Walk the project directory for tests and returns a list.
:return: list | def _get_files(self):
"""
Walk the project directory for tests and returns a list.
:return: list
"""
excludes = [
'.git',
'.tox',
'.vagrant',
'.venv',
os.path.basename(self._config.verifier.directory),
]
... |
Bake a `yamllint` command so it's ready to execute and returns None.
:return: None | def bake(self):
"""
Bake a `yamllint` command so it's ready to execute and returns None.
:return: None
"""
self._yamllint_command = sh.yamllint.bake(
self.options,
self._tests,
_env=self.env,
_out=LOG.out,
_err=LOG.erro... |
Turn input into a native string if possible. | def str_if_nested_or_str(s):
"""Turn input into a native string if possible."""
if isinstance(s, ALL_STRING_TYPES):
return str(s)
if isinstance(s, (list, tuple)):
return type(s)(map(str_if_nested_or_str, s))
if isinstance(s, (dict, )):
return stringify_dict_contents(s)
return... |
Turn dict keys and values into native strings. | def stringify_dict_contents(dct):
"""Turn dict keys and values into native strings."""
return {
str_if_nested_or_str(k): str_if_nested_or_str(v)
for k, v in dct.items()
} |
Use the provisioner to start the instances. | def create(ctx, scenario_name, driver_name): # pragma: no cover
""" Use the provisioner to start the instances. """
args = ctx.obj.get('args')
subcommand = base._get_subcommand(__name__)
command_args = {
'subcommand': subcommand,
'driver_name': driver_name,
}
base.execute_cmdli... |
Execute the actions necessary to perform a `molecule create` and
returns None.
:return: None | def execute(self):
"""
Execute the actions necessary to perform a `molecule create` and
returns None.
:return: None
"""
self.print_info()
self._config.state.change_state('driver', self._config.driver.name)
if self._config.driver.delegated and not self._c... |
Initialize a new role from a Cookiecutter URL. | def template(ctx, url, no_input, role_name): # pragma: no cover
""" Initialize a new role from a Cookiecutter URL. """
command_args = {
'role_name': role_name,
'subcommand': __name__,
'url': url,
'no_input': no_input,
}
t = Template(command_args)
t.execute() |
Execute the actions necessary to perform a `molecule init template` and
returns None.
:return: None | def execute(self):
"""
Execute the actions necessary to perform a `molecule init template` and
returns None.
:return: None
"""
role_name = self._command_args['role_name']
url = self._command_args['url']
no_input = self._command_args['no_input']
r... |
Execute the actions necessary to prepare the instances and returns
None.
:return: None | def execute(self):
"""
Execute the actions necessary to prepare the instances and returns
None.
:return: None
"""
self.print_info()
if (self._config.state.prepared
and not self._config.command_args.get('force')):
msg = 'Skipping, inst... |
Changes the state of the instance data with the given
``key`` and the provided ``value``.
Wrapping with a decorator is probably not necessary.
:param key: A ``str`` containing the key to update
:param value: A value to change the ``key`` to
:return: None | def change_state(self, key, value):
"""
Changes the state of the instance data with the given
``key`` and the provided ``value``.
Wrapping with a decorator is probably not necessary.
:param key: A ``str`` containing the key to update
:param value: A value to change the ... |
Bake a ``shell`` command so it's ready to execute and returns None.
:return: None | def bake(self):
"""
Bake a ``shell`` command so it's ready to execute and returns None.
:return: None
"""
command_list = self.command.split(' ')
command, args = command_list[0], command_list[1:]
self._sh_command = getattr(sh, command)
# Reconstruct comma... |
Bake a `rubocop` command so it's ready to execute and returns None.
:return: None | def bake(self):
"""
Bake a `rubocop` command so it's ready to execute and returns None.
:return: None
"""
self._rubocop_command = sh.rubocop.bake(
self.options,
self._tests,
_env=self.env,
_out=LOG.out,
_err=LOG.error) |
Execute the actions necessary to perform a `molecule destroy` and
returns None.
:return: None | def execute(self):
"""
Execute the actions necessary to perform a `molecule destroy` and
returns None.
:return: None
"""
self.print_info()
if self._config.command_args.get('destroy') == 'never':
msg = "Skipping, '--destroy=never' requested."
... |
Interpolate the provided data and return a dict.
Currently, this is used to reinterpolate the `molecule.yml` inside an
Ansible playbook. If there were any interpolation errors, they would
have been found and raised earlier.
:return: dict | def from_yaml(data):
"""
Interpolate the provided data and return a dict.
Currently, this is used to reinterpolate the `molecule.yml` inside an
Ansible playbook. If there were any interpolation errors, they would
have been found and raised earlier.
:return: dict
"""
molecule_env_file ... |
\b
_____ _ _
| |___| |___ ___ _ _| |___
| | | | . | | -_| _| | | | -_|
|_|_|_|___|_|___|___|___|_|___|
Molecule aids in the development and testing of Ansible roles.
Enable autocomplete issue:
eval "$(_MOLECULE_COMPLETE=source molecule)" | def main(ctx, debug, base_config, env_file): # pragma: no cover
"""
\b
_____ _ _
| |___| |___ ___ _ _| |___
| | | | . | | -_| _| | | | -_|
|_|_|_|___|_|___|___|___|_|___|
Molecule aids in the development and testing of Ansible roles.
Enable autocomplete issue:
... |
List matrix of steps used to test instances. | def matrix(ctx, scenario_name, subcommand): # pragma: no cover
"""
List matrix of steps used to test instances.
"""
args = ctx.obj.get('args')
command_args = {
'subcommand': subcommand,
}
s = scenarios.Scenarios(
base.get_configs(args, command_args), scenario_name)
s.p... |
Process templates as found in the named directory.
:param template_dir: A string containing an absolute or relative path
to a directory where the templates are located. If the provided
directory is a relative path, it is resolved using a known location.
:param extra_context: A dict of... | def _process_templates(self,
template_dir,
extra_context,
output_dir,
overwrite=True):
"""
Process templates as found in the named directory.
:param template_dir: A string containing an a... |
Redirect the stdout to a log file. | def stdout_cm(self):
""" Redirect the stdout to a log file. """
with open(self._get_stdout_log(), 'a+') as fh:
msg = '### {} ###\n'.format(self._datetime)
fh.write(msg)
fh.flush()
yield fh |
Redirect the stderr to a log file. | def stderr_cm(self):
""" Redirect the stderr to a log file. """
with open(self._get_stderr_log(), 'a+') as fh:
msg = '### {} ###\n'.format(self._datetime)
fh.write(msg)
fh.flush()
try:
yield fh
except Exception as e:
... |
Collects the instances state and returns a list.
.. important::
Molecule assumes all instances were created successfully by
Ansible, otherwise Ansible would return an error on create. This
may prove to be a bad assumption. However, configuring Molecule's
drive... | def status(self):
"""
Collects the instances state and returns a list.
.. important::
Molecule assumes all instances were created successfully by
Ansible, otherwise Ansible would return an error on create. This
may prove to be a bad assumption. However, co... |
Prune the scenario ephemeral directory files and returns None.
"safe files" will not be pruned, including the ansible configuration
and inventory used by this scenario, the scenario state file, and
files declared as "safe_files" in the ``driver`` configuration
declared in ``molecule.yml... | def prune(self):
"""
Prune the scenario ephemeral directory files and returns None.
"safe files" will not be pruned, including the ansible configuration
and inventory used by this scenario, the scenario state file, and
files declared as "safe_files" in the ``driver`` configurati... |
Select the sequence based on scenario and subcommand of the provided
scenario object and returns a list.
:param scenario: A scenario object.
:param skipped: An optional bool to include skipped scenarios.
:return: list | def sequence(self):
"""
Select the sequence based on scenario and subcommand of the provided
scenario object and returns a list.
:param scenario: A scenario object.
:param skipped: An optional bool to include skipped scenarios.
:return: list
"""
s = scena... |
Prepare the scenario for Molecule and returns None.
:return: None | def _setup(self):
"""
Prepare the scenario for Molecule and returns None.
:return: None
"""
if not os.path.isdir(self.inventory_directory):
os.makedirs(self.inventory_directory) |
Lists status of instances. | def list(ctx, scenario_name, format): # pragma: no cover
""" Lists status of instances. """
args = ctx.obj.get('args')
subcommand = base._get_subcommand(__name__)
command_args = {
'subcommand': subcommand,
'format': format,
}
statuses = []
s = scenarios.Scenarios(
b... |
Shows the tabulate data on the screen and returns None.
:param headers: A list of column headers.
:param data: A list of tabular data to display.
:returns: None | def _print_tabulate_data(headers, data, table_format): # pragma: no cover
"""
Shows the tabulate data on the screen and returns None.
:param headers: A list of column headers.
:param data: A list of tabular data to display.
:returns: None
"""
print(tabulate.tabulate(data, headers, tablefm... |
Initialize a new role for use with Molecule. | def role(ctx, dependency_name, driver_name, lint_name, provisioner_name,
role_name, verifier_name, template): # pragma: no cover
""" Initialize a new role for use with Molecule. """
command_args = {
'dependency_name': dependency_name,
'driver_name': driver_name,
'lint_name': li... |
Check if this host has already been added to the database, if not add it in. | def add_computer(self, ip, hostname, domain, os, instances):
"""
Check if this host has already been added to the database, if not add it in.
"""
cur = self.conn.cursor()
cur.execute('SELECT * FROM computers WHERE ip LIKE ?', [ip])
results = cur.fetchall()
if no... |
Execute the actions necessary to perform a `molecule init role` and
returns None.
:return: None | def execute(self):
"""
Execute the actions necessary to perform a `molecule init role` and
returns None.
:return: None
"""
role_name = self._command_args['role_name']
role_directory = os.getcwd()
msg = 'Initializing new role {}...'.format(role_name)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.