Decorator to mark a function as columns formatter.
325238
def columns_formatter(cls, colname):
        """"""
        def wrapper(func):
            cls.columns_formatters[colname] = func
            return func
        return wrapper
637506
def representation_function_compiler(self, func_name):
        """"""

        def get_col_accessor(col):
            return ALCHEMY_TEMPLATES.col_accessor.safe_substitute(col=col)

        def get_col_evaluator(col):
            return ALCHEMY_TEMPLATES.col_evaluator.safe_substitute(col=col)

        col_evaluators = ", ".join([get_col_evaluator(n) for n in self.primary_keys])
        col_accessors = ", ".join([get_col_accessor(n) for n in self.primary_keys])

        return ALCHEMY_TEMPLATES.representor_function.safe_substitute(func_name=func_name,
                                                                      col_accessors=col_accessors,
                                                                      col_evaluators=col_evaluators,
                                                                      class_name=self.class_name)
427843
def format_doc(fun):
    """"""
    SEPARATOR = '============================='
    func = cvloop.functions.__dict__[fun]

    doc_lines = ['{}'.format(l).strip() for l in func.__doc__.split('\n')]
    if hasattr(func, '__init__'):
        doc_lines.append(SEPARATOR)
        doc_lines += ['{}'.format(l).strip() for l in
                      func.__init__.__doc__.split('\n')]

    mod_lines = []
    argblock = False
    returnblock = False
    for line in doc_lines:
        if line == SEPARATOR:
            mod_lines.append('\n#### `{}.__init__(...)`:\n\n'.format(fun))
        elif 'Args:' in line:
            argblock = True
            if GENERATE_ARGS:
                mod_lines.append('**{}**\n'.format(line))
        elif 'Returns:' in line:
            returnblock = True
            mod_lines.append('\n**{}**'.format(line))
        elif not argblock and not returnblock:
            mod_lines.append('{}\n'.format(line))
        elif argblock and not returnblock and ':' in line:
            if GENERATE_ARGS:
                mod_lines.append('- *{}:* {}\n'.format(
                    *line.split(':')))
        elif returnblock:
            mod_lines.append(line)
        else:
            mod_lines.append('{}\n'.format(line))
    return mod_lines
1062869
def annotate_mapper(**decargs):
    """"""
    def decorator(func):
        """Annotate events with entry and/or exit timestamps."""
        def wrapper(event, *args, **kwargs):
            """Add enter and exit annotations to the processed event."""
            funcname = ":".join([func.__module__, func.__name__])
            enter_ts = time.time()
            out = func(event, *args, **kwargs)
            enter_key = funcname + "|enter"
            out = annotate_event(out, enter_key, ts=enter_ts, **decargs)
            exit_key = funcname + "|exit"
            out = annotate_event(out, exit_key, ts=time.time(), **decargs)
            return out

        return wrapper
    return decorator
583716
def table_formatter(self, dataframe, inc_header=1, inc_index=1):
        """"""
        return TableFormatter(dataframe, inc_header=inc_header, inc_index=inc_index)
1171265
def indent(func):
    
    def wrapper(self, *args, **kwds):
        func(self, *args, **kwds)
        return Indent(self)
    return wrapper
106777
def decorator(caller, _func=None):
    """"""
    if _func is not None:  # return a decorated function
        # this is obsolete behavior; you should use decorate instead
        return decorate(_func, caller)
    # else return a decorator function
    if inspect.isclass(caller):
        name = caller.__name__.lower()
        doc = 'decorator(%s) converts functions/generators into ' \
              'factories of %s objects' % (caller.__name__, caller.__name__)
    elif inspect.isfunction(caller):
        if caller.__name__ == '<lambda>':
            name = '_lambda_'
        else:
            name = caller.__name__
        doc = caller.__doc__
    else:  # assume caller is an object with a __call__ method
        name = caller.__class__.__name__.lower()
        doc = caller.__call__.__doc__
    evaldict = dict(_call_=caller, _decorate_=decorate)
    return FunctionMaker.create(
        '%s(func)' % name, 'return _decorate_(func, _call_)',
        evaldict, doc=doc, module=caller.__module__,
        __wrapped__=caller)
