handle command and check business rules
188024
function (aggregate, streams, clb) {
        debug('handle command');
        self.letHandleCommandByAggregate(aggregate, cmd, function (err) { // err is a business rule error
          if (err) {
            return clb(err);
          }
          clb(null, aggregate, streams);
        });
      }
521667
def handle(self, *args, **options):
        """"""
        verbosity = int(options.get('verbosity'))

        # Check that the specified output format is valid
        if options['format'] != 'plain' and options['format'] != 'yaml':
            raise CommandError("Unknown output format: %s" % options['format'])

        # Gather only unique latest custom Docker requirements that the processes are using
        # The 'image' field is optional, so be careful about that as well
        unique_docker_images = set(
            p.requirements['executor']['docker']['image']
            for p in Process.objects.filter(is_active=True).order_by(
                'slug', '-version'
            ).distinct(
                'slug'
            ).only(
                'requirements'
            ).filter(
                requirements__icontains='docker'
            )
            if 'image' in p.requirements.get('executor', {}).get('docker', {})
        )

        # Add the default image.
        unique_docker_images.add(DEFAULT_CONTAINER_IMAGE)

        # Pull images if requested or just output the list in specified format
        if options['pull']:
            # Remove set of already pulled images.
            with PULLED_IMAGES_LOCK:
                unique_docker_images.difference_update(PULLED_IMAGES)

            # Get the desired 'docker' command from settings or use the default
            docker = getattr(settings, 'FLOW_DOCKER_COMMAND', 'docker')

            # Pull each image
            for img in unique_docker_images:
                ret = subprocess.call(
                    shlex.split('{} pull {}'.format(docker, img)),
                    stdout=None if verbosity > 0 else subprocess.DEVNULL,
                    stderr=None if verbosity > 0 else subprocess.DEVNULL,
                )

                # Update set of pulled images.
                with PULLED_IMAGES_LOCK:
                    PULLED_IMAGES.add(img)

                if ret != 0:
                    errmsg = "Failed to pull Docker image '{}'!".format(img)

                    if not options['ignore_pull_errors']:
                        # Print error and stop execution
                        raise CommandError(errmsg)
                    else:
                        # Print error, but keep going
                        logger.error(errmsg)
                        if verbosity > 0:
                            self.stderr.write(errmsg)
                else:
                    msg = "Docker image '{}' pulled successfully!".format(img)
                    logger.info(msg)
                    if verbosity > 0:
                        self.stdout.write(msg)
        else:
            # Sort the set of unique Docker images for nicer output.
            unique_docker_images = sorted(unique_docker_images)

            # Convert the set of unique Docker images into a list of dicts for easier output
            imgs = [
                dict(name=s[0], tag=s[1] if len(s) == 2 else 'latest')
                for s in (img.split(':') for img in unique_docker_images)
            ]

            # Output in YAML or plaintext (one image per line), as requested
            if options['format'] == 'yaml':
                out = yaml.safe_dump(imgs, default_flow_style=True, default_style="'")
            else:
                out = functools.reduce(operator.add,
                                       ('{name}:{tag}\n'.format(**i) for i in imgs), '')

            self.stdout.write(out, ending='')
827984
function execCmd(cmd, allowedErrors = []) {
  debug(`About to execute cmd: ${cmd} with allowed errors: ${JSON.stringify(allowedErrors)}`);
  return exec(cmd, {})
    .then((result) => {
      debug(`Executed successfully cmd: ${cmd}: `, result.stdout);
      const { stdout } = result;
      return stdout;
    })
    .catch((error) => {
      debug(`Executed with error cmd: ${cmd}: `, error.stdout, error.stderr);
      if (allowedErrors.some(allowedError => allowedError.test(error.stderr))) {
        return Promise.resolve(error.stderr);
      }
      return Promise.reject(error);
    });
}
924552
def exec_cmd(self, command, **kwargs):
        """"""
        self._is_allowed_command(command)
        self._check_command_parameters(**kwargs)

        if command == 'load':
            kwargs['command'] = command
            self._check_exclusive_parameters(**kwargs)
            requests_params = self._handle_requests_params(kwargs)
            session = self._meta_data['bigip']._meta_data['icr_session']
            try:

                session.post(
                    self._meta_data['uri'], json=kwargs, **requests_params)

            except HTTPError as err:
                if err.response.status_code != 502:
                    raise
                return

        else:
            return self._exec_cmd(command, **kwargs)
