Build docstring for symbolic functions.
16311
def _build_doc(func_name,
               desc,
               arg_names,
               arg_types,
               arg_desc,
               key_var_num_args=None,
               ret_type=None):
    """"""
    param_str = _build_param_doc(arg_names, arg_types, arg_desc)
    if key_var_num_args:
        desc += '\nThis function support variable length of positional input.'
    doc_str = ('%s\n\n' +
               '%s\n' +
               'name : string, optional.\n' +
               '    Name of the resulting symbol.\n\n' +
               'Returns\n' +
               '-------\n' +
               'Symbol\n' +
               '    The result symbol.')
    doc_str = doc_str % (desc, param_str)
    extra_doc = "\n" + '\n'.join([x.__doc__ for x in type.__subclasses__(SymbolDoc)
                                  if x.__name__ == '%sDoc' % func_name])
    doc_str += _re.sub(_re.compile("    "), "", extra_doc)
    doc_str = _re.sub('NDArray-or-Symbol', 'Symbol', doc_str)
    return doc_str
86545
def niceStringify( self ):
        "  "

        out = ""
        if self.docstring is not None:
            out += str( self.docstring )
        if not self.encoding is None:
            if out != "":
                out += '\n'
            out += str( self.encoding )
        for item in self.imports:
            if out != "":
                out += '\n'
            out += str( item )
        for item in self.globals:
            if out != "":
                out += '\n'
            out += str( item )
        for item in self.functions:
            if out != "":
                out += '\n'
            out += item.niceStringify( 0 )
        for item in self.classes:
            if out != "":
                out += '\n'
            out += item.niceStringify( 0 )
        return out
75699
def stringfy(expr, sym_const=None, sym_states=None, sym_algebs=None):
    """"""
    if not sym_const:
        sym_const = []
    if not sym_states:
        sym_states = []
    if not sym_algebs:
        sym_algebs = []
    expr_str = []
    if type(expr) in (int, float):
        return expr
    if expr.is_Atom:
        if expr in sym_const:
            expr_str = 'self.{}'.format(expr)
        elif expr in sym_states:
            expr_str = 'dae.x[self.{}]'.format(expr)
        elif expr in sym_algebs:
            expr_str = 'dae.y[self.{}]'.format(expr)
        elif expr.is_Number:
            if expr.is_Integer:
                expr_str = str(int(expr))
            else:
                expr_str = str(float(expr))
            # if expr.is_negative:
            #     expr_str = '{}'.format(expr)
            # else:
            #     expr_str = str(expr)
        else:
            raise AttributeError('Unknown free symbol <{}>'.format(expr))
    else:
        nargs = len(expr.args)
        arg_str = []
        for arg in expr.args:
            arg_str.append(stringfy(arg, sym_const, sym_states, sym_algebs))

        if expr.is_Add:
            expr_str = ''
            for idx, item in enumerate(arg_str):
                if idx == 0:
                    if len(item) > 1 and item[1] == ' ':
                        item = item[0] + item[2:]
                if idx > 0:
                    if item[0] == '-':
                        item = ' ' + item
                    else:
                        item = ' + ' + item
                expr_str += item

        elif expr.is_Mul:
            if nargs == 2 and expr.args[0].is_Integer:  # number * matrix
                if expr.args[0].is_positive:
                    expr_str = '{}*{}'.format(*arg_str)
                elif expr.args[0] == Integer('-1'):
                    expr_str = '- {}'.format(arg_str[1])
                else:  # negative but not -1
                    expr_str = '{}*{}'.format(*arg_str)
            else:  # matrix dot multiplication
                if expr.args[0] == Integer('-1'):
                    # bring '-' out of mul()
                    expr_str = ', '.join(arg_str[1:])
                    expr_str = '- mul(' + expr_str + ')'
                else:
                    expr_str = ', '.join(arg_str)
                    expr_str = 'mul(' + expr_str + ')'
        elif expr.is_Function:
            expr_str = ', '.join(arg_str)
            expr_str = str(expr.func) + '(' + expr_str + ')'
        elif expr.is_Pow:
            if arg_str[1] == '-1':
                expr_str = 'div(1, {})'.format(arg_str[0])
            else:
                expr_str = '({})**{}'.format(*arg_str)
        elif expr.is_Div:
            expr_str = ', '.join(arg_str)
            expr_str = 'div(' + expr_str + ')'
        else:
            raise NotImplementedError
    return expr_str
