Query tool.
@param {!wtf.pal.IPlatform} platform Platform abstraction layer.
@param {!Array.<string>} args Command line arguments.
@param {function(number)} done Call to end the program with a return code.
429089
function runTool(platform, args, done) {
  if (args.length < 1) {
    console.log('usage: query.js file.wtf-trace "[query string]"');
    done(1);
    return;
  }

  var inputFile = args[0];
  var exprArgs = args.slice(1);
  var expr = exprArgs.join(' ').trim();

  console.log('Querying ' + inputFile + '...');

  // Create database for querying.
  var loadStart = wtf.now();
  wtf.db.load(inputFile, function(db) {
    if (db instanceof Error) {
      console.log('ERROR: unable to open ' + inputFile, db);
      done(1);
      return;
    }

    var loadDuration = wtf.now() - loadStart;
    console.log('Database loaded in ' + loadDuration.toFixed(3) + 'ms');
    console.log('');

    queryDatabase(db, expr);

    done(0);
  });
}
852655
function (args, onDone, extra) {
		// if args are not provided then we shift the parameters
		if (typeof args === 'function') {
			extra = onDone;
			onDone = args;
			args = {};
		}

		// TODO: perform argument type check (currently there's none, so internal API calls won't do type checks)
		// TODO: move checker to here

		var onError = function(err) {
			LOG.error('onError '+ err, l_name);
			UTIL.safeCall(onDone, err);
		}

		function onExec() {
			// make actual call to user-defined function
			// NOTE: we also return values for direct function calls
			return UTIL.safeCall(l_list[name], args, function (err, result, unsupported_return) {
				if (err) {
					LOG.error('[' + name + '] error:', l_name);
					LOG.error(err, l_name);
				}

				if (unsupported_return) {
					var errmsg = 'onDone() in SR.API does not support more than one return variable, please return everything inside a result object';
					LOG.error(errmsg, l_name);
					LOG.stack();
					return UTIL.safeCall(onDone, errmsg);
				}

				// perform post-event actions, if any
				if (l_afterActions.hasOwnProperty(name) === false) {
					return UTIL.safeCall(onDone, err, result);
				}

				var posts = l_afterActions[name];
				var promise = undefined;
				for (var i=0; i < posts.length; i++) {
					if (!promise) {
						promise = post_action(args, { err: err, result: result }, posts[i], extra);
					} else {
						promise = promise.then(post_action(args, { err: err, result: result }, posts[i], extra));
					}
				}

				// last action
				promise.then(new SR.promise(function (resolve, reject) {
					//LOG.warn('everything is done... call original onDone...', l_name);
					UTIL.safeCall(onDone, err, result);
					resolve();
				}));

			}, extra);
		}

		// perform pre-event actions, if any
		if (l_beforeActions.hasOwnProperty(name) === false) {
			return onExec();
		}

		const pres = l_beforeActions[name].map((callback) => pre_action(args, callback, extra));
		pres.reduce((p, callback) => p.then(() => callback), Promise.resolve())
			.then(onExec)
			.catch((err) => {
				LOG.error(err);
				onDone(err);
			});
	}