1112306
function command(req, res) {

  this.stats.commands++;

  //console.dir(this);

  // guaranteed to have a string command by connection
  var cmd = req.cmd
    // guaranteed to have an arguments array by connection
    , args = req.args

    // select implementation should guarantee a valid db index
    // on the connection
    , db = this.store.getDatabase(req.conn.db)
    // info object used by the validate function
    , exec = this.execs[cmd]
    , info = {
      db: db, conf: this.conf, conn: req.conn, exec: exec, commands: this.execs}
    // should we queue this command in a transaction
    // of just execute it
    , queue = cmd !== DISCARD && cmd !== EXEC
    // flag if command is acceptable when busy
    , acceptable;

  // raw arguments list, before validation
  // used so that the slowlog does not show modified arguments
  req.raw = args.slice(0);

  //console.error('server processing command: %s', cmd);
  //console.error('server processing command: %j', args);
    //

  if(ScriptManager.busy && !req.script) {
    // compare on command instances
    // in case they have been renamed
    acceptable =
      (exec === Shutdown
       && ('' + args[0] || '').toLowerCase() === NOSAVE)
      || (exec === Script
        && ('' + args[0] || '').toLowerCase() === KILL);
    if(!acceptable) return res.send(StoreError.Busy);
  }

  if(exec === false) {
    return res.send(StoreError.UnknownDisabled);
  }else if(!exec) {
    return res.send(new UnknownCommand(cmd));
  }

  try {
    exec.validate.call(this, cmd, args, info);

    // inject references
    req.db = db;
    req.conf = this.conf;
    req.exec = exec;

    // these properties are available on the req
    delete info.db;
    delete info.conn;
    delete info.conf;

    // inject the info object which is decorated with
    // additional useful information on validation
    req.info = info;

    // alias the command definition
    req.def = req.exec.definition;
  }catch(e) {
    // let the transaction decide how to proceed on error
    if(req.conn.transaction) {
      return req.conn.transaction.add(e, req, res);
    }
    return res.send(e);
  }

  if(req.conn.transaction && queue) {
    return req.conn.transaction.add(null, req, res);
  }

  this.execute(exec, req, res);

}
305575
async def handle_command(bot: NoneBot, ctx: Context_T) -> bool:
    
    cmd, current_arg = parse_command(bot, str(ctx['message']).lstrip())
    is_privileged_cmd = cmd and cmd.privileged
    if is_privileged_cmd and cmd.only_to_me and not ctx['to_me']:
        is_privileged_cmd = False
    disable_interaction = is_privileged_cmd

    if is_privileged_cmd:
        logger.debug(f'Command {cmd.name} is a privileged command')

    ctx_id = context_id(ctx)

    if not is_privileged_cmd:
        # wait for 1.5 seconds (at most) if the current session is running
        retry = 5
        while retry > 0 and \
                _sessions.get(ctx_id) and _sessions[ctx_id].running:
            retry -= 1
            await asyncio.sleep(0.3)

    check_perm = True
    session = _sessions.get(ctx_id) if not is_privileged_cmd else None
    if session:
        if session.running:
            logger.warning(f'There is a session of command '
                           f'{session.cmd.name} running, notify the user')
            asyncio.ensure_future(send(
                bot, ctx,
                render_expression(bot.config.SESSION_RUNNING_EXPRESSION)
            ))
            # pretend we are successful, so that NLP won't handle it
            return True

        if session.is_valid:
            logger.debug(f'Session of command {session.cmd.name} exists')
            # since it's in a session, the user must be talking to me
            ctx['to_me'] = True
            session.refresh(ctx, current_arg=str(ctx['message']))
            # there is no need to check permission for existing session
            check_perm = False
        else:
            # the session is expired, remove it
            logger.debug(f'Session of command {session.cmd.name} is expired')
            if ctx_id in _sessions:
                del _sessions[ctx_id]
            session = None

    if not session:
        if not cmd:
            logger.debug('Not a known command, ignored')
            return False
        if cmd.only_to_me and not ctx['to_me']:
            logger.debug('Not to me, ignored')
            return False
        session = CommandSession(bot, ctx, cmd, current_arg=current_arg)
        logger.debug(f'New session of command {session.cmd.name} created')

    return await _real_run_command(session, ctx_id, check_perm=check_perm,
                                   disable_interaction=disable_interaction)