104945
function DocAction(docStr) {
    return function (target, propertyKey, descriptor) {
        let m = exports.globalKCState.getOrInsertController(target.constructor).getOrInsertMethod(propertyKey);
        m.docString = docStr;
    };
}
182709
def _generate_numpy_doc(self, func_info):
        """"""
        numpy_doc = ''

        arg_names = func_info.arg_name_list
        arg_types = func_info.arg_type_list
        arg_values = func_info.arg_value_list

        if len(arg_names) > 0 and arg_names[0] == 'self':
            del arg_names[0]
            del arg_types[0]
            del arg_values[0]

        indent1 = func_info.func_indent + self.code_editor.indent_chars
        indent2 = func_info.func_indent + self.code_editor.indent_chars * 2

        numpy_doc += '\n{}\n'.format(indent1)

        if len(arg_names) > 0:
            numpy_doc += '\n{}Parameters'.format(indent1)
            numpy_doc += '\n{}----------\n'.format(indent1)

        arg_text = ''
        for arg_name, arg_type, arg_value in zip(arg_names, arg_types,
                                                 arg_values):
            arg_text += '{}{} : '.format(indent1, arg_name)
            if arg_type:
                arg_text += '{}'.format(arg_type)
            else:
                arg_text += 'TYPE'

            if arg_value:
                arg_text += ', optional'

            arg_text += '\n{}DESCRIPTION.'.format(indent2)

            if arg_value:
                arg_value = arg_value.replace(self.quote3, self.quote3_other)
                arg_text += ' The default is {}.'.format(arg_value)

            arg_text += '\n'

        numpy_doc += arg_text

        if func_info.raise_list:
            numpy_doc += '\n{}Raises'.format(indent1)
            numpy_doc += '\n{}------'.format(indent1)
            for raise_type in func_info.raise_list:
                numpy_doc += '\n{}{}'.format(indent1, raise_type)
                numpy_doc += '\n{}DESCRIPTION.'.format(indent2)
            numpy_doc += '\n'

        numpy_doc += '\n'
        if func_info.has_yield:
            header = '{0}Yields\n{0}------\n'.format(indent1)
        else:
            header = '{0}Returns\n{0}-------\n'.format(indent1)

        return_type_annotated = func_info.return_type_annotated
        if return_type_annotated:
            return_section = '{}{}{}'.format(header, indent1,
                                             return_type_annotated)
            return_section += '\n{}DESCRIPTION.'.format(indent2)
        else:
            return_element_type = indent1 + '{return_type}\n' + indent2 + \
                'DESCRIPTION.'
            placeholder = return_element_type.format(return_type='TYPE')
            return_element_name = indent1 + '{return_name} : ' + \
                placeholder.lstrip()

            try:
                return_section = self._generate_docstring_return_section(
                    func_info.return_value_in_body, header,
                    return_element_name, return_element_type, placeholder,
                    indent1)
            except (ValueError, IndexError):
                return_section = '{}{}None.'.format(header, indent1)

        numpy_doc += return_section
        numpy_doc += '\n\n{}{}'.format(indent1, self.quote3)

        return numpy_doc
975095
def _add_to_docstring(string):
    '''

    '''
    def wrapper(method):
        if method.__doc__ is not None:
            method.__doc__ += string
        else:
            method.__doc__ = string
        return method
    return wrapper
