_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q33900
_copy_binder_notebooks
train
def _copy_binder_notebooks(app): """Copy Jupyter notebooks to the binder notebooks directory. Copy each output gallery directory structure but only including the Jupyter notebook files.""" gallery_conf = app.config.sphinx_gallery_conf gallery_dirs = gallery_conf.get('gallery_dirs') binder_conf...
python
{ "resource": "" }
q33901
check_binder_conf
train
def check_binder_conf(binder_conf): """Check to make sure that the Binder configuration is correct.""" # Grab the configuration and return None if it's not configured binder_conf = {} if binder_conf is None else binder_conf if not isinstance(binder_conf, dict): raise ValueError('`binder_conf` mu...
python
{ "resource": "" }
q33902
parse_source_file
train
def parse_source_file(filename): """Parse source file into AST node Parameters ---------- filename : str File path Returns ------- node : AST node content : utf-8 encoded string """ # can't use codecs.open(filename, 'r', 'utf-8') here b/c ast doesn't # work with un...
python
{ "resource": "" }
q33903
get_docstring_and_rest
train
def get_docstring_and_rest(filename): """Separate ``filename`` content between docstring and the rest Strongly inspired from ast.get_docstring. Returns ------- docstring : str docstring of ``filename`` rest : str ``filename`` content without the docstring """ node, cont...
python
{ "resource": "" }
q33904
extract_file_config
train
def extract_file_config(content): """ Pull out the file-specific config specified in the docstring. """ prop_pat = re.compile( r"^\s*#\s*sphinx_gallery_([A-Za-z0-9_]+)\s*=\s*(.+)\s*$", re.MULTILINE) file_conf = {} for match in re.finditer(prop_pat, content): name = match...
python
{ "resource": "" }
q33905
split_code_and_text_blocks
train
def split_code_and_text_blocks(source_file): """Return list with source file separated into code and text blocks. Returns ------- file_conf : dict File-specific settings given in source file comments as: ``# sphinx_gallery_<name> = <value>`` blocks : list (label, content, li...
python
{ "resource": "" }
q33906
parse_config
train
def parse_config(app): """Process the Sphinx Gallery configuration""" try: plot_gallery = eval(app.builder.config.plot_gallery) except TypeError: plot_gallery = bool(app.builder.config.plot_gallery) src_dir = app.builder.srcdir abort_on_example_error = app.builder.config.abort_on_exa...
python
{ "resource": "" }
q33907
get_subsections
train
def get_subsections(srcdir, examples_dir, sortkey): """Return the list of subsections of a gallery Parameters ---------- srcdir : str absolute path to directory containing conf.py examples_dir : str path to the examples directory relative to conf.py sortkey : callable Th...
python
{ "resource": "" }
q33908
_prepare_sphx_glr_dirs
train
def _prepare_sphx_glr_dirs(gallery_conf, srcdir): """Creates necessary folders for sphinx_gallery files """ examples_dirs = gallery_conf['examples_dirs'] gallery_dirs = gallery_conf['gallery_dirs'] if not isinstance(examples_dirs, list): examples_dirs = [examples_dirs] if not isinstance(ga...
python
{ "resource": "" }
q33909
generate_gallery_rst
train
def generate_gallery_rst(app): """Generate the Main examples gallery reStructuredText Start the sphinx-gallery configuration and recursively scan the examples directories in order to populate the examples gallery """ logger.info('generating gallery...', color='white') gallery_conf = parse_confi...
python
{ "resource": "" }
q33910
_sec_to_readable
train
def _sec_to_readable(t): """Convert a number of seconds to a more readable representation.""" # This will only work for < 1 day execution time # And we reserve 2 digits for minutes because presumably # there aren't many > 99 minute scripts, but occasionally some # > 9 minute ones t = datetime(1,...
python
{ "resource": "" }
q33911
touch_empty_backreferences
train
def touch_empty_backreferences(app, what, name, obj, options, lines): """Generate empty back-reference example files This avoids inclusion errors/warnings if there are no gallery examples for a class / module that is being parsed by autodoc""" if not bool(app.config.sphinx_gallery_conf['backreferences...
python
{ "resource": "" }
q33912
_parse_failures
train
def _parse_failures(gallery_conf): """Split the failures.""" failing_examples = set(gallery_conf['failing_examples'].keys()) expected_failing_examples = set( os.path.normpath(os.path.join(gallery_conf['src_dir'], path)) for path in gallery_conf['expected_failing_examples']) failing_as_ex...
python
{ "resource": "" }
q33913
summarize_failing_examples
train
def summarize_failing_examples(app, exception): """Collects the list of falling examples and prints them with a traceback. Raises ValueError if there where failing examples. """ if exception is not None: return # Under no-plot Examples are not run so nothing to summarize if not app.con...
python
{ "resource": "" }
q33914
collect_gallery_files
train
def collect_gallery_files(examples_dirs): """Collect python files from the gallery example directories.""" files = [] for example_dir in examples_dirs: for root, dirnames, filenames in os.walk(example_dir): for filename in filenames: if filename.endswith('.py'): ...
python
{ "resource": "" }
q33915
check_duplicate_filenames
train
def check_duplicate_filenames(files): """Check for duplicate filenames across gallery directories.""" # Check whether we'll have duplicates used_names = set() dup_names = list() for this_file in files: this_fname = os.path.basename(this_file) if this_fname in used_names: ...
python
{ "resource": "" }
q33916
setup
train
def setup(app): """Setup sphinx-gallery sphinx extension""" sphinx_compatibility._app = app app.add_config_value('sphinx_gallery_conf', DEFAULT_GALLERY_CONF, 'html') for key in ['plot_gallery', 'abort_on_example_error']: app.add_config_value(key, get_default_config_value(key), 'html') try:...
python
{ "resource": "" }
q33917
replace_py_ipynb
train
def replace_py_ipynb(fname): """Replace .py extension in filename by .ipynb""" fname_prefix, extension = os.path.splitext(fname) allowed_extension = '.py' if extension != allowed_extension: raise ValueError( "Unrecognized file extension, expected %s, got %s" % (allowed_ex...
python
{ "resource": "" }
q33918
get_md5sum
train
def get_md5sum(src_file): """Returns md5sum of file""" with open(src_file, 'rb') as src_data: src_content = src_data.read() return hashlib.md5(src_content).hexdigest()
python
{ "resource": "" }
q33919
ZabbixResponse.parse
train
def parse(self, response): """Parse zabbix response.""" info = response.get('info') res = self._regex.search(info) self._processed += int(res.group(1)) self._failed += int(res.group(2)) self._total += int(res.group(3)) self._time += Decimal(res.group(4)) ...
python
{ "resource": "" }
q33920
ZabbixSender._load_from_config
train
def _load_from_config(self, config_file): """Load zabbix server IP address and port from zabbix agent config file. If ServerActive variable is not found in the file, it will use the default: 127.0.0.1:10051 :type config_file: str :param use_config: Path to zabbix_agentd...
python
{ "resource": "" }
q33921
ZabbixSender._receive
train
def _receive(self, sock, count): """Reads socket to receive data from zabbix server. :type socket: :class:`socket._socketobject` :param socket: Socket to read. :type count: int :param count: Number of bytes to read from socket. """ buf = b'' while len(...
python
{ "resource": "" }
q33922
ZabbixSender._create_messages
train
def _create_messages(self, metrics): """Create a list of zabbix messages from a list of ZabbixMetrics. :type metrics_array: list :param metrics_array: List of :class:`zabbix.sender.ZabbixMetric`. :rtype: list :return: List of zabbix messages. """ messages = [] ...
python
{ "resource": "" }
q33923
ZabbixSender._create_request
train
def _create_request(self, messages): """Create a formatted request to zabbix from a list of messages. :type messages: list :param messages: List of zabbix messages :rtype: list :return: Formatted zabbix request """ msg = ','.join(messages) request = '{{...
python
{ "resource": "" }
q33924
ZabbixSender._create_packet
train
def _create_packet(self, request): """Create a formatted packet from a request. :type request: str :param request: Formatted zabbix request :rtype: str :return: Data packet for zabbix """ data_len = struct.pack('<Q', len(request)) packet = b'ZBXD\x01' +...
python
{ "resource": "" }
q33925
ZabbixSender._get_response
train
def _get_response(self, connection): """Get response from zabbix server, reads from self.socket. :type connection: :class:`socket._socketobject` :param connection: Socket to read. :rtype: dict :return: Response from zabbix server or False in case of error. """ ...
python
{ "resource": "" }
q33926
ZabbixSender._chunk_send
train
def _chunk_send(self, metrics): """Send the one chunk metrics to zabbix server. :type metrics: list :param metrics: List of :class:`zabbix.sender.ZabbixMetric` to send to Zabbix :rtype: str :return: Response from Zabbix Server """ messages = self._cr...
python
{ "resource": "" }
q33927
ZabbixSender.send
train
def send(self, metrics): """Send the metrics to zabbix server. :type metrics: list :param metrics: List of :class:`zabbix.sender.ZabbixMetric` to send to Zabbix :rtype: :class:`pyzabbix.sender.ZabbixResponse` :return: Parsed response from Zabbix Server """ ...
python
{ "resource": "" }
q33928
ZabbixAPI._login
train
def _login(self, user='', password=''): """Do login to zabbix server. :type user: str :param user: Zabbix user :type password: str :param password: Zabbix user password """ logger.debug("ZabbixAPI.login({0},{1})".format(user, password)) self.auth = Non...
python
{ "resource": "" }
q33929
ZabbixAPI._logout
train
def _logout(self): """Do logout from zabbix server.""" if self.auth: logger.debug("ZabbixAPI.logout()") if self.user.logout(): self.auth = None
python
{ "resource": "" }
q33930
ZabbixAPI.do_request
train
def do_request(self, method, params=None): """Make request to Zabbix API. :type method: str :param method: ZabbixAPI method, like: `apiinfo.version`. :type params: str :param params: ZabbixAPI method arguments. >>> from pyzabbix import ZabbixAPI >>> z = ZabbixA...
python
{ "resource": "" }
q33931
ZabbixAPI.get_id
train
def get_id(self, item_type, item=None, with_id=False, hostid=None, **args): """Return id or ids of zabbix objects. :type item_type: str :param item_type: Type of zabbix object. (eg host, item etc.) :type item: str :param item: Name of zabbix object. If it is `None`, return list...
python
{ "resource": "" }
q33932
generate_optimized_y_move_down_x_SOL
train
def generate_optimized_y_move_down_x_SOL(y_dist): """ move down y_dist, set x=0 """ # Optimization to move N lines and go to SOL in one command. Note that some terminals # may not support this so we might have to remove this optimization or make it optional # if that winds up mattering for terminals ...
python
{ "resource": "" }
q33933
GitRepository.get_head
train
def get_head(self) -> Commit: """ Get the head commit. :return: Commit of the head commit """ head_commit = self.repo.head.commit return Commit(head_commit, self.path, self.main_branch)
python
{ "resource": "" }
q33934
GitRepository.get_list_commits
train
def get_list_commits(self, branch: str = None, reverse_order: bool = True) \ -> Generator[Commit, None, None]: """ Return a generator of commits of all the commits in the repo. :return: Generator[Commit], the generator of all the commits in the r...
python
{ "resource": "" }
q33935
GitRepository.get_commit
train
def get_commit(self, commit_id: str) -> Commit: """ Get the specified commit. :param str commit_id: hash of the commit to analyze :return: Commit """ return Commit(self.repo.commit(commit_id), self.path, self.main_branch)
python
{ "resource": "" }
q33936
GitRepository.get_commit_from_gitpython
train
def get_commit_from_gitpython(self, commit: GitCommit) -> Commit: """ Build a PyDriller commit object from a GitPython commit object. This is internal of PyDriller, I don't think users generally will need it. :param GitCommit commit: GitPython commit :return: Commit comm...
python
{ "resource": "" }
q33937
GitRepository.get_commit_from_tag
train
def get_commit_from_tag(self, tag: str) -> Commit: """ Obtain the tagged commit. :param str tag: the tag :return: Commit commit: the commit the tag referred to """ try: selected_tag = self.repo.tags[tag] return self.get_commit(selected_tag.commit....
python
{ "resource": "" }
q33938
Modification.added
train
def added(self) -> int: """ Return the total number of added lines in the file. :return: int lines_added """ added = 0 for line in self.diff.replace('\r', '').split("\n"): if line.startswith('+') and not line.startswith('+++'): added += 1 ...
python
{ "resource": "" }
q33939
Modification.removed
train
def removed(self): """ Return the total number of deleted lines in the file. :return: int lines_deleted """ removed = 0 for line in self.diff.replace('\r', '').split("\n"): if line.startswith('-') and not line.startswith('---'): removed += 1 ...
python
{ "resource": "" }
q33940
Commit.author
train
def author(self) -> Developer: """ Return the author of the commit as a Developer object. :return: author """ return Developer(self._c_object.author.name, self._c_object.author.email)
python
{ "resource": "" }
q33941
Commit.committer
train
def committer(self) -> Developer: """ Return the committer of the commit as a Developer object. :return: committer """ return Developer(self._c_object.committer.name, self._c_object.committer.email)
python
{ "resource": "" }
q33942
Commit.parents
train
def parents(self) -> List[str]: """ Return the list of parents SHAs. :return: List[str] parents """ parents = [] for p in self._c_object.parents: parents.append(p.hexsha) return parents
python
{ "resource": "" }
q33943
Commit.modifications
train
def modifications(self) -> List[Modification]: """ Return a list of modified files. :return: List[Modification] modifications """ if self._modifications is None: self._modifications = self._get_modifications() return self._modifications
python
{ "resource": "" }
q33944
Commit.branches
train
def branches(self) -> Set[str]: """ Return the set of branches that contain the commit. :return: set(str) branches """ if self._branches is None: self._branches = self._get_branches() return self._branches
python
{ "resource": "" }
q33945
_lex_file_object
train
def _lex_file_object(file_obj): """ Generates token tuples from an nginx config file object Yields 3-tuples like (token, lineno, quoted) """ token = '' # the token buffer token_line = 0 # the line the token starts on next_token_is_directive = True it = itertools.chain.from_iterable(f...
python
{ "resource": "" }
q33946
_balance_braces
train
def _balance_braces(tokens, filename=None): """Raises syntax errors if braces aren't balanced""" depth = 0 for token, line, quoted in tokens: if token == '}' and not quoted: depth -= 1 elif token == '{' and not quoted: depth += 1 # raise error if we ever hav...
python
{ "resource": "" }
q33947
lex
train
def lex(filename): """Generates tokens from an nginx config file""" with io.open(filename, mode='r', encoding='utf-8') as f: it = _lex_file_object(f) it = _balance_braces(it, filename) for token, line, quoted in it: yield (token, line, quoted)
python
{ "resource": "" }
q33948
_prepare_if_args
train
def _prepare_if_args(stmt): """Removes parentheses from an "if" directive's arguments""" args = stmt['args'] if args and args[0].startswith('(') and args[-1].endswith(')'): args[0] = args[0][1:].lstrip() args[-1] = args[-1][:-1].rstrip() start = int(not args[0]) end = len(arg...
python
{ "resource": "" }
q33949
_combine_parsed_configs
train
def _combine_parsed_configs(old_payload): """ Combines config files into one by using include directives. :param old_payload: payload that's normally returned by parse() :return: the new combined payload """ old_configs = old_payload['config'] def _perform_includes(block): for stmt...
python
{ "resource": "" }
q33950
rmrf
train
def rmrf(items, verbose=True): "Silently remove a list of directories or files" if isinstance(items, str): items = [items] for item in items: if verbose: print("Removing {}".format(item)) shutil.rmtree(item, ignore_errors=True) # rmtree doesn't remove bare files ...
python
{ "resource": "" }
q33951
docs
train
def docs(context, builder='html'): "Build documentation using sphinx" cmdline = 'python -msphinx -M {} {} {} {}'.format(builder, DOCS_SRCDIR, DOCS_BUILDDIR, SPHINX_OPTS) context.run(cmdline)
python
{ "resource": "" }
q33952
eggs_clean
train
def eggs_clean(context): "Remove egg directories" #pylint: disable=unused-argument dirs = set() dirs.add('.eggs') for name in os.listdir(os.curdir): if name.endswith('.egg-info'): dirs.add(name) if name.endswith('.egg'): dirs.add(name) rmrf(dirs)
python
{ "resource": "" }
q33953
tag
train
def tag(context, name, message=''): "Add a Git tag and push it to origin" # If a tag was provided on the command-line, then add a Git tag and push it to origin if name: context.run('git tag -a {} -m {!r}'.format(name, message)) context.run('git push origin {}'.format(name))
python
{ "resource": "" }
q33954
validatetag
train
def validatetag(context): "Check to make sure that a tag exists for the current HEAD and it looks like a valid version number" # Validate that a Git tag exists for the current commit HEAD result = context.run("git describe --exact-match --tags $(git log -n1 --pretty='%h')") tag = result.stdout.rstrip() ...
python
{ "resource": "" }
q33955
AlerterApp._preloop_hook
train
def _preloop_hook(self) -> None: """ Start the alerter thread """ # This runs after cmdloop() acquires self.terminal_lock, which will be locked until the prompt appears. # Therefore this is the best place to start the alerter thread since there is no risk of it alerting # before the prom...
python
{ "resource": "" }
q33956
AlerterApp.do_start_alerts
train
def do_start_alerts(self, _): """ Starts the alerter thread """ if self._alerter_thread.is_alive(): print("The alert thread is already started") else: self._stop_thread = False self._alerter_thread = threading.Thread(name='alerter', target=self._alerter_thread...
python
{ "resource": "" }
q33957
AlerterApp._alerter_thread_func
train
def _alerter_thread_func(self) -> None: """ Prints alerts and updates the prompt any time the prompt is showing """ self._alert_count = 0 self._next_alert_time = 0 while not self._stop_thread: # Always acquire terminal_lock before printing alerts or updating the prompt ...
python
{ "resource": "" }
q33958
quote_string_if_needed
train
def quote_string_if_needed(arg: str) -> str: """ Quotes a string if it contains spaces and isn't already quoted """ if is_quoted(arg) or ' ' not in arg: return arg if '"' in arg: quote = "'" else: quote = '"' return quote + arg + quote
python
{ "resource": "" }
q33959
namedtuple_with_defaults
train
def namedtuple_with_defaults(typename: str, field_names: Union[str, List[str]], default_values: collections.Iterable = ()): """ Convenience function for defining a namedtuple with default values From: https://stackoverflow.com/questions/11351032/namedtuple-and-default-values-fo...
python
{ "resource": "" }
q33960
cast
train
def cast(current: Any, new: str) -> Any: """Tries to force a new value into the same type as the current when trying to set the value for a parameter. :param current: current value for the parameter, type varies :param new: new value :return: new value with same type as current, or the current value if...
python
{ "resource": "" }
q33961
which
train
def which(editor: str) -> Optional[str]: """Find the full path of a given editor. Return the full path of the given editor, or None if the editor can not be found. :param editor: filename of the editor to check, ie 'notepad.exe' or 'vi' :return: a full path or None """ try: editor_...
python
{ "resource": "" }
q33962
is_text_file
train
def is_text_file(file_path: str) -> bool: """Returns if a file contains only ASCII or UTF-8 encoded text. :param file_path: path to the file being checked :return: True if the file is a text file, False if it is binary. """ import codecs expanded_path = os.path.abspath(os.path.expanduser(file_...
python
{ "resource": "" }
q33963
remove_duplicates
train
def remove_duplicates(list_to_prune: List) -> List: """Removes duplicates from a list while preserving order of the items. :param list_to_prune: the list being pruned of duplicates :return: The pruned list """ temp_dict = collections.OrderedDict() for item in list_to_prune: temp_dict[it...
python
{ "resource": "" }
q33964
alphabetical_sort
train
def alphabetical_sort(list_to_sort: Iterable[str]) -> List[str]: """Sorts a list of strings alphabetically. For example: ['a1', 'A11', 'A2', 'a22', 'a3'] To sort a list in place, don't call this method, which makes a copy. Instead, do this: my_list.sort(key=norm_fold) :param list_to_sort: the li...
python
{ "resource": "" }
q33965
natural_sort
train
def natural_sort(list_to_sort: Iterable[str]) -> List[str]: """ Sorts a list of strings case insensitively as well as numerically. For example: ['a1', 'A2', 'a3', 'A11', 'a22'] To sort a list in place, don't call this method, which makes a copy. Instead, do this: my_list.sort(key=natural_keys) ...
python
{ "resource": "" }
q33966
find_editor
train
def find_editor() -> str: """Find a reasonable editor to use by default for the system that the cmd2 application is running on.""" editor = os.environ.get('EDITOR') if not editor: if sys.platform[:3] == 'win': editor = 'notepad' else: # Favor command-line editors firs...
python
{ "resource": "" }
q33967
StdSim.write
train
def write(self, s: str) -> None: """Add str to internal bytes buffer and if echo is True, echo contents to inner stream""" if not isinstance(s, str): raise TypeError('write() argument must be str, not {}'.format(type(s))) if not self.pause_storage: self.buffer.byte_buf +...
python
{ "resource": "" }
q33968
StdSim.getvalue
train
def getvalue(self) -> str: """Get the internal contents as a str""" return self.buffer.byte_buf.decode(encoding=self.encoding, errors=self.errors)
python
{ "resource": "" }
q33969
ByteBuf.write
train
def write(self, b: bytes) -> None: """Add bytes to internal bytes buffer and if echo is True, echo contents to inner stream.""" if not isinstance(b, bytes): raise TypeError('a bytes-like object is required, not {}'.format(type(b))) if not self.std_sim_instance.pause_storage: ...
python
{ "resource": "" }
q33970
CmdLineApp.add_whitespace_hook
train
def add_whitespace_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData: """A hook to split alphabetic command names immediately followed by a number. l24 -> l 24 list24 -> list 24 list 24 -> list 24 """ command = data.statement.command #...
python
{ "resource": "" }
q33971
CmdLineApp.downcase_hook
train
def downcase_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData: """A hook to make uppercase commands lowercase.""" command = data.statement.command.lower() data.statement = self.statement_parser.parse("{} {}".format( command, '' if data.statemen...
python
{ "resource": "" }
q33972
CmdLineApp.abbrev_hook
train
def abbrev_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData: """Accept unique abbreviated commands""" func = self.cmd_func(data.statement.command) if func is None: # check if the entered command might be an abbreviation possible_cmds = [cmd for...
python
{ "resource": "" }
q33973
CmdLineApp.do_list
train
def do_list(self, arglist: List[str]) -> None: """Generate a list of 10 numbers.""" if arglist: first = arglist[0] try: first = int(first) except ValueError: first = 1 else: first = 1 last = first + 10 ...
python
{ "resource": "" }
q33974
SubcommandsExample.do_base
train
def do_base(self, args): """Base command help""" func = getattr(args, 'func', None) if func is not None: # Call whatever sub-command function was selected func(self, args) else: # No sub-command was provided, so call help self.do_help('base...
python
{ "resource": "" }
q33975
SubcommandsExample.do_alternate
train
def do_alternate(self, args): """Alternate command help""" func = getattr(args, 'func', None) if func is not None: # Call whatever sub-command function was selected func(self, args) else: # No sub-command was provided, so call help self.do_...
python
{ "resource": "" }
q33976
main
train
def main(argv=None): """Run when invoked from the operating system shell""" parser = argparse.ArgumentParser( description='Commands as arguments' ) command_help = 'optional command to run, if no command given, enter an interactive shell' parser.add_argument('command', nargs='?', ...
python
{ "resource": "" }
q33977
TabCompleteExample.do_add_item
train
def do_add_item(self, args): """Add item command help""" if args.food: add_item = args.food elif args.sport: add_item = args.sport elif args.other: add_item = args.other else: add_item = 'no items' self.poutput("You added {...
python
{ "resource": "" }
q33978
CmdLineApp.do_tag
train
def do_tag(self, args: argparse.Namespace): """create an html tag""" # The Namespace always includes the Statement object created when parsing the command line statement = args.__statement__ self.poutput("The command line you ran was: {}".format(statement.command_and_args)) self...
python
{ "resource": "" }
q33979
CmdLineApp.do_tagg
train
def do_tagg(self, arglist: List[str]): """version of creating an html tag using arglist instead of argparser""" if len(arglist) >= 2: tag = arglist[0] content = arglist[1:] self.poutput('<{0}>{1}</{0}>'.format(tag, ' '.join(content))) else: self.pe...
python
{ "resource": "" }
q33980
ReplWithExitCode.do_exit
train
def do_exit(self, arg_list: List[str]) -> bool: """Exit the application with an optional exit code. Usage: exit [exit_code] Where: * exit_code - integer exit code to return to the shell """ # If an argument was provided if arg_list: try: self.exit_code =...
python
{ "resource": "" }
q33981
categorize
train
def categorize(func: Union[Callable, Iterable], category: str) -> None: """Categorize a function. The help command output will group this function under the specified category heading :param func: function to categorize :param category: category to put it in """ if isinstance(func, Iterable): ...
python
{ "resource": "" }
q33982
with_category
train
def with_category(category: str) -> Callable: """A decorator to apply a category to a command function.""" def cat_decorator(func): categorize(func, category) return func return cat_decorator
python
{ "resource": "" }
q33983
with_argparser_and_unknown_args
train
def with_argparser_and_unknown_args(argparser: argparse.ArgumentParser, preserve_quotes: bool = False) -> \ Callable[[argparse.Namespace, List], Optional[bool]]: """A decorator to alter a cmd2 method to populate its ``args`` argument by parsing arguments with the given instance of argparse.ArgumentParse...
python
{ "resource": "" }
q33984
Cmd.decolorized_write
train
def decolorized_write(self, fileobj: IO, msg: str) -> None: """Write a string to a fileobject, stripping ANSI escape sequences if necessary Honor the current colors setting, which requires us to check whether the fileobject is a tty. """ if self.colors.lower() == constants.COLOR...
python
{ "resource": "" }
q33985
Cmd.perror
train
def perror(self, err: Union[str, Exception], traceback_war: bool = True, err_color: str = Fore.LIGHTRED_EX, war_color: str = Fore.LIGHTYELLOW_EX) -> None: """ Print error message to sys.stderr and if debug is true, print an exception Traceback if one exists. :param err: an Exception or e...
python
{ "resource": "" }
q33986
Cmd.pfeedback
train
def pfeedback(self, msg: str) -> None: """For printing nonessential feedback. Can be silenced with `quiet`. Inclusion in redirected output is controlled by `feedback_to_output`.""" if not self.quiet: if self.feedback_to_output: self.poutput(msg) else: ...
python
{ "resource": "" }
q33987
Cmd.ppaged
train
def ppaged(self, msg: str, end: str = '\n', chop: bool = False) -> None: """Print output using a pager if it would go off screen and stdout isn't currently being redirected. Never uses a pager inside of a script (Python or text) or when output is being redirected or piped or when stdout or stdi...
python
{ "resource": "" }
q33988
Cmd.reset_completion_defaults
train
def reset_completion_defaults(self) -> None: """ Resets tab completion settings Needs to be called each time readline runs tab completion """ self.allow_appended_space = True self.allow_closing_quote = True self.completion_header = '' self.display_matches ...
python
{ "resource": "" }
q33989
Cmd.basic_complete
train
def basic_complete(text: str, line: str, begidx: int, endidx: int, match_against: Iterable) -> List[str]: """ Performs tab completion against a list :param text: the string prefix we are attempting to match (all returned matches must begin with it) :param line: the current input line wi...
python
{ "resource": "" }
q33990
Cmd.delimiter_complete
train
def delimiter_complete(self, text: str, line: str, begidx: int, endidx: int, match_against: Iterable, delimiter: str) -> List[str]: """ Performs tab completion against a list but each match is split on a delimiter and only the portion of the match being tab completed i...
python
{ "resource": "" }
q33991
Cmd.get_exes_in_path
train
def get_exes_in_path(starts_with: str) -> List[str]: """Returns names of executables in a user's path :param starts_with: what the exes should start with. leave blank for all exes in path. :return: a list of matching exe names """ # Purposely don't match any executable containin...
python
{ "resource": "" }
q33992
Cmd._autocomplete_default
train
def _autocomplete_default(self, text: str, line: str, begidx: int, endidx: int, argparser: argparse.ArgumentParser) -> List[str]: """Default completion function for argparse commands.""" completer = AutoCompleter(argparser, self) tokens, _ = self.tokens_for_complet...
python
{ "resource": "" }
q33993
Cmd.get_all_commands
train
def get_all_commands(self) -> List[str]: """Returns a list of all commands.""" return [name[len(COMMAND_FUNC_PREFIX):] for name in self.get_names() if name.startswith(COMMAND_FUNC_PREFIX) and callable(getattr(self, name))]
python
{ "resource": "" }
q33994
Cmd.get_visible_commands
train
def get_visible_commands(self) -> List[str]: """Returns a list of commands that have not been hidden or disabled.""" commands = self.get_all_commands() # Remove the hidden commands for name in self.hidden_commands: if name in commands: commands.remove(name) ...
python
{ "resource": "" }
q33995
Cmd.get_commands_aliases_and_macros_for_completion
train
def get_commands_aliases_and_macros_for_completion(self) -> List[str]: """Return a list of visible commands, aliases, and macros for tab completion""" visible_commands = set(self.get_visible_commands()) alias_names = set(self.get_alias_names()) macro_names = set(self.get_macro_names()) ...
python
{ "resource": "" }
q33996
Cmd.get_help_topics
train
def get_help_topics(self) -> List[str]: """ Returns a list of help topics """ return [name[len(HELP_FUNC_PREFIX):] for name in self.get_names() if name.startswith(HELP_FUNC_PREFIX) and callable(getattr(self, name))]
python
{ "resource": "" }
q33997
Cmd.sigint_handler
train
def sigint_handler(self, signum: int, frame) -> None: """Signal handler for SIGINTs which typically come from Ctrl-C events. If you need custom SIGINT behavior, then override this function. :param signum: signal number :param frame """ if self.cur_pipe_proc_reader is no...
python
{ "resource": "" }
q33998
Cmd.parseline
train
def parseline(self, line: str) -> Tuple[str, str, str]: """Parse the line into a command name and a string containing the arguments. NOTE: This is an override of a parent class method. It is only used by other parent class methods. Different from the parent class method, this ignores self.ide...
python
{ "resource": "" }
q33999
Cmd._run_cmdfinalization_hooks
train
def _run_cmdfinalization_hooks(self, stop: bool, statement: Optional[Statement]) -> bool: """Run the command finalization hooks""" with self.sigint_protection: if not sys.platform.startswith('win') and self.stdout.isatty(): # Before the next command runs, fix any terminal pr...
python
{ "resource": "" }