Perform actions in the api from the CLI
540118
def perform_action(self, action):
        
        form = ToolForm
        s_action = form_action = action.split('_')[0]
        form_name = s_action.title() + ' tools'
        cores = False
        a_type = 'containers'
        forms = [action.upper() + 'TOOLS']
        form_args = {'color': 'CONTROL',
                     'names': [s_action],
                     'name': form_name,
                     'action_dict': {'action_name': s_action,
                                     'present_t': s_action + 'ing ' + a_type,
                                     'past_t': s_action.title() + ' ' + a_type,
                                     'action': form_action,
                                     'type': a_type,
                                     'cores': cores}}
        # grammar rules
        vowels = ['a', 'e', 'i', 'o', 'u']

        # consonant-vowel-consonant ending
        # Eg: stop -> stopping
        if s_action[-1] not in vowels and \
           s_action[-2] in vowels and \
           s_action[-3] not in vowels:
            form_args['action_dict']['present_t'] = s_action + \
                s_action[-1] + 'ing ' + a_type

        # word ends with a 'e'
        # eg: remove -> removing
        if s_action[-1] == 'e':
            form_args['action_dict']['present_t'] = s_action[:-1] \
                + 'ing ' + a_type

        if s_action == 'configure':
            form_args['names'].pop()
            form_args['names'].append('get_configure')
            form_args['names'].append('save_configure')
            form_args['names'].append('restart_tools')
        if action == 'add':
            form = AddForm
            forms = ['ADD', 'ADDOPTIONS', 'CHOOSETOOLS']
            form_args['name'] = 'Add plugins'
            form_args['name'] += '\t'*6 + '^Q to quit'
        elif action == 'inventory':
            form = InventoryToolsForm
            forms = ['INVENTORY']
            form_args = {'color': 'STANDOUT', 'name': 'Inventory of tools'}
        elif action == 'services':
            form = ServicesForm
            forms = ['SERVICES']
            form_args = {'color': 'STANDOUT',
                         'name': 'Plugin Services',
                         'core': True}
        elif action == 'services_external':
            form = ServicesForm
            forms = ['SERVICES']
            form_args = {'color': 'STANDOUT',
                         'name': 'External Services',
                         'core': True,
                         'external': True}
        form_args['name'] += '\t'*8 + '^T to toggle main'
        if s_action in self.view_togglable:
            form_args['name'] += '\t'*8 + '^V to toggle group view'
        try:
            self.remove_forms(forms)
            thr = Thread(target=self.add_form, args=(),
                         kwargs={'form': form,
                                 'form_name': forms[0],
                                 'form_args': form_args})
            thr.start()
            while thr.is_alive():
                npyscreen.notify('Please wait, loading form...',
                                 title='Loading')
                time.sleep(1)
        except Exception as e:  # pragma: no cover
            pass
        return
1034201
def run(): # pragma: no cover
    """"""
    out_file, out_format, arguments = parse()
    user, key = arguments.pop('user', None), arguments.pop('key', None)
    if not user or not key:
        sys.stderr.write('Credentials are required to perform API calls.\n')
        sys.exit(1)

    api = API(user, key, https=arguments.pop('https'), verify_ssl=arguments.pop('verify_ssl'),
              rate_limit=arguments.pop('rate_limit'))
    response = getattr(api, arguments.pop('api_call'))(**arguments)
    output = str(getattr(response, out_format) if out_format != 'list' else response.as_list())
    out_file.write(output if output.endswith('\n') else output + '\n')
926602
def execute(context)
      cmd       = context[:cmd]
      opts      = context[:opts] || {}
      args      = context[:args] || []
      cmd_args  = context[:cmd_args]
      cli_shell = context[:shell] || shell

      unless cmd.callable?
        return root['help'].call(opts, cmd_args, shell)
      end

      cmd = handle_callable_option(root, cmd)
      cmd.call(opts, args, cli_shell)

    end