1128679
def _prepare_docstrings(self, frame):
        """"""
        if config.USEAUTODOC:
            filename = inspect.getsourcefile(frame)
            with open(filename) as file_:
                sources = file_.read().split('"""')
            for code, doc in zip(sources[::2], sources[1::2]):
                code = code.strip()
                key = code.split('\n')[-1].split()[0]
                value = self.get(key)
                if value:
                    value.__doc__ = doc
1053551
def _get_docstring_indent(definition, docstring):
        """"""
        before_docstring, _, _ = definition.source.partition(docstring)
        _, _, indent = before_docstring.rpartition('\n')
        return indent
996259
def main():
    """"""

    # pylint: disable=global-statement
    global PANDOCVERSION
    global AttrTable

    # Get the output format and document
    fmt = args.fmt
    doc = json.loads(STDIN.read())

    # Initialize pandocxnos
    # pylint: disable=too-many-function-args
    PANDOCVERSION = pandocxnos.init(args.pandocversion, doc)

    # Element primitives
    AttrTable = elt('Table', 6)

    # Chop up the doc
    meta = doc['meta'] if PANDOCVERSION >= '1.18' else doc[0]['unMeta']
    blocks = doc['blocks'] if PANDOCVERSION >= '1.18' else doc[1:]

    # Process the metadata variables
    process(meta)

    # First pass
    detach_attrs_table = detach_attrs_factory(Table)
    insert_secnos = insert_secnos_factory(Table)
    delete_secnos = delete_secnos_factory(Table)
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [attach_attrs_table, insert_secnos,
                                process_tables, delete_secnos,
                                detach_attrs_table], blocks)

    # Second pass
    process_refs = process_refs_factory(references.keys())
    replace_refs = replace_refs_factory(references,
                                        use_cleveref_default, False,
                                        plusname if not capitalize else
                                        [name.title() for name in plusname],
                                        starname, 'table')
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [repair_refs, process_refs, replace_refs],
                               altered)

    # Insert supporting TeX
    if fmt in ['latex']:

        rawblocks = []

        if has_unnumbered_tables:
            rawblocks += [RawBlock('tex', TEX0),
                          RawBlock('tex', TEX1),
                          RawBlock('tex', TEX2)]

        if captionname != 'Table':
            rawblocks += [RawBlock('tex', TEX3 % captionname)]

        insert_rawblocks = insert_rawblocks_factory(rawblocks)

        altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                                   [insert_rawblocks], altered)

    # Update the doc
    if PANDOCVERSION >= '1.18':
        doc['blocks'] = altered
    else:
        doc = doc[:1] + altered

    # Dump the results
    json.dump(doc, STDOUT)

    # Flush stdout
    STDOUT.flush()
1253962
def _parse_docstring(docstring):
    """"""
    params = {}

    if not docstring:
        return None, params

    try:
        help_msg = _DOCSTRING_REGEX.search(docstring).group()
        help_msg = _strip_lines(help_msg)
    except AttributeError:
        help_msg = None

    for param in _DOCSTRING_PARAM_REGEX.finditer(docstring):
        param_definition = param.group(1).rsplit(' ', 1)
        if len(param_definition) == 2:
            param_type, param_name = param_definition
        else:
            param_type = None
            param_name = param_definition[0]

        param_help = param.group(2).strip()
        params[param_name] = param_type, _strip_lines(param_help)
    return help_msg, params
1284995
def _symbolic_product_helper():
    """"""
    from sympy import symbols, Matrix

    D11, D12, D13, D21, D22, D23, D31, D32, D33 =\
        symbols('D11, D12, D13, D21, D22, D23, D31, D32, D33')

    D = Matrix([[D11, D12, D13], [D21, D22, D23], [D31, D32, D33]])
    grad = Matrix([['dx', 'dy', 'dz']]).T
    div = grad.T

    a = div * D * grad

    print(a[0])
473292
def _docstring_key(self, line):
        """"""
        decormatch = self.docparser.RE_DECOR.match(line)
        if decormatch is not None:
            key = "{}.{}".format(self.docelement.name, decormatch.group("name"))
        else:
            key = self.element.name

        return key