232363
def act(self, cmd_name, param):
        
        command = getattr(self, cmd_name)
        if param:
            command(param)
        else:
            command()
440411
def handle(self, *args, **options):
        do_run = options["run"]

        if do_run:
            if not options["confirm"]:
                self.ask("===== WARNING! =====\n\n"
                         "This script will DESTROY data! Ensure that you have a properly backed-up copy of your database before proceeding.\n\n"
                         "===== WARNING! =====\n\n"
                         "Continue?")
        else:
            self.stdout.write("In pretend mode.")

        current_year = timezone.now().year
        new_senior_year = current_year + 1
        turnover_date = datetime.datetime(current_year, 7, 1)
        self.stdout.write("Turnover date set to: {}".format(turnover_date.strftime("%c")))

        if not self.chk("SENIOR_GRADUATION_YEAR = {} in settings/__init__.py".format(new_senior_year),
                        settings.SENIOR_GRADUATION_YEAR == new_senior_year):
            return
        

        self.stdout.write("Resolving absences")
        if do_run:
            self.clear_absences()

        self.stdout.write("Updating welcome state")
        if do_run:
            self.update_welcome()

        self.stdout.write("Deleting graduated users")
        if do_run:
            self.handle_delete()

        self.stdout.write("Archiving admin comments")
        if do_run:
            self.archive_admin_comments()
546180
def process_rules(self, path: Path, system: System):
        """"""
        self.context.update({
            'system': system,
        })
        document = FileSystem.load_yaml(path, required=True)
        for module, rules in document.items():
            click.secho('process: {0}'.format(module), fg='green')
            self._process_rules(rules, system)
306251
def check_command(args):
    """"""
    outdated = check_requirements_file(args.requirements_file,
                                       args.skip_packages)

    if outdated:
        print('Requirements in {} are out of date:'.format(
            args.requirements_file))

        for item in outdated:
            print(' * {} is {} latest is {}.'.format(*item))

        sys.exit(1)
    else:
        print('Requirements in {} are up to date.'.format(
            args.requirements_file))
940569
def execute(self, command):
        """"""
        pData = c_char_p(command)
        cbData = DWORD(len(command) + 1)
        hDdeData = DDE.ClientTransaction(pData, cbData, self._hConv, HSZ(), CF_TEXT, XTYP_EXECUTE, TIMEOUT_ASYNC, LPDWORD())
        if not hDdeData:
            raise DDEError("Unable to send command", self._idInst)
        DDE.FreeDataHandle(hDdeData)
13744
def check(self, records):
        """"""
        for value, target in records:
            LOGGER.info("%s [%s]: %s", self.name, target, value)
            if value is None:
                self.notify(self.no_data, value, target)
                continue
            for rule in self.rules:
                if self.evaluate_rule(rule, value, target):
                    self.notify(rule['level'], value, target, rule=rule)
                    break
            else:
                self.notify('normal', value, target, rule=rule)

            self.history[target].append(value)
