_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q34000 | Cmd.runcmds_plus_hooks | train | def runcmds_plus_hooks(self, cmds: List[str]) -> bool:
"""Convenience method to run multiple commands by onecmd_plus_hooks.
This method adds the given cmds to the command queue and processes the
queue until completion or an error causes it to abort. Scripts that are
loaded will have the... | python | {
"resource": ""
} |
q34001 | Cmd._complete_statement | train | def _complete_statement(self, line: str) -> Statement:
"""Keep accepting lines of input until the command is complete.
There is some pretty hacky code here to handle some quirks of
self.pseudo_raw_input(). It returns a literal 'eof' if the input
pipe runs out. We can't refactor it becau... | python | {
"resource": ""
} |
q34002 | Cmd._redirect_output | train | def _redirect_output(self, statement: Statement) -> Tuple[bool, utils.RedirectionSavedState]:
"""Handles output redirection for >, >>, and |.
:param statement: a parsed statement from the user
:return: A bool telling if an error occurred and a utils.RedirectionSavedState object
"""
... | python | {
"resource": ""
} |
q34003 | Cmd._restore_output | train | def _restore_output(self, statement: Statement, saved_state: utils.RedirectionSavedState) -> None:
"""Handles restoring state after output redirection as well as
the actual pipe operation if present.
:param statement: Statement object which contains the parsed input from the user
:param... | python | {
"resource": ""
} |
q34004 | Cmd.cmd_func_name | train | def cmd_func_name(self, command: str) -> str:
"""Get the method name associated with a given command.
:param command: command to look up method name which implements it
:return: method name which implements the given command
"""
target = COMMAND_FUNC_PREFIX + command
ret... | python | {
"resource": ""
} |
q34005 | Cmd._run_macro | train | def _run_macro(self, statement: Statement) -> bool:
"""
Resolve a macro and run the resulting string
:param statement: the parsed statement from the command line
:return: a flag indicating whether the interpretation of commands should stop
"""
from itertools import islic... | python | {
"resource": ""
} |
q34006 | Cmd.pseudo_raw_input | train | def pseudo_raw_input(self, prompt: str) -> str:
"""Began life as a copy of cmd's cmdloop; like raw_input but
- accounts for changed stdin, stdout
- if input is a pipe (instead of a tty), look at self.echo
to decide whether to print the prompt and the input
"""
if self.... | python | {
"resource": ""
} |
q34007 | Cmd._cmdloop | train | def _cmdloop(self) -> bool:
"""Repeatedly issue a prompt, accept input, parse an initial prefix
off the received input, and dispatch to action methods, passing them
the remainder of the line as argument.
This serves the same role as cmd.cmdloop().
:return: True implies the enti... | python | {
"resource": ""
} |
q34008 | Cmd.alias_create | train | def alias_create(self, args: argparse.Namespace) -> None:
"""Create or overwrite an alias"""
# Validate the alias name
valid, errmsg = self.statement_parser.is_valid_command(args.name)
if not valid:
self.perror("Invalid alias name: {}".format(errmsg), traceback_war=False)
... | python | {
"resource": ""
} |
q34009 | Cmd.alias_list | train | def alias_list(self, args: argparse.Namespace) -> None:
"""List some or all aliases"""
if args.name:
for cur_name in utils.remove_duplicates(args.name):
if cur_name in self.aliases:
self.poutput("alias create {} {}".format(cur_name, self.aliases[cur_name])... | python | {
"resource": ""
} |
q34010 | Cmd.macro_create | train | def macro_create(self, args: argparse.Namespace) -> None:
"""Create or overwrite a macro"""
# Validate the macro name
valid, errmsg = self.statement_parser.is_valid_command(args.name)
if not valid:
self.perror("Invalid macro name: {}".format(errmsg), traceback_war=False)
... | python | {
"resource": ""
} |
q34011 | Cmd.macro_list | train | def macro_list(self, args: argparse.Namespace) -> None:
"""List some or all macros"""
if args.name:
for cur_name in utils.remove_duplicates(args.name):
if cur_name in self.macros:
self.poutput("macro create {} {}".format(cur_name, self.macros[cur_name].val... | python | {
"resource": ""
} |
q34012 | Cmd.complete_help_command | train | def complete_help_command(self, text: str, line: str, begidx: int, endidx: int) -> List[str]:
"""Completes the command argument of help"""
# Complete token against topics and visible commands
topics = set(self.get_help_topics())
visible_commands = set(self.get_visible_commands())
... | python | {
"resource": ""
} |
q34013 | Cmd.complete_help_subcommand | train | def complete_help_subcommand(self, text: str, line: str, begidx: int, endidx: int) -> List[str]:
"""Completes the subcommand argument of help"""
# Get all tokens through the one being completed
tokens, _ = self.tokens_for_completion(line, begidx, endidx)
if not tokens:
retu... | python | {
"resource": ""
} |
q34014 | Cmd.do_help | train | def do_help(self, args: argparse.Namespace) -> None:
"""List available commands or provide detailed help for a specific command"""
if not args.command or args.verbose:
self._help_menu(args.verbose)
else:
# Getting help for a specific command
func = self.cmd_f... | python | {
"resource": ""
} |
q34015 | Cmd._help_menu | train | def _help_menu(self, verbose: bool = False) -> None:
"""Show a list of commands which help can be displayed for.
"""
# Get a sorted list of help topics
help_topics = utils.alphabetical_sort(self.get_help_topics())
# Get a sorted list of visible command names
visible_comm... | python | {
"resource": ""
} |
q34016 | Cmd._print_topics | train | def _print_topics(self, header: str, cmds: List[str], verbose: bool) -> None:
"""Customized version of print_topics that can switch between verbose or traditional output"""
import io
if cmds:
if not verbose:
self.print_topics(header, cmds, 15, 80)
else:
... | python | {
"resource": ""
} |
q34017 | Cmd.do_shortcuts | train | def do_shortcuts(self, _: argparse.Namespace) -> None:
"""List available shortcuts"""
result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in sorted(self.shortcuts))
self.poutput("Shortcuts for other commands:\n{}\n".format(result)) | python | {
"resource": ""
} |
q34018 | Cmd.do_quit | train | def do_quit(self, _: argparse.Namespace) -> bool:
"""Exit this application"""
self._should_quit = True
return self._STOP_AND_EXIT | python | {
"resource": ""
} |
q34019 | Cmd.select | train | def select(self, opts: Union[str, List[str], List[Tuple[Any, Optional[str]]]],
prompt: str = 'Your choice? ') -> str:
"""Presents a numbered menu to the user. Modeled after
the bash shell's SELECT. Returns the item chosen.
Argument ``opts`` can be:
| a singl... | python | {
"resource": ""
} |
q34020 | Cmd.show | train | def show(self, args: argparse.Namespace, parameter: str = '') -> None:
"""Shows current settings of parameters.
:param args: argparse parsed arguments from the set command
:param parameter: optional search parameter
"""
param = utils.norm_fold(parameter.strip())
result =... | python | {
"resource": ""
} |
q34021 | Cmd.do_set | train | def do_set(self, args: argparse.Namespace) -> None:
"""Set a settable parameter or show current settings of parameters"""
# Check if param was passed in
if not args.param:
return self.show(args)
param = utils.norm_fold(args.param.strip())
# Check if value was passed... | python | {
"resource": ""
} |
q34022 | Cmd.do_shell | train | def do_shell(self, args: argparse.Namespace) -> None:
"""Execute a command as if at the OS prompt"""
import subprocess
# Create a list of arguments to shell
tokens = [args.command] + args.command_args
# Support expanding ~ in quoted paths
for index, _ in enumerate(token... | python | {
"resource": ""
} |
q34023 | Cmd._reset_py_display | train | def _reset_py_display() -> None:
"""
Resets the dynamic objects in the sys module that the py and ipy consoles fight over.
When a Python console starts it adopts certain display settings if they've already been set.
If an ipy console has previously been run, then py uses its settings and... | python | {
"resource": ""
} |
q34024 | Cmd.do_pyscript | train | def do_pyscript(self, args: argparse.Namespace) -> bool:
"""Run a Python script file inside the console"""
script_path = os.path.expanduser(args.script_path)
py_return = False
# Save current command line arguments
orig_args = sys.argv
try:
# Overwrite sys.ar... | python | {
"resource": ""
} |
q34025 | Cmd._generate_transcript | train | def _generate_transcript(self, history: List[Union[HistoryItem, str]], transcript_file: str) -> None:
"""Generate a transcript file from a given history of commands."""
import io
# Validate the transcript file path to make sure directory exists and write access is available
transcript_pa... | python | {
"resource": ""
} |
q34026 | Cmd.do_edit | train | def do_edit(self, args: argparse.Namespace) -> None:
"""Edit a file in a text editor"""
if not self.editor:
raise EnvironmentError("Please use 'set editor' to specify your text editing program of choice.")
command = utils.quote_string_if_needed(os.path.expanduser(self.editor))
... | python | {
"resource": ""
} |
q34027 | Cmd.do_eos | train | def do_eos(self, _: argparse.Namespace) -> None:
"""Handle cleanup when a script has finished executing"""
if self._script_dir:
self._script_dir.pop() | python | {
"resource": ""
} |
q34028 | Cmd.async_alert | train | def async_alert(self, alert_msg: str, new_prompt: Optional[str] = None) -> None: # pragma: no cover
"""
Display an important message to the user while they are at the prompt in between commands.
To the user it appears as if an alert message is printed above the prompt and their current input
... | python | {
"resource": ""
} |
q34029 | Cmd.set_window_title | train | def set_window_title(self, title: str) -> None: # pragma: no cover
"""
Set the terminal window title
IMPORTANT: This function will not set the title unless it can acquire self.terminal_lock to avoid
writing to stderr while a command is running. Therefore it is best to acquir... | python | {
"resource": ""
} |
q34030 | Cmd._initialize_plugin_system | train | def _initialize_plugin_system(self) -> None:
"""Initialize the plugin system"""
self._preloop_hooks = []
self._postloop_hooks = []
self._postparsing_hooks = []
self._precmd_hooks = []
self._postcmd_hooks = []
self._cmdfinalization_hooks = [] | python | {
"resource": ""
} |
q34031 | Cmd._validate_callable_param_count | train | def _validate_callable_param_count(cls, func: Callable, count: int) -> None:
"""Ensure a function has the given number of parameters."""
signature = inspect.signature(func)
# validate that the callable has the right number of parameters
nparam = len(signature.parameters)
if npara... | python | {
"resource": ""
} |
q34032 | Cmd._validate_prepostloop_callable | train | def _validate_prepostloop_callable(cls, func: Callable[[None], None]) -> None:
"""Check parameter and return types for preloop and postloop hooks."""
cls._validate_callable_param_count(func, 0)
# make sure there is no return notation
signature = inspect.signature(func)
if signatu... | python | {
"resource": ""
} |
q34033 | Cmd.register_preloop_hook | train | def register_preloop_hook(self, func: Callable[[None], None]) -> None:
"""Register a function to be called at the beginning of the command loop."""
self._validate_prepostloop_callable(func)
self._preloop_hooks.append(func) | python | {
"resource": ""
} |
q34034 | Cmd.register_postloop_hook | train | def register_postloop_hook(self, func: Callable[[None], None]) -> None:
"""Register a function to be called at the end of the command loop."""
self._validate_prepostloop_callable(func)
self._postloop_hooks.append(func) | python | {
"resource": ""
} |
q34035 | Cmd.register_postparsing_hook | train | def register_postparsing_hook(self, func: Callable[[plugin.PostparsingData], plugin.PostparsingData]) -> None:
"""Register a function to be called after parsing user input but before running the command"""
self._validate_postparsing_callable(func)
self._postparsing_hooks.append(func) | python | {
"resource": ""
} |
q34036 | Cmd._validate_prepostcmd_hook | train | def _validate_prepostcmd_hook(cls, func: Callable, data_type: Type) -> None:
"""Check parameter and return types for pre and post command hooks."""
signature = inspect.signature(func)
# validate that the callable has the right number of parameters
cls._validate_callable_param_count(func,... | python | {
"resource": ""
} |
q34037 | Cmd.register_precmd_hook | train | def register_precmd_hook(self, func: Callable[[plugin.PrecommandData], plugin.PrecommandData]) -> None:
"""Register a hook to be called before the command function."""
self._validate_prepostcmd_hook(func, plugin.PrecommandData)
self._precmd_hooks.append(func) | python | {
"resource": ""
} |
q34038 | Cmd.register_postcmd_hook | train | def register_postcmd_hook(self, func: Callable[[plugin.PostcommandData], plugin.PostcommandData]) -> None:
"""Register a hook to be called after the command function."""
self._validate_prepostcmd_hook(func, plugin.PostcommandData)
self._postcmd_hooks.append(func) | python | {
"resource": ""
} |
q34039 | Cmd._validate_cmdfinalization_callable | train | def _validate_cmdfinalization_callable(cls, func: Callable[[plugin.CommandFinalizationData],
plugin.CommandFinalizationData]) -> None:
"""Check parameter and return types for command finalization hooks."""
cls._validate_callable_param_count(... | python | {
"resource": ""
} |
q34040 | Cmd.register_cmdfinalization_hook | train | def register_cmdfinalization_hook(self, func: Callable[[plugin.CommandFinalizationData],
plugin.CommandFinalizationData]) -> None:
"""Register a hook to be called after a command is completed, whether it completes successfully or not."""
self._v... | python | {
"resource": ""
} |
q34041 | StatementParser.is_valid_command | train | def is_valid_command(self, word: str) -> Tuple[bool, str]:
"""Determine whether a word is a valid name for a command.
Commands can not include redirection characters, whitespace,
or termination characters. They also cannot start with a
shortcut.
If word is not a valid command, ... | python | {
"resource": ""
} |
q34042 | StatementParser.tokenize | train | def tokenize(self, line: str, expand: bool = True) -> List[str]:
"""
Lex a string into a list of tokens. Shortcuts and aliases are expanded and comments are removed
:param line: the command line being lexed
:param expand: If True, then aliases and shortcuts will be expanded.
... | python | {
"resource": ""
} |
q34043 | StatementParser.parse | train | def parse(self, line: str, expand: bool = True) -> Statement:
"""
Tokenize the input and parse it into a Statement object, stripping
comments, expanding aliases and shortcuts, and extracting output
redirection directives.
:param line: the command line being parsed
:param... | python | {
"resource": ""
} |
q34044 | StatementParser.parse_command_only | train | def parse_command_only(self, rawinput: str) -> Statement:
"""Partially parse input into a Statement object.
The command is identified, and shortcuts and aliases are expanded.
Multiline commands are identified, but terminators and output
redirection are not parsed.
This method i... | python | {
"resource": ""
} |
q34045 | StatementParser._expand | train | def _expand(self, line: str) -> str:
"""Expand shortcuts and aliases"""
# expand aliases
# make a copy of aliases so we can edit it
tmp_aliases = list(self.aliases.keys())
keep_expanding = bool(tmp_aliases)
while keep_expanding:
for cur_alias in tmp_aliases:
... | python | {
"resource": ""
} |
q34046 | StatementParser._command_and_args | train | def _command_and_args(tokens: List[str]) -> Tuple[str, str]:
"""Given a list of tokens, return a tuple of the command
and the args as a string.
"""
command = ''
args = ''
if tokens:
command = tokens[0]
if len(tokens) > 1:
args = ' '.join(... | python | {
"resource": ""
} |
q34047 | StatementParser._split_on_punctuation | train | def _split_on_punctuation(self, tokens: List[str]) -> List[str]:
"""Further splits tokens from a command line using punctuation characters
Punctuation characters are treated as word breaks when they are in
unquoted strings. Each run of punctuation characters is treated as a
single token... | python | {
"resource": ""
} |
q34048 | ArgumentAndOptionPrinter.do_aprint | train | def do_aprint(self, statement):
"""Print the argument string this basic command is called with."""
self.poutput('aprint was called with argument: {!r}'.format(statement))
self.poutput('statement.raw = {!r}'.format(statement.raw))
self.poutput('statement.argv = {!r}'.format(statement.argv... | python | {
"resource": ""
} |
q34049 | HelpCategories.do_disable_commands | train | def do_disable_commands(self, _):
"""Disable the Application Management commands"""
message_to_print = "{} is not available while {} commands are disabled".format(COMMAND_NAME,
self.CMD_CAT_APP_MGMT)
self.disa... | python | {
"resource": ""
} |
q34050 | register_custom_actions | train | def register_custom_actions(parser: argparse.ArgumentParser) -> None:
"""Register custom argument action types"""
parser.register('action', None, _StoreRangeAction)
parser.register('action', 'store', _StoreRangeAction)
parser.register('action', 'append', _AppendRangeAction) | python | {
"resource": ""
} |
q34051 | ACArgumentParser.error | train | def error(self, message: str) -> None:
"""Custom error override. Allows application to control the error being displayed by argparse"""
if len(self._custom_error_message) > 0:
message = self._custom_error_message
self._custom_error_message = ''
lines = message.split('\n'... | python | {
"resource": ""
} |
q34052 | TabCompleteExample.instance_query_movie_ids | train | def instance_query_movie_ids(self) -> List[str]:
"""Demonstrates showing tabular hinting of tab completion information"""
completions_with_desc = []
# Sort the movie id strings with a natural sort since they contain numbers
for movie_id in utils.natural_sort(self.MOVIE_DATABASE_IDS):
... | python | {
"resource": ""
} |
q34053 | TabCompleteExample.do_video | train | def do_video(self, args):
"""Video management command demonstrates multiple layers of sub-commands being handled by AutoCompleter"""
func = getattr(args, 'func', None)
if func is not None:
# Call whatever subcommand function was selected
func(self, args)
else:
... | python | {
"resource": ""
} |
q34054 | TabCompleteExample.complete_media | train | def complete_media(self, text, line, begidx, endidx):
""" Adds tab completion to media"""
choices = {'actor': query_actors, # function
'director': TabCompleteExample.static_list_directors, # static list
'movie_file': (self.path_complete,)
}
... | python | {
"resource": ""
} |
q34055 | HistoryItem.pr | train | def pr(self, script=False, expanded=False, verbose=False) -> str:
"""Represent a HistoryItem in a pretty fashion suitable for printing.
If you pass verbose=True, script and expanded will be ignored
:return: pretty print string version of a HistoryItem
"""
if verbose:
... | python | {
"resource": ""
} |
q34056 | History._zero_based_index | train | def _zero_based_index(self, onebased: Union[int, str]) -> int:
"""Convert a one-based index to a zero-based index."""
result = int(onebased)
if result > 0:
result -= 1
return result | python | {
"resource": ""
} |
q34057 | History.append | train | def append(self, new: Statement) -> None:
"""Append a HistoryItem to end of the History list
:param new: command line to convert to HistoryItem and add to the end of the History list
"""
new = HistoryItem(new)
list.append(self, new)
new.idx = len(self) | python | {
"resource": ""
} |
q34058 | History.get | train | def get(self, index: Union[int, str]) -> HistoryItem:
"""Get item from the History list using 1-based indexing.
:param index: optional item to get (index as either integer or string)
:return: a single HistoryItem
"""
index = int(index)
if index == 0:
raise In... | python | {
"resource": ""
} |
q34059 | History.span | train | def span(self, span: str) -> List[HistoryItem]:
"""Return an index or slice of the History list,
:param span: string containing an index or a slice
:return: a list of HistoryItems
This method can accommodate input in any of these forms:
a
-a
a..b or... | python | {
"resource": ""
} |
q34060 | History.str_search | train | def str_search(self, search: str) -> List[HistoryItem]:
"""Find history items which contain a given string
:param search: the string to search for
:return: a list of history items, or an empty list if the string was not found
"""
def isin(history_item):
"""filter fun... | python | {
"resource": ""
} |
q34061 | History.regex_search | train | def regex_search(self, regex: str) -> List[HistoryItem]:
"""Find history items which match a given regular expression
:param regex: the regular expression to search for.
:return: a list of history items, or an empty list if the string was not found
"""
regex = regex.strip()
... | python | {
"resource": ""
} |
q34062 | PagedOutput.page_file | train | def page_file(self, file_path: str, chop: bool=False):
"""Helper method to prevent having too much duplicated code."""
filename = os.path.expanduser(file_path)
try:
with open(filename, 'r') as f:
text = f.read()
self.ppaged(text, chop=chop)
except ... | python | {
"resource": ""
} |
q34063 | PagedOutput.do_page_wrap | train | def do_page_wrap(self, args: List[str]):
"""Read in a text file and display its output in a pager, wrapping long lines if they don't fit.
Usage: page_wrap <file_path>
"""
if not args:
self.perror('page_wrap requires a path to a file as an argument', traceback_war=False)
... | python | {
"resource": ""
} |
q34064 | PagedOutput.do_page_truncate | train | def do_page_truncate(self, args: List[str]):
"""Read in a text file and display its output in a pager, truncating long lines if they don't fit.
Truncated lines can still be accessed by scrolling to the right using the arrow keys.
Usage: page_chop <file_path>
"""
if not args:
... | python | {
"resource": ""
} |
q34065 | rl_force_redisplay | train | def rl_force_redisplay() -> None: # pragma: no cover
"""
Causes readline to display the prompt and input text wherever the cursor is and start
reading input from this location. This is the proper way to restore the input line after
printing to the screen
"""
if not sys.stdout.isatty():
... | python | {
"resource": ""
} |
q34066 | rl_get_point | train | def rl_get_point() -> int: # pragma: no cover
"""
Returns the offset of the current cursor position in rl_line_buffer
"""
if rl_type == RlType.GNU:
return ctypes.c_int.in_dll(readline_lib, "rl_point").value
elif rl_type == RlType.PYREADLINE:
return readline.rl.mode.l_buffer.point
... | python | {
"resource": ""
} |
q34067 | rl_make_safe_prompt | train | def rl_make_safe_prompt(prompt: str) -> str: # pragma: no cover
"""Overcome bug in GNU Readline in relation to calculation of prompt length in presence of ANSI escape codes.
:param prompt: original prompt
:return: prompt safe to pass to GNU Readline
"""
if rl_type == RlType.GNU:
# start co... | python | {
"resource": ""
} |
q34068 | CmdLineApp._set_prompt | train | def _set_prompt(self):
"""Set prompt so it displays the current working directory."""
self.cwd = os.getcwd()
self.prompt = Fore.CYAN + '{!r} $ '.format(self.cwd) + Fore.RESET | python | {
"resource": ""
} |
q34069 | CmdLineApp.postcmd | train | def postcmd(self, stop: bool, line: str) -> bool:
"""Hook method executed just after a command dispatch is finished.
:param stop: if True, the command has indicated the application should exit
:param line: the command line text for this command
:return: if this is True, the application ... | python | {
"resource": ""
} |
q34070 | CmdLineApp.do_dir | train | def do_dir(self, args, unknown):
"""List contents of current directory."""
# No arguments for this command
if unknown:
self.perror("dir does not take any positional arguments:", traceback_war=False)
self.do_help('dir')
self._last_result = cmd2.CommandResult(''... | python | {
"resource": ""
} |
q34071 | pop_density | train | def pop_density(data: CityInfo) -> str:
"""Calculate the population density from the data entry"""
if not isinstance(data, CityInfo):
raise AttributeError("Argument to pop_density() must be an instance of CityInfo")
return no_dec(data.get_population() / data.get_area()) | python | {
"resource": ""
} |
q34072 | make_table_parser | train | def make_table_parser() -> cmd2.argparse_completer.ACArgumentParser:
"""Create a unique instance of an argparse Argument parser for processing table arguments.
NOTE: The two cmd2 argparse decorators require that each parser be unique, even if they are essentially a deep copy
of each other. For cases like ... | python | {
"resource": ""
} |
q34073 | TableDisplay.ptable | train | def ptable(self, rows, columns, grid_args, row_stylist):
"""Format tabular data for pretty-printing as a fixed-width table and then display it using a pager.
:param rows: can be a list-of-lists (or another iterable of iterables), a two-dimensional
NumPy array, or an Iterable of non... | python | {
"resource": ""
} |
q34074 | Pirate.postcmd | train | def postcmd(self, stop, line):
"""Runs right before a command is about to return."""
if self.gold != self.initial_gold:
self.poutput('Now we gots {0} doubloons'.format(self.gold))
if self.gold < 0:
self.poutput("Off to debtorrr's prison.")
stop = True
... | python | {
"resource": ""
} |
q34075 | Pirate.do_sing | train | def do_sing(self, arg):
"""Sing a colorful song."""
color_escape = COLORS.get(self.songcolor, Fore.RESET)
self.poutput(arg, color=color_escape) | python | {
"resource": ""
} |
q34076 | Pirate.do_yo | train | def do_yo(self, args):
"""Compose a yo-ho-ho type chant with flexible options."""
chant = ['yo'] + ['ho'] * args.ho
separator = ', ' if args.commas else ' '
chant = separator.join(chant)
self.poutput('{0} and a bottle of {1}'.format(chant, args.beverage)) | python | {
"resource": ""
} |
q34077 | get_sub_commands | train | def get_sub_commands(parser: argparse.ArgumentParser) -> List[str]:
"""Get a list of sub-commands for an ArgumentParser"""
sub_cmds = []
# Check if this is parser has sub-commands
if parser is not None and parser._subparsers is not None:
# Find the _SubParsersAction for the sub-commands of thi... | python | {
"resource": ""
} |
q34078 | main | train | def main() -> None:
"""Main function of this script"""
# Make sure we have access to self
if 'self' not in globals():
print("Run 'set locals_in_py true' and then rerun this script")
return
# Make sure the user passed in an output file
if len(sys.argv) != 2:
print("Usage: {}... | python | {
"resource": ""
} |
q34079 | cached | train | def cached(cache, key=keys.hashkey, lock=None):
"""Decorator to wrap a function with a memoizing callable that saves
results in a cache.
"""
def decorator(func):
if cache is None:
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
elif lock is None:
... | python | {
"resource": ""
} |
q34080 | cachedmethod | train | def cachedmethod(cache, key=keys.hashkey, lock=None):
"""Decorator to wrap a class or instance method with a memoizing
callable that saves results in a cache.
"""
def decorator(method):
if lock is None:
def wrapper(self, *args, **kwargs):
c = cache(self)
... | python | {
"resource": ""
} |
q34081 | iter_result_proxy | train | def iter_result_proxy(rp, step=None):
"""Iterate over the ResultProxy."""
while True:
if step is None:
chunk = rp.fetchall()
else:
chunk = rp.fetchmany(step)
if not chunk:
break
for row in chunk:
yield row | python | {
"resource": ""
} |
q34082 | normalize_column_name | train | def normalize_column_name(name):
"""Check if a string is a reasonable thing to use as a column name."""
if not isinstance(name, six.string_types):
raise ValueError('%r is not a valid column name.' % name)
# limit to 63 characters
name = name.strip()[:63]
# column names can be 63 *bytes* max... | python | {
"resource": ""
} |
q34083 | safe_url | train | def safe_url(url):
"""Remove password from printed connection URLs."""
parsed = urlparse(url)
if parsed.password is not None:
pwd = ':%s@' % parsed.password
url = url.replace(pwd, ':*****@')
return url | python | {
"resource": ""
} |
q34084 | index_name | train | def index_name(table, columns):
"""Generate an artificial index name."""
sig = '||'.join(columns)
key = sha1(sig.encode('utf-8')).hexdigest()[:16]
return 'ix_%s_%s' % (table, key) | python | {
"resource": ""
} |
q34085 | ensure_tuple | train | def ensure_tuple(obj):
"""Try and make the given argument into a tuple."""
if obj is None:
return tuple()
if isinstance(obj, Iterable) and not isinstance(obj, six.string_types):
return tuple(obj)
return obj, | python | {
"resource": ""
} |
q34086 | pad_chunk_columns | train | def pad_chunk_columns(chunk):
"""Given a set of items to be inserted, make sure they all have the
same columns by padding columns with None if they are missing."""
columns = set()
for record in chunk:
columns.update(record.keys())
for record in chunk:
for column in columns:
... | python | {
"resource": ""
} |
q34087 | Types.guess | train | def guess(cls, sample):
"""Given a single sample, guess the column type for the field.
If the sample is an instance of an SQLAlchemy type, the type will be
used instead.
"""
if isinstance(sample, TypeEngine):
return sample
if isinstance(sample, bool):
... | python | {
"resource": ""
} |
q34088 | Table.insert | train | def insert(self, row, ensure=None, types=None):
"""Add a ``row`` dict by inserting it into the table.
If ``ensure`` is set, any of the keys of the row are not
table columns, they will be created automatically.
During column creation, ``types`` will be checked for a key
matching... | python | {
"resource": ""
} |
q34089 | Table.insert_ignore | train | def insert_ignore(self, row, keys, ensure=None, types=None):
"""Add a ``row`` dict into the table if the row does not exist.
If rows with matching ``keys`` exist they will be added to the table.
Setting ``ensure`` results in automatically creating missing columns,
i.e., keys of the row... | python | {
"resource": ""
} |
q34090 | Table.insert_many | train | def insert_many(self, rows, chunk_size=1000, ensure=None, types=None):
"""Add many rows at a time.
This is significantly faster than adding them one by one. Per default
the rows are processed in chunks of 1000 per commit, unless you specify
a different ``chunk_size``.
See :py:m... | python | {
"resource": ""
} |
q34091 | Table.update | train | def update(self, row, keys, ensure=None, types=None, return_count=False):
"""Update a row in the table.
The update is managed via the set of column names stated in ``keys``:
they will be used as filters for the data to be updated, using the
values in ``row``.
::
# u... | python | {
"resource": ""
} |
q34092 | Table.upsert | train | def upsert(self, row, keys, ensure=None, types=None):
"""An UPSERT is a smart combination of insert and update.
If rows with matching ``keys`` exist they will be updated, otherwise a
new row is inserted in the table.
::
data = dict(id=10, title='I am a banana!')
... | python | {
"resource": ""
} |
q34093 | Table.delete | train | def delete(self, *clauses, **filters):
"""Delete rows from the table.
Keyword arguments can be used to add column-based filters. The filter
criterion will always be equality:
::
table.delete(place='Berlin')
If no arguments are given, all records are deleted.
... | python | {
"resource": ""
} |
q34094 | Table._reflect_table | train | def _reflect_table(self):
"""Load the tables definition from the database."""
with self.db.lock:
try:
self._table = SQLATable(self.name,
self.db.metadata,
schema=self.db.schema,
... | python | {
"resource": ""
} |
q34095 | Table._sync_table | train | def _sync_table(self, columns):
"""Lazy load, create or adapt the table structure in the database."""
if self._table is None:
# Load an existing table from the database.
self._reflect_table()
if self._table is None:
# Create the table with an initial set of co... | python | {
"resource": ""
} |
q34096 | Table.drop | train | def drop(self):
"""Drop the table from the database.
Deletes both the schema and all the contents within it.
"""
with self.db.lock:
if self.exists:
self._threading_warn()
self.table.drop(self.db.executable, checkfirst=True)
sel... | python | {
"resource": ""
} |
q34097 | Table.has_index | train | def has_index(self, columns):
"""Check if an index exists to cover the given ``columns``."""
if not self.exists:
return False
columns = set([normalize_column_name(c) for c in columns])
if columns in self._indexes:
return True
for column in columns:
... | python | {
"resource": ""
} |
q34098 | Table.create_index | train | def create_index(self, columns, name=None, **kw):
"""Create an index to speed up queries on a table.
If no ``name`` is given a random name is created.
::
table.create_index(['name', 'country'])
"""
columns = [normalize_column_name(c) for c in ensure_tuple(columns)]
... | python | {
"resource": ""
} |
q34099 | Table.find | train | def find(self, *_clauses, **kwargs):
"""Perform a simple search on the table.
Simply pass keyword arguments as ``filter``.
::
results = table.find(country='France')
results = table.find(country='France', year=1980)
Using ``_limit``::
# just return ... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.