Same as get_invocation_command_nodefault, except that if no tool is found,
        returns either the user-provided-command, if present, or the 'tool' parameter.
769086
def get_invocation_command(toolset, tool, user_provided_command = [],
                           additional_paths = [], path_last = False):
    
    assert isinstance(toolset, basestring)
    assert isinstance(tool, basestring)
    assert is_iterable_typed(user_provided_command, basestring)
    assert is_iterable_typed(additional_paths, basestring) or additional_paths is None
    assert isinstance(path_last, (int, bool))

    result = get_invocation_command_nodefault(toolset, tool,
                                              user_provided_command,
                                              additional_paths,
                                              path_last)

    if not result:
        if user_provided_command:
            result = user_provided_command[0]
        else:
            result = tool

    assert(isinstance(result, str))

    return result
713669
function(node) {
      me.current_ = node;
      if (!node) {
        return me.defaultOnSuccess_(node);
      }
      var x = /** @type {ydn.db.con.simple.Node} */ (node.value);
      var e_key = x.getKey();
      var cmp = ydn.db.cmp(e_key, key);
      if (me.reverse) {
        if (cmp != 1) {
          return me.defaultOnSuccess_(node);
        }
      } else {
        if (cmp != -1) {
          return me.defaultOnSuccess_(node);
        }
      }
    }
179635
protected FindCommandResult findAndCreateCommand(String[] args) throws CommandInitException {
	  String commandName = args[0];
	  String[] remainingArguments = StringUtils.stripArgs(args, 1);
		
	  // Check top level commands for app
	  Class<? extends Command<? extends CLIContext>> commandClass = _commands.get(commandName);
		
		if (commandClass == null) {
			return null;
		}
		try {
		  // Create the instance of the root class and let that class hunt for any subcommands
		  Command<? extends CLIContext> rootCmd = (Command<? extends CLIContext>)commandClass.newInstance();
		  
			return rootCmd.findAndCreateCommand(remainingArguments);
		}
		catch (Exception e) {
			throw new CommandInitException(commandName);
		}
	}
1245395
def get_command(self, ctx, name):
        """"""
        if name not in self.daemon_class.list_actions():
            return None

        # The context object is a Daemon object
        daemon = ctx.obj

        def subcommand(debug=False):
            """Call a daemonocle action."""
            if daemon.detach and debug:
                daemon.detach = False

            daemon.do_action(name)

        # Override the docstring for the function so that it shows up
        # correctly in the help output
        subcommand.__doc__ = daemon.get_action(name).__doc__

        if name == 'start':
            # Add a --debug option for start
            subcommand = click.option(
                '--debug', is_flag=True,
                help='Do NOT detach and run in the background.'
            )(subcommand)

        # Make it into a click command
        subcommand = click.command(
            name, options_metavar=self.options_metavar)(subcommand)

        return subcommand
949036
def get_command(self, ctx, name):
        """"""
        if not self._commands_dir:
            return defaults.get_command(ctx, name)

        ns = {}
        fn = os.path.join(self._commands_dir, name + '.py')

        try:
            with open(fn) as f:
                code = compile(f.read(), fn, 'exec')
        except IOError:
            return defaults.get_command(ctx, name)

        eval(code, ns, ns)

        CLI = 'cli'

        try:
            return ns[CLI]
        except KeyError:
            ctx.fail('`{}` not defined in "{}"'.format(CLI, name))
51528
def get_handler(self, *args, **options):
        
        handler = super(Command, self).get_handler(*args, **options)
        insecure_serving = options.get('insecure_serving', False)
        if self.should_use_static_handler(options):
            return StaticFilesHandler(handler)
        return handler
1325659
def get_ns_command(self, cmd_name):
        
        namespace, command = _split_ns_command(cmd_name)
        if not namespace:
            # Name space not given, look for the command
            spaces = self.__find_command_ns(command)
            if not spaces:
                # Unknown command
                raise ValueError("Unknown command {0}".format(command))
            elif len(spaces) > 1:
                # Multiple possibilities
                if spaces[0] == DEFAULT_NAMESPACE:
                    # Default name space has priority
                    namespace = DEFAULT_NAMESPACE

                else:
                    # Ambiguous name
                    raise ValueError(
                        "Multiple name spaces for command '{0}': {1}".format(
                            command, ", ".join(sorted(spaces))
                        )
                    )
            else:
                # Use the found name space
                namespace = spaces[0]

        # Command found
        return namespace, command