615565
def _to_docstring(doc):
    

    def format_fn(line, status):
        """ format function """
        # swap &lt; &gt; to < >
        line = re_to_tag.sub(r"<\1>", line)
        if re_to_data.match(line):
            line = re_to_data.sub(r"@\1 ", line)
            status["eat_line"] = True
        line = re_to_defaults.sub(r"\1", line)
        if status["listing"]:
            # parameters
            if re_to_param.match(line):
                line = re_to_param.sub(r"    \1: ", line)
            # status items
            elif re_to_status.match(line):
                line = re_to_status.sub(r"    \1 ", line)
            # bullets
            elif re_to_item.match(line):
                line = re_to_item.sub(r"    -", line)
            # is continuation line
            else:
                line = " " * 8 + line.lstrip()
        return line

    return _reformat_docstring(doc, format_fn)
557112
def function_application(func):
    
    if func not in NUMEXPR_MATH_FUNCS:
        raise ValueError("Unsupported mathematical function '%s'" % func)

    @with_doc(func)
    @with_name(func)
    def mathfunc(self):
        if isinstance(self, NumericalExpression):
            return NumExprFactor(
                "{func}({expr})".format(func=func, expr=self._expr),
                self.inputs,
                dtype=float64_dtype,
            )
        else:
            return NumExprFactor(
                "{func}(x_0)".format(func=func),
                (self,),
                dtype=float64_dtype,
            )
    return mathfunc
733336
def print_docs(self):
        '''
        
        '''
        docs = {}
        for name, func in six.iteritems(self.minion.functions):
            if name not in docs:
                if func.__doc__:
                    docs[name] = func.__doc__
        for name in sorted(docs):
            if name.startswith(self.opts.get('fun', '')):
                salt.utils.stringutils.print_cli('{0}:\n{1}\n'.format(name, docs[name]))
442585
def _parse_decorated_functions(self, code):
        """"""
        matches = re.finditer(r"""
                # @rest decorators
                (?P<decorators>
                    (?:@rest\(.+?\)\n)+  # one or more @rest decorators inside
                )
                # docstring delimited by 3 double quotes
                .+?"{3}(?P<docstring>.+?)"{3}
                """, code, re.VERBOSE | re.DOTALL)

        for function_match in matches:
            m_dict = function_match.groupdict()
            self._parse_docstring(m_dict['docstring'])
            self._add_function_paths(m_dict['decorators'])
810196
def build_ast(self):
        """"""
        n = self.root_node
        if n.type == syms.file_input:
            stmts = []
            for i in range(len(n.children) - 1):
                stmt = n.children[i]
                if stmt.type == tokens.NEWLINE:
                    continue
                sub_stmts_count = self.number_of_statements(stmt)
                if sub_stmts_count == 1:
                    stmts.append(self.handle_stmt(stmt))
                else:
                    stmt = stmt.children[0]
                    for j in range(sub_stmts_count):
                        small_stmt = stmt.children[j * 2]
                        stmts.append(self.handle_stmt(small_stmt))
            return ast.Module(stmts)
        elif n.type == syms.eval_input:
            body = self.handle_testlist(n.children[0])
            return ast.Expression(body)
        elif n.type == syms.single_input:
            first_child = n.children[0]
            if first_child.type == tokens.NEWLINE:
                # An empty line.
                return ast.Interactive([])
            else:
                num_stmts = self.number_of_statements(first_child)
                if num_stmts == 1:
                    stmts = [self.handle_stmt(first_child)]
                else:
                    stmts = []
                    for i in range(0, len(first_child.children), 2):
                        stmt = first_child.children[i]
                        if stmt.type == tokens.NEWLINE:
                            break
                        stmts.append(self.handle_stmt(stmt))
                return ast.Interactive(stmts)
        else:
            raise AssertionError("unknown root node")