1034251
function(query) {
	//	console.log(query);
	// Loop over all sources
	// Todo: make this loop smaller and more graspable
	for (var k = 0, klen = query.sources.length; k < klen; k++) {
		var source = query.sources[k];
		delete source.ix;
		// If there is indexation rule
		//console.log('preIndex', source);
		//console.log(source);
		if (k > 0 && source.optimization == 'ix' && source.onleftfn && source.onrightfn) {
			// If there is no table.indices - create it
			if (source.databaseid && alasql.databases[source.databaseid].tables[source.tableid]) {
				if (!alasql.databases[source.databaseid].tables[source.tableid].indices)
					query.database.tables[source.tableid].indices = {};
				// Check if index already exists
				var ixx =
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.onrightfns + '`' + source.srcwherefns)
					];
				if (!alasql.databases[source.databaseid].tables[source.tableid].dirty && ixx) {
					source.ix = ixx;
				}
			}

			if (!source.ix) {
				source.ix = {};
				// Walking over source data
				var scope = {};
				var i = 0;
				var ilen = source.data.length;
				var dataw;
				//				while(source.getfn i<ilen) {

				while (
					(dataw = source.data[i]) ||
					(source.getfn && (dataw = source.getfn(i))) ||
					i < ilen
				) {
					if (source.getfn && !source.dontcache) source.data[i] = dataw;
					//					scope[tableid] = dataw;

					//				for(var i=0, ilen=source.data.length; i<ilen; i++) {
					// Prepare scope for indexation
					scope[source.alias || source.tableid] = dataw;

					// Check if it apply to where function
					if (source.srcwherefn(scope, query.params, alasql)) {
						// Create index entry for each address
						var addr = source.onrightfn(scope, query.params, alasql);
						var group = source.ix[addr];
						if (!group) {
							group = source.ix[addr] = [];
						}
						group.push(dataw);
					}
					i++;
				}

				if (
					source.databaseid &&
					alasql.databases[source.databaseid].tables[source.tableid]
				) {
					// Save index to original table
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.onrightfns + '`' + source.srcwherefns)
					] =
						source.ix;
				}
			}
			//console.log(38,274,source.ix);

			// Optimization for WHERE column = expression
		} else if (source.wxleftfn) {
			if (!alasql.databases[source.databaseid].engineid) {
				// Check if index exists
				ixx =
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.wxleftfns + '`')
					];
			}
			if (!alasql.databases[source.databaseid].tables[source.tableid].dirty && ixx) {
				// Use old index if exists
				source.ix = ixx;
				// Reduce data (apply filter)
				source.data = source.ix[source.wxrightfn(null, query.params, alasql)];
			} else {
				// Create new index
				source.ix = {};
				// Prepare scope
				scope = {};
				// Walking on each source line
				i = 0;
				ilen = source.data.length;
				dataw;
				//				while(source.getfn i<ilen) {

				while (
					(dataw = source.data[i]) ||
					(source.getfn && (dataw = source.getfn(i))) ||
					i < ilen
				) {
					if (source.getfn && !source.dontcache) source.data[i] = dataw;
					//					for(var i=0, ilen=source.data.length; i<ilen; i++) {
					scope[source.alias || source.tableid] = source.data[i];
					// Create index entry
					addr = source.wxleftfn(scope, query.params, alasql);
					group = source.ix[addr];
					if (!group) {
						group = source.ix[addr] = [];
					}
					group.push(source.data[i]);
					i++;
				}
				//					query.database.tables[source.tableid].indices[hash(source.wxleftfns+'`'+source.onwherefns)] = source.ix;
				if (!alasql.databases[source.databaseid].engineid) {
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.wxleftfns + '`')
					] =
						source.ix;
				}
			}
			// Apply where filter to reduces rows
			if (source.srcwherefns) {
				if (source.data) {
					scope = {};
					source.data = source.data.filter(function(r) {
						scope[source.alias] = r;
						return source.srcwherefn(scope, query.params, alasql);
					});
				} else {
					source.data = [];
				}
			}
			//			}
			// If there is no any optimization than apply srcwhere filter
		} else if (source.srcwherefns && !source.dontcache) {
			if (source.data) {
				var scope = {};
				// TODO!!!!! Data as Function

				source.data = source.data.filter(function(r) {
					scope[source.alias] = r;
					//					console.log(288,source);
					return source.srcwherefn(scope, query.params, alasql);
				});

				scope = {};
				i = 0;
				ilen = source.data.length;
				//var dataw;
				var res = [];
				//				while(source.getfn i<ilen) {

				while (
					(dataw = source.data[i]) ||
					(source.getfn && (dataw = source.getfn(i))) ||
					i < ilen
				) {
					if (source.getfn && !source.dontcache) source.data[i] = dataw;
					scope[source.alias] = dataw;
					if (source.srcwherefn(scope, query.params, alasql)) res.push(dataw);
					i++;
				}
				source.data = res;
			} else {
				source.data = [];
			}
		}
		// Change this to another place (this is a wrong)
		if (source.databaseid && alasql.databases[source.databaseid].tables[source.tableid]) {
			//query.database.tables[source.tableid].dirty = false;
		} else {
			// this is a subquery?
		}
	}
}
1182954
def handle_jmespath_query(self, args):
        
        continue_flag = False
        query_symbol = SELECT_SYMBOL['query']
        symbol_len = len(query_symbol)
        try:
            if len(args) == 1:
                # if arguments start with query_symbol, just print query result
                if args[0] == query_symbol:
                    result = self.last.result
                elif args[0].startswith(query_symbol):
                    result = jmespath.search(args[0][symbol_len:], self.last.result)
                print(json.dumps(result, sort_keys=True, indent=2), file=self.output)
            elif args[0].startswith(query_symbol):
                # print error message, user unsure of query shortcut usage
                print(("Usage Error: " + os.linesep +
                       "1. Use {0} stand-alone to display previous result with optional filtering "
                       "(Ex: {0}[jmespath query])" +
                       os.linesep + "OR:" + os.linesep +
                       "2. Use {0} to query the previous result for argument values "
                       "(Ex: group show --name {0}[jmespath query])").format(query_symbol), file=self.output)
            else:
                # query, inject into cmd
                def jmespath_query(match):
                    if match.group(0) == query_symbol:
                        return str(self.last.result)
                    query_result = jmespath.search(match.group(0)[symbol_len:], self.last.result)
                    return str(query_result)

                def sub_result(arg):
                    escaped_symbol = re.escape(query_symbol)
                    # regex captures query symbol and all characters following it in the argument
                    return json.dumps(re.sub(r'%s.*' % escaped_symbol, jmespath_query, arg))
                cmd_base = ' '.join(map(sub_result, args))
                self.cli_execute(cmd_base)
            continue_flag = True
        except (jmespath.exceptions.ParseError, CLIError) as e:
            print("Invalid Query Input: " + str(e), file=self.output)
            continue_flag = True
        return continue_flag