543958
function Command (name, cli, action) {
  if (!(this instanceof Command)) {
    return new Command(name, cli, action)
  }
  this.name = name
  this.cli = cli
  this.action = action
}
389443
def _dispatch(self, cmd, args):
        
        if cmd in self.clis:
            extern_cmd, args = args[0], args[1:]
            self.clis[cmd]._dispatch(extern_cmd, args)
        else:
            if cmd in self.cmds:
                callback, parser = self.cmds[cmd]
                try:
                    p_args = parser.parse_args(args)
                except SystemExit:
                    return
                callback(**dict(filter(lambda p:p[1] != None, p_args._get_kwargs())))
            else:
                self._invalid_cmd(command=cmd)
562520
def execute_locally(self):
        """"""
        # Make script file #
        self.make_script()
        # Do it #
        with open(self.kwargs['out_file'], 'w') as handle:
            sh.python(self.script_path, _out=handle, _err=handle)
1299131
def _RunClientAction(self, action, request, parser_factory, path_type):
    """"""
    responses = list(action(request))

    if parser_factory is None:
      return responses

    # parse the responses
    parsed_responses = []

    for response in responses:
      for parser in parser_factory.SingleResponseParsers():
        parsed_responses.extend(
            parser.ParseResponse(self.knowledge_base, response, path_type))

      for parser in parser_factory.SingleFileParsers():
        precondition.AssertType(response, rdf_client_fs.StatEntry)
        pathspec = response.pathspec
        with vfs.VFSOpen(pathspec) as filedesc:
          parsed_responses.extend(
              parser.ParseFile(self.knowledge_base, pathspec, filedesc))

    for parser in parser_factory.MultiResponseParsers():
      parsed_responses.extend(
          parser.ParseResponses(self.knowledge_base, responses))

    for parser in parser_factory.MultiFileParsers():
      precondition.AssertIterableType(responses, rdf_client_fs.StatEntry)
      pathspecs = [response.pathspec for response in responses]
      with vfs.VFSMultiOpen(pathspecs) as filedescs:
        parsed_responses.extend(
            parser.ParseFiles(self.knowledge_base, pathspecs, filedescs))

    return parsed_responses
207954
def main(reraise_exceptions=False, **kwargs):
    """"""
    exit_status = 0

    try:
        cli.main(**kwargs)
    except SoftLayer.SoftLayerAPIError as ex:
        if 'invalid api token' in ex.faultString.lower():
            print("Authentication Failed: To update your credentials, use 'slcli config setup'")
            exit_status = 1
        else:
            print(str(ex))
            exit_status = 1
    except SoftLayer.SoftLayerError as ex:
        print(str(ex))
        exit_status = 1
    except exceptions.CLIAbort as ex:
        print(str(ex.message))
        exit_status = ex.code
    except Exception:
        if reraise_exceptions:
            raise

        import traceback
        print("An unexpected error has occured:")
        print(str(traceback.format_exc()))
        print("Feel free to report this error as it is likely a bug:")
        print("    https://github.com/softlayer/softlayer-python/issues")
        print("The following snippet should be able to reproduce the error")
        exit_status = 1

    sys.exit(exit_status)
1045187
def _push_actions(self):
        
        data = cherrypy.request.json
        with self.app.lock:
            self.app.add_actions(data['actions'], data['scheduler_instance_id'])
1034011
def action(func=None,
           cloudmap=None,
           instances=None,
           provider=None,
           instance=None,
           opts=None,
           **kwargs):
    '''
    
    '''
    info = {}
    client = _get_client()
    if isinstance(opts, dict):
        client.opts.update(opts)
    try:
        info = client.action(
            func,
            cloudmap,
            instances,
            provider,
            instance,
            salt.utils.args.clean_kwargs(**kwargs)
        )
    except SaltCloudConfigError as err:
        log.error(err)
    return info
1282914
def do_output(self, *args):
        
        if args:
            action, params = args[0], args[1:]
            log.debug("Pass %s directly to output with %s", action, params)
            function = getattr(self.output, "do_" + action, None)
            if function:
                function(*params)
