Parse func's function source code as Python and Markdown cells.
        :param func: Python function to parse
        :param kwargs: variables to inject as first Python cell
        :return:
964651
def add(self, func, **kwargs):
        

        params = set(kwargs.keys())
        func_params = set(inspect.getargspec(func).args)

        # ignore self, which is present when extending Notebook.
        if 'self' in func_params:
            func_params.remove('self')

        if params != func_params:
            fatal('Params {} not matching cells function params {}'.format(list(params), list(func_params)))

        lines = inspect.getsourcelines(func)[0][1:]

        buffer = ""
        indent_count = None
        inside_markdown = False
        return_found = False

        for line in lines:

            # remove base indentation of function 'func'
            if len(line.strip()) > 0:
                if not indent_count:
                    indent_count = 0
                    for c in line:
                        if c not in [' ', '\t']:
                            break
                        else:
                            indent_count += 1
                line = line[indent_count:]

            if not inside_markdown and line.strip() == "return":
                logging.info('Encountered "return" statement, ignoring the rest of the notebook.')
                break

            if line.strip() == "'''":  # if md block begin/end, or new cell...
                if len(buffer.strip()) > 0:
                    if not inside_markdown:  # if md block begin: new markdown block! flush buffer
                        self.add_cell_code(buffer)
                    else:  # if md block end: markdown block completed! flush buffer
                        self.add_cell_markdown(buffer)
                buffer = ""
                inside_markdown = not inside_markdown
            else:
                buffer += line

        if len(buffer.strip()) > 0:
            if not inside_markdown:
                self.add_cell_code(buffer)
            else:
                self.add_cell_markdown(buffer)

        if len(kwargs) > 0:
            # We have parameters to inject into the notebook.
            # If the first cell is Markdown, assume that is the title and
            # insert parameters as 2nd cell. Otherwise, as 1st cell.
            if len(self.nb['cells']) > 0 and self.nb['cells'][0].cell_type == 'markdown':
                self.add_cell_params(kwargs, 1)
            else:
                self.add_cell_params(kwargs, 0)
1326550
def label_from_func(self, func:Callable, label_cls:Callable=None, **kwargs)->'LabelList':
        ""
        return self._label_from_list([func(o) for o in self.items], label_cls=label_cls, **kwargs)
1066429
def _inject_func(func, conn):
    
    name = func.__name__
    if not name in conn.namespace:
        if isbuiltin(func):
            inject_code = '%s = %s' % (name, name)
        elif isfunction(func):
            inject_code = getsource(func)
        conn.execute(inject_code)
    return conn.namespace[name]
1191712
def arg(*args, **kwargs):
    
    def decorate(func):
        """
        Decorate
        """
        # we'll set the command name with the passed cmd_name argument, if
        # exist, else the command name will be the function name
        func.__cmd_name__ = kwargs.pop(
            'cmd_name', getattr(func, '__cmd_name__', func.__name__))
        # retrieve the class (SillyClass)
        func.__cls__ = utils.check_class()
        if not hasattr(func, '__arguments__'):
            # if the funcion hasn't the __arguments__ yet, we'll setup them
            # using get_functarguments.
            func.__arguments__ = utils.get_functarguments(func)
        if len(args) or len(kwargs):
            # if we have some argument or keyword argument
            # we'll try to get the destination name from the kwargs ('dest')
            # else we'll use the last arg name as destination
            arg_name = kwargs.get(
                'dest', args[-1].lstrip('-').replace('-', '_'))
            try:
                # we try to get the command index.
                idx = func.__named__.index(arg_name)
                # and delete it from the named list
                del func.__named__[idx]
                # and delete it from the arguments list
                del func.__arguments__[idx]
            except ValueError:
                pass
            # append the args and kwargs to the function arguments list
            func.__arguments__.append((args, kwargs,))
        if func.__cls__ is None and isinstance(func, types.FunctionType):
            # if the function don't have a class and is a FunctionType
            # we'll add it directly to he commands list.
            ap_ = ArgParseInator(skip_init=True)
            if func.__cmd_name__ not in ap_.commands:
                # we'll add it if not exists
                ap_.commands[func.__cmd_name__] = func
        return func
    return decorate
844293
def split_kwargs_by_func(kwargs, func):
    ""
    args = func_args(func)
    func_kwargs = {a:kwargs.pop(a) for a in args if a in kwargs}
    return func_kwargs, kwargs
503472
def get_kwarg_names(func):
    
    sig = inspect.signature(func)
    kwonlyargs = [p.name for p in sig.parameters.values()
                  if p.default is not p.empty]
    return kwonlyargs