1049613
function _pipe(method, args, done) {

  let proc;
  let isProc =
    typeof method === 'object' &&
    (method.constructor && method.constructor.name === 'ChildProcess');

  done = done || function () {};

  if (typeof args === 'function') {
    done = args;
    args = undefined;
  }

  // Ensure args array.
  args = args || [];

  // Allow passing args as a string.
  // supports either ' ' or ', '.
  if (typeof args === 'string') {
    let splitChar = ~args.indexOf(',') ? ',' : ' ';
    if (splitChar === ',')
      args = args.replace(/\s/g, '');
    args = args.split(splitChar);
  }

  // If string assume command set method to spawn.
  if (typeof method === 'string') {
    args = [method, args];
    method = spawn;
  }

  if (isProc)
    proc = method;

  if (!proc)
    proc = method(...args);

  const thru = thruHandler(done);

  proc.stdin = proc.stdin || process.stdin;
  proc.stdout = proc.stdout || process.stdout;
  proc.stderr = proc.stderr || process.stderr;

  proc.stdout.pipe(thru);

  return proc;

}
261076
function (done) {
            var select = {};
            select[pathName] = 1;

            Model.findOne({_id: model}, select, function (err, doc) {
              if (err) return done(err);
              if (!doc) return done(null, []);

              done(null, doc[pathName].reduce(function (o, friend) {
                o[friend._id] = friend.toObject();
                return o;
              }, {}));
            });
          }
523706
function () {
				if (q) {
					for (var i = 0, len = arguments.length; i < len; i++) {
						q.push(arguments[i]);
						if (!q.pending) {
							doNext.apply({}, q.args || []);
						}
					}
				}
				return me;
			}
1019888
def _query(action=None,
           command=None,
           args=None,
           method='GET',
           header_dict=None,
           data=None,
           url='https://api.linode.com/'):
    '''
    
    '''
    global LASTCALL
    vm_ = get_configured_provider()

    ratelimit_sleep = config.get_cloud_config_value(
        'ratelimit_sleep', vm_, __opts__, search_global=False, default=0,
    )
    apikey = config.get_cloud_config_value(
        'apikey', vm_, __opts__, search_global=False
    )

    if not isinstance(args, dict):
        args = {}

    if 'api_key' not in args.keys():
        args['api_key'] = apikey

    if action and 'api_action' not in args.keys():
        args['api_action'] = '{0}.{1}'.format(action, command)

    if header_dict is None:
        header_dict = {}

    if method != 'POST':
        header_dict['Accept'] = 'application/json'

    decode = True
    if method == 'DELETE':
        decode = False

    now = int(time.mktime(datetime.datetime.now().timetuple()))
    if LASTCALL >= now:
        time.sleep(ratelimit_sleep)

    result = __utils__['http.query'](
        url,
        method,
        params=args,
        data=data,
        header_dict=header_dict,
        decode=decode,
        decode_type='json',
        text=True,
        status=True,
        hide_fields=['api_key', 'rootPass'],
        opts=__opts__,
    )

    if 'ERRORARRAY' in result['dict']:
        if result['dict']['ERRORARRAY']:
            error_list = []

            for error in result['dict']['ERRORARRAY']:
                msg = error['ERRORMESSAGE']

                if msg == "Authentication failed":
                    raise SaltCloudSystemExit(
                        'Linode API Key is expired or invalid'
                    )
                else:
                    error_list.append(msg)
            raise SaltCloudException(
                'Linode API reported error(s): {}'.format(", ".join(error_list))
            )

    LASTCALL = int(time.mktime(datetime.datetime.now().timetuple()))
    log.debug('Linode Response Status Code: %s', result['status'])

    return result['dict']
