Register a function to be called after parsing user input but before running the command
481202
def register_postparsing_hook(self, func: Callable[[plugin.PostparsingData], plugin.PostparsingData]) -> None:
        """"""
        self._validate_postparsing_callable(func)
        self._postparsing_hooks.append(func)
832727
def _call_wrapper(self, time, function, *args):
        """"""
        # execute the function
        function(*args)
        if function in self._callback.keys():
            repeat = self._callback[function][1]
            if repeat:
                # setup the call back again and update the id
                callback_id = self.tk.after(time, self._call_wrapper, time, function, *args)
                self._callback[function][0] = callback_id
            else:
                # remove it from the call back dictionary
                self._callback.pop(function)
135925
def register_command(self, name, command):
        
        if name in self.commands:
            raise RuntimeError('%s is already defined' % name)
        self.commands[name] = command
714992
function(func,args){
    if(!(typeof func === 'function')){
      throw new Error('The arguments must passed and they be a function .');
    }
    var funcStr = func.toString();
    var regexpComment = /\/\*([\s\S]*?)\*\//;
    var regexpVariable = /#{([\s\S]*?)}/g;
    if(!regexpComment.test(funcStr)){
      throw new Error("Comment not found.");
    }
    var match = regexpComment.exec(funcStr);
    var str = match[1];
    if(regexpVariable.test(str) && !args){
      throw new Error('args not passed .');
    }
    return str.replace(regexpVariable, function(match, key, index, str){
      key = key.trim();
      if(!(key in args)){
        throw new Error(key + ' is not passed from arguments.', key);
        return '';
      }else{
        return args[key];
      }
    });
  }
833305
def _call_event(self, event_name, cmd, pargs, kwargs, **kws):
        
        def get_result_params(res):
            """return the right list of params"""
            if not isinstance(res, (list, tuple)):
                return res, pargs, kwargs
            elif len(res) == 2:
                return res, pargs, kwargs
            return res[0], (pargs[0], ) + tuple(res[1]), kwargs
        if hasattr(cmd, event_name):
            return get_result_params(
                getattr(cmd, event_name)(pargs[0], *pargs[1:], **kwargs))
        elif hasattr(cmd.__cls__, event_name):
            return get_result_params(
                getattr(cmd.__cls__, event_name)(
                    pargs[0], cmd.__cmd_name__ or cmd.__name__, *pargs[1:],
                    **kwargs))
        return None, pargs, kwargs
105798
def function_call_prepare_action(self, text, loc, fun):
        """"""
        exshared.setpos(loc, text)
        if DEBUG > 0:
            print("FUN_PREP:",fun)
            if DEBUG == 2: self.symtab.display()
            if DEBUG > 2: return
        index = self.symtab.lookup_symbol(fun.name, SharedData.KINDS.FUNCTION)
        if index == None:
            raise SemanticException("'%s' is not a function" % fun.name)
        #save any previous function call data (for nested function calls)
        self.function_call_stack.append(self.function_call_index)
        self.function_call_index = index
        self.function_arguments_stack.append(self.function_arguments[:])
        del self.function_arguments[:]
        self.codegen.save_used_registers()
1245906
def register_delete_command(self, delete_func):
        
        description = "Permanently delete a project."
        delete_parser = self.subparsers.add_parser('delete', description=description)
        add_project_name_or_id_arg(delete_parser, help_text_suffix="delete")
        _add_force_arg(delete_parser, "Do not prompt before deleting.")
        delete_parser.set_defaults(func=delete_func)
603887
def parse_input(command_input=None):
    """"""
    parser = argparse.ArgumentParser(
        prog='python3 ok',
        description=__doc__,
        usage='%(prog)s [--help] [options]',
        formatter_class=argparse.RawDescriptionHelpFormatter)

    testing = parser.add_argument_group('running tests')
    testing.add_argument('-q', '--question', type=str, action='append',
                        help="run tests for a specific question")
    testing.add_argument('--suite', type=str, default=None,
                        help="run cases from a specific suite")
    testing.add_argument('--case', type=str, action='append',
                        help="run specific cases")
    testing.add_argument('-u', '--unlock', action='store_true',
                        help="unlock tests interactively")
    testing.add_argument('-i', '--interactive', action='store_true',
                        help="start the Python interpreter after a failed test")
    testing.add_argument('-v', '--verbose', action='store_true',
                        help="show all tests, not just passing tests")
    testing.add_argument('-t', '--testing', nargs='?', type=str, const='mytests.rst', 
                        help='run tests from rst file (default: mytests.rst)')
    testing.add_argument('--all', action='store_true',
                        help="run tests for all questions in config file")
    testing.add_argument('--submit', action='store_true',
                        help="submit the assignment")
    testing.add_argument('--backup', action='store_true',
                        help="attempt to reliably backup your work")
    testing.add_argument('--revise', action='store_true',
                        help="submit composition revision")
    testing.add_argument('--timeout', type=int, default=10,
                        help="set the timeout duration (in seconds) for running tests")
    testing.add_argument('-cov', '--coverage', action='store_true',
                        help="get suggestions on what lines to add tests for")

    # Experiments
    experiment = parser.add_argument_group('experiment options')
    experiment.add_argument('--no-experiments', action='store_true',
                        help="do not run experimental features")
    experiment.add_argument('--hint', action='store_true',
                        help="give a hint (if available)")
    experiment.add_argument('--style', action='store_true',
                        help="run AutoStyle feedback system")
    experiment.add_argument('--collab', action='store_true',
                        help="launch collaborative programming environment")

    # Debug information
    debug = parser.add_argument_group('debugging options')
    debug.add_argument('--version', action='store_true',
                        help="print the version number and exit")
    debug.add_argument('--tests', action='store_true',
                        help="display a list of all available tests")
    debug.add_argument('--debug', action='store_true',
                        help="show debugging output")

    # Grading
    grading = parser.add_argument_group('grading options')
    grading.add_argument('--lock', action='store_true',
                        help="lock the tests in a directory")
    grading.add_argument('--score', action='store_true',
                        help="score the assignment")
    grading.add_argument('--score-out', type=str,
                        nargs='?', const=None, default=None,
                        help="write scores to a file")
    grading.add_argument('--config', type=str,
                        help="use a specific configuration file")

    # Server parameters
    server = parser.add_argument_group('server options')
    server.add_argument('--local', action='store_true',
                        help="disable any network activity")
    server.add_argument('--server', type=str,
                        default='okpy.org',
                        help="set the server address")
    server.add_argument('--authenticate', action='store_true',
                        help="authenticate, ignoring previous authentication")
    server.add_argument('--no-browser', action='store_true',
                        help="do not use a web browser for authentication")
    server.add_argument('--get-token', action='store_true',
                        help="get ok access token")
    server.add_argument('--insecure', action='store_true',
                        help="use http instead of https")
    server.add_argument('--no-update', action='store_true',
                        help="do not check for ok updates")
    server.add_argument('--update', action='store_true',
                        help="update ok and exit")

    return parser.parse_args(command_input)
1059234
def register_function(self, patterns, instances=None, **reg_kwargs):
        """"""

        def wrapper(function):
            self.register(patterns, function, instances=instances, **reg_kwargs)
            return function

        return wrapper
388603
def register(self, f, *args, **kwargs):
        
        self._functions.append(lambda: f(*args, **kwargs))
971104
def post_run_hook(self, func, prefix=None):
        
        cf = self.capture(func, prefix=prefix)
        self.post_run_hooks.append(cf)
        return cf