1103644
def trace_decorator(self):
        """"""

        def decorator(func):

            def wrapper(*args, **kwargs):
                self.tracer.start_span(name=func.__name__)
                return_value = func(*args, **kwargs)
                self.tracer.end_span()
                return return_value

            return wrapper

        return decorator
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
378091
def _format_cell(val, colkeywords):
    
    out=""

    # String arrays are returned as dict, undo that for printing
    if isinstance(val, dict):
        tmpdict=numpy.array(val['array'])
        tmpdict.reshape(val['shape'])
        # Leave out quotes around strings
        numpy.set_printoptions(formatter={'all':lambda x: str(x)})
        out+=numpy.array2string(tmpdict, separator=', ')
        # Revert previous numpy print options
        numpy.set_printoptions(formatter=None)
    else:
        valtype='other'

        # Check if the column unit is like 'm' or ['m','m','m']
        singleUnit=('QuantumUnits' in colkeywords and
                    (numpy.array(colkeywords['QuantumUnits'])==numpy.array(colkeywords['QuantumUnits'])[0]).all())
        if colkeywords.get('MEASINFO',{}).get('type')=='epoch' and singleUnit:
            # Format a date/time. Use quanta for scalars, use numpy for array logic around it
            # (quanta does not support higher dimensional arrays)
            valtype='epoch'
            if isinstance(val, numpy.ndarray):
                numpy.set_printoptions(formatter={'all':lambda x: _format_date(x,colkeywords['QuantumUnits'][0])})
                out+=numpy.array2string(val,separator=', ')
                numpy.set_printoptions(formatter=None)
            else:
                out+=_format_date(val,colkeywords['QuantumUnits'][0])
        elif colkeywords.get('MEASINFO',{}).get('type')=='direction' and singleUnit and val.shape==(1,2):
                # Format one direction. TODO: extend to array of directions
                valtype='direction'
                out+="["
                part=quantity(val[0,0],'rad').formatted("TIME",precision=9)
                part=re.sub(r'(\d+):(\d+):(.*)',r'\1h\2m\3',part)
                out+=part+", "
                part=quantity(val[0,1],'rad').formatted("ANGLE",precision=9)
                part=re.sub(r'(\d+)\.(\d+)\.(.*)',r'\1d\2m\3',part)
                out+=part+"]"
        elif isinstance(val, numpy.ndarray) and singleUnit:
            # Format any array with units
            valtype='quanta'
            numpy.set_printoptions(formatter={'all':lambda x: _format_quantum(x, colkeywords['QuantumUnits'][0])})
            out+=numpy.array2string(val,separator=', ')
            numpy.set_printoptions(formatter=None)
        elif isinstance(val, numpy.ndarray):
            valtype='other'
            # Undo quotes around strings
            numpy.set_printoptions(formatter={'all':lambda x: str(x)})
            out+=numpy.array2string(val,separator=', ')
            numpy.set_printoptions(formatter=None)
        elif singleUnit:
            valtype='onequantum'
            out+=_format_quantum(val, colkeywords['QuantumUnits'][0])
        else:
            valtype='other'
            out+=str(val)

    if 'QuantumUnits' in colkeywords and valtype=='other':
        # Print units if they haven't been taken care of
        if not (numpy.array(colkeywords['QuantumUnits'])==numpy.array(colkeywords['QuantumUnits'])[0]).all():
            # Multiple different units for element in an array.
            # For now, just print the units and let the user figure out what it means
            out+=" "+str(colkeywords['QuantumUnits'])
        else:
            out+=" "+colkeywords['QuantumUnits'][0]

    # Numpy sometimes adds double newlines, don't do that
    out=out.replace('\n\n','\n')
    return out
1299094
def make_multi_cols(self, num_class, name):
        ''''''
        cols = ['c' + str(i) + '_' for i in xrange(num_class)]
        cols = map(lambda x: x + name, cols)
        return cols
769444
def show(self, func_name, values, labels=None):
        """"""
        s = self.Stanza(self.indent)
        if func_name == '<module>' and self.in_console:
            func_name = '<console>'
        s.add([func_name + ': '])
        reprs = map(self.safe_repr, values)
        if labels:
            sep = ''
            for label, repr in zip(labels, reprs):
                s.add([label + '=', self.CYAN, repr, self.NORMAL], sep)
                sep = ', '
        else:
            sep = ''
            for repr in reprs:
                s.add([self.CYAN, repr, self.NORMAL], sep)
                sep = ', '
        self.writer.write(s.chunks)
992928
def _indent_decor(lbl):
    
    def closure_indent(func):
        if util_arg.TRACE:
            @ignores_exc_tb(outer_wrapper=False)
            #@wraps(func)
            def wrp_indent(*args, **kwargs):
                with util_print.Indenter(lbl):
                    print('    ...trace[in]')
                    ret = func(*args, **kwargs)
                    print('    ...trace[out]')
                    return ret
        else:
            @ignores_exc_tb(outer_wrapper=False)
            #@wraps(func)
            def wrp_indent(*args, **kwargs):
                with util_print.Indenter(lbl):
                    ret = func(*args, **kwargs)
                    return ret
        wrp_indent_ = ignores_exc_tb(wrp_indent)
        wrp_indent_ = preserve_sig(wrp_indent, func)
        return wrp_indent_
    return closure_indent
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
1102214
def map(self, func, *columns):
        
        if not columns:
            return map(func, self.rows)
        else:
            values = (self.values(column) for column in columns)
            result = [map(func, v) for v in values]
            if len(columns) == 1:
                return result[0]
            else:
                return result
86937
def __insert_wrapper(func):
        """"""
        def check_func(self, key, new_item, instance=0):
            if key not in self.keys():
                raise KeyError("%s not a key in label" % (key))
            if not isinstance(new_item, (list, OrderedMultiDict)):
                raise TypeError("The new item must be a list or PVLModule")
            if isinstance(new_item, OrderedMultiDict):
                new_item = list(new_item)
            return func(self, key, new_item, instance)
        return check_func
176028
def _onDecorator(self, name, line, pos, absPosition):
        """"""
        # A class or a function must be on the top of the stack
        d = Decorator(name, line, pos, absPosition)
        if self.__lastDecorators is None:
            self.__lastDecorators = [d]
        else:
            self.__lastDecorators.append(d)