737288
function PlatformInfo(PlatformCtor, platformId) {

    this._Ctor = PlatformCtor;
    this._platformId = platformId;

    // Prefix all platform-specific args with the platform name
    var argSpec = PlatformCtor.getArgs ? PlatformCtor.getArgs() : {};
    this._argSpec = {};
    for (var cmd in argSpec) {
        var cmdArgSpec = argSpec[cmd];
        var platformCmdArgSpec = {};
        for (var key in cmdArgSpec) {
            platformCmdArgSpec["--" + platformId + "-" + key] = cmdArgSpec[key];
        }
        this._argSpec[cmd] = platformCmdArgSpec;
    }

    // Look for platforms env vars
    this._envSpec = PlatformCtor.getEnv ? PlatformCtor.getEnv() : {};
}
791189
function(fns, done) {
    done = done || function() {};
    this.map(fns, function(fn, callback) {
      fn(callback);
    }, done);
  }
1146230
public static void processCommandLine(TextUICommandLine commandLine, String[] argv, IFindBugsEngine findBugs)
            throws IOException, FilterException {
        // Expand option files in command line.
        // An argument beginning with "@" is treated as specifying
        // the name of an option file.
        // Each line of option files are treated as a single argument.
        // Blank lines and comment lines (beginning with "#")
        // are ignored.
        try {
            argv = commandLine.expandOptionFiles(argv, true, true);
        } catch (HelpRequestedException e) {
            showHelp(commandLine);
        }

        int argCount = 0;
        try {
            argCount = commandLine.parse(argv);
        } catch (IllegalArgumentException e) {
            LOG.severe(e.getMessage());
            showHelp(commandLine);
        } catch (HelpRequestedException e) {
            showHelp(commandLine);
        }

        Project project = commandLine.getProject();
        for (int i = argCount; i < argv.length; ++i) {
            project.addFile(argv[i]);
        }
        commandLine.handleXArgs();

        commandLine.configureEngine(findBugs);
        if (commandLine.getProject().getFileCount() == 0 &&
                !commandLine.justPrintConfiguration() && !commandLine.justPrintVersion()) {
            LOG.warning("No files to be analyzed");

            showHelp(commandLine);
        }
    }
1235019
function parse(input, done) {
  if (input && input.args) return done(undefined, input);
  if (input) done(undefined, {args: [].concat(input)});
  cmd([], done);
}
1219273
function queryCommandSupported(command) {
        command = command.toLowerCase();

        if (commands.exec[command]) {
          return true;
        }

        // Browser commands
        try {
          return editor.getDoc().queryCommandSupported(command);
        } catch (ex) {
          // Fails sometimes see bug: 1896577
        }

        return false;
      }
593274
function cmd_unlock(args, done) {
    var seneca = this
    cmd_increment_lock(seneca, args.id, true, function(err) {
      if (err) return done(err, { ok: false, why: err })
      done(null, { ok: true })
    })
  }
612687
function executeCmd(cmd, debug, quitapp) {
    if (typeof cmd !== 'object') {
        throw new Error('Empty or invalid argument list!');
    }

    let finalcmd = cmd.join(' ');

    if (debug) {
        // debug mode, print to console
        console.log(`Debug shutdown command: ${finalcmd}`)
        if (quitapp) {
            console.log("Now exit app...");
            app.exit(0);
        }
    } else {
        cp.exec(finalcmd, (err, stdout, stderr) => {
            if (err) {
                console.error(err);
                return;
            }
            //console.log(stdout);
            if (quitapp) {
                app.exit(0);
            }
        });
    }
}
1316977
function done() {
    // get the next route from the stack
    route = stack.pop()

    var callback
    // if the stack is not empty yet, i.e., if this is not
    // the last route part, the callback standard callback is provided
    if (stack.length) {
      callback = done
    }
    // otherwise a slightly modified callback is provided
    else {
      callback = function() {
        done.end()
      }
      callback.redirect = done.redirect
      callback.render = function() {
        res.render.apply(res, [req.app._currentRoute].concat(Array.prototype.slice.call(arguments), finalize))
      }
    }

    // exectue the route part
    route.execute(req.app, req, res, callback)
  }
1245374
function execute(args) {
    try {
        const currentOptions = options.parse(args)
        return executeOptions(currentOptions)
    } catch (error) {
        console.error(error.message)
        return 1
    }
}