1054924
function getBowerCommand(cmd) {
    // bower has some commands that are provided in a nested object structure, e.g. `bower cache clean`.
    var bowerCommand;

    // clean up the command given, to avoid unnecessary errors
    cmd = cmd.trim();

    var nestedCommand = cmd.split(' ');

    if (nestedCommand.length > 1) {
        // To enable that kind of nested commands, we try to resolve those commands, before passing them to bower.
        for (var commandPos = 0; commandPos < nestedCommand.length; commandPos++) {
            if (bowerCommand) {
                // when the root command is already there, walk into the depth.
                bowerCommand = bowerCommand[nestedCommand[commandPos]];
            } else {
                // the first time we look for the "root" commands available in bower
                bowerCommand = bower.commands[nestedCommand[commandPos]];
            }
        }
    } else {
        // if the command isn't nested, just go ahead as usual
        bowerCommand = bower.commands[cmd];
    }

    // try to give a good error description to the user when a bad command was passed
    if (bowerCommand === undefined) {
        throw new PluginError(PLUGIN_NAME, 'The command \'' + cmd + '\' is not available in the bower commands');
    }

    return bowerCommand;
}
1154204
def get_tool(name, context=None, default=_marker):
    

    # Try first with the context
    if context is not None:
        try:
            context = get_object(context)
            return getToolByName(context, name)
        except (APIError, AttributeError) as e:
            # https://github.com/senaite/bika.lims/issues/396
            logger.warn("get_tool::getToolByName({}, '{}') failed: {} "
                        "-> falling back to plone.api.portal.get_tool('{}')"
                        .format(repr(context), name, repr(e), name))
            return get_tool(name, default=default)

    # Try with the plone api
    try:
        return ploneapi.portal.get_tool(name)
    except InvalidParameterError:
        if default is not _marker:
            return default
        fail("No tool named '%s' found." % name)
41493
def _check_toolplus(x):
    
    import argparse
    Tool = collections.namedtuple("Tool", ["name", "fname"])
    std_choices = set(["data", "cadd", "dbnsfp", "ericscript"])
    if x in std_choices:
        return Tool(x, None)
    elif "=" in x and len(x.split("=")) == 2:
        name, fname = x.split("=")
        fname = os.path.normpath(os.path.realpath(fname))
        if not os.path.exists(fname):
            raise argparse.ArgumentTypeError("Unexpected --toolplus argument for %s. File does not exist: %s"
                                             % (name, fname))
        return Tool(name, fname)
    else:
        raise argparse.ArgumentTypeError("Unexpected --toolplus argument. Expect toolname=filename.")
703296
async def _default_help_command(ctx, *commands : str):
    """"""
    bot = ctx.bot
    destination = ctx.message.author if bot.pm_help else ctx.message.channel

    def repl(obj):
        return _mentions_transforms.get(obj.group(0), '')

    # help by itself just lists our own commands.
    if len(commands) == 0:
        pages = bot.formatter.format_help_for(ctx, bot)
    elif len(commands) == 1:
        # try to see if it is a cog name
        name = _mention_pattern.sub(repl, commands[0])
        command = None
        if name in [x.lower() for x in bot.cogs]:
            command = bot.cogs[[x for x in bot.cogs if x.lower() == name][0]]
        else:
            command = bot.commands.get(name)
            if command is None:
                await bot.responses.failure(destination=destination, message=bot.command_not_found.format(name))
                return

        pages = bot.formatter.format_help_for(ctx, command)
    else:
        name = _mention_pattern.sub(repl, commands[0])
        command = bot.commands.get(name)
        if command is None:
            await bot.responses.failure(destination=destination, message=bot.command_not_found.format(name))
            return

        for key in commands[1:]:
            try:
                key = _mention_pattern.sub(repl, key)
                command = command.commands.get(key)
                if command is None:
                    await bot.responses.failure(destination=destination, message=bot.command_not_found.format(name))
                    return
            except AttributeError:
                await bot.responses.failure(destination=destination, message=bot.command_has_no_subcommands.format(command, key))
                return

        pages = bot.formatter.format_help_for(ctx, command)

    if bot.pm_help is None:
        characters = sum(map(lambda l: len(l), pages.values()))
        if characters > 1000:
            destination = ctx.message.author

    await bot.responses.full(destination=destination, **pages)