120746
def run():
    """"""

    # Use print() instead of logging when running in CLI mode:
    set_pyftpsync_logger(None)

    parser = argparse.ArgumentParser(
        description="Synchronize folders over FTP.",
        epilog="See also https://github.com/mar10/pyftpsync",
        parents=[verbose_parser],
    )

    # Note: we want to allow --version to be combined with --verbose. However
    # on Py2, argparse makes sub-commands mandatory, unless `action="version"` is used.
    if check_cli_verbose(3) > 3:
        version_info = "pyftpsync/{} Python/{} {}".format(
            __version__, PYTHON_VERSION, platform.platform()
        )
    else:
        version_info = "{}".format(__version__)

    parser.add_argument("-V", "--version", action="version", version=version_info)

    subparsers = parser.add_subparsers(help="sub-command help")

    # --- Create the parser for the "upload" command ---------------------------

    sp = subparsers.add_parser(
        "upload",
        parents=[verbose_parser, common_parser, matcher_parser, creds_parser],
        help="copy new and modified files to remote folder",
    )

    sp.add_argument(
        "local",
        metavar="LOCAL",
        default=".",
        help="path to local folder (default: %(default)s)",
    )
    sp.add_argument("remote", metavar="REMOTE", help="path to remote folder")
    sp.add_argument(
        "--force",
        action="store_true",
        help="overwrite remote files, even if the target is newer "
        "(but no conflict was detected)",
    )
    sp.add_argument(
        "--resolve",
        default="ask",
        choices=["local", "skip", "ask"],
        help="conflict resolving strategy (default: '%(default)s')",
    )
    sp.add_argument(
        "--delete",
        action="store_true",
        help="remove remote files if they don't exist locally",
    )
    sp.add_argument(
        "--delete-unmatched",
        action="store_true",
        help="remove remote files if they don't exist locally "
        "or don't match the current filter (implies '--delete' option)",
    )

    sp.set_defaults(command="upload")

    # --- Create the parser for the "download" command -------------------------

    sp = subparsers.add_parser(
        "download",
        parents=[verbose_parser, common_parser, matcher_parser, creds_parser],
        help="copy new and modified files from remote folder to local target",
    )

    sp.add_argument(
        "local",
        metavar="LOCAL",
        default=".",
        help="path to local folder (default: %(default)s)",
    )
    sp.add_argument("remote", metavar="REMOTE", help="path to remote folder")
    sp.add_argument(
        "--force",
        action="store_true",
        help="overwrite local files, even if the target is newer "
        "(but no conflict was detected)",
    )
    sp.add_argument(
        "--resolve",
        default="ask",
        choices=["remote", "skip", "ask"],
        help="conflict resolving strategy (default: '%(default)s')",
    )
    sp.add_argument(
        "--delete",
        action="store_true",
        help="remove local files if they don't exist on remote target",
    )
    sp.add_argument(
        "--delete-unmatched",
        action="store_true",
        help="remove local files if they don't exist on remote target "
        "or don't match the current filter (implies '--delete' option)",
    )

    sp.set_defaults(command="download")

    # --- Create the parser for the "sync" command -----------------------------

    sp = subparsers.add_parser(
        "sync",
        parents=[verbose_parser, common_parser, matcher_parser, creds_parser],
        help="synchronize new and modified files between remote folder and local target",
    )

    sp.add_argument(
        "local",
        metavar="LOCAL",
        default=".",
        help="path to local folder (default: %(default)s)",
    )
    sp.add_argument("remote", metavar="REMOTE", help="path to remote folder")
    sp.add_argument(
        "--resolve",
        default="ask",
        choices=["old", "new", "local", "remote", "skip", "ask"],
        help="conflict resolving strategy (default: '%(default)s')",
    )

    sp.set_defaults(command="sync")

    # --- Create the parser for the "run" command -----------------------------

    add_run_parser(subparsers)

    # --- Create the parser for the "scan" command -----------------------------

    add_scan_parser(subparsers)

    # --- Parse command line ---------------------------------------------------

    args = parser.parse_args()

    args.verbose -= args.quiet
    del args.quiet

    # print("verbose", args.verbose)

    ftp_debug = 0
    if args.verbose >= 6:
        ftp_debug = 1

    # Modify the `args` from the `pyftpsync.yaml` config:
    if getattr(args, "command", None) == "run":
        handle_run_command(parser, args)

    if callable(getattr(args, "command", None)):
        # scan_handler
        try:
            return args.command(parser, args)
        except KeyboardInterrupt:
            print("\nAborted by user.", file=sys.stderr)
            sys.exit(3)

    elif not hasattr(args, "command"):
        parser.error(
            "missing command (choose from 'upload', 'download', 'run', 'sync', 'scan')"
        )

    # Post-process and check arguments
    if hasattr(args, "delete_unmatched") and args.delete_unmatched:
        args.delete = True

    args.local_target = make_target(args.local, {"ftp_debug": ftp_debug})

    if args.remote == ".":
        parser.error("'.' is expected to be the local target (not remote)")
    args.remote_target = make_target(args.remote, {"ftp_debug": ftp_debug})
    if not isinstance(args.local_target, FsTarget) and isinstance(
        args.remote_target, FsTarget
    ):
        parser.error("a file system target is expected to be local")

    # Let the command handler do its thing
    opts = namespace_to_dict(args)
    if args.command == "upload":
        s = UploadSynchronizer(args.local_target, args.remote_target, opts)
    elif args.command == "download":
        s = DownloadSynchronizer(args.local_target, args.remote_target, opts)
    elif args.command == "sync":
        s = BiDirSynchronizer(args.local_target, args.remote_target, opts)
    else:
        parser.error("unknown command '{}'".format(args.command))

    s.is_script = True

    try:
        s.run()
    except KeyboardInterrupt:
        print("\nAborted by user.", file=sys.stderr)
        sys.exit(3)
    finally:
        # Prevent sporadic exceptions in ftplib, when closing in __del__
        s.local.close()
        s.remote.close()

    stats = s.get_stats()
    if args.verbose >= 5:
        pprint(stats)
    elif args.verbose >= 1:
        if args.dry_run:
            print("(DRY-RUN) ", end="")
        print(
            "Wrote {}/{} files in {} directories, skipped: {}.".format(
                stats["files_written"],
                stats["local_files"],
                stats["local_dirs"],
                stats["conflict_files_skipped"],
            ),
            end="",
        )
        if stats["interactive_ask"]:
            print()
        else:
            print(" Elap: {}.".format(stats["elap_str"]))

    return
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();
    }