244205
function actions()
    {
        $error = $this->start();

        // Handle user requests
        if ($action = rcube_utils::get_input_value('_act', rcube_utils::INPUT_GPC)) {
            $fid = (int) rcube_utils::get_input_value('_fid', rcube_utils::INPUT_POST);

            if ($action == 'delete' && !$error) {
                if (isset($this->script[$fid])) {
                    if ($this->sieve->script->delete_rule($fid))
                        $result = $this->save_script();

                    if ($result === true) {
                        $this->rc->output->show_message('managesieve.filterdeleted', 'confirmation');
                        $this->rc->output->command('managesieve_updatelist', 'del', array('id' => $fid));
                    }
                    else {
                        $this->rc->output->show_message('managesieve.filterdeleteerror', 'error');
                    }
                }
            }
            else if ($action == 'move' && !$error) {
                if (isset($this->script[$fid])) {
                    $to   = (int) rcube_utils::get_input_value('_to', rcube_utils::INPUT_POST);
                    $rule = $this->script[$fid];

                    // remove rule
                    unset($this->script[$fid]);
                    $this->script = array_values($this->script);

                    // add at target position
                    if ($to >= count($this->script)) {
                        $this->script[] = $rule;
                    }
                    else {
                        $script = array();
                        foreach ($this->script as $idx => $r) {
                            if ($idx == $to)
                                $script[] = $rule;
                            $script[] = $r;
                        }
                        $this->script = $script;
                    }

                    $this->sieve->script->content = $this->script;
                    $result = $this->save_script();

                    if ($result === true) {
                        $result = $this->list_rules();

                        $this->rc->output->show_message('managesieve.moved', 'confirmation');
                        $this->rc->output->command('managesieve_updatelist', 'list',
                            array('list' => $result, 'clear' => true, 'set' => $to));
                    }
                    else {
                        $this->rc->output->show_message('managesieve.moveerror', 'error');
                    }
                }
            }
            else if ($action == 'act' && !$error) {
                if (isset($this->script[$fid])) {
                    $rule     = $this->script[$fid];
                    $disabled = !empty($rule['disabled']);
                    $rule['disabled'] = !$disabled;
                    $result = $this->sieve->script->update_rule($fid, $rule);

                    if ($result !== false)
                        $result = $this->save_script();

                    if ($result === true) {
                        if ($rule['disabled'])
                            $this->rc->output->show_message('managesieve.deactivated', 'confirmation');
                        else
                            $this->rc->output->show_message('managesieve.activated', 'confirmation');
                        $this->rc->output->command('managesieve_updatelist', 'update',
                            array('id' => $fid, 'disabled' => $rule['disabled']));
                    }
                    else {
                        if ($rule['disabled'])
                            $this->rc->output->show_message('managesieve.deactivateerror', 'error');
                        else
                            $this->rc->output->show_message('managesieve.activateerror', 'error');
                    }
                }
            }
            else if ($action == 'setact' && !$error) {
                $script_name = rcube_utils::get_input_value('_set', rcube_utils::INPUT_POST, true);
                $result = $this->activate_script($script_name);
                $kep14  = $this->rc->config->get('managesieve_kolab_master');

                if ($result === true) {
                    $this->rc->output->set_env('active_sets', $this->active);
                    $this->rc->output->show_message('managesieve.setactivated', 'confirmation');
                    $this->rc->output->command('managesieve_updatelist', 'setact',
                        array('name' => $script_name, 'active' => true, 'all' => !$kep14));
                }
                else {
                    $this->rc->output->show_message('managesieve.setactivateerror', 'error');
                }
            }
            else if ($action == 'deact' && !$error) {
                $script_name = rcube_utils::get_input_value('_set', rcube_utils::INPUT_POST, true);
                $result = $this->deactivate_script($script_name);

                if ($result === true) {
                    $this->rc->output->set_env('active_sets', $this->active);
                    $this->rc->output->show_message('managesieve.setdeactivated', 'confirmation');
                    $this->rc->output->command('managesieve_updatelist', 'setact',
                        array('name' => $script_name, 'active' => false));
                }
                else {
                    $this->rc->output->show_message('managesieve.setdeactivateerror', 'error');
                }
            }
            else if ($action == 'setdel' && !$error) {
                $script_name = rcube_utils::get_input_value('_set', rcube_utils::INPUT_POST, true);
                $result = $this->remove_script($script_name);

                if ($result === true) {
                    $this->rc->output->show_message('managesieve.setdeleted', 'confirmation');
                    $this->rc->output->command('managesieve_updatelist', 'setdel',
                        array('name' => $script_name));
                    $this->rc->session->remove('managesieve_current');
                }
                else {
                    $this->rc->output->show_message('managesieve.setdeleteerror', 'error');
                }
            }
            else if ($action == 'setget') {
                $this->rc->request_security_check(rcube_utils::INPUT_GET);

                $script_name = rcube_utils::get_input_value('_set', rcube_utils::INPUT_GPC, true);
                $script      = $this->sieve->get_script($script_name);

                if ($script === false) {
                    exit;
                }

                $browser = new rcube_browser;

                // send download headers
                header("Content-Type: application/octet-stream");
                header("Content-Length: ".strlen($script));

                if ($browser->ie) {
                    header("Content-Type: application/force-download");
                    $filename = rawurlencode($script_name);
                }
                else {
                    $filename = addcslashes($script_name, '\\"');
                }

                header("Content-Disposition: attachment; filename=\"$filename.txt\"");
                echo $script;
                exit;
            }
            else if ($action == 'list') {
                $result = $this->list_rules();

                $this->rc->output->command('managesieve_updatelist', 'list', array('list' => $result));
            }
            else if ($action == 'ruleadd') {
                $rid = rcube_utils::get_input_value('_rid', rcube_utils::INPUT_POST);
                $id = $this->genid();
                $content = $this->rule_div($fid, $id, false);

                $this->rc->output->command('managesieve_rulefill', $content, $id, $rid);
            }
            else if ($action == 'actionadd') {
                $aid = rcube_utils::get_input_value('_aid', rcube_utils::INPUT_POST);
                $id = $this->genid();
                $content = $this->action_div($fid, $id, false);

                $this->rc->output->command('managesieve_actionfill', $content, $id, $aid);
            }
            else if ($action == 'addresses') {
                $aid = rcube_utils::get_input_value('_aid', rcube_utils::INPUT_POST);

                $this->rc->output->command('managesieve_vacation_addresses_update', $aid, $this->user_emails());
            }

            $this->rc->output->send();
        }
        else if ($this->rc->task == 'mail') {
            // Initialize the form
            $rules = rcube_utils::get_input_value('r', rcube_utils::INPUT_GET);
            if (!empty($rules)) {
                $tests = array();
                foreach ($rules as $rule) {
                    list($header, $value) = explode(':', $rule, 2);
                    $tests[] = array(
                        'type' => 'contains',
                        'test' => 'header',
                        'arg1' => $header,
                        'arg2' => $value,
                    );
                }

                $this->form = array(
                    'join'  => count($tests) > 1 ? 'allof' : 'anyof',
                    'name'  => '',
                    'tests' => $tests,
                    'actions' => array(
                        0 => array('type' => 'fileinto'),
                        1 => array('type' => 'stop'),
                    ),
                );
            }
        }

        $this->send();
    }
946717
def check_command(self, command):
        

        # Use `command` to see if command is callable, store exit code
        code = os.system("command -v {0} >/dev/null 2>&1 || {{ exit 1; }}".format(command))

        # If exit code is not 0, report which command failed and return False, else return True
        if code != 0:
            print("Command is not callable: {0}".format(command))
            return False
        else:
            return True
677657
function validate(cmd, args, info) {
  AbstractCommand.prototype.validate.apply(this, arguments);
  if(!info.conn.transaction) {
    throw DiscardWithoutMulti;
  }
}
1078514
def handle_cmd_options():
    '''
    
    '''
    parser = OptionParser()
    parser.add_option("-s", "--silent", action="store_true", dest="silent",
                      help="print any warnings", default=False)
    (options, args) = parser.parse_args()
    return options, args
319862
def _handle_command_buffer(self):
        """"""
        if self._should_write_to_command_buffer:
            self._write_to_command_buffer(self._commands.to_json())
            self._should_write_to_command_buffer = False
            self._commands.clear()