593495
def node_module_exists(command, install_instructions = 'npm install -g')
      cmd = `if hash #{command} 2>/dev/null; then echo "true"; else echo "false"; fi`
      if cmd.include? "false"
        command_msg = "Missing command #{command}"
        abort "#{command_msg}: Please run `#{install_instructions} #{command}` And try again\n"
        exit 1
      end
    end
161399
def get_command(self):
        
        cmd = None
        count = len(self.command_list)
        if count > 0:
            cmd = self.command_list.pop(0)
        ## If that was the last line, turn off lines_pending
        if count == 1:
            self.cmd_ready = False
        return cmd
852321
def default_value(self, argname):
        
        i = _find_arg(argname, self.args)[0]
        if i is not None:
            idx = i - (len(self.args) - len(self.defaults))
            if idx >= 0:
                return self.defaults[idx]
        i = _find_arg(argname, self.kwonlyargs)[0]
        if i is not None and self.kw_defaults[i] is not None:
            return self.kw_defaults[i]
        raise exceptions.NoDefault(func=self.parent, name=argname)
762078
def _get_picard_cmd(self, command, memscale=None):
        
        resources = config_utils.get_resources("picard", self._config)
        if memscale:
            jvm_opts = get_picard_opts(self._config, memscale=memscale)
        elif resources.get("jvm_opts"):
            jvm_opts = resources.get("jvm_opts")
        else:
            jvm_opts = self._jvm_opts
        if os.path.isdir(self._picard_ref):
            dist_file = self._get_jar(command)
            return ["java"] + jvm_opts + get_default_jvm_opts() + ["-jar", dist_file]
        else:
            # XXX Cannot currently set JVM opts with picard-tools script
            return [self._picard_ref, command]
508552
def commandfactory(cmdline, mode='global'):
    
    # split commandname and parameters
    if not cmdline:
        return None
    logging.debug('mode:%s got commandline "%s"', mode, cmdline)
    # allow to shellescape without a space after '!'
    if cmdline.startswith('!'):
        cmdline = 'shellescape \'%s\'' % cmdline[1:]
    cmdline = re.sub(r'"(.*)"', r'"\\"\1\\""', cmdline)
    try:
        args = split_commandstring(cmdline)
    except ValueError as e:
        raise CommandParseError(str(e))
    args = [string_decode(x, 'utf-8') for x in args]
    logging.debug('ARGS: %s', args)
    cmdname = args[0]
    args = args[1:]

    # unfold aliases
    # TODO: read from settingsmanager

    # get class, argparser and forced parameter
    (cmdclass, parser, forcedparms) = lookup_command(cmdname, mode)
    if cmdclass is None:
        msg = 'unknown command: %s' % cmdname
        logging.debug(msg)
        raise CommandParseError(msg)

    parms = vars(parser.parse_args(args))
    parms.update(forcedparms)

    logging.debug('cmd parms %s', parms)

    # create Command
    cmd = cmdclass(**parms)

    # set pre and post command hooks
    get_hook = settings.get_hook
    cmd.prehook = get_hook('pre_%s_%s' % (mode, cmdname)) or \
        get_hook('pre_global_%s' % cmdname)
    cmd.posthook = get_hook('post_%s_%s' % (mode, cmdname)) or \
        get_hook('post_global_%s' % cmdname)

    return cmd
584424
def default_tool_argparser(description, example_parameters):
    
    import argparse
    epilog = '\n'
    for k, v in sorted(example_parameters.items()):
        epilog += '  ' + k + '\n'
    p = argparse.ArgumentParser(
        description=description,
        add_help=False,
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=('available values for examples (exkey):'+epilog))
    return p