88683
def execute(options):
    """"""
    # Load the key in PKCS 12 format that you downloaded from the Google APIs
    # Console when you created your Service account.
    package_name = options['<package>']
    source_directory = options['<output_dir>']

    if options['upload'] is True:
        upstream = True
    else:
        upstream = False

    sub_tasks = {'images': options['--images'], 'listings': options['--listings'], 'inapp': options['--inapp']}
    if sub_tasks == {'images': False, 'listings': False, 'inapp': False}:
        sub_tasks = {'images': True, 'listings': True, 'inapp': True}

    credentials = create_credentials(credentials_file=options['--credentials'],
                                     service_email=options['--service-email'],
                                     service_key=options['--key'])

    command = SyncCommand(
        package_name, source_directory, upstream, credentials, **sub_tasks)
    command.execute()
408727
def make_action category, name, defopts, opts = {}
      req = Net::HTTP::Post.new(
        category.nil? ? "#{API_URI.path}/#{name}" : "#{API_URI.path}/#{category}/#{name}"
      )
      form = get_form_data(defopts, opts)
      RegApi2.form_to_be_sent(req.path, form)

      req.set_form_data(form)
      res = http.request(req)

      handle_response(defopts, res)
    end
924048
def invoke(self):
        
        args = self._get_args()
        self._action(*args)
        for callback in self._post_callbacks:
            callback()
1343931
def perform_action(
            self, action, machines, params, progress_title, success_title):
        """"""
        if len(machines) == 0:
            return 0
        with utils.Spinner() as context:
            return self._async_perform_action(
                context, action, list(machines), params,
                progress_title, success_title)