text stringlengths 81 112k |
|---|
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_op... |
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_upd... |
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.i... |
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, ut... |
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... |
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(se... |
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 ... |
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',... |
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,
... |
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, )):
... |
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... |
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.s... |
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 ... |
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... |
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.pr... |
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,... |
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], c... |
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,
se... |
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._co... |
\b
_____ _ _
| |___| |___ ___ _ _| |___
| | | | . | | -_| _| | | | -_|
|_|_|_|___|_|___|___|___|_|___|
Molecule aids in the development and testing of Ansible roles.
Enable autocomplete issue:
eval "$(_MOLECULE_COMPLETE=source molecule)"
def main(ctx, debug, base_... |
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... |
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_confi... |
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... |
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
... |
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... |
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... |
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... |
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 = sc... |
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.
... |
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,
'driv... |
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['r... |
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 com... |
Removes a credential ID from the database
def remove_credentials(self, credIDs):
"""
Removes a credential ID from the database
"""
for credID in credIDs:
cur = self.conn.cursor()
cur.execute("DELETE FROM users WHERE id=?", [credID])
cur.close() |
URL URL for the download cradle
def options(self, context, module_options):
'''
URL URL for the download cradle
'''
if not 'URL' in module_options:
context.log.error('URL option is required!')
exit(1)
self.url = module_options['URL'] |
SERVER IP of the SMB server
NAME LNK file name
CLEANUP Cleanup (choices: True or False)
def options(self, context, module_options):
'''
SERVER IP of the SMB server
NAME LNK file name
CLEANUP Cleanup (choices: True or False)
... |
COMMAND Mimikatz command to execute (default: 'sekurlsa::logonpasswords')
def options(self, context, module_options):
'''
COMMAND Mimikatz command to execute (default: 'sekurlsa::logonpasswords')
'''
self.command = 'privilege::debug sekurlsa::logonpasswords exit'
if module_... |
uniquify mimikatz tuples based on the password
cred format- (credType, domain, username, password, hostname, sid)
Stolen from the Empire project.
def uniquify_tuples(self, tuples):
"""
uniquify mimikatz tuples based on the password
cred format- (credType, domain, username, pass... |
Parse the output from Invoke-Mimikatz to return credential sets.
This was directly stolen from the Empire project as well.
def parse_mimikatz(self, data):
"""
Parse the output from Invoke-Mimikatz to return credential sets.
This was directly stolen from the Empire project as well.
... |
CONTYPE Specifies the VNC connection type, choices are: reverse, bind (default: reverse).
PORT VNC Port (default: 5900)
PASSWORD Specifies the connection password.
def options(self, context, module_options):
'''
CONTYPE Specifies the VNC connection type, choices are: reverse, ... |
Check if this host has already been added to the database, if not add it in.
def add_computer(self, ip, hostname, domain, os, dc=None):
"""
Check if this host has already been added to the database, if not add it in.
"""
domain = domain.split('.')[0].upper()
cur = self.conn.curs... |
Check if this credential has already been added to the database, if not add it in.
def add_credential(self, credtype, domain, username, password, groupid=None, pillaged_from=None):
"""
Check if this credential has already been added to the database, if not add it in.
"""
domain = domain... |
Check if this User ID is valid.
def is_user_valid(self, userID):
"""
Check if this User ID is valid.
"""
cur = self.conn.cursor()
cur.execute('SELECT * FROM users WHERE id=? LIMIT 1', [userID])
results = cur.fetchall()
cur.close()
return len(results) > 0 |
Return hosts from the database.
def get_computers(self, filterTerm=None, domain=None):
"""
Return hosts from the database.
"""
cur = self.conn.cursor()
# if we're returning a single host by ID
if self.is_computer_valid(filterTerm):
cur.execute("SELECT * FRO... |
Check if this group ID is valid.
def is_group_valid(self, groupID):
"""
Check if this group ID is valid.
"""
cur = self.conn.cursor()
cur.execute('SELECT * FROM groups WHERE id=? LIMIT 1', [groupID])
results = cur.fetchall()
cur.close()
logging.debug('is... |
Return groups from the database
def get_groups(self, filterTerm=None, groupName=None, groupDomain=None):
"""
Return groups from the database
"""
if groupDomain:
groupDomain = groupDomain.split('.')[0].upper()
cur = self.conn.cursor()
if self.is_group_valid(... |
Check if this credential has already been added to the database, if not add it in.
def add_credential(self, url, username, password):
"""
Check if this credential has already been added to the database, if not add it in.
"""
cur = self.conn.cursor()
cur.execute("SELECT * FROM c... |
Check if this credential ID is valid.
def is_credential_valid(self, credentialID):
"""
Check if this credential ID is valid.
"""
cur = self.conn.cursor()
cur.execute('SELECT * FROM credentials WHERE id=? LIMIT 1', [credentialID])
results = cur.fetchall()
cur.clos... |
Check if this credential ID is valid.
def is_host_valid(self, hostID):
"""
Check if this credential ID is valid.
"""
cur = self.conn.cursor()
cur.execute('SELECT * FROM host WHERE id=? LIMIT 1', [hostID])
results = cur.fetchall()
cur.close()
return len(re... |
Return credentials from the database.
def get_credentials(self, filterTerm=None):
"""
Return credentials from the database.
"""
cur = self.conn.cursor()
# if we're returning a single credential by ID
if self.is_credential_valid(filterTerm):
cur.execute("SEL... |
THOROUGH Searches entire filesystem for certain file extensions (default: False)
ALLDOMAIN Queries Active Direcotry for a list of all domain-joined computers and runs SessionGopher against all of them (default: False)
def options(self, context, module_options):
'''
THOROUGH Searches entire... |
INJECT If set to true, this allows PowerView to work over 'stealthier' execution methods which have non-interactive contexts (e.g. WMI) (default: True)
def options(self, context, module_options):
'''
INJECT If set to true, this allows PowerView to work over 'stealthier' execution methods whi... |
THREADS Max numbers of threads to execute on target (defaults to 20)
COLLECTIONMETHOD Method used by BloodHound ingestor to collect data (defaults to 'Default')
CSVPATH (optional) Path where csv files will be written on target (defaults to C:\)
NEO4JURI (opt... |
Parse the output from Invoke-BloodHound
def parse_ouput(self, data, context, response):
'''
Parse the output from Invoke-BloodHound
'''
parsedData = data.split("!-!")
nameList = ['user_sessions', 'group_membership.csv', 'acls.csv', 'local_admins.csv', 'trusts.csv']
for ... |
ACTION Enable/Disable RDP (choices: enable, disable)
def options(self, context, module_options):
'''
ACTION Enable/Disable RDP (choices: enable, disable)
'''
if not 'ACTION' in module_options:
context.log.error('ACTION option not specified!')
exit(1)
... |
LISTENER Listener name to generate the launcher for
def options(self, context, module_options):
'''
LISTENER Listener name to generate the launcher for
'''
if not 'LISTENER' in module_options:
context.log.error('LISTENER option is required!')
sys.exit(... |
PATH Path to dll/exe to inject
PROCID Process ID to inject into (default: current powershell process)
EXEARGS Arguments to pass to the executable being reflectively loaded (default: None)
def options(self, context, module_options):
'''
PATH Path to dll/exe to inje... |
USER Search for the specified username in available tokens (default: None)
USERFILE File containing usernames to search for in available tokens (defult: None)
def options(self, context, module_options):
'''
USER Search for the specified username in available tokens (default: ... |
PATH Path to the file containing raw shellcode to inject
PROCID Process ID to inject into (default: current powershell process)
def options(self, context, module_options):
'''
PATH Path to the file containing raw shellcode to inject
PROCID Process ID to inject in... |
SCRIPT Script version to execute (choices: bash, python) (default: bash)
def options(self, context, module_options):
'''
SCRIPT Script version to execute (choices: bash, python) (default: bash)
'''
scripts = {'PYTHON': get_script('mimipenguin/mimipenguin.py'),
'BASH... |
Oook.. Think my heads going to explode
So Mimikatz's DPAPI module requires the path to Chrome's database in double quotes otherwise it can't interpret paths with spaces.
Problem is Invoke-Mimikatz interpretes double qoutes as seperators for the arguments to pass to the injected mimikatz binary.... |
Abondon all hope ye who enter here.
You're now probably wondering if I was drunk and/or high when writing this.
Getting this to work took a toll on my sanity. So yes. a lot.
def _spider(self, subfolder, depth):
'''
Abondon all hope ye who enter here.
You're now p... |
Given a command, mode, and a PATH string, return the path which
conforms to the given mode on the PATH, or None if there is no such
file.
`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
of os.environ.get("PATH"), or can be overridden with a custom search
path.
Note: This func... |
DOMAIN Domain to enumerate DNS for. Defaults to all zones.
def options(self, context, module_options):
'''
DOMAIN Domain to enumerate DNS for. Defaults to all zones.
'''
self.domains = None
if module_options and 'DOMAIN' in module_options:
sel... |
LHOST IP hosting the handler
LPORT Handler port
PAYLOAD Payload to inject: reverse_http or reverse_https (default: reverse_https)
PROCID Process ID to inject into (default: current powershell process)
def options(self, context, module_options):
'''
LHOST... |
if is_powershell_installed():
temp = tempfile.NamedTemporaryFile(prefix='cme_',
suffix='.ps1',
dir='/tmp')
temp.write(command)
temp.read()
encoding_types = [1,2,3,4,5,6]
while True:
... |
# Array to store all selected PowerShell execution flags.
powerShellFlags = []
noProfile = '-nop'
nonInteractive = '-noni'
windowStyle = '-w'
# Build the PowerShell execution flags by randomly selecting execution flags substrings and randomizing the order.
# This is to prevent Blue Team from p... |
SERVER IP of the SMB server
NAME SCF file name
CLEANUP Cleanup (choices: True or False)
def options(self, context, module_options):
'''
SERVER IP of the SMB server
NAME SCF file name
CLEANUP Cleanup (choices: True or False)
'''
... |
This gets called when a module has finshed executing, removes the host from the connection tracker list
def stop_tracking_host(self):
'''
This gets called when a module has finshed executing, removes the host from the connection tracker list
'''
try:
self.server.hosts.re... |
PROCESS Process to hook, only x86 processes are supported by NetRipper currently (Choices: firefox, chrome, putty, winscp, outlook, lync)
def options(self, context, module_options):
'''
PROCESS Process to hook, only x86 processes are supported by NetRipper currently (Choices: firefox, chrome, putty... |
TIMEOUT Specifies the interval in minutes to capture keystrokes.
STREAM Specifies whether to stream the keys over the network (default: False)
POLL Specifies the interval in seconds to poll the log file (default: 20)
def options(self, context, module_options):
'''
TIMEOUT Sp... |
Tab-complete 'creds' commands.
def complete_hosts(self, text, line, begidx, endidx):
"Tab-complete 'creds' commands."
commands = ["add", "remove", "dc"]
mline = line.partition(' ')[2]
offs = len(mline) - len(text)
return [s[offs:] for s in commands if s.startswith(mline)] |
Is the current line a (possibly escaped) Jupyter magic, and should it be commented?
def is_magic(line, language, global_escape_flag=True):
"""Is the current line a (possibly escaped) Jupyter magic, and should it be commented?"""
if language in ['octave', 'matlab']:
return False
if _MAGIC_FORCE_ESC_... |
Escape Jupyter magics with '#
def comment_magic(source, language='python', global_escape_flag=True):
"""Escape Jupyter magics with '# '"""
parser = StringParser(language)
next_is_magic = False
for pos, line in enumerate(source):
if not parser.is_quoted() and (next_is_magic or is_magic(line, lan... |
Uncomment once a commented line
def unesc(line, language):
"""Uncomment once a commented line"""
comment = _COMMENT[language]
if line.startswith(comment + ' '):
return line[len(comment) + 1:]
if line.startswith(comment):
return line[len(comment):]
return line |
Escape code start with '#
def escape_code_start(source, ext, language='python'):
"""Escape code start with '# '"""
parser = StringParser(language)
for pos, line in enumerate(source):
if not parser.is_quoted() and is_escaped_code_start(line, ext):
source[pos] = _SCRIPT_EXTENSIONS.get(ext... |
Unescape code start
def unescape_code_start(source, ext, language='python'):
"""Unescape code start"""
parser = StringParser(language)
for pos, line in enumerate(source):
if not parser.is_quoted() and is_escaped_code_start(line, ext):
unescaped = unesc(line, language)
# don'... |
Return the metadata filter represented as either None (no filter),
or a dictionary with at most two keys: 'additional' and 'excluded',
which contain either a list of metadata names, or the string 'all
def metadata_filter_as_dict(metadata_config):
"""Return the metadata filter represented as either None (no... |
Convert a filter, represented as a dictionary with 'additional' and 'excluded' entries, to a string
def metadata_filter_as_string(metadata_filter):
"""Convert a filter, represented as a dictionary with 'additional' and 'excluded' entries, to a string"""
if not isinstance(metadata_filter, dict):
return ... |
Update or set the notebook and cell metadata filters
def update_metadata_filters(metadata, jupyter_md, cell_metadata):
"""Update or set the notebook and cell metadata filters"""
cell_metadata = [m for m in cell_metadata if m not in ['language', 'magic_args']]
if 'cell_metadata_filter' in metadata.get('ju... |
Apply the filter and replace 'all' with the actual or filtered keys
def apply_metadata_filters(user_filter, default_filter, actual_keys):
"""Apply the filter and replace 'all' with the actual or filtered keys"""
default_filter = metadata_filter_as_dict(default_filter) or {}
user_filter = metadata_filter_a... |
Filter the cell or notebook metadata, according to the user preference
def filter_metadata(metadata, user_filter, default_filter):
"""Filter the cell or notebook metadata, according to the user preference"""
actual_keys = set(metadata.keys())
keep_keys = apply_metadata_filters(user_filter, default_filter, ... |
Return the default language given the notebook metadata, and a file extension
def default_language_from_metadata_and_ext(metadata, ext):
"""Return the default language given the notebook metadata, and a file extension"""
default_from_ext = _SCRIPT_EXTENSIONS.get(ext, {}).get('language', 'python')
language... |
Set main language for the given collection of cells, and
use magics for cells that use other languages
def set_main_and_cell_language(metadata, cells, ext):
"""Set main language for the given collection of cells, and
use magics for cells that use other languages"""
main_language = (metadata.get('kernel... |
Return cell language and language options, if any
def cell_language(source):
"""Return cell language and language options, if any"""
if source:
line = source[0]
if line.startswith('%%'):
magic = line[2:]
if ' ' in magic:
lang, magic_args = magic.split(' '... |
Return commented lines
def comment_lines(lines, prefix):
"""Return commented lines"""
if not prefix:
return lines
return [prefix + ' ' + line if line else prefix for line in lines] |
Read a new line
def read_line(self, line):
"""Read a new line"""
if self.ignore:
return
for i, char in enumerate(line):
if char not in ['"', "'"]:
continue
# Is the char escaped?
if line[i - 1:i] == '\\':
continue
... |
Draw a histogram as a stepped patch.
Extra kwargs are passed through to `fill_between`
Parameters
----------
ax : Axes
The axes to plot to
edges : array
A length n+1 array giving the left edges of each bin and the
right edge of the last bin.
values : array
A l... |
ax : axes.Axes
The axes to add artists too
stacked_data : array or Mapping
A (N, M) shaped array. The first dimension will be iterated over to
compute histograms row-wise
sty_cycle : Cycler or operable of dict
Style to apply to each set
bottoms : array, optional
T... |
Use Jupytext's contents manager
def load_jupyter_server_extension(app): # pragma: no cover
"""Use Jupytext's contents manager"""
if isinstance(app.contents_manager_class, TextFileContentsManager):
app.log.info("[Jupytext Server Extension] NotebookApp.contents_manager_class is "
"(... |
Read a notebook from a string
def reads(text, fmt, as_version=4, **kwargs):
"""Read a notebook from a string"""
fmt = copy(fmt)
fmt = long_form_one_format(fmt)
ext = fmt['extension']
if ext == '.ipynb':
return nbformat.reads(text, as_version, **kwargs)
format_name = read_format_from_m... |
Read a notebook from a file
def read(file_or_stream, fmt, as_version=4, **kwargs):
"""Read a notebook from a file"""
fmt = long_form_one_format(fmt)
if fmt['extension'] == '.ipynb':
notebook = nbformat.read(file_or_stream, as_version, **kwargs)
rearrange_jupytext_metadata(notebook.metadata)... |
Read a notebook from the file with given name
def readf(nb_file, fmt=None):
"""Read a notebook from the file with given name"""
if nb_file == '-':
text = sys.stdin.read()
fmt = fmt or divine_format(text)
return reads(text, fmt)
_, ext = os.path.splitext(nb_file)
fmt = copy(fmt ... |
Write a notebook to a string
def writes(notebook, fmt, version=nbformat.NO_CONVERT, **kwargs):
"""Write a notebook to a string"""
metadata = deepcopy(notebook.metadata)
rearrange_jupytext_metadata(metadata)
fmt = copy(fmt)
fmt = long_form_one_format(fmt, metadata)
ext = fmt['extension']
for... |
Write a notebook to a file
def write(notebook, file_or_stream, fmt, version=nbformat.NO_CONVERT, **kwargs):
"""Write a notebook to a file"""
# Python 2 compatibility
text = u'' + writes(notebook, fmt, version, **kwargs)
file_or_stream.write(text)
# Add final newline #165
if not text.endswith(u'... |
Write a notebook to the file with given name
def writef(notebook, nb_file, fmt=None):
"""Write a notebook to the file with given name"""
if nb_file == '-':
write(notebook, sys.stdout, fmt)
return
_, ext = os.path.splitext(nb_file)
fmt = copy(fmt or {})
fmt = long_form_one_format(fm... |
Create directory if fmt has a prefix
def create_prefix_dir(nb_file, fmt):
"""Create directory if fmt has a prefix"""
if 'prefix' in fmt:
nb_dir = os.path.dirname(nb_file) + os.path.sep
if not os.path.isdir(nb_dir):
logging.log(logging.WARNING, "[jupytext] creating missing directory ... |
Update format options with the values in the notebook metadata, and record those
options in the notebook metadata
def update_fmt_with_notebook_options(self, metadata):
"""Update format options with the values in the notebook metadata, and record those
options in the notebook metadata"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.