387066
def run_triggers(step, pre_post, args=(), **kwargs):
    '''
    
    '''
    if not isinstance(step, str) or not isinstance(pre_post, str):
        return
    if trace_triggers:
        msg = 'Trigger for %s: %s' % (step, pre_post)
        sys.stderr.write(msg.center(80, '-') + '\n')
    if args is None:
        args = ()
    if not isinstance(args, tuple):
        return
    cfg = __get_config()
    if cfg is None:
        return
    if step not in cfg:
        return
    if not isinstance(cfg[step], dict):
        return
    if pre_post not in cfg[step]:
        return
    d = cfg[step][pre_post]
    l = d.get('cmdlist', [])
    if not l:
        return

    show_output = d.get('show_output', None)
    show_err = d.get('show_err', None)
    ignore_err = d.get('ignore_err', None)

    run_in_order(
        l,
        show_output=show_output,
        show_err=show_err,
        ignore_err=ignore_err,
        args=args,
        pre_post=pre_post,
        kwargs=kwargs
    )
337014
def command(self, init=False):
        """"""

        def wrapper(func):
            header = '\n'.join([s for s in (func.__doc__ or '').split('\n')
                                if not s.strip().startswith(':')])
            parser = self.parsers.add_parser(func.__name__, description=header)
            args, vargs, kw, defs, kwargs, kwdefs, anns = inspect.getfullargspec(func)
            defs = defs or []
            kwargs_ = dict(zip(args[-len(defs):], defs))
            docs = dict(PARAM_RE.findall(func.__doc__ or ""))

            def process_arg(name, *, value=..., **opts):
                argname = name.replace('_', '-').lower()
                arghelp = docs.get(vargs, '')
                if value is ...:
                    return parser.add_argument(argname, help=arghelp, **opts)

                if isinstance(value, bool):
                    if value:
                        return parser.add_argument(
                            "--no-" + argname, dest=name, action="store_false",
                            help="Disable %s" % (arghelp or name).lower())

                    return parser.add_argument(
                        "--" + argname, dest=name, action="store_true",
                        help="Enable %s" % (arghelp or name).lower())

                if isinstance(value, list):
                    return parser.add_argument(
                        "--" + argname, action="append", default=value, help=arghelp)

                return parser.add_argument(
                    "--" + argname, type=anns.get(name, type(value)),
                    default=value, help=arghelp + ' [%s]' % repr(value))

            if vargs:
                process_arg('*', nargs="*", metavar=vargs)

            for name, value in (kwdefs or {}).items():
                process_arg(name, value=value)

            for name in args:
                process_arg(name, value=kwargs_.get(name, ...))

            self.handlers[func.__name__] = func
            func.parser = parser
            return func

        if callable(init):
            init.__init__ = True
            return wrapper(init)

        def decorator(func):
            func.__init__ = bool(init)
            return wrapper(func)

        return decorator
761298
def pre_run_hook(self, func, prefix=None):
        
        cf = self.capture(func, prefix=prefix)
        self.pre_run_hooks.append(cf)
        return cf
648203
def bind(self, fn):
        '''
        '''
        @Parser
        def bind_parser(text, index):
            res = self(text, index)
            return res if not res.status else fn(res.value)(text, res.index)
        return bind_parser
501776
function initializeCommands() {
        var prefs = getPreferences();

        CommandManager.register(Strings.CMD_FILE_CLOSE_BELOW, closeBelow, function () {
            handleClose(closeBelow);
        });
        CommandManager.register(Strings.CMD_FILE_CLOSE_OTHERS, closeOthers, function () {
            handleClose(closeOthers);
        });
        CommandManager.register(Strings.CMD_FILE_CLOSE_ABOVE, closeAbove, function () {
            handleClose(closeAbove);
        });

        if (prefs.closeBelow) {
            workingSetListCmenu.addMenuItem(closeBelow, "", Menus.AFTER, Commands.FILE_CLOSE);
        }
        if (prefs.closeOthers) {
            workingSetListCmenu.addMenuItem(closeOthers, "", Menus.AFTER, Commands.FILE_CLOSE);
        }
        if (prefs.closeAbove) {
            workingSetListCmenu.addMenuItem(closeAbove, "", Menus.AFTER, Commands.FILE_CLOSE);
        }
        menuEntriesShown = prefs;
    }
645575
def add_command(self, command, function, description=None):
        

        self.registered[command] = {
            'function': function, 'description': description
        }