439338
def get_valid_kwargs(func, potential_kwargs):
    
    kwargs = {}
    for name in get_kwarg_names(func):
        with suppress(KeyError):
            kwargs[name] = potential_kwargs[name]
    return kwargs
617056
def parse_all_arguments(func):
    
    args = dict()
    if sys.version_info < (3, 0):
        func_args = inspect.getargspec(func)
        if func_args.defaults is not None:
            val = len(func_args.defaults)
            for i, itm in enumerate(func_args.args[-val:]):
                args[itm] = func_args.defaults[i]
    else:
        func_args = inspect.signature(func)
        for itm in list(func_args.parameters)[1:]:
            param = func_args.parameters[itm]
            if param.default is not param.empty:
                args[param.name] = param.default
    return args
1172661
def wrap_function(func):
    
    if is_text(func):
        return compile_expression(func)

    numarg = func.__code__.co_argcount
    if numarg == 0:

        def temp(row, rownum, rows):
            return func()

        return temp
    elif numarg == 1:

        def temp(row, rownum, rows):
            return func(row)

        return temp
    elif numarg == 2:

        def temp(row, rownum, rows):
            return func(row, rownum)

        return temp
    elif numarg == 3:
        return func
1171265
def indent(func):
    
    def wrapper(self, *args, **kwds):
        func(self, *args, **kwds)
        return Indent(self)
    return wrapper
1240031
def compile_func(arg_names, statements, name='_the_func', debug=False):
    
    func_def = ast.FunctionDef(
        name=name,
        args=ast.arguments(
            args=[ast.arg(arg=n, annotation=None) for n in arg_names],
            kwonlyargs=[],
            kw_defaults=[],
            defaults=[ex_literal(None) for _ in arg_names],
        ),
        body=statements,
        decorator_list=[],
    )

    mod = ast.Module([func_def])
    ast.fix_missing_locations(mod)

    prog = compile(mod, '<generated>', 'exec')

    # Debug: show bytecode.
    if debug:
        dis.dis(prog)
        for const in prog.co_consts:
            if isinstance(const, types.CodeType):
                dis.dis(const)

    the_locals = {}
    exec(prog, {}, the_locals)
    return the_locals[name]
427996
def get_parser(func, parent):
    
    parser = parent.add_parser(func.__cmd_name__, help=func.__doc__)
    for args, kwargs in func.__arguments__:
        parser.add_argument(*args, **kwargs)
    return parser
256452
def deprecated(message=""):
    
    def decorator_wrapper(func):
        """
        Generate decorator wrapper function
        :param func: function to be decorated
        :return: wrapper
        """
        @functools.wraps(func)
        def function_wrapper(*args, **kwargs):
            """
            Wrapper which recognize deprecated line from source code
            :param args: args for actual function
            :param kwargs: kwargs for actual functions
            :return: something that actual function might returns
            """
            current_call_source = '|'.join(traceback.format_stack(inspect.currentframe()))
            if current_call_source not in function_wrapper.last_call_source:
                warnings.warn("Function {} is now deprecated! {}".format(func.__name__, message),
                              category=DeprecationWarning, stacklevel=2)
                function_wrapper.last_call_source.add(current_call_source)

            return func(*args, **kwargs)

        function_wrapper.last_call_source = set()

        return function_wrapper
    return decorator_wrapper
525861
def absorb_args(self, func):
        
        @wraps(func)
        def wrapper(*args, **kwargs):
            return func()
        return wrapper
883769
def handle_keywords(self, func, node, offset=0):
        '''
        
        '''
        func_argument_names = {}
        for i, arg in enumerate(func.args.args[offset:]):
            assert isinstance(arg, ast.Name)
            func_argument_names[arg.id] = i

        nargs = len(func.args.args) - offset
        defaults = func.args.defaults
        keywords = {func_argument_names[kw.arg]: kw.value
                    for kw in node.keywords}
        node.args.extend([None] * (1 + max(keywords.keys()) - len(node.args)))

        replacements = {}
        for index, arg in enumerate(node.args):
            if arg is None:
                if index in keywords:
                    replacements[index] = deepcopy(keywords[index])
                else:  # must be a default value
                    replacements[index] = deepcopy(defaults[index - nargs])
        return replacements
597649
def _correct_args(func, kwargs):
    
    args = inspect.getargspec(func)[0]
    return [kwargs[arg] for arg in args] + kwargs['__args']
348633
def decorator(self, func):
        
        if inspect.isfunction(func):
            func._methodview = self
        elif inspect.ismethod(func):
            func.__func__._methodview = self
        else:
            raise AssertionError('Can only decorate function and methods, {} given'.format